Skip to Content
defold-typescript
Get startedGuidesAPILibraries
Defold

resource

Functions and constants to access resources.

Functions

resource.atlas(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

Load an atlas and set it to a sprite:

// Load an atlas and set it to a sprite:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_atlas: resource.atlas("/atlas.atlas") },

  init(self) {
    go.set("#sprite", "image", self.my_atlas);
  },
});
go.property("my_atlas", resource.atlas("/atlas.atlas"))
function init(self)
  go.set("#sprite", "image", self.my_atlas)
end

Load an atlas and set it to a gui:

// Load an atlas and set it to a gui:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_atlas: resource.atlas("/atlas.atlas") },

  init(self) {
    go.set("#gui", "textures", self.my_atlas, { key: "my_atlas" });
  },
});
go.property("my_atlas", resource.atlas("/atlas.atlas"))
function init(self)
  go.set("#gui", "textures", self.my_atlas, {key = "my_atlas"})
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

resource.buffer(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

// Set a unique buffer it to a sprite:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_buffer: resource.buffer("/cube.buffer") },

  init(self) {
    go.set("#mesh", "vertices", self.my_buffer);
  },
});
go.property("my_buffer", resource.buffer("/cube.buffer"))
function init(self)
  go.set("#mesh", "vertices", self.my_buffer)
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

resource.create_atlas(path: string, table: resource.Atlas): Hash

This function creates a new atlas resource that can be used in the same way as any atlas created during build time. The path used for creating the atlas must be unique, trying to create a resource at a path that is already registered will trigger an error. If the intention is to instead modify an existing atlas, use the resource.set_atlas function. Also note that the path to the new atlas resource must have a '.texturesetc' extension, meaning "/path/my_atlas" is not a valid path but "/path/my_atlas.texturesetc" is. When creating the atlas, at least one geometry and one animation is required, and an error will be raised if these requirements are not met. A reference to the resource will be held by the collection that created the resource and will automatically be released when that collection is destroyed. Note that releasing a resource essentially means decreasing the reference count of that resource, and not necessarily that it will be deleted.

// Create a backing texture and an atlas
export default defineScript({
  init() {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGBA;
    if (format === undefined) return;
    // create an empty texture
    const tparams = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };
    const my_texture_id = resource.create_texture("/my_texture.texturec", tparams);

    // optionally use resource.set_texture to upload data to texture

    // create an atlas with one animation and one square geometry
    // note that the function doesn't support hashes for the texture,
    // you need to use a string for the texture path here aswell
    const aparams = {
      texture: "/my_texture.texturec",
      animations: [
        {
          id: "my_animation",
          width: 128,
          height: 128,
          frames: [1],
        },
      ],
      geometries: [
        {
          id: "idle0",
          width: 128,
          height: 128,
          pivot_x: 0.5,
          pivot_y: 0.5,
          vertices: [0, 0, 0, 128, 128, 128, 128, 0],
          uvs: [0, 0, 0, 128, 128, 128, 128, 0],
          indices: [0, 1, 2, 0, 2, 3],
        },
      ],
    } satisfies Parameters<typeof resource.create_atlas>[1];
    const my_atlas_id = resource.create_atlas("/my_atlas.texturesetc", aparams);

    // assign the atlas to the 'sprite' component on the same go
    go.set("#sprite", "image", my_atlas_id);
  },
});
function init(self)
    -- create an empty texture
    local tparams = {
        width          = 128,
        height         = 128,
        type           = graphics.TEXTURE_TYPE_2D,
        format         = graphics.TEXTURE_FORMAT_RGBA,
    }
    local my_texture_id = resource.create_texture("/my_texture.texturec", tparams)

    -- optionally use resource.set_texture to upload data to texture

    -- create an atlas with one animation and one square geometry
    -- note that the function doesn't support hashes for the texture,
    -- you need to use a string for the texture path here aswell
    local aparams = {
        texture = "/my_texture.texturec",
        animations = {
            {
                id          = "my_animation",
                width       = 128,
                height      = 128,
                frames      = { 1 }
            }
        },
        geometries = {
            {
                id = 'idle0',
                width = 128,
                height = 128,
                pivot_x = 0.5,
                pivot_y = 0.5,
                vertices  = {
                    0,   0,
                    0,   128,
                    128, 128,
                    128, 0
                },
                uvs = {
                    0,   0,
                    0,   128,
                    128, 128,
                    128, 0
                },
                indices = {0,1,2,0,2,3}
            }
        }
    }
    local my_atlas_id = resource.create_atlas("/my_atlas.texturesetc", aparams)

    -- assign the atlas to the 'sprite' component on the same go
    go.set("#sprite", "image", my_atlas_id)
end

Parameters

  • path: string — The path to the resource.
  • table: resource.Atlas — atlas creation data. ⚠️ frame_start is 1-based; passed to Defold unchanged. ⚠️ frame_end is 1-based; passed to Defold unchanged. ⚠️ frame_start is 1-based; passed to Defold unchanged. ⚠️ frame_end is 1-based; passed to Defold unchanged. ⚠️ frames is 1-based; passed to Defold unchanged. 0️⃣ indices is 0-based; passed to Defold unchanged.

Returns

  • path: Hash — Returns the atlas resource path

resource.create_buffer(path: string, table: resource.BufferCreationParams): Hash

This function creates a new buffer resource that can be used in the same way as any buffer created during build time. The function requires a valid buffer created from either buffer.create or another pre-existing buffer resource. By default, the new resource will take ownership of the buffer lua reference, meaning the buffer will not automatically be removed when the lua reference to the buffer is garbage collected. This behaviour can be overruled by specifying 'transfer_ownership = false' in the argument table. If the new buffer resource is created from a buffer object that is created by another resource, the buffer object will be copied and the new resource will effectively own a copy of the buffer instead. Note that the path to the new resource must have the '.bufferc' extension, "/path/my_buffer" is not a valid path but "/path/my_buffer.bufferc" is. The path must also be unique, attempting to create a buffer with the same name as an existing resource will raise an error.

Create a buffer object and bind it to a buffer resource

// Create a buffer object and bind it to a buffer resource
export default defineScript({
  init() {
    const size = 1;
    const positions = [
      // triangle 1
      size, size, 0,
      -size, -size, 0,
      size, -size, 0,
      // triangle 2
      size, size, 0,
      -size, size, 0,
      -size, -size, 0,
    ];

    const buffer_handle = buffer.create(positions.length, [
      {
        name: hash("position"),
        type: buffer.VALUE_TYPE_FLOAT32,
        count: 3,
      },
    ]);

    const stream = buffer.get_stream(buffer_handle, hash("position"));

    // transfer vertex data to buffer
    positions.forEach((value, k) => {
      stream[k] = value;
    });

    const my_buffer = resource.create_buffer("/my_buffer.bufferc", { buffer: buffer_handle });
    go.set("/go#mesh", "vertices", my_buffer);
  },
});
function init(self)
    local size = 1
    local positions = {
        -- triangle 1
         size,  size, 0,
        -size, -size, 0,
         size, -size, 0,
        -- triangle 2
         size, size,  0,
        -size,  size, 0,
        -size, -size, 0,
    }

    local buffer_handle = buffer.create(#positions, {
        {
            name  = hash("position"),
            type  = buffer.VALUE_TYPE_FLOAT32,
            count = 3
        }
    })

    local stream = buffer.get_stream(buffer_handle, hash("position"))

    -- transfer vertex data to buffer
    for k=1,#positions do
        stream[k] = positions[k]
    end

    local my_buffer = resource.create_buffer("/my_buffer.bufferc", { buffer = buffer_handle })
    go.set("/go#mesh", "vertices", my_buffer)
