Codea icon Scenes & Entities

Reference › Scenes, entities, cameras, effects and lights

Guides

Scenes in Codea top ↑

Overview

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 ↑

Overview

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

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

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 ↑

Type

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

Class Property

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)

Static Method

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)

Static Method

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)

Static Method

Syntax

scene.read(key)

Loads and returns a scene with the supplied asset key

Parameters

key asset.key.

Asset key identifying the scene file.

Returns

scene

scene.save(key, scene)

Static Method

Syntax

scene.save(key, scene)

Saves the supplied scene at the given asset key location

Parameters

key asset.key.

Asset key identifying the scene file.

scene scene.

Scene to save.

scene.name

Property

Syntax

scene.name

Gets or sets a name for this scene

scene.world2d

Property

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

Property

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

Property

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

Property

Syntax

scene.skyBlur

The blur strength of the skybox

scene.skyExposure

Property

Syntax

scene.skyExposure

The brightness of the skybox

scene.camera

Property

Syntax

scene.camera

scene.sun

Property

Syntax

scene.sun

scene.canvas

Property

Syntax

scene.canvas

scene.pixelsPerUnit

Property

Syntax

scene.pixelsPerUnit

The amount of pixels that are in a grid unit

scene.drawOrder

Property

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)

Method

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)

Method

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)

Method

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]()

Method

Syntax

scene:index(name) [metamethod]()

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

Returns

entity

scene:draw()

Method

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)

Method

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 ↑

Type

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

Property

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

Property

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

Property

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

Property

Syntax

entity.id

A read-only identifier unique to the entity

entity.name

Property

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)

Method

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

Method

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)

Method

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)

Method

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)

Method

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

Property

Syntax

entity.components

Retrieves a list of all components attached to this entity

entity:dispatch(name, ...)

Method

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

Property

Syntax

entity.parent

The parent of this entity or nil if it is a root entity

entity.root

Property

Syntax

entity.root

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

entity.children

Property

Syntax

entity.children

A list of all immediate children of this entity

entity.childCount

Property

Syntax

entity.childCount

The number of children that this entity possesses

entity.depth

Property

Syntax

entity.depth

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

entity:index(name) [metamethod]()

Method

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)

Method

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)

Method

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)

Method

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)

Method

Syntax

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

Parameters

entity entity.

Sibling to place this entity before or after.

entity:moveAfter(entity)

Method

Syntax

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

Parameters

entity entity.

Sibling to place this entity before or after.

entity.position

Property

Syntax

entity.position

The position of the entity in local 3D space

entity.worldPosition

Property

Syntax

entity.worldPosition

The position of the entity in global 3D space

entity.scale

Property

Syntax

entity.scale

The scale of the entity in local 3D space

entity.uniformScale

Property

Syntax

entity.uniformScale

The uniform scale of the entity in local 3D space

entity.rotation

Property

Syntax

entity.rotation

The rotation of the entity in local 3D space

entity.worldRotation

Property

Syntax

entity.worldRotation

The rotation of the entity in world 3D space

entity.eulerRotation

Property

Syntax

entity.eulerRotation

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

entity.x

Property

Syntax

entity.x

The x position of the entity in local 3D space

entity.y

Property

Syntax

entity.y

The y position of the entity in local 3D space

entity.z

Property

Syntax

entity.z

The z position of the entity in local 3D space

entity.sx

Property

Syntax

entity.sx

The x scale of the entity in local 3D space

entity.sy

Property

Syntax

entity.sy

The y scale of the entity in local 3D space

entity.sz

Property

Syntax

entity.sz

The z scale of the entity in local 3D space

entity.rx

Property

Syntax

entity.rx

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

entity.ry

Property

Syntax

entity.ry

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

entity.rz

Property

Syntax

entity.rz

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

entity.forward

Property

Syntax

entity.forward

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

entity.right

Property

Syntax

entity.right

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

entity.up

Property

Syntax

entity.up

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

entity:transformPoint(localPoint)

Method

Syntax

entity:transformPoint(localPoint)

Transform a point from local to world space

Parameters

localPoint vec3.

The point to transform

entity:inverseTransformPoint(worldPoint)

Method

Syntax

entity:inverseTransformPoint(worldPoint)

Transform a point from world to local space

Parameters

worldPoint vec3.

The point to transform

entity:transformDirection(localDir)

Method

Syntax

entity:transformDirection(localDir)

Transform a vector from local to world space

Parameters

localDir vec3.

The vector to transform

entity:inverseTransformDirection(worldDir)

Method

Syntax

entity:inverseTransformDirection(worldDir)

Transform a vector from world to local space

Parameters

worldDir vec3.

The vector to transform

entity:translate(x, y, z)

Method

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

Property

Syntax

entity.sprite

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

entity.color

Property

Syntax

entity.color

The tint color to use

entity.visible

Property

Syntax

entity.visible

Sets/gets whether the entity should be drawn or not

entity.flipX

