Codea icon Scenes & Entities

Reference › Scenes, entities, cameras, effects and lights

Guides

Scenes in Codea top ↑

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
end

Creating Scenes

Create a scene with scene() and assign it to scene.main to draw and update it each frame.

scn = scene()
scene.main = scn

You can have multiple scenes and switch between them by reassigning scene.main.

Entities

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 origin

Components

Components 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)

Drawing in an Entity

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)
end

The 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.

The Scene Camera

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 units

Use camera.rigs.orbit to add an interactive orbit controller that works with mouse and touch:

cam:add(camera.rigs.orbit)

Lifecycle Callbacks

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 top ↑

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.

Getting started

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
end

HDR highlights and exposure

Set cam.tonemap = camera.agx to retain detail in bright lights and reflections that would otherwise clip to white. AgX runs after bloom and tilt shift, before color grading and custom effects. It preserves middle gray and rolls bright, saturated colors toward white. The output is SDR; this does not enable an HDR display mode.

cam.exposure = -1 halves the brightness of the entire camera image before tone mapping; 1 doubles it. Exposure is measured in stops, defaults to zero, and accepts values from -16 to 16. Bloom’s threshold is evaluated before this adjustment. The original floating-point scene sampler in custom effects remains unexposed and untonemapped.

Use camera.linear with zero exposure to leave the image unchanged. Set cam.effectsEnabled = false to bypass these adjustments along with the other camera effects.

Brightness and contrast

Set cam.brightness = 1.2 to make the picture brighter, or use a value below 1 to darken it. Zero makes the picture black. The default is 1, which leaves brightness unchanged.

Set cam.contrast = 1.1 to make light and dark areas stand out more. A value of 0.5 gives softer contrast; 0 produces a flat grey image. The default is 1, which leaves contrast unchanged.

Color lookup tables

A lookup table maps all three color channels together, allowing looks that brightness and saturation alone cannot produce. Assign a horizontal strip LUT:

cam.lut = image.read(asset.MyLut, {srgb = false})
cam.lutStrength = 0.7

Use an N*N by N image (N from 2 to 64): N square slices laid out left to right, red increasing across each slice and green increasing upward. Successive slices represent increasing blue. Load LUT images with srgb = false as shown above. PNG strips work directly; .cube text files and other layouts need conversion first.

For a procedural identity LUT:

local n = 16
local lut = image.pixel(n*n, n, false, 1, image.rgba8)
for b = 0, n-1 do
    for g = 0, n-1 do
        for r = 0, n-1 do
            lut:setValue(b*n+r+1, g+1, r/(n-1), g/(n-1), b/(n-1), 1)
        end
    end
end
lut:apply()
cam.lut = lut

Use lutStrength to blend the look into the original picture. Set it to zero or assign nil to lut to turn it off. Strong LUT grading can flatten very bright highlights; reduce its strength if you want to retain more of their original appearance.

Tilt shift and custom effects

cam.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 color grading. 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.

Depth-aware custom effects

Declare uniform sampler2D sceneDepth to use the original scene’s depth in an effect, such as fog that increases with distance. It uses nearest filtering with clamped edges and the same UVs as scene. Values range from 0 at the near plane to 1 at the far plane; this is nonlinear for perspective cameras. Cleared background has depth 1. Only draws that write depth appear in the texture: transparent objects with depth writes disabled are absent. Bloom, blur and earlier custom effects do not change it.

Optional uniform mat4 cameraProjection and cameraInverseProjection contain the camera projection and its inverse. They differ from the fullscreen pass’s u_proj. Optional uniform vec4 sceneResolution contains original width, height and their reciprocals in pixels. This works with offset viewports and resized targets.

For example, show view-space depth (nearer surfaces are brighter):

cam:addEffect([[
uniform sampler2D sceneDepth;
uniform mat4 cameraInverseProjection;
void main() {
    float depth = texture(sceneDepth, uv).r;
    // Texture rows run down; clip-space Y runs up. Depth is already [0,1].
    vec4 view = cameraInverseProjection *
                vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
    float distance = abs(view.z / view.w);
    float shade = depth >= 1.0 ? 0.0 : clamp(1.0 - distance / 20.0, 0.0, 1.0);
    FragColor = vec4(vec3(shade), texture(source, uv).a);
}
]])

This example works with perspective and orthographic cameras. Adjust 20.0 to change the distance over which the depth visualization fades.

Smoother edges

Set cam.antialias = true to smooth jagged diagonal lines and object outlines in the camera image. Antialiasing runs after custom effects and leaves UI drawn afterward untouched. It is off by default.

