GPUCHANNEL

GPUChannel and the dynamic bitstream

GPUChannel drives the GPU for the Web 4 Channel Paradigm (see the manual). It runs as Device sub-channel 0 (flat id 16) and connects to the CPU through DMAChannel (Device sub 3), not through the crossbar; the 8 MB crossbar carries traffic between the core channels only. The frame it draws lives on the GPU as a pair of textures, one being drawn and one being shown; the packed 4–7-bit command stream runs on the GPU stream executor, and the display draws the shown texture with the work kept on the GPU. This page covers the DMA and quadratic framing, the execution paths, the GPU threads and the GPUInfo object, image gobs, the command map, the packed bitstream and the display tick.

DMAChannel: how the GPU meets the CPU

DEVICE SUB 3 · FLAT 19 4,096-BYTE FRAMES NO LOCKS · NO WAITS

DMAChannel is Device sub-channel 3 (DMAChannel.c). It is the one link between the CPU and the GPU. GPUChannel (Device sub 0) connects to the rest of the channels through DMAChannel. The 8 MB crossbar (the Blitter Bus that NetXecChannel allocates) carries traffic between the core channels only, so GPU traffic never takes a crossbar slot.

Where DMAChannel sits

The frame

ItemValue
Frame size4,096 bytes = 512 words of 64 bits
Word 1seq, the tick number, written first
Words 2–510the body: lane states (DmaStateSet), requests, results
Word 511trailer, the seq again, written last. A reader accepts a frame only when seq and trailer match (DmaFrameValid), so a torn frame is always caught.
Blockstruct DmaBlock { uint64_t HostToGpu[4][512]; uint64_t GpuToHost[4][512]; }: 32,768 bytes, 4 KB aligned, from AllocMem

One tick through the DMA

  1. Tick n starts on the NetXec 16 ms grid.
  2. The CPU writes HostToGpu[n&3]: seq in word 1, the body with DmaStateSet, then the trailer in word 511 (DMAPublish).
  3. GPUChannel records the command buffer: the lane job and the seal pass, using slot n&3 of its transfer buffers. A slot is reused only after its fence has signalled. RunLaneJob submits it with no wait.
  4. The DMA carries the frame to the GPU. The lane job reads it and does the tick’s work.
  5. The seal pass builds GpuToHost[n&3] on the GPU: seq, lane states and trailer, the whole 4,096-byte frame in GPU memory.
  6. Next tick, the frame comes home. ReadLaneJob copies the finished frame of the last tick into the DmaBlock (DMAGpuStore) once its fence has signalled.
  7. The CPU reads GpuToHost[(n−2)&3], the frame the GPU sealed two ticks ago, and checks seq and trailer. A frame that has not arrived yet is counted as stale, and the tick carries on.
  8. Frame swap: if(flag^=1) swaps the display and render pointers. This is the only sync point.

See it running in the quadratic framing animation below, and read the whole DMA story in the manual.

Quadratic framing (qframing)

STEP 43 4 FRAMES EACH WAY READBACK 2 TICKS OLD 60 FPS

Quadratic framing gives the DMA four frames in each direction instead of two (DMA_QUAD_FRAMES 4, DMA_QUAD_MASK 3). On tick n the CPU writes host-to-GPU slot n&3 and reads GPU-to-host slot (n−2)&3, so the frame it reads is always two ticks old (DMA_GPU_AGE 2). With four slots in a ring, the GPU has two full ticks to finish and copy a frame home before the CPU looks at it, and the CPU never stands still waiting for it.

Watch it run

First comes the setup: AllocMem sets aside cleared GPU memory, and the thread channel creates a GPU thread that joins the 16 ms tick. Then the work repeats every tick. Each box says who owns it right now (CPU, DMA or GPU) and changes color as its job changes. The two blue DMA lanes light up whenever the DMA is copying: the top lane carries frames to the GPU, the bottom lane carries the GPU’s finished frames back. Orange dots are commands, blue dots are frames going to the GPU, and pink dots are results coming back to the CPU two ticks later. Screens A and B swap every tick: one is being drawn while the other is shown.

Use Non-resident and Resident to compare. Non-resident packs the commands and copies them to the GPU every tick. Resident sends them once at the start and keeps them on the GPU; after that the CPU only says “repeat” each tick, so the DMA lane carries less.

Quadratic framing running: AllocMem setup, the GPU thread, CPU, command buffer, the DMA lanes, the GPU and the eight DMA frames At the start AllocMem allocates zeroed GPU memory blocks and the thread channel creates a GPU thread on the NetXec tick. Then each tick the CPU writes host-to-GPU frame n and 3, the DMA copies it to the GPU, the GPU reads it and seals GPU-to-host frame n and 3, the DMA copies that back, and the CPU reads the GPU-to-host frame from two ticks before. In non-resident mode the commands are packed and copied by DMA every tick; in resident mode they were uploaded once and the CPU only writes the repeat-stream flag. CPU is writing frame 1 for the GPU CPU is reading GPU frame 3 (finished 2 ticks ago) CPU is writing frame 2 for the GPU CPU is reading GPU frame 4 (finished 2 ticks ago) CPU is writing frame 3 for the GPU CPU is reading GPU frame 1 (finished 2 ticks ago) CPU is writing frame 4 for the GPU CPU is reading GPU frame 2 (finished 2 ticks ago) DMA → GPU DMA → CPU Frames the CPU sends to the GPU (4 take turns) Frames the GPU sends back to the CPU (4 take turns) DMA to GPU DMA to CPU CPUpacking + writingruns the channelsevery 16 ms tick CPU"repeat" + frameruns the channelsevery 16 ms tick GPUwaitingGPU workingfinishing + drawingwaiting runs the commands sent ↻ repeats saved commands Commands for the GPUpackingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree Commands for the GPU"repeat" noteowner: CPUkept on GPUowner: GPUGPU repeats themowner: GPUkept on GPUowner: GPU CPU → GPUframe 1writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 1freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree CPU → GPUframe 2writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 2freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree CPU → GPUframe 3writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 3freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree CPU → GPUframe 4writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 4freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree screen Adrawingdrawingdrawingon screen screen Bdrawingdrawingdrawingon screen screens swap every tick ⇄ screen swap DMA copying frame 1 + commands to the GPU DMA copying frame 1 to the GPU DMA copying GPU frame 1 back to the CPU DMA copying frame 2 + commands to the GPU DMA copying frame 2 to the GPU DMA copying GPU frame 2 back to the CPU DMA copying frame 3 + commands to the GPU DMA copying frame 3 to the GPU DMA copying GPU frame 3 back to the CPU DMA copying frame 4 + commands to the GPU DMA copying frame 4 to the GPU DMA copying GPU frame 4 back to the CPU repeat frame result frame result frame result frame result Non-resident: every tick the CPU packs the commands and the DMA copies them to the GPUThe DMA also carries the small frame to the GPU and the finished frame back Resident: the commands stay on the GPU; every tick the CPU just says "repeat"No commands to copy: the DMA carries only the small frame to the GPU and the finished frame back One loop = 4 ticks of 16 ms, slowed down so you can follow it. Nobody waits: a frame is reused only after the GPU has finished with it. GPU thread createdby the thread channel joined the 16 ms tick ✓ GPU memory set up by AllocMem (cleared to zero) DMA framesDMABlock · 32 KB Screen buffersGPUFrame GPU settingsGPUState GPU thread memorythread state Saved commandskept on the GPU sent once Setup: AllocMem sets aside cleared GPU memorythen the thread channel creates a GPU thread and joins it to the 16 ms tick Quadratic framing running: AllocMem setup, the GPU thread, CPU, command buffer, the DMA lanes, the GPU and the eight DMA frames At the start AllocMem allocates zeroed GPU memory blocks and the thread channel creates a GPU thread on the NetXec tick. Then each tick the CPU writes host-to-GPU frame n and 3, the DMA copies it to the GPU, the GPU reads it and seals GPU-to-host frame n and 3, the DMA copies that back, and the CPU reads the GPU-to-host frame from two ticks before. In non-resident mode the commands are packed and copied by DMA every tick; in resident mode they were uploaded once and the CPU only writes the repeat-stream flag. CPU is writing frame 1 for the GPU CPU is reading GPU frame 3 (finished 2 ticks ago) CPU is writing frame 2 for the GPU CPU is reading GPU frame 4 (finished 2 ticks ago) CPU is writing frame 3 for the GPU CPU is reading GPU frame 1 (finished 2 ticks ago) CPU is writing frame 4 for the GPU CPU is reading GPU frame 2 (finished 2 ticks ago) DMA → GPU DMA → CPU to the GPU back to CPU commands DMA to GPU DMA to CPU CPUpacking + writingruns the channelsevery 16 ms tick CPU"repeat" + frameruns the channelsevery 16 ms tick GPUwaitingGPU workingfinishing + drawingwaiting runs the commands sent ↻ repeats saved commands Commandspackingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree Commands"repeat" noteowner: CPUkept on GPUowner: GPUGPU repeats themowner: GPUkept on GPUowner: GPU CPU → GPUframe 1writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 1freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree CPU → GPUframe 2writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 2freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree CPU → GPUframe 3writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 3freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree CPU → GPUframe 4writingowner: CPUDMA copyingowner: DMAGPU workingowner: GPUfree GPU → CPUframe 4freeGPU finishingowner: GPUDMA copyingowner: DMAready(for the CPU)CPU readingowner: CPUfree screen Adrawingdrawingdrawingon screen screen Bdrawingdrawingdrawingon screen screens swap every tick ⇄ screen swap DMA copying frame 1 + commands to the GPU DMA copying frame 1 to the GPU DMA copying GPU frame 1 back to the CPU DMA copying frame 2 + commands to the GPU DMA copying frame 2 to the GPU DMA copying GPU frame 2 back to the CPU DMA copying frame 3 + commands to the GPU DMA copying frame 3 to the GPU DMA copying GPU frame 3 back to the CPU DMA copying frame 4 + commands to the GPU DMA copying frame 4 to the GPU DMA copying GPU frame 4 back to the CPU repeat frame result frame result frame result frame result Non-resident: every tickcommands are packed and copied Resident: commands stay on GPUCPU just says "repeat" One loop = 4 ticks of 16 ms, slowed down. GPU thread createdby the thread channel joined the 16 ms tick ✓ GPU memory (AllocMem) DMA framesDMABlock · 32 KB Screen buffersGPUFrame GPU settingsGPUState GPU thread memorythread state Saved commandskept on the GPU sent once Setup: AllocMem sets asidecleared GPU memory, then aGPU thread joins the tick

