babylon.scene.js 78 KB

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