end

Create a buffer resource from existing resource

// Create a buffer resource from existing resource
export default defineScript({
  init() {
    const res = resource.get_buffer("/my_buffer_path.bufferc");
    // create a cloned buffer resource from another resource buffer
    const buf = resource.create_buffer("/my_cloned_buffer.bufferc", { buffer: res });
    // assign cloned buffer to a mesh component
    go.set("/go#mesh", "vertices", buf);
  },
});
function init(self)
    local res = resource.get_buffer("/my_buffer_path.bufferc")
    -- create a cloned buffer resource from another resource buffer
    local buf = reource.create_buffer("/my_cloned_buffer.bufferc", { buffer = res })
    -- assign cloned buffer to a mesh component
    go.set("/go#mesh", "vertices", buf)
end

Parameters

Returns

  • path: Hash — Returns the buffer resource path

resource.create_sound_data(path: string, options: resource.SoundDataOptions & ({ partial?: false } | ({ partial: true } & Required<Pick<resource.SoundDataOptions, "filesize">>))): Hash

Creates a sound data resource Supported formats are .oggc, .opusc and .wavc

export default defineScript({
  init() {
    // create a new sound resource, given the initial chunk of the file
    const [data] = sys.load_resource("/sounds/music_header.oggc");
    if (data === undefined) {
      return;
    }
    const filesize = 1048576;
    const relative_path = "/a/unique/resource/name.oggc";
    const hash = resource.create_sound_data(relative_path, { data, filesize, partial: true });
    go.set("#music", "sound", hash); // override the previous sound resource
    sound.play("#music"); // start the playing
  },
});
function init(self)
    -- create a new sound resource, given the initial chunk of the file
    local relative_path = "/a/unique/resource/name.oggc"
    local hash = resource.create_sound_data(relative_path, { data = data, filesize = filesize, partial = true })
    go.set("#music", "sound", hash) -- override the previous sound resource
    sound.play("#music") -- start the playing
end

Parameters

Returns

  • path_hash: Hash — the resulting path hash to the resource

resource.create_texture(path: string, table: resource.TextureCreationParams, buffer?: Opaque<"buffer"> & { length: LuaLengthMethod<number> }): Hash

Creates a new texture resource that can be used in the same way as any texture created during build time. The path used for creating the texture must be unique, trying to create a resource at a path that is already registered will trigger an error. If the intention is to instead modify an existing texture, use the resource.set_texture function. Also note that the path to the new texture resource must have a '.texturec' extension, meaning "/path/my_texture" is not a valid path but "/path/my_texture.texturec" is. If the texture is created without a buffer, the pixel data will be blank.

Check whether a texture format is supported by the device:

if (graphics.TEXTURE_FORMAT_RGBA16F !== undefined) {
  // It is safe to use this format.
}
if graphics.TEXTURE_FORMAT_RGBA16F ~= nil then
    -- It is safe to use this format.
end

3D textures are currently only supported on OpenGL and Vulkan adapters. Check whether the device supports 3D textures before using them:

if (graphics.TEXTURE_TYPE_3D !== undefined) {
  // The device and graphics adapter support 3D textures.
}
if graphics.TEXTURE_TYPE_3D ~= nil then
    -- The device and graphics adapter support 3D textures.
end

How to create an 128x128 RGBA texture resource and assign it to a model

// How to create an 128x128 RGBA texture resource and assign it to a model
export default defineScript({
  init() {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGBA;
    if (format === undefined) return;
    const tparams = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };
    const my_texture_id = resource.create_texture("/my_custom_texture.texturec", tparams);
    go.set("#model", "texture0", my_texture_id);
  },
});
function init(self)
    local tparams = {
       width          = 128,
       height         = 128,
       type           = graphics.TEXTURE_TYPE_2D,
       format         = graphics.TEXTURE_FORMAT_RGBA,
   }
   local my_texture_id = resource.create_texture("/my_custom_texture.texturec", tparams)
   go.set("#model", "texture0", my_texture_id)
end

How to create an 128x128 floating point texture (RGBA32F) resource from a buffer object

// How to create an 128x128 floating point texture (RGBA32F) resource from a buffer object
export default defineScript({
  init() {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGBA32F;
    if (format === undefined) return;
    // Create a new buffer with 4 components and FLOAT32 type
    const tbuffer = buffer.create(128 * 128, [{ name: hash("rgba"), type: buffer.VALUE_TYPE_FLOAT32, count: 4 }]);
    const tstream = buffer.get_stream(tbuffer, hash("rgba"));

    // Fill the buffer stream with some float values
    for (let y = 0; y < 128; y++) {
      for (let x = 0; x < 128; x++) {
        const index = y * 128 * 4 + x * 4;
        tstream[index + 0] = 999.0;
        tstream[index + 1] = -1.0;
        tstream[index + 2] = 0.5;
        tstream[index + 3] = 1.0;
      }
    }

    // Create a 2D Texture with a RGBA23F format
    const tparams = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };

    // Note that we pass the buffer as the last argument here!
    const my_texture_id = resource.create_texture("/my_custom_texture.texturec", tparams, tbuffer);

    // assign the texture to a model
    go.set("#model", "texture0", my_texture_id);
  },
});
function init(self)
    -- Create a new buffer with 4 components and FLOAT32 type
    local tbuffer = buffer.create(128 * 128, { {name=hash("rgba"), type=buffer.VALUE_TYPE_FLOAT32, count=4} } )
    local tstream = buffer.get_stream(tbuffer, hash("rgba"))

    -- Fill the buffer stream with some float values
    for y=1,128 do
        for x=1,128 do
            local index = (y-1) * 128 * 4 + (x-1) * 4 + 1
            tstream[index + 0] = 999.0
            tstream[index + 1] = -1.0
            tstream[index + 2] = 0.5
            tstream[index + 3] = 1.0
        end
    end

    -- Create a 2D Texture with a RGBA23F format
    local tparams = {
       width          = 128,
       height         = 128,
       type           = graphics.TEXTURE_TYPE_2D,
       format         = graphics.TEXTURE_FORMAT_RGBA32F,
   }

   -- Note that we pass the buffer as the last argument here!
   local my_texture_id = resource.create_texture("/my_custom_texture.texturec", tparams, tbuffer)

   -- assign the texture to a model
   go.set("#model", "texture0", my_texture_id)
end

How to create a 32x32x32 floating point 3D texture that can be used to generate volumetric data in a compute shader

// How to create a 32x32x32 floating point 3D texture that can be used to generate volumetric data in a compute shader
export default defineScript({
  init() {
    // the engine registers a texture type or format only when the driver supports it
    const type = graphics.TEXTURE_TYPE_IMAGE_3D;
    const format = graphics.TEXTURE_FORMAT_RGBA32F;
    if (type === undefined || format === undefined) return;
    const t_volume = resource.create_texture("/my_backing_texture.texturec", {
      type,
      width: 32,
      height: 32,
      depth: 32,
      format,
      flags: graphics.TEXTURE_USAGE_FLAG_STORAGE + graphics.TEXTURE_USAGE_FLAG_SAMPLE,
    });

    // pass the backing texture to the render script
    msg.post("@render:", "add_textures", [t_volume]);
  },
});
function init(self)
    local t_volume = resource.create_texture("/my_backing_texture.texturec", {
        type   = graphics.TEXTURE_TYPE_IMAGE_3D,
        width  = 32,
        height = 32,
        depth  = 32,
        format = graphics.TEXTURE_FORMAT_RGBA32F,
        flags  = graphics.TEXTURE_USAGE_FLAG_STORAGE + graphics.TEXTURE_USAGE_FLAG_SAMPLE,
    })

    -- pass the backing texture to the render script
    msg.post("@render:", "add_textures", { t_volume })
