
Mirror Engine API / CameraComponent
Class: CameraComponent
The Camera Component enables an Entity to render the scene. A scene requires at least one enabled camera component to be rendered. Note that multiple camera components can be enabled simultaneously (for split-screen or offscreen rendering, for example).
// Add a CameraComponent to an entity
const entity = new Entity()
entity.addComponent('camera', {
nearClip: 1,
farClip: 100,
fov: 55
})
// Get the CameraComponent on an entity
const cameraComponent = entity.camera
// Update a property on a camera component
entity.camera.nearClip = 2
Extends
Component
Properties
entity
entity: Entity
The Entity that this Component is attached to.
Inherited from
Component.entity
system
system: ComponentSystem
The ComponentSystem used to create this Component.
Inherited from
Component.system
aperture
Get Signature
get aperture(): number
Gets the camera aperture in f-stops.
Returns
number
Set Signature
set aperture(value: number): void
Sets the camera aperture in f-stops. Default is 16. Higher value means less exposure.
Parameters
value
number
Returns
void
aspectRatio
Get Signature
get aspectRatio(): number
Gets the aspect ratio (width divided by height) of the camera.
Returns
number
Set Signature
set aspectRatio(value: number): void
Sets the aspect ratio (width divided by height) of the camera. If aspectRatioMode
is
ASPECT_AUTO, then this value will be automatically calculated every frame, and you
can only read it. If it's ASPECT_MANUAL, you can set the value.
Parameters
value
number
Returns
void
aspectRatioMode
Get Signature
get aspectRatioMode(): number
Gets the aspect ratio mode of the camera.
Returns
number
Set Signature
set aspectRatioMode(value: number): void
Sets the aspect ratio mode of the camera. Can be:
- ASPECT_AUTO: aspect ratio will be calculated from the current render target's width divided by height.
- ASPECT_MANUAL: use the aspectRatio value.
Defaults to ASPECT_AUTO.
Parameters
value
number
Returns
void
calculateProjection
Get Signature
get calculateProjection(): CalculateMatrixCallback
Gets the custom function to calculate the camera projection matrix manually.
Returns
CalculateMatrixCallback
Set Signature
set calculateProjection(value: CalculateMatrixCallback): void
Sets the custom function to calculate the camera projection matrix manually. Can be used for complex effects like doing oblique projection. Function is called using component's scope.
Arguments:
- Mat4 transformMatrix: output of the function
- view: Type of view. Can be VIEW_CENTER, VIEW_LEFT or VIEW_RIGHT.
Left and right are only used in stereo rendering.
Parameters
value
CalculateMatrixCallback
Returns
void
calculateTransform
Get Signature
get calculateTransform(): CalculateMatrixCallback
Gets the custom function to calculate the camera transformation matrix manually.
Returns
CalculateMatrixCallback
Set Signature
set calculateTransform(value: CalculateMatrixCallback): void
Sets the custom function to calculate the camera transformation matrix manually. Can be used for complex effects like reflections. Function is called using component's scope. Arguments:
- Mat4 transformMatrix: output of the function.
- view: Type of view. Can be VIEW_CENTER, VIEW_LEFT or VIEW_RIGHT.
Left and right are only used in stereo rendering.
Parameters
value
CalculateMatrixCallback
Returns
void
clearColor
Get Signature
get clearColor(): Color
Gets the camera component's clear color.
Returns
Set Signature
set clearColor(value: Color): void
Sets the camera component's clear color. Defaults to [0.75, 0.75, 0.75, 1]
.
Parameters
value
Returns
void
clearColorBuffer
Get Signature
get clearColorBuffer(): boolean
Gets whether the camera will automatically clear the color buffer before rendering.
Returns
boolean
Set Signature
set clearColorBuffer(value: boolean): void
Sets whether the camera will automatically clear the color buffer before rendering. Defaults to true.
Parameters
value
boolean
Returns
void
clearDepthBuffer
Get Signature
get clearDepthBuffer(): boolean
Gets whether the camera will automatically clear the depth buffer before rendering.
Returns
boolean
Set Signature
set clearDepthBuffer(value: boolean): void
Sets whether the camera will automatically clear the depth buffer before rendering. Defaults to true.
Parameters
value
boolean
Returns
void
clearStencilBuffer
Get Signature
get clearStencilBuffer(): boolean
Gets whether the camera will automatically clear the stencil buffer before rendering.
Returns
boolean
Set Signature
set clearStencilBuffer(value: boolean): void
Sets whether the camera will automatically clear the stencil buffer before rendering. Defaults to true.
Parameters
value
boolean
Returns
void
cullFaces
Get Signature
get cullFaces(): boolean
Gets whether the camera will cull triangle faces.
Returns
boolean
Set Signature
set cullFaces(value: boolean): void
Sets whether the camera will cull triangle faces. If true, the camera will take
material.cull
into account. Otherwise both front and back faces will be rendered. Defaults
to true.
Parameters
value
boolean
Returns
void
disablePostEffectsLayer
Get Signature
get disablePostEffectsLayer(): number
Gets the layer id of the layer on which the post-processing of the camera stops being applied to.
Returns
number
Set Signature
set disablePostEffectsLayer(layer: number): void
Sets the layer id of the layer on which the post-processing of the camera stops being applied
to. Defaults to LAYERID_UI, which causes post-processing to not be applied to UI
layer and any following layers for the camera. Set to undefined
for post-processing to be
applied to all layers of the camera.
Parameters
layer
number
Returns
void
enabled
Get Signature
get enabled(): boolean
Gets the enabled state of the component.
Returns
boolean
Set Signature
set enabled(arg: boolean): void
Sets the enabled state of the component.
Parameters
arg
boolean
Returns
void
Inherited from
Component.enabled
farClip
Get Signature
get farClip(): number
Gets the distance from the camera after which no rendering will take place.
Returns
number
Set Signature
set farClip(value: number): void
Sets the distance from the camera after which no rendering will take place. Defaults to 1000.
Parameters
value
number
Returns
void
flipFaces
Get Signature
get flipFaces(): boolean
Gets whether the camera will flip the face direction of triangles.
Returns
boolean
Set Signature
set flipFaces(value: boolean): void
Sets whether the camera will flip the face direction of triangles. If set to true, the camera will invert front and back faces. Can be useful for reflection rendering. Defaults to false.
Parameters
value
boolean
Returns
void
fog
Get Signature
get fog(): null | FogParams
Gets a FogParams that defines fog parameters, or null if those are not set.
Returns
null
| FogParams
Set Signature
set fog(value: null | FogParams): void
Sets the fog parameters. If this is not null, the camera will use these fog parameters instead of those specified on the Scene#fog.
Parameters
value
null
| FogParams
Returns
void
fov
Get Signature
get fov(): number
Gets the field of view of the camera in degrees.
Returns
number
Set Signature
set fov(value: number): void
Sets the field of view of the camera in degrees. Usually this is the Y-axis field of view, see CameraComponent#horizontalFov. Used for PROJECTION_PERSPECTIVE cameras only. Defaults to 45.
Parameters
value
number
Returns
void
frustum
Get Signature
get frustum(): Frustum
Gets the camera's frustum shape.
Returns
frustumCulling
Get Signature
get frustumCulling(): boolean
Gets whether frustum culling is enabled.
Returns
boolean
Set Signature
set frustumCulling(value: boolean): void
Sets whether frustum culling is enabled. This controls the culling of mesh instances against the camera frustum, i.e. if objects outside of the camera's frustum should be omitted from rendering. If false, all mesh instances in the scene are rendered by the camera, regardless of visibility. Defaults to false.
Parameters
value
boolean
Returns
void
gammaCorrection
Get Signature
get gammaCorrection(): number
Gets the gamma correction used when rendering the scene.
Returns
number
Set Signature
set gammaCorrection(value: number): void
Sets the gamma correction to apply when rendering the scene. Can be:
Defaults to GAMMA_SRGB.
Parameters
value
number
Returns
void
horizontalFov
Get Signature
get horizontalFov(): boolean
Gets whether the camera's field of view (fov
) is horizontal or vertical.
Returns
boolean
Set Signature
set horizontalFov(value: boolean): void
Sets whether the camera's field of view (fov
) is horizontal or vertical. Defaults to
false (meaning it is vertical by default).
Parameters
value
boolean
Returns
void
jitter
Get Signature
get jitter(): number
Gets the jitter intensity applied in the projection matrix.
Returns
number
Set Signature
set jitter(value: number): void
Sets the jitter intensity applied in the projection matrix. Used for jittered sampling by TAA.
A value of 1 represents a jitter in the range of [-1, 1]
of a pixel. Smaller values result
in a crisper yet more aliased outcome, whereas increased values produce a smoother but blurred
result. Defaults to 0, representing no jitter.
Parameters
value
number
Returns
void
layers
Get Signature
get layers(): number[]
Gets the array of layer IDs (Layer#id) to which this camera belongs.
Returns
number
[]
Set Signature
set layers(newValue: number[]): void
Sets the array of layer IDs (Layer#id) to which this camera should belong. Don't
push, pop, splice or modify this array, if you want to change it, set a new one instead.
Defaults to [LAYERID_WORLD, LAYERID_DEPTH, LAYERID_SKYBOX, LAYERID_UI, LAYERID_IMMEDIATE]
.
Parameters
newValue
number
[]
Returns
void
nearClip
Get Signature
get nearClip(): number
Gets the distance from the camera before which no rendering will take place.
Returns
number
Set Signature
set nearClip(value: number): void
Sets the distance from the camera before which no rendering will take place. Defaults to 0.1.
Parameters
value
number
Returns
void
orthoHeight
Get Signature
get orthoHeight(): number
Gets the half-height of the orthographic view window (in the Y-axis).
Returns
number
Set Signature
set orthoHeight(value: number): void
Sets the half-height of the orthographic view window (in the Y-axis). Used for PROJECTION_ORTHOGRAPHIC cameras only. Defaults to 10.
Parameters
value
number
Returns
void
postEffects
Get Signature
get postEffects(): PostEffectQueue
Gets the post effects queue for this camera. Use this to add or remove post effects from the camera.
Returns
priority
Get Signature
get priority(): number
Gets the priority to control the render order of this camera.
Returns
number
Set Signature
set priority(newValue: number): void
Sets the priority to control the render order of this camera. Cameras with a smaller priority value are rendered first. Defaults to 0.
Parameters
newValue
number
Returns
void
projection
Get Signature
get projection(): number
Gets the type of projection used to render the camera.
Returns
number
Set Signature
set projection(value: number): void
Sets the type of projection used to render the camera. Can be:
- PROJECTION_PERSPECTIVE: A perspective projection. The camera frustum resembles a truncated pyramid.
- PROJECTION_ORTHOGRAPHIC: An orthographic projection. The camera frustum is a cuboid.
Defaults to PROJECTION_PERSPECTIVE.
Parameters
value
number
Returns
void
projectionMatrix
Get Signature
get projectionMatrix(): Mat4
Gets the camera's projection matrix.
Returns
rect
Get Signature
get rect(): Vec4
Gets the rendering rectangle for the camera.
Returns
Set Signature
set rect(value: Vec4): void
Sets the rendering rectangle for the camera. This controls where on the screen the camera
will render in normalized screen coordinates. Defaults to [0, 0, 1, 1]
.
Parameters
value
Returns
void
renderTarget
Get Signature
get renderTarget(): RenderTarget
Gets the render target to which rendering of the camera is performed.
Returns
RenderTarget
Set Signature
set renderTarget(value: RenderTarget): void
Sets the render target to which rendering of the camera is performed. If not set, it will render simply to the screen.
Parameters
value
RenderTarget
Returns
void
scissorRect
Get Signature
get scissorRect(): Vec4
Gets the scissor rectangle for the camera.
Returns
Set Signature
set scissorRect(value: Vec4): void
Sets the scissor rectangle for the camera. This clips all pixels which are not in the
rectangle. The order of the values is [x, y, width, height]
. Defaults to [0, 0, 1, 1]
.
Parameters
value
Returns
void
sensitivity
Get Signature
get sensitivity(): number
Gets the camera sensitivity in ISO.
Returns
number
Set Signature
set sensitivity(value: number): void
Sets the camera sensitivity in ISO. Defaults to 1000. Higher value means more exposure.
Parameters
value
number
Returns
void
shutter
Get Signature
get shutter(): number
Gets the camera shutter speed in seconds.
Returns
number
Set Signature
set shutter(value: number): void
Sets the camera shutter speed in seconds. Defaults to 1/1000s. Longer shutter means more exposure.
Parameters
value
number
Returns
void
toneMapping
Get Signature
get toneMapping(): number
Gets the tonemapping transform applied to the rendered color buffer.
Returns
number
Set Signature
set toneMapping(value: number): void
Sets the tonemapping transform to apply to the rendered color buffer. Can be:
Defaults to TONEMAP_LINEAR.
Parameters
value
number
Returns
void
viewMatrix
Get Signature
get viewMatrix(): Mat4
Gets the camera's view matrix.
Returns
Methods
calculateAspectRatio()
calculateAspectRatio(rt?: null | RenderTarget): number
Calculates aspect ratio value for a given render target.
Parameters
rt?
Optional render target. If unspecified, the backbuffer is used.
null
| RenderTarget
Returns
number
The aspect ratio of the render target (or backbuffer).
endXr()
endXr(callback?: XrErrorCallback): void
Attempt to end XR session of this camera.
Parameters
callback?
XrErrorCallback
Optional callback function called once session is ended. The callback has one argument Error - it is null if successfully ended XR session.
Returns
void
Example
// On an entity with a camera component
this.entity.camera.endXr(function (err) {
// not anymore in XR
})
fire()
fire(
name: string,
arg1?: any,
arg2?: any,
arg3?: any,
arg4?: any,
arg5?: any,
arg6?: any,
arg7?: any,
arg8?: any): EventHandler
Fire an event, all additional arguments are passed on to the event listener.
Parameters
name
string
Name of event to fire.
arg1?
any
First argument that is passed to the event handler.
arg2?
any
Second argument that is passed to the event handler.
arg3?
any
Third argument that is passed to the event handler.
arg4?
any
Fourth argument that is passed to the event handler.
arg5?
any
Fifth argument that is passed to the event handler.
arg6?
any
Sixth argument that is passed to the event handler.
arg7?
any
Seventh argument that is passed to the event handler.
arg8?
any
Eighth argument that is passed to the event handler.
Returns
Self for chaining.
Example
obj.fire('test', 'This is the message')
Inherited from
Component.fire
getShaderPass()
getShaderPass(): undefined | string
Shader pass name.
Returns
undefined
| string
The name of the shader pass, or undefined if no shader pass is set.
hasEvent()
hasEvent(name: string): boolean
Test if there are any handlers bound to an event name.
Parameters
name
string
The name of the event to test.
Returns
boolean
True if the object has handlers bound to the specified event name.
Example
obj.on('test', () => {}) // bind an event to 'test'
obj.hasEvent('test') // returns true
obj.hasEvent('hello') // returns false
Inherited from
Component.hasEvent
off()
off(
name?: string,
callback?: HandleEventCallback,
scope?: any): EventHandler
Detach an event handler from an event. If callback is not provided then all callbacks are unbound from the event, if scope is not provided then all events with the callback will be unbound.
Parameters
name?
string
Name of the event to unbind.
callback?
HandleEventCallback
Function to be unbound.
scope?
any
Scope that was used as the this when the event is fired.
Returns
Self for chaining.
Example
const handler = () => {}
obj.on('test', handler)
obj.off() // Removes all events
obj.off('test') // Removes all events called 'test'
obj.off('test', handler) // Removes all handler functions, called 'test'
obj.off('test', handler, this) // Removes all handler functions, called 'test' with scope this
Inherited from
Component.off
on()
on(
name: string,
callback: HandleEventCallback,
scope?: any): EventHandle
Attach an event handler to an event.
Parameters
name
string
Name of the event to bind the callback to.
callback
HandleEventCallback
Function that is called when event is fired. Note the callback is limited to 8 arguments.
scope?
any
= ...
Object to use as 'this' when the event is fired, defaults to current this.
Returns
Can be used for removing event in the future.
Examples
obj.on('test', (a, b) => {
console.log(a + b)
})
obj.fire('test', 1, 2) // prints 3 to the console
const evt = obj.on('test', (a, b) => {
console.log(a + b)
})
// some time later
evt.off()
Inherited from
Component.on
once()
once(
name: string,
callback: HandleEventCallback,
scope?: any): EventHandle
Attach an event handler to an event. This handler will be removed after being fired once.
Parameters
name
string
Name of the event to bind the callback to.
callback
HandleEventCallback
Function that is called when event is fired. Note the callback is limited to 8 arguments.
scope?
any
= ...
Object to use as 'this' when the event is fired, defaults to current this.
Returns
- can be used for removing event in the future.
Example
obj.once('test', (a, b) => {
console.log(a + b)
})
obj.fire('test', 1, 2) // prints 3 to the console
obj.fire('test', 1, 2) // not going to get handled
Inherited from
Component.once
requestSceneColorMap()
requestSceneColorMap(enabled: boolean): void
Request the scene to generate a texture containing the scene color map. Note that this call is accumulative, and for each enable request, a disable request need to be called. Note that this setting is ignored when the CameraComponent#renderPasses is used.
Parameters
enabled
boolean
True to request the generation, false to disable it.
Returns
void
requestSceneDepthMap()
requestSceneDepthMap(enabled: boolean): void
Request the scene to generate a texture containing the scene depth map. Note that this call is accumulative, and for each enable request, a disable request need to be called. Note that this setting is ignored when the CameraComponent#renderPasses is used.
Parameters
enabled
boolean
True to request the generation, false to disable it.
Returns
void
screenToWorld()
screenToWorld(
screenx: number,
screeny: number,
cameraz: number,
worldCoord?: Vec3): Vec3
Convert a point from 2D screen space to 3D world space.
Parameters
screenx
number
X coordinate on Mirror Engine' canvas element. Should be in the range
0 to canvas.offsetWidth
of the application's canvas element.
screeny
number
Y coordinate on Mirror Engine' canvas element. Should be in the range
0 to canvas.offsetHeight
of the application's canvas element.
cameraz
number
The distance from the camera in world space to create the new point.
worldCoord?
3D vector to receive world coordinate result.
Returns
The world space coordinate.
Example
// Get the start and end points of a 3D ray fired from a screen click position
const start = entity.camera.screenToWorld(
clickX,
clickY,
entity.camera.nearClip
)
const end = entity.camera.screenToWorld(clickX, clickY, entity.camera.farClip)
// Use the ray coordinates to perform a raycast
app.systems.rigidbody.raycastFirst(start, end, function (result) {
console.log('Entity ' + result.entity.name + ' was selected')
})
setShaderPass()
setShaderPass(name: string): number
Sets the name of the shader pass the camera will use when rendering.
In addition to existing names (see the parameter description), a new name can be specified, which creates a new shader pass with the given name. The name provided can only use alphanumeric characters and underscores. When a shader is compiled for the new pass, a define is added to the shader. For example, if the name is 'custom_rendering', the define 'CUSTOM_RENDERING_PASS' is added to the shader, allowing the shader code to conditionally execute code only when that shader pass is active.
Another instance where this approach may prove useful is when a camera needs to render a more cost-effective version of shaders, such as when creating a reflection texture. To accomplish this, a callback on the material that triggers during shader compilation can be used. This callback can modify the shader generation options specifically for this shader pass.
const shaderPassId = camera.setShaderPass('custom_rendering')
material.onUpdateShader = function (options) {
if (options.pass === shaderPassId) {
options.litOptions.normalMapEnabled = false
options.litOptions.useSpecular = false
}
return options
}
Parameters
name
string
The name of the shader pass. Defaults to undefined, which is equivalent to SHADERPASS_FORWARD. Can be:
- SHADERPASS_FORWARD
- SHADERPASS_ALBEDO
- SHADERPASS_OPACITY
- SHADERPASS_WORLDNORMAL
- SHADERPASS_SPECULARITY
- SHADERPASS_GLOSS
- SHADERPASS_METALNESS
- SHADERPASS_AO
- SHADERPASS_EMISSION
- SHADERPASS_LIGHTING
- SHADERPASS_UV0
Returns
number
The id of the shader pass.
startXr()
startXr(
type: string,
spaceType: string,
options?: {
anchors: boolean;
callback: XrErrorCallback;
depthSensing: {
dataFormatPreference: string;
usagePreference: string;
};
imageTracking: boolean;
optionalFeatures: string[];
planeDetection: boolean;
}): void
Attempt to start XR session with this camera.
Parameters
type
string
The type of session. Can be one of the following:
- XRTYPE_INLINE: Inline - always available type of session. It has limited feature availability and is rendered into HTML element.
- XRTYPE_VR: Immersive VR - session that provides exclusive access to the VR device with the best available tracking features.
- XRTYPE_AR: Immersive AR - session that provides exclusive access to the VR/AR device that is intended to be blended with the real-world environment.
spaceType
string
Reference space type. Can be one of the following:
- XRSPACE_VIEWER: Viewer - always supported space with some basic tracking capabilities.
- XRSPACE_LOCAL: Local - represents a tracking space with a native origin near the viewer at the time of creation. It is meant for seated or basic local XR sessions.
- XRSPACE_LOCALFLOOR: Local Floor - represents a tracking space with a native origin at the floor in a safe position for the user to stand. The y-axis equals 0 at floor level. Floor level value might be estimated by the underlying platform. It is meant for seated or basic local XR sessions.
- XRSPACE_BOUNDEDFLOOR: Bounded Floor - represents a tracking space with its native origin at the floor, where the user is expected to move within a pre-established boundary.
- XRSPACE_UNBOUNDED: Unbounded - represents a tracking space where the user is expected to move freely around their environment, potentially long distances from their starting point.
options?
Object with options for XR session initialization.
anchors?
boolean
Optional boolean to attempt to enable XrAnchors.
callback?
XrErrorCallback
Optional callback function called once the session is started. The callback has one argument Error - it is null if the XR session started successfully.
depthSensing?
{
dataFormatPreference
: string
;
usagePreference
: string
;
}
Optional object with parameters to attempt to enable depth sensing.
depthSensing.dataFormatPreference?
string
Optional data format preference for depth sensing. Can be 'luminance-alpha' or 'float32' (XRDEPTHSENSINGFORMAT_*), defaults to 'luminance-alpha'. Most preferred and supported will be chosen by the underlying depth sensing system.
depthSensing.usagePreference?
string
Optional usage preference for depth sensing, can be 'cpu-optimized' or 'gpu-optimized' (XRDEPTHSENSINGUSAGE_*), defaults to 'cpu-optimized'. Most preferred and supported will be chosen by the underlying depth sensing system.
imageTracking?
boolean
Set to true to attempt to enable XrImageTracking.
optionalFeatures?
string
[]
Optional features for XRSession start. It is used for getting access to additional WebXR spec extensions.
planeDetection?
boolean
Set to true to attempt to enable XrPlaneDetection.
Returns
void
Example
// On an entity with a camera component
this.entity.camera.startXr(XRTYPE_VR, XRSPACE_LOCAL, {
callback: function (err) {
if (err) {
// failed to start XR session
} else {
// in XR
}
}
})
worldToScreen()
worldToScreen(worldCoord: Vec3, screenCoord?: Vec3): Vec3
Convert a point from 3D world space to 2D screen space.
Parameters
worldCoord
The world space coordinate.
screenCoord?
3D vector to receive screen coordinate result.
Returns
The screen space coordinate.