babylon.scene.ts 44 KB

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