Antialiasing uses extra memory and rendering time. Compare the image and frame rate on your target device. Very fine details can still flicker as the camera moves, and edges defined only by transparency stay unchanged.

Smoother gradients

Set cam.debanding = true when dark skies, fog or other smooth gradients show visible steps. It adds a subtle, static texture that makes those steps less noticeable. The default is false.

Debanding runs after custom effects and antialiasing. Its pattern stays still as the camera moves, and it cannot recover detail lost in the source image. Enable it where the smoother result is worth the additional memory and rendering time.

Layering cameras and controlling effects

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

scene top ↑

Syntax

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

Syntax

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)

Syntax

scene.default3d(name)

Creates the default 3D scene containing a perspective camera, directional light and HDR environment, with an optional name

Parameters

name string, optional.

Name assigned to the scene or entity, or the entity name to search for.

Returns

scene

scene.default2d(name)

Syntax

scene.default2d(name)

Creates the default 2D scene containing an orthographic camera, with an optional name

Parameters

name string, optional.

Name assigned to the scene or entity, or the entity name to search for.

Returns

scene

scene.read(key)

Syntax

scene.read(key)

Loads and returns a scene with the supplied asset key, or nil if there is no scene file there. The .scene extension can be left out of the key

Parameters

key asset.key.

Asset key identifying the scene file.

Returns

scene

scene.save(key, scene)

Syntax

scene.save(key, scene)

Saves the supplied scene at the given asset key location, adding the .scene extension if the key doesn’t end with it

Parameters

key asset.key.

Asset key identifying the scene file.

scene scene.

Scene to save.

scene.save(asset.documents .. "Level1.scene", scn)
scn = scene.read(asset.documents .. "Level1.scene")

scene.name

Syntax

scene.name

Gets or sets a name for this scene

scene.shadowAtlasSize

Syntax

scene.shadowAtlasSize

Width and height of the scene’s shared spot-shadow atlas, default 2048. Set 0 to disable spot shadows. Positive integer sizes round up to powers of two from 64 through 4096.

world.shadowAtlasSize = 2048
spot.castShadows = true
spot.shadowOptions.size = 512

scene.world2d

Syntax

scene.world2d

Gets the scene’s 2D physics world, providing access to various physics functions and properties such as physics2d.world.applyForce()

scene.world3d

Syntax

scene.world3d

Gets the scene’s 3D physics world, providing access to various physics functions and properties such as physics3d.world.applyForce()

scene.sky

Syntax

scene.sky

Sets the sky visuals, which will depend on the type used:

  • asset.key - Use an image pointed to by a given asset key
  • image - Use an image directly (assumed to be a cube image)
  • color - Use a solid color

scene.skyBlur

Syntax

scene.skyBlur

The blur strength of the skybox

scene.skyExposure

Syntax

scene.skyExposure

The brightness of the skybox

scene.camera

Syntax

scene.camera

scene.sun

Syntax

scene.sun

scene.canvas

Syntax

scene.canvas

scene.pixelsPerUnit

Syntax

scene.pixelsPerUnit

The amount of pixels that are in a grid unit

scene.drawOrder

Syntax

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 distance

scene:entity(name)

Syntax

scene:entity(name)

Creates a new blank entity with an optional name

Parameters

name string, optional.

Name assigned to the scene or entity, or the entity name to search for.

Returns

entity

scene:findEntity(name)

Syntax

scene:findEntity(name)

Parameters

name string.

Name assigned to the scene or entity, or the entity name to search for.

Returns

entity

scene:entities(activeOnly)

Syntax

scene:entities(activeOnly)

Returns a table containing all root entities

Parameters

activeOnly boolean, optional, default true.

When set, returns only active root entities

Returns

table

scene:index(name) [metamethod]()

Syntax

scene:index(name) [metamethod]()

Returns the root entity with the given name (if it exists)

Returns

entity

scene:draw()

Syntax

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)

Syntax

scene:update(deltaTime)

Updates the scene, called automatically when draw() is called but can also be called manutally if needed

Parameters

deltaTime number.

Elapsed simulation time in seconds.

Entity

entity top ↑

Syntax

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

Syntax

entity.active

The active state of this entity, when inactive an entity will not be rendered, simulate physics or respond to automatic callbacks

Example

Show code (55 lines)
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

Syntax

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

Syntax

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

Syntax

entity.id

A read-only identifier unique to the entity

entity.name

Syntax

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)

Syntax

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

Parameters

delay number, optional.

Delay before destruction, in seconds; omit to destroy on the next scene update.

Example

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, ...)