Property

Syntax

entity.flipX

Flips the sprite on the x-axis

entity.flipY

Property

Syntax

entity.flipY

Flips the sprite on the y-axis

entity.mesh

Property

Syntax

entity.mesh

The mesh attached to this entity. This will be drawn the entities’ transform within the scene

entity.material

Property

Syntax

entity.material

The material attached to this entity (used in conjunction with meshes/sprites)

entity.size

Property

Syntax

entity.size

The size of the UI element

entity.anchorX

Property

Syntax

entity.anchorX

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

Values:

  • LEFT
  • CENTER
  • RIGHT
  • STRETCH

entity.anchorY

Property

Syntax

entity.anchorY

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

Values:

  • TOP
  • MIDDLE
  • BOTTOM
  • STRETCH

entity.pivot

Property

Syntax

entity.pivot

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

entity.clip

Property

Syntax

entity.clip

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

entity.body2d

Property

Syntax

entity.body2d

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

entity.collider2d

Property

Syntax

entity.collider2d

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

entity.colliders2d

Property

Syntax

entity.colliders2d

All attached 2D physics colliders

entity.joints2d

Property

Syntax

entity.joints2d

All attached 2D physics joints

entity.body3d

Property

Syntax

entity.body3d

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

entity.collider3d

Property

Syntax

entity.collider3d

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

entity.colliders3d

Property

Syntax

entity.colliders3d

All attached 3D physics colliders

entity.joints3d

Property

Syntax

entity.joints3d

All attached 3D physics joints

entity.created

Property

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

Property

Syntax

entity.destroyed

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

entity.collisionBegan2d

Property

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

Property

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

Property

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

Property

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

Property

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

Property

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 ↑

Type

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)

Static Method

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)

Static Method

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

Property

Syntax

camera.isOrtho

Determines if the camera is orthographic or perspective

camera.orthoSize

Property

Syntax

camera.orthoSize

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

camera.clearMode

Property

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
  • camera.sky - clear depth and draw the scene sky (the default for a 3D scene)

camera.clearColor

Property

Syntax

camera.clearColor

The color to use when clearing the screen with this camera

camera.fieldOfView

Property

Syntax

camera.fieldOfView

The field of view for this camera when in perspective mode

camera.nearPlane

Property

Syntax

camera.nearPlane

The distance of near view plane from the view origin

camera.farPlane

Property

Syntax

camera.farPlane

The distance of far view plane from the view origin

camera.priority

Property

Syntax

camera.priority

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

camera.projection

Property

Syntax

camera.projection

Sets/gets a custom projection matrix

camera.view

Property

Syntax

camera.view

Sets/gets a custom view matrix

camera.viewport

Property

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

Property

Syntax

camera.aspect

Sets/gets the aspect ratio of the viewport

camera:apply()

Method

Syntax

camera:apply()

Apply this cameras settings to the matrix stack

camera:screenToWorld(x, y, z)

Method

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)

Method

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)

Method

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

Property

Syntax

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

Property

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

Property

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

Property

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

Property

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

Property

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:addEffect(source)

Method

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

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)

Method

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

Parameters

effect shader.

Full-screen effect shader.

Returns

shader

The same shader instance.

camera:removeEffect(effect)

Method

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

Method

Syntax

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

Property

Syntax

camera.bloom.strength

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

camera.bloom.threshold

Property

Syntax

camera.bloom.threshold

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

camera.tiltShift.blur

Property

Syntax

camera.tiltShift.blur

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

camera.tiltShift.focus

Property

Syntax

camera.tiltShift.focus

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

camera.tiltShift.range

Property

Syntax

camera.tiltShift.range

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

camera.tiltShift.falloff

Property

Syntax

camera.tiltShift.falloff

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

Lights

Lighting a Scene top ↑

Overview

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

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 ↑

Type

Syntax

light

light.directional(direction)

Static Method

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)

Static Method

Syntax

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

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)

Static Method

Syntax

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

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)

Static Method

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

Static Method

Syntax

light.pop()

Pops a light source from the rendering stack

light.clear()

Static Method

Syntax

light.clear()

Clears all lights from the rendering stack

light.type

Property

Syntax

light.type

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

  • DIRECTIONAL
  • POINT
  • SPOT
  • ENVIRONMENT

light.intensity

Property

Syntax

light.intensity

The intensity of the light source

light.color

Property

Syntax

light.color

The color of the light source

light.castShadows

Property

Syntax

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

Property

Syntax

light.shadowOptions

Get the shadow options for this light

note: shadows currently only work with directional lights

light.shadowOptions

Type

Syntax

light.shadowOptions

light.shadowOptions.cascades

Property

Syntax

light.shadowOptions.cascades

The number of shadow cascades to used in rendering. The maximum number of cascades is 5

light.shadowOptions.size

Property

Syntax

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

Property

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

Property

Syntax

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

Property

Syntax

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

Property

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

Property

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

Property

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

Property

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