Setting up: AllocMem sets aside cleared GPU memory.

  • CPU writing
  • DMA copying
  • GPU working
  • ready for the CPU
  • CPU reading
  • free
  • kept on the GPU
  • memory set up (AllocMem)
  • GPU thread
Each tickNon-residentResident
Commands packed by the CPUevery tickonce, at the start
Commands copied by the DMAevery tickonce at the start, none per tick
What the CPU writesthe commands and the small framea tiny “repeat” note and the small frame
DMA lane to the GPUsmall frame plus the commandssmall frame only
DMA lane back to the CPUthe GPU’s finished framethe GPU’s finished frame
What the GPU doesruns the commands it was sentrepeats the commands it keeps
For programmers
  • Frames 1–4 are slots 0–3: the CPU writes HostToGpu[n&3] and reads GpuToHost[(n−2)&3] (DMA_GPU_AGE 2), all in struct DmaBlock.
  • “Free” means the slot’s fence has signalled; “GPU finishing” is the seal pass; the screen swap is if(flag^=1) swapping the display and render pointers.
  • Setup: AllocMem blocks DMABlock, GPUFrame, GPUState and the caller-owned GPU_MEMORY thread state, all zeroed. The GPU thread comes from GetNetXecThread(MF_THREAD, &req) with GPU_THREAD in tr_flags.
  • Resident: the stream is packed and sent once; with GPU_FLAG_REPEAT_STREAM set, GPUChannel reruns the GPU records with no unpack and no upload (step 26).

Measured with step 43

TestResult
lanejob_test, Part B (3 runs)1,797 frames, 0 torn
lanejob_test, Part C (3 runs)598 exchanges, 0 torn, 0 stale
RunLaneJob submit, median175–195 µs (step 42: 313–412 µs)
Tony’s tour runSmooth as butter

From source to the screen

The C program is built once into channels.exe (build_ucrt.sh, then build_channels.sh). At start-up it hands its GLSL compute and vertex shaders to shaderc, which compiles them to SPIR-V. SDL GPU loads the SPIR-V on Vulkan into a compute pipeline and a graphics pipeline; each tick the compute work is dispatched and the display texture is drawn.

Build pipeline: C program and GLSL compute and vertex shaders, shaderc to SPIR-V, SDL GPU on Vulkan, compute and graphics pipelines, dispatch and draw C program your source code C build build scripts channels.exe the one program GLSL compute GPU work program GLSL vertex GPU drawing program shaderc translator SPIR-V GPU-ready code SDL GPU talks to Vulkan Compute pipeline set up for work Graphics pipeline set up for drawing Dispatch GPU does the work Draw GPU draws the picture Frame shown 60 times a second loads its GPU programs C and GLSL in, a picture on screen out Build pipeline: C program and GLSL compute and vertex shaders, shaderc to SPIR-V, SDL GPU on Vulkan, compute and graphics pipelines, dispatch and draw C program your source code C build build scripts channels.exe the one program GLSL compute GPU work program GLSL vertex GPU drawing program shaderc translator SPIR-V GPU-ready code SDL GPU talks to Vulkan Compute pipeline set up for work Graphics pipeline set up for drawing Dispatch GPU does the work Draw GPU draws the picture Frame shown 60 times a second C and GLSL in, a picture on screen out

From your C program and GPU programs to a picture on the screen.

Current GPU backend and compute path

Verified November 8, 2026 (MST). The Windows Vulkan automatic-selection correction is installed and channels7.exe rebuilt. An automatic source-shader request that permits SPIR-V now selects Vulkan where SDL could otherwise prefer D3D. Backend choice stays with an explicit driver or shader-format mask, including D3D masks and native non-D3D defaults; D3D support remains available.

Shader compilation

The verified Vulkan source path is GLSL → shaderc → SPIR-V → Vulkan, using the existing shaderc_shared.dll. A diagnostic load guard recorded zero attempts to load d3dcompiler, dxcompiler, dxil.dll or spirv-cross. Other explicitly selected backends keep their own source paths.

Which commands actually run on the GPU?

Checked November 13, 2026 (UTC-7). With a GPU device open, the packed drawing stream, the frame compute commands, the moving lines, the GPU threads and the layer compose all run on the GPU, against a frame that stays on the GPU. The C opcode handlers are the host path and the comparison the tests run with GPU_STREAM_CPU=1. The display loop keeps the frame on the GPU. ReadGPUFrame and GPUFrameSync are the GPU-to-CPU paths, used by tests and screenshots.

PathWhat runs, and where
Packed 4–7-bit drawing streamGPUInstallStream → GPURunStream → GpuDispatch. With a device, StreamDecodeLocked turns the opcodes into records of eight words (op, x0, y0, x1, y1, fg, bg, kind), up to 128 per run, and StreamExecLocked runs them on the GPU in one command buffer and one submit with no fence: the stream_pix compute pipeline (GLSL GwGlslStreamPix), one compute pass per op, on the resident frame buffer. Pixel, line, rectangle, ellipse, polygon, spline, image, gather (blur, rotate, scale, mirror and the rest) and row ops are executor kinds. Register and flag ops (NOP, BLIT, SETAPEN, SETBPEN, CHANNEL_ALLOCATE, CHANNEL_FREE, CUSTOM0, INTERRUPT, BEZIER_UPDATE) keep their host meaning. With GPU_FLAG_REPEAT_STREAM, a stream that was packed and sent once runs again from its resident records: the packed bytes stay resident.
CPU handlers (host path and test comparison)The same GpuDispatch runs the C handlers in gpu_ops[] on the host frame for the host path and when GPU_STREAM_CPU=1 selects the comparison run. Tests compare the two paths pixel for pixel.
Frame compute commandsGPUW_COMPUTE / GPUW_CHAIN → RunCompute. On the GPU the ops run on the resident frame (StreamComputeLocked, pipeline gpuchan_argb_resident from GwGlslGpuchanArgb). The work stays on the resident frame. StageCompute / StageComputeChain remain as the explicit upload-dispatch-download API, and RefCompute is the CPU reference.
Resident bytecode computeGPUW_BC_RUN → BcRun → ResidentRecBc binds the program and calls SDL_DispatchGPUCompute with the bcvm_res pipeline (GwGlslBcvmRes). It interprets resident bytecode against the GPU-resident heap. This bytecode is a different format from the packed drawing stream.
Resident heap and image operationsCompute pipelines res_maint, res_argb, res_argb_tex and res_dark, recorded by ResidentRecMaint, ResidentRecArgbPub, ResidentRecArgbTex and ResidentRecDark.
Loaded kernelsGPUKernelLoad creates the pipeline; GPURun / GPURun3D bind it and call SDL_DispatchGPUCompute. Examples: test/shaders/gpufold_add.spv and test/shaders/gpuadd_3d.spv. An explicit CPU selection runs the CPU twin.
Moving linesGPUMovingLines keeps the 12 lines on the GPU: one command buffer per frame steps them (line_bounce compute, the same 16.16 bounce as the CPU) and draws them into the frame's render slot. The lines stay on the GPU. The host path uses the CPU bounce with a per-frame segment upload.
GPU threadsGetNetXecThread(MF_THREAD) GPU threads run once per NetXec tick inside TickGPUFrame (pipeline gpu_thread), in the same command buffer as the frame swap. Their fences are queried, and the tick moves on.
Layers and the displayWhen layers are active they are composed on the GPU (layer_compose). TickGPUFrame turns the drawn render slot into the display slot. DrawGPUFrame puts the display slot on the NetXec renderer as an SDL texture over the GPU texture, on the same device: zero copy.

Memory device versus resident compute

