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
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on:
push:
branches: [main]
pull_request:
branches: [main, feature/model-import-compatibility-phase1, codex/asset-throughput, codex/texture-stage-timings, feature/iso-defrag-planning-and-evacuation]
branches: [main, feat/streamable-texture-assets, feature/model-import-compatibility-phase1, codex/asset-throughput, codex/texture-stage-timings, feature/iso-defrag-planning-and-evacuation]
workflow_dispatch:

permissions:
Expand Down
43 changes: 43 additions & 0 deletions docs/streamable-textures.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,46 @@ 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.

## Detached runtime uploads

`DetachedTextureUpload.Create(width, height, format, nativeBytes, crc32)` owns
one private allocation, charged through `StagedBytes`. Between frames, read at
most your configured chunk budget into a reusable aligned `NativeBuffer`, then
await `StageChunkAsync(source, sourceOffset, destinationOffset, count)`. Chunks
must be sequential, contiguous and 32-byte aligned. Both allocations stay held
until the service copy and application continuation finish. Do not mutate raw
addresses while held; normal buffer writes and storage reads reject reuse.

`CompletedBytes` observes the completed task and incremental native-source CRC.
`Seal()` rejects missing bytes or a checksum mismatch. `TryPublish` invalidates
the GX texture cache on the application executor and transfers one immutable
`Texture2D` to the caller. No copy or global GPU wait occurs at publication.
The owner no longer counts the allocation after transfer; the caller counts
`Texture2D.NativeBytes` as active, and later as retired.

On cancellation, await `AbortAsync()` before reusing either allocation.
`Dispose()` refuses a running copy; it cancels queued work but never frees
memory under a worker. Failed uploads cannot publish. No whole-image managed
staging array or permanent second texture is required. Existing
`StreamingTexture` keeps its fixed-size front/back contract.

Compose authored animation with each level's static usable rectangle using
`authored.Then(levelMapping)`. `UvTransform.Then` preserves a complete affine
matrix, including nonuniform gutters after rotation; no geometry rebuild or
lossy decomposition into scale/rotation is necessary.

Record the final reader using `GraphicsDevice.InsertFence()`. Once the texture
is removed from all draw bindings, `Texture2D.TryDisposeAfterFence(fence)` frees
it only when that fence completes, without another GPU wait. A fence cannot
protect later submissions: resolve and pin immediately before drawing, and
never submit a retired texture. Normal `Dispose()` retains its conservative
existing behavior.

