Backend target storage
mirui::render::BackendTarget describes native output storage and source-owned CPU readback. It is a backend extension interface; application components use Texture and Outputs.
| Backend | Backing Storage | Thread Ownership | Readback Support | Target Budget Scope |
|---|---|---|---|---|
Software (CPU) | Checked CPU byte plane (Straight RGBA / format-specific) | Portable (Send + Sync with sync) | Zero-copy resident borrow (Texture::pixels) | Shared Outputs pool ledger (pixels + paint workspace) |
SDL-GPU | Single-sample packed Premultiplied RGBA8 texture | Creating-thread bound (ThreadOwner + ThreadResource<T>) | Direct regional/full readback (readback_bytes = 0 staging) | Outputs pool + Factory with_projective_fallback workspace |
WGPU | Resolved view + optional MSAA attachment (RGBA8) | Portable Device / Queue context (Send + Sync) | Native hosts via row-aligned staging buffer (none on WASM) | Outputs pool (incl. readback_bytes) + Factory with_target_edit_budget |
Web Canvas | Offscreen <canvas> / 2D context & ImageData cache | Browser main / worker thread local | Synchronous 2D getImageData (unavailable on browser WGPU) | Shared Outputs pool + upload cache limits |
With the optional sync feature, target payloads must implement Send + Sync. This constrains the transferable representation; raw objects with creating-thread restrictions remain in their thread owner. The default feature set retains local payloads. See shared textures for application handoff.
Storage and lifetime
Before producing an offscreen `WidgetTexture`, the renderer builds a `TargetPlan` accounting for both device texture storage and any required fallback/readback staging bytes.
let plan = renderer.plan_target(TargetDescriptor { width, height, alpha })?;Includes SDL-GPU / WGPU 256-byte row alignment paddingTargetDescriptor combines a checked PlaneLayout with TargetAlpha::Straight or Premultiplied. The alpha encoding describes stored channels, independently of the destination blending policy in AlphaMode.
TargetPlan reports native storage bytes, drawing workspace bytes and readback_bytes. Storage includes multisample and resolve attachments. Readback bytes bound the backend-owned staging needed to read the complete source, excluding the destination CPU pixels. SDL writes directly into that destination and reports zero; WGPU reports the row-aligned staging buffer size and checks the device buffer limit before allocation. CPU copies need separate admission; a plan is not evidence that allocation succeeded. allocated_bytes() reports the actual target allocation.
Widget output admission protects the remaining pending outputs' conservative pixel requirements and shared paint workspace through the existing byte budget before preferring native consumer targets. Reusable native targets also retain their required shared binding workspace. Dependency invalidation and View execution remain producer-first, and every storage slot is admitted before a View runs. Completed outputs and frozen history keep their storage. If conservative working-set protection or native planning metadata cannot be prepared, admission retains producer-first storage selection. Native-only planning metadata reuses capacity within the current capture tree and is released on structural shrink, output exit or memory trimming; software-only preparation does not allocate it. This metadata is additional to the pixel budget.
Pending sources with a CPU consumer prefer CPU production, including sources shared with native consumers. Native consumers use their existing upload path for those CPU pixels. Completed native sources are reused without executing their Views again. Replacing reusable native storage with CPU pixels requires spare capacity outside the remaining working-set reservation; when it cannot be proven, native storage is retained and necessary source readback remains available. This preference uses current output dependencies rather than widget or device-specific rules.
Shared storage requires BackendTarget::retain_storage(TargetStorage). The producer attaches one receipt after allocation and before publication; a wrapper forwards it to the actual resource owner. The receipt retains both the existing storage charge and readback allowance. Clones retain those same charges without reserving them again. Release the receipt after the associated resources and staging, including any deferred owner-thread destruction. Repeated attachment is an error. Native plans include their receipt-retention fields, and the output budget also accounts for shared receipt ownership.
Thread-bound resources
With shared storage and std, thread-bound backends can use render::target::ThreadOwner and ThreadResource<T>. The token is transferable even when T is local. with resolves the native resource only on its creating thread; another thread receives WrongThread, a closed owner receives InvalidTexture, and recursive access receives InvalidScope. Returned values cannot borrow the native resource. No remote device calls are queued.
Include owner.metadata_bytes::<T>()? in planning and recheck token.metadata_bytes()? for actual allocation. retain_storage partitions the already admitted charge between the native storage, token control and owner metadata. collect destroys retired values outside registry borrows, without allocating; an idle owner with no retirements returns immediately. Call it at existing safe maintenance boundaries. close invalidates all tokens before destroying idle values; an active callback releases its value on return. Closed tokens retain their metadata charges until released. Unpublished resources released on their owner thread are destroyed before the creation reservation is returned; admitted resources retain the normal deferred retirement path. The default local storage path does not compile this helper.
A target owns the device resources required to sample, read and release its storage. It must not borrow a temporary renderer or require a window frame to remain alive. Validate native handles against device identity and resource generation before using them; matching concrete payload types alone is insufficient.
SDL-GPU targets
SDL-GPU surfaces and upload caches share one renderer/window owner and resource generation. Temporary renderers borrow driver state only during upload, drawing or readback. Source pixel preparation, CPU glyph rasterization, software fallback and region-edit callbacks run outside that borrow. A conflicting driver borrow returns RenderError::InvalidScope; retained caches keep the underlying renderer alive until their textures are released.
SDL-GPU native targets use single-sample, packed RGBA8 storage with premultiplied channels. Window MSAA does not add multisample attachments to these textures. Local storage retains its renderer owner after the surface and factory are dropped. Shared storage keeps raw textures on their creating thread and transfers metadata and tokens; source readback on another thread returns WrongThread. Closing a shared surface invalidates its native sources and destroys idle raw targets before releasing the renderer. Prepared CPU guards remain readable, and tokens retain their control charges through deferred destruction. Creation, renderer preparation and idle frame maintenance collect retired targets at safe owner boundaries. Rebuilding clears the complete target; incremental scopes preserve valid contents. Binding saves the parent target, viewport, clip, scale, logical size, draw color and blend mode. Failed, abandoned, out-of-order or stale restoration prevents further device submission.
SDL source reads and region-edit callbacks expose straight-alpha pixels. Software fallback converts the affected region before drawing and converts it back before replacement, reusing its existing workspace. Non-source-over composites on transparent native targets use this path. Source readback accepts padded destinations, including buffers without trailing padding after the final row. Prepared nested binding and source readback allocate no additional Rust storage; target creation and explicit snapshots allocate storage.
SDL consumers sample completed same-device native textures directly for source-over when the driver supports premultiplied blending. Rectangle and affine-quad sampling apply opacity to both premultiplied color and alpha. Other devices, unsupported blending and other composite modes use source-owned pixels and the existing upload cache. Active or unfinished sources are rejected before cache lookup. Sampling runs inside a callback with a short texture borrow; raw texture references cannot escape that callback. The device borrow covers only drawing, and source readback occurs outside it.
WGPU targets
WGPU frame attachments determine pipeline format, sample count, clipping bounds and readback format. The resolved view retains its backing texture; a multisample view retains the attachment loaded by subsequent passes. Command encoding, uniform storage and pipeline caching remain shared by the renderer.
Native WGPU targets retain the original device context and queue independently of the surface and factory. Packed RGBA8 targets preserve their multisample and resolve attachments across incremental scopes. Rebuild clears transparent once; failed writes require rebuilding. Nested scopes restore attachments and viewport scale, including scales below one. Frame workspace remains reusable while no attachment is bound, so offscreen work does not initialize or clear the window.
WGPU consumers sample completed targets from the same device directly through their resolved views, without creating CPU pixels or upload-cache entries. Other sources use source-owned readback and the existing upload cache. Source checks precede cache lookup, and active or unfinished targets cannot be sampled even when cached pixels exist. Device identity is checked independently of texture handles. Rectangle and projective blits preserve source alpha encoding and apply opacity and corner coverage once.
Device loss and abandoned or out-of-order restoration invalidate native resources and block later rendering and presentation. Source reads reject active or unfinished targets and return straight-alpha pixels through the shared readback implementation. Non-source-over composites on transparent native targets use the existing software fallback. WGPU native targets are available on native hosts; synchronous source readback is not provided by the WASM backend.
Native WGPU readback reuses a device-specific staging buffer and mapping completion state. Shared targets retain the existing portable device context through shared storage, publish completed/active state atomically, and take the readback workspace out of its metadata gate while running driver operations. The readback lease restores storage on return or unwinding; a conflicting immediate backend read returns InvalidScope. Ordinary Texture polling coordinates readers through the existing mirror state. Plans account for the additional shared readback control storage. Factory memory trimming releases that storage; growth replaces it, and failed mapping discards it before retrying. Source bytes are converted directly into checked pixel storage, preserving destination stride and padding. Explicit snapshots still allocate independent CPU pixels, and GPU command encoding and mapping retain their driver costs.
Source reads
Renderer::route classifies a request, prepare(request, route, cx) retains its ready source storage, and submit(&PreparedDraw) consumes that storage. Preparation does not borrow the renderer across its return. RenderEngine<T> exposes the same preparation step. compose_backend! uses its declared command routes for classification, preparation, ordinary submission and text-run submission, including nested compositions. If preparation changes the command kind, submission uses the prepared command's route. An engine's begin runs only after preparation succeeds; a failed begin does not call end, while a failed submission still does.
poll_draw_request(request, text_run, cx) runs the same route, preparation and submission sequence with the caller's task context and optional TextRunIdentity. Pending preparation never submits. Its default implementation uses the backend's existing methods; third-party renderers need no additional implementation. Independent preparation remains available for retained source leases and scene replay's saved routes.
draw_request(&request) and draw_text_run(&request, identity) use this entry with a no-op waker and return ResourcePending for pending preparation. Use poll_draw_request with a task context when source readiness must wake the caller. Region and projective wrappers normalize a polled request once before forwarding it, including its text identity and waker. Independent route and prepare calls each normalize their own input; submission never reapplies the transform.
Software submission samples the retained source region using the original image dimensions, keeping integer row-copy and fractional sampling paths. SDL-GPU and WGPU sample compatible native sources directly. Upload-cache misses only consume resident pixels and never initiate source readback. Source and destination budgets remain separate.
SDL-GPU, WGPU and Web Canvas upload prepared source rectangles into full-size cached textures without changing UV coordinates. Coverage is recorded only after successful upload, using one bounded rectangle per cache entry; unions with holes are never treated as valid. Coverage metadata counts toward the existing cache limit. Integer-aligned draws retain a conservative sampling footprint, including filtering neighbors; fractional placement and arbitrary transforms prepare the full source.
WGPU queue writes copy regional source bytes into driver-owned staging before the CPU lease ends. RGBA rows retain their original stride without a packing allocation; other pixel formats use the existing conversion path on the requested region. GPU views retain their storage through queued drawing even if the upload cache evicts its index.
Web Canvas copies prepared regions into its existing offscreen texture cache using original source offsets. Partial or non-RGBA rows use the existing packed RGBA conversion; complete packed RGBA sources remain directly borrowed during upload preparation. Warm coverage performs no upload or conversion. Glyph cache storage and budgets are independent and unchanged.
Third-party CPU renderers can use the default prepare implementation and read draw.texture_region(). Native renderers override preparation to check source-device compatibility and return PreparedDraw::native, or prepare CPU pixels before using an upload path. A renderer must recheck destination state and reject a changed output scale before submitting; a prepared source does not reserve destination workspace. Engines that specialize text runs can override submit_text_run; its default uses the engine's ordinary submit implementation.
Third-party upload backends can call PreparedDraw::poll_upload(request, route, scale, cx) for conservative nearest/bilinear source coverage, or poll_complete if their cache requires complete images. Both preserve the original draw request and retain the source lease through submission. They are available without enabling an internal GPU backend. Upload from draw.texture_region().tiles() instead of querying the source cache again: a retained lease remains valid even after another preparation replaces its cache index. Device textures retain their original dimensions, and partial coverage must never be exposed as a complete native output.
use core::task::{Context, Poll};
use mirui::render::{DrawRequest, RenderError, Renderer};
fn poll_draw(
renderer: &mut dyn Renderer,
request: DrawRequest<'_, '_>,
cx: &mut Context<'_>,
) -> Poll<Result<(), RenderError>> {
let route = renderer.route(&request)?;
let draw = core::task::ready!(renderer.prepare(request, route, cx))?;
Poll::Ready(renderer.submit(&draw))
}Region readback and CPU cache
PreparedDraw::poll_cpu(request, route, output_scale, cx) retains the source pixels needed by a draw. Direct CPU storage, including mapped RAW images, remains a complete borrowed view without computing a regional footprint. Sources requiring preparation use the software rasterizer's integer and fractional sampling calculations for axis-aligned draws; arbitrary transforms conservatively retain the complete source. This does not trigger full-image decoding or readback for directly borrowed storage. texture_region() exposes the ready lease without performing another read. PreparedDraw::native retains command and source identity without CPU readback, leaving device compatibility and feedback checks to the backend. The token copies the existing command description, borrows its resources and does not borrow the destination renderer. request() returns the retained original geometry, not the cropped region's dimensions.
Texture::backend_target() gives backend implementations a checked, read-only native payload without submitting work or reading pixels. Some permits inspection with as_any; consumers must still check destination device identity and reject active-target feedback. CPU textures and unavailable native storage return None; preparation then checks and pins the requested CPU region, including cached regions that outlive their source device. Missing regions retain the source error. Unfinished contents and access conflicts return errors; the method cannot be used to acquire a writable target.
read_pixels_into(region, destination) receives a source-pixel Region and a prepared TexturePixelsMut matching that region's dimensions and the source format. TargetDescriptor::readback_region validates the request and returns the checked backend rectangle; invalid, empty and out-of-bounds requests fail before writing. The destination uses local coordinates and its own stride. Full reads pass target.descriptor().region(). Source reads write straight-alpha pixels, including when native storage is premultiplied. The source implementation completes necessary pending writes and restores any changed device state on both success and error. Device restoration failures must prevent further submission.
The backend does not create a second persistent CPU cache or retain the destination borrow. Pixel caching and publication belong to the common resource layer. Newly allocated native storage is not a completed image and must not be published before initialization and successful production.
Texture::pixels() only borrows resident pixels. Ok(None) denotes a valid source needing readback; Texture::read_pixels() prepares its CPU copy and returns a TexturePixels guard. Multiple guards share those bytes. Unchanged resident pixels need no additional readback, and rewriting the source invalidates the copy while retaining its allocation. Failed or interrupted writes cannot expose stale pixels; a failed read cannot publish a partially populated copy. A valid CPU copy remains readable after source device loss.
Cached pixel views retain immutable storage through cache handles rather than holding a cache-manager borrow. Device validation and readback execute outside the manager borrow; recursive reads of the same in-flight copy return InvalidScope. Failed or unwound reads restore reusable storage without publishing its bytes. The cache owner is allocated on the first read; subsequent views and prepared readback retries allocate no additional Rust storage. Pixel allocation charges remain alive until the last storage handle is released.
Texture::pixels_in(Region) borrows a resident source region without allocation, copying or device work. Region and TextureRegion::get_pixel use absolute source pixel coordinates; TexturePixels returned by pixels() or tiles() uses coordinates local to its view. A subview retains the source stride and includes only the bytes needed through its final pixel, not trailing row padding. Invalid ranges return an error. An in-bounds empty region is ready with no tiles; Ok(None) denotes missing resident data, not an empty region. Keep the region alive while using its borrowed views.
poll_pixels_in(region, cx) prepares the requested source region, while poll_read_pixels(cx) prepares a complete contiguous view. Resident views complete immediately without allocating. Native device readback remains synchronous and may wait for the device; polling does not turn driver calls into asynchronous work. Native region reads use region-sized destinations rather than reading the complete source.
Output admission and publication
Native CPU cache admission reserves one full pixel plane and its cache-owner metadata. Regional allocations, including independently pinned owners, draw from that same reservation; unused bytes remain committed to the source. Insufficient capacity returns ResourceLimit(Texture) without changing live views. Unpinned buffers are reused, and a resident complete image supplies regional subviews without another allocation or readback. A partial cached region remains readable after device loss but cannot stand in for a complete image. Default budget limits are unchanged.
Native output admission reserves target storage, a complete CPU copy and backend readback staging in the shared output budget. The CPU copy is allocated on demand, then charged at its actual capacity. The staging reservation remains held through native resource retirement; it is an admission bound, not a measurement of driver memory. Native cache accounting includes these reserved bytes. Pixel guards and upload keys do not create another pixel cache; keys retain an identity token without retaining the source device. Cold target metadata allocations are separate from image-plane byte accounting.
Output publication retains an already valid CPU copy under the published revision, including copies read for history comparison. Current and previous outputs remain separate slots. Native writes use TargetUpdate::Rebuild through the existing renderer scope; no additional publication state or renderer is required. Shared storage makes read-only pixel guards transferable while preserving their borrowing lifetimes. CPU construction itself does not allocate device ownership or native caches.
Native output reservations check the selected writable slot against its producer and plan. Compatible storage is reused; incompatible storage is released and recreated within the existing budget without replacing frozen history. Check errors propagate without recreating storage. Newly created targets must also satisfy the producer's reuse check. A valid cached output remains available to other devices without reallocating its source; readiness checks validate source availability without readback, including an existing CPU copy after device loss.
An output read pins its storage. Memory trimming preserves borrowed output pixels, their records and their budget charge; a later trim can reclaim them after the reads are dropped. Active write and workspace leases keep their existing release-on-return behavior.
Output production automatically selects native targets when the backend plan and complete storage/workspace requirements fit. Otherwise it selects software pixels before invoking the View. Native binding workspace is separate from View paint workspace in the same output budget; sequential targets reuse the largest required binding buffer. Rejected native admission preserves reusable CPU storage and frozen history. Backend failures propagate without replaying the View. Memory trimming releases both workspaces through the output plan.
Binding workspace is required only by pending native writes, not by completed sources or retained history. Software production can reclaim unused binding storage under budget pressure, while preserving storage needed by earlier admitted native writes in the same batch. Idle batches retain reusable capacity.
Renderer scopes
SDL-GPU and native WGPU target planning requires enough configured destination workspace for a complete target-sized fallback. SDL checks its existing ProjectiveFallback capacity, including row alignment; WGPU checks with_target_edit_budget and the device readback limit. Missing capacity returns None before drawing. Binding rechecks the workspace; WGPU prepares reusable edit bytes and staging before entering the callback. Incremental binding never replaces target storage to satisfy these checks. Output storage, history, source CPU copies, source staging and shared paint/binding workspace use the output budget; destination fallback buffers and upload caches retain their Factory limits. The output budget is not a total backend memory limit.
For SDL-GPU native outputs, configure the shared destination workspace when constructing the factory:
use mirui::render::{PlaneLayout, ProjectiveFallback};
use mirui::render::texture::ColorFormat;
use mirui::surface::sdl_gpu::SdlGpuFactory;
let layout = PlaneLayout::packed(640, 480, ColorFormat::RGBA8888).unwrap();
let factory = SdlGpuFactory::new().with_projective_fallback(
ProjectiveFallback::new(vec![0; layout.required_bytes()])
);
// Pass factory to App::with_factory(surface, factory).This example reserves one 1,228,800-byte workspace at setup for a packed 640×480 RGBA target. Use the largest intended physical paint footprint, including output scale and overflow; resized or larger targets can select software production when this fixed capacity is insufficient. Configure App::with_offscreen_pool_budget separately for simultaneously live output slots and source-read reservations. A larger output pool alone does not supply SDL destination workspace. Inspect sdl.target.workspace and output.target decisions to distinguish these two capacity checks.
Each Renderer declares type TargetState; renderers without native target support use (). Native backends implement plan_target, can_reuse_target, create_target, bind_target and restore_target. Planning returns None when native storage is unsupported. The binding state must not borrow the renderer or the supplied workspace.
can_reuse_target(target, plan) checks writable storage compatibility without binding, allocating, submitting or reading pixels. A different device, stale generation or incompatible attachments return Ok(false); destination failures and active-target conflicts return errors. Incomplete contents do not prevent storage reuse for rebuilding. Binding repeats the shared backend checks and separately requires completed contents for Incremental. An incremental operation never replaces mismatched storage or changes itself into a rebuild. Readable source textures use their existing source validation and conversion paths, independently of writable target compatibility.
The default with_target implementation flushes parent work, validates and binds the target, calls the drawing callback once, flushes successful child work and restores the parent. The callback receives the original renderer, including its composed engines. Callback and submission errors still restore the parent; the earliest error is returned. Unwinding attempts restoration, but abort does not run cleanup.
with_target(target, viewport, update, workspace, body) passes TargetUpdate to bind_target. Rebuild initializes the entire target to zero before drawing, independently of parent clipping, transforms or blending: alpha formats start transparent and opaque formats start black. Even an empty callback must complete this initialization. Intermediate flushes and returns from nested scopes preserve the current scope's contents. Incremental retains successfully completed contents and rejects newly allocated targets or targets with failed writes before invoking the callback. Background colors use ordinary drawing commands, not a separate initialization setting.
The backend checks content validity when binding and invalidates partially modified contents on failure. A failed write is not a rollback; the affected target must be rebuilt before incremental drawing or source reads. Preserving multisampled contents requires retaining the attachments actually loaded by subsequent drawing, not only their resolved image; include those attachments in the storage plan. Shared output textures and retained history are not writable target handles.
restore_target(state, completed) receives true only when the callback and child flush succeeded. Accept child contents only if restoration also succeeds; otherwise invalidate them. It does not signal publication or window presentation. On failure, pending child commands must be discarded or safely completed on their original target before restoring the parent. Failed binding must restore its partial state or invalidate the device; failed restoration must prevent later submission. Restoring a parent must not initialize it again.
Conformance
compose_backend! forwards target planning, reuse checks, creation, binding and restoration to its default field. It uses the default scope executor, preserving every original engine and concrete renderer type, including nested compositions and borrowed engines. No additional DSL, projection type or callback adapter is required from the backend author.
An independent target uses its own viewport and local coordinates. Region offsets and projective transforms on the parent renderer do not transform the new image during production; they apply when drawing into the parent again, including when compositing the finished image. Coordinate wrappers forward target scopes without reapplying parent transforms. Software render_scope keeps its existing parent-region coordinate mapping.
The external implementation in the composed-target contract tests exercises target planning, allocation, two nested concrete engines, independent target contents, failed production, foreign-device rejection and source reading after renderer destruction. Its NativeFactory uses the existing RendererFactory associated renderer lifetime to borrow both engines each frame; a target survives across those frames and remains readable after the surface and factory are dropped. The fixture models a native device in memory; it does not require GPU hardware.
The update contracts check invalidation after failed binding, submission, callbacks and nested unwinding; restoration failure also prevents later submissions. Nested incremental scopes preserve both targets across intermediate flushes without allocating after preparation. These checks exercise the shared executor and macro routing, not a GPU driver.
SDL frame tracing
With perf, output.target records native/CPU output selection, storage reuse and admission failures. sdl.target.workspace identifies missing or insufficient SDL destination-fallback workspace independently of the output pool. These are bounded decision events, not GPU durations; see timing diagnostics for identity, byte-count and attribution rules.
Offscreen production spans distinguish software and native rendering. SDL image-source upload, target readback and target writeback records expose logical pixel payload bytes and the native call result. They exclude driver conversion, glyph-atlas uploads and generated-gradient uploads; successful calls do not establish GPU completion. Row padding is excluded, including a short final row.
With performance tracing enabled, sdl.target.select and sdl.target.restore include SDL's implicit submission when changing targets; sdl.state.select and sdl.state.restore measure the remaining property updates. sdl.frame.compose includes copying the retained image to the window. At the completed-frame boundary, sdl.queue.submit submits queued commands before sdl.present presents the window. Submission errors use the existing frame failure path and do not acknowledge pending damage.
These spans measure time on the calling thread. Submission and presentation can both block inside the driver; neither span measures GPU execution alone. No GPU-idle synchronization is inserted for tracing.