ConvexGeometry.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute
  4. } from 'three';
  5. import { ConvexHull } from '../math/ConvexHull.js';
  6. /**
  7. * This class can be used to generate a convex hull for a given array of 3D points.
  8. * The average time complexity for this task is considered to be O(nlog(n)).
  9. *
  10. * ```js
  11. * const geometry = new ConvexGeometry( points );
  12. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  13. * const mesh = new THREE.Mesh( geometry, material );
  14. * scene.add( mesh );
  15. * ```
  16. *
  17. * @augments BufferGeometry
  18. * @three_import import { ConvexGeometry } from 'three/addons/geometries/ConvexGeometry.js';
  19. */
  20. class ConvexGeometry extends BufferGeometry {
  21. /**
  22. * Constructs a new convex geometry.
  23. *
  24. * @param {Array<Vector3>} points - An array of points in 3D space which should be enclosed by the convex hull.
  25. */
  26. constructor( points = [] ) {
  27. super();
  28. // buffers
  29. const vertices = [];
  30. const normals = [];
  31. const convexHull = new ConvexHull().setFromPoints( points );
  32. // generate vertices and normals
  33. const faces = convexHull.faces;
  34. for ( let i = 0; i < faces.length; i ++ ) {
  35. const face = faces[ i ];
  36. let edge = face.edge;
  37. // we move along a doubly-connected edge list to access all face points (see HalfEdge docs)
  38. do {
  39. const point = edge.head().point;
  40. vertices.push( point.x, point.y, point.z );
  41. normals.push( face.normal.x, face.normal.y, face.normal.z );
  42. edge = edge.next;
  43. } while ( edge !== face.edge );
  44. }
  45. // build geometry
  46. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  47. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  48. }
  49. }
  50. export { ConvexGeometry };