API reference
Materials and textures
A material says how a surface looks: PBR (lit) or unlit, up to six textures, and a few numbers such as base color and roughness. Every material is one row in a GPU table, and every texture gets a slot in one big bindless texture array. One shader reads both for all objects.
In short
createMaterial(MaterialType::PBR, {albedo})makes a material; the vector order isPbrSlot.- Change a material: copy it with
getMaterial, edit,updateMaterial. Every object that uses it changes in the next frame. loadTextureloads in the background. Itsformatnames the slot: color textures are sRGB (the default); normal, metallic-roughness and occlusion maps must beR8G8B8A8_UNORM. A .ktx2 file stays block-compressed on the GPU (texture compression).- An entity waits, undrawn, until all its textures are loaded.
- Limits:
EngineConfig::maxMaterialsmaterials alive at once (4096 by default),RendererConfig::maxBindlessTexturestexture slots (16384 by default, lowered to what the device allows). A destroyed material's row and a destroyed texture's slot are reused.
TextureHandle. It sees slot numbers in the material row. A slot of INVALID_TEXTURE_INDEX (0xFFFFFFFF) means "no texture": the shader uses the factor alone.1Create a material
enum class MaterialType { PBR, UNLIT, TERRAIN, VECTOR, POINTS, GLYPHS, COUNT };
- PBR
- Lit by the scene's lights (metallic-roughness model). Reads the texture slots listed in the slot table.
- UNLIT
- Only the base color (texture × factor), not lit. It goes through the tone map like every other color (Tone mapping).
- TERRAIN
- A terrain tile: the shared grid lifted by
Material::terrain's heights, then lit asPBRwith the albedo (the imagery) as base color. Made bycreateTerrainTile(Terrain from height maps). - VECTOR
- Lines, polygons and points (vector features), styled by
Material::vector, unlit. It is alwaysBLENDand double-sided, whateverupdateMaterialsets: its smooth edges are blended, in the Transparent pass, in itsdrawOrder(Vector lines, polygons and points). - POINTS
- A point cloud chunk (point clouds), styled by
Material::points, unlit. A chunk is drawn only with aPOINTSmaterial, by a run of its own after the opaque and cut-out draws; on a triangle mesh it shades asPBR.alphaModeanddoubleSideddo not apply (Point clouds). - GLYPHS
- A glyph chunk (glyphs): its shape drawn once per glyph, lit as
PBRwith itsparams, the base color times each glyph's color or its scalar throughMaterial::glyphs' colormap. A chunk is drawn only with aGLYPHSmaterial;doubleSidedturns off the back-face culling of every glyph draw of the scene,alphaModedoes not apply (Instanced glyphs). - COUNT
- Not a type; it counts the values.
MaterialHandle createMaterial(MaterialType type, std::vector<TextureHandle> textures = {}, bool doubleSided = false);
Creates a material with the default values below and writes its row. Each valid texture without a bindless slot gets one; a texture that already has a slot keeps it, so materials can share textures. Entities that use the material can be drawn from the next frame on.
- type
PBR,UNLITorTERRAIN(whose heights you then set interrainwithupdateMaterial, or letcreateTerrainTiledo it all).- textures
- In
PbrSlotorder: albedo, metallic, roughness, normal, occlusion, emissive. Leave the end out, or pass{}for an empty slot. Entries after the sixth are ignored. Textures that still load are fine. - doubleSided
- True: back faces are drawn too (no culling) and lit with the flipped normal.
Returns an invalid handle and logs an error when EngineConfig::maxMaterials materials are alive (the default material is one of them); the error names the field. destroyMaterial gives a row back.
// examples/00_hello_scene
rasm::TextureHandle albedo = engine.loadTexture("models/obj/bunny/bunny-atlas.jpg");
rasm::MaterialHandle material =
engine.createMaterial(rasm::MaterialType::PBR, {albedo});
// Your own normal map: data, so UNORM. It goes in slot 3 (NORMAL),
// so slots 1 and 2 stay empty.
rasm::TextureHandle normal =
engine.loadTexture("brick_normal.png", rasm::Format::R8G8B8A8_UNORM);
std::vector<rasm::TextureHandle> textures = {albedo, {}, {}, normal};
rasm::MaterialHandle brick = engine.createMaterial(rasm::MaterialType::PBR, textures);
Default values
params after createMaterial: white and opaque, not metallic, fully rough, so a texture alone decides the color. Index a value with static_cast<uint32_t>(PbrParam::ROUGHNESS); a color is three floats from its index, the albedo four.Entities without a material, and sub-meshes whose material is missing, use the default material that the engine makes at start. It follows glTF: white, metallic 1, roughness 1.
2The Material record
struct Material
{
const char* name{};
MaterialHandle handle{};
MaterialType type{};
TextureHandle textures[MAX_TEXTURE_SLOTS];
uint32_t texCoords[MAX_TEXTURE_SLOTS];
TextureTransform textureTransforms[MAX_TEXTURE_SLOTS];
float params[MAX_PARAM_SLOTS];
bool doubleSided{};
AlphaMode alphaMode{};
float alphaCutoff = 0.5f;
BlendMethod blendMethod = BlendMethod::SORTED;
TerrainMaterial terrain = {};
VectorMaterial vector = {};
PointMaterial points = {};
GlyphMaterial glyphs = {};
};
- name
- A label: "pbr", "unlit", or "default". The engine keeps only the pointer, so point it at a string that lives as long as the engine (a string literal).
- handle
- The material's own handle.
updateMaterialkeeps the right one, whatever you put here. - type
PBRorUNLIT.- textures
- One texture per
PbrSlot; an invalid handle means none. - texCoords
- Which UV set (0, 1 or 2) each texture uses. Default 0. A value of 3 or more uses set 0.
- textureTransforms
- An offset, rotation and scale of each texture's UVs (
TextureTransform).METALLIC's is the metallic-roughness texture's;ROUGHNESS's is not read. - params
- The numbers, indexed by
PbrParam(diagram above). All are linear values. - doubleSided
- Draw back faces too.
- alphaMode
- Solid, cut-out or see-through (
AlphaMode). DefaultNONE: solid. - alphaCutoff
- For
MASK: no pixel where alpha is below it. Default 0.5. - blendMethod
- For
BLEND: sorted, weighted or additive (BlendMethod). DefaultSORTED. AGLYPHSmaterial is always weighted, aVECTORone sorted. - vector
- For
VECTORonly: the style (VectorMaterial).textures[ALBEDO]is the icon atlas of points built with icons. - points
- For
POINTSonly: the points' style (PointMaterial). - glyphs
- For
GLYPHSonly: how the glyphs are colored (GlyphMaterial). - terrain
- For
TERRAINonly: the tile's heights (TerrainMaterial). The imagery istextures[ALBEDO], and its part of the imagetextureTransforms[ALBEDO].
The flat params array is easy to index wrongly; docs/code_review.md plans a typed struct (C9).
struct TerrainMaterial
{
TextureHandle heights;
float heightScale = 1.0f;
float heightOffset = 0.0f;
float minHeight = 0.0f;
float maxHeight = 0.0f;
float skirt = 0.0f;
double sphereRadius = 0.0;
};
- heights
- An
R16_UNORMorR32_SFLOATtexture (another format is dropped with an error) of (cells + 3)² samples, cells being those of the entity's grid: the grid's points and a border of one sample from the neighbours, so normals match across edges. A material that uses it waits for it like for any texture;destroyTexturetakes it away (the tile is then flat). - heightScale, heightOffset
- Metres =
heightOffset+heightScale× sample, where anR16_UNORMsample is its integer (0 to 65535) and anR32_SFLOATone its value. With a power-of-two scale and an offset that is a multiple of it, neighbour tiles get bit-equal edges. - minHeight, maxHeight
- The lowest and highest heights in metres: the tile's box (
getTerrainTransform). The shader usesminHeighttoo, so change it together with the entity's transform. - skirt
- Metres the skirt hangs below the tile's edges, to hide cracks next to tiles of other levels. At least the coarser tile's geometric error.
- sphereRadius
- 0: flat. Else the tile bends down by d² / 2R at d metres from its centre, to sit on a planet (6 371 000 for the Earth): 5 cm off the sphere at 100 km.
struct VectorMaterial
{
glm::vec4 color = glm::vec4(1.0f);
float width = 1.0f;
VectorUnit widthUnit = VectorUnit::PIXELS;
VectorFacing facing = VectorFacing::SCREEN;
float dashLength = 0.0f;
float gapLength = 0.0f;
glm::vec4 outlineColor = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
float outlineWidth = 0.0f;
int32_t drawOrder = 0;
VectorDepth depth = VectorDepth::TESTED;
FontHandle font;
PointColorMode colorMode = PointColorMode::COLOR;
TextureHandle colormap;
ScalarRange range = {};
};
A layer's style. Every feature is at least one pixel wide; a thinner one keeps one pixel and fades by its coverage, so it neither vanishes nor shimmers.
- color
- Linear RGB and straight alpha, times the vertex colors (a line's points' colors,
addVectorLines). - width, widthUnit
- A line's width or a point's diameter, in pixels on screen (
VectorUnit::PIXELS) or metres in the world (VectorUnit::METRES). Polygons have none. - facing
VectorFacing::SCREEN: spread across the screen, never foreshortened.VectorFacing::GROUND: in the ground's plane under the feature (its up), lying on the ground.- dashLength, gapLength
- In
widthUnit; both above 0 for dashes. In pixels they follow the pixel's size at each vertex. - outlineColor, outlineWidth
- A band along a line's or point's edge, inside
width: a road's casing, a marker's ring. - drawOrder
- −127 to 127: blended draws of a lower order are drawn first; the scene's other see-through draws sort at 0, by depth. It holds while the GPU blend sort runs; with frozen culling (
setCullingFrozen) the blended draws go in list order. - depth
VectorDepth::TESTED: hidden behind what is in front, nearer than the ground it lies on by 1/4096 of its distance, whatever the projection.VectorDepth::OVERLAY: over everything, never occlusion culled.- font
- Labels (
addVectorLabels): the font whose atlas their glyphs come from (createFont).widthis then the text's size (an em),outlineColorandoutlineWidthits halo, which reaches at most half the atlas's distance range;facinganddashLengthdo not apply: text always faces the screen. Without a live font, labels draw nothing. - colorMode, colormap, range
- Data lines:
COLOR(the default) multiplies by the points' colors.SCALARreads each point's value as a scalar, given toaddVectorLines'scalars, interpolates it along the line and maps it per pixel throughrangeandcolormap(createColormap), timescolor; a value outside a range without clamp draws nothing, and a line without values iscolor(Values through a colormap).
// examples/25_vector_map: roads 7 px wide with a 1.5 px casing.
rasm::Material values = engine.getMaterial(material);
values.vector = {.color = glm::vec4(1.0f, 0.75f, 0.25f, 1.0f), .width = 7.0f, .outlineColor = glm::vec4(0.55f, 0.32f, 0.08f, 1.0f), .outlineWidth = 1.5f, .drawOrder = -10};
engine.updateMaterial(material, values);
enum class VectorUnit : uint32_t { PIXELS, METRES };
enum class VectorFacing : uint32_t { SCREEN, GROUND };
enum class VectorDepth : uint32_t { TESTED, OVERLAY };
The choices of VectorMaterial: VectorUnit for the width and dashes, VectorFacing for the plane a width spreads in, VectorDepth for the depth test.
enum class PbrSlot { ALBEDO, METALLIC, ROUGHNESS, NORMAL, OCCLUSION, EMISSIVE, COUNT };
Index into textures and texCoords. MAX_TEXTURE_SLOTS = 6 (PbrSlot::COUNT).
| Slot | Format | What the shader reads |
|---|---|---|
ALBEDO | R8G8B8A8_SRGB | RGBA × albedo factor × the vertex color. Alpha counts only with MASK or BLEND. |
METALLIC | R8G8B8A8_UNORM | The glTF metallic-roughness texture: G × roughness factor, B × metallic factor. |
ROUGHNESS | R8G8B8A8_UNORM | Nothing: roughness comes from the METALLIC texture's G. glTF import puts the same texture in both slots. |
NORMAL | R8G8B8A8_UNORM | Tangent-space normal, scaled by NORMAL_SCALE. Uses the vertex tangent, or builds one from the UVs. |
OCCLUSION | R8G8B8A8_UNORM | R, mixed in by OCCLUSION_STRENGTH. It darkens only the ambient light. |
EMISSIVE | R8G8B8A8_SRGB | RGB × emissive factor × emissive strength, added to the result. The factor alone glows without a texture. |
UNLIT materials read only ALBEDO. The format column is a rule: a data texture in an sRGB format gives wrong values, and nothing checks it.
enum class PbrParam : uint32_t
{
ALBEDO = 0, // vec4
METALLIC = 4, // float
ROUGHNESS = 5, // float
NORMAL_SCALE = 6, // float
OCCLUSION_STRENGTH = 7, // float
EMISSIVE_FACTOR = 8, // vec3
EMISSIVE_STRENGTH = 11, // float
COUNT = 12,
};
Offsets into params. MAX_PARAM_SLOTS = 12 (PbrParam::COUNT). Roughness is clamped to 0.045 – 1 and metallic to 0 – 1 in the shader. The albedo's fourth float is its alpha (glTF's base color alpha). EMISSIVE_STRENGTH multiplies the emissive factor, so a glow can pass 1 (glTF KHR_materials_emissive_strength).
enum class PointShape : uint32_t
{
SQUARE,
ROUND,
SPHERE,
};
enum class PointSizeMode : uint32_t
{
FIXED,
ADAPTIVE,
};
enum class PointColorMode : uint32_t
{
COLOR,
SCALAR,
};
struct PointMaterial
{
glm::vec4 color = glm::vec4(1.0f);
float size = 2.0f;
VectorUnit sizeUnit = VectorUnit::PIXELS;
PointShape shape = PointShape::ROUND;
PointColorMode colorMode = PointColorMode::COLOR;
TextureHandle colormap;
ScalarRange range = {};
float density = 2.0f;
PointSizeMode sizeMode = PointSizeMode::FIXED;
float maxSize = 8.0f;
};
The style of point cloud chunks (Point clouds). Each point is drawn as one triangle cut to its shape, unlit.
- color
- Linear RGB, times the point's color or its colormap color. Points are opaque: alpha 0 hides them, any other alpha draws them whole, and the points' own colors' alpha is not read.
- size, sizeUnit
- The diameter in pixels (the same at every distance) or metres; at least one pixel.
- shape
SQUARE;ROUND, a disc, smooth-edged with MSAA;SPHERE, a disc that writes a sphere's depth, so points meet as balls would. Points under 3 pixels are drawn square.- colorMode
PointColorModealso colors glyphs and data lines.COLOR: the chunk's own colors (white without them).SCALAR: each point's value throughrangeandcolormap(coloralone without either).- colormap, range
- A colormap from
createColormap, and the values it spans (ScalarRange). - density
- Level of detail: a chunk draws the first
density× D² / a points of its order (D its sphere's diameter on screen, a a point's area in pixels, π/4 of the square for a round point). 1 leaves about 0.3 % of a flat surface empty, 2 none; 0 draws every point. - sizeMode, maxSize
FIXED: every point issize.ADAPTIVE: a point grows, up tomaxSizepixels, where its chunk's points no longer cover the grounddensitytimes atsize: from that spacing on screen on, and faster, so near the camera they cover it about 4 times and a sparse sample still closes. The spacing is the chunk's (PointCloudChunkDesc::spacing); a finer chunk over a point takes it back tosize(PointChunkLod). Points that already cover keepsize, so far chunks stay on the compute path; a near chunk whose points grow past 2 pixels is drawn by triangles (Adaptive point size).
const rasm::MaterialHandle material = engine.createMaterial(rasm::MaterialType::POINTS);
rasm::Material values = engine.getMaterial(material);
values.points = {.size = 2.0f, .colorMode = rasm::PointColorMode::SCALAR, .colormap = engine.createColormap(rasm::ColormapPreset::TURBO), .range = {.min = -20.0f, .max = 50.0f}};
engine.updateMaterial(material, values);
struct GlyphMaterial
{
PointColorMode colorMode = PointColorMode::COLOR;
TextureHandle colormap;
ScalarRange range = {};
};
How a GLYPHS material colors its glyphs (Instanced glyphs). The shape is lit as PBR: params give its roughness and metallic, and the albedo factor multiplies each glyph's color. With alphaMode BLEND the glyphs are see-through, always by weighted blending: their alpha is the albedo factor's times the glyph color's (examples/31_oit).
- colorMode
COLOR: the chunk's own colors (GlyphChunkDesc::colors), white without them.SCALAR: each glyph's scalar throughrangeandcolormap; a glyph whose scalar is outside a range without clamp is not drawn.- colormap, range
- A colormap from
createColormap, and the values it spans (ScalarRange, linear or logarithmic).
// examples/30_glyphs: arrows colored by the flow's speed.
const rasm::MaterialHandle material = engine.createMaterial(rasm::MaterialType::GLYPHS);
rasm::Material values = engine.getMaterial(material);
values.params[static_cast<uint32_t>(rasm::PbrParam::ROUGHNESS)] = 0.45f;
values.glyphs = {.colorMode = rasm::PointColorMode::SCALAR, .colormap = engine.createColormap(rasm::ColormapPreset::VIRIDIS), .range = {.min = 0.0f, .max = 9.2f}};
engine.updateMaterial(material, values);
enum class AlphaMode : uint32_t
{
NONE,
MASK,
BLEND,
};
How a material uses its alpha (albedo factor × texture × vertex color), glTF's alphaMode. The transparency guide explains each.
- NONE
- Solid; alpha is ignored. This is glTF's
OPAQUE(that name is a macro in<windows.h>). - MASK
- A cut-out: no pixel where alpha <
alphaCutoff, solid elsewhere. Leaves, fences, decals with hard edges. Its shadow has the same holes. - BLEND
- See-through: drawn after everything else, mixed with what is behind by its alpha, and not written to depth. Glass, smoke, water. How it is mixed is the material's
blendMethod: sorted back to front by default. Its shadow is as dense as its alpha.
Changing it with updateMaterial moves the material's entities to another draw run in the next frame.
enum class BlendMethod : uint32_t
{
SORTED,
WEIGHTED,
ADDITIVE,
};
How a BLEND material's draws go over what is behind them (Material::blendMethod). The weighted blended transparency guide explains the weighted and additive methods.
- SORTED
- The default. Drawn back to front, a draw at a time, over everything else: exact between draws, but not inside one draw, and nested or crossing objects can pop as the camera moves. For labels, UI, map layers with a draw order and a few panes of glass.
- WEIGHTED
- Weighted blended order-independent transparency: drawn in any order, at a fixed cost a pixel, with no popping. The coverage (how much of the background shows) is exact; the color is a mean of the layers weighted toward the near ones. For dense see-through data: nested iso-surfaces, volume slices, see-through CAD parts. Weighted surfaces go under the sorted ones: a sorted surface behind a weighted one is still drawn over it, so use one method for see-through things that overlap each other. A
GLYPHSmaterial withAlphaMode::BLENDis always weighted. - ADDITIVE
- Adds its light (color × alpha) and hides nothing, in any order: glows, density and X-ray views. Drawn after the weighted surfaces and before the sorted ones; it casts no shadow.
A pick (PickDesc::minAlpha) hits the nearest weighted or additive surface whose alpha is at least minAlpha. On a GPU without the independentBlend feature, weighted and additive materials are drawn sorted, with a warning. VECTOR materials are always sorted.
rasm::Material material = engine.getMaterial(handle);
material.alphaMode = rasm::AlphaMode::BLEND;
material.blendMethod = rasm::BlendMethod::WEIGHTED;
engine.updateMaterial(handle, material);
struct TextureTransform
{
glm::vec2 offset = glm::vec2(0.0f);
float rotation = 0.0f;
glm::vec2 scale = glm::vec2(1.0f);
};
Moves a texture on the surface (glTF KHR_texture_transform): the UVs are scaled, then turned by rotation radians, then moved by offset. The default changes nothing. Tiling a texture 4 times is a scale of 4; a texture atlas uses scale and offset to pick its part.
auto values = engine.getMaterial(floor);
values.textureTransforms[static_cast<uint32_t>(rasm::PbrSlot::ALBEDO)].scale = glm::vec2(4.0f);
engine.updateMaterial(floor, values);
3Read and change a material
- Copy it.
getMaterialreturns a reference into the engine's list. Copy it into a local variable (auto values = ...): the reference can move when another material is created. - Edit the copy. Change factors, textures, the type or
doubleSided. - Call
updateMaterial. It replaces the whole record. New textures get bindless slots now, and the row is rewritten in CPU memory. - Next
beginFrame. The row is uploaded, so every entity that uses the material shows the change in that frame. It costs one row, however many entities use it. - If a new texture still loads, the entities that use the material are not drawn until it finishes, so nothing is drawn half-loaded. A changed
doubleSidedoralphaModerebuilds the draw lists of their scenes.
// examples/03_instances: one material; the 10 spinning cubes and up to
// 2,000 spawned cubes that use it change color every frame.
auto values = engine.getMaterial(pulse);
const auto albedo = static_cast<uint32_t>(rasm::PbrParam::ALBEDO);
values.params[albedo] = 0.5f + 0.5f * std::sin(t);
values.params[albedo + 1] = 0.5f + 0.5f * std::sin(t + 2.1f);
values.params[albedo + 2] = 0.5f + 0.5f * std::sin(t + 4.2f);
engine.updateMaterial(pulse, values);
const Material& getMaterial(const MaterialHandle& handle);
The material's current values. An invalid handle returns the default material. A handle that looks valid but is unknown logs an error and also returns the default material.
void destroyMaterial(MaterialHandle material);
Destroys the material. What used it falls back from the next frame on: an entity made with it uses its mesh's material or the default one, and a glTF sub-mesh that used it uses its entity's material. Their instance rows are rewritten, and the material's row goes to the next material at once. Its textures stay: they are yours, or the mesh's that imported them. The default material is refused.
Nothing is searched when no entity uses the material (destroy the entities first); otherwise every entity is checked once.
void updateMaterial(MaterialHandle material, const Material& values);
Replaces the material's values (steps above). Every entity and glTF sub-mesh that uses it changes in the next frame.
- material
- The material to change. Invalid: logs "Invalid material handle for updating material." and does nothing.
- values
- The whole new record. Its
handlefield is ignored.
4Textures
At the call
Reads only the image header (width, height), creates the texture with that size, and returns its handle. You can put it in a material at once.
Later
A load worker decodes the pixels to RGBA8 and makes their mip levels, or reads and transcodes a .ktx2 file, whose levels come from the file. A later beginFrame copies the levels into the texture, under the per-frame load budget. Then isLoaded is true and waiting entities are drawn.
TextureHandle loadTexture(const std::string& path, Format format = Format::R8G8B8A8_SRGB);
Starts loading a .png, .jpg or .jpeg image, or a .ktx2 file. Images with fewer channels are expanded to RGBA. An AssetLoader call; an Engine has it too, for its own loader.
- path
- Relative to
EngineConfig::assetRoot, or absolute. The extension is checked in lower case only. - format
- The slot the texture is for.
R8G8B8A8_SRGB(default) for a color slot: albedo and emissive.R8G8B8A8_UNORMfor a data slot: normal, metallic-roughness and occlusion maps. Any other format logs "loadTexture takes R8G8B8A8_SRGB for a color slot or R8G8B8A8_UNORM for a data slot." and returns an invalid handle.
An image is uploaded in exactly that format. A .ktx2 file gets the best GPU format the device has for the slot and the file's channels, which getTextureDesc then reports:
| Slot, channels in the file | Format, best first |
|---|---|
color (R8G8B8A8_SRGB), any | BC7_SRGB, ASTC_4x4_SRGB, ETC2_R8G8B8A8_SRGB, R8G8B8A8_SRGB |
data (R8G8B8A8_UNORM), 3 or 4 | BC7_UNORM, ASTC_4x4_UNORM, ETC2_R8G8B8A8_UNORM, R8G8B8A8_UNORM |
| data, 2 (a normal map's x and y) | BC5_UNORM, EAC_R11G11_UNORM, R8G8B8A8_UNORM with z computed |
| data, 1 | BC4_UNORM, EAC_R11_UNORM, R8G8B8A8_UNORM |
A Basis file (ETC1S or UASTC) is transcoded on the worker; any other KTX2 file keeps its own format, read as sRGB or UNORM by the slot, and fails if the device can't sample it. The file's mips are used. A Basis file without mips becomes RGBA8 with mips made on the worker, and logs a warning that names the file and the fix (ktx create --generate-mipmap).
loads in the background The same path with the same format returns the same handle. The same file as sRGB and as UNORM gives two textures.
| Problem | When | Result |
|---|---|---|
| Wrong format, unknown extension, or a header that cannot be read (missing file) | at the call | error logged, invalid handle |
| A KTX2 file the device can't sample (a non-Basis format it lacks), or that is not a 2D texture | at the call | error logged, invalid handle |
| The pixels do not decode | in a later beginFrame | error logged, the texture stays plain white (a flat normal for a two-channel format); isLoaded becomes true |
bool isLoaded(TextureHandle texture) const;
True when the texture's pixels are uploaded (also after a failed decode, which leaves it white). False while it loads and for an invalid handle. A createTexture texture is always loaded; a glTF import's is loaded once filled. A Renderer method: the renderer marks the textures a loader makes (loadingTextures) and never reads the loader.
5Bindless textures
All textures that shaders can sample sit in one descriptor set: an array of RendererConfig::maxBindlessTextures slots (16384 by default), binding 0 of set 0, seen by every shader stage, compute included. Materials fill it for you. You need these functions only for your own shaders, like the full-screen passes of examples/01_render_graph/main.cpp:
// Slang: the array the engine binds
[[vk::binding(0, 0)]]
Sampler2D gTextures[];
// C++: find the slot, then pass it in a push constant
const rasm::TextureHandle texture = engine.getRenderTargetTexture(rtHandle);
uint32_t textureIndex = engine.getBindlessTextureIndex(texture);
ctx.bindDescriptorSet(commandBuffer, overlayPipeline,
engine.getBindlessDescriptorSet(), 0);
ctx.pushConstants(commandBuffer, overlayPipeline, &textureIndex, sizeof(textureIndex), 0);
| Who adds textures | Sampler |
|---|---|
createMaterial, updateMaterial | LINEAR_REPEAT |
| glTF import | from the glTF sampler (see below) |
createRenderTarget (one slot per color texture) | LINEAR_CLAMP |
the engine, for each D32_SFLOAT depth texture of a render target or the window, with EngineConfig::occlusionCulling; always for a depth-only target and a target with a MOTION_FORMAT color | NEAREST_CLAMP |
getUiTexture, for a loaded texture that has no slot yet | LINEAR_REPEAT |
the UI, with EngineConfig::ui, for ImGui's own textures (its font atlas); it reuses the slot of a UI texture it destroys | LINEAR_CLAMP |
you, with addBindlessTexture | your choice |
uint32_t addBindlessTexture(const DescriptorSetHandle& bindlessSet, const TextureHandle& texture, SamplerType sampler = SamplerType::LINEAR_REPEAT, uint32_t slot = MAX_BINDLESS_TEXTURES);
Writes the texture into a slot of the bindless set, with one of the shared samplers. The slot is usable at once.
- bindlessSet
- Pass
getBindlessDescriptorSet(). - texture
- Any texture created as sampled.
- sampler
- Filter and edge mode, see
SamplerType. - slot
MAX_BINDLESS_TEXTURES(the default): the texture's own slot if it has one, else a free slot. A number below the set's slot count: that slot, replacing what was there; the texture that held it loses it.- returns
- The slot, or
UINT32_MAXon error ("Failed to add bindless texture." is logged): all 1024 slots held or waiting for the GPU, a bad slot or sampler, or an unknown or destroyed texture.
A texture holds one slot: a second call without a slot returns it unchanged, since a frame in flight may sample it (a different sampler logs an error; make a second texture for it). The slot is freed with the texture (destroyTexture), once no frame in flight samples it, and then reused.
uint32_t getBindlessTextureIndex(const TextureHandle& texture);
The texture's slot in the bindless set, or UINT32_MAX if it was never added. For a render target, ask with getRenderTargetTexture (or getRenderTargetDepthTexture for its depth) every frame, because a history target has a texture per frame slot.
enum class SamplerType
{
LINEAR_REPEAT,
LINEAR_MIRRORED_REPEAT,
LINEAR_CLAMP,
NEAREST_REPEAT,
NEAREST_MIRRORED_REPEAT,
NEAREST_CLAMP,
COUNT,
};
The six samplers that all bindless textures share (in rasm/render/resource.h; also on low-level.html). LINEAR_* filter smoothly between pixels and mip levels, with 8× anisotropic filtering. NEAREST_* take the closest pixel (pixel art, data). The *_REPEAT samplers tile the image, *_MIRRORED_REPEAT tile it with every other copy flipped, and *_CLAMP stretch the edge pixels. COUNT is not a sampler.
6What glTF import creates
loadGLTF turns each glTF material into a Material and each image into a texture. The worker that reads the file also makes each image's mip levels (once per kind of slot: color, data, or a normal map, whose levels are renormalized). The materials and textures are created on the main thread when the file's upload starts, in beginFrame, and the textures are filled a few per frame after that.
| glTF | RASM |
|---|---|
| a material | one PBR material per file (shared by every primitive that uses it) |
KHR_materials_unlit | UNLIT, and only the base color texture is uploaded |
doubleSided | doubleSided |
alphaMode, alphaCutoff | alphaMode (OPAQUE becomes NONE), alphaCutoff |
| base color (with its alpha), metallic, roughness, emissive factors; normal scale; occlusion strength | the matching PbrParam values |
KHR_materials_emissive_strength | EMISSIVE_STRENGTH |
KHR_texture_transform on a texture | its textureTransforms entry; the extension's texCoord, when present, replaces the texture's |
| base color and emissive textures | R8G8B8A8_SRGB; from a KTX2 image, the best sRGB block format the device has (BC7_SRGB, …) |
| metallic-roughness, normal, occlusion textures | R8G8B8A8_UNORM, or a UNORM block format from a KTX2 image (BC5_UNORM for a two-channel normal map, BC4_UNORM for a one-channel occlusion map); metallic-roughness goes in both METALLIC and ROUGHNESS |
KHR_texture_basisu on a texture | its KTX2 image, transcoded on the worker (texture compression); the texture's own source, a PNG or JPEG fallback, when the KTX2 image fails |
texCoord of each texture | texCoords; a set above 2 logs a warning and uses set 0 |
| a sampler | wrapS picks repeat, mirrored repeat or clamp for both axes; magFilter picks nearest or linear |
| an image | one texture per (image, format, sampler) in a file; not 8-bit per channel: error, no texture |
Each glTF material takes one of the 254 free materials and each image one or more bindless slots, and they belong to the mesh: destroyMesh destroys them with it. Two files that share a material or image create it twice. A primitive without a material uses the entity's material.
7Limits
| Constant | Value | Meaning |
|---|---|---|
EngineConfig::maxMaterials | 4096 | materials alive at once, the default material included; the table has one more row, 304 B each, twice |
RendererConfig::maxBindlessTextures | 16384 | texture slots, shared by materials, glTF images, render targets and you; lowered to the device's limit |
MAX_TEXTURE_SLOTS | 6 | textures per material |
MAX_PARAM_SLOTS | 12 | floats in params |
INVALID_TEXTURE_INDEX | 0xFFFFFFFF | "no texture" in a material row |
How the slots and rows work inside: Bindless resources, Color spaces.