Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): 2D texture arrays, created from layers and sampled by textureArray material params

yhh496afad45c5a
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index b9ad9c5e8..6f2a9509e 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4050,6 +4050,8 @@ flowZ: number
height: number
key: number
shore: number
+still: number
+surf: number
swell: number
```
@@ -8700,6 +8702,7 @@ number
default: number[]
defaultTexture: string | undefined
displayName: string
+layered: true | undefined
name: string
range: { min: number; max: number; } | undefined
texel: "data" | undefined
@@ -11784,9 +11787,12 @@ owner: Int32Array<ArrayBufferLike>
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
+steep: Float32Array<ArrayBufferLike>
+still: Float32Array<ArrayBufferLike>
+surf: Float32Array<ArrayBufferLike>
swell: Float32Array<ArrayBufferLike>
-static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
-static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => Generator<number, WaterField, void>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => WaterField
+static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => Generator<number, WaterField, void>
static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
static prototype: WaterField
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index f756b7e26..fad13b103 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4058,6 +4058,8 @@ flowZ: number
height: number
key: number
shore: number
+still: number
+surf: number
swell: number
```
@@ -8913,6 +8915,7 @@ number
default: number[]
defaultTexture: string | undefined
displayName: string
+layered: true | undefined
name: string
range: { min: number; max: number; } | undefined
texel: "data" | undefined
@@ -11997,9 +12000,12 @@ owner: Int32Array<ArrayBufferLike>
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
+steep: Float32Array<ArrayBufferLike>
+still: Float32Array<ArrayBufferLike>
+surf: Float32Array<ArrayBufferLike>
swell: Float32Array<ArrayBufferLike>
-static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
-static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => Generator<number, WaterField, void>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => WaterField
+static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => Generator<number, WaterField, void>
static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
static prototype: WaterField
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 81c170345..061e65349 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4045,6 +4045,8 @@ flowZ: number
height: number
key: number
shore: number
+still: number
+surf: number
swell: number
```
@@ -8695,6 +8697,7 @@ number
default: number[]
defaultTexture: string | undefined
displayName: string
+layered: true | undefined
name: string
range: { min: number; max: number; } | undefined
texel: "data" | undefined
@@ -11779,9 +11782,12 @@ owner: Int32Array<ArrayBufferLike>
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
+steep: Float32Array<ArrayBufferLike>
+still: Float32Array<ArrayBufferLike>
+surf: Float32Array<ArrayBufferLike>
swell: Float32Array<ArrayBufferLike>
-static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
-static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => Generator<number, WaterField, void>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => WaterField
+static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => Generator<number, WaterField, void>
static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
static prototype: WaterField
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 998e9b8a6..a6f23b2a7 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4045,6 +4045,8 @@ flowZ: number
height: number
key: number
shore: number
+still: number
+surf: number
swell: number
```
@@ -8988,6 +8990,7 @@ number
default: number[]
defaultTexture: string | undefined
displayName: string
+layered: true | undefined
name: string
range: { min: number; max: number; } | undefined
texel: "data" | undefined
@@ -12078,9 +12081,12 @@ owner: Int32Array<ArrayBufferLike>
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
+steep: Float32Array<ArrayBufferLike>
+still: Float32Array<ArrayBufferLike>
+surf: Float32Array<ArrayBufferLike>
swell: Float32Array<ArrayBufferLike>
-static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
-static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => Generator<number, WaterField, void>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => WaterField
+static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => Generator<number, WaterField, void>
static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
static prototype: WaterField
```
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 8ac6d8df1..d5d78b6ad 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -240,6 +240,7 @@ createCompressedTexture: ((width: number, height: number, format: number, dataPt
createLabelAtlasFont: (textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number) => number
createShader: (vertSrc: string, fragSrc: string) => number
createTexture: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, content: TextureContent) => number
+createTextureArray: ((width: number, height: number, layers: number, pixels: number, pixelsLen: number, format: number, filterMode: number, wrapMode: number, content: TextureContent) => number) | undefined
createTextureEx: (width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number, content: TextureContent) => number
createTextureFromBytes: ((width: number, height: number, pixels: Uint8Array, format: number, flipY: boolean, content: TextureContent, filterMode?: number, wrapMode?: number) => number) | undefined
createTextureFromKTX2: ((bytes: Uint8Array, srgb: boolean) => { handle: number; width: number; height: number; format?: number; blockRefused?: boolean; } | null) | undefined
diff --git a/sdk/etc/water.api.md b/sdk/etc/water.api.md
index be351c3e5..495ed446a 100644
--- a/sdk/etc/water.api.md
+++ b/sdk/etc/water.api.md
@@ -42,6 +42,8 @@ flowZ: number
height: number
key: number
shore: number
+still: number
+surf: number
swell: number
```
@@ -155,9 +157,12 @@ owner: Int32Array<ArrayBufferLike>
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
+steep: Float32Array<ArrayBufferLike>
+still: Float32Array<ArrayBufferLike>
+surf: Float32Array<ArrayBufferLike>
swell: Float32Array<ArrayBufferLike>
-static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
-static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => Generator<number, WaterField, void>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => WaterField
+static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => Generator<number, WaterField, void>
static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
static prototype: WaterField
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index c093d401c..1a074e8ce 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4045,6 +4045,8 @@ flowZ: number
height: number
key: number
shore: number
+still: number
+surf: number
swell: number
```
@@ -8702,6 +8704,7 @@ number
default: number[]
defaultTexture: string | undefined
displayName: string
+layered: true | undefined
name: string
range: { min: number; max: number; } | undefined
texel: "data" | undefined
@@ -11786,9 +11789,12 @@ owner: Int32Array<ArrayBufferLike>
ranges: (shoreReach?: number) => ZoneRanges
sample: (x: number, z: number) => FieldSample | null
shore: Float32Array<ArrayBufferLike>
+steep: Float32Array<ArrayBufferLike>
+still: Float32Array<ArrayBufferLike>
+surf: Float32Array<ArrayBufferLike>
swell: Float32Array<ArrayBufferLike>
-static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => WaterField
-static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround) => Generator<number, WaterField, void>
+static bake: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => WaterField
+static baking: (grid: ZoneGrid, bodies: readonly ZoneBody[], ground?: ZoneGround, surfLength?: number) => Generator<number, WaterField, void>
static new (grid: ZoneGrid, ocean: ZoneOcean | null): WaterField
static prototype: WaterField
```
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 10a8ee9fb..b0c79d06d 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -239,6 +239,7 @@ export interface NativeEngineApi {
rm_createLabelAtlasFont?(rm: unknown, textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
rm_createShader?(rm: unknown, vertSrc: string, fragSrc: string): number;
rm_createTexture?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean, content: number): number;
+ rm_createTextureArray?(rm: unknown, width: number, height: number, layers: number, pixelsPtr: number, pixelsLen: number, format: number, filterMode: number, wrapMode: number, content: number): number;
rm_createTextureEx?(rm: unknown, width: number, height: number, pixelsPtr: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number, content: number): number;
rm_forgoTextureContent?(rm: unknown, handle: number): void;
rm_getBitmapFontRefCount?(rm: unknown, handleId: number): number;
@@ -561,6 +562,7 @@ export function createNativeEngineApi(
bind('rm_createLabelAtlasFont', 'es_rm_createLabelAtlasFont', true);
bind('rm_createShader', 'es_rm_createShader', true);
bind('rm_createTexture', 'es_rm_createTexture', true);
+ bind('rm_createTextureArray', 'es_rm_createTextureArray', true);
bind('rm_createTextureEx', 'es_rm_createTextureEx', true);
bind('rm_forgoTextureContent', 'es_rm_forgoTextureContent', true);
bind('rm_getBitmapFontRefCount', 'es_rm_getBitmapFontRefCount', true);
diff --git a/sdk/src/render/shaderReflect.ts b/sdk/src/render/shaderReflect.ts
index a82e8e1cd..660d94e76 100644
--- a/sdk/src/render/shaderReflect.ts
+++ b/sdk/src/render/shaderReflect.ts
@@ -18,6 +18,7 @@
*
* Grammar (matches ShaderParser):
* #pragma param <name> <type> [default(csv)] [range(min,max)] [ui(hint)] [texel(data)]
+ * (<type> `textureArray` reads as a `texture` param with `layered` set)
* #pragma domain <Unlit|Lit|PostProcess|UI>
*/
@@ -41,6 +42,12 @@ export interface ShaderParam {
* packed roughness), which sRGB decode would bend. Absent means colour.
*/
texel?: 'data';
+ /**
+ * Declared `textureArray`: a 2D texture array, sampled with a layer index
+ * (`texture(u_x, vec3(uv, layer))`). Set it with `Material.tex` on a handle from
+ * `createTextureArrayFromPixels`. Absent means a plain 2D texture.
+ */
+ layered?: true;
}
export interface ShaderReflection {
@@ -79,10 +86,12 @@ function parseParam(arg: string): ShaderParam | null {
const tokens = arg.trim().split(/\s+/);
const name = tokens[0];
const typeStr = tokens[1];
- if (!name || !typeStr || !TYPES.has(typeStr as ShaderParamType)) return null;
- const type = typeStr as ShaderParamType;
+ const layered = typeStr === 'textureArray';
+ if (!name || !typeStr || (!layered && !TYPES.has(typeStr as ShaderParamType))) return null;
+ const type: ShaderParamType = layered ? 'texture' : (typeStr as ShaderParamType);
const param: ShaderParam = { name, type, displayName: displayNameFor(name), default: defaultForType(type) };
+ if (layered) param.layered = true;
const def = clause(arg, 'default');
if (def !== undefined) {
diff --git a/sdk/src/runtime/runtimeAssets.ts b/sdk/src/runtime/runtimeAssets.ts
index 46f354969..03086a874 100644
--- a/sdk/src/runtime/runtimeAssets.ts
+++ b/sdk/src/runtime/runtimeAssets.ts
@@ -181,6 +181,38 @@ export function createTextureFromPixels(
});
}
+/**
+ * A 2D texture array of same-size RGBA8 layers, for a `textureArray` material param (`Material.tex(handle)`).
+ * Layers go up in the rows given, never flipped, and are fixed: there is no sub-rectangle update. Pass
+ * `TextureContent.Retained` for an array that must survive a device loss. Returns 0 when the engine refuses it.
+ */
+export function createTextureArrayFromPixels(
+ module: ESEngineModule | null,
+ source: { width: number; height: number; layers: readonly Uint8Array[] },
+ content: TextureContent,
+ params?: TextureParams,
+ owner?: CppResourceManager,
+): number {
+ const { width, height, layers } = source;
+ const layerBytes = width * height * 4;
+ if (layers.length === 0 || layers.some((layer) => layer.length !== layerBytes)) {
+ throw new Error(`createTextureArrayFromPixels: every layer must be ${width}x${height} RGBA8 (${layerBytes} bytes)`);
+ }
+ const rm = owner ?? requireResourceManager();
+ if (!rm.createTextureArray || !module) {
+ throw new Error('createTextureArrayFromPixels: needs the wasm ResourceManager and its heap');
+ }
+ const format = samplesAsSrgb(params?.srgb) ? 2 : 1;
+ const filter = params ? textureFilterCode(params) : -1;
+ const wrap = WRAP_MODE_MAP[params?.wrapMode ?? 'clamp'] ?? 1;
+ const total = layerBytes * layers.length;
+ return withMalloc(module, total, ptr => {
+ if (!ptr) return 0;
+ layers.forEach((layer, i) => module.HEAPU8.set(layer, ptr + i * layerBytes));
+ return rm.createTextureArray!(width, height, layers.length, ptr, total, format, filter, wrap, content);
+ });
+}
+
/**
* Upload pixels into a sub-rectangle of an existing texture. Lets the dynamic
* glyph atlas pack glyphs individually instead of re-uploading
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index e81faf55e..db502662d 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -80,6 +80,11 @@ export interface CppResourceManager {
createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, content: TextureContent): number;
/** `filterMode`: bit 0 is linear over nearest, bit 1 a mip chain (see `textureFilterCode`). */
createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number, content: TextureContent): number;
+ /**
+ * A 2D texture array of `layers` RGBA8 layers, `pixelsLen` bytes back to back; `filterMode` and `wrapMode` are
+ * {@link createTextureEx}'s codes. Absent on an older wasm build.
+ */
+ createTextureArray?(width: number, height: number, layers: number, pixels: number, pixelsLen: number, format: number, filterMode: number, wrapMode: number, content: TextureContent): number;
/**
* Module-free texture upload: take the RGBA bytes directly instead of a wasm
* heap pointer. Present ONLY on the native ResourceManager (embedded Dawn, no
diff --git a/sdk/tests/shader-reflect.test.ts b/sdk/tests/shader-reflect.test.ts
index fb256c8c3..b8196d879 100644
--- a/sdk/tests/shader-reflect.test.ts
+++ b/sdk/tests/shader-reflect.test.ts
@@ -22,6 +22,13 @@ void main() {}
`;
describe('reflectEsshader', () => {
+ it('reads a textureArray param as a layered texture param', () => {
+ const r = reflectEsshader('#pragma param u_layers textureArray default(white) texel(data)\n#pragma param u_plain texture\n');
+ const [layers, plain] = r.params;
+ expect(layers).toMatchObject({ name: 'u_layers', type: 'texture', layered: true, defaultTexture: 'white', texel: 'data' });
+ expect(plain!.layered).toBeUndefined();
+ });
+
it('parses domain and all params', () => {
const r = reflectEsshader(SRC);
expect(r.domain).toBe('Unlit');
diff --git a/sdk/tests/texture-array-upload.test.ts b/sdk/tests/texture-array-upload.test.ts
new file mode 100644
index 000000000..40258770b
--- /dev/null
+++ b/sdk/tests/texture-array-upload.test.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, vi } from 'vitest';
+import { createTextureArrayFromPixels } from '../src/runtime/runtimeAssets';
+import { TextureContent, type CppResourceManager, type ESEngineModule } from '../src/wasm';
+
+function harness() {
+ const heap = new Uint8Array(1024);
+ const module = { HEAPU8: heap, _malloc: vi.fn(() => 64), _free: vi.fn() } as unknown as ESEngineModule;
+ let seen: Uint8Array | null = null;
+ const createTextureArray = vi.fn((_w: number, _h: number, _l: number, ptr: number, len: number) => {
+ seen = heap.slice(ptr, ptr + len);
+ return 7;
+ });
+ return { module, rm: { createTextureArray } as unknown as CppResourceManager, createTextureArray, seen: () => seen };
+}
+
+describe('createTextureArrayFromPixels', () => {
+ it('lays the layers back to back and passes createTextureEx codes', () => {
+ const h = harness();
+ const layers = [new Uint8Array(16).fill(1), new Uint8Array(16).fill(2), new Uint8Array(16).fill(3)];
+ const handle = createTextureArrayFromPixels(h.module, { width: 2, height: 2, layers }, TextureContent.Retained,
+ { filterMode: 'linear', wrapMode: 'repeat', mipmaps: true, srgb: false }, h.rm);
+ expect(handle).toBe(7);
+ expect(h.createTextureArray).toHaveBeenCalledWith(2, 2, 3, 64, 48, 1, 3, 0, TextureContent.Retained);
+ expect([...h.seen()!]).toEqual([...layers[0]!, ...layers[1]!, ...layers[2]!]);
+ expect(h.module._free).toHaveBeenCalledWith(64);
+ });
+
+ it('refuses a layer of the wrong size before touching the heap', () => {
+ const h = harness();
+ expect(() => createTextureArrayFromPixels(h.module, { width: 2, height: 2, layers: [new Uint8Array(16), new Uint8Array(12)] },
+ TextureContent.Retained, undefined, h.rm)).toThrow(/2x2 RGBA8/);
+ expect(h.module._malloc).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cpp
index 3444a3240..eab395a25 100644
--- a/src/esengine/bindings/ResourceManagerBindings.cpp
+++ b/src/esengine/bindings/ResourceManagerBindings.cpp
@@ -32,6 +32,22 @@ TextureFormat boundaryTextureFormat(i32 format) {
return format == 2 ? TextureFormat::SRGB8A8 : TextureFormat::RGBA8;
}
+/** Bit 0 of the filter code picks linear over nearest; bit 1 asks for a mip chain, which the device rebuilds whenever
+ * the pixels change. A negative code is linear without mips. */
+void applySamplingCodes(TextureSpecification& spec, i32 filterMode, i32 wrapMode) {
+ const bool coded = filterMode >= 0;
+ spec.generateMips = coded && (filterMode & 2) != 0;
+ spec.minFilter = (coded && (filterMode & 1) == 0) ? TextureFilter::Nearest : TextureFilter::Linear;
+ spec.magFilter = spec.minFilter;
+
+ switch (wrapMode) {
+ case 0: spec.wrapS = TextureWrap::Repeat; spec.wrapT = TextureWrap::Repeat; break;
+ case 1: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;
+ case 2: spec.wrapS = TextureWrap::MirroredRepeat; spec.wrapT = TextureWrap::MirroredRepeat; break;
+ default: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;
+ }
+}
+
} // namespace
u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,
@@ -57,19 +73,7 @@ u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,
spec.width = width;
spec.height = height;
spec.format = texFormat;
- // Bit 0 of the filter code picks linear over nearest; bit 1 asks for a mip
- // chain, which the device rebuilds whenever the pixels change.
- const bool coded = filterMode >= 0;
- spec.generateMips = coded && (filterMode & 2) != 0;
- spec.minFilter = (coded && (filterMode & 1) == 0) ? TextureFilter::Nearest : TextureFilter::Linear;
- spec.magFilter = spec.minFilter;
-
- switch (wrapMode) {
- case 0: spec.wrapS = TextureWrap::Repeat; spec.wrapT = TextureWrap::Repeat; break;
- case 1: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;
- case 2: spec.wrapS = TextureWrap::MirroredRepeat; spec.wrapT = TextureWrap::MirroredRepeat; break;
- default: spec.wrapS = TextureWrap::ClampToEdge; spec.wrapT = TextureWrap::ClampToEdge; break;
- }
+ applySamplingCodes(spec, filterMode, wrapMode);
auto handle = rm.createTexture(static_cast<resource::ResourceContent>(content), spec);
if (!handle.isValid()) {
@@ -90,6 +94,22 @@ u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,
return handle.id();
}
+u32 rm_createTextureArray(resource::ResourceManager& rm, u32 width, u32 height, u32 layers,
+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format,
+ i32 filterMode, i32 wrapMode, u32 content) {
+ const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTextureArray");
+ if (!pixels) return 0;
+ TextureSpecification spec;
+ spec.width = width;
+ spec.height = height;
+ spec.layers = layers;
+ spec.format = format == 2 ? TextureFormat::SRGB8A8 : TextureFormat::RGBA8;
+ applySamplingCodes(spec, filterMode, wrapMode);
+ auto handle = rm.createTextureArray(static_cast<resource::ResourceContent>(content), spec,
+ ConstSpan<u8>(pixels, pixelsLen));
+ return handle.id();
+}
+
/**
* Whether the ACTIVE backend can sample this compressed format — the question
* WebGL extensions answer for one backend only, and answer with "none" for the
diff --git a/src/esengine/bindings/ResourceManagerBindings.hpp b/src/esengine/bindings/ResourceManagerBindings.hpp
index b065c5538..54f695913 100644
--- a/src/esengine/bindings/ResourceManagerBindings.hpp
+++ b/src/esengine/bindings/ResourceManagerBindings.hpp
@@ -24,6 +24,13 @@ u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,
u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,
uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY,
i32 filterMode, i32 wrapMode, u32 content);
+/**
+ * A 2D texture array of `layers` RGBA8 layers, `pixelsLen` bytes of them back to back. `filterMode` and `wrapMode`
+ * are createTextureEx's codes; there is no flipY, the layers are taken in the rows given.
+ */
+u32 rm_createTextureArray(resource::ResourceManager& rm, u32 width, u32 height, u32 layers,
+ uintptr_t pixelsPtr, u32 pixelsLen, i32 format,
+ i32 filterMode, i32 wrapMode, u32 content);
u32 rm_createShader(resource::ResourceManager& rm,
const std::string& vertSrc, const std::string& fragSrc);
/** Whether the active backend samples this compressed format. */
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 7af252cb6..8e263a33e 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -491,6 +491,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::class_<esengine::resource::ResourceManager>("ResourceManager")
.function("createTexture", &esengine::rm_createTexture)
.function("createTextureEx", &esengine::rm_createTextureEx)
+ .function("createTextureArray", &esengine::rm_createTextureArray)
.function("createShader", &esengine::rm_createShader)
.function("supportsCompressedFormat", &esengine::rm_supportsCompressedFormat)
.function("createCompressedTexture", &esengine::rm_createCompressedTexture)
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index c98c3e186..be877fa28 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -252,7 +252,7 @@ bool glExtensionPresent(const char* name) {
* floor, a hair card or a sleeve seen edge-on washes out; with this the sampler takes extra samples along the long side instead.
* WebGL2 has it as an extension and an extension may be absent, so it is asked once and left alone where it is not there.
*/
-void setAnisotropy(const TextureDesc& desc, bool mipped) {
+void setAnisotropy(const TextureDesc& desc, bool mipped, GLenum target = GL_TEXTURE_2D) {
static const GLfloat kMax = [] {
constexpr GLenum kMaxAnisotropy = 0x84FF; // GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT
if (!(glExtensionPresent("GL_EXT_texture_filter_anisotropic") || glExtensionPresent("EXT_texture_filter_anisotropic"))) return 1.0f;
@@ -263,7 +263,7 @@ void setAnisotropy(const TextureDesc& desc, bool mipped) {
if (kMax <= 1.0f) return;
constexpr GLenum kTextureMaxAnisotropy = 0x84FE; // GL_TEXTURE_MAX_ANISOTROPY_EXT
const bool linear = desc.minFilter != TextureFilter::Nearest && desc.magFilter != TextureFilter::Nearest;
- glTexParameterf(GL_TEXTURE_2D, kTextureMaxAnisotropy, (mipped && linear) ? (kMax < 16.0f ? kMax : 16.0f) : 1.0f);
+ glTexParameterf(target, kTextureMaxAnisotropy, (mipped && linear) ? (kMax < 16.0f ? kMax : 16.0f) : 1.0f);
}
std::string readShaderInfoLog(GLuint shader) {
@@ -381,6 +381,7 @@ bool GLDevice::recreateDevice() {
// behind its id; nothing here survives but the maps' shape.
buffer_names_.clear();
texture_names_.clear();
+ array_names_.clear();
program_names_.clear();
framebuffer_names_.clear();
query_names_.clear();
@@ -749,6 +750,7 @@ GfxUniformType fromGLUniformType(GLenum type) {
case GL_FLOAT_MAT4: return GfxUniformType::Mat4;
case GL_SAMPLER_2D: return GfxUniformType::Sampler2D;
case GL_SAMPLER_CUBE: return GfxUniformType::SamplerCube;
+ case GL_SAMPLER_2D_ARRAY: return GfxUniformType::Sampler2DArray;
default: return GfxUniformType::Unknown;
}
}
@@ -1107,11 +1109,16 @@ void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32
// Textures
// =============================================================================
+u32 GLDevice::textureTarget(u32 name) const {
+ return !array_names_.empty() && array_names_.count(name) ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D;
+}
+
+// A unit holds a 2D and an array binding side by side; the sampler type of the program decides which is read.
void GLDevice::bindTexture(u32 slot, TextureHandle texture) {
const u32 name = nameOf(texture_names_, static_cast<u32>(texture));
if (slot >= kTextureSlots) { // beyond the cache — bind directly
glActiveTexture(GL_TEXTURE0 + slot);
- glBindTexture(GL_TEXTURE_2D, name);
+ glBindTexture(textureTarget(name), name);
return;
}
if (bound_texture_[slot] == name) return; // already bound to this sampler unit
@@ -1119,12 +1126,12 @@ void GLDevice::bindTexture(u32 slot, TextureHandle texture) {
glActiveTexture(GL_TEXTURE0 + slot);
active_texture_unit_ = slot;
}
- glBindTexture(GL_TEXTURE_2D, name);
+ glBindTexture(textureTarget(name), name);
bound_texture_[slot] = name;
}
void GLDevice::bindTextureForEdit(u32 name) {
- glBindTexture(GL_TEXTURE_2D, name);
+ glBindTexture(textureTarget(name), name);
if (active_texture_unit_ < kTextureSlots) bound_texture_[active_texture_unit_] = name;
}
@@ -1136,7 +1143,7 @@ void GLDevice::evictSamplerBinding(u32 name) {
glActiveTexture(GL_TEXTURE0 + slot);
active_texture_unit_ = slot;
}
- glBindTexture(GL_TEXTURE_2D, 0);
+ glBindTexture(textureTarget(name), 0);
bound_texture_[slot] = 0;
}
}
@@ -1165,6 +1172,22 @@ bool GLDevice::backendCreateTexture(u32 id, const TextureDesc& desc, const void*
setName(texture_names_, id, name);
auto gl = toGLPixelFormat(desc.format);
+ if (desc.layers > 1) {
+ // WebGL2 refuses UNPACK_FLIP_Y for a 3D upload, so the layers go up in the rows given.
+ array_names_.insert(name);
+ bindTextureForEdit(name);
+ const TightRowScope rows(desc.format, desc.width);
+ glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, static_cast<GLint>(gl.internalFormat),
+ static_cast<GLsizei>(desc.width), static_cast<GLsizei>(desc.height),
+ static_cast<GLsizei>(desc.layers), 0, gl.format, gl.type, pixels);
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, toGLMinFilter(desc));
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
+ glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
+ setAnisotropy(desc, desc.mipmaps, GL_TEXTURE_2D_ARRAY);
+ if (desc.mipmaps && pixels) glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
+ return true;
+ }
bindTextureForEdit(name);
const TightRowScope rows(desc.format, desc.width);
if (pixels && desc.flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);
@@ -1236,6 +1259,7 @@ void GLDevice::backendDeleteTexture(u32 id) {
} else {
evictSamplerBinding(name);
glDeleteTextures(1, &name);
+ array_names_.erase(name);
}
setName(texture_names_, id, 0);
}
@@ -1260,19 +1284,23 @@ void GLDevice::backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,
}
void GLDevice::backendSetTextureParams(u32 id, const TextureDesc& desc) {
- bindTextureForEdit(nameOf(texture_names_, id));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLMinFilter(desc));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
- setAnisotropy(desc, desc.mipmaps);
+ const u32 name = nameOf(texture_names_, id);
+ const GLenum target = textureTarget(name);
+ bindTextureForEdit(name);
+ glTexParameteri(target, GL_TEXTURE_MIN_FILTER, toGLMinFilter(desc));
+ glTexParameteri(target, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
+ glTexParameteri(target, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
+ glTexParameteri(target, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
+ setAnisotropy(desc, desc.mipmaps, target);
}
void GLDevice::backendGenerateMipmaps(u32 id) {
- bindTextureForEdit(nameOf(texture_names_, id));
- glGenerateMipmap(GL_TEXTURE_2D);
+ const u32 name = nameOf(texture_names_, id);
+ const GLenum target = textureTarget(name);
+ bindTextureForEdit(name);
+ glGenerateMipmap(target);
if (const TextureDesc* desc = textureDesc(TextureHandle{id})) {
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLMinFilter(*desc));
+ glTexParameteri(target, GL_TEXTURE_MIN_FILTER, toGLMinFilter(*desc));
}
}
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index 41110d4c2..aef3e3308 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -22,6 +22,7 @@
#include "./GfxDevice.hpp"
#include <unordered_map>
+#include <unordered_set>
#include <vector>
namespace esengine {
@@ -199,6 +200,11 @@ private:
// target's own attachment must not stay bound to a sampler while it is drawn to.
void evictSamplerBinding(u32 name);
+ /** GL_TEXTURE_2D_ARRAY for a name created as an array, GL_TEXTURE_2D otherwise. */
+ u32 textureTarget(u32 name) const;
+ /** The GL names of this generation's texture arrays: every bind and edit of one names its target. */
+ std::unordered_set<u32> array_names_;
+
/** GL names by registry id for this generation; 0 = none. */
std::vector<u32> buffer_names_;
std::vector<u32> texture_names_;
diff --git a/src/esengine/renderer/rhi/GfxDevice.cpp b/src/esengine/renderer/rhi/GfxDevice.cpp
index d1a4fe75a..beb87b3b6 100644
--- a/src/esengine/renderer/rhi/GfxDevice.cpp
+++ b/src/esengine/renderer/rhi/GfxDevice.cpp
@@ -41,8 +41,10 @@ void patchImage(std::vector<u8>& image, u32 imageWidth, u32 imageHeight, u32 bpp
std::vector<u8> uploadOrderImage(const TextureDesc& desc, const void* pixels) {
const u32 bpp = gfxBytesPerPixel(desc.format);
- std::vector<u8> image(static_cast<usize>(desc.width) * desc.height * bpp, 0);
- if (pixels) {
+ std::vector<u8> image(static_cast<usize>(desc.width) * desc.height * bpp * std::max(1u, desc.layers), 0);
+ if (pixels && desc.layers > 1) {
+ std::memcpy(image.data(), pixels, image.size());
+ } else if (pixels) {
patchImage(image, desc.width, desc.height, bpp, 0, 0, desc.width, desc.height,
static_cast<const u8*>(pixels), desc.flipY);
}
@@ -395,6 +397,10 @@ void GfxDevice::invalidatePipelineCache() {
TextureHandle GfxDevice::createTexture(const TextureDesc& desc, GfxContent content, const void* pixels) {
if (device_status_ == GfxDeviceStatus::Dead) return TextureHandle::Invalid;
+ if (desc.layers > 1 && (desc.samples > 1 || desc.storage || isDepthFormat(desc.format))) {
+ ES_LOG_ERROR("GfxDevice::createTexture: a texture array is sampled colour only");
+ return TextureHandle::Invalid;
+ }
const bool usable = isDeviceUsable();
GfxTextureRecord record{desc, content};
if (content.kind() == GfxContentKind::Retained && (desc.samples > 1 || isDepthFormat(desc.format))) {
@@ -531,6 +537,10 @@ void GfxDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u3
const u32 id = static_cast<u32>(texture);
auto* record = registry_.textures.find(id);
if (!record || !pixels || record->compressed) return;
+ if (record->desc.layers > 1) {
+ ES_LOG_ERROR("GfxDevice::updateTexture: texture {} is an array, whose layers are fixed at creation", id);
+ return;
+ }
const TextureDesc& desc = record->desc;
const bool whole = x == 0 && y == 0 && width >= desc.width && height >= desc.height;
if (!record->bytes.empty()) {
@@ -864,7 +874,7 @@ u64 GfxDevice::estimatedGpuBytes() const {
* ((static_cast<u64>(height) + block.blockHeight - 1) / block.blockHeight) * block.bytesPerBlock;
} else {
bytes += static_cast<u64>(width) * height * gfxBytesPerPixel(texture.desc.format)
- * std::max(1u, texture.desc.samples);
+ * std::max(1u, texture.desc.samples) * std::max(1u, texture.desc.layers);
}
if (width == 1 && height == 1) break;
width = std::max(1u, width / 2); height = std::max(1u, height / 2);
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index 57c20deb4..963a4c65d 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -399,7 +399,7 @@ struct BufferDesc {
};
/**
- * @brief Immutable creation parameters of a 2D texture.
+ * @brief Immutable creation parameters of a 2D texture or 2D texture array.
* @details `flipY` applies to the initial pixel upload only (WebGL upload state;
* native backends flip CPU-side at load time).
*/
@@ -420,6 +420,10 @@ struct TextureDesc {
/// Writable from a compute shader as a storage texture. RGBA8, RGBA16F and RGBA32F only, and only on a device
/// that supportsCompute(); a texture asked for this elsewhere is created without it.
bool storage = false;
+ /// Above 1 the texture is a 2D ARRAY of this many layers, sampled through `sampler2DArray` /
+ /// `texture_2d_array`. Its pixels are the layers back to back, each width * height texels. Colour, single-sample
+ /// and sampled only: never an attachment, a storage target or compressed, and `flipY` does not apply.
+ u32 layers = 1;
};
/**
@@ -720,6 +724,7 @@ enum class GfxUniformType : u8 {
Mat4,
Sampler2D,
SamplerCube,
+ Sampler2DArray,
};
struct GfxUniformInfo {
diff --git a/src/esengine/renderer/rhi/Texture.cpp b/src/esengine/renderer/rhi/Texture.cpp
index 086e9e7c7..f65b50f07 100644
--- a/src/esengine/renderer/rhi/Texture.cpp
+++ b/src/esengine/renderer/rhi/Texture.cpp
@@ -89,6 +89,16 @@ Unique<Texture> Texture::create(GfxDevice& device, GfxContent content, const Tex
return texture;
}
+Unique<Texture> Texture::createArray(GfxDevice& device, GfxContent content, const TextureSpecification& spec,
+ const void* pixels) {
+ auto texture = makeUnique<Texture>();
+ texture->device_ = &device;
+ if (!texture->initialize(spec, content, pixels, false)) {
+ return nullptr;
+ }
+ return texture;
+}
+
Unique<Texture> Texture::create(GfxDevice& device, GfxContent content, u32 width, u32 height,
std::span<const u8> pixels, TextureFormat format, bool flipY) {
[[maybe_unused]] u32 expectedSize = width * height * bytesPerPixel(format);
@@ -200,6 +210,7 @@ bool Texture::initialize(const TextureSpecification& spec, GfxContent content, c
desc.wrapT = spec.wrapT;
desc.mipmaps = spec.generateMips;
desc.flipY = flipY;
+ desc.layers = spec.layers ? spec.layers : 1;
handle_ = device_->createTexture(desc, content, pixels);
if (handle_ == TextureHandle::Invalid) {
diff --git a/src/esengine/renderer/rhi/Texture.hpp b/src/esengine/renderer/rhi/Texture.hpp
index 37a748445..9d5d9d515 100644
--- a/src/esengine/renderer/rhi/Texture.hpp
+++ b/src/esengine/renderer/rhi/Texture.hpp
@@ -88,6 +88,8 @@ struct TextureSpecification {
TextureWrap wrapT = TextureWrap::Repeat;
/** @brief Generate mipmaps automatically */
bool generateMips = true;
+ /** @brief Above 1, a 2D texture array of this many layers (see TextureDesc::layers) */
+ u32 layers = 1;
};
// =============================================================================
@@ -167,6 +169,14 @@ public:
*/
static Unique<Texture> borrow(GfxDevice& device, TextureHandle texture, u32 width, u32 height);
+ /**
+ * @brief Creates a 2D texture array from `spec.layers` layers of `spec.width` x `spec.height`.
+ * @param pixels The layers back to back, layer 0 first, rows bottom-up as the engine samples them;
+ * `spec.width * spec.height * bpp * spec.layers` bytes. Its contents are fixed: setData is refused.
+ */
+ static Unique<Texture> createArray(GfxDevice& device, GfxContent content, const TextureSpecification& spec,
+ const void* pixels);
+
/**
* @brief Takes @p from's pixels behind this texture's handle; @p from is empty afterwards.
* @details How owed content is paid: the provider loads it the ordinary way and
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 5431bfae3..699323304 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -227,6 +227,7 @@ void WebGPUDevice::releaseDeviceObjects() {
dummy_ubo_ = BufferRec{};
releaseTexture(dummy_texture_);
releaseTexture(dummy_depth_texture_);
+ releaseTexture(dummy_array_texture_);
// GPU timing resources.
if (timestamp_qset_) { wgpuQuerySetRelease(timestamp_qset_); timestamp_qset_ = nullptr; }
@@ -719,7 +720,8 @@ u64 WebGPUDevice::estimatedGpuBytes() const {
return size * wgpuTextureGetDepthOrArrayLayers(texture);
};
for (const auto& [id, texture] : textures_) bytes += textureBytes(texture.texture);
- bytes += textureBytes(dummy_texture_.texture) + textureBytes(dummy_depth_texture_.texture);
+ bytes += textureBytes(dummy_texture_.texture) + textureBytes(dummy_depth_texture_.texture)
+ + textureBytes(dummy_array_texture_.texture);
bytes += textureBytes(surface_depth_texture_) + textureBytes(surface_msaa_texture_);
return bytes;
}
@@ -887,10 +889,11 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
return false;
}
+ const u32 layers = desc.layers > 1 ? desc.layers : 1;
WGPUTextureDescriptor td{};
td.dimension = WGPUTextureDimension_2D;
td.format = toWGPUTextureFormat(desc.format);
- td.size = WGPUExtent3D{desc.width, desc.height, 1};
+ td.size = WGPUExtent3D{desc.width, desc.height, layers};
td.sampleCount = desc.samples > 1 ? kMsaaSamples : 1;
td.mipLevelCount = 1;
if (desc.mipmaps && td.sampleCount == 1 && !isDepthFormat(td.format)) {
@@ -925,7 +928,16 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
}
WGPUTextureView view = nullptr;
- if (td.mipLevelCount > 1) {
+ if (layers > 1) {
+ // Never an attachment, so the one view is the sampled one: every layer, every level.
+ WGPUTextureViewDescriptor vd{};
+ vd.format = td.format;
+ vd.dimension = WGPUTextureViewDimension_2DArray;
+ vd.mipLevelCount = td.mipLevelCount;
+ vd.arrayLayerCount = layers;
+ vd.aspect = WGPUTextureAspect_All;
+ view = wgpuTextureCreateView(texture, &vd);
+ } else if (td.mipLevelCount > 1) {
WGPUTextureViewDescriptor vd{};
vd.format = td.format;
vd.dimension = WGPUTextureViewDimension_2D;
@@ -953,7 +965,7 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
vd.arrayLayerCount = 1;
vd.aspect = WGPUTextureAspect_DepthOnly;
sampleView = wgpuTextureCreateView(texture, &vd);
- } else if (td.mipLevelCount > 1) {
+ } else if (td.mipLevelCount > 1 && layers == 1) {
sampleView = wgpuTextureCreateView(texture, nullptr);
}
@@ -962,8 +974,17 @@ bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, Text
packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT),
td.sampleCount, td.mipLevelCount};
out.storage = storage;
-
- if (pixels && !isDepthFormat(td.format)) {
+ out.layers = layers;
+
+ if (pixels && !isDepthFormat(td.format) && layers > 1) {
+ // An array takes its layers in the rows given, as GL does (which cannot flip a 3D upload).
+ const usize layerBytes = static_cast<usize>(desc.width) * desc.height * gfxBytesPerPixel(desc.format);
+ for (u32 layer = 0; layer < layers; ++layer) {
+ writeTexture(out, 0, 0, desc.width, desc.height,
+ static_cast<const u8*>(pixels) + layerBytes * layer, false, layer);
+ }
+ if (out.mipLevels > 1) buildMipChain(out);
+ } else if (pixels && !isDepthFormat(td.format)) {
// desc.flipY, not false: the caller's orientation request has to reach the
// upload, which is where the row reversal happens (see writeTexture).
writeTexture(out, 0, 0, desc.width, desc.height, pixels, desc.flipY);
@@ -1082,7 +1103,7 @@ void WebGPUDevice::backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 hei
}
void WebGPUDevice::writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width, u32 height,
- const void* pixels, bool flipY) {
+ const void* pixels, bool flipY, u32 layer) {
if (!pixels || !queue_ || !rec.texture) return;
if (isDepthFormat(rec.format)) {
ES_LOG_ERROR("WebGPUDevice::updateTexture: depth-stencil textures are attachment-only");
@@ -1090,7 +1111,7 @@ void WebGPUDevice::writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width,
}
WGPUTexelCopyTextureInfo dst{};
dst.texture = rec.texture;
- dst.origin = WGPUOrigin3D{static_cast<u32>(x), static_cast<u32>(y), 0};
+ dst.origin = WGPUOrigin3D{static_cast<u32>(x), static_cast<u32>(y), layer};
// Source rows are what the caller allocated; destination rows are the texel
// size WebGPU stores. They differ for RGB8, which has no WebGPU format and so
@@ -1232,6 +1253,8 @@ bool WebGPUDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,
scanWGSLBindingMask(source.fragmentSrc, 1);
rec.group1DepthMask = scanWGSLDepthTextureMask(source.vertexSrc, 1) |
scanWGSLDepthTextureMask(source.fragmentSrc, 1);
+ rec.group1ArrayMask = scanWGSLArrayTextureMask(source.vertexSrc, 1) |
+ scanWGSLArrayTextureMask(source.fragmentSrc, 1);
// What the VERTEX stage declares, on its own: a sampled texture is visible
// to the fragment stage alone unless the layout says otherwise, and reading
// one it was not given is a pipeline WebGPU rejects with nothing named.
@@ -1337,7 +1360,8 @@ WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {
// holds by identity.
pd.layout = pipelineLayoutFor(progIt->second.group0Mask, progIt->second.group1Mask,
progIt->second.group1DepthMask,
- progIt->second.group1VertexMask);
+ progIt->second.group1VertexMask,
+ progIt->second.group1ArrayMask);
pd.vertex.module = progIt->second.vertex;
pd.vertex.entryPoint = sv("vs_main");
pd.vertex.bufferCount = slotCount;
@@ -1589,22 +1613,28 @@ void WebGPUDevice::buildMipChain(const TextureRec& rec) {
// frame, and the frame's encoder may have a pass open.
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
if (!encoder) return;
+ // Each layer of an array is its own chain: views[layer * mipLevels + level] is one level of one layer.
std::vector<WGPUTextureView> views;
std::vector<WGPUBindGroup> groups;
- for (u32 level = 0; level < rec.mipLevels; ++level) {
- WGPUTextureViewDescriptor vd{};
- vd.format = rec.format;
- vd.dimension = WGPUTextureViewDimension_2D;
- vd.baseMipLevel = level;
- vd.mipLevelCount = 1;
- vd.arrayLayerCount = 1;
- vd.aspect = WGPUTextureAspect_All;
- views.push_back(wgpuTextureCreateView(rec.texture, &vd));
+ for (u32 layer = 0; layer < rec.layers; ++layer) {
+ for (u32 level = 0; level < rec.mipLevels; ++level) {
+ WGPUTextureViewDescriptor vd{};
+ vd.format = rec.format;
+ vd.dimension = WGPUTextureViewDimension_2D;
+ vd.baseMipLevel = level;
+ vd.mipLevelCount = 1;
+ vd.baseArrayLayer = layer;
+ vd.arrayLayerCount = 1;
+ vd.aspect = WGPUTextureAspect_All;
+ views.push_back(wgpuTextureCreateView(rec.texture, &vd));
+ }
}
- for (u32 level = 1; level < rec.mipLevels; ++level) {
+ for (u32 step = 0; step < rec.layers * rec.mipLevels; ++step) {
+ const u32 level = step % rec.mipLevels;
+ if (level == 0) continue;
WGPUBindGroupEntry entries[2]{};
entries[0].binding = 0;
- entries[0].textureView = views[level - 1];
+ entries[0].textureView = views[step - 1];
entries[1].binding = 1;
entries[1].sampler = mip_sampler_;
WGPUBindGroupDescriptor bgd{};
@@ -1616,7 +1646,7 @@ void WebGPUDevice::buildMipChain(const TextureRec& rec) {
groups.push_back(group);
WGPURenderPassColorAttachment color{};
- color.view = views[level];
+ color.view = views[step];
color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
color.loadOp = WGPULoadOp_Clear;
color.storeOp = WGPUStoreOp_Store;
@@ -1844,13 +1874,10 @@ void WebGPUDevice::drawInternalClear(bool color, bool depth, bool stencil,
}
WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthMask,
- u32 vertexMask) {
- // depthMask is part of the key: the same bindings sampled as depth are a
- // DIFFERENT layout, and sharing one entry would bind a float texture under a
- // depth declaration. vertexMask likewise — visibility is part of an entry.
- const u64 key = (static_cast<u64>(group) << 32) | mask
- ^ (static_cast<u64>(depthMask) << 48)
- ^ (static_cast<u64>(vertexMask) << 16);
+ u32 vertexMask, u32 arrayMask) {
+ // Every mask is part of the key: the same bindings sampled as depth or as an
+ // array are a DIFFERENT layout, and visibility is part of an entry too.
+ const std::array<u32, 5> key{group, mask, depthMask, vertexMask, arrayMask};
auto cached = group_layouts_.find(key);
if (cached != group_layouts_.end()) return cached->second;
if (!device_) return nullptr;
@@ -1893,7 +1920,8 @@ WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthM
(depthMask & (1u << tb)) ? WGPUTextureSampleType_Depth
: (mask & (1u << sb)) ? WGPUTextureSampleType_Float
: WGPUTextureSampleType_UnfilterableFloat;
- e.texture.viewDimension = WGPUTextureViewDimension_2D;
+ e.texture.viewDimension = (arrayMask & (1u << tb)) ? WGPUTextureViewDimension_2DArray
+ : WGPUTextureViewDimension_2D;
entries[count++] = e;
}
if (mask & (1u << sb)) {
@@ -1915,12 +1943,11 @@ WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u32 mask, u32 depthM
}
WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u32 group1Mask,
- u32 group1DepthMask, u32 group1VertexMask) {
- // The depth and visibility masks change the group-1 layout under this
+ u32 group1DepthMask, u32 group1VertexMask,
+ u32 group1ArrayMask) {
+ // The depth, visibility and array masks change the group-1 layout under this
// pipeline, so they have to reach the key here too — see groupLayoutFor.
- const u64 key = ((static_cast<u64>(group1Mask) << 32) | group0Mask)
- ^ (static_cast<u64>(group1DepthMask) << 16)
- ^ (static_cast<u64>(group1VertexMask) << 8);
+ const std::array<u32, 5> key{group0Mask, group1Mask, group1DepthMask, group1VertexMask, group1ArrayMask};
auto cached = pipeline_layouts_.find(key);
if (cached != pipeline_layouts_.end()) return cached->second;
if (!device_) return nullptr;
@@ -1931,7 +1958,7 @@ WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u32 group1Mas
u32 count = 0;
if (group0Mask != 0 || group1Mask != 0) bgls[count++] = groupLayoutFor(0, group0Mask);
if (group1Mask != 0) {
- bgls[count++] = groupLayoutFor(1, group1Mask, group1DepthMask, group1VertexMask);
+ bgls[count++] = groupLayoutFor(1, group1Mask, group1DepthMask, group1VertexMask, group1ArrayMask);
}
WGPUPipelineLayoutDescriptor pld{};
@@ -1961,6 +1988,12 @@ void WebGPUDevice::ensureDummies() {
td.format = GfxPixelFormat::Depth24Stencil8;
makeTexture(td, nullptr, dummy_depth_texture_);
}
+ if (!dummy_array_texture_.texture) {
+ const u8 white[8] = {255, 255, 255, 255, 255, 255, 255, 255};
+ TextureDesc td{};
+ td.layers = 2;
+ makeTexture(td, white, dummy_array_texture_);
+ }
}
WGPUBindGroup WebGPUDevice::cachedBindGroup(u32 group, u32 mask, const u64* ids, u32 idCount,
@@ -2050,6 +2083,7 @@ void WebGPUDevice::flushBindGroup() {
if (prog->group1Mask != 0) {
const TextureRec* dummy = dummy_texture_.texture ? &dummy_texture_ : nullptr;
const TextureRec* depthDummy = dummy_depth_texture_.texture ? &dummy_depth_texture_ : nullptr;
+ const TextureRec* arrayDummy = dummy_array_texture_.texture ? &dummy_array_texture_ : nullptr;
WGPUBindGroupEntry texEntries[kTextureSlots * 2];
u32 texCount = 0;
@@ -2070,8 +2104,13 @@ void WebGPUDevice::flushBindGroup() {
// unit is unbound: the white dummy under `sampleType = Depth` is
// a validation error, not a blank sample.
const bool wantsDepth = (prog->group1DepthMask & (1u << tb)) != 0;
+ // The view's dimension must be the declaration's: an array where a
+ // 2D texture is declared, or the reverse, is the dummy of the right kind.
+ const bool wantsArray = (prog->group1ArrayMask & (1u << tb)) != 0;
const TextureRec* src = rec;
if (wantsDepth && !isDepthFormat(src->format)) src = depthDummy;
+ else if (wantsArray && src->layers == 1) src = arrayDummy;
+ else if (!wantsArray && src->layers > 1) src = dummy;
if (!src) continue;
WGPUBindGroupEntry e{};
e.binding = tb;
@@ -2088,7 +2127,7 @@ void WebGPUDevice::flushBindGroup() {
WGPUBindGroupDescriptor tgd{};
tgd.layout = groupLayoutFor(1, prog->group1Mask, prog->group1DepthMask,
- prog->group1VertexMask);
+ prog->group1VertexMask, prog->group1ArrayMask);
tgd.entryCount = texCount;
tgd.entries = texEntries;
u64 tids[kTextureSlots * 2];
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index fb70e38fd..260002b4f 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -35,6 +35,8 @@
#include <webgpu/webgpu.h>
+#include <array>
+#include <map>
#include <string>
#include <unordered_map>
#include <vector>
@@ -372,6 +374,8 @@ private:
u32 mipLevels = 1;
/// Created with StorageBinding: a compute shader may write it.
bool storage = false;
+ /// Above 1 a 2D array: `view` and `sampleView` are then the one 2DArray view of every layer and level.
+ u32 layers = 1;
};
struct ProgramRec {
WGPUShaderModule vertex = nullptr;
@@ -390,6 +394,8 @@ private:
u32 group1VertexMask = 0;
/// Which of group1Mask's bindings are `texture_depth_2d`.
u32 group1DepthMask = 0;
+ /// Which of group1Mask's bindings are `texture_2d_array`.
+ u32 group1ArrayMask = 0;
};
/// What a pass's second colour attachment means to the pipeline drawn into it: there is none, the
/// pipeline writes it, or the pipeline leaves it alone (its target is declared with an empty write mask).
@@ -434,8 +440,9 @@ private:
WGPUBuffer makeBuffer(GfxBufferUsage usage, u32 size, const void* data);
/** @brief A texture and its views; false with @p out untouched when creation fails. */
bool makeTexture(const TextureDesc& desc, const void* pixels, TextureRec& out);
+ /** @brief Writes a rectangle of one layer (layer 0 of a plain 2D texture). */
void writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width, u32 height,
- const void* pixels, bool flipY);
+ const void* pixels, bool flipY, u32 layer = 0);
/** @brief Releases a texture's views and storage, dropping bind groups that name them. */
void releaseTexture(TextureRec& rec);
/** @brief Returns the cached explicit bind-group layout for a binding mask.
@@ -444,12 +451,12 @@ private:
* convention (engine units 0..7 at 0..7/8..15, material units 8..15
* at 16..23/24..31). */
WGPUBindGroupLayout groupLayoutFor(u32 group, u32 mask, u32 depthMask = 0,
- u32 vertexMask = 0);
+ u32 vertexMask = 0, u32 arrayMask = 0);
/** @brief Returns the cached explicit pipeline layout for a program's masks.
* A program with group-1 bindings but an empty group 0 still gets a
* (zero-entry) group-0 layout, so group indices stay positional. */
WGPUPipelineLayout pipelineLayoutFor(u32 group0Mask, u32 group1Mask, u32 group1DepthMask = 0,
- u32 group1VertexMask = 0);
+ u32 group1VertexMask = 0, u32 group1ArrayMask = 0);
/** @brief Lazily creates the dummy backfill resources: a zeroed uniform
* buffer and a 1x1 white texture, standing in for declared-but-
* unbound bindings (GL reads an unbound block/unit without
@@ -665,12 +672,11 @@ private:
std::unordered_map<u8, WGPUSampler> samplers_; ///< Keyed by packed filter/wrap params.
- // Explicit layouts, cached by binding mask (key = group << 32 | mask for
- // bind-group layouts, group1Mask << 32 | group0Mask for pipeline layouts).
- // Pipelines and bind groups share the cached objects, so group
- // compatibility holds by identity.
- std::unordered_map<u64, WGPUBindGroupLayout> group_layouts_;
- std::unordered_map<u64, WGPUPipelineLayout> pipeline_layouts_;
+ // Explicit layouts, cached by every mask that shapes them: {group, mask, depth, vertex, array} for
+ // bind-group layouts, {group0, group1, depth, vertex, array} for pipeline layouts. Pipelines and bind groups
+ // share the cached objects, so group compatibility holds by identity.
+ std::map<std::array<u32, 5>, WGPUBindGroupLayout> group_layouts_;
+ std::map<std::array<u32, 5>, WGPUPipelineLayout> pipeline_layouts_;
// Backfill belongs to this backend, not to the registry: nothing above it can
// name these, so they are made again lazily rather than recovered.
BufferRec dummy_ubo_; ///< Zeroed backfill for declared-but-unbound UBO slots.
@@ -679,6 +685,9 @@ private:
/// entry is a validation error, so a declared-but-unbound depth binding
/// needs a depth texture to stand in.
TextureRec dummy_depth_texture_;
+ /// The same for an array unit: white layers under a `texture_2d_array` declaration (two, since one layer
+ /// makes a plain 2D texture here).
+ TextureRec dummy_array_texture_;
/** This device's objects by registry id. */
std::unordered_map<u32, BufferRec> buffers_;
diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
index c193c5a07..841b76f41 100644
--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
@@ -381,13 +381,10 @@ inline constexpr u32 kGroup1TextureUnits = WGSL_MAX_TEXTURE_UNITS;
// the shader assembler EMITS what this backend reads back, so one of them owns the rule.
/**
- * @brief Bit mask of the group's bindings a WGSL source declares as DEPTH textures.
- * @details A `texture_depth_2d` binding needs `sampleType = Depth` in its layout
- * entry and a depth-aspect view under it; bound as an ordinary float
- * texture WebGPU rejects the pipeline. Same source scan as
- * {@link scanWGSLBindingMask}, reading the declaration that follows.
+ * @brief Bit mask of the group's bindings whose declaration names the type `kind`.
+ * @details Same source scan as {@link scanWGSLBindingMask}, reading the declaration that follows each binding.
*/
-inline u32 scanWGSLDepthTextureMask(const char* source, u32 group) {
+inline u32 scanWGSLTextureKindMask(const char* source, u32 group, const char* kind) {
if (!source) return 0;
u32 mask = 0;
for (const char* p = source; (p = std::strstr(p, "@group(")) != nullptr;) {
@@ -404,14 +401,32 @@ inline u32 scanWGSLDepthTextureMask(const char* source, u32 group) {
if (end == b) continue;
p = end;
// The declaration this binding attributes: up to the `;` that ends it,
- // so a `texture_depth_2d` further down the file cannot be read as this one's.
+ // so a matching type further down the file cannot be read as this one's.
const char* semi = std::strchr(p, ';');
- const char* depth = std::strstr(p, "texture_depth_2d");
- if (idx < 32 && depth && (!semi || depth < semi)) mask |= (1u << idx);
+ const char* type = std::strstr(p, kind);
+ if (idx < 32 && type && (!semi || type < semi)) mask |= (1u << idx);
}
return mask;
}
+/**
+ * @brief Bit mask of the group's bindings a WGSL source declares as DEPTH textures.
+ * @details A `texture_depth_2d` binding needs `sampleType = Depth` in its layout
+ * entry and a depth-aspect view under it; bound as an ordinary float
+ * texture WebGPU rejects the pipeline.
+ */
+inline u32 scanWGSLDepthTextureMask(const char* source, u32 group) {
+ return scanWGSLTextureKindMask(source, group, "texture_depth_2d");
+}
+
+/**
+ * @brief Bit mask of the group's bindings a WGSL source declares as `texture_2d_array`.
+ * @details Such a binding's layout entry is `viewDimension = 2DArray`, and only an array view binds under it.
+ */
+inline u32 scanWGSLArrayTextureMask(const char* source, u32 group) {
+ return scanWGSLTextureKindMask(source, group, "texture_2d_array");
+}
+
/// WriteBuffer's size (and offset) must be a 4-byte multiple; buffers are allocated
/// rounded up so the slack exists. Callers supply exactly `size` bytes, so an
/// unaligned size must be staged, never read up to `alignedWriteSize` in place.
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 005b56143..28024b119 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -235,6 +235,25 @@ TextureHandle ResourceManager::createTexture(ResourceContent content, u32 width,
return textures_.add(std::move(texture), "", bytes);
}
+TextureHandle ResourceManager::createTextureArray(ResourceContent content, const TextureSpecification& spec,
+ ConstSpan<u8> pixels) {
+ if (!device_) return {};
+ const bool rgba = spec.format == TextureFormat::RGBA8 || spec.format == TextureFormat::SRGB8A8;
+ const usize layerBytes = static_cast<usize>(spec.width) * spec.height * 4;
+ const usize bytes = layerBytes * spec.layers;
+ if (!rgba || spec.layers < 1 || layerBytes == 0 || pixels.size() != bytes) {
+ ES_LOG_ERROR("createTextureArray: {} bytes for {} RGBA8 layers of {}x{} (expected {})",
+ pixels.size(), spec.layers, spec.width, spec.height, bytes);
+ return TextureHandle();
+ }
+ auto texture = Texture::createArray(*device_, toGfxContent(content), spec, pixels.data());
+ if (!texture) {
+ ES_LOG_ERROR("Failed to create texture array");
+ return TextureHandle();
+ }
+ return textures_.add(std::move(texture), "", bytes);
+}
+
TextureHandle ResourceManager::createCompressedTexture(ResourceContent content, u32 width, u32 height,
GfxCompressedFormat format, ConstSpan<u8> data,
u32 mipLevels) {
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 6e751315f..e13db82c2 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -256,6 +256,15 @@ public:
TextureHandle createTexture(ResourceContent content, u32 width, u32 height, ConstSpan<u8> pixels,
TextureFormat format, bool flipY = false);
+ /**
+ * @brief Creates a 2D texture array from `spec.layers` same-size RGBA8 (or SRGB8A8) layers.
+ * @param pixels The layers back to back, layer 0 first; exactly
+ * `spec.width * spec.height * 4 * spec.layers` bytes, or nothing is made.
+ * @return Handle to the texture, or invalid handle on failure
+ */
+ TextureHandle createTextureArray(ResourceContent content, const TextureSpecification& spec,
+ ConstSpan<u8> pixels);
+
/**
* @brief Creates a block-compressed texture (KTX2 → ETC2/ASTC/BC), uploading
* the pre-compressed blocks for mip level 0. Tracked like any texture;
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index d2eb6e200..d0abe5fff 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -1132,7 +1132,7 @@ std::string wgslMaterialTextureDecls(const ParsedShader& parsed, const std::stri
if (only && only->find(p.name) == std::string::npos) continue;
const u32 unit = static_cast<u32>(p.textureUnit);
src += "@group(1) @binding(" + std::to_string(unit + 8) + ") var " + p.name +
- " : texture_2d<f32>;\n";
+ (p.layered ? " : texture_2d_array<f32>;\n" : " : texture_2d<f32>;\n");
if (body.find(p.name + "_s") == std::string::npos) continue;
src += "@group(1) @binding(" + std::to_string(unit + 16) + ") var " + p.name +
"_s : sampler;\n";
@@ -2348,7 +2348,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
}
for (const auto& p : parsed.properties) {
if (p.fromParam && p.type == ShaderPropertyType::Texture) {
- assembled << "uniform highp sampler2D " << p.name << ";\n";
+ assembled << (p.layered ? "uniform highp sampler2DArray " : "uniform highp sampler2D ") << p.name << ";\n";
++headerLines;
}
}
@@ -3460,7 +3460,8 @@ ShaderProperty ShaderParser::parseParamDirective(const std::string& argument) {
prop.name.clear(); // signal invalid → caller drops it
return prop;
}
- prop.type = stringToPropertyType(typeStr);
+ prop.layered = typeStr == "textureArray";
+ prop.type = prop.layered ? ShaderPropertyType::Texture : stringToPropertyType(typeStr);
// Extract the contents of a `key(...)` clause from the directive argument.
auto clause = [&](const char* key) -> std::optional<std::string> {
diff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hpp
index 59f350ca2..559708bd4 100644
--- a/src/esengine/resource/ShaderParser.hpp
+++ b/src/esengine/resource/ShaderParser.hpp
@@ -109,6 +109,9 @@ struct ShaderProperty {
i32 std140Offset = -1;
/// Sampler unit for a texture param (>= MATERIAL_TEXTURE_UNIT_BASE), or -1 otherwise.
i32 textureUnit = -1;
+ /// A texture param declared `textureArray`: a 2D texture array, declared `sampler2DArray` /
+ /// `texture_2d_array<f32>` and sampled with a layer index. Everything else is as for `texture`.
+ bool layered = false;
/// Optional editor metadata (range slider bounds, UI hint). Drives the inspector panel;
/// not used in codegen. hasRange == false leaves the field a plain numeric input.
diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cpp
index bb2b26c51..b478f2db8 100644
--- a/tests/renderer/test_shader_variant.cpp
+++ b/tests/renderer/test_shader_variant.cpp
@@ -192,6 +192,47 @@ void main() { fragColor = vec4(1.0); }
#pragma end
)";
+// A `textureArray` param is a texture param in every respect but its declared type.
+static const char* TEXTURE_ARRAY_PARAM = R"(#pragma shader "Layers"
+#pragma version 300 es
+#pragma domain Unlit
+#pragma param u_mask texture default(white)
+#pragma param u_layers textureArray
+
+#pragma fragment
+precision mediump float;
+in vec2 v_texCoord;
+out vec4 fragColor;
+void main() { fragColor = texture(u_layers, vec3(v_texCoord, 1.0)) * texture(u_mask, v_texCoord); }
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ return textureSample(u_layers, u_layers_s, v.v_texCoord, 1) * textureSample(u_mask, u_mask_s, v.v_texCoord);
+}
+#pragma end
+)";
+
+static void testTextureArrayParam() {
+ ParsedShader p = ShaderParser::parse(TEXTURE_ARRAY_PARAM);
+ CHECK(p.valid, "textureArray shader parses");
+ const ShaderProperty* layers = nullptr;
+ for (const auto& prop : p.properties) if (prop.name == "u_layers") layers = &prop;
+ CHECK(layers && layers->type == ShaderPropertyType::Texture && layers->layered && layers->textureUnit == 9,
+ "textureArray is a layered texture param on the next material unit");
+
+ const std::string frag = ShaderParser::assembleStage(p, ShaderStage::Fragment);
+ CHECK(frag.find("uniform highp sampler2DArray u_layers;") != std::string::npos &&
+ frag.find("uniform highp sampler2D u_mask;") != std::string::npos,
+ "GLSL declares the array param as sampler2DArray and the plain one as sampler2D");
+
+ const std::string wgsl = ShaderParser::assembleStage(p, ShaderStage::Fragment, "", {}, ShaderTargetLanguage::WGSL);
+ CHECK(wgsl.find("@group(1) @binding(17) var u_layers : texture_2d_array<f32>;") != std::string::npos &&
+ wgsl.find("@group(1) @binding(25) var u_layers_s : sampler;") != std::string::npos &&
+ wgsl.find("@group(1) @binding(16) var u_mask : texture_2d<f32>;") != std::string::npos,
+ "WGSL declares the array param as texture_2d_array at its unit's bindings");
+}
+
static void testWGSLEmission() {
const auto wgsl = [](const ParsedShader& p, ShaderStage s,
const std::vector<std::string>& features = {}) {
@@ -662,6 +703,7 @@ int main() {
testFragmentOnly();
testHandWrittenFrameBlock();
testWGSLEmission();
+ testTextureArrayParam();
testSystemValuesTrailAttributes();
testVertexHook();
testShadowGraft();
diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cpp
index 3a9f1d324..e77628acc 100644
--- a/tests/renderer/test_webgpu_device.cpp
+++ b/tests/renderer/test_webgpu_device.cpp
@@ -168,6 +168,17 @@ TEST_CASE("binding-mask scan mirrors the declarations an explicit layout carries
CHECK(scanWGSLBindingMask("no bindings here", 0) == 0u);
}
+TEST_CASE("an array texture declaration is told apart from a 2D one by its own binding") {
+ const char* mixed = R"(
+@group(1) @binding(16) var u_albedo : texture_2d_array<f32>;
+@group(1) @binding(17) var u_mask : texture_2d<f32>;
+@group(1) @binding(24) var u_albedo_s : sampler;
+)";
+ CHECK(scanWGSLArrayTextureMask(mixed, 1) == (1u << 16));
+ CHECK(scanWGSLArrayTextureMask(mixed, 0) == 0u);
+ CHECK(scanWGSLDepthTextureMask(mixed, 1) == 0u);
+}
+
TEST_CASE("colour formats that a pass validates apart get variant slots apart") {
// WebGPU validates a pipeline's colour format against the pass and rejects
// the command buffer when they differ. A surface is BGRA and a render target
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index a031b81c5..f866af997 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2822,4 +2822,6 @@ export const NOTED = {
{"note":"Foam is where waves burst, not along every shore."},
"fix(water): a gentle beach keeps less of the breakers' white than rock does":
{"note":"Foam is where waves burst, not along every shore."},
+ "feat(render): 2D texture arrays, created from layers and sampled by textureArray material params":
+ {"internal":"Groundwork for the terrain's layer arrays: a game has no public call that makes an array yet, so the terrain change that uses it carries the note."},
};