Skip to content

DynamicMesh

Library · DynamicMesh · server and client scripts

DynamicMesh builds a 3D shape from vertices and triangles while the game runs, such as generated terrain. A dynamic mesh exists only on the client that builds it. Reserve room with :SetCounts(vertices, indices), copy count items from byte offset in data to mesh position start with :WriteVertices(data, offset, start, count) and :WriteIndices(data, offset, start, count), and show the mesh on an entity with :Apply(target). A mesh takes up to 60000 vertices and 60000 indices; a client has room for 64 dynamic meshes, which share one pool of 262144 vertices and 786432 indices.

A vertex is eight 32-bit floats, 32 bytes:

Byte offset Value
0, 4, 8 Position X, Y, Z, in units, relative to the entity
12, 16 Texture coordinate U, V, from 0 to 1
20, 24, 28 Normal X, Y, Z: a direction of length 1 out of the surface

An index is a 32-bit unsigned integer that names a vertex, counting from 0. Each triangle takes three indices, counterclockwise as seen from the side that shows.

new

Function
new() -> DynamicMesh

DynamicMesh.new creates an empty mesh.

Example

-- Client script: a 4 by 4 unit floor tile.
local mesh = DynamicMesh.new()
mesh:SetCounts(4, 6)

local vBuf = buffer.create(4 * 32)
local function writeVertex(
    idx: number,
    x: number,
    y: number,
    z: number,
    u: number,
    v: number,
    nx: number,
    ny: number,
    nz: number
)
    local base = idx * 32
    buffer.writef32(vBuf, base + 0, x)
    buffer.writef32(vBuf, base + 4, y)
    buffer.writef32(vBuf, base + 8, z)
    buffer.writef32(vBuf, base + 12, u)
    buffer.writef32(vBuf, base + 16, v)
    buffer.writef32(vBuf, base + 20, nx)
    buffer.writef32(vBuf, base + 24, ny)
    buffer.writef32(vBuf, base + 28, nz)
end

writeVertex(0, -2, 0, -2, 0, 0, 0, 1, 0)
writeVertex(1, 2, 0, -2, 1, 0, 0, 1, 0)
writeVertex(2, 2, 0, 2, 1, 1, 0, 1, 0)
writeVertex(3, -2, 0, 2, 0, 1, 0, 1, 0)

local iBuf = buffer.create(6 * 4)
local indices = { 0, 2, 1, 0, 3, 2 }
for i, vertIdx in indices do
    buffer.writeu32(iBuf, (i - 1) * 4, vertIdx)
end

mesh:WriteVertices(vBuf, 0, 0, 4)
mesh:WriteIndices(iBuf, 0, 0, 6)

local platform = World.Spawn({
    Position = Vector3.new(0, 1, 10),
    Mesh = mesh.Asset,
})