PlaneGeometry.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { BufferGeometry } from '../core/BufferGeometry.js';
  2. import { Float32BufferAttribute } from '../core/BufferAttribute.js';
  3. class PlaneGeometry extends BufferGeometry {
  4. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  5. super();
  6. this.type = 'PlaneGeometry';
  7. this.parameters = {
  8. width: width,
  9. height: height,
  10. widthSegments: widthSegments,
  11. heightSegments: heightSegments
  12. };
  13. const width_half = width / 2;
  14. const height_half = height / 2;
  15. const gridX = Math.floor( widthSegments );
  16. const gridY = Math.floor( heightSegments );
  17. const gridX1 = gridX + 1;
  18. const gridY1 = gridY + 1;
  19. const segment_width = width / gridX;
  20. const segment_height = height / gridY;
  21. //
  22. const indices = [];
  23. const vertices = [];
  24. const normals = [];
  25. const uvs = [];
  26. for ( let iy = 0; iy < gridY1; iy ++ ) {
  27. const y = iy * segment_height - height_half;
  28. for ( let ix = 0; ix < gridX1; ix ++ ) {
  29. const x = ix * segment_width - width_half;
  30. vertices.push( x, - y, 0 );
  31. normals.push( 0, 0, 1 );
  32. uvs.push( ix / gridX );
  33. uvs.push( 1 - ( iy / gridY ) );
  34. }
  35. }
  36. for ( let iy = 0; iy < gridY; iy ++ ) {
  37. for ( let ix = 0; ix < gridX; ix ++ ) {
  38. const a = ix + gridX1 * iy;
  39. const b = ix + gridX1 * ( iy + 1 );
  40. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  41. const d = ( ix + 1 ) + gridX1 * iy;
  42. indices.push( a, b, d );
  43. indices.push( b, c, d );
  44. }
  45. }
  46. this.setIndex( indices );
  47. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  48. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  49. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  50. }
  51. static fromJSON( data ) {
  52. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  53. }
  54. }
  55. export { PlaneGeometry, PlaneGeometry as PlaneBufferGeometry };