JFLib

render2d/scene.rs#

Source: lib/render2d/scene.rs

scene -- a scene's entities, layers, styles and camera, and what goes up of them (lib.rs has the overview,
docs/RENDER2D.md the reasons)

On the CPU: one Ent per entity with its f64 geometry, one LayerSlot per layer.  On the GPU: one record of 64 bytes
per segment (common.wgsl Record) in one pool.  Every layer owns a region of the pool, whole pages of 256 records:
its entities' records lie there in the order of insertion, each entity's together, so the pages of the visible
layers in their draw order are the painter's order the visibility keeps (cull.wgsl).  An insert appends at its
layer's end; an update in place when its records fit what the entity holds (alloc), else the layer is laid out
anew with room for it (repack); a remove leaves free records (zeros), and a layer whose free records outgrow its
live ones is laid out anew without them.  A region that is too small, a repack, a new or removed layer: a new
pool, the GPU copies what stays across (no copy within one buffer: WebGPU forbids it), only changed entities'
records come from the CPU.

What a frame sends (prepare, then Renderer::record copies it inside the frame's commands, behind the barrier
against the frame before): the view; the styles when they changed; the visible layers' entries and table when they
changed; the changed records, in runs (few runs: a copy each) or through the scatter shader (many); the changed
instances.  A prepare that never reached a submission: the next sends everything again.

Blocks (G6b2, docs/RENDER2D.md "Blöcke"): a block's entities are Ents of no layer, in its list; its records lie once
in the pool, in variants (one per zoom band its instances need where it holds curves or fills, one with its arcs as
curves for uneven scales) whose regions follow the layers'.  An insert on a layer holds one record of zeros there (its
place in the order).  The instances (each copy of an insert on a layer, each copy of a nested insert per instance of
its block, depth first) are laid out anew when inserts or blocks change, else only moved inserts' transforms go up;
the visibility's entries name a page, an instance, a range of the page (several small instances in one entry).
  • struct Camera what a scene shows: the point of the drawing at the target's middle, drawing units per pixel, and the rotation (radians, counter-clockwise: the drawing turns that way on the screen). The y axis points up on the screen
    • center: [f64; 2]
    • scale: f64
    • rotation: f64