The GPU memory device and the resident compute device are separate. Initialize SDL VIDEO before opening the GPU memory path, observing the existing SDL-thread ownership rules. Opening the memory path before video initialization can report memory device none (Video subsystem not initialized): host fallback while a later, independent resident compute device still executes real Vulkan dispatches. Read compute availability from GPUComputeAvailable() / GPUComputeHandle(). The host memory path remains supported.

GPUComputeAvailable() reports compute availability; GPUComputeHandle() is non-NULL when available. GPUCOMPUTE_FORCE_CPU=1 selects the supported CPU path. Resident variables use GPUVarNew, GPUVarSet, GPUVarGet and GPUVarFree; kernels use GPUKernelLoad, GPURun/GPURun3D and GPUKernelFree. These compute APIs are the kernel interface. GPUInstallStream/GPURunStream, below, is the packed drawing-command interface, with register and flag ops keeping their host meaning.

Physical validation and limits

Acceptance used a physical NVIDIA GeForce RTX 5060, driver 616.92, Vulkan 1.4.351. All eleven scoped runs exited 0, including resident Vulkan (73 checks), generic Vulkan (31 passes), production add (24 passes), production fold (25 passes), and the resident CPU twin (46,750 checks). Video-ready variants verified both the memory and resident devices on physical Vulkan. The build produced the 138-object library, 16 tools and channels7.exe.

These are correctness and backend-selection results, with the existing resident-test tolerances: 1,910 denormal FDIV/FFMA/FSQRT results stay under those exclusions, and 708 FDIV/FSQRT results differ by 1 ulp, inside the existing 2-ulp tolerance. Tolerances and exclusions stay as they are. The physical device ran clear of the earlier software-Vulkan failures. This acceptance covers the demonstrated Vulkan dispatch and readback path.

Performance is workload-dependent

Keep submission timing separate from completion and readback. One manual fold run measured 999 submit-only dispatches at 153.115 ms total (153.27 µs each), then verified correct readback. A different gpu_fold_time workload—1,000 BC_RUN operations with 256 invocations—took 9,860.511 ms on GPU versus 9.885 ms on CPU, with zero wrong results in either path and 1,048,576 words transferred up and down each. That small interpreter workload ran faster on the CPU in this measurement; treat the two figures as workload-specific.

Launching and diagnosing

./channels7 live

Run this from the project directory to launch the application. Plain ./channels7 defaults to the test suite. Vulkan dispatch and readback results stand on their own. The latest full default run also reported separate JavaChannel environment, shared-memory and asset-path results, which belong with those checks. A VK_EXT_headless_surface warning still allowed the demonstrated compute initialization; continue from later device-creation and dispatch results.

Source scope. The execution paths and the function list on this page were checked against /workspace/s31/chk3/GPUChannel.c as of November 13, 2026, 17:53 (UTC-7), md5 8f8128741af7c34689e63e5531cf624c, and the matching channels.h in the same tree.

GPU threads and the GPUInfo GPU object (GPUThreads.c)

Added November 12, 2026 (MST). AllocMem creates GPU memory. GetNetXecThread(MF_THREAD, &req) creates the GPU thread and binds it to a block the caller already allocated. Close the thread first, then FreeMem the block: CloseNetXecThread leaves the caller's block in place for that FreeMem. GPUThreads.c is a working example: two GPU threads, a resident 160×160×16 int64 volume, and a ChannelData GPU object printed once a second.

The GPU object

This GPU OBJECT GPUInfo is the 208-byte ChannelData object (struct GPUThreadsInfo) that GPUThreads updates once a second. It is the 208-byte ChannelData object, separate from the 56-byte struct GPUInfo used by GPUMSG_QUERY. The object is meant to go through ObjectWhack (./ow); see the ODL documentation. Memory prefixes such as GPU may precede an object definition.

GPU OBJECT GPUInfo;
{
    uint32_t  gi_magic = 0x54555047;   // 'GPUT' — object magic
    uint32_t  gi_second;               // ClockChannel timer fire count
    uint32_t  gi_w = 1280;             // display width in pixels
    uint32_t  gi_h = 720;              // display height in pixels
    uint32_t  gi_pages = 2;            // resident frame pages (render and display)
    uint32_t  gi_vw = 160;             // volume width in cells
    uint32_t  gi_vh = 160;             // volume height in cells
    uint32_t  gi_vd = 16;              // volume depth in cells
    uint32_t  gi_points = 226857;      // live points in the volume
    uint32_t  gi_dev64;                // non-zero if the device has shaderFloat64 and shaderInt64
    uint32_t  gi_formats;              // SDL_GPU shader format flags (SPIR-V bit, and others)
    uint32_t  gi_fps_x100;             // measured frames per second times 100
    uint64_t  gi_frames;               // frames presented since start
    uint64_t  gi_vortex_ticks;         // Vortex GPU thread ticks
    uint64_t  gi_info_ticks;           // GPUInfo GPU thread ticks
    uint64_t  gi_presents;             // GPU frame draws (StatGPUFrame)
    uint64_t  gi_gpu_bytes;            // GPU memory in use (GetGPUMemory)
    uint64_t  gi_pool_bytes;           // ChannelData GPU object pool bytes
    uint64_t  gi_waits;                // frame-loop GPU waits
    uint64_t  gi_downloads;            // frame-loop GPU downloads
    uint64_t  gi_uploads;              // frame-loop GPU uploads
    int8_t    gi_device[64];           // ASCII device name; ODL char is 16-bit
    uint32_t  gi_mode;                 // demo mode: 0 vortex, 1 4-bit command set
    uint32_t  gi_op;                   // 4-bit opcode shown while the command-set demo runs
    uint64_t  gi_stream_runs;          // GPU stream runs (StatGPUStream)
    uint64_t  gi_stream_passes;        // GPU stream passes (StatGPUStream)
}

The C struct below is what GPUThreads.c fills once a second (InfoTick) and writes with UpdateGPUObject. It matches the GPU OBJECT GPUInfo listing above field for field, 208 bytes. ODL uses int8_t for the ASCII device name because ODL char is 16-bit; the C struct uses char[64] for the same 8-bit bytes. It is separate from the 56-byte struct GPUInfo used by GPUMSG_QUERY.

The C structure

/* the 208-byte print-path object; GPUMSG_QUERY uses the 56-byte struct GPUInfo */
struct GPUThreadsInfo {
    uint32_t gi_magic;            /* 'GPUT' — object magic */
    uint32_t gi_second;           /* ClockChannel timer fire count */
    uint32_t gi_w;                /* display width in pixels (1280) */
    uint32_t gi_h;                /* display height in pixels (720) */
    uint32_t gi_pages;            /* resident frame pages: render and display (2) */
    uint32_t gi_vw;               /* volume width in cells (160) */
    uint32_t gi_vh;               /* volume height in cells (160) */
    uint32_t gi_vd;               /* volume depth in cells (16) */
    uint32_t gi_points;           /* live points in the volume */
    uint32_t gi_dev64;            /* non-zero if the device has shaderFloat64 and shaderInt64 */
    uint32_t gi_formats;          /* SDL_GPU shader format flags (SPIR-V bit, and others) */
    uint32_t gi_fps_x100;         /* measured frames per second times 100 */
    uint64_t gi_frames;           /* frames presented since start */
    uint64_t gi_vortex_ticks;     /* Vortex GPU thread ticks */
    uint64_t gi_info_ticks;       /* GPUInfo GPU thread ticks */
    uint64_t gi_presents;         /* GPU frame draws (StatGPUFrame) */
    uint64_t gi_gpu_bytes;        /* GPU memory in use (GetGPUMemory) */
    uint64_t gi_pool_bytes;       /* ChannelData GPU object pool bytes */
    uint64_t gi_waits;            /* frame-loop GPU waits */
    uint64_t gi_downloads;        /* frame-loop GPU downloads */
    uint64_t gi_uploads;          /* frame-loop GPU uploads */
    char     gi_device[64];       /* 8-bit device name; ODL uses int8_t for ASCII because ODL char is 16-bit */
    uint32_t gi_mode;             /* current demo mode: vortex or 4-bit command set */
    uint32_t gi_op;               /* 4-bit opcode shown when the command-set demo is running */
    uint64_t gi_stream_runs;      /* GPU stream runs (StatGPUStream) */
    uint64_t gi_stream_passes;    /* GPU stream passes (StatGPUStream) */
};

The two request structures

struct MemoryAllocationRequest {           /* 48 bytes */
    uint64_t ma_size;                      /* payload bytes (element size * width * height * depth) */
    void    *ma_name;                      /* wide name, copied onto the handle (unset = anonymous) */
    uint8_t  ma_ram_type;                  /* where it lives: HEAP_MEMORY, GPU_MEMORY, ... */
    uint8_t  ma_data_type;                 /* element type and shape, e.g. DATA_LONG_3D_ARRAY */
    uint8_t  ma_dimension_type;            /* dimension when it is not already in ma_data_type */
    uint8_t  ma_flags;
    uint32_t pad1;
    uint32_t ma_width;                     /* 2D/3D extents in elements (0 = none); x fastest, then y, then z */
    uint32_t ma_height;                    /* 2D: ma_size == elem * width * height */
    uint32_t ma_depth;                     /* 3D: elem * width * height * depth; each <= MEM_EXTENT_MAX */
    char     ma_pad[12];
};

