Getting Started with Craft

Basic Project

Create a new project and make sure to select the Craft addon

Use this code to create a basic spinning cube

 -- Hello Craft
function setup()
    -- Create an entity
    cube = craft.entity()
    -- Create a unit cube mesh
    cubeMesh = craft.mesh.cube(vec3(1,1,1))
    -- Add a renderer component to the entity (this will actually draw the cube)
    renderer = cube:add(craft.renderer, cubeMesh)
    -- Set a material on the renderer (this determines the appearance of the surface)
    renderer.material = craft.material("Materials:Standard")
    -- Set the map image for the material (the surface texture)
    renderer.material.map = readImage("Blocks:Brick Red")

    -- Create some parameters to modify the material appearance
    parameter.color("AmbientColor", color(50,50,50))
    parameter.color("Diffuse", color(255,255,255))
    parameter.color("Emissive", color(0,0,0))

    craft.scene.camera.position = vec3(0,0,5)
    craft.scene.camera.rotation = quat.eulerAngles(0,0,180)
end

-- Called every frame for updating entities and game logic
function update()
    -- Make the cube rotate and update the material using the parameters
    cube.rotation = quat.eulerAngles(45 * ElapsedTime, 45 * ElapsedTime, 45 * ElapsedTime)
    craft.scene.ambientColor = AmbientColor
    renderer.material.diffuse = Diffuse
    renderer.material.emissive = Emissive
end

-- Only used fir 2D drawing
function draw()
end

Let's break this down line by line.

cube = craft.entity()

	

This creates an entity. Entities are flexible objects that can be customised to change their appearance and behaviour.

cubeMesh = craft.mesh.cube(vec3(1,1,1))

This creates a cube mesh with dimensions 1x1x1

renderer = cube:add(craft.renderer, cubeMesh)

This creates and adds a rendering component to the entity, which will actually draw the mesh

renderer.material = craft.material("Materials:Standard")

This attaches a material to the cube's renderer using the Standard material. Standard is a flexible material that has many options for customing surface appearance.

renderer.material.map = readImage("Blocks:Brick Red")

This sets the material map to a red brick texture.

craft.scene.camera.position = vec3(0,0,5)

The scene camera actually draws the objects on screen and this sets the position in 3D space. The scene.camera object is actually an entity with a camera component.

craft.scene.camera.rotation = quat.eulerAngles(0,0,180)

The quat type is short for quaternion, which is used to represent rotations in 3D space. The quat.eulerAngles(x,y,z) function can be used to create a quaternion using some euler angles in degrees (rotations around the x, y and z angles).

The Examples

Block Library

An example of a set of block types for use in voxel-based projects. Include this as a project dependency if you want to use these block types in your own project. Remember to include the line:

allBlocks = blocks()
to load them.

Voxel Terrain

Voxel Player

Voxel Editor

Crosser

Planet 3D

Cameras

Touches

UI

Scene

Description

The scene represents Craft's 3D environment including some basic built-in objects such as the sun, sky and camera.

Properties

Name Type Description
camera
entity The built-in camera for the scene
sun
entity A built-in directional light in the scene that serves as the primary light source. Has a light component that can be used to modify the sun color and intensity
sky
entity A built-in sky box that serves as the background for the scene. Has a renderer component that can be used to modify the sky colors. Use sky.material.horizonColor and sky.material.skyColor to adjust appearance

Entity

Description

Entities are flexible objects that can be customised to change their appearance and behaviour. You can customise an entity by adding components. Each type of component serves a different purpose. Renderer components change entity appearance, physics components give entities physical behaviour.

Properties

Name Type Description
position
vec3
rotation
quat
worldPosition
vec3
parent
entity

Methods

Examples

-- create a new entity
myEntity = craft.entity()

local r = myEntity:add(craft.renderer, craft.mesh.cube(vec3(1,1,1)))
r.material = craft.material("Materials:Standard")
r.material.map = readImage("Blocks:Brick Red")

myEntity.position = vec3(10,10,10)
myEntity.rotation = quat.eulerAngles(45,45,45)
myEntity.scale = vec3(0.5, 0.5, 0.5)

myEntity:add(craft.shape.box, vec3(1,1,1), vec3(0,0,0))
myEntity:add(craft.rigidbody, DYNAMIC, 0.5)

childEntity = craft.entity()
childEntity.parent = myEntity

Renderer

Description

