Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions DolphinDotNet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DisplayConfigurationSmoke",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HardwareAssetCompatibilityPolicyTests", "tests\HardwareAssetCompatibilityPolicyTests\HardwareAssetCompatibilityPolicyTests.csproj", "{8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StreamableTextureTests", "tests\StreamableTextureTests\StreamableTextureTests.csproj", "{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -177,6 +179,10 @@ Global
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000016}.Release|Any CPU.Build.0 = Release|Any CPU
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -204,6 +210,7 @@ Global
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000014} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068}
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000015} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068}
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000016} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068}
{8A1D0B64-59B7-44F6-A0A9-4AD8FC000090} = {8A1D0B64-59B7-44F6-A0A9-4AD8FC000068}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8A1D0B64-59B7-44F6-A0A9-4AD8FC0003E7}
Expand Down
68 changes: 68 additions & 0 deletions docs/streamable-textures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Independently streamable texture levels

DNLT v1 (`.dnlod`) stores independently checksummed GX-native images. Level 0 is
the finest; physical payload order is coarsest first. A header/index read is
sufficient to discover levels; image payloads are validated separately, after
bounded reads. This format does not change DNTX v1/v2 or `StreamingTexture`.

```sh
dnd-assets texture grass.png grass.dnlod --streamable --mipmaps --format cmpr
dnd-assets texture grass.png grass.dnlod --streamable --mipmaps --format rgba8 --min-size 8
dnd-assets texture grass.png grass.dnlod --streamable --mipmaps --levels 0,2,4 --gutter 4
dnd-assets texture --low grass_low.png --high grass_high.png grass.dnlod --streamable --quality-pair
```

`--format auto` (default) uses CMPR for opaque/binary-alpha images and RGBA8 for
smooth alpha. Explicit CMPR rejects smooth alpha rather than making it opaque.
Mips use premultiplied-aware box filtering in byte/sRGB space. Binary CMPR mip
coverage retains the nearest representable number of opaque texels, with stable
raster-order ties. CMPR encoding is deterministic RGB565 endpoint quantization
and nearest-palette matching; it is not a perceptual/high-effort compressor.

`--min-size` is a power-of-two cutoff for the largest dimension; short axes
clamp at 1. `--levels` preserves the original mip exponents and must lie above
the cutoff. A low/high pair has exactly HIGH (0) and LOW (1), accepts independent
non-power-of-two dimensions and never synthesizes intermediate images. Without
`--mipmaps`, a standalone streamable image has one entry and flags 0.

`--gutter` extrudes 0–16 border pixels around each independently stored image.
The index includes per-level source-normalized scale/offset mappings. These
identify a finite positive usable rectangle within the native image; source
mip dimensions (native dimensions times UV scale) must follow the authored
half-size progression. Compose these mappings with authored/scrolled material
UVs instead of modifying mesh geometry. Guttered native dimensions must still
fit the 1024-texel limit. Native padding replicates edge texels.

The tool also writes `OUTPUT.manifest.json`: deterministic level dimensions,
byte ranges, CRC32, UV mappings, format/alpha decisions and source RGBA hashes.
CLI manifests additionally include the encoded source-file SHA-256 hashes.

## Binary contract

All metadata is little endian. The 64-byte header is: magic `DNLT`, version 1,
flags (1 mip chain, 2 sparse mips, 4 quality pair), logical full width/height,
default GX format, entry count, initial coarse entry index, table offset (64),
first data offset, file length, metadata CRC32, optional UV-table offset and
length, then eight zero-reserved bytes. Flags 0 describe one standalone image;
valid mip flag combinations are 1 and 3; quality pair is 4.

Each 32-byte table entry is logical LOD (u32), native width/height (u16 each),
GX format (u32: 6 RGBA8 or 14 CMPR), zero flags, offset, padded native byte count,
payload CRC32 and zero reserved. Table order is increasing logical LOD. The
optional UV table follows immediately: float32 scaleU, scaleV, offsetU, offsetV
for each entry. Metadata CRC32 covers both tables, excluding the header/padding.
An absent UV table means identity. Payloads are contiguous, 32-byte aligned and
ordered from coarsest to finest; total file length is bounded to 16 MiB.
RGBA8 uses 4×4, 64-byte tiles; CMPR uses 8×8, 32-byte tiles, including tiny mips.

`Dolphin.Formats.StreamableTextureDescriptor.GetMetadataBytes(header, fileLength)`
validates a 64-byte header before a bounded metadata read. `Read(prefix,
fileLength)` validates metadata without touching payloads and returns an
immutable descriptor. `GetLevel` returns independent native ranges, logical
exponents and UV mappings. Validate each payload using its CRC, or incrementally
with `ComputeCrc32(..., initial)`, before GPU publication. Descriptor parsing
never allocates GPU resources and never implicitly reads a complete file.

