babylon.scene.js 68 KB

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