babylon.scene.js 47 KB

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