babylon.scene.js 68 KB

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