Run `dotnet run --project tests/StreamableTextureTests -c Release` for independent
BTI pixel decoding, coverage/filtering, sparse/pair/gutter cases, corrupt-header
and truncation checks, fuzz inputs and DNTX compatibility checks.
1 change: 1 addition & 0 deletions scripts/ci_test_suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ def main(area):
build("tests/GraphicsPhaseOneSmoke/GraphicsPhaseOneSmoke.csproj")
build("tests/GraphicsPhaseTwoSmoke/GraphicsPhaseTwoSmoke.csproj")
test("tests/TextureStreamingTests")
test("tests/StreamableTextureTests")
test("tests/EffectCompilerTests")
with tempfile.TemporaryDirectory() as tmp:
run("dotnet","run","--project","tests/ModelAssetTests","-c","Release","--",tmp)
Expand Down
116 changes: 116 additions & 0 deletions src/DolphinDotNet.Core/Dolphin/Formats/StreamableTextureDescriptor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
using System;
using System.IO;

namespace Dolphin.Formats;

[Flags]
public enum StreamableTextureFlags { None=0, MipChain=1, SparseLevels=2, QualityPair=4 }

/// <summary>Static source-normalized UV mapping for one independently stored image.</summary>
public readonly struct TextureLodUv
{
public readonly float ScaleU,ScaleV,OffsetU,OffsetV;
public TextureLodUv(float scaleU,float scaleV,float offsetU,float offsetV)
{ScaleU=scaleU;ScaleV=scaleV;OffsetU=offsetU;OffsetV=offsetV;}
public static TextureLodUv Identity=>new TextureLodUv(1,1,0,0);
}

public readonly struct StreamableTextureLevel
{
public readonly int LogicalLod,Width,Height,Format,Offset,Length;
public readonly uint Crc32;
public readonly TextureLodUv Uv;
internal StreamableTextureLevel(int lod,int width,int height,int format,int offset,int length,uint crc,TextureLodUv uv)
{LogicalLod=lod;Width=width;Height=height;Format=format;Offset=offset;Length=length;Crc32=crc;Uv=uv;}
}