struct ThreadRequest {                     /* 64 bytes */
    const char *tr_name;                   /* thread name (reuse by name) */
    uint32_t    tr_pad8;                   /* 0; the old type field: the thread type is now a tr_flags bit */
    uint32_t    tr_flags;                  /* steps per tick (low 16 bits), GPU_THREAD_PAUSED, GPU_THREAD, CLOUD_THREAD, CLOUD_BIND_GPU */
    uint32_t    tr_groups;                 /* GPU: workgroups of 64 per step */
    uint32_t    tr_pad32;
    int       (*tr_func)(void *);          /* CPU entry */
    void       *tr_data;                   /* CPU user data */
    const char *tr_glsl;                   /* GPU: helpers + void main() */
    void       *tr_state;                  /* GPU: AllocMem(MF_EXT) GPU_MEMORY payload, caller-owned */
    void       *tr_target;                 /* GPU: optional pixel block the thread plots into (NULL = none) */
};

/* tr_flags bits (defines.h). No type bit set = a local CPU thread, the default. */
#define THREAD_STEPS_MASK  0xFFFFu         /* low 16 bits: steps per tick (<= GPU_THREAD_STEPS_MAX) */
#define GPU_THREAD_PAUSED  0x10000u        /* bit 16: open the GPU thread paused */
#define GPU_THREAD         0x20000u        /* bit 17: GPU thread (local GPU when CLOUD_THREAD is clear) */
#define CLOUD_THREAD       0x40000u        /* bit 18: cloud thread; alone = CLOUD_MEMORY, no GPU (the cloud default) */
#define CLOUD_BIND_GPU     0x80000u        /* bit 19: allow binding a GPU, or a bank of GPUs, on a cloud thread (default clear) */

Thread type lives in tr_flags, above GPU_THREAD_PAUSED. GPU_THREAD is 0x20000u so it sits clear of the step count in the low 16 bits. The former type word is padding, so ThreadRequest stays 64 bytes with tr_flags at offset 12. A CPU thread is the default when no type bit is set, and GetNetXecThread(name, func, data) is unchanged.

The type bits combine, so a GPU can run on a cloud. The combinations are:

CLOUD_BIND_GPU is the bind option used with CLOUD_THREAD: set it to allow GPU binding. The cloud flags and the bind option are in the API. A CLOUD_THREAD request returns NULL, allocates nothing, and leaves no record.

The two-thread setup

Both threads share the volume. Vortex (thread A) turns the points each tick and plots them into its tr_target, a 1280×720×2-page DATA_INT_3D_ARRAY block of ARGB words. TickGPUFrame draws that page into the GPU frame, and DrawGPUFrame shows it with no per-frame transfer. Its groups cover the larger of the 409,600 volume cells and the 921,600 pixels. GPUInfo (thread B) has no target and recolours the volume once a second (every 60th tick). Both threads are opened before the first tick. The GPUInfo ChannelData object is filled on the host by the timer callback and written with UpdateGPUObject, one small upload a second. The calls below are the ones in GPUThreads.c, where the two AllocMem and two GetNetXecThread requests are made by its GpuBlock and GpuThread helpers.

struct MemoryAllocationRequest ma;         /* AllocMem(MF_EXT) request; filled for each block */
struct ThreadRequest tr;                   /* GetNetXecThread(MF_THREAD) request; filled for each thread */
struct ChannelData desc;                   /* descriptor for the GPUInfo ChannelData object */
struct ClockChannel *clk;                  /* ClockChannel used to print GPUInfo once a second */
struct NetXecThread *vortex, *gpuinfo;     /* the two GPU threads: Vortex (A) and GPUInfo (B) */
struct GPUThreadsApp app;                  /* memset 0; app.snap is the struct GPUThreadsInfo */
int64_t *volume;                           /* payload of the shared 160 x 160 x 16 int64 volume */
uint32_t *pixels, obj = 0, timer;          /* pixel pages; GPU object id; ClockChannel timer id */

/* the shared volume: 160 x 160 x 16 int64 */
memset(&ma, 0, sizeof ma);                 /* clear the request; AllocMem must see a zeroed struct */
ma.ma_size = 8ull * 160 * 160 * 16;        /* payload bytes: 8-byte int64 * width * height * depth */
ma.ma_name = L"GPUThreads.Vortex";         /* wide name copied onto the handle as mh_name */
ma.ma_ram_type = GPU_MEMORY;               /* allocate in GPU RAM, not host heap */
ma.ma_data_type = DATA_LONG_3D_ARRAY;      /* kernel sees this shape, not a flat uint state[] */
ma.ma_width = 160;                         /* volume width in cells */
ma.ma_height = 160;                        /* volume height in cells */
ma.ma_depth = 16;                          /* volume depth in cells */
volume = AllocMem(MF_EXT, &ma);            /* zeroed; caller frees with FreeMem after CloseNetXecThread */

/* Vortex's target: 1280 x 720 x 2 pages of ARGB words */
memset(&ma, 0, sizeof ma);                 /* reuse ma; clear it for the pixel block */
ma.ma_size = 4ull * 1280 * 720 * 2;        /* payload bytes: 4-byte ARGB * width * height * 2 pages */
ma.ma_name = L"GPUThreads.Pixels";         /* wide name for the display-page block */
ma.ma_ram_type = GPU_MEMORY;               /* GPU-resident pages; no per-frame transfer */
ma.ma_data_type = DATA_INT_3D_ARRAY;       /* 3D int array: two ARGB pages */
ma.ma_width = 1280;                        /* display width in pixels */
ma.ma_height = 720;                        /* display height in pixels */
ma.ma_depth = 2;                           /* two complete display buffers: render and display */
pixels = AllocMem(MF_EXT, &ma);            /* zeroed */
GPUMemUpload(pixels);                      /* once: the zero pages onto the GPU */

/* thread A: Vortex */
memset(&tr, 0, sizeof tr);                 /* clear the thread request */
tr.tr_name = "Vortex";                     /* thread name; reuse by name */
tr.tr_glsl = VortexK;                      /* kernel: helpers + void main(); turns and plots the volume */
tr.tr_state = volume;                      /* already-allocated GPU_MEMORY volume; ThreadChannel must not allocate */
tr.tr_target = pixels;                     /* Vortex plots into the 1280 x 720 x 2 ARGB pages */
tr.tr_groups = (1280u * 720u + 63u) / 64u; /* the larger of 160*160*16 cells and 1280*720 pixels */
tr.tr_flags = GPU_THREAD | 1;              /* local GPU thread (GPU_THREAD bit, no CLOUD_THREAD), one step per tick */
vortex = GetNetXecThread(MF_THREAD, &tr);  /* name is on the request; opens before the first tick */

/* thread B: GPUInfo, the same volume, no target */
memset(&tr, 0, sizeof tr);                 /* reuse tr; clear it for the second thread */
tr.tr_name = "GPUInfo";                    /* thread name; reuse by name */
tr.tr_glsl = InfoK;                        /* kernel: recolours the volume once a second (every 60th tick) */
tr.tr_state = volume;                      /* the same shared volume as Vortex */
tr.tr_target = NULL;                       /* GPUInfo has no pixel target; Vortex plots the page */
tr.tr_groups = (160u * 160u * 16u + 63u) / 64u; /* one group per 64 volume cells */
tr.tr_flags = GPU_THREAD | 1;              /* local GPU thread (GPU_THREAD bit, no CLOUD_THREAD), one step per tick */
gpuinfo = GetNetXecThread(MF_THREAD, &tr); /* opened before the first tick */

/* the GPUInfo GPU object */
memset(&desc, 0, sizeof desc);             /* clear the ChannelData descriptor */
desc.cd_type = DATA_BYTE_ARRAY;            /* object is a byte array of struct GPUThreadsInfo */
desc.cd_count[0] = sizeof(struct GPUThreadsInfo); /* element count: the live object size (208 bytes) */
desc.cd_bytes = sizeof(struct GPUThreadsInfo);    /* payload bytes */
GPUPutChannelObject(&desc, &app.snap, GPU_OBJ_READ | GPU_OBJ_WRITE, &obj); /* create the GPUInfo object from app.snap; obj receives the id; read+write */

/* print it once a second on the ClockChannel timer */
clk = ClockChannelGet();                   /* already-open ClockChannel, if any */
if (!clk) clk = OpenClockChannel();        /* open one if none is open */
timer = StartTimerChannel("GPUInfo", 1000, 1, InfoTick, &app); /* 1000 ms, repeat; InfoTick is the host callback */
/* InfoTick fills app.snap from host counters and prints it; the main loop
   copies it to in and calls UpdateGPUObject(obj, 0, &in, sizeof in) */

/* each frame: TickGPUFrame(); DrawGPUFrame(ren, 0, 0, 1280, 720); SDL_RenderPresent(ren); */

/* close: CloseNetXecThread first, then FreeMem */
StopTimerChannel(timer);                   /* stop the 1 s print timer */
ReleaseGPUObject(obj);                     /* drop the GPUInfo GPU object */
CloseNetXecThread(vortex);                 /* stop Vortex; the volume and pixels stay with the caller */
CloseNetXecThread(gpuinfo);                /* stop GPUInfo; the shared volume stays with the caller */
TickGPUFrame();                            /* GPUThreads ticks 4 times: in-flight work retires */
FreeMem(volume);                           /* caller frees the block after CloseNetXecThread */
FreeMem(pixels);                           /* free the two display pages after the threads are closed */