The renderer component...

Constructors

Properties

Methods

Light

Description

The light component...

Constructors

Constants

Properties

Methods

Mesh

Description

The mesh class represents 3D geometry, which can be rendered via the renderer component. For now the craft mesh class is not compatible with the existing Codea mesh and shader classes but there are plans to merge them down the line.

Properties

Name Type Description
vertexCount
int The number of vertices in this mesh
indexCount
int The number of indices in this mesh
valid
bool Whether or not this mesh is in a valid state for rendering
bounds
bounds The physical bounds of this mesh in local coordinates (i.e. the smallest box that fits all vertices)

Constructors

Signature Returns Description
mesh()
mesh Creates an empty mesh
mesh(assetName)
mesh Loads a mesh from the model asset specified by assetName. For now only the wavefront obj model format is supported. Collada and fbx support is planned for future upates

Functions

Name Returns Description
cube(size, offset)
mesh Creates a cube mesh. The size parameter controls the dimensions of the cube. The offset parameter controls the location of the cube.
icoSphere(radius, subdivs, faceted)
mesh Creates an ico sphere mesh (sphere made from equal sized triangles). The subdivs parameter controls how dense the resulting sphere is (how many triangles). The faceted parameter controls whether the normals for the ico sphere are flat or smooth. Does not generate texture coordinates

Methods

Signature Returns Description
resizeVertices(size)
none Resize the number of vertices in this mesh.
resizeIndices(size)
none Resize the number of indices in this mesh. This must be a multiple of 3 for triangle meshes.
position(index)
position(index, v)
position(index, x, y, z)
none or float x3 Get or set vertex position of this mesh for a given index. Index must be within [0, vertexCount].
normal(index)
normal(index, v)
normal(index, x, y, z)
none or float x3 Get or set vertex normal of this mesh for a given index. Index must be within [0, vertexCount].
uv(index)
uv(index, v)
uv(index, u, v)
none or float x2 Get or set vertex texture coordinate of this mesh for a given index. Index must be within [0, vertexCount].
color(index)
color(index, c)
color(index, r, g, b)
color(index, r, g, b, a)
none or int x4 Get or set vertex color of this mesh for a given index. Index must be within [0, vertexCount].

Material

Description

The material class represents the visual appearance of an object. Materials are applied to entities via renderer components. Each type of material has a number of properties in the form of numbers, images, colors and vectors that can be used to modify their appearance.

Properties (Materials:Standard)

The standard material uses a flexible physically based shader that provides a realistic lighting model. This material is slower to render than "Materials:Specular"

Name Type Default Description
diffuse
color
color(255,255,255)
The surface color of this material.
map
string or image
nil
The surface texture of this material.
offsetRepeat
vec4
vec4(0,0,1,1)
The offset and repeat factors for the textures applied to this material.
opacity
float
1.0
The opacity of this material (how visible it is).
emissive
color
color(0,0,0)
Emissive light emitted from this material.
blendMode
int
NONE
The blend mode of this material, can be: NORMAL, ADDITIVE, MULTIPLY, NONE.
normalMap
string or image
nil
The normal map for this material.
normalScale
vec2
vec2(-0.1, -0.1)
The strength of the normal map effect in each direction.
displacementMap
image or string
nil
displacementBias
float
0.0
displacementScale
float
1.0
roughness
float
0.0
roughnessMap
image or string
nil
metalness
float
0.0
metalnessMap
image or string
nil

Constructors

Signature Returns Description
material(assetName)
material Creates a new material instance using the assetName provided. Currently the following material types are available: "Materials:Standard", "Materials:Specular", "Materials:Basic", "Materials:Skybox". At the moment, custom shaders cannot be created for materials, which will be addressed in a future update.

Methods

Voxels

Description

The voxels system craft.voxels represents a voxel terrain system that is loaded on the fly. This allows for large open-world environments that can be generated procedurally.

Voxel terrain is made up of multiple chunks, which represent small regions of the landscape. Each chunk is generated and meshed in the background automatically.

The initial size of the terrain is set by calling voxels:resize(size), which sets the size of the terrain in chunks. At the moment only one vertical chunk is supported. Each chunk is 16x128x16 voxels by default.

Properties

Name Type Description
coordinates
vec3 The current coordinates of the viewer (in world space). You use this to tell the voxel system where to stream in chunks
visibleRadius
integer The radius of the area to load in (in chunks)

