babylon.scene.js 71 KB

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