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.

fix(import): preserve normal strength and specular glossiness materials

yhh11a4b003d5b4
diff --git a/pipeline/src/assets/gltfImport.ts b/pipeline/src/assets/gltfImport.ts
index 0a77b12d2..3340510c9 100644
--- a/pipeline/src/assets/gltfImport.ts
+++ b/pipeline/src/assets/gltfImport.ts
@@ -46,6 +46,14 @@ interface GltfTextureRef {
extensions?: Record<string, unknown>;
}
+interface GltfSpecularGlossiness {
+ diffuseFactor?: number[];
+ diffuseTexture?: GltfTextureRef;
+ specularFactor?: number[];
+ glossinessFactor?: number;
+ specularGlossinessTexture?: GltfTextureRef;
+}
+
/**
* `EXT_meshopt_compression` on a bufferView: the view's bytes live compressed in
* another buffer, and decoding one yields exactly the bytes the view declares —
@@ -579,18 +587,18 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm
const src = ctx.json.materials?.[index] ?? {};
const label = src.name ? `material "${src.name}"` : `material ${index}`;
const pbr = src.pbrMetallicRoughness ?? {};
- const factor = pbr.baseColorFactor ?? [1, 1, 1, 1];
+ const legacy = src.extensions?.KHR_materials_pbrSpecularGlossiness;
+ const specGloss = src.extensions?.KHR_materials_unlit === undefined && legacy && typeof legacy === 'object'
+ ? legacy as GltfSpecularGlossiness : undefined;
+ const factor = (specGloss ? specGloss.diffuseFactor : pbr.baseColorFactor) ?? [1, 1, 1, 1];
const unused: string[] = [];
- if (src.normalTexture?.scale !== undefined && src.normalTexture.scale !== 1) {
- unused.push(`normal-map scale ${src.normalTexture.scale}`);
- }
const partial: string[] = [];
for (const [name, value] of Object.entries(src.extensions ?? {})) {
if (!SHADING_EXTENSIONS.has(name)) unused.push(name);
// A layer's maps are not carried (the Model shader has no unit left for them): its factors are, and what a
// map would have varied across the surface is said to be flat.
- else if (value && typeof value === 'object'
+ else if (name !== 'KHR_materials_pbrSpecularGlossiness' && value && typeof value === 'object'
&& Object.keys(value).some(key => key.endsWith('Texture'))) partial.push(name);
}
if (unused.length > 0) ctx.warnings.push(`${label}: ${unused.join(', ')} not imported`);
@@ -599,8 +607,8 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm
}
const layers = readShadingLayers(src.extensions ?? {});
- const texture = pbr.baseColorTexture
- ? readTexture(ctx, textureCache, pbr.baseColorTexture, label) : null;
+ const colorTexture = specGloss ? specGloss.diffuseTexture : pbr.baseColorTexture;
+ const texture = colorTexture ? readTexture(ctx, textureCache, colorTexture, label) : null;
// PBR properties are only fallbacks on an unlit material. Reading them as
// shading would change the authored style and upload textures never sampled.
if (src.extensions?.KHR_materials_unlit !== undefined) return {
@@ -613,12 +621,17 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm
};
const normal = src.normalTexture
? readTexture(ctx, textureCache, src.normalTexture, label) : null;
+ const normalScale = src.normalTexture?.scale ?? 1;
+ const validNormalScale = typeof normalScale === 'number' && Number.isFinite(normalScale);
+ if (!validNormalScale) ctx.warnings.push(`${label}: invalid normal-map scale; using 1`);
const emissiveMap = src.emissiveTexture
? readTexture(ctx, textureCache, src.emissiveTexture, label) : null;
const occlusionMap = src.occlusionTexture
? readTexture(ctx, textureCache, src.occlusionTexture, label) : null;
- const metalRoughMap = pbr.metallicRoughnessTexture
+ const metalRoughMap = !specGloss && pbr.metallicRoughnessTexture
? readTexture(ctx, textureCache, pbr.metallicRoughnessTexture, label) : null;
+ const specGlossMap = specGloss?.specularGlossinessTexture
+ ? readTexture(ctx, textureCache, specGloss.specularGlossinessTexture, label) : null;
const strengthExtension = src.extensions?.KHR_materials_emissive_strength as
{ emissiveStrength?: unknown } | undefined;
const strengthValue = strengthExtension?.emissiveStrength === undefined
@@ -653,6 +666,7 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm
cullBackfaces: src.doubleSided !== true,
...(texture ? { baseColorTexture: texture } : {}),
...(normal ? { normalTexture: normal } : {}),
+ ...(normal && validNormalScale && normalScale !== 1 ? { normalScale } : {}),
...(emissive.some(v => v !== 0)
? { emissive: [emissive[0] ?? 0, emissive[1] ?? 0, emissive[2] ?? 0] as [number, number, number] }
: {}),
@@ -661,9 +675,13 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm
occlusionTexture: occlusionMap,
occlusionStrength: src.occlusionTexture?.strength ?? 1,
} : {}),
- metallic,
- roughness,
- ...(metalRoughMap ? { metallicRoughnessTexture: metalRoughMap } : {}),
+ ...(specGloss ? {
+ specularGlossiness: {
+ specular: [specGloss.specularFactor?.[0] ?? 1, specGloss.specularFactor?.[1] ?? 1, specGloss.specularFactor?.[2] ?? 1] as [number, number, number],
+ glossiness: specGloss.glossinessFactor ?? 1,
+ },
+ ...(specGlossMap ? { specularGlossinessTexture: specGlossMap } : {}),
+ } : { metallic, roughness, ...(metalRoughMap ? { metallicRoughnessTexture: metalRoughMap } : {}) }),
...(src.alphaMode === 'MASK' ? { alphaCutoff: src.alphaCutoff ?? 0.5 } : {}),
...(flow ? { flowTexture: flow } : {}),
...(shift ? { shiftTexture: shift } : {}),
@@ -675,6 +693,7 @@ function readMaterial(ctx: MaterialContext, textureCache: Map<number, ImportedIm
/** The extensions that say something about SHADING and are read into the Model shader's layers. */
const SHADING_EXTENSIONS = new Set([
'KHR_materials_unlit',
+ 'KHR_materials_pbrSpecularGlossiness',
'KHR_materials_emissive_strength', 'KHR_materials_clearcoat', 'KHR_materials_sheen', 'KHR_materials_anisotropy',
'KHR_materials_ior', 'KHR_materials_specular', 'KHR_materials_transmission', 'KHR_materials_volume',
'KHR_materials_diffuse_transmission', 'KHR_materials_iridescence',
diff --git a/pipeline/src/assets/importModelFile.ts b/pipeline/src/assets/importModelFile.ts
index ac2bb506a..91033f75a 100644
--- a/pipeline/src/assets/importModelFile.ts
+++ b/pipeline/src/assets/importModelFile.ts
@@ -16,7 +16,7 @@ import { isInsideRoot, resolveInside } from '../fs/pathSandbox';
import { adoptOrphan } from './assetMeta';
import {
encodeImportedMesh, assembleModelPrefab, materialProducts, applyLightmapUV, importedImageSettings,
- generateLods, lodName, encodeGeneratedLod, orderHairTriangles,
+ generateLods, lodName, encodeGeneratedLod, orderHairTriangles, IMPORTED_MATERIAL_IMAGE_SLOTS,
type ImportedMesh, type ImportedNode, type SpecularMapReading,
} from './modelImport';
import { modelStem, readModelSource } from './readModelSource';
@@ -126,7 +126,6 @@ export async function importModelFile(opts: ImportModelOptions): Promise<Importe
// A model exported with the path its artist had on their machine (`E:/props/road/wall.png`) names an image that is not there, and which sits
// beside the model in the project it was brought into: the name alone finds it, as a DCC tool's own import does.
- const slotNames = ['baseColorTexture', 'normalTexture', 'emissiveTexture', 'occlusionTexture', 'metallicRoughnessTexture', 'flowTexture', 'shiftTexture'] as const;
const beside = new Map<string, string>();
for (const [i, uri] of externalFiles.entries()) {
if (existsSync(path.join(sourceDir, uri))) continue;
@@ -139,7 +138,7 @@ export async function importModelFile(opts: ImportModelOptions): Promise<Importe
for (const mesh of meshes) {
const material = mesh.material as Record<string, unknown> | undefined;
if (!material) continue;
- for (const slot of slotNames) {
+ for (const slot of IMPORTED_MATERIAL_IMAGE_SLOTS) {
const image = material[slot] as { external?: boolean; file?: string } | undefined;
const found = image?.external && image.file !== undefined ? beside.get(image.file) : undefined;
if (image && found !== undefined) image.file = found;
@@ -201,11 +200,10 @@ export async function importModelFile(opts: ImportModelOptions): Promise<Importe
// `.psd` the project never had).
const lost = new Set(externalFiles.filter((uri) => !externalRefs.has(uri) && !existsSync(path.join(sourceDir, uri))));
if (lost.size > 0) {
- const slots = ['baseColorTexture', 'normalTexture', 'emissiveTexture', 'occlusionTexture', 'metallicRoughnessTexture', 'flowTexture', 'shiftTexture'] as const;
for (const mesh of meshes) {
const material = mesh.material as Record<string, unknown> | undefined;
if (!material) continue;
- for (const slot of slots) {
+ for (const slot of IMPORTED_MATERIAL_IMAGE_SLOTS) {
const image = material[slot] as { external?: boolean; file?: string } | undefined;
if (image?.external && image.file !== undefined && lost.has(image.file)) delete material[slot];
}
diff --git a/pipeline/src/assets/modelImages.ts b/pipeline/src/assets/modelImages.ts
index ced260c13..d70063c22 100644
--- a/pipeline/src/assets/modelImages.ts
+++ b/pipeline/src/assets/modelImages.ts
@@ -11,15 +11,14 @@
import { PNG } from 'pngjs';
import { decodeDds, isDds } from './ddsDecode';
import { encodeRgbaPng } from './png';
-import type { ImportedImageRef, ImportedMaterial, ModelImportResult } from './modelImport';
+import { IMPORTED_MATERIAL_IMAGE_SLOTS, type ImportedImageRef, type ImportedMaterial, type ModelImportResult } from './modelImport';
-type ImageSlot = 'baseColorTexture' | 'normalTexture' | 'emissiveTexture'
- | 'occlusionTexture' | 'metallicRoughnessTexture';
-const SLOTS: ImageSlot[] = ['baseColorTexture', 'normalTexture', 'emissiveTexture',
- 'occlusionTexture', 'metallicRoughnessTexture'];
+type ImageSlot = typeof IMPORTED_MATERIAL_IMAGE_SLOTS[number];
/** Slots whose texels are numbers, not colour: sampled through sRGB decode they bend. */
-const DATA_SLOTS = new Set<ImageSlot>(['normalTexture', 'occlusionTexture', 'metallicRoughnessTexture']);
+// Specular/glossiness shares the Model shader's packed-map unit. Its RGB is
+// decoded explicitly there, while alpha stays linear.
+const DATA_SLOTS = new Set<ImageSlot>(['normalTexture', 'occlusionTexture', 'metallicRoughnessTexture', 'specularGlossinessTexture', 'flowTexture', 'shiftTexture']);
interface Pixels { width: number; height: number; rgba: Uint8Array }
@@ -234,7 +233,7 @@ export function prepareModelImages(result: ModelImportResult,
for (const material of materials) {
const label = `material "${material.name}"`;
packSeparateMaps(material, label);
- for (const slot of SLOTS) {
+ for (const slot of IMPORTED_MATERIAL_IMAGE_SLOTS) {
const ref = material[slot];
if (!ref) continue;
const { pixels, ref: converted } = load(ref, label);
diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.ts
index 899850cfb..c6cfdf927 100644
--- a/pipeline/src/assets/modelImport.ts
+++ b/pipeline/src/assets/modelImport.ts
@@ -77,6 +77,8 @@ export interface ImportedMaterial {
baseColorTexture?: ImportedImageRef;
/** Tangent-space normal map, read against the mesh's own tangent frame where it has one (see meshTangents.ts). */
normalTexture?: ImportedImageRef;
+ /** Tangent-space X/Y scale, applied before renormalizing the sampled normal. */
+ normalScale?: number;
/** Light the surface makes, unaffected by the scene's lights. */
emissive?: [number, number, number];
emissiveTexture?: ImportedImageRef;
@@ -93,6 +95,9 @@ export interface ImportedMaterial {
roughness?: number;
/** glTF's packing: roughness in green, metal in blue, multiplying the factors. */
metallicRoughnessTexture?: ImportedImageRef;
+ /** Legacy glTF specular/glossiness: diffuse uses baseColor; specular is linear RGB and gloss is linear alpha. */
+ specularGlossiness?: { specular: [number, number, number]; glossiness: number };
+ specularGlossinessTexture?: ImportedImageRef;
/**
* Metalness, roughness and occlusion as the source wrote them: a separate image each, the value in its red channel (roughness
* inverted when the source gave glossiness). Image preparation packs them into the one map above, glTF's way, and removes this.
@@ -145,6 +150,12 @@ export interface ImportedMaterialAsset {
images: ImportedImageRef[];
}
+/** Every image reference carried by an imported material, shared by preparation, copying and missing-file cleanup. */
+export const IMPORTED_MATERIAL_IMAGE_SLOTS = [
+ 'baseColorTexture', 'normalTexture', 'emissiveTexture', 'occlusionTexture',
+ 'metallicRoughnessTexture', 'specularGlossinessTexture', 'flowTexture', 'shiftTexture',
+] as const;
+
/** An image the source carries inline, to be written beside the meshes. */
export interface ImportedTexture {
/** `<stem>_<image index>.<ext>` — named for the source, since an inline image has no name. */
@@ -630,7 +641,8 @@ const MATERIAL_LAYER_PROPERTIES: readonly [keyof ImportedMaterial, string][] = [
*/
function needsMaterial(material: ImportedMaterial | undefined): material is ImportedMaterial {
return !!material && !!(material.unlit || material.normalTexture || material.emissive || material.emissiveTexture
- || material.occlusionTexture || material.alphaCutoff || material.metallicRoughnessTexture
+ || material.occlusionTexture || material.alphaCutoff || material.metallicRoughnessTexture || material.specularGlossiness
+ || (material.normalScale ?? 1) !== 1
|| (material.metallic ?? 0) !== 0 || (material.roughness ?? 1) !== 1
|| MATERIAL_LAYER_PROPERTIES.some(([field]) => material[field] !== undefined));
}
@@ -813,8 +825,8 @@ export function importedImageSettings(meshes: ImportedMesh[]):
const out = new Map<string, { external: boolean; settings: NonNullable<ImportedImageRef['settings']> }>();
for (const mesh of meshes) {
const m = mesh.material;
- for (const image of [m?.baseColorTexture, m?.normalTexture, m?.emissiveTexture,
- m?.occlusionTexture, m?.metallicRoughnessTexture, m?.flowTexture, m?.shiftTexture]) {
+ for (const slot of IMPORTED_MATERIAL_IMAGE_SLOTS) {
+ const image = m?.[slot];
if (!image) continue;
const seen = out.get(image.file);
out.set(image.file, { external: image.external, settings: { ...image.settings, ...seen?.settings } });
@@ -845,7 +857,9 @@ export function materialProducts(meshes: ImportedMesh[], stem: string,
});
continue;
}
- const shading = refs.characters ? characterShading(material) : undefined;
+ // A name-based character preset cannot express specular/glossiness. Keep
+ // that authored BRDF on the general Model shader instead of losing it.
+ const shading = refs.characters && !material.specularGlossiness ? characterShading(material) : undefined;
const images: ImportedImageRef[] = [];
const properties: Record<string, unknown> = {};
@@ -857,7 +871,13 @@ export function materialProducts(meshes: ImportedMesh[], stem: string,
bind('u_normalMap', material.normalTexture);
bind('u_emissiveMap', material.emissiveTexture);
bind('u_occlusionMap', material.occlusionTexture);
- bind('u_metallicRoughnessMap', material.metallicRoughnessTexture);
+ bind('u_metallicRoughnessMap', material.specularGlossiness ? material.specularGlossinessTexture : material.metallicRoughnessTexture);
+ if (material.normalScale !== undefined) properties.u_normalScale = material.normalScale;
+ if (material.specularGlossiness) {
+ const [r, g, b] = material.specularGlossiness.specular;
+ properties.u_specularColor = { r, g, b, a: 1 };
+ properties.u_glossiness = material.specularGlossiness.glossiness;
+ }
// Written even at the engine's own defaults: glTF's are 1 and 1, so a
// product that left them out would read as a surface it is not.
if (material.metallic !== undefined) properties.u_metallic = material.metallic;
@@ -884,9 +904,11 @@ export function materialProducts(meshes: ImportedMesh[], stem: string,
version: MATERIAL_FORMAT_VERSION,
type: 'material',
shader: shading ? `builtin:${shading}` : 'builtin:model',
+ ...(material.specularGlossiness ? { switches: { ES_SPECULAR_GLOSSINESS: true } } : {}),
// Hair is cut out and feathered by coverage, which only an unblended draw gets.
blendMode: material.opaque || shading === 'hair' ? BlendMode.None : BlendMode.Normal,
- depthTest: material.opaque || shading === 'hair',
+ // Blended surfaces still test against opaque geometry in front.
+ depthTest: true,
depthWrite: material.opaque || shading === 'hair',
cull: material.cullBackfaces ? CullMode.Back : CullMode.None,
properties,
diff --git a/pipeline/tests/gltf-import.test.ts b/pipeline/tests/gltf-import.test.ts
index 8292110d0..8411f0fca 100644
--- a/pipeline/tests/gltf-import.test.ts
+++ b/pipeline/tests/gltf-import.test.ts
@@ -210,19 +210,68 @@ describe('glTF material import', () => {
pbrMetallicRoughness: { metallicFactor: 1, roughnessFactor: 0.3 },
normalTexture: { index: 0, scale: 0.4 }, emissiveFactor: [1, 0, 0],
alphaMode: 'MASK', alphaCutoff: 0.4, doubleSided: false,
- extensions: { KHR_materials_pbrSpecularGlossiness: {} },
+ extensions: { EXT_unimplemented_surface: {} },
}];
const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
const line = warnings.join('\n');
- expect(line).toContain('normal-map scale 0.4');
- expect(line).toContain('KHR_materials_pbrSpecularGlossiness');
+ expect(line).not.toContain('normal-map scale');
+ expect(line).toContain('EXT_unimplemented_surface');
// The channels that DO reach a shader are products, not warnings — metal and
// roughness among them now that the lighting model has a view direction.
expect(line).not.toContain('metallic-roughness');
expect(line).not.toContain('emissive');
expect(line).not.toContain('alpha cutoff');
expect(materialProducts(meshes, 'model')[0]!.data.properties)
- .toMatchObject({ u_metallic: 1, u_roughness: 0.3 });
+ .toMatchObject({ u_metallic: 1, u_roughness: 0.3, u_normalScale: 0.4 });
+ });
+
+ it.each([0, 0.5, 2, -1])('preserves normal scale %s through the material product', async scale => {
+ const doc = withInlineImage();
+ (doc.materials as Record<string, unknown>[])[0]!.normalTexture = { index: 0, scale };
+ const result = await importGltfMeshes(gltf(doc), 'normal');
+ expect(result.meshes[0]!.material!.normalScale).toBe(scale);
+ expect(materialProducts(result.meshes, 'normal')[0]!.data.properties.u_normalScale).toBe(scale);
+ expect(result.warnings.join('\n')).not.toContain('normal-map scale');
+ });
+
+ it('reports an invalid normal scale and keeps the default', async () => {
+ const doc = withInlineImage();
+ (doc.materials as Record<string, unknown>[])[0]!.normalTexture = { index: 0, scale: 'wrong' };
+ const result = await importGltfMeshes(gltf(doc), 'normal');
+ expect(result.meshes[0]!.material!.normalScale).toBeUndefined();
+ expect(result.warnings.join('\n')).toContain('invalid normal-map scale');
+ });
+
+ it('prefers specular/glossiness to the metallic fallback and preserves its diffuse alpha and packed map', async () => {
+ const doc = withInlineImage();
+ doc.images = [{ uri: 'diffuse.png' }, { uri: 'specular.png' }, { uri: 'unused-fallback.png' }];
+ doc.textures = [{ source: 0 }, { source: 1 }, { source: 2 }];
+ doc.materials = [{
+ name: 'Skin', alphaMode: 'MASK', alphaCutoff: 0.3,
+ pbrMetallicRoughness: { baseColorFactor: [1, 0, 0, 1], baseColorTexture: { index: 2 }, metallicFactor: 1, roughnessFactor: 1 },
+ extensions: { KHR_materials_pbrSpecularGlossiness: {
+ diffuseFactor: [0.2, 0.4, 0.6, 0.8], diffuseTexture: { index: 0 },
+ specularFactor: [0.08, 0.16, 0.24], glossinessFactor: 0.7, specularGlossinessTexture: { index: 1 },
+ } },
+ }];
+ const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'legacy');
+ const material = meshes[0]!.material!;
+ expect(material).toMatchObject({ baseColor: [0.2, 0.4, 0.6, 0.8], baseColorTexture: { file: 'diffuse.png' }, specularGlossiness: { specular: [0.08, 0.16, 0.24], glossiness: 0.7 }, specularGlossinessTexture: { file: 'specular.png' } });
+ expect(material.metallic).toBeUndefined();
+ expect(material.roughness).toBeUndefined();
+ const product = materialProducts(meshes, 'legacy', { characters: true })[0]!;
+ expect(product.data).toMatchObject({ shader: 'builtin:model', switches: { ES_SPECULAR_GLOSSINESS: true }, properties: { u_specularColor: { r: 0.08, g: 0.16, b: 0.24, a: 1 }, u_glossiness: 0.7, u_alphaCutoff: 0.3 } });
+ expect(product.images.map(i => i.file)).toEqual(['specular.png']);
+ expect(warnings.join('\n')).not.toContain('not imported');
+ });
+
+ it('uses the specular/glossiness defaults even when the metallic fallback says something else', async () => {
+ const doc = withInlineImage();
+ (doc.materials as Record<string, unknown>[])[0]!.extensions = { KHR_materials_pbrSpecularGlossiness: {} };
+ const { meshes } = await importGltfMeshes(gltf(doc), 'legacy');
+ expect(meshes[0]!.material).toMatchObject({ baseColor: [1, 1, 1, 1], specularGlossiness: { specular: [1, 1, 1], glossiness: 1 } });
+ expect(meshes[0]!.material!.baseColorTexture).toBeUndefined();
+ expect(materialProducts(meshes, 'legacy')).toHaveLength(1);
});
it('is opaque and single-sided unless the source says otherwise', async () => {
@@ -462,14 +511,15 @@ describe('glTF material products', () => {
? undefined : { r: strength, g: strength * 0.5, b: 0, a: 1 });
});
- it('defaults an omitted strength to one and still reports unsupported extensions', async () => {
+ it('defaults an omitted emissive strength to one on a specular/glossiness material', async () => {
const doc = shaded({
emissiveFactor: [1, 0.5, 0],
extensions: { KHR_materials_emissive_strength: {}, KHR_materials_pbrSpecularGlossiness: {} },
});
const { meshes, warnings } = await importGltfMeshes(gltf(doc), 'model');
expect(meshes[0]!.material?.emissive).toEqual([1, 0.5, 0]);
- expect(warnings).toEqual(['material "Shaded": KHR_materials_pbrSpecularGlossiness not imported']);
+ expect(meshes[0]!.material?.specularGlossiness).toEqual({ specular: [1, 1, 1], glossiness: 1 });
+ expect(warnings).toEqual([]);
});
it('carries the shading layers its extensions state, as the Model shader parameters', async () => {
@@ -544,7 +594,7 @@ describe('glTF material products', () => {
emissiveFactor: [1, 1, 1], alphaMode: 'BLEND', doubleSided: true,
}));
expect(blended.products[0]!.data).toMatchObject({
- blendMode: BlendMode.Normal, depthTest: false, depthWrite: false, cull: CullMode.None,
+ blendMode: BlendMode.Normal, depthTest: true, depthWrite: false, cull: CullMode.None,
});
});
diff --git a/pipeline/tests/model-images.test.ts b/pipeline/tests/model-images.test.ts
index 7dff2125f..3f69274e0 100644
--- a/pipeline/tests/model-images.test.ts
+++ b/pipeline/tests/model-images.test.ts
@@ -7,7 +7,7 @@ import { describe, it, expect } from 'vitest';
import { PNG } from 'pngjs';
import { prepareModelImages } from '../src/assets/modelImages';
import { encodeRgbaPng } from '../src/assets/png';
-import type { ImportedMaterial, ModelImportResult } from '../src/assets/modelImport';
+import { importedImageSettings, type ImportedMaterial, type ModelImportResult } from '../src/assets/modelImport';
/** An 8x8 uncompressed BGRA DDS, every texel `bgra`. */
function dds(bgra: number[]): Uint8Array {
@@ -38,6 +38,19 @@ function model(material: Partial<ImportedMaterial>, externalFiles: string[] = []
}
describe('preparing a model\'s images', () => {
+ it('retains specular RGB and linear gloss alpha while scheduling one explicit shader decode', () => {
+ const packed = png(i => [40 + i, 100, 180, 70 + i]);
+ const result = model({
+ specularGlossiness: { specular: [1, 1, 1], glossiness: 1 },
+ specularGlossinessTexture: { file: 'packed.png', external: true, settings: { sRGB: true, wrapMode: 'clamp' } },
+ }, ['packed.png']);
+ prepareModelImages(result, () => packed);
+ expect(result.meshes[0]!.material!.specularGlossinessTexture).toEqual({ file: 'packed.png', external: true, settings: { sRGB: false, wrapMode: 'clamp' } });
+ expect(importedImageSettings(result.meshes).get('packed.png')?.settings).toMatchObject({ sRGB: false, wrapMode: 'clamp' });
+ expect(result.textures).toEqual([]);
+ expect(result.externalFiles).toEqual(['packed.png']);
+ });
+
it('turns an external DDS into an embedded PNG, keeping its sampler settings', () => {
const files: Record<string, Uint8Array> = { 'Textures/Wall.dds': dds([30, 20, 10, 255]) };
const result = model({ baseColorTexture: { file: 'Textures/Wall.dds', external: true, settings: { wrapMode: 'clamp' } } },
diff --git a/pipeline/tests/model-missing-texture.test.ts b/pipeline/tests/model-missing-texture.test.ts
index 3e25bbeb5..9682ccbc5 100644
--- a/pipeline/tests/model-missing-texture.test.ts
+++ b/pipeline/tests/model-missing-texture.test.ts
@@ -10,7 +10,7 @@ import path from 'node:path';
import { afterAll, describe, expect, it } from 'vitest';
import { importModelFile } from '../src/assets/importModelFile';
-function triangleGltf(image: string): string {
+function triangleGltf(image: string, specularGlossiness = false): string {
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
const indices = new Uint16Array([0, 1, 2, 0]);
const bytes = Buffer.concat([Buffer.from(positions.buffer), Buffer.from(indices.buffer)]);
@@ -18,7 +18,9 @@ function triangleGltf(image: string): string {
asset: { version: '2.0' },
scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: 'tri' }],
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
- materials: [{ name: 'wall', pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],
+ materials: [specularGlossiness
+ ? { extensions: { KHR_materials_pbrSpecularGlossiness: { specularGlossinessTexture: { index: 0 } } } }
+ : { name: 'wall', pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],
textures: [{ source: 0 }], images: [{ uri: image }],
buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36, target: 34962 }, { buffer: 0, byteOffset: 36, byteLength: 6, target: 34963 }],
@@ -33,12 +35,12 @@ describe('a model that names a texture the project does not have', () => {
const roots: string[] = [];
afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); });
- async function run(image: string, withFile: boolean, besideAs = image) {
+ async function run(image: string, withFile: boolean, besideAs = image, specularGlossiness = false) {
const root = mkdtempSync(path.join(tmpdir(), 'model-missing-'));
roots.push(root);
const src = path.join(root, 'assets', 'models');
mkdirSync(src, { recursive: true });
- writeFileSync(path.join(src, 'tri.gltf'), triangleGltf(image));
+ writeFileSync(path.join(src, 'tri.gltf'), triangleGltf(image, specularGlossiness));
if (withFile) writeFileSync(path.join(src, besideAs), Buffer.from('89504e470d0a1a0a', 'hex'));
const result = await importModelFile({ root, destDir: 'assets/models', absSource: path.join(src, 'tri.gltf') });
const text = readdirSync(src).map((f) => (/\.(esprefab|esmaterial)$/.test(f) ? readFileSync(path.join(src, f), 'utf8') : '')).join('\n');
@@ -69,4 +71,19 @@ describe('a model that names a texture the project does not have', () => {
expect(result.warnings.some((w) => w.includes('wall.png'))).toBe(true);
expect(text).not.toContain('E:/');
});
+
+ it('repairs a specular/glossiness map from beside the model', async () => {
+ const { result, text } = await run('E:/props/sg.png', true, 'sg.png', true);
+ expect(result.warnings.some(w => w.includes('is not there'))).toBe(false);
+ expect(text).toContain('"u_metallicRoughnessMap": "sg.png"');
+ expect(text).toContain('u_metallicRoughnessMap');
+ expect(text).not.toContain('E:/');
+ });
+
+ it('removes a missing specular/glossiness map and keeps its workflow', async () => {
+ const { result, text } = await run('E:/props/sg.png', false, 'sg.png', true);
+ expect(result.warnings.some(w => w.includes('sg.png'))).toBe(true);
+ expect(text).not.toContain('sg.png');
+ expect(text).toContain('ES_SPECULAR_GLOSSINESS');
+ });
});