Syntax

entity:add(component, ...)

Adds a component to this entity, there are several types of objects that can act as entities

  • Lua classes/components
  • Anything you can dream of…
  • built-in classes
  • camera.rigs.orbit
  • camera.rigs.canvas
  • physics3d.grabber
  • voxel.world
  • assets
  • mesh
  • image / image.slice

Note on Lua classes/components

Parameters

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)

Syntax

entity:remove(component)

Removes a given component type from this entity

Parameters

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)

Syntax

entity:has(component)

Checks if a component type is attached to this entity

Parameters

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)

Syntax

entity:get(component)

Retrieves a component type attached to this entity

Parameters

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

Syntax

entity.components

Retrieves a list of all components attached to this entity

entity:dispatch(name, ...)

Syntax

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

Parameters

name string.

The name of the method to call

... any.

Additional arguments forwarded to the component constructor or dispatched method.

entity.parent

Syntax

entity.parent

The parent of this entity or nil if it is a root entity. Assigning a descendant as the parent raises an error without changing the hierarchy. Assigning self or the existing parent leaves the hierarchy unchanged.

entity:reparent(parent, keepWorld)

Syntax

entity:reparent(parent, keepWorld)

Move this entity and its children under a new parent. By default, they keep their position, rotation and size in the scene. Pass nil to detach them from their current parent.

Pass false for keepWorld to keep the entity’s local position, rotation and scale instead, just as assigning entity.parent does.

Keeping world placement is supported for ordinary 3D entities, but not for layout-managed panels or physics bodies and colliders. Moving between rotated parents with different scales can also fail if it would require skewing the entity. In that case, use more uniform parent scales or pass false to keep local placement instead.

The new parent must belong to the same scene.

Parameters

parent entity or nil.

new parent, or nil for the scene root

keepWorld boolean, optional, default true.

preserve world placement; defaults to true

object:reparent(newParent)        -- keep its world placement
object:reparent(nil)              -- detach without moving
object:reparent(newParent, false) -- keep its local transform

entity.root

Syntax

entity.root

The root parent entity in the scene heirarchy (or self if this entity has no parent)

entity.children

Syntax

entity.children

A list of all immediate children of this entity

entity.childCount

Syntax

entity.childCount

The number of children that this entity possesses

entity.depth

Syntax

entity.depth

The depth of this entity in the hierarchy (roots have a depth of 0).

entity:index(name) [metamethod]()

Syntax

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)

Syntax

entity:child(name)

Creates a new child entity of this entity

Parameters

name string.

Name of the child entity or component method to find or invoke.

entity:findChild(name)

Syntax

entity:findChild(name)

Parameters

name string.

Name of the child entity or component method to find or invoke.

Returns

value

Finds the child named name or nil if it does not exist

entity:childAt(index)

Syntax

entity:childAt(index)

Parameters

index integer.

Child index, starting at 1.

Returns

value

The child entity at a given index (between 1..childCount) or nil if an invalid index is supplied

entity:moveBefore(entity)

Syntax

entity:moveBefore(entity)

Rearranges this entity to appear before the supplied entity in the transform hierarchy

This may change the parent to make this entity a sibling of the supplied entity. A move that would create a cycle raises an error before changing the hierarchy. Moving relative to self leaves the hierarchy unchanged.

Parameters

entity entity.

Sibling to place this entity before or after.

entity:moveAfter(entity)

Syntax

entity:moveAfter(entity)

Rearranges this entity to appear after the supplied entity in the transform hierarchy

This may change the parent to make this entity a sibling of the supplied entity. A move that would create a cycle raises an error before changing the hierarchy. Moving relative to self leaves the hierarchy unchanged.

Parameters

entity entity.

Sibling to place this entity before or after.

entity.position

Syntax

entity.position

The position of the entity in local 3D space

entity.worldPosition

Syntax

entity.worldPosition

The position of the entity in global 3D space

entity.scale

Syntax

entity.scale

The scale of the entity in local 3D space

entity.uniformScale

Syntax

entity.uniformScale

The uniform scale of the entity in local 3D space

entity.rotation

Syntax

entity.rotation

The rotation of the entity in local 3D space

entity.worldRotation

Syntax

entity.worldRotation

The rotation of the entity in world 3D space

entity.eulerRotation

Syntax

entity.eulerRotation

The euler rotation of the entity in local 3D space (in degrees)

entity.x

Syntax

entity.x

The x position of the entity in local 3D space

entity.y

Syntax

entity.y

The y position of the entity in local 3D space

entity.z

Syntax

entity.z

The z position of the entity in local 3D space

