babylon.scene.js 46 KB

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