babylon.scene.ts 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095
  1. module BABYLON {
  2. export interface IDisposable {
  3. dispose(): void;
  4. }
  5. /**
  6. * Represents a scene to be rendered by the engine.
  7. * @see http://doc.babylonjs.com/page.php?p=21911
  8. */
  9. export class Scene {
  10. // Statics
  11. private static _FOGMODE_NONE = 0;
  12. private static _FOGMODE_EXP = 1;
  13. private static _FOGMODE_EXP2 = 2;
  14. private static _FOGMODE_LINEAR = 3;
  15. public static MinDeltaTime = 1.0;
  16. public static MaxDeltaTime = 1000.0;
  17. public static get FOGMODE_NONE(): number {
  18. return Scene._FOGMODE_NONE;
  19. }
  20. public static get FOGMODE_EXP(): number {
  21. return Scene._FOGMODE_EXP;
  22. }
  23. public static get FOGMODE_EXP2(): number {
  24. return Scene._FOGMODE_EXP2;
  25. }
  26. public static get FOGMODE_LINEAR(): number {
  27. return Scene._FOGMODE_LINEAR;
  28. }
  29. // Members
  30. public autoClear = true;
  31. public clearColor: any = new Color3(0.2, 0.2, 0.3);
  32. public ambientColor = new Color3(0, 0, 0);
  33. /**
  34. * A function to be executed before rendering this scene
  35. * @type {Function}
  36. */
  37. public beforeRender: () => void;
  38. /**
  39. * A function to be executed after rendering this scene
  40. * @type {Function}
  41. */
  42. public afterRender: () => void;
  43. /**
  44. * A function to be executed when this scene is disposed.
  45. * @type {Function}
  46. */
  47. public onDispose: () => void;
  48. public beforeCameraRender: (camera: Camera) => void;
  49. public afterCameraRender: (camera: Camera) => void;
  50. public forceWireframe = false;
  51. public forcePointsCloud = false;
  52. public forceShowBoundingBoxes = false;
  53. public clipPlane: Plane;
  54. public animationsEnabled = true;
  55. // Pointers
  56. private _onPointerMove: (evt: PointerEvent) => void;
  57. private _onPointerDown: (evt: PointerEvent) => void;
  58. public onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void;
  59. public cameraToUseForPointers: Camera = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  60. private _pointerX: number;
  61. private _pointerY: number;
  62. private _meshUnderPointer: AbstractMesh;
  63. // Keyboard
  64. private _onKeyDown: (evt: Event) => void;
  65. private _onKeyUp: (evt: Event) => void;
  66. // Fog
  67. /**
  68. * is fog enabled on this scene.
  69. * @type {boolean}
  70. */
  71. public fogEnabled = true;
  72. public fogMode = Scene.FOGMODE_NONE;
  73. public fogColor = new Color3(0.2, 0.2, 0.3);
  74. public fogDensity = 0.1;
  75. public fogStart = 0;
  76. public fogEnd = 1000.0;
  77. // Lights
  78. /**
  79. * is shadow enabled on this scene.
  80. * @type {boolean}
  81. */
  82. public shadowsEnabled = true;
  83. /**
  84. * is light enabled on this scene.
  85. * @type {boolean}
  86. */
  87. public lightsEnabled = true;
  88. /**
  89. * All of the lights added to this scene.
  90. * @see BABYLON.Light
  91. * @type {BABYLON.Light[]}
  92. */
  93. public lights = new Array<Light>();
  94. public onNewLightAdded: (newLight?: Light, positionInArray?: number, scene?: Scene) => void;
  95. public onLightRemoved: (removedLight?: Light) => void;
  96. // Cameras
  97. /**
  98. * All of the cameras added to this scene.
  99. * @see BABYLON.Camera
  100. * @type {BABYLON.Camera[]}
  101. */
  102. public cameras = new Array<Camera>();
  103. public onNewCameraAdded: (newCamera?: Camera, positionInArray?: number, scene?: Scene) => void;
  104. public onCameraRemoved: (removedCamera?: Camera) => void;
  105. public activeCameras = new Array<Camera>();
  106. public activeCamera: Camera;
  107. // Meshes
  108. /**
  109. * All of the (abstract) meshes added to this scene.
  110. * @see BABYLON.AbstractMesh
  111. * @type {BABYLON.AbstractMesh[]}
  112. */
  113. public meshes = new Array<AbstractMesh>();
  114. public onNewMeshAdded: (newMesh?: AbstractMesh, positionInArray?: number, scene?: Scene) => void;
  115. public onMeshRemoved: (removedMesh?: AbstractMesh) => void;
  116. // Geometries
  117. private _geometries = new Array<Geometry>();
  118. public materials = new Array<Material>();
  119. public multiMaterials = new Array<MultiMaterial>();
  120. public defaultMaterial = new StandardMaterial("default material", this);
  121. // Textures
  122. public texturesEnabled = true;
  123. public textures = new Array<BaseTexture>();
  124. // Particles
  125. public particlesEnabled = true;
  126. public particleSystems = new Array<ParticleSystem>();
  127. // Sprites
  128. public spritesEnabled = true;
  129. public spriteManagers = new Array<SpriteManager>();
  130. // Layers
  131. public layers = new Array<Layer>();
  132. // Skeletons
  133. public skeletonsEnabled = true;
  134. public skeletons = new Array<Skeleton>();
  135. // Lens flares
  136. public lensFlaresEnabled = true;
  137. public lensFlareSystems = new Array<LensFlareSystem>();
  138. // Collisions
  139. public collisionsEnabled = true;
  140. public gravity = new Vector3(0, -9.0, 0);
  141. // Postprocesses
  142. public postProcessesEnabled = true;
  143. public postProcessManager: PostProcessManager;
  144. public postProcessRenderPipelineManager: PostProcessRenderPipelineManager;
  145. // Customs render targets
  146. public renderTargetsEnabled = true;
  147. public dumpNextRenderTargets = false;
  148. public customRenderTargets = new Array<RenderTargetTexture>();
  149. // Delay loading
  150. public useDelayedTextureLoading: boolean;
  151. // Imported meshes
  152. public importedMeshesFiles = new Array<String>();
  153. // Database
  154. public database; //ANY
  155. // Actions
  156. /**
  157. * This scene's action manager
  158. * @type {BABYLON.ActionManager}
  159. */
  160. public actionManager: ActionManager;
  161. public _actionManagers = new Array<ActionManager>();
  162. private _meshesForIntersections = new SmartArray<AbstractMesh>(256);
  163. // Procedural textures
  164. public proceduralTexturesEnabled = true;
  165. public _proceduralTextures = new Array<ProceduralTexture>();
  166. // Sound Tracks
  167. public mainSoundTrack: SoundTrack;
  168. public soundTracks = new Array<SoundTrack>();
  169. private _audioEnabled = true;
  170. private _headphone = false;
  171. //Simplification Queue
  172. public simplificationQueue: SimplificationQueue;
  173. // Private
  174. private _engine: Engine;
  175. private _totalVertices = 0;
  176. public _activeVertices = 0;
  177. public _activeParticles = 0;
  178. private _lastFrameDuration = 0;
  179. private _evaluateActiveMeshesDuration = 0;
  180. private _renderTargetsDuration = 0;
  181. public _particlesDuration = 0;
  182. private _renderDuration = 0;
  183. public _spritesDuration = 0;
  184. private _animationRatio = 0;
  185. private _animationStartDate: number;
  186. public _cachedMaterial: Material;
  187. private _renderId = 0;
  188. private _executeWhenReadyTimeoutId = -1;
  189. public _toBeDisposed = new SmartArray<IDisposable>(256);
  190. private _onReadyCallbacks = new Array<() => void>();
  191. private _pendingData = [];//ANY
  192. private _onBeforeRenderCallbacks = new Array<() => void>();
  193. private _onAfterRenderCallbacks = new Array<() => void>();
  194. private _activeMeshes = new SmartArray<Mesh>(256);
  195. private _processedMaterials = new SmartArray<Material>(256);
  196. private _renderTargets = new SmartArray<RenderTargetTexture>(256);
  197. public _activeParticleSystems = new SmartArray<ParticleSystem>(256);
  198. private _activeSkeletons = new SmartArray<Skeleton>(32);
  199. public _activeBones = 0;
  200. private _renderingManager: RenderingManager;
  201. private _physicsEngine: PhysicsEngine;
  202. public _activeAnimatables = new Array<Animatable>();
  203. private _transformMatrix = Matrix.Zero();
  204. private _pickWithRayInverseMatrix: Matrix;
  205. private _scaledPosition = Vector3.Zero();
  206. private _scaledVelocity = Vector3.Zero();
  207. private _boundingBoxRenderer: BoundingBoxRenderer;
  208. private _outlineRenderer: OutlineRenderer;
  209. private _viewMatrix: Matrix;
  210. private _projectionMatrix: Matrix;
  211. private _frustumPlanes: Plane[];
  212. private _selectionOctree: Octree<AbstractMesh>;
  213. private _pointerOverMesh: AbstractMesh;
  214. private _debugLayer: DebugLayer;
  215. private _depthRenderer: DepthRenderer;
  216. /**
  217. * @constructor
  218. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  219. */
  220. constructor(engine: Engine) {
  221. this._engine = engine;
  222. engine.scenes.push(this);
  223. this._renderingManager = new RenderingManager(this);
  224. this.postProcessManager = new PostProcessManager(this);
  225. this.postProcessRenderPipelineManager = new PostProcessRenderPipelineManager();
  226. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  227. this._outlineRenderer = new OutlineRenderer(this);
  228. this.attachControl();
  229. this._debugLayer = new DebugLayer(this);
  230. this.mainSoundTrack = new SoundTrack(this, { mainTrack: true });
  231. //simplification queue
  232. this.simplificationQueue = new SimplificationQueue();
  233. }
  234. // Properties
  235. public get debugLayer(): DebugLayer {
  236. return this._debugLayer;
  237. }
  238. /**
  239. * The mesh that is currently under the pointer.
  240. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  241. */
  242. public get meshUnderPointer(): AbstractMesh {
  243. return this._meshUnderPointer;
  244. }
  245. /**
  246. * Current on-screen X position of the pointer
  247. * @return {number} X position of the pointer
  248. */
  249. public get pointerX(): number {
  250. return this._pointerX;
  251. }
  252. /**
  253. * Current on-screen Y position of the pointer
  254. * @return {number} Y position of the pointer
  255. */
  256. public get pointerY(): number {
  257. return this._pointerY;
  258. }
  259. public getCachedMaterial(): Material {
  260. return this._cachedMaterial;
  261. }
  262. public getBoundingBoxRenderer(): BoundingBoxRenderer {
  263. return this._boundingBoxRenderer;
  264. }
  265. public getOutlineRenderer(): OutlineRenderer {
  266. return this._outlineRenderer;
  267. }
  268. public getEngine(): Engine {
  269. return this._engine;
  270. }
  271. public getTotalVertices(): number {
  272. return this._totalVertices;
  273. }
  274. public getActiveVertices(): number {
  275. return this._activeVertices;
  276. }
  277. public getActiveParticles(): number {
  278. return this._activeParticles;
  279. }
  280. public getActiveBones(): number {
  281. return this._activeBones;
  282. }
  283. // Stats
  284. public getLastFrameDuration(): number {
  285. return this._lastFrameDuration;
  286. }
  287. public getEvaluateActiveMeshesDuration(): number {
  288. return this._evaluateActiveMeshesDuration;
  289. }
  290. public getActiveMeshes(): SmartArray<Mesh> {
  291. return this._activeMeshes;
  292. }
  293. public getRenderTargetsDuration(): number {
  294. return this._renderTargetsDuration;
  295. }
  296. public getRenderDuration(): number {
  297. return this._renderDuration;
  298. }
  299. public getParticlesDuration(): number {
  300. return this._particlesDuration;
  301. }
  302. public getSpritesDuration(): number {
  303. return this._spritesDuration;
  304. }
  305. public getAnimationRatio(): number {
  306. return this._animationRatio;
  307. }
  308. public getRenderId(): number {
  309. return this._renderId;
  310. }
  311. public incrementRenderId(): void {
  312. this._renderId++;
  313. }
  314. private _updatePointerPosition(evt: PointerEvent): void {
  315. var canvasRect = this._engine.getRenderingCanvasClientRect();
  316. this._pointerX = evt.clientX - canvasRect.left;
  317. this._pointerY = evt.clientY - canvasRect.top;
  318. if (this.cameraToUseForPointers) {
  319. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  320. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  321. }
  322. }
  323. // Pointers handling
  324. public attachControl() {
  325. this._onPointerMove = (evt: PointerEvent) => {
  326. var canvas = this._engine.getRenderingCanvas();
  327. this._updatePointerPosition(evt);
  328. var pickResult = this.pick(this._pointerX, this._pointerY,
  329. (mesh: AbstractMesh): boolean => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers,
  330. false,
  331. this.cameraToUseForPointers);
  332. if (pickResult.hit) {
  333. this._meshUnderPointer = pickResult.pickedMesh;
  334. this.setPointerOverMesh(pickResult.pickedMesh);
  335. canvas.style.cursor = "pointer";
  336. } else {
  337. this.setPointerOverMesh(null);
  338. canvas.style.cursor = "";
  339. this._meshUnderPointer = null;
  340. }
  341. };
  342. this._onPointerDown = (evt: PointerEvent) => {
  343. var predicate = null;
  344. if (!this.onPointerDown) {
  345. predicate = (mesh: AbstractMesh): boolean => {
  346. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  347. };
  348. }
  349. this._updatePointerPosition(evt);
  350. var pickResult = this.pick(this._pointerX, this._pointerY, predicate, false, this.cameraToUseForPointers);
  351. if (pickResult.hit) {
  352. if (pickResult.pickedMesh.actionManager) {
  353. switch (evt.button) {
  354. case 0:
  355. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnLeftPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  356. break;
  357. case 1:
  358. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnCenterPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  359. break;
  360. case 2:
  361. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnRightPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  362. break;
  363. }
  364. pickResult.pickedMesh.actionManager.processTrigger(ActionManager.OnPickTrigger, ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  365. }
  366. }
  367. if (this.onPointerDown) {
  368. this.onPointerDown(evt, pickResult);
  369. }
  370. };
  371. this._onKeyDown = (evt: Event) => {
  372. if (this.actionManager) {
  373. this.actionManager.processTrigger(ActionManager.OnKeyDownTrigger, ActionEvent.CreateNewFromScene(this, evt));
  374. }
  375. };
  376. this._onKeyUp = (evt: Event) => {
  377. if (this.actionManager) {
  378. this.actionManager.processTrigger(ActionManager.OnKeyUpTrigger, ActionEvent.CreateNewFromScene(this, evt));
  379. }
  380. };
  381. var eventPrefix = Tools.GetPointerPrefix();
  382. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  383. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  384. Tools.RegisterTopRootEvents([
  385. { name: "keydown", handler: this._onKeyDown },
  386. { name: "keyup", handler: this._onKeyUp }
  387. ]);
  388. }
  389. public detachControl() {
  390. var eventPrefix = Tools.GetPointerPrefix();
  391. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  392. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  393. Tools.UnregisterTopRootEvents([
  394. { name: "keydown", handler: this._onKeyDown },
  395. { name: "keyup", handler: this._onKeyUp }
  396. ]);
  397. }
  398. // Ready
  399. public isReady(): boolean {
  400. if (this._pendingData.length > 0) {
  401. return false;
  402. }
  403. for (var index = 0; index < this._geometries.length; index++) {
  404. var geometry = this._geometries[index];
  405. if (geometry.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  406. return false;
  407. }
  408. }
  409. for (index = 0; index < this.meshes.length; index++) {
  410. var mesh = this.meshes[index];
  411. if (!mesh.isReady()) {
  412. return false;
  413. }
  414. var mat = mesh.material;
  415. if (mat) {
  416. if (!mat.isReady(mesh)) {
  417. return false;
  418. }
  419. }
  420. }
  421. return true;
  422. }
  423. public resetCachedMaterial(): void {
  424. this._cachedMaterial = null;
  425. }
  426. public registerBeforeRender(func: () => void): void {
  427. this._onBeforeRenderCallbacks.push(func);
  428. }
  429. public unregisterBeforeRender(func: () => void): void {
  430. var index = this._onBeforeRenderCallbacks.indexOf(func);
  431. if (index > -1) {
  432. this._onBeforeRenderCallbacks.splice(index, 1);
  433. }
  434. }
  435. public registerAfterRender(func: () => void): void {
  436. this._onAfterRenderCallbacks.push(func);
  437. }
  438. public unregisterAfterRender(func: () => void): void {
  439. var index = this._onAfterRenderCallbacks.indexOf(func);
  440. if (index > -1) {
  441. this._onAfterRenderCallbacks.splice(index, 1);
  442. }
  443. }
  444. public _addPendingData(data): void {
  445. this._pendingData.push(data);
  446. }
  447. public _removePendingData(data): void {
  448. var index = this._pendingData.indexOf(data);
  449. if (index !== -1) {
  450. this._pendingData.splice(index, 1);
  451. }
  452. }
  453. public getWaitingItemsCount(): number {
  454. return this._pendingData.length;
  455. }
  456. /**
  457. * Registers a function to be executed when the scene is ready.
  458. * @param {Function} func - the function to be executed.
  459. */
  460. public executeWhenReady(func: () => void): void {
  461. this._onReadyCallbacks.push(func);
  462. if (this._executeWhenReadyTimeoutId !== -1) {
  463. return;
  464. }
  465. this._executeWhenReadyTimeoutId = setTimeout(() => {
  466. this._checkIsReady();
  467. }, 150);
  468. }
  469. public _checkIsReady() {
  470. if (this.isReady()) {
  471. this._onReadyCallbacks.forEach(func => {
  472. func();
  473. });
  474. this._onReadyCallbacks = [];
  475. this._executeWhenReadyTimeoutId = -1;
  476. return;
  477. }
  478. this._executeWhenReadyTimeoutId = setTimeout(() => {
  479. this._checkIsReady();
  480. }, 150);
  481. }
  482. // Animations
  483. /**
  484. * Will start the animation sequence of a given target
  485. * @param target - the target
  486. * @param {number} from - from which frame should animation start
  487. * @param {number} to - till which frame should animation run.
  488. * @param {boolean} [loop] - should the animation loop
  489. * @param {number} [speedRatio] - the speed in which to run the animation
  490. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  491. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  492. * @return {BABYLON.Animatable} the animatable object created for this animation
  493. * @see BABYLON.Animatable
  494. * @see http://doc.babylonjs.com/page.php?p=22081
  495. */
  496. public beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, animatable?: Animatable): Animatable {
  497. if (speedRatio === undefined) {
  498. speedRatio = 1.0;
  499. }
  500. this.stopAnimation(target);
  501. if (!animatable) {
  502. animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  503. }
  504. // Local animations
  505. if (target.animations) {
  506. animatable.appendAnimations(target, target.animations);
  507. }
  508. // Children animations
  509. if (target.getAnimatables) {
  510. var animatables = target.getAnimatables();
  511. for (var index = 0; index < animatables.length; index++) {
  512. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  513. }
  514. }
  515. return animatable;
  516. }
  517. public beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable {
  518. if (speedRatio === undefined) {
  519. speedRatio = 1.0;
  520. }
  521. var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  522. return animatable;
  523. }
  524. public getAnimatableByTarget(target: any): Animatable {
  525. for (var index = 0; index < this._activeAnimatables.length; index++) {
  526. if (this._activeAnimatables[index].target === target) {
  527. return this._activeAnimatables[index];
  528. }
  529. }
  530. return null;
  531. }
  532. /**
  533. * Will stop the animation of the given target
  534. * @param target - the target
  535. * @see beginAnimation
  536. */
  537. public stopAnimation(target: any): void {
  538. var animatable = this.getAnimatableByTarget(target);
  539. if (animatable) {
  540. animatable.stop();
  541. }
  542. }
  543. private _animate(): void {
  544. if (!this.animationsEnabled) {
  545. return;
  546. }
  547. if (!this._animationStartDate) {
  548. this._animationStartDate = Tools.Now;
  549. }
  550. // Getting time
  551. var now = Tools.Now;
  552. var delay = now - this._animationStartDate;
  553. for (var index = 0; index < this._activeAnimatables.length; index++) {
  554. this._activeAnimatables[index]._animate(delay);
  555. }
  556. }
  557. // Matrix
  558. public getViewMatrix(): Matrix {
  559. return this._viewMatrix;
  560. }
  561. public getProjectionMatrix(): Matrix {
  562. return this._projectionMatrix;
  563. }
  564. public getTransformMatrix(): Matrix {
  565. return this._transformMatrix;
  566. }
  567. public setTransformMatrix(view: Matrix, projection: Matrix): void {
  568. this._viewMatrix = view;
  569. this._projectionMatrix = projection;
  570. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  571. }
  572. // Methods
  573. public addMesh(newMesh: AbstractMesh) {
  574. var position = this.meshes.push(newMesh);
  575. if (this.onNewMeshAdded) {
  576. this.onNewMeshAdded(newMesh, position, this);
  577. }
  578. }
  579. public removeMesh(toRemove: AbstractMesh): number {
  580. var index = this.meshes.indexOf(toRemove);
  581. if (index !== -1) {
  582. // Remove from the scene if mesh found
  583. this.meshes.splice(index, 1);
  584. }
  585. if (this.onMeshRemoved) {
  586. this.onMeshRemoved(toRemove);
  587. }
  588. return index;
  589. }
  590. public removeLight(toRemove: Light): number {
  591. var index = this.lights.indexOf(toRemove);
  592. if (index !== -1) {
  593. // Remove from the scene if mesh found
  594. this.lights.splice(index, 1);
  595. }
  596. if (this.onLightRemoved) {
  597. this.onLightRemoved(toRemove);
  598. }
  599. return index;
  600. }
  601. public removeCamera(toRemove: Camera): number {
  602. var index = this.cameras.indexOf(toRemove);
  603. if (index !== -1) {
  604. // Remove from the scene if mesh found
  605. this.cameras.splice(index, 1);
  606. }
  607. if (this.onCameraRemoved) {
  608. this.onCameraRemoved(toRemove);
  609. }
  610. return index;
  611. }
  612. public addLight(newLight: Light) {
  613. var position = this.lights.push(newLight);
  614. if (this.onNewLightAdded) {
  615. this.onNewLightAdded(newLight, position, this);
  616. }
  617. }
  618. public addCamera(newCamera: Camera) {
  619. var position = this.cameras.push(newCamera);
  620. if (this.onNewCameraAdded) {
  621. this.onNewCameraAdded(newCamera, position, this);
  622. }
  623. }
  624. /**
  625. * sets the active camera of the scene using its ID
  626. * @param {string} id - the camera's ID
  627. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  628. * @see activeCamera
  629. */
  630. public setActiveCameraByID(id: string): Camera {
  631. var camera = this.getCameraByID(id);
  632. if (camera) {
  633. this.activeCamera = camera;
  634. return camera;
  635. }
  636. return null;
  637. }
  638. /**
  639. * sets the active camera of the scene using its name
  640. * @param {string} name - the camera's name
  641. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  642. * @see activeCamera
  643. */
  644. public setActiveCameraByName(name: string): Camera {
  645. var camera = this.getCameraByName(name);
  646. if (camera) {
  647. this.activeCamera = camera;
  648. return camera;
  649. }
  650. return null;
  651. }
  652. /**
  653. * get a material using its id
  654. * @param {string} the material's ID
  655. * @return {BABYLON.Material|null} the material or null if none found.
  656. */
  657. public getMaterialByID(id: string): Material {
  658. for (var index = 0; index < this.materials.length; index++) {
  659. if (this.materials[index].id === id) {
  660. return this.materials[index];
  661. }
  662. }
  663. return null;
  664. }
  665. /**
  666. * get a material using its name
  667. * @param {string} the material's name
  668. * @return {BABYLON.Material|null} the material or null if none found.
  669. */
  670. public getMaterialByName(name: string): Material {
  671. for (var index = 0; index < this.materials.length; index++) {
  672. if (this.materials[index].name === name) {
  673. return this.materials[index];
  674. }
  675. }
  676. return null;
  677. }
  678. public getCameraByID(id: string): Camera {
  679. for (var index = 0; index < this.cameras.length; index++) {
  680. if (this.cameras[index].id === id) {
  681. return this.cameras[index];
  682. }
  683. }
  684. return null;
  685. }
  686. /**
  687. * get a camera using its name
  688. * @param {string} the camera's name
  689. * @return {BABYLON.Camera|null} the camera or null if none found.
  690. */
  691. public getCameraByName(name: string): Camera {
  692. for (var index = 0; index < this.cameras.length; index++) {
  693. if (this.cameras[index].name === name) {
  694. return this.cameras[index];
  695. }
  696. }
  697. return null;
  698. }
  699. /**
  700. * get a light node using its name
  701. * @param {string} the light's name
  702. * @return {BABYLON.Light|null} the light or null if none found.
  703. */
  704. public getLightByName(name: string): Light {
  705. for (var index = 0; index < this.lights.length; index++) {
  706. if (this.lights[index].name === name) {
  707. return this.lights[index];
  708. }
  709. }
  710. return null;
  711. }
  712. /**
  713. * get a light node using its ID
  714. * @param {string} the light's id
  715. * @return {BABYLON.Light|null} the light or null if none found.
  716. */
  717. public getLightByID(id: string): Light {
  718. for (var index = 0; index < this.lights.length; index++) {
  719. if (this.lights[index].id === id) {
  720. return this.lights[index];
  721. }
  722. }
  723. return null;
  724. }
  725. /**
  726. * get a geometry using its ID
  727. * @param {string} the geometry's id
  728. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  729. */
  730. public getGeometryByID(id: string): Geometry {
  731. for (var index = 0; index < this._geometries.length; index++) {
  732. if (this._geometries[index].id === id) {
  733. return this._geometries[index];
  734. }
  735. }
  736. return null;
  737. }
  738. /**
  739. * add a new geometry to this scene.
  740. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  741. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  742. * @return {boolean} was the geometry added or not
  743. */
  744. public pushGeometry(geometry: Geometry, force?: boolean): boolean {
  745. if (!force && this.getGeometryByID(geometry.id)) {
  746. return false;
  747. }
  748. this._geometries.push(geometry);
  749. return true;
  750. }
  751. public getGeometries(): Geometry[] {
  752. return this._geometries;
  753. }
  754. /**
  755. * Get a the first added mesh found of a given ID
  756. * @param {string} id - the id to search for
  757. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  758. */
  759. public getMeshByID(id: string): AbstractMesh {
  760. for (var index = 0; index < this.meshes.length; index++) {
  761. if (this.meshes[index].id === id) {
  762. return this.meshes[index];
  763. }
  764. }
  765. return null;
  766. }
  767. /**
  768. * Get a the last added mesh found of a given ID
  769. * @param {string} id - the id to search for
  770. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  771. */
  772. public getLastMeshByID(id: string): AbstractMesh {
  773. for (var index = this.meshes.length - 1; index >= 0; index--) {
  774. if (this.meshes[index].id === id) {
  775. return this.meshes[index];
  776. }
  777. }
  778. return null;
  779. }
  780. /**
  781. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  782. * @param {string} id - the id to search for
  783. * @return {BABYLON.Node|null} the node found or null if not found at all.
  784. */
  785. public getLastEntryByID(id: string): Node {
  786. for (var index = this.meshes.length - 1; index >= 0; index--) {
  787. if (this.meshes[index].id === id) {
  788. return this.meshes[index];
  789. }
  790. }
  791. for (index = this.cameras.length - 1; index >= 0; index--) {
  792. if (this.cameras[index].id === id) {
  793. return this.cameras[index];
  794. }
  795. }
  796. for (index = this.lights.length - 1; index >= 0; index--) {
  797. if (this.lights[index].id === id) {
  798. return this.lights[index];
  799. }
  800. }
  801. return null;
  802. }
  803. public getNodeByName(name: string): Node {
  804. var mesh = this.getMeshByName(name);
  805. if (mesh) {
  806. return mesh;
  807. }
  808. var light = this.getLightByName(name);
  809. if (light) {
  810. return light;
  811. }
  812. return this.getCameraByName(name);
  813. }
  814. public getMeshByName(name: string): AbstractMesh {
  815. for (var index = 0; index < this.meshes.length; index++) {
  816. if (this.meshes[index].name === name) {
  817. return this.meshes[index];
  818. }
  819. }
  820. return null;
  821. }
  822. public getSoundByName(name: string): Sound {
  823. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  824. if (this.mainSoundTrack.soundCollection[index].name === name) {
  825. return this.mainSoundTrack.soundCollection[index];
  826. }
  827. }
  828. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  829. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  830. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  831. return this.soundTracks[sdIndex].soundCollection[index];
  832. }
  833. }
  834. }
  835. return null;
  836. }
  837. public getLastSkeletonByID(id: string): Skeleton {
  838. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  839. if (this.skeletons[index].id === id) {
  840. return this.skeletons[index];
  841. }
  842. }
  843. return null;
  844. }
  845. public getSkeletonById(id: string): Skeleton {
  846. for (var index = 0; index < this.skeletons.length; index++) {
  847. if (this.skeletons[index].id === id) {
  848. return this.skeletons[index];
  849. }
  850. }
  851. return null;
  852. }
  853. public getSkeletonByName(name: string): Skeleton {
  854. for (var index = 0; index < this.skeletons.length; index++) {
  855. if (this.skeletons[index].name === name) {
  856. return this.skeletons[index];
  857. }
  858. }
  859. return null;
  860. }
  861. public isActiveMesh(mesh: Mesh): boolean {
  862. return (this._activeMeshes.indexOf(mesh) !== -1);
  863. }
  864. private _evaluateSubMesh(subMesh: SubMesh, mesh: AbstractMesh): void {
  865. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  866. var material = subMesh.getMaterial();
  867. if (mesh.showSubMeshesBoundingBox) {
  868. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  869. }
  870. if (material) {
  871. // Render targets
  872. if (material.getRenderTargetTextures) {
  873. if (this._processedMaterials.indexOf(material) === -1) {
  874. this._processedMaterials.push(material);
  875. this._renderTargets.concat(material.getRenderTargetTextures());
  876. }
  877. }
  878. // Dispatch
  879. this._activeVertices += subMesh.indexCount;
  880. this._renderingManager.dispatch(subMesh);
  881. }
  882. }
  883. }
  884. private _evaluateActiveMeshes(): void {
  885. this.activeCamera._activeMeshes.reset();
  886. this._activeMeshes.reset();
  887. this._renderingManager.reset();
  888. this._processedMaterials.reset();
  889. this._activeParticleSystems.reset();
  890. this._activeSkeletons.reset();
  891. this._boundingBoxRenderer.reset();
  892. if (!this._frustumPlanes) {
  893. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  894. } else {
  895. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  896. }
  897. // Meshes
  898. var meshes: AbstractMesh[];
  899. var len: number;
  900. if (this._selectionOctree) { // Octree
  901. var selection = this._selectionOctree.select(this._frustumPlanes);
  902. meshes = selection.data;
  903. len = selection.length;
  904. } else { // Full scene traversal
  905. len = this.meshes.length;
  906. meshes = this.meshes;
  907. }
  908. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  909. var mesh = meshes[meshIndex];
  910. if (mesh.isBlocked) {
  911. continue;
  912. }
  913. this._totalVertices += mesh.getTotalVertices();
  914. if (!mesh.isReady()) {
  915. continue;
  916. }
  917. mesh.computeWorldMatrix();
  918. // Intersections
  919. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([ActionManager.OnIntersectionEnterTrigger, ActionManager.OnIntersectionExitTrigger])) {
  920. this._meshesForIntersections.pushNoDuplicate(mesh);
  921. }
  922. // Switch to current LOD
  923. var meshLOD = mesh.getLOD(this.activeCamera);
  924. if (!meshLOD) {
  925. continue;
  926. }
  927. mesh._preActivate();
  928. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  929. this._activeMeshes.push(mesh);
  930. this.activeCamera._activeMeshes.push(mesh);
  931. mesh._activate(this._renderId);
  932. this._activeMesh(meshLOD);
  933. }
  934. }
  935. // Particle systems
  936. var beforeParticlesDate = Tools.Now;
  937. if (this.particlesEnabled) {
  938. Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  939. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  940. var particleSystem = this.particleSystems[particleIndex];
  941. if (!particleSystem.isStarted()) {
  942. continue;
  943. }
  944. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  945. this._activeParticleSystems.push(particleSystem);
  946. particleSystem.animate();
  947. }
  948. }
  949. Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  950. }
  951. this._particlesDuration += Tools.Now - beforeParticlesDate;
  952. }
  953. private _activeMesh(mesh: AbstractMesh): void {
  954. if (mesh.skeleton && this.skeletonsEnabled) {
  955. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  956. }
  957. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  958. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  959. }
  960. if (mesh && mesh.subMeshes) {
  961. // Submeshes Octrees
  962. var len: number;
  963. var subMeshes: SubMesh[];
  964. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  965. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  966. len = intersections.length;
  967. subMeshes = intersections.data;
  968. } else {
  969. subMeshes = mesh.subMeshes;
  970. len = subMeshes.length;
  971. }
  972. for (var subIndex = 0; subIndex < len; subIndex++) {
  973. var subMesh = subMeshes[subIndex];
  974. this._evaluateSubMesh(subMesh, mesh);
  975. }
  976. }
  977. }
  978. public updateTransformMatrix(force?: boolean): void {
  979. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  980. }
  981. private _renderForCamera(camera: Camera): void {
  982. var engine = this._engine;
  983. this.activeCamera = camera;
  984. if (!this.activeCamera)
  985. throw new Error("Active camera not set");
  986. Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  987. // Viewport
  988. engine.setViewport(this.activeCamera.viewport);
  989. // Camera
  990. this._renderId++;
  991. this.updateTransformMatrix();
  992. if (this.beforeCameraRender) {
  993. this.beforeCameraRender(this.activeCamera);
  994. }
  995. // Meshes
  996. var beforeEvaluateActiveMeshesDate = Tools.Now;
  997. Tools.StartPerformanceCounter("Active meshes evaluation");
  998. this._evaluateActiveMeshes();
  999. this._evaluateActiveMeshesDuration += Tools.Now - beforeEvaluateActiveMeshesDate;
  1000. Tools.EndPerformanceCounter("Active meshes evaluation");
  1001. // Skeletons
  1002. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  1003. var skeleton = this._activeSkeletons.data[skeletonIndex];
  1004. skeleton.prepare();
  1005. }
  1006. // Render targets
  1007. var beforeRenderTargetDate = Tools.Now;
  1008. if (this.renderTargetsEnabled) {
  1009. Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1010. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  1011. var renderTarget = this._renderTargets.data[renderIndex];
  1012. if (renderTarget._shouldRender()) {
  1013. this._renderId++;
  1014. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  1015. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  1016. }
  1017. }
  1018. Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1019. this._renderId++;
  1020. }
  1021. if (this._renderTargets.length > 0) { // Restore back buffer
  1022. engine.restoreDefaultFramebuffer();
  1023. }
  1024. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1025. // Prepare Frame
  1026. this.postProcessManager._prepareFrame();
  1027. var beforeRenderDate = Tools.Now;
  1028. // Backgrounds
  1029. if (this.layers.length) {
  1030. engine.setDepthBuffer(false);
  1031. var layerIndex;
  1032. var layer;
  1033. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1034. layer = this.layers[layerIndex];
  1035. if (layer.isBackground) {
  1036. layer.render();
  1037. }
  1038. }
  1039. engine.setDepthBuffer(true);
  1040. }
  1041. // Render
  1042. Tools.StartPerformanceCounter("Main render");
  1043. this._renderingManager.render(null, null, true, true);
  1044. Tools.EndPerformanceCounter("Main render");
  1045. // Bounding boxes
  1046. this._boundingBoxRenderer.render();
  1047. // Lens flares
  1048. if (this.lensFlaresEnabled) {
  1049. Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1050. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  1051. this.lensFlareSystems[lensFlareSystemIndex].render();
  1052. }
  1053. Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1054. }
  1055. // Foregrounds
  1056. if (this.layers.length) {
  1057. engine.setDepthBuffer(false);
  1058. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1059. layer = this.layers[layerIndex];
  1060. if (!layer.isBackground) {
  1061. layer.render();
  1062. }
  1063. }
  1064. engine.setDepthBuffer(true);
  1065. }
  1066. this._renderDuration += Tools.Now - beforeRenderDate;
  1067. // Finalize frame
  1068. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  1069. // Update camera
  1070. this.activeCamera._updateFromScene();
  1071. // Reset some special arrays
  1072. this._renderTargets.reset();
  1073. if (this.afterCameraRender) {
  1074. this.afterCameraRender(this.activeCamera);
  1075. }
  1076. Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1077. }
  1078. private _processSubCameras(camera: Camera): void {
  1079. if (camera.subCameras.length === 0) {
  1080. this._renderForCamera(camera);
  1081. return;
  1082. }
  1083. // Sub-cameras
  1084. for (var index = 0; index < camera.subCameras.length; index++) {
  1085. this._renderForCamera(camera.subCameras[index]);
  1086. }
  1087. this.activeCamera = camera;
  1088. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  1089. // Update camera
  1090. this.activeCamera._updateFromScene();
  1091. }
  1092. private _checkIntersections(): void {
  1093. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1094. var sourceMesh = this._meshesForIntersections.data[index];
  1095. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1096. var action = sourceMesh.actionManager.actions[actionIndex];
  1097. if (action.trigger === ActionManager.OnIntersectionEnterTrigger || action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1098. var parameters = action.getTriggerParameter();
  1099. var otherMesh = parameters instanceof AbstractMesh ? parameters : parameters.mesh;
  1100. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1101. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1102. if (areIntersecting && currentIntersectionInProgress === -1) {
  1103. if (action.trigger === ActionManager.OnIntersectionEnterTrigger) {
  1104. action._executeCurrent(ActionEvent.CreateNew(sourceMesh));
  1105. sourceMesh._intersectionsInProgress.push(otherMesh);
  1106. } else if (action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1107. sourceMesh._intersectionsInProgress.push(otherMesh);
  1108. }
  1109. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === ActionManager.OnIntersectionExitTrigger) {
  1110. action._executeCurrent(ActionEvent.CreateNew(sourceMesh));
  1111. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1112. if (indexOfOther > -1) {
  1113. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  1114. }
  1115. }
  1116. }
  1117. }
  1118. }
  1119. }
  1120. public render(): void {
  1121. var startDate = Tools.Now;
  1122. this._particlesDuration = 0;
  1123. this._spritesDuration = 0;
  1124. this._activeParticles = 0;
  1125. this._renderDuration = 0;
  1126. this._renderTargetsDuration = 0;
  1127. this._evaluateActiveMeshesDuration = 0;
  1128. this._totalVertices = 0;
  1129. this._activeVertices = 0;
  1130. this._activeBones = 0;
  1131. this.getEngine().resetDrawCalls();
  1132. this._meshesForIntersections.reset();
  1133. this.resetCachedMaterial();
  1134. Tools.StartPerformanceCounter("Scene rendering");
  1135. // Actions
  1136. if (this.actionManager) {
  1137. this.actionManager.processTrigger(ActionManager.OnEveryFrameTrigger, null);
  1138. }
  1139. //Simplification Queue
  1140. if (!this.simplificationQueue.running) {
  1141. this.simplificationQueue.executeNext();
  1142. }
  1143. // Before render
  1144. if (this.beforeRender) {
  1145. this.beforeRender();
  1146. }
  1147. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  1148. this._onBeforeRenderCallbacks[callbackIndex]();
  1149. }
  1150. // Animations
  1151. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1152. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1153. this._animate();
  1154. // Physics
  1155. if (this._physicsEngine) {
  1156. Tools.StartPerformanceCounter("Physics");
  1157. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  1158. Tools.EndPerformanceCounter("Physics");
  1159. }
  1160. // Customs render targets
  1161. var beforeRenderTargetDate = Tools.Now;
  1162. var engine = this.getEngine();
  1163. var currentActiveCamera = this.activeCamera;
  1164. if (this.renderTargetsEnabled) {
  1165. Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1166. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1167. var renderTarget = this.customRenderTargets[customIndex];
  1168. if (renderTarget._shouldRender()) {
  1169. this._renderId++;
  1170. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1171. if (!this.activeCamera)
  1172. throw new Error("Active camera not set");
  1173. // Viewport
  1174. engine.setViewport(this.activeCamera.viewport);
  1175. // Camera
  1176. this.updateTransformMatrix();
  1177. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  1178. }
  1179. }
  1180. Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1181. this._renderId++;
  1182. }
  1183. if (this.customRenderTargets.length > 0) { // Restore back buffer
  1184. engine.restoreDefaultFramebuffer();
  1185. }
  1186. this._renderTargetsDuration += Tools.Now - beforeRenderTargetDate;
  1187. this.activeCamera = currentActiveCamera;
  1188. // Procedural textures
  1189. if (this.proceduralTexturesEnabled) {
  1190. Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1191. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1192. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1193. if (proceduralTexture._shouldRender()) {
  1194. proceduralTexture.render();
  1195. }
  1196. }
  1197. Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1198. }
  1199. // Clear
  1200. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1201. // Shadows
  1202. if (this.shadowsEnabled) {
  1203. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1204. var light = this.lights[lightIndex];
  1205. var shadowGenerator = light.getShadowGenerator();
  1206. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1207. this._renderTargets.push(shadowGenerator.getShadowMap());
  1208. }
  1209. }
  1210. }
  1211. // Depth renderer
  1212. if (this._depthRenderer) {
  1213. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1214. }
  1215. // RenderPipeline
  1216. this.postProcessRenderPipelineManager.update();
  1217. // Multi-cameras?
  1218. if (this.activeCameras.length > 0) {
  1219. var currentRenderId = this._renderId;
  1220. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1221. this._renderId = currentRenderId;
  1222. this._processSubCameras(this.activeCameras[cameraIndex]);
  1223. }
  1224. } else {
  1225. if (!this.activeCamera) {
  1226. throw new Error("No camera defined");
  1227. }
  1228. this._processSubCameras(this.activeCamera);
  1229. }
  1230. // Intersection checks
  1231. this._checkIntersections();
  1232. // Update the audio listener attached to the camera
  1233. this._updateAudioParameters();
  1234. // After render
  1235. if (this.afterRender) {
  1236. this.afterRender();
  1237. }
  1238. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  1239. this._onAfterRenderCallbacks[callbackIndex]();
  1240. }
  1241. // Cleaning
  1242. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1243. this._toBeDisposed.data[index].dispose();
  1244. this._toBeDisposed[index] = null;
  1245. }
  1246. this._toBeDisposed.reset();
  1247. if (this.dumpNextRenderTargets) {
  1248. this.dumpNextRenderTargets = false;
  1249. }
  1250. Tools.EndPerformanceCounter("Scene rendering");
  1251. this._lastFrameDuration = Tools.Now - startDate;
  1252. }
  1253. private _updateAudioParameters() {
  1254. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  1255. return;
  1256. }
  1257. var listeningCamera: Camera;
  1258. var audioEngine = Engine.audioEngine;
  1259. if (this.activeCameras.length > 0) {
  1260. listeningCamera = this.activeCameras[0];
  1261. } else {
  1262. listeningCamera = this.activeCamera;
  1263. }
  1264. if (listeningCamera && audioEngine.canUseWebAudio) {
  1265. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1266. var mat = Matrix.Invert(listeningCamera.getViewMatrix());
  1267. var cameraDirection = Vector3.TransformNormal(new Vector3(0, 0, -1), mat);
  1268. cameraDirection.normalize();
  1269. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1270. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1271. var sound = this.mainSoundTrack.soundCollection[i];
  1272. if (sound.useCustomAttenuation) {
  1273. sound.updateDistanceFromListener();
  1274. }
  1275. }
  1276. for (i = 0; i < this.soundTracks.length; i++) {
  1277. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1278. sound = this.soundTracks[i].soundCollection[j];
  1279. if (sound.useCustomAttenuation) {
  1280. sound.updateDistanceFromListener();
  1281. }
  1282. }
  1283. }
  1284. }
  1285. }
  1286. // Audio
  1287. public get audioEnabled(): boolean {
  1288. return this._audioEnabled;
  1289. }
  1290. public set audioEnabled(value: boolean) {
  1291. this._audioEnabled = value;
  1292. if (this._audioEnabled) {
  1293. this._enableAudio();
  1294. }
  1295. else {
  1296. this._disableAudio();
  1297. }
  1298. }
  1299. private _disableAudio() {
  1300. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1301. this.mainSoundTrack.soundCollection[i].pause();
  1302. }
  1303. for (i = 0; i < this.soundTracks.length; i++) {
  1304. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1305. this.soundTracks[i].soundCollection[j].pause();
  1306. }
  1307. }
  1308. }
  1309. private _enableAudio() {
  1310. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1311. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  1312. this.mainSoundTrack.soundCollection[i].play();
  1313. }
  1314. }
  1315. for (i = 0; i < this.soundTracks.length; i++) {
  1316. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1317. if (this.soundTracks[i].soundCollection[j].isPaused) {
  1318. this.soundTracks[i].soundCollection[j].play();
  1319. }
  1320. }
  1321. }
  1322. }
  1323. public get headphone(): boolean {
  1324. return this._headphone;
  1325. }
  1326. public set headphone(value: boolean) {
  1327. this._headphone = value;
  1328. if (this._headphone) {
  1329. this._switchAudioModeForHeadphones();
  1330. }
  1331. else {
  1332. this._switchAudioModeForNormalSpeakers();
  1333. }
  1334. }
  1335. private _switchAudioModeForHeadphones() {
  1336. this.mainSoundTrack.switchPanningModelToHRTF();
  1337. for (var i = 0; i < this.soundTracks.length; i++) {
  1338. this.soundTracks[i].switchPanningModelToHRTF();
  1339. }
  1340. }
  1341. private _switchAudioModeForNormalSpeakers() {
  1342. this.mainSoundTrack.switchPanningModelToEqualPower();
  1343. for (var i = 0; i < this.soundTracks.length; i++) {
  1344. this.soundTracks[i].switchPanningModelToEqualPower();
  1345. }
  1346. }
  1347. public enableDepthRenderer(): DepthRenderer {
  1348. if (this._depthRenderer) {
  1349. return this._depthRenderer;
  1350. }
  1351. this._depthRenderer = new DepthRenderer(this);
  1352. return this._depthRenderer;
  1353. }
  1354. public disableDepthRenderer(): void {
  1355. if (!this._depthRenderer) {
  1356. return;
  1357. }
  1358. this._depthRenderer.dispose();
  1359. this._depthRenderer = null;
  1360. }
  1361. public dispose(): void {
  1362. this.beforeRender = null;
  1363. this.afterRender = null;
  1364. this.skeletons = [];
  1365. this._boundingBoxRenderer.dispose();
  1366. if (this._depthRenderer) {
  1367. this._depthRenderer.dispose();
  1368. }
  1369. // Debug layer
  1370. this.debugLayer.hide();
  1371. // Events
  1372. if (this.onDispose) {
  1373. this.onDispose();
  1374. }
  1375. this._onBeforeRenderCallbacks = [];
  1376. this._onAfterRenderCallbacks = [];
  1377. this.detachControl();
  1378. // Release sounds & sounds tracks
  1379. this.disposeSounds();
  1380. // Detach cameras
  1381. var canvas = this._engine.getRenderingCanvas();
  1382. var index;
  1383. for (index = 0; index < this.cameras.length; index++) {
  1384. this.cameras[index].detachControl(canvas);
  1385. }
  1386. // Release lights
  1387. while (this.lights.length) {
  1388. this.lights[0].dispose();
  1389. }
  1390. // Release meshes
  1391. while (this.meshes.length) {
  1392. this.meshes[0].dispose(true);
  1393. }
  1394. // Release cameras
  1395. while (this.cameras.length) {
  1396. this.cameras[0].dispose();
  1397. }
  1398. // Release materials
  1399. while (this.materials.length) {
  1400. this.materials[0].dispose();
  1401. }
  1402. // Release particles
  1403. while (this.particleSystems.length) {
  1404. this.particleSystems[0].dispose();
  1405. }
  1406. // Release sprites
  1407. while (this.spriteManagers.length) {
  1408. this.spriteManagers[0].dispose();
  1409. }
  1410. // Release layers
  1411. while (this.layers.length) {
  1412. this.layers[0].dispose();
  1413. }
  1414. // Release textures
  1415. while (this.textures.length) {
  1416. this.textures[0].dispose();
  1417. }
  1418. // Post-processes
  1419. this.postProcessManager.dispose();
  1420. // Physics
  1421. if (this._physicsEngine) {
  1422. this.disablePhysicsEngine();
  1423. }
  1424. // Remove from engine
  1425. index = this._engine.scenes.indexOf(this);
  1426. if (index > -1) {
  1427. this._engine.scenes.splice(index, 1);
  1428. }
  1429. this._engine.wipeCaches();
  1430. }
  1431. // Release sounds & sounds tracks
  1432. public disposeSounds() {
  1433. this.mainSoundTrack.dispose();
  1434. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  1435. this.soundTracks[scIndex].dispose();
  1436. }
  1437. }
  1438. // Collisions
  1439. public _getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: AbstractMesh = null): void {
  1440. position.divideToRef(collider.radius, this._scaledPosition);
  1441. velocity.divideToRef(collider.radius, this._scaledVelocity);
  1442. collider.retry = 0;
  1443. collider.initialVelocity = this._scaledVelocity;
  1444. collider.initialPosition = this._scaledPosition;
  1445. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  1446. finalPosition.multiplyInPlace(collider.radius);
  1447. }
  1448. private _collideWithWorld(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: AbstractMesh = null): void {
  1449. var closeDistance = Engine.CollisionsEpsilon * 10.0;
  1450. if (collider.retry >= maximumRetry) {
  1451. finalPosition.copyFrom(position);
  1452. return;
  1453. }
  1454. collider._initialize(position, velocity, closeDistance);
  1455. // Check all meshes
  1456. for (var index = 0; index < this.meshes.length; index++) {
  1457. var mesh = this.meshes[index];
  1458. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  1459. mesh._checkCollision(collider);
  1460. }
  1461. }
  1462. if (!collider.collisionFound) {
  1463. position.addToRef(velocity, finalPosition);
  1464. return;
  1465. }
  1466. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  1467. collider._getResponse(position, velocity);
  1468. }
  1469. if (velocity.length() <= closeDistance) {
  1470. finalPosition.copyFrom(position);
  1471. return;
  1472. }
  1473. collider.retry++;
  1474. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  1475. }
  1476. // Octrees
  1477. public getWorldExtends(): { min: Vector3; max: Vector3 } {
  1478. var min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1479. var max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1480. for (var index = 0; index < this.meshes.length; index++) {
  1481. var mesh = this.meshes[index];
  1482. mesh.computeWorldMatrix(true);
  1483. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  1484. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  1485. Tools.CheckExtends(minBox, min, max);
  1486. Tools.CheckExtends(maxBox, min, max);
  1487. }
  1488. return {
  1489. min: min,
  1490. max: max
  1491. };
  1492. }
  1493. public createOrUpdateSelectionOctree(maxCapacity = 64, maxDepth = 2): Octree<AbstractMesh> {
  1494. if (!this._selectionOctree) {
  1495. this._selectionOctree = new Octree<AbstractMesh>(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  1496. }
  1497. var worldExtends = this.getWorldExtends();
  1498. // Update octree
  1499. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  1500. return this._selectionOctree;
  1501. }
  1502. // Picking
  1503. public createPickingRay(x: number, y: number, world: Matrix, camera: Camera): Ray {
  1504. var engine = this._engine;
  1505. if (!camera) {
  1506. if (!this.activeCamera)
  1507. throw new Error("Active camera not set");
  1508. camera = this.activeCamera;
  1509. }
  1510. var cameraViewport = camera.viewport;
  1511. var viewport = cameraViewport.toGlobal(engine);
  1512. // Moving coordinates to local viewport world
  1513. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1514. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1515. return Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1516. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1517. }
  1518. private _internalPick(rayFunction: (world: Matrix) => Ray, predicate: (mesh: AbstractMesh) => boolean, fastCheck?: boolean): PickingInfo {
  1519. var pickingInfo = null;
  1520. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  1521. var mesh = this.meshes[meshIndex];
  1522. if (predicate) {
  1523. if (!predicate(mesh)) {
  1524. continue;
  1525. }
  1526. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  1527. continue;
  1528. }
  1529. var world = mesh.getWorldMatrix();
  1530. var ray = rayFunction(world);
  1531. var result = mesh.intersects(ray, fastCheck);
  1532. if (!result || !result.hit)
  1533. continue;
  1534. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1535. continue;
  1536. pickingInfo = result;
  1537. if (fastCheck) {
  1538. break;
  1539. }
  1540. }
  1541. return pickingInfo || new PickingInfo();
  1542. }
  1543. public pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo {
  1544. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1545. /// <param name="x">X position on screen</param>
  1546. /// <param name="y">Y position on screen</param>
  1547. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  1548. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1549. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  1550. return this._internalPick(world => this.createPickingRay(x, y, world, camera), predicate, fastCheck);
  1551. }
  1552. public pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean) {
  1553. return this._internalPick(world => {
  1554. if (!this._pickWithRayInverseMatrix) {
  1555. this._pickWithRayInverseMatrix = Matrix.Identity();
  1556. }
  1557. world.invertToRef(this._pickWithRayInverseMatrix);
  1558. return Ray.Transform(ray, this._pickWithRayInverseMatrix);
  1559. }, predicate, fastCheck);
  1560. }
  1561. public setPointerOverMesh(mesh: AbstractMesh): void {
  1562. if (this._pointerOverMesh === mesh) {
  1563. return;
  1564. }
  1565. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1566. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOutTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1567. }
  1568. this._pointerOverMesh = mesh;
  1569. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1570. this._pointerOverMesh.actionManager.processTrigger(ActionManager.OnPointerOverTrigger, ActionEvent.CreateNew(this._pointerOverMesh));
  1571. }
  1572. }
  1573. public getPointerOverMesh(): AbstractMesh {
  1574. return this._pointerOverMesh;
  1575. }
  1576. // Physics
  1577. public getPhysicsEngine(): PhysicsEngine {
  1578. return this._physicsEngine;
  1579. }
  1580. public enablePhysics(gravity: Vector3, plugin?: IPhysicsEnginePlugin): boolean {
  1581. if (this._physicsEngine) {
  1582. return true;
  1583. }
  1584. this._physicsEngine = new PhysicsEngine(plugin);
  1585. if (!this._physicsEngine.isSupported()) {
  1586. this._physicsEngine = null;
  1587. return false;
  1588. }
  1589. this._physicsEngine._initialize(gravity);
  1590. return true;
  1591. }
  1592. public disablePhysicsEngine(): void {
  1593. if (!this._physicsEngine) {
  1594. return;
  1595. }
  1596. this._physicsEngine.dispose();
  1597. this._physicsEngine = undefined;
  1598. }
  1599. public isPhysicsEnabled(): boolean {
  1600. return this._physicsEngine !== undefined;
  1601. }
  1602. public setGravity(gravity: Vector3): void {
  1603. if (!this._physicsEngine) {
  1604. return;
  1605. }
  1606. this._physicsEngine._setGravity(gravity);
  1607. }
  1608. public createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any {
  1609. if (parts.parts) { // Old API
  1610. options = parts;
  1611. parts = parts.parts;
  1612. }
  1613. if (!this._physicsEngine) {
  1614. return null;
  1615. }
  1616. for (var index = 0; index < parts.length; index++) {
  1617. var mesh = parts[index].mesh;
  1618. mesh._physicImpostor = parts[index].impostor;
  1619. mesh._physicsMass = options.mass / parts.length;
  1620. mesh._physicsFriction = options.friction;
  1621. mesh._physicRestitution = options.restitution;
  1622. }
  1623. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  1624. }
  1625. public deleteCompoundImpostor(compound: any): void {
  1626. for (var index = 0; index < compound.parts.length; index++) {
  1627. var mesh = compound.parts[index].mesh;
  1628. mesh._physicImpostor = PhysicsEngine.NoImpostor;
  1629. this._physicsEngine._unregisterMesh(mesh);
  1630. }
  1631. }
  1632. // Misc.
  1633. public createDefaultCameraOrLight() {
  1634. // Light
  1635. if (this.lights.length === 0) {
  1636. new HemisphericLight("default light", Vector3.Up(), this);
  1637. }
  1638. // Camera
  1639. if (!this.activeCamera) {
  1640. var camera = new FreeCamera("default camera", Vector3.Zero(), this);
  1641. // Compute position
  1642. var worldExtends = this.getWorldExtends();
  1643. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  1644. camera.position = new Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  1645. camera.setTarget(worldCenter);
  1646. this.activeCamera = camera;
  1647. }
  1648. }
  1649. // Tags
  1650. private _getByTags(list: any[], tagsQuery: string, forEach?: (item: any) => void): any[] {
  1651. if (tagsQuery === undefined) {
  1652. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  1653. return list;
  1654. }
  1655. var listByTags = [];
  1656. forEach = forEach || ((item: any) => { return; });
  1657. for (var i in list) {
  1658. var item = list[i];
  1659. if (Tags.MatchesQuery(item, tagsQuery)) {
  1660. listByTags.push(item);
  1661. forEach(item);
  1662. }
  1663. }
  1664. return listByTags;
  1665. }
  1666. public getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[] {
  1667. return this._getByTags(this.meshes, tagsQuery, forEach);
  1668. }
  1669. public getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[] {
  1670. return this._getByTags(this.cameras, tagsQuery, forEach);
  1671. }
  1672. public getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[] {
  1673. return this._getByTags(this.lights, tagsQuery, forEach);
  1674. }
  1675. public getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[] {
  1676. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  1677. }
  1678. }
  1679. }