entity.sx

Syntax

entity.sx

The x scale of the entity in local 3D space

entity.sy

Syntax

entity.sy

The y scale of the entity in local 3D space

entity.sz

Syntax

entity.sz

The z scale of the entity in local 3D space

entity.rx

Syntax

entity.rx

The euler rotation around the local x axis of the entity in degrees

entity.ry

Syntax

entity.ry

The euler rotation around the local y axis of the entity in degrees

entity.rz

Syntax

entity.rz

The euler rotation around the local z axis of the entity in degrees

entity.forward

Syntax

entity.forward

The positive z axis of this entity’s coordinate space transformed into world space

entity.right

Syntax

entity.right

The positive x axis of this entity’s coordinate space transformed into world space

entity.up

Syntax

entity.up

The positive y axis of this entity’s coordinate space transformed into world space

entity:transformPoint(localPoint)

Syntax

entity:transformPoint(localPoint)

Transform a point from local to world space

Parameters

localPoint vec3.

The point to transform

entity:inverseTransformPoint(worldPoint)

Syntax

entity:inverseTransformPoint(worldPoint)

Transform a point from world to local space

Parameters

worldPoint vec3.

The point to transform

entity:transformDirection(localDir)

Syntax

entity:transformDirection(localDir)

Transform a vector from local to world space

Parameters

localDir vec3.

The vector to transform

entity:inverseTransformDirection(worldDir)

Syntax

entity:inverseTransformDirection(worldDir)

Transform a vector from world to local space

Parameters

worldDir vec3.

The vector to transform

entity:translate(x, y, z)

Syntax

entity:translate(x, y, z)

Moves the entity by the provided translation vector in local space

Also supports vec2 and vec3 parameters

Parameters

x number.

Translation along the x axis.

y number.

Translation along the y axis.

z number, optional.

Translation along the z axis.

entity.color

Syntax

entity.color

Tints whatever this entity draws, whether a sprite or a mesh. For meshes the color multiplies the base color of the entity’s material, so entities sharing a material can each have their own color without copying it. Defaults to white, which leaves the sprite or material unchanged

The color can be set before a sprite or mesh is attached, and is kept when either is replaced. Its alpha fades sprites and transparent materials, but an opaque material stays opaque

glass = material.lit()
glass.blend = BLEND_TRANSPARENT

a.material = glass
b.material = glass
b.color = color(255, 80, 80)  -- tints b, a is unchanged

entity.instances

Syntax

entity.instances

The number of instances of this entity’s mesh drawn each frame. Every instance uses the entity’s transform, so a shader tells them apart with gl_InstanceID, for example to offset each one in its vertex function. Each of the mesh’s submeshes is drawn this many times with its own material, so every material needs the same offset. Skinned meshes share one pose across instances. Defaults to 1

Only the base mesh is known outside the shader:

  • Shadows are cast by one instance, at the entity’s transform
  • bounds, worldBounds and picking cover the base mesh
  • An entity with more than one instance is always drawn, without culling against the view
  • Transparent instances are sorted as one object
grid.mesh = mesh.box(vec3(0.1))
grid.material = material(gridShader) -- positions each box from gl_InstanceID
grid.instances = 100

entity.visible

Syntax

entity.visible

Sets/gets whether the entity should be drawn or not

entity.sprite

Syntax

entity.sprite

The sprite (image.slice) attached to this entity. This will be drawn at the entities’ transform within the scene

entity.flipX

Syntax

entity.flipX

Flips the sprite on the x-axis

entity.flipY

Syntax

entity.flipY

Flips the sprite on the y-axis

entity.mesh

Syntax

entity.mesh

The mesh attached to this entity, drawn using the entity’s transform within the scene. Assign nil to remove the mesh. Replacing a mesh recreates its instantiated mesh nodes; user-created child entities are retained.

Attaching a mesh copies any materials the mesh has into this entity, so later changes to the mesh’s own materials don’t affect it. Use entity.material to change how this entity looks

entity.material

Syntax

entity.material

The material this entity draws its mesh with, used in place of the mesh’s own material. Assigning it sets every part of the mesh; reading it gives the first part’s material. Use entity.setMaterial() to set one part

Assigning a material shares it with any other entities using it. Use material.copy() to give this entity its own, or entity.color to change only its color

box.mesh = mesh.box(1, 1, 1)
box.material = material.lit()
box.material.color = color(80, 160, 255)

entity.materialCount

Syntax

entity.materialCount

The number of materials this entity has, one for each part of its mesh

entity:getMaterial(index)

Syntax

entity:getMaterial(index)