impl Camera

  • const fn new(center: [f64; 2], scale: f64) -> Camera

  • fn to_screen(&self, p: [f64; 2], size: (u32, u32)) -> [f64; 2] a point of the drawing in pixels of a target of size (x right, y down from its top left corner; a pixel's centre at + 0.5)

  • fn to_drawing(&self, q: [f64; 2], size: (u32, u32)) -> [f64; 2] the point of the drawing under a pixel position of a target of size

  • fn pan(&mut self, dx: f64, dy: f64) the drawing follows a pointer that moved by (dx, dy) pixels (a drag)

  • fn zoom_at(&mut self, q: [f64; 2], factor: f64, size: (u32, u32)) zoom in by factor (below 1: out) about the pixel position q of a target of size: the point under q stays

  • enum Unit how a style's width is measured

    • Px -- pixels of the target, whatever the zoom
    • Drawing -- units of the drawing: the stroke grows and shrinks with the zoom
  • enum Cap how an open end ends

    • Butt -- at the end point
    • Round -- a half circle around it
    • Square -- half the width beyond it
  • enum Join how two segments of a polyline meet on the outer side of the turn

    • Miter -- the outer edges meet, up to the miter limit; beyond it a bevel
    • Round -- a circle around the vertex
    • Bevel -- a straight cut between the outer corners
/// the most entries of a dash pattern (Style::dash)
DASH_MAX: usize = 8
/// the most line families of a hatch (Style::hatch)
HATCH_MAX: usize = 4
/// the most entries of a hatch family's dash pattern (HatchLine::dash)
HATCH_DASH_MAX: usize = 6
  • struct HatchLine a family of a hatch's parallel lines, as DXF has them: their angle (radians, counter-clockwise from the x axis), the base point one of them runs through, the spacing between neighbouring lines (at right angles to them) and how far each line's pattern is shifted along against the one before; a dash pattern (on, off, ... in drawing units; none: solid lines; an entry of 0 is a dot). Made with new and changed field by field (it may grow)
    • angle: f64
    • base: [f64; 2]
    • spacing: f64
    • shift: f64
    • dash: [f64; HATCH_DASH_MAX]
    • dashes: u32

impl HatchLine

  • const fn new(angle: f64, spacing: f64) -> HatchLine solid lines at an angle, spacing apart, through the origin

  • fn dashed(mut self, pattern: &[f64]) -> HatchLine the same with a dash pattern (at most HATCH_DASH_MAX entries, drawing units)

  • struct Style a stroke's look. Made with new and changed field by field (it may grow)

    • color: u32 -- 0xAARRGGBB: sRGB codes as the target shows them, straight alpha
    • width: f32 -- in units; 0 (or anything thinner than a pixel): a hairline, 1 px wide
    • unit: Unit
    • cap: Cap
    • join: Join
    • miter_limit: f32 -- the longest miter over the width (lib/gfx's and SVG's ratio); at least 1
    • dash: [f32; DASH_MAX] -- a dash pattern: lengths on and off in turn, starting with on, the first dashes entries (0: solid). An odd count runs twice (on, off, on, then off, on, off), as in SVG; every dash ends in cap, joins only where a dash runs through a vertex. The pattern runs along each entity from its start (a closed polyline's first point, an arc's start, a circle's angle 0), across the joins of a polyline
    • dashes: u32
    • dash_unit: Unit -- the unit of the pattern's lengths and of its phase
    • dash_phase: f32 -- how far into the pattern an entity starts (in dash_units)
    • hatch: [HatchLine; HATCH_MAX] -- a fill's hatch: the first hatches line families (0: the fill is solid), drawn in color over nothing, the lines hatch_width px wide (0, or thinner than a pixel: 1 px); strokes ignore it
    • hatches: u32
    • hatch_width: f32
    • transparency: Transparency -- AutoCAD's transparency of what the style draws: its layer's (the default), its block insert's, or its own; the colour's alpha times 1 - percent / 100 (G6b2)
    • by_block: u32 -- inside a block, what an entity of this style takes from its insert's style instead of its own (BY_BLOCK_COLOR, BY_BLOCK_WIDTH, BY_BLOCK_DASH; DXF's ByBlock); outside a block the style's own (G6b2)
  • enum Transparency AutoCAD's transparency of an entity (Style::transparency): 0 to TRANSPARENCY_MAX percent, multiplied into the colour's alpha (alpha (100 - percent) / 100, rounded); not group compositing: overlapping entities blend each (docs/RENDER2D.md "Transparenz")

    • ByLayer -- its layer's (Layer::transparency)
    • ByBlock -- inside a block its insert's style's (that one's ByLayer: the insert's layer); outside a block none
    • Percent(u32) -- its own, in percent
/// the most transparency AutoCAD has (percent)
TRANSPARENCY_MAX: u32 = 90
/// Style::by_block: inside a block the colour, the width (and its unit), the dash pattern (entries, unit, phase) come from
/// the insert's style
BY_BLOCK_COLOR: u32 = 1
BY_BLOCK_WIDTH: u32 = 2
BY_BLOCK_DASH: u32 = 4

impl Style

  • const fn new(color: u32) -> Style a hairline of a colour: width 0, butt caps, miter joins with the limit 4, solid

  • fn hatched(mut self, families: &[HatchLine], width: f32) -> Style the same with a hatch (at most HATCH_MAX families; none: a solid fill) of lines width px wide

  • fn dashed(mut self, pattern: &[f32], unit: Unit, phase: f32) -> Style the same with a dash pattern (at most DASH_MAX entries; an empty one: solid), its unit and phase

  • struct StyleId(pub u32) a style of a Scene

  • struct Layer a layer's settings. Made with new and changed field by field (it may grow)

    • visible: bool
    • order: i32 -- layers are drawn by this, lowest first; equal ones in the order they were added
    • transparency: u32 -- AutoCAD's transparency of the entities whose style says Transparency::ByLayer (percent, 0 to TRANSPARENCY_MAX; G6b2): changing it sends no records

impl Layer

  • const fn new(order: i32) -> Layer

  • struct BlockId a block of a Scene: entities defined once (Scene::insert_in, in the block's units) and inserted many times (Shape::Insert); dead after remove_block

    • slot: u32
  • struct Block a block's settings. Made with new and changed field by field (it may grow)

    • base: [f64; 2] -- the point of the block that lands on an insert's at (DXF's base point)

impl Block

  • const fn new() -> Block
/// the most levels of blocks inside blocks below an insert on a layer (nested inserts; a cycle is refused anyway)
BLOCK_DEPTH: u32 = 16
  • struct Insert a block placed by an entity (Shape::Insert): its base point to at, scaled (each axis; a negative scale mirrors, unequal magnitudes scale unevenly: circles become ellipses), turned by rotation (radians, counter-clockwise); an array of columns by rows copies spacing apart along the insert's turned x and y (drawing units, not scaled: DXF's MINSERT). Made with new and changed field by field (it may grow)
    • block: BlockId
    • at: [f64; 2]
    • rotation: f64
    • scale: [f64; 2]
    • columns: u32
    • rows: u32
    • spacing: [f64; 2]