end

How to create 512x512 texture array with 5 pages.

// How to create 512x512 texture array with 5 pages.
// the engine registers a texture format only when the driver supports it
const format = graphics.TEXTURE_FORMAT_RGB;
if (format !== undefined) {
  const new_tex = resource.create_texture("/runtime/example_array.texturec", {
    type: graphics.TEXTURE_TYPE_2D_ARRAY,
    width: 512,
    height: 512,
    page_count: 5,
    format,
  });
}
        local new_tex = resource.create_texture("/runtime/example_array.texturec", {
            type = graphics.TEXTURE_TYPE_2D_ARRAY,
            width = 512,
            height = 512,
            page_count = 5,
            format = graphics.TEXTURE_FORMAT_RGB,
        })

Parameters

  • path: string — The path to the resource.
  • table: resource.TextureCreationParams — texture creation parameters
  • buffer?: Opaque<"buffer"> & { length: LuaLengthMethod<number> } — optional buffer of precreated pixel data

Returns

  • path: Hash — The path to the resource.

resource.create_texture_async(path: string, table: resource.TextureCreationParams, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } | undefined, callback: (self: unknown, request_id: number, result: resource.TextureCreationResult) => void): LuaMultiReturn<[Hash, number]>

Creates a new texture resource that can be used in the same way as any texture created during build time. The path used for creating the texture must be unique, trying to create a resource at a path that is already registered will trigger an error. If the intention is to instead modify an existing texture, use the resource.set_texture function. Also note that the path to the new texture resource must have a '.texturec' extension, meaning "/path/my_texture" is not a valid path but "/path/my_texture.texturec" is. If the texture is created without a buffer, the pixel data will be blank. The difference between the async version and resource.create_texture is that the texture data will be uploaded in a graphics worker thread. The function will return a resource immediately that contains a 1x1 blank texture which can be used immediately after the function call. When the new texture has been uploaded, the initial blank texture will be deleted and replaced with the new texture. Be careful when using the initial texture handle handle as it will not be valid after the upload has finished.

Check whether a texture format is supported by the device:

if (graphics.TEXTURE_FORMAT_RGBA16F !== undefined) {
  // It is safe to use this format.
}
if graphics.TEXTURE_FORMAT_RGBA16F ~= nil then
    -- It is safe to use this format.
end

3D textures are currently only supported on OpenGL and Vulkan adapters. Check whether the device supports 3D textures before using them:

if (graphics.TEXTURE_TYPE_3D !== undefined) {
  // The device and graphics adapter support 3D textures.
}
if graphics.TEXTURE_TYPE_3D ~= nil then
    -- The device and graphics adapter support 3D textures.
end

Create a texture resource asyncronously with a buffer and a callback

// Create a texture resource asyncronously with a buffer and a callback
function callback(self: unknown, request_id: number, result: resource.TextureCreationResult) {
  // The resource has been updated with a new texture,
  // so we can update other systems with the new handle,
  // or update components to use the resource if we want
  const tinfo = resource.get_texture_info(result.path);
  msg.post("@render:", "set_backing_texture", { handle: tinfo.handle });
}

export default defineScript({
  init() {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGBA;
    if (format === undefined) return;
    // Create a texture resource async
    const tparams = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };

    // Create a new buffer with 4 components
    const tbuffer = buffer.create(tparams.width * tparams.height, [{ name: hash("rgba"), type: buffer.VALUE_TYPE_UINT8, count: 4 }]);
    const tstream = buffer.get_stream(tbuffer, hash("rgba"));

    // Fill the buffer stream with some float values
    for (let y = 0; y < tparams.width; y++) {
      for (let x = 0; x < tparams.height; x++) {
        const index = y * 128 * 4 + x * 4;
        tstream[index + 0] = 255;
        tstream[index + 1] = 0;
        tstream[index + 2] = 255;
        tstream[index + 3] = 255;
      }
    }
    // create the texture
    const [tpath, request_id] = resource.create_texture_async("/my_texture.texturec", tparams, tbuffer, callback);
    // at this point you can use the resource as-is, but note that the texture will be a blank 1x1 texture
    // that will be removed once the new texture has been updated
    go.set("#model", "texture0", tpath);
  },
});
function callback(self, request_id, result)
    -- The resource has been updated with a new texture,
    -- so we can update other systems with the new handle,
    -- or update components to use the resource if we want
    local tinfo = resource.get_texture_info(result.path)
    msg.post("@render:", "set_backing_texture", tinfo.handle)
end
function init(self)
    -- Create a texture resource async
    local tparams = {
        width          = 128,
        height         = 128,
        type           = graphics.TEXTURE_TYPE_2D,
        format         = graphics.TEXTURE_FORMAT_RGBA,
    }

    -- Create a new buffer with 4 components
    local tbuffer = buffer.create(tparams.width * tparams.height, { {name=hash("rgba"), type=buffer.VALUE_TYPE_UINT8, count=4} } )
    local tstream = buffer.get_stream(tbuffer, hash("rgba"))

    -- Fill the buffer stream with some float values
    for y=1,tparams.width do
        for x=1,tparams.height do
            local index = (y-1) * 128 * 4 + (x-1) * 4 + 1
            tstream[index + 0] = 255
            tstream[index + 1] = 0
            tstream[index + 2] = 255
            tstream[index + 3] = 255
        end
    end
    -- create the texture
    local tpath, request_id = resource.create_texture_async("/my_texture.texturec", tparams, tbuffer, callback)
    -- at this point you can use the resource as-is, but note that the texture will be a blank 1x1 texture
    -- that will be removed once the new texture has been updated
    go.set("#model", "texture0", tpath)
end

Create a texture resource asynchronously with a callback that does nothing

// Create a texture resource asyncronously without handling its completion
export default defineScript({
  init() {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGBA;
    if (format === undefined) return;
    // Create a texture resource async
    const tparams = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };

    // Create a new buffer with 4 components
    const tbuffer = buffer.create(tparams.width * tparams.height, [{ name: hash("rgba"), type: buffer.VALUE_TYPE_UINT8, count: 4 }]);
    const tstream = buffer.get_stream(tbuffer, hash("rgba"));

    // Fill the buffer stream with some float values
    for (let y = 0; y < tparams.width; y++) {
      for (let x = 0; x < tparams.height; x++) {
        const index = y * 128 * 4 + x * 4;
        tstream[index + 0] = 255;
        tstream[index + 1] = 0;
        tstream[index + 2] = 255;
        tstream[index + 3] = 255;
      }
    }
    // create the texture
    // the binding requires a callback function, so pass one that does nothing
    const [tpath, request_id] = resource.create_texture_async("/my_texture.texturec", tparams, tbuffer, () => {});
    // at this point you can use the resource as-is, but note that the texture will be a blank 1x1 texture
    // that will be removed once the new texture has been updated
    go.set("#model", "texture0", tpath);
  },
});
function init(self)
    -- Create a texture resource async
    local tparams = {
        width          = 128,
        height         = 128,
        type           = graphics.TEXTURE_TYPE_2D,
        format         = graphics.TEXTURE_FORMAT_RGBA,
    }

    -- Create a new buffer with 4 components
    local tbuffer = buffer.create(tparams.width * tparams.height, { {name=hash("rgba"), type=buffer.VALUE_TYPE_UINT8, count=4} } )
    local tstream = buffer.get_stream(tbuffer, hash("rgba"))

    -- Fill the buffer stream with some float values
    for y=1,tparams.width do
        for x=1,tparams.height do
            local index = (y-1) * 128 * 4 + (x-1) * 4 + 1
            tstream[index + 0] = 255
            tstream[index + 1] = 0
            tstream[index + 2] = 255
            tstream[index + 3] = 255
        end
    end
    -- create the texture
    local tpath, request_id = resource.create_texture_async("/my_texture.texturec", tparams, tbuffer)
    -- at this point you can use the resource as-is, but note that the texture will be a blank 1x1 texture
    -- that will be removed once the new texture has been updated
    go.set("#model", "texture0", tpath)