Gets the material for one part of this entity’s mesh

Parameters

index number.

Index of the mesh part, starting at 1.

Returns

material

The material, or nil if the part uses its mesh’s own material

entity:setMaterial(material, index)

Syntax

entity:setMaterial(material, index)

Sets the material for one part of this entity’s mesh. Assigning nil makes the part use its mesh’s own material

Parameters

material material.

Material to use, or nil.

index number.

Index of the mesh part, starting at 1.

car.mesh = asset.Car
car.material = paint
car:setMaterial(glass, 2)

entity.size

Syntax

entity.size

The size of the UI element

entity.anchorX

Syntax

entity.anchorX

The horizontal anchoring of this UI element within its parent coordinate system

Values:

  • LEFT
  • CENTER
  • RIGHT
  • STRETCH

entity.anchorY

Syntax

entity.anchorY

The vertical anchoring of this UI element within its parent coordinate system

Values:

  • TOP
  • MIDDLE
  • BOTTOM
  • STRETCH

entity.pivot

Syntax

entity.pivot

The pivot point, representing the center of the UI element (in normalized coordinates)

entity.clip

Syntax

entity.clip

When enabled, clips drawing to within the bounds of the UI element

entity.body2d

Syntax

entity.body2d

The attached 2D physics body (if there is one)

entity.collider2d

Syntax

entity.collider2d

The first attached 2D physics collider (if there is one)

entity.colliders2d

Syntax

entity.colliders2d

All attached 2D physics colliders

entity.joints2d

Syntax

entity.joints2d

All attached 2D physics joints

entity.body3d

Syntax

entity.body3d

The attached 3D physics body (if there is one)

entity.collider3d

Syntax

entity.collider3d

The first attached 3D physics collider (if there is one)

entity.colliders3d

Syntax

entity.colliders3d

All attached 3D physics colliders

entity.joints3d

Syntax

entity.joints3d

All attached 3D physics joints

entity.created

Syntax

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

Syntax

entity.destroyed

Callback for the destroyed() event, which is called right before the entity is destroyed

entity.collisionBegan2d

Syntax

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

Syntax

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

Syntax

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

Syntax

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

Syntax

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

Syntax

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

camera top ↑

Syntax

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)

Syntax

camera.ortho(size, near, far)

Parameters

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.

Returns

camera

A new orthographic camera

camera.perspective(fov, near, far)

Syntax

camera.perspective(fov, near, far)

Parameters

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.

Returns

camera

A new perspective camera

camera.isOrtho

Syntax

camera.isOrtho

Determines if the camera is orthographic or perspective

camera.orthoSize

Syntax

camera.orthoSize

The ortho graphic size (height) of this camera when in orthographic mode

camera.clearMode

Syntax

camera.clearMode

The clear mode, which can be one of the following values:

  • camera.none - do not clear the background
  • camera.color - clear the color only
  • camera.depth - clear the depth only
  • camera.depthAndColor - clear both the depth and color, using clearColor
  • camera.sky - clear depth and draw the scene sky

Perspective cameras start with camera.sky and orthographic cameras with camera.depthAndColor. scene.camera is the camera’s entity, so use get(camera) to reach the camera itself.

-- Show a solid color behind the default camera instead of the sky
cam = scn.camera:get(camera)
cam.clearMode = camera.depthAndColor
cam.clearColor = color(40, 40, 50)

camera.clearColor

Syntax

camera.clearColor

The color to use when clearing the screen with this camera

camera.fieldOfView

Syntax

camera.fieldOfView

The field of view for this camera when in perspective mode

camera.nearPlane

Syntax

camera.nearPlane

The distance of near view plane from the view origin

camera.farPlane

Syntax

camera.farPlane

The distance of far view plane from the view origin

camera.priority

Syntax

camera.priority

The priority of the camera when used within a scene (cameras with lower values are drawn first)

camera.projection

Syntax

camera.projection

Sets/gets a custom projection matrix

camera.view

Syntax

camera.view

Sets/gets a custom view matrix

camera.viewport

Syntax

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 viewport
  • y: The y position of the viewport
  • z: The width of the viewport
  • w: The height of the viewport

camera.aspect

Syntax

camera.aspect

Sets/gets the aspect ratio of the viewport

camera:apply()

Syntax

camera:apply()

Apply this cameras settings to the matrix stack

camera:screenToWorld(x, y, z)

Syntax

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

Parameters

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.

Returns

number

The point at screen position x, y projected z units into the screen in world space

number
number

camera:screenToRay(x, y)

Syntax

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

Parameters

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.