ImageToGPU and LoadGPUGob

Added November 12, 2026 (MST). ImageToGPU loads a PNG as a ContainerChannel image gadget and makes its face GPU-resident: one named AllocMem GPU_MEMORY block, uploaded once and left resident. LoadGPUGob does the same for an existing image gadget whose face the caller already set. DRAW_IMAGE blits the bound gob; the 8×8 checker is only the fallback when nothing is bound.

The calls

struct ContGob *ImageToGPU(struct GPUChannel *gpu, const char *path);  /* PNG → image gadget; NULL on failure */
int  SetGPUImage(struct GPUChannel *gpu, struct ContGob *gob);         /* bind which gob DRAW_IMAGE draws; NULL = checker */
void ReleaseGPUImage(struct GPUChannel *gpu, struct ContGob *gob);     /* frees the GPU block; an ImageToGPU gadget is removed and freed */
int  GPUImageInfo(const struct ContGob *gob, uint32_t **px, uint32_t *w, uint32_t *h);
int  LoadGPUGob(struct GPUChannel *gpu, struct ContGob *gob);          /* 0 ok, -1 fail */

ImageToGPU

The PNG is loaded with SDL3_image as a real ContainerChannel image gadget (struct ContGadget, which starts with struct ContGob), sized to the image at 0,0 (the caller can move it). It is made with ContainerGadgetCreate. The ARGB face is set with ContainerGadgetSetFaceARGB to a named AllocMem GPU_MEMORY block, uploaded once at load and left resident. ImageToGPU uses the open ContainerChannel, or opens one if none is open (ContainerChannelGet, the same pattern as ClockChannelGet). The path may be a file relative to the working directory, or an asset name. It returns the Gob when the file or asset loads as a GPU-backed image of 4096 or under.

DRAW_IMAGE blits the bound gob's image (channel state holds image_gob). The stream shader reads the gob's block directly on the GPU and scales it into the geom rect, with alpha over the frame. An empty rect means the image's own size. The CPU OpImage path uses the same integer math so results match. The 8×8 checker is only the fallback when no image gob is bound. Changing the bound image cancels automatic pack-once/repeat so the next run is decoded again; after that, the same stream repeats with no record upload (GPU_FLAG_REPEAT_STREAM / the same-stream rule).

LoadGPUGob

LoadGPUGob takes an existing ContainerChannel image gadget (ContGob at offset 0). The caller gives it a host ARGB face or a file image, then loads it. If the gob is already GPU-resident (already in the live list), a second call keeps the existing upload and leaves pack-once in place. LoadGPUGob returns success for a gadget that has a host ARGB face or a file image in GPU-backed memory.

struct ContGob *gob;
struct ContGadget *ga;

/* ImageToGPU: PNG to an image gadget, uploaded once and left resident */
gob = ImageToGPU(gpu, "channel_icons.png");
if (!gob) /* file, decode, size or GPU-memory check */ ;
SetGPUImage(gpu, gob);                     /* DRAW_IMAGE now blits this gob; NULL binds the checker */

/* LoadGPUGob: an existing gadget whose face the caller already set */
ContainerGadgetSetFaceImage(ga, "channel_icons.png", NULL);
/* or ContainerGadgetSetFaceARGB(ga, host_pixels, NULL, w, h); */
if (LoadGPUGob(gpu, &ga->gob) != 0) /* no image / not a gadget / not GPU-backed */ ;
/* DRAW_IMAGE draws it; a second LoadGPUGob keeps the upload and pack-once */

/* free: ReleaseGPUImage before CloseContainerChannel */
ReleaseGPUImage(gpu, gob);                 /* ImageToGPU gob: frees the block, removes the gadget from the container and frees it */
ReleaseGPUImage(gpu, &ga->gob);            /* LoadGPUGob gob: frees the block it allocated; the gadget stays with the caller */

Call ReleaseGPUImage before CloseContainerChannel. For a gob ImageToGPU created, ReleaseGPUImage frees the GPU block, takes the gadget out of the container member list (ContainerGadgetRemove) and frees it; the gob pointer is invalid afterwards. For a pre-existing gadget that LoadGPUGob loaded, ReleaseGPUImage frees the block it allocated and leaves the gadget to the caller.

The GPUThreads demo loads channel_icons.png (2440×1022) with ImageToGPU into dest 660,396–1240,639, then calls LoadGPUGob on that same gob (already resident, 0 uploads).

At most 16 image gobs can be live at once. A released ImageToGPU gadget no longer stays in the member list, so loading and releasing images repeatedly keeps the container bounded. LoadGPUGob is gadget-only.

1. Where GPUChannel sits

LIVE 4–7-BIT GPU STREAM EXECUTOR DEVICE SUB 0 · FLAT 16

The packed drawing stream accepts widths 4, 5, 6 and 7. The dispatch table registers opcodes through GPU_MIRROR_VERT (0x6C), including the wider effects and the user slots. Width is uniform within each installed stream. The 2- and 3-bit names below mark where those narrower opcode ranges end inside a 4–7-bit installed stream.

GPUChannel is the Device core's sub-channel 0 (flat id 16). There is one GPUChannel at a time (GPUChannelGet). AttachGPUChannel opens it as Device sub 0. ContainerChannel uses that same Device sub 0 channel: OpenContainerGPUChannel attaches it and records CC_FLAG_GPU_ATTACHED, or, in standalone tests with a held channel, records CC_FLAG_GPU_HELD. A channel opened by OpenGPUChannelFor(owner) is owned, and the owner's CloseGPUChannelFor closes it.

ItemValue
Channel id0x00475055 ('GPU')
Host frameARGB words 0xAARRGGBB in a GPU_MEMORY block. It opens at 64x64; GPUResizeFrame replaces it, up to 4096 on a side (the new frame is in place before the old one is freed; a zero side leaves the current frame in place). With a device it is the CPU twin; the display shows the GPU frame.
GPU frameOpenGPUFrame(w, h): two GPU textures, render and display, cleared on the GPU. TickGPUFrame swaps them once per NetXec tick when something was drawn; DrawGPUFrame shows the display slot.
controlHost gate for the packed stream: nonzero lets GPURunStream run it, and the run clears it. It is not a GPU fence.
signalHost flag set by GPU_BLIT. The display treats a moving-line frame as ready; a leftover 4-bit test frame is not drawn over the view.

2. Dynamic bitstream

A stream is a list of opcodes packed into the channel buffer. One stream has one field width. The width is not mixed inside the buffer. To change width, install another stream.

2.1. Bytes in the channel buffer

OffsetSizeMeaning
04 bytesMarker 0x00000000. Command mode. A mismatch rejects the run.
41 byteField width. The current installer accepts 4, 5, 6 or 7.
5packed bytesOpcodes, low bit first. Count is at most 64. Packed length is (count * width + 7) / 8. The buffer is 256 bytes, so 5 + packed must fit.

PackBits keeps the low width bits of each source byte and shifts them into the output LSB first. When the accumulator crosses a byte, that byte is stored and the leftover bits stay in the next byte. UnPackBits uses a 16-bit accumulator so a field that straddles two source bytes is not dropped. Install checks the round trip: each unpacked value must equal the opcode masked to the field. A value that does not fit the width is rejected.

The built-in 4-bit test is 15 opcodes. 15 * 4 = 60 bits = 8 packed bytes. A passing run reports ops=15, packed=8, ran=15, fg=333, checksum=0x9507fb5f, signal=1.

2.2. Changing the bit width

The width is the smallest field that can name the highest opcode in that span. A wider field still decodes every narrower opcode. A 5-bit stream can carry NOP (0x00) and EDGE_DETECT (0x1F) in the same buffer. A 4-bit stream cannot name 0x10, because those bits are not in the field.

WidthNames throughOpcodes in the fieldStream
2 (legacy span label)GPU_COPY 0x010x00-0x01 named here; 2 bits can encode 0x00-0x03Included when the stream is 4-bit. Not a separate install width.
3GPU_DRAW_LINE 0x070x00-0x07Same. The 4-bit stream already carries them.
4GPU_CUSTOM0 0x0F0x00-0x0F (16 commands)Accepted; also used by the original 4-bit demo.
5GPU_EDGE_DETECT 0x1F0x00-0x1FAccepted; registered drawing handlers.
6GPU_BEZIER_UPDATE 0x3F0x00-0x3FAccepted; registered drawing handlers.
7GPU_MIRROR_VERT 0x6C0x00-0x7F, used through 0x6CAccepted; registered drawing handlers.

The "16 COMMAND SET" on the display is this 4-bit span, 0x00 through 0x0F. It is 16 opcodes in a 4-bit field (the encoding width is 4 bits).

3. The GPU command set

Numbers below are the drawing-command map. The current GPUChannel dispatch table registers the 4-, 5-, 6- and 7-bit ranges through 0x6C. The effects are what the C handlers in GPUChannel.c do, and the tests compare the GPU stream with those handlers. Spelling follows the source: GPU_DRAW_ELIPSE.