end

Parameters

  • path: string — The path to the resource.
  • table: resource.TextureCreationParams — texture creation parameters
  • buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } | undefined — optional buffer of precreated pixel data
  • callback: (self: unknown, request_id: number, result: resource.TextureCreationResult) => void — callback function invoked when the texture is created

Returns

  • path: Hash — The path to the texture resource.
  • request_id: number — The request id for the async request.

resource.font(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

Load a font and set it to a label:

// Load a font and set it to a label:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_font: resource.font("/font.font") },

  init(self) {
    go.set("#label", "font", self.my_font);
  },
});
go.property("my_font", resource.font("/font.font"))
function init(self)
  go.set("#label", "font", self.my_font)
end

Load a font and set it to a gui:

// Load a font and set it to a gui:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_font: resource.font("/font.font") },

  init(self) {
    go.set("#gui", "fonts", self.my_font, { key: "my_font" });
  },
});
go.property("my_font", resource.font("/font.font"))
function init(self)
  go.set("#gui", "fonts", self.my_font, {key = "my_font"})
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

resource.get_atlas(path: Hash | string): resource.AtlasData

Returns the atlas data for an atlas

Parameters

  • path: Hash | string — The path to the atlas resource

Returns

  • data: resource.AtlasData — atlas data. ⚠️ frames is 1-based; passed to Defold unchanged. 0️⃣ indices is 0-based; passed to Defold unchanged.

resource.get_buffer(path: Hash | string): Opaque<"buffer"> & { length: LuaLengthMethod<number> }

gets the buffer from a resource

// How to get the data from a buffer
export default defineScript({
  init() {
    const res_path = go.get<mesh.Properties>()("#mesh", "vertices");
    const buf = resource.get_buffer(res_path);
    const stream_positions = buffer.get_stream(buf, "position");

    for (let i = 0; i < stream_positions.length(); i++) {
      print(i, stream_positions[i]);
    }
  },
});
function init(self)

    local res_path = go.get("#mesh", "vertices")
    local buf = resource.get_buffer(res_path)
    local stream_positions = buffer.get_stream(buf, "position")

    for i=1,#stream_positions do
        print(i, stream_positions[i])
    end
end

Parameters

  • path: Hash | string — The path to the resource

Returns

  • buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } — The resource buffer

resource.get_render_target_info(path: Hash | string | Opaque<"render_target"> | number): resource.RenderTargetInfo

Gets render target info from a render target resource path or a render target handle

Get the metadata from a render target resource

// Get the metadata from a render target resource
export default defineScript({
  init() {
    const info = resource.get_render_target_info("/my_render_target.render_targetc");
    // the info table contains meta data about all the render target attachments
    // so it's not necessary to use resource.get_texture here, but we do it here
    // just to show that it's possible:
    const info_attachment_1 = resource.get_texture_info(info.attachments[0]!.handle);
  },
});
function init(self)
    local info = resource.get_render_target_info("/my_render_target.render_targetc")
    -- the info table contains meta data about all the render target attachments
    -- so it's not necessary to use resource.get_texture here, but we do it here
    -- just to show that it's possible:
    local info_attachment_1 = resource.get_texture_info(info.attachments[1].handle)
end

Get a texture attachment from a render target and set it on a model component

// Get a texture attachment from a render target and set it on a model component
export default defineScript({
  init() {
    const info = resource.get_render_target_info("/my_render_target.render_targetc");
    const attachment = info.attachments[0]!.texture!;
    // you can also get texture info from the 'texture' field, since it's a resource hash
    const texture_info = resource.get_texture_info(attachment);
    go.set("#model", "texture0", attachment);
  },
});
function init(self)
    local info = resource.get_render_target_info("/my_render_target.render_targetc")
    local attachment = info.attachments[1].texture
    -- you can also get texture info from the 'texture' field, since it's a resource hash
    local texture_info = resource.get_texture_info(attachment)
    go.set("#model", "texture0", attachment)
end

Parameters

  • path: Hash | string | Opaque<"render_target"> | number — The path to the resource or a render target handle

Returns

resource.get_text_metrics(2 overloads): resource.TextMetrics

Gets the text metrics from a font. Rich text markup is measured using its visible text and font sizes. If markup cannot be parsed, the text is measured literally. Inline sprites reserve their specified dimensions, or one em by default.

  1. (url: Hash | string, text: string)

  2. (url: Hash | string, text: string, options: resource.TextMetricsOptions)

    Parameters

    • url: Hash | string — the font to get the (unscaled) metrics from
    • text: string — text to measure
    • options: resource.TextMetricsOptions — optional text-metric options

    Returns

export default defineScript({
  init() {
    const font = go.get<label.Properties>()("#label", "font");
    const metrics = resource.get_text_metrics(font, "The quick brown fox\n jumps over the lazy dog");
    pprint(metrics);
  },
});
function init(self)
    local font = go.get("#label", "font")
    local metrics = resource.get_text_metrics(font, "The quick brown fox\n jumps over the lazy dog")
    pprint(metrics)
end

resource.get_texture_info(path: Hash | string | Opaque<"texture"> | number): resource.TextureInfo

Gets texture info from a texture resource path or a texture handle

Create a new texture and get the metadata from it

// Create a new texture and get the metadata from it
export default defineScript({
  init() {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGBA;
    if (format === undefined) return;
    // create an empty texture
    const tparams = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };

    const my_texture_path = resource.create_texture("/my_texture.texturec", tparams);
    const my_texture_info = resource.get_texture_info(my_texture_path);

    // my_texture_info now contains
    // {
    //      handle = <the-numeric-handle>,
    //      width = 128,
    //      height = 128,
    //      depth = 1
    //      mipmaps = 1,
    //      page_count = 1,
    //      type = graphics.TEXTURE_TYPE_2D,
    //      flags = graphics.TEXTURE_USAGE_FLAG_SAMPLE
    // }
  },
});
function init(self)
    -- create an empty texture
    local tparams = {
        width          = 128,
        height         = 128,
        type           = graphics.TEXTURE_TYPE_2D,
        format         = graphics.TEXTURE_FORMAT_RGBA,
    }

    local my_texture_path = resource.create_texture("/my_texture.texturec", tparams)
    local my_texture_info = resource.get_texture_info(my_texture_path)

    -- my_texture_info now contains
    -- {
    --      handle = <the-numeric-handle>,
    --      width = 128,
    --      height = 128,
    --      depth = 1
    --      mipmaps = 1,
    --      page_count = 1,
    --      type = graphics.TEXTURE_TYPE_2D,
    --      flags = graphics.TEXTURE_USAGE_FLAG_SAMPLE
    -- }
end

Get the meta data from an atlas resource