Returns

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)

Syntax

camera:worldToScreen(x, y, z)

Takes a 3D point in world space and projects it onto screen coordinates (in points)

Parameters

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.

Returns

number

The point in world space (x, y, z) projected onto the screen

number

camera.effectsEnabled

Syntax

camera.effectsEnabled

Enable effects 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.ambientOcclusion

Syntax

camera.ambientOcclusion

Add soft shading where nearby surfaces meet. Ambient occlusion is off by default. Set cam.ambientOcclusion.strength = 2 to try it, then adjust cam.ambientOcclusion.radius to change how far the shading spreads. Set the fields on the existing table.

Ambient occlusion affects ambient lighting on lit meshes. Direct light, light emitted by materials, and unlit surfaces keep their brightness. The effect uses the visible scene (screen-space ambient occlusion), so edges can sometimes show halos.

Set strength to 0 to turn it off. Check the effect and frame rate on your target device because it uses additional memory and rendering time.

camera.ambientOcclusion.strength

Syntax

camera.ambientOcclusion.strength

How strongly nearby surfaces darken ambient lighting, from 0 (off) to 4. Defaults to 0. Start with 1 or 2 and increase it for more pronounced contact shading.

camera.ambientOcclusion.radius

Syntax

camera.ambientOcclusion.radius

How far ambient shading spreads around nearby surfaces, from 0 to 16. Defaults to 1. Increase it for broader shading or reduce it for tighter contact shading. Zero turns the effect off. The radius is a visual control and has no fixed scale in scene units.

camera.effectStats

Syntax

camera.effectStats

Inspect how much work and texture memory this camera’s effects use. Read the statistics after drawing the scene to compare effect settings. Values describe the camera’s most recent draw.

Images may be kept for reuse when effects are disabled, so memory use may stay above zero. These values cover camera effects, not all scene drawing, shadows or GPU timing. Changing the returned table does not change the camera.

world:draw()
local stats = cam.effectStats
print(stats.effectPasses, stats.textureBytes / 1048576, "MiB")

camera.bloom

Syntax

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

Syntax

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.tonemap

Syntax

camera.tonemap

Choose how bright highlights appear in the camera image. The default, camera.linear, leaves brightness unchanged; very bright areas can appear solid white. Set cam.tonemap = camera.agx to keep more detail in bright lights and reflections, with a softer transition to white. Tone mapping runs before color grading and custom effects.

camera.linear

Syntax

camera.linear

Pass-through tone mapping; the default value of tonemap.

camera.agx

Syntax

camera.agx

AgX tone mapping for SDR output, selected with cam.tonemap = camera.agx.

camera.exposure

Syntax

camera.exposure

Brighten or darken the entire camera image before tone mapping. Defaults to 0 (unchanged). Use 1 to double brightness or -1 to halve it; values range from -16 to 16. Works with either tone mapping mode.

camera.antialias

Syntax

camera.antialias

Set cam.antialias = true to smooth jagged edges in the camera image. Defaults to false. The camera currently uses SMAA after custom effects. UI drawn afterward is unaffected. Set effectsEnabled = false to bypass antialiasing along with the other camera effects.

camera.brightness

Syntax

camera.brightness

Brighten or darken the camera image. Defaults to 1 (unchanged). Use 0 for black, values between 0 and 1 to darken, and values above 1 to brighten. For example, cam.brightness = 1.2 makes the image brighter.

camera.contrast

Syntax

camera.contrast

Adjust the difference between light and dark areas. Defaults to 1 (unchanged). Use 0 for a flat grey image, 0.5 for softer contrast, or values above 1 for stronger contrast with darker shadows and brighter highlights.

camera.saturation

Syntax

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.lut

Syntax

camera.lut

Apply a color lookup table to give the camera image a different look, such as warmer colors or a film-style grade. Defaults to nil (off). Load a horizontal strip with image.read(asset.MyLut, {srgb = false}).

The image must be N*N pixels wide and N pixels high, with N from 2 to 64. Each square slice maps red from left to right and green from bottom to top; the slices map blue from left to right. See Camera Effects for an example.

camera.lutStrength

Syntax

camera.lutStrength

How strongly the lookup table changes the picture, from 0 (off) to 1 (full strength, the default). Use a value such as 0.5 for a subtler look. Has no effect when lut is nil.

camera.vignette

Syntax

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

Syntax

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.debanding

Syntax

camera.debanding

Reduce visible steps in smooth gradients, such as dark skies and fog. Defaults to false. Set to true to add a very subtle, static texture that makes those steps less noticeable. Unlike grain, it does not animate.