Methods

Name Returns Description
generate(luaString, functionName)
none This function sets the lua string to execute when generating each chunk in the terrain. luaString contains the code to be run, while functionName is the function to use for actual generation. The function must take at least one parameter, which is the chunk (actually a volume component). The function can then set the voxels in that volume to create the terrain.

Examples

-- Main Tab
function setup()
	-- Make sure to include Block Library project as a dependency
	allBlocks = blocks()

	local size = vec3(100,1,100)
	local coordinates = vec3(size.x/2 * 16, 70, size.z/2 * 16)

	-- Set the size of the terrain
	craft.voxels:resize(size)

	-- Set the coordinates at the middle of the terrain
	craft.voxels.coordinates = coordinates

	-- Use the code in another tab to generate the terrain
	craft.voxels:generate(readProjectTab("Generation"), "generateTerrain")

	craft.scene.camera.position = coordinates
	craft.scene.camera.rotation = quat.eulerAngles(45,0,45)
end

-- Generation Tab 
function generateTerrain(chunk)
    cx, cy, cz = chunk:size()
    
    SEA_LEVEL = 40
    
    -- block types as noise sources
    air = craft.noise.const(0)
    dirt = craft.noise.const(chunk:blockID("Dirt"))    
    stone = craft.noise.const(chunk:blockID("Stone"))    
    grass = craft.noise.const(chunk:blockID("Grass"))       
    water = craft.noise.const(chunk:blockID("Water"))       
    sand = craft.noise.const(chunk:blockID("Sand"))           
    
    local n = split(air, grass, SEA_LEVEL)
    n = split(n, dirt, SEA_LEVEL-1)   
    n = split(n, stone, SEA_LEVEL-4)   
    n = warp(n, hills(20))    
    
    chunk:setWithNoise(n)
end

-- take two noise functions and split based on elevation
function split(a,b,depth)
    depth = depth or 64
    
    local s = craft.noise.select()
    s:setSource(0, a)
    s:setSource(1, b)   
    s:setSource(2, craft.noise.gradient()) 
    s:setBounds(1.0 - depth / (cy + 0.0), 1.0)
    
    return s
end

-- warp one noise function using others
function warp(input, d1, d2, d3)

	if d1 and d2 and d3 then
		local zero = craft.noise.const()
	    
	    local displace = craft.noise.displace()
	    displace:setSource(0, input)
	    displace:setSource(1, d1) -- x
	    displace:setSource(2, d2) -- y
	    displace:setSource(3, d3) -- z

        return displace
	else
		local zero = craft.noise.const()
	    
	    local displace = craft.noise.displace()
	    displace:setSource(0, input)
	    displace:setSource(1, zero) -- x
	    displace:setSource(2, d1) -- y
	    displace:setSource(3, zero) -- z

	   return displace
	end
end

-- generic hills (height map style)
function hills(height, offset, frequency, octaves)

	height = height or 10
    offset = offset or 0
	octaves = octaves or 5
	frequency = frequency or 0.25

	local heightNorm = height / (cy + 0.0)

	local shape = craft.noise.perlin()
    shape.octaves = octaves
    shape.frequency = frequency
    
    local shape2D = craft.noise.scale(1,0,1)
    shape2D:setSource(0, shape)

    local shapeFinal = craft.noise.scaleOffset()
    shapeFinal:setSource(0, shape2D)
    shapeFinal.scale = -heightNorm * 0.5
    shapeFinal.offset = -heightNorm - offset/cy ---heightNorm*2   

    return shapeFinal
end

Voxel Generation

An efficient way to generate voxel terrain is to use a noise tree. Craft comes with a variety of noise generation functions that can be combined together. Craft uses the libnoise library.

The most basic form of noise is noise.const, which always returns the same value. Each block type has a fixed ID, which allows us to use constants to represent a particular type of block. If we just use a single constant noise factor we get the following:

function generateTerrain(chunk)
	-- Make terrain a solid block of dirt
	local n = craft.noise.const(chunk:blockID("Dirt"))
	chunk:setWithNoise(n)
end

Noise

Description

Properties

Methods

Block

Description

Properties

Methods

Volume

Description

Properties

Methods

Physics

Description

Properties

Methods

Rigidbody

Description

Constants

Constructors

Properties

Methods

Box

Description

Properties

Methods

Sphere

Description

Properties

Methods

Capsule

Description

Properties

Methods