// Get the meta data from an atlas resource
export default defineScript({
  init() {
    const my_atlas_info = resource.get_atlas("/my_atlas.a.texturesetc");
    const my_texture_info = resource.get_texture_info(my_atlas_info.texture);

    // my_texture_info now contains the information about the texture that is backing the atlas
  },
});
function init(self)
    local my_atlas_info   = resource.get_atlas("/my_atlas.a.texturesetc")
    local my_texture_info = resource.get_texture_info(my_atlas_info.texture)

    -- my_texture_info now contains the information about the texture that is backing the atlas
end

Parameters

  • path: Hash | string | Opaque<"texture"> | number — The path to the resource or a texture handle

Returns

resource.load(path: string): Opaque<"buffer"> & { length: LuaLengthMethod<number> }

Loads the resource data for a specific resource.

// read custom resource data into buffer
const buffer = resource.load("/resources/datafile");
-- read custom resource data into buffer
local buffer = resource.load("/resources/datafile")

In order for the engine to include custom resources in the build process, you need to specify them in the "game.project" settings file:

// [project]
// title = My project
// version = 0.1
// custom_resources = resources/,assets/level_data.json
[project]
title = My project
version = 0.1
custom_resources = resources/,assets/level_data.json

Parameters

  • path: string — The path to the resource

Returns

  • buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } — Returns the buffer stored on disc

resource.material(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

Load a material and set it to a sprite:

// Load a material and set it to a sprite:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_material: resource.material("/material.material") },

  init(self) {
    go.set("#sprite", "material", self.my_material);
  },
});
go.property("my_material", resource.material("/material.material"))
function init(self)
  go.set("#sprite", "material", self.my_material)
end

Load a material resource and update a named material with the resource:

// Load a material resource and update a named material with the resource:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_material: resource.material("/material.material") },

  init(self) {
    go.set("#gui", "materials", self.my_material, { key: "my_material" });
  },
});
go.property("my_material", resource.material("/material.material"))
function init(self)
  go.set("#gui", "materials", self.my_material, {key = "my_material"})
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

resource.release(path: Hash | string): void

Release a resource. This is a potentially dangerous operation, releasing resources currently being used can cause unexpected behaviour.

Parameters

  • path: Hash | string — The path to the resource.

resource.render_target(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

// Set a render target color attachment as a model texture:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_render_target: resource.render_target("/rt.render_target") },

  init(self) {
    const rt_info = resource.get_render_target_info(self.my_render_target);
    go.set("#model", "texture0", rt_info.attachments[0]!.texture!);
  },
});
go.property("my_render_target", resource.render_target("/rt.render_target"))
function init(self)
  local rt_info = resource.get_render_target_info(self.my_render_target)
  go.set("#model", "texture0", rt_info.attachments[1].texture)
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

resource.set(path: string | Hash, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }): void

Sets the resource data for a specific resource

// Assuming the folder "/res" is added to the project custom resources:
// load a texture resource and set it on a sprite
const buffer = resource.load("/res/new.texturec");
resource.set(go.get<sprite.Properties>()("#sprite", "texture0"), buffer);
-- load a texture resource and set it on a sprite
local buffer = resource.load("/res/new.texturec")
resource.set(go.get("#sprite", "texture0"), buffer)

Parameters

  • path: string | Hash — The path to the resource
  • buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } — The buffer of precreated data, suitable for the intended resource type

resource.set_atlas(path: Hash | string, table: resource.Atlas): void

Sets the data for a specific atlas resource. Setting new atlas data is specified by passing in a texture path for the backing texture of the atlas, a list of geometries and a list of animations that map to the entries in the geometry list. The geometry entries are represented by three lists: vertices, uvs and indices that together represent triangles that are used in other parts of the engine to produce render objects from. Vertex and uv coordinates for the geometries are expected to be in pixel coordinates where 0,0 is the top left corner of the texture. There is no automatic padding or margin support when setting custom data, which could potentially cause filtering artifacts if used with a material sampler that has linear filtering. If that is an issue, you need to calculate padding and margins manually before passing in the geometry data to this function.

Add a new animation to an existing atlas

// Add a new animation to an existing atlas
export default defineScript({
  init() {
    const data = resource.get_atlas("/main/my_atlas.a.texturesetc");
    const my_animation = {
      id: "my_new_animation",
      width: 128,
      height: 128,
      frame_start: 1,
      frame_end: 6,
      playback: go.PLAYBACK_LOOP_PINGPONG,
      fps: 8,
      flip_vertical: false,
      flip_horizontal: false,
    };
    // set_atlas takes each animation's frames as a non-empty list
    const animations = data.animations.flatMap((animation) => {
      // an animation described by frame_start/frame_end passes through as-is
      if (!("frames" in animation)) return [animation];
      const [first, ...rest] = (animation.frames as number[] | undefined) ?? [];
      return first === undefined ? [] : [{ ...animation, frames: [first, ...rest] as [number, ...number[]] }];
    });
    // set_atlas needs at least one animation and one geometry
    const [first_geometry, ...geometries] = data.geometries;
    if (first_geometry !== undefined) {
      resource.set_atlas("/main/my_atlas.a.texturesetc", {
        ...data,
        animations: [my_animation, ...animations],
        geometries: [first_geometry, ...geometries],
      });
    }
  },
});
function init(self)
    local data = resource.get_atlas("/main/my_atlas.a.texturesetc")
    local my_animation = {
        id          = "my_new_animation",
        width       = 128,
        height      = 128,
        frame_start = 1,
        frame_end   = 6,
        playback    = go.PLAYBACK_LOOP_PINGPONG,
        fps         = 8
    }
    table.insert(data.animations, my_animation)
    resource.set_atlas("/main/my_atlas.a.texturesetc", data)
end

Sets atlas data for a 256x256 texture with a single animation being rendered as a quad

// Sets atlas data for a 256x256 texture with a single animation being rendered as a quad
export default defineScript({
  init() {
    const params = {
      texture: "/main/my_256x256_texture.texturec",
      animations: [
        {
          id: "my_animation",
          width: 256,
          height: 256,
          frames: [1],
        },
      ],
      geometries: [
        {
          vertices: [0, 0, 0, 256, 256, 256, 256, 0],
          uvs: [0, 0, 0, 256, 256, 256, 256, 0],
          indices: [0, 1, 2, 0, 2, 3],
        },
      ],
    } satisfies Parameters<typeof resource.set_atlas>[1];
    resource.set_atlas("/main/test.a.texturesetc", params);
  },
});
function init(self)
    local params = {
        texture = "/main/my_256x256_texture.texturec",
        animations = {
            {
                id          = "my_animation",
                width       = 256,
                height      = 256,
                frames      = { 1 }
            }
        },
        geometries = {
            {
                vertices = {
                    0,   0,
                    0,   256,
                    256, 256,
                    256, 0
                },
                uvs = {
                    0, 0,
                    0, 256,
                    256, 256,
                    256, 0
                },
                indices = { 0,1,2,0,2,3 }
            }
        }
    }
    resource.set_atlas("/main/test.a.texturesetc", params)
end

Parameters

  • path: Hash | string — The path to the atlas resource
  • table: resource.Atlas — atlas data. ⚠️ frame_start is 1-based; passed to Defold unchanged. ⚠️ frame_end is 1-based; passed to Defold unchanged. ⚠️ frame_start is 1-based; passed to Defold unchanged. ⚠️ frame_end is 1-based; passed to Defold unchanged. ⚠️ frames is 1-based; passed to Defold unchanged. 0️⃣ indices is 0-based; passed to Defold unchanged.