Debanding applies after custom effects and uses additional memory and rendering time. Set effectsEnabled = false to bypass it along with the other camera effects.

camera:addEffect(source)

Syntax

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, exposure, tone mapping and color grading. Intermediate custom-effect images are RGBA8 by default, or RGBA16F with debanding = true or antialias = true. Antialiasing runs after custom effects, followed by debanding. 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.

Declare uniform sampler2D sceneOcclusion; to inspect this camera’s AO visibility. Its red channel is 1 for unoccluded pixels and approaches 0 for stronger occlusion. It uses the same uv coordinates as scene and returns white when AO is disabled. This texture is already applied during indirect lighting; multiplying the finished color by it would apply AO again and would also darken direct light and emission.

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.

Parameters

source string.

GLSL fragment body, or a complete fragment shader with a version declaration.

Returns

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)

Syntax

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, scene, sceneDepth, sceneResolution, cameraProjection, cameraInverseProjection, and sceneOcclusion are supplied when declared (see Camera Effects). The shader returned by the source-string overload can be reused with another camera. Uniforms are shared when the same shader instance is reused.

Parameters

effect shader.

Full-screen effect shader.

Returns

shader

The same shader instance.

camera:removeEffect(effect)

Syntax

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.

Parameters

effect shader.

Shader previously returned by addEffect.

camera:clearEffects()

Syntax

camera:clearEffects()

Remove all custom shaders from this camera. Built-in effects keep their settings. Use effectsEnabled = false to bypass both built-in and custom effects without discarding settings.

camera.bloom.strength

Syntax

camera.bloom.strength

Glow amount, default 0 (off). Positive values add bloom.

camera.bloom.threshold

Syntax

camera.bloom.threshold

Brightness cutoff for bloom, default 0.9. Lower values include more of the image.

camera.tiltShift.blur

Syntax

camera.tiltShift.blur

Maximum blur radius in points, default 0 (off).

camera.tiltShift.focus

Syntax

camera.tiltShift.focus

Center of the sharp band as a fraction of image height from the bottom, default 0.5.

camera.tiltShift.range

Syntax

camera.tiltShift.range

Half-height of the sharp band as a fraction of image height, default 0.12.

camera.tiltShift.falloff

Syntax

camera.tiltShift.falloff

Distance outside the sharp band over which blur reaches its maximum, default 0.4.

camera.rigs.orbit top ↑

Syntax

camera.rigs.orbit

A component that orbits a camera entity around a target point. Drag with one finger (or scroll on a trackpad) to turn, pinch to zoom, and move a pinch to pan the target. A released swipe keeps turning and slows down, and a zoom past the distance limits stretches, then eases back.

scn = scene.default3d()
local orbit = scn.camera:add(camera.rigs.orbit)
orbit.target = vec3(0, 1, 0)
orbit.distance = 6
orbit.minDistance, orbit.maxDistance = 2, 20

camera.rigs.orbit.target

Syntax

camera.rigs.orbit.target

The point the camera orbits and looks at. Defaults to the origin.

camera.rigs.orbit.distance

Syntax

camera.rigs.orbit.distance

How far the camera is from the target. Defaults to 10.

camera.rigs.orbit.angles

Syntax

camera.rigs.orbit.angles

The camera’s pitch (x) and yaw (y) in degrees.

camera.rigs.orbit.minDistance

Syntax

camera.rigs.orbit.minDistance

The closest a zoom settles at. Defaults to 0.

camera.rigs.orbit.maxDistance

Syntax

camera.rigs.orbit.maxDistance

The farthest a zoom settles at. Defaults to no limit.

camera.rigs.orbit.minPitch

Syntax

camera.rigs.orbit.minPitch

The lowest pitch in degrees. Defaults to -90.

camera.rigs.orbit.maxPitch

Syntax

camera.rigs.orbit.maxPitch

The highest pitch in degrees. Defaults to 90.

camera.rigs.orbit.sensitivity

Syntax

camera.rigs.orbit.sensitivity

Degrees turned per point dragged. Defaults to 0.5.

camera.rigs.orbit.inertia

Syntax

camera.rigs.orbit.inertia

Whether a released swipe keeps turning. Defaults to true.

camera.rigs.orbit.enabled

Syntax

camera.rigs.orbit.enabled

Whether the rig responds to gestures. Defaults to true.

camera.rigs.orbit.gestures

Syntax

camera.rigs.orbit.gestures

Whether the rig listens to touches anywhere on screen. Set it to false to drive the rig yourself with grab(), rotate(), moveTarget(), zoom() and release(), for example when the view only fills part of the screen.

