scene

Backend-neutral ECS scene extraction and mixed drawing composition

Garnet scene

require "garnet-scene" extracts the existing ECS entities into backend-neutral Graphics::Drawing snapshots. No renderer, window or vector dependency is required. Use garnet-vector when vector primitives are wanted. Extraction runs on the World owner thread. Call the backend on its renderer owner thread.

require "garnet-scene"
require "garnet-vector"
alias C = Garnet::Graphics::Components
alias S = Garnet::Scene::Components

panel = Garnet::Entity.new
panel << S::Transform.new(x: 100_f32, y: 80_f32)
panel << C::Layer.new(opacity: 0.8_f32)
shape = Garnet::Entity.new
shape << C::Drawable.new(Garnet::Vector::Shape.new(
  Garnet::Vector::Path.circle(40, 40, 30), Garnet::Color::WHITE))
panel << shape

drawing = Garnet::Scene.new.extract(panel)
texture = renderer.render(drawing, Garnet::Graphics::RenderTarget.new(640, 480))

Making a 2D game

Add Garnet::Scene::Plugin to a World. It animates sprites, propagates transforms, runs camera systems and, in PrepareRender, extracts every world root through each active camera and submits the drawing to the RenderQueue resource at RenderQueue::WORLD. A renderer plugin presents the queue. The Screen resource (updated by the host plugin) supplies the logical size. With no camera, the world is drawn with an identity view, so world units are logical screen pixels.

require "garnet-scene"
alias S = Garnet::Scene::Components

world = Garnet::World.new
world.add_plugin(Garnet::Scene::Plugin.new)

frames = Garnet::Graphics::TextureRegion.new(sheet_texture).grid(32, 32)
run = Garnet::Scene::SpriteClip.new(frames[0, 6], fps: 12, events: {2 => "step", 5 => "step"})

hero = Garnet::Scene.animated_sprite(run, at: {64, 64}, anchor: {0.5, 1}, z: 1)
world.adopt(hero)
world.adopt(Garnet::Scene.tilemap(level_map))
world.adopt(Garnet::Scene.camera(zoom: 2, follow: hero, smoothing: 150.milliseconds,
  deadzone: {32, 16}, bounds: {0, 0, level_width, level_height}, shake: true))

world.schedule.add(:update, name: "hero.input") do |w, seconds|
  w.query(Garnet::Mut(S::Transform), Garnet::Mut(Garnet::Graphics::Components::Sprite), has: {Hero}) do |_, transform, sprite|
    transform.x += speed * seconds
    sprite.value = sprite.value.copy_with(flip_x: speed < 0)
  end
  w.events(Garnet::Scene::AnimationEvent) { |event| play_footstep if event.name == "step" }
end
world.run

The builders (Scene.sprite, Scene.animated_sprite, Scene.group, Scene.picture, Scene.tilemap, Scene.camera, Scene.camera_3d) return detached entities like the UI widget factories. Attach them with world.adopt(entity), world.adopt(entity, parent) or parent << entity. Positions are at: {x, y}; numbers of any type are accepted.

Plugin systems, all named for schedule.enable/disable:

System Phase Order
scene.sprite_animation PostUpdate ANIMATION_ORDER (-1100)
scene.transforms PostUpdate TRANSFORM_ORDER (-1000)
scene.camera_follow PostUpdate CAMERA_FOLLOW_ORDER (-900)
scene.camera_bounds PostUpdate CAMERA_BOUNDS_ORDER (-800)
scene.camera_shake PostUpdate CAMERA_SHAKE_ORDER (-700)
scene.extract PrepareRender EXTRACT_ORDER (0)

Gameplay that reads GlobalTransform should run in PostUpdate after TRANSFORM_ORDER. Mark roots drawn elsewhere (such as a UI tree) with Components::ScreenSpace so cameras skip them, and 3D roots with Components::Scene3DRoot (see 3D cameras on screen). Scene::TransformPlugin installs only transform propagation.

Coordinate conventions

2D is X-right, Y-down, with the origin at the top-left of the screen when no camera is used; positive angles rotate clockwise on screen. 3D is right-handed and Y-up; cameras look down their local -Z. When 2D components (Transform, Placement, ...) sit inside a 3D hierarchy they are flipped (flip * local_2d * flip with flip = scale(1, -1, 1)), so authored 2D content keeps reading top-down on its plane.

Transforms

