ParametricGeometry.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. ( function () {
  2. /**
  3. * Parametric Surfaces Geometry
  4. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  5. */
  6. class ParametricGeometry extends THREE.BufferGeometry {
  7. constructor( func = ( u, v, target ) => target.set( u, v, Math.cos( u ) * Math.sin( v ) ), slices = 8, stacks = 8 ) {
  8. super();
  9. this.type = 'ParametricGeometry';
  10. this.parameters = {
  11. func: func,
  12. slices: slices,
  13. stacks: stacks
  14. };
  15. // buffers
  16. const indices = [];
  17. const vertices = [];
  18. const normals = [];
  19. const uvs = [];
  20. const EPS = 0.00001;
  21. const normal = new THREE.Vector3();
  22. const p0 = new THREE.Vector3(),
  23. p1 = new THREE.Vector3();
  24. const pu = new THREE.Vector3(),
  25. pv = new THREE.Vector3();
  26. // generate vertices, normals and uvs
  27. const sliceCount = slices + 1;
  28. for ( let i = 0; i <= stacks; i ++ ) {
  29. const v = i / stacks;
  30. for ( let j = 0; j <= slices; j ++ ) {
  31. const u = j / slices;
  32. // vertex
  33. func( u, v, p0 );
  34. vertices.push( p0.x, p0.y, p0.z );
  35. // normal
  36. // approximate tangent vectors via finite differences
  37. if ( u - EPS >= 0 ) {
  38. func( u - EPS, v, p1 );
  39. pu.subVectors( p0, p1 );
  40. } else {
  41. func( u + EPS, v, p1 );
  42. pu.subVectors( p1, p0 );
  43. }
  44. if ( v - EPS >= 0 ) {
  45. func( u, v - EPS, p1 );
  46. pv.subVectors( p0, p1 );
  47. } else {
  48. func( u, v + EPS, p1 );
  49. pv.subVectors( p1, p0 );
  50. }
  51. // cross product of tangent vectors returns surface normal
  52. normal.crossVectors( pu, pv ).normalize();
  53. normals.push( normal.x, normal.y, normal.z );
  54. // uv
  55. uvs.push( u, v );
  56. }
  57. }
  58. // generate indices
  59. for ( let i = 0; i < stacks; i ++ ) {
  60. for ( let j = 0; j < slices; j ++ ) {
  61. const a = i * sliceCount + j;
  62. const b = i * sliceCount + j + 1;
  63. const c = ( i + 1 ) * sliceCount + j + 1;
  64. const d = ( i + 1 ) * sliceCount + j;
  65. // faces one and two
  66. indices.push( a, b, d );
  67. indices.push( b, c, d );
  68. }
  69. }
  70. // build geometry
  71. this.setIndex( indices );
  72. this.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  73. this.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  74. this.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) );
  75. }
  76. }
  77. THREE.ParametricGeometry = ParametricGeometry;
  78. } )();