babylon.abstractMesh.ts 84 KB

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