Run `python3 scripts/ci_detached_textures.py` for native range/lifetime tests
and Debug/Release managed AOT with GC stress. Build
`tests/fixtures/DetachedTextures` and run
`python3 scripts/dolphin_detached_textures.py Game.dol --logs out/fresh-capture`
for repeated RGBA8/CMPR resolution changes and independent pixel-patch checks.
The fixture uses two explicitly counted 32-KiB source buffers, with at most one
detached destination per lane. Emulator timings are not console measurements.
6 changes: 6 additions & 0 deletions include/dnd_draw.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ int dnd_texture_package(DndArray *package,int linear);
int dnd_texture_ipl_font(DndArray *metadata,int linear);
int dnd_texture_sampler(int token,int wrap_s,int wrap_t,int min_filter,int mag_filter,float lod_bias);
int dnd_texture_allocate_native(int width,int height,int format,int linear);
int dnd_texture_allocate_detached(int width,int height,int format,int linear);
int dnd_texture_upload_hold(int token);
int dnd_texture_upload_unhold(int token);
int dnd_texture_stage_buffer_range(int texture_token,int buffer_token,int source_offset,int destination_offset,int count);
/* Caller supplies the final reader fence; successful release never waits on GX. */
int dnd_texture_release_completed(int token,int fence);
int dnd_texture_update_native(int token,DndArray *payload,int source_offset,int count);
int dnd_texture_update_buffer(int texture_token,int buffer_token,int source_offset,int count);
/* CPU-only staging to a texture allocation that is NOT referenced by in-flight GX
Expand Down
12 changes: 12 additions & 0 deletions scripts/ci_detached_textures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Exercise native lifetime guards and the managed owner through actual AOT."""
from pathlib import Path
import tempfile
import sys
from ci_graphics_phase_one import main,run
if __name__=='__main__':
with tempfile.TemporaryDirectory(prefix='dnd-detached-') as folder:
binary=Path(folder)/'ranges'
dead='-Wl,-dead_strip' if sys.platform=='darwin' else '-Wl,--gc-sections'
run('cc','-std=c11','-Wall','-Wextra','-Werror','-O1','-ffunction-sections','-fdata-sections','-Iinclude','tests/detached_texture_test.c','source/draw_resources.c',dead,'-lm','-o',binary)
run(binary)
main('DetachedTextureUploadSmoke','detached_texture_host.c')
1 change: 1 addition & 0 deletions scripts/ci_test_suite.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ def main(area):
if source=="audio_formats_test":run(binary,tmp)
else:run(binary)
elif area=="graphics":
run("python3","scripts/ci_detached_textures.py") # DetachedTextureUploadSmoke (Debug/Release AOT + GC stress)
run("python3","scripts/ci_display.py") # DisplayConfigurationSmoke
run("python3","scripts/ci_graphics_phase_one.py")
run("python3","scripts/ci_graphics_phase_two.py")
Expand Down
27 changes: 27 additions & 0 deletions scripts/dolphin_detached_textures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""RGBA8/CMPR pixel consistency under repeated detached resolution swaps."""
import argparse
from pathlib import Path
from dolphin_texture_test import FRAME_BYTES,run
def validate_capture(raw):
if len(raw)%FRAME_BYTES or len(raw)//FRAME_BYTES<60:raise AssertionError('Insufficient complete frames')
publications=[]
for start in range(len(raw)-30*FRAME_BYTES,len(raw),FRAME_BYTES):
rgb=raw[start:start+FRAME_BYTES]
for left in (32,352):
for dx,dy,color in ((64,64,(255,0,0)),(192,64,(0,255,0)),(64,192,(255,0,255)),(192,192,(0,255,255))):
at=((80+dy)*640+left+dx)*3
if max(abs(a-b) for a,b in zip(rgb[at:at+3],color))>12:raise AssertionError('Corrupt or missing detached pixels')
fields=[]
for k in range(6):
value=0
for bit in range(16):
at=(404*640+32+(k*16+bit)*6+2)*3
if sum(rgb[at:at+3])>384:value|=1<<bit
fields.append(value)
if fields[0]!=0x444c or min(fields[2:4])<4:raise AssertionError('Insufficient resolution swaps')
publications.append(fields[2:4])
return dict(validatedTailFrames=30,rgba8Publications=publications[-1][0],cmprPublications=publications[-1][1],pixelPatches=8)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('dol',type=Path);p.add_argument('--logs',type=Path,required=True);p.add_argument('--seconds',type=float,default=25);p.add_argument('--backend',choices=['OGL','Software'],default='OGL')
a=p.parse_args();a.streaming=a.benchmark=False;a.mode='detached';a.binary='/usr/games/dolphin-emu-nogui'
run(a,validate_capture)
50 changes: 44 additions & 6 deletions source/draw_resources.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ typedef struct {
void *allocation;
unsigned char *data;
int kind,bytes,generation;
bool pending,io_busy;
bool pending,io_busy,detached;
bool uniform_color;
uint32_t mesh_color;
int holds,geometry,extra_bytes;
int holds,geometry,extra_bytes,staged_bytes;
void *command_allocation;
unsigned char *commands;
float logical_width,logical_height;
Expand Down Expand Up @@ -97,8 +97,9 @@ static void release(Resource *r) {
int dnd_draw_release(int token) {
if(dnd_raw_depth() || token==active_canvas) return -1;
Resource *r=find(token,0); if(!r) return -1;
if(r->detached&&!r->holds){release(r);return 0;}
if(dnd_device_active() || r->holds) r->pending=true;
else { dnd_draw_backend_wait(); release(r); }
else { if(!r->detached)dnd_draw_backend_wait(); release(r); }
return 0;
}
void dnd_draw_collect(void) { for(int i=0;i<SLOTS;i++) if(slots[i].pending && !slots[i].holds) release(&slots[i]); }
Expand Down Expand Up @@ -155,7 +156,7 @@ static bool array_range(DndArray *a,int index,int count) {
}
int dnd_buffer_copy(int token,int offset,DndArray *array,int index,int count,int write) {
Resource *r=find(token,BUFFER);
if(dnd_raw_depth() || dnd_device_active() || !r || r->io_busy || !array_range(array,index,count) || offset<0 || offset>r->bytes || (size_t)count*array->element_size>(size_t)(r->bytes-offset)) return -1;
if(dnd_raw_depth() || dnd_device_active() || !r || r->io_busy || (write&&r->holds) || !array_range(array,index,count) || offset<0 || offset>r->bytes || (size_t)count*array->element_size>(size_t)(r->bytes-offset)) return -1;
void *p=(unsigned char*)array->data+(size_t)index*array->element_size;
if(write) memcpy(r->data+offset,p,(size_t)count*array->element_size);
else memcpy(p,r->data+offset,(size_t)count*array->element_size);
Expand Down Expand Up @@ -222,6 +223,41 @@ int dnd_texture_allocate_native(int w,int h,int format,int linear) {
dnd_draw_backend_flush(r->data,bytes,2);
return token;
}
/* The detached target is private until publication. No GX command/cache
* invalidation is needed to allocate it; CPU staging flushes exact ranges. */
int dnd_texture_allocate_detached(int w,int h,int format,int linear) {
dnd_async_require_application_thread();
int bytes=texture_size(w,h,format);
if(dnd_device_active()||dnd_raw_depth()||bytes<0||(linear!=0&&linear!=1))return 0;
int token=create(TEXTURE,bytes,32);Resource *r=find(token,TEXTURE);if(!r)return 0;
r->width=w;r->height=h;r->format=format;r->linear=linear;r->detached=true;return token;
}
int dnd_texture_upload_hold(int token) {
dnd_async_require_application_thread();Resource *r=find(token,TEXTURE);
if(!r||!r->detached||r->holds)return -1;
r->holds++;return 0;
}
int dnd_texture_upload_unhold(int token) {
dnd_async_require_application_thread();int index=(token&1023)-1;
if(token<=0||index<0||index>=SLOTS)return -1;
Resource *r=&slots[index];
if(r->kind!=TEXTURE||r->generation!=(token>>10)||!r->detached||r->holds<=0)return -1;
if(--r->holds==0&&r->pending)release(r);
return 0;
}
int dnd_texture_stage_buffer_range(int token,int buffer_token,int source_offset,int destination_offset,int count) {
int index=(token&1023)-1;if(token<=0||index<0||index>=SLOTS)return -1;Resource *r=&slots[index];
if(r->kind!=TEXTURE||r->generation!=(token>>10)||!r->detached||r->holds<=0||source_offset<0||destination_offset<0||count<=0||
((source_offset|destination_offset|count)&31)||destination_offset!=r->staged_bytes||destination_offset>r->bytes||count>r->bytes-destination_offset)return -1;
uint64_t address=dnd_buffer_held_address(buffer_token,source_offset,count);if(!address)return -1;
memcpy(r->data+destination_offset,(const void*)(uintptr_t)address,(size_t)count);
dnd_draw_backend_flush(r->data+destination_offset,count,0);r->staged_bytes+=count;return 0;
}
int dnd_texture_release_completed(int token,int fence) {
dnd_async_require_application_thread();Resource *r=find(token,TEXTURE);
if(dnd_raw_depth()||!r||r->detached||r->holds||fence<=0||!dnd_device_fence_completed(fence))return -1;
release(r);return 0;
}
int dnd_texture_update_native(int token,DndArray *payload,int source_offset,int count) {
Resource *r=find(token,TEXTURE);
if(dnd_device_active() || dnd_raw_depth() || !r || !payload ||
Expand Down Expand Up @@ -269,7 +305,9 @@ int dnd_texture_stage_buffer(int token,int buffer_token,int offset,int count) {
}
int dnd_texture_publish_staged(int token) {
dnd_async_require_application_thread();
if(dnd_raw_depth() || dnd_device_pass()==3 || !find(token,TEXTURE))return -1;
Resource *r=find(token,TEXTURE);
if(dnd_raw_depth() || dnd_device_pass()==3 || !r || r->holds || (r->detached&&r->staged_bytes!=r->bytes))return -1;
r->detached=false;
/* The backend issues GX_InvalidateTexAll only; no GPU completion wait. */
dnd_draw_backend_publish_texture();
return 0;
Expand Down Expand Up @@ -383,7 +421,7 @@ int dnd_texture_sampler(int token,int wrap_s,int wrap_t,int min_filter,int mag_f
}
static bool texture(int token,DndDrawTexture *out) {
memset(out,0,sizeof(*out));if(!token)return true;
Resource *r=find(token,TEXTURE);if(!r)return false;
Resource *r=find(token,TEXTURE);if(!r||r->detached)return false;
*out=(DndDrawTexture){r->data,(uint32_t)r->bytes,r->width,r->height,r->format,r->linear!=0,r->levels,r->sampler_set,r->wrap_s,r->wrap_t,r->min_filter,r->mag_filter,r->lod_bias};return true;
}
int dnd_texture_resolve(int token,DndDrawTexture *out){return texture(token,out)?0:-1;}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Dolphin.Graphics;

/// <summary>One private single-level allocation. Queue sequential aligned native
/// chunks between frames; the service executor copies/flushes CPU memory only.
/// A failed/cancelled upload cannot publish or invalidate the visible fallback.</summary>
public sealed class DetachedTextureUpload : IDisposable
{
private Texture2D? texture;
private readonly CancellationTokenSource cancellation=new CancellationTokenSource();
private readonly uint expectedCrc;
private Task? pending;
private int completed,pendingBytes;
private uint crc,pendingCrc;
private bool failed,sealedUpload,aborting,disposed;
public int ExpectedBytes {get;}
public int CompletedBytes {get{Check();Observe();return completed;}}
public int StagedBytes=>texture==null?0:ExpectedBytes;
public bool HasPendingCopy=>pending!=null&&!pending.IsCompleted;
private DetachedTextureUpload(Texture2D target,int bytes,uint checksum){texture=target;ExpectedBytes=bytes;expectedCrc=checksum;}
private static void Application(){if(!Dolphin.Threading.Tasks.Scheduler.IsApplicationThread)throw new InvalidOperationException("Use the application executor for upload ownership and publication.");}
private void Check(){Application();if(disposed)throw new ObjectDisposedException("DetachedTextureUpload");}
public static DetachedTextureUpload Create(int width,int height,NativeTextureFormat format,int expectedNativeBytes,uint expectedCrc32)
{
Application();var target=Texture2D.CreateDetached(width,height,format);
if(target.NativeBytes!=expectedNativeBytes){target.Dispose();throw new ArgumentException("Native payload size differs from texture allocation.");}
return new DetachedTextureUpload(target,expectedNativeBytes,expectedCrc32);
}
private void Observe()
{
if(pending==null)return;if(!pending.IsCompleted)throw new InvalidOperationException("Wait for the pending chunk before reusing its range.");
var work=pending;pending=null;
try{work.GetAwaiter().GetResult();completed+=pendingBytes;crc=pendingCrc;}
catch{failed=true;throw;}
}
/// <summary>Source ownership is retained through cancellation and completion.
/// A held source cannot be overwritten through NativeBuffer.Write. Chunks
/// must be contiguous, nonoverlapping, 32-byte aligned and complete.</summary>
public Task StageChunkAsync(NativeBuffer source,int sourceOffset,int destinationOffset,int count,CancellationToken cancellationToken=default)
{
Check();Observe();if(texture==null||failed||aborting||sealedUpload)throw new InvalidOperationException("Upload no longer accepts chunks.");
if(source==null)throw new ArgumentNullException("source");source.GetAddress(0);
if(sourceOffset<0||destinationOffset!=completed||count<=0||((sourceOffset|destinationOffset|count)&31)!=0||sourceOffset>source.Length||count>source.Length-sourceOffset||count>ExpectedBytes-completed)throw new ArgumentOutOfRangeException("count");
cancellationToken.ThrowIfCancellationRequested();cancellation.Token.ThrowIfCancellationRequested();
pendingCrc=source.ComputeCrc32(sourceOffset,count,crc);pendingBytes=count;
if(NativeGraphics.BufferHold(source.Token)<0)throw new InvalidOperationException("Cannot hold source storage.");
if(NativeGraphics.TextureUploadHold(texture.Token)<0){NativeGraphics.BufferUnhold(source.Token);throw new InvalidOperationException("Cannot hold detached destination.");}
try{pending=Copy(texture.Token,source.Token,sourceOffset,destinationOffset,count,cancellation.Token,cancellationToken);return pending;}
catch{NativeGraphics.TextureUploadUnhold(texture.Token);NativeGraphics.BufferUnhold(source.Token);throw;}
}
private static async Task Copy(int target,int source,int sourceOffset,int destinationOffset,int count,CancellationToken stop,CancellationToken token)
{
try{
await Task.Run(()=>{
token.ThrowIfCancellationRequested();stop.ThrowIfCancellationRequested();
if(NativeGraphics.TextureStageBufferRange(target,source,sourceOffset,destinationOffset,count)<0)throw new InvalidOperationException("Detached range copy failed.");
});
}finally{NativeGraphics.TextureUploadUnhold(target);NativeGraphics.BufferUnhold(source);}
}
public void Seal()
{
Check();Observe();if(failed||aborting||texture==null)throw new InvalidOperationException("Upload cannot be sealed.");
if(completed!=ExpectedBytes)throw new InvalidOperationException("Upload has missing ranges.");
if(crc!=expectedCrc){failed=true;throw new InvalidDataException("Detached texture payload CRC mismatch.");}
sealedUpload=true;
}
public bool TryPublish(out Texture2D? published)
{
Check();published=null;if(aborting||failed||!sealedUpload||texture==null||HasPendingCopy)return false;Observe();
texture.PublishDetached();published=texture;texture=null;return true;
}
/// <summary>Cancel queued work, join any started CPU copy, then release the
/// never-visible destination. Source and destination remain held until join.</summary>
public async Task AbortAsync()
{
Check();aborting=true;cancellation.Cancel();var work=pending;
if(work!=null)try{await work;}catch(Exception){}pending=null;
texture?.Dispose();texture=null;disposed=true;cancellation.Dispose();
}
public void Dispose()
{
if(disposed)return;Application();aborting=true;cancellation.Cancel();
if(HasPendingCopy)throw new InvalidOperationException("Await AbortAsync before disposing a running copy.");
if(pending!=null){try{Observe();}catch(Exception){}}texture?.Dispose();texture=null;disposed=true;cancellation.Dispose();
}
}
1 change: 1 addition & 0 deletions src/DolphinDotNet.GameCube/Dolphin/Graphics/GpuFence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ public readonly struct GpuFence
{
private readonly int value;
internal GpuFence(int value){this.value=value;}
internal int Value=>value;
public bool IsValid=>value!=0;
public bool IsCompleted=>IsValid && NativeGraphics.DeviceFenceCompleted(value)!=0;
}
Loading
Loading