impl Insert

  • const fn new(block: BlockId, at: [f64; 2]) -> Insert the block at a point, unscaled, unturned, one copy

  • struct InstanceInfo what the blocks of a scene hold and what the last prepare sent of them (Scene::instance_info). It may grow

    • blocks: u32 -- live blocks; their variants in the pool (a block with curves or fills one per zoom band its inserts need, one with arcs another for inserts that scale unevenly) and those variants' records
    • variants: u32
    • block_records: u32
    • instances: u32 -- instances (an insert's copies, nested inserts each once per instance of their block) and the entries of the visibility
    • entries: u32
    • rebuilt: bool -- the instances laid out anew (an insert added or removed, a block changed, a variant came or went)
    • sent_instances: u32 -- instances whose transforms went up, their bytes; block records that went up (in UploadInfo's records too)
    • sent_bytes: u64
    • sent_block_records: u32
  • struct LayerId a layer of a Scene; dead after remove_layer

    • slot: u32
  • struct EntityId an entity of a Scene; dead after remove, also when its place has gone to another one

    • slot: u32
  • enum Shape<'a> what an entity is (more kinds come: text)

    • Line { a: [f64; 2], b: [f64; 2] }
    • Polyline { points: &'a [[f64; 2]], closed: bool } -- at least one point; closed: a segment from the last back to the first, joined at every point
    • Arc { center: [f64; 2], radius: f64, start: f64, sweep: f64 } -- a circular arc: its centre, radius (above 0), the angle it starts at and how far it turns (radians; positive: counter-clockwise, the drawing's y pointing up; not 0). A sweep of a full turn or more is a circle whose dash pattern starts at start. Drawn in pieces of at most ARC_STEP, coverage from the circle itself
    • Circle { center: [f64; 2], radius: f64 } -- a circle (its dash pattern starts at angle 0 and runs counter-clockwise)
    • Quadratic { points: &'a [[f64; 2]], closed: bool } -- quadratic Bézier pieces end to end: the start, then per piece its control point and its end (1 + 2k points, k at least 1); closed: the end joins the start (a straight segment where they differ). Curves are flattened into segments per zoom band within curve::FLAT_TOL px (docs/RENDER2D.md "Kurven"); the joins between pieces are the style's, the dash pattern runs along the curve's length
    • Cubic { points: &'a [[f64; 2]], closed: bool } -- cubic Bézier pieces: per piece its two control points and its end (1 + 3k points)
    • Ellipse { center: [f64; 2], radii: [f64; 2], rotation: f64, start: f64, sweep: f64 } -- an elliptic arc: the point at the parameter t is center + R(rotation) (radii[0] cos t, radii[1] sin t), from t = start over sweep (radians, not 0; a full turn or more: the closed ellipse, starting at start); radii above 0
    • Spline { degree: u32, points: &'a [[f64; 2]], weights: &'a [f64], knots: &'a [f64], closed: bool } -- a B-spline of degree 1 to 3 (at least degree + 1 points), rational where weights has one positive weight per point (empty: all 1), on knots (empty: clamped and uniform, through the first and last point; else points + degree + 1 non-decreasing values, the curve from knots[degree] to knots[points]); closed with empty knots: periodic (smooth all round), else the end joins the start. As DXF's SPLINE
    • Fill { rings: &'a [&'a [Shape<'a>]] } -- a filled area: its rings, each the shapes of the list end to end (a shape that does not start where the one before ended: a straight segment between them; the last back to the first), even-odd between rings (a ring inside a hole is an island). Triangulated on the CPU, its edge smoothed as strokes are; the style's colour, or its hatch (docs/RENDER2D.md "Flächen")
    • Insert(Insert) -- a block (G6b2): on a layer in its place in the order, or inside another block; its entities in their order, each with its style or by block the insert's (docs/RENDER2D.md "Blöcke")
    • Text(Text<'a>) -- a single line of text (G6c; DXF's TEXT): its glyphs from the scene's atlas of distance fields, small as bars, very large as fills of their outlines; the style's colour (docs/RENDER2D.md "Text")
    • MText(MText<'a>) -- text of several lines (G6c; the basics of DXF's MTEXT)
/// the largest angle of one piece of an arc (a record): a full circle is 16 of them.  Its quad covers the piece's ring
/// between the chord inside and the tangent outside, so that the pixels the fragment shader looks at follow the stroke
/// (docs/RENDER2D.md "Bögen und Kreise")
ARC_STEP: f64 = core::f64::consts::PI / 8.0
  • struct UploadInfo what prepare sent for this frame

    • records: u32 -- records that came from the CPU (changed entities, free places), and in how many runs
    • runs: u32
    • scatter: bool -- they went through the scatter shader (many runs), else a copy per run
    • rebuild: bool -- a new pool (a layout changed), and the records the GPU copied across into it
    • moved: u64
    • tables: bool -- the visible layers' pages and table went up
    • bytes: u64 -- everything prepare wrote for the GPU, the view included
  • struct FrameStats what a finished frame measured (Scene::set_stats)

    • frame: u64 -- counts the scene's frames from 0
    • visible: u64 -- records the visibility found in the target
    • stamps: Option<[f64; 4]> -- the GPU's clock (ms) at the start, after the uploads, after the visibility, after the draw (None: no timestamps here)
/// (G6c) text from this many pixels per em on is drawn as fills of its outlines (the edge error of the atlas's class L grows
/// with the size: docs/RENDER2D.md "Entscheidungen in G6c"); textc.wgsl's T_BAR and text.wgsl's T_SL below it
TEXT_FILL_FROM: f64 = 160.0
/// (G6c) text.wgsl's T_SL: from this many pixels per em (the map's larger stretch) the glyphs come from class L
TEXT_LARGE_FROM: f64 = 40.0
/// (G6c) textc.wgsl's T_BAR: below this many pixels per em a text is drawn as bars
TEXT_BAR_BELOW: f64 = 7.0
  • struct Scene entities, layers, styles and the camera of one scene: on a Renderer's device, or without one (Scene::new_cpu; draw_cpu draws it through lib/gfx)

  • struct TextInfo what a scene's text holds (Scene::text_info). It may grow

    • fonts: u32
    • glyphs: u32 -- the glyph table's rows, their tiles of class S and L, the atlas's pages (PAGE x PAGE texels, 4 bytes each) and the texture's layers
    • tiles_s: u32
    • tiles_l: u32
    • pages: u32
    • layers: u32
    • made: u32 -- tiles made so far; glyphs that found no page (the device's most layers)
    • failed: u32
    • fills: u32 -- texts drawn as fills now; texts that changed between glyphs and fills in the last prepare
    • switched: u32
    • sent_bytes: u64 -- what the last prepare sent of the atlas (bytes) and of the glyph table (rows)
    • sent_rows: u32
    • decided_scale: f64 -- the scale text decides its mode and class by (Camera::scale's units)

impl Scene

  • fn new(r: &Renderer) -> Result<Scene> a scene on a renderer's device (Scene::new_cpu, then attach)
  • fn new_cpu() -> Scene a scene without a device (G6e1): everything but a frame on the GPU works on it (entities, layers, styles, blocks, text, picking, selection, snaps, highlights, the overlay), and draw_cpu draws it through lib/gfx. attach puts it on a renderer's device (all of it goes up with the next prepare), detach takes it off again (a lost device: the drawing stays)
  • fn attach(&mut self, r: &Renderer) -> Result<()> the scene on a renderer's device (G6e1): its buffers made there, everything it holds goes up with the next prepare. Attached to another renderer before, it leaves that one first; to the same one, nothing happens. An error leaves it without a device
  • fn detach(&mut self) the scene off its device (G6e1; a lost device, another renderer next): what it made there goes, what it holds stays; draw_cpu draws it, attach puts it on a device again
  • fn attached(&self) -> bool the scene is on a renderer's device (Scene::new, attach); else only draw_cpu draws it
  • fn add_style(&mut self, s: &Style) -> Result<StyleId> a style for entities; the next frame shows it
  • fn set_style(&mut self, id: StyleId, s: &Style) -> Result<()> a style changed: every entity of it shows the change with the next frame (nothing else goes up)
  • fn style(&self, id: StyleId) -> Option<Style>
  • fn add_layer(&mut self, l: &Layer) -> Result<LayerId> a new layer, empty, on top of those of its order
  • fn set_layer(&mut self, id: LayerId, l: &Layer) -> Result<()> shown or hidden, its place in the draw order, its transparency (nothing of its entities goes up: the layer table)
  • fn layer(&self, id: LayerId) -> Result<Layer>
  • fn remove_layer(&mut self, id: LayerId) -> Result<()> the layer goes, with every entity on it
  • fn drawn_layers(&self) -> Vec<LayerId> the visible layers in the order the last prepare drew them (the lists' order: lists_buffer)
  • fn add_font(&mut self, data: &[u8], face: u32) -> Result<text::FontId> a font from TrueType or OpenType bytes (face: a collection's font, else 0), lib/text's parser
  • fn fonts(&mut self) -> &mut Fonts the scene's fonts: their metrics and glyph outlines, and what lays text out with them (text::layout_text, layout_mtext: the CPU path of G6e draws the same layout)
  • fn add_text_style(&mut self, s: &TextStyle) -> Result<TextStyleId> a text style (DXF's STYLE) for texts
  • fn set_text_style(&mut self, id: TextStyleId, s: &TextStyle) -> Result<()> a text style changes: every text of it is laid out again (its records go up, a block's once for all its inserts)
  • fn text_style(&self, id: TextStyleId) -> Option<TextStyle>
  • fn text_layout(&self, id: EntityId) -> Option<&text::Layout> a text's layout (G6d picks with its extent: TextLayout::quad, bounds; G6e draws it): None for any other entity
  • fn text_info(&self) -> TextInfo what the scene's text holds (TextInfo)
  • fn atlas_hash(&self) -> u64 (tests) FNV-1a of the atlas's pages: the same bytes on every target for the same texts
  • fn insert(&mut self, layer: LayerId, style: StyleId, s: &Shape) -> Result<EntityId> a new entity at the end of its layer (drawn over everything there); an insert of a block (Shape::Insert) sits there with its block's entities
  • fn update(&mut self, id: EntityId, s: &Shape) -> Result<()> new geometry; the entity keeps its place in the draw order (in its layer or its block). An insert on a layer that stays an insert of the same block with as many copies only moves: its instances' transforms go up, nothing else
  • fn set_entity_style(&mut self, id: EntityId, style: StyleId) -> Result<()> another style: its records go up again (a block's entity: its block's, once for all its inserts; an insert: what its block's entities take by block)
  • fn remove(&mut self, id: EntityId) -> Result<()> the entity goes; its records become free places (and its id dead); a block's entity leaves its block (its records go up once for all its inserts)
  • fn len(&self) -> u32 entities alive (a block's entities and inserts each once)
  • fn is_empty(&self) -> bool
  • fn locate(&self, id: EntityId) -> Option<(u32, u32)> (tests, tools) an entity's records as the last prepare laid them out: its first record's place in the pool and the records of its geometry (a polyline of n points: n - 1, closed n; a point: 1; an insert on a layer: its one record of zeros); None for a block's entity (its records lie in its block's variants)
  • fn add_block(&mut self, b: &Block) -> Result<BlockId> a new block, empty: entities go into it with insert_in, Shape::Insert places it
  • fn block(&self, id: BlockId) -> Result<Block>
  • fn set_block(&mut self, id: BlockId, b: &Block) -> Result<()> a block's base point changed: every insert shows it (its records go up once)
  • fn remove_block(&mut self, id: BlockId) -> Result<()> the block goes with its entities; refused while an insert places it
  • fn insert_in(&mut self, block: BlockId, style: StyleId, s: &Shape) -> Result<EntityId> a new entity at the end of a block (its units: the block's base lands on an insert's point); a Shape::Insert of another block nests it (no cycles, at most BLOCK_DEPTH levels). Every insert of the block shows it with the next frame, the block's records going up once
  • fn instance_info(&self) -> InstanceInfo what the blocks hold and what the last prepare sent of them
  • fn set_camera(&mut self, c: &Camera) -> Result<()>
  • fn camera(&self) -> &Camera
  • fn set_culling(&mut self, on: bool) false: every live record of a visible layer is drawn (a test's comparison, a debugging aid)
  • fn set_stats(&mut self, on: bool) FrameStats of each frame: the records found visible (a small copy per frame), the GPU's times
  • fn upload_info(&self) -> UploadInfo what the last prepare sent
  • fn lists_buffer(&self) -> &Buffer (tests, tools) after a frame's visibility: per visible layer in draw order (drawn_layers) its first place in the visible list and its count (16 bytes each); the visible list (record places in the pool); the indirect draws. These and pool_buffer panic on a scene without a device (Scene::attached)
  • fn visible_buffer(&self) -> &Buffer
  • fn draws_buffer(&self) -> &Buffer
  • fn pool_buffer(&self) -> &Buffer (tests, tools) the pool of records (common.wgsl Record, 64 bytes each)
  • fn wait_slot(&mut self) -> Result<()> wait for the frame that last used this frame's slot, so its data can be written; prepare does it too. The browser cannot wait, and needs not: its writes go in queue order
  • fn take_stats(&mut self) -> Vec<FrameStats> the finished frames' stats since the last call
  • fn collect_stats(&mut self) after Device::wait_idle: the stats of what was still in flight
  • fn reflattened(&self) -> u32 curves and fills the last prepare flattened again (their zoom band changed, or the view left their window)
  • fn prepare(&mut self, r: &mut Renderer, size: (u32, u32)) -> Result<()> the frame's data for Renderer::record: waits for this slot's last frame, sends what changed. size: the target's in pixels
  • fn submitted(&mut self, id: SubmitId) the frame went to the GPU: Queue::submit's or Swapchain::present's answer

Source: docs/API.md in the JFLib repository.