3.1. Four-bit set, 0x00-0x0F (live)

OpcodeNameWhat it does
0x00GPU_NOPNo pixels. Ends the 2-bit span's useful range together with COPY.
0x01GPU_COPYCopies one row of the frame. 2-bit span ends here.
0x02GPU_FILLFills the frame with the background pen.
0x03GPU_BLITSets signal to 1. The display thread presents.
0x04GPU_CLEARFills the frame with 0.
0x05GPU_SETAPENForeground pen becomes 0xFFFFFFFF.
0x06GPU_SETBPENBackground pen becomes 0xFF102040.
0x07GPU_DRAW_LINELine from (x0,y0) to (x1,y1) in the foreground pen. 3-bit span ends here. The moving overlay uses this opcode with 16.16 endpoints.
0x08GPU_DRAW_RECTANGLERectangle outline on the same pen and rect.
0x09GPU_DRAW_ELIPSEEllipse in the rect.
0x0AGPU_DRAW_IMAGE8x8 checker at the rect origin.
0x0BGPU_DRAW_POLYGONTriangle on the rect: base along y1, apex at the top midpoint.
0x0CGPU_SPLINEQuadratic curve across the rect, 16 segments. Section 5 has the control points and the formula.
0x0DGPU_CHANNEL_ALLOCATEClears the free-request flag. When the frame has been freed, it allocates it again at the current frame_w × frame_h through AllocMemExt(GPU_MEMORY), zeroed, and named GPUFrame. When a frame is already present, the flag clear is the whole effect. If allocation returns no frame, the stream sets op_error and stops.
0x0EGPU_CHANNEL_FREEFrees the frame immediately (FreeMem) and sets the free-request flag. The frame pointer is cleared, and ALLOCATE can allocate it again.
0x0FGPU_CUSTOM0Sets the custom flag. 4-bit span ends here.

GPURunDraws clears the frame, packs a 4-bit stream, and applies one geom (x0, y0, x1, y1, color) as the pen and the rect for that opcode. color 0 is a legal pen. The geom test draws a red line and a green rectangle, then restores the 64x64 frame.

3.2. Five-bit set, 0x10-0x1F (registered handlers)

REGISTERED DRAWING HANDLERS
OpcodeNameWhat it does
0x10GPU_ALPHA_BLITFor each pixel, blends the foreground pen over the frame using the pen's alpha: (fg×a + pixel×(255-a))/255, then writes alpha 255.
0x11GPU_ALPHABLENDAverages each RGB channel of the pixel with the foreground pen and writes alpha 255.
0x12GPU_ALPHA_FILLFills the frame with the background pen's RGB and alpha 0x80.
0x13GPU_COLORKEYA pixel whose RGB matches the foreground pen becomes 0; otherwise it is unchanged.
0x14GPU_COLOR_CORRECTAdds 32 to red only, clamped to 0..255. Green, blue and alpha are unchanged.
0x15GPU_BRIGHTNESSAdds 32 to red, green and blue, clamped to 0..255. Alpha is unchanged.
0x16GPU_CONTRASTFor each of R, G, B: (c-128)×2+128, clamped to 0..255. Alpha is unchanged.
0x17GPU_SATURATIONDoubles the distance of R, G, B from their average y=(R+G+B)/3, then clamps. Alpha is unchanged.
0x18GPU_HUE_ROTATESwaps red and blue (R,G,B becomes B,G,R). Alpha is unchanged.
0x19GPU_COLOR_FILTERKeeps red and alpha; sets green and blue to 0 (a red-only filter).
0x1AGPU_INVERT_COLORSInverts red, green and blue (255-c). Alpha is unchanged.
0x1BGPU_GRAYSCALESets R, G and B to (R+G+B)/3. Alpha is unchanged.
0x1CGPU_TILEMAP_COPYCopies an 8×8 block from (x0,y0) to (x1,y1). Samples outside the frame are 0.
0x1DGPU_TILEMAP_FILLFills the frame with a 1-pixel checker of the foreground and background pens, using (x^y)&1.
0x1EGPU_MASKReplaces each pixel with (pixel & foreground pen).
0x1FGPU_EDGE_DETECTIn each row, a pixel becomes the foreground pen if it differs from its left neighbour, else 0. Column 0 is set to 0. 5-bit span ends here.

3.3. Six-bit set, 0x20-0x3F (registered handlers)

OpcodeNameWhat it does
0x20GPU_MOTION_BLURHorizontal 2-tap blur: each pixel except the last in the row becomes the average of itself and its right neighbour. The same handler as SOFTEN and BLUR.
0x21GPU_WARPRotates each row one pixel to the right; the last pixel wraps to column 0.
0x22GPU_NOISEXORs each pixel with (i×17)&0x000F0F0F, where i is the pixel index.
0x23GPU_SCRATCHDraws a horizontal line in the foreground pen across the frame at y0.
0x24GPU_SHADOWFor each non-zero-alpha pixel, plots 0x80000000 at (x+1,y+1). Walks from the bottom-right so each shadow is written once.
0x25GPU_OUTLINEIn each row, a zero pixel that follows a non-zero pixel is set to the foreground pen.
0x26GPU_MULTIPLYPer RGB channel: pixel×fg/255. Alpha is taken from the pixel.
0x27GPU_SCREENPer RGB channel: 255-(255-p)×(255-fg)/255. Alpha is taken from the pixel.
0x28GPU_ADDITIVEPer RGB channel: clamp(p+fg). Alpha is taken from the pixel.
0x29GPU_SUBTRACTIVEPer RGB channel: clamp(p-fg). Alpha is taken from the pixel.
0x2AGPU_DIFFERENCEPer RGB channel: abs(p-fg). Alpha is taken from the pixel.
0x2BGPU_LIGHTENPer RGB channel: max(p, fg). Alpha is taken from the pixel.
0x2CGPU_DARKENPer RGB channel: min(p, fg). Alpha is taken from the pixel.
0x2DGPU_SOFTENSame as GPU_MOTION_BLUR: a horizontal 2-tap average.
0x2EGPU_SHARPENHorizontal sharpen: each pixel except the last becomes 2×itself minus its right neighbour, per RGB, clamped.
0x2FGPU_EMBOSSFrom the right, each pixel's red minus its left neighbour's red, plus 128, written as grey RGB. Alpha is kept. Column 0 is unchanged.
0x30GPU_PIXELATEEach pixel is replaced by the pixel at (x&~1, y&~1), a 2×2 block.
0x31GPU_DITHERA pixel with even (x+y), or with red < 128, becomes 0; otherwise it becomes the foreground pen with alpha 255.
0x32GPU_HIGHLIGHTIf R+G+B > 384, the pixel becomes 0xFFFFFFFF; otherwise it is unchanged.
0x33GPU_SHADOWIZEHalves red, green and blue. Alpha is unchanged.
0x34GPU_OPAQUESets alpha to 255. RGB is unchanged.
0x35GPU_TRANSLUCENTSets alpha to 0x80. RGB is unchanged.
0x36GPU_GLOWIf alpha is non-zero, adds 40 to red, green and blue, clamped. Transparent pixels are unchanged.
0x37GPU_FADE_INAdds 32 to alpha, or sets it to 255 if it is already above 223. RGB is unchanged.
0x38GPU_FADE_OUTSubtracts 32 from alpha, or sets it to 0 if it is below 32. RGB is unchanged.
0x39GPU_BLURSame as GPU_MOTION_BLUR: a horizontal 2-tap average.
0x3AGPU_CONTOURSame as GPU_EDGE_DETECT.
0x3BGPU_INTERRUPTSets the interrupt flag (GPU_FLAG_INTERRUPT) for the stream to act on.
0x3CGPU_ZOOM_INSame as GPU_SCALE_UP: nearest-neighbour 2× of the top-left quadrant into the whole frame.
0x3DGPU_ZOOM_OUTSame as GPU_SCALE_DOWN: even pixels are copied into the top-left quadrant; the rest of the frame is cleared to 0.
0x3EGPU_BEZIER_PLOTSame as GPU_SPLINE: a quadratic curve across the rect, 16 segments.
0x3FGPU_BEZIER_UPDATEMoves (x0,y0) one pixel toward (x1,y1). 6-bit span ends here.

3.4. Seven-bit set, 0x40-0x6C (registered handlers)

GPU_USER_FUNCTION0 through GPU_USER_FUNCTION35 (0x40 through 0x63) are reserved for user-registered functions. The transform opcodes follow.

OpcodeNameWhat it does
0x40-0x63GPU_USER_FUNCTION0 .. 35Reserved for user-registered functions. The default handler sets GPU_FLAG_CUSTOM and plots one test pixel at ((op&7), ((op>>3)&7)) in colour 0xFF000000 | ((op&0xFF)×0x00010101).
0x64GPU_SCALE_UPNearest-neighbour 2× of the top-left quadrant into the whole frame. Same handler as GPU_ZOOM_IN.
0x65GPU_SCALE_DOWNEven pixels are copied into the top-left quadrant; the rest of the frame is cleared to 0. Same handler as GPU_ZOOM_OUT.
0x66GPU_ROTATE_LEFTRotates a square frame, 2 pixels or more on a side, 90° counter-clockwise.
0x67GPU_ROTATE_RIGHTRotates a square frame, 2 pixels or more on a side, 90° clockwise.
0x68GPU_ROTATE_180Reverses the pixel array in place (180°).
0x69GPU_FLIP_HORIZSwaps pixels about the vertical centre of each row.
0x6AGPU_FLIP_VERTSwaps rows about the horizontal centre.
0x6BGPU_MIRROR_HORIZCopies the left half of each row onto the right half.
0x6CGPU_MIRROR_VERTCopies the top half of the frame onto the bottom half. 7-bit span ends here.

