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 Camerawhat 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 screencenter: [f64; 2]scale: f64rotation: f64
impl Camera
const fn new(center: [f64; 2], scale: f64) -> Camerafn to_screen(&self, p: [f64; 2], size: (u32, u32)) -> [f64; 2]a point of the drawing in pixels of a target ofsize(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 ofsizefn 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 byfactor(below 1: out) about the pixel position q of a target ofsize: the point under q staysenum Unithow a style's width is measuredPx-- pixels of the target, whatever the zoomDrawing-- units of the drawing: the stroke grows and shrinks with the zoom
enum Caphow an open end endsButt-- at the end pointRound-- a half circle around itSquare-- half the width beyond it
enum Joinhow two segments of a polyline meet on the outer side of the turnMiter-- the outer edges meet, up to the miter limit; beyond it a bevelRound-- a circle around the vertexBevel-- 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 HatchLinea 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 withnewand changed field by field (it may grow)angle: f64base: [f64; 2]spacing: f64shift: f64dash: [f64; HATCH_DASH_MAX]dashes: u32
impl HatchLine
const fn new(angle: f64, spacing: f64) -> HatchLinesolid lines at an angle,spacingapart, through the originfn dashed(mut self, pattern: &[f64]) -> HatchLinethe same with a dash pattern (at most HATCH_DASH_MAX entries, drawing units)struct Stylea stroke's look. Made withnewand changed field by field (it may grow)color: u32-- 0xAARRGGBB: sRGB codes as the target shows them, straight alphawidth: f32-- inunits; 0 (or anything thinner than a pixel): a hairline, 1 px wideunit: Unitcap: Capjoin: Joinmiter_limit: f32-- the longest miter over the width (lib/gfx's and SVG's ratio); at least 1dash: [f32; DASH_MAX]-- a dash pattern: lengths on and off in turn, starting with on, the firstdashesentries (0: solid). An odd count runs twice (on, off, on, then off, on, off), as in SVG; every dash ends incap, 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 polylinedashes: u32dash_unit: Unit-- the unit of the pattern's lengths and of its phasedash_phase: f32-- how far into the pattern an entity starts (indash_units)hatch: [HatchLine; HATCH_MAX]-- a fill's hatch: the firsthatchesline families (0: the fill is solid), drawn incolorover nothing, the lineshatch_widthpx wide (0, or thinner than a pixel: 1 px); strokes ignore ithatches: u32hatch_width: f32transparency: 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 TransparencyAutoCAD'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 nonePercent(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) -> Stylea hairline of a colour: width 0, butt caps, miter joins with the limit 4, solidfn hatched(mut self, families: &[HatchLine], width: f32) -> Stylethe same with a hatch (at most HATCH_MAX families; none: a solid fill) of lineswidthpx widefn dashed(mut self, pattern: &[f32], unit: Unit, phase: f32) -> Stylethe same with a dash pattern (at most DASH_MAX entries; an empty one: solid), its unit and phasestruct StyleId(pub u32)a style of a Scenestruct Layera layer's settings. Made withnewand changed field by field (it may grow)visible: boolorder: i32-- layers are drawn by this, lowest first; equal ones in the order they were addedtransparency: 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) -> Layerstruct BlockIda block of a Scene: entities defined once (Scene::insert_in, in the block's units) and inserted many times (Shape::Insert); dead after remove_blockslot: u32
struct Blocka block's settings. Made withnewand changed field by field (it may grow)base: [f64; 2]-- the point of the block that lands on an insert'sat(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 Inserta block placed by an entity (Shape::Insert): its base point toat, scaled (each axis; a negative scale mirrors, unequal magnitudes scale unevenly: circles become ellipses), turned byrotation(radians, counter-clockwise); an array ofcolumnsbyrowscopiesspacingapart along the insert's turned x and y (drawing units, not scaled: DXF's MINSERT). Made withnewand changed field by field (it may grow)block: BlockIdat: [f64; 2]rotation: f64scale: [f64; 2]columns: u32rows: u32spacing: [f64; 2]
impl Insert
const fn new(block: BlockId, at: [f64; 2]) -> Insertthe block at a point, unscaled, unturned, one copystruct InstanceInfowhat the blocks of a scene hold and what the last prepare sent of them (Scene::instance_info). It may growblocks: 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' recordsvariants: u32block_records: u32instances: u32-- instances (an insert's copies, nested inserts each once per instance of their block) and the entries of the visibilityentries: u32rebuilt: 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: u64sent_block_records: u32
struct LayerIda layer of a Scene; dead after remove_layerslot: u32
struct EntityIdan entity of a Scene; dead after remove, also when its place has gone to another oneslot: 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 pointArc { 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 atstart. Drawn in pieces of at most ARC_STEP, coverage from the circle itselfCircle { 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 lengthCubic { 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 oversweep(radians, not 0; a full turn or more: the closed ellipse, starting atstart); radii above 0Spline { 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 whereweightshas one positive weight per point (empty: all 1), onknots(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 SPLINEFill { 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 UploadInfowhat prepare sent for this framerecords: u32-- records that came from the CPU (changed entities, free places), and in how many runsruns: u32scatter: bool-- they went through the scatter shader (many runs), else a copy per runrebuild: bool-- a new pool (a layout changed), and the records the GPU copied across into itmoved: u64tables: bool-- the visible layers' pages and table went upbytes: u64-- everything prepare wrote for the GPU, the view included
struct FrameStatswhat a finished frame measured (Scene::set_stats)frame: u64-- counts the scene's frames from 0visible: u64-- records the visibility found in the targetstamps: 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 Sceneentities, 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 TextInfowhat a scene's text holds (Scene::text_info). It may growfonts: u32glyphs: 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 layerstiles_s: u32tiles_l: u32pages: u32layers: u32made: u32-- tiles made so far; glyphs that found no page (the device's most layers)failed: u32fills: u32-- texts drawn as fills now; texts that changed between glyphs and fills in the last prepareswitched: u32sent_bytes: u64-- what the last prepare sent of the atlas (bytes) and of the glyph table (rows)sent_rows: u32decided_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() -> Scenea 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 devicefn 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 againfn attached(&self) -> boolthe scene is on a renderer's device (Scene::new, attach); else only draw_cpu draws itfn add_style(&mut self, s: &Style) -> Result<StyleId>a style for entities; the next frame shows itfn 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 orderfn 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 itfn 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 parserfn fonts(&mut self) -> &mut Fontsthe 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 textsfn 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 entityfn text_info(&self) -> TextInfowhat 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 textsfn 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 entitiesfn 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 elsefn 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) -> u32entities alive (a block's entities and inserts each once)fn is_empty(&self) -> boolfn 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 itfn 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 itfn 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 oncefn instance_info(&self) -> InstanceInfowhat the blocks hold and what the last prepare sent of themfn set_camera(&mut self, c: &Camera) -> Result<()>fn camera(&self) -> &Camerafn 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 timesfn upload_info(&self) -> UploadInfowhat the last prepare sentfn 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) -> &Bufferfn draws_buffer(&self) -> &Bufferfn 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 orderfn take_stats(&mut self) -> Vec<FrameStats>the finished frames' stats since the last callfn collect_stats(&mut self)after Device::wait_idle: the stats of what was still in flightfn reflattened(&self) -> u32curves 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 pixelsfn submitted(&mut self, id: SubmitId)the frame went to the GPU: Queue::submit's or Swapchain::present's answer