babylon.abstractMesh.ts 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. module BABYLON {
  2. /** @hidden */
  3. class _FacetDataStorage {
  4. // facetData private properties
  5. public facetPositions: Vector3[]; // facet local positions
  6. public facetNormals: Vector3[]; // facet local normals
  7. public facetPartitioning: number[][]; // partitioning array of facet index arrays
  8. public facetNb: number = 0; // facet number
  9. public partitioningSubdivisions: number = 10; // number of subdivisions per axis in the partioning space
  10. public partitioningBBoxRatio: number = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11. public facetDataEnabled: boolean = false; // is the facet data feature enabled on this mesh ?
  12. public facetParameters: any = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13. public bbSize: Vector3 = Vector3.Zero(); // bbox size approximated for facet data
  14. public subDiv = { // actual number of subdivisions per axis for ComputeNormals()
  15. max: 1,
  16. X: 1,
  17. Y: 1,
  18. Z: 1
  19. };
  20. public facetDepthSort: boolean = false; // is the facet depth sort to be computed
  21. public facetDepthSortEnabled: boolean = false; // is the facet depth sort initialized
  22. public depthSortedIndices: IndicesArray; // copy of the indices array to store them once sorted
  23. public depthSortedFacets: { ind: number, sqDistance: number }[]; // array of depth sorted facets
  24. public facetDepthSortFunction: (f1: { ind: number, sqDistance: number }, f2: { ind: number, sqDistance: number }) => number; // facet depth sort function
  25. public facetDepthSortFrom: Vector3; // location where to depth sort from
  26. public facetDepthSortOrigin: Vector3; // same as facetDepthSortFrom but expressed in the mesh local space
  27. public invertedMatrix: Matrix; // Inverted world matrix.
  28. }
  29. /**
  30. * Class used to store all common mesh properties
  31. */
  32. export class AbstractMesh extends TransformNode implements IDisposable, ICullable, IGetSetVerticesData {
  33. /** No occlusion */
  34. public static OCCLUSION_TYPE_NONE = 0;
  35. /** Occlusion set to optimisitic */
  36. public static OCCLUSION_TYPE_OPTIMISTIC = 1;
  37. /** Occlusion set to strict */
  38. public static OCCLUSION_TYPE_STRICT = 2;
  39. /** Use an accurante occlusion algorithm */
  40. public static OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  41. /** Use a conservative occlusion algorithm */
  42. public static OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  43. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  44. public static readonly CULLINGSTRATEGY_STANDARD = 0;
  45. /** Culling strategy with bounding sphere only and then frustum culling */
  46. public static readonly CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  47. /**
  48. * No billboard
  49. */
  50. public static get BILLBOARDMODE_NONE(): number {
  51. return TransformNode.BILLBOARDMODE_NONE;
  52. }
  53. /** Billboard on X axis */
  54. public static get BILLBOARDMODE_X(): number {
  55. return TransformNode.BILLBOARDMODE_X;
  56. }
  57. /** Billboard on Y axis */
  58. public static get BILLBOARDMODE_Y(): number {
  59. return TransformNode.BILLBOARDMODE_Y;
  60. }
  61. /** Billboard on Z axis */
  62. public static get BILLBOARDMODE_Z(): number {
  63. return TransformNode.BILLBOARDMODE_Z;
  64. }
  65. /** Billboard on all axes */
  66. public static get BILLBOARDMODE_ALL(): number {
  67. return TransformNode.BILLBOARDMODE_ALL;
  68. }
  69. private _facetData = new _FacetDataStorage();
  70. /** Gets ot sets the culling strategy to use to find visible meshes */
  71. public cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  72. /**
  73. * Gets the number of facets in the mesh
  74. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  75. */
  76. public get facetNb(): number {
  77. return this._facetData.facetNb;
  78. }
  79. /**
  80. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  81. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  82. */
  83. public get partitioningSubdivisions(): number {
  84. return this._facetData.partitioningSubdivisions;
  85. }
  86. public set partitioningSubdivisions(nb: number) {
  87. this._facetData.partitioningSubdivisions = nb;
  88. }
  89. /**
  90. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  91. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  92. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  93. */
  94. public get partitioningBBoxRatio(): number {
  95. return this._facetData.partitioningBBoxRatio;
  96. }
  97. public set partitioningBBoxRatio(ratio: number) {
  98. this._facetData.partitioningBBoxRatio = ratio;
  99. }
  100. /**
  101. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  102. * Works only for updatable meshes.
  103. * Doesn't work with multi-materials
  104. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  105. */
  106. public get mustDepthSortFacets(): boolean {
  107. return this._facetData.facetDepthSort;
  108. }
  109. public set mustDepthSortFacets(sort: boolean) {
  110. this._facetData.facetDepthSort = sort;
  111. }
  112. /**
  113. * The location (Vector3) where the facet depth sort must be computed from.
  114. * By default, the active camera position.
  115. * Used only when facet depth sort is enabled
  116. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  117. */
  118. public get facetDepthSortFrom(): Vector3 {
  119. return this._facetData.facetDepthSortFrom;
  120. }
  121. public set facetDepthSortFrom(location: Vector3) {
  122. this._facetData.facetDepthSortFrom = location;
  123. }
  124. /**
  125. * gets a boolean indicating if facetData is enabled
  126. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  127. */
  128. public get isFacetDataEnabled(): boolean {
  129. return this._facetData.facetDataEnabled;
  130. }
  131. /** @hidden */
  132. public _updateNonUniformScalingState(value: boolean): boolean {
  133. if (!super._updateNonUniformScalingState(value)) {
  134. return false;
  135. }
  136. this._markSubMeshesAsMiscDirty();
  137. return true;
  138. }
  139. // Events
  140. /**
  141. * An event triggered when this mesh collides with another one
  142. */
  143. public onCollideObservable = new Observable<AbstractMesh>();
  144. private _onCollideObserver: Nullable<Observer<AbstractMesh>>;
  145. /** Set a function to call when this mesh collides with another one */
  146. public set onCollide(callback: () => void) {
  147. if (this._onCollideObserver) {
  148. this.onCollideObservable.remove(this._onCollideObserver);
  149. }
  150. this._onCollideObserver = this.onCollideObservable.add(callback);
  151. }
  152. /**
  153. * An event triggered when the collision's position changes
  154. */
  155. public onCollisionPositionChangeObservable = new Observable<Vector3>();
  156. private _onCollisionPositionChangeObserver: Nullable<Observer<Vector3>>;
  157. /** Set a function to call when the collision's position changes */
  158. public set onCollisionPositionChange(callback: () => void) {
  159. if (this._onCollisionPositionChangeObserver) {
  160. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  161. }
  162. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  163. }
  164. /**
  165. * An event triggered when material is changed
  166. */
  167. public onMaterialChangedObservable = new Observable<AbstractMesh>();
  168. // Properties
  169. /**
  170. * Gets or sets the orientation for POV movement & rotation
  171. */
  172. public definedFacingForward = true;
  173. /** @hidden */
  174. public _occlusionQuery: Nullable<WebGLQuery>;
  175. private _visibility = 1.0;
  176. /**
  177. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  178. */
  179. public get visibility(): number {
  180. return this._visibility;
  181. }
  182. /**
  183. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  184. */
  185. public set visibility(value: number) {
  186. if (this._visibility === value) {
  187. return;
  188. }
  189. this._visibility = value;
  190. this._markSubMeshesAsMiscDirty();
  191. }
  192. /** Gets or sets the alpha index used to sort transparent meshes
  193. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  194. */
  195. public alphaIndex = Number.MAX_VALUE;
  196. /**
  197. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  198. */
  199. public isVisible = true;
  200. /**
  201. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  202. */
  203. public isPickable = true;
  204. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  205. public showSubMeshesBoundingBox = false;
  206. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  207. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  208. */
  209. public isBlocker = false;
  210. /**
  211. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  212. */
  213. public enablePointerMoveEvents = false;
  214. /**
  215. * Specifies the rendering group id for this mesh (0 by default)
  216. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  217. */
  218. public renderingGroupId = 0;
  219. private _material: Nullable<Material>;
  220. /** Gets or sets current material */
  221. public get material(): Nullable<Material> {
  222. return this._material;
  223. }
  224. public set material(value: Nullable<Material>) {
  225. if (this._material === value) {
  226. return;
  227. }
  228. // remove from material mesh map id needed
  229. if (this._material && this._material.meshMap) {
  230. this._material.meshMap[this.uniqueId] = undefined;
  231. }
  232. this._material = value;
  233. if (value && value.meshMap) {
  234. value.meshMap[this.uniqueId] = this;
  235. }
  236. if (this.onMaterialChangedObservable.hasObservers) {
  237. this.onMaterialChangedObservable.notifyObservers(this);
  238. }
  239. if (!this.subMeshes) {
  240. return;
  241. }
  242. this._unBindEffect();
  243. }
  244. private _receiveShadows = false;
  245. /**
  246. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  247. * @see http://doc.babylonjs.com/babylon101/shadows
  248. */
  249. public get receiveShadows(): boolean {
  250. return this._receiveShadows;
  251. }
  252. public set receiveShadows(value: boolean) {
  253. if (this._receiveShadows === value) {
  254. return;
  255. }
  256. this._receiveShadows = value;
  257. this._markSubMeshesAsLightDirty();
  258. }
  259. /** Defines color to use when rendering outline */
  260. public outlineColor = Color3.Red();
  261. /** Define width to use when rendering outline */
  262. public outlineWidth = 0.02;
  263. /** Defines color to use when rendering overlay */
  264. public overlayColor = Color3.Red();
  265. /** Defines alpha to use when rendering overlay */
  266. public overlayAlpha = 0.5;
  267. private _hasVertexAlpha = false;
  268. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  269. public get hasVertexAlpha(): boolean {
  270. return this._hasVertexAlpha;
  271. }
  272. public set hasVertexAlpha(value: boolean) {
  273. if (this._hasVertexAlpha === value) {
  274. return;
  275. }
  276. this._hasVertexAlpha = value;
  277. this._markSubMeshesAsAttributesDirty();
  278. this._markSubMeshesAsMiscDirty();
  279. }
  280. private _useVertexColors = true;
  281. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  282. public get useVertexColors(): boolean {
  283. return this._useVertexColors;
  284. }
  285. public set useVertexColors(value: boolean) {
  286. if (this._useVertexColors === value) {
  287. return;
  288. }
  289. this._useVertexColors = value;
  290. this._markSubMeshesAsAttributesDirty();
  291. }
  292. private _computeBonesUsingShaders = true;
  293. /**
  294. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  295. */
  296. public get computeBonesUsingShaders(): boolean {
  297. return this._computeBonesUsingShaders;
  298. }
  299. public set computeBonesUsingShaders(value: boolean) {
  300. if (this._computeBonesUsingShaders === value) {
  301. return;
  302. }
  303. this._computeBonesUsingShaders = value;
  304. this._markSubMeshesAsAttributesDirty();
  305. }
  306. private _numBoneInfluencers = 4;
  307. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  308. public get numBoneInfluencers(): number {
  309. return this._numBoneInfluencers;
  310. }
  311. public set numBoneInfluencers(value: number) {
  312. if (this._numBoneInfluencers === value) {
  313. return;
  314. }
  315. this._numBoneInfluencers = value;
  316. this._markSubMeshesAsAttributesDirty();
  317. }
  318. private _applyFog = true;
  319. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  320. public get applyFog(): boolean {
  321. return this._applyFog;
  322. }
  323. public set applyFog(value: boolean) {
  324. if (this._applyFog === value) {
  325. return;
  326. }
  327. this._applyFog = value;
  328. this._markSubMeshesAsMiscDirty();
  329. }
  330. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  331. public useOctreeForRenderingSelection = true;
  332. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  333. public useOctreeForPicking = true;
  334. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  335. public useOctreeForCollisions = true;
  336. private _layerMask: number = 0x0FFFFFFF;
  337. /**
  338. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  339. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  340. */
  341. public get layerMask(): number {
  342. return this._layerMask;
  343. }
  344. public set layerMask(value: number) {
  345. if (value === this._layerMask) {
  346. return;
  347. }
  348. this._layerMask = value;
  349. this._resyncLightSources();
  350. }
  351. /**
  352. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  353. */
  354. public alwaysSelectAsActiveMesh = false;
  355. /**
  356. * Gets or sets the current action manager
  357. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  358. */
  359. public actionManager: Nullable<ActionManager> = null;
  360. // Collisions
  361. private _checkCollisions = false;
  362. private _collisionMask = -1;
  363. private _collisionGroup = -1;
  364. /**
  365. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  366. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  367. */
  368. public ellipsoid = new Vector3(0.5, 1, 0.5);
  369. /**
  370. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  371. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  372. */
  373. public ellipsoidOffset = new Vector3(0, 0, 0);
  374. private _collider: Collider;
  375. private _oldPositionForCollisions = new Vector3(0, 0, 0);
  376. private _diffPositionForCollisions = new Vector3(0, 0, 0);
  377. /**
  378. * Gets or sets a collision mask used to mask collisions (default is -1).
  379. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  380. */
  381. public get collisionMask(): number {
  382. return this._collisionMask;
  383. }
  384. public set collisionMask(mask: number) {
  385. this._collisionMask = !isNaN(mask) ? mask : -1;
  386. }
  387. /**
  388. * Gets or sets the current collision group mask (-1 by default).
  389. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  390. */
  391. public get collisionGroup(): number {
  392. return this._collisionGroup;
  393. }
  394. public set collisionGroup(mask: number) {
  395. this._collisionGroup = !isNaN(mask) ? mask : -1;
  396. }
  397. // Edges
  398. /**
  399. * Defines edge width used when edgesRenderer is enabled
  400. * @see https://www.babylonjs-playground.com/#10OJSG#13
  401. */
  402. public edgesWidth = 1;
  403. /**
  404. * Defines edge color used when edgesRenderer is enabled
  405. * @see https://www.babylonjs-playground.com/#10OJSG#13
  406. */
  407. public edgesColor = new Color4(1, 0, 0, 1);
  408. /** @hidden */
  409. public _edgesRenderer: Nullable<IEdgesRenderer>;
  410. /** @hidden */
  411. public _masterMesh: Nullable<AbstractMesh>;
  412. /** @hidden */
  413. public _boundingInfo: Nullable<BoundingInfo>;
  414. /** @hidden */
  415. public _renderId = 0;
  416. /**
  417. * Gets or sets the list of subMeshes
  418. * @see http://doc.babylonjs.com/how_to/multi_materials
  419. */
  420. public subMeshes: SubMesh[];
  421. /** @hidden */
  422. public _intersectionsInProgress = new Array<AbstractMesh>();
  423. /** @hidden */
  424. public _unIndexed = false;
  425. /** @hidden */
  426. public _lightSources = new Array<Light>();
  427. /** @hidden */
  428. public get _positions(): Nullable<Vector3[]> {
  429. return null;
  430. }
  431. // Loading properties
  432. /** @hidden */
  433. public _waitingActions: any;
  434. /** @hidden */
  435. public _waitingFreezeWorldMatrix: Nullable<boolean>;
  436. // Skeleton
  437. private _skeleton: Nullable<Skeleton>;
  438. /** @hidden */
  439. public _bonesTransformMatrices: Nullable<Float32Array>;
  440. /**
  441. * Gets or sets a skeleton to apply skining transformations
  442. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  443. */
  444. public set skeleton(value: Nullable<Skeleton>) {
  445. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  446. this._skeleton._unregisterMeshWithPoseMatrix(this);
  447. }
  448. if (value && value.needInitialSkinMatrix) {
  449. value._registerMeshWithPoseMatrix(this);
  450. }
  451. this._skeleton = value;
  452. if (!this._skeleton) {
  453. this._bonesTransformMatrices = null;
  454. }
  455. this._markSubMeshesAsAttributesDirty();
  456. }
  457. public get skeleton(): Nullable<Skeleton> {
  458. return this._skeleton;
  459. }
  460. /**
  461. * An event triggered when the mesh is rebuilt.
  462. */
  463. public onRebuildObservable = new Observable<AbstractMesh>();
  464. // Constructor
  465. /**
  466. * Creates a new AbstractMesh
  467. * @param name defines the name of the mesh
  468. * @param scene defines the hosting scene
  469. */
  470. constructor(name: string, scene: Nullable<Scene> = null) {
  471. super(name, scene, false);
  472. this.getScene().addMesh(this);
  473. this._resyncLightSources();
  474. }
  475. /**
  476. * Returns the string "AbstractMesh"
  477. * @returns "AbstractMesh"
  478. */
  479. public getClassName(): string {
  480. return "AbstractMesh";
  481. }
  482. /**
  483. * Gets a string representation of the current mesh
  484. * @param fullDetails defines a boolean indicating if full details must be included
  485. * @returns a string representation of the current mesh
  486. */
  487. public toString(fullDetails?: boolean): string {
  488. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof InstancedMesh ? "YES" : "NO");
  489. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  490. if (this._skeleton) {
  491. ret += ", skeleton: " + this._skeleton.name;
  492. }
  493. if (fullDetails) {
  494. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  495. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  496. }
  497. return ret;
  498. }
  499. /** @hidden */
  500. public _rebuild(): void {
  501. this.onRebuildObservable.notifyObservers(this);
  502. if (this._occlusionQuery) {
  503. this._occlusionQuery = null;
  504. }
  505. if (!this.subMeshes) {
  506. return;
  507. }
  508. for (var subMesh of this.subMeshes) {
  509. subMesh._rebuild();
  510. }
  511. }
  512. /** @hidden */
  513. public _resyncLightSources(): void {
  514. this._lightSources.length = 0;
  515. for (var light of this.getScene().lights) {
  516. if (!light.isEnabled()) {
  517. continue;
  518. }
  519. if (light.canAffectMesh(this)) {
  520. this._lightSources.push(light);
  521. }
  522. }
  523. this._markSubMeshesAsLightDirty();
  524. }
  525. /** @hidden */
  526. public _resyncLighSource(light: Light): void {
  527. var isIn = light.isEnabled() && light.canAffectMesh(this);
  528. var index = this._lightSources.indexOf(light);
  529. if (index === -1) {
  530. if (!isIn) {
  531. return;
  532. }
  533. this._lightSources.push(light);
  534. } else {
  535. if (isIn) {
  536. return;
  537. }
  538. this._lightSources.splice(index, 1);
  539. }
  540. this._markSubMeshesAsLightDirty();
  541. }
  542. /** @hidden */
  543. public _unBindEffect() {
  544. for (var subMesh of this.subMeshes) {
  545. subMesh.setEffect(null);
  546. }
  547. }
  548. /** @hidden */
  549. public _removeLightSource(light: Light): void {
  550. var index = this._lightSources.indexOf(light);
  551. if (index === -1) {
  552. return;
  553. }
  554. this._lightSources.splice(index, 1);
  555. this._markSubMeshesAsLightDirty();
  556. }
  557. private _markSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  558. if (!this.subMeshes) {
  559. return;
  560. }
  561. for (var subMesh of this.subMeshes) {
  562. if (subMesh._materialDefines) {
  563. func(subMesh._materialDefines);
  564. }
  565. }
  566. }
  567. /** @hidden */
  568. public _markSubMeshesAsLightDirty() {
  569. this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty());
  570. }
  571. /** @hidden */
  572. public _markSubMeshesAsAttributesDirty() {
  573. this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty());
  574. }
  575. /** @hidden */
  576. public _markSubMeshesAsMiscDirty() {
  577. if (!this.subMeshes) {
  578. return;
  579. }
  580. for (var subMesh of this.subMeshes) {
  581. var material = subMesh.getMaterial();
  582. if (material) {
  583. material.markAsDirty(Material.MiscDirtyFlag);
  584. }
  585. }
  586. }
  587. /**
  588. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  589. */
  590. public get scaling(): Vector3 {
  591. return this._scaling;
  592. }
  593. public set scaling(newScaling: Vector3) {
  594. this._scaling = newScaling;
  595. if (this.physicsImpostor) {
  596. this.physicsImpostor.forceUpdate();
  597. }
  598. }
  599. // Methods
  600. /**
  601. * Returns true if the mesh is blocked. Implemented by child classes
  602. */
  603. public get isBlocked(): boolean {
  604. return false;
  605. }
  606. /**
  607. * Returns the mesh itself by default. Implemented by child classes
  608. * @param camera defines the camera to use to pick the right LOD level
  609. * @returns the currentAbstractMesh
  610. */
  611. public getLOD(camera: Camera): Nullable<AbstractMesh> {
  612. return this;
  613. }
  614. /**
  615. * Returns 0 by default. Implemented by child classes
  616. * @returns an integer
  617. */
  618. public getTotalVertices(): number {
  619. return 0;
  620. }
  621. /**
  622. * Returns null by default. Implemented by child classes
  623. * @returns null
  624. */
  625. public getIndices(): Nullable<IndicesArray> {
  626. return null;
  627. }
  628. /**
  629. * Returns the array of the requested vertex data kind. Implemented by child classes
  630. * @param kind defines the vertex data kind to use
  631. * @returns null
  632. */
  633. public getVerticesData(kind: string): Nullable<FloatArray> {
  634. return null;
  635. }
  636. /**
  637. * Sets the vertex data of the mesh geometry for the requested `kind`.
  638. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  639. * Note that a new underlying VertexBuffer object is created each call.
  640. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  641. * @param kind defines vertex data kind:
  642. * * BABYLON.VertexBuffer.PositionKind
  643. * * BABYLON.VertexBuffer.UVKind
  644. * * BABYLON.VertexBuffer.UV2Kind
  645. * * BABYLON.VertexBuffer.UV3Kind
  646. * * BABYLON.VertexBuffer.UV4Kind
  647. * * BABYLON.VertexBuffer.UV5Kind
  648. * * BABYLON.VertexBuffer.UV6Kind
  649. * * BABYLON.VertexBuffer.ColorKind
  650. * * BABYLON.VertexBuffer.MatricesIndicesKind
  651. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  652. * * BABYLON.VertexBuffer.MatricesWeightsKind
  653. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  654. * @param data defines the data source
  655. * @param updatable defines if the data must be flagged as updatable (or static)
  656. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  657. * @returns the current mesh
  658. */
  659. public setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh {
  660. return this;
  661. }
  662. /**
  663. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  664. * If the mesh has no geometry, it is simply returned as it is.
  665. * @param kind defines vertex data kind:
  666. * * BABYLON.VertexBuffer.PositionKind
  667. * * BABYLON.VertexBuffer.UVKind
  668. * * BABYLON.VertexBuffer.UV2Kind
  669. * * BABYLON.VertexBuffer.UV3Kind
  670. * * BABYLON.VertexBuffer.UV4Kind
  671. * * BABYLON.VertexBuffer.UV5Kind
  672. * * BABYLON.VertexBuffer.UV6Kind
  673. * * BABYLON.VertexBuffer.ColorKind
  674. * * BABYLON.VertexBuffer.MatricesIndicesKind
  675. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  676. * * BABYLON.VertexBuffer.MatricesWeightsKind
  677. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  678. * @param data defines the data source
  679. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  680. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  681. * @returns the current mesh
  682. */
  683. public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh {
  684. return this;
  685. }
  686. /**
  687. * Sets the mesh indices,
  688. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  689. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  690. * @param totalVertices Defines the total number of vertices
  691. * @returns the current mesh
  692. */
  693. public setIndices(indices: IndicesArray, totalVertices: Nullable<number>): AbstractMesh {
  694. return this;
  695. }
  696. /**
  697. * Gets a boolean indicating if specific vertex data is present
  698. * @param kind defines the vertex data kind to use
  699. * @returns true is data kind is present
  700. */
  701. public isVerticesDataPresent(kind: string): boolean {
  702. return false;
  703. }
  704. /**
  705. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  706. * @returns a BoundingInfo
  707. */
  708. public getBoundingInfo(): BoundingInfo {
  709. if (this._masterMesh) {
  710. return this._masterMesh.getBoundingInfo();
  711. }
  712. if (!this._boundingInfo) {
  713. // this._boundingInfo is being created here
  714. this._updateBoundingInfo();
  715. }
  716. // cannot be null.
  717. return this._boundingInfo!;
  718. }
  719. /**
  720. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  721. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  722. * @returns the current mesh
  723. */
  724. public normalizeToUnitCube(includeDescendants = true): AbstractMesh {
  725. let boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  726. let sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  727. let maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  728. if (maxDimension === 0) {
  729. return this;
  730. }
  731. let scale = 1 / maxDimension;
  732. this.scaling.scaleInPlace(scale);
  733. return this;
  734. }
  735. /**
  736. * Overwrite the current bounding info
  737. * @param boundingInfo defines the new bounding info
  738. * @returns the current mesh
  739. */
  740. public setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh {
  741. this._boundingInfo = boundingInfo;
  742. return this;
  743. }
  744. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  745. public get useBones(): boolean {
  746. return (<boolean>(this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)));
  747. }
  748. /** @hidden */
  749. public _preActivate(): void {
  750. }
  751. /** @hidden */
  752. public _preActivateForIntermediateRendering(renderId: number): void {
  753. }
  754. /** @hidden */
  755. public _activate(renderId: number): void {
  756. this._renderId = renderId;
  757. }
  758. /**
  759. * Gets the current world matrix
  760. * @returns a Matrix
  761. */
  762. public getWorldMatrix(): Matrix {
  763. if (this._masterMesh) {
  764. return this._masterMesh.getWorldMatrix();
  765. }
  766. return super.getWorldMatrix();
  767. }
  768. /** @hidden */
  769. public _getWorldMatrixDeterminant(): number {
  770. if (this._masterMesh) {
  771. return this._masterMesh._getWorldMatrixDeterminant();
  772. }
  773. return super._getWorldMatrixDeterminant();
  774. }
  775. // ================================== Point of View Movement =================================
  776. /**
  777. * Perform relative position change from the point of view of behind the front of the mesh.
  778. * This is performed taking into account the meshes current rotation, so you do not have to care.
  779. * Supports definition of mesh facing forward or backward
  780. * @param amountRight defines the distance on the right axis
  781. * @param amountUp defines the distance on the up axis
  782. * @param amountForward defines the distance on the forward axis
  783. * @returns the current mesh
  784. */
  785. public movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh {
  786. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  787. return this;
  788. }
  789. /**
  790. * Calculate relative position change from the point of view of behind the front of the mesh.
  791. * This is performed taking into account the meshes current rotation, so you do not have to care.
  792. * Supports definition of mesh facing forward or backward
  793. * @param amountRight defines the distance on the right axis
  794. * @param amountUp defines the distance on the up axis
  795. * @param amountForward defines the distance on the forward axis
  796. * @returns the new displacement vector
  797. */
  798. public calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3 {
  799. var rotMatrix = new Matrix();
  800. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  801. rotQuaternion.toRotationMatrix(rotMatrix);
  802. var translationDelta = Vector3.Zero();
  803. var defForwardMult = this.definedFacingForward ? -1 : 1;
  804. Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  805. return translationDelta;
  806. }
  807. // ================================== Point of View Rotation =================================
  808. /**
  809. * Perform relative rotation change from the point of view of behind the front of the mesh.
  810. * Supports definition of mesh facing forward or backward
  811. * @param flipBack defines the flip
  812. * @param twirlClockwise defines the twirl
  813. * @param tiltRight defines the tilt
  814. * @returns the current mesh
  815. */
  816. public rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh {
  817. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  818. return this;
  819. }
  820. /**
  821. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  822. * Supports definition of mesh facing forward or backward.
  823. * @param flipBack defines the flip
  824. * @param twirlClockwise defines the twirl
  825. * @param tiltRight defines the tilt
  826. * @returns the new rotation vector
  827. */
  828. public calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3 {
  829. var defForwardMult = this.definedFacingForward ? 1 : -1;
  830. return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  831. }
  832. /**
  833. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  834. * @param includeDescendants Include bounding info from descendants as well (true by default)
  835. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  836. * @returns the new bounding vectors
  837. */
  838. public getHierarchyBoundingVectors(includeDescendants = true, predicate: Nullable<(abstractMesh: AbstractMesh) => boolean> = null): { min: Vector3, max: Vector3 } {
  839. // Ensures that all world matrix will be recomputed.
  840. this.getScene().incrementRenderId();
  841. this.computeWorldMatrix(true);
  842. let min: Vector3;
  843. let max: Vector3;
  844. let boundingInfo = this.getBoundingInfo();
  845. if (!this.subMeshes) {
  846. min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  847. max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  848. } else {
  849. min = boundingInfo.boundingBox.minimumWorld;
  850. max = boundingInfo.boundingBox.maximumWorld;
  851. }
  852. if (includeDescendants) {
  853. let descendants = this.getDescendants(false);
  854. for (var descendant of descendants) {
  855. let childMesh = <AbstractMesh>descendant;
  856. childMesh.computeWorldMatrix(true);
  857. // Filters meshes based on custom predicate function.
  858. if (predicate && !predicate(childMesh)) {
  859. continue;
  860. }
  861. //make sure we have the needed params to get mix and max
  862. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  863. continue;
  864. }
  865. let childBoundingInfo = childMesh.getBoundingInfo();
  866. let boundingBox = childBoundingInfo.boundingBox;
  867. var minBox = boundingBox.minimumWorld;
  868. var maxBox = boundingBox.maximumWorld;
  869. Tools.CheckExtends(minBox, min, max);
  870. Tools.CheckExtends(maxBox, min, max);
  871. }
  872. }
  873. return {
  874. min: min,
  875. max: max
  876. };
  877. }
  878. /** @hidden */
  879. public _updateBoundingInfo(): AbstractMesh {
  880. if (this._boundingInfo) {
  881. this._boundingInfo.update(this.worldMatrixFromCache);
  882. }
  883. else {
  884. this._boundingInfo = new BoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);
  885. }
  886. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  887. return this;
  888. }
  889. /** @hidden */
  890. public _updateSubMeshesBoundingInfo(matrix: Matrix): AbstractMesh {
  891. if (!this.subMeshes) {
  892. return this;
  893. }
  894. let count = this.subMeshes.length;
  895. for (var subIndex = 0; subIndex < count; subIndex++) {
  896. var subMesh = this.subMeshes[subIndex];
  897. if (count > 1 || !subMesh.IsGlobal) {
  898. subMesh.updateBoundingInfo(matrix);
  899. }
  900. }
  901. return this;
  902. }
  903. /** @hidden */
  904. protected _afterComputeWorldMatrix(): void {
  905. // Bounding info
  906. this._updateBoundingInfo();
  907. }
  908. /**
  909. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  910. * A mesh is in the frustum if its bounding box intersects the frustum
  911. * @param frustumPlanes defines the frustum to test
  912. * @returns true if the mesh is in the frustum planes
  913. */
  914. public isInFrustum(frustumPlanes: Plane[]): boolean {
  915. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  916. }
  917. /**
  918. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  919. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  920. * @param frustumPlanes defines the frustum to test
  921. * @returns true if the mesh is completely in the frustum planes
  922. */
  923. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  924. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  925. }
  926. /**
  927. * True if the mesh intersects another mesh or a SolidParticle object
  928. * @param mesh defines a target mesh or SolidParticle to test
  929. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  930. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  931. * @returns true if there is an intersection
  932. */
  933. public intersectsMesh(mesh: AbstractMesh | SolidParticle, precise: boolean = false, includeDescendants?: boolean): boolean {
  934. if (!this._boundingInfo || !mesh._boundingInfo) {
  935. return false;
  936. }
  937. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  938. return true;
  939. }
  940. if (includeDescendants) {
  941. for (var child of this.getChildMeshes()) {
  942. if (child.intersectsMesh(mesh, precise, true)) {
  943. return true;
  944. }
  945. }
  946. }
  947. return false;
  948. }
  949. /**
  950. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  951. * @param point defines the point to test
  952. * @returns true if there is an intersection
  953. */
  954. public intersectsPoint(point: Vector3): boolean {
  955. if (!this._boundingInfo) {
  956. return false;
  957. }
  958. return this._boundingInfo.intersectsPoint(point);
  959. }
  960. /**
  961. * Gets the position of the current mesh in camera space
  962. * @param camera defines the camera to use
  963. * @returns a position
  964. */
  965. public getPositionInCameraSpace(camera: Nullable<Camera> = null): Vector3 {
  966. if (!camera) {
  967. camera = (<Camera>this.getScene().activeCamera);
  968. }
  969. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  970. }
  971. /**
  972. * Returns the distance from the mesh to the active camera
  973. * @param camera defines the camera to use
  974. * @returns the distance
  975. */
  976. public getDistanceToCamera(camera: Nullable<Camera> = null): number {
  977. if (!camera) {
  978. camera = (<Camera>this.getScene().activeCamera);
  979. }
  980. return this.absolutePosition.subtract(camera.position).length();
  981. }
  982. // Collisions
  983. /**
  984. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  985. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  986. */
  987. public get checkCollisions(): boolean {
  988. return this._checkCollisions;
  989. }
  990. public set checkCollisions(collisionEnabled: boolean) {
  991. this._checkCollisions = collisionEnabled;
  992. if (this.getScene().workerCollisions) {
  993. this.getScene().collisionCoordinator.onMeshUpdated(this);
  994. }
  995. }
  996. /**
  997. * Gets Collider object used to compute collisions (not physics)
  998. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  999. */
  1000. public get collider(): Collider {
  1001. return this._collider;
  1002. }
  1003. /**
  1004. * Move the mesh using collision engine
  1005. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  1006. * @param displacement defines the requested displacement vector
  1007. * @returns the current mesh
  1008. */
  1009. public moveWithCollisions(displacement: Vector3): AbstractMesh {
  1010. var globalPosition = this.getAbsolutePosition();
  1011. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  1012. if (!this._collider) {
  1013. this._collider = new Collider();
  1014. }
  1015. this._collider._radius = this.ellipsoid;
  1016. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  1017. return this;
  1018. }
  1019. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh> = null) => {
  1020. //TODO move this to the collision coordinator!
  1021. if (this.getScene().workerCollisions) {
  1022. newPosition.multiplyInPlace(this._collider._radius);
  1023. }
  1024. newPosition.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  1025. if (this._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {
  1026. this.position.addInPlace(this._diffPositionForCollisions);
  1027. }
  1028. if (collidedMesh) {
  1029. this.onCollideObservable.notifyObservers(collidedMesh);
  1030. }
  1031. this.onCollisionPositionChangeObservable.notifyObservers(this.position);
  1032. }
  1033. // Collisions
  1034. /** @hidden */
  1035. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): AbstractMesh {
  1036. this._generatePointsArray();
  1037. if (!this._positions) {
  1038. return this;
  1039. }
  1040. // Transformation
  1041. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  1042. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  1043. subMesh._lastColliderWorldVertices = [];
  1044. subMesh._trianglePlanes = [];
  1045. var start = subMesh.verticesStart;
  1046. var end = (subMesh.verticesStart + subMesh.verticesCount);
  1047. for (var i = start; i < end; i++) {
  1048. subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  1049. }
  1050. }
  1051. // Collide
  1052. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, (<IndicesArray>this.getIndices()), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  1053. if (collider.collisionFound) {
  1054. collider.collidedMesh = this;
  1055. }
  1056. return this;
  1057. }
  1058. /** @hidden */
  1059. public _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): AbstractMesh {
  1060. const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  1061. const len = subMeshes.length;
  1062. for (var index = 0; index < len; index++) {
  1063. var subMesh = subMeshes.data[index];
  1064. // Bounding test
  1065. if (len > 1 && !subMesh._checkCollision(collider)) {
  1066. continue;
  1067. }
  1068. this._collideForSubMesh(subMesh, transformMatrix, collider);
  1069. }
  1070. return this;
  1071. }
  1072. /** @hidden */
  1073. public _checkCollision(collider: Collider): AbstractMesh {
  1074. // Bounding box test
  1075. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
  1076. return this;
  1077. }
  1078. // Transformation matrix
  1079. const collisionsScalingMatrix = Tmp.Matrix[0];
  1080. const collisionsTransformMatrix = Tmp.Matrix[1];
  1081. Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  1082. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  1083. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  1084. return this;
  1085. }
  1086. // Picking
  1087. /** @hidden */
  1088. public _generatePointsArray(): boolean {
  1089. return false;
  1090. }
  1091. /**
  1092. * Checks if the passed Ray intersects with the mesh
  1093. * @param ray defines the ray to use
  1094. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  1095. * @returns the picking info
  1096. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  1097. */
  1098. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  1099. var pickingInfo = new PickingInfo();
  1100. const intersectionTreshold = this.getClassName() === "LinesMesh" ? (<LinesMesh>(this as any)).intersectionThreshold : 0;
  1101. const boundingInfo = this._boundingInfo;
  1102. if (!this.subMeshes || !boundingInfo || !ray.intersectsSphere(boundingInfo.boundingSphere, intersectionTreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionTreshold)) {
  1103. return pickingInfo;
  1104. }
  1105. if (!this._generatePointsArray()) {
  1106. return pickingInfo;
  1107. }
  1108. var intersectInfo: Nullable<IntersectionInfo> = null;
  1109. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  1110. var len: number = subMeshes.length;
  1111. for (var index = 0; index < len; index++) {
  1112. var subMesh = subMeshes.data[index];
  1113. // Bounding test
  1114. if (len > 1 && !subMesh.canIntersects(ray)) {
  1115. continue;
  1116. }
  1117. var currentIntersectInfo = subMesh.intersects(ray, (<Vector3[]>this._positions), (<IndicesArray>this.getIndices()), fastCheck);
  1118. if (currentIntersectInfo) {
  1119. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  1120. intersectInfo = currentIntersectInfo;
  1121. intersectInfo.subMeshId = index;
  1122. if (fastCheck) {
  1123. break;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. if (intersectInfo) {
  1129. // Get picked point
  1130. const world = this.getWorldMatrix();
  1131. const worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  1132. const direction = ray.direction.scaleToRef(intersectInfo.distance, Tmp.Vector3[0]);
  1133. const worldDirection = Vector3.TransformNormal(direction, world);
  1134. const pickedPoint = worldDirection.addInPlace(worldOrigin);
  1135. // Return result
  1136. pickingInfo.hit = true;
  1137. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  1138. pickingInfo.pickedPoint = pickedPoint;
  1139. pickingInfo.pickedMesh = this;
  1140. pickingInfo.bu = intersectInfo.bu || 0;
  1141. pickingInfo.bv = intersectInfo.bv || 0;
  1142. pickingInfo.faceId = intersectInfo.faceId;
  1143. pickingInfo.subMeshId = intersectInfo.subMeshId;
  1144. return pickingInfo;
  1145. }
  1146. return pickingInfo;
  1147. }
  1148. /**
  1149. * Clones the current mesh
  1150. * @param name defines the mesh name
  1151. * @param newParent defines the new mesh parent
  1152. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  1153. * @returns the new mesh
  1154. */
  1155. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable<AbstractMesh> {
  1156. return null;
  1157. }
  1158. /**
  1159. * Disposes all the submeshes of the current meshnp
  1160. * @returns the current mesh
  1161. */
  1162. public releaseSubMeshes(): AbstractMesh {
  1163. if (this.subMeshes) {
  1164. while (this.subMeshes.length) {
  1165. this.subMeshes[0].dispose();
  1166. }
  1167. } else {
  1168. this.subMeshes = new Array<SubMesh>();
  1169. }
  1170. return this;
  1171. }
  1172. /**
  1173. * Releases resources associated with this abstract mesh.
  1174. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  1175. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  1176. */
  1177. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  1178. var index: number;
  1179. // Smart Array Retainers.
  1180. this.getScene().freeActiveMeshes();
  1181. this.getScene().freeRenderingGroups();
  1182. // Action manager
  1183. if (this.actionManager !== undefined && this.actionManager !== null) {
  1184. this.actionManager.dispose();
  1185. this.actionManager = null;
  1186. }
  1187. // Skeleton
  1188. this._skeleton = null;
  1189. // Intersections in progress
  1190. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  1191. var other = this._intersectionsInProgress[index];
  1192. var pos = other._intersectionsInProgress.indexOf(this);
  1193. other._intersectionsInProgress.splice(pos, 1);
  1194. }
  1195. this._intersectionsInProgress = [];
  1196. // Lights
  1197. var lights = this.getScene().lights;
  1198. lights.forEach((light: Light) => {
  1199. var meshIndex = light.includedOnlyMeshes.indexOf(this);
  1200. if (meshIndex !== -1) {
  1201. light.includedOnlyMeshes.splice(meshIndex, 1);
  1202. }
  1203. meshIndex = light.excludedMeshes.indexOf(this);
  1204. if (meshIndex !== -1) {
  1205. light.excludedMeshes.splice(meshIndex, 1);
  1206. }
  1207. // Shadow generators
  1208. var generator = light.getShadowGenerator();
  1209. if (generator) {
  1210. var shadowMap = generator.getShadowMap();
  1211. if (shadowMap && shadowMap.renderList) {
  1212. meshIndex = shadowMap.renderList.indexOf(this);
  1213. if (meshIndex !== -1) {
  1214. shadowMap.renderList.splice(meshIndex, 1);
  1215. }
  1216. }
  1217. }
  1218. });
  1219. // SubMeshes
  1220. if (this.getClassName() !== "InstancedMesh") {
  1221. this.releaseSubMeshes();
  1222. }
  1223. // Query
  1224. let engine = this.getScene().getEngine();
  1225. if (this._occlusionQuery) {
  1226. this.isOcclusionQueryInProgress = false;
  1227. engine.deleteQuery(this._occlusionQuery);
  1228. this._occlusionQuery = null;
  1229. }
  1230. // Engine
  1231. engine.wipeCaches();
  1232. // Remove from scene
  1233. this.getScene().removeMesh(this);
  1234. if (disposeMaterialAndTextures) {
  1235. if (this.material) {
  1236. this.material.dispose(false, true);
  1237. }
  1238. }
  1239. if (!doNotRecurse) {
  1240. // Particles
  1241. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  1242. if (this.getScene().particleSystems[index].emitter === this) {
  1243. this.getScene().particleSystems[index].dispose();
  1244. index--;
  1245. }
  1246. }
  1247. }
  1248. // facet data
  1249. if (this._facetData.facetDataEnabled) {
  1250. this.disableFacetData();
  1251. }
  1252. this.onAfterWorldMatrixUpdateObservable.clear();
  1253. this.onCollideObservable.clear();
  1254. this.onCollisionPositionChangeObservable.clear();
  1255. this.onRebuildObservable.clear();
  1256. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1257. }
  1258. /**
  1259. * Adds the passed mesh as a child to the current mesh
  1260. * @param mesh defines the child mesh
  1261. * @returns the current mesh
  1262. */
  1263. public addChild(mesh: AbstractMesh): AbstractMesh {
  1264. mesh.setParent(this);
  1265. return this;
  1266. }
  1267. /**
  1268. * Removes the passed mesh from the current mesh children list
  1269. * @param mesh defines the child mesh
  1270. * @returns the current mesh
  1271. */
  1272. public removeChild(mesh: AbstractMesh): AbstractMesh {
  1273. mesh.setParent(null);
  1274. return this;
  1275. }
  1276. // Facet data
  1277. /** @hidden */
  1278. private _initFacetData(): AbstractMesh {
  1279. const data = this._facetData;
  1280. if (!data.facetNormals) {
  1281. data.facetNormals = new Array<Vector3>();
  1282. }
  1283. if (!data.facetPositions) {
  1284. data.facetPositions = new Array<Vector3>();
  1285. }
  1286. if (!data.facetPartitioning) {
  1287. data.facetPartitioning = new Array<number[]>();
  1288. }
  1289. data.facetNb = ((<IndicesArray>this.getIndices()).length / 3) | 0;
  1290. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  1291. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  1292. for (var f = 0; f < data.facetNb; f++) {
  1293. data.facetNormals[f] = Vector3.Zero();
  1294. data.facetPositions[f] = Vector3.Zero();
  1295. }
  1296. data.facetDataEnabled = true;
  1297. return this;
  1298. }
  1299. /**
  1300. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  1301. * This method can be called within the render loop.
  1302. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
  1303. * @returns the current mesh
  1304. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1305. */
  1306. public updateFacetData(): AbstractMesh {
  1307. const data = this._facetData;
  1308. if (!data.facetDataEnabled) {
  1309. this._initFacetData();
  1310. }
  1311. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1312. var indices = this.getIndices();
  1313. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1314. var bInfo = this.getBoundingInfo();
  1315. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  1316. // init arrays, matrix and sort function on first call
  1317. data.facetDepthSortEnabled = true;
  1318. if (indices instanceof Uint16Array) {
  1319. data.depthSortedIndices = new Uint16Array(indices!);
  1320. }
  1321. else if (indices instanceof Uint32Array) {
  1322. data.depthSortedIndices = new Uint32Array(indices!);
  1323. }
  1324. else {
  1325. var needs32bits = false;
  1326. for (var i = 0; i < indices!.length; i++) {
  1327. if (indices![i] > 65535) {
  1328. needs32bits = true;
  1329. break;
  1330. }
  1331. }
  1332. if (needs32bits) {
  1333. data.depthSortedIndices = new Uint32Array(indices!);
  1334. }
  1335. else {
  1336. data.depthSortedIndices = new Uint16Array(indices!);
  1337. }
  1338. }
  1339. data.facetDepthSortFunction = function(f1, f2) {
  1340. return (f2.sqDistance - f1.sqDistance);
  1341. };
  1342. if (!data.facetDepthSortFrom) {
  1343. var camera = this.getScene().activeCamera;
  1344. data.facetDepthSortFrom = (camera) ? camera.position : Vector3.Zero();
  1345. }
  1346. data.depthSortedFacets = [];
  1347. for (var f = 0; f < data.facetNb; f++) {
  1348. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  1349. data.depthSortedFacets.push(depthSortedFacet);
  1350. }
  1351. data.invertedMatrix = Matrix.Identity();
  1352. data.facetDepthSortOrigin = Vector3.Zero();
  1353. }
  1354. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
  1355. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
  1356. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
  1357. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  1358. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  1359. data.subDiv.max = data.partitioningSubdivisions;
  1360. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  1361. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  1362. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  1363. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  1364. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  1365. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  1366. // set the parameters for ComputeNormals()
  1367. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  1368. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  1369. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  1370. data.facetParameters.bInfo = bInfo;
  1371. data.facetParameters.bbSize = data.bbSize;
  1372. data.facetParameters.subDiv = data.subDiv;
  1373. data.facetParameters.ratio = this.partitioningBBoxRatio;
  1374. data.facetParameters.depthSort = data.facetDepthSort;
  1375. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  1376. this.computeWorldMatrix(true);
  1377. this._worldMatrix.invertToRef(data.invertedMatrix);
  1378. Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  1379. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  1380. }
  1381. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  1382. VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  1383. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  1384. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  1385. var l = (data.depthSortedIndices.length / 3) | 0;
  1386. for (var f = 0; f < l; f++) {
  1387. var sind = data.depthSortedFacets[f].ind;
  1388. data.depthSortedIndices[f * 3] = indices![sind];
  1389. data.depthSortedIndices[f * 3 + 1] = indices![sind + 1];
  1390. data.depthSortedIndices[f * 3 + 2] = indices![sind + 2];
  1391. }
  1392. this.updateIndices(data.depthSortedIndices);
  1393. }
  1394. return this;
  1395. }
  1396. /**
  1397. * Returns the facetLocalNormals array.
  1398. * The normals are expressed in the mesh local spac
  1399. * @returns an array of Vector3
  1400. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1401. */
  1402. public getFacetLocalNormals(): Vector3[] {
  1403. if (!this._facetData.facetNormals) {
  1404. this.updateFacetData();
  1405. }
  1406. return this._facetData.facetNormals;
  1407. }
  1408. /**
  1409. * Returns the facetLocalPositions array.
  1410. * The facet positions are expressed in the mesh local space
  1411. * @returns an array of Vector3
  1412. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1413. */
  1414. public getFacetLocalPositions(): Vector3[] {
  1415. if (!this._facetData.facetPositions) {
  1416. this.updateFacetData();
  1417. }
  1418. return this._facetData.facetPositions;
  1419. }
  1420. /**
  1421. * Returns the facetLocalPartioning array
  1422. * @returns an array of array of numbers
  1423. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1424. */
  1425. public getFacetLocalPartitioning(): number[][] {
  1426. if (!this._facetData.facetPartitioning) {
  1427. this.updateFacetData();
  1428. }
  1429. return this._facetData.facetPartitioning;
  1430. }
  1431. /**
  1432. * Returns the i-th facet position in the world system.
  1433. * This method allocates a new Vector3 per call
  1434. * @param i defines the facet index
  1435. * @returns a new Vector3
  1436. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1437. */
  1438. public getFacetPosition(i: number): Vector3 {
  1439. var pos = Vector3.Zero();
  1440. this.getFacetPositionToRef(i, pos);
  1441. return pos;
  1442. }
  1443. /**
  1444. * Sets the reference Vector3 with the i-th facet position in the world system
  1445. * @param i defines the facet index
  1446. * @param ref defines the target vector
  1447. * @returns the current mesh
  1448. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1449. */
  1450. public getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh {
  1451. var localPos = (this.getFacetLocalPositions())[i];
  1452. var world = this.getWorldMatrix();
  1453. Vector3.TransformCoordinatesToRef(localPos, world, ref);
  1454. return this;
  1455. }
  1456. /**
  1457. * Returns the i-th facet normal in the world system.
  1458. * This method allocates a new Vector3 per call
  1459. * @param i defines the facet index
  1460. * @returns a new Vector3
  1461. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1462. */
  1463. public getFacetNormal(i: number): Vector3 {
  1464. var norm = Vector3.Zero();
  1465. this.getFacetNormalToRef(i, norm);
  1466. return norm;
  1467. }
  1468. /**
  1469. * Sets the reference Vector3 with the i-th facet normal in the world system
  1470. * @param i defines the facet index
  1471. * @param ref defines the target vector
  1472. * @returns the current mesh
  1473. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1474. */
  1475. public getFacetNormalToRef(i: number, ref: Vector3) {
  1476. var localNorm = (this.getFacetLocalNormals())[i];
  1477. Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  1478. return this;
  1479. }
  1480. /**
  1481. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
  1482. * @param x defines x coordinate
  1483. * @param y defines y coordinate
  1484. * @param z defines z coordinate
  1485. * @returns the array of facet indexes
  1486. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1487. */
  1488. public getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable<number[]> {
  1489. var bInfo = this.getBoundingInfo();
  1490. const data = this._facetData;
  1491. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  1492. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  1493. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  1494. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  1495. return null;
  1496. }
  1497. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  1498. }
  1499. /**
  1500. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  1501. * @param projected sets as the (x,y,z) world projection on the facet
  1502. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  1503. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  1504. * @param x defines x coordinate
  1505. * @param y defines y coordinate
  1506. * @param z defines z coordinate
  1507. * @returns the face index if found (or null instead)
  1508. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1509. */
  1510. public getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): Nullable<number> {
  1511. var world = this.getWorldMatrix();
  1512. var invMat = Tmp.Matrix[5];
  1513. world.invertToRef(invMat);
  1514. var invVect = Tmp.Vector3[8];
  1515. Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  1516. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  1517. if (projected) {
  1518. // tranform the local computed projected vector to world coordinates
  1519. Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  1520. }
  1521. return closest;
  1522. }
  1523. /**
  1524. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  1525. * @param projected sets as the (x,y,z) local projection on the facet
  1526. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  1527. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  1528. * @param x defines x coordinate
  1529. * @param y defines y coordinate
  1530. * @param z defines z coordinate
  1531. * @returns the face index if found (or null instead)
  1532. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1533. */
  1534. public getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): Nullable<number> {
  1535. var closest = null;
  1536. var tmpx = 0.0;
  1537. var tmpy = 0.0;
  1538. var tmpz = 0.0;
  1539. var d = 0.0; // tmp dot facet normal * facet position
  1540. var t0 = 0.0;
  1541. var projx = 0.0;
  1542. var projy = 0.0;
  1543. var projz = 0.0;
  1544. // Get all the facets in the same partitioning block than (x, y, z)
  1545. var facetPositions = this.getFacetLocalPositions();
  1546. var facetNormals = this.getFacetLocalNormals();
  1547. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  1548. if (!facetsInBlock) {
  1549. return null;
  1550. }
  1551. // Get the closest facet to (x, y, z)
  1552. var shortest = Number.MAX_VALUE; // init distance vars
  1553. var tmpDistance = shortest;
  1554. var fib; // current facet in the block
  1555. var norm; // current facet normal
  1556. var p0; // current facet barycenter position
  1557. // loop on all the facets in the current partitioning block
  1558. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  1559. fib = facetsInBlock[idx];
  1560. norm = facetNormals[fib];
  1561. p0 = facetPositions[fib];
  1562. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  1563. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  1564. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  1565. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  1566. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  1567. projx = x + norm.x * t0;
  1568. projy = y + norm.y * t0;
  1569. projz = z + norm.z * t0;
  1570. tmpx = projx - x;
  1571. tmpy = projy - y;
  1572. tmpz = projz - z;
  1573. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  1574. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  1575. shortest = tmpDistance;
  1576. closest = fib;
  1577. if (projected) {
  1578. projected.x = projx;
  1579. projected.y = projy;
  1580. projected.z = projz;
  1581. }
  1582. }
  1583. }
  1584. }
  1585. return closest;
  1586. }
  1587. /**
  1588. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  1589. * @returns the parameters
  1590. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1591. */
  1592. public getFacetDataParameters(): any {
  1593. return this._facetData.facetParameters;
  1594. }
  1595. /**
  1596. * Disables the feature FacetData and frees the related memory
  1597. * @returns the current mesh
  1598. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1599. */
  1600. public disableFacetData(): AbstractMesh {
  1601. if (this._facetData.facetDataEnabled) {
  1602. this._facetData.facetDataEnabled = false;
  1603. this._facetData.facetPositions = new Array<Vector3>();
  1604. this._facetData.facetNormals = new Array<Vector3>();
  1605. this._facetData.facetPartitioning = new Array<number[]>();
  1606. this._facetData.facetParameters = null;
  1607. this._facetData.depthSortedIndices = new Uint32Array(0);
  1608. }
  1609. return this;
  1610. }
  1611. /**
  1612. * Updates the AbstractMesh indices array
  1613. * @param indices defines the data source
  1614. * @returns the current mesh
  1615. */
  1616. public updateIndices(indices: IndicesArray): AbstractMesh {
  1617. return this;
  1618. }
  1619. /**
  1620. * Creates new normals data for the mesh
  1621. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  1622. * @returns the current mesh
  1623. */
  1624. public createNormals(updatable: boolean): AbstractMesh {
  1625. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1626. var indices = this.getIndices();
  1627. var normals: FloatArray;
  1628. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1629. normals = (<FloatArray>this.getVerticesData(VertexBuffer.NormalKind));
  1630. } else {
  1631. normals = [];
  1632. }
  1633. VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  1634. this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
  1635. return this;
  1636. }
  1637. /**
  1638. * Align the mesh with a normal
  1639. * @param normal defines the normal to use
  1640. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  1641. * @returns the current mesh
  1642. */
  1643. public alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh {
  1644. if (!upDirection) {
  1645. upDirection = Axis.Y;
  1646. }
  1647. var axisX = Tmp.Vector3[0];
  1648. var axisZ = Tmp.Vector3[1];
  1649. Vector3.CrossToRef(upDirection, normal, axisZ);
  1650. Vector3.CrossToRef(normal, axisZ, axisX);
  1651. if (this.rotationQuaternion) {
  1652. Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  1653. } else {
  1654. Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  1655. }
  1656. return this;
  1657. }
  1658. /** @hidden */
  1659. public _checkOcclusionQuery(): boolean { // Will be replaced by correct code if Occlusion queries are referenced
  1660. return false;
  1661. }
  1662. }
  1663. }