orbit.gestures = false

function touched(touch)
    if touch.began then
        orbit:grab()
    elseif touch.moving then
        orbit:rotate(touch.delta)
    else
        orbit:release(touch.delta * (1 / time.delta))
    end
end

camera.rigs.orbit:grab()

Syntax

camera.rigs.orbit:grab()

Starts a gesture: stops any momentum and lets the zoom stretch past its limits.

camera.rigs.orbit:rotate(delta)

Syntax

camera.rigs.orbit:rotate(delta)

Turns the camera as if dragged by delta points.

Parameters

delta vec2.

The drag in points

camera.rigs.orbit:moveTarget(from, to)

Syntax

camera.rigs.orbit:moveTarget(from, to)

Pans the target so the point under screen point from moves to to.

Parameters

from vec2.

A screen point

to vec2.

A screen point

camera.rigs.orbit:zoom(scale)

Syntax

camera.rigs.orbit:zoom(scale)

Zooms in by scale, such as a pinch’s change in size (gesture.pinchDelta).

Parameters

scale number.

Values above 1 zoom in

camera.rigs.orbit:release(velocity)

Syntax

camera.rigs.orbit:release(velocity)

Ends a gesture. With inertia on, velocity (points per second) keeps the camera turning.

Parameters

velocity vec2, optional.

The drag’s velocity in points per second

Lights

Lighting a Scene top ↑

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.

Scene point and spot lights support up to 1024 lights per view. Keep light ranges close to the area they need to illuminate to reduce shading cost.

Using a light as a component in a scene

Show code (33 lines)
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
end

light top ↑

Syntax

light

light.directional(direction)

Syntax

light.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.

Parameters

direction vec3, optional.

The direction vector the light casts in world space, defaults to vec3(0, -1, 0)

Returns

light

A new directional light

sun = scn:entity("sun")
sunLight = sun:add(light.directional(vec3(0, -1, 0)))
sunLight.castShadows = true

light.point(position)

Syntax

light.point(position)

Create a new positional point light that radiates in all directions from a given position.

Attach this light to a scene entity to illuminate nearby meshes.

Parameters

position vec3, optional.

The world-space position of the light source, defaults to the origin

Returns

light

A new point light

light.spot(position, direction)

Syntax

light.spot(position, direction)

Create a new spot light that emits a cone of light from a position toward a direction.

Attach this light to a scene entity to illuminate meshes inside its cone. Up to 16 eligible spots can cast shadows through castShadows and scene.shadowAtlasSize. Immediate-mode light.push() illuminates meshes without shadows.

Parameters

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)

Returns

light

A new spot light

light.push(light)

Syntax

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.

Parameters

light light.

The light to push onto the rendering stack

Returns

light

The same light for chaining

light.pop()

Syntax

light.pop()

Pops a light source from the rendering stack

light.clear()

Syntax

light.clear()

Clears all lights from the rendering stack

light.type

Syntax

light.type

Get/set the type of light. Possible values are:

  • DIRECTIONAL
  • POINT
  • SPOT
  • ENVIRONMENT

light.intensity

Syntax

light.intensity

The intensity of the light source

light.color

Syntax

light.color

The color of the light source

light.castShadows

Syntax

light.castShadows

Enables shadow casting for one directional light and up to 16 scene spot lights.

light.shadowOptions

Syntax

light.shadowOptions

Get the shadow options for this light. Spot shadows use size, far, constantBias, normalBias and the polygon-offset settings. Cascades and the near/far hints apply only to directional shadows.

light.shadowOptions

Syntax

light.shadowOptions

light.shadowOptions.cascades

Syntax

light.shadowOptions.cascades

Normalized split positions between the camera near and far planes. For example, {0.2, 0.5} creates three cascades. Provide one to three increasing values between 0 and 1.

light.shadowOptions.size

Syntax

light.shadowOptions.size

The width and height of each shadow texture. Higher values add detail at the cost of memory and rendering time.

light.shadowOptions.constantBias

Syntax

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

Syntax

light.shadowOptions.normalBias

Reduce unwanted dark speckles or stripes on a surface’s own shadow. Defaults to 1. Increase it slightly to hide these marks; values that are too large can make shadows look detached from their objects.

light.shadowOptions.far

Syntax

light.shadowOptions.far

The maximum distance from a spot light at which it casts shadows. Defaults to 0, which uses the light’s full range. Use a smaller positive distance to limit shadows without shortening the light’s reach.

light.shadowOptions.nearHint

Syntax

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

Syntax

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

Syntax

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

Syntax

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