babylon.scene.js 66 KB

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