An entity's 2D local frame is Placement * Pose * Socket * Affine * Transform and its 3D local frame is Pose3D * Transform3D (followed by the flipped 2D frame). The transform system maintains Components::GlobalTransform (every entity) and Components::GlobalTransform3D (entities with 3D components and their descendants). Each pass walks the hierarchy but only recomputes entities whose local components changed (by revision), were added or removed, or were reparented, plus their descendants; a pass with no world changes returns immediately. Call Scene::Transforms.propagate(world) when driving a world without the plugin.

scene.world_transform(entity), scene.world_position(entity), scene.world_transform_3d(entity) and scene.world_position_3d(entity) return the cached matrix when it is provably current (no local frame on the ancestor chain changed since its pass), and compose the hierarchy otherwise. GlobalTransform offers x, y, position (a tuple), translation (a Vec2) and angle; GlobalTransform3D#position returns a Vec3.

Transform also works with Garnet::Math::Vec2: Transform.new(position, angle, scale), #position, #scale, #with_position, #translated and #look_at(target), which turns the local +X axis toward target.

Transform, Placement, Z, Sprite, Camera3D.perspective/orthographic and Transform3D accept any Number. Transform.new(x: 1, y: 2, scale: 3) sets a uniform scale.

Cameras

Components::Camera2D.new(zoom:, rotation:, viewport:, clear_color:, active:, priority:, layer:, pixel_aligned:) makes an entity a camera centred on its world position. viewport is {x, y, width, height} in fractions of the screen; two cameras with half-screen viewports give split screen (each is clipped to its rectangle and its clear_color fills it). Cameras draw in ascending priority. A camera without a viewport sets the frame clear color.

  • CameraFollow.new(target, smoothing, deadzone_width, deadzone_height, offset_x, offset_y, lookahead) moves the camera's Transform toward the target's world position. smoothing is an exponential time constant (Time::Span, zero snaps; the first frame always snaps), the deadzone is a box the target can move in freely, and lookahead leads the target by its velocity times that span.
  • CameraBounds.new(min_x, min_y, max_x, max_y) keeps the visible area inside a world rectangle, centring when the rectangle is smaller than the view.
  • CameraShake.new(recovery: 1.second, max_offset_x:, max_offset_y:, max_angle:, frequency:, seed:) is trauma based: camera.mut(CameraShake).add_trauma(0.5). Trauma decays linearly over recovery; the displacement is trauma squared times the maxima, applied only when rendering.

scene.camera_view(camera, screen), scene.screen_to_world(camera, screen, x, y) and scene.world_to_screen(...) convert between spaces, for example for mouse picking.

Fitting and anchoring

