babylon.scene.ts 43 KB

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