babylon.scene.js 69 KB

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