babylon.scene.js 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  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.constantlyUpdateMeshUnderPointer = false;
  22. 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
  23. // Fog
  24. /**
  25. * is fog enabled on this scene.
  26. * @type {boolean}
  27. */
  28. this.fogEnabled = true;
  29. this.fogMode = Scene.FOGMODE_NONE;
  30. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  31. this.fogDensity = 0.1;
  32. this.fogStart = 0;
  33. this.fogEnd = 1000.0;
  34. // Lights
  35. /**
  36. * is shadow enabled on this scene.
  37. * @type {boolean}
  38. */
  39. this.shadowsEnabled = true;
  40. /**
  41. * is light enabled on this scene.
  42. * @type {boolean}
  43. */
  44. this.lightsEnabled = true;
  45. /**
  46. * All of the lights added to this scene.
  47. * @see BABYLON.Light
  48. * @type {BABYLON.Light[]}
  49. */
  50. this.lights = new Array();
  51. // Cameras
  52. /**
  53. * All of the cameras added to this scene.
  54. * @see BABYLON.Camera
  55. * @type {BABYLON.Camera[]}
  56. */
  57. this.cameras = new Array();
  58. this.activeCameras = new Array();
  59. // Meshes
  60. /**
  61. * All of the (abstract) meshes added to this scene.
  62. * @see BABYLON.AbstractMesh
  63. * @type {BABYLON.AbstractMesh[]}
  64. */
  65. this.meshes = new Array();
  66. // Geometries
  67. this._geometries = new Array();
  68. this.materials = new Array();
  69. this.multiMaterials = new Array();
  70. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  71. // Textures
  72. this.texturesEnabled = true;
  73. this.textures = new Array();
  74. // Particles
  75. this.particlesEnabled = true;
  76. this.particleSystems = new Array();
  77. // Sprites
  78. this.spritesEnabled = true;
  79. this.spriteManagers = new Array();
  80. // Layers
  81. this.layers = new Array();
  82. // Skeletons
  83. this.skeletonsEnabled = true;
  84. this.skeletons = new Array();
  85. // Lens flares
  86. this.lensFlaresEnabled = true;
  87. this.lensFlareSystems = new Array();
  88. // Collisions
  89. this.collisionsEnabled = true;
  90. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  91. // Postprocesses
  92. this.postProcessesEnabled = true;
  93. // Customs render targets
  94. this.renderTargetsEnabled = true;
  95. this.dumpNextRenderTargets = false;
  96. this.customRenderTargets = new Array();
  97. // Imported meshes
  98. this.importedMeshesFiles = new Array();
  99. // Probes
  100. this.probesEnabled = true;
  101. this.reflectionProbes = new Array();
  102. this._actionManagers = new Array();
  103. this._meshesForIntersections = new BABYLON.SmartArray(256);
  104. // Procedural textures
  105. this.proceduralTexturesEnabled = true;
  106. this._proceduralTextures = new Array();
  107. this.soundTracks = new Array();
  108. this._audioEnabled = true;
  109. this._headphone = false;
  110. this._totalVertices = 0;
  111. this._activeIndices = 0;
  112. this._activeParticles = 0;
  113. this._lastFrameDuration = 0;
  114. this._evaluateActiveMeshesDuration = 0;
  115. this._renderTargetsDuration = 0;
  116. this._particlesDuration = 0;
  117. this._renderDuration = 0;
  118. this._spritesDuration = 0;
  119. this._animationRatio = 0;
  120. this._renderId = 0;
  121. this._executeWhenReadyTimeoutId = -1;
  122. this._toBeDisposed = new BABYLON.SmartArray(256);
  123. this._onReadyCallbacks = new Array();
  124. this._pendingData = []; //ANY
  125. this._onBeforeRenderCallbacks = new Array();
  126. this._onAfterRenderCallbacks = new Array();
  127. this._activeMeshes = new BABYLON.SmartArray(256);
  128. this._processedMaterials = new BABYLON.SmartArray(256);
  129. this._renderTargets = new BABYLON.SmartArray(256);
  130. this._activeParticleSystems = new BABYLON.SmartArray(256);
  131. this._activeSkeletons = new BABYLON.SmartArray(32);
  132. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  133. this._activeBones = 0;
  134. this._activeAnimatables = new Array();
  135. this._transformMatrix = BABYLON.Matrix.Zero();
  136. this._edgesRenderers = new BABYLON.SmartArray(16);
  137. this._uniqueIdCounter = 0;
  138. this._engine = engine;
  139. engine.scenes.push(this);
  140. this._renderingManager = new BABYLON.RenderingManager(this);
  141. this.postProcessManager = new BABYLON.PostProcessManager(this);
  142. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  143. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  144. if (BABYLON.OutlineRenderer) {
  145. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  146. }
  147. this.attachControl();
  148. this._debugLayer = new BABYLON.DebugLayer(this);
  149. if (BABYLON.SoundTrack) {
  150. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  151. }
  152. //simplification queue
  153. if (BABYLON.SimplificationQueue) {
  154. this.simplificationQueue = new BABYLON.SimplificationQueue();
  155. }
  156. //collision coordinator initialization. For now legacy per default.
  157. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  158. }
  159. Object.defineProperty(Scene, "FOGMODE_NONE", {
  160. get: function () {
  161. return Scene._FOGMODE_NONE;
  162. },
  163. enumerable: true,
  164. configurable: true
  165. });
  166. Object.defineProperty(Scene, "FOGMODE_EXP", {
  167. get: function () {
  168. return Scene._FOGMODE_EXP;
  169. },
  170. enumerable: true,
  171. configurable: true
  172. });
  173. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  174. get: function () {
  175. return Scene._FOGMODE_EXP2;
  176. },
  177. enumerable: true,
  178. configurable: true
  179. });
  180. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  181. get: function () {
  182. return Scene._FOGMODE_LINEAR;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. Object.defineProperty(Scene.prototype, "debugLayer", {
  188. // Properties
  189. get: function () {
  190. return this._debugLayer;
  191. },
  192. enumerable: true,
  193. configurable: true
  194. });
  195. Object.defineProperty(Scene.prototype, "workerCollisions", {
  196. get: function () {
  197. return this._workerCollisions;
  198. },
  199. set: function (enabled) {
  200. enabled = (enabled && !!Worker);
  201. this._workerCollisions = enabled;
  202. if (this.collisionCoordinator) {
  203. this.collisionCoordinator.destroy();
  204. }
  205. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  206. this.collisionCoordinator.init(this);
  207. },
  208. enumerable: true,
  209. configurable: true
  210. });
  211. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  212. get: function () {
  213. return this._selectionOctree;
  214. },
  215. enumerable: true,
  216. configurable: true
  217. });
  218. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  219. /**
  220. * The mesh that is currently under the pointer.
  221. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  222. */
  223. get: function () {
  224. return this._meshUnderPointer;
  225. },
  226. enumerable: true,
  227. configurable: true
  228. });
  229. Object.defineProperty(Scene.prototype, "pointerX", {
  230. /**
  231. * Current on-screen X position of the pointer
  232. * @return {number} X position of the pointer
  233. */
  234. get: function () {
  235. return this._pointerX;
  236. },
  237. enumerable: true,
  238. configurable: true
  239. });
  240. Object.defineProperty(Scene.prototype, "pointerY", {
  241. /**
  242. * Current on-screen Y position of the pointer
  243. * @return {number} Y position of the pointer
  244. */
  245. get: function () {
  246. return this._pointerY;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Scene.prototype.getCachedMaterial = function () {
  252. return this._cachedMaterial;
  253. };
  254. Scene.prototype.getBoundingBoxRenderer = function () {
  255. return this._boundingBoxRenderer;
  256. };
  257. Scene.prototype.getOutlineRenderer = function () {
  258. return this._outlineRenderer;
  259. };
  260. Scene.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. Scene.prototype.getTotalVertices = function () {
  264. return this._totalVertices;
  265. };
  266. Scene.prototype.getActiveIndices = function () {
  267. return this._activeIndices;
  268. };
  269. Scene.prototype.getActiveParticles = function () {
  270. return this._activeParticles;
  271. };
  272. Scene.prototype.getActiveBones = function () {
  273. return this._activeBones;
  274. };
  275. // Stats
  276. Scene.prototype.getLastFrameDuration = function () {
  277. return this._lastFrameDuration;
  278. };
  279. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  280. return this._evaluateActiveMeshesDuration;
  281. };
  282. Scene.prototype.getActiveMeshes = function () {
  283. return this._activeMeshes;
  284. };
  285. Scene.prototype.getRenderTargetsDuration = function () {
  286. return this._renderTargetsDuration;
  287. };
  288. Scene.prototype.getRenderDuration = function () {
  289. return this._renderDuration;
  290. };
  291. Scene.prototype.getParticlesDuration = function () {
  292. return this._particlesDuration;
  293. };
  294. Scene.prototype.getSpritesDuration = function () {
  295. return this._spritesDuration;
  296. };
  297. Scene.prototype.getAnimationRatio = function () {
  298. return this._animationRatio;
  299. };
  300. Scene.prototype.getRenderId = function () {
  301. return this._renderId;
  302. };
  303. Scene.prototype.incrementRenderId = function () {
  304. this._renderId++;
  305. };
  306. Scene.prototype._updatePointerPosition = function (evt) {
  307. var canvasRect = this._engine.getRenderingCanvasClientRect();
  308. this._pointerX = evt.clientX - canvasRect.left;
  309. this._pointerY = evt.clientY - canvasRect.top;
  310. if (this.cameraToUseForPointers) {
  311. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  312. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  313. }
  314. };
  315. // Pointers handling
  316. Scene.prototype.attachControl = function () {
  317. var _this = this;
  318. var spritePredicate = function (sprite) {
  319. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  320. };
  321. this._onPointerMove = function (evt) {
  322. var canvas = _this._engine.getRenderingCanvas();
  323. _this._updatePointerPosition(evt);
  324. // Meshes
  325. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); }, false, _this.cameraToUseForPointers);
  326. if (pickResult.hit && pickResult.pickedMesh) {
  327. _this._meshUnderPointer = pickResult.pickedMesh;
  328. _this.setPointerOverMesh(pickResult.pickedMesh);
  329. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  330. canvas.style.cursor = "pointer";
  331. }
  332. else {
  333. canvas.style.cursor = "";
  334. }
  335. }
  336. else {
  337. // Sprites
  338. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  339. if (pickResult.hit && pickResult.pickedSprite) {
  340. canvas.style.cursor = "pointer";
  341. }
  342. else {
  343. // Restore pointer
  344. _this.setPointerOverMesh(null);
  345. canvas.style.cursor = "";
  346. _this._meshUnderPointer = null;
  347. }
  348. }
  349. if (_this.onPointerMove) {
  350. _this.onPointerMove(evt, pickResult);
  351. }
  352. };
  353. this._onPointerDown = function (evt) {
  354. _this._updatePointerPosition(evt);
  355. var predicate = null;
  356. // Meshes
  357. if (!_this.onPointerDown) {
  358. predicate = function (mesh) {
  359. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  360. };
  361. }
  362. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  363. if (pickResult.hit && pickResult.pickedMesh) {
  364. if (pickResult.pickedMesh.actionManager) {
  365. switch (evt.button) {
  366. case 0:
  367. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  368. break;
  369. case 1:
  370. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  371. break;
  372. case 2:
  373. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  374. break;
  375. }
  376. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  377. }
  378. }
  379. if (_this.onPointerDown) {
  380. _this.onPointerDown(evt, pickResult);
  381. }
  382. // Sprites
  383. if (_this.spriteManagers.length > 0) {
  384. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  385. if (pickResult.hit && pickResult.pickedSprite) {
  386. if (pickResult.pickedSprite.actionManager) {
  387. switch (evt.button) {
  388. case 0:
  389. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  390. break;
  391. case 1:
  392. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  393. break;
  394. case 2:
  395. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  396. break;
  397. }
  398. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  399. }
  400. }
  401. }
  402. };
  403. this._onPointerUp = function (evt) {
  404. var predicate = null;
  405. _this._updatePointerPosition(evt);
  406. if (!_this.onPointerUp) {
  407. predicate = function (mesh) {
  408. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  409. };
  410. }
  411. // Meshes
  412. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  413. if (pickResult.hit && pickResult.pickedMesh) {
  414. if (pickResult.pickedMesh.actionManager) {
  415. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  416. }
  417. }
  418. if (_this.onPointerUp) {
  419. _this.onPointerUp(evt, pickResult);
  420. }
  421. // Sprites
  422. if (_this.spriteManagers.length > 0) {
  423. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  424. if (pickResult.hit && pickResult.pickedSprite) {
  425. if (pickResult.pickedSprite.actionManager) {
  426. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  427. }
  428. }
  429. }
  430. };
  431. this._onKeyDown = function (evt) {
  432. if (_this.actionManager) {
  433. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  434. }
  435. };
  436. this._onKeyUp = function (evt) {
  437. if (_this.actionManager) {
  438. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  439. }
  440. };
  441. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  442. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  443. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  444. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  445. // Wheel
  446. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  447. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  448. BABYLON.Tools.RegisterTopRootEvents([
  449. { name: "keydown", handler: this._onKeyDown },
  450. { name: "keyup", handler: this._onKeyUp }
  451. ]);
  452. };
  453. Scene.prototype.detachControl = function () {
  454. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  455. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  456. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  457. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  458. // Wheel
  459. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  460. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  461. BABYLON.Tools.UnregisterTopRootEvents([
  462. { name: "keydown", handler: this._onKeyDown },
  463. { name: "keyup", handler: this._onKeyUp }
  464. ]);
  465. };
  466. // Ready
  467. Scene.prototype.isReady = function () {
  468. if (this._pendingData.length > 0) {
  469. return false;
  470. }
  471. var index;
  472. for (index = 0; index < this._geometries.length; index++) {
  473. var geometry = this._geometries[index];
  474. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  475. return false;
  476. }
  477. }
  478. for (index = 0; index < this.meshes.length; index++) {
  479. var mesh = this.meshes[index];
  480. if (!mesh.isReady()) {
  481. return false;
  482. }
  483. var mat = mesh.material;
  484. if (mat) {
  485. if (!mat.isReady(mesh)) {
  486. return false;
  487. }
  488. }
  489. }
  490. return true;
  491. };
  492. Scene.prototype.resetCachedMaterial = function () {
  493. this._cachedMaterial = null;
  494. };
  495. Scene.prototype.registerBeforeRender = function (func) {
  496. this._onBeforeRenderCallbacks.push(func);
  497. };
  498. Scene.prototype.unregisterBeforeRender = function (func) {
  499. var index = this._onBeforeRenderCallbacks.indexOf(func);
  500. if (index > -1) {
  501. this._onBeforeRenderCallbacks.splice(index, 1);
  502. }
  503. };
  504. Scene.prototype.registerAfterRender = function (func) {
  505. this._onAfterRenderCallbacks.push(func);
  506. };
  507. Scene.prototype.unregisterAfterRender = function (func) {
  508. var index = this._onAfterRenderCallbacks.indexOf(func);
  509. if (index > -1) {
  510. this._onAfterRenderCallbacks.splice(index, 1);
  511. }
  512. };
  513. Scene.prototype._addPendingData = function (data) {
  514. this._pendingData.push(data);
  515. };
  516. Scene.prototype._removePendingData = function (data) {
  517. var index = this._pendingData.indexOf(data);
  518. if (index !== -1) {
  519. this._pendingData.splice(index, 1);
  520. }
  521. };
  522. Scene.prototype.getWaitingItemsCount = function () {
  523. return this._pendingData.length;
  524. };
  525. /**
  526. * Registers a function to be executed when the scene is ready.
  527. * @param {Function} func - the function to be executed.
  528. */
  529. Scene.prototype.executeWhenReady = function (func) {
  530. var _this = this;
  531. this._onReadyCallbacks.push(func);
  532. if (this._executeWhenReadyTimeoutId !== -1) {
  533. return;
  534. }
  535. this._executeWhenReadyTimeoutId = setTimeout(function () {
  536. _this._checkIsReady();
  537. }, 150);
  538. };
  539. Scene.prototype._checkIsReady = function () {
  540. var _this = this;
  541. if (this.isReady()) {
  542. this._onReadyCallbacks.forEach(function (func) {
  543. func();
  544. });
  545. this._onReadyCallbacks = [];
  546. this._executeWhenReadyTimeoutId = -1;
  547. return;
  548. }
  549. this._executeWhenReadyTimeoutId = setTimeout(function () {
  550. _this._checkIsReady();
  551. }, 150);
  552. };
  553. // Animations
  554. /**
  555. * Will start the animation sequence of a given target
  556. * @param target - the target
  557. * @param {number} from - from which frame should animation start
  558. * @param {number} to - till which frame should animation run.
  559. * @param {boolean} [loop] - should the animation loop
  560. * @param {number} [speedRatio] - the speed in which to run the animation
  561. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  562. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  563. * @return {BABYLON.Animatable} the animatable object created for this animation
  564. * @see BABYLON.Animatable
  565. * @see http://doc.babylonjs.com/page.php?p=22081
  566. */
  567. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  568. if (speedRatio === void 0) { speedRatio = 1.0; }
  569. this.stopAnimation(target);
  570. if (!animatable) {
  571. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  572. }
  573. // Local animations
  574. if (target.animations) {
  575. animatable.appendAnimations(target, target.animations);
  576. }
  577. // Children animations
  578. if (target.getAnimatables) {
  579. var animatables = target.getAnimatables();
  580. for (var index = 0; index < animatables.length; index++) {
  581. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  582. }
  583. }
  584. return animatable;
  585. };
  586. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  587. if (speedRatio === undefined) {
  588. speedRatio = 1.0;
  589. }
  590. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  591. return animatable;
  592. };
  593. Scene.prototype.getAnimatableByTarget = function (target) {
  594. for (var index = 0; index < this._activeAnimatables.length; index++) {
  595. if (this._activeAnimatables[index].target === target) {
  596. return this._activeAnimatables[index];
  597. }
  598. }
  599. return null;
  600. };
  601. /**
  602. * Will stop the animation of the given target
  603. * @param target - the target
  604. * @see beginAnimation
  605. */
  606. Scene.prototype.stopAnimation = function (target) {
  607. var animatable = this.getAnimatableByTarget(target);
  608. if (animatable) {
  609. animatable.stop();
  610. }
  611. };
  612. Scene.prototype._animate = function () {
  613. if (!this.animationsEnabled) {
  614. return;
  615. }
  616. if (!this._animationStartDate) {
  617. this._animationStartDate = BABYLON.Tools.Now;
  618. }
  619. // Getting time
  620. var now = BABYLON.Tools.Now;
  621. var delay = now - this._animationStartDate;
  622. for (var index = 0; index < this._activeAnimatables.length; index++) {
  623. this._activeAnimatables[index]._animate(delay);
  624. }
  625. };
  626. // Matrix
  627. Scene.prototype.getViewMatrix = function () {
  628. return this._viewMatrix;
  629. };
  630. Scene.prototype.getProjectionMatrix = function () {
  631. return this._projectionMatrix;
  632. };
  633. Scene.prototype.getTransformMatrix = function () {
  634. return this._transformMatrix;
  635. };
  636. Scene.prototype.setTransformMatrix = function (view, projection) {
  637. this._viewMatrix = view;
  638. this._projectionMatrix = projection;
  639. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  640. };
  641. // Methods
  642. Scene.prototype.addMesh = function (newMesh) {
  643. newMesh.uniqueId = this._uniqueIdCounter++;
  644. var position = this.meshes.push(newMesh);
  645. //notify the collision coordinator
  646. this.collisionCoordinator.onMeshAdded(newMesh);
  647. if (this.onNewMeshAdded) {
  648. this.onNewMeshAdded(newMesh, position, this);
  649. }
  650. };
  651. Scene.prototype.removeMesh = function (toRemove) {
  652. var index = this.meshes.indexOf(toRemove);
  653. if (index !== -1) {
  654. // Remove from the scene if mesh found
  655. this.meshes.splice(index, 1);
  656. }
  657. //notify the collision coordinator
  658. this.collisionCoordinator.onMeshRemoved(toRemove);
  659. if (this.onMeshRemoved) {
  660. this.onMeshRemoved(toRemove);
  661. }
  662. return index;
  663. };
  664. Scene.prototype.removeSkeleton = function (toRemove) {
  665. var index = this.skeletons.indexOf(toRemove);
  666. if (index !== -1) {
  667. // Remove from the scene if mesh found
  668. this.skeletons.splice(index, 1);
  669. }
  670. return index;
  671. };
  672. Scene.prototype.removeLight = function (toRemove) {
  673. var index = this.lights.indexOf(toRemove);
  674. if (index !== -1) {
  675. // Remove from the scene if mesh found
  676. this.lights.splice(index, 1);
  677. }
  678. if (this.onLightRemoved) {
  679. this.onLightRemoved(toRemove);
  680. }
  681. return index;
  682. };
  683. Scene.prototype.removeCamera = function (toRemove) {
  684. var index = this.cameras.indexOf(toRemove);
  685. if (index !== -1) {
  686. // Remove from the scene if mesh found
  687. this.cameras.splice(index, 1);
  688. }
  689. // Remove from activeCameras
  690. var index2 = this.activeCameras.indexOf(toRemove);
  691. if (index2 !== -1) {
  692. // Remove from the scene if mesh found
  693. this.activeCameras.splice(index2, 1);
  694. }
  695. // Reset the activeCamera
  696. if (this.activeCamera === toRemove) {
  697. if (this.cameras.length > 0) {
  698. this.activeCamera = this.cameras[0];
  699. }
  700. else {
  701. this.activeCamera = null;
  702. }
  703. }
  704. if (this.onCameraRemoved) {
  705. this.onCameraRemoved(toRemove);
  706. }
  707. return index;
  708. };
  709. Scene.prototype.addLight = function (newLight) {
  710. newLight.uniqueId = this._uniqueIdCounter++;
  711. var position = this.lights.push(newLight);
  712. if (this.onNewLightAdded) {
  713. this.onNewLightAdded(newLight, position, this);
  714. }
  715. };
  716. Scene.prototype.addCamera = function (newCamera) {
  717. newCamera.uniqueId = this._uniqueIdCounter++;
  718. var position = this.cameras.push(newCamera);
  719. if (this.onNewCameraAdded) {
  720. this.onNewCameraAdded(newCamera, position, this);
  721. }
  722. };
  723. /**
  724. * sets the active camera of the scene using its ID
  725. * @param {string} id - the camera's ID
  726. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  727. * @see activeCamera
  728. */
  729. Scene.prototype.setActiveCameraByID = function (id) {
  730. var camera = this.getCameraByID(id);
  731. if (camera) {
  732. this.activeCamera = camera;
  733. return camera;
  734. }
  735. return null;
  736. };
  737. /**
  738. * sets the active camera of the scene using its name
  739. * @param {string} name - the camera's name
  740. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  741. * @see activeCamera
  742. */
  743. Scene.prototype.setActiveCameraByName = function (name) {
  744. var camera = this.getCameraByName(name);
  745. if (camera) {
  746. this.activeCamera = camera;
  747. return camera;
  748. }
  749. return null;
  750. };
  751. /**
  752. * get a material using its id
  753. * @param {string} the material's ID
  754. * @return {BABYLON.Material|null} the material or null if none found.
  755. */
  756. Scene.prototype.getMaterialByID = function (id) {
  757. for (var index = 0; index < this.materials.length; index++) {
  758. if (this.materials[index].id === id) {
  759. return this.materials[index];
  760. }
  761. }
  762. return null;
  763. };
  764. /**
  765. * get a material using its name
  766. * @param {string} the material's name
  767. * @return {BABYLON.Material|null} the material or null if none found.
  768. */
  769. Scene.prototype.getMaterialByName = function (name) {
  770. for (var index = 0; index < this.materials.length; index++) {
  771. if (this.materials[index].name === name) {
  772. return this.materials[index];
  773. }
  774. }
  775. return null;
  776. };
  777. Scene.prototype.getLensFlareSystemByName = function (name) {
  778. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  779. if (this.lensFlareSystems[index].name === name) {
  780. return this.lensFlareSystems[index];
  781. }
  782. }
  783. return null;
  784. };
  785. Scene.prototype.getCameraByID = function (id) {
  786. for (var index = 0; index < this.cameras.length; index++) {
  787. if (this.cameras[index].id === id) {
  788. return this.cameras[index];
  789. }
  790. }
  791. return null;
  792. };
  793. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  794. for (var index = 0; index < this.cameras.length; index++) {
  795. if (this.cameras[index].uniqueId === uniqueId) {
  796. return this.cameras[index];
  797. }
  798. }
  799. return null;
  800. };
  801. /**
  802. * get a camera using its name
  803. * @param {string} the camera's name
  804. * @return {BABYLON.Camera|null} the camera or null if none found.
  805. */
  806. Scene.prototype.getCameraByName = function (name) {
  807. for (var index = 0; index < this.cameras.length; index++) {
  808. if (this.cameras[index].name === name) {
  809. return this.cameras[index];
  810. }
  811. }
  812. return null;
  813. };
  814. /**
  815. * get a light node using its name
  816. * @param {string} the light's name
  817. * @return {BABYLON.Light|null} the light or null if none found.
  818. */
  819. Scene.prototype.getLightByName = function (name) {
  820. for (var index = 0; index < this.lights.length; index++) {
  821. if (this.lights[index].name === name) {
  822. return this.lights[index];
  823. }
  824. }
  825. return null;
  826. };
  827. /**
  828. * get a light node using its ID
  829. * @param {string} the light's id
  830. * @return {BABYLON.Light|null} the light or null if none found.
  831. */
  832. Scene.prototype.getLightByID = function (id) {
  833. for (var index = 0; index < this.lights.length; index++) {
  834. if (this.lights[index].id === id) {
  835. return this.lights[index];
  836. }
  837. }
  838. return null;
  839. };
  840. /**
  841. * get a light node using its scene-generated unique ID
  842. * @param {number} the light's unique id
  843. * @return {BABYLON.Light|null} the light or null if none found.
  844. */
  845. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  846. for (var index = 0; index < this.lights.length; index++) {
  847. if (this.lights[index].uniqueId === uniqueId) {
  848. return this.lights[index];
  849. }
  850. }
  851. return null;
  852. };
  853. /**
  854. * get a geometry using its ID
  855. * @param {string} the geometry's id
  856. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  857. */
  858. Scene.prototype.getGeometryByID = function (id) {
  859. for (var index = 0; index < this._geometries.length; index++) {
  860. if (this._geometries[index].id === id) {
  861. return this._geometries[index];
  862. }
  863. }
  864. return null;
  865. };
  866. /**
  867. * add a new geometry to this scene.
  868. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  869. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  870. * @return {boolean} was the geometry added or not
  871. */
  872. Scene.prototype.pushGeometry = function (geometry, force) {
  873. if (!force && this.getGeometryByID(geometry.id)) {
  874. return false;
  875. }
  876. this._geometries.push(geometry);
  877. //notify the collision coordinator
  878. this.collisionCoordinator.onGeometryAdded(geometry);
  879. if (this.onGeometryAdded) {
  880. this.onGeometryAdded(geometry);
  881. }
  882. return true;
  883. };
  884. /**
  885. * Removes an existing geometry
  886. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  887. * @return {boolean} was the geometry removed or not
  888. */
  889. Scene.prototype.removeGeometry = function (geometry) {
  890. var index = this._geometries.indexOf(geometry);
  891. if (index > -1) {
  892. this._geometries.splice(index, 1);
  893. //notify the collision coordinator
  894. this.collisionCoordinator.onGeometryDeleted(geometry);
  895. if (this.onGeometryRemoved) {
  896. this.onGeometryRemoved(geometry);
  897. }
  898. return true;
  899. }
  900. return false;
  901. };
  902. Scene.prototype.getGeometries = function () {
  903. return this._geometries;
  904. };
  905. /**
  906. * Get the first added mesh found of a given ID
  907. * @param {string} id - the id to search for
  908. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  909. */
  910. Scene.prototype.getMeshByID = function (id) {
  911. for (var index = 0; index < this.meshes.length; index++) {
  912. if (this.meshes[index].id === id) {
  913. return this.meshes[index];
  914. }
  915. }
  916. return null;
  917. };
  918. /**
  919. * Get a mesh with its auto-generated unique id
  920. * @param {number} uniqueId - the unique id to search for
  921. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  922. */
  923. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  924. for (var index = 0; index < this.meshes.length; index++) {
  925. if (this.meshes[index].uniqueId === uniqueId) {
  926. return this.meshes[index];
  927. }
  928. }
  929. return null;
  930. };
  931. /**
  932. * Get a the last added mesh found of a given ID
  933. * @param {string} id - the id to search for
  934. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  935. */
  936. Scene.prototype.getLastMeshByID = function (id) {
  937. for (var index = this.meshes.length - 1; index >= 0; index--) {
  938. if (this.meshes[index].id === id) {
  939. return this.meshes[index];
  940. }
  941. }
  942. return null;
  943. };
  944. /**
  945. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  946. * @param {string} id - the id to search for
  947. * @return {BABYLON.Node|null} the node found or null if not found at all.
  948. */
  949. Scene.prototype.getLastEntryByID = function (id) {
  950. var index;
  951. for (index = this.meshes.length - 1; index >= 0; index--) {
  952. if (this.meshes[index].id === id) {
  953. return this.meshes[index];
  954. }
  955. }
  956. for (index = this.cameras.length - 1; index >= 0; index--) {
  957. if (this.cameras[index].id === id) {
  958. return this.cameras[index];
  959. }
  960. }
  961. for (index = this.lights.length - 1; index >= 0; index--) {
  962. if (this.lights[index].id === id) {
  963. return this.lights[index];
  964. }
  965. }
  966. return null;
  967. };
  968. Scene.prototype.getNodeByID = function (id) {
  969. var mesh = this.getMeshByID(id);
  970. if (mesh) {
  971. return mesh;
  972. }
  973. var light = this.getLightByID(id);
  974. if (light) {
  975. return light;
  976. }
  977. return this.getCameraByID(id);
  978. };
  979. Scene.prototype.getNodeByName = function (name) {
  980. var mesh = this.getMeshByName(name);
  981. if (mesh) {
  982. return mesh;
  983. }
  984. var light = this.getLightByName(name);
  985. if (light) {
  986. return light;
  987. }
  988. return this.getCameraByName(name);
  989. };
  990. Scene.prototype.getMeshByName = function (name) {
  991. for (var index = 0; index < this.meshes.length; index++) {
  992. if (this.meshes[index].name === name) {
  993. return this.meshes[index];
  994. }
  995. }
  996. return null;
  997. };
  998. Scene.prototype.getSoundByName = function (name) {
  999. var index;
  1000. if (BABYLON.AudioEngine) {
  1001. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  1002. if (this.mainSoundTrack.soundCollection[index].name === name) {
  1003. return this.mainSoundTrack.soundCollection[index];
  1004. }
  1005. }
  1006. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  1007. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  1008. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  1009. return this.soundTracks[sdIndex].soundCollection[index];
  1010. }
  1011. }
  1012. }
  1013. }
  1014. return null;
  1015. };
  1016. Scene.prototype.getLastSkeletonByID = function (id) {
  1017. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  1018. if (this.skeletons[index].id === id) {
  1019. return this.skeletons[index];
  1020. }
  1021. }
  1022. return null;
  1023. };
  1024. Scene.prototype.getSkeletonById = function (id) {
  1025. for (var index = 0; index < this.skeletons.length; index++) {
  1026. if (this.skeletons[index].id === id) {
  1027. return this.skeletons[index];
  1028. }
  1029. }
  1030. return null;
  1031. };
  1032. Scene.prototype.getSkeletonByName = function (name) {
  1033. for (var index = 0; index < this.skeletons.length; index++) {
  1034. if (this.skeletons[index].name === name) {
  1035. return this.skeletons[index];
  1036. }
  1037. }
  1038. return null;
  1039. };
  1040. Scene.prototype.isActiveMesh = function (mesh) {
  1041. return (this._activeMeshes.indexOf(mesh) !== -1);
  1042. };
  1043. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  1044. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  1045. var material = subMesh.getMaterial();
  1046. if (mesh.showSubMeshesBoundingBox) {
  1047. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  1048. }
  1049. if (material) {
  1050. // Render targets
  1051. if (material.getRenderTargetTextures) {
  1052. if (this._processedMaterials.indexOf(material) === -1) {
  1053. this._processedMaterials.push(material);
  1054. this._renderTargets.concat(material.getRenderTargetTextures());
  1055. }
  1056. }
  1057. // Dispatch
  1058. this._activeIndices += subMesh.indexCount;
  1059. this._renderingManager.dispatch(subMesh);
  1060. }
  1061. }
  1062. };
  1063. Scene.prototype._evaluateActiveMeshes = function () {
  1064. this.activeCamera._activeMeshes.reset();
  1065. this._activeMeshes.reset();
  1066. this._renderingManager.reset();
  1067. this._processedMaterials.reset();
  1068. this._activeParticleSystems.reset();
  1069. this._activeSkeletons.reset();
  1070. this._softwareSkinnedMeshes.reset();
  1071. this._boundingBoxRenderer.reset();
  1072. this._edgesRenderers.reset();
  1073. if (!this._frustumPlanes) {
  1074. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  1075. }
  1076. else {
  1077. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  1078. }
  1079. // Meshes
  1080. var meshes;
  1081. var len;
  1082. if (this._selectionOctree) {
  1083. var selection = this._selectionOctree.select(this._frustumPlanes);
  1084. meshes = selection.data;
  1085. len = selection.length;
  1086. }
  1087. else {
  1088. len = this.meshes.length;
  1089. meshes = this.meshes;
  1090. }
  1091. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  1092. var mesh = meshes[meshIndex];
  1093. if (mesh.isBlocked) {
  1094. continue;
  1095. }
  1096. this._totalVertices += mesh.getTotalVertices();
  1097. if (!mesh.isReady() || !mesh.isEnabled()) {
  1098. continue;
  1099. }
  1100. mesh.computeWorldMatrix();
  1101. // Intersections
  1102. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  1103. this._meshesForIntersections.pushNoDuplicate(mesh);
  1104. }
  1105. // Switch to current LOD
  1106. var meshLOD = mesh.getLOD(this.activeCamera);
  1107. if (!meshLOD) {
  1108. continue;
  1109. }
  1110. mesh._preActivate();
  1111. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  1112. this._activeMeshes.push(mesh);
  1113. this.activeCamera._activeMeshes.push(mesh);
  1114. mesh._activate(this._renderId);
  1115. this._activeMesh(meshLOD);
  1116. }
  1117. }
  1118. // Particle systems
  1119. var beforeParticlesDate = BABYLON.Tools.Now;
  1120. if (this.particlesEnabled) {
  1121. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  1122. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  1123. var particleSystem = this.particleSystems[particleIndex];
  1124. if (!particleSystem.isStarted()) {
  1125. continue;
  1126. }
  1127. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  1128. this._activeParticleSystems.push(particleSystem);
  1129. particleSystem.animate();
  1130. }
  1131. }
  1132. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  1133. }
  1134. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  1135. };
  1136. Scene.prototype._activeMesh = function (mesh) {
  1137. if (mesh.skeleton && this.skeletonsEnabled) {
  1138. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  1139. if (!mesh.computeBonesUsingShaders) {
  1140. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  1141. }
  1142. }
  1143. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  1144. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  1145. }
  1146. if (mesh._edgesRenderer) {
  1147. this._edgesRenderers.push(mesh._edgesRenderer);
  1148. }
  1149. if (mesh && mesh.subMeshes) {
  1150. // Submeshes Octrees
  1151. var len;
  1152. var subMeshes;
  1153. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  1154. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  1155. len = intersections.length;
  1156. subMeshes = intersections.data;
  1157. }
  1158. else {
  1159. subMeshes = mesh.subMeshes;
  1160. len = subMeshes.length;
  1161. }
  1162. for (var subIndex = 0; subIndex < len; subIndex++) {
  1163. var subMesh = subMeshes[subIndex];
  1164. this._evaluateSubMesh(subMesh, mesh);
  1165. }
  1166. }
  1167. };
  1168. Scene.prototype.updateTransformMatrix = function (force) {
  1169. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  1170. };
  1171. Scene.prototype._renderForCamera = function (camera) {
  1172. var engine = this._engine;
  1173. this.activeCamera = camera;
  1174. if (!this.activeCamera)
  1175. throw new Error("Active camera not set");
  1176. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1177. // Viewport
  1178. engine.setViewport(this.activeCamera.viewport);
  1179. // Camera
  1180. this.resetCachedMaterial();
  1181. this._renderId++;
  1182. this.updateTransformMatrix();
  1183. if (this.beforeCameraRender) {
  1184. this.beforeCameraRender(this.activeCamera);
  1185. }
  1186. // Meshes
  1187. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  1188. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  1189. this._evaluateActiveMeshes();
  1190. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  1191. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  1192. // Skeletons
  1193. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  1194. var skeleton = this._activeSkeletons.data[skeletonIndex];
  1195. skeleton.prepare();
  1196. }
  1197. // Software skinning
  1198. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  1199. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  1200. mesh.applySkeleton(mesh.skeleton);
  1201. }
  1202. // Render targets
  1203. var beforeRenderTargetDate = BABYLON.Tools.Now;
  1204. if (this.renderTargetsEnabled) {
  1205. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1206. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  1207. var renderTarget = this._renderTargets.data[renderIndex];
  1208. if (renderTarget._shouldRender()) {
  1209. this._renderId++;
  1210. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  1211. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  1212. }
  1213. }
  1214. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  1215. this._renderId++;
  1216. }
  1217. if (this._renderTargets.length > 0) {
  1218. engine.restoreDefaultFramebuffer();
  1219. }
  1220. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  1221. // Prepare Frame
  1222. this.postProcessManager._prepareFrame();
  1223. var beforeRenderDate = BABYLON.Tools.Now;
  1224. // Backgrounds
  1225. var layerIndex;
  1226. var layer;
  1227. if (this.layers.length) {
  1228. engine.setDepthBuffer(false);
  1229. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1230. layer = this.layers[layerIndex];
  1231. if (layer.isBackground) {
  1232. layer.render();
  1233. }
  1234. }
  1235. engine.setDepthBuffer(true);
  1236. }
  1237. // Render
  1238. BABYLON.Tools.StartPerformanceCounter("Main render");
  1239. this._renderingManager.render(null, null, true, true);
  1240. BABYLON.Tools.EndPerformanceCounter("Main render");
  1241. // Bounding boxes
  1242. this._boundingBoxRenderer.render();
  1243. // Edges
  1244. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  1245. this._edgesRenderers.data[edgesRendererIndex].render();
  1246. }
  1247. // Lens flares
  1248. if (this.lensFlaresEnabled) {
  1249. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1250. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  1251. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  1252. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  1253. lensFlareSystem.render();
  1254. }
  1255. }
  1256. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  1257. }
  1258. // Foregrounds
  1259. if (this.layers.length) {
  1260. engine.setDepthBuffer(false);
  1261. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  1262. layer = this.layers[layerIndex];
  1263. if (!layer.isBackground) {
  1264. layer.render();
  1265. }
  1266. }
  1267. engine.setDepthBuffer(true);
  1268. }
  1269. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  1270. // Finalize frame
  1271. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  1272. // Update camera
  1273. this.activeCamera._updateFromScene();
  1274. // Reset some special arrays
  1275. this._renderTargets.reset();
  1276. if (this.afterCameraRender) {
  1277. this.afterCameraRender(this.activeCamera);
  1278. }
  1279. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  1280. };
  1281. Scene.prototype._processSubCameras = function (camera) {
  1282. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  1283. this._renderForCamera(camera);
  1284. return;
  1285. }
  1286. // rig cameras
  1287. for (var index = 0; index < camera._rigCameras.length; index++) {
  1288. this._renderForCamera(camera._rigCameras[index]);
  1289. }
  1290. this.activeCamera = camera;
  1291. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  1292. // Update camera
  1293. this.activeCamera._updateFromScene();
  1294. };
  1295. Scene.prototype._checkIntersections = function () {
  1296. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  1297. var sourceMesh = this._meshesForIntersections.data[index];
  1298. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  1299. var action = sourceMesh.actionManager.actions[actionIndex];
  1300. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1301. var parameters = action.getTriggerParameter();
  1302. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  1303. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  1304. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  1305. if (areIntersecting && currentIntersectionInProgress === -1) {
  1306. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  1307. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1308. sourceMesh._intersectionsInProgress.push(otherMesh);
  1309. }
  1310. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1311. sourceMesh._intersectionsInProgress.push(otherMesh);
  1312. }
  1313. }
  1314. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  1315. //They intersected, and now they don't.
  1316. //is this trigger an exit trigger? execute an event.
  1317. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1318. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  1319. }
  1320. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  1321. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  1322. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  1323. }
  1324. }
  1325. }
  1326. }
  1327. }
  1328. };
  1329. Scene.prototype.render = function () {
  1330. var startDate = BABYLON.Tools.Now;
  1331. this._particlesDuration = 0;
  1332. this._spritesDuration = 0;
  1333. this._activeParticles = 0;
  1334. this._renderDuration = 0;
  1335. this._renderTargetsDuration = 0;
  1336. this._evaluateActiveMeshesDuration = 0;
  1337. this._totalVertices = 0;
  1338. this._activeIndices = 0;
  1339. this._activeBones = 0;
  1340. this.getEngine().resetDrawCalls();
  1341. this._meshesForIntersections.reset();
  1342. this.resetCachedMaterial();
  1343. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  1344. // Actions
  1345. if (this.actionManager) {
  1346. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  1347. }
  1348. //Simplification Queue
  1349. if (this.simplificationQueue && !this.simplificationQueue.running) {
  1350. this.simplificationQueue.executeNext();
  1351. }
  1352. // Animations
  1353. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  1354. this._animationRatio = deltaTime * (60.0 / 1000.0);
  1355. this._animate();
  1356. // Physics
  1357. if (this._physicsEngine) {
  1358. BABYLON.Tools.StartPerformanceCounter("Physics");
  1359. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  1360. BABYLON.Tools.EndPerformanceCounter("Physics");
  1361. }
  1362. // Before render
  1363. if (this.beforeRender) {
  1364. this.beforeRender();
  1365. }
  1366. var callbackIndex;
  1367. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  1368. this._onBeforeRenderCallbacks[callbackIndex]();
  1369. }
  1370. // Customs render targets
  1371. var beforeRenderTargetDate = BABYLON.Tools.Now;
  1372. var engine = this.getEngine();
  1373. var currentActiveCamera = this.activeCamera;
  1374. if (this.renderTargetsEnabled) {
  1375. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1376. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  1377. var renderTarget = this.customRenderTargets[customIndex];
  1378. if (renderTarget._shouldRender()) {
  1379. this._renderId++;
  1380. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  1381. if (!this.activeCamera)
  1382. throw new Error("Active camera not set");
  1383. // Viewport
  1384. engine.setViewport(this.activeCamera.viewport);
  1385. // Camera
  1386. this.updateTransformMatrix();
  1387. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  1388. }
  1389. }
  1390. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  1391. this._renderId++;
  1392. }
  1393. if (this.customRenderTargets.length > 0) {
  1394. engine.restoreDefaultFramebuffer();
  1395. }
  1396. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  1397. this.activeCamera = currentActiveCamera;
  1398. // Procedural textures
  1399. if (this.proceduralTexturesEnabled) {
  1400. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1401. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  1402. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  1403. if (proceduralTexture._shouldRender()) {
  1404. proceduralTexture.render();
  1405. }
  1406. }
  1407. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  1408. }
  1409. // Clear
  1410. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  1411. // Shadows
  1412. if (this.shadowsEnabled) {
  1413. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  1414. var light = this.lights[lightIndex];
  1415. var shadowGenerator = light.getShadowGenerator();
  1416. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  1417. this._renderTargets.push(shadowGenerator.getShadowMap());
  1418. }
  1419. }
  1420. }
  1421. // Depth renderer
  1422. if (this._depthRenderer) {
  1423. this._renderTargets.push(this._depthRenderer.getDepthMap());
  1424. }
  1425. // RenderPipeline
  1426. this.postProcessRenderPipelineManager.update();
  1427. // Multi-cameras?
  1428. if (this.activeCameras.length > 0) {
  1429. var currentRenderId = this._renderId;
  1430. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  1431. this._renderId = currentRenderId;
  1432. this._processSubCameras(this.activeCameras[cameraIndex]);
  1433. }
  1434. }
  1435. else {
  1436. if (!this.activeCamera) {
  1437. throw new Error("No camera defined");
  1438. }
  1439. this._processSubCameras(this.activeCamera);
  1440. }
  1441. // Intersection checks
  1442. this._checkIntersections();
  1443. // Update the audio listener attached to the camera
  1444. if (BABYLON.AudioEngine) {
  1445. this._updateAudioParameters();
  1446. }
  1447. // After render
  1448. if (this.afterRender) {
  1449. this.afterRender();
  1450. }
  1451. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  1452. this._onAfterRenderCallbacks[callbackIndex]();
  1453. }
  1454. // Cleaning
  1455. for (var index = 0; index < this._toBeDisposed.length; index++) {
  1456. this._toBeDisposed.data[index].dispose();
  1457. this._toBeDisposed[index] = null;
  1458. }
  1459. this._toBeDisposed.reset();
  1460. if (this.dumpNextRenderTargets) {
  1461. this.dumpNextRenderTargets = false;
  1462. }
  1463. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  1464. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  1465. };
  1466. Scene.prototype._updateAudioParameters = function () {
  1467. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  1468. return;
  1469. }
  1470. var listeningCamera;
  1471. var audioEngine = BABYLON.Engine.audioEngine;
  1472. if (this.activeCameras.length > 0) {
  1473. listeningCamera = this.activeCameras[0];
  1474. }
  1475. else {
  1476. listeningCamera = this.activeCamera;
  1477. }
  1478. if (listeningCamera && audioEngine.canUseWebAudio) {
  1479. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  1480. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  1481. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  1482. cameraDirection.normalize();
  1483. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  1484. var i;
  1485. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1486. var sound = this.mainSoundTrack.soundCollection[i];
  1487. if (sound.useCustomAttenuation) {
  1488. sound.updateDistanceFromListener();
  1489. }
  1490. }
  1491. for (i = 0; i < this.soundTracks.length; i++) {
  1492. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1493. sound = this.soundTracks[i].soundCollection[j];
  1494. if (sound.useCustomAttenuation) {
  1495. sound.updateDistanceFromListener();
  1496. }
  1497. }
  1498. }
  1499. }
  1500. };
  1501. Object.defineProperty(Scene.prototype, "audioEnabled", {
  1502. // Audio
  1503. get: function () {
  1504. return this._audioEnabled;
  1505. },
  1506. set: function (value) {
  1507. this._audioEnabled = value;
  1508. if (BABYLON.AudioEngine) {
  1509. if (this._audioEnabled) {
  1510. this._enableAudio();
  1511. }
  1512. else {
  1513. this._disableAudio();
  1514. }
  1515. }
  1516. },
  1517. enumerable: true,
  1518. configurable: true
  1519. });
  1520. Scene.prototype._disableAudio = function () {
  1521. var i;
  1522. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1523. this.mainSoundTrack.soundCollection[i].pause();
  1524. }
  1525. for (i = 0; i < this.soundTracks.length; i++) {
  1526. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1527. this.soundTracks[i].soundCollection[j].pause();
  1528. }
  1529. }
  1530. };
  1531. Scene.prototype._enableAudio = function () {
  1532. var i;
  1533. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  1534. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  1535. this.mainSoundTrack.soundCollection[i].play();
  1536. }
  1537. }
  1538. for (i = 0; i < this.soundTracks.length; i++) {
  1539. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  1540. if (this.soundTracks[i].soundCollection[j].isPaused) {
  1541. this.soundTracks[i].soundCollection[j].play();
  1542. }
  1543. }
  1544. }
  1545. };
  1546. Object.defineProperty(Scene.prototype, "headphone", {
  1547. get: function () {
  1548. return this._headphone;
  1549. },
  1550. set: function (value) {
  1551. this._headphone = value;
  1552. if (BABYLON.AudioEngine) {
  1553. if (this._headphone) {
  1554. this._switchAudioModeForHeadphones();
  1555. }
  1556. else {
  1557. this._switchAudioModeForNormalSpeakers();
  1558. }
  1559. }
  1560. },
  1561. enumerable: true,
  1562. configurable: true
  1563. });
  1564. Scene.prototype._switchAudioModeForHeadphones = function () {
  1565. this.mainSoundTrack.switchPanningModelToHRTF();
  1566. for (var i = 0; i < this.soundTracks.length; i++) {
  1567. this.soundTracks[i].switchPanningModelToHRTF();
  1568. }
  1569. };
  1570. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  1571. this.mainSoundTrack.switchPanningModelToEqualPower();
  1572. for (var i = 0; i < this.soundTracks.length; i++) {
  1573. this.soundTracks[i].switchPanningModelToEqualPower();
  1574. }
  1575. };
  1576. Scene.prototype.enableDepthRenderer = function () {
  1577. if (this._depthRenderer) {
  1578. return this._depthRenderer;
  1579. }
  1580. this._depthRenderer = new BABYLON.DepthRenderer(this);
  1581. return this._depthRenderer;
  1582. };
  1583. Scene.prototype.disableDepthRenderer = function () {
  1584. if (!this._depthRenderer) {
  1585. return;
  1586. }
  1587. this._depthRenderer.dispose();
  1588. this._depthRenderer = null;
  1589. };
  1590. Scene.prototype.dispose = function () {
  1591. this.beforeRender = null;
  1592. this.afterRender = null;
  1593. this.skeletons = [];
  1594. this._boundingBoxRenderer.dispose();
  1595. if (this._depthRenderer) {
  1596. this._depthRenderer.dispose();
  1597. }
  1598. // Debug layer
  1599. this.debugLayer.hide();
  1600. // Events
  1601. if (this.onDispose) {
  1602. this.onDispose();
  1603. }
  1604. this._onBeforeRenderCallbacks = [];
  1605. this._onAfterRenderCallbacks = [];
  1606. this.detachControl();
  1607. // Release sounds & sounds tracks
  1608. if (BABYLON.AudioEngine) {
  1609. this.disposeSounds();
  1610. }
  1611. // Detach cameras
  1612. var canvas = this._engine.getRenderingCanvas();
  1613. var index;
  1614. for (index = 0; index < this.cameras.length; index++) {
  1615. this.cameras[index].detachControl(canvas);
  1616. }
  1617. // Release lights
  1618. while (this.lights.length) {
  1619. this.lights[0].dispose();
  1620. }
  1621. // Release meshes
  1622. while (this.meshes.length) {
  1623. this.meshes[0].dispose(true);
  1624. }
  1625. // Release cameras
  1626. while (this.cameras.length) {
  1627. this.cameras[0].dispose();
  1628. }
  1629. // Release materials
  1630. while (this.materials.length) {
  1631. this.materials[0].dispose();
  1632. }
  1633. // Release particles
  1634. while (this.particleSystems.length) {
  1635. this.particleSystems[0].dispose();
  1636. }
  1637. // Release sprites
  1638. while (this.spriteManagers.length) {
  1639. this.spriteManagers[0].dispose();
  1640. }
  1641. // Release layers
  1642. while (this.layers.length) {
  1643. this.layers[0].dispose();
  1644. }
  1645. // Release textures
  1646. while (this.textures.length) {
  1647. this.textures[0].dispose();
  1648. }
  1649. // Post-processes
  1650. this.postProcessManager.dispose();
  1651. // Physics
  1652. if (this._physicsEngine) {
  1653. this.disablePhysicsEngine();
  1654. }
  1655. // Remove from engine
  1656. index = this._engine.scenes.indexOf(this);
  1657. if (index > -1) {
  1658. this._engine.scenes.splice(index, 1);
  1659. }
  1660. this._engine.wipeCaches();
  1661. };
  1662. // Release sounds & sounds tracks
  1663. Scene.prototype.disposeSounds = function () {
  1664. this.mainSoundTrack.dispose();
  1665. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  1666. this.soundTracks[scIndex].dispose();
  1667. }
  1668. };
  1669. // Octrees
  1670. Scene.prototype.getWorldExtends = function () {
  1671. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  1672. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  1673. for (var index = 0; index < this.meshes.length; index++) {
  1674. var mesh = this.meshes[index];
  1675. mesh.computeWorldMatrix(true);
  1676. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  1677. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  1678. BABYLON.Tools.CheckExtends(minBox, min, max);
  1679. BABYLON.Tools.CheckExtends(maxBox, min, max);
  1680. }
  1681. return {
  1682. min: min,
  1683. max: max
  1684. };
  1685. };
  1686. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  1687. if (maxCapacity === void 0) { maxCapacity = 64; }
  1688. if (maxDepth === void 0) { maxDepth = 2; }
  1689. if (!this._selectionOctree) {
  1690. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  1691. }
  1692. var worldExtends = this.getWorldExtends();
  1693. // Update octree
  1694. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  1695. return this._selectionOctree;
  1696. };
  1697. // Picking
  1698. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  1699. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  1700. var engine = this._engine;
  1701. if (!camera) {
  1702. if (!this.activeCamera)
  1703. throw new Error("Active camera not set");
  1704. camera = this.activeCamera;
  1705. }
  1706. var cameraViewport = camera.viewport;
  1707. var viewport = cameraViewport.toGlobal(engine);
  1708. // Moving coordinates to local viewport world
  1709. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1710. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1711. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  1712. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  1713. };
  1714. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  1715. var engine = this._engine;
  1716. if (!camera) {
  1717. if (!this.activeCamera)
  1718. throw new Error("Active camera not set");
  1719. camera = this.activeCamera;
  1720. }
  1721. var cameraViewport = camera.viewport;
  1722. var viewport = cameraViewport.toGlobal(engine);
  1723. var identity = BABYLON.Matrix.Identity();
  1724. // Moving coordinates to local viewport world
  1725. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  1726. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  1727. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  1728. };
  1729. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  1730. var pickingInfo = null;
  1731. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  1732. var mesh = this.meshes[meshIndex];
  1733. if (predicate) {
  1734. if (!predicate(mesh)) {
  1735. continue;
  1736. }
  1737. }
  1738. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  1739. continue;
  1740. }
  1741. var world = mesh.getWorldMatrix();
  1742. var ray = rayFunction(world);
  1743. var result = mesh.intersects(ray, fastCheck);
  1744. if (!result || !result.hit)
  1745. continue;
  1746. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1747. continue;
  1748. pickingInfo = result;
  1749. if (fastCheck) {
  1750. break;
  1751. }
  1752. }
  1753. return pickingInfo || new BABYLON.PickingInfo();
  1754. };
  1755. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  1756. var pickingInfo = null;
  1757. camera = camera || this.activeCamera;
  1758. if (this.spriteManagers.length > 0) {
  1759. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  1760. var spriteManager = this.spriteManagers[spriteIndex];
  1761. if (!spriteManager.isPickable) {
  1762. continue;
  1763. }
  1764. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  1765. if (!result || !result.hit)
  1766. continue;
  1767. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  1768. continue;
  1769. pickingInfo = result;
  1770. if (fastCheck) {
  1771. break;
  1772. }
  1773. }
  1774. }
  1775. return pickingInfo || new BABYLON.PickingInfo();
  1776. };
  1777. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  1778. var _this = this;
  1779. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1780. /// <param name="x">X position on screen</param>
  1781. /// <param name="y">Y position on screen</param>
  1782. /// <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>
  1783. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1784. /// <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>
  1785. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  1786. };
  1787. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  1788. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  1789. /// <param name="x">X position on screen</param>
  1790. /// <param name="y">Y position on screen</param>
  1791. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  1792. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  1793. /// <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>
  1794. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  1795. };
  1796. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  1797. var _this = this;
  1798. return this._internalPick(function (world) {
  1799. if (!_this._pickWithRayInverseMatrix) {
  1800. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  1801. }
  1802. world.invertToRef(_this._pickWithRayInverseMatrix);
  1803. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  1804. }, predicate, fastCheck);
  1805. };
  1806. Scene.prototype.setPointerOverMesh = function (mesh) {
  1807. if (this._pointerOverMesh === mesh) {
  1808. return;
  1809. }
  1810. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1811. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  1812. }
  1813. this._pointerOverMesh = mesh;
  1814. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  1815. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  1816. }
  1817. };
  1818. Scene.prototype.getPointerOverMesh = function () {
  1819. return this._pointerOverMesh;
  1820. };
  1821. // Physics
  1822. Scene.prototype.getPhysicsEngine = function () {
  1823. return this._physicsEngine;
  1824. };
  1825. /**
  1826. * Enables physics to the current scene
  1827. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  1828. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  1829. * @return {boolean} was the physics engine initialized
  1830. */
  1831. Scene.prototype.enablePhysics = function (gravity, plugin) {
  1832. if (this._physicsEngine) {
  1833. return true;
  1834. }
  1835. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  1836. if (!this._physicsEngine.isSupported()) {
  1837. this._physicsEngine = null;
  1838. return false;
  1839. }
  1840. this._physicsEngine._initialize(gravity);
  1841. return true;
  1842. };
  1843. Scene.prototype.disablePhysicsEngine = function () {
  1844. if (!this._physicsEngine) {
  1845. return;
  1846. }
  1847. this._physicsEngine.dispose();
  1848. this._physicsEngine = undefined;
  1849. };
  1850. Scene.prototype.isPhysicsEnabled = function () {
  1851. return this._physicsEngine !== undefined;
  1852. };
  1853. /**
  1854. * Sets the gravity of the physics engine (and NOT of the scene)
  1855. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  1856. */
  1857. Scene.prototype.setGravity = function (gravity) {
  1858. if (!this._physicsEngine) {
  1859. return;
  1860. }
  1861. this._physicsEngine._setGravity(gravity);
  1862. };
  1863. Scene.prototype.createCompoundImpostor = function (parts, options) {
  1864. if (parts.parts) {
  1865. options = parts;
  1866. parts = parts.parts;
  1867. }
  1868. if (!this._physicsEngine) {
  1869. return null;
  1870. }
  1871. for (var index = 0; index < parts.length; index++) {
  1872. var mesh = parts[index].mesh;
  1873. mesh._physicImpostor = parts[index].impostor;
  1874. mesh._physicsMass = options.mass / parts.length;
  1875. mesh._physicsFriction = options.friction;
  1876. mesh._physicRestitution = options.restitution;
  1877. }
  1878. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  1879. };
  1880. Scene.prototype.deleteCompoundImpostor = function (compound) {
  1881. for (var index = 0; index < compound.parts.length; index++) {
  1882. var mesh = compound.parts[index].mesh;
  1883. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  1884. this._physicsEngine._unregisterMesh(mesh);
  1885. }
  1886. };
  1887. // Misc.
  1888. Scene.prototype.createDefaultCameraOrLight = function () {
  1889. // Light
  1890. if (this.lights.length === 0) {
  1891. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  1892. }
  1893. // Camera
  1894. if (!this.activeCamera) {
  1895. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  1896. // Compute position
  1897. var worldExtends = this.getWorldExtends();
  1898. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  1899. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  1900. camera.setTarget(worldCenter);
  1901. this.activeCamera = camera;
  1902. }
  1903. };
  1904. // Tags
  1905. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  1906. if (tagsQuery === undefined) {
  1907. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  1908. return list;
  1909. }
  1910. var listByTags = [];
  1911. forEach = forEach || (function (item) { return; });
  1912. for (var i in list) {
  1913. var item = list[i];
  1914. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  1915. listByTags.push(item);
  1916. forEach(item);
  1917. }
  1918. }
  1919. return listByTags;
  1920. };
  1921. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  1922. return this._getByTags(this.meshes, tagsQuery, forEach);
  1923. };
  1924. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  1925. return this._getByTags(this.cameras, tagsQuery, forEach);
  1926. };
  1927. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  1928. return this._getByTags(this.lights, tagsQuery, forEach);
  1929. };
  1930. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  1931. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  1932. };
  1933. // Statics
  1934. Scene._FOGMODE_NONE = 0;
  1935. Scene._FOGMODE_EXP = 1;
  1936. Scene._FOGMODE_EXP2 = 2;
  1937. Scene._FOGMODE_LINEAR = 3;
  1938. Scene.MinDeltaTime = 1.0;
  1939. Scene.MaxDeltaTime = 1000.0;
  1940. return Scene;
  1941. })();
  1942. BABYLON.Scene = Scene;
  1943. })(BABYLON || (BABYLON = {}));