resource.set_buffer(path: Hash | string, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }, table?: resource.BufferUpdateOptions): void

Sets the buffer of a resource. By default, setting the resource buffer will either copy the data from the incoming buffer object to the buffer stored in the destination resource, or make a new buffer object if the sizes between the source buffer and the destination buffer stored in the resource differs. In some cases, e.g performance reasons, it might be beneficial to just set the buffer object on the resource without copying or cloning. To achieve this, set the transfer_ownership flag to true in the argument table. Transferring ownership from a lua buffer to a resource with this function works exactly the same as resource.create_buffer: the destination resource will take ownership of the buffer held by the lua reference, i.e the buffer will not automatically be removed when the lua reference to the buffer is garbage collected. Note: When setting a buffer with transfer_ownership = true, the currently bound buffer in the resource will be destroyed.

// How to set the data from a buffer
function fill_stream(stream: { [index: number]: number }, verts: number[]) {
  verts.forEach((value, key) => {
    stream[key] = value;
  });
}

export default defineScript({
  init() {
    const res_path = go.get<mesh.Properties>()("#mesh", "vertices");

    const positions = [
      1, -1, 0,
      1, 1, 0,
      -1, -1, 0,
    ];

    const num_verts = positions.length / 3;

    // create a new buffer
    let buf = buffer.create(num_verts, [{ name: hash("position"), type: buffer.VALUE_TYPE_FLOAT32, count: 3 }]);

    buf = resource.get_buffer(res_path);
    const stream_positions = buffer.get_stream(buf, "position");

    fill_stream(stream_positions, positions);

    resource.set_buffer(res_path, buf);
  },
});
local function fill_stream(stream, verts)
    for key, value in ipairs(verts) do
        stream[key] = verts[key]
    end
end

function init(self)

    local res_path = go.get("#mesh", "vertices")

    local positions = {
         1, -1, 0,
         1,  1, 0,
         -1, -1, 0
    }

    local num_verts = #positions / 3

    -- create a new buffer
    local buf = buffer.create(num_verts, {
        { name = hash("position"), type=buffer.VALUE_TYPE_FLOAT32, count = 3 }
    })

    local buf = resource.get_buffer(res_path)
    local stream_positions = buffer.get_stream(buf, "position")

    fill_stream(stream_positions, positions)

    resource.set_buffer(res_path, buf)
end

Parameters

  • path: Hash | string — The path to the resource
  • buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } — The resource buffer
  • table?: resource.BufferUpdateOptions — optional buffer-resource update options

resource.set_sound(path: Hash | string, buffer: string): void

Update internal sound resource (wavc/oggc/opusc) with new data

Parameters

  • path: Hash | string — The path to the resource
  • buffer: string — A lua string containing the binary sound data

resource.set_texture(path: Hash | string, table: resource.TextureUpdateParams, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }): void

Sets the pixel data for a specific texture.

Check whether a texture format is supported by the device:

if (graphics.TEXTURE_FORMAT_RGBA16F !== undefined) {
  // It is safe to use this format.
}
if graphics.TEXTURE_FORMAT_RGBA16F ~= nil then
    -- It is safe to use this format.
end

Check whether the device supports 3D textures before using them:

if (graphics.TEXTURE_TYPE_3D !== undefined) {
  // The device and graphics adapter support 3D textures.
}
if graphics.TEXTURE_TYPE_3D ~= nil then
    -- The device and graphics adapter support 3D textures.
end

How to set all pixels of an atlas

// How to set all pixels of an atlas
export default defineScript({
  init() {
    const height = 128;
    const width = 128;
    const buf = buffer.create(width * height, [{ name: hash("rgb"), type: buffer.VALUE_TYPE_UINT8, count: 3 }]);
    const stream = buffer.get_stream(buf, hash("rgb"));

    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        const index = y * width * 3 + x * 3;
        stream[index + 0] = 0xff;
        stream[index + 1] = 0x80;
        stream[index + 2] = 0x10;
      }
    }

    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGB;
    if (format !== undefined) {
      const resource_path = go.get<model.Properties>()("#model", "texture0");
      const args = { width, height, type: graphics.TEXTURE_TYPE_2D, format, num_mip_maps: 1 };
      resource.set_texture(resource_path, args, buf);
    }
    return { buffer: buf, stream };
  },
});
function init(self)
  self.height = 128
  self.width = 128
  self.buffer = buffer.create(self.width * self.height, { {name=hash("rgb"), type=buffer.VALUE_TYPE_UINT8, count=3} } )
  self.stream = buffer.get_stream(self.buffer, hash("rgb"))

  for y=1,self.height do
      for x=1,self.width do
          local index = (y-1) * self.width * 3 + (x-1) * 3 + 1
          self.stream[index + 0] = 0xff
          self.stream[index + 1] = 0x80
          self.stream[index + 2] = 0x10
      end
  end

  local resource_path = go.get("#model", "texture0")
  local args = { width=self.width, height=self.height, type=graphics.TEXTURE_TYPE_2D, format=graphics.TEXTURE_FORMAT_RGB, num_mip_maps=1 }
  resource.set_texture( resource_path, args, self.buffer )
end

How to update a specific region of an atlas by using the x,y values. Assumes the already set atlas is a 128x128 texture.

// How to update a specific region of an atlas by using the x,y values. Assumes the already set atlas is a 128x128 texture.
export default defineScript({
  init() {
    const x = 16;
    const y = 16;
    const height = 128 - x * 2;
    const width = 128 - y * 2;
    const buf = buffer.create(width * height, [{ name: hash("rgb"), type: buffer.VALUE_TYPE_UINT8, count: 3 }]);
    const stream = buffer.get_stream(buf, hash("rgb"));

    for (let row = 0; row < height; row++) {
      for (let col = 0; col < width; col++) {
        const index = row * width * 3 + col * 3;
        stream[index + 0] = 0xff;
        stream[index + 1] = 0x80;
        stream[index + 2] = 0x10;
      }
    }

    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGB;
    if (format !== undefined) {
      const resource_path = go.get<model.Properties>()("#model", "texture0");
      const args = { width, height, x, y, type: graphics.TEXTURE_TYPE_2D, format, num_mip_maps: 1 };
      resource.set_texture(resource_path, args, buf);
    }
    return { buffer: buf, stream };
  },
});
function init(self)
  self.x = 16
  self.y = 16
  self.height = 128 - self.x * 2
  self.width = 128 - self.y * 2
  self.buffer = buffer.create(self.width * self.height, { {name=hash("rgb"), type=buffer.VALUE_TYPE_UINT8, count=3} } )
  self.stream = buffer.get_stream(self.buffer, hash("rgb"))

  for y=1,self.height do
      for x=1,self.width do
          local index = (y-1) * self.width * 3 + (x-1) * 3 + 1
          self.stream[index + 0] = 0xff
          self.stream[index + 1] = 0x80
          self.stream[index + 2] = 0x10
      end
  end

  local resource_path = go.get("#model", "texture0")
  local args = { width=self.width, height=self.height, x=self.x, y=self.y, type=graphics.TEXTURE_TYPE_2D, format=graphics.TEXTURE_FORMAT_RGB, num_mip_maps=1 }
  resource.set_texture(resource_path, args, self.buffer )
end

Update a texture from a buffer resource

