babylon.scene.js 49 KB

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