/// <summary>Immutable, header/index-only DNLT v1 descriptor. Reading this type never
/// reads a payload or allocates GPU resources. DNTX v1/v2 are separate formats.</summary>
public sealed class StreamableTextureDescriptor
{
public const int HeaderBytes=64,EntryBytes=32,MaximumLevels=11,MaximumFileBytes=16*1024*1024;
private readonly StreamableTextureLevel[] levels;
public int Width {get;}
public int Height {get;}
public int DefaultFormat {get;}
public int FileLength {get;}
public int MetadataBytes {get;}
public int CoarseIndex=>levels.Length-1;
public int Count=>levels.Length;
public StreamableTextureFlags Flags {get;}
public bool IsQualityPair=>(Flags&StreamableTextureFlags.QualityPair)!=0;
private StreamableTextureDescriptor(int width,int height,int format,int fileLength,int metadataBytes,StreamableTextureFlags flags,StreamableTextureLevel[] levels)
{Width=width;Height=height;DefaultFormat=format;FileLength=fileLength;MetadataBytes=metadataBytes;Flags=flags;this.levels=levels;}
public StreamableTextureLevel GetLevel(int index)
{if(index<0||index>=levels.Length)throw new ArgumentOutOfRangeException("index");return levels[index];}
private static void Need(bool valid,string reason){if(!valid)throw new InvalidDataException("DNLT: "+reason);}
private static uint U32(byte[] b,int at)
{return (uint)(b[at]|b[at+1]<<8|b[at+2]<<16|b[at+3]<<24);}
private static int Int(byte[] b,int at)
{uint value=U32(b,at);Need(value<=int.MaxValue,"integer overflow");return (int)value;}
private static int U16(byte[] b,int at)=>b[at]|b[at+1]<<8;
private static float Float(byte[] b,int at)=>Dolphin.Numerics.BitConverter.Int32BitsToSingle((int)U32(b,at));
private static bool Finite(float x)=>!float.IsNaN(x)&&!float.IsInfinity(x);
public static uint ComputeCrc32(byte[] bytes,int offset,int count,uint initial=0)
{
if(bytes==null)throw new ArgumentNullException("bytes");
if(offset<0||count<0||offset>bytes.Length||count>bytes.Length-offset)throw new ArgumentOutOfRangeException("count");
uint crc=~initial;for(int i=offset;i<offset+count;i++){crc^=bytes[i];for(int bit=0;bit<8;bit++)crc=(crc>>1)^((crc&1)!=0?0xedb88320u:0);}return ~crc;
}
public static int NativeByteCount(int width,int height,int format)
{
Need(width>0&&height>0&&width<=1024&&height<=1024,"native dimensions");
Need(format==6||format==14,"unsupported GX format");
return format==6?((width+3)/4)*((height+3)/4)*64:((width+7)/8)*((height+7)/8)*32;
}
/// <summary>Validate the fixed header before issuing the bounded metadata read.</summary>
public static int GetMetadataBytes(byte[] header,int actualFileLength=-1)
{
if(header==null)throw new ArgumentNullException("header");Need(header.Length>=HeaderBytes,"truncated header");
Need(U32(header,0)==0x544c4e44&&Int(header,4)==1,"magic/version");
int flags=Int(header,8),count=Int(header,24),uv=Int(header,48),uvBytes=Int(header,52),length=Int(header,40);
Need((flags==0||flags==1||flags==3||flags==4)&&count>0&&count<=MaximumLevels,"flags/level count");
Need(flags!=4||count==2,"quality pair count");Need(flags!=0||count==1,"single-image count");
int tableEnd=HeaderBytes+count*EntryBytes;
Need(Int(header,32)==HeaderBytes&&Int(header,28)==count-1,"index/coarse entry");
Need((uv==0&&uvBytes==0)||(uv==tableEnd&&uvBytes==count*16),"UV table range");
int metadata=tableEnd+uvBytes,data=(metadata+31)&~31;
Need(Int(header,36)==data&&length>=data&&length<=MaximumFileBytes&&(length&31)==0,"data/file bounds");
Need(actualFileLength<0||length==actualFileLength,"declared file length");
Need(U32(header,56)==0&&U32(header,60)==0,"reserved header fields");
int width=Int(header,12),height=Int(header,16);NativeByteCount(width,height,Int(header,20));
if((flags&1)!=0)Need((width&(width-1))==0&&(height&(height-1))==0,"mip logical dimensions must be powers of two");
return metadata;
}
public static StreamableTextureDescriptor Read(byte[] prefix,int actualFileLength=-1)
{
int metadata=GetMetadataBytes(prefix,actualFileLength);Need(prefix.Length>=metadata,"truncated metadata");
int count=Int(prefix,24),width=Int(prefix,12),height=Int(prefix,16),uvOffset=Int(prefix,48),flags=Int(prefix,8);
Need(ComputeCrc32(prefix,HeaderBytes,metadata-HeaderBytes)==U32(prefix,44),"metadata checksum");
int maxLod=0,largest=Math.Max(width,height);while(largest>1){maxLod++;largest/=2;}
var levels=new StreamableTextureLevel[count];int previous=-1;
for(int i=0;i<count;i++){
int at=HeaderBytes+i*EntryBytes,lod=Int(prefix,at),w=U16(prefix,at+4),h=U16(prefix,at+6),format=Int(prefix,at+8),offset=Int(prefix,at+16),length=Int(prefix,at+20);
Need(lod>previous&&lod<MaximumLevels,"unordered/duplicate logical level");previous=lod;
Need(U32(prefix,at+12)==0&&U32(prefix,at+28)==0,"entry flags/reserved fields");
Need(length==NativeByteCount(w,h,format)&&(offset&31)==0,"native size/alignment");
Need(offset>=Int(prefix,36)&&offset<=Int(prefix,40)&&length<=Int(prefix,40)-offset,"payload bounds");
var uv=uvOffset==0?TextureLodUv.Identity:new TextureLodUv(Float(prefix,uvOffset+i*16),Float(prefix,uvOffset+i*16+4),Float(prefix,uvOffset+i*16+8),Float(prefix,uvOffset+i*16+12));
Need(Finite(uv.ScaleU)&&Finite(uv.ScaleV)&&Finite(uv.OffsetU)&&Finite(uv.OffsetV),"nonfinite UV transform");
Need(uv.ScaleU>0&&uv.ScaleV>0&&uv.OffsetU>=0&&uv.OffsetV>=0&&uv.ScaleU+uv.OffsetU<=1.00001f&&uv.ScaleV+uv.OffsetV<=1.00001f,"UV usable rectangle");
if((flags&1)!=0){
Need(lod<=maxLod,"logical mip exponent");
Need(Math.Abs(w*uv.ScaleU-Math.Max(1,width>>lod))<.02f&&Math.Abs(h*uv.ScaleV-Math.Max(1,height>>lod))<.02f,"mip half-size progression");
}else Need(lod==i&&(i!=0||(Math.Abs(w*uv.ScaleU-width)<.02f&&Math.Abs(h*uv.ScaleV-height)<.02f)),"HIGH/LOW quality pair");
levels[i]=new StreamableTextureLevel(lod,w,h,format,offset,length,U32(prefix,at+24),uv);
}
if(flags==1){Need(count==maxLod+1,"incomplete full mip chain");for(int i=0;i<count;i++)Need(levels[i].LogicalLod==i,"missing full-chain mip");}
int cursor=Int(prefix,36);for(int i=count-1;i>=0;i--){Need(levels[i].Offset==cursor,"coarse-first payload order or overlap");cursor+=levels[i].Length;}
Need(cursor==Int(prefix,40),"trailing or missing payload bytes");
return new StreamableTextureDescriptor(width,height,Int(prefix,20),cursor,metadata,(StreamableTextureFlags)flags,levels);
}
/// <summary>Check a complete payload, or pass chunk results incrementally to
/// ComputeCrc32 and compare with GetLevel(index).Crc32 before publication.</summary>
public bool ValidatePayload(int index,byte[] bytes,int offset=0)
{var level=GetLevel(index);return ComputeCrc32(bytes,offset,level.Length)==level.Crc32;}
}
Loading
Loading