// Update a texture from a buffer resource
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_buffer: resource.buffer("/my_default_buffer.buffer") },

  init(self) {
    // the engine registers a texture format only when the driver supports it
    const format = graphics.TEXTURE_FORMAT_RGB;
    if (format === undefined) return;
    const resource_path = go.get<model.Properties>()("#model", "texture0");
    // the "my_buffer" resource is expected to hold 128 * 128 * 3 bytes!
    const args = {
      width: 128,
      height: 128,
      type: graphics.TEXTURE_TYPE_2D,
      format,
    };
    // Note that the extra resource.get_buffer call is a requirement here
    // since the "self.my_buffer" is just pointing to a buffer resource path
    // and not an actual buffer object or buffer resource.
    resource.set_texture(resource_path, args, resource.get_buffer(self.my_buffer));
  },
});
go.property("my_buffer", resource.buffer("/my_default_buffer.buffer"))

function init(self)
    local resource_path = go.get("#model", "texture0")
    -- the "my_buffer" resource is expected to hold 128 * 128 * 3 bytes!
    local args = {
         width  = 128,
         height = 128,
         type   = graphics.TEXTURE_TYPE_2D,
         format = graphics.TEXTURE_FORMAT_RGB
     }
    -- Note that the extra resource.get_buffer call is a requirement here
    -- since the "self.my_buffer" is just pointing to a buffer resource path
    -- and not an actual buffer object or buffer resource.
    resource.set_texture(resource_path, args, resource.get_buffer(self.my_buffer))
end

Update an existing 3D texture from a lua buffer

// Update an existing 3D texture from a lua buffer
export default defineScript({
  init() {
    // the engine registers a texture type or format only when the driver supports it
    const type = graphics.TEXTURE_TYPE_IMAGE_3D;
    const format = graphics.TEXTURE_FORMAT_RGBA32F;
    if (type === undefined || format === undefined) return;
    // create a buffer that can hold the data of a 8x8x8 texture
    const tbuffer = buffer.create(8 * 8 * 8, [{ name: hash("rgba"), type: buffer.VALUE_TYPE_FLOAT32, count: 4 }]);
    const tstream = buffer.get_stream(tbuffer, hash("rgba"));

    // populate the buffer with some data
    let index = 0;
    for (let z = 1; z <= 8; z++) {
      for (let y = 1; y <= 8; y++) {
        for (let x = 1; x <= 8; x++) {
          tstream[index + 0] = x;
          tstream[index + 1] = y;
          tstream[index + 2] = z;
          tstream[index + 3] = 1.0;
          index = index + 4;
        }
      }
    }

    const t_args = {
      type,
      width: 8,
      height: 8,
      depth: 8,
      format,
    };

    // This expects that the texture resource "/my_3d_texture.texturec" already exists
    // and is a 3D texture resource. To create a dynamic 3D texture resource
    // use the "resource.create_texture" function.
    resource.set_texture("/my_3d_texture.texturec", t_args, tbuffer);
  },
});
function init(self)
    -- create a buffer that can hold the data of a 8x8x8 texture
    local tbuffer = buffer.create(8 * 8 * 8, { {name=hash("rgba"), type=buffer.VALUE_TYPE_FLOAT32, count=4} } )
    local tstream = buffer.get_stream(tbuffer, hash("rgba"))

    -- populate the buffer with some data
    local index = 1
    for z=1,8 do
        for y=1,8 do
            for x=1,8 do
                tstream[index + 0] = x
                tstream[index + 1] = y
                tstream[index + 2] = z
                tstream[index + 3] = 1.0
                index = index + 4
            end
        end
    end

    local t_args = {
        type   = graphics.TEXTURE_TYPE_IMAGE_3D,
        width  = 8,
        height = 8,
        depth  = 8,
        format = graphics.TEXTURE_FORMAT_RGBA32F
    }

    -- This expects that the texture resource "/my_3d_texture.texturec" already exists
    -- and is a 3D texture resource. To create a dynamic 3D texture resource
    -- use the "resource.create_texture" function.
    resource.set_texture("/my_3d_texture.texturec", t_args, tbuffer)
end

Update texture 2nd array page with loaded texture from png

// Update texture 2nd array page with loaded texture from png
const tex_path = "/bundle_resources/page_02.png";
const [data] = sys.load_resource(tex_path);
// the engine registers a texture format only when the driver supports it
const format = graphics.TEXTURE_FORMAT_RGB;
if (data !== undefined && format !== undefined) {
  const buf = image.load_buffer(data);
  if (buf !== undefined) {
    // new_tex is the resource handle of a texture created via resource.create_texture
    const new_tex = resource.create_texture("/my_array_texture.texturec", {
      type: graphics.TEXTURE_TYPE_2D_ARRAY,
      width: buf.width,
      height: buf.height,
      page_count: 2,
      format,
    });
    resource.set_texture(
      new_tex,
      {
        type: graphics.TEXTURE_TYPE_2D_ARRAY,
        width: buf.width,
        height: buf.height,
        page: 1,
        format,
      },
      buf.buffer,
    );
    go.set("#mesh", "texture0", new_tex);
  }
}
    -- new_tex is resource handle of texture which was created via resource.create_resource
    local tex_path = "/bundle_resources/page_02.png"
    local data = sys.load_resource(tex_path)
    local buf = image.load_buffer(data)
    resource.set_texture(new_tex, {
        type = graphics.TEXTURE_TYPE_2D_ARRAY,
        width = buf.width,
        height = buf.height,
        page = 1,
        format = graphics.TEXTURE_FORMAT_RGB
    }, buf.buffer)
    go.set("#mesh", "texture0", new_tex)

Parameters

  • path: Hash | string — The path to the resource
  • table: resource.TextureUpdateParams — texture update parameters. 0️⃣ page is 0-based; passed to Defold unchanged. 0️⃣ mipmap is 0-based; passed to Defold unchanged.
  • buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } — The buffer of precreated pixel data To update a cube map texture you need to pass in six times the amount of data via the buffer, since a cube map has six sides! 3D textures are currently only supported on OpenGL and Vulkan adapters.

resource.texture(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

// Load a texture and set it to a model:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_texture: resource.texture("/texture.png") },

  init(self) {
    go.set("#model", "texture0", self.my_texture);
  },
});
go.property("my_texture", resource.texture("/texture.png"))
function init(self)
  go.set("#model", "texture0", self.my_texture)
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

resource.tile_source(path?: string): Hash

Constructor-like function with two purposes:

  • Load the specified resource as part of loading the script
  • Create a resource reference that resolves to the hashed path of the run-time resource

This function can only be called within go.property function calls.

// Load tile source and set it to a tile map:
export default defineScript({
  // Never call `go.property` yourself: the transpiler emits the chunk-scope
  // registration from this field, and only this field types the property onto `self`.
  properties: { my_tile_source: resource.tile_source("/tilesource.tilesource") },

  init(self) {
    go.set("#tilemap", "tile_source", self.my_tile_source);
  },
});
go.property("my_tile_source", resource.tile_source("/tilesource.tilesource"))
function init(self)
  go.set("#tilemap", "tile_source", self.my_tile_source)
end

Parameters

  • path?: string — optional resource path string to the resource

Returns

  • resource: Hash — a reference to the binary version of the resource

Types

interface resource.Animation { id: string; width: number; height: number; frames?: number[]; frame_start?: number; frame_end?: number; playback?: go.Playback; fps?: number; flip_vertical?: boolean; flip_horizontal?: boolean; }

interface resource.AnimationData { id: string; width: number; height: number; frames: number[]; playback: go.Playback; fps: number; flip_vertical: boolean; flip_horizontal: boolean; }

