Source: geometry/PlaneGeometry.js

  1. import { Geometry } from './Geometry.js';
  2. import { BufferAttribute } from './BufferAttribute.js';
  3. /**
  4. * A class for generating plane geometries.
  5. * @constructor
  6. * @memberof zen3d
  7. * @extends zen3d.Geometry
  8. * @param {number} [width=1] — Width along the X axis.
  9. * @param {number} [height=1] — Height along the Y axis.
  10. * @param {Integer} [widthSegments=1] — Optional.
  11. * @param {Integer} [heightSegments=1] — Optional.
  12. */
  13. function PlaneGeometry(width, height, widthSegments, heightSegments) {
  14. Geometry.call(this);
  15. this.buildGeometry(width, height, widthSegments, heightSegments);
  16. }
  17. PlaneGeometry.prototype = Object.assign(Object.create(Geometry.prototype), {
  18. constructor: PlaneGeometry,
  19. buildGeometry: function(width, height, widthSegments, heightSegments) {
  20. width = width || 1;
  21. height = height || 1;
  22. var width_half = width / 2;
  23. var height_half = height / 2;
  24. var gridX = Math.floor(widthSegments) || 1;
  25. var gridY = Math.floor(heightSegments) || 1;
  26. var gridX1 = gridX + 1;
  27. var gridY1 = gridY + 1;
  28. var segment_width = width / gridX;
  29. var segment_height = height / gridY;
  30. var ix, iy;
  31. // buffers
  32. var indices = [];
  33. var vertices = [];
  34. var normals = [];
  35. var uvs = [];
  36. // generate vertices, normals and uvs
  37. for (iy = 0; iy < gridY1; iy++) {
  38. var y = iy * segment_height - height_half;
  39. for (ix = 0; ix < gridX1; ix++) {
  40. var x = ix * segment_width - width_half;
  41. vertices.push(x, 0, y);
  42. normals.push(0, 1, 0);
  43. uvs.push(ix / gridX);
  44. uvs.push(1 - (iy / gridY));
  45. }
  46. }
  47. // indices
  48. for (iy = 0; iy < gridY; iy++) {
  49. for (ix = 0; ix < gridX; ix++) {
  50. var a = ix + gridX1 * iy;
  51. var b = ix + gridX1 * (iy + 1);
  52. var c = (ix + 1) + gridX1 * (iy + 1);
  53. var d = (ix + 1) + gridX1 * iy;
  54. // faces
  55. indices.push(a, b, d);
  56. indices.push(b, c, d);
  57. }
  58. }
  59. // build geometry
  60. this.setIndex(indices);
  61. this.addAttribute('a_Position', new BufferAttribute(new Float32Array(vertices), 3));
  62. this.addAttribute('a_Normal', new BufferAttribute(new Float32Array(normals), 3));
  63. this.addAttribute('a_Uv', new BufferAttribute(new Float32Array(uvs), 2));
  64. this.computeBoundingBox();
  65. this.computeBoundingSphere();
  66. }
  67. });
  68. export { PlaneGeometry };