babylon.scene.js 68 KB

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