interface resource.Atlas { texture: string | Hash; animations: [Omit<resource.Animation, "frame_start" | "frame_end"> & ({ frames: [number, ...number[]] } | { frame_start: number; frame_end: number }), ...(Omit<resource.Animation, "frame_start" | "frame_end"> & ({ frames: [number, ...number[]] } | { frame_start: number; frame_end: number }))[]]; geometries: [resource.Geometry, ...resource.Geometry[]]; }

interface resource.AtlasData { texture: string | Hash; animations: resource.AnimationData[]; geometries: resource.GeometryData[]; }

interface resource.BufferCreationParams { buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }; transfer_ownership?: boolean; }

interface resource.BufferUpdateOptions { transfer_ownership?: boolean; }

interface resource.Geometry { id?: string; width?: number; height?: number; pivot_x?: number; pivot_y?: number; rotated?: boolean; vertices: number[]; uvs: number[]; indices: number[]; }

interface resource.GeometryData { width: number; height: number; pivot_x: number; pivot_y: number; rotated: boolean; vertices: number[]; uvs: number[]; indices: number[]; }

interface resource.RenderTargetAttachmentInfo { handle: Opaque<"texture">; width: number; height: number; depth: number; page_count: number; mipmaps: number; flags: graphics.TextureUsageFlag | number; type: graphics.TextureType; buffer_type: graphics.BufferType; texture?: Hash; }

interface resource.RenderTargetInfo { handle: Opaque<"render_target">; sample_count: number; attachments: resource.RenderTargetAttachmentInfo[]; }

interface resource.SoundDataOptions { data: string | Opaque<"buffer">; filesize?: number; partial?: boolean; }

interface resource.TextMetrics { width: number; height: number; max_ascent: number; max_descent: number; }

interface resource.TextMetricsOptions { width?: number; leading?: number; tracking?: number; line_break?: boolean; }

interface resource.TextureCreationParams { type: graphics.TextureType; width: number; height: number; depth?: number; page_count?: number; format: graphics.TextureFormat; flags?: graphics.TextureUsageFlag | number; max_mipmaps?: number; compression_type?: graphics.CompressionType; }

interface resource.TextureCreationResult { path: Hash; }

interface resource.TextureInfo { handle: Opaque<"texture">; width: number; height: number; depth: number; page_count: number; mipmaps: number; flags: graphics.TextureUsageFlag | number; type: graphics.TextureType; }

interface resource.TextureUpdateParams { type: graphics.TextureType; width: number; height: number; depth?: number; format: graphics.TextureFormat; x?: number; y?: number; z?: number; page?: number; mipmap?: number; compression_type?: graphics.CompressionType; }

On this page

Functionsresource.atlas(path?: string): Hashresource.buffer(path?: string): Hashresource.create_atlas(path: string, table: resource.Atlas): Hashresource.create_buffer(path: string, table: resource.BufferCreationParams): Hashresource.create_sound_data(path: string, options: resource.SoundDataOptions & ({ partial?: false } | ({ partial: true } & Required<Pick<resource.SoundDataOptions, "filesize">>))): Hashresource.create_texture(path: string, table: resource.TextureCreationParams, buffer?: Opaque<"buffer"> & { length: LuaLengthMethod<number> }): Hashresource.create_texture_async(path: string, table: resource.TextureCreationParams, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> } | undefined, callback: (self: unknown, request_id: number, result: resource.TextureCreationResult) => void): LuaMultiReturn<[Hash, number]>resource.font(path?: string): Hashresource.get_atlas(path: Hash | string): resource.AtlasDataresource.get_buffer(path: Hash | string): Opaque<"buffer"> & { length: LuaLengthMethod<number> }resource.get_render_target_info(path: Hash | string | Opaque<"render_target"> | number): resource.RenderTargetInforesource.get_text_metrics(2 overloads): resource.TextMetricsresource.get_texture_info(path: Hash | string | Opaque<"texture"> | number): resource.TextureInforesource.load(path: string): Opaque<"buffer"> & { length: LuaLengthMethod<number> }resource.material(path?: string): Hashresource.release(path: Hash | string): voidresource.render_target(path?: string): Hashresource.set(path: string | Hash, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }): voidresource.set_atlas(path: Hash | string, table: resource.Atlas): voidresource.set_buffer(path: Hash | string, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }, table?: resource.BufferUpdateOptions): voidresource.set_sound(path: Hash | string, buffer: string): voidresource.set_texture(path: Hash | string, table: resource.TextureUpdateParams, buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }): voidresource.texture(path?: string): Hashresource.tile_source(path?: string): HashTypesinterface resource.Animation { id: string; width: number; height: number; frames?: number[]; frame_start?: number; frame_end?: number; playback?: go.Playback; fps?: number; flip_vertical?: boolean; flip_horizontal?: boolean; }interface resource.AnimationData { id: string; width: number; height: number; frames: number[]; playback: go.Playback; fps: number; flip_vertical: boolean; flip_horizontal: boolean; }interface resource.Atlas { texture: string | Hash; animations: [Omit<resource.Animation, "frame_start" | "frame_end"> & ({ frames: [number, ...number[]] } | { frame_start: number; frame_end: number }), ...(Omit<resource.Animation, "frame_start" | "frame_end"> & ({ frames: [number, ...number[]] } | { frame_start: number; frame_end: number }))[]]; geometries: [resource.Geometry, ...resource.Geometry[]]; }interface resource.AtlasData { texture: string | Hash; animations: resource.AnimationData[]; geometries: resource.GeometryData[]; }interface resource.BufferCreationParams { buffer: Opaque<"buffer"> & { length: LuaLengthMethod<number> }; transfer_ownership?: boolean; }interface resource.BufferUpdateOptions { transfer_ownership?: boolean; }interface resource.Geometry { id?: string; width?: number; height?: number; pivot_x?: number; pivot_y?: number; rotated?: boolean; vertices: number[]; uvs: number[]; indices: number[]; }interface resource.GeometryData { width: number; height: number; pivot_x: number; pivot_y: number; rotated: boolean; vertices: number[]; uvs: number[]; indices: number[]; }interface resource.RenderTargetAttachmentInfo { handle: Opaque<"texture">; width: number; height: number; depth: number; page_count: number; mipmaps: number; flags: graphics.TextureUsageFlag | number; type: graphics.TextureType; buffer_type: graphics.BufferType; texture?: Hash; }interface resource.RenderTargetInfo { handle: Opaque<"render_target">; sample_count: number; attachments: resource.RenderTargetAttachmentInfo[]; }interface resource.SoundDataOptions { data: string | Opaque<"buffer">; filesize?: number; partial?: boolean; }interface resource.TextMetrics { width: number; height: number; max_ascent: number; max_descent: number; }interface resource.TextMetricsOptions { width?: number; leading?: number; tracking?: number; line_break?: boolean; }interface resource.TextureCreationParams { type: graphics.TextureType; width: number; height: number; depth?: number; page_count?: number; format: graphics.TextureFormat; flags?: graphics.TextureUsageFlag | number; max_mipmaps?: number; compression_type?: graphics.CompressionType; }interface resource.TextureCreationResult { path: Hash; }interface resource.TextureInfo { handle: Opaque<"texture">; width: number; height: number; depth: number; page_count: number; mipmaps: number; flags: graphics.TextureUsageFlag | number; type: graphics.TextureType; }interface resource.TextureUpdateParams { type: graphics.TextureType; width: number; height: number; depth?: number; format: graphics.TextureFormat; x?: number; y?: number; z?: number; page?: number; mipmap?: number; compression_type?: graphics.CompressionType; }