camera.ts 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. import { serialize, SerializationHelper, serializeAsVector3 } from "../Misc/decorators";
  2. import { SmartArray } from "../Misc/smartArray";
  3. import { Tools } from "../Misc/tools";
  4. import { Observable } from "../Misc/observable";
  5. import { Nullable } from "../types";
  6. import { CameraInputsManager } from "./cameraInputsManager";
  7. import { Scene } from "../scene";
  8. import { Matrix, Vector3, Viewport, Plane, Frustum } from "../Maths/math";
  9. import { Node } from "../node";
  10. import { Mesh } from "../Meshes/mesh";
  11. import { AbstractMesh } from "../Meshes/abstractMesh";
  12. import { Ray } from "../Culling/ray";
  13. import { ICullable } from "../Culling/boundingInfo";
  14. import { Logger } from "../Misc/logger";
  15. import { Animation } from "../Animations/animation";
  16. declare type PostProcess = import("../PostProcesses/postProcess").PostProcess;
  17. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  18. declare type FreeCamera = import("./freeCamera").FreeCamera;
  19. declare type TargetCamera = import("./targetCamera").TargetCamera;
  20. /**
  21. * This is the base class of all the camera used in the application.
  22. * @see http://doc.babylonjs.com/features/cameras
  23. */
  24. export class Camera extends Node {
  25. /** @hidden */
  26. public static _createDefaultParsedCamera = (name: string, scene: Scene): Camera => {
  27. throw "UniversalCamera needs to be imported before deserialization can create a default camera.";
  28. }
  29. /**
  30. * This is the default projection mode used by the cameras.
  31. * It helps recreating a feeling of perspective and better appreciate depth.
  32. * This is the best way to simulate real life cameras.
  33. */
  34. public static readonly PERSPECTIVE_CAMERA = 0;
  35. /**
  36. * This helps creating camera with an orthographic mode.
  37. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  38. */
  39. public static readonly ORTHOGRAPHIC_CAMERA = 1;
  40. /**
  41. * This is the default FOV mode for perspective cameras.
  42. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  43. */
  44. public static readonly FOVMODE_VERTICAL_FIXED = 0;
  45. /**
  46. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  47. */
  48. public static readonly FOVMODE_HORIZONTAL_FIXED = 1;
  49. /**
  50. * This specifies ther is no need for a camera rig.
  51. * Basically only one eye is rendered corresponding to the camera.
  52. */
  53. public static readonly RIG_MODE_NONE = 0;
  54. /**
  55. * Simulates a camera Rig with one blue eye and one red eye.
  56. * This can be use with 3d blue and red glasses.
  57. */
  58. public static readonly RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  59. /**
  60. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  61. */
  62. public static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  63. /**
  64. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  65. */
  66. public static readonly RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  67. /**
  68. * Defines that both eyes of the camera will be rendered over under each other.
  69. */
  70. public static readonly RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  71. /**
  72. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  73. */
  74. public static readonly RIG_MODE_VR = 20;
  75. /**
  76. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  77. */
  78. public static readonly RIG_MODE_WEBVR = 21;
  79. /**
  80. * Custom rig mode allowing rig cameras to be populated manually with any number of cameras
  81. */
  82. public static readonly RIG_MODE_CUSTOM = 22;
  83. /**
  84. * Defines if by default attaching controls should prevent the default javascript event to continue.
  85. */
  86. public static ForceAttachControlToAlwaysPreventDefault = false;
  87. /**
  88. * @hidden
  89. * Might be removed once multiview will be a thing
  90. */
  91. public static UseAlternateWebVRRendering = false;
  92. /**
  93. * Define the input manager associated with the camera.
  94. */
  95. public inputs: CameraInputsManager<Camera>;
  96. /**
  97. * Define the current local position of the camera in the scene
  98. */
  99. @serializeAsVector3()
  100. public position: Vector3;
  101. /**
  102. * The vector the camera should consider as up.
  103. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  104. */
  105. @serializeAsVector3()
  106. public upVector = Vector3.Up();
  107. /**
  108. * Define the current limit on the left side for an orthographic camera
  109. * In scene unit
  110. */
  111. @serialize()
  112. public orthoLeft: Nullable<number> = null;
  113. /**
  114. * Define the current limit on the right side for an orthographic camera
  115. * In scene unit
  116. */
  117. @serialize()
  118. public orthoRight: Nullable<number> = null;
  119. /**
  120. * Define the current limit on the bottom side for an orthographic camera
  121. * In scene unit
  122. */
  123. @serialize()
  124. public orthoBottom: Nullable<number> = null;
  125. /**
  126. * Define the current limit on the top side for an orthographic camera
  127. * In scene unit
  128. */
  129. @serialize()
  130. public orthoTop: Nullable<number> = null;
  131. /**
  132. * Field Of View is set in Radians. (default is 0.8)
  133. */
  134. @serialize()
  135. public fov = 0.8;
  136. /**
  137. * Define the minimum distance the camera can see from.
  138. * This is important to note that the depth buffer are not infinite and the closer it starts
  139. * the more your scene might encounter depth fighting issue.
  140. */
  141. @serialize()
  142. public minZ = 1;
  143. /**
  144. * Define the maximum distance the camera can see to.
  145. * This is important to note that the depth buffer are not infinite and the further it end
  146. * the more your scene might encounter depth fighting issue.
  147. */
  148. @serialize()
  149. public maxZ = 10000.0;
  150. /**
  151. * Define the default inertia of the camera.
  152. * This helps giving a smooth feeling to the camera movement.
  153. */
  154. @serialize()
  155. public inertia = 0.9;
  156. /**
  157. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  158. */
  159. @serialize()
  160. public mode = Camera.PERSPECTIVE_CAMERA;
  161. /**
  162. * Define wether the camera is intermediate.
  163. * This is useful to not present the output directly to the screen in case of rig without post process for instance
  164. */
  165. public isIntermediate = false;
  166. /**
  167. * Define the viewport of the camera.
  168. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  169. */
  170. public viewport = new Viewport(0, 0, 1.0, 1.0);
  171. /**
  172. * Restricts the camera to viewing objects with the same layerMask.
  173. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  174. */
  175. @serialize()
  176. public layerMask: number = 0x0FFFFFFF;
  177. /**
  178. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  179. */
  180. @serialize()
  181. public fovMode: number = Camera.FOVMODE_VERTICAL_FIXED;
  182. /**
  183. * Rig mode of the camera.
  184. * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  185. * This is normally controlled byt the camera themselves as internal use.
  186. */
  187. @serialize()
  188. public cameraRigMode = Camera.RIG_MODE_NONE;
  189. /**
  190. * Defines the distance between both "eyes" in case of a RIG
  191. */
  192. @serialize()
  193. public interaxialDistance: number;
  194. /**
  195. * Defines if stereoscopic rendering is done side by side or over under.
  196. */
  197. @serialize()
  198. public isStereoscopicSideBySide: boolean;
  199. /**
  200. * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
  201. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  202. * else in the scene.
  203. */
  204. public customRenderTargets = new Array<RenderTargetTexture>();
  205. /**
  206. * When set, the camera will render to this render target instead of the default canvas
  207. */
  208. public outputRenderTarget: Nullable<RenderTargetTexture> = null;
  209. /**
  210. * Observable triggered when the camera view matrix has changed.
  211. */
  212. public onViewMatrixChangedObservable = new Observable<Camera>();
  213. /**
  214. * Observable triggered when the camera Projection matrix has changed.
  215. */
  216. public onProjectionMatrixChangedObservable = new Observable<Camera>();
  217. /**
  218. * Observable triggered when the inputs have been processed.
  219. */
  220. public onAfterCheckInputsObservable = new Observable<Camera>();
  221. /**
  222. * Observable triggered when reset has been called and applied to the camera.
  223. */
  224. public onRestoreStateObservable = new Observable<Camera>();
  225. /** @hidden */
  226. public _cameraRigParams: any;
  227. /** @hidden */
  228. public _rigCameras = new Array<Camera>();
  229. /** @hidden */
  230. public _rigPostProcess: Nullable<PostProcess>;
  231. protected _webvrViewMatrix = Matrix.Identity();
  232. /** @hidden */
  233. public _skipRendering = false;
  234. /** @hidden */
  235. public _alternateCamera: Camera;
  236. /** @hidden */
  237. public _projectionMatrix = new Matrix();
  238. /** @hidden */
  239. public _postProcesses = new Array<Nullable<PostProcess>>();
  240. /** @hidden */
  241. public _activeMeshes = new SmartArray<AbstractMesh>(256);
  242. protected _globalPosition = Vector3.Zero();
  243. /** hidden */
  244. public _computedViewMatrix = Matrix.Identity();
  245. private _doNotComputeProjectionMatrix = false;
  246. private _transformMatrix = Matrix.Zero();
  247. private _frustumPlanes: Plane[];
  248. private _refreshFrustumPlanes = true;
  249. private _storedFov: number;
  250. private _stateStored: boolean;
  251. /**
  252. * Instantiates a new camera object.
  253. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  254. * @see http://doc.babylonjs.com/features/cameras
  255. * @param name Defines the name of the camera in the scene
  256. * @param position Defines the position of the camera
  257. * @param scene Defines the scene the camera belongs too
  258. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  259. */
  260. constructor(name: string, position: Vector3, scene: Scene, setActiveOnSceneIfNoneActive = true) {
  261. super(name, scene);
  262. this.getScene().addCamera(this);
  263. if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) {
  264. this.getScene().activeCamera = this;
  265. }
  266. this.position = position;
  267. }
  268. /**
  269. * Store current camera state (fov, position, etc..)
  270. * @returns the camera
  271. */
  272. public storeState(): Camera {
  273. this._stateStored = true;
  274. this._storedFov = this.fov;
  275. return this;
  276. }
  277. /**
  278. * Restores the camera state values if it has been stored. You must call storeState() first
  279. */
  280. protected _restoreStateValues(): boolean {
  281. if (!this._stateStored) {
  282. return false;
  283. }
  284. this.fov = this._storedFov;
  285. return true;
  286. }
  287. /**
  288. * Restored camera state. You must call storeState() first.
  289. * @returns true if restored and false otherwise
  290. */
  291. public restoreState(): boolean {
  292. if (this._restoreStateValues()) {
  293. this.onRestoreStateObservable.notifyObservers(this);
  294. return true;
  295. }
  296. return false;
  297. }
  298. /**
  299. * Gets the class name of the camera.
  300. * @returns the class name
  301. */
  302. public getClassName(): string {
  303. return "Camera";
  304. }
  305. /** @hidden */
  306. public readonly _isCamera = true;
  307. /**
  308. * Gets a string representation of the camera useful for debug purpose.
  309. * @param fullDetails Defines that a more verboe level of logging is required
  310. * @returns the string representation
  311. */
  312. public toString(fullDetails?: boolean): string {
  313. var ret = "Name: " + this.name;
  314. ret += ", type: " + this.getClassName();
  315. if (this.animations) {
  316. for (var i = 0; i < this.animations.length; i++) {
  317. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  318. }
  319. }
  320. if (fullDetails) {
  321. }
  322. return ret;
  323. }
  324. /**
  325. * Gets the current world space position of the camera.
  326. */
  327. public get globalPosition(): Vector3 {
  328. return this._globalPosition;
  329. }
  330. /**
  331. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  332. * @returns the active meshe list
  333. */
  334. public getActiveMeshes(): SmartArray<AbstractMesh> {
  335. return this._activeMeshes;
  336. }
  337. /**
  338. * Check wether a mesh is part of the current active mesh list of the camera
  339. * @param mesh Defines the mesh to check
  340. * @returns true if active, false otherwise
  341. */
  342. public isActiveMesh(mesh: Mesh): boolean {
  343. return (this._activeMeshes.indexOf(mesh) !== -1);
  344. }
  345. /**
  346. * Is this camera ready to be used/rendered
  347. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  348. * @return true if the camera is ready
  349. */
  350. public isReady(completeCheck = false): boolean {
  351. if (completeCheck) {
  352. for (var pp of this._postProcesses) {
  353. if (pp && !pp.isReady()) {
  354. return false;
  355. }
  356. }
  357. }
  358. return super.isReady(completeCheck);
  359. }
  360. /** @hidden */
  361. public _initCache() {
  362. super._initCache();
  363. this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  364. this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  365. this._cache.mode = undefined;
  366. this._cache.minZ = undefined;
  367. this._cache.maxZ = undefined;
  368. this._cache.fov = undefined;
  369. this._cache.fovMode = undefined;
  370. this._cache.aspectRatio = undefined;
  371. this._cache.orthoLeft = undefined;
  372. this._cache.orthoRight = undefined;
  373. this._cache.orthoBottom = undefined;
  374. this._cache.orthoTop = undefined;
  375. this._cache.renderWidth = undefined;
  376. this._cache.renderHeight = undefined;
  377. }
  378. /** @hidden */
  379. public _updateCache(ignoreParentClass?: boolean): void {
  380. if (!ignoreParentClass) {
  381. super._updateCache();
  382. }
  383. this._cache.position.copyFrom(this.position);
  384. this._cache.upVector.copyFrom(this.upVector);
  385. }
  386. /** @hidden */
  387. public _isSynchronized(): boolean {
  388. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  389. }
  390. /** @hidden */
  391. public _isSynchronizedViewMatrix(): boolean {
  392. if (!super._isSynchronized()) {
  393. return false;
  394. }
  395. return this._cache.position.equals(this.position)
  396. && this._cache.upVector.equals(this.upVector)
  397. && this.isSynchronizedWithParent();
  398. }
  399. /** @hidden */
  400. public _isSynchronizedProjectionMatrix(): boolean {
  401. var check = this._cache.mode === this.mode
  402. && this._cache.minZ === this.minZ
  403. && this._cache.maxZ === this.maxZ;
  404. if (!check) {
  405. return false;
  406. }
  407. var engine = this.getEngine();
  408. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  409. check = this._cache.fov === this.fov
  410. && this._cache.fovMode === this.fovMode
  411. && this._cache.aspectRatio === engine.getAspectRatio(this);
  412. }
  413. else {
  414. check = this._cache.orthoLeft === this.orthoLeft
  415. && this._cache.orthoRight === this.orthoRight
  416. && this._cache.orthoBottom === this.orthoBottom
  417. && this._cache.orthoTop === this.orthoTop
  418. && this._cache.renderWidth === engine.getRenderWidth()
  419. && this._cache.renderHeight === engine.getRenderHeight();
  420. }
  421. return check;
  422. }
  423. /**
  424. * Attach the input controls to a specific dom element to get the input from.
  425. * @param element Defines the element the controls should be listened from
  426. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  427. */
  428. public attachControl(element: HTMLElement, noPreventDefault?: boolean): void {
  429. }
  430. /**
  431. * Detach the current controls from the specified dom element.
  432. * @param element Defines the element to stop listening the inputs from
  433. */
  434. public detachControl(element: HTMLElement): void {
  435. }
  436. /**
  437. * Update the camera state according to the different inputs gathered during the frame.
  438. */
  439. public update(): void {
  440. this._checkInputs();
  441. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  442. this._updateRigCameras();
  443. }
  444. }
  445. /** @hidden */
  446. public _checkInputs(): void {
  447. this.onAfterCheckInputsObservable.notifyObservers(this);
  448. }
  449. /** @hidden */
  450. public get rigCameras(): Camera[] {
  451. return this._rigCameras;
  452. }
  453. /**
  454. * Gets the post process used by the rig cameras
  455. */
  456. public get rigPostProcess(): Nullable<PostProcess> {
  457. return this._rigPostProcess;
  458. }
  459. /**
  460. * Internal, gets the first post proces.
  461. * @returns the first post process to be run on this camera.
  462. */
  463. public _getFirstPostProcess(): Nullable<PostProcess> {
  464. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  465. if (this._postProcesses[ppIndex] !== null) {
  466. return this._postProcesses[ppIndex];
  467. }
  468. }
  469. return null;
  470. }
  471. private _cascadePostProcessesToRigCams(): void {
  472. // invalidate framebuffer
  473. var firstPostProcess = this._getFirstPostProcess();
  474. if (firstPostProcess) {
  475. firstPostProcess.markTextureDirty();
  476. }
  477. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  478. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  479. var cam = this._rigCameras[i];
  480. var rigPostProcess = cam._rigPostProcess;
  481. // for VR rig, there does not have to be a post process
  482. if (rigPostProcess) {
  483. var isPass = rigPostProcess.getEffectName() === "pass";
  484. if (isPass) {
  485. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  486. cam.isIntermediate = this._postProcesses.length === 0;
  487. }
  488. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  489. rigPostProcess.markTextureDirty();
  490. } else {
  491. cam._postProcesses = this._postProcesses.slice(0);
  492. }
  493. }
  494. }
  495. /**
  496. * Attach a post process to the camera.
  497. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  498. * @param postProcess The post process to attach to the camera
  499. * @param insertAt The position of the post process in case several of them are in use in the scene
  500. * @returns the position the post process has been inserted at
  501. */
  502. public attachPostProcess(postProcess: PostProcess, insertAt: Nullable<number> = null): number {
  503. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  504. Logger.Error("You're trying to reuse a post process not defined as reusable.");
  505. return 0;
  506. }
  507. if (insertAt == null || insertAt < 0) {
  508. this._postProcesses.push(postProcess);
  509. } else if (this._postProcesses[insertAt] === null) {
  510. this._postProcesses[insertAt] = postProcess;
  511. } else {
  512. this._postProcesses.splice(insertAt, 0, postProcess);
  513. }
  514. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  515. return this._postProcesses.indexOf(postProcess);
  516. }
  517. /**
  518. * Detach a post process to the camera.
  519. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  520. * @param postProcess The post process to detach from the camera
  521. */
  522. public detachPostProcess(postProcess: PostProcess): void {
  523. var idx = this._postProcesses.indexOf(postProcess);
  524. if (idx !== -1) {
  525. this._postProcesses[idx] = null;
  526. }
  527. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  528. }
  529. /**
  530. * Gets the current world matrix of the camera
  531. */
  532. public getWorldMatrix(): Matrix {
  533. if (this._isSynchronizedViewMatrix()) {
  534. return this._worldMatrix;
  535. }
  536. // Getting the the view matrix will also compute the world matrix.
  537. this.getViewMatrix();
  538. return this._worldMatrix;
  539. }
  540. /** @hidden */
  541. public _getViewMatrix(): Matrix {
  542. return Matrix.Identity();
  543. }
  544. /**
  545. * Gets the current view matrix of the camera.
  546. * @param force forces the camera to recompute the matrix without looking at the cached state
  547. * @returns the view matrix
  548. */
  549. public getViewMatrix(force?: boolean): Matrix {
  550. if (!force && this._isSynchronizedViewMatrix()) {
  551. return this._computedViewMatrix;
  552. }
  553. this.updateCache();
  554. this._computedViewMatrix = this._getViewMatrix();
  555. this._currentRenderId = this.getScene().getRenderId();
  556. this._childRenderId = this._currentRenderId;
  557. this._refreshFrustumPlanes = true;
  558. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  559. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  560. }
  561. this.onViewMatrixChangedObservable.notifyObservers(this);
  562. this._computedViewMatrix.invertToRef(this._worldMatrix);
  563. return this._computedViewMatrix;
  564. }
  565. /**
  566. * Freeze the projection matrix.
  567. * It will prevent the cache check of the camera projection compute and can speed up perf
  568. * if no parameter of the camera are meant to change
  569. * @param projection Defines manually a projection if necessary
  570. */
  571. public freezeProjectionMatrix(projection?: Matrix): void {
  572. this._doNotComputeProjectionMatrix = true;
  573. if (projection !== undefined) {
  574. this._projectionMatrix = projection;
  575. }
  576. }
  577. /**
  578. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  579. */
  580. public unfreezeProjectionMatrix(): void {
  581. this._doNotComputeProjectionMatrix = false;
  582. }
  583. /**
  584. * Gets the current projection matrix of the camera.
  585. * @param force forces the camera to recompute the matrix without looking at the cached state
  586. * @returns the projection matrix
  587. */
  588. public getProjectionMatrix(force?: boolean): Matrix {
  589. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  590. return this._projectionMatrix;
  591. }
  592. // Cache
  593. this._cache.mode = this.mode;
  594. this._cache.minZ = this.minZ;
  595. this._cache.maxZ = this.maxZ;
  596. // Matrix
  597. this._refreshFrustumPlanes = true;
  598. var engine = this.getEngine();
  599. var scene = this.getScene();
  600. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  601. this._cache.fov = this.fov;
  602. this._cache.fovMode = this.fovMode;
  603. this._cache.aspectRatio = engine.getAspectRatio(this);
  604. if (this.minZ <= 0) {
  605. this.minZ = 0.1;
  606. }
  607. if (scene.useRightHandedSystem) {
  608. Matrix.PerspectiveFovRHToRef(this.fov,
  609. engine.getAspectRatio(this),
  610. this.minZ,
  611. this.maxZ,
  612. this._projectionMatrix,
  613. this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  614. } else {
  615. Matrix.PerspectiveFovLHToRef(this.fov,
  616. engine.getAspectRatio(this),
  617. this.minZ,
  618. this.maxZ,
  619. this._projectionMatrix,
  620. this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  621. }
  622. } else {
  623. var halfWidth = engine.getRenderWidth() / 2.0;
  624. var halfHeight = engine.getRenderHeight() / 2.0;
  625. if (scene.useRightHandedSystem) {
  626. Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth,
  627. this.orthoRight || halfWidth,
  628. this.orthoBottom || -halfHeight,
  629. this.orthoTop || halfHeight,
  630. this.minZ,
  631. this.maxZ,
  632. this._projectionMatrix);
  633. } else {
  634. Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth,
  635. this.orthoRight || halfWidth,
  636. this.orthoBottom || -halfHeight,
  637. this.orthoTop || halfHeight,
  638. this.minZ,
  639. this.maxZ,
  640. this._projectionMatrix);
  641. }
  642. this._cache.orthoLeft = this.orthoLeft;
  643. this._cache.orthoRight = this.orthoRight;
  644. this._cache.orthoBottom = this.orthoBottom;
  645. this._cache.orthoTop = this.orthoTop;
  646. this._cache.renderWidth = engine.getRenderWidth();
  647. this._cache.renderHeight = engine.getRenderHeight();
  648. }
  649. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  650. return this._projectionMatrix;
  651. }
  652. /**
  653. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  654. * @returns a Matrix
  655. */
  656. public getTransformationMatrix(): Matrix {
  657. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  658. return this._transformMatrix;
  659. }
  660. private _updateFrustumPlanes(): void {
  661. if (!this._refreshFrustumPlanes) {
  662. return;
  663. }
  664. this.getTransformationMatrix();
  665. if (!this._frustumPlanes) {
  666. this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);
  667. } else {
  668. Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  669. }
  670. this._refreshFrustumPlanes = false;
  671. }
  672. /**
  673. * Checks if a cullable object (mesh...) is in the camera frustum
  674. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  675. * @param target The object to check
  676. * @returns true if the object is in frustum otherwise false
  677. */
  678. public isInFrustum(target: ICullable): boolean {
  679. this._updateFrustumPlanes();
  680. return target.isInFrustum(this._frustumPlanes);
  681. }
  682. /**
  683. * Checks if a cullable object (mesh...) is in the camera frustum
  684. * Unlike isInFrustum this cheks the full bounding box
  685. * @param target The object to check
  686. * @returns true if the object is in frustum otherwise false
  687. */
  688. public isCompletelyInFrustum(target: ICullable): boolean {
  689. this._updateFrustumPlanes();
  690. return target.isCompletelyInFrustum(this._frustumPlanes);
  691. }
  692. /**
  693. * Gets a ray in the forward direction from the camera.
  694. * @param length Defines the length of the ray to create
  695. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  696. * @param origin Defines the start point of the ray which defaults to the camera position
  697. * @returns the forward ray
  698. */
  699. public getForwardRay(length = 100, transform?: Matrix, origin?: Vector3): Ray {
  700. if (!transform) {
  701. transform = this.getWorldMatrix();
  702. }
  703. if (!origin) {
  704. origin = this.position;
  705. }
  706. var forward = this._scene.useRightHandedSystem ? new Vector3(0, 0, -1) : new Vector3(0, 0, 1);
  707. var forwardWorld = Vector3.TransformNormal(forward, transform);
  708. var direction = Vector3.Normalize(forwardWorld);
  709. return new Ray(origin, direction, length);
  710. }
  711. /**
  712. * Releases resources associated with this node.
  713. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  714. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  715. */
  716. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  717. // Observables
  718. this.onViewMatrixChangedObservable.clear();
  719. this.onProjectionMatrixChangedObservable.clear();
  720. this.onAfterCheckInputsObservable.clear();
  721. this.onRestoreStateObservable.clear();
  722. // Inputs
  723. if (this.inputs) {
  724. this.inputs.clear();
  725. }
  726. // Animations
  727. this.getScene().stopAnimation(this);
  728. // Remove from scene
  729. this.getScene().removeCamera(this);
  730. while (this._rigCameras.length > 0) {
  731. let camera = this._rigCameras.pop();
  732. if (camera) {
  733. camera.dispose();
  734. }
  735. }
  736. // Postprocesses
  737. if (this._rigPostProcess) {
  738. this._rigPostProcess.dispose(this);
  739. this._rigPostProcess = null;
  740. this._postProcesses = [];
  741. }
  742. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  743. this._rigPostProcess = null;
  744. this._postProcesses = [];
  745. } else {
  746. var i = this._postProcesses.length;
  747. while (--i >= 0) {
  748. var postProcess = this._postProcesses[i];
  749. if (postProcess) {
  750. postProcess.dispose(this);
  751. }
  752. }
  753. }
  754. // Render targets
  755. var i = this.customRenderTargets.length;
  756. while (--i >= 0) {
  757. this.customRenderTargets[i].dispose();
  758. }
  759. this.customRenderTargets = [];
  760. // Active Meshes
  761. this._activeMeshes.dispose();
  762. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  763. }
  764. /**
  765. * Gets the left camera of a rig setup in case of Rigged Camera
  766. */
  767. public get leftCamera(): Nullable<FreeCamera> {
  768. if (this._rigCameras.length < 1) {
  769. return null;
  770. }
  771. return (<FreeCamera>this._rigCameras[0]);
  772. }
  773. /**
  774. * Gets the right camera of a rig setup in case of Rigged Camera
  775. */
  776. public get rightCamera(): Nullable<FreeCamera> {
  777. if (this._rigCameras.length < 2) {
  778. return null;
  779. }
  780. return (<FreeCamera>this._rigCameras[1]);
  781. }
  782. /**
  783. * Gets the left camera target of a rig setup in case of Rigged Camera
  784. * @returns the target position
  785. */
  786. public getLeftTarget(): Nullable<Vector3> {
  787. if (this._rigCameras.length < 1) {
  788. return null;
  789. }
  790. return (<TargetCamera>this._rigCameras[0]).getTarget();
  791. }
  792. /**
  793. * Gets the right camera target of a rig setup in case of Rigged Camera
  794. * @returns the target position
  795. */
  796. public getRightTarget(): Nullable<Vector3> {
  797. if (this._rigCameras.length < 2) {
  798. return null;
  799. }
  800. return (<TargetCamera>this._rigCameras[1]).getTarget();
  801. }
  802. /**
  803. * @hidden
  804. */
  805. public setCameraRigMode(mode: number, rigParams: any): void {
  806. if (this.cameraRigMode === mode) {
  807. return;
  808. }
  809. while (this._rigCameras.length > 0) {
  810. let camera = this._rigCameras.pop();
  811. if (camera) {
  812. camera.dispose();
  813. }
  814. }
  815. this.cameraRigMode = mode;
  816. this._cameraRigParams = {};
  817. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  818. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  819. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  820. this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  821. // create the rig cameras, unless none
  822. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  823. let leftCamera = this.createRigCamera(this.name + "_L", 0);
  824. let rightCamera = this.createRigCamera(this.name + "_R", 1);
  825. if (leftCamera && rightCamera) {
  826. this._rigCameras.push(leftCamera);
  827. this._rigCameras.push(rightCamera);
  828. }
  829. }
  830. switch (this.cameraRigMode) {
  831. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  832. Camera._setStereoscopicAnaglyphRigMode(this);
  833. break;
  834. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  835. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  836. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  837. Camera._setStereoscopicRigMode(this);
  838. break;
  839. case Camera.RIG_MODE_VR:
  840. Camera._setVRRigMode(this, rigParams);
  841. break;
  842. case Camera.RIG_MODE_WEBVR:
  843. Camera._setWebVRRigMode(this, rigParams);
  844. break;
  845. }
  846. this._cascadePostProcessesToRigCams();
  847. this.update();
  848. }
  849. /** @hidden */
  850. public static _setStereoscopicRigMode(camera: Camera) {
  851. throw "Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode";
  852. }
  853. /** @hidden */
  854. public static _setStereoscopicAnaglyphRigMode(camera: Camera) {
  855. throw "Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode";
  856. }
  857. /** @hidden */
  858. public static _setVRRigMode(camera: Camera, rigParams: any) {
  859. throw "Import Cameras/RigModes/vrRigMode before using VR rig mode";
  860. }
  861. /** @hidden */
  862. public static _setWebVRRigMode(camera: Camera, rigParams: any) {
  863. throw "Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode";
  864. }
  865. /** @hidden */
  866. public _getVRProjectionMatrix(): Matrix {
  867. Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  868. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  869. return this._projectionMatrix;
  870. }
  871. protected _updateCameraRotationMatrix() {
  872. //Here for WebVR
  873. }
  874. protected _updateWebVRCameraRotationMatrix() {
  875. //Here for WebVR
  876. }
  877. /**
  878. * This function MUST be overwritten by the different WebVR cameras available.
  879. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  880. * @hidden
  881. */
  882. public _getWebVRProjectionMatrix(): Matrix {
  883. return Matrix.Identity();
  884. }
  885. /**
  886. * This function MUST be overwritten by the different WebVR cameras available.
  887. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  888. * @hidden
  889. */
  890. public _getWebVRViewMatrix(): Matrix {
  891. return Matrix.Identity();
  892. }
  893. /** @hidden */
  894. public setCameraRigParameter(name: string, value: any) {
  895. if (!this._cameraRigParams) {
  896. this._cameraRigParams = {};
  897. }
  898. this._cameraRigParams[name] = value;
  899. //provisionnally:
  900. if (name === "interaxialDistance") {
  901. this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637);
  902. }
  903. }
  904. /**
  905. * needs to be overridden by children so sub has required properties to be copied
  906. * @hidden
  907. */
  908. public createRigCamera(name: string, cameraIndex: number): Nullable<Camera> {
  909. return null;
  910. }
  911. /**
  912. * May need to be overridden by children
  913. * @hidden
  914. */
  915. public _updateRigCameras() {
  916. for (var i = 0; i < this._rigCameras.length; i++) {
  917. this._rigCameras[i].minZ = this.minZ;
  918. this._rigCameras[i].maxZ = this.maxZ;
  919. this._rigCameras[i].fov = this.fov;
  920. this._rigCameras[i].upVector.copyFrom(this.upVector);
  921. }
  922. // only update viewport when ANAGLYPH
  923. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  924. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  925. }
  926. }
  927. /** @hidden */
  928. public _setupInputs() {
  929. }
  930. /**
  931. * Serialiaze the camera setup to a json represention
  932. * @returns the JSON representation
  933. */
  934. public serialize(): any {
  935. var serializationObject = SerializationHelper.Serialize(this);
  936. // Type
  937. serializationObject.type = this.getClassName();
  938. // Parent
  939. if (this.parent) {
  940. serializationObject.parentId = this.parent.id;
  941. }
  942. if (this.inputs) {
  943. this.inputs.serialize(serializationObject);
  944. }
  945. // Animations
  946. SerializationHelper.AppendSerializedAnimations(this, serializationObject);
  947. serializationObject.ranges = this.serializeAnimationRanges();
  948. return serializationObject;
  949. }
  950. /**
  951. * Clones the current camera.
  952. * @param name The cloned camera name
  953. * @returns the cloned camera
  954. */
  955. public clone(name: string): Camera {
  956. return SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  957. }
  958. /**
  959. * Gets the direction of the camera relative to a given local axis.
  960. * @param localAxis Defines the reference axis to provide a relative direction.
  961. * @return the direction
  962. */
  963. public getDirection(localAxis: Vector3): Vector3 {
  964. var result = Vector3.Zero();
  965. this.getDirectionToRef(localAxis, result);
  966. return result;
  967. }
  968. /**
  969. * Gets the direction of the camera relative to a given local axis into a passed vector.
  970. * @param localAxis Defines the reference axis to provide a relative direction.
  971. * @param result Defines the vector to store the result in
  972. */
  973. public getDirectionToRef(localAxis: Vector3, result: Vector3): void {
  974. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  975. }
  976. /**
  977. * Gets a camera constructor for a given camera type
  978. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  979. * @param name The name of the camera the result will be able to instantiate
  980. * @param scene The scene the result will construct the camera in
  981. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  982. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  983. * @returns a factory method to construc the camera
  984. */
  985. static GetConstructorFromName(type: string, name: string, scene: Scene, interaxial_distance: number = 0, isStereoscopicSideBySide: boolean = true): () => Camera {
  986. let constructorFunc = Node.Construct(type, name, scene, {
  987. interaxial_distance: interaxial_distance,
  988. isStereoscopicSideBySide: isStereoscopicSideBySide
  989. });
  990. if (constructorFunc) {
  991. return <() => Camera>constructorFunc;
  992. }
  993. // Default to universal camera
  994. return () => Camera._createDefaultParsedCamera(name, scene);
  995. }
  996. /**
  997. * Compute the world matrix of the camera.
  998. * @returns the camera workd matrix
  999. */
  1000. public computeWorldMatrix(): Matrix {
  1001. return this.getWorldMatrix();
  1002. }
  1003. /**
  1004. * Parse a JSON and creates the camera from the parsed information
  1005. * @param parsedCamera The JSON to parse
  1006. * @param scene The scene to instantiate the camera in
  1007. * @returns the newly constructed camera
  1008. */
  1009. public static Parse(parsedCamera: any, scene: Scene): Camera {
  1010. var type = parsedCamera.type;
  1011. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  1012. var camera = SerializationHelper.Parse(construct, parsedCamera, scene);
  1013. // Parent
  1014. if (parsedCamera.parentId) {
  1015. camera._waitingParentId = parsedCamera.parentId;
  1016. }
  1017. //If camera has an input manager, let it parse inputs settings
  1018. if (camera.inputs) {
  1019. camera.inputs.parse(parsedCamera);
  1020. camera._setupInputs();
  1021. }
  1022. if ((<any>camera).setPosition) { // need to force position
  1023. camera.position.copyFromFloats(0, 0, 0);
  1024. (<any>camera).setPosition(Vector3.FromArray(parsedCamera.position));
  1025. }
  1026. // Target
  1027. if (parsedCamera.target) {
  1028. if ((<any>camera).setTarget) {
  1029. (<any>camera).setTarget(Vector3.FromArray(parsedCamera.target));
  1030. }
  1031. }
  1032. // Apply 3d rig, when found
  1033. if (parsedCamera.cameraRigMode) {
  1034. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  1035. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  1036. }
  1037. // Animations
  1038. if (parsedCamera.animations) {
  1039. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  1040. var parsedAnimation = parsedCamera.animations[animationIndex];
  1041. camera.animations.push(Animation.Parse(parsedAnimation));
  1042. }
  1043. Node.ParseAnimationRanges(camera, parsedCamera, scene);
  1044. }
  1045. if (parsedCamera.autoAnimate) {
  1046. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  1047. }
  1048. return camera;
  1049. }
  1050. }