A scene holds the objects in a 2D or 3D world. Each object is an entity; add components such as a mesh, camera, light, or physics body to give it an appearance or behavior.
Codea draws and updates the scene for you, including its physics simulation.
function setup()
scn = scene()
-- Camera entity
local cam = scn:entity("camera")
cam:add(camera.perspective(60))
cam:add(camera.rigs.orbit)
cam.z = -10
-- A sphere
local sphere = scn:entity("sphere")
sphere:add(mesh.sphere(1))
-- Make this the active scene
scene.main = scn
endCreate a scene with scene() and assign it to scene.main to draw and update it each frame.
scn = scene()
scene.main = scnYou can have multiple scenes and switch between them by reassigning scene.main.
Entities are the basic building blocks of a scene. They have a transform (position, rotation, scale) and can hold any number of components.
Create entities with scene:entity():
-- Named entity (accessible by name later)
local ball = scn:entity("ball")
-- Access by name
print(scn.ball)Child entities are created under an existing entity and inherit its transform:
local arm = scn:entity("arm")
local hand = arm:child("hand")
hand.z = 2 -- 2 units ahead of the arm's local originComponents add behaviour to entities. Attach them with entity.add():
local sphere = scn:entity("sphere")
-- Add a mesh
sphere:add(mesh.sphere(1))
-- Add a lit material
sphere.material = material.lit()
-- Add a 3D physics body
sphere:add(physics3d.body(physics3d.DYNAMIC))
sphere:add(physics3d.sphere(1))Custom Lua classes are also valid components:
Rotator = class("Rotator")
function Rotator:update(dt)
self.entity.ry = self.entity.ry + dt * 90
end
local cube = scn:entity()
cube:add(mesh.box())
cube:add(Rotator)An entity or script component can implement draw() to draw sprites, text, and shapes in the entity’s local coordinates. Each callback starts with the entity’s world transform and inherits the current drawing style. Codea restores the style and model, view, and projection matrices afterward, including after an error or unmatched stack operations. There is no implicit style reset. Use explicit pushes and pops when you need separate styles or transforms within a callback.
Sprites and text normally draw over scene geometry. Enable style.depth() to let opaque objects hide them:
function ball:draw()
style.depth(true).textRenderer(style.atlas)
fill(255)
fontSize(1)
shapeMode(CENTER)
textAlign(CENTER | MIDDLE)
matrix.translate(0, 1.5, 0)
text(self.name)
endThe atlas text renderer keeps small world-space text sharp. Depth-tested sprites and text do not write depth, and retain their drawing order after scene geometry. This requires a depth buffer and a scene using drawOrder.distance; ordered 2D scenes do not depth-test.
Every scene needs at least one camera entity with a camera component attached:
local cam = scn:entity("camera")
cam:add(camera.perspective(60)) -- 60° field of view
cam.z = -5 -- Pull back 5 unitsUse camera.rigs.orbit to add an interactive orbit controller that works with mouse and touch:
cam:add(camera.rigs.orbit)Give an entity an update() function to move it each frame, or a touched() function to respond to touches. You can also define these functions in a Lua component:
local ent = scn:entity()
function ent:update(dt)
self.ry = self.ry + dt * 45
end
function ent:touched(touch)
if touch.began then
self:destroy()
end
return true -- capture the touch
end
Camera effects change the finished picture of a scene. Add bloom to make bright areas glow, adjust the colors, darken the edges with a vignette, or blur part of the picture with tilt shift.
Attach a camera to a scene entity and set its effect properties. Effects run when the camera draws the scene. camera:apply() sets the drawing matrices only; it does not apply effects to shapes or meshes you draw yourself.
function setup()
local world = scene()
local eye = world:entity("Camera")
eye.z = -8
local cam = eye:add(camera.perspective(60))
cam.bloom.strength = 0.6
cam.bloom.threshold = 0.9
cam.saturation = 1.1
cam.vignette = 0.2
cam.grain = 0.02
local ball = world:entity("Ball")
ball:add(mesh.sphere(1))
scene.main = world
endcam.tiltShift.blur = 6 adds up to six points of blur outside the sharp band. The defaults keep the middle of the image sharp. Adjust focus, range and falloff together to place the band and soften its edges.
Add your own shader with cam:addEffect(source). Custom effects run in the order you add them, after the built-in effects. Each receives the picture so far as source; declare a scene sampler to also read the original picture. Use the returned shader to change its uniforms. See Camera for details.
With camera.none or camera.depth as the clear mode, the finished picture is drawn over what is already on screen. Keep alpha in custom shaders so transparent areas stay transparent. A camera that clears color first clears its whole image. Effects follow the camera’s viewport and resize with it.
Bloom uses smaller images, while tilt shift and custom shaders work on full-size images and can cost more to draw. Set bloom strength or tilt-shift blur to zero to skip that effect. Set cam.effectsEnabled = false to turn off all effects. cam:clearEffects() removes custom effects without resetting the built-in settings.
scene
Holds the entities in a 2D or 3D world and handles their drawing, input, and physics. Set scene.main to draw and update a scene automatically.
scene.main
Sets the main Codea scene, which will be automatically drawn, updated and handle touch events
function setup()
scene.main = scene.default3d()
end
scene.default3d(name)
Creates the default 3D scene containing a perspective camera, directional light and HDR environment, with an optional name
| name | string, optional. Name assigned to the scene or entity, or the entity name to search for. |
scene |
scene.default2d(name)
Creates the default 2D scene containing an orthographic camera, with an optional name
| name | string, optional. Name assigned to the scene or entity, or the entity name to search for. |
scene |
scene.read(key)
Loads and returns a scene with the supplied asset key
| key | asset.key. Asset key identifying the scene file. |
scene |
scene.save(key, scene)
Saves the supplied scene at the given asset key location
| key | asset.key. Asset key identifying the scene file. |
| scene | scene. Scene to save. |
scene.name
Gets or sets a name for this scene
scene.world2d
Gets the scene’s 2D physics world, providing access to various physics functions and properties such as physics2d.world.applyForce()
scene.world3d
Gets the scene’s 3D physics world, providing access to various physics functions and properties such as physics3d.world.applyForce()
scene.sky
Sets the sky visuals, which will depend on the type used:
asset.key - Use an image pointed to by a given asset keyimage - Use an image directly (assumed to be a cube image)color - Use a solid colorscene.skyBlur
The blur strength of the skybox
scene.skyExposure
The brightness of the skybox
scene.camera
scene.sun
scene.canvas
scene.pixelsPerUnit
The amount of pixels that are in a grid unit
scene.drawOrder
How the scene orders its draws, which can be one of the following values:
drawOrder.distance - draw opaque objects first, then transparent objects sorted back to front by distance from the camera (default)drawOrder.ordered - draw objects in the order they are submitted, without sorting by distancescene:entity(name)
Creates a new blank entity with an optional name
| name | string, optional. Name assigned to the scene or entity, or the entity name to search for. |
entity |
scene:findEntity(name)
| name | string. Name assigned to the scene or entity, or the entity name to search for. |
entity |
scene:entities(activeOnly)
Returns a table containing all root entities
| activeOnly | boolean, optional, default true. When set, returns only active root entities |
table |
scene:index(name) [metamethod]()
Returns the root entity with the given name (if it exists)
entity |
scene:draw()
Immediately draws the scene to the current context. When autoUpdate is enabled, update(dt) will be called as well
If set as scene.main this will be called automatically right before the global draw() function
scene:update(deltaTime)
Updates the scene, called automatically when draw() is called but can also be called manutally if needed
| deltaTime | number. Elapsed simulation time in seconds. |
entity
A scene entity, created using scene.entity() that exists as part of the scene hierarchy. Entity behaviour and visuals are customised by addings various types of components or assets, such as sprite.slice, camera and mesh
There are shortcut properties to attach some common components, while others are built-in (such as transforms, names and relationships)
entity.active
The active state of this entity, when inactive an entity will not be rendered, simulate physics or respond to automatic callbacks
function setup()
scene.main = scene.default3d()
red = material.lit()
red.color = color.red
red.roughness = 1
green = material.lit()
green.color = color.green
green.roughness = 1
blue = material.lit()
blue.color = color.blue
blue.roughness = 1
-- Create some sphere that orbit each other with parenting
e1 = scene.main:entity()
e1.mesh = mesh.sphere(1.0)
e1.mesh.material = red
e1.update = function(entity, dt)
entity.rotation = quat.eulerAngles(0, 0, time.elapsed * 90)
end
e2 = e1:child()
e2.y = -2.5
e2.mesh = mesh.sphere(0.5)
e2.mesh.material = green
e2.update = e1.update
e3 = e2:child()
e3.y = -1
e3.mesh = mesh.sphere(0.25)
e3.mesh.material = blue
-- Test switching entity active states on and off for bits of the hierarchy
parameter.boolean("E1_Active", true, function(b)
e1.active = b
end)
parameter.watch("e1.activeInHierarchy")
parameter.boolean("E2_Active", true, function(b)
e2.active = b
end)
parameter.watch("e2.activeInHierarchy")
parameter.boolean("E3_Active", true, function(b)
e3.active = b
end)
parameter.watch("e3.activeInHierarchy")
end
entity.activeInHierarchy
The computed active in hierarchy state of this entity. Only true when all parents up to the root are active as well
entity.valid
Checks the validity of this entity. When an entity is destroyed it is invalid and can no longer be used. non-valid entities will raise errors when calling functions or accessing properties
entity.id
A read-only identifier unique to the entity
entity.name
The name of the entity, useful when referring to the entity later using the scene and entity indexers
scene.main = scene()
scene.main:entity("ball") -- create a new entity named 'ball'
print(scene.main.ball) -- retrieve the entity named 'ball'
entity:destroy(delay)
Marks this entity for destruction in the next scene.update(), or after a delay (in seconds), further access to this entity after destruction will result in errors
| delay | number, optional. Delay before destruction, in seconds; omit to destroy on the next scene update. |
function setup()
scene.main = scene.default3d()
e = scene.main:entity()
e.rotation = quat.eulerAngles(45, 45, 45)
e.mesh = mesh.box(1,1,1)
e.mesh.material = material.lit()
-- Destroy after 1 second when touched
e.touched = function(entity, touch)
if touch.began then entity:destroy(1) end
end
-- Play hurt sound when destroyed
e.destroyed = function()
sound.play(SOUND_HURT)
end
end
entity:add(component, ...)
Adds a component to this entity, there are several types of objects that can act as entities
camera.rigs.orbitcamera.rigs.canvasphysics3d.grabbervoxel.worldmeshimage / image.sliceNote on Lua classes/components
| component | table or userdata. Component class or supported asset type; add() also accepts assets such as a mesh or image. |
| ... | any. Additional arguments forwarded to the component constructor or dispatched method. |
scene.main = scene()
local sphere = scene.main:entity()
sphere:add(mesh.sphere(1)) -- Add a sphere mesh to the entity
-- Add an orbit rig to the camera (supersedes OrbitViewer from Craft)
scene.camera:add(camera.rigs.orbit)
-- Hypothetical day-night cycle Lua component for making the same orbit the planet
scene.sun:add(DayNightCycle, 60)
entity:remove(component)
Removes a given component type from this entity
| component | table or userdata. Component class or supported asset type; add() also accepts assets such as a mesh or image. |
scene.main = scene()
local sphere = scene.main:entity()
sphere:add(mesh.sphere(1)) -- add a sphere mesh to the entity
sphere:remove(mesh) -- remove the sphere mesh
entity:has(component)
Checks if a component type is attached to this entity
| component | table or userdata. Component class or supported asset type; add() also accepts assets such as a mesh or image. |
scene.main = scene()
local sphere = scene.main:entity()
sphere:add(mesh.sphere(1)) -- add a sphere mesh to the entity
print(sphere:has(mesh)) -- prints 'true'
entity:get(component)
Retrieves a component type attached to this entity
| component | table or userdata. Component class or supported asset type; add() also accepts assets such as a mesh or image. |
scene.main = scene()
local sphere = scene.main:entity()
sphere:add(mesh.sphere(1)) -- add a sphere mesh to the entity
print(sphere:get(mesh)) -- prints the mesh description
entity.components
Retrieves a list of all components attached to this entity
entity:dispatch(name, ...)
Calls the method name on this entity (including any custom methods) and any attached custom lua components. Additional arguments will be passed to the method as well
| name | string. The name of the method to call |
| ... | any. Additional arguments forwarded to the component constructor or dispatched method. |
entity.parent
The parent of this entity or nil if it is a root entity
entity.root
The root parent entity in the scene heirarchy (or self if this entity has no parent)
entity.children
A list of all immediate children of this entity
entity.childCount
The number of children that this entity possesses
entity.depth
The depth of this entity in the hierarchy (roots have a depth of 0)
entity:index(name) [metamethod]()
Retrieves children with the supplied name using the property syntax (i.e. myEntity.theChildName)
Note that this will not work if the child name is an existing property or method name in the entity class
entity:child(name)
Creates a new child entity of this entity
| name | string. Name of the child entity or component method to find or invoke. |
entity:findChild(name)
| name | string. Name of the child entity or component method to find or invoke. |
| value | Finds the child named name or nil if it does not exist |
entity:childAt(index)
| index | integer. Child index, starting at 1. |
| value | The child entity at a given index (between 1..childCount) or nil if an invalid index is supplied |
entity:moveBefore(entity)
Rearranges this entity to appear before the supplied entity in the transform hierarchy
Note this may result in an entity’s parent changing to make it the sibling or another entity
| entity | entity. Sibling to place this entity before or after. |
entity:moveAfter(entity)
Rearranges this entity to appear after the supplied entity in the transform hierarchy
Note this may result in an entity’s parent changing to make it the sibling or another entity
| entity | entity. Sibling to place this entity before or after. |
entity.position
The position of the entity in local 3D space
entity.worldPosition
The position of the entity in global 3D space
entity.scale
The scale of the entity in local 3D space
entity.uniformScale
The uniform scale of the entity in local 3D space
entity.rotation
The rotation of the entity in local 3D space
entity.worldRotation
The rotation of the entity in world 3D space
entity.eulerRotation
The euler rotation of the entity in local 3D space (in degrees)
entity.x
The x position of the entity in local 3D space
entity.y
The y position of the entity in local 3D space
entity.z
The z position of the entity in local 3D space
entity.sx
The x scale of the entity in local 3D space
entity.sy
The y scale of the entity in local 3D space
entity.sz
The z scale of the entity in local 3D space
entity.rx
The euler rotation around the local x axis of the entity in degrees
entity.ry
The euler rotation around the local y axis of the entity in degrees
entity.rz
The euler rotation around the local z axis of the entity in degrees
entity.forward
The positive z axis of this entity’s coordinate space transformed into world space
entity.right
The positive x axis of this entity’s coordinate space transformed into world space
entity.up
The positive y axis of this entity’s coordinate space transformed into world space
entity:transformPoint(localPoint)
Transform a point from local to world space
| localPoint | vec3. The point to transform |
entity:inverseTransformPoint(worldPoint)
Transform a point from world to local space
| worldPoint | vec3. The point to transform |
entity:transformDirection(localDir)
Transform a vector from local to world space
| localDir | vec3. The vector to transform |
entity:inverseTransformDirection(worldDir)
Transform a vector from world to local space
| worldDir | vec3. The vector to transform |
entity:translate(x, y, z)
Moves the entity by the provided translation vector in local space
Also supports vec2 and vec3 parameters
| x | number. Translation along the x axis. |
| y | number. Translation along the y axis. |
| z | number, optional. Translation along the z axis. |
entity.sprite
The sprite (image.slice) attached to this entity. This will be drawn at the entities’ transform within the scene
entity.color
The tint color to use
entity.visible
Sets/gets whether the entity should be drawn or not
entity.flipX
Flips the sprite on the x-axis
entity.flipY
Flips the sprite on the y-axis
entity.mesh
The mesh attached to this entity. This will be drawn the entities’ transform within the scene
entity.material
The material attached to this entity (used in conjunction with meshes/sprites)
entity.size
The size of the UI element
entity.anchorX
The horizontal anchoring of this UI element within its parent coordinate system
Values:
LEFTCENTERRIGHTSTRETCHentity.anchorY
The vertical anchoring of this UI element within its parent coordinate system
Values:
TOPMIDDLEBOTTOMSTRETCHentity.pivot
The pivot point, representing the center of the UI element (in normalized coordinates)
entity.clip
When enabled, clips drawing to within the bounds of the UI element
entity.body2d
The attached 2D physics body (if there is one)
entity.collider2d
The first attached 2D physics collider (if there is one)
entity.colliders2d
All attached 2D physics colliders
entity.joints2d
All attached 2D physics joints
entity.body3d
The attached 3D physics body (if there is one)
entity.collider3d
The first attached 3D physics collider (if there is one)
entity.colliders3d
All attached 3D physics colliders
entity.joints3d
All attached 3D physics joints
entity.created
Callback for the created(…) event, which is called right after a Lua component is created, and forwards all parameters passed from the entity:add(component, ...) function
SelfDestructor = class('SelfDestructor')
-- Called when created but no parameters are forwarded here
function SelfDestructor:init()
end
-- Use for custom component initialization, all parameters forwarded to here
function SelfDestructor:created(delay)
print("I will self destruct in ", delay, " seconds")
self.entity:destroy(delay)
end
...
local ent = main.scene:entity()
ent:add(SelfDestructor, 3) -- prints "I will self destruct in 3 seconds"
entity.destroyed
Callback for the destroyed() event, which is called right before the entity is destroyed
entity.collisionBegan2d
Callback for the collisionBegan2d(contact) event, which is called when a collision occurs with a physics2d.body attached to this entity
entity.collisionBegan3d
Callback for the collisionBegan3d(contact) event, which is called when a collision occurs with a physics3d.body attached to this entity
entity.update
Callback for the update(dt) event, which is called on all active entities once per frame. The dt parameter passes the delta time of the enclosing scene for this frame
entity.fixedUpdate
Callback for the fixedUpdate(dt) event, which is called on all active entities once per fixed update (called a fixed number of times per second). The dt parameter passes the fixed delta time of the enclosing scene
entity.touched
Callback for the touched(touch) event, which is called whenever a touch occurs (in response to user interaction)
During the BEGAN phase of an incomming touch, returning true from this function will capture the touch for all subsequent events, otherwise the touch will be lost
entity.hitTest
Enables hit testing for the touched(touch) event, which will filter touches based on collision checks using attached physics components on the main camera
camera
A camera object used for rendering. Can also be used as a component in scenes
scn = scene()
-- Create an entity and attach a perspective camera to it
cam = scn:entity():add(camera.perspective(45, 0.1, 100))
-- Use a camera directly with drawing calls
cam = camera.perspective(45, 0.1, 100)
cam:apply()
camera.ortho(size, near, far)
| size | number. Vertical span of the orthographic view, in world units. |
| near | number, optional. Distance to the near clipping plane, in world units. |
| far | number, optional. Distance to the far clipping plane, in world units. |
camera |
A new orthographic camera |
camera.perspective(fov, near, far)
| fov | number. Vertical field of view, in degrees. |
| near | number, optional. Distance to the near clipping plane, in world units. |
| far | number, optional. Distance to the far clipping plane, in world units. |
camera |
A new perspective camera |
camera.isOrtho
Determines if the camera is orthographic or perspective
camera.orthoSize
The ortho graphic size (height) of this camera when in orthographic mode
camera.clearMode
The clear mode, which can be one of the following values:
camera.none - do not clear the backgroundcamera.color - clear the color onlycamera.depth - clear the depth onlycamera.depthAndColor - clear both the depth and colorcamera.sky - clear depth and draw the scene sky (the default for a 3D scene)camera.clearColor
The color to use when clearing the screen with this camera
camera.fieldOfView
The field of view for this camera when in perspective mode
camera.nearPlane
The distance of near view plane from the view origin
camera.farPlane
The distance of far view plane from the view origin
camera.priority
The priority of the camera when used within a scene (cameras with lower values are drawn first)
camera.projection
Sets/gets a custom projection matrix
camera.view
Sets/gets a custom view matrix
camera.viewport
Sets/gets the current viewport using normalized coordinates. Can be used for adjusting the rendered area of the camera relative to the screen. For instance, writing camera.viewport = vec4(0.0, 0.0, 0.5, 1.0) will render the camera to only the left half of the screen.
x: The x position of the viewporty: The y position of the viewportz: The width of the viewportw: The height of the viewportcamera.aspect
Sets/gets the aspect ratio of the viewport
camera:apply()
Apply this cameras settings to the matrix stack
camera:screenToWorld(x, y, z)
Takes a 2D point on the screen (in points) and a depth value and unprojects this point into 3D space. Useful for things like raycasting from touches
| x | number. x coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
| y | number. y coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
| z | number. z coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
number |
The point at screen position x, y projected z units into the screen in world space |
number |
|
number |
camera:screenToRay(x, y)
Takes a 2D point on the screen (in points) and returns a ray that starts at the camera and points through that point into the scene. Use it with raycasts to find what is under a touch
| x | number. x coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
| y | number. y coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
vec3 |
The origin of the ray and its direction (normalized) |
vec3 |
function touched(touch)
local origin, dir = scene.main.camera:get(camera):screenToRay(touch.x, touch.y)
local hit = scene.main.world3d:raycast(origin, dir, 100)
end
camera:worldToScreen(x, y, z)
Takes a 3D point in world space and projects it onto screen coordinates (in points)
| x | number. x coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
| y | number. y coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
| z | number. z coordinate of the point being converted; screen x/y are in points and world coordinates are in scene units. |
number |
The point in world space (x, y, z) projected onto the screen |
number |
camera.effectsEnabled
Enable post-processing for this camera. Defaults to true. Set to false for a reflection or other secondary draw, then restore it. Settings and custom effects are retained while disabled. Effects are only used when the camera renders a scene; cam:apply() alone applies matrices.
camera.bloom
Read-only settings object; change its fields rather than replacing it. Bloom spreads bright parts of the camera image into a glow. A strength of zero skips the bloom passes. The camera renders into a floating-point image before finishing, preserving brightness above white.
camera.tiltShift
Read-only settings object; change its fields rather than replacing it. Blur increases away from a sharp horizontal band. Coordinates for the band are fractions of the camera image height, measured from the bottom. A blur of zero skips tilt shift. This is an image-space effect, not a depth-of-field simulation.
camera.saturation
Color saturation, default 1. Use 0 for grayscale, values between 0 and 1 for muted color, and values above 1 for stronger color.
camera.vignette
Darkening toward the image edges, default 0 (off). Start with a small positive value such as 0.2 and adjust for the image. Values are not clamped by the setter.
camera.grain
Animated film-grain strength, default 0 (off). Small positive values such as 0.02 add subtle noise. Values are not clamped by the setter.
camera:addEffect(source)
Compile a fragment-shader body and append it to this camera’s custom effect chain. Returns the shader, which can be used to set uniforms or remove the effect later. Effects run in insertion order, after tilt shift, bloom and color grading. Intermediate custom-effect images are RGBA8; scene still provides the original floating-point camera image.
The supplied body has uv (texture coordinates), FragColor (output), source (sampler2D containing the previous stage), resolution (vec4: pixel width, pixel height, inverse width, inverse height), and time (seconds) declared for it. Declare uniform sampler2D scene; to sample the camera image before any effects. Write all four components of FragColor, preserving alpha when compositing cameras.
If the source contains #version, it is treated as a complete fragment shader: provide the declarations yourself. Effect passes disable depth testing and depth writes and manage their own blend state.
| source | string. GLSL fragment body, or a complete fragment shader with a version declaration. |
shader |
The appended effect shader. |
local effect = cam:addEffect([[
uniform sampler2D scene;
void main() {
vec4 processed = texture(source, uv);
vec4 original = texture(scene, uv);
// Keep the center sharp while retaining effects at the edges.
float edge = smoothstep(0.15, 0.5, length(uv - vec2(0.5)));
FragColor = mix(original, processed, edge);
}
]])
camera:addEffect(effect)
Append an existing shader and return it. It must render a full-screen image using the effect vertex layout and declare a source sampler. resolution and scene are supplied when declared. The shader returned by the source-string overload can be reused with another camera. Uniforms are shared when the same shader instance is reused.
| effect | shader. Full-screen effect shader. |
shader |
The same shader instance. |
camera:removeEffect(effect)
Remove every occurrence of this shader from this camera’s custom chain. Does nothing if it is absent. Built-in effect settings are unchanged.
| effect | shader. Shader previously returned by addEffect. |
camera:clearEffects()
Remove all custom shaders from this camera. Bloom, tilt shift, saturation, vignette and grain settings are unchanged. Use effectsEnabled = false to bypass both built-in and custom effects without discarding settings.
camera.bloom.strength
Glow amount, default 0 (off). Positive values add bloom.
camera.bloom.threshold
Brightness cutoff for bloom, default 0.9. Lower values include more of the image.
camera.tiltShift.blur
Maximum blur radius in points, default 0 (off).
camera.tiltShift.focus
Center of the sharp band as a fraction of image height from the bottom, default 0.5.
camera.tiltShift.range
Half-height of the sharp band as a fraction of image height, default 0.12.
camera.tiltShift.falloff
Distance outside the sharp band over which blur reaches its maximum, default 0.4.
Add lights to show the shape and surface of 3D objects. Attach a light to an entity in a scene, or use light.push() and light.pop() when drawing meshes yourself.
Using a light as a component in a scene
function setup()
-- Create a basic scene with a single directional light source
scn = scene()
sun = scn:entity("sun")
sun.eulerRotation = vec3(45, 45, 0)
sunLight = sun:add(light.directional(vec3(0,-1,0)))
sunLight.castShadows = true
-- Add a model to represent the sun
sun:add(mesh.cone())
sun.material = material.unlit()
sun.material.color = color.yellow
sun.position = vec3(0,3,0)
inspector.add(sun)
cam = scn:entity("camera")
cam:add(camera.perspective(60))
cam:add(camera.rigs.orbit)
cam.z = -10
-- Some stuff to light
sphere = scn:entity("sphere")
sphere:add(mesh.sphere())
ground = scn:entity("ground")
ground:add(mesh.plane())
ground.y = -1
ground.uniformScale = 10
scene.main = scn
endlight.directional(direction)
Create a new directional light. Directional lights simulate a distant light source (like the sun) that casts parallel rays in a given direction and supports shadow mapping.
| direction | vec3, optional. The direction vector the light casts in world space, defaults to vec3(0, -1, 0) |
light |
A new directional light |
sun = scn:entity("sun")
sunLight = sun:add(light.directional(vec3(0, -1, 0)))
sunLight.castShadows = true
light.point(position)
Create a new positional point light that radiates in all directions from a given position.
Note: point lights are not currently supported by the renderer
| position | vec3, optional. The world-space position of the light source, defaults to the origin |
light |
A new point light |
light.spot(position, direction)
Create a new spot light that emits a cone of light from a position toward a direction.
Note: spot lights are not currently supported by the renderer
| position | vec3, optional. The world-space position of the light source, defaults to the origin |
| direction | vec3, optional. The direction the cone points in world space, defaults to vec3(0, -1, 0) |
light |
A new spot light |
light.push(light)
Adds a light for meshes drawn after this call. Pair it with light.pop() when finished.
This applies basic lighting to 3D objects with lit materials for all subsequent draw calls until light.pop() is called. Immediate mode lighting does not support advanced features such as shadows — use scene-based lights for those.
| light | light. The light to push onto the rendering stack |
light |
The same light for chaining |
light.pop()
Pops a light source from the rendering stack
light.clear()
Clears all lights from the rendering stack
light.type
Get/set the type of light. Possible values are:
light.intensity
The intensity of the light source
light.color
The color of the light source
light.castShadows
Enables/disables shadow casting. Cascaded shadow mapping works for a single directional light source
note: shadows currently only work with directional lights
light.shadowOptions
Get the shadow options for this light
note: shadows currently only work with directional lights
light.shadowOptions
light.shadowOptions.cascades
The number of shadow cascades to used in rendering. The maximum number of cascades is 5
light.shadowOptions.size
The size of the cascade textures to use when rendering. High values result in more detailed shadows at the cost of memory and rendering performance
light.shadowOptions.constantBias
This attribute represents the constant bias applied to the depth values during shadow map comparisons. It helps in reducing self-shadowing artifacts by offsetting the comparison depth slightly. The default value is set to 0.001
light.shadowOptions.normalBias
This attribute denotes the normal bias applied during shadow map comparisons. Normal bias helps in mitigating surface acne by adjusting the depth comparison based on surface normals. The default value is set to 0.1
light.shadowOptions.far
The far clipping plane distance for the shadow map rendering. It defines the maximum distance up to which shadows will be calculated. The default value is set to 0.0, implying no limit by default
light.shadowOptions.nearHint
A hint for the near clipping plane distance for shadow map rendering. It suggests the minimum distance from the camera to start shadow map calculations efficiently. The default value is set to 1
light.shadowOptions.farHint
Similar to ‘nearHint’, this provides a hint for the far clipping plane distance for shadow map rendering. It suggests the maximum distance from the camera for efficient shadow map calculations. The default value is set to 100
light.shadowOptions.polygonOffsetConstant
This represents the constant factor used in polygon offset calculations. It adjusts the depth values of rendered polygons to resolve depth fighting issues. The default value is set to 0.5
light.shadowOptions.polygonOffsetSlope
Denotes the slope factor used in polygon offset calculations. It works in conjunction with the constant factor to provide precise depth adjustments for polygons. The default value is set to 2.0