MeshSurfaceSampler.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import {
  2. Triangle,
  3. Vector2,
  4. Vector3
  5. } from 'three';
  6. const _face = new Triangle();
  7. const _color = new Vector3();
  8. const _uva = new Vector2(), _uvb = new Vector2(), _uvc = new Vector2();
  9. /**
  10. * Utility class for sampling weighted random points on the surface of a mesh.
  11. *
  12. * Building the sampler is a one-time O(n) operation. Once built, any number of
  13. * random samples may be selected in O(logn) time. Memory usage is O(n).
  14. *
  15. * References:
  16. * - {@link http://www.joesfer.com/?p=84}
  17. * - {@link https://stackoverflow.com/a/4322940/1314762}
  18. *
  19. * ```js
  20. * const sampler = new MeshSurfaceSampler( surfaceMesh )
  21. * .setWeightAttribute( 'color' )
  22. * .build();
  23. *
  24. * const mesh = new THREE.InstancedMesh( sampleGeometry, sampleMaterial, 100 );
  25. *
  26. * const position = new THREE.Vector3();
  27. * const matrix = new THREE.Matrix4();
  28. *
  29. * // Sample randomly from the surface, creating an instance of the sample geometry at each sample point.
  30. *
  31. * for ( let i = 0; i < 100; i ++ ) {
  32. *
  33. * sampler.sample( position );
  34. * matrix.makeTranslation( position.x, position.y, position.z );
  35. * mesh.setMatrixAt( i, matrix );
  36. *
  37. * }
  38. *
  39. * scene.add( mesh );
  40. * ```
  41. *
  42. * @three_import import { MeshSurfaceSampler } from 'three/addons/math/MeshSurfaceSampler.js';
  43. */
  44. class MeshSurfaceSampler {
  45. /**
  46. * Constructs a mesh surface sampler.
  47. *
  48. * @param {Mesh} mesh - Surface mesh from which to sample.
  49. */
  50. constructor( mesh ) {
  51. this.geometry = mesh.geometry;
  52. this.randomFunction = Math.random;
  53. this.indexAttribute = this.geometry.index;
  54. this.positionAttribute = this.geometry.getAttribute( 'position' );
  55. this.normalAttribute = this.geometry.getAttribute( 'normal' );
  56. this.colorAttribute = this.geometry.getAttribute( 'color' );
  57. this.uvAttribute = this.geometry.getAttribute( 'uv' );
  58. this.weightAttribute = null;
  59. this.distribution = null;
  60. }
  61. /**
  62. * Specifies a vertex attribute to be used as a weight when sampling from the surface.
  63. * Faces with higher weights are more likely to be sampled, and those with weights of
  64. * zero will not be sampled at all. For vector attributes, only .x is used in sampling.
  65. *
  66. * If no weight attribute is selected, sampling is randomly distributed by area.
  67. *
  68. * @param {string} name - The attribute name.
  69. * @return {MeshSurfaceSampler} A reference to this sampler.
  70. */
  71. setWeightAttribute( name ) {
  72. this.weightAttribute = name ? this.geometry.getAttribute( name ) : null;
  73. return this;
  74. }
  75. /**
  76. * Processes the input geometry and prepares to return samples. Any configuration of the
  77. * geometry or sampler must occur before this method is called. Time complexity is O(n)
  78. * for a surface with n faces.
  79. *
  80. * @return {MeshSurfaceSampler} A reference to this sampler.
  81. */
  82. build() {
  83. const indexAttribute = this.indexAttribute;
  84. const positionAttribute = this.positionAttribute;
  85. const weightAttribute = this.weightAttribute;
  86. const totalFaces = indexAttribute ? ( indexAttribute.count / 3 ) : ( positionAttribute.count / 3 );
  87. const faceWeights = new Float32Array( totalFaces );
  88. // Accumulate weights for each mesh face.
  89. for ( let i = 0; i < totalFaces; i ++ ) {
  90. let faceWeight = 1;
  91. let i0 = 3 * i;
  92. let i1 = 3 * i + 1;
  93. let i2 = 3 * i + 2;
  94. if ( indexAttribute ) {
  95. i0 = indexAttribute.getX( i0 );
  96. i1 = indexAttribute.getX( i1 );
  97. i2 = indexAttribute.getX( i2 );
  98. }
  99. if ( weightAttribute ) {
  100. faceWeight = weightAttribute.getX( i0 )
  101. + weightAttribute.getX( i1 )
  102. + weightAttribute.getX( i2 );
  103. }
  104. _face.a.fromBufferAttribute( positionAttribute, i0 );
  105. _face.b.fromBufferAttribute( positionAttribute, i1 );
  106. _face.c.fromBufferAttribute( positionAttribute, i2 );
  107. faceWeight *= _face.getArea();
  108. faceWeights[ i ] = faceWeight;
  109. }
  110. // Store cumulative total face weights in an array, where weight index
  111. // corresponds to face index.
  112. const distribution = new Float32Array( totalFaces );
  113. let cumulativeTotal = 0;
  114. for ( let i = 0; i < totalFaces; i ++ ) {
  115. cumulativeTotal += faceWeights[ i ];
  116. distribution[ i ] = cumulativeTotal;
  117. }
  118. this.distribution = distribution;
  119. return this;
  120. }
  121. /**
  122. * Allows to set a custom random number generator. Default is `Math.random()`.
  123. *
  124. * @param {Function} randomFunction - A random number generator.
  125. * @return {MeshSurfaceSampler} A reference to this sampler.
  126. */
  127. setRandomGenerator( randomFunction ) {
  128. this.randomFunction = randomFunction;
  129. return this;
  130. }
  131. /**
  132. * Selects a random point on the surface of the input geometry, returning the
  133. * position and optionally the normal vector, color and UV Coordinate at that point.
  134. * Time complexity is O(log n) for a surface with n faces.
  135. *
  136. * @param {Vector3} targetPosition - The target object holding the sampled position.
  137. * @param {Vector3} targetNormal - The target object holding the sampled normal.
  138. * @param {Color} targetColor - The target object holding the sampled color.
  139. * @param {Vector2} targetUV - The target object holding the sampled uv coordinates.
  140. * @return {MeshSurfaceSampler} A reference to this sampler.
  141. */
  142. sample( targetPosition, targetNormal, targetColor, targetUV ) {
  143. const faceIndex = this._sampleFaceIndex();
  144. return this._sampleFace( faceIndex, targetPosition, targetNormal, targetColor, targetUV );
  145. }
  146. // private
  147. _sampleFaceIndex() {
  148. const cumulativeTotal = this.distribution[ this.distribution.length - 1 ];
  149. return this._binarySearch( this.randomFunction() * cumulativeTotal );
  150. }
  151. _binarySearch( x ) {
  152. const dist = this.distribution;
  153. let start = 0;
  154. let end = dist.length - 1;
  155. let index = - 1;
  156. while ( start <= end ) {
  157. const mid = Math.ceil( ( start + end ) / 2 );
  158. if ( mid === 0 || dist[ mid - 1 ] <= x && dist[ mid ] > x ) {
  159. index = mid;
  160. break;
  161. } else if ( x < dist[ mid ] ) {
  162. end = mid - 1;
  163. } else {
  164. start = mid + 1;
  165. }
  166. }
  167. return index;
  168. }
  169. _sampleFace( faceIndex, targetPosition, targetNormal, targetColor, targetUV ) {
  170. let u = this.randomFunction();
  171. let v = this.randomFunction();
  172. if ( u + v > 1 ) {
  173. u = 1 - u;
  174. v = 1 - v;
  175. }
  176. // get the vertex attribute indices
  177. const indexAttribute = this.indexAttribute;
  178. let i0 = faceIndex * 3;
  179. let i1 = faceIndex * 3 + 1;
  180. let i2 = faceIndex * 3 + 2;
  181. if ( indexAttribute ) {
  182. i0 = indexAttribute.getX( i0 );
  183. i1 = indexAttribute.getX( i1 );
  184. i2 = indexAttribute.getX( i2 );
  185. }
  186. _face.a.fromBufferAttribute( this.positionAttribute, i0 );
  187. _face.b.fromBufferAttribute( this.positionAttribute, i1 );
  188. _face.c.fromBufferAttribute( this.positionAttribute, i2 );
  189. targetPosition
  190. .set( 0, 0, 0 )
  191. .addScaledVector( _face.a, u )
  192. .addScaledVector( _face.b, v )
  193. .addScaledVector( _face.c, 1 - ( u + v ) );
  194. if ( targetNormal !== undefined ) {
  195. if ( this.normalAttribute !== undefined ) {
  196. _face.a.fromBufferAttribute( this.normalAttribute, i0 );
  197. _face.b.fromBufferAttribute( this.normalAttribute, i1 );
  198. _face.c.fromBufferAttribute( this.normalAttribute, i2 );
  199. targetNormal.set( 0, 0, 0 ).addScaledVector( _face.a, u ).addScaledVector( _face.b, v ).addScaledVector( _face.c, 1 - ( u + v ) ).normalize();
  200. } else {
  201. _face.getNormal( targetNormal );
  202. }
  203. }
  204. if ( targetColor !== undefined && this.colorAttribute !== undefined ) {
  205. _face.a.fromBufferAttribute( this.colorAttribute, i0 );
  206. _face.b.fromBufferAttribute( this.colorAttribute, i1 );
  207. _face.c.fromBufferAttribute( this.colorAttribute, i2 );
  208. _color
  209. .set( 0, 0, 0 )
  210. .addScaledVector( _face.a, u )
  211. .addScaledVector( _face.b, v )
  212. .addScaledVector( _face.c, 1 - ( u + v ) );
  213. targetColor.r = _color.x;
  214. targetColor.g = _color.y;
  215. targetColor.b = _color.z;
  216. }
  217. if ( targetUV !== undefined && this.uvAttribute !== undefined ) {
  218. _uva.fromBufferAttribute( this.uvAttribute, i0 );
  219. _uvb.fromBufferAttribute( this.uvAttribute, i1 );
  220. _uvc.fromBufferAttribute( this.uvAttribute, i2 );
  221. targetUV.set( 0, 0 ).addScaledVector( _uva, u ).addScaledVector( _uvb, v ).addScaledVector( _uvc, 1 - ( u + v ) );
  222. }
  223. return this;
  224. }
  225. }
  226. export { MeshSurfaceSampler };