babylon.scene.ts 45 KB

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