4. NetXecChannel timing

The display loop runs on the thread that called SDL_Init, one frame per NetXec tick (NETXEC_TICK_MS 16, about 60 frames per second). Container rides this tick. The tick is paced by NetXecTickWait on a fixed grid, not by a plain sleep.

4.1. One display tick

OrderCallWhat it does
1NetXecHandPendingEventsPolls SDL and hands each event to EventChannel. Escape opens diagnostics; q requests quit.
2Watchdog, GuruHealthTickCore-channel wait checks, and the Guru health count for a restarted user main.
3TickAudioSync, TickVideoThe NetXec media clock steers the audio stream, and the video frame due on that clock is put on its texture.
4TickGPUFrameThe render slot drawn last tick becomes the display slot, and every running GPU thread runs once, in one command buffer and one submit with no wait.
5ContainerTickAdvances splines, orbits and anim gobs, composes the view, steps the GPU moving lines when GPURender is on, and draws the GPU frame's display slot with DrawGPUFrame (zero copy). Skipped when a nested container run owns the frame, because that run ticks itself.
6NetXecTickWaitWaits for the next tick on the grid.

The moving lines are 12 segments with 16.16 fixed-point endpoints, so a step smaller than one pixel is kept; the frame is the size of the letterbox, so lines are not snapped to a view pixel and then upscaled. NX_AUTOQUIT_MS=n stops the loop after n milliseconds for a timed smoke; it is not a second frame clock.

5. Splines

Two different splines live in the tree. GPU_SPLINE (opcode 0x0C) is a quadratic curve drawn once into the GPU frame. ContSpline is a HyperView path that walks a gob from waypoint to waypoint on each display tick. The current dispatch table also registers GPU_BEZIER_PLOT (0x3E) and GPU_BEZIER_UPDATE (0x3F); the following quadratic and HyperView path walkthrough describes the original display demo.

5.1. GPU_SPLINE, the quadratic

The curve is a quadratic Bezier inside the current rectangle (x0, y0, x1, y1). It is stroked in the foreground pen. Sixteen steps. Each step is a straight GPU line, so the curve is a polyline of 16 segments.

PointWhere
Start P0(x0, y1). Bottom-left when y1 is below y0 in screen coordinates, because y grows downward.
Control C((x0 + x1) / 2, y0). Middle of the top edge.
End P2(x1, y0). Top-right of the same rect.

Step i runs from 1 to 16. t is i. u is 16 - t. The point is

x = (u*u*x0 + 2*u*t*cx + t*t*x1) / 256
y = (u*u*y1 + 2*u*t*cy + t*t*y0) / 256

That is the quadratic (1-s)^2 P0 + 2(1-s)s C + s^2 P2 with s = t/16. Dividing by 256 is (16*16). At s = 0 the point is P0. At s = 1 the point is P2. The control point pulls the bow up to the top edge. The 4-bit test uses the rect 8,8 through 48,40, so that curve is part of the 333 foreground pixels.

5.2. ContSpline, the HyperView path

ContSpline is 504 bytes and holds up to 32 waypoints. Each segment is an octant step. ContainerSplineCreate takes parallel x, y, and optional z arrays, a velocity in pixels per tick, and flags. A missing z array stores z = 1 and does not set the Z buffer flag. A supplied z array sets CSP_ZBUFFER, the same idea as HyperView SP_ZBUFFER_ENA. ContainerGobAttachSpline stores the pointer on the gob, sets CGOB_SPLINE_ENA, and places the gob on waypoint 0.

The eight octants set the step. Octant 0 is straight up (dx 0, dy -velocity). Then clockwise: up-right, right, down-right, down, down-left, left, up-left. Screen y grows downward, so negative dy is up. Z steps by the same velocity toward the target, or 0 when the Z buffer flag is off. When z is above 20 the Z step is doubled. When z is below 7 the Z step is shifted right by 3, and a zero result becomes 1 or -1 so the gob still moves. Z is never left below 1.

ContainerSplineAdvance runs once per display tick from ContAdvanceAllSplines, and only for a gob whose flags include CGOB_SPLINE_ENA. X, Y, and Z each walk toward the segment target. If the remaining distance is within one step, the coordinate snaps to the target and that axis is marked arrived. CSP_ARRIVED is all three axis bits. On arrival the path takes the next waypoint. At the end, CSP_STOP_AT_END clears CSP_ON and CGOB_SPLINE_ENA. CSP_BOUNCE_AT_END reverses dir. CSP_WRAP_AT_END returns to waypoint 0. A move pushes the old position so the background under the gob can be restored.

The path color stored on the spline is 0x00FFCC44. CSP_PATH_LINE and CSP_TRACE_LINE are the paint flags. This path is the HyperView compose, separate from opcode 0x0C.

6. Functions

The public GPUChannel calls a program uses, with signatures from channels.h in the same tree as the source stamp above. The opcode handlers are static in GPUChannel.c; programs use the public calls below. The compute, bytecode and resident layers folded into GPUChannel.c use PascalCase names (for example StageOpen, ComputeKernelCreate, BytecodeRun, ResidentGpuOpen).

6.1. GPUChannel

