babylon.abstractMesh.ts 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  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. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  1101. return pickingInfo;
  1102. }
  1103. if (!this._generatePointsArray()) {
  1104. return pickingInfo;
  1105. }
  1106. var intersectInfo: Nullable<IntersectionInfo> = null;
  1107. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  1108. var len: number = subMeshes.length;
  1109. for (var index = 0; index < len; index++) {
  1110. var subMesh = subMeshes.data[index];
  1111. // Bounding test
  1112. if (len > 1 && !subMesh.canIntersects(ray)) {
  1113. continue;
  1114. }
  1115. var currentIntersectInfo = subMesh.intersects(ray, (<Vector3[]>this._positions), (<IndicesArray>this.getIndices()), fastCheck);
  1116. if (currentIntersectInfo) {
  1117. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  1118. intersectInfo = currentIntersectInfo;
  1119. intersectInfo.subMeshId = index;
  1120. if (fastCheck) {
  1121. break;
  1122. }
  1123. }
  1124. }
  1125. }
  1126. if (intersectInfo) {
  1127. // Get picked point
  1128. var world = this.getWorldMatrix();
  1129. var worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  1130. var direction = ray.direction.clone();
  1131. direction = direction.scale(intersectInfo.distance);
  1132. var worldDirection = Vector3.TransformNormal(direction, world);
  1133. var pickedPoint = worldOrigin.add(worldDirection);
  1134. // Return result
  1135. pickingInfo.hit = true;
  1136. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  1137. pickingInfo.pickedPoint = pickedPoint;
  1138. pickingInfo.pickedMesh = this;
  1139. pickingInfo.bu = intersectInfo.bu || 0;
  1140. pickingInfo.bv = intersectInfo.bv || 0;
  1141. pickingInfo.faceId = intersectInfo.faceId;
  1142. pickingInfo.subMeshId = intersectInfo.subMeshId;
  1143. return pickingInfo;
  1144. }
  1145. return pickingInfo;
  1146. }
  1147. /**
  1148. * Clones the current mesh
  1149. * @param name defines the mesh name
  1150. * @param newParent defines the new mesh parent
  1151. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  1152. * @returns the new mesh
  1153. */
  1154. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable<AbstractMesh> {
  1155. return null;
  1156. }
  1157. /**
  1158. * Disposes all the submeshes of the current meshnp
  1159. * @returns the current mesh
  1160. */
  1161. public releaseSubMeshes(): AbstractMesh {
  1162. if (this.subMeshes) {
  1163. while (this.subMeshes.length) {
  1164. this.subMeshes[0].dispose();
  1165. }
  1166. } else {
  1167. this.subMeshes = new Array<SubMesh>();
  1168. }
  1169. return this;
  1170. }
  1171. /**
  1172. * Releases resources associated with this abstract mesh.
  1173. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  1174. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  1175. */
  1176. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  1177. var index: number;
  1178. // Smart Array Retainers.
  1179. this.getScene().freeActiveMeshes();
  1180. this.getScene().freeRenderingGroups();
  1181. // Action manager
  1182. if (this.actionManager !== undefined && this.actionManager !== null) {
  1183. this.actionManager.dispose();
  1184. this.actionManager = null;
  1185. }
  1186. // Skeleton
  1187. this._skeleton = null;
  1188. // Intersections in progress
  1189. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  1190. var other = this._intersectionsInProgress[index];
  1191. var pos = other._intersectionsInProgress.indexOf(this);
  1192. other._intersectionsInProgress.splice(pos, 1);
  1193. }
  1194. this._intersectionsInProgress = [];
  1195. // Lights
  1196. var lights = this.getScene().lights;
  1197. lights.forEach((light: Light) => {
  1198. var meshIndex = light.includedOnlyMeshes.indexOf(this);
  1199. if (meshIndex !== -1) {
  1200. light.includedOnlyMeshes.splice(meshIndex, 1);
  1201. }
  1202. meshIndex = light.excludedMeshes.indexOf(this);
  1203. if (meshIndex !== -1) {
  1204. light.excludedMeshes.splice(meshIndex, 1);
  1205. }
  1206. // Shadow generators
  1207. var generator = light.getShadowGenerator();
  1208. if (generator) {
  1209. var shadowMap = generator.getShadowMap();
  1210. if (shadowMap && shadowMap.renderList) {
  1211. meshIndex = shadowMap.renderList.indexOf(this);
  1212. if (meshIndex !== -1) {
  1213. shadowMap.renderList.splice(meshIndex, 1);
  1214. }
  1215. }
  1216. }
  1217. });
  1218. // SubMeshes
  1219. if (this.getClassName() !== "InstancedMesh") {
  1220. this.releaseSubMeshes();
  1221. }
  1222. // Query
  1223. let engine = this.getScene().getEngine();
  1224. if (this._occlusionQuery) {
  1225. this.isOcclusionQueryInProgress = false;
  1226. engine.deleteQuery(this._occlusionQuery);
  1227. this._occlusionQuery = null;
  1228. }
  1229. // Engine
  1230. engine.wipeCaches();
  1231. // Remove from scene
  1232. this.getScene().removeMesh(this);
  1233. if (disposeMaterialAndTextures) {
  1234. if (this.material) {
  1235. this.material.dispose(false, true);
  1236. }
  1237. }
  1238. if (!doNotRecurse) {
  1239. // Particles
  1240. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  1241. if (this.getScene().particleSystems[index].emitter === this) {
  1242. this.getScene().particleSystems[index].dispose();
  1243. index--;
  1244. }
  1245. }
  1246. }
  1247. // facet data
  1248. if (this._facetData.facetDataEnabled) {
  1249. this.disableFacetData();
  1250. }
  1251. this.onAfterWorldMatrixUpdateObservable.clear();
  1252. this.onCollideObservable.clear();
  1253. this.onCollisionPositionChangeObservable.clear();
  1254. this.onRebuildObservable.clear();
  1255. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1256. }
  1257. /**
  1258. * Adds the passed mesh as a child to the current mesh
  1259. * @param mesh defines the child mesh
  1260. * @returns the current mesh
  1261. */
  1262. public addChild(mesh: AbstractMesh): AbstractMesh {
  1263. mesh.setParent(this);
  1264. return this;
  1265. }
  1266. /**
  1267. * Removes the passed mesh from the current mesh children list
  1268. * @param mesh defines the child mesh
  1269. * @returns the current mesh
  1270. */
  1271. public removeChild(mesh: AbstractMesh): AbstractMesh {
  1272. mesh.setParent(null);
  1273. return this;
  1274. }
  1275. // Facet data
  1276. /** @hidden */
  1277. private _initFacetData(): AbstractMesh {
  1278. const data = this._facetData;
  1279. if (!data.facetNormals) {
  1280. data.facetNormals = new Array<Vector3>();
  1281. }
  1282. if (!data.facetPositions) {
  1283. data.facetPositions = new Array<Vector3>();
  1284. }
  1285. if (!data.facetPartitioning) {
  1286. data.facetPartitioning = new Array<number[]>();
  1287. }
  1288. data.facetNb = ((<IndicesArray>this.getIndices()).length / 3) | 0;
  1289. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  1290. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  1291. for (var f = 0; f < data.facetNb; f++) {
  1292. data.facetNormals[f] = Vector3.Zero();
  1293. data.facetPositions[f] = Vector3.Zero();
  1294. }
  1295. data.facetDataEnabled = true;
  1296. return this;
  1297. }
  1298. /**
  1299. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  1300. * This method can be called within the render loop.
  1301. * 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
  1302. * @returns the current mesh
  1303. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1304. */
  1305. public updateFacetData(): AbstractMesh {
  1306. const data = this._facetData;
  1307. if (!data.facetDataEnabled) {
  1308. this._initFacetData();
  1309. }
  1310. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1311. var indices = this.getIndices();
  1312. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1313. var bInfo = this.getBoundingInfo();
  1314. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  1315. // init arrays, matrix and sort function on first call
  1316. data.facetDepthSortEnabled = true;
  1317. if (indices instanceof Uint16Array) {
  1318. data.depthSortedIndices = new Uint16Array(indices!);
  1319. }
  1320. else if (indices instanceof Uint32Array) {
  1321. data.depthSortedIndices = new Uint32Array(indices!);
  1322. }
  1323. else {
  1324. var needs32bits = false;
  1325. for (var i = 0; i < indices!.length; i++) {
  1326. if (indices![i] > 65535) {
  1327. needs32bits = true;
  1328. break;
  1329. }
  1330. }
  1331. if (needs32bits) {
  1332. data.depthSortedIndices = new Uint32Array(indices!);
  1333. }
  1334. else {
  1335. data.depthSortedIndices = new Uint16Array(indices!);
  1336. }
  1337. }
  1338. data.facetDepthSortFunction = function(f1, f2) {
  1339. return (f2.sqDistance - f1.sqDistance);
  1340. };
  1341. if (!data.facetDepthSortFrom) {
  1342. var camera = this.getScene().activeCamera;
  1343. data.facetDepthSortFrom = (camera) ? camera.position : Vector3.Zero();
  1344. }
  1345. data.depthSortedFacets = [];
  1346. for (var f = 0; f < data.facetNb; f++) {
  1347. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  1348. data.depthSortedFacets.push(depthSortedFacet);
  1349. }
  1350. data.invertedMatrix = Matrix.Identity();
  1351. data.facetDepthSortOrigin = Vector3.Zero();
  1352. }
  1353. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
  1354. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
  1355. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
  1356. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  1357. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  1358. data.subDiv.max = data.partitioningSubdivisions;
  1359. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  1360. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  1361. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  1362. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  1363. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  1364. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  1365. // set the parameters for ComputeNormals()
  1366. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  1367. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  1368. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  1369. data.facetParameters.bInfo = bInfo;
  1370. data.facetParameters.bbSize = data.bbSize;
  1371. data.facetParameters.subDiv = data.subDiv;
  1372. data.facetParameters.ratio = this.partitioningBBoxRatio;
  1373. data.facetParameters.depthSort = data.facetDepthSort;
  1374. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  1375. this.computeWorldMatrix(true);
  1376. this._worldMatrix.invertToRef(data.invertedMatrix);
  1377. Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  1378. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  1379. }
  1380. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  1381. VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  1382. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  1383. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  1384. var l = (data.depthSortedIndices.length / 3) | 0;
  1385. for (var f = 0; f < l; f++) {
  1386. var sind = data.depthSortedFacets[f].ind;
  1387. data.depthSortedIndices[f * 3] = indices![sind];
  1388. data.depthSortedIndices[f * 3 + 1] = indices![sind + 1];
  1389. data.depthSortedIndices[f * 3 + 2] = indices![sind + 2];
  1390. }
  1391. this.updateIndices(data.depthSortedIndices);
  1392. }
  1393. return this;
  1394. }
  1395. /**
  1396. * Returns the facetLocalNormals array.
  1397. * The normals are expressed in the mesh local spac
  1398. * @returns an array of Vector3
  1399. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1400. */
  1401. public getFacetLocalNormals(): Vector3[] {
  1402. if (!this._facetData.facetNormals) {
  1403. this.updateFacetData();
  1404. }
  1405. return this._facetData.facetNormals;
  1406. }
  1407. /**
  1408. * Returns the facetLocalPositions array.
  1409. * The facet positions are expressed in the mesh local space
  1410. * @returns an array of Vector3
  1411. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1412. */
  1413. public getFacetLocalPositions(): Vector3[] {
  1414. if (!this._facetData.facetPositions) {
  1415. this.updateFacetData();
  1416. }
  1417. return this._facetData.facetPositions;
  1418. }
  1419. /**
  1420. * Returns the facetLocalPartioning array
  1421. * @returns an array of array of numbers
  1422. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1423. */
  1424. public getFacetLocalPartitioning(): number[][] {
  1425. if (!this._facetData.facetPartitioning) {
  1426. this.updateFacetData();
  1427. }
  1428. return this._facetData.facetPartitioning;
  1429. }
  1430. /**
  1431. * Returns the i-th facet position in the world system.
  1432. * This method allocates a new Vector3 per call
  1433. * @param i defines the facet index
  1434. * @returns a new Vector3
  1435. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1436. */
  1437. public getFacetPosition(i: number): Vector3 {
  1438. var pos = Vector3.Zero();
  1439. this.getFacetPositionToRef(i, pos);
  1440. return pos;
  1441. }
  1442. /**
  1443. * Sets the reference Vector3 with the i-th facet position in the world system
  1444. * @param i defines the facet index
  1445. * @param ref defines the target vector
  1446. * @returns the current mesh
  1447. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1448. */
  1449. public getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh {
  1450. var localPos = (this.getFacetLocalPositions())[i];
  1451. var world = this.getWorldMatrix();
  1452. Vector3.TransformCoordinatesToRef(localPos, world, ref);
  1453. return this;
  1454. }
  1455. /**
  1456. * Returns the i-th facet normal in the world system.
  1457. * This method allocates a new Vector3 per call
  1458. * @param i defines the facet index
  1459. * @returns a new Vector3
  1460. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1461. */
  1462. public getFacetNormal(i: number): Vector3 {
  1463. var norm = Vector3.Zero();
  1464. this.getFacetNormalToRef(i, norm);
  1465. return norm;
  1466. }
  1467. /**
  1468. * Sets the reference Vector3 with the i-th facet normal in the world system
  1469. * @param i defines the facet index
  1470. * @param ref defines the target vector
  1471. * @returns the current mesh
  1472. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1473. */
  1474. public getFacetNormalToRef(i: number, ref: Vector3) {
  1475. var localNorm = (this.getFacetLocalNormals())[i];
  1476. Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  1477. return this;
  1478. }
  1479. /**
  1480. * 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)
  1481. * @param x defines x coordinate
  1482. * @param y defines y coordinate
  1483. * @param z defines z coordinate
  1484. * @returns the array of facet indexes
  1485. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1486. */
  1487. public getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable<number[]> {
  1488. var bInfo = this.getBoundingInfo();
  1489. const data = this._facetData;
  1490. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  1491. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  1492. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  1493. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  1494. return null;
  1495. }
  1496. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  1497. }
  1498. /**
  1499. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  1500. * @param projected sets as the (x,y,z) world projection on the facet
  1501. * @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
  1502. * @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
  1503. * @param x defines x coordinate
  1504. * @param y defines y coordinate
  1505. * @param z defines z coordinate
  1506. * @returns the face index if found (or null instead)
  1507. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1508. */
  1509. public getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): Nullable<number> {
  1510. var world = this.getWorldMatrix();
  1511. var invMat = Tmp.Matrix[5];
  1512. world.invertToRef(invMat);
  1513. var invVect = Tmp.Vector3[8];
  1514. Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  1515. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  1516. if (projected) {
  1517. // tranform the local computed projected vector to world coordinates
  1518. Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  1519. }
  1520. return closest;
  1521. }
  1522. /**
  1523. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  1524. * @param projected sets as the (x,y,z) local projection on the facet
  1525. * @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
  1526. * @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
  1527. * @param x defines x coordinate
  1528. * @param y defines y coordinate
  1529. * @param z defines z coordinate
  1530. * @returns the face index if found (or null instead)
  1531. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1532. */
  1533. public getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): Nullable<number> {
  1534. var closest = null;
  1535. var tmpx = 0.0;
  1536. var tmpy = 0.0;
  1537. var tmpz = 0.0;
  1538. var d = 0.0; // tmp dot facet normal * facet position
  1539. var t0 = 0.0;
  1540. var projx = 0.0;
  1541. var projy = 0.0;
  1542. var projz = 0.0;
  1543. // Get all the facets in the same partitioning block than (x, y, z)
  1544. var facetPositions = this.getFacetLocalPositions();
  1545. var facetNormals = this.getFacetLocalNormals();
  1546. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  1547. if (!facetsInBlock) {
  1548. return null;
  1549. }
  1550. // Get the closest facet to (x, y, z)
  1551. var shortest = Number.MAX_VALUE; // init distance vars
  1552. var tmpDistance = shortest;
  1553. var fib; // current facet in the block
  1554. var norm; // current facet normal
  1555. var p0; // current facet barycenter position
  1556. // loop on all the facets in the current partitioning block
  1557. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  1558. fib = facetsInBlock[idx];
  1559. norm = facetNormals[fib];
  1560. p0 = facetPositions[fib];
  1561. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  1562. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  1563. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  1564. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  1565. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  1566. projx = x + norm.x * t0;
  1567. projy = y + norm.y * t0;
  1568. projz = z + norm.z * t0;
  1569. tmpx = projx - x;
  1570. tmpy = projy - y;
  1571. tmpz = projz - z;
  1572. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  1573. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  1574. shortest = tmpDistance;
  1575. closest = fib;
  1576. if (projected) {
  1577. projected.x = projx;
  1578. projected.y = projy;
  1579. projected.z = projz;
  1580. }
  1581. }
  1582. }
  1583. }
  1584. return closest;
  1585. }
  1586. /**
  1587. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  1588. * @returns the parameters
  1589. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1590. */
  1591. public getFacetDataParameters(): any {
  1592. return this._facetData.facetParameters;
  1593. }
  1594. /**
  1595. * Disables the feature FacetData and frees the related memory
  1596. * @returns the current mesh
  1597. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  1598. */
  1599. public disableFacetData(): AbstractMesh {
  1600. if (this._facetData.facetDataEnabled) {
  1601. this._facetData.facetDataEnabled = false;
  1602. this._facetData.facetPositions = new Array<Vector3>();
  1603. this._facetData.facetNormals = new Array<Vector3>();
  1604. this._facetData.facetPartitioning = new Array<number[]>();
  1605. this._facetData.facetParameters = null;
  1606. this._facetData.depthSortedIndices = new Uint32Array(0);
  1607. }
  1608. return this;
  1609. }
  1610. /**
  1611. * Updates the AbstractMesh indices array
  1612. * @param indices defines the data source
  1613. * @returns the current mesh
  1614. */
  1615. public updateIndices(indices: IndicesArray): AbstractMesh {
  1616. return this;
  1617. }
  1618. /**
  1619. * Creates new normals data for the mesh
  1620. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  1621. * @returns the current mesh
  1622. */
  1623. public createNormals(updatable: boolean): AbstractMesh {
  1624. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1625. var indices = this.getIndices();
  1626. var normals: FloatArray;
  1627. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1628. normals = (<FloatArray>this.getVerticesData(VertexBuffer.NormalKind));
  1629. } else {
  1630. normals = [];
  1631. }
  1632. VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  1633. this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
  1634. return this;
  1635. }
  1636. /**
  1637. * Align the mesh with a normal
  1638. * @param normal defines the normal to use
  1639. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  1640. * @returns the current mesh
  1641. */
  1642. public alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh {
  1643. if (!upDirection) {
  1644. upDirection = Axis.Y;
  1645. }
  1646. var axisX = Tmp.Vector3[0];
  1647. var axisZ = Tmp.Vector3[1];
  1648. Vector3.CrossToRef(upDirection, normal, axisZ);
  1649. Vector3.CrossToRef(normal, axisZ, axisX);
  1650. if (this.rotationQuaternion) {
  1651. Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  1652. } else {
  1653. Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  1654. }
  1655. return this;
  1656. }
  1657. /** @hidden */
  1658. public _checkOcclusionQuery(): boolean { // Will be replaced by correct code if Occlusion queries are referenced
  1659. return false;
  1660. }
  1661. }
  1662. }