babylon.scene.js 59 KB

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