FunctionWhat it does
OpenGPUChannel(nx)Opens the channel once: the channel, a 256-byte stream buffer, Runtime, RunInfo, the lock and a 64x64 GPU_MEMORY host frame. A second call returns the same channel.
AttachGPUChannel(nx, w, h, dev_flags)Opens the GPUChannel as Device sub 0 and sizes its frame (0, 0 = the default). Safe to call twice.
OpenGPUChannelFor(owner) / CloseGPUChannelForAn owned channel: the owner's CloseGPUChannelFor closes it.
CloseGPUChannel(gpu)Drops a reference; the last one frees the frame, buffer, Runtime, RunInfo, lock and the stream executor's GPU objects.
GPUChannelGet()Returns the open channel, or NULL.
GPUInstallStream(gpu, ops, count, width)Packs a stream: width 4, 5, 6 or 7, count 1..64. Writes the marker, the width byte and the packed opcodes, checks the unpack. Returns 0 or -1.
GPURunStream(gpu)Runs the installed stream: on the GPU stream executor with a device, on the C handlers without one (or with GPU_STREAM_CPU=1). control must be nonzero and is cleared. Returns 0 or -1.
GPUChannelTest4(gpu)Installs and runs the 15-opcode 4-bit test. Passes when all 15 ran, signal is 1, foreground pixels exist and the custom flag is set.
GPUResizeFrame(gpu, w, h)Replaces the host frame (and the executor's frame buffers) at w x h, up to 4096 a side. The new frame is in place before the old one is freed; a zero side leaves the current frame in place.
GPURunDraws(gpu, ops, geom, count)Clears the frame, packs a 4-bit stream and applies one GPUGeom (rect and pen) per opcode. The clear is the stream's first GPU record, so it is one run.
GPUChannelTestDraw(gpu)Draws a red line and a green corner on a 128x64 frame, then restores 64x64.
GPUFrameSync(gpu) / ReadGPUFrame(argb, w, h, slot)GPU-to-CPU frame paths for tests and screenshots.
OpenGPUFrame(w, h) / CloseGPUFrame()The GPU frame pair (render and display textures), cleared on the GPU.
TickGPUFrame()Once per NetXec tick: swaps render and display when something was drawn and runs every GPU thread once. Returns 1 swapped, 0 nothing drawn, <0 error.
DrawGPUFrame(ren, x, y, w, h)Draws the display slot on an SDL renderer on the same device: zero copy.
GPURender(on)Turns the moving-line layer on or off.
GPUMovingLines(w, h)Steps and draws the 12 lines into the render slot of a frame the size of the letterbox, on the GPU, with the host path stepping the same 16.16 bounce.
GPUDrawCommandSet(surface, x, y)Draws the "16 COMMAND SET" panel, 00 NOP through 0F CUSTOM0, on a ContainerChannel WINDOW surface (0 = the joined surface).
GPUOverlay(surface, x, y, w, h)Puts the newest GPU frame (or the GPU layer compose) on a WINDOW surface as a GPU texture, and blits the host frame when the surface is on the host path. Returns 1 drawn, 0 when there is no frame to draw, or a negative code.
ImageToGPU(gpu, path) / LoadGPUGob(gpu, gob)An image gadget whose ARGB face is a GPU_MEMORY block uploaded once (see Image gobs above).
SetGPUImage(gpu, gob) / GPUImageInfo(gob, ...)Binds the gob DRAW_IMAGE draws (NULL = the checker) / reads its block and size.
ReleaseGPUImage(gpu, gob)Frees the block. An ImageToGPU gadget is removed from the container member list and freed; a LoadGPUGob gadget is left to its caller.
GPUPutChannelObject / UpdateGPUObject / ReleaseGPUObjectChannelData GPU objects such as GPUInfo: create, update a range, release.
GPUKernelLoad / GPURun / GPURun3D / GPUKernelFreeLoaded compute kernels on the resident device (CPU twin when CPU is selected).
GPUVarNew / GPUVarSet / GPUVarGet / GPUVarFreeResident variables for the loaded kernels.

6.2. Command mailbox

The command mailbox is GPUChannelCommand. Member write/read is the ChannelData path on a joined GPUChannel.

FunctionWhat it does
int GPUChannelCommand(struct GPUChannel *gpu, uint32_t op, const void *in, uint32_t in_len, void *out, uint32_t out_cap, uint32_t *out_len)Sends one mailbox opcode with an optional input buffer and optional output buffer. Returns 0 on success, or a negative error.
int JoinGPUChannel(struct Channel *caller, uint32_t *member_id)Joins the caller to the open GPUChannel and returns a member id.
int LeaveGPUChannel(struct Channel *caller, uint32_t member_id)Leaves the GPUChannel, dropping that member id.
int WriteGPUChannel(uint32_t member_id, const struct ChannelData *req, const void *payload, uint64_t payload_bytes)Writes one ChannelData request, and an optional payload, for that member.
int ReadGPUChannel(uint32_t member_id, struct ChannelData *reply, void *payload, uint64_t payload_cap, uint64_t *payload_len)Reads one ChannelData reply, and an optional payload, for that member.

6.3. GPU thread controls

The public path is GetNetXecThread(MF_THREAD, &req) with GPU_THREAD in tr_flags. OpenGPUThread and CloseGPUThread are GPUChannel's implementers, used by ThreadChannel.

FunctionWhat it does
int OpenGPUThread(const struct ThreadRequest *req, uint32_t *handle)Used by ThreadChannel: creates a GPU thread and returns its generation-checked handle.
int CloseGPUThread(uint32_t handle)Used by ThreadChannel: closes that GPU thread handle.
int PauseGPUThread(struct NetXecThread *t)Pauses a live GPU thread (the NetXecThread* with TH_FLAG_GPU).
int ResumeGPUThread(struct NetXecThread *t)Resumes a paused GPU thread.
int PostGPUThread(struct NetXecThread *t, const uint32_t *words, uint32_t n)Posts words to the thread's inbox. Returns GPU_ERR_FULL until the tick has taken the last post.
int PeekGPUThread(struct NetXecThread *t, uint32_t *words, uint32_t n, uint64_t *tick)Copies the last retired outbox immediately.
int StatGPUThread(const struct NetXecThread *t, struct GPUThreadStat *st)Fills counters for that thread, or the global counters when t is NULL.
void CloseGPUThreads(void)Closes every GPU thread.
void GPUThreadsFramePeriod(uint64_t period_ns)Tells GPU threads the NetXec tick period. Sustained misses throttle GPU threads.
uint32_t GPUThreadRecords(uint32_t *rec, uint32_t max)Writes slot, state, handle and owner (4 words each) for each live GPU thread, up to max records.

6.4. GPU memory

AllocGPU / FreeGPU work on the host path and on a registered device. GPUChannel registers its SDL_GPUDevice with GPUMemSetDevice when the device is up, and clears that registration before the device is destroyed.

FunctionWhat it does
void *AllocGPUMem(uint64_t size)AllocMem wrapper that requests GPU_MEMORY. The payload is zeroed. Free it with FreeMem.
void *AllocGPU(uint64_t size, const wchar_t *name)Named GPU_MEMORY allocation (host-staged, and device-backed when a device is set).
void FreeGPU(void *ptr, uint64_t size)Frees a block from AllocGPU, on the host path and on a registered device.
void GPUMemSetDevice(struct SDL_GPUDevice *dev)Registers or clears the SDL_GPUDevice used to back GPU memory.
int GPUMemUpload(const void *p)Uploads a whole block from the host to its GPU buffer. Returns 0 on a device-backed block, or -1 on a host-only block.
int GPUMemDownload(const void *p)Downloads a whole block from its GPU buffer to the host. Returns 0 on a device-backed block, or -1 on a host-only block.
struct SDL_GPUBuffer *GPUMemBuffer(const void *p, uint64_t *offset)Returns the GPU buffer for a device-backed block or payload pointer, and an optional offset.
long long GetGPUMemory(void)Bytes currently charged to GPU_MEMORY. The call stomps the volatile sample.
uint32_t AllocGPUResource(void *device, uint32_t kind, const void *info, uint64_t bytes, const char *name)Creates an SDL GPU object through the resource table. A non-zero handle is a live resource. bytes is the GPU_MEMORY estimate.
void *GPUResourceObject(uint32_t h)Returns the SDL object for a live handle, or NULL if the handle is stale.
int FreeGPUResource(uint32_t h)Releases that handle. Returns 0, or -1 on a stale handle or a double free.
uint32_t GPUResourceCount(void)Number of live GPU resource handles.

6.5. Resident draw calls

FunctionWhat it does
int GPUDrawOpen(void *sdl_window)Opens the resident draw path and claims the window. Returns 1 when the GPU path is ready.
int GPUDrawReady(void)Returns whether the resident draw path is ready.
const char *GPUDrawDriver(void)Returns the GPU driver name for the open draw path.
int GPUDrawTexSet(uint32_t id, const uint32_t *argb, uint32_t w, uint32_t h)Creates or resizes texture id and uploads ARGB8888 pixels.
void GPUDrawTexFree(uint32_t id)Frees texture id.
int GPUDrawTexFrame(uint32_t id, uint32_t src)Binds id to a GPU frame source (GPU_FRAME_SRC_*) already on the GPU. No upload.
int GPUDrawFrame(const uint8_t *recs, uint32_t n, uint32_t w, uint32_t h, uint32_t clear_argb, const char *shot_bmp)Draws n records into the GPU target (w×h), then blits it to the window swapchain. If shot_bmp is not NULL, downloads the target and saves it as BMP. Returns the number of draw calls, or <0 on error.
int GPUDrawFlush(const uint8_t *recs, uint32_t n, uint32_t w, uint32_t h, int clear, uint32_t clear_argb)Flushes n records into the target texture, ready for a later present. clear selects a CLEAR load (first pass after a clear); otherwise LOAD appends to earlier flushes. Returns the number of draw calls, or <0 on error.
int GPUDrawReadPixels(int32_t x, int32_t y, uint32_t w, uint32_t h, uint32_t *out)Synchronous ARGB8888 readback of a target-texture region. Call it after GPUDrawFlush.
int GPUDrawPresent(const char *shot_bmp)Blits the target texture to the swapchain. If shot_bmp is not NULL, saves the target as BMP first.
void GPUDrawClose(void)Closes the resident draw path and releases its window claim.

6.6. Stream stats

FunctionWhat it does
int StatGPUStream(struct GPUStreamStat *s)Fills stream counters: whether the stream is on the GPU, the frame size, runs, records, passes, presents, host uploads and reads, plus the step-26 fields record_uploads, record_resident and repeats.
int GPUStreamForceCPU(int on)Selects the CPU handlers (1), the GPU path (0), or queries the current mode (-1). Returns the previous value.

6.7. Vulkan video device

The process has one SDL_GPUDevice, created on first use. When the automatic Vulkan/SPIR-V path is taken, it is opened so Vulkan Video decode can sit on that same device.

FunctionWhat it does
void *GPUDeviceRef(const char *who)Returns the process's one SDL_GPUDevice (created on first use) and adds a user. who is a label for the ref.
void GPUDeviceUnref(void *dev)Drops one user of that device. The last user destroys it.
int GPUDeviceRefs(void)Returns the current user count of the one device.
void GPUDeviceShutdown(void)End of run: destroys the parked device once its users have been dropped.
int GPUDeviceVideoExtensions(void *dev, const char *const **names)Returns the count of Vulkan Video extensions on that device, and optionally the name list. Returns 0 when the list is empty.
void *GPUChannelHandle(void)Returns the GPUChannel SDL_GPUDevice pointer, or NULL.
int GPUDevice64(void *dev)Returns 1 if dev was created with shaderFloat64 and shaderInt64.

6.8. Bit packer

FunctionWhat it does
PackBits(source, bitwidth, target, length)Keeps the low bitwidth bits of each source byte and packs them LSB first into target.
UnPackBits(source, target, packed_length, bitwidth, output_length)Reads packed fields back out. A 16-bit accumulator keeps a field that straddles two source bytes.
SET_BITSINWIDTH(target, width)Macro. Stores the mask (1 << width) - 1.

6.9. Spline

FunctionWhat it does
ContainerSplineCreate(...)Builds a ContSpline. Needs at least two points. Caps the count at 32. Arms the first segment. Arguments: container, name, x[], y[], z[], npoints, velocity, flags.
ContainerGobAttachSpline(gob, sp)Attaches the path and moves the gob to waypoint 0.
ContainerSplineAdvance(sp, gob)One HyperView step on X, Y, and Z. Advances, bounces, wraps, or stops at the end.
ContAdvanceAllSplines(cc)Calls advance for every spline-enabled gob. ContainerTick calls this once per 16 ms tick.
Hits--