# Shapes, paint, and coverage

[Canonical page](https://nothing.graphics/docs/format/spec/graphics) · [Page source on GitHub](https://github.com/gridaco/nothing/blob/main/ncf/spec/graphics.md)

Drawable geometry, paint stacks, strokes, gradients, images and coverage.



**Level 1 review draft.** A `shape` owns editable geometry and the
operations that give it an appearance. At a sample time each stroke uses the
same evaluated geometry. A stroke can select an interval along a contour.
Paints are local to the fill or stroke that consumes them.
[Level 1 specification](https://nothing.graphics/docs/format/spec) · [Canonical specimen](https://github.com/gridaco/nothing/blob/main/ncf/examples/canonical-draft.nothing)

## Non-destructive authoring [#non-destructive-authoring]

A `shape` retains its identity across geometry edits. Changing its `rect`
child to an `ellipse` edits the geometry of the existing shape. The shape
keeps its paint and its place in the scene. An animation targeting the shape
can therefore continue to target it across that edit.

A fill or stroke owns its gradient. Author the gradient and its stops
inline under the consumer's `paint` element. Two shapes can start with
identical gradients and an edit to a stop affects only the consuming paint.
In the canonical specimen, changing the circle's geometry and changing a
stop in its linear gradient are independent edits.

## Timed composition [#timed-composition]

A scene can contain shapes and timed placements in drawing order. A
`sequence` places audio, footage, a referenced scene, or inline content. Sampling
at time `t` determines which placements are active and their local sample times.
The same rule applies recursively inside a compound clip for both picture
and sound. Overlapping audio contributions mix on the output sample grid.
[Sequence syntax and sampling rules](https://nothing.graphics/docs/format/spec/sequences)

A timed scene declares its authored frame rate. An element owns the keyframes
for its animated properties. A key can address a frame or an exact instant in
seconds on the owning timeline. [Property animation](https://nothing.graphics/docs/format/spec/animation)

## Shapes [#shapes]

Each `shape` has exactly one geometry child. Geometry and paint use the
same local coordinates, with x increasing to the right and y increasing down.
The shape contributes one drawable to its enclosing scene, shape, group, or inline sequence.
A shape under a boolean or mask contributes to its owner in the role given below.

| Owner      | Graphics children                                                                                                                                        | Meaning of order                                                                                                                                                                                         |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `shape`    | One geometry, zero or one `fill`, zero or more `stroke` siblings, rectangle shadows, attached drawables, optional `filter`, `backdrop-filter` and `mask` | An attachment before the geometry paints beneath the host’s own appearance. One after it paints above. [Paint order](https://nothing.graphics/docs/format/spec/attached-drawables#order-and-compositing) |
| `boolean`  | Two or more operand shapes                                                                                                                               | The first operand supplies the starting region for subtraction.                                                                                                                                          |
| `fill`     | One or more `paint` children                                                                                                                             | Later paints cover earlier paints within this operation.                                                                                                                                                 |
| `stroke`   | One or more `paint` children and zero or one `trim`                                                                                                      | Paints stack in authored order on the selected stroke region.                                                                                                                                            |
| `paint`    | One `solid`, `image`, or `gradient`                                                                                                                      | The child supplies the paint value.                                                                                                                                                                      |
| `gradient` | Ordered `stop` children                                                                                                                                  | Each stop owns its ramp position and color.                                                                                                                                                              |
| `mask`     | One source shape                                                                                                                                         | The source supplies coverage in the owner's local coordinates.                                                                                                                                           |

A property owner can also contain its `animate` declarations. These do not
occupy graphics slots. Report a missing or excess required child at its
owner, and identify a child or property attached to the wrong owner at its
source location. For example, a second fill is an error. A second stroke
starts another independent drawing operation.

| Geometry   | Definition                                                                                                                 |
| ---------- | -------------------------------------------------------------------------------------------------------------------------- |
| `rect`     | `width` and `height` around the registered point                                                                           |
| `circle`   | `r` and the registered box                                                                                                 |
| `ellipse`  | `rx`, `ry` and the registered box                                                                                          |
| `line`     | Endpoints (`x1`, `y1`) and (`x2`, `y2`)                                                                                    |
| `polyline` | Straight segments through the coordinate pairs in `points`                                                                 |
| `polygon`  | The same point sequence with a closing segment back to the first point                                                     |
| `path`     | SVG path data in `d`                                                                                                       |
| `boolean`  | Region formed by combining two or more ordered operand shapes                                                              |
| `text`     | Editable copy, spans, and their laid-out glyph geometry. [Text and layout](https://nothing.graphics/docs/format/spec/text) |

Supply the geometry fields listed above in local units. The document-wide
lexical and viewport rules apply. For these three primitives the [boxed geometry contract](https://nothing.graphics/docs/format/spec/boxed-geometry) resolves local bounds from dimensions, registration fractions and contour offsets. Rectangle dimensions and circle or ellipse
radii are nonnegative. A zero dimension or radius gives zero filled area. Attachments can still measure degenerate bounds or a contour. [Hosts at their limits](https://nothing.graphics/docs/format/spec/attached-drawables#what-a-geometry-offers)
An SVG importer resolves omitted geometry values or relative lengths using
their SVG meanings. Author point lists as ordered `x,y` pairs separated
by whitespace. An empty list has no bounds or contour. The single-contour examples use straight segments between
successive points. [SVG shapes](https://www.w3.org/TR/SVG2/shapes.html)

### Path data [#path-data]

A `path` requires one `d` attribute in the [SVG 2 path-data syntax](https://www.w3.org/TR/SVG2/paths.html#PathDataBNF), evaluated after XML attribute decoding. Use the raw command string in local units. CSS values such as `none` and `path(...)` are outside this grammar. An empty or whitespace-only value gives empty geometry. A nonempty path starts with `M` or `m`.

Use either case for each command family. `M/m` moves, `Z/z` closes, `L/l`, `H/h` and `V/v` draw lines, `C/c` and `S/s` draw cubic Béziers, `Q/q` and `T/t` draw quadratic Béziers, and `A/a` draw elliptical arcs. Lowercase drawing and move commands use relative coordinates. An initial `m` is relative to the origin. Extra coordinate pairs after either move command draw implicit lines in the same coordinate mode. Other commands with parameters can repeat across complete argument groups. A close returns the current point to the subpath start. Each smooth curve reflects the preceding control point only after a curve of the corresponding family and otherwise uses the current point.

Apply SVG's comma and whitespace rules, including adjacent numbers when their token boundaries are unambiguous, signed coordinates, fractional numbers and exponents. A decimal point requires at least one digit after it. Arc flags consume exactly one digit each, either `0` or `1`, including when adjacent to each other or the endpoint. For arcs, omit a segment ending at its start point, draw a line for a zero radius, use the magnitudes of signed radii, and scale insufficient radii together until the ellipse reaches the endpoints. [SVG path commands and implementation notes](https://www.w3.org/TR/SVG2/paths.html)

Consume the entire attribute. An invalid command, separator, flag, incomplete argument group or non-finite number requires a diagnostic at the path's source location. Reject the malformed value as a whole. Keep the authored spelling, separators and command case when saving an unrelated edit.

A path owns its interior through the optional `fill-rule` attribute. Use the SVG winding rules across all subpaths together. The default `nonzero` includes points whose signed winding number is nonzero. Under `evenodd`, a point is inside when a ray from it to the exterior crosses the path an odd number of times. Two nested contours drawn in the same direction therefore have a filled center under `nonzero` and a hole under `evenodd`. Reversing the inner contour makes a hole under both rules. These definitions include self-intersections. A path owns one rule for every paint in its fill, with hold keys for animation. Diagnose any other value. [SVG winding rules](https://www.w3.org/TR/SVG2/painting.html#FillRuleProperty)

For fill coverage, implicitly close each open subpath. This closure contributes only to the interior. Strokes follow the authored commands. A closed path used as a geometry mask or boolean operand supplies the same sampled interior, even when it has no paint. The closed-contour requirement in those two roles applies to each drawn subpath. [Compound-path fixture](https://github.com/gridaco/nothing/blob/main/ncf/conformance/compound-path.nothing)

A path can have multiple subpaths. The [fill operation](https://nothing.graphics/docs/format/spec/graphics#paint) receives the whole path, and [contour trim](https://nothing.graphics/docs/format/spec/contour-trim) selects one interval across the drawn lengths of its subpaths in authored order. [Structured animation rules](https://nothing.graphics/docs/format/spec/animation#property-types-and-exceptions) apply to `d` values.

### Rectangle corners [#rectangle-corners]

A rectangle owns five optional nonnegative finite lengths in local units.
`corner-radius` supplies the shared radius and defaults to zero.
`corner-top-left-radius`, `corner-top-right-radius`,
`corner-bottom-right-radius`, and `corner-bottom-left-radius` each default
to the sampled shared radius. An explicit corner value, including zero,
overrides that default. Each property accepts an ordinary scalar track on
the rectangle. When a corner track releases, use its authored base or,
if absent, the current shared radius. Left and right refer to the local
rectangle before any transform or reflection.

```xml
<rect width="120" height="40"
      corner-radius="12" corner-bottom-left-radius="0"/>
```

First sample the dimensions and the four corner values. For each edge,
divide its length by the sum of its two adjacent radii, skipping a sum of
zero. Multiply all four radii by the smallest of those ratios and 1.
These used radii determine circular quarter-arcs tangent to the edges. A
zero radius leaves a square corner. A zero width or height gives zero filled
area and retains the collapsed contour for attachments. For example,
radius 100 on a 120 × 40 rectangle uses 20 at every
corner. Increasing just the height to 80 gives 40. Saving the width or
height edit preserves the authored radius of 100. This proportional rule
keeps the corner radii in the same ratios when constraints overlap.
[CSS overlapping curves](https://www.w3.org/TR/css-backgrounds-3/#corner-overlap)

Fills, strokes, trim, mask coverage and boolean operands use this contour.
Image paints still fit to the rectangle's full width and height before
clipping to its rounded outline. Stroke distance starts on the top edge
at `(left + usedTopLeft, top)` of the resolved box and increases clockwise. [Contour trim](https://nothing.graphics/docs/format/spec/contour-trim)

### Boolean geometry [#boolean-geometry]

A `boolean` occupies the geometry slot of a `shape`. It owns two or more
ordered `shape` children as operands. Here the word cuts its letter shapes out of
the rectangle. The enclosing shape supplies the blue paint.

```xml
<shape>
  <boolean type="subtraction">
    <shape>
      <rect anchor-u="0" anchor-v="0" offset-x="104" width="200" height="64" corner-radius="8"/>
    </shape>
    <shape>
      <text x="204" y="48" text-anchor="middle" font-family="PT Serif"
            font-size="44" font-weight="700">BOOK</text>
    </shape>
  </boolean>
  <fill>
    <paint>
      <solid color="#29547EFF"/>
    </paint>
  </fill>
</shape>
```

| Required `type` | Region of the result                                          |
| --------------- | ------------------------------------------------------------- |
| `union`         | Inside at least one operand                                   |
| `intersection`  | Inside every operand                                          |
| `subtraction`   | Inside the first operand and outside every subsequent operand |
| `exclusion`     | Inside an odd number of operands                              |

Only direct `shape` children are operands. Reordering them preserves the
region for union, intersection, and exclusion. For subtraction, the first
shape is the region to cut. The remaining shapes can be reordered freely.
In the example, reversing the two operands gives an empty result because the
rectangle contains all of the glyph ink. Preserve the authored order on save,
including for operations whose resulting region is invariant under reordering.

An operand contributes its geometry in the enclosing shape's coordinate space.
Apply the operand shape's sampled local-to-parent transform to its contour before
the boolean operation. Transforming the enclosing shape moves the entire result.
Each operand retains its identity and any authored appearance. Resolving an operand
requests only its geometry and local transform. Only the enclosing
shape paints the result, so a stroke on that shape follows the boundary of
the result, including holes. Changing `type` preserves the operand shapes and
their order. A child shape can itself have boolean geometry for a nested
operation.

A shape whose geometry is `text` is a valid operand in **every position** of
`union`, `intersection`, `subtraction`, and `exclusion`. At the requested
sample, lay out its current text and spans using the bound fonts. Use the union
of the positioned glyphs’ filled outlines as one operand. Spaces contribute
advance only. Overlapping glyphs contribute their shared area once, including
when the enclosing operation is exclusion. An empty string contributes an
empty region. Apply the operand shape’s transform once. Its fill, stroke,
shadows, filter, mask and opacity have no effect on this geometry. Preserve
the editable text, spans and font properties when saving the boolean.
[Glyph geometry](https://nothing.graphics/docs/format/spec/text#glyph-geometry)

The [cutout example](https://github.com/gridaco/nothing/blob/main/ncf/conformance/cutout.nothing) subtracts `BOOK` from a blue
card. Each O’s ink cuts through the card, leaving its enclosed center blue.
Changing the word to `INK` recomputes the holes. The white line drawn later
crosses them continuously. With the text as the first operand instead,
subtraction would retain only the glyph ink outside the rectangle.

The same operand model admits simple closed contours and nested boolean
results. How an open contour or the expanded outline of an operand's stroke could supply a
boolean region remains open. Closed compound paths supply the interior defined by their sampled `fill-rule`.

## Paint [#paint]

A shape may own at most one fill and any number of sibling `stroke`
elements. Draw the fill first, then the strokes in document order, bottom
to top. Each stroke expands the same shape geometry with its own width,
alignment, caps and joins. Sampling a width track changes only the stroke
that owns it. Sampling the geometry supplies the contour for every stroke.
An optional `trim` owned by a stroke selects a local arc-length interval
for that stroke and all its paints. Its siblings retain their own coverage.
[Stroke trimming](https://nothing.graphics/docs/format/spec/contour-trim)

The fill and each stroke own one or more ordered `paint` children. The first paint
is the bottom layer. Every paint owns exactly one typed value. Reordering
two paints changes their stacking order while preserving their editable values.
An omitted operation contributes nothing. Text can have independent fills on
authored spans even when the enclosing shape has no fill. [Text appearance](https://nothing.graphics/docs/format/spec/text#appearance-and-editing)

A paint's `blend-mode` defaults to `normal` (source over). This draft also
defines `multiply` and `screen` with their usual separable blend functions
`s × d` and `s + d − s × d` on normalized channels. Within a stack,
combine each upper paint with the accumulated lower paints. Apply coverage
once to the assembled stack and use the bottom paint's mode to composite
the stack onto its destination. Apply this rule separately to each stroke's
paint stack using that stroke's expanded outline. Solid alpha comes from
`color` once. Use encoded sRGB channels for these blend functions and
source-over alpha for compositing. Reference values precede output-device
conversion and quantization.
[Compositing and blending](https://www.w3.org/TR/compositing-1/) · [Paint stack precedent](https://github.com/gridaco/nothing/blob/main/ncf/docs/renderer-precedents.md)

A stroke owns its explicit nonnegative `stroke-width`. Zero width contributes
no coverage. For uniform strokes on a single
contour, `stroke-linecap` accepts butt (default), round or square,
`stroke-linejoin` accepts miter (default), round or bevel, and
`stroke-miterlimit` defaults to 4. A miter beyond the limit becomes a bevel.
`stroke-align` accepts center (default), inside or outside. For a simple
closed contour an inside or outside stroke occupies its full width on that
side. An open contour uses center alignment. Per-side and variable widths
and multi-contour alignment require further rules.

A `solid` carries a `color`. An `image` carries an `href` relative to
the document that declares the paint. Report a missing image at that paint.
The reference form uses `preserveAspectRatio="xMidYMid slice"`. Scale the
intrinsic image uniformly until it covers the local geometry bounds on both
axes, center it in those bounds, and paint through the operation's coverage.
A referenced still SVG uses the same image paint as a raster asset. The
shape owns the placement and the asset owns its artwork. Resolve SVG
intrinsic proportions from its intrinsic dimensions or `viewBox` according
to SVG image sizing. With no intrinsic aspect ratio, use the paint bounds
as the SVG viewport. Apply the image fit once and clip through the shape.
Treat the asset as an independent image document. Internal IDs, styles
and fragment references resolve within that document. Use ordinary SVG
image processing for still artwork, with scripting, interaction and external
resource loading disabled. Embedded data and same-document references can
supply its pixels. Preserve painted alpha, including for an image-painted
mask source. A source-preserving edit retains the authored `href`. Replacing
the asset affects each use on the next render. This case covers still images.
[SVG image placement](https://www.w3.org/TR/SVG2/embedded.html#ImageElement) ·
[SVG image processing modes](https://www.w3.org/TR/SVG2/conform.html#referencing-modes)

A `gradient` carries ordered stops and a required `type`
that determines how the stops map onto the shape. Changing the type can
reuse the same stops in the same order.

| Gradient `type` | Geometry               | Meaning                                                                                   |
| --------------- | ---------------------- | ----------------------------------------------------------------------------------------- |
| `linear`        | `x1`, `y1`, `x2`, `y2` | A ramp from the first endpoint to the second                                              |
| `radial`        | `cx`, `cy`, `r`        | Offset zero at the center and one at the radius                                           |
| `sweep`         | `cx`, `cy`             | One clockwise revolution around the center, starting on the positive x axis               |
| `diamond`       | `cx`, `cy`, `rx`, `ry` | Offset zero at the center and one on the diamond whose vertices lie at the two axis radii |

For a nondegenerate linear gradient with start `a` and end `b`, the ramp
coordinate at point `p` is the dot product of `p - a` and `b - a` divided
by the squared length of `b - a`.
For a radial gradient, divide distance from the center by `r`. For a sweep,
a quarter-turn clockwise from the positive x axis gives 0.25. For a diamond
with positive radii, the ramp coordinate is `abs(x - cx) / rx + abs(y - cy) / ry`.
These coordinates locate a point on the ramp before evaluating its stops.
[SVG gradient geometry](https://www.w3.org/TR/SVG2/pservers.html) · [Sweep and diamond renderer precedent](https://github.com/gridaco/nothing/blob/main/n2/crates/grida/src/painter/gradient.rs)

The linear and radial gradients explicitly select local coordinates with
`gradientUnits="userSpaceOnUse"`. The sweep origin uses ramp position zero.
Coincident linear endpoints and zero or negative gradient radii lie outside
this review profile and require a diagnostic on the gradient.

Gradients carry ordered `stop` children, each with an `offset` from zero to
one and a `stop-color`. Solid and stop colors use `#RRGGBBAA`, with encoded
sRGB red, green and blue, followed by linear alpha. Each byte represents
its unsigned value divided by 255.

At a given time, sample each stop's properties. Compute its effective
position as the greater of its sampled offset and the preceding effective
position. The first position is the first sampled offset. This preserves
document order and every authored value when animated stops cross.

* Zero stops contribute transparent paint. One stop colors the whole ramp.
* Before the first effective position, use the first color. Beyond the last,
  use the last color. At coincident positions use the last color there.
* Between distinct positions, interpolate the four **straight** channels
  independently, using the fraction of the interval traversed. Approach a
  group of coincident stops using its first color and leave it using its last.
  Apply alpha when compositing the sampled color.

These spatial rules adopt SVG's stop ordering, endpoint padding, and
straight-color interpolation. Between color keys the same four channels use
the interval fraction supplied by temporal easing. [Property interpolation](https://nothing.graphics/docs/format/spec/animation#property-types-and-exceptions) · [SVG gradient stops](https://www.w3.org/TR/SVG2/pservers.html#GradientStops) · [Gradient animation cases](https://github.com/gridaco/nothing/blob/main/ncf/conformance/README.md#gradient-animation)

## Mask on a shape [#mask-on-a-shape]

A `mask` is an optional direct child of a `shape`, `group`, or `sequence`.
Its parent supplies the content. Its one nested `shape` supplies coverage
in the parent's local coordinates. The declaration occupies no drawing slot.
Moving it among the same parent's children preserves the result. Moving it
to a different eligible parent changes which content receives its coverage.
Apply the mask once to the assembled picture. On a shape this includes
the fill, every stroke and all attached pictures. Outside the source, coverage is zero.

* `type="geometry"` takes the filled interior of the source geometry with
  its local transform. It admits simple closed contours, closed compound
  paths with their sampled `fill-rule`, the glyph region
  of text, and closed regions produced by the admitted boolean operations.
  Skip the source’s attachments, paint, strokes, box shadows, source and backdrop filters, opacity and own mask. Its own locator and transform still place the geometry. [Letter matte and cutout](https://nothing.graphics/docs/format/spec/text#a-letter-as-a-matte-or-cutout)
* `type="alpha"` uses the rendered source alpha. Opaque black and opaque
  white both reveal the owner.
* `type="luminance"` samples the composited source in encoded sRGB. For
  straight components in \[0, 1], coverage is
  `A × (0.2126 R + 0.7152 G + 0.0722 B)`. At zero alpha coverage is
  zero. Opaque black hides and opaque white reveals. This fixes the color
  space for the CSS Masking procedure and takes the channel weights from
  Filter Effects Level 1. [Mask processing](https://www.w3.org/TR/css-masking-1/#MaskValues)
  · [Luminance to alpha](https://www.w3.org/TR/filter-effects-1/#feColorMatrixElement)

The mask source owns its geometry, paint and animation in the usual way.
Groups and placements use the same coverage operations in their own local
coordinates. The spatial chapter specifies their coordinate spaces and how
the assembled layer enters its parent. SVG mask regions and bounding-box units
remain open. [Spatial composition](https://nothing.graphics/docs/format/spec/spatial) · [Renderer precedents and remaining decisions](https://github.com/gridaco/nothing/blob/main/ncf/docs/renderer-precedents.md) · [CSS mask processing](https://www.w3.org/TR/css-masking-1/)

## Evaluating a shape [#evaluating-a-shape]

1. Sample the shape, its geometry, paint, and mask properties at the owning
   composition's time. Base evaluation uses their authored values.
2. Resolve the host geometry once. Paint attached drawables that precede its geometry element. Draw the host’s outer box shadows, fill, inset shadows and strokes, then the remaining attachments. Run its [source filter](https://nothing.graphics/docs/format/spec/filters) on the assembled image. [Attachment order](https://nothing.graphics/docs/format/spec/attached-drawables#order-and-compositing)
3. Apply the sampled mask coverage and the shape's `opacity` to the completed
   appearance. Opacity ranges from 0 to 1 and defaults to 1. Where opaque
   fill and stroke overlap on a transparent destination, a shape opacity
   of 0.5 produces alpha 0.5 even in the overlap.
4. Apply the shape's local-to-parent transform. Its geometry, paints and
   mask travel together. Groups and placements follow the same spatial
   contract. [Spatial composition](https://nothing.graphics/docs/format/spec/spatial)

These rules determine source ownership, order, and coverage. A paint's blend
mode works within the owner's appearance. Group compositing follows the
spatial contract. Sampling at antialiased edges and output device color
management require further rendering rules. [Property defaults and sampling](https://nothing.graphics/docs/format/spec/animation#property-types-and-exceptions)