Camera2D.new(fit: {x, y, width, height}) frames a world rectangle in the viewport each frame, deriving zoom and centre (the entity position and zoom are then ignored; shake still applies). fit_mode: :contain (default) shows all of it, :cover fills the viewport and crops. align: {ax, ay} places the rectangle in spare space or picks the visible part ({0.5, 0.5} centres, {0.5, 0} keeps its top edge at the viewport's top). With pixel_aligned, a fitted zoom of at least 1 is floored to an integer.

inset: {left, top, right, bottom} (logical units) shrinks the viewport, for example to keep the field below a HUD bar:

world.spawn(Camera2D.new(inset: {0, 102, 0, 0}, fit: {-18, 0, 676, 418}, align: {0.5, 0}))

Components::ViewportAnchor.new(node) replaces the fractional viewport with a node's rectangle on screen (insets still apply). The rectangle comes from the node's Components::ScreenRect or from a reader registered with Scene.register_screen_rect(Type) { |component| {x, y, w, h} or nil }. UI::Plugin registers UI::Bounds, so a UI node's laid-out rectangle works directly. The camera draws nothing until the rectangle is known. scene.screen_rect(node) returns it.

stage << UI::Bounds.new # with UI::Plugin installed
camera << Garnet::Scene::Components::ViewportAnchor.new(stage)

3D cameras on screen

Mark each 3D world root with Components::Scene3DRoot.new(layers = 1): 2D cameras skip it (as they skip ScreenSpace roots and Camera3D roots). Add Components::ScreenCamera3D to a Camera3D entity and Scene::Plugin renders it to the screen alongside the 2D cameras:

level = world.spawn(S::Scene3DRoot.new, S::Environment3D.new(environment))
camera = world.spawn(S::Camera3D.perspective(0.8), S::Transform3D.look_at(eye, target),
  S::ScreenCamera3D.new(clear_color: sky), parent: level)

ScreenCamera3D.new(root:, layers:, viewport:, inset:, clear_color:, active:, priority:, layer:, target:) renders root when given, otherwise every visible Scene3DRoot whose layers intersect its layers (each as its own depth-tested pass, in root order). Viewport, inset, ViewportAnchor, priority, activity and RenderQueue layer work as for Camera2D; at equal priority 3D cameras draw before 2D cameras (including the implicit identity camera used when there is no Camera2D), so 2D sprites overlay the 3D view. The scene renders at the viewport's framebuffer pixel size unless target fixes a resolution. clear_color fills the viewport behind the first pass (and sets the frame clear color for a full-screen camera). Shadow cameras and other Camera3Ds without ScreenCamera3D are not drawn.

scene.world_to_screen_3d(camera, point) projects a world point to logical screen coordinates through the camera's on-screen viewport (nil behind the camera), for speech bubbles, health bars or hit sparks. scene.screen_to_ray(camera, x, y) returns a Graphics::ViewportRay for picking, and scene.view_projection_3d(camera) the matrix both use. They read the camera's World Screen resource unless a Screen is passed.

To show a 3D view inside UI geometry instead (where UI panels must draw behind and in front of it), keep using a View3D node in the UI tree.

Sprites, sheets and animation

Graphics::Components::Sprite.new(region, width, height, anchor_x, anchor_y, tint, flip_x: false, flip_y: false) mirrors the image inside its rectangle with flip_x/flip_y. sprite.with_region(region) swaps the image and keeps the rest.

Graphics::TextureRegion#grid(frame_width, frame_height, columns:, rows:, margin:, spacing:, count:) slices a sheet (or an atlas region) into frames in row-major order. SpriteAtlas#frames("run_") returns the named regions with a prefix in natural order.

Scene::SpriteClip.new(frames, fps: 12) or SpriteClip.new(frames, durations: [...]) describes a clip with mode: :loop | :once | :ping_pong and optional events: {frame => "name"} markers. Components::SpriteAnimation.new(clip, speed: 1) plays it on the entity's sprite; control it with entity.mut(SpriteAnimation).play(other_clip), .pause, .resume and .restart. The system emits Scene::AnimationEvent(entity, clip, name, frame) when playback enters a marked frame and Scene::AnimationFinished(entity, clip) when a once clip ends; read them with world.events.

Tile maps

Components::TileMap.new(map, sampler) draws a Graphics::TileMap with tile (0, 0) at the entity origin. When the extraction knows its visible output rectangle (camera extraction, or scene.extract(root, camera)), only visible columns and rows are drawn, and the drawing for a visible range is cached until the range changes.

Custom drawables

Extraction runs through a registry of drawable extractors. The built-in components (Picture, View3D, Drawable, MeshDrawable, Sprite, Surface, Pattern, TileMap, orders 0–700) use the same mechanism, so games and other shards can add their own:

Garnet::Scene.register_drawable(Healthbar, order: 800) do |entity, bar, transform, output|
  output << Garnet::Graphics::PrimitiveOp.new(bar.primitive, transform)
end

The block receives the entity, its component, its output transform (view included) and a Scene::DrawContext. Append operations with <<; use output.visible_bounds to cull, and output.capture(viewport_entity) or output.extract_3d(...) for nested content with dependency-cycle checks. scene.register_drawable registers for one Scene only, and closing the returned DrawableExtractor unregisters it. Scene.register_drawable_3d does the same for 3D extraction (MeshDrawable3D, Drawables3D, Plane2D and Sprite are built in); its DrawContext3D#<< culls Draw3Ds against the view.

Extraction cost

Extraction writes operations straight into the parent's list (a nested drawing is only allocated for effects, layers, masks, clips, blends and viewports), skips lookups for component types no entity in the world has, reuses each sprite's primitive, sorts children only when one has a Z, and skips per-node validation for World entities (the World already guarantees a tree). With the plugin, extraction reads GlobalTransform instead of recomposing frames.

Components and composition

Scene::Components::Transform supplies translation, rotation in radians and scale. Drawable extent/anchor belongs to Graphics::Components::Sprite, never inherited placement. MeshDrawable consumes existing meshes/materials; Drawable consumes any immutable Graphics::Primitive. Children inherit all ancestor transforms. Descending Scene::Components::Z and insertion-order ties preserve existing drawing order.

Graphics::Components::Picture.new(drawing) instances an existing immutable Graphics::Drawing under the entity's normal transform and composition. This works for code-recorded drawings and loaded SVG documents alike. Extraction emits a neutral PictureOp; the picture retains its internal groups, masks, patterns and ordering without requiring a separate scene hierarchy.

Scene::Components::Placement.new(x, y) supplies a generated positioning offset before the authored Transform: T(placement) * affine_frame * visual_transform. Scene::Components::Affine.new(matrix) supplies an optional finite 2D affine frame for generated positioning such as skeletal sockets, retaining shear and reflections. Its default is identity. Layout can therefore update placement without overwriting game-authored animation. Scene::Components::Visibility.new(false) suppresses an entity's entire rendered subtree. These components have no UI dependency.

Clip(primitive) restricts the entity and all descendants to geometric coverage, ignoring the primitive's color, texture and alpha. Clips can nest with masks and layers. Layer(opacity:) applies opacity after composing the entity and its descendants. Mask(source, mode: :alpha | :luminance, inverted: false) identifies a live direct child as an input subtree. The child uses the parent's coordinate system and is excluded from ordinary color drawing. The source may contain meshes, images, vectors, and nested groups. Missing/dead/detached sources raise explicitly; no automatic reparenting occurs. Hierarchy cycles, duplicate parents within an extracted hierarchy, and composition dependency cycles raise.

Viewport(width, height) rasterizes a subtree in local coordinates and displays the result as an extent-sized quad when encountered in normal traversal. Its entity placement applies once to that quad. scene.render_to_texture(renderer, viewport_entity) explicitly captures just its local contents into a retained texture version. Surface(source_viewport, mesh) samples a viewport's current extracted contents on an arbitrary mesh. Keep a source viewport outside the displayed root if it should only be an input. Each extraction observes current entity components; previously extracted drawings and rendered textures remain unchanged. Viewports currently rerender per use and do not implement incremental caching.

For a screenshot from any 2D entity, call scene.capture(renderer, entity, target). The target sets the pixel dimensions. Omit it when the entity has a Viewport. Both capture and render_to_texture ignore the 2D root's placement and use its local origin. For a 3D subtree use scene.capture(renderer, entity, camera, target) or the corresponding render_to_texture overload. The 3D camera and subtree use their world transforms.

capture waits for GPU readback and returns a top-down RGBA8 image. image.bytes returns the byte slice. For GPU-only composition, reference the source viewport from a Surface in another scene or keep the texture returned by render_to_texture. Without ECS, render a Graphics::Drawing or Graphics::Frame3D directly and call renderer.readback(texture) as needed.

Pattern(source_viewport, primitive, mapping = nil) paints a primitive with the source viewport's current contents. It adds its own drawable operation, as Surface does. Consumer placement, clips, masks and group opacity apply normally. The source uses its local viewport coordinates, independently of the source entity's placement in another scene. Missing/dead sources and dependency cycles through patterns, surfaces or nested viewports raise explicitly.

tile = Garnet::Entity.new
tile << C::Viewport.new(16, 16)
tile << C::Drawable.new(Garnet::Vector::Shape.new(
  Garnet::Vector::Path.circle(8, 8, 5), Garnet::Color::WHITE))
panel << C::Pattern.new(tile, Garnet::Vector::Shape.new(
  Garnet::Vector::Path.rect(0, 0, 200, 80), Garnet::Color::WHITE),
  Garnet::Graphics::PatternMapping.new(32, 32))

Modify the tile's ordinary components or children and extract again to update the pattern. Each extraction seals its source contents into a neutral PatternOp; earlier drawings and GPU outputs retain their versions. Mapping controls tile size/addressing/filtering independently of viewport resolution. Omitted mapping uses viewport dimensions. Sources can mix vector and raster content and nested patterns. The source stays an ordinary entity subtree: a source also attached under the displayed root is drawn there normally. Tiles currently rerender per use; resolution is explicit and no incremental tile cache is implemented.

Ordinary containers do not create offscreen passes. Masked/translucent groups and explicit viewports do. Initial layers use full-target intermediate textures; tight bounds, pooling, generic filters, arbitrary blend modes, and input routing through viewports remain later work. extract(root, transform, bounds: {x, y, w, h}) accepts an explicit view transform and an optional visible output rectangle, and extract_all(roots, transform) extracts several roots into one drawing. The existing card system supplies a centered view; standalone drawings use top-left pixel coordinates.

This replaces garnet-renderer-gl-scene and its GL-namespaced components. The card example now uses Sprite for size/anchor and Transform for placement. ECS storage, update scheduling, and custom components remain the existing system; this change does not introduce a second scene hierarchy.

Graphics::Components::Effects.new(chain) applies an immutable graphics EffectChain to the combined subtree. Graphics::Components::Blend.new(:multiply) blends that subtree with preceding siblings. Extraction applies effects first, then layer opacity/mask and clip, then blending. The ordinary scene nesting controls isolation; the same behavior is available without ECS through graphics recorder operations. Blur widths are output pixels, independent of entity scale.

For World entities, scene.world_transform(entity) accumulates the live hierarchy. scene.reparent_keep_world(entity, parent) preserves the accumulated affine transform and the entity's authored placement and visual transform. A singular destination is rejected before changing the hierarchy. Scene::Camera provides an explicit orthographic view with viewport origin, rotation and zoom. Set pixel_aligned: true with an integer zoom and zero rotation to snap translation to output pixels.

2D and 3D in one World

Scene#extract produces a 2D drawing, optionally through Scene::Camera for pixel-space pan, zoom and rotation (Components::Camera2D entities do the same through Scene::Plugin). Scene#extract_3d(root, camera, target) produces a depth-tested frame from the same World. Put Components::Camera3D.orthographic(height) or Components::Camera3D.perspective(fov_y) on the camera entity and place it with Transform3D. The orthographic view preserves apparent size. Both projections can show meshes and planes.

alias S = Garnet::Scene::Components
alias G = Garnet::Graphics
alias M = Garnet::Math

world = Garnet::World.new
root = world.create
camera = world.create(root)
camera << S::Camera3D.orthographic(10)
camera << S::Transform3D.new(0, 0, 8)

actor = world.create(root)
actor << G::Components::Sprite.new(sprite_region, width: 1_f32, height: 2_f32)
actor << S::Billboard3D.new(upright: true)

model = world.create(root)
model << S::Drawables3D.new(model_pose.draws)

scene = Garnet::Scene.new
frame = scene.extract_3d(root, camera, G::RenderTarget.new(800, 600))
texture = renderer.render(frame)

Transform3D stores position, rotation (a Quaternion) and scale, with readable getters (x, y, z, forward, right, up) and a derived matrix. Construct it with Transform3D.new(x, y, z, rotation:, scale:), Transform3D.new(position:, rotation:, scale:) or from a matrix (the exact matrix, including shear, is kept until a field is replaced). Change it with entity.mut(Transform3D).position = ... or copy_with. Transform3D.look_at(eye, target, up) and transform.look_at(target) aim -Z at a point; Scene.camera_3d(Camera3D.perspective(1.0), eye:, target:) builds a camera entity.

A 3D node inherits the parent frame, then applies Transform3D and its ordinary 2D placement, affine and transform. The latter retain X-right, Y-down authored coordinates on the plane, which maps into the Y-up world. A sprite keeps its existing size, anchor, tint and atlas UV mapping. Rotate its entity to place the plane or attach Billboard3D to face the selected camera. reparent_keep_world_3d preserves the composed frame when both the new parent and the 2D placement are invertible.

Use Plane2D.new(target, world_width, world_height) on a node to capture its 2D drawing and descendants, including UI, vector effects and clipped groups. The target describes pixel resolution and the two floats describe world extent. Its 3D descendants continue through the normal 3D traversal. Nested 2D content inside the capture shares its canvas. Set a cutout Material3D for a captured sprite that should write depth.

Put View3D.new(source, camera, target) on a 2D node to display a world view inside HUD or UI geometry. Both embedding directions resolve the current snapshot on the GPU. Extraction rejects dependency cycles. Add Light3D components for world lights, Environment3D for ambient and fog, and ShadowView3D on the 3D root with a second orthographic camera for directional shadows. PointShadow3D supplies an alternative shadow view from a point-light entity. Attach Components::Shadows3D with up to four ShadowCaster3D bindings for independent lights. The indices refer to the frame's light order, with environment lights followed by scene lights. Highlight3D marks geometry for the root's optional Outline3D.

Repository

scene

Owner
Statistic
  • 0
  • 0
  • 0
  • 5
  • 2
  • about 8 hours ago
  • November 30, 2026
License

MIT License

Links
Synced at

Wed, 02 Dec 2026 03:59:47 GMT

Languages