Skip to content

AI-native design editor. Open-source Figma alternative.

perf(canvas): renderer hot paths, overlays, and structure (#1624)

Danila Poyarkov9ef92a7711e0
diff --git a/changes/1602/breaking.md b/changes/1602/breaking.md
deleted file mode 100644
index 4e0cfb9c1..000000000
--- a/changes/1602/breaking.md
+++ /dev/null
@@ -1 +0,0 @@
-- A vector's per-region paints live on its network: `VectorRegion` has `fills` and `fillStyleId`, and `GeometryPath` no longer has them. `cloneVectorNetwork` moved from `@open-pencil/scene-graph/vector-network` to `@open-pencil/scene-graph/copy`. `@open-pencil/fig/node-change` no longer exports `resolveStyleOverrideFills` or `resolveVectorStyleOverrideFills`, and `resolveGeometryPaths` no longer takes fills by style ID.
diff --git a/changes/1602/fixed.md b/changes/1602/fixed.md
deleted file mode 100644
index abdc57a70..000000000
--- a/changes/1602/fixed.md
+++ /dev/null
@@ -1 +0,0 @@
-- Vectors whose regions have their own colors keep them when pasted from Figma, and through edits that add or remove regions.
diff --git a/changes/1624/changed.md b/changes/1624/changed.md
new file mode 100644
index 000000000..bb22a3913
--- /dev/null
+++ b/changes/1624/changed.md
@@ -0,0 +1,3 @@
+- Progressive rendering is the default canvas renderer; the previous renderer remains available in Settings under Rendering.
+- Zooming under progressive rendering keeps rendering during the gesture and sharpens the whole viewport in one frame when it ends, instead of tile by tile.
+- A page first shown under progressive rendering appears whole once its visible tiles exist, rather than tile by tile.
diff --git a/changes/1624/fixed.md b/changes/1624/fixed.md
new file mode 100644
index 000000000..2a7f4c116
--- /dev/null
+++ b/changes/1624/fixed.md
@@ -0,0 +1,4 @@
+- A dashed ellipse, polygon, or vector no longer leaves its dash on the section or boolean drawn after it.
+- Boolean operations draw each stroke with its own colour binding, gradient or image, cap, join, and dash.
+- Flashes and AI highlights outline a layer inside a rotated or flipped frame where it is drawn.
+- Zooming into a document that draws image previews shows previews sharpened for the zoom under progressive rendering.
diff --git a/changes/1624/performance.md b/changes/1624/performance.md
new file mode 100644
index 000000000..24fa40151
--- /dev/null
+++ b/changes/1624/performance.md
@@ -0,0 +1,5 @@
+- Large pages record faster: a layer costs fewer renderer calls, a chunk clips to its frames with one call, and a boolean operation keeps its result between draws.
+- Adding, removing, or moving a layer on a large page no longer re-renders the whole page: only the tiles it touched render again.
+- Selection chrome, rulers, labels, and issue markers draw with fewer calls per frame: outlines, dashes, colours, and label widths are kept between frames and the rulers' ticks draw as one batch.
+- Pages with thousands of text layers draw and record faster: shaped text stays prepared across frames, a text's fonts are checked once per frame, and emoji share the text's paragraph.
+- Typing into a page of tens of thousands of layers no longer stalls at every keystroke: the font status follows the edited layer instead of walking the page, and the page's coarse copies rebuild once the edit pauses.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index a17ebf590..75c2f15e3 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -80,7 +80,8 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.
### Paints
- A gradient or image paint builds a Skia shader through `applyGradientFill` and `applyImageFill` (`packages/core/src/canvas/fills.ts`), which take the target `Paint`, so a stroke reuses them instead of a second shader path. Both say whether they set one; a caller skips the paint when they did not, since CanvasKit builds no gradient from a transform it cannot invert and an image may not be decoded yet (`packages/core/tests/canvas/paints.test.ts`).
-- `forVisibleStrokes` (`packages/core/src/canvas/scene.ts`) is where a stroke's shader is set and cleared; stroke draw helpers take an already-configured `strokePaint` and must not reset its shader.
+- `packages/core/src/canvas/scene.ts` walks the tree and dispatches: text draws in `canvas/text/render.ts`, a layer's strokes in `canvas/strokes/dispatch.ts`, and a shape with effects through its raster or picture cache in `canvas/renderer/effect-raster-cache.ts`; keep `scene.ts` to traversal and move a new drawing domain beside those.
+- `forVisibleStrokes` (`packages/core/src/canvas/strokes.ts`) is where a stroke's shader and dash are set and cleared, for shapes and booleans alike; stroke draw helpers take an already-configured `strokePaint` and must not reset its shader, and a dash goes on through `withStrokeDash`, which frees the effect (`packages/core/tests/canvas/strokes.test.ts`).
- Shadows are cast from what a layer draws, children included, through `drawSilhouette` (`packages/core/src/canvas/shadows/silhouette.ts`); a container's shadows are drawn by `renderLayerShadows` around its children, not by `renderShape`. A faster path for a shape must give the same pixels as its silhouette (`packages/core/tests/canvas/shadows.test.ts`).
### Caches
diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.ts
index a8a87c6d3..7e677bf36 100644
--- a/packages/core/src/canvas/boolean.ts
+++ b/packages/core/src/canvas/boolean.ts
@@ -9,8 +9,15 @@ import { getTextOutlineSupport } from '#core/text/outlines'
import { isOpenVectorNetwork } from '#core/vector/connectivity'
import { addOpenSegmentsToPath } from '#core/vector/path-helpers'
+import { clearFillShader } from './fills'
import { sharedPath } from './paths/shared'
import type { SkiaRenderer } from './renderer'
+import {
+ configureStrokePaint,
+ forVisibleStrokes,
+ normalizeDashPattern,
+ withStrokeDash
+} from './strokes'
import { makeLineStrokeOutline } from './strokes/line'
import { textNodeToOutlinePath } from './text/outlines'
@@ -498,18 +505,18 @@ export function paintBooleanOperation(
try {
canvas.drawPath(path, r.fillPaint)
} finally {
- r.fillPaint.setShader(null)
+ clearFillShader(r)
}
}
between?.()
- for (const stroke of node.strokes) {
- if (!stroke.visible) continue
- const color = r.resolveStrokeColor(stroke, 0, node, graph)
- r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
- r.strokePaint.setAlphaf(stroke.opacity)
- drawAlignedStroke(r, canvas, path, stroke)
- }
+ // Each stroke resolves its own binding and shader, with its cap, join, and dash, as a shape's.
+ forVisibleStrokes(r, node, graph, (stroke, color) => {
+ configureStrokePaint(r, node, stroke, color)
+ withStrokeDash(r, normalizeDashPattern(stroke.dashPattern), 0, () =>
+ drawAlignedStroke(r, canvas, path, stroke)
+ )
+ })
} finally {
path.delete()
}
diff --git a/packages/core/src/canvas/effects.ts b/packages/core/src/canvas/effects.ts
index 841c8530f..567bbdf7c 100644
--- a/packages/core/src/canvas/effects.ts
+++ b/packages/core/src/canvas/effects.ts
@@ -4,10 +4,29 @@ import { readEffectiveFigmaRawField } from '@open-pencil/fig'
import type { SceneNode } from '@open-pencil/scene-graph'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
+import { ResourceCache } from '#core/cache/resource'
import { BLACK } from '#core/constants'
import type { SkiaRenderer } from './renderer'
+/**
+ * Filters a renderer keeps between frames, by their parameters: shadows and blurs reuse one across
+ * every node and frame that shares them. Bounded, so a slider dragged through hundreds of values
+ * frees the ones it passed rather than keeping them for the session.
+ */
+const MAX_CACHED_FILTERS = 256
+
+export type ImageFilterCache = ResourceCache<string, ImageFilter>
+export type MaskFilterCache = ResourceCache<number, MaskFilter>
+
+export function createImageFilterCache(): ImageFilterCache {
+ return new ResourceCache({ maxEntries: MAX_CACHED_FILTERS, dispose: (filter) => filter.delete() })
+}
+
+export function createMaskFilterCache(): MaskFilterCache {
+ return new ResourceCache({ maxEntries: MAX_CACHED_FILTERS, dispose: (filter) => filter.delete() })
+}
+
/**
* The Gaussian sigma that draws a Figma blur radius as Figma does. Measured on Figma 126 exports,
* layer blur, both shadows, and background blur fall off as a Gaussian of 0.43 × radius; Figma's
@@ -23,42 +42,44 @@ export function getCachedDropShadow(
dy: number,
sigma: number,
color: Float32Array
-): ImageFilter {
+): ImageFilter | null {
const key = `ds:${dx},${dy},${sigma},${color[0]},${color[1]},${color[2]},${color[3]}`
- let filter = r.imageFilterCache.get(key)
- if (!filter) {
- filter = r.ck.ImageFilter.MakeDropShadowOnly(dx, dy, sigma, sigma, color, null)
- r.imageFilterCache.set(key, filter)
- }
- return filter
+ return cachedImageFilter(r, key, () =>
+ r.ck.ImageFilter.MakeDropShadowOnly(dx, dy, sigma, sigma, color, null)
+ )
}
-export function getCachedBlur(r: SkiaRenderer, sigma: number): ImageFilter {
- const key = `blur:${sigma}`
- let filter = r.imageFilterCache.get(key)
- if (!filter) {
- filter = r.ck.ImageFilter.MakeBlur(sigma, sigma, r.ck.TileMode.Clamp, null)
- r.imageFilterCache.set(key, filter)
- }
- return filter
+export function getCachedBlur(r: SkiaRenderer, sigma: number): ImageFilter | null {
+ return cachedImageFilter(r, `blur:${sigma}`, () =>
+ r.ck.ImageFilter.MakeBlur(sigma, sigma, r.ck.TileMode.Clamp, null)
+ )
}
-export function getCachedDecalBlur(r: SkiaRenderer, sigma: number): ImageFilter {
- const key = `dblur:${sigma}`
- let filter = r.imageFilterCache.get(key)
- if (!filter) {
- filter = r.ck.ImageFilter.MakeBlur(sigma, sigma, r.ck.TileMode.Decal, null)
- r.imageFilterCache.set(key, filter)
- }
+export function getCachedDecalBlur(r: SkiaRenderer, sigma: number): ImageFilter | null {
+ return cachedImageFilter(r, `dblur:${sigma}`, () =>
+ r.ck.ImageFilter.MakeBlur(sigma, sigma, r.ck.TileMode.Decal, null)
+ )
+}
+
+/** CanvasKit makes no filter for a blur too small to draw; a paint takes null as none. */
+export function getCachedMaskBlur(r: SkiaRenderer, sigma: number): MaskFilter | null {
+ const cached = r.maskFilterCache.get(sigma)
+ if (cached) return cached
+ // Typed as always made; at runtime a sigma too small to blur makes none.
+ const filter = r.ck.MaskFilter.MakeBlur(r.ck.BlurStyle.Normal, sigma, true) as MaskFilter | null
+ if (filter) r.maskFilterCache.set(sigma, filter)
return filter
}
-export function getCachedMaskBlur(r: SkiaRenderer, sigma: number): MaskFilter {
- let filter = r.maskFilterCache.get(sigma)
- if (!filter) {
- filter = r.ck.MaskFilter.MakeBlur(r.ck.BlurStyle.Normal, sigma, true)
- r.maskFilterCache.set(sigma, filter)
- }
+function cachedImageFilter(
+ r: SkiaRenderer,
+ key: string,
+ make: () => ImageFilter | null
+): ImageFilter | null {
+ const cached = r.imageFilterCache.get(key)
+ if (cached) return cached
+ const filter = make()
+ if (filter) r.imageFilterCache.set(key, filter)
return filter
}
@@ -145,7 +166,7 @@ function renderNoiseEffect(
const value = seededNoise((x + 1) * 73856093 + (y + 1) * 19349663)
if (value > density) continue
const alpha = Math.max(0, Math.min(1, opacity * (0.35 + value * 0.65)))
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, alpha))
+ paint.setColorComponents(color.r, color.g, color.b, alpha)
canvas.drawRect(
r.ck.LTRBRect(x, y, Math.min(node.width, x + 1), Math.min(node.height, y + 1)),
paint
diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.ts
index 6a9d1ecd5..cebcc29f8 100644
--- a/packages/core/src/canvas/fills.ts
+++ b/packages/core/src/canvas/fills.ts
@@ -4,7 +4,6 @@ import type { SceneNode, SceneGraph, Fill } from '@open-pencil/scene-graph'
import { invertGradientTransform } from '@open-pencil/scene-graph/gradient'
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'
-import { fillGeometryMatchesRegions, hasRegionFills } from '@open-pencil/scene-graph/vector-network'
import { setPaintBlendMode } from './blend'
import { makeDiamondGradient } from './gradients/diamond'
@@ -34,10 +33,11 @@ export function paintFills(
: r.applyFill(fill, node, graph, fillIndex)
if (!applied) continue
r.fillPaint.setAlphaf(fill.opacity)
- setPaintBlendMode(r, r.fillPaint, fill.blendMode)
+ const blends = fill.blendMode !== undefined && fill.blendMode !== 'NORMAL'
+ if (blends) setPaintBlendMode(r, r.fillPaint, fill.blendMode)
draw(fill)
- r.fillPaint.setShader(null)
- r.fillPaint.setBlendMode(r.ck.BlendMode.SrcOver)
+ clearFillShader(r)
+ if (blends) setPaintBlendMode(r, r.fillPaint, 'NORMAL')
}
}
@@ -48,28 +48,47 @@ export function drawVectorMultiStyleFills(
graph: SceneGraph,
patternStack?: Set<string>
): boolean {
- const network = node.type === 'VECTOR' ? node.vectorNetwork : null
- if (!network || !hasRegionFills(network)) return false
- const { regions } = network
- const paths =
- (fillGeometryMatchesRegions(node.fillGeometry, network) ? r.getFillGeometry(node) : null) ??
- r.getVectorPaths(node)
+ if (node.type !== 'VECTOR' || !node.fillGeometry.some((geometry) => geometry.fills?.length)) {
+ return false
+ }
+ const paths = r.getFillGeometry(node)
if (!paths) return false
- for (const [index, region] of regions.entries()) {
+ for (let index = 0; index < node.fillGeometry.length; index++) {
+ const geometry = node.fillGeometry[index]
const path = paths[index]
+ const usesPathFills = Boolean(geometry.fills?.length)
paintFills(
r,
- region.fills ?? node.fills,
+ usesPathFills ? (geometry.fills ?? []) : node.fills,
node,
graph,
() => canvas.drawPath(path, r.fillPaint),
- { bindToNodeFills: !region.fills, patternStack }
+ { bindToNodeFills: !usesPathFills, patternStack }
)
}
return true
}
+/** Clears the fill paint's shader, when it has one; a layer with plain fills makes no call. */
+export function clearFillShader(r: SkiaRenderer): void {
+ if (!r.fillPaintShaded) return
+ r.fillPaint.setShader(null)
+ r.fillPaintShaded = false
+}
+
+export function clearStrokeShader(r: SkiaRenderer): void {
+ if (!r.strokePaintShaded) return
+ r.strokePaint.setShader(null)
+ r.strokePaintShaded = false
+}
+
+/** Records that `paint`, when it is a shared one, now carries a shader. */
+function markShaded(r: SkiaRenderer, paint: Paint): void {
+ if (paint === r.fillPaint) r.fillPaintShaded = true
+ else if (paint === r.strokePaint) r.strokePaintShaded = true
+}
+
export function drawNodeFill(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): void {
if (node.type === 'TEXT') r.renderText(canvas, node, fill)
else if (node.type !== 'LINE') {
@@ -85,11 +104,11 @@ export function applyFill(
fillIndex = 0,
patternStack = new Set<string>()
): boolean {
- r.fillPaint.setShader(null)
+ clearFillShader(r)
if (fill.type === 'SOLID') {
const c = r.resolveFillColor(fill, fillIndex, node, graph)
- r.fillPaint.setColor(r.ck.Color4f(c.r, c.g, c.b, c.a))
+ r.fillPaint.setColorComponents(c.r, c.g, c.b, c.a)
return true
}
@@ -105,7 +124,7 @@ export function applyFill(
if (fill.type === 'PATTERN' || fill.type === 'NOISE' || fill.type === 'CUSTOM') {
const c = r.resolveFillColor(fill, fillIndex, node, graph)
- r.fillPaint.setColor(r.ck.Color4f(c.r, c.g, c.b, c.a))
+ r.fillPaint.setColorComponents(c.r, c.g, c.b, c.a)
return true
}
@@ -224,6 +243,7 @@ function applyPatternFill(
tileRect
)
r.fillPaint.setShader(shader)
+ r.fillPaintShaded = true
shader.delete()
picture.delete()
return true
@@ -292,6 +312,7 @@ export function applyGradientFill(
if (!shader) return false
try {
paint.setShader(shader)
+ markShaded(r, paint)
} finally {
shader.delete()
}
@@ -423,6 +444,7 @@ function setImageShader(
)
try {
paint.setShader(shader)
+ markShaded(r, paint)
} finally {
shader.delete()
}
@@ -440,10 +462,14 @@ export function applyImageFill(
if (!hash) return false
const live = r.liveImages.get(hash)
if (live?.surface === r.surface) return setImageShader(r, fill, node, live.image, paint)
- if (r.viewportImageRendering) r.noteImageFillUser(hash, node.id)
+ if (r.viewportImageRendering) {
+ r.noteImageFillUser(hash, node.id)
+ r.previewsDrawn = true
+ }
+ // The preview's resolution follows the detail the drawing is for: the viewport's scale, or a
+ // tile's level, whose chunk pictures record again when a finer tile needs more.
const preview = r.viewportImageRendering
- ? // eslint-disable-next-line open-pencil/no-zoom-in-scene-drawing -- picks the preview resolution, not a size; preview mode draws the scene uncached on every frame, and tiles redraw the node when a sharper preview decodes.
- r.imagePreviews.get(graph, hash, previewEdge(node, r.zoom, r.dpr))
+ ? r.imagePreviews.get(graph, hash, previewEdge(node, r.imageDetailScale))
: undefined
if (r.viewportImageRendering && !preview) return false
const key = preview?.key ?? hash
diff --git a/packages/core/src/canvas/guides/draw.ts b/packages/core/src/canvas/guides/draw.ts
index f6c45f105..b3a1dc331 100644
--- a/packages/core/src/canvas/guides/draw.ts
+++ b/packages/core/src/canvas/guides/draw.ts
@@ -3,6 +3,7 @@ import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { guideOwnersOnPage } from '@open-pencil/scene-graph/guides'
+import { dashEffect } from '#core/canvas/overlays/outline'
import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'
import { getGuideScreenSegment } from './geometry'
@@ -37,7 +38,7 @@ function drawGuide(
state: GuideVisualState = 'idle'
): void {
const color = guideColor(state)
- r.auxStroke.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.auxStroke.setColorComponents(color.r, color.g, color.b, color.a)
const segment = getGuideScreenSegment(
graph,
owner,
@@ -67,12 +68,10 @@ function drawGuide(
}
if (!preview || owner.type === 'CANVAS') return
- const dash = r.ck.PathEffect.MakeDash(GUIDE_DASH, 0)
- r.auxStroke.setPathEffect(dash)
+ r.auxStroke.setPathEffect(dashEffect(r, GUIDE_DASH[0] ?? 0, GUIDE_DASH[1] ?? 0))
if (axis === 'x') canvas.drawLine(segment.x1, 0, segment.x1, r.viewportHeight, r.auxStroke)
else canvas.drawLine(0, segment.y1, r.viewportWidth, segment.y1, r.auxStroke)
r.auxStroke.setPathEffect(null)
- dash.delete()
}
export function drawGuides(
diff --git a/packages/core/src/canvas/highlight-rect.ts b/packages/core/src/canvas/highlight-rect.ts
index 46d62afe0..8c9b3b879 100644
--- a/packages/core/src/canvas/highlight-rect.ts
+++ b/packages/core/src/canvas/highlight-rect.ts
@@ -1,20 +1,18 @@
-import type { Canvas, Paint } from 'canvaskit-wasm'
+import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { FLASH_PADDING, FLASH_STROKE_WIDTH, FLASH_RADIUS } from '#core/constants'
+import { FLASH_PADDING, FLASH_RADIUS, FLASH_STROKE_WIDTH } from '#core/constants'
+import { type RotationPreview } from '#core/geometry'
+import { inNodeSpace, withScreenStroke } from './overlays/outline'
import type { SkiaRenderer } from './renderer'
-export function ensureFlashPaint(r: SkiaRenderer): Paint {
- if (!r._flashPaint) {
- r._flashPaint = new r.ck.Paint()
- r._flashPaint.setStyle(r.ck.PaintStyle.Stroke)
- r._flashPaint.setAntiAlias(true)
- }
- return r._flashPaint
-}
-
+/**
+ * Outlines the layer `nodeId` with a rounded stroke sized in screen pixels, placed through its
+ * own and its ancestors' transforms, so a layer inside a rotated or flipped frame is outlined
+ * where it is drawn.
+ */
export function drawNodeHighlightRect(
r: SkiaRenderer,
canvas: Canvas,
@@ -22,30 +20,27 @@ export function drawNodeHighlightRect(
nodeId: string,
color: { r: number; g: number; b: number },
opacity: number,
- extraPad = 0
+ extraPad = 0,
+ preview?: RotationPreview | null
): boolean {
const node = graph.getNode(nodeId)
if (!node) return false
-
- const abs = graph.getAbsolutePosition(nodeId)
- const cx = (abs.x + node.width / 2) * r.zoom + r.panX
- const cy = (abs.y + node.height / 2) * r.zoom + r.panY
- const hw = (node.width / 2) * r.zoom
- const hh = (node.height / 2) * r.zoom
- const pad = FLASH_PADDING + extraPad
-
- const paint = ensureFlashPaint(r)
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, opacity))
- paint.setStrokeWidth(FLASH_STROKE_WIDTH)
-
- canvas.save()
- if (node.rotation !== 0) canvas.rotate(node.rotation, cx, cy)
- const rect = r.ck.RRectXY(
- r.ck.LTRBRect(cx - hw - pad, cy - hh - pad, cx + hw + pad, cy + hh + pad),
- FLASH_RADIUS,
- FLASH_RADIUS
+ const pad = (FLASH_PADDING + extraPad) / r.zoom
+ const radius = FLASH_RADIUS / r.zoom
+ inNodeSpace(r, canvas, r.sceneGeometry(graph, preview), node, () =>
+ withScreenStroke(
+ r,
+ { color: r.ck.Color4f(color.r, color.g, color.b, opacity), width: FLASH_STROKE_WIDTH },
+ (paint) =>
+ canvas.drawRRect(
+ r.ck.RRectXY(
+ r.ck.LTRBRect(-pad, -pad, node.width + pad, node.height + pad),
+ radius,
+ radius
+ ),
+ paint
+ )
+ )
)
- canvas.drawRRect(rect, paint)
- canvas.restore()
return true
}
diff --git a/packages/core/src/canvas/issues/draw.ts b/packages/core/src/canvas/issues/draw.ts
index 64371b53e..11ba38a39 100644
--- a/packages/core/src/canvas/issues/draw.ts
+++ b/packages/core/src/canvas/issues/draw.ts
@@ -3,6 +3,7 @@ import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { cachedGlyphWidth } from '#core/canvas/labels/paragraph-cache'
import { inNodeSpace, withScreenStroke } from '#core/canvas/overlays/outline'
import type { SkiaRenderer } from '#core/canvas/renderer'
import {
@@ -14,7 +15,7 @@ import {
ISSUE_MARKER_RING_WIDTH,
ISSUE_WARNING_COLOR
} from '#core/constants'
-import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+import { type RotationPreview } from '#core/geometry'
import { issueMarkerLabel } from './layout'
import type { DesignIssueHighlight, DesignIssueSeverity, PlacedIssueMarker } from './types'
@@ -56,7 +57,7 @@ export function drawIssueHighlight(
if (!highlight || !node) return
const color = issueSeverityColor(highlight.severity)
- inNodeSpace(r, canvas, createSceneGeometry(graph, preview), node, () => {
+ inNodeSpace(r, canvas, r.sceneGeometry(graph, preview), node, () => {
r.auxFill.setColor(color4f(r, color, ISSUE_HIGHLIGHT_FILL_ALPHA))
canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), r.auxFill)
const stroke = { color: color4f(r, color), width: ISSUE_HIGHLIGHT_STROKE_WIDTH }
@@ -143,7 +144,7 @@ function drawMarker(
radius + ring,
radius + ring
)
- r.auxFill.setColor(r.ck.Color4f(0, 0, 0, MARKER_SHADOW_ALPHA))
+ r.auxFill.setColorComponents(0, 0, 0, MARKER_SHADOW_ALPHA)
r.auxFill.setMaskFilter(r.getCachedMaskBlur(MARKER_SHADOW_SIGMA))
canvas.drawRRect(shadow, r.auxFill)
r.auxFill.setMaskFilter(null)
@@ -195,9 +196,7 @@ function drawMarker(
const font = r.sizeFont
if (!font) return
const label = issueMarkerLabel(marker.count)
- let textWidth = 0
- for (const width of font.getGlyphWidths(font.getGlyphIDs(label))) textWidth += width
- font.setEmbolden(true)
+ const textWidth = cachedGlyphWidth(r, font, label)
r.auxFill.setColor(color4f(r, issueSeverityForeground(marker.severity)))
canvas.drawText(
label,
@@ -206,7 +205,6 @@ function drawMarker(
r.auxFill,
font
)
- font.setEmbolden(false)
}
/** Draws placed markers so the first placed, most severe marker ends up on top. */
@@ -216,8 +214,14 @@ export function drawIssueMarkers(
placed: readonly PlacedIssueMarker[],
hoveredKey: string | null | undefined
): void {
- for (let index = placed.length - 1; index >= 0; index--) {
- const marker = placed[index]
- drawMarker(r, canvas, marker, marker.key === hoveredKey)
+ // Every label is bold: the font is set once around the loop, not twice per marker.
+ r.sizeFont?.setEmbolden(true)
+ try {
+ for (let index = placed.length - 1; index >= 0; index--) {
+ const marker = placed[index]
+ drawMarker(r, canvas, marker, marker.key === hoveredKey)
+ }
+ } finally {
+ r.sizeFont?.setEmbolden(false)
}
}
diff --git a/packages/core/src/canvas/labels/draw.ts b/packages/core/src/canvas/labels/draw.ts
index 9c7ceee8b..9d7610f3d 100644
--- a/packages/core/src/canvas/labels/draw.ts
+++ b/packages/core/src/canvas/labels/draw.ts
@@ -73,7 +73,7 @@ function drawSectionTitle(
try {
const matrix = labelScreenMatrix(labelTransform(node, graph, overlays?.rotationPreview), r)
canvas.concat(matrix)
- r.auxFill.setColor(r.ck.Color4f(background.r, background.g, background.b, background.a))
+ r.auxFill.setColorComponents(background.r, background.g, background.b, background.a)
const { x, y, width, height } = layout.bounds
const bounds = r.ck.RRectXY(
r.ck.LTRBRect(x, y, x + width, y + height),
diff --git a/packages/core/src/canvas/labels/paragraph-cache.ts b/packages/core/src/canvas/labels/paragraph-cache.ts
index 66b0c54a8..4dc4c2651 100644
--- a/packages/core/src/canvas/labels/paragraph-cache.ts
+++ b/packages/core/src/canvas/labels/paragraph-cache.ts
@@ -5,6 +5,7 @@ import type { Size } from '@open-pencil/scene-graph/primitives'
import { detectTextDirection } from '@open-pencil/scene-graph/text/direction'
import { ResourceCache } from '#core/cache/resource'
+import type { SkiaRenderer } from '#core/canvas/renderer'
import { resolveParagraphFontFamilies } from '#core/canvas/text/font-families'
import { DEFAULT_FONT_FAMILY, SECTION_TITLE_FONT_FAMILY } from '#core/constants'
import { textHasFallbackScript } from '#core/text/coverage'
@@ -52,6 +53,31 @@ export function measureGlyphWidth(font: Font, text: string): number {
return width
}
+const MAX_CACHED_WIDTHS_PER_FONT = 4096
+
+/**
+ * `text`'s advance in `font`, kept with the renderer: chrome measures the same few labels on
+ * every frame, and each measurement is two native calls. A font reloaded is a new object, so
+ * its widths start over.
+ */
+export function cachedGlyphWidth(
+ r: Pick<SkiaRenderer, 'glyphWidths'>,
+ font: Font,
+ text: string
+): number {
+ let widths = r.glyphWidths.get(font)
+ if (!widths) {
+ widths = new Map()
+ r.glyphWidths.set(font, widths)
+ }
+ const cached = widths.get(text)
+ if (cached !== undefined) return cached
+ if (widths.size >= MAX_CACHED_WIDTHS_PER_FONT) widths.clear()
+ const width = measureGlyphWidth(font, text)
+ widths.set(text, width)
+ return width
+}
+
function retire(entry: LabelParagraphEntry): void {
entry.retired = true
if (entry.users === 0) entry.paragraph.delete()
diff --git a/packages/core/src/canvas/labels/status.ts b/packages/core/src/canvas/labels/status.ts
index 87cd610ab..664145b39 100644
--- a/packages/core/src/canvas/labels/status.ts
+++ b/packages/core/src/canvas/labels/status.ts
@@ -149,13 +149,13 @@ export function drawSectionStatus(
SECTION_TITLE_RADIUS
)
const { background } = colors
- r.auxFill.setColor(r.ck.Color4f(background.r, background.g, background.b, background.a))
+ r.auxFill.setColorComponents(background.r, background.g, background.b, background.a)
canvas.drawRRect(bounds, r.auxFill)
r.auxStroke.setColor(colors.border)
r.auxStroke.setStrokeWidth(1)
r.auxStroke.setPathEffect(null)
canvas.drawRRect(bounds, r.auxStroke)
- r.auxFill.setColor(r.ck.Color4f(label.color.r, label.color.g, label.color.b, 1))
+ r.auxFill.setColorComponents(label.color.r, label.color.g, label.color.b, 1)
canvas.drawCircle(
x + SECTION_TITLE_PADDING_X + DOT_RADIUS,
y + height / 2,
@@ -191,6 +191,6 @@ export function drawStatusDot(
label: StatusState,
center: Vector
): void {
- r.auxFill.setColor(r.ck.Color4f(label.color.r, label.color.g, label.color.b, 1))
+ r.auxFill.setColorComponents(label.color.r, label.color.g, label.color.b, 1)
canvas.drawCircle(center.x, center.y, DOT_RADIUS, r.auxFill)
}
diff --git a/packages/core/src/canvas/labels/style.ts b/packages/core/src/canvas/labels/style.ts
index cfc3fc200..f47642632 100644
--- a/packages/core/src/canvas/labels/style.ts
+++ b/packages/core/src/canvas/labels/style.ts
@@ -4,7 +4,7 @@ import Matrix from '@open-pencil/scene-graph/matrix'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas/renderer'
-import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+import type { RotationPreview, SceneGeometry } from '#core/geometry'
import { canvasLabelForeground } from './color'
import type { LabelHitOptions } from './hit-test'
@@ -52,11 +52,7 @@ function frameTitlePoint(
}
}
-function sectionContains(
- geometry: ReturnType<typeof createSceneGeometry>,
- section: SceneNode,
- point: Vector
-): boolean {
+function sectionContains(geometry: SceneGeometry, section: SceneNode, point: Vector): boolean {
const inverse = Matrix.invert(geometry.worldMatrix(section))
if (!inverse) return false
const local = Matrix.mapPoint(inverse, point)
@@ -76,7 +72,7 @@ function frameTitleBackground(
preview?: RotationPreview | null
): Color {
const point = frameTitlePoint(r, graph, node, layout, preview)
- const geometry = createSceneGeometry(graph, preview)
+ const geometry = r.sceneGeometry(graph, preview)
const sections: SceneNode[] = []
for (
let ancestor = node.parentId ? graph.getNode(node.parentId) : undefined;
diff --git a/packages/core/src/canvas/labels/text.ts b/packages/core/src/canvas/labels/text.ts
deleted file mode 100644
index 3cd62325f..000000000
--- a/packages/core/src/canvas/labels/text.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { Font } from 'canvaskit-wasm'
-
-import { ELLIPSIS } from '#core/text/ellipsis'
-
-export function measureLabelText(font: Font, text: string): number {
- const glyphIds = font.getGlyphIDs(text)
- const widths = font.getGlyphWidths(glyphIds)
- let result = 0
- for (const width of widths) result += width
- return result
-}
-
-export function ellipsizeLabelText(font: Font, text: string, maxWidth: number): string {
- if (maxWidth <= 0) return ''
- if (measureLabelText(font, text) <= maxWidth) return text
-
- const ellipsisWidth = measureLabelText(font, ELLIPSIS)
- if (maxWidth <= ellipsisWidth) return ELLIPSIS
-
- let width = 0
- let end = 0
- const glyphIds = font.getGlyphIDs(text)
- const widths = font.getGlyphWidths(glyphIds)
- for (let index = 0; index < widths.length; index++) {
- if (width + widths[index] + ellipsisWidth > maxWidth) break
- width += widths[index]
- end = index + 1
- }
- return text.slice(0, end) + ELLIPSIS
-}
diff --git a/packages/core/src/canvas/layout-grids.ts b/packages/core/src/canvas/layout-grids.ts
index eba4510f3..28ff8673c 100644
--- a/packages/core/src/canvas/layout-grids.ts
+++ b/packages/core/src/canvas/layout-grids.ts
@@ -107,11 +107,15 @@ function drawSquareGrid(
}
}
+const GRID_CONTAINER_TYPES = new Set(['FRAME', 'COMPONENT', 'INSTANCE', 'COMPONENT_SET', 'SECTION'])
+
export function drawLayoutGrids(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {
+ // Only containers carry grids; every other layer skips the raw field read.
+ if (!GRID_CONTAINER_TYPES.has(node.type)) return
for (const rawGrid of rawLayoutGrids(node)) {
const grid = gridGeometry(rawGrid)
if (!grid) continue
- r.auxFill.setColor(r.ck.Color4f(grid.color.r, grid.color.g, grid.color.b, grid.color.a))
+ r.auxFill.setColorComponents(grid.color.r, grid.color.g, grid.color.b, grid.color.a)
if (grid.pattern === 'GRID') drawSquareGrid(r, canvas, node, grid)
else if (grid.pattern === 'ROWS') drawRowGrid(r, canvas, node, grid)
else drawColumnGrid(r, canvas, node, grid)
diff --git a/packages/core/src/canvas/node-edit-overlay.ts b/packages/core/src/canvas/node-edit-overlay.ts
index d7e099dcf..1a8c18c63 100644
--- a/packages/core/src/canvas/node-edit-overlay.ts
+++ b/packages/core/src/canvas/node-edit-overlay.ts
@@ -1,4 +1,4 @@
-import type { Canvas, Paint } from 'canvaskit-wasm'
+import type { Canvas, CanvasKit, Paint } from 'canvaskit-wasm'
import type {
VectorVertex,
@@ -83,8 +83,6 @@ export function drawNodeEditOverlay(
if (vertices.length === 0) return
- ensureNodeEditPaints(r)
-
const toScreen: ToScreenFn = (x, y) => ({
x: x * r.zoom + r.panX,
y: y * r.zoom + r.panY
@@ -188,125 +186,64 @@ function drawLiveShape(
}
// ---------------------------------------------------------------------------
-// Lazy paint cache
+// Paints
// ---------------------------------------------------------------------------
-const paintCache = new WeakMap<
- SkiaRenderer,
- {
- handleLinePaint: Paint
- handleLineSelectedPaint: Paint
- handleLineHoverPaint: Paint
- vertexStroke1px: Paint
- vertexSelectedFill: Paint
- handleSelectedFill: Paint
- handleSelectedStroke: Paint
- handleHoverFill: Paint
- handleHoverStroke: Paint
- techStrokePaint: Paint
- segmentSelectedPaint: Paint
- }
->()
-
-function ensureNodeEditPaints(r: SkiaRenderer) {
- if (paintCache.has(r)) return
- const ck = r.ck
-
- // Default handle line — gray
- const handleLinePaint = new ck.Paint()
- handleLinePaint.setStyle(ck.PaintStyle.Stroke)
- handleLinePaint.setStrokeWidth(1)
- handleLinePaint.setColor(ck.Color4f(0.6, 0.6, 0.6, 1))
- handleLinePaint.setAntiAlias(true)
-
- // Selected handle line — blue
- const handleLineSelectedPaint = new ck.Paint()
- handleLineSelectedPaint.setStyle(ck.PaintStyle.Stroke)
- handleLineSelectedPaint.setStrokeWidth(1)
- handleLineSelectedPaint.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
- handleLineSelectedPaint.setAntiAlias(true)
-
- // Hover handle line — light blue
- const handleLineHoverPaint = new ck.Paint()
- handleLineHoverPaint.setStyle(ck.PaintStyle.Stroke)
- handleLineHoverPaint.setStrokeWidth(1)
- handleLineHoverPaint.setColor(ck.Color4f(LIGHT_BLUE[0], LIGHT_BLUE[1], LIGHT_BLUE[2], 1))
- handleLineHoverPaint.setAntiAlias(true)
-
- // Vertex stroke — blue 1px
- const vertexStroke1px = new ck.Paint()
- vertexStroke1px.setStyle(ck.PaintStyle.Stroke)
- vertexStroke1px.setStrokeWidth(1)
- vertexStroke1px.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
- vertexStroke1px.setAntiAlias(true)
-
- // Vertex selected fill — blue
- const vertexSelectedFill = new ck.Paint()
- vertexSelectedFill.setStyle(ck.PaintStyle.Fill)
- vertexSelectedFill.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
- vertexSelectedFill.setAntiAlias(true)
-
- // Selected handle diamond — blue fill
- const handleSelectedFill = new ck.Paint()
- handleSelectedFill.setStyle(ck.PaintStyle.Fill)
- handleSelectedFill.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
- handleSelectedFill.setAntiAlias(true)
-
- // Selected handle diamond — white outset stroke 3px
- const handleSelectedStroke = new ck.Paint()
- handleSelectedStroke.setStyle(ck.PaintStyle.Stroke)
- handleSelectedStroke.setStrokeWidth(3)
- handleSelectedStroke.setColor(ck.Color4f(1, 1, 1, 1))
- handleSelectedStroke.setAntiAlias(true)
-
- // Hover handle diamond — light blue fill
- const handleHoverFill = new ck.Paint()
- handleHoverFill.setStyle(ck.PaintStyle.Fill)
- handleHoverFill.setColor(ck.Color4f(LIGHT_BLUE[0], LIGHT_BLUE[1], LIGHT_BLUE[2], 1))
- handleHoverFill.setAntiAlias(true)
-
- // Hover handle diamond — white outset stroke 3px
- const handleHoverStroke = new ck.Paint()
- handleHoverStroke.setStyle(ck.PaintStyle.Stroke)
- handleHoverStroke.setStrokeWidth(3)
- handleHoverStroke.setColor(ck.Color4f(1, 1, 1, 1))
- handleHoverStroke.setAntiAlias(true)
-
- // Technical stroke: rgb(178,178,178) = 0.698
- const techStrokePaint = new ck.Paint()
- techStrokePaint.setStyle(ck.PaintStyle.Stroke)
- techStrokePaint.setStrokeWidth(1)
- techStrokePaint.setColor(ck.Color4f(0.698, 0.698, 0.698, 1))
- techStrokePaint.setAntiAlias(true)
-
- // Selected segment — blue 2px
- const segmentSelectedPaint = new ck.Paint()
- segmentSelectedPaint.setStyle(ck.PaintStyle.Stroke)
- segmentSelectedPaint.setStrokeWidth(2)
- segmentSelectedPaint.setColor(ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1))
- segmentSelectedPaint.setAntiAlias(true)
-
- paintCache.set(r, {
- handleLinePaint,
- handleLineSelectedPaint,
- handleLineHoverPaint,
- vertexStroke1px,
- vertexSelectedFill,
- handleSelectedFill,
- handleSelectedStroke,
- handleHoverFill,
- handleHoverStroke,
- techStrokePaint,
- segmentSelectedPaint
- })
+export interface NodeEditPaints {
+ handleLinePaint: Paint
+ handleLineSelectedPaint: Paint
+ handleLineHoverPaint: Paint
+ vertexStroke1px: Paint
+ vertexSelectedFill: Paint
+ handleSelectedFill: Paint
+ handleSelectedStroke: Paint
+ handleHoverFill: Paint
+ handleHoverStroke: Paint
+ techStrokePaint: Paint
+ segmentSelectedPaint: Paint
+}
+
+function strokePaint(ck: CanvasKit, width: number, color: Float32Array): Paint {
+ const paint = new ck.Paint()
+ paint.setStyle(ck.PaintStyle.Stroke)
+ paint.setStrokeWidth(width)
+ paint.setColor(color)
+ paint.setAntiAlias(true)
+ return paint
}
-function getNodeEditPaints(r: SkiaRenderer) {
- const paints = paintCache.get(r)
- if (!paints) {
- throw new Error('Node edit paints are not initialized')
+function fillPaint(ck: CanvasKit, color: Float32Array): Paint {
+ const paint = new ck.Paint()
+ paint.setStyle(ck.PaintStyle.Fill)
+ paint.setColor(color)
+ paint.setAntiAlias(true)
+ return paint
+}
+
+/** The renderer owns these: it creates them with its other paints and frees them when destroyed. */
+export function createNodeEditPaints(ck: CanvasKit): NodeEditPaints {
+ const blue = ck.Color4f(BLUE[0], BLUE[1], BLUE[2], 1)
+ const lightBlue = ck.Color4f(LIGHT_BLUE[0], LIGHT_BLUE[1], LIGHT_BLUE[2], 1)
+ const white = ck.Color4f(1, 1, 1, 1)
+ return {
+ handleLinePaint: strokePaint(ck, 1, ck.Color4f(0.6, 0.6, 0.6, 1)),
+ handleLineSelectedPaint: strokePaint(ck, 1, blue),
+ handleLineHoverPaint: strokePaint(ck, 1, lightBlue),
+ vertexStroke1px: strokePaint(ck, 1, blue),
+ vertexSelectedFill: fillPaint(ck, blue),
+ handleSelectedFill: fillPaint(ck, blue),
+ // White outset strokes around the selected and hovered handle diamonds.
+ handleSelectedStroke: strokePaint(ck, 3, white),
+ handleHoverFill: fillPaint(ck, lightBlue),
+ handleHoverStroke: strokePaint(ck, 3, white),
+ // Technical stroke: rgb(178, 178, 178).
+ techStrokePaint: strokePaint(ck, 1, ck.Color4f(0.698, 0.698, 0.698, 1)),
+ segmentSelectedPaint: strokePaint(ck, 2, blue)
}
- return paints
+}
+
+export function disposeNodeEditPaints(paints: NodeEditPaints): void {
+ for (const paint of Object.values(paints)) paint.delete()
}
// ---------------------------------------------------------------------------
@@ -322,7 +259,7 @@ function drawTechStroke(
segments: VectorSegment[],
regions: VectorRegion[]
): void {
- const { techStrokePaint } = getNodeEditPaints(r)
+ const { techStrokePaint } = r.nodeEditPaints
const node = graph.getNode(nodeId)
if (!node) return
const world = getWorldMatrix(node, graph)
@@ -358,7 +295,7 @@ function drawSelectedSegments(
selectedSegmentIndices: Set<number>,
toScreen: ToScreenFn
): void {
- const { segmentSelectedPaint, vertexStroke1px } = getNodeEditPaints(r)
+ const { segmentSelectedPaint, vertexStroke1px } = r.nodeEditPaints
const network = { vertices, segments, regions: [] }
for (const index of selectedSegmentIndices) {
if (index >= segments.length) continue
@@ -395,7 +332,7 @@ function drawEditHandles(
selectedHandles: Set<number>,
hovered: HandleInfo
): void {
- const paints = getNodeEditPaints(r)
+ const paints = r.nodeEditPaints
for (let si = 0; si < segments.length; si++) {
const seg = segments[si]
drawSegmentHandle(
@@ -438,7 +375,7 @@ function drawSegmentHandle(
toScreen: ToScreenFn,
selectedHandles: Set<number>,
hovered: HandleInfo,
- paints: ReturnType<typeof getNodeEditPaints>
+ paints: NodeEditPaints
): void {
const vertexIndex = tangentField === 'tangentStart' ? seg.start : seg.end
if (!handleVisibleVertices.has(vertexIndex)) return
@@ -508,7 +445,7 @@ function drawEditVertices(
toScreen: ToScreenFn
): void {
const vertexFill = r.penVertexFill
- const { vertexStroke1px, vertexSelectedFill } = getNodeEditPaints(r)
+ const { vertexStroke1px, vertexSelectedFill } = r.nodeEditPaints
for (let i = 0; i < vertices.length; i++) {
const v = toScreen(vertices[i].x, vertices[i].y)
diff --git a/packages/core/src/canvas/overlays/auto-layout-hover.ts b/packages/core/src/canvas/overlays/auto-layout-hover.ts
index 067c2a54a..9b6c5bfcd 100644
--- a/packages/core/src/canvas/overlays/auto-layout-hover.ts
+++ b/packages/core/src/canvas/overlays/auto-layout-hover.ts
@@ -3,6 +3,7 @@ import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { cachedGlyphWidth } from '#core/canvas/labels/paragraph-cache'
import { strokeLayoutChildren } from '#core/canvas/overlays/layout-outlines'
import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'
import {
@@ -118,8 +119,7 @@ function drawValuePill(
const font = r.valueFont ?? r.labelFont
if (!font) return
const glyphs = font.getGlyphIDs(text)
- let advance = 0
- for (const glyphWidth of font.getGlyphWidths(glyphs)) advance += glyphWidth
+ const advance = cachedGlyphWidth(r, font, text)
// The ink's top and bottom, so the digits sit in the middle whatever the font's metrics.
const bounds = font.getGlyphBounds(glyphs)
let top = 0
@@ -137,7 +137,7 @@ function drawValuePill(
)
r.auxFill.setColor(canvasColor(r, color))
canvas.drawRRect(rect, r.auxFill)
- r.auxFill.setColor(r.ck.Color4f(1, 1, 1, 1))
+ r.auxFill.setColorComponents(1, 1, 1, 1)
canvas.drawText(text, x - advance / 2, y - (top + bottom) / 2, r.auxFill, font)
}
diff --git a/packages/core/src/canvas/overlays/component-sets.ts b/packages/core/src/canvas/overlays/component-sets.ts
index 9829891e0..fa373c111 100644
--- a/packages/core/src/canvas/overlays/component-sets.ts
+++ b/packages/core/src/canvas/overlays/component-sets.ts
@@ -5,7 +5,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { labelViewport } from '#core/canvas/labels/layout'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { COMPONENT_SET_OUTLINE_RADIUS } from '#core/constants'
-import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+import { type RotationPreview } from '#core/geometry'
import { inNodeSpace, withScreenStroke } from './outline'
@@ -26,7 +26,7 @@ export function drawComponentSetBorders(
.filter(({ node }) => !node.strokes.some((stroke) => stroke.visible))
if (sets.length === 0) return
- const geometry = createSceneGeometry(graph, preview)
+ const geometry = r.sceneGeometry(graph, preview)
const stroke = {
color: r.compColor(),
width: r.COMPONENT_SET_BORDER_WIDTH,
diff --git a/packages/core/src/canvas/overlays/connectors.ts b/packages/core/src/canvas/overlays/connectors.ts
index 1b97a255f..953e2f027 100644
--- a/packages/core/src/canvas/overlays/connectors.ts
+++ b/packages/core/src/canvas/overlays/connectors.ts
@@ -12,7 +12,6 @@ import {
CONNECTOR_SEGMENT_HANDLE,
connectorRouteHandles,
connectorScreenEnds,
- createSceneGeometry,
viewportMatrix,
type RotationPreview
} from '#core/geometry'
@@ -36,7 +35,7 @@ function strokeConnectorLine(
// Traced as drawn, its elbows rounded.
const paths = vectorNetworkToPath(r.ck, line.vectorNetwork, line.cornerRadius)
canvas.save()
- canvas.concat(createSceneGeometry(graph, preview).screenMatrix(line, r))
+ canvas.concat(r.sceneGeometry(graph, preview).screenMatrix(line, r))
for (const path of paths) {
canvas.drawPath(path, paint)
path.delete()
diff --git a/packages/core/src/canvas/overlays/feedback.ts b/packages/core/src/canvas/overlays/feedback.ts
index 0088aca9e..1fcb94a9b 100644
--- a/packages/core/src/canvas/overlays/feedback.ts
+++ b/packages/core/src/canvas/overlays/feedback.ts
@@ -68,7 +68,7 @@ export function drawSnapMarks(r: SkiaRenderer, canvas: Canvas, guides?: SnapGuid
function vertexSnapPaint(r: SkiaRenderer, alpha: number) {
const { r: red, g, b } = VERTEX_SNAP_COLOR
r.auxStroke.setStrokeWidth(1)
- r.auxStroke.setColor(r.ck.Color4f(red, g, b, alpha))
+ r.auxStroke.setColorComponents(red, g, b, alpha)
return r.auxStroke
}
diff --git a/packages/core/src/canvas/overlays/gradient-handles.ts b/packages/core/src/canvas/overlays/gradient-handles.ts
index 9c810a820..6ac3819d4 100644
--- a/packages/core/src/canvas/overlays/gradient-handles.ts
+++ b/packages/core/src/canvas/overlays/gradient-handles.ts
@@ -50,10 +50,10 @@ function strokeWithShadow(r: SkiaRenderer, canvas: Canvas, path: Path) {
paint.setPathEffect(null)
paint.setStrokeWidth(1)
paint.setMaskFilter(getCachedMaskBlur(r, SHADOW_BLUR))
- paint.setColor(r.ck.Color4f(0, 0, 0, SHADOW_ALPHA))
+ paint.setColorComponents(0, 0, 0, SHADOW_ALPHA)
canvas.drawPath(path, paint)
paint.setMaskFilter(null)
- paint.setColor(r.ck.Color4f(1, 1, 1, 1))
+ paint.setColorComponents(1, 1, 1, 1)
canvas.drawPath(path, paint)
path.delete()
}
@@ -61,10 +61,10 @@ function strokeWithShadow(r: SkiaRenderer, canvas: Canvas, path: Path) {
function drawDot(r: SkiaRenderer, canvas: Canvas, point: Vector) {
const paint = r.auxFill
paint.setMaskFilter(getCachedMaskBlur(r, SHADOW_BLUR))
- paint.setColor(r.ck.Color4f(0, 0, 0, SHADOW_ALPHA))
+ paint.setColorComponents(0, 0, 0, SHADOW_ALPHA)
canvas.drawCircle(point.x, point.y + 0.5, GRADIENT_HANDLE.dotRadius, paint)
paint.setMaskFilter(null)
- paint.setColor(r.ck.Color4f(1, 1, 1, 1))
+ paint.setColorComponents(1, 1, 1, 1)
canvas.drawCircle(point.x, point.y, GRADIENT_HANDLE.dotRadius, paint)
}
@@ -80,7 +80,7 @@ function drawStop(
const border = selected ? SELECTED_BORDER : STOP_BORDER
const paint = r.auxFill
paint.setMaskFilter(null)
- paint.setColor(r.ck.Color4f(border.r, border.g, border.b, 1))
+ paint.setColorComponents(border.r, border.g, border.b, 1)
// The pointer leaves the square's edge facing the spot it marks.
const { center, pointing } = stop
const edge = {
@@ -111,9 +111,9 @@ function drawStop(
center.y + half - inset
)
canvas.drawRect(rect(0), paint)
- paint.setColor(r.ck.Color4f(1, 1, 1, 1))
+ paint.setColorComponents(1, 1, 1, 1)
canvas.drawRect(rect(2), paint)
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ paint.setColorComponents(color.r, color.g, color.b, color.a)
canvas.drawRect(rect(3), paint)
}
diff --git a/packages/core/src/canvas/overlays/index.ts b/packages/core/src/canvas/overlays/index.ts
index 627925621..6b4d7ea4f 100644
--- a/packages/core/src/canvas/overlays/index.ts
+++ b/packages/core/src/canvas/overlays/index.ts
@@ -6,8 +6,7 @@ export {
drawNodeOutline,
drawNodeSelection,
drawParentFrameOutlines,
- drawSelection,
- getRotatedCorners
+ drawSelection
} from './selection'
export { drawAutoLayoutHover } from './auto-layout-hover'
export {
diff --git a/packages/core/src/canvas/overlays/layout-outlines.ts b/packages/core/src/canvas/overlays/layout-outlines.ts
index 25317233c..aa2b92e54 100644
--- a/packages/core/src/canvas/overlays/layout-outlines.ts
+++ b/packages/core/src/canvas/overlays/layout-outlines.ts
@@ -4,7 +4,9 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'
import { LAYOUT_OUTLINE_DASH, LAYOUT_OUTLINE_GAP } from '#core/constants'
-import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+import { type RotationPreview } from '#core/geometry'
+
+import { dashEffect } from './outline'
function isFlowLayout(node: SceneNode | undefined): node is SceneNode {
return node?.layoutMode === 'HORIZONTAL' || node?.layoutMode === 'VERTICAL'
@@ -26,12 +28,8 @@ export function strokeLayoutOutlines(
preview?: RotationPreview | null
): void {
if (nodes.length === 0) return
- const geometry = createSceneGeometry(graph, preview)
- // MakeDash allocates a WASM PathEffect the JS GC won't reclaim; free it after drawing.
- const dash = r.ck.PathEffect.MakeDash(
- [LAYOUT_OUTLINE_DASH / r.zoom, LAYOUT_OUTLINE_GAP / r.zoom],
- 0
- )
+ const geometry = r.sceneGeometry(graph, preview)
+ const dash = dashEffect(r, LAYOUT_OUTLINE_DASH / r.zoom, LAYOUT_OUTLINE_GAP / r.zoom)
r.auxStroke.setStrokeWidth(1 / r.zoom)
r.auxStroke.setColor(r.outlineColor(container, graph))
r.auxStroke.setPathEffect(dash)
@@ -44,7 +42,6 @@ export function strokeLayoutOutlines(
}
} finally {
r.auxStroke.setPathEffect(null)
- dash.delete()
}
}
diff --git a/packages/core/src/canvas/overlays/measurement.ts b/packages/core/src/canvas/overlays/measurement.ts
index e4e0c3d66..a76234a9e 100644
--- a/packages/core/src/canvas/overlays/measurement.ts
+++ b/packages/core/src/canvas/overlays/measurement.ts
@@ -1,11 +1,11 @@
import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
-import Matrix from '@open-pencil/scene-graph/matrix'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import { cachedGlyphWidth } from '#core/canvas/labels/paragraph-cache'
import type { SkiaRenderer } from '#core/canvas/renderer'
import {
MEASUREMENT_COLOR,
@@ -15,6 +15,8 @@ import {
MEASUREMENT_TEXT_BASELINE
} from '#core/constants'
+import { outlineNode } from './outline'
+
export interface MeasurementSegment {
axis: 'x' | 'y'
from: number
@@ -147,12 +149,7 @@ function selectedBounds(graph: SceneGraph, selectedIds: Set<string>): Rect | nul
}
function textWidth(r: SkiaRenderer, text: string): number {
- const font = r.sizeFont
- if (!font) return 0
- const widths = font.getGlyphWidths(font.getGlyphIDs(text))
- let width = 0
- for (const glyphWidth of widths) width += glyphWidth
- return width
+ return r.sizeFont ? cachedGlyphWidth(r, r.sizeFont, text) : 0
}
function drawPill(r: SkiaRenderer, canvas: Canvas, text: string, x: number, y: number) {
@@ -169,7 +166,7 @@ function drawPill(r: SkiaRenderer, canvas: Canvas, text: string, x: number, y: n
MEASUREMENT_PILL_RADIUS,
MEASUREMENT_PILL_RADIUS
)
- r.auxFill.setColor(r.ck.Color4f(MEASUREMENT_COLOR.r, MEASUREMENT_COLOR.g, MEASUREMENT_COLOR.b, 1))
+ r.auxFill.setColorComponents(MEASUREMENT_COLOR.r, MEASUREMENT_COLOR.g, MEASUREMENT_COLOR.b, 1)
canvas.drawRRect(rect, r.auxFill)
r.auxFill.setColor(r.ck.WHITE)
canvas.drawText(
@@ -182,27 +179,9 @@ function drawPill(r: SkiaRenderer, canvas: Canvas, text: string, x: number, y: n
}
function drawTargetOutline(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph, target: SceneNode) {
- const world = getWorldMatrix(target, graph)
- const view = Matrix.multiply(Matrix.translated(r.panX, r.panY), Matrix.scaled(r.zoom, r.zoom))
- const points = Matrix.mapPoints(Matrix.multiply(view, world), [
- 0,
- 0,
- target.width,
- 0,
- target.width,
- target.height,
- 0,
- target.height
- ])
- const path = new r.ck.PathBuilder()
- path.moveTo(points[0], points[1])
- path.lineTo(points[2], points[3])
- path.lineTo(points[4], points[5])
- path.lineTo(points[6], points[7])
- path.close()
- const immutablePath = path.detachAndDelete()
- canvas.drawPath(immutablePath, r.auxStroke)
- immutablePath.delete()
+ outlineNode(r, canvas, graph, target.id, {
+ color: r.ck.Color4f(MEASUREMENT_COLOR.r, MEASUREMENT_COLOR.g, MEASUREMENT_COLOR.b, 1)
+ })
}
export function drawMeasurementSegment(
diff --git a/packages/core/src/canvas/overlays/outline.ts b/packages/core/src/canvas/overlays/outline.ts
index 04147aa6a..191a313a0 100644
--- a/packages/core/src/canvas/overlays/outline.ts
+++ b/packages/core/src/canvas/overlays/outline.ts
@@ -1,9 +1,29 @@
-import type { Canvas, Color, Paint } from 'canvaskit-wasm'
+import type { Canvas, Color, Paint, PathEffect } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { ResourceCache } from '#core/cache/resource'
import type { SkiaRenderer } from '#core/canvas/renderer'
-import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+import type { RotationPreview, SceneGeometry } from '#core/geometry'
+
+/** Dashes drawn each frame, by their on and off lengths at the zoom they were made for. */
+const MAX_CACHED_DASHES = 32
+
+export type DashEffectCache = ResourceCache<string, PathEffect>
+
+export function createDashEffectCache(): DashEffectCache {
+ return new ResourceCache({ maxEntries: MAX_CACHED_DASHES, dispose: (effect) => effect.delete() })
+}
+
+/** A dash of `on` and `off` lengths, kept between frames; the paint it goes on borrows it. */
+export function dashEffect(r: SkiaRenderer, on: number, off: number, phase = 0): PathEffect {
+ const key = `${on},${off},${phase}`
+ const cached = r.dashEffects.get(key)
+ if (cached) return cached
+ const effect = r.ck.PathEffect.MakeDash([on, off], phase)
+ r.dashEffects.set(key, effect)
+ return effect
+}
/** An outline sized in screen pixels, so it looks the same at every zoom. */
export interface ScreenStroke {
@@ -17,25 +37,22 @@ export interface ScreenStroke {
/**
* Draw with the shared stroke paint set to `stroke` at the live zoom. Editor chrome draws this
* way, every frame, in the overlay pass: the scene is cached and scaled while navigating, so
- * anything sized by the zoom must not be drawn there. The paint is reset and the dash freed
- * afterwards, since the paint is shared and a dash is native memory.
+ * anything sized by the zoom must not be drawn there. The paint is reset afterwards, since it is
+ * shared; the dash comes from the renderer's cache, so a frame makes none.
*/
export function withScreenStroke(
r: SkiaRenderer,
stroke: ScreenStroke,
draw: (paint: Paint) => void
): void {
- const dash = stroke.dash
- ? r.ck.PathEffect.MakeDash([stroke.dash[0] / r.zoom, stroke.dash[1] / r.zoom], 0)
- : null
+ const dash = stroke.dash ? dashEffect(r, stroke.dash[0] / r.zoom, stroke.dash[1] / r.zoom) : null
r.auxStroke.setStrokeWidth((stroke.width ?? 1) / r.zoom)
r.auxStroke.setColor(stroke.color)
- r.auxStroke.setPathEffect(dash)
+ if (dash) r.auxStroke.setPathEffect(dash)
try {
draw(r.auxStroke)
} finally {
- r.auxStroke.setPathEffect(null)
- dash?.delete()
+ if (dash) r.auxStroke.setPathEffect(null)
}
}
@@ -43,7 +60,7 @@ export function withScreenStroke(
export function inNodeSpace(
r: SkiaRenderer,
canvas: Canvas,
- geometry: ReturnType<typeof createSceneGeometry>,
+ geometry: SceneGeometry,
node: SceneNode,
draw: () => void
): void {
@@ -67,9 +84,9 @@ export function outlineNode(
): void {
const node = nodeId ? graph.getNode(nodeId) : undefined
if (!node) return
- inNodeSpace(r, canvas, createSceneGeometry(graph, preview), node, () =>
+ inNodeSpace(r, canvas, r.sceneGeometry(graph, preview), node, () =>
withScreenStroke(r, stroke, (paint) =>
- canvas.drawRect(r.ck.LTRBRect(0, 0, node.width, node.height), paint)
+ canvas.drawRect(r.ltrb(0, 0, node.width, node.height), paint)
)
)
}
diff --git a/packages/core/src/canvas/overlays/pixel-grid.ts b/packages/core/src/canvas/overlays/pixel-grid.ts
index 34dc52fc8..67b03bfff 100644
--- a/packages/core/src/canvas/overlays/pixel-grid.ts
+++ b/packages/core/src/canvas/overlays/pixel-grid.ts
@@ -61,7 +61,7 @@ export function drawPixelGrid(r: SkiaRenderer, canvas: Canvas): void {
}
const color = lineColor(r.pageColor)
const step = r.zoom * r.dpr
- const shader = r.pixelGridEffect.makeShader([
+ const uniforms = [
r.panX * r.dpr,
r.panY * r.dpr,
step,
@@ -71,11 +71,16 @@ export function drawPixelGrid(r: SkiaRenderer, canvas: Canvas): void {
color.b,
color.a,
r.dpr
- ])
+ ]
+ // The shader holds only these uniforms, so a hover repaint at the same view reuses it.
+ const key = uniforms.join(',')
+ if (r.pixelGridShader?.key !== key) {
+ r.pixelGridShader?.shader.delete()
+ r.pixelGridShader = { key, shader: r.pixelGridEffect.makeShader(uniforms) }
+ }
// Skia scales a shader by the paint's alpha, which earlier overlays may have left translucent.
r.auxFill.setAlphaf(1)
- r.auxFill.setShader(shader)
+ r.auxFill.setShader(r.pixelGridShader.shader)
canvas.drawRect(r.ck.LTRBRect(0, 0, r.viewportWidth, r.viewportHeight), r.auxFill)
r.auxFill.setShader(null)
- shader.delete()
}
diff --git a/packages/core/src/canvas/overlays/presence.ts b/packages/core/src/canvas/overlays/presence.ts
index 068eb6775..816647dac 100644
--- a/packages/core/src/canvas/overlays/presence.ts
+++ b/packages/core/src/canvas/overlays/presence.ts
@@ -1,11 +1,11 @@
import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph } from '@open-pencil/scene-graph'
-import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import Matrix from '@open-pencil/scene-graph/matrix'
import type { PresenceCursor, SkiaRenderer } from '#core/canvas/renderer'
+import { outlineNode } from './outline'
+
const CURSOR_SIZE = 9
const LABEL_PADDING_X = 4
const LABEL_PADDING_Y = 2
@@ -21,7 +21,7 @@ const LABEL_SPARKLE_GAP = 3
function drawSelection(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph, cursor: PresenceCursor) {
if (!cursor.selection?.length && !cursor.outline?.length) return
const { r: red, g, b } = cursor.color
- r.auxStroke.setColor(r.ck.Color4f(red, g, b, 0.6))
+ r.auxStroke.setColorComponents(red, g, b, 0.6)
r.auxStroke.setStrokeWidth(1.5)
r.auxStroke.setPathEffect(null)
// Outlines of what is not a layer yet, such as JSX an agent is still streaming.
@@ -36,31 +36,9 @@ function drawSelection(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph, curso
r.auxStroke
)
}
- for (const nodeId of cursor.selection ?? []) {
- const node = graph.getNode(nodeId)
- if (!node) continue
- // Map the corners through the node's world matrix, as the shape is rendered, so the
- // box tracks rotation, flips, and parent transforms.
- const corners = Matrix.mapPoints(getWorldMatrix(node, graph), [
- 0,
- 0,
- node.width,
- 0,
- node.width,
- node.height,
- 0,
- node.height
- ])
- const box = new r.ck.PathBuilder()
- box.moveTo(corners[0] * r.zoom + r.panX, corners[1] * r.zoom + r.panY)
- for (let i = 2; i < corners.length; i += 2) {
- box.lineTo(corners[i] * r.zoom + r.panX, corners[i + 1] * r.zoom + r.panY)
- }
- box.close()
- const path = box.detachAndDelete()
- canvas.drawPath(path, r.auxStroke)
- path.delete()
- }
+ // In the layer's own space, so the box tracks rotation, flips, and parent transforms.
+ const box = { color: r.ck.Color4f(red, g, b, 0.6), width: 1.5 }
+ for (const nodeId of cursor.selection ?? []) outlineNode(r, canvas, graph, nodeId, box)
}
function arrowPath(r: SkiaRenderer, x: number, y: number) {
@@ -101,7 +79,7 @@ function drawArrow(r: SkiaRenderer, canvas: Canvas, x: number, y: number, cursor
r.auxStroke.setPathEffect(null)
canvas.drawPath(path, r.auxStroke)
const { r: red, g, b } = cursor.color
- r.auxFill.setColor(r.ck.Color4f(red, g, b, 1))
+ r.auxFill.setColorComponents(red, g, b, 1)
canvas.drawPath(path, r.auxFill)
path.delete()
}
diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.ts
index fb9694a55..b981bd942 100644
--- a/packages/core/src/canvas/overlays/selection.ts
+++ b/packages/core/src/canvas/overlays/selection.ts
@@ -2,9 +2,8 @@ import type { Canvas } from 'canvaskit-wasm'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { layerRotates } from '@open-pencil/scene-graph/generated'
-import { computeBounds, rotatedCorners } from '@open-pencil/scene-graph/geometry'
+import { computeBounds } from '@open-pencil/scene-graph/geometry'
import Matrix from '@open-pencil/scene-graph/matrix'
-import type { Vector } from '@open-pencil/scene-graph/primitives'
import { slotPropertyId } from '@open-pencil/scene-graph/slots'
import { drawConnectorHover, drawConnectorSelection } from '#core/canvas/overlays/connectors'
@@ -13,6 +12,8 @@ import {
HANDLE_HALF_SIZE,
ROTATION_HANDLE_DISTANCE,
CODE_FOCUS_FILL_ALPHA,
+ PARENT_OUTLINE_ALPHA,
+ PARENT_OUTLINE_DASH,
SELECTION_DASH_ALPHA,
SECTION_HOVER_STROKE_WIDTH
} from '#core/constants'
@@ -28,7 +29,7 @@ import {
} from '#core/geometry'
import { pointAtArc, textPathStartArc } from '#core/text/path'
-import { inNodeSpace, outlineNode, withScreenStroke } from './outline'
+import { inNodeSpace, outlineNode, type ScreenStroke, withScreenStroke } from './outline'
/** The dash of faint selection bounds, in screen pixels. */
const SELECTION_DASH = [4, 4] as const
@@ -50,7 +51,7 @@ export function drawHoverHighlight(
r.auxStroke.setColor(r.outlineColor(node, graph))
r.auxStroke.setPathEffect(null)
canvas.save()
- canvas.concat(createSceneGeometry(graph, preview).screenMatrix(node, r))
+ canvas.concat(r.sceneGeometry(graph, preview).screenMatrix(node, r))
r.strokeNodeShape(canvas, node, r.auxStroke)
canvas.restore()
}
@@ -73,7 +74,7 @@ export function drawCodeFocus(
component ? r.compColor(CODE_FOCUS_FILL_ALPHA) : r.selColor(CODE_FOCUS_FILL_ALPHA)
)
const color = component ? r.compColor() : r.selColor()
- inNodeSpace(r, canvas, createSceneGeometry(graph, preview), node, () => {
+ inNodeSpace(r, canvas, r.sceneGeometry(graph, preview), node, () => {
r.strokeNodeShape(canvas, node, r.auxFill)
withScreenStroke(r, { color }, (paint) => r.strokeNodeShape(canvas, node, paint))
})
@@ -249,7 +250,7 @@ function drawTextPathSelection(
box.y,
box.x + box.width,
box.y + box.height,
- rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {
+ rotationHandleLayout(node, r.sceneGeometry(graph, preview), r.zoom, {
x: box.x,
y: box.y,
width: box.width,
@@ -361,7 +362,7 @@ export function drawNodeSelection(
// A generated frame such as a sticky note may stay upright, and a line turns by its ends.
!layerRotates(node) || isLineLike(node)
? null
- : rotationHandleLayout(node, createSceneGeometry(graph, preview), r.zoom, {
+ : rotationHandleLayout(node, r.sceneGeometry(graph, preview), r.zoom, {
x: x1,
y: y1,
width: x2 - x1,
@@ -395,30 +396,15 @@ export function drawParentFrameOutlines(
if (!grandparent || grandparent.type === 'CANVAS') continue
drawn.add(parent.id)
+ outlineNode(r, canvas, graph, parent.id, parentOutline(r), preview)
+ }
+}
- const m = createSceneGeometry(graph, preview).screenMatrix(parent, r)
-
- const pts = Matrix.mapPoints(m, [
- 0,
- 0,
- parent.width,
- 0,
- parent.width,
- parent.height,
- 0,
- parent.height
- ])
-
- const path = new r.ck.PathBuilder()
- path.moveTo(pts[0], pts[1])
- path.lineTo(pts[2], pts[3])
- path.lineTo(pts[4], pts[5])
- path.lineTo(pts[6], pts[7])
- path.close()
-
- const immutablePath = path.detachAndDelete()
- canvas.drawPath(immutablePath, r.parentOutlinePaint)
- immutablePath.delete()
+/** The dashed outline of a selected layer's parent, in the selection colour, faded. */
+function parentOutline(r: SkiaRenderer): ScreenStroke {
+ return {
+ color: r.selColor(PARENT_OUTLINE_ALPHA),
+ dash: [PARENT_OUTLINE_DASH, PARENT_OUTLINE_DASH]
}
}
@@ -440,7 +426,7 @@ export function drawGroupBounds(
graph: SceneGraph,
preview?: RotationPreview | null
): void {
- const geometry = createSceneGeometry(graph, preview)
+ const geometry = r.sceneGeometry(graph, preview)
const bounds = computeBounds(nodes.map(geometry.bounds))
const [minX, minY, maxX, maxY] = Matrix.mapPoints(viewportMatrix(r), [
bounds.x,
@@ -455,14 +441,6 @@ export function drawGroupBounds(
drawBoundsHandlesScreenSpace(r, canvas, minX, minY, maxX, maxY)
}
-export function getRotatedCorners(r: SkiaRenderer, n: SceneNode, abs: Vector): Vector[] {
- const cx = (abs.x + n.width / 2) * r.zoom + r.panX
- const cy = (abs.y + n.height / 2) * r.zoom + r.panY
- const hw = (n.width / 2) * r.zoom
- const hh = (n.height / 2) * r.zoom
- return rotatedCorners(cx, cy, hw, hh, n.rotation)
-}
-
export function drawHandle(r: SkiaRenderer, canvas: Canvas, x: number, y: number): void {
r.auxFill.setColor(r.ck.WHITE)
const s = HANDLE_HALF_SIZE / r.zoom
diff --git a/packages/core/src/canvas/overlays/shape-handles.ts b/packages/core/src/canvas/overlays/shape-handles.ts
index 50fdd866d..8867447e0 100644
--- a/packages/core/src/canvas/overlays/shape-handles.ts
+++ b/packages/core/src/canvas/overlays/shape-handles.ts
@@ -15,7 +15,6 @@ import {
SHAPE_HANDLE,
shapeHandleLayout,
shapeHandleValue,
- createSceneGeometry,
type RotationPreview
} from '#core/geometry'
@@ -36,7 +35,7 @@ export function drawShapeHandles(
if (!hover || selectedIds.size !== 1 || !selectedIds.has(hover.nodeId)) return
const node = graph.getNode(hover.nodeId)
if (!node) return
- const handles = shapeHandleLayout(node, createSceneGeometry(graph, preview), r)
+ const handles = shapeHandleLayout(node, r.sceneGeometry(graph, preview), r)
if (!handles) return
const color = r.outlineColor(node, graph)
const fill = r.auxFill
diff --git a/packages/core/src/canvas/overlays/slots.ts b/packages/core/src/canvas/overlays/slots.ts
index b0b760778..d4ca682d2 100644
--- a/packages/core/src/canvas/overlays/slots.ts
+++ b/packages/core/src/canvas/overlays/slots.ts
@@ -5,7 +5,7 @@ import { instanceSlotFrames, slotPropertyId } from '@open-pencil/scene-graph/slo
import type { SkiaRenderer } from '#core/canvas/renderer'
import { SLOT_EMPTY_FILL_ALPHA } from '#core/constants'
-import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+import { type RotationPreview } from '#core/geometry'
import { inNodeSpace, withScreenStroke } from './outline'
@@ -50,7 +50,7 @@ export function drawSlotOutlines(
if (hoveredNodeId) slots.delete(hoveredNodeId)
if (slots.size === 0) return
- const geometry = createSceneGeometry(graph, preview)
+ const geometry = r.sceneGeometry(graph, preview)
r.auxFill.setColor(r.slotColor(SLOT_EMPTY_FILL_ALPHA))
withScreenStroke(r, { color: r.slotColor(), dash: [SLOT_DASH, SLOT_DASH] }, (paint) => {
for (const frame of slots.values()) {
diff --git a/packages/core/src/canvas/overlays/text-edit.ts b/packages/core/src/canvas/overlays/text-edit.ts
index 5d19e45ed..556d3ad82 100644
--- a/packages/core/src/canvas/overlays/text-edit.ts
+++ b/packages/core/src/canvas/overlays/text-edit.ts
@@ -64,7 +64,7 @@ export function drawTextEditOverlay(
const caret = editor.getCaretRect()
if (caret) {
const color = textCaretColor(node, editor.caretIndex ?? 0)
- r.auxFill.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.auxFill.setColorComponents(color.r, color.g, color.b, color.a)
const w = TEXT_CARET_WIDTH / r.zoom
canvas.drawRect(
r.ck.LTRBRect(caret.x - w / 2, caret.y0, caret.x + w / 2, caret.y1),
@@ -118,7 +118,7 @@ function drawPathTextCaret(
if (!caret) return
r.auxStroke.setStrokeWidth(TEXT_CARET_WIDTH / r.zoom)
const color = textCaretColor(node, editor.caretIndex ?? 0)
- r.auxStroke.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.auxStroke.setColorComponents(color.r, color.g, color.b, color.a)
r.auxStroke.setPathEffect(null)
canvas.drawLine(caret.from.x, caret.from.y, caret.to.x, caret.to.y, r.auxStroke)
}
diff --git a/packages/core/src/canvas/pen-overlay.ts b/packages/core/src/canvas/pen-overlay.ts
index 932f8ba17..cebf62003 100644
--- a/packages/core/src/canvas/pen-overlay.ts
+++ b/packages/core/src/canvas/pen-overlay.ts
@@ -179,7 +179,7 @@ export function drawPencilOverlay(
for (const point of rest) path.lineTo(point.x * r.zoom + r.panX, point.y * r.zoom + r.panY)
const { color, weight } = pencilState.preview
const paint = r.pencilStrokePaint
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ paint.setColorComponents(color.r, color.g, color.b, color.a)
paint.setStrokeWidth(weight * r.zoom)
const stroke = path.detachAndDelete()
canvas.drawPath(stroke, paint)
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 48a47c831..522938f28 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -22,18 +22,24 @@ import type { EditorState } from '#core/editor/types'
import { RenderProfiler } from '#core/profiler'
import type { FontResolutionSnapshot } from '#core/text/resolver'
+import { createImageFilterCache, createMaskFilterCache } from './effects'
import { createImageCache } from './images/cache'
import { ImagePreviewCache } from './images/previews'
import { LabelCache } from './labels/cache'
import * as LabelHitTest from './labels/hit-test'
import { LabelParagraphCache } from './labels/paragraph-cache'
import { labelHitOptions } from './labels/style'
+import { createDashEffectCache } from './overlays/outline'
import { NodePathCaches } from './paths/cache'
import * as RenderColors from './renderer/colors'
import * as RendererFonts from './renderer/fonts'
import { destroyRenderer, releaseLiveImages } from './renderer/lifecycle'
import { installRendererDomainMethods, type RendererDomainMethods } from './renderer/methods'
-import { initializeRendererPaints, initializeSelectionPaintColors } from './renderer/paints'
+import {
+ initializeRendererPaints,
+ initializeRulerPaintColors,
+ initializeSelectionPaintColors
+} from './renderer/paints'
import * as RenderPipeline from './renderer/pipeline'
import type { SceneBacking, SceneBackingBuild } from './renderer/retained-backing/types'
import * as RendererState from './renderer/state'
@@ -56,16 +62,16 @@ import type {
Blender,
Paint,
Font,
- FontMgr,
TypefaceFontProvider,
SkPicture,
- ImageFilter,
- MaskFilter,
RuntimeEffect,
+ Shader,
Image,
TextureSource
} from 'canvaskit-wasm'
+import { createSceneGeometry, type RotationPreview, type SceneGeometry } from '#core/geometry'
+
export interface SubtreePictureCacheEntry {
picture: SkPicture
pageId: string | null
@@ -81,6 +87,7 @@ export interface PendingFontNode {
import type { PlacedIssueMarker } from './issues/types'
import type { PlacedStatusLabel } from './labels/status'
+import type { NodeEditPaints } from './node-edit-overlay'
import { EffectRasterCache } from './renderer/effect-raster-cache'
import { TiledSceneController } from './renderer/tiles'
import type { TransientCanvasPreview } from './renderer/transient-previews'
@@ -107,14 +114,29 @@ export class SkiaRenderer {
linearDodgeBlender: Blender | null = null
declare strokePaint: Paint
declare selectionPaint: Paint
- declare parentOutlinePaint: Paint
declare snapPaint: Paint
declare auxFill: Paint
declare auxStroke: Paint
declare opacityPaint: Paint
declare effectLayerPaint: Paint
- imageFilterCache = new Map<string, ImageFilter | null>()
- maskFilterCache = new Map<number, MaskFilter | null>()
+ /** Whether the shared fill and stroke paints carry a shader, so clearing one is a call only when needed. */
+ fillPaintShaded = false
+ strokePaintShaded = false
+ /** Dashes the overlay pass draws with, kept between frames. */
+ readonly dashEffects = createDashEffectCache()
+ /** Label widths by font and text, so chrome measures a label once. */
+ readonly glyphWidths = new WeakMap<Font, Map<string, number>>()
+ /** The pixel grid's shader, kept while its uniforms hold. */
+ pixelGridShader: { key: string; shader: Shader } | null = null
+ /** Scene geometry shared by everything drawn in one frame; `pipeline` starts each frame afresh. */
+ frameGeometry: {
+ graph: SceneGraph
+ preview: RotationPreview | null
+ geometry: SceneGeometry
+ } | null = null
+ private readonly colors = new Map<string, Float32Array>()
+ imageFilterCache = createImageFilterCache()
+ maskFilterCache = createMaskFilterCache()
_tmpColor = new Float32Array(4)
_tmpRect = new Float32Array(4)
textFont: Font | null = null
@@ -124,7 +146,6 @@ export class SkiaRenderer {
valueFont: Font | null = null
sectionTitleFont: Font | null = null
componentLabelFont: Font | null = null
- fontMgr: FontMgr | null = null
fontProvider: TypefaceFontProvider | null = null
fontsLoaded = false
fontGeneration = 0
@@ -148,6 +169,14 @@ export class SkiaRenderer {
this.decodedPreviewHashes.add(hash)
this.onImagePreviewReady?.(hash)
})
+ /**
+ * Device pixels per world unit the drawing in progress is for: the viewport's scale in a frame,
+ * a tile's level while it records. Image previews are chosen at this detail, so a picture that
+ * drew them is recorded again when a finer tile asks for more.
+ */
+ imageDetailScale = 1
+ /** Whether the drawing in progress drew an image preview; chunk pictures note it to re-record. */
+ previewsDrawn = false
/** Nodes whose image fills drew each image while previews were on, for redrawing them sharper. */
readonly imageFillUsers = new Map<string, Set<string>>()
/** Images whose sharper preview has decoded since the last frame. */
@@ -222,6 +251,7 @@ export class SkiaRenderer {
declare penHandlePaint: Paint
declare penVertexFill: Paint
declare penVertexStroke: Paint
+ declare nodeEditPaints: NodeEditPaints
panX = 0
panY = 0
@@ -247,7 +277,6 @@ export class SkiaRenderer {
_nodeCount = 0
_culledCount = 0
_flashes: Array<{ nodeId: string; startTime: number }> = []
- _flashPaint: Paint | null = null
_aiActiveNodes: Set<string> = new Set()
_aiDoneFlashes: Array<{ nodeId: string; startTime: number }> = []
@@ -265,7 +294,6 @@ export class SkiaRenderer {
declare drawParentFrameOutlines: RendererDomainMethods['drawParentFrameOutlines']
declare drawNodeOutline: RendererDomainMethods['drawNodeOutline']
declare drawGroupBounds: RendererDomainMethods['drawGroupBounds']
- declare getRotatedCorners: RendererDomainMethods['getRotatedCorners']
declare drawHandle: RendererDomainMethods['drawHandle']
declare drawSnapGuides: RendererDomainMethods['drawSnapGuides']
declare drawSnapMarks: RendererDomainMethods['drawSnapMarks']
@@ -331,29 +359,65 @@ export class SkiaRenderer {
return rc
}
+ /** A colour the chrome draws with every frame, allocated once per theme; callers do not write to it. */
+ private cachedColor(key: string, r: number, g: number, b: number, a: number): Float32Array {
+ const cached = this.colors.get(key)
+ if (cached) return cached
+ const color = this.ck.Color4f(r, g, b, a)
+ this.colors.set(key, color)
+ return color
+ }
+
selColor(alpha = 1) {
const { r, g, b } = this.selectionTheme.color
- return this.ck.Color4f(r, g, b, alpha)
+ return this.cachedColor(`sel:${alpha}`, r, g, b, alpha)
}
selForegroundColor() {
const { r, g, b } = this.selectionTheme.foreground
- return this.ck.Color4f(r, g, b, 1)
+ return this.cachedColor('selfg', r, g, b, 1)
}
/** Switches selection chrome to `theme`, repainting the paints that keep it between frames. */
setSelectionTheme(theme: SelectionTheme = DEFAULT_SELECTION_THEME): void {
if (isEqual(theme, this.selectionTheme)) return
this.selectionTheme = { color: { ...theme.color }, foreground: { ...theme.foreground } }
+ this.colors.clear()
initializeSelectionPaintColors(this)
}
+ /** Recolours the ruler paints when the theme changes, rather than on every frame. */
+ setRulerTheme(theme: RulerTheme | null): void {
+ if (isEqual(theme, this.rulerTheme)) return
+ this.rulerTheme = theme
+ initializeRulerPaintColors(this)
+ }
+
+ /** The geometry of this frame, shared by every overlay that draws from the graph. */
+ sceneGeometry(graph: SceneGraph, preview?: RotationPreview | null): SceneGeometry {
+ const current = this.frameGeometry
+ // A caller that knows no preview takes the frame's geometry as it stands, previewed or not:
+ // a flash follows the layer where it is shown, and the frame keeps one geometry.
+ if (current?.graph === graph && (preview === undefined || current.preview === preview)) {
+ return current.geometry
+ }
+ const geometry = createSceneGeometry(graph, preview)
+ this.frameGeometry = { graph, preview: preview ?? null, geometry }
+ return geometry
+ }
+
compColor(alpha = 1) {
- return this.ck.Color4f(COMPONENT_COLOR.r, COMPONENT_COLOR.g, COMPONENT_COLOR.b, alpha)
+ return this.cachedColor(
+ `comp:${alpha}`,
+ COMPONENT_COLOR.r,
+ COMPONENT_COLOR.g,
+ COMPONENT_COLOR.b,
+ alpha
+ )
}
slotColor(alpha = 1) {
- return this.ck.Color4f(SLOT_COLOR.r, SLOT_COLOR.g, SLOT_COLOR.b, alpha)
+ return this.cachedColor(`slot:${alpha}`, SLOT_COLOR.r, SLOT_COLOR.g, SLOT_COLOR.b, alpha)
}
/**
@@ -499,11 +563,30 @@ export class SkiaRenderer {
if (node.type === 'TEXT') {
this.invalidateNodePicture(id)
this.tiledScene.invalidateNode(id, graph)
+ this.invalidateBooleanAncestors(graph, node)
}
pending.push(...node.childIds)
}
}
+ /**
+ * A boolean operation keeps its result between draws, and a text operand whose outline waited
+ * for its font gave it none: the fonts arriving drop the results of the operations above.
+ */
+ private invalidateBooleanAncestors(graph: SceneGraph, node: SceneNode): void {
+ const seen = new Set<string>()
+ let parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ while (parent && !seen.has(parent.id)) {
+ seen.add(parent.id)
+ if (parent.type === 'BOOLEAN_OPERATION') {
+ this.invalidateVectorPath(parent.id)
+ this.invalidateNodePicture(parent.id)
+ this.tiledScene.invalidateNode(parent.id, graph)
+ }
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
+ }
+ }
+
invalidateAllPictures(): void {
RendererState.invalidateAllPictures(this)
}
@@ -534,7 +617,10 @@ export class SkiaRenderer {
const image = source && this.surface.makeImageFromTextureSource(textureSource(source))
if (image) this.liveImages.set(hash, { image, surface: this.surface })
}
- for (const id of nodeIds) this.invalidateNodePicture(id)
+ for (const id of nodeIds) {
+ this.invalidateNodePicture(id)
+ this.tiledScene.invalidateNode(id)
+ }
return this.liveImages.has(hash)
}
@@ -550,6 +636,13 @@ export class SkiaRenderer {
this.invalidateAllPictures()
}
+ /** Forgets a layer that left the document: its drawing and the fonts it was waiting for. */
+ forgetNode(nodeId: string): void {
+ this.pendingFontNodes.delete(nodeId)
+ this.textPictureGenerations.delete(nodeId)
+ this.invalidateNodePicture(nodeId)
+ }
+
/** Drops `nodeId`'s cached drawing; `changedKeys`, when known, lets text keep its glyph coverage. */
invalidateNodePicture(nodeId: string, changedKeys?: readonly (keyof SceneNode)[]): void {
RendererState.invalidateNodePicture(this, nodeId, changedKeys)
@@ -684,8 +777,25 @@ export class SkiaRenderer {
return RenderText.measureTextNode(this, node, maxWidth)
}
+ /** Readiness of a text's fonts, found once per layer per font generation; a change to the layer drops it. */
+ readonly textReadiness = new Map<
+ string,
+ { node: SceneNode; generation: number; readiness: RenderText.NodeFontReadiness }
+ >()
+
nodeFontReadiness(node: SceneNode): RenderText.NodeFontReadiness {
- return RenderText.nodeFontReadiness(this, node)
+ if (node.type !== 'TEXT') return 'ready'
+ const cached = this.textReadiness.get(node.id)
+ if (cached?.node === node && cached.generation === this.fontGeneration) {
+ return cached.readiness
+ }
+ const readiness = RenderText.nodeFontReadiness(this, node)
+ // A text waiting on a demand another text raised is told nothing when that demand settles,
+ // so a pending reading is asked again each frame until the fonts arrive or give up.
+ if (readiness !== 'pending') {
+ this.textReadiness.set(node.id, { node, generation: this.fontGeneration, readiness })
+ }
+ return readiness
}
isNodeFontLoaded(node: SceneNode): boolean {
diff --git a/packages/core/src/canvas/renderer/chunks/build.ts b/packages/core/src/canvas/renderer/chunks/build.ts
new file mode 100644
index 000000000..4942ce7ea
--- /dev/null
+++ b/packages/core/src/canvas/renderer/chunks/build.ts
@@ -0,0 +1,203 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'
+import { computeDescendantVisualBounds, type VisualBounds } from '@open-pencil/scene-graph/geometry'
+import type { Mat3 } from '@open-pencil/scene-graph/matrix'
+import Matrix from '@open-pencil/scene-graph/matrix'
+
+import { worldNodeVisualBounds } from '#core/canvas/renderer/visual-bounds'
+import { nodeHasRadius, nodeHasSmoothCorners } from '#core/canvas/shapes'
+
+export type RenderChunkKind = 'self' | 'subtree'
+
+export interface RenderChunkContext {
+ parentTransform: Mat3
+ /**
+ * The world box left by every clipping ancestor that is only translated and square-cornered,
+ * the usual frame, so a record clips to it with one call; null when none clips so.
+ */
+ clipRect: VisualBounds | null
+ /** Clipping ancestors that are rotated, flipped, scaled, or rounded, clipped under their matrix. */
+ ancestorClipIds: string[]
+}
+
+export interface RenderChunk {
+ id: string
+ nodeId: string
+ kind: RenderChunkKind
+ context: RenderChunkContext
+ interruptible: boolean
+ /** Draw order across the page: the page child's position, then the order within its subtree. */
+ painterOrder: number
+ /** The page child whose subtree holds the chunk; a structural edit rebuilds that subtree alone. */
+ topId: string
+ localOrder: number
+ minX: number
+ minY: number
+ maxX: number
+ maxY: number
+ nodeCount: number
+ estimatedCost: number
+}
+
+export interface RenderChunkBuildStats {
+ nodesVisited: number
+ chunksBuilt: number
+ maximumChunkNodes: number
+ maximumAtomicChunkNodes: number
+ oversizedAtomicChunks: number
+}
+
+export const MAX_CHUNK_NODES = 32
+/** Painter orders of one page child's chunks fit under those of the next. */
+export const PAINTER_ORDER_SPAN = 2 ** 24
+
+export function painterOrderOf(topIndex: number, localOrder: number): number {
+ return topIndex * PAINTER_ORDER_SPAN + localOrder
+}
+
+export function nodeRequiresAtomicChunk(graph: SceneGraph, node: SceneNode): boolean {
+ const isolated =
+ node.opacity < 1 ||
+ (node.blendMode !== 'NORMAL' && node.blendMode !== 'PASS_THROUGH') ||
+ node.effects.some(
+ (effect) =>
+ effect.visible &&
+ (effect.type === 'LAYER_BLUR' ||
+ effect.type === 'FOREGROUND_BLUR' ||
+ effect.type === 'BACKGROUND_BLUR')
+ )
+ const hasMasks = node.childIds.some((childId) => graph.getNode(childId)?.isMask === true)
+ return isolated || hasMasks
+}
+
+export function shouldSplit(graph: SceneGraph, node: SceneNode, descendantCount: number): boolean {
+ return (
+ node.childIds.length > 0 &&
+ descendantCount > MAX_CHUNK_NODES &&
+ !nodeRequiresAtomicChunk(graph, node)
+ )
+}
+
+export function estimateCost(nodeCount: number, node: SceneNode): number {
+ const visibleEffects = node.effects.filter((effect) => effect.visible).length
+ return nodeCount + visibleEffects * 8
+}
+
+export function subtreeBounds(graph: SceneGraph, nodeId: string) {
+ return computeDescendantVisualBounds(
+ [nodeId],
+ (id) => graph.getNode(id),
+ (id) => graph.getAbsolutePosition(id)
+ )
+}
+
+/** One walk from the root composes the parent's transform and gathers the clips on the way. */
+export function chunkContext(graph: SceneGraph, node: SceneNode): RenderChunkContext {
+ const chain: SceneNode[] = []
+ let parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ while (parent) {
+ chain.push(parent)
+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
+ }
+ let matrix = Matrix.identity()
+ let clipRect: VisualBounds | null = null
+ const ancestorClipIds: string[] = []
+ for (let index = chain.length - 1; index >= 0; index--) {
+ const ancestor = chain[index]
+ matrix = Matrix.multiply(matrix, getNodeLocalMatrix(ancestor))
+ if (!ancestor.clipsContent) continue
+ const translated = matrix[0] === 1 && matrix[1] === 0 && matrix[3] === 0 && matrix[4] === 1
+ if (translated && !nodeHasRadius(ancestor) && !nodeHasSmoothCorners(ancestor)) {
+ const box = {
+ minX: matrix[2],
+ minY: matrix[5],
+ maxX: matrix[2] + ancestor.width,
+ maxY: matrix[5] + ancestor.height
+ }
+ clipRect = clipRect
+ ? {
+ minX: Math.max(clipRect.minX, box.minX),
+ minY: Math.max(clipRect.minY, box.minY),
+ maxX: Math.min(clipRect.maxX, box.maxX),
+ maxY: Math.min(clipRect.maxY, box.maxY)
+ }
+ : box
+ } else {
+ ancestorClipIds.push(ancestor.id)
+ }
+ }
+ return { parentTransform: matrix, clipRect, ancestorClipIds }
+}
+
+export function countDescendants(graph: SceneGraph, nodeIds: string[]) {
+ const counts = new Map<string, number>()
+ let visited = 0
+ const stack: Array<{ nodeId: string; expanded: boolean }> = nodeIds.map((nodeId) => ({
+ nodeId,
+ expanded: false
+ }))
+ while (stack.length > 0) {
+ const entry = stack.pop()
+ if (!entry) continue
+ const node = graph.getNode(entry.nodeId)
+ if (!node?.visible) continue
+ if (!entry.expanded) {
+ visited++
+ stack.push({ nodeId: entry.nodeId, expanded: true })
+ for (const childId of node.childIds) stack.push({ nodeId: childId, expanded: false })
+ continue
+ }
+ let count = 1
+ for (const childId of node.childIds) count += counts.get(childId) ?? 0
+ counts.set(node.id, count)
+ }
+ return { counts, visited }
+}
+
+/**
+ * The chunks of `rootId`'s subtree in draw order, each numbered by `order` from its position in
+ * that order; `topId` is the page child the subtree lies under.
+ */
+export function buildChunks(
+ graph: SceneGraph,
+ rootId: string,
+ topId: string,
+ topIndex: number,
+ counts: Map<string, number>
+) {
+ const chunks: RenderChunk[] = []
+ let position = 0
+ const stack = [rootId]
+ while (stack.length > 0) {
+ const nodeId = stack.pop()
+ if (!nodeId) continue
+ const node = graph.getNode(nodeId)
+ if (!node?.visible) continue
+ const descendantCount = counts.get(nodeId) ?? 1
+ const split = shouldSplit(graph, node, descendantCount)
+ const kind: RenderChunkKind = split ? 'self' : 'subtree'
+ const bounds = split ? worldNodeVisualBounds(graph, node) : subtreeBounds(graph, nodeId)
+ if (bounds) {
+ const nodeCount = split ? 1 : descendantCount
+ chunks.push({
+ id: `${nodeId}:${kind}`,
+ nodeId,
+ kind,
+ context: chunkContext(graph, node),
+ interruptible: split || !nodeRequiresAtomicChunk(graph, node),
+ painterOrder: painterOrderOf(topIndex, position),
+ topId,
+ localOrder: position++,
+ ...bounds,
+ nodeCount,
+ estimatedCost: estimateCost(nodeCount, node)
+ })
+ }
+ if (!split) continue
+ for (let childIndex = node.childIds.length - 1; childIndex >= 0; childIndex--) {
+ const childId = node.childIds[childIndex]
+ if (childId) stack.push(childId)
+ }
+ }
+ return chunks
+}
diff --git a/packages/core/src/canvas/renderer/chunks/cache.ts b/packages/core/src/canvas/renderer/chunks/cache.ts
index 666ebc293..2021ff17a 100644
--- a/packages/core/src/canvas/renderer/chunks/cache.ts
+++ b/packages/core/src/canvas/renderer/chunks/cache.ts
@@ -10,27 +10,49 @@ import { recordRenderChunk } from './record'
interface CachedChunkPicture {
picture: SkPicture
fontGeneration: number
+ /** The detail the picture's image previews were chosen for; none when it drew no preview. */
+ previewDetail: number | null
+}
+
+/** Read after recording, through a call, so the flag reset before it is not taken as final. */
+function drewPreviews(renderer: Pick<SkiaRenderer, 'previewsDrawn'>): boolean {
+ return renderer.previewsDrawn
}
export class RenderChunkPictureCache {
private readonly entries = new Map<string, CachedChunkPicture>()
+ /**
+ * A picture holds for the renderer's fonts, and, when it drew image previews, for a detail no
+ * finer than it was recorded at: a tile two levels in asks for sharper previews than one
+ * recorded at a page's fit zoom, and gets them recorded again.
+ */
+ private current(renderer: SkiaRenderer, cached: CachedChunkPicture | undefined): boolean {
+ return (
+ cached !== undefined &&
+ cached.fontGeneration === renderer.fontGeneration &&
+ (cached.previewDetail === null || cached.previewDetail >= renderer.imageDetailScale)
+ )
+ }
+
get(renderer: SkiaRenderer, graph: SceneGraph, chunk: RenderChunk): SkPicture {
const cached = this.entries.get(chunk.id)
- if (cached?.fontGeneration === renderer.fontGeneration) return cached.picture
+ if (cached && this.current(renderer, cached)) return cached.picture
cached?.picture.delete()
this.entries.delete(chunk.id)
+ renderer.previewsDrawn = false
const recorded = recordRenderChunk(renderer, graph, chunk)
this.entries.set(chunk.id, {
picture: recorded.picture,
- fontGeneration: renderer.fontGeneration
+ fontGeneration: renderer.fontGeneration,
+ previewDetail: drewPreviews(renderer) ? renderer.imageDetailScale : null
})
return recorded.picture
}
- /** Whether `chunk`'s picture is recorded for the renderer's current fonts. */
+ /** Whether `chunk`'s picture is recorded for the renderer's current fonts and detail. */
has(renderer: SkiaRenderer, chunk: RenderChunk): boolean {
- return this.entries.get(chunk.id)?.fontGeneration === renderer.fontGeneration
+ return this.current(renderer, this.entries.get(chunk.id))
}
invalidate(chunkId: string): void {
diff --git a/packages/core/src/canvas/renderer/chunks/index.ts b/packages/core/src/canvas/renderer/chunks/index.ts
index a980fa46b..6d3f52eb2 100644
--- a/packages/core/src/canvas/renderer/chunks/index.ts
+++ b/packages/core/src/canvas/renderer/chunks/index.ts
@@ -1,165 +1,38 @@
import RBush from 'rbush'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'
-import type { Mat3 } from '@open-pencil/scene-graph/matrix'
-import Matrix from '@open-pencil/scene-graph/matrix'
import { worldNodeVisualBounds } from '#core/canvas/renderer/visual-bounds'
-export type RenderChunkKind = 'self' | 'subtree'
+import {
+ buildChunks,
+ chunkContext,
+ countDescendants,
+ MAX_CHUNK_NODES,
+ PAINTER_ORDER_SPAN,
+ painterOrderOf,
+ type RenderChunk,
+ type RenderChunkBuildStats,
+ subtreeBounds
+} from './build'
-export interface RenderChunkContext {
- parentTransform: Mat3
- ancestorClipIds: string[]
-}
-
-export interface RenderChunk {
- id: string
- nodeId: string
- kind: RenderChunkKind
- context: RenderChunkContext
- interruptible: boolean
- painterOrder: number
- minX: number
- minY: number
- maxX: number
- maxY: number
- nodeCount: number
- estimatedCost: number
-}
-
-export interface RenderChunkBuildStats {
- nodesVisited: number
- chunksBuilt: number
- maximumChunkNodes: number
- maximumAtomicChunkNodes: number
- oversizedAtomicChunks: number
-}
-
-const MAX_CHUNK_NODES = 32
-
-export function nodeRequiresAtomicChunk(graph: SceneGraph, node: SceneNode): boolean {
- const isolated =
- node.opacity < 1 ||
- (node.blendMode !== 'NORMAL' && node.blendMode !== 'PASS_THROUGH') ||
- node.effects.some(
- (effect) =>
- effect.visible &&
- (effect.type === 'LAYER_BLUR' ||
- effect.type === 'FOREGROUND_BLUR' ||
- effect.type === 'BACKGROUND_BLUR')
- )
- const hasMasks = node.childIds.some((childId) => graph.getNode(childId)?.isMask === true)
- return isolated || hasMasks
-}
-
-function shouldSplit(graph: SceneGraph, node: SceneNode, descendantCount: number): boolean {
- return (
- node.childIds.length > 0 &&
- descendantCount > MAX_CHUNK_NODES &&
- !nodeRequiresAtomicChunk(graph, node)
- )
-}
-
-function estimateCost(nodeCount: number, node: SceneNode): number {
- const visibleEffects = node.effects.filter((effect) => effect.visible).length
- return nodeCount + visibleEffects * 8
-}
-
-function subtreeBounds(graph: SceneGraph, nodeId: string) {
- return computeDescendantVisualBounds(
- [nodeId],
- (id) => graph.getNode(id),
- (id) => graph.getAbsolutePosition(id)
- )
-}
-
-function clipAncestorIds(graph: SceneGraph, node: SceneNode): string[] {
- const ids: string[] = []
- let parent = node.parentId ? graph.getNode(node.parentId) : undefined
- while (parent) {
- if (parent.clipsContent) ids.unshift(parent.id)
- parent = parent.parentId ? graph.getNode(parent.parentId) : undefined
- }
- return ids
-}
-
-function chunkContext(graph: SceneGraph, node: SceneNode): RenderChunkContext {
- const parent = node.parentId ? graph.getNode(node.parentId) : undefined
- return {
- parentTransform: parent ? getWorldMatrix(parent, graph) : Matrix.identity(),
- ancestorClipIds: clipAncestorIds(graph, node)
- }
-}
-
-function countDescendants(graph: SceneGraph, nodeIds: string[]) {
- const counts = new Map<string, number>()
- let visited = 0
- const stack: Array<{ nodeId: string; expanded: boolean }> = nodeIds.map((nodeId) => ({
- nodeId,
- expanded: false
- }))
- while (stack.length > 0) {
- const entry = stack.pop()
- if (!entry) continue
- const node = graph.getNode(entry.nodeId)
- if (!node?.visible) continue
- if (!entry.expanded) {
- visited++
- stack.push({ nodeId: entry.nodeId, expanded: true })
- for (const childId of node.childIds) stack.push({ nodeId: childId, expanded: false })
- continue
- }
- let count = 1
- for (const childId of node.childIds) count += counts.get(childId) ?? 0
- counts.set(node.id, count)
- }
- return { counts, visited }
-}
-
-function buildChunks(graph: SceneGraph, nodeIds: string[], counts: Map<string, number>) {
- const chunks: RenderChunk[] = []
- let painterOrder = 0
- const stack = [...nodeIds].reverse()
- while (stack.length > 0) {
- const nodeId = stack.pop()
- if (!nodeId) continue
- const node = graph.getNode(nodeId)
- if (!node?.visible) continue
- const descendantCount = counts.get(nodeId) ?? 1
- const split = shouldSplit(graph, node, descendantCount)
- const kind: RenderChunkKind = split ? 'self' : 'subtree'
- const bounds = split ? worldNodeVisualBounds(graph, node) : subtreeBounds(graph, nodeId)
- if (bounds) {
- const nodeCount = split ? 1 : descendantCount
- chunks.push({
- id: `${nodeId}:${kind}`,
- nodeId,
- kind,
- context: chunkContext(graph, node),
- interruptible: split || !nodeRequiresAtomicChunk(graph, node),
- painterOrder: painterOrder++,
- ...bounds,
- nodeCount,
- estimatedCost: estimateCost(nodeCount, node)
- })
- }
- if (!split) continue
- for (let childIndex = node.childIds.length - 1; childIndex >= 0; childIndex--) {
- const childId = node.childIds[childIndex]
- if (childId) stack.push(childId)
- }
- }
- return chunks
-}
+export { nodeRequiresAtomicChunk } from './build'
+export type {
+ RenderChunk,
+ RenderChunkBuildStats,
+ RenderChunkContext,
+ RenderChunkKind
+} from './build'
export class RenderChunkIndex {
private readonly tree = new RBush<RenderChunk>()
private readonly chunks = new Map<string, RenderChunk>()
private readonly chunkIdsByNode = new Map<string, Set<string>>()
private readonly chunkIdsByDependency = new Map<string, Set<string>>()
+ private readonly dependenciesByChunk = new Map<string, string[]>()
+ private readonly chunkIdsByTop = new Map<string, Set<string>>()
+ /** The bounds of every chunk, computed when asked and dropped when the chunks change. */
+ private cachedBounds: Pick<RenderChunk, 'minX' | 'minY' | 'maxX' | 'maxY'> | null | undefined
static build(
graph: SceneGraph,
@@ -181,7 +54,9 @@ export class RenderChunkIndex {
}
const { counts, visited } = countDescendants(graph, page.childIds)
- const chunks = buildChunks(graph, page.childIds, counts)
+ const chunks = page.childIds.flatMap((topId, topIndex) =>
+ buildChunks(graph, topId, topId, topIndex, counts)
+ )
index.bulkLoad(chunks, graph)
return {
index,
@@ -201,22 +76,312 @@ export class RenderChunkIndex {
}
bulkLoad(chunks: RenderChunk[], graph?: SceneGraph): void {
- this.tree.clear()
- this.chunks.clear()
- this.chunkIdsByNode.clear()
- this.chunkIdsByDependency.clear()
+ this.dispose()
this.tree.load(chunks)
- for (const chunk of chunks) {
- this.chunks.set(chunk.id, chunk)
- const ids = this.chunkIdsByNode.get(chunk.nodeId) ?? new Set<string>()
- ids.add(chunk.id)
- this.chunkIdsByNode.set(chunk.nodeId, ids)
- if (graph) this.indexDependencies(graph, chunk)
+ for (const chunk of chunks) this.register(chunk, graph)
+ }
+
+ private register(chunk: RenderChunk, graph?: SceneGraph): void {
+ this.chunks.set(chunk.id, chunk)
+ const ids = this.chunkIdsByNode.get(chunk.nodeId) ?? new Set<string>()
+ ids.add(chunk.id)
+ this.chunkIdsByNode.set(chunk.nodeId, ids)
+ const topIds = this.chunkIdsByTop.get(chunk.topId) ?? new Set<string>()
+ topIds.add(chunk.id)
+ this.chunkIdsByTop.set(chunk.topId, topIds)
+ if (graph) this.indexDependencies(graph, chunk)
+ }
+
+ private unregister(chunk: RenderChunk): void {
+ this.tree.remove(chunk)
+ this.chunks.delete(chunk.id)
+ this.chunkIdsByNode.get(chunk.nodeId)?.delete(chunk.id)
+ this.chunkIdsByTop.get(chunk.topId)?.delete(chunk.id)
+ for (const dependencyId of this.dependenciesByChunk.get(chunk.id) ?? []) {
+ this.chunkIdsByDependency.get(dependencyId)?.delete(chunk.id)
+ }
+ this.dependenciesByChunk.delete(chunk.id)
+ }
+
+ /** Whether `nodeId` is a page child whose subtree the index holds chunks for. */
+ hasTop(nodeId: string): boolean {
+ return (this.chunkIdsByTop.get(nodeId)?.size ?? 0) > 0
+ }
+
+ /**
+ * Replaces the chunks of the page child `topId`'s subtree with ones built from the graph as it
+ * is now, or only removes them when the page no longer shows it. Returns both sets, so the
+ * caller can drop their pictures and the tiles they covered or cover.
+ */
+ rebuildTop(
+ graph: SceneGraph,
+ pageId: string,
+ topId: string
+ ): { removed: RenderChunk[]; added: RenderChunk[] } {
+ const removed = [...(this.chunkIdsByTop.get(topId) ?? [])].flatMap((id) => {
+ const chunk = this.chunks.get(id)
+ return chunk ? [chunk] : []
+ })
+ for (const chunk of removed) this.unregister(chunk)
+ const topIndex = graph.getNode(pageId)?.childIds.indexOf(topId) ?? -1
+ const added =
+ topIndex >= 0
+ ? buildChunks(graph, topId, topId, topIndex, countDescendants(graph, [topId]).counts)
+ : []
+ for (const chunk of added) {
+ this.tree.insert(chunk)
+ this.register(chunk, graph)
+ }
+ if (removed.length > 0 || added.length > 0) this.cachedBounds = undefined
+ return { removed, added }
+ }
+
+ /**
+ * Replaces the chunks a change at `nodeId` can affect, so a layer added or removed deep in a
+ * large page rebuilds a few chunks rather than the page child's thousands: the nearest
+ * chunk-owning ancestor's subtree when that ancestor is one chunk, or, when it is split into
+ * children, only the child subtree on the way to the layer. New chunks take draw orders between
+ * their neighbours'. Null when no chunk on the page holds the layer, which a caller answers by
+ * rebuilding everything.
+ */
+ rebuildFrom(
+ graph: SceneGraph,
+ pageId: string,
+ nodeId: string
+ ): { removed: RenderChunk[]; added: RenderChunk[] } | null {
+ const found = this.chunkOwnerOf(graph, nodeId)
+ if (!found) return null
+ const { owner, ownerChunk, path } = found
+ if (ownerChunk.kind === 'subtree') return this.rebuildOwner(graph, pageId, owner, ownerChunk)
+ // The owner draws itself and each child subtree apart: only the one on the path changes.
+ const child = path.at(-1)
+ if (!child) return this.rebuildOwner(graph, pageId, owner, ownerChunk)
+ return this.replaceSubtree(graph, pageId, ownerChunk.topId, owner.id, child.id)
+ }
+
+ /**
+ * The nearest layer from `nodeId` upward that owns a chunk, its chunk, and the layers passed
+ * on the way, nearest the owner last; null off the page or on a parent cycle.
+ */
+ /** Rebuilds the chunks of `owner` whole: the top it is, or its subtree within its top. */
+ private rebuildOwner(
+ graph: SceneGraph,
+ pageId: string,
+ owner: SceneNode,
+ ownerChunk: RenderChunk
+ ): { removed: RenderChunk[]; added: RenderChunk[] } | null {
+ if (owner.parentId === pageId) return this.rebuildTop(graph, pageId, owner.id)
+ return this.replaceSubtree(graph, pageId, ownerChunk.topId, owner.id, owner.id)
+ }
+
+ private chunkOwnerOf(
+ graph: SceneGraph,
+ nodeId: string
+ ): { owner: SceneNode; ownerChunk: RenderChunk; path: SceneNode[] } | null {
+ const path: SceneNode[] = []
+ const seen = new Set<string>()
+ let node = graph.getNode(nodeId)
+ while (node && !seen.has(node.id) && (this.chunkIdsByNode.get(node.id)?.size ?? 0) === 0) {
+ seen.add(node.id)
+ path.push(node)
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ }
+ if (!node || seen.has(node.id)) return null
+ const ownerChunk = this.getChunksForNode(node.id).at(0)
+ return ownerChunk ? { owner: node, ownerChunk, path } : null
+ }
+
+ /**
+ * Under a split owner: the chunks of layers that are gone or no longer under it, and the roots
+ * of subtree chunks that recorded a layer since removed.
+ */
+ private danglingUnder(
+ graph: SceneGraph,
+ ownerId: string
+ ): { removed: RenderChunk[]; stale: string[] } {
+ const removed: RenderChunk[] = []
+ const stale: string[] = []
+ for (const chunk of this.getChunksDependingOnNode(ownerId)) {
+ if (chunk.nodeId === ownerId) continue
+ if (!graph.getNode(chunk.nodeId) || !this.isUnder(graph, chunk.nodeId, ownerId)) {
+ removed.push(chunk)
+ continue
+ }
+ const dependencies = this.dependenciesByChunk.get(chunk.id) ?? []
+ if (chunk.kind === 'subtree' && dependencies.some((id) => !graph.getNode(id))) {
+ stale.push(chunk.nodeId)
+ }
+ }
+ return { removed, stale }
+ }
+
+ /** Whether `nodeId` is `ancestorId` or lies under it. */
+ private isUnder(graph: SceneGraph, nodeId: string, ancestorId: string): boolean {
+ const seen = new Set<string>()
+ let node = graph.getNode(nodeId)
+ while (node && !seen.has(node.id)) {
+ if (node.id === ancestorId) return true
+ seen.add(node.id)
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ }
+ return false
+ }
+
+ /**
+ * Removes the chunks `nodeId` and its descendants own, before the layer is rebuilt where it
+ * now is; a chunk of an ancestor's subtree that holds the layer stays for `rebuildFrom`.
+ */
+ /** Whether the chunk `id` is still in the index. */
+ has(id: string): boolean {
+ return this.chunks.has(id)
+ }
+
+ /**
+ * The subtree chunks of `nodeId`'s ancestors that drew it, as the index last built them: after
+ * a move they still hold the layer at its old place until they are built again.
+ */
+ chunksHolding(graph: SceneGraph, nodeId: string): RenderChunk[] {
+ return this.getChunksDependingOnNode(nodeId).filter(
+ (chunk) => chunk.nodeId !== nodeId && !this.isUnder(graph, chunk.nodeId, nodeId)
+ )
+ }
+
+ dropChunksOf(graph: SceneGraph, nodeId: string): RenderChunk[] {
+ const removed = this.getChunksDependingOnNode(nodeId).filter(
+ (chunk) => chunk.nodeId === nodeId || this.isUnder(graph, chunk.nodeId, nodeId)
+ )
+ for (const chunk of removed) this.unregister(chunk)
+ if (removed.length > 0) this.cachedBounds = undefined
+ return removed
+ }
+
+ /**
+ * After a layer under `parentId` was removed: drops the chunks of layers that are gone and
+ * rebuilds the subtree chunks that recorded one, without touching the parent's other children.
+ */
+ pruneUnder(
+ graph: SceneGraph,
+ pageId: string,
+ parentId: string
+ ): { removed: RenderChunk[]; added: RenderChunk[] } | null {
+ const found = this.chunkOwnerOf(graph, parentId)
+ if (!found) return null
+ const { owner, ownerChunk } = found
+ if (ownerChunk.kind === 'subtree') return this.rebuildOwner(graph, pageId, owner, ownerChunk)
+ const { removed, stale } = this.danglingUnder(graph, owner.id)
+ for (const chunk of removed) this.unregister(chunk)
+ const added: RenderChunk[] = []
+ for (const rootId of stale) {
+ const rebuilt = this.replaceSubtree(graph, pageId, ownerChunk.topId, owner.id, rootId)
+ if (rebuilt) {
+ removed.push(...rebuilt.removed)
+ added.push(...rebuilt.added)
+ }
+ }
+ if (removed.length > 0) this.cachedBounds = undefined
+ return { removed, added }
+ }
+
+ /** Rebuilds the chunks of `rootId`'s subtree, a child subtree of `ownerId` or the owner itself. */
+ private replaceSubtree(
+ graph: SceneGraph,
+ pageId: string,
+ topId: string,
+ ownerId: string,
+ rootId: string
+ ): { removed: RenderChunk[]; added: RenderChunk[] } | null {
+ const topIndex = graph.getNode(pageId)?.childIds.indexOf(topId) ?? -1
+ if (topIndex < 0) return null
+ const removed = this.getChunksDependingOnNode(rootId)
+ const { start, end } = this.orderWindow(graph, topId, topIndex, ownerId, rootId, removed)
+ for (const chunk of removed) this.unregister(chunk)
+ const counts = countDescendants(graph, [rootId]).counts
+ const built = buildChunks(graph, rootId, topId, topIndex, counts)
+ const step = (end - start) / (built.length + 1)
+ // Each insertion halves the gap to the neighbour; once the gap is below a double's
+ // resolution the orders would collide, so the top is numbered afresh instead.
+ if (start + step === start || end - step === end) {
+ const top = this.rebuildTop(graph, pageId, topId)
+ return { removed: [...removed, ...top.removed], added: top.added }
+ }
+ for (const [position, chunk] of built.entries()) {
+ chunk.painterOrder = start + step * (position + 1)
+ chunk.localOrder = chunk.painterOrder - topIndex * PAINTER_ORDER_SPAN
+ this.tree.insert(chunk)
+ this.register(chunk, graph)
+ }
+ this.cachedBounds = undefined
+ return { removed, added: built }
+ }
+
+ /**
+ * The draw orders the rebuilt chunks must fall between: those of what draws before the subtree
+ * and after it. With chunks to replace, their own range bounds it; for a new subtree, the
+ * nearest siblings with chunks on either side do, or the owner and what follows its subtree.
+ */
+ private orderWindow(
+ graph: SceneGraph,
+ topId: string,
+ topIndex: number,
+ ownerId: string,
+ rootId: string,
+ removed: RenderChunk[]
+ ): { start: number; end: number } {
+ // Replaced chunks draw first in their window, so the lower bound is just before them.
+ const first =
+ removed.length > 0
+ ? this.orderBefore(topId, Math.min(...removed.map((chunk) => chunk.painterOrder)))
+ : this.orderBeforeSibling(graph, ownerId, rootId)
+ const last =
+ removed.length > 0 ? Math.max(...removed.map((chunk) => chunk.painterOrder)) : first
+ let end = painterOrderOf(topIndex + 1, 0)
+ for (const id of this.chunkIdsByTop.get(topId) ?? []) {
+ const chunk = this.chunks.get(id)
+ if (chunk && chunk.painterOrder > last && chunk.painterOrder < end) end = chunk.painterOrder
+ }
+ return { start: first === -Infinity ? painterOrderOf(topIndex, 0) - 1 : first, end }
+ }
+
+ /**
+ * The greatest draw order among the siblings before `rootId` under `ownerId`, the owner's own
+ * when none of them draws, or minus infinity when nothing draws before the subtree.
+ */
+ private orderBeforeSibling(graph: SceneGraph, ownerId: string, rootId: string): number {
+ const siblings = graph.getNode(ownerId)?.childIds ?? []
+ let start = -Infinity
+ for (let index = siblings.indexOf(rootId) - 1; index >= 0 && start === -Infinity; index--) {
+ for (const chunk of this.getChunksDependingOnNode(siblings[index])) {
+ start = Math.max(start, chunk.painterOrder)
+ }
+ }
+ if (start === -Infinity) return this.getChunksForNode(ownerId)[0]?.painterOrder ?? -Infinity
+ return start
+ }
+
+ /** The greatest draw order on the page child below `order`, or the start of its range. */
+ private orderBefore(topId: string, order: number): number {
+ let before = -Infinity
+ for (const id of this.chunkIdsByTop.get(topId) ?? []) {
+ const chunk = this.chunks.get(id)
+ if (chunk && chunk.painterOrder < order && chunk.painterOrder > before)
+ before = chunk.painterOrder
+ }
+ return before
+ }
+
+ /** Renumbers every chunk's draw order after the page's own children were reordered. */
+ renumber(graph: SceneGraph, pageId: string): void {
+ const childIds = graph.getNode(pageId)?.childIds ?? []
+ const topIndexById = new Map(childIds.map((id, index) => [id, index]))
+ for (const chunk of this.chunks.values()) {
+ const topIndex = topIndexById.get(chunk.topId)
+ if (topIndex !== undefined) chunk.painterOrder = painterOrderOf(topIndex, chunk.localOrder)
}
}
/** The world bounds all chunks lie in, or null for an empty page. */
bounds(): Pick<RenderChunk, 'minX' | 'minY' | 'maxX' | 'maxY'> | null {
+ if (this.cachedBounds !== undefined) return this.cachedBounds
let bounds: Pick<RenderChunk, 'minX' | 'minY' | 'maxX' | 'maxY'> | null = null
for (const chunk of this.chunks.values()) {
bounds = bounds
@@ -228,6 +393,7 @@ export class RenderChunkIndex {
}
: { minX: chunk.minX, minY: chunk.minY, maxX: chunk.maxX, maxY: chunk.maxY }
}
+ this.cachedBounds = bounds
return bounds
}
@@ -252,6 +418,7 @@ export class RenderChunkIndex {
}
Object.assign(chunk, bounds, { context: chunkContext(graph, node) })
this.tree.insert(chunk)
+ this.cachedBounds = undefined
updated++
}
return updated
@@ -295,6 +462,7 @@ export class RenderChunkIndex {
ids.add(chunk.id)
this.chunkIdsByDependency.set(dependencyId, ids)
}
+ this.dependenciesByChunk.set(chunk.id, [...dependencies])
}
size(): number {
@@ -306,14 +474,12 @@ export class RenderChunkIndex {
this.chunks.clear()
this.chunkIdsByNode.clear()
this.chunkIdsByDependency.clear()
+ this.dependenciesByChunk.clear()
+ this.chunkIdsByTop.clear()
+ this.cachedBounds = undefined
}
}
export { RenderChunkPictureCache } from './cache'
-export {
- deleteRecordedRenderChunks,
- drawRecordedRenderChunks,
- drawRenderChunkDirect,
- recordRenderChunk
-} from './record'
+export { drawRenderChunkDirect, recordRenderChunk } from './record'
export type { RecordedRenderChunk } from './record'
diff --git a/packages/core/src/canvas/renderer/chunks/record.ts b/packages/core/src/canvas/renderer/chunks/record.ts
index 97be83847..0975c66b6 100644
--- a/packages/core/src/canvas/renderer/chunks/record.ts
+++ b/packages/core/src/canvas/renderer/chunks/record.ts
@@ -6,7 +6,7 @@ import Matrix from '@open-pencil/scene-graph/matrix'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { recordWorldPicture, withWorldViewport } from '#core/canvas/renderer/picture'
-import { clipNodeShape } from '#core/canvas/shapes'
+import { clipNodeShape, withNodeOutline } from '#core/canvas/shapes'
import type { RenderChunk } from './index'
@@ -15,27 +15,67 @@ export interface RecordedRenderChunk {
picture: SkPicture
}
+/**
+ * Clips to an ancestor's outline in world space. A frame that is only translated, the common
+ * case, clips its box or rounded box moved into place, one call; a rotated, flipped, or scaled
+ * one clips under its matrix and restores it.
+ */
function clipAncestor(r: SkiaRenderer, canvas: Canvas, graph: SceneGraph, node: SceneNode): void {
- canvas.concat(getWorldMatrix(node, graph))
+ const world = getWorldMatrix(node, graph)
+ const translated = world[0] === 1 && world[1] === 0 && world[3] === 0 && world[4] === 1
+ if (translated) {
+ const tx = world[2]
+ const ty = world[5]
+ const clipped = withNodeOutline(r, node, (outline) => {
+ if (outline.kind === 'rect') {
+ canvas.clipRect(
+ r.ltrb(tx, ty, tx + node.width, ty + node.height),
+ r.ck.ClipOp.Intersect,
+ true
+ )
+ return true
+ }
+ if (outline.kind === 'rrect') {
+ const rrect = outline.rrect.slice()
+ rrect[0] += tx
+ rrect[1] += ty
+ rrect[2] += tx
+ rrect[3] += ty
+ canvas.clipRRect(rrect, r.ck.ClipOp.Intersect, true)
+ return true
+ }
+ return false
+ })
+ if (clipped) return
+ }
+ canvas.concat(world)
clipNodeShape(r, canvas, node)
- const inverse = Matrix.invert(getWorldMatrix(node, graph))
+ const inverse = Matrix.invert(world)
if (inverse) canvas.concat(inverse)
}
function drawChunkContent(
- renderer: SkiaRenderer,
+ r: SkiaRenderer,
canvas: Canvas,
graph: SceneGraph,
chunk: RenderChunk
): void {
canvas.save()
+ const { clipRect } = chunk.context
+ if (clipRect) {
+ canvas.clipRect(
+ r.ltrb(clipRect.minX, clipRect.minY, clipRect.maxX, clipRect.maxY),
+ r.ck.ClipOp.Intersect,
+ true
+ )
+ }
for (const ancestorId of chunk.context.ancestorClipIds) {
const ancestor = graph.getNode(ancestorId)
- if (ancestor) clipAncestor(renderer, canvas, graph, ancestor)
+ if (ancestor) clipAncestor(r, canvas, graph, ancestor)
}
canvas.concat(chunk.context.parentTransform)
- if (chunk.kind === 'self') renderer.renderNodeSelf(canvas, graph, chunk.nodeId)
- else renderer.renderNode(canvas, graph, chunk.nodeId, {}, 0, 0, true)
+ if (chunk.kind === 'self') r.renderNodeSelf(canvas, graph, chunk.nodeId)
+ else r.renderNode(canvas, graph, chunk.nodeId, {}, 0, 0, chunk.context.parentTransform)
canvas.restore()
}
@@ -58,11 +98,3 @@ export function recordRenderChunk(
)
return { chunk, picture }
}
-
-export function drawRecordedRenderChunks(canvas: Canvas, chunks: RecordedRenderChunk[]): void {
- for (const recorded of chunks) canvas.drawPicture(recorded.picture)
-}
-
-export function deleteRecordedRenderChunks(chunks: RecordedRenderChunk[]): void {
- for (const recorded of chunks) recorded.picture.delete()
-}
diff --git a/packages/core/src/canvas/renderer/effect-raster-cache.ts b/packages/core/src/canvas/renderer/effect-raster-cache.ts
index f6c75f34d..7ad7df048 100644
--- a/packages/core/src/canvas/renderer/effect-raster-cache.ts
+++ b/packages/core/src/canvas/renderer/effect-raster-cache.ts
@@ -1,6 +1,10 @@
-import type { Image as CKImage } from 'canvaskit-wasm'
+import type { Canvas, Image as CKImage } from 'canvaskit-wasm'
+
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { arrowCapOverflow } from '@open-pencil/scene-graph/arrow-caps'
import { ResourceCache } from '#core/cache/resource'
+import type { SkiaRenderer } from '#core/canvas/renderer'
export interface EffectRasterCacheEntry {
image: CKImage
@@ -48,3 +52,128 @@ export function canCacheEffectRaster(width: number, height: number, scale: numbe
Math.ceil(width * scale) * Math.ceil(height * scale) <= MAX_EFFECT_RASTER_ENTRY_PIXELS
)
}
+
+function canRasterCacheEffects(visibleEffects: SceneNode['effects']): boolean {
+ return (
+ visibleEffects.length > 0 &&
+ visibleEffects.every(
+ (effect) => effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
+ )
+ )
+}
+
+/**
+ * Draws a shape with effects from its cached raster or picture, recording one when there is
+ * none: while the retained backing records, a shadowed shape rasterizes once at the current
+ * scale; otherwise its drawing is kept as a picture.
+ */
+export function renderShapeThroughEffectCaches(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ graph: SceneGraph,
+ effects: SceneNode['effects']
+): void {
+ const canRasterCache = r.renderingSceneBacking && canRasterCacheEffects(effects)
+ const targetScale = effectRasterScale(r.zoom * r.dpr)
+ const cachedRaster = canRasterCache ? r.effectRasterCache.get(node.id) : null
+ if (
+ cachedRaster &&
+ (cachedRaster.fontGeneration !== r.fontGeneration ||
+ !effectRasterScaleMatches(cachedRaster.scale, targetScale))
+ ) {
+ r.effectRasterCache.delete(node.id)
+ } else if (cachedRaster) {
+ canvas.drawImageRectOptions(
+ cachedRaster.image,
+ r.ck.LTRBRect(0, 0, cachedRaster.image.width(), cachedRaster.image.height()),
+ r.ck.LTRBRect(
+ cachedRaster.left,
+ cachedRaster.top,
+ cachedRaster.left + cachedRaster.width,
+ cachedRaster.top + cachedRaster.height
+ ),
+ r.ck.FilterMode.Linear,
+ r.ck.MipmapMode.None,
+ null
+ )
+ return
+ }
+
+ // An arrow head reaches past the shape, and its shadow reaches past the head: both margins.
+ const margin =
+ r.effectOverflow(node) + arrowCapOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
+ const width = node.width + margin * 2
+ const height = node.height + margin * 2
+ const scale = targetScale
+ // A surface the GPU cannot give falls through to the picture path below.
+ const surface =
+ canRasterCache && canCacheEffectRaster(width, height, scale)
+ ? r.surface.makeSurface({
+ width: Math.ceil(width * scale),
+ height: Math.ceil(height * scale),
+ colorType: r.ck.ColorType.RGBA_8888,
+ alphaType: r.ck.AlphaType.Premul,
+ colorSpace: r.ck.ColorSpace.SRGB
+ })
+ : null
+ if (surface) {
+ const rasterCanvas = surface.getCanvas()
+ try {
+ rasterCanvas.clear(r.ck.TRANSPARENT)
+ rasterCanvas.scale(scale, scale)
+ rasterCanvas.translate(margin, margin)
+ r.renderShapeUncached(rasterCanvas, node, graph)
+ surface.flush()
+ const image = surface.makeImageSnapshot()
+ const retained = r.effectRasterCache.set(node.id, {
+ image,
+ left: -margin,
+ top: -margin,
+ width,
+ height,
+ scale,
+ pixels: image.width() * image.height(),
+ fontGeneration: r.fontGeneration
+ })
+ try {
+ canvas.drawImageRectOptions(
+ image,
+ r.ck.LTRBRect(0, 0, image.width(), image.height()),
+ r.ck.LTRBRect(-margin, -margin, node.width + margin, node.height + margin),
+ r.ck.FilterMode.Linear,
+ r.ck.MipmapMode.None,
+ null
+ )
+ } finally {
+ if (!retained) image.delete()
+ }
+ return
+ } finally {
+ surface.delete()
+ }
+ }
+
+ const cached = r.nodePictureCache.get(node.id)
+ const cachedGeneration = r.nodePictureCacheGenerations.get(node.id)
+ if (cached && cachedGeneration === r.fontGeneration) {
+ canvas.drawPicture(cached)
+ return
+ }
+ if (cached) cached.delete()
+ r.nodePictureCache.delete(node.id)
+ r.nodePictureCacheGenerations.delete(node.id)
+
+ const bounds = r.ck.LTRBRect(-margin, -margin, node.width + margin, node.height + margin)
+ const recorder = new r.ck.PictureRecorder()
+ try {
+ const recCanvas = recorder.beginRecording(bounds)
+ r.renderShapeUncached(recCanvas, node, graph)
+ const picture = recorder.finishRecordingAsPicture()
+ r.nodePictureCache.set(node.id, picture)
+ r.nodePictureCacheGenerations.set(node.id, r.fontGeneration)
+ canvas.drawPicture(picture)
+ } finally {
+ recorder.delete()
+ }
+}
diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.ts
index c8cc577f4..c1dcd7389 100644
--- a/packages/core/src/canvas/renderer/fonts.ts
+++ b/packages/core/src/canvas/renderer/fonts.ts
@@ -147,7 +147,6 @@ export async function loadFonts(
r.componentLabelFont = new r.ck.Font(typeface, COMPONENT_LABEL_FONT_SIZE)
r.profiler.setTypeface(typeface)
}
- r.fontMgr = r.ck.FontMgr.FromData(fontData) ?? null
}
r.fontsLoaded = true
diff --git a/packages/core/src/canvas/renderer/lifecycle.ts b/packages/core/src/canvas/renderer/lifecycle.ts
index e204052f9..98cf75af0 100644
--- a/packages/core/src/canvas/renderer/lifecycle.ts
+++ b/packages/core/src/canvas/renderer/lifecycle.ts
@@ -1,3 +1,4 @@
+import { disposeNodeEditPaints } from '#core/canvas/node-edit-overlay'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { clearSubtreePictureCache } from '#core/canvas/renderer/state'
import { fontManager } from '#core/text/font/manager'
@@ -50,7 +51,6 @@ export function destroyRenderer(r: SkiaRenderer): void {
releaseRuntimeEffects(r)
r.strokePaint.delete()
r.selectionPaint.delete()
- r.parentOutlinePaint.delete()
r.snapPaint.delete()
r.auxFill.delete()
r.auxStroke.delete()
@@ -61,7 +61,6 @@ export function destroyRenderer(r: SkiaRenderer): void {
r.valueFont?.delete()
r.sectionTitleFont?.delete()
r.componentLabelFont?.delete()
- r.fontMgr?.delete()
const fontProvider = r.fontProvider
r.fontProvider = null
r.fontsLoaded = false
@@ -83,10 +82,12 @@ export function destroyRenderer(r: SkiaRenderer): void {
r.penVertexFill.delete()
r.penVertexStroke.delete()
r.effectLayerPaint.delete()
- for (const filter of r.imageFilterCache.values()) filter?.delete()
r.imageFilterCache.clear()
- for (const filter of r.maskFilterCache.values()) filter?.delete()
r.maskFilterCache.clear()
+ r.dashEffects.clear()
+ r.pixelGridShader?.shader.delete()
+ r.pixelGridShader = null
+ disposeNodeEditPaints(r.nodeEditPaints)
for (const pic of r.nodePictureCache.values()) pic?.delete()
r.nodePictureCache.clear()
r.labelParagraphCache.clear()
@@ -95,7 +96,6 @@ export function destroyRenderer(r: SkiaRenderer): void {
r.tiledScene.destroy()
clearSubtreePictureCache(r)
clearRetainedSceneState(r)
- r._flashPaint?.delete()
r.profiler.destroy()
r.surface.delete()
}
diff --git a/packages/core/src/canvas/renderer/methods.ts b/packages/core/src/canvas/renderer/methods.ts
index 37980c293..79db655b9 100644
--- a/packages/core/src/canvas/renderer/methods.ts
+++ b/packages/core/src/canvas/renderer/methods.ts
@@ -1,7 +1,8 @@
import type { ImageFilter, MaskFilter, Canvas, Paint, Path } from 'canvaskit-wasm'
import type { Fill, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
+import type { Mat3 } from '@open-pencil/scene-graph/matrix'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
import type { SnapGuide } from '@open-pencil/scene-graph/snap'
import * as Effects from '#core/canvas/effects'
@@ -9,7 +10,6 @@ import * as Fills from '#core/canvas/fills'
import * as Labels from '#core/canvas/labels/draw'
import * as NodeEditOverlay from '#core/canvas/node-edit-overlay'
import * as Overlays from '#core/canvas/overlays'
-import * as AIOverlays from '#core/canvas/overlays/ai'
import * as PenOverlay from '#core/canvas/pen-overlay'
import type { SkiaRenderer } from '#core/canvas/renderer'
import type { PresenceCursor, RenderOverlays } from '#core/canvas/renderer/types'
@@ -105,10 +105,6 @@ const rendererMethods = {
Overlays.drawGroupBounds(this, canvas, nodes, graph, preview)
},
- getRotatedCorners(n: SceneNode, abs: Vector): Vector[] {
- return Overlays.getRotatedCorners(this, n, abs)
- },
-
drawHandle(canvas: Canvas, x: number, y: number): void {
Overlays.drawHandle(this, canvas, x, y)
},
@@ -127,7 +123,6 @@ const rendererMethods = {
drawFlashes(canvas: Canvas, graph: SceneGraph): void {
Overlays.drawFlashes(this, canvas, graph)
- AIOverlays.drawAIOverlays(this, canvas, graph)
},
drawLayoutInsertIndicator(
@@ -211,18 +206,9 @@ const rendererMethods = {
overlays: RenderOverlays,
parentAbsX?: number,
parentAbsY?: number,
- hasTransformedAncestor?: boolean
+ frame?: Mat3 | null
): void {
- SceneRender.renderNode(
- this,
- canvas,
- graph,
- nodeId,
- overlays,
- parentAbsX,
- parentAbsY,
- hasTransformedAncestor
- )
+ SceneRender.renderNode(this, canvas, graph, nodeId, overlays, parentAbsX, parentAbsY, frame)
},
renderSection(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {
@@ -330,19 +316,24 @@ const rendererMethods = {
return Shapes.getStrokeGeometry(this, node)
},
- getCachedDropShadow(dx: number, dy: number, sigma: number, color: Float32Array): ImageFilter {
+ getCachedDropShadow(
+ dx: number,
+ dy: number,
+ sigma: number,
+ color: Float32Array
+ ): ImageFilter | null {
return Effects.getCachedDropShadow(this, dx, dy, sigma, color)
},
- getCachedBlur(sigma: number): ImageFilter {
+ getCachedBlur(sigma: number): ImageFilter | null {
return Effects.getCachedBlur(this, sigma)
},
- getCachedDecalBlur(sigma: number): ImageFilter {
+ getCachedDecalBlur(sigma: number): ImageFilter | null {
return Effects.getCachedDecalBlur(this, sigma)
},
- getCachedMaskBlur(sigma: number): MaskFilter {
+ getCachedMaskBlur(sigma: number): MaskFilter | null {
return Effects.getCachedMaskBlur(this, sigma)
},
diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.ts
index 7a9ce0ca3..a829d7691 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -5,6 +5,8 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { drawGuides } from '#core/canvas/guides/draw'
import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'
import { layoutIssueMarkers } from '#core/canvas/issues/layout'
+import { cachedGlyphWidth } from '#core/canvas/labels/paragraph-cache'
+import { drawAIOverlays } from '#core/canvas/overlays/ai'
import { drawComponentSetBorders } from '#core/canvas/overlays/component-sets'
import { drawConnectorTarget } from '#core/canvas/overlays/connectors'
import { drawDropTarget, drawEditingText } from '#core/canvas/overlays/feedback'
@@ -65,13 +67,7 @@ function updateIssueMarkers(r: SkiaRenderer, graph: SceneGraph, overlays: Render
r.issueMarkers = []
return
}
- const measureText = (text: string) => {
- const font = r.sizeFont
- if (!font) return 0
- let width = 0
- for (const glyph of font.getGlyphWidths(font.getGlyphIDs(text))) width += glyph
- return width
- }
+ const measureText = (text: string) => (r.sizeFont ? cachedGlyphWidth(r, r.sizeFont, text) : 0)
const inset = r.showRulers ? RULER_SIZE : 0
r.issueMarkers = layoutIssueMarkers(graph, markers, {
pageId: r.pageId ?? '',
@@ -137,6 +133,7 @@ export function drawOverlayPass(
r.profiler.endPhase('render:selection')
r.drawFlashes(canvas, graph)
+ drawAIOverlays(r, canvas, graph)
if (overlays.guides?.redline) drawMeasurementSegment(r, canvas, overlays.guides.redline.segment)
drawGuides(r, canvas, graph, overlays.guides)
r.drawSnapGuides(canvas, overlays.snapGuides)
diff --git a/packages/core/src/canvas/renderer/paints.ts b/packages/core/src/canvas/renderer/paints.ts
index e1145013b..1a0497b34 100644
--- a/packages/core/src/canvas/renderer/paints.ts
+++ b/packages/core/src/canvas/renderer/paints.ts
@@ -1,8 +1,8 @@
+import { createNodeEditPaints } from '#core/canvas/node-edit-overlay'
import type { SkiaRenderer } from '#core/canvas/renderer'
import {
DEFAULT_FONT_SIZE,
PARENT_OUTLINE_ALPHA,
- PARENT_OUTLINE_DASH,
PEN_PATH_STROKE_WIDTH,
RULER_BG_COLOR,
RULER_TEXT_COLOR,
@@ -26,18 +26,10 @@ export function initializeRendererPaints(r: SkiaRenderer): void {
r.selectionPaint.setStrokeWidth(1)
r.selectionPaint.setAntiAlias(true)
- r.parentOutlinePaint = new ck.Paint()
- r.parentOutlinePaint.setStyle(ck.PaintStyle.Stroke)
- r.parentOutlinePaint.setStrokeWidth(1)
- r.parentOutlinePaint.setAntiAlias(true)
- r.parentOutlinePaint.setPathEffect(
- ck.PathEffect.MakeDash([PARENT_OUTLINE_DASH, PARENT_OUTLINE_DASH], 0)
- )
-
r.snapPaint = new ck.Paint()
r.snapPaint.setStyle(ck.PaintStyle.Stroke)
r.snapPaint.setStrokeWidth(1)
- r.snapPaint.setColor(ck.Color4f(SNAP_COLOR.r, SNAP_COLOR.g, SNAP_COLOR.b, 1))
+ r.snapPaint.setColorComponents(SNAP_COLOR.r, SNAP_COLOR.g, SNAP_COLOR.b, 1)
r.snapPaint.setAntiAlias(true)
r.auxFill = new ck.Paint()
@@ -54,7 +46,7 @@ export function initializeRendererPaints(r: SkiaRenderer): void {
const bg = RULER_BG_COLOR
r.rulerBgPaint = new ck.Paint()
- r.rulerBgPaint.setColor(ck.Color4f(bg.r, bg.g, bg.b, 1))
+ r.rulerBgPaint.setColorComponents(bg.r, bg.g, bg.b, 1)
r.rulerTickPaint = new ck.Paint()
r.rulerTickPaint.setColor(
@@ -65,7 +57,7 @@ export function initializeRendererPaints(r: SkiaRenderer): void {
const tc = RULER_TEXT_COLOR
r.rulerTextPaint = new ck.Paint()
- r.rulerTextPaint.setColor(ck.Color4f(tc.r, tc.g, tc.b, 1))
+ r.rulerTextPaint.setColorComponents(tc.r, tc.g, tc.b, 1)
r.rulerTextPaint.setAntiAlias(true)
r.rulerHlPaint = new ck.Paint()
@@ -75,19 +67,19 @@ export function initializeRendererPaints(r: SkiaRenderer): void {
r.rulerBadgePaint.setAntiAlias(true)
r.rulerLabelPaint = new ck.Paint()
- r.rulerLabelPaint.setColor(ck.Color4f(1, 1, 1, 1))
+ r.rulerLabelPaint.setColorComponents(1, 1, 1, 1)
r.rulerLabelPaint.setAntiAlias(true)
r.penPathPaint = new ck.Paint()
r.penPathPaint.setStyle(ck.PaintStyle.Stroke)
r.penPathPaint.setStrokeWidth(1)
- r.penPathPaint.setColor(ck.Color4f(0.698, 0.698, 0.698, 1))
+ r.penPathPaint.setColorComponents(0.698, 0.698, 0.698, 1)
r.penPathPaint.setAntiAlias(true)
r.penLiveStrokePaint = new ck.Paint()
r.penLiveStrokePaint.setStyle(ck.PaintStyle.Stroke)
r.penLiveStrokePaint.setStrokeWidth(PEN_PATH_STROKE_WIDTH)
- r.penLiveStrokePaint.setColor(ck.Color4f(0, 0, 0, 1))
+ r.penLiveStrokePaint.setColorComponents(0, 0, 0, 1)
r.penLiveStrokePaint.setAntiAlias(true)
r.pencilStrokePaint = new ck.Paint()
@@ -111,13 +103,25 @@ export function initializeRendererPaints(r: SkiaRenderer): void {
r.penVertexStroke.setStrokeWidth(1)
r.penVertexStroke.setAntiAlias(true)
+ r.nodeEditPaints = createNodeEditPaints(ck)
+
initializeSelectionPaintColors(r)
}
/** Colors the long-lived paints drawn in the selection color; rerun when that color changes. */
export function initializeSelectionPaintColors(r: SkiaRenderer): void {
r.selectionPaint.setColor(r.selColor())
- r.parentOutlinePaint.setColor(r.selColor(PARENT_OUTLINE_ALPHA))
r.penHandlePaint.setColor(r.selColor(PARENT_OUTLINE_ALPHA))
r.penVertexStroke.setColor(r.selColor())
}
+
+/** Colours the ruler paints from the ruler theme, or the defaults without one. */
+export function initializeRulerPaintColors(r: SkiaRenderer): void {
+ const theme = r.rulerTheme
+ const background = theme?.background ?? { ...RULER_BG_COLOR, a: 1 }
+ const tick = theme?.tick ?? { ...RULER_TICK_COLOR, a: 1 }
+ const text = theme?.text ?? { ...RULER_TEXT_COLOR, a: 1 }
+ r.rulerBgPaint.setColorComponents(background.r, background.g, background.b, background.a)
+ r.rulerTickPaint.setColorComponents(tick.r, tick.g, tick.b, tick.a)
+ r.rulerTextPaint.setColorComponents(text.r, text.g, text.b, text.a)
+}
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index e3e5ae029..9397249b0 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -76,7 +76,7 @@ export function renderFromEditorState(
r.viewportHeight = viewportHeight
r.showRulers = showRulers
r.pageColor = state.pageColor
- r.rulerTheme = state.rulerTheme ?? null
+ r.setRulerTheme(state.rulerTheme ?? null)
r.setSelectionTheme(state.selectionTheme)
r.pageId = state.currentPageId
r.navigationPhase = state.navigation.phase
@@ -248,6 +248,7 @@ export function render(
r.syncFontGeneration()
r.flushDecodedPreviews(graph)
r.nodePaths.releaseUncached()
+ r.frameGeometry = null
const p = r.profiler
p.beginFrame()
p.setScenePictureDrawTime(0)
@@ -269,6 +270,7 @@ export function render(
w: r.viewportWidth / r.zoom,
h: r.viewportHeight / r.zoom
}
+ r.imageDetailScale = r.zoom * r.dpr
updateSceneBackingPreviewState(r, layer)
const { requiresUncachedSceneRender, canUsePicture, cacheMissReason } = getSceneRenderPolicy(
diff --git a/packages/core/src/canvas/renderer/state.ts b/packages/core/src/canvas/renderer/state.ts
index 58413f067..3fafd1b29 100644
--- a/packages/core/src/canvas/renderer/state.ts
+++ b/packages/core/src/canvas/renderer/state.ts
@@ -25,6 +25,7 @@ export function clearSubtreePictureCache(r: SkiaRenderer): void {
export function invalidateAllPictures(r: SkiaRenderer): void {
r.textPreparationCache.clear()
+ r.textReadiness.clear()
invalidateScenePicture(r)
r.tiledScene.invalidateStructure()
for (const pic of r.nodePictureCache.values()) pic?.delete()
@@ -42,6 +43,7 @@ export function invalidateNodePicture(
r.textPreparationCache.deleteNode(nodeId, {
keepShaping: changedKeys !== undefined && !changesShaping(changedKeys)
})
+ r.textReadiness.delete(nodeId)
r.effectRasterCache.delete(nodeId)
const pic = r.nodePictureCache.get(nodeId)
if (pic) {
diff --git a/packages/core/src/canvas/renderer/tiles/cache.ts b/packages/core/src/canvas/renderer/tiles/cache.ts
index 3f2dfca1f..533970887 100644
--- a/packages/core/src/canvas/renderer/tiles/cache.ts
+++ b/packages/core/src/canvas/renderer/tiles/cache.ts
@@ -1,5 +1,7 @@
import type { Image as CKImage } from 'canvaskit-wasm'
+import { intersectVisualBounds } from '@open-pencil/scene-graph/geometry'
+
import { ResourceCache } from '#core/cache/resource'
import {
@@ -125,6 +127,20 @@ export class TileImageCache {
if (levels.size === 0) this.entriesByLevel.delete(entry.key.pageId)
}
+ /**
+ * Marks every tile of `level` as used now, so it is evicted after everything else: the page
+ * copy is the stand-in of last resort, and a zoom that renders through the budget must not
+ * lose it to tiles it will discard at the next step.
+ */
+ touchLevel(pageId: string, level: number): void {
+ const tiles = this.entriesByLevel.get(pageId)?.get(level)
+ if (!tiles) return
+ for (const id of tiles.keys()) {
+ const entry = this.entries.get(id)
+ if (entry) entry.lastUsed = ++this.clock
+ }
+ }
+
/** The cached tiles of one level of a page, in no particular order. */
tilesAtLevel(pageId: string, level: number): Iterable<CachedTile> {
return this.entriesByLevel.get(pageId)?.get(level)?.values() ?? []
@@ -142,18 +158,25 @@ export class TileImageCache {
* Cached tiles of other levels that stand in for `key`'s missing tile, scaled, in drawing
* order: the nearest level that covers all of the area first, then the nearer partial levels
* over it, nearest last, so the sharpest content ends on top and the complete level fills
- * whatever the partial ones miss. The search passes over partial levels beyond the layered
- * ones until it finds a complete one, so a hole shows the page copy rather than the page
- * colour. Null when no level has a tile there.
+ * whatever the partial ones miss. The area is the tile's overlap with `content`, the page's
+ * bounds, so the page copy counts as complete under a tile that reaches past the page; a tile
+ * off the page keeps its own area. The search passes over partial levels beyond the layered ones until it finds a complete one, so
+ * a hole shows the page copy rather than the page colour. Null when no level has a tile there.
*/
- findFallback(key: TileKey, levels: number[]): CachedTile[] | null {
+ findFallback(
+ key: TileKey,
+ levels: number[],
+ content: TileWorldBounds | null = null
+ ): CachedTile[] | null {
const bounds = tileWorldBounds(key)
+ // A tile off the page keeps its own area.
+ const area = content ? (intersectVisualBounds(bounds, content) ?? bounds) : bounds
// Shrink by a hair so a boundary shared with the next tile does not ask for that tile too.
const inset = {
- minX: bounds.minX + 1e-6,
- minY: bounds.minY + 1e-6,
- maxX: bounds.maxX - 1e-6,
- maxY: bounds.maxY - 1e-6
+ minX: area.minX + 1e-6,
+ minY: area.minY + 1e-6,
+ maxX: area.maxX - 1e-6,
+ maxY: area.maxY - 1e-6
}
const partial: CachedTile[][] = []
let base: CachedTile[] | null = null
diff --git a/packages/core/src/canvas/renderer/tiles/controller.ts b/packages/core/src/canvas/renderer/tiles/controller.ts
index 12239a498..18666da47 100644
--- a/packages/core/src/canvas/renderer/tiles/controller.ts
+++ b/packages/core/src/canvas/renderer/tiles/controller.ts
@@ -16,23 +16,32 @@ import {
viewportTileBytes,
viewportTileCacheBudget
} from './cache'
+import { TileCostModel } from './cost'
+import { exactTileLevel, type TileKey, tileLevel, type TileWorldBounds } from './geometry'
+import { pageBackdropPlan, type TilePlan, planTiles, type TilePlanOptions } from './planner'
+import { drawPresentation, resolveVisible, type VisiblePresentation } from './presentation'
import {
- MAX_TILE_LEVEL,
- MIN_TILE_LEVEL,
- TILE_DEVICE_SIZE,
- type TileKey,
- tileLevel,
- type TileWorldBounds
-} from './geometry'
-import { planTiles, type TilePlanOptions } from './planner'
-import { drawPresentation, resolveVisible } from './presentation'
-import { childTileKeys, deleteRenderedTile, downsampleTile, renderTile, tileChunks } from './render'
+ childTileKeys,
+ deleteRenderedTile,
+ downsampleTile,
+ estimateTileCost,
+ recordTilePictures,
+ renderTile,
+ tileJobResult
+} from './render'
import {
emptyTileSchedulerMetrics,
TileScheduler,
type TileJob,
type TileSchedulerMetrics
} from './scheduler'
+import {
+ applyInvalidations,
+ applyStructureChanges,
+ type PageTiles,
+ type PendingInvalidation,
+ type PendingStructureChange
+} from './structure'
import { TileSurfacePool } from './surface-pool'
import { emitTileCoverageComplete, emitTileFrameTrace } from './telemetry'
@@ -48,27 +57,13 @@ const BACKDROP_LEVEL_RATIO = 4
const BACKDROP_OVERSCAN = 1
/** How many halvings of the visible level the pyramid keeps: 2⁶ covers a 64× zoom out. */
const PYRAMID_LEVELS = 6
-/** The whole page is kept at a level where its longer side spans this many tiles. */
-const PAGE_BACKDROP_TILES = 4
-const TILE_COST_SMOOTHING = 0.3
-/** Exact levels are keyed to this many bits of the scale's logarithm: stable across float noise. */
-const EXACT_LEVEL_BITS = 20
-
/**
- * The level a settled view renders at: the device scale itself, so tiles draw on whole device
- * pixels without resampling, rounded so a gesture that ends a few ulps from where it began
- * finds its tiles again instead of rendering them anew. Quantized levels serve the backdrop.
+ * How long after a content change the background stages wait: an edit in progress, such as
+ * typing, invalidates the page copy and the backdrop under it at every keystroke, and a coarse
+ * tile over thousands of chunks costs a frame or more to render from the scene, so they are
+ * rebuilt once the content has been still for this long.
*/
-function exactTileLevel(scale: number): number {
- const clamped = Math.min(MAX_TILE_LEVEL, Math.max(MIN_TILE_LEVEL, scale))
- return 2 ** (Math.round(Math.log2(clamped) * 2 ** EXACT_LEVEL_BITS) / 2 ** EXACT_LEVEL_BITS)
-}
-
-function smoothCost(previous: number | undefined, costMs: number): number {
- if (previous === undefined) return costMs
- return previous * (1 - TILE_COST_SMOOTHING) + costMs * TILE_COST_SMOOTHING
-}
-
+const BACKGROUND_QUIET_MS = 300
export interface TiledSceneFrameResult {
/** Every visible tile exists at the current level. */
covered: boolean
@@ -103,29 +98,33 @@ export class TiledSceneController {
private navigationGeneration = -1
private navigationActive = false
private cancelledJobs = 0
- private pendingInvalidations: Array<{
- nodeId: string
- previousBounds: TileWorldBounds[]
- }> = []
+ private pendingInvalidations: PendingInvalidation[] = []
+ /** Layers added, removed, moved between parents, or changed in kind since the last frame. */
+ private pendingStructure: PendingStructureChange[] = []
private lastCoveredGeneration = ''
private lastLevel: number | null = null
+ /**
+ * The level whose visible tiles have all been presented at once. Another level's tiles are
+ * held back, with the nearest level scaled in their place, until every visible one exists, so
+ * a zoom ends with the viewport sharpening in one frame rather than tile by tile. The level
+ * once committed, tiles a pan reveals or an edit renews present as they land.
+ */
+ private committedLevel: number | null = null
/**
* Set when a frame of background work evicted a tile its own plan needs: the cache cannot hold
* the plan, so the stages stop rather than render each other out until the view changes.
*/
private backgroundSaturated = false
+ /** When the content last changed, so the background stages wait for a quiet spell. */
+ private lastContentChangeAt = Number.NEGATIVE_INFINITY
+ /** The last frame withheld the background stages for the quiet spell: frames must go on. */
+ private backgroundWaiting = false
private readonly tileCacheBudget: (viewportBytes: number) => number
private readonly pictureCache = new RenderChunkPictureCache()
private readonly tileCache = new TileImageCache()
private readonly surfacePool = new TileSurfacePool()
private readonly scheduler: TileScheduler
- /** Smoothed render time of each tile already rendered, in ms. */
- private readonly measuredCosts = new Map<string, number>()
- /**
- * Smoothed render time of any tile, in ms: the estimate for a tile not rendered yet. The
- * scheduler compares estimates with its frame budget, so they must be times, not node counts.
- */
- private typicalCostMs: number | undefined
+ private readonly costs = new TileCostModel()
constructor(options: TiledSceneControllerOptions = {}) {
this.now = options.now ?? rendererNow
@@ -146,7 +145,7 @@ export class TiledSceneController {
node &&
owningChunks.some((chunk) => chunk.interruptible === nodeRequiresAtomicChunk(graph, node))
) {
- this.invalidateStructure()
+ this.invalidateStructure(nodeId, node.parentId)
return
}
this.pendingInvalidations.push({
@@ -155,8 +154,19 @@ export class TiledSceneController {
})
}
- invalidateStructure(): void {
- this.invalidate()
+ /**
+ * A structural change: `nodeId` was added, removed, moved under another parent, or changed in
+ * a way that reshapes its chunks. The page child whose subtree holds it is rebuilt at the next
+ * frame, with its pictures and the tiles it touched; the rest of the page keeps its tiles.
+ * Without a layer, as when a document loads or is replaced, everything is dropped.
+ */
+ invalidateStructure(nodeId?: string, parentId?: string | null): void {
+ if (nodeId === undefined) {
+ this.invalidate()
+ return
+ }
+ if (!this.index) return
+ this.pendingStructure.push({ nodeId, parentId: parentId ?? null })
}
/**
@@ -165,7 +175,7 @@ export class TiledSceneController {
* settlement means the visible tiles.
*/
hasPendingWork(): boolean {
- return this.pendingInvalidations.length > 0
+ return this.pendingInvalidations.length > 0 || this.pendingStructure.length > 0
}
/** The tile cache's current byte budget. */
@@ -177,10 +187,12 @@ export class TiledSceneController {
* Renders due tiles within the frame's budget and presents the viewport from the cache: exact
* tiles where they exist, the nearest level's tiles scaled where they do not, and the page
* colour where no level has one, until its tile renders. Nothing is drawn straight from the
- * scene, whose whole-page picture a large document cannot afford. Navigation keeps presenting,
- * renders under a shorter budget while panning or paused, and renders nothing while the zoom
- * level moves; the retained backing plays no part. Idle time builds a pyramid of downsampled copies and a
- * scene-rendered backdrop around the viewport, so a zoom out finds scaled stand-ins.
+ * scene, whose whole-page picture a large document cannot afford. Navigation keeps presenting
+ * and renders under a shorter budget: the exact level while panning or paused, and while the
+ * zoom level moves the quantized step at or above the scale, whose tiles outlive the frame and
+ * stand in, scaled by a fifth at most, until the exact level is complete; the retained backing
+ * plays no part. Idle time builds a pyramid of downsampled copies and a scene-rendered
+ * backdrop around the viewport, so a zoom out finds scaled stand-ins.
*/
renderFrame(
renderer: SkiaRenderer,
@@ -201,12 +213,15 @@ export class TiledSceneController {
const index = this.index
if (!index || !renderer.pageId) return this.emptyResult()
- // A zoom in motion changes level every frame, and a tile rendered mid-gesture is obsolete
- // within a few frames, so while the level moves nothing renders and the pyramid, the page
- // copy, and the earlier levels stand in, scaled; a zoom that pauses, and a pan, render at
- // the exact level under the moving budget.
- const level = exactTileLevel(renderer.zoom * renderer.dpr)
+ // A zoom in motion changes the exact level every frame, and a tile rendered at it is obsolete
+ // within a few frames, so while the level moves the frame renders the quantized step at or
+ // above the scale instead: its tiles serve every frame until the zoom crosses the next step,
+ // and then stand in for the exact level, scaled down by a fifth at most. A zoom that pauses,
+ // and a pan, render the exact level under the moving budget.
+ const scale = renderer.zoom * renderer.dpr
+ const level = exactTileLevel(scale)
const zooming = renderer.navigationPhase === 'zoom' && level !== this.lastLevel
+ const renderLevel = zooming ? tileLevel(scale) : level
if (level !== this.lastLevel || this.navigationActive) this.backgroundSaturated = false
this.lastLevel = level
this.tileCache.setBudget(
@@ -221,25 +236,18 @@ export class TiledSceneController {
renderer,
renderer.pageId,
index,
- level,
+ renderLevel,
viewport,
contentGeneration,
navigationGeneration
)
const plan = planTiles(this.tileCache, planOptions)
- let metrics: TileSchedulerMetrics
- if (zooming) {
- metrics = emptyTileSchedulerMetrics()
- metrics.remaining = plan.jobs.length
- metrics.skippedWithFallback = plan.jobs.filter((job) => job.fallbackAvailable).length
- } else {
- this.scheduler.enqueue(plan.jobs)
- metrics = this.scheduler.runFrame(
- (job, remainingMs) => this.executeJob(renderer, graph, index, job, remainingMs),
- this.navigationActive ? NAVIGATION_TILE_BUDGET_MS : TILE_FRAME_BUDGET_MS,
- this.firstJobLimit()
- )
- }
+ this.scheduler.enqueue(plan.jobs)
+ const metrics = this.scheduler.runFrame(
+ (job, remainingMs) => this.executeJob(renderer, graph, index, job, remainingMs),
+ this.navigationActive ? NAVIGATION_TILE_BUDGET_MS : TILE_FRAME_BUDGET_MS,
+ this.firstJobLimit()
+ )
metrics.cancelledJobs += this.cancelledJobs
this.cancelledJobs = 0
// A background tile that evicted one of the plan's own levels would render in circles.
@@ -269,13 +277,7 @@ export class TiledSceneController {
},
true
).visible
- const presentation = resolveVisible(
- this.tileCache,
- visible,
- renderer.pageId,
- level,
- index.bounds()
- )
+ const presentation = this.presentLevel(visible, renderer.pageId, level, index.bounds())
canvas.save()
// Snapped to device pixels, an exact tile lands texel on pixel and copies rather than samples.
canvas.translate(
@@ -316,7 +318,8 @@ export class TiledSceneController {
return {
covered,
pending: visiblePending || !covered,
- backgroundPending: !this.navigationActive && this.scheduler.pending() > 0,
+ backgroundPending:
+ !this.navigationActive && (this.scheduler.pending() > 0 || this.backgroundWaiting),
metrics,
fallbackTileCount: presentation.fallback.length,
uncoveredAreaCount: presentation.uncovered,
@@ -324,6 +327,26 @@ export class TiledSceneController {
}
}
+ /**
+ * A level arrives whole: until every visible tile exists, those that do stay hidden behind
+ * the nearest level, which the zoom just rendered, or behind the page colour when a page is
+ * first shown, and the level is committed once they all exist, after which tiles present as
+ * they land.
+ */
+ private presentLevel(
+ visible: TilePlan['visible'],
+ pageId: string,
+ level: number,
+ content: TileWorldBounds | null
+ ): VisiblePresentation {
+ if (this.committedLevel !== level && visible.every(({ tile }) => tile !== null)) {
+ this.committedLevel = level
+ }
+ const presented =
+ this.committedLevel === level ? visible : visible.map(({ key }) => ({ key, tile: null }))
+ return resolveVisible(this.tileCache, presented, pageId, level, content)
+ }
+
invalidate(): void {
this.cancelledJobs += this.scheduler.clear()
this.index?.dispose()
@@ -332,8 +355,12 @@ export class TiledSceneController {
this.contentGeneration = -1
this.lastCoveredGeneration = ''
this.lastLevel = null
+ this.committedLevel = null
+ this.lastContentChangeAt = Number.NEGATIVE_INFINITY
+ this.backgroundWaiting = false
this.pendingInvalidations = []
- this.measuredCosts.clear()
+ this.pendingStructure = []
+ this.costs.clear()
this.pictureCache.clear()
this.tileCache.clear()
}
@@ -343,7 +370,6 @@ export class TiledSceneController {
this.cancelledJobs = 0
this.navigationGeneration = -1
this.navigationActive = false
- this.typicalCostMs = undefined
this.surfacePool.clear()
}
@@ -367,6 +393,9 @@ export class TiledSceneController {
// invalidateStructure(), so a new content generation on its own is a redraw request (every
// requestRender() bumps it) and the rendered tiles stay valid. Invalidations also arrive
// without a new generation, as when an image preview decodes.
+ if (this.index && this.pageId === renderer.pageId && this.pendingStructure.length > 0) {
+ this.applyPendingStructure(graph, contentGeneration)
+ }
if (
this.index &&
this.pageId === renderer.pageId &&
@@ -383,23 +412,36 @@ export class TiledSceneController {
}
private applyPendingInvalidations(graph: SceneGraph, contentGeneration: number): void {
- const index = this.index
- if (!index || !this.pageId) return
- this.tileCache.advanceGeneration(contentGeneration)
- for (const invalidation of this.pendingInvalidations) {
- const before = invalidation.previousBounds
- const chunks = index.getChunksDependingOnNode(invalidation.nodeId)
- for (const chunk of chunks) this.pictureCache.invalidate(chunk.id)
- for (const chunk of chunks) index.updateNode(graph, chunk.nodeId)
- const after = index.getChunksDependingOnNode(invalidation.nodeId)
- for (const bounds of [...before, ...after]) {
- this.tileCache.invalidateBounds(this.pageId, bounds, contentGeneration)
- }
- }
+ const page = this.pageTiles()
+ if (!page) return
+ applyInvalidations(page, graph, this.pendingInvalidations, contentGeneration)
+ if (this.pendingInvalidations.length > 0) this.lastContentChangeAt = this.now()
this.pendingInvalidations = []
this.contentGeneration = contentGeneration
}
+ private applyPendingStructure(graph: SceneGraph, contentGeneration: number): void {
+ const page = this.pageTiles()
+ if (!page) return
+ if (!applyStructureChanges(page, graph, this.pendingStructure, contentGeneration)) {
+ this.invalidate()
+ return
+ }
+ this.pendingStructure = []
+ this.contentGeneration = contentGeneration
+ this.lastContentChangeAt = this.now()
+ }
+
+ private pageTiles(): PageTiles | null {
+ if (!this.index || !this.pageId) return null
+ return {
+ index: this.index,
+ pageId: this.pageId,
+ pictureCache: this.pictureCache,
+ tileCache: this.tileCache
+ }
+ }
+
private ensureIndex(graph: SceneGraph, pageId: string | null, contentGeneration: number): void {
if (this.index && this.pageId === pageId && this.contentGeneration === contentGeneration) return
this.index?.dispose()
@@ -421,56 +463,6 @@ export class TiledSceneController {
return this.navigationActive ? NAVIGATION_FIRST_TILE_LIMIT_MS : Number.POSITIVE_INFINITY
}
- /**
- * A tile over nothing is free; while moving, a tile with a chunk picture still to record is
- * beyond the frame, since recording cannot be bounded below one chunk; otherwise the tile's
- * own smoothed cost, or that of any tile until it has been measured.
- */
- private estimateCost(
- renderer: SkiaRenderer,
- index: RenderChunkIndex,
- key: TileKey,
- moving: boolean
- ): number {
- const chunks = tileChunks(index, key)
- if (chunks.length === 0) return 0
- if (
- moving &&
- chunks.some(
- (chunk) =>
- (chunk.kind !== 'subtree' || chunk.interruptible) &&
- !this.pictureCache.has(renderer, chunk)
- )
- ) {
- return Number.POSITIVE_INFINITY
- }
- return this.measuredCosts.get(this.costKey(key)) ?? this.typicalCostMs ?? 0
- }
-
- /**
- * Recording a chunk's picture is the dear part of a tile, so a tile whose chunks are not all
- * recorded yet records them until the frame's budget is spent and defers the rest; the tile
- * itself renders, from recorded pictures, on the frame that finds them all present.
- */
- private recordChunkPictures(
- renderer: SkiaRenderer,
- graph: SceneGraph,
- index: RenderChunkIndex,
- key: TileKey,
- remainingMs: number
- ): boolean {
- const deadline = this.now() + remainingMs
- let recorded = 0
- for (const chunk of tileChunks(index, key)) {
- if (chunk.kind === 'subtree' && !chunk.interruptible) continue
- if (this.pictureCache.has(renderer, chunk)) continue
- if (recorded > 0 && this.now() >= deadline) return false
- this.pictureCache.get(renderer, graph, chunk)
- recorded++
- }
- return true
- }
-
/**
* The frame's plan options: the visible tiles and, while idle and the cache can hold them, the
* background stages; queued jobs for other levels are discarded, and the cache counts the
@@ -488,7 +480,8 @@ export class TiledSceneController {
// Jobs planned at another level draw nothing the viewport shows now; a downsample is cheap
// and feeds the fallback at any level, so it stays.
const backdropLevel = tileLevel((level / BACKDROP_LEVEL_RATIO) * (1 - 1e-9))
- const pageBackdrop = this.pageBackdrop(index, level)
+ const pageBackdrop = pageBackdropPlan(index.bounds(), level)
+ if (pageBackdrop) this.tileCache.touchLevel(pageId, pageBackdrop.level)
this.cancelledJobs += this.scheduler.discard(
(job) =>
job.kind !== 'downsample' &&
@@ -503,11 +496,23 @@ export class TiledSceneController {
overscanTiles: this.backgroundSaturated ? 0 : TILE_OVERSCAN,
navigationGeneration,
contentGeneration,
- estimateCost: (key) => this.estimateCost(renderer, index, key, this.navigationActive),
+ estimateCost: (key) =>
+ estimateTileCost(
+ renderer,
+ index,
+ this.pictureCache,
+ this.costs,
+ key,
+ this.navigationActive
+ ),
globalFallbackAvailable: true
}
- // Background stages wait for idle: a moving frame has only its budget to give.
- const background = !this.navigationActive && !this.backgroundSaturated
+ // Background stages wait for idle, a moving frame having only its budget to give, and for
+ // the content to have been still a while, so an edit in progress rebuilds the visible tiles
+ // alone.
+ const quiet = this.now() - this.lastContentChangeAt >= BACKGROUND_QUIET_MS
+ const background = !this.navigationActive && !this.backgroundSaturated && quiet
+ this.backgroundWaiting = !this.navigationActive && !this.backgroundSaturated && !quiet
if (background) {
planOptions.backdrop = { level: backdropLevel, overscanTiles: BACKDROP_OVERSCAN }
planOptions.pageBackdrop = pageBackdrop
@@ -530,7 +535,10 @@ export class TiledSceneController {
const startedAt = this.now()
if (
job.kind !== 'downsample' &&
- !this.recordChunkPictures(renderer, graph, index, job.key, remainingMs)
+ !recordTilePictures(renderer, graph, index, this.pictureCache, job.key, {
+ now: this.now,
+ remainingMs
+ })
) {
return { renderMs: this.now() - startedAt, overBudget: false, deferred: true }
}
@@ -539,20 +547,22 @@ export class TiledSceneController {
? this.downsample(renderer, job)
: renderTile(renderer, graph, index, job.key, this.pictureCache, this.surfacePool)
if (!tile) return { renderMs: 0, overBudget: job.kind !== 'downsample' }
- if (job.kind !== 'downsample') this.recordCost(job.key, this.now() - startedAt)
+ if (job.kind !== 'downsample') {
+ this.costs.record(job.key, this.now() - startedAt, tile.chunkCount)
+ }
if (
job.navigationGeneration !== this.navigationGeneration ||
job.contentGeneration !== this.contentGeneration
) {
deleteRenderedTile(tile)
- return this.jobResult(tile)
+ return tileJobResult(tile, TILE_FRAME_BUDGET_MS)
}
this.tileCache.takeWatchedEvictions()
this.tileCache.install(tile, job.contentGeneration)
if (job.priority === 'overscan' && this.tileCache.takeWatchedEvictions() > 0) {
this.backgroundSaturated = true
}
- return this.jobResult(tile)
+ return tileJobResult(tile, TILE_FRAME_BUDGET_MS)
}
/** Null when a child has gone since the job was planned; the next plan decides again. */
@@ -566,53 +576,11 @@ export class TiledSceneController {
return downsampleTile(renderer, job.key, children, this.surfacePool)
}
- /**
- * The whole page at a level coarse enough to fit PAGE_BACKDROP_TILES along its longer side,
- * or undefined when the visible level is already that coarse. The level depends only on the
- * page, so its tiles stay valid across zooms.
- */
- private pageBackdrop(
- index: RenderChunkIndex,
- level: number
- ): { level: number; bounds: TileWorldBounds } | undefined {
- const bounds = index.bounds()
- if (!bounds) return undefined
- const span = Math.max(bounds.maxX - bounds.minX, bounds.maxY - bounds.minY, 1)
- const pageLevel = Math.max(
- MIN_TILE_LEVEL,
- tileLevel((PAGE_BACKDROP_TILES * TILE_DEVICE_SIZE) / span)
- )
- if (pageLevel >= level) return undefined
- return { level: pageLevel, bounds }
- }
-
/** Whether the cache holds a fresh tile for `key`. */
isRendered(key: TileKey): boolean {
return this.tileCache.getIfPresent(key)?.contentGeneration === this.contentGeneration
}
- private jobResult(tile: NonNullable<ReturnType<typeof renderTile>>) {
- return {
- renderMs: tile.renderMs,
- overBudget: tile.renderMs > TILE_FRAME_BUDGET_MS,
- allocationMs: tile.allocationMs,
- drawMs: tile.drawMs,
- flushMs: tile.flushMs,
- snapshotMs: tile.snapshotMs,
- chunkCount: tile.chunkCount
- }
- }
-
- private recordCost(key: TileKey, costMs: number): void {
- const id = this.costKey(key)
- this.measuredCosts.set(id, smoothCost(this.measuredCosts.get(id), costMs))
- this.typicalCostMs = smoothCost(this.typicalCostMs, costMs)
- }
-
- private costKey(key: TileKey): string {
- return `${key.level}:${key.x}:${key.y}`
- }
-
private emptyResult(): TiledSceneFrameResult {
return {
covered: false,
diff --git a/packages/core/src/canvas/renderer/tiles/cost.ts b/packages/core/src/canvas/renderer/tiles/cost.ts
new file mode 100644
index 000000000..938740666
--- /dev/null
+++ b/packages/core/src/canvas/renderer/tiles/cost.ts
@@ -0,0 +1,60 @@
+import type { TileKey } from './geometry'
+
+const TILE_COST_SMOOTHING = 0.3
+/** Tiles whose own time is kept; past this the oldest reading goes, a session never clearing. */
+const MAX_MEASURED_TILES = 4096
+
+function smoothCost(previous: number | undefined, costMs: number): number {
+ if (previous === undefined) return costMs
+ return previous * (1 - TILE_COST_SMOOTHING) + costMs * TILE_COST_SMOOTHING
+}
+
+/**
+ * Smoothed render times of the tiles rendered so far, in ms, for the scheduler's estimates: a
+ * tile rendered before is estimated at its own smoothed time, and one not rendered yet from
+ * its chunk count, since a coarse tile over a whole page costs a hundred times one over a
+ * corner of it, at the per-chunk time of its own level first, since a chunk clipped to a fine
+ * tile costs less than one drawn whole into a coarse one. The scheduler compares estimates with
+ * its frame budget, so they must be times, not counts.
+ */
+export class TileCostModel {
+ private readonly measured = new Map<string, number>()
+ private readonly perChunkMsByLevel = new Map<number, number>()
+ private perChunkMs: number | undefined
+
+ /** The estimated render time of `key`, which has `chunkCount` chunks to draw. */
+ estimate(key: TileKey, chunkCount: number): number {
+ const measured = this.measured.get(this.id(key))
+ if (measured !== undefined) return measured
+ const perChunk = this.perChunkMsByLevel.get(key.level) ?? this.perChunkMs ?? 0
+ return perChunk * chunkCount
+ }
+
+ record(key: TileKey, costMs: number, chunkCount: number): void {
+ const id = this.id(key)
+ const previous = this.measured.get(id)
+ if (previous !== undefined) this.measured.delete(id)
+ else if (this.measured.size >= MAX_MEASURED_TILES) {
+ const oldest = this.measured.keys().next().value
+ if (oldest !== undefined) this.measured.delete(oldest)
+ }
+ this.measured.set(id, smoothCost(previous, costMs))
+ if (chunkCount === 0) return
+ const perChunk = costMs / chunkCount
+ this.perChunkMsByLevel.set(
+ key.level,
+ smoothCost(this.perChunkMsByLevel.get(key.level), perChunk)
+ )
+ this.perChunkMs = smoothCost(this.perChunkMs, perChunk)
+ }
+
+ clear(): void {
+ this.measured.clear()
+ this.perChunkMsByLevel.clear()
+ this.perChunkMs = undefined
+ }
+
+ private id(key: TileKey): string {
+ return `${key.level}:${key.x}:${key.y}`
+ }
+}
diff --git a/packages/core/src/canvas/renderer/tiles/geometry.ts b/packages/core/src/canvas/renderer/tiles/geometry.ts
index 5e0436ede..e88ed310e 100644
--- a/packages/core/src/canvas/renderer/tiles/geometry.ts
+++ b/packages/core/src/canvas/renderer/tiles/geometry.ts
@@ -63,3 +63,16 @@ export function tileKeysForWorldBounds(
export function tileKeyString(key: TileKey): string {
return `${key.pageId}:${key.level}:${key.x}:${key.y}`
}
+
+/** Exact levels are keyed to this many bits of the scale's logarithm: stable across float noise. */
+const EXACT_LEVEL_BITS = 20
+
+/**
+ * The level a settled view renders at: the device scale itself, so tiles draw on whole device
+ * pixels without resampling, rounded so a gesture that ends a few ulps from where it began
+ * finds its tiles again instead of rendering them anew. Quantized levels serve the backdrop.
+ */
+export function exactTileLevel(scale: number): number {
+ const clamped = Math.min(MAX_TILE_LEVEL, Math.max(MIN_TILE_LEVEL, scale))
+ return 2 ** (Math.round(Math.log2(clamped) * 2 ** EXACT_LEVEL_BITS) / 2 ** EXACT_LEVEL_BITS)
+}
diff --git a/packages/core/src/canvas/renderer/tiles/planner.ts b/packages/core/src/canvas/renderer/tiles/planner.ts
index e65e456c4..5cb5f26b8 100644
--- a/packages/core/src/canvas/renderer/tiles/planner.ts
+++ b/packages/core/src/canvas/renderer/tiles/planner.ts
@@ -1,9 +1,11 @@
import type { CachedTile, TileImageCache } from './cache'
import {
MIN_TILE_LEVEL,
+ TILE_DEVICE_SIZE,
type TileKey,
type TileWorldBounds,
tileKeysForWorldBounds,
+ tileLevel,
tileWorldBounds,
tileKeyString,
tileWorldSize
@@ -38,6 +40,28 @@ export interface TilePlanOptions {
pyramid?: { levels: number }
}
+/** The whole page is kept at a level where its longer side spans this many tiles. */
+const PAGE_BACKDROP_TILES = 4
+
+/**
+ * The whole page at a level coarse enough to fit PAGE_BACKDROP_TILES along its longer side, or
+ * undefined when the visible level is already that coarse. The level depends only on the page,
+ * so its tiles stay valid across zooms.
+ */
+export function pageBackdropPlan(
+ bounds: TileWorldBounds | null,
+ level: number
+): { level: number; bounds: TileWorldBounds } | undefined {
+ if (!bounds) return undefined
+ const span = Math.max(bounds.maxX - bounds.minX, bounds.maxY - bounds.minY, 1)
+ const pageLevel = Math.max(
+ MIN_TILE_LEVEL,
+ tileLevel((PAGE_BACKDROP_TILES * TILE_DEVICE_SIZE) / span)
+ )
+ if (pageLevel >= level) return undefined
+ return { level: pageLevel, bounds }
+}
+
export interface TilePlan {
jobs: TileJob[]
visible: Array<{ key: TileKey; tile: CachedTile | null }>
diff --git a/packages/core/src/canvas/renderer/tiles/presentation.ts b/packages/core/src/canvas/renderer/tiles/presentation.ts
index ae187c709..022b05d29 100644
--- a/packages/core/src/canvas/renderer/tiles/presentation.ts
+++ b/packages/core/src/canvas/renderer/tiles/presentation.ts
@@ -36,7 +36,7 @@ export function resolveVisible(
continue
}
levels ??= cache.fallbackLevels(pageId, level)
- const tiles = cache.findFallback(key, levels)
+ const tiles = cache.findFallback(key, levels, content)
if (tiles) {
presentation.fallback.push({ key, tiles })
continue
diff --git a/packages/core/src/canvas/renderer/tiles/render.ts b/packages/core/src/canvas/renderer/tiles/render.ts
index 2e348850b..7734e2b42 100644
--- a/packages/core/src/canvas/renderer/tiles/render.ts
+++ b/packages/core/src/canvas/renderer/tiles/render.ts
@@ -12,7 +12,9 @@ import {
import { rendererNow } from '#core/canvas/renderer/clock'
import type { CachedTile } from './cache'
+import type { TileCostModel } from './cost'
import { TILE_DEVICE_SIZE, type TileKey, tileWorldBounds } from './geometry'
+import type { TileJobResult } from './scheduler'
import type { TileSurfacePool } from './surface-pool'
export interface RenderedTile {
@@ -56,6 +58,8 @@ export function renderTile(
if (!surface) return null
const allocationMs = rendererNow() - allocationStartedAt
const canvas = surface.getCanvas()
+ const previousDetail = renderer.imageDetailScale
+ renderer.imageDetailScale = key.level
canvas.save()
try {
canvas.clear(
@@ -111,6 +115,7 @@ export function renderTile(
}
} finally {
canvas.restore()
+ renderer.imageDetailScale = previousDetail
surfacePool.release(surface)
}
}
@@ -211,6 +216,19 @@ export function downsampleTile(
}
}
+/** The scheduler's account of a rendered tile: over budget when it alone took longer than one. */
+export function tileJobResult(tile: RenderedTile, budgetMs: number): TileJobResult {
+ return {
+ renderMs: tile.renderMs,
+ overBudget: tile.renderMs > budgetMs,
+ allocationMs: tile.allocationMs,
+ drawMs: tile.drawMs,
+ flushMs: tile.flushMs,
+ snapshotMs: tile.snapshotMs,
+ chunkCount: tile.chunkCount
+ }
+}
+
export function deleteRenderedTile(tile: RenderedTile): void {
tile.image?.delete()
}
@@ -218,3 +236,63 @@ export function deleteRenderedTile(tile: RenderedTile): void {
export function tileChunks(index: RenderChunkIndex, key: TileKey): RenderChunk[] {
return index.search(tileWorldBounds(key))
}
+
+/**
+ * The estimated time to render `key`: a tile over nothing is free; while moving, a tile with a
+ * chunk picture still to record is beyond the frame, since recording cannot be bounded below
+ * one chunk; otherwise the cost model's estimate.
+ */
+export function estimateTileCost(
+ renderer: SkiaRenderer,
+ index: RenderChunkIndex,
+ pictureCache: RenderChunkPictureCache,
+ costs: TileCostModel,
+ key: TileKey,
+ moving: boolean
+): number {
+ const chunks = tileChunks(index, key)
+ if (chunks.length === 0) return 0
+ if (
+ moving &&
+ chunks.some(
+ (chunk) =>
+ (chunk.kind !== 'subtree' || chunk.interruptible) && !pictureCache.has(renderer, chunk)
+ )
+ ) {
+ return Number.POSITIVE_INFINITY
+ }
+ return costs.estimate(key, chunks.length)
+}
+
+/**
+ * Recording a chunk's picture is the dear part of a tile, so a tile whose chunks are not all
+ * recorded yet records them until the frame's budget is spent and defers the rest; the tile
+ * itself renders, from recorded pictures, on the frame that finds them all present. False when
+ * some remain for the next frame.
+ */
+export function recordTilePictures(
+ renderer: SkiaRenderer,
+ graph: SceneGraph,
+ index: RenderChunkIndex,
+ pictureCache: RenderChunkPictureCache,
+ key: TileKey,
+ budget: { now: () => number; remainingMs: number }
+): boolean {
+ const deadline = budget.now() + budget.remainingMs
+ let recorded = 0
+ // Pictures record at the tile's detail, so their image previews suit its level.
+ const previousDetail = renderer.imageDetailScale
+ renderer.imageDetailScale = key.level
+ try {
+ for (const chunk of tileChunks(index, key)) {
+ if (chunk.kind === 'subtree' && !chunk.interruptible) continue
+ if (pictureCache.has(renderer, chunk)) continue
+ if (recorded > 0 && budget.now() >= deadline) return false
+ pictureCache.get(renderer, graph, chunk)
+ recorded++
+ }
+ } finally {
+ renderer.imageDetailScale = previousDetail
+ }
+ return true
+}
diff --git a/packages/core/src/canvas/renderer/tiles/structure.ts b/packages/core/src/canvas/renderer/tiles/structure.ts
new file mode 100644
index 000000000..c49d7d158
--- /dev/null
+++ b/packages/core/src/canvas/renderer/tiles/structure.ts
@@ -0,0 +1,134 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import type {
+ RenderChunk,
+ RenderChunkIndex,
+ RenderChunkPictureCache
+} from '#core/canvas/renderer/chunks'
+
+import type { TileImageCache } from './cache'
+import type { TileWorldBounds } from './geometry'
+
+/** Structural changes a frame applies one subtree at a time; more rebuild the whole page. */
+const MAX_INCREMENTAL_STRUCTURE_CHANGES = 32
+
+/** A layer that changed, with the bounds of the chunks that drew it before the change. */
+export interface PendingInvalidation {
+ nodeId: string
+ previousBounds: TileWorldBounds[]
+}
+
+/** A layer added, removed, or moved, with the parent that reported it. */
+export interface PendingStructureChange {
+ nodeId: string
+ parentId: string | null
+}
+
+/** What a page's changes are applied to: its chunk index and the caches built from it. */
+export interface PageTiles {
+ index: RenderChunkIndex
+ pageId: string
+ pictureCache: RenderChunkPictureCache
+ tileCache: TileImageCache
+}
+
+type ChunkChange = { removed: RenderChunk[]; added: RenderChunk[]; reordered?: boolean }
+
+/**
+ * Applies the layers' changes to the page: each chunk that drew a changed layer drops its
+ * picture and takes its new bounds, and the tiles under its old bounds and its new ones are
+ * marked for rendering again.
+ */
+export function applyInvalidations(
+ page: PageTiles,
+ graph: SceneGraph,
+ invalidations: readonly PendingInvalidation[],
+ contentGeneration: number
+): void {
+ const { index, pageId, pictureCache, tileCache } = page
+ tileCache.advanceGeneration(contentGeneration)
+ for (const invalidation of invalidations) {
+ const before = invalidation.previousBounds
+ const chunks = index.getChunksDependingOnNode(invalidation.nodeId)
+ for (const chunk of chunks) pictureCache.invalidate(chunk.id)
+ for (const chunk of chunks) index.updateNode(graph, chunk.nodeId)
+ const after = index.getChunksDependingOnNode(invalidation.nodeId)
+ for (const bounds of [...before, ...after]) {
+ tileCache.invalidateBounds(pageId, bounds, contentGeneration)
+ }
+ }
+}
+
+/**
+ * Applies the structural changes to the page, one layer at a time: the chunks of the smallest
+ * subtree that held each are built again, their pictures dropped, and the tiles they touched
+ * marked for rendering again. False when the page must be built from nothing instead: the page
+ * is gone, a change cannot be placed, or a bulk edit such as a paste of hundreds of layers would
+ * read the whole index once per layer.
+ */
+export function applyStructureChanges(
+ page: PageTiles,
+ graph: SceneGraph,
+ changes: readonly PendingStructureChange[],
+ contentGeneration: number
+): boolean {
+ const { index, pageId, pictureCache, tileCache } = page
+ if (!graph.getNode(pageId)) return false
+ if (changes.length > MAX_INCREMENTAL_STRUCTURE_CHANGES) return false
+ tileCache.advanceGeneration(contentGeneration)
+ let reordered = false
+ const rebuiltIds = new Set<string>()
+ for (const { nodeId, parentId } of changes) {
+ // A layer is rebuilt once, however many parents reported it: a move reports both.
+ if (rebuiltIds.has(nodeId)) continue
+ rebuiltIds.add(nodeId)
+ const node = graph.getNode(nodeId)
+ let changed: ChunkChange | null = null
+ if (node) changed = rebuildLayer(graph, index, pageId, node)
+ else if (parentId) changed = index.pruneUnder(graph, pageId, parentId)
+ if (!changed) return false
+ reordered ||= changed.reordered === true
+ for (const chunk of changed.removed) pictureCache.invalidate(chunk.id)
+ for (const chunk of changed.removed)
+ tileCache.invalidateBounds(pageId, chunk, contentGeneration)
+ for (const chunk of changed.added) tileCache.invalidateBounds(pageId, chunk, contentGeneration)
+ }
+ if (reordered) index.renumber(graph, pageId)
+ return true
+}
+
+/**
+ * Rebuilds the chunks of a layer added, moved, or reordered, where it is now: a page child's top
+ * whole, which also drops the chunks of a layer that left the page, or else the layer's own
+ * chunks under its nearest chunk owner; and the subtree chunks that drew it on its old path are
+ * built again without it, so a move leaves no ghost behind. A page child changes the draw order
+ * of all, which the caller renumbers.
+ */
+function rebuildLayer(
+ graph: SceneGraph,
+ index: RenderChunkIndex,
+ pageId: string,
+ node: SceneNode
+): ChunkChange | null {
+ const holding = index.chunksHolding(graph, node.id)
+ const removed: RenderChunk[] = []
+ const added: RenderChunk[] = []
+ const merge = (change: ChunkChange | null) => {
+ if (!change) return false
+ removed.push(...change.removed)
+ added.push(...change.added)
+ return true
+ }
+ const reordered = node.parentId === pageId || index.hasTop(node.id)
+ if (reordered) merge(index.rebuildTop(graph, pageId, node.id))
+ if (node.parentId !== pageId) {
+ removed.push(...index.dropChunksOf(graph, node.id))
+ if (!merge(index.rebuildFrom(graph, pageId, node.id))) return null
+ }
+ for (const chunk of holding) {
+ // Replaced already when the old path and the new one share the owner.
+ if (!index.has(chunk.id)) continue
+ if (!merge(index.rebuildFrom(graph, pageId, chunk.nodeId))) return null
+ }
+ return { removed, added, reordered }
+}
diff --git a/packages/core/src/canvas/rulers.ts b/packages/core/src/canvas/rulers.ts
index 310197a35..75112185f 100644
--- a/packages/core/src/canvas/rulers.ts
+++ b/packages/core/src/canvas/rulers.ts
@@ -20,6 +20,7 @@ import {
RULER_MAJOR_TOLERANCE
} from '#core/constants'
+import { cachedGlyphWidth } from './labels/paragraph-cache'
import type { SkiaRenderer } from './renderer'
interface SelectionScreenBounds {
@@ -61,12 +62,14 @@ function drawHorizontalRulerTicks(
const worldRight = (vw - r.panX) / r.zoom
const startX = Math.floor(worldLeft / step) * step
+ // Every tick is one line segment in a single draw; only the labels are drawn one by one.
+ const ticks: number[] = []
for (let wx = startX; wx <= worldRight; wx += minorStep) {
const sx = wx * r.zoom + r.panX
if (sx < R) continue
const isMajor = Math.abs(wx % step) < RULER_MAJOR_TOLERANCE
const tickLen = isMajor ? R * RULER_MAJOR_TICK : R * RULER_MINOR_TICK
- canvas.drawLine(sx, R - tickLen, sx, R, r.rulerTickPaint)
+ ticks.push(sx, R - tickLen, sx, R)
if (isMajor) {
const skipForBadge =
@@ -77,6 +80,7 @@ function drawHorizontalRulerTicks(
}
}
}
+ canvas.drawPoints(r.ck.PointMode.Lines, ticks, r.rulerTickPaint)
canvas.restore()
}
@@ -98,12 +102,13 @@ function drawVerticalRulerTicks(
const worldBottom = (vh - r.panY) / r.zoom
const startY = Math.floor(worldTop / step) * step
+ const ticks: number[] = []
for (let wy = startY; wy <= worldBottom; wy += minorStep) {
const sy = wy * r.zoom + r.panY
if (sy < R) continue
const isMajor = Math.abs(wy % step) < RULER_MAJOR_TOLERANCE
const tickLen = isMajor ? R * RULER_MAJOR_TICK : R * RULER_MINOR_TICK
- canvas.drawLine(R - tickLen, sy, R, sy, r.rulerTickPaint)
+ ticks.push(R - tickLen, sy, R, sy)
if (isMajor) {
const skipForBadge =
@@ -118,6 +123,7 @@ function drawVerticalRulerTicks(
}
}
}
+ canvas.drawPoints(r.ck.PointMode.Lines, ticks, r.rulerTickPaint)
canvas.restore()
}
@@ -133,13 +139,6 @@ export function drawRulers(
const vh = r.viewportHeight
if (vw === 0 || vh === 0) return
- if (r.rulerTheme) {
- const { background, tick, text } = r.rulerTheme
- r.rulerBgPaint.setColor(r.ck.Color4f(background.r, background.g, background.b, background.a))
- r.rulerTickPaint.setColor(r.ck.Color4f(tick.r, tick.g, tick.b, tick.a))
- r.rulerTextPaint.setColor(r.ck.Color4f(text.r, text.g, text.b, text.a))
- }
-
canvas.drawRect(r.ck.LTRBRect(0, 0, vw, R), r.rulerBgPaint)
canvas.drawRect(r.ck.LTRBRect(0, R, R, vh), r.rulerBgPaint)
canvas.drawRect(r.ck.LTRBRect(0, 0, R, R), r.rulerBgPaint)
@@ -225,10 +224,9 @@ function drawGuideRulerLabel(
screenPosition: number
): void {
const label = String(Math.round(position * 100) / 100)
- r.auxFill.setColor(r.ck.Color4f(MEASUREMENT_COLOR.r, MEASUREMENT_COLOR.g, MEASUREMENT_COLOR.b, 1))
+ r.auxFill.setColorComponents(MEASUREMENT_COLOR.r, MEASUREMENT_COLOR.g, MEASUREMENT_COLOR.b, 1)
if (axis === 'x') {
- const widths = font.getGlyphWidths(font.getGlyphIDs(label))
- const textWidth = widths.reduce((sum, width) => sum + width, 0)
+ const textWidth = cachedGlyphWidth(r, font, label)
canvas.drawText(
label,
screenPosition - textWidth / 2,
@@ -305,9 +303,7 @@ export function drawRulerBadge(
axis: 'horizontal' | 'vertical'
): void {
const R = RULER_SIZE
- const glyphIds = font.getGlyphIDs(label)
- const widths = font.getGlyphWidths(glyphIds)
- const textW = widths.reduce((s, w) => s + w, 0)
+ const textW = cachedGlyphWidth(r, font, label)
const pad = RULER_BADGE_PADDING
const h = RULER_BADGE_HEIGHT
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 7bb7613bb..92906f5ca 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -1,28 +1,12 @@
-/* eslint-disable max-lines -- scene dispatch stays together while shape domains live in sibling modules */
-import type { Canvas, Path } from 'canvaskit-wasm'
+import type { Canvas } from 'canvaskit-wasm'
import { type SceneNode, type SceneGraph, type Fill } from '@open-pencil/scene-graph'
-import {
- arrowCapOverflow,
- collectArrowEndpoints,
- hasTrimmedShaft,
- trimArrowShafts
-} from '@open-pencil/scene-graph/arrow-caps'
-import Matrix from '@open-pencil/scene-graph/matrix'
-import type { Color } from '@open-pencil/scene-graph/primitives'
+import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'
+import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
import { textLinesOverflow } from '@open-pencil/scene-graph/text'
-import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'
-import { shownText } from '#core/text/case'
-import { mayHoldEmoji } from '#core/text/emoji'
+import { nodeOrientationMatrix, projectedNode } from '#core/geometry'
import { fontManager } from '#core/text/font/manager'
-import {
- addStrokeRunToPath,
- strokeRuns,
- vectorNetworkToCenterlinePath,
- vectorNetworkToPath
-} from '#core/vector'
-import { isOpenVectorNetwork } from '#core/vector/connectivity'
import { needsIsolatedBlendLayer, setPaintBlendMode } from './blend'
import { renderBooleanOperation } from './boolean'
@@ -31,39 +15,25 @@ import { drawVectorMultiStyleFills, paintFills } from './fills'
import { drawLayoutGrids } from './layout-grids'
import { renderMaskedChildIds } from './masks'
import type { SkiaRenderer, RenderOverlays } from './renderer'
-import {
- canCacheEffectRaster,
- effectRasterScale,
- effectRasterScaleMatches
-} from './renderer/effect-raster-cache'
+import { renderShapeThroughEffectCaches } from './renderer/effect-raster-cache'
import { mapVisualBounds, subtreeVisualBounds } from './renderer/visual-bounds'
import { isolatesInnerShadows, renderLayerShadows } from './shadows'
import { isLayerContainer } from './shadows/silhouette'
import {
configureStrokePaint,
- drawArrowHeads,
- applyStrokeShader,
drawDashedRRectWithSolidCorners,
drawStyledRRectStroke,
- getStrokeCapEntity,
- getStrokeJoinEntity,
- normalizeDashPattern,
- setStrokeBlendMode
+ forVisibleStrokes
} from './strokes'
-import { drawLineStroke } from './strokes/line'
-import { drawOutlinedDashes } from './strokes/outlined-dashes'
-import { drawDashedRectStroke, strokeDashesByOutline, strokeSideWeights } from './strokes/sides'
-import { textVerticalOffset, withTextParagraph } from './text'
-import { drawTextLayout } from './text/decorations'
import {
- canDrawSavedText,
- drawDerivedText,
- drawReflowedPathTextSilhouettes,
- drawsSavedText,
- isReflowedPathText
-} from './text/derived'
-import { drawLaidOutEmoji, drawSavedEmoji } from './text/emoji'
+ drawFigmaDashes,
+ isPathTextWithStrokeGeometry,
+ paintNodeStrokes,
+ vectorStrokePaths
+} from './strokes/dispatch'
+import { drawReflowedPathTextSilhouettes, isReflowedPathText } from './text/derived'
import { stickyPlaceholderNode } from './text/placeholder'
+import { drawTextEmoji, hasOverflowPathTextPaint, renderText } from './text/render'
function drawVisibleFills(
r: SkiaRenderer,
@@ -78,21 +48,44 @@ function hasNodeTransform(node: SceneNode): boolean {
return node.rotation !== 0 || node.flipX || node.flipY
}
-function hasOverflowPathTextPaint(node: SceneNode): boolean {
+/**
+ * The frame a node's children are placed in, composed on the way down: null while every ancestor
+ * is an unrotated, unflipped translation, which `absX`/`absY` carry more cheaply; from the first
+ * transformed layer on, its world matrix, so no node below it walks to the root to find its own.
+ */
+function childFrame(
+ frame: Mat3 | null,
+ node: SceneNode,
+ parentAbsX: number,
+ parentAbsY: number,
+ preview?: RenderOverlays['rotationPreview']
+): Mat3 | null {
+ const projected = projectedNode(node, preview)
+ if (frame) return Matrix.multiply(frame, getNodeLocalMatrix(projected))
+ if (!hasNodeTransform(projected)) return null
+ return Matrix.multiply(Matrix.translated(parentAbsX, parentAbsY), getNodeLocalMatrix(projected))
+}
+
+/** The node's world matrix from its frame, or from its absolute position when it has none. */
+function worldMatrixIn(
+ frame: Mat3 | null,
+ node: SceneNode,
+ parentAbsX: number,
+ parentAbsY: number,
+ preview?: RenderOverlays['rotationPreview']
+): Mat3 {
return (
- node.textPathData != null &&
- ((node.derivedTextGlyphs?.length ?? 0) > 0 ||
- (Array.isArray(node.strokeGeometry) && node.strokeGeometry.length > 0))
+ childFrame(frame, node, parentAbsX, parentAbsY, preview) ??
+ Matrix.translated(parentAbsX + node.x, parentAbsY + node.y)
)
}
function isCulled(
r: SkiaRenderer,
- graph: SceneGraph,
node: SceneNode,
absX: number,
absY: number,
- hasTransformedAncestor: boolean,
+ frame: Mat3 | null,
preview?: RenderOverlays['rotationPreview']
): boolean {
const canCull =
@@ -104,35 +97,31 @@ function isCulled(
const linesOverflow = textLinesOverflow(node)
const vp = r.worldViewport
- if (hasTransformedAncestor) {
- if (linesOverflow > 0) return false
- const bounds = createSceneGeometry(graph, preview).bounds(node)
- return (
- bounds.x > vp.x + vp.w ||
- bounds.y > vp.y + vp.h ||
- bounds.x + bounds.width < vp.x ||
- bounds.y + bounds.height < vp.y
- )
- }
const bw = node.width
const bh = node.height + linesOverflow
- if (projectedNode(node, preview).rotation !== 0) {
- const diag = Math.hypot(bw, bh)
- const { x: cx, y: cy } = createSceneGeometry(graph, preview).toWorld(node, {
- x: bw / 2,
- y: bh / 2
- })
+ if (frame || projectedNode(node, preview).rotation !== 0) {
+ const bounds = mapVisualBounds(
+ worldMatrixIn(frame, node, absX - node.x, absY - node.y, preview),
+ {
+ minX: 0,
+ minY: 0,
+ maxX: bw,
+ maxY: bh
+ }
+ )
return (
- cx - diag / 2 > vp.x + vp.w ||
- cy - diag / 2 > vp.y + vp.h ||
- cx + diag / 2 < vp.x ||
- cy + diag / 2 < vp.y
+ bounds.minX > vp.x + vp.w ||
+ bounds.minY > vp.y + vp.h ||
+ bounds.maxX < vp.x ||
+ bounds.maxY < vp.y
)
}
return absX > vp.x + vp.w || absY > vp.y + vp.h || absX + bw < vp.x || absY + bh < vp.y
}
function applyNodeTransforms(canvas: Canvas, node: SceneNode, overlays: RenderOverlays): void {
+ // Most layers are neither rotated nor flipped: their orientation is the identity, not a call.
+ if (!hasNodeTransform(projectedNode(node, overlays.rotationPreview))) return
canvas.concat(nodeOrientationMatrix(node, overlays.rotationPreview))
}
function renderNodeContent(
@@ -161,7 +150,8 @@ function renderMaskNodeContent(
node: SceneNode,
overlays: RenderOverlays,
absX: number,
- absY: number
+ absY: number,
+ frame: Mat3 | null
): void {
canvas.save()
canvas.translate(node.x, node.y)
@@ -185,7 +175,16 @@ function renderMaskNodeContent(
applyNodeTransforms(canvas, node, overlays)
renderNodeContent(r, canvas, graph, node.maskType === 'VECTOR' ? opaqueFills(node) : node, {})
// A group or frame used as a mask masks with what its layers draw, as in Figma.
- renderChildren(r, canvas, graph, node, overlays, absX + node.x, absY + node.y, true)
+ renderChildren(
+ r,
+ canvas,
+ graph,
+ node,
+ overlays,
+ absX + node.x,
+ absY + node.y,
+ childFrame(frame, node, absX, absY, overlays.rotationPreview)
+ )
if (layered) canvas.restore()
canvas.restore()
}
@@ -206,7 +205,7 @@ function renderChildIds(
overlays: RenderOverlays,
absX: number,
absY: number,
- hasTransformedAncestor: boolean
+ frame: Mat3 | null
): void {
renderMaskedChildIds(
r,
@@ -216,10 +215,10 @@ function renderChildIds(
const child = graph.getNode(childId)
return child?.visible && child.isMask ? child.maskType : null
},
- (childId) => r.renderNode(canvas, graph, childId, overlays, absX, absY, hasTransformedAncestor),
+ (childId) => r.renderNode(canvas, graph, childId, overlays, absX, absY, frame),
(childId) => {
const child = graph.getNode(childId)
- if (child) renderMaskNodeContent(r, canvas, graph, child, overlays, absX, absY)
+ if (child) renderMaskNodeContent(r, canvas, graph, child, overlays, absX, absY, frame)
},
(childId) => {
const child = graph.getNode(childId)
@@ -237,7 +236,7 @@ function renderChildren(
overlays: RenderOverlays,
absX: number,
absY: number,
- hasTransformedAncestor: boolean
+ frame: Mat3 | null
): void {
if (node.type === 'BOOLEAN_OPERATION') return
const isClippableContainer =
@@ -245,10 +244,10 @@ function renderChildren(
if (isClippableContainer && node.clipsContent && node.childIds.length > 0) {
canvas.save()
r.clipNodeShape(canvas, node)
- renderChildIds(r, canvas, graph, node.childIds, overlays, absX, absY, hasTransformedAncestor)
+ renderChildIds(r, canvas, graph, node.childIds, overlays, absX, absY, frame)
canvas.restore()
} else {
- renderChildIds(r, canvas, graph, node.childIds, overlays, absX, absY, hasTransformedAncestor)
+ renderChildIds(r, canvas, graph, node.childIds, overlays, absX, absY, frame)
}
}
export function renderNodeSelf(
@@ -276,15 +275,9 @@ export function renderNodeSelf(
canvas.restore()
}
-function viewportLayerBounds(
- r: SkiaRenderer,
- graph: SceneGraph,
- node: SceneNode,
- padding: number,
- preview?: RenderOverlays['rotationPreview']
-): Float32Array | null {
+function viewportLayerBounds(r: SkiaRenderer, world: Mat3, padding: number): Float32Array | null {
if (!r.boundEffectLayersToViewport) return null
- const inverse = Matrix.invert(createSceneGeometry(graph, preview).worldMatrix(node))
+ const inverse = Matrix.invert(world)
if (!inverse) return null
const viewport = r.worldViewport
const bounds = mapVisualBounds(inverse, {
@@ -309,9 +302,10 @@ function nodeIsolationLayerBounds(
r: SkiaRenderer,
graph: SceneGraph,
node: SceneNode,
+ world: Mat3,
preview?: RenderOverlays['rotationPreview']
): Float32Array {
- const viewportBounds = viewportLayerBounds(r, graph, node, 0, preview)
+ const viewportBounds = viewportLayerBounds(r, world, 0)
if (viewportBounds) return viewportBounds
const bounds = subtreeVisualBounds(graph, node, nodeOrientationMatrix(node, preview), preview)
return r.ck.LTRBRect(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
@@ -327,6 +321,11 @@ function drawsNode(node: SceneNode, overlays: RenderOverlays): boolean {
return overlays.nodeEditState?.nodeId !== node.id && !overlays.playIslands?.has(node.id)
}
+/**
+ * Draws a layer and its subtree. `frame` is the world matrix of the nearest transformed ancestor,
+ * or null when `parentAbsX`/`parentAbsY` place the layer; a chunk recorded in world space passes
+ * its parent's transform.
+ */
export function renderNode(
r: SkiaRenderer,
canvas: Canvas,
@@ -335,7 +334,7 @@ export function renderNode(
overlays: RenderOverlays,
parentAbsX = 0,
parentAbsY = 0,
- hasTransformedAncestor = false
+ frame: Mat3 | null = null
): void {
const found = graph.getNode(nodeId)
if (!found || !drawsNode(found, overlays)) return
@@ -346,7 +345,7 @@ export function renderNode(
const absX = parentAbsX + node.x
const absY = parentAbsY + node.y
- if (isCulled(r, graph, node, absX, absY, hasTransformedAncestor, overlays.rotationPreview)) {
+ if (isCulled(r, node, absX, absY, frame, overlays.rotationPreview)) {
r._culledCount++
return
}
@@ -354,9 +353,10 @@ export function renderNode(
canvas.save()
canvas.translate(node.x, node.y)
+ const world = () => worldMatrixIn(frame, node, parentAbsX, parentAbsY, overlays.rotationPreview)
const needsNodeLayer = node.opacity < 1 || needsIsolatedBlendLayer(node.blendMode)
if (needsNodeLayer) {
- const layerBounds = nodeIsolationLayerBounds(r, graph, node, overlays.rotationPreview)
+ const layerBounds = nodeIsolationLayerBounds(r, graph, node, world(), overlays.rotationPreview)
r.opacityPaint.setAlphaf(node.opacity)
setPaintBlendMode(r, r.opacityPaint, node.blendMode)
canvas.saveLayer(r.opacityPaint, layerBounds)
@@ -375,7 +375,7 @@ export function renderNode(
const blurPadding = layerBlur.radius * 2
canvas.saveLayer(
r.effectLayerPaint,
- viewportLayerBounds(r, graph, node, blurPadding, overlays.rotationPreview) ??
+ viewportLayerBounds(r, world(), blurPadding) ??
r.ck.LTRBRect(
-blurPadding,
-blurPadding,
@@ -397,7 +397,7 @@ export function renderNode(
overlays,
absX,
absY,
- hasTransformedAncestor || hasNodeTransform(projectedNode(node, overlays.rotationPreview))
+ childFrame(frame, node, parentAbsX, parentAbsY, overlays.rotationPreview)
)
renderLayerShadows(r, canvas, graph, node, 'front')
@@ -421,31 +421,6 @@ function makeNodeRRect(r: SkiaRenderer, node: SceneNode, radius: number): Float3
return r.ck.RRectXY(rect, radius, radius)
}
-/**
- * Every stroke a node draws passes through here, so a gradient or image stroke gets its shader
- * here rather than in each draw helper, and the shader is cleared before the next stroke.
- */
-function forVisibleStrokes(
- r: SkiaRenderer,
- node: SceneNode,
- graph: SceneGraph,
- draw: (stroke: SceneNode['strokes'][number], color: Color) => void
-): void {
- for (let index = 0; index < node.strokes.length; index++) {
- const stroke = node.strokes[index]
- if (!stroke.visible) continue
- const draws = applyStrokeShader(r, stroke, index, node, graph)
- setStrokeBlendMode(r, stroke.blendMode)
- try {
- if (draws) draw(stroke, r.resolveStrokeColor(stroke, index, node, graph))
- } finally {
- r.strokePaint.setShader(null)
- r.fillPaint.setShader(null)
- setStrokeBlendMode(r, 'NORMAL')
- }
- }
-}
-
/** Fill a section's or set's rounded bounds and return them, for its strokes to follow. */
function fillRoundedBounds(
r: SkiaRenderer,
@@ -514,490 +489,19 @@ function shapeEffects(node: SceneNode): SceneNode['effects'] {
)
}
-function canRasterCacheEffects(node: SceneNode): boolean {
- const visibleEffects = shapeEffects(node)
- return (
- visibleEffects.length > 0 &&
- visibleEffects.every(
- (effect) => effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
- )
- )
-}
-
export function renderShape(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
graph: SceneGraph
): void {
- const hasEffects = shapeEffects(node).length > 0
- if (r.viewportImageRendering || !hasEffects) {
+ const effects = shapeEffects(node)
+ if (r.viewportImageRendering || effects.length === 0) {
r.renderShapeUncached(canvas, node, graph)
return
}
- const canRasterCache = r.renderingSceneBacking && canRasterCacheEffects(node)
- const targetScale = effectRasterScale(r.zoom * r.dpr)
- const cachedRaster = canRasterCache ? r.effectRasterCache.get(node.id) : null
- if (
- cachedRaster &&
- (cachedRaster.fontGeneration !== r.fontGeneration ||
- !effectRasterScaleMatches(cachedRaster.scale, targetScale))
- ) {
- r.effectRasterCache.delete(node.id)
- } else if (cachedRaster) {
- canvas.drawImageRectOptions(
- cachedRaster.image,
- r.ck.LTRBRect(0, 0, cachedRaster.image.width(), cachedRaster.image.height()),
- r.ck.LTRBRect(
- cachedRaster.left,
- cachedRaster.top,
- cachedRaster.left + cachedRaster.width,
- cachedRaster.top + cachedRaster.height
- ),
- r.ck.FilterMode.Linear,
- r.ck.MipmapMode.None,
- null
- )
- return
- }
-
- const margin = Math.max(
- r.effectOverflow(node),
- arrowCapOverflow(node.strokes, node.strokeCap, node.vectorNetwork)
- )
- const width = node.width + margin * 2
- const height = node.height + margin * 2
- const scale = targetScale
- if (canRasterCache && canCacheEffectRaster(width, height, scale)) {
- const surface = r.surface.makeSurface({
- width: Math.ceil(width * scale),
- height: Math.ceil(height * scale),
- colorType: r.ck.ColorType.RGBA_8888,
- alphaType: r.ck.AlphaType.Premul,
- colorSpace: r.ck.ColorSpace.SRGB
- })
- const rasterCanvas = surface.getCanvas()
- try {
- rasterCanvas.clear(r.ck.TRANSPARENT)
- rasterCanvas.scale(scale, scale)
- rasterCanvas.translate(margin, margin)
- r.renderShapeUncached(rasterCanvas, node, graph)
- surface.flush()
- const image = surface.makeImageSnapshot()
- const retained = r.effectRasterCache.set(node.id, {
- image,
- left: -margin,
- top: -margin,
- width,
- height,
- scale,
- pixels: image.width() * image.height(),
- fontGeneration: r.fontGeneration
- })
- try {
- canvas.drawImageRectOptions(
- image,
- r.ck.LTRBRect(0, 0, image.width(), image.height()),
- r.ck.LTRBRect(-margin, -margin, node.width + margin, node.height + margin),
- r.ck.FilterMode.Linear,
- r.ck.MipmapMode.None,
- null
- )
- } finally {
- if (!retained) image.delete()
- }
- return
- } finally {
- surface.delete()
- }
- }
-
- const cached = r.nodePictureCache.get(node.id)
- const cachedGeneration = r.nodePictureCacheGenerations.get(node.id)
- if (cached && cachedGeneration === r.fontGeneration) {
- canvas.drawPicture(cached)
- return
- }
- if (cached) cached.delete()
- r.nodePictureCache.delete(node.id)
- r.nodePictureCacheGenerations.delete(node.id)
-
- const bounds = r.ck.LTRBRect(-margin, -margin, node.width + margin, node.height + margin)
- const recorder = new r.ck.PictureRecorder()
- try {
- const recCanvas = recorder.beginRecording(bounds)
- r.renderShapeUncached(recCanvas, node, graph)
- const picture = recorder.finishRecordingAsPicture()
- r.nodePictureCache.set(node.id, picture)
- r.nodePictureCacheGenerations.set(node.id, r.fontGeneration)
- canvas.drawPicture(picture)
- } finally {
- recorder.delete()
- }
-}
-
-function drawVectorStrokeGeometry(
- r: SkiaRenderer,
- canvas: Canvas,
- sg: Path[],
- sc: Color,
- opacity: number
-): void {
- r.fillPaint.setColor(r.ck.Color4f(sc.r, sc.g, sc.b, sc.a))
- r.fillPaint.setAlphaf(opacity)
- for (const p of sg) canvas.drawPath(p, r.fillPaint)
-}
-
-function vectorStrokePaths(r: SkiaRenderer, node: SceneNode): Path[] | null {
- if (!node.vectorNetwork) return null
- const cached = r.nodePaths.vectorStroke.get(node.id)
- if (cached) return cached
-
- // A path per run, so the corners inside a run join and only its open ends take caps.
- const { segments, vertices } = node.vectorNetwork
- const paths = strokeRuns(segments).map((run) => {
- const path = new r.ck.PathBuilder()
- addStrokeRunToPath(path, run, segments, vertices)
- return path.detachAndDelete()
- })
-
- if (paths.length === 0) return null
- r.nodePaths.store(r.nodePaths.vectorStroke, node.id, paths)
- return paths
-}
-
-/** Stroke outlines are cached under `<nodeId>|…`, which `NodePathCaches.invalidate` removes. */
-function strokeOutlineKey(
- node: SceneNode,
- stroke: SceneNode['strokes'][0],
- source: 'runs' | 'regions' | 'closed' | 'open'
-): string {
- return `${node.id}|${source}|${stroke.weight}|${stroke.cap ?? node.strokeCap}|${stroke.join ?? node.strokeJoin}|${node.strokeMiterLimit}`
-}
-
-function drawVectorPathStrokes(
- r: SkiaRenderer,
- canvas: Canvas,
- vectorPaths: Path[],
- stroke: SceneNode['strokes'][0],
- sc: Color,
- miterLimit: number,
- outlineCacheKey?: string
-): void {
- const dash = normalizeDashPattern(stroke.dashPattern)
- if (dash.length > 0) {
- r.strokePaint.setColor(r.ck.Color4f(sc.r, sc.g, sc.b, sc.a))
- r.strokePaint.setAlphaf(stroke.opacity)
- r.strokePaint.setStrokeWidth(stroke.weight)
- r.strokePaint.setStrokeCap(getStrokeCapEntity(r, stroke.cap ?? 'NONE'))
- r.strokePaint.setStrokeJoin(getStrokeJoinEntity(r, stroke.join ?? 'MITER'))
- r.strokePaint.setStrokeMiter(miterLimit)
- const effect = r.ck.PathEffect.MakeDash(dash, 0)
- r.strokePaint.setPathEffect(effect)
- for (const vp of vectorPaths) canvas.drawPath(vp, r.strokePaint)
- r.strokePaint.setPathEffect(null)
- effect.delete()
- return
- }
- const strokeOpts = {
- width: stroke.weight,
- miter_limit: miterLimit,
- cap: getStrokeCapEntity(r, stroke.cap ?? 'NONE'),
- join: getStrokeJoinEntity(r, stroke.join ?? 'MITER')
- }
- r.fillPaint.setColor(r.ck.Color4f(sc.r, sc.g, sc.b, sc.a))
- r.fillPaint.setAlphaf(stroke.opacity)
-
- const cached = outlineCacheKey ? r.nodePaths.strokeOutline.get(outlineCacheKey) : undefined
- if (cached) {
- for (const outline of cached) canvas.drawPath(outline, r.fillPaint)
- return
- }
- const outlines: Path[] = []
- for (const vp of vectorPaths) {
- const outline = vp.makeStroked(strokeOpts)
- if (outline) outlines.push(outline)
- }
- for (const outline of outlines) canvas.drawPath(outline, r.fillPaint)
- // Drawing copies the outline, so one without a cache key is done with here.
- if (outlineCacheKey) r.nodePaths.store(r.nodePaths.strokeOutline, outlineCacheKey, outlines)
- else for (const outline of outlines) outline.delete()
-}
-
-/**
- * Draws a dashed stroke on a rectangle, frame, section, or component set with Figma's dash
- * layout, and returns false when the stroke has no dashes or has round or square dash ends on
- * sides of their own weights, which that layout does not cover.
- */
-function drawFigmaDashes(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- stroke: SceneNode['strokes'][0]
-): boolean {
- const dash = normalizeDashPattern(stroke.dashPattern)
- if (dash.length === 0) return false
- if (strokeDashesByOutline(node, stroke)) {
- drawDashedRectStroke(r, canvas, node, stroke, strokeSideWeights(node, stroke), dash)
- } else if (node.independentStrokeWeights) {
- return false
- } else {
- drawOutlinedDashes(r, canvas, node, stroke, dash)
- }
- return true
-}
-
-function drawRegularStroke(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- stroke: SceneNode['strokes'][0],
- sc: Color
-): void {
- configureStrokePaint(r, node, stroke, sc)
- const dash = normalizeDashPattern(stroke.dashPattern)
- r.strokePaint.setPathEffect(dash.length > 0 ? r.ck.PathEffect.MakeDash(dash, 0) : null)
-
- if (node.independentStrokeWeights && r.isRectangularType(node.type)) {
- r.drawIndividualSideStrokes(canvas, node, stroke)
- } else if (!r.isRectangularType(node.type) || !drawFigmaDashes(r, canvas, node, stroke)) {
- r.drawStrokeWithAlign(canvas, node, stroke.align)
- }
-}
-
-/**
- * Strokes a vector's paths on the side its alignment takes, as a shape's stroke is: a centred
- * stroke twice as wide, kept inside its closed regions for `INSIDE` and outside them for
- * `OUTSIDE`. Open segments enclose nothing to take a side of, so they stroke centred.
- */
-function drawAlignedVectorPathStrokes(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- vectorPaths: Path[],
- stroke: SceneNode['strokes'][0],
- sc: Color
-): void {
- const miter = node.strokeMiterLimit
- // `vectorNetworkToPath` lists a path for each region, then one for the open segments.
- const regions = node.vectorNetwork?.regions.length ?? 0
- const closed = vectorPaths.slice(0, regions)
- const inside = stroke.align === 'INSIDE' && closed.length > 0 ? unitePaths(r, closed) : null
- const sided = clipToStrokeSide(r, canvas, closed, stroke.align, inside)
- inside?.delete()
- if (!sided) {
- const outlineKey = strokeOutlineKey(node, stroke, 'regions')
- drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, miter, outlineKey)
- return
- }
- const doubled = { ...stroke, weight: stroke.weight * 2 }
- drawVectorPathStrokes(
- r,
- canvas,
- closed,
- doubled,
- sc,
- miter,
- strokeOutlineKey(node, doubled, 'closed')
- )
- canvas.restore()
- const open = vectorPaths.slice(regions)
- if (open.length > 0)
- drawVectorPathStrokes(
- r,
- canvas,
- open,
- stroke,
- sc,
- miter,
- strokeOutlineKey(node, stroke, 'open')
- )
-}
-
-function clipToStrokeSide(
- r: SkiaRenderer,
- canvas: Canvas,
- closed: Path[],
- align: SceneNode['strokes'][0]['align'],
- inside: Path | null
-): boolean {
- if (align === 'OUTSIDE' && closed.length > 0) {
- canvas.save()
- for (const path of closed) {
- canvas.clipPath(path, r.ck.ClipOp.Difference, true)
- }
- return true
- }
- if (align !== 'INSIDE' || !inside) {
- return false
- }
- canvas.save()
- canvas.clipPath(inside, r.ck.ClipOp.Intersect, true)
- return true
-}
-
-function cachedFillUnion(r: SkiaRenderer, node: SceneNode, fillPaths: Path[]): Path | null {
- const key = `${node.id}|fill-union`
- const cached = r.nodePaths.strokeOutline.get(key)
- if (cached) {
- return cached[0]
- }
- const united = unitePaths(r, fillPaths)
- if (united) {
- r.nodePaths.store(r.nodePaths.strokeOutline, key, [united])
- }
- return united
-}
-
-/** One path covering every path given, which a clip can keep the inside of. */
-function unitePaths(r: SkiaRenderer, paths: Path[]): Path | null {
- let united: Path | null = paths[0]?.copy() ?? null
- for (const path of paths.slice(1)) {
- if (!united) break
- const next = r.ck.Path.MakeFromOp(united, path, r.ck.PathOp.Union)
- united.delete()
- united = next
- }
- return united
-}
-
-function drawNodeStroke(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- stroke: SceneNode['strokes'][0],
- sc: Color,
- sg: Path[] | null,
- vectorPaths: Path[] | null,
- vectorStroke: Path[] | null
-): void {
- const shouldStrokeVectorCenterline =
- vectorStroke &&
- stroke.align === 'CENTER' &&
- node.cornerRadius === 0 &&
- node.type === 'VECTOR' &&
- !node.fills.some((fill) => fill.visible)
- if (shouldStrokeVectorCenterline) {
- const outlineKey = strokeOutlineKey(node, stroke, 'runs')
- drawVectorPathStrokes(r, canvas, vectorStroke, stroke, sc, node.strokeMiterLimit, outlineKey)
- return
- }
- if (!sg) {
- if (vectorPaths) drawAlignedVectorPathStrokes(r, canvas, node, vectorPaths, stroke, sc)
- else drawRegularStroke(r, canvas, node, stroke, sc)
- return
- }
- if (node.type === 'VECTOR' && stroke.align !== 'CENTER') {
- drawFillSideStrokeGeometry(r, canvas, node, stroke, sc, sg)
- return
- }
- if (stroke.align !== 'INSIDE') {
- if (node.type === 'VECTOR' || node.type === 'TEXT') {
- drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
- } else drawRegularStroke(r, canvas, node, stroke, sc)
- return
- }
-
- canvas.save()
- r.clipNodeShape(canvas, node)
- drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
- canvas.restore()
-}
-
-function drawFillSideStrokeGeometry(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- stroke: SceneNode['strokes'][0],
- sc: Color,
- sg: Path[]
-): void {
- const fillPaths = r.getFillGeometry(node)
- const sideable = fillPaths && !(node.vectorNetwork && isOpenVectorNetwork(node.vectorNetwork))
- const inside = sideable && stroke.align === 'INSIDE' ? cachedFillUnion(r, node, fillPaths) : null
- if (!sideable || !clipToStrokeSide(r, canvas, fillPaths, stroke.align, inside)) {
- drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
- return
- }
- drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
- canvas.restore()
-}
-
-function isPathTextWithStrokeGeometry(node: SceneNode): boolean {
- return (
- node.type === 'TEXT' &&
- node.textPathData !== null &&
- (node.derivedTextGlyphs?.length ?? 0) > 0 &&
- node.strokeGeometry.length > 0
- )
-}
-
-/**
- * Draws arrow-cap heads for a stroke on a vector's open path ends. Runs after the shaft
- * regardless of which branch painted it, so heads survive fills, non-center alignment, corner
- * radii, and dashed shafts.
- */
-function drawNodeArrowHeads(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- stroke: SceneNode['strokes'][0],
- color: Color
-): void {
- if (node.type !== 'VECTOR' || !node.vectorNetwork) return
- const endpoints = collectArrowEndpoints(node.vectorNetwork, stroke.cap ?? node.strokeCap)
- if (endpoints.length > 0) {
- drawArrowHeads(r, canvas, endpoints, stroke.weight, color, stroke.opacity)
- }
-}
-
-function paintNodeStrokes(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- graph: SceneGraph,
- sg: Path[] | null,
- vectorPaths: Path[] | null,
- vectorStroke: Path[] | null
-): void {
- forVisibleStrokes(r, node, graph, (stroke, color) => {
- if (node.type === 'LINE') {
- drawLineStroke(r, canvas, node, stroke, color)
- return
- }
- if (
- stroke.dashPattern &&
- stroke.dashPattern.length > 0 &&
- node.type === 'VECTOR' &&
- node.vectorNetwork
- ) {
- const centerline = vectorNetworkToCenterlinePath(r.ck, node.vectorNetwork, node.cornerRadius)
- drawVectorPathStrokes(r, canvas, [centerline], stroke, color, node.strokeMiterLimit)
- centerline.delete()
- drawNodeArrowHeads(r, canvas, node, stroke, color)
- return
- }
- const cap = stroke.cap ?? node.strokeCap
- if (
- !sg &&
- stroke.align === 'CENTER' &&
- node.type === 'VECTOR' &&
- node.vectorNetwork &&
- hasTrimmedShaft(node.vectorNetwork, cap)
- ) {
- // The line stops short of a triangle or equilateral head, so it is stroked from its own
- // pulled-back copy rather than the cached paths; saved stroke geometry is already trimmed.
- const network = trimArrowShafts(node.vectorNetwork, cap, stroke.weight)
- const paths = vectorNetworkToPath(r.ck, network, node.cornerRadius)
- drawVectorPathStrokes(r, canvas, paths, stroke, color, node.strokeMiterLimit)
- for (const path of paths) path.delete()
- drawNodeArrowHeads(r, canvas, node, stroke, color)
- return
- }
- drawNodeStroke(r, canvas, node, stroke, color, sg, vectorPaths, vectorStroke)
- drawNodeArrowHeads(r, canvas, node, stroke, color)
- })
+ renderShapeThroughEffectCaches(r, canvas, node, graph, effects)
}
/** Draws a shape with its own effects: Figma puts inner shadows over fills and under strokes. */
@@ -1049,128 +553,4 @@ export function paintShapeContent(
}
}
-function hasComplexTextFill(fill?: Fill): boolean {
- return fill !== undefined && fill.type !== 'SOLID'
-}
-
-function drawPaintedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {
- if (!r.fontsLoaded || !r.fontProvider) return false
- // Apply the shader directly to native glyphs: coverage layers add another rounding pass.
- return withTextParagraph(
- r,
- node,
- r.ck.Color4f(0, 0, 0, 1),
- {
- halfLeading: true,
- foregroundPaint: r.fillPaint
- },
- (paragraph, prepared) => {
- const y = textVerticalOffset(node, paragraph.getHeight())
- drawTextLayout(r.ck, canvas, node, prepared, y, r.fillPaint)
- return true
- }
- )
-}
-
-function drawResolvedPathText(
- r: SkiaRenderer,
- canvas: Canvas,
- node: SceneNode,
- fontReadiness: ReturnType<SkiaRenderer['nodeFontReadiness']>,
- fill?: Fill
-): boolean {
- return (
- // Resolving the exact face must not replace curved glyph placement with a straight paragraph.
- fontReadiness !== 'exhausted' &&
- node.textPathData !== null &&
- drawDerivedText(r, canvas, node, fill)
- )
-}
-
-/** Whether the text is drawn from the editor's own layout, which leaves its emoji to be drawn. */
-function drawsLaidOutText(r: SkiaRenderer, node: SceneNode): boolean {
- if (!r.fontsLoaded || !r.fontProvider || node.textPathData !== null) return false
- const readiness = r.nodeFontReadiness(node)
- return readiness !== 'pending' && readiness !== 'exhausted' && mayHoldEmoji(shownText(node))
-}
-
-/**
- * The emoji of a text, once whatever fills it has: over its saved glyphs' placeholder squares, or
- * over the blank squares the editor's layout gives them.
- */
-function drawTextEmoji(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {
- const saved = drawsSavedText(node)
- if (!saved && !drawsLaidOutText(r, node)) return
- canvas.save()
- if (saved) drawSavedEmoji(r, canvas, node)
- else {
- withTextParagraph(r, node, r.ck.BLACK, { halfLeading: true }, (paragraph) =>
- drawLaidOutEmoji(r, canvas, node, paragraph, textVerticalOffset(node, paragraph.getHeight()))
- )
- }
- canvas.restore()
-}
-
-function drawSavedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): boolean {
- return canDrawSavedText(node, fill) && drawDerivedText(r, canvas, node, fill)
-}
-
-export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): void {
- const text = node.text
- if (!text) return
-
- canvas.save()
-
- if (drawSavedText(r, canvas, node, fill)) {
- canvas.restore()
- return
- }
- const fontReadiness = r.nodeFontReadiness(node)
- if (fontReadiness === 'pending') {
- canvas.restore()
- return
- }
- if (drawResolvedPathText(r, canvas, node, fontReadiness, fill)) {
- canvas.restore()
- return
- }
- if (fontReadiness === 'exhausted') {
- if (node.textPicture && r.isTextPictureCurrent(node)) {
- const pic = r.ck.MakePicture(node.textPicture)
- if (pic) {
- canvas.drawPicture(pic)
- pic.delete()
- canvas.restore()
- return
- }
- }
- if (drawDerivedText(r, canvas, node, fill)) {
- canvas.restore()
- return
- }
- canvas.restore()
- return
- }
- if (hasComplexTextFill(fill) && drawPaintedText(r, canvas, node)) {
- canvas.restore()
- return
- }
- if (r.fontsLoaded && r.fontProvider) {
- withTextParagraph(
- r,
- node,
- r.fillPaint.getColor(),
- { halfLeading: true },
- (paragraph, prepared) => {
- const paragraphY = textVerticalOffset(node, paragraph.getHeight())
- drawTextLayout(r.ck, canvas, node, prepared, paragraphY, r.fillPaint)
- }
- )
- } else if (r.textFont) {
- const fontSize = node.fontSize || r.DEFAULT_FONT_SIZE
- const paragraphY = textVerticalOffset(node, fontSize)
- canvas.drawText(shownText(node), 0, paragraphY + fontSize, r.fillPaint, r.textFont)
- }
-
- canvas.restore()
-}
+export { renderText }
diff --git a/packages/core/src/canvas/shadows.ts b/packages/core/src/canvas/shadows.ts
index 29cdca107..205a19f63 100644
--- a/packages/core/src/canvas/shadows.ts
+++ b/packages/core/src/canvas/shadows.ts
@@ -2,7 +2,6 @@ import type { Canvas, ImageFilter } from 'canvaskit-wasm'
import type { BlendMode, Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import Matrix from '@open-pencil/scene-graph/matrix'
-import { regionFills } from '@open-pencil/scene-graph/vector-network'
import { nodeOrientationMatrix } from '#core/geometry'
@@ -119,31 +118,33 @@ function drawSilhouetteDropShadow(
morphology
)
: r.getCachedDropShadow(effect.offset.x, effect.offset.y, sigma, color)
- const paint = new ck.Paint()
+ // The layer copies the paint, so the shared one is reset at once for whatever draws inside.
+ const paint = r.effectLayerPaint
paint.setImageFilter(filter)
setPaintBlendMode(r, paint, blendMode)
canvas.saveLayer(paint, bounds)
+ paint.setImageFilter(null)
+ paint.setBlendMode(ck.BlendMode.SrcOver)
try {
draw()
} finally {
canvas.restore()
- paint.delete()
if (morphology) {
- filter.delete()
+ filter?.delete()
morphology.delete()
}
}
}
function drawKnockout(r: SkiaRenderer, canvas: Canvas, bounds: Float32Array, draw: () => void) {
- const paint = new r.ck.Paint()
+ const paint = r.effectLayerPaint
paint.setBlendMode(r.ck.BlendMode.DstOut)
canvas.saveLayer(paint, bounds)
+ paint.setBlendMode(r.ck.BlendMode.SrcOver)
try {
draw()
} finally {
canvas.restore()
- paint.delete()
}
}
@@ -245,10 +246,10 @@ function renderDropShadow(
}
const bounds = shadowLayerBounds(r, graph, node, effect, spread, includeChildren)
- const isolation = knockout ? new r.ck.Paint() : null
- if (isolation) {
- setPaintBlendMode(r, isolation, blendMode)
- canvas.saveLayer(isolation, bounds)
+ if (knockout) {
+ setPaintBlendMode(r, r.effectLayerPaint, blendMode)
+ canvas.saveLayer(r.effectLayerPaint, bounds)
+ setPaintBlendMode(r, r.effectLayerPaint, 'NORMAL')
}
try {
drawSilhouetteDropShadow(
@@ -257,7 +258,7 @@ function renderDropShadow(
effect,
spread,
bounds,
- isolation ? 'NORMAL' : blendMode,
+ knockout ? 'NORMAL' : blendMode,
() => drawSilhouette(r, canvas, graph, node, 'cast', includeChildren)
)
if (knockout) {
@@ -266,10 +267,7 @@ function renderDropShadow(
)
}
} finally {
- if (isolation) {
- canvas.restore()
- isolation.delete()
- }
+ if (knockout) canvas.restore()
resetEffectLayerPaint(r)
}
}
@@ -318,7 +316,7 @@ function drawSilhouetteInnerShadow(
canvas.saveLayer(r.effectLayerPaint, inverse)
restoreCount++
- r.auxFill.setColor(ck.Color4f(0, 0, 0, 1))
+ r.auxFill.setColorComponents(0, 0, 0, 1)
canvas.drawRect(inverse, r.auxFill)
r.effectLayerPaint.setImageFilter(null)
@@ -383,7 +381,7 @@ export function isolatesInnerShadows(node: SceneNode): boolean {
return (
shadows.length > 0 &&
shadows.every((effect) => !needsIsolatedBlendLayer(effect.blendMode)) &&
- [...node.fills, ...regionFills(node.vectorNetwork)].every(
+ [...node.fills, ...node.fillGeometry.flatMap((geometry) => geometry.fills ?? [])].every(
(fill) => !fill.visible || !needsIsolatedBlendLayer(fill.blendMode)
)
)
diff --git a/packages/core/src/canvas/shadows/shape.ts b/packages/core/src/canvas/shadows/shape.ts
index 56a684c15..5421c166a 100644
--- a/packages/core/src/canvas/shadows/shape.ts
+++ b/packages/core/src/canvas/shadows/shape.ts
@@ -241,7 +241,7 @@ export function drawShapeInnerShadow(
isolated = false
): void {
const sp = spread
- r.auxFill.setColor(r.ck.Color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a))
+ r.auxFill.setColorComponents(effect.color.r, effect.color.g, effect.color.b, effect.color.a)
r.auxFill.setImageFilter(r.getCachedDecalBlur(blurSigma(effect.radius)))
canvas.save()
diff --git a/packages/core/src/canvas/shadows/silhouette.ts b/packages/core/src/canvas/shadows/silhouette.ts
index c89ccb1e1..ff95ab1a2 100644
--- a/packages/core/src/canvas/shadows/silhouette.ts
+++ b/packages/core/src/canvas/shadows/silhouette.ts
@@ -4,7 +4,6 @@ import type { Fill, NodeType, SceneGraph, SceneNode, Stroke } from '@open-pencil
import { strokeOverflow as strokeReach } from '@open-pencil/scene-graph/geometry'
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Rect } from '@open-pencil/scene-graph/primitives'
-import { regionFills } from '@open-pencil/scene-graph/vector-network'
import { paintBooleanOperation } from '#core/canvas/boolean'
import { renderMaskedChildIds } from '#core/canvas/masks'
@@ -53,7 +52,10 @@ export function isLayerContainer(node: SceneNode): boolean {
}
export function fillsCastShadow(node: SceneNode): boolean {
- return node.fills.some(paintCastsShadow) || regionFills(node.vectorNetwork).some(paintCastsShadow)
+ return (
+ node.fills.some(paintCastsShadow) ||
+ node.fillGeometry.some((geometry) => geometry.fills?.some(paintCastsShadow) ?? false)
+ )
}
export function paintsCastShadow(node: SceneNode): boolean {
@@ -94,17 +96,14 @@ function silhouetteProxy(node: SceneNode, mode: SilhouetteMode): SceneNode | nul
...node,
fills,
strokes,
- vectorNetwork: node.vectorNetwork && {
- ...node.vectorNetwork,
- regions: node.vectorNetwork.regions.map((region) =>
- region.fills
- ? {
- ...region,
- fills: coversArea || region.fills.some(paintCastsShadow) ? [SILHOUETTE_PAINT] : []
- }
- : region
- )
- },
+ fillGeometry: node.fillGeometry.map((geometry) =>
+ geometry.fills
+ ? {
+ ...geometry,
+ fills: coversArea || geometry.fills.some(paintCastsShadow) ? [SILHOUETTE_PAINT] : []
+ }
+ : geometry
+ ),
effects: [],
boundVariables: {}
}
diff --git a/packages/core/src/canvas/shapes.ts b/packages/core/src/canvas/shapes.ts
index 032400e5f..b99b30587 100644
--- a/packages/core/src/canvas/shapes.ts
+++ b/packages/core/src/canvas/shapes.ts
@@ -1,4 +1,4 @@
-import type { Canvas, Paint, Path } from 'canvaskit-wasm'
+import type { Canvas, EmbindEnumEntity, Paint, Path } from 'canvaskit-wasm'
import type { SceneNode } from '@open-pencil/scene-graph'
import { polygonOutline, type PolygonOutlineCommand } from '@open-pencil/scene-graph/polygon'
@@ -101,7 +101,8 @@ function pathsOutline(
*/
function nodeOutline(r: SkiaRenderer, node: SceneNode, spread: number): NodeOutline {
// `0 - spread` rather than `-spread`: a spread of 0 must not put -0 into flattened geometry.
- const rect = r.ck.LTRBRect(0 - spread, 0 - spread, node.width + spread, node.height + spread)
+ const rect = () =>
+ r.ck.LTRBRect(0 - spread, 0 - spread, node.width + spread, node.height + spread)
switch (node.type) {
case 'VECTOR': {
const paths = r.getFillGeometry(node) ?? r.getVectorPaths(node) ?? []
@@ -111,7 +112,7 @@ function nodeOutline(r: SkiaRenderer, node: SceneNode, spread: number): NodeOutl
const geometry = r.getFillGeometry(node)
if (geometry) return pathsOutline(r, geometry, spread, false)
if (node.arcData) return pathsOutline(r, [makeArcPath(r, node)], spread, true)
- return { kind: 'oval', rect }
+ return { kind: 'oval', rect: rect() }
}
case 'POLYGON':
case 'STAR':
@@ -122,7 +123,7 @@ function nodeOutline(r: SkiaRenderer, node: SceneNode, spread: number): NodeOutl
return { kind: 'paths', paths: [makeSmoothRRectPath(r, node, spread)], owned: true }
}
if (nodeHasRadius(node)) return { kind: 'rrect', rrect: makeRRectWithSpread(r, node, spread) }
- return { kind: 'rect', rect }
+ return { kind: 'rect', rect: rect() }
}
}
@@ -259,9 +260,14 @@ export function makeRRectWithSpread(
)
}
-export function clipNodeShape(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {
+/** Clips to the layer's outline, or with `op` to everything but it. */
+export function clipNodeShape(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ op: EmbindEnumEntity = r.ck.ClipOp.Intersect
+): void {
withNodeOutline(r, node, (outline) => {
- const op = r.ck.ClipOp.Intersect
if (outline.kind === 'rect') canvas.clipRect(outline.rect, op, true)
else if (outline.kind === 'rrect') canvas.clipRRect(outline.rrect, op, true)
else if (outline.kind === 'paths' && outline.paths.length === 1) {
diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.ts
index 58da96bdb..472642961 100644
--- a/packages/core/src/canvas/strokes.ts
+++ b/packages/core/src/canvas/strokes.ts
@@ -12,9 +12,10 @@ import {
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import { setPaintBlendMode } from './blend'
-import { applyGradientFill, applyImageFill } from './fills'
+import { applyGradientFill, applyImageFill, clearFillShader, clearStrokeShader } from './fills'
import type { SkiaRenderer } from './renderer'
import {
+ clipNodeShape,
drawOutline,
makeShapeWithTextDetailsPath,
nodeHasSmoothCorners,
@@ -73,7 +74,7 @@ export function drawDashedRRectWithSolidCorners(
const bottom = node.height - inset
const radius = Math.max(0, cornerRadius - inset)
- r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.strokePaint.setColorComponents(color.r, color.g, color.b, color.a)
r.strokePaint.setStrokeWidth(stroke.weight)
r.strokePaint.setAlphaf(stroke.opacity)
r.strokePaint.setStrokeCap(r.ck.StrokeCap.Butt)
@@ -110,12 +111,12 @@ export function drawDashedRRectWithSolidCorners(
r.strokePaint
)
- r.strokePaint.setPathEffect(dash.length > 0 ? r.ck.PathEffect.MakeDash(dash, dashPhase) : null)
- canvas.drawLine(left + radius, top, right - radius, top, r.strokePaint)
- canvas.drawLine(right, top + radius, right, bottom - radius, r.strokePaint)
- canvas.drawLine(right - radius, bottom, left + radius, bottom, r.strokePaint)
- canvas.drawLine(left, bottom - radius, left, top + radius, r.strokePaint)
- r.strokePaint.setPathEffect(null)
+ withStrokeDash(r, dash, dashPhase, () => {
+ canvas.drawLine(left + radius, top, right - radius, top, r.strokePaint)
+ canvas.drawLine(right, top + radius, right, bottom - radius, r.strokePaint)
+ canvas.drawLine(right - radius, bottom, left + radius, bottom, r.strokePaint)
+ canvas.drawLine(left, bottom - radius, left, top + radius, r.strokePaint)
+ })
}
/** The outline a polygonal head fills: a triangle, an equilateral arrow, or a diamond. */
@@ -184,7 +185,7 @@ export function drawArrowHeads(
const { x, y, angle } = endpoint
switch (endpoint.cap) {
case 'ARROW_LINES':
- r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.strokePaint.setColorComponents(color.r, color.g, color.b, color.a)
r.strokePaint.setAlphaf(opacity)
r.strokePaint.setStrokeWidth(weight)
// One path, so the wings meet in a round join rather than overlapping at the tip.
@@ -221,7 +222,7 @@ function strokeWings(r: SkiaRenderer, canvas: Canvas, [first, second]: [ArrowWin
}
function setHeadPaint(r: SkiaRenderer, color: Color, opacity: number) {
- r.fillPaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.fillPaint.setColorComponents(color.r, color.g, color.b, color.a)
r.fillPaint.setAlphaf(opacity)
}
@@ -254,8 +255,8 @@ export function applyStrokeShader(
node: SceneNode,
graph: SceneGraph
): boolean {
- r.strokePaint.setShader(null)
- r.fillPaint.setShader(null)
+ clearStrokeShader(r)
+ clearFillShader(r)
if (stroke.type.startsWith('GRADIENT') && stroke.gradientStops && stroke.gradientTransform) {
let built = true
for (const paint of [r.strokePaint, r.fillPaint]) {
@@ -293,6 +294,59 @@ export function setStrokeBlendMode(r: SkiaRenderer, mode: BlendMode | undefined)
setPaintBlendMode(r, r.fillPaint, mode)
}
+/**
+ * Every stroke a node draws passes through here, so a gradient or image stroke gets its shader
+ * here rather than in each draw helper, with its blend mode, and the shader, blend mode, and any
+ * dash are cleared before the next stroke: the paints are shared, and a node must not inherit
+ * what the previous one set.
+ */
+export function forVisibleStrokes(
+ r: SkiaRenderer,
+ node: SceneNode,
+ graph: SceneGraph,
+ draw: (stroke: Stroke, color: Color) => void
+): void {
+ for (let index = 0; index < node.strokes.length; index++) {
+ const stroke = node.strokes[index]
+ if (!stroke.visible) continue
+ const draws = applyStrokeShader(r, stroke, index, node, graph)
+ setStrokeBlendMode(r, stroke.blendMode)
+ try {
+ if (draws) draw(stroke, r.resolveStrokeColor(stroke, index, node, graph))
+ } finally {
+ clearStrokeShader(r)
+ clearFillShader(r)
+ r.strokePaint.setPathEffect(null)
+ setStrokeBlendMode(r, 'NORMAL')
+ }
+ }
+}
+
+/**
+ * Draws with `dash` set on the stroke paint, then clears it and frees the effect: the paint keeps
+ * its own reference, and the handle is native memory the garbage collector never reclaims.
+ */
+export function withStrokeDash(
+ r: SkiaRenderer,
+ dash: readonly number[],
+ phase: number,
+ draw: () => void
+): void {
+ if (dash.length === 0) {
+ r.strokePaint.setPathEffect(null)
+ draw()
+ return
+ }
+ const effect = r.ck.PathEffect.MakeDash([...dash], phase)
+ r.strokePaint.setPathEffect(effect)
+ try {
+ draw()
+ } finally {
+ r.strokePaint.setPathEffect(null)
+ effect.delete()
+ }
+}
+
/** Leaves any shader in place: a shaded stroke's color is unused, but its alpha still applies. */
export function configureStrokePaint(
r: SkiaRenderer,
@@ -300,7 +354,7 @@ export function configureStrokePaint(
stroke: Stroke,
color: Color
): void {
- r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ r.strokePaint.setColorComponents(color.r, color.g, color.b, color.a)
r.strokePaint.setStrokeWidth(stroke.weight)
r.strokePaint.setAlphaf(stroke.opacity)
r.strokePaint.setStrokeCap(getStrokeCapEntity(r, stroke.cap ?? node.strokeCap))
@@ -319,9 +373,7 @@ export function drawStyledRRectStroke(
): void {
const dash = normalizeDashPattern(stroke.dashPattern)
configureStrokePaint(r, node, stroke, color)
- r.strokePaint.setPathEffect(dash.length > 0 ? r.ck.PathEffect.MakeDash(dash, dashPhase) : null)
- r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke)
- r.strokePaint.setPathEffect(null)
+ withStrokeDash(r, dash, dashPhase, () => r.drawRRectStrokeWithAlign(canvas, rrect, node, stroke))
}
/** Strokes a layer's outline, or a vector's own paths, open ones included. */
@@ -345,20 +397,8 @@ export function drawStrokeWithAlign(
canvas.restore()
} else if (align === 'OUTSIDE') {
canvas.save()
- const bigRect = r.ck.LTRBRect(-node.width, -node.height, node.width * 2, node.height * 2)
- const outerPath = new r.ck.PathBuilder()
- outerPath.addRect(bigRect)
- const innerPath = r.makeNodeShapePath(node)
- const immutableOuterPath = outerPath.detachAndDelete()
- const clipPath = r.ck.Path.MakeFromOp(immutableOuterPath, innerPath, r.ck.PathOp.Difference)
- immutableOuterPath.delete()
- innerPath.delete()
- if (!clipPath) {
- canvas.restore()
- return
- }
- canvas.clipPath(clipPath, r.ck.ClipOp.Intersect, true)
- clipPath.delete()
+ // Everything but the shape: the stroke at double weight then shows only its outer half.
+ clipNodeShape(r, canvas, node, r.ck.ClipOp.Difference)
const origWidth = r.strokePaint.getStrokeWidth()
r.strokePaint.setStrokeWidth(origWidth * 2)
r.drawNodeStroke(canvas, node)
@@ -400,25 +440,7 @@ export function drawRRectStrokeWithAlign(
canvas.restore()
} else if (stroke.align === 'OUTSIDE') {
canvas.save()
- const outerPath = new r.ck.PathBuilder()
- outerPath.addRect(r.ck.LTRBRect(-node.width, -node.height, node.width * 2, node.height * 2))
- const innerPath = new r.ck.PathBuilder()
- innerPath.addRRect(rrect)
- const immutableOuterPath = outerPath.detachAndDelete()
- const immutableInnerPath = innerPath.detachAndDelete()
- const clipPath = r.ck.Path.MakeFromOp(
- immutableOuterPath,
- immutableInnerPath,
- r.ck.PathOp.Difference
- )
- immutableOuterPath.delete()
- immutableInnerPath.delete()
- if (!clipPath) {
- canvas.restore()
- return
- }
- canvas.clipPath(clipPath, r.ck.ClipOp.Intersect, true)
- clipPath.delete()
+ canvas.clipRRect(rrect, r.ck.ClipOp.Difference, true)
r.strokePaint.setStrokeWidth(stroke.weight * 2)
canvas.drawRRect(rrect, r.strokePaint)
r.strokePaint.setStrokeWidth(stroke.weight)
diff --git a/packages/core/src/canvas/strokes/dispatch.ts b/packages/core/src/canvas/strokes/dispatch.ts
new file mode 100644
index 000000000..06dd44534
--- /dev/null
+++ b/packages/core/src/canvas/strokes/dispatch.ts
@@ -0,0 +1,407 @@
+import type { Canvas, Path } from 'canvaskit-wasm'
+
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ collectArrowEndpoints,
+ hasTrimmedShaft,
+ trimArrowShafts
+} from '@open-pencil/scene-graph/arrow-caps'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import {
+ configureStrokePaint,
+ drawArrowHeads,
+ forVisibleStrokes,
+ getStrokeCapEntity,
+ getStrokeJoinEntity,
+ normalizeDashPattern,
+ withStrokeDash
+} from '#core/canvas/strokes'
+import {
+ addStrokeRunToPath,
+ strokeRuns,
+ vectorNetworkToCenterlinePath,
+ vectorNetworkToPath
+} from '#core/vector'
+import { isOpenVectorNetwork } from '#core/vector/connectivity'
+
+import { drawLineStroke } from './line'
+import { drawOutlinedDashes } from './outlined-dashes'
+import { drawDashedRectStroke, strokeDashesByOutline, strokeSideWeights } from './sides'
+
+function drawVectorStrokeGeometry(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ sg: Path[],
+ sc: Color,
+ opacity: number
+): void {
+ r.fillPaint.setColorComponents(sc.r, sc.g, sc.b, sc.a)
+ r.fillPaint.setAlphaf(opacity)
+ for (const p of sg) canvas.drawPath(p, r.fillPaint)
+}
+
+export function vectorStrokePaths(r: SkiaRenderer, node: SceneNode): Path[] | null {
+ if (!node.vectorNetwork) return null
+ const cached = r.nodePaths.vectorStroke.get(node.id)
+ if (cached) return cached
+
+ // A path per run, so the corners inside a run join and only its open ends take caps.
+ const { segments, vertices } = node.vectorNetwork
+ const paths = strokeRuns(segments).map((run) => {
+ const path = new r.ck.PathBuilder()
+ addStrokeRunToPath(path, run, segments, vertices)
+ return path.detachAndDelete()
+ })
+
+ if (paths.length === 0) return null
+ r.nodePaths.store(r.nodePaths.vectorStroke, node.id, paths)
+ return paths
+}
+
+/** Stroke outlines are cached under `<nodeId>|…`, which `NodePathCaches.invalidate` removes. */
+function strokeOutlineKey(
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0],
+ source: 'runs' | 'regions' | 'closed' | 'open' | 'trimmed'
+): string {
+ return `${node.id}|${source}|${stroke.weight}|${stroke.cap ?? node.strokeCap}|${stroke.join ?? node.strokeJoin}|${node.strokeMiterLimit}`
+}
+
+function drawVectorPathStrokes(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ vectorPaths: Path[],
+ stroke: SceneNode['strokes'][0],
+ sc: Color,
+ miterLimit: number,
+ outlineCacheKey?: string
+): void {
+ const dash = normalizeDashPattern(stroke.dashPattern)
+ if (dash.length > 0) {
+ r.strokePaint.setColorComponents(sc.r, sc.g, sc.b, sc.a)
+ r.strokePaint.setAlphaf(stroke.opacity)
+ r.strokePaint.setStrokeWidth(stroke.weight)
+ r.strokePaint.setStrokeCap(getStrokeCapEntity(r, stroke.cap ?? 'NONE'))
+ r.strokePaint.setStrokeJoin(getStrokeJoinEntity(r, stroke.join ?? 'MITER'))
+ r.strokePaint.setStrokeMiter(miterLimit)
+ withStrokeDash(r, dash, 0, () => {
+ for (const vp of vectorPaths) canvas.drawPath(vp, r.strokePaint)
+ })
+ return
+ }
+ const strokeOpts = {
+ width: stroke.weight,
+ miter_limit: miterLimit,
+ cap: getStrokeCapEntity(r, stroke.cap ?? 'NONE'),
+ join: getStrokeJoinEntity(r, stroke.join ?? 'MITER')
+ }
+ r.fillPaint.setColorComponents(sc.r, sc.g, sc.b, sc.a)
+ r.fillPaint.setAlphaf(stroke.opacity)
+
+ const cached = outlineCacheKey ? r.nodePaths.strokeOutline.get(outlineCacheKey) : undefined
+ if (cached) {
+ for (const outline of cached) canvas.drawPath(outline, r.fillPaint)
+ return
+ }
+ const outlines: Path[] = []
+ for (const vp of vectorPaths) {
+ const outline = vp.makeStroked(strokeOpts)
+ if (outline) outlines.push(outline)
+ }
+ for (const outline of outlines) canvas.drawPath(outline, r.fillPaint)
+ // Drawing copies the outline, so one without a cache key is done with here.
+ if (outlineCacheKey) r.nodePaths.store(r.nodePaths.strokeOutline, outlineCacheKey, outlines)
+ else for (const outline of outlines) outline.delete()
+}
+
+/**
+ * Draws a dashed stroke on a rectangle, frame, section, or component set with Figma's dash
+ * layout, and returns false when the stroke has no dashes or has round or square dash ends on
+ * sides of their own weights, which that layout does not cover.
+ */
+export function drawFigmaDashes(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0]
+): boolean {
+ const dash = normalizeDashPattern(stroke.dashPattern)
+ if (dash.length === 0) return false
+ if (strokeDashesByOutline(node, stroke)) {
+ drawDashedRectStroke(r, canvas, node, stroke, strokeSideWeights(node, stroke), dash)
+ } else if (node.independentStrokeWeights) {
+ return false
+ } else {
+ drawOutlinedDashes(r, canvas, node, stroke, dash)
+ }
+ return true
+}
+
+function drawRegularStroke(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0],
+ sc: Color
+): void {
+ configureStrokePaint(r, node, stroke, sc)
+ withStrokeDash(r, normalizeDashPattern(stroke.dashPattern), 0, () => {
+ if (node.independentStrokeWeights && r.isRectangularType(node.type)) {
+ r.drawIndividualSideStrokes(canvas, node, stroke)
+ } else if (!r.isRectangularType(node.type) || !drawFigmaDashes(r, canvas, node, stroke)) {
+ r.drawStrokeWithAlign(canvas, node, stroke.align)
+ }
+ })
+}
+
+function drawNodeStroke(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0],
+ sc: Color,
+ sg: Path[] | null,
+ vectorPaths: Path[] | null,
+ vectorStroke: Path[] | null
+): void {
+ const shouldStrokeVectorCenterline =
+ vectorStroke &&
+ stroke.align === 'CENTER' &&
+ node.cornerRadius === 0 &&
+ node.type === 'VECTOR' &&
+ !node.fills.some((fill) => fill.visible)
+ if (shouldStrokeVectorCenterline) {
+ const outlineKey = strokeOutlineKey(node, stroke, 'runs')
+ drawVectorPathStrokes(r, canvas, vectorStroke, stroke, sc, node.strokeMiterLimit, outlineKey)
+ return
+ }
+ if (!sg) {
+ if (vectorPaths) drawAlignedVectorPathStrokes(r, canvas, node, vectorPaths, stroke, sc)
+ else drawRegularStroke(r, canvas, node, stroke, sc)
+ return
+ }
+ if (node.type === 'VECTOR' && stroke.align !== 'CENTER') {
+ drawFillSideStrokeGeometry(r, canvas, node, stroke, sc, sg)
+ return
+ }
+ if (stroke.align !== 'INSIDE') {
+ if (node.type === 'VECTOR' || node.type === 'TEXT') {
+ drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
+ } else drawRegularStroke(r, canvas, node, stroke, sc)
+ return
+ }
+
+ canvas.save()
+ r.clipNodeShape(canvas, node)
+ drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
+ canvas.restore()
+}
+
+export function isPathTextWithStrokeGeometry(node: SceneNode): boolean {
+ return (
+ node.type === 'TEXT' &&
+ node.textPathData !== null &&
+ (node.derivedTextGlyphs?.length ?? 0) > 0 &&
+ node.strokeGeometry.length > 0
+ )
+}
+
+/**
+ * Draws arrow-cap heads for a stroke on a vector's open path ends. Runs after the shaft
+ * regardless of which branch painted it, so heads survive fills, non-center alignment, corner
+ * radii, and dashed shafts.
+ */
+function drawNodeArrowHeads(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0],
+ color: Color
+): void {
+ if (node.type !== 'VECTOR' || !node.vectorNetwork) return
+ const endpoints = collectArrowEndpoints(node.vectorNetwork, stroke.cap ?? node.strokeCap)
+ if (endpoints.length > 0) {
+ drawArrowHeads(r, canvas, endpoints, stroke.weight, color, stroke.opacity)
+ }
+}
+
+export function paintNodeStrokes(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ graph: SceneGraph,
+ sg: Path[] | null,
+ vectorPaths: Path[] | null,
+ vectorStroke: Path[] | null
+): void {
+ forVisibleStrokes(r, node, graph, (stroke, color) => {
+ if (node.type === 'LINE') {
+ drawLineStroke(r, canvas, node, stroke, color)
+ return
+ }
+ if (
+ stroke.dashPattern &&
+ stroke.dashPattern.length > 0 &&
+ node.type === 'VECTOR' &&
+ node.vectorNetwork
+ ) {
+ const key = `${node.id}|centerline|${node.cornerRadius}`
+ let centerline = r.nodePaths.strokeOutline.get(key)
+ if (!centerline) {
+ centerline = [vectorNetworkToCenterlinePath(r.ck, node.vectorNetwork, node.cornerRadius)]
+ r.nodePaths.store(r.nodePaths.strokeOutline, key, centerline)
+ }
+ drawVectorPathStrokes(r, canvas, centerline, stroke, color, node.strokeMiterLimit)
+ drawNodeArrowHeads(r, canvas, node, stroke, color)
+ return
+ }
+ const cap = stroke.cap ?? node.strokeCap
+ if (
+ !sg &&
+ stroke.align === 'CENTER' &&
+ node.type === 'VECTOR' &&
+ node.vectorNetwork &&
+ hasTrimmedShaft(node.vectorNetwork, cap)
+ ) {
+ // The line stops short of a triangle or equilateral head, so it is stroked from its own
+ // pulled-back copy rather than the cached paths; saved stroke geometry is already trimmed.
+ const key = `${node.id}|trimmed|${cap}|${stroke.weight}|${node.cornerRadius}`
+ let paths = r.nodePaths.strokeOutline.get(key)
+ if (!paths) {
+ const network = trimArrowShafts(node.vectorNetwork, cap, stroke.weight)
+ paths = vectorNetworkToPath(r.ck, network, node.cornerRadius)
+ r.nodePaths.store(r.nodePaths.strokeOutline, key, paths)
+ }
+ drawVectorPathStrokes(
+ r,
+ canvas,
+ paths,
+ stroke,
+ color,
+ node.strokeMiterLimit,
+ strokeOutlineKey(node, stroke, 'trimmed')
+ )
+ drawNodeArrowHeads(r, canvas, node, stroke, color)
+ return
+ }
+ drawNodeStroke(r, canvas, node, stroke, color, sg, vectorPaths, vectorStroke)
+ drawNodeArrowHeads(r, canvas, node, stroke, color)
+ })
+}
+
+/**
+ * Strokes a vector's paths on the side its alignment takes, as a shape's stroke is: a centred
+ * stroke twice as wide, kept inside its closed regions for `INSIDE` and outside them for
+ * `OUTSIDE`. Open segments enclose nothing to take a side of, so they stroke centred.
+ */
+function drawAlignedVectorPathStrokes(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ vectorPaths: Path[],
+ stroke: SceneNode['strokes'][0],
+ sc: Color
+): void {
+ const miter = node.strokeMiterLimit
+ // `vectorNetworkToPath` lists a path for each region, then one for the open segments.
+ const regions = node.vectorNetwork?.regions.length ?? 0
+ const closed = vectorPaths.slice(0, regions)
+ const inside = stroke.align === 'INSIDE' && closed.length > 0 ? unitePaths(r, closed) : null
+ const sided = clipToStrokeSide(r, canvas, closed, stroke.align, inside)
+ inside?.delete()
+ if (!sided) {
+ const outlineKey = strokeOutlineKey(node, stroke, 'regions')
+ drawVectorPathStrokes(r, canvas, vectorPaths, stroke, sc, miter, outlineKey)
+ return
+ }
+ const doubled = { ...stroke, weight: stroke.weight * 2 }
+ drawVectorPathStrokes(
+ r,
+ canvas,
+ closed,
+ doubled,
+ sc,
+ miter,
+ strokeOutlineKey(node, doubled, 'closed')
+ )
+ canvas.restore()
+ const open = vectorPaths.slice(regions)
+ if (open.length > 0)
+ drawVectorPathStrokes(
+ r,
+ canvas,
+ open,
+ stroke,
+ sc,
+ miter,
+ strokeOutlineKey(node, stroke, 'open')
+ )
+}
+
+function clipToStrokeSide(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ closed: Path[],
+ align: SceneNode['strokes'][0]['align'],
+ inside: Path | null
+): boolean {
+ if (align === 'OUTSIDE' && closed.length > 0) {
+ canvas.save()
+ for (const path of closed) {
+ canvas.clipPath(path, r.ck.ClipOp.Difference, true)
+ }
+ return true
+ }
+ if (align !== 'INSIDE' || !inside) {
+ return false
+ }
+ canvas.save()
+ canvas.clipPath(inside, r.ck.ClipOp.Intersect, true)
+ return true
+}
+
+function cachedFillUnion(r: SkiaRenderer, node: SceneNode, fillPaths: Path[]): Path | null {
+ const key = `${node.id}|fill-union`
+ const cached = r.nodePaths.strokeOutline.get(key)
+ if (cached) {
+ return cached[0]
+ }
+ const united = unitePaths(r, fillPaths)
+ if (united) {
+ r.nodePaths.store(r.nodePaths.strokeOutline, key, [united])
+ }
+ return united
+}
+
+/** One path covering every path given, which a clip can keep the inside of. */
+function unitePaths(r: SkiaRenderer, paths: Path[]): Path | null {
+ let united: Path | null = paths[0]?.copy() ?? null
+ for (const path of paths.slice(1)) {
+ if (!united) break
+ const next = r.ck.Path.MakeFromOp(united, path, r.ck.PathOp.Union)
+ united.delete()
+ united = next
+ }
+ return united
+}
+
+function drawFillSideStrokeGeometry(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ stroke: SceneNode['strokes'][0],
+ sc: Color,
+ sg: Path[]
+): void {
+ const fillPaths = r.getFillGeometry(node)
+ const sideable = fillPaths && !(node.vectorNetwork && isOpenVectorNetwork(node.vectorNetwork))
+ const inside = sideable && stroke.align === 'INSIDE' ? cachedFillUnion(r, node, fillPaths) : null
+ if (!sideable || !clipToStrokeSide(r, canvas, fillPaths, stroke.align, inside)) {
+ drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
+ return
+ }
+ drawVectorStrokeGeometry(r, canvas, sg, sc, stroke.opacity)
+ canvas.restore()
+}
diff --git a/packages/core/src/canvas/text/decorations.ts b/packages/core/src/canvas/text/decorations.ts
index 264275c2e..d78312a06 100644
--- a/packages/core/src/canvas/text/decorations.ts
+++ b/packages/core/src/canvas/text/decorations.ts
@@ -304,7 +304,7 @@ export function drawTextDecorations(
if (fill?.type === 'SOLID') {
const { r: red, g, b, a } = resolveRGBAForPreview(fill.color).color
paint.setShader(null)
- paint.setColor(ck.Color4f(red, g, b, a * fill.opacity))
+ paint.setColorComponents(red, g, b, a * fill.opacity)
}
if (rect.style === 'DOTTED') drawDots(canvas, rect, paint)
else if (rect.style === 'WAVY') drawWave(ck, canvas, rect, paint)
diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.ts
index 507731722..a7292635e 100644
--- a/packages/core/src/canvas/text/derived.ts
+++ b/packages/core/src/canvas/text/derived.ts
@@ -191,7 +191,7 @@ export function drawReflowedPathTextSilhouettes(
const paint = new r.ck.Paint()
paint.setAntiAlias(true)
paint.setStyle(r.ck.PaintStyle.Fill)
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))
+ paint.setColorComponents(color.r, color.g, color.b, color.a)
paint.setAlphaf(stroke.opacity)
try {
for (const glyph of glyphs) {
@@ -317,7 +317,7 @@ function drawGlyphOutline(r: SkiaRenderer, canvas: Canvas, path: Path, runFills?
for (const fill of runFills) {
if (!fill.visible || fill.type !== 'SOLID') continue
const color = fill.color
- paint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a * fill.opacity))
+ paint.setColorComponents(color.r, color.g, color.b, color.a * fill.opacity)
canvas.drawPath(path, paint)
}
} finally {
diff --git a/packages/core/src/canvas/text/layout/build.ts b/packages/core/src/canvas/text/layout/build.ts
index 33d939424..f9d32d7da 100644
--- a/packages/core/src/canvas/text/layout/build.ts
+++ b/packages/core/src/canvas/text/layout/build.ts
@@ -304,7 +304,8 @@ function buildBlocks(
lines: paragraphLines(r, blockNode, color, options, firstLineIndent),
x: 0,
y: 0,
- visible: true
+ visible: true,
+ metrics: []
}
}
}
diff --git a/packages/core/src/canvas/text/layout/index.ts b/packages/core/src/canvas/text/layout/index.ts
index c8a825744..065825805 100644
--- a/packages/core/src/canvas/text/layout/index.ts
+++ b/packages/core/src/canvas/text/layout/index.ts
@@ -59,6 +59,8 @@ export interface TextLayoutBlock {
y: number
/** Whether the block is shown, as truncation hides blocks past its last line. */
visible: boolean
+ /** The paragraph's line metrics, read once when the block is laid out. */
+ metrics: LineMetrics[]
}
export interface TextCaretBox {
@@ -105,7 +107,8 @@ export class TextLayout {
lines,
x: 0,
y: 0,
- visible: true
+ visible: true,
+ metrics: []
}
])
}
@@ -137,26 +140,38 @@ export class TextLayout {
continue
}
block.paragraph.layout(Math.max(1, width - block.inset))
+ block.metrics = block.paragraph.getLineMetrics()
// A block capped for a narrower layout gets its lines back when there is room for them.
const cap = this.caps.get(block) ?? this.maxLines ?? Infinity
- const overflows = block.paragraph.getLineMetrics().length > remaining
+ const overflows = block.metrics.length > remaining
const clipped = cap < remaining && block.paragraph.didExceedMaxLines()
if ((overflows || clipped) && block.rebuild) {
block.paragraph.delete()
block.paragraph = block.rebuild(remaining)
this.caps.set(block, remaining)
block.paragraph.layout(Math.max(1, width - block.inset))
+ block.metrics = block.paragraph.getLineMetrics()
}
if (block.paragraph.didExceedMaxLines()) this.truncated = true
if (index > 0) y += block.spaceBefore
block.x = block.rtl ? 0 : block.inset
block.y = y
y += block.paragraph.getHeight()
- lines += block.paragraph.getLineMetrics().length
+ lines += block.metrics.length
}
this.placeLines(width)
for (const block of this.visibleBlocks()) this.placeMarker(block)
this.collectLines()
+ this.height = this.measureHeight()
+ }
+
+ /** The laid-out height, kept from the layout so a draw asks the paragraphs nothing. */
+ private height: number | null = null
+
+ private measureHeight(): number {
+ const last = this.visibleBlocks().at(-1)
+ if (this.placedHeight !== null) return this.placedHeight
+ return last ? last.y + last.paragraph.getHeight() : 0
}
private clearPlacements(): void {
@@ -165,6 +180,7 @@ export class TextLayout {
}
this.placements.clear()
this.placedHeight = null
+ this.height = null
}
/**
@@ -190,7 +206,7 @@ export class TextLayout {
private offsetAt(block: TextLayoutBlock, y: number): number {
const placement = this.placements.get(block)
if (!placement) return 0
- const lines = block.paragraph.getLineMetrics()
+ const lines = block.metrics
const index = lines.findIndex((line) => y < line.baseline + line.descent)
return placement.offsets[index === -1 ? lines.length - 1 : index] ?? 0
}
@@ -201,7 +217,7 @@ export class TextLayout {
private placeMarker(block: TextLayoutBlock): void {
const marker = block.marker
- const first = block.paragraph.getLineMetrics().at(0)
+ const first = block.metrics.at(0)
if (!marker || !first) return
const markerLine = marker.paragraph.getLineMetrics().at(0)
const width = marker.paragraph.getLongestLine()
@@ -232,7 +248,7 @@ export class TextLayout {
for (const [blockIndex, block] of visible.entries()) {
this.lineOffsets.push(this.lines.length)
if (block.marker) block.marker.lineNumber = this.lines.length
- const metrics = block.paragraph.getLineMetrics()
+ const metrics = block.metrics
const boxes = this.placements.get(block)?.boxes
const blockEnd = block.start + block.length
for (const [lineIndex, line] of metrics.entries()) {
@@ -265,9 +281,7 @@ export class TextLayout {
}
getHeight(): number {
- const last = this.visibleBlocks().at(-1)
- if (this.placedHeight !== null) return this.placedHeight
- return last ? last.y + last.paragraph.getHeight() : 0
+ return this.height ?? this.measureHeight()
}
getLongestLine(): number {
diff --git a/packages/core/src/canvas/text/layout/lines.ts b/packages/core/src/canvas/text/layout/lines.ts
index cffc68965..196a8b736 100644
--- a/packages/core/src/canvas/text/layout/lines.ts
+++ b/packages/core/src/canvas/text/layout/lines.ts
@@ -24,6 +24,8 @@ export interface TextLayoutBlockLines {
/** What placing a text layout block's lines reads of it. */
interface LineBlock {
paragraph: Paragraph
+ /** The paragraph's line metrics as laid out, so placing reads them from the block. */
+ metrics: LineMetrics[]
lines?: TextLayoutBlockLines
lead: number
length: number
@@ -254,7 +256,7 @@ export function placeLines<Block extends LineBlock>(
blocks: readonly Block[],
width: number
): PlacedLines<Block> | null {
- const metrics = blocks.map((block) => block.paragraph.getLineMetrics())
+ const metrics = blocks.map((block) => block.metrics)
// A single line has none to be spaced from.
if (metrics.flat().length < 2) return null
const boxes = lineBoxes(ck, blocks, metrics)
diff --git a/packages/core/src/canvas/text/preparation/cache.ts b/packages/core/src/canvas/text/preparation/cache.ts
index 668aaee95..6f29d280f 100644
--- a/packages/core/src/canvas/text/preparation/cache.ts
+++ b/packages/core/src/canvas/text/preparation/cache.ts
@@ -6,10 +6,11 @@ import type { Size } from '@open-pencil/scene-graph/primitives'
import { ResourceCache } from '#core/cache/resource'
import type { missingGlyphOccurrences } from '#core/text/resolver'
-// Bound both the number of native paragraphs and the text retained by them.
-// Source UTF-16 units are a workload bound, not an estimate of native bytes.
-const MAX_PREPARED_PARAGRAPHS = 1024
-const MAX_PREPARED_TEXT_UNITS = 262_144
+// Bound both the number of native paragraphs and the text retained by them. Source UTF-16 units
+// are a workload bound, not an estimate of native bytes. A page of a few thousand texts must fit,
+// or every record shapes them all again: the Preline CMS page holds 2,448.
+const MAX_PREPARED_PARAGRAPHS = 8192
+const MAX_PREPARED_TEXT_UNITS = 1_048_576
// Layout measures a text at a few widths; more than this means the widths are not repeating.
const MAX_MEASURED_WIDTHS = 16
// Bound the shapings layers share by their key length, which holds the text.
diff --git a/packages/core/src/canvas/text/render.ts b/packages/core/src/canvas/text/render.ts
new file mode 100644
index 000000000..d4d65142b
--- /dev/null
+++ b/packages/core/src/canvas/text/render.ts
@@ -0,0 +1,150 @@
+import type { Canvas } from 'canvaskit-wasm'
+
+import type { Fill, SceneNode } from '@open-pencil/scene-graph'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import { textVerticalOffset, withTextParagraph } from '#core/canvas/text'
+import { shownText } from '#core/text/case'
+import { mayHoldEmoji } from '#core/text/emoji'
+
+import { drawTextLayout } from './decorations'
+import { canDrawSavedText, drawDerivedText, drawsSavedText } from './derived'
+import { drawLaidOutEmoji, drawSavedEmoji } from './emoji'
+
+export function hasOverflowPathTextPaint(node: SceneNode): boolean {
+ return (
+ node.textPathData != null &&
+ ((node.derivedTextGlyphs?.length ?? 0) > 0 ||
+ (Array.isArray(node.strokeGeometry) && node.strokeGeometry.length > 0))
+ )
+}
+
+function hasComplexTextFill(fill?: Fill): boolean {
+ return fill !== undefined && fill.type !== 'SOLID'
+}
+
+function drawPaintedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode): boolean {
+ if (!r.fontsLoaded || !r.fontProvider) return false
+ // Apply the shader directly to native glyphs: coverage layers add another rounding pass.
+ return withTextParagraph(
+ r,
+ node,
+ r.ck.Color4f(0, 0, 0, 1),
+ {
+ halfLeading: true,
+ foregroundPaint: r.fillPaint
+ },
+ (paragraph, prepared) => {
+ const y = textVerticalOffset(node, paragraph.getHeight())
+ drawTextLayout(r.ck, canvas, node, prepared, y, r.fillPaint)
+ return true
+ }
+ )
+}
+
+function drawResolvedPathText(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ fontReadiness: ReturnType<SkiaRenderer['nodeFontReadiness']>,
+ fill?: Fill
+): boolean {
+ return (
+ // Resolving the exact face must not replace curved glyph placement with a straight paragraph.
+ fontReadiness !== 'exhausted' &&
+ node.textPathData !== null &&
+ drawDerivedText(r, canvas, node, fill)
+ )
+}
+
+/** Whether the text is drawn from the editor's own layout, which leaves its emoji to be drawn. */
+function drawsLaidOutText(r: SkiaRenderer, node: SceneNode): boolean {
+ if (!r.fontsLoaded || !r.fontProvider || node.textPathData !== null) return false
+ const readiness = r.nodeFontReadiness(node)
+ return readiness !== 'pending' && readiness !== 'exhausted' && mayHoldEmoji(shownText(node))
+}
+
+/**
+ * The emoji of a text, once whatever fills it has: over its saved glyphs' placeholder squares, or
+ * over the blank squares the editor's layout gives them.
+ */
+export function drawTextEmoji(r: SkiaRenderer, canvas: Canvas, node: SceneNode): void {
+ const saved = drawsSavedText(node)
+ if (!saved && !drawsLaidOutText(r, node)) return
+ canvas.save()
+ if (saved) drawSavedEmoji(r, canvas, node)
+ else {
+ // The paragraph the fills just drew with: its colour keys the prepared text, and a solid fill
+ // leaves it on the fill paint, so no second paragraph is shaped for the emoji.
+ const lastFill = node.fills.findLast((fill) => fill.visible)
+ const color = hasComplexTextFill(lastFill) ? r.ck.Color4f(0, 0, 0, 1) : r.fillPaint.getColor()
+ withTextParagraph(r, node, color, { halfLeading: true }, (paragraph) =>
+ drawLaidOutEmoji(r, canvas, node, paragraph, textVerticalOffset(node, paragraph.getHeight()))
+ )
+ }
+ canvas.restore()
+}
+
+function drawSavedText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): boolean {
+ return canDrawSavedText(node, fill) && drawDerivedText(r, canvas, node, fill)
+}
+
+export function renderText(r: SkiaRenderer, canvas: Canvas, node: SceneNode, fill?: Fill): void {
+ const text = node.text
+ if (!text) return
+
+ canvas.save()
+
+ if (drawSavedText(r, canvas, node, fill)) {
+ canvas.restore()
+ return
+ }
+ const fontReadiness = r.nodeFontReadiness(node)
+ if (fontReadiness === 'pending') {
+ canvas.restore()
+ return
+ }
+ if (drawResolvedPathText(r, canvas, node, fontReadiness, fill)) {
+ canvas.restore()
+ return
+ }
+ if (fontReadiness === 'exhausted') {
+ if (node.textPicture && r.isTextPictureCurrent(node)) {
+ const pic = r.ck.MakePicture(node.textPicture)
+ if (pic) {
+ canvas.drawPicture(pic)
+ pic.delete()
+ canvas.restore()
+ return
+ }
+ }
+ if (drawDerivedText(r, canvas, node, fill)) {
+ canvas.restore()
+ return
+ }
+ canvas.restore()
+ return
+ }
+ if (hasComplexTextFill(fill) && drawPaintedText(r, canvas, node)) {
+ canvas.restore()
+ return
+ }
+ if (r.fontsLoaded && r.fontProvider) {
+ withTextParagraph(
+ r,
+ node,
+ r.fillPaint.getColor(),
+ { halfLeading: true },
+ (paragraph, prepared) => {
+ const paragraphY = textVerticalOffset(node, paragraph.getHeight())
+ drawTextLayout(r.ck, canvas, node, prepared, paragraphY, r.fillPaint)
+ }
+ )
+ } else if (r.textFont) {
+ const fontSize = node.fontSize || r.DEFAULT_FONT_SIZE
+ const paragraphY = textVerticalOffset(node, fontSize)
+ canvas.drawText(shownText(node), 0, paragraphY + fontSize, r.fillPaint, r.textFont)
+ }
+
+ canvas.restore()
+}
diff --git a/packages/core/src/editor/graph-events.ts b/packages/core/src/editor/graph-events.ts
index e2e33f0a2..def009ca0 100644
--- a/packages/core/src/editor/graph-events.ts
+++ b/packages/core/src/editor/graph-events.ts
@@ -9,7 +9,7 @@ type EmittedGraphEventName = keyof SceneGraphEvents
/** The renderer surface graph events invalidate; tests provide a double of just this. */
export type GraphEventRenderer = Pick<
SkiaRenderer,
- 'invalidateVectorPath' | 'invalidateNodePicture'
+ 'invalidateVectorPath' | 'invalidateNodePicture' | 'forgetNode'
> & {
tiledScene: Pick<SkiaRenderer['tiledScene'], 'invalidateNode' | 'invalidateStructure'>
}
@@ -59,6 +59,39 @@ export function rendererInvalidationForChanges(
return { geometryCache, nodePicture }
}
+/** The boolean operations `id` lies in, nearest first: any change inside one changes its result. */
+function booleanAncestorIds(graph: SceneGraph, id: string | null | undefined): string[] {
+ const ids: string[] = []
+ const seen = new Set<string>()
+ let node = id ? graph.getNode(id) : undefined
+ // Bad data can hold a parent cycle; the walk ends where it has been.
+ while (node && !seen.has(node.id)) {
+ seen.add(node.id)
+ if (node.type === 'BOOLEAN_OPERATION') ids.push(node.id)
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
+ }
+ return ids
+}
+
+/**
+ * Drops the cached result of every boolean operation `id` lies in, on each renderer: a change
+ * inside an operation changes what it draws and the box it takes.
+ */
+export function invalidateBooleanAncestors(
+ graph: SceneGraph,
+ renderers: Iterable<GraphEventRenderer>,
+ id: string | null | undefined
+): void {
+ const ancestorIds = booleanAncestorIds(graph, id)
+ if (ancestorIds.length === 0) return
+ for (const renderer of renderers) {
+ for (const ancestorId of ancestorIds) {
+ renderer.invalidateVectorPath(ancestorId)
+ renderer.invalidateNodePicture(ancestorId)
+ }
+ }
+}
+
function invalidateRenderersForChange(
graph: SceneGraph,
renderers: Iterable<GraphEventRenderer>,
@@ -67,12 +100,14 @@ function invalidateRenderersForChange(
invalidateNodePicture: boolean
) {
const invalidation = rendererInvalidationForChanges(changes, { preview: !invalidateNodePicture })
+ // From the layer itself: a boolean operation's own change, such as its operation, counts too.
+ invalidateBooleanAncestors(graph, renderers, id)
for (const renderer of renderers) {
if (invalidation.geometryCache) renderer.invalidateVectorPath(id)
if (invalidation.nodePicture)
renderer.invalidateNodePicture(id, Object.keys(changes) as (keyof SceneNode)[])
if (Object.keys(changes).some((key) => TILED_CHUNK_TOPOLOGY_KEYS.has(key as keyof SceneNode))) {
- renderer.tiledScene.invalidateStructure()
+ renderer.tiledScene.invalidateStructure(id, graph.getNode(id)?.parentId ?? null)
} else {
renderer.tiledScene.invalidateNode(id, graph)
}
@@ -121,11 +156,19 @@ export function createGraphEventSubscription(options: GraphEventOptions) {
options.emitEditorEvent('node:previewUpdated', id, changes)
}
- function onNodeStructureChanged(nodeId: string) {
+ /** Tells the renderers a layer was added, removed, or moved under `parentId`. */
+ function invalidateStructure(nodeId: string, parentId?: string | null) {
+ const graph = options.getGraph()
+ const parent = parentId ?? graph.getNode(nodeId)?.parentId ?? null
+ invalidateBooleanAncestors(graph, options.getRenderers(), parent)
for (const renderer of options.getRenderers()) {
renderer.invalidateNodePicture(nodeId)
- renderer.tiledScene.invalidateStructure()
+ renderer.tiledScene.invalidateStructure(nodeId, parent)
}
+ }
+
+ function onNodeStructureChanged(nodeId: string, parentId?: string | null) {
+ invalidateStructure(nodeId, parentId)
options.scheduleComponentSync(nodeId)
requestRenderFor(options.getGraph())
}
@@ -154,20 +197,28 @@ export function createGraphEventSubscription(options: GraphEventOptions) {
// the parent it had finds that component when the sync runs.
deleted: (id, parentId) => {
options.emitEditorEvent('node:deleted', id, parentId)
- onNodeStructureChanged(id)
+ for (const renderer of options.getRenderers()) renderer.forgetNode(id)
+ onNodeStructureChanged(id, parentId)
flowChanged(parentId)
if (parentId) options.scheduleComponentSync(parentId)
},
reparented: (nodeId, oldParentId, newParentId) => {
options.emitEditorEvent('node:reparented', nodeId, oldParentId, newParentId)
- onNodeStructureChanged(nodeId)
+ // Both parents are told; the frame is asked for once.
+ invalidateStructure(nodeId, newParentId)
+ invalidateStructure(nodeId, oldParentId)
+ options.scheduleComponentSync(nodeId)
+ requestRenderFor(options.getGraph())
flowChanged(oldParentId)
flowChanged(newParentId)
if (oldParentId) options.scheduleComponentSync(oldParentId)
},
reordered: (nodeId, parentId, index, previousParentId) => {
options.emitEditorEvent('node:reordered', nodeId, parentId, index, previousParentId)
- onNodeStructureChanged(nodeId)
+ onNodeStructureChanged(nodeId, parentId)
+ if (previousParentId && previousParentId !== parentId) {
+ onNodeStructureChanged(nodeId, previousParentId)
+ }
flowChanged(parentId)
flowChanged(previousParentId)
if (previousParentId && previousParentId !== parentId) {
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index 532406795..975b4da8b 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -12,7 +12,7 @@ import { applyBoundVisibilityEdit, bindsVisibility } from './components/authorin
import { createLayoutModeActions } from './layout-mode'
import { createNodePreviewActions } from './node-preview'
import { createNudgeActions } from './nudge'
-import { refitGroupsAroundLayers } from './structure/group/bounds'
+import { refitContainers, refitGroupsAroundLayers } from './structure/group/bounds'
import { pathTextEditChanges } from './text/path-edit'
import type { EditorContext } from './types'
import { createVariableBindingActions } from './variable-bindings'
@@ -37,6 +37,7 @@ export function createNodeActions(ctx: EditorContext) {
// A layer's modes reach the layers inside it.
if (changes.variableModes) reconcileVariableLayouts(ctx.graph, { subtrees: [id] })
if (changes.visible !== undefined) refitGroupsAroundLayers(ctx, [id])
+ if (changes.booleanOperation !== undefined) refitContainers(ctx, [id])
ctx.runLayoutForNode(id)
}
diff --git a/packages/core/src/editor/shapes/pen.ts b/packages/core/src/editor/shapes/pen.ts
index f5fc5aa6a..caffaccad 100644
--- a/packages/core/src/editor/shapes/pen.ts
+++ b/packages/core/src/editor/shapes/pen.ts
@@ -5,8 +5,8 @@ import type {
VectorSegment,
VectorVertex
} from '@open-pencil/scene-graph'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/copy'
import type { Vector } from '@open-pencil/scene-graph/primitives'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
import { BLACK } from '#core/constants'
import { createVectorFromNetwork, type CreateShape } from '#core/editor/shapes/vector'
diff --git a/packages/core/src/editor/structure/group/bounds.ts b/packages/core/src/editor/structure/group/bounds.ts
index 17decbb21..7623fa72f 100644
--- a/packages/core/src/editor/structure/group/bounds.ts
+++ b/packages/core/src/editor/structure/group/bounds.ts
@@ -27,6 +27,14 @@ export function fitEnclosingGroupsWithUndo(ctx: EditorContext, parentIds: Iterab
})
}
+/**
+ * Refits these containers themselves and the groups around them: a boolean operation whose
+ * operation changed takes the box of its new result, as it does when an operand moves.
+ */
+export function refitContainers(ctx: EditorContext, ids: Iterable<string>) {
+ fitEnclosingGroups(ctx.graph, ids, groupFitOptions(ctx.getRenderer(), ctx.graph))
+}
+
/**
* Refits the groups around layers that were shown or hidden, since a group spans only the layers
* it shows. The fit follows from what the layers show, so an edit that replays on undo and redo
diff --git a/packages/core/src/figma-api/accessors/vector.ts b/packages/core/src/figma-api/accessors/vector.ts
index ab73d7253..812274dea 100644
--- a/packages/core/src/figma-api/accessors/vector.ts
+++ b/packages/core/src/figma-api/accessors/vector.ts
@@ -1,7 +1,7 @@
import type {
+ GeometryPath,
HandleMirroring,
VectorNetwork as SceneVectorNetwork,
- VectorRegion as SceneVectorRegion,
VectorSegment,
VectorVertex,
WindingRule
@@ -26,6 +26,7 @@ import {
import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { geometryBlobToSVGPath } from '#core/io/formats/svg/paths'
import { computeAccurateBounds } from '#core/vector/curve-math'
+import { regenerateFillGeometry } from '#core/vector/fill-geometry'
export interface FigmaVectorPath {
readonly windingRule: WindingRule | 'NONE'
@@ -88,22 +89,13 @@ function normalizeInputNetwork(value: FigmaVectorNetwork): SceneVectorNetwork {
y: segment.tangentEnd?.y ?? 0
}
})),
- regions: regions.map(sceneRegion)
+ regions: regions.map((region) => ({
+ windingRule: region.windingRule,
+ loops: region.loops.map((loop) => [...loop])
+ }))
})
}
-/** A region as the network stores it, with paints of its own only when Figma's names them. */
-function sceneRegion(region: FigmaVectorRegion): SceneVectorRegion {
- const scene: SceneVectorRegion = {
- windingRule: region.windingRule,
- loops: region.loops.map((loop) => [...loop])
- }
- if (region.fills !== undefined)
- scene.fills = parseFigmaPaints(region.fills, 'set_vectorNetwork', 'vectorNetwork')
- if (region.fillStyleId) scene.fillStyleId = region.fillStyleId
- return scene
-}
-
function validateRegionPaintMetadata(regions: readonly FigmaVectorRegion[]): void {
for (let index = 0; index < regions.length; index++) {
const region = regions[index]
@@ -116,11 +108,23 @@ function validateRegionPaintMetadata(regions: readonly FigmaVectorRegion[]): voi
}
}
-/** The network as the layer's path; its fill geometry rebuilds from it when next needed. */
+function geometryForRegions(regions: readonly FigmaVectorRegion[]): GeometryPath[] {
+ if (!regions.some((region) => region.fills !== undefined || region.fillStyleId !== undefined)) {
+ return []
+ }
+ return regions.map((region) => ({
+ windingRule: region.windingRule,
+ commandsBlob: new Uint8Array(),
+ fills: parseFigmaPaints(region.fills ?? [], 'set_vectorNetwork', 'vectorNetwork'),
+ fillStyleId: region.fillStyleId ?? ''
+ }))
+}
+
function setGeometry(
target: ProxyThis,
internals: NodeProxyInternals,
- network: SceneVectorNetwork
+ network: SceneVectorNetwork,
+ fillGeometry: GeometryPath[]
): void {
const node = raw(target, internals)
const bounds = computeAccurateBounds(network)
@@ -128,6 +132,8 @@ function setGeometry(
const normalized = hasGeometry
? transformVectorNetwork([1, 0, -bounds.x, 0, 1, -bounds.y, 0, 0, 1], network)
: structuredClone(EMPTY_NETWORK)
+ const normalizedGeometry =
+ fillGeometry.length > 0 ? regenerateFillGeometry(normalized, fillGeometry) : []
updateNode(target, internals, {
x: hasGeometry ? node.x + bounds.x : node.x,
@@ -135,7 +141,7 @@ function setGeometry(
width: hasGeometry ? bounds.width : 0,
height: hasGeometry ? bounds.height : 0,
vectorNetwork: normalized,
- fillGeometry: [],
+ fillGeometry: normalizedGeometry,
strokeGeometry: []
})
}
@@ -160,8 +166,9 @@ function assignVectorNetwork(
if (errors.length > 0) throw new TypeError(`Invalid vectorNetwork: ${errors.join('; ')}`)
validateRegionPaintMetadata(value.regions ?? [])
const network = normalizeInputNetwork(value)
+ const fillGeometry = geometryForRegions(value.regions ?? [])
prepareVectorDataEdit(target, internals, setter)
- setGeometry(target, internals, network)
+ setGeometry(target, internals, network, fillGeometry)
}
function readVectorPaths(
@@ -199,15 +206,15 @@ function readVectorNetwork(target: ProxyThis, internals: NodeProxyInternals): Fi
})
)
const sourceRegions = (network as Partial<SceneVectorNetwork>).regions ?? []
- // A region without paints of its own reads the layer's, as in Figma.
- const regions = sourceRegions.map((region) =>
- Object.freeze({
+ const regions = sourceRegions.map((region, index) => {
+ const geometry = node.fillGeometry.at(index)
+ return Object.freeze({
windingRule: region.windingRule,
loops: Object.freeze(region.loops.map((loop) => Object.freeze([...loop]))),
- fillStyleId: region.fillStyleId ?? '',
- fills: Object.freeze((region.fills ?? node.fills).map((paint) => toFigmaPaint(paint)))
+ fillStyleId: geometry?.fillStyleId ?? '',
+ fills: Object.freeze((geometry?.fills ?? []).map((paint) => toFigmaPaint(paint)))
})
- )
+ })
return Object.freeze({
vertices: Object.freeze(vertices),
segments: Object.freeze(segments),
@@ -243,7 +250,7 @@ export function installVectorNodeProxyAccessors(
if (!Array.isArray(value)) throw new TypeError('vectorPaths must be an array')
const network = networkFromVectorPaths(value)
prepareVectorDataEdit(this, internals, 'vectorPaths')
- setGeometry(this, internals, network)
+ setGeometry(this, internals, network, [])
},
enumerable: true,
configurable: true
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 84c7a7b45..20f56ad62 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -9,6 +9,7 @@ import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas'
import { groupFitOptions } from '#core/canvas/boolean'
import { IS_BROWSER, type InterfaceTheme } from '#core/constants'
+import { invalidateBooleanAncestors } from '#core/editor/graph-events'
import { newLayerDefaults } from '#core/editor/shapes/defaults'
import { booleanOperationPaints, createBooleanOperation } from '#core/editor/structure/boolean'
import { wrapNodes } from '#core/editor/structure/container-wrap'
@@ -105,6 +106,7 @@ export class FigmaAPI implements NodeProxyHost {
private _nodeCache = new Map<string, FigmaNodeProxy>()
private _pageProxies = new WeakSet<FigmaNodeProxy>()
private _renderer: SkiaRenderer | null = null
+ private _unbindRendererEvents: (() => void) | null = null
/** The interface theme new sections take their fill from, as in Figma. */
theme: InterfaceTheme = 'light'
@@ -126,8 +128,33 @@ export class FigmaAPI implements NodeProxyHost {
this._currentPageId = pages[0]?.id ?? graph.rootId
}
+ /**
+ * The renderer that measures for the API: boolean results and flattened vectors. It keeps
+ * each boolean operation's result between readings, so the API tells it when a change lands
+ * inside one, as the editor does for its renderers.
+ */
setRenderer(renderer: SkiaRenderer | null): void {
+ this._unbindRendererEvents?.()
+ this._unbindRendererEvents = null
this._renderer = renderer
+ if (!renderer) return
+ const graph = this.graph
+ const invalidate = (id: string | null | undefined) =>
+ invalidateBooleanAncestors(graph, [renderer], id)
+ this._unbindRendererEvents = graph.onNodeEvents({
+ created: (node) => invalidate(node.parentId),
+ updated: (id) => invalidate(id),
+ previewUpdated: (id) => invalidate(id),
+ deleted: (_id, parentId) => invalidate(parentId),
+ reparented: (id, oldParentId) => {
+ invalidate(oldParentId)
+ invalidate(graph.getNode(id)?.parentId)
+ },
+ reordered: (_id, parentId, _index, previousParentId) => {
+ invalidate(parentId)
+ invalidate(previousParentId)
+ }
+ })
}
get groupFitOptions(): GroupFitOptions {
diff --git a/packages/core/src/geometry/scene.ts b/packages/core/src/geometry/scene.ts
index 5bc1636ec..9ee889611 100644
--- a/packages/core/src/geometry/scene.ts
+++ b/packages/core/src/geometry/scene.ts
@@ -6,7 +6,7 @@ import {
getWorldHandles,
getWorldMatrix
} from '@open-pencil/scene-graph/coordinate'
-import Matrix from '@open-pencil/scene-graph/matrix'
+import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
import type { Vector, Rect } from '@open-pencil/scene-graph/primitives'
import type { RotationPreview, ViewportTransform } from './types'
@@ -36,7 +36,15 @@ export function createSceneGeometry(graph: SceneGraph, preview?: RotationPreview
return source ? node(source) : undefined
}
}
- const worldMatrix = (source: SceneNode) => getWorldMatrix(node(source), reader)
+ // One view serves one draw or input operation, so a layer's world matrix is walked once.
+ const worldMatrices = new Map<string, Mat3>()
+ const worldMatrix = (source: SceneNode): Mat3 => {
+ const cached = worldMatrices.get(source.id)
+ if (cached) return cached
+ const matrix = getWorldMatrix(node(source), reader)
+ worldMatrices.set(source.id, matrix)
+ return matrix
+ }
const screenMatrix = (source: SceneNode, viewport: ViewportTransform) =>
Matrix.multiply(viewportMatrix(viewport), worldMatrix(source))
@@ -85,7 +93,7 @@ export function createSceneGeometry(graph: SceneGraph, preview?: RotationPreview
},
/** Same world-space rectangle, with reflected axes removed for readable labels. */
unreflectedWorldMatrix(source: SceneNode) {
- const world = worldMatrix(source)
+ const world = [...worldMatrix(source)]
const { x: flipX, y: flipY } = reflections(source)
const origin = Matrix.mapPoint(world, {
x: flipX < 0 ? source.width : 0,
diff --git a/packages/core/src/io/formats/fig/export/index.ts b/packages/core/src/io/formats/fig/export/index.ts
index a5cc32536..69ee872b0 100644
--- a/packages/core/src/io/formats/fig/export/index.ts
+++ b/packages/core/src/io/formats/fig/export/index.ts
@@ -253,16 +253,18 @@ function canUseWorker(): boolean {
return typeof Worker !== 'undefined' && IS_BROWSER
}
-function compressViaWorker(
- schemaDeflated: Uint8Array,
- kiwiData: Uint8Array,
- thumbnailPNG: Uint8Array,
- metaJSON: string,
- imageEntries: Array<{ name: string; data: Uint8Array }>,
- figKiwiVersion?: number,
- compressionLevel?: number,
- kind?: FigFileKind
-): Promise<Uint8Array> {
+/** Compresses in a worker; it takes what `compressFigData` takes. */
+function compressViaWorker(...args: Parameters<typeof compressFigData>): Promise<Uint8Array> {
+ const [
+ schemaDeflated,
+ kiwiData,
+ thumbnailPNG,
+ metaJSON,
+ imageEntries,
+ figKiwiVersion,
+ compressionLevel,
+ kind
+ ] = args
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module'
diff --git a/packages/core/src/io/formats/raster/headless.ts b/packages/core/src/io/formats/raster/headless.ts
index fa0c34f10..18d9dacf2 100644
--- a/packages/core/src/io/formats/raster/headless.ts
+++ b/packages/core/src/io/formats/raster/headless.ts
@@ -45,6 +45,8 @@ export async function headlessRenderNodes(
} = {}
): Promise<Uint8Array | null> {
const { ck, renderer } = await getRenderer()
+ // One renderer serves every document: paths keyed by layer id must not outlive theirs.
+ renderer.nodePaths.clear()
renderer.invalidateAllPictures()
await renderer.prepareForExport(graph, pageId, nodeIds)
return renderNodesToImage(ck, renderer, graph, pageId, nodeIds, {
@@ -62,6 +64,8 @@ export async function headlessRenderThumbnail(
height: number
): Promise<Uint8Array | null> {
const { ck, renderer } = await getRenderer()
+ // One renderer serves every document: paths keyed by layer id must not outlive theirs.
+ renderer.nodePaths.clear()
renderer.invalidateAllPictures()
await renderer.prepareForExport(graph, pageId, graph.getNode(pageId)?.childIds ?? [])
return renderThumbnail(ck, renderer, graph, pageId, width, height)
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index d5fc79781..13eb83638 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -29,17 +29,12 @@ import {
export { geometryBlobToSVGPath, nodeOutlinePath, type OutlineNode } from './paths'
import type { SceneGraph, SceneNode, Fill, Stroke, VectorNetwork } from '@open-pencil/scene-graph'
-import {
- hasRegionFills,
- looseSegments,
- regionSVGPaths
-} from '@open-pencil/scene-graph/vector-network'
+import { looseSegments, regionSVGPaths } from '@open-pencil/scene-graph/vector-network'
import { arrowHeadElements, openPathElements, vectorArrowHeads } from './arrows'
import type { SVGExportContext, SVGFontAlias } from './defs'
import { svg, renderSVGNode } from './node'
import type { SVGNode } from './node'
-import { fillOutlines, paintedOutline } from './regions'
import { alignedStroke, alignedStrokeElement, shapeWithTextDetailElements } from './strokes'
import { renderTextNode } from './text/export'
import type { SVGTextLayout } from './text/lines'
@@ -60,30 +55,49 @@ function networkElements(
return [...regions, ...openPathElements(node, network, common, looseSegments)]
}
-type SVGAttrs = Record<string, string | number | undefined>
-
function vectorShapeElements(
node: SceneNode,
- common: SVGAttrs,
- strokeAttrs: SVGAttrs,
+ common: Record<string, string | number | undefined>,
+ strokeAttrs: Record<string, string | number | undefined>,
ctx: SVGExportContext,
fallbackFills?: Fill[]
): SVGNode[] {
const elements: SVGNode[] = []
- const filled = fillOutlines(node)
- for (const outline of filled?.outlines ?? []) {
- const attrs = {
- d: outline.d,
- 'fill-rule': outline.windingRule === 'EVENODD' ? 'evenodd' : undefined,
- ...common
+ if (node.fillGeometry.length > 0) {
+ for (const geo of node.fillGeometry) {
+ const d = geometryBlobToSVGPath(geo.commandsBlob)
+ if (!d) continue
+ const attrs = {
+ d,
+ 'fill-rule': geo.windingRule === 'EVENODD' ? 'evenodd' : undefined,
+ ...common
+ }
+ const pathFills = geo.fills?.length ? geo.fills : fallbackFills
+ if (!pathFills) {
+ elements.push(svg('path', attrs))
+ continue
+ }
+ const visibleFills = pathFills.filter((fill) => fill.visible)
+ if (visibleFills.length === 0) {
+ elements.push(svg('path', { ...attrs, fill: 'none' }))
+ continue
+ }
+ for (const [index, fill] of visibleFills.entries()) {
+ const fillAttr = resolveFill(fill, node, ctx)
+ if (!fillAttr) continue
+ elements.push(
+ svg('path', {
+ ...attrs,
+ fill: fillAttr,
+ 'fill-opacity': solidFillOpacity(fill, ctx.colorSpace),
+ stroke: index === visibleFills.length - 1 ? common.stroke : 'none'
+ })
+ )
+ }
}
- elements.push(...paintedOutline(node, attrs, ctx, outline.fills ?? fallbackFills))
+ } else if (node.vectorNetwork) {
+ elements.push(...networkElements(node, node.vectorNetwork, common))
}
- const network = node.vectorNetwork
- if (network && !filled) elements.push(...networkElements(node, network, common))
- // Traced regions leave the open segments, which the canvas strokes, to add here.
- else if (network && filled?.traced && looseSegments(network).length > 0)
- elements.push(...openPathElements(node, network, common, looseSegments))
if (node.strokeGeometry.length > 0 && strokeAttrs.stroke && strokeAttrs.stroke !== 'none') {
for (const geo of node.strokeGeometry) {
const d = geometryBlobToSVGPath(geo.commandsBlob)
@@ -297,7 +311,7 @@ function buildSVGStrokeAttrs(
}
function hasPathLevelFills(node: SceneNode): boolean {
- return node.type === 'VECTOR' && hasRegionFills(node.vectorNetwork)
+ return node.type === 'VECTOR' && node.fillGeometry.some((geometry) => geometry.fills?.length)
}
function buildShapeChildren(
diff --git a/packages/core/src/io/formats/svg/regions.ts b/packages/core/src/io/formats/svg/regions.ts
deleted file mode 100644
index 7a74380f3..000000000
--- a/packages/core/src/io/formats/svg/regions.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import type { Fill, SceneNode, WindingRule } from '@open-pencil/scene-graph'
-import {
- fillGeometryMatchesRegions,
- hasRegionFills,
- regionSVGPaths
-} from '@open-pencil/scene-graph/vector-network'
-
-import { resolveFill, solidFillOpacity, type SVGExportContext } from './defs'
-import { svg, type SVGNode } from './node'
-import { geometryBlobToSVGPath } from './paths'
-
-/** An outline to fill and the paints of its own, if any. */
-export interface FillOutline {
- d: string
- windingRule: WindingRule
- fills?: Fill[]
-}
-
-/** A vector's filled outlines, and whether they were traced from its network's regions. */
-export interface FillOutlines {
- outlines: FillOutline[]
- traced: boolean
-}
-
-/**
- * A vector's filled outlines as the canvas draws them. Regions with paints of their own fill
- * their outlines from the fill geometry when it has one per region, or else their traced loops.
- */
-export function fillOutlines(node: SceneNode): FillOutlines | null {
- const network = node.vectorNetwork
- if (network && hasRegionFills(network)) {
- const traced = !fillGeometryMatchesRegions(node.fillGeometry, network)
- const paths = traced
- ? regionSVGPaths(network)
- : node.fillGeometry.map((geometry) => geometryBlobToSVGPath(geometry.commandsBlob))
- const outlines = network.regions.flatMap((region, index) => {
- const d = paths[index]
- if (!d) return []
- const windingRule = traced ? region.windingRule : node.fillGeometry[index].windingRule
- return [{ d, windingRule, fills: region.fills }]
- })
- return { outlines, traced }
- }
- if (node.fillGeometry.length === 0) return null
- const outlines = node.fillGeometry.flatMap((geometry) => {
- const d = geometryBlobToSVGPath(geometry.commandsBlob)
- return d ? [{ d, windingRule: geometry.windingRule }] : []
- })
- return { outlines, traced: false }
-}
-
-/** An outline painted once per visible paint, the last one carrying the stroke. */
-export function paintedOutline(
- node: SceneNode,
- attrs: Record<string, string | number | undefined>,
- ctx: SVGExportContext,
- pathFills: Fill[] | undefined
-): SVGNode[] {
- if (!pathFills) return [svg('path', attrs)]
- const visibleFills = pathFills.filter((fill) => fill.visible)
- if (visibleFills.length === 0) return [svg('path', { ...attrs, fill: 'none' })]
- return visibleFills.flatMap((fill, index) => {
- const fillAttr = resolveFill(fill, node, ctx)
- if (!fillAttr) return []
- return [
- svg('path', {
- ...attrs,
- fill: fillAttr,
- 'fill-opacity': solidFillOpacity(fill, ctx.colorSpace),
- stroke: index === visibleFills.length - 1 ? attrs.stroke : 'none'
- })
- ]
- })
-}
diff --git a/packages/core/src/library/materialize.ts b/packages/core/src/library/materialize.ts
index 1a9983196..dd5649358 100644
--- a/packages/core/src/library/materialize.ts
+++ b/packages/core/src/library/materialize.ts
@@ -1,6 +1,5 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { cloneNodeProps } from '@open-pencil/scene-graph/copy'
-import { regionFills } from '@open-pencil/scene-graph/vector-network'
import { remapCopiedReferences } from './copied-references'
import { findLibraryDefinition } from './definitions'
@@ -110,7 +109,10 @@ function copyImages(source: SceneGraph, target: SceneGraph, mappedIds: Map<strin
const hashes = new Set<string>()
for (const sourceId of mappedIds.keys()) {
const node = source.getNode(sourceId)
- const fills = [...(node?.fills ?? []), ...regionFills(node?.vectorNetwork ?? null)]
+ const fills = [
+ ...(node?.fills ?? []),
+ ...(node?.fillGeometry.flatMap((geometry) => geometry.fills ?? []) ?? [])
+ ]
for (const fill of fills) {
if (fill.type === 'IMAGE' && fill.imageHash) hashes.add(fill.imageHash)
}
diff --git a/packages/core/src/text/font/status.ts b/packages/core/src/text/font/status.ts
index 9f7e3e25e..5ae786501 100644
--- a/packages/core/src/text/font/status.ts
+++ b/packages/core/src/text/font/status.ts
@@ -43,33 +43,99 @@ function faceKey(family: string, style: string, name: string): string {
/** The text nodes under each root, and each root that is itself text. */
function rootTextNodes(graph: SceneGraph, rootIds: readonly string[]): SceneNode[] {
- return rootIds.flatMap((rootId) => {
- const root = graph.getNode(rootId)
- if (!root) return []
- const nodes = [root, ...graph.flattenTree(rootId).map(({ node }) => node)]
- return nodes.filter((node) => node.type === 'TEXT')
- })
+ const texts: SceneNode[] = []
+ const stack = [...rootIds]
+ while (stack.length > 0) {
+ const node = graph.getNode(stack.pop() ?? '')
+ if (!node) continue
+ if (node.type === 'TEXT') texts.push(node)
+ for (const childId of node.childIds) stack.push(childId)
+ }
+ return texts
}
-function collectFaceUses(graph: SceneGraph, rootIds: readonly string[]): MutableFontFaceUse[] {
- const uses = new Map<string, MutableFontFaceUse>()
- for (const node of rootTextNodes(graph, rootIds)) {
- // Faces that load as one style ("Book" and "Roman" at 400) are still faces of their own.
- for (const { family, style, name } of collectNamedNodeFontFaces(node)) {
- const key = faceKey(family, style, name)
- const use = uses.get(key) ?? {
- family,
- style,
- name,
- nodeIds: new Set<string>(),
- nodeNames: new Set<string>()
+type TextFontFaces = {
+ name: string
+ faces: Array<{ family: string; style: string; name: string }>
+}
+
+/**
+ * The faces each text under the roots uses, kept by layer: a status is read from the layers
+ * as they are, and an edit updates the one layer it touched, so a page of tens of thousands of
+ * layers is walked once rather than at every keystroke.
+ */
+export class DocumentFontUses {
+ private readonly byNode = new Map<string, TextFontFaces>()
+ private readonly roots: readonly string[]
+
+ constructor(
+ private readonly graph: SceneGraph,
+ rootIds: string | readonly string[]
+ ) {
+ this.roots = typeof rootIds === 'string' ? [rootIds] : rootIds
+ for (const node of rootTextNodes(graph, this.roots)) this.remember(node)
+ }
+
+ /**
+ * `nodeId` changed, arrived, or moved: the faces of the text it is or holds are read again
+ * where they are now, and those moved off the roots are forgotten.
+ */
+ update(nodeId: string): void {
+ const node = this.graph.getNode(nodeId)
+ // Gone, or no longer text: whatever it was remembered as is forgotten.
+ if (node?.type !== 'TEXT') this.byNode.delete(nodeId)
+ if (!node) return
+ const under = this.underRoots(nodeId)
+ for (const node of rootTextNodes(this.graph, [nodeId])) {
+ if (under) this.remember(node)
+ else this.byNode.delete(node.id)
+ }
+ }
+
+ /** `nodeId` left the document, with whatever was under it. */
+ remove(nodeId: string): void {
+ this.byNode.delete(nodeId)
+ }
+
+ status(manager: FontManager = fontManager): DocumentFontStatus {
+ const uses = new Map<string, MutableFontFaceUse>()
+ for (const [nodeId, { name, faces }] of this.byNode) {
+ // A layer deleted under a deleted ancestor reported nothing itself; it is skipped here.
+ if (!this.graph.getNode(nodeId)) continue
+ // Faces that load as one style ("Book" and "Roman" at 400) are still faces of their own.
+ for (const { family, style, name: faceName } of faces) {
+ const key = faceKey(family, style, faceName)
+ const use = uses.get(key) ?? {
+ family,
+ style,
+ name: faceName,
+ nodeIds: new Set<string>(),
+ nodeNames: new Set<string>()
+ }
+ use.nodeIds.add(nodeId)
+ use.nodeNames.add(name)
+ uses.set(key, use)
}
- use.nodeIds.add(node.id)
- use.nodeNames.add(node.name)
- uses.set(key, use)
}
+ const faces = [...uses.values()]
+ .map((use) => faceStatus(use, manager))
+ .sort((a, b) => a.family.localeCompare(b.family) || a.name.localeCompare(b.name))
+ const issues = faces.filter((face) => face.status !== 'available')
+ return { faithful: issues.length === 0, faces, issues }
+ }
+
+ private remember(node: SceneNode): void {
+ this.byNode.set(node.id, { name: node.name, faces: collectNamedNodeFontFaces(node) })
+ }
+
+ private underRoots(nodeId: string): boolean {
+ let current: string | null = nodeId
+ while (current) {
+ if (this.roots.includes(current)) return true
+ current = this.graph.getNode(current)?.parentId ?? null
+ }
+ return false
}
- return [...uses.values()]
}
function faceStatus(use: MutableFontFaceUse, manager: FontManager): DocumentFontFaceStatus {
@@ -121,10 +187,5 @@ export function documentFontStatus(
rootIds: string | readonly string[],
manager: FontManager = fontManager
): DocumentFontStatus {
- const roots = typeof rootIds === 'string' ? [rootIds] : rootIds
- const faces = collectFaceUses(graph, roots)
- .map((use) => faceStatus(use, manager))
- .sort((a, b) => a.family.localeCompare(b.family) || a.name.localeCompare(b.name))
- const issues = faces.filter((face) => face.status !== 'available')
- return { faithful: issues.length === 0, faces, issues }
+ return new DocumentFontUses(graph, rootIds).status(manager)
}
diff --git a/packages/core/src/tools/vector/path.ts b/packages/core/src/tools/vector/path.ts
index c0b19b593..cef0fc1a0 100644
--- a/packages/core/src/tools/vector/path.ts
+++ b/packages/core/src/tools/vector/path.ts
@@ -1,7 +1,7 @@
import * as v from 'valibot'
import type { SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/copy'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
import type { FigmaAPI } from '#core/figma-api'
import { defineTool, nodeIdInputSchema, nodeInputSchema, toolNumber } from '#core/tools/schema'
diff --git a/packages/core/src/vector/fill-geometry.ts b/packages/core/src/vector/fill-geometry.ts
index 33bc40f03..9ff6a82ab 100644
--- a/packages/core/src/vector/fill-geometry.ts
+++ b/packages/core/src/vector/fill-geometry.ts
@@ -42,8 +42,11 @@ class GeometryBlobBuilder implements PathSink {
}
/**
- * Rebuild fillGeometry from a (possibly edited) VectorNetwork: one outline per region, in region
- * order, or one for the open chain of a network without regions. Paints stay on the regions.
+ * Rebuild fillGeometry command blobs from a (possibly edited) VectorNetwork so
+ * fills follow network edits. Imported .fig vectors pair fillGeometry entries
+ * with network regions positionally (fillGeometry[i] ↔ regions[i]); per-path
+ * fills are preserved. Networks without regions (open chains) map to a
+ * single fillGeometry entry.
*/
export function regenerateFillGeometry(
network: VectorNetwork,
@@ -51,6 +54,26 @@ export function regenerateFillGeometry(
): GeometryPath[] {
if (existing.length === 0) return existing
const { vertices, segments, regions } = network
+
+ if (regions.length === existing.length) {
+ return existing.map((g, i) => {
+ const region = regions[i]
+ const builder = new GeometryBlobBuilder()
+ for (const loop of region.loops) addLoopToPath(builder, loop, segments, vertices)
+ return { ...g, windingRule: region.windingRule, commandsBlob: builder.toBlob() }
+ })
+ }
+
+ if (regions.length === 0 && existing.length === 1) {
+ const builder = new GeometryBlobBuilder()
+ addOpenSegmentsToPath(builder, segments, vertices)
+ return [{ ...existing[0], commandsBlob: builder.toBlob() }]
+ }
+
+ // Region count no longer matches the imported fillGeometry (e.g. a region was
+ // deleted mid-edit) — the style mapping is unknown. Rebuild from the live
+ // network so committed fillGeometry stays coherent with vectorNetwork; styles
+ // fall back to node-level fills.
if (regions.length > 0) {
return regions.map((region) => {
const builder = new GeometryBlobBuilder()
@@ -61,8 +84,7 @@ export function regenerateFillGeometry(
if (segments.length > 0) {
const builder = new GeometryBlobBuilder()
addOpenSegmentsToPath(builder, segments, vertices)
- const windingRule = existing.length === 1 ? existing[0].windingRule : 'NONZERO'
- return [{ windingRule, commandsBlob: builder.toBlob() }]
+ return [{ windingRule: 'NONZERO' as const, commandsBlob: builder.toBlob() }]
}
return []
}
diff --git a/packages/core/tests/canvas/effects.test.ts b/packages/core/tests/canvas/effects.test.ts
new file mode 100644
index 000000000..4a3cc09b5
--- /dev/null
+++ b/packages/core/tests/canvas/effects.test.ts
@@ -0,0 +1,30 @@
+import { afterAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1), 'surface'))
+
+afterAll(() => renderer.destroy())
+
+test('filters are shared by their parameters and bounded, freeing the ones that fall out', () => {
+ const first = expectDefined(renderer.getCachedBlur(1), 'blur')
+ expect(renderer.getCachedBlur(1)).toBe(first)
+ const shadow = renderer.getCachedDropShadow(2, 3, 1.5, ck.BLACK)
+ expect(renderer.getCachedDropShadow(2, 3, 1.5, ck.BLACK)).toBe(shadow)
+ expect(renderer.imageFilterCache.size).toBe(2)
+
+ // A slider dragged through hundreds of radii keeps only the latest filters.
+ for (let step = 0; step < 300; step++) renderer.getCachedBlur(2 + step * 0.01)
+ expect(renderer.imageFilterCache.size).toBeLessThanOrEqual(256)
+ expect(first.isDeleted()).toBe(true)
+ expect(renderer.getCachedBlur(1)).not.toBe(first)
+
+ const mask = expectDefined(renderer.getCachedMaskBlur(1), 'mask blur')
+ for (let step = 0; step < 300; step++) renderer.getCachedMaskBlur(2 + step * 0.01)
+ expect(renderer.maskFilterCache.size).toBeLessThanOrEqual(256)
+ expect(mask.isDeleted()).toBe(true)
+})
diff --git a/packages/core/tests/canvas/highlight-rect.test.ts b/packages/core/tests/canvas/highlight-rect.test.ts
new file mode 100644
index 000000000..c4db87904
--- /dev/null
+++ b/packages/core/tests/canvas/highlight-rect.test.ts
@@ -0,0 +1,65 @@
+import { expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { drawNodeHighlightRect } from '#core/canvas/highlight-rect'
+
+const ck = await initCanvasKit()
+
+function pixel(surface: ReturnType<typeof ck.MakeSurface> & object, x: number, y: number) {
+ const image = surface.makeImageSnapshot()
+ const pixels = expectDefined(
+ image.readPixels(x, y, {
+ width: 1,
+ height: 1,
+ colorType: ck.ColorType.RGBA_8888,
+ alphaType: ck.AlphaType.Unpremul,
+ colorSpace: ck.ColorSpace.SRGB
+ }),
+ 'pixel'
+ )
+ image.delete()
+ return [pixels[0], pixels[1], pixels[2], pixels[3]]
+}
+
+test('a highlighted layer inside a flipped frame is outlined where it is drawn', () => {
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0], 'page')
+ const frame = graph.createNode('FRAME', page.id, {
+ x: 0,
+ y: 0,
+ width: 200,
+ height: 100,
+ flipX: true,
+ fills: []
+ })
+ const child = graph.createNode('RECTANGLE', frame.id, {
+ x: 0,
+ y: 40,
+ width: 20,
+ height: 20,
+ fills: []
+ })
+ const surface = expectDefined(ck.MakeSurface(200, 100), 'surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ try {
+ renderer.pageId = page.id
+ renderer.zoom = 1
+ const canvas = surface.getCanvas()
+ canvas.clear(ck.WHITE)
+ expect(drawNodeHighlightRect(renderer, canvas, graph, child.id, { r: 0, g: 0, b: 1 }, 1)).toBe(
+ true
+ )
+ surface.flush()
+ // Flipped, the child sits at x 180..200; the outline's top edge runs 5 px above its box.
+ expect(pixel(surface, 190, 35)[2]).toBeGreaterThan(200)
+ expect(pixel(surface, 190, 35)[0]).toBeLessThan(60)
+ expect(pixel(surface, 10, 35)).toEqual([255, 255, 255, 255])
+ } finally {
+ renderer.destroy()
+ }
+})
diff --git a/packages/core/tests/canvas/labels/paragraph-cache.test.ts b/packages/core/tests/canvas/labels/paragraph-cache.test.ts
new file mode 100644
index 000000000..6ba3d5748
--- /dev/null
+++ b/packages/core/tests/canvas/labels/paragraph-cache.test.ts
@@ -0,0 +1,25 @@
+import { afterAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+
+import { cachedGlyphWidth, measureGlyphWidth } from '#core/canvas/labels/paragraph-cache'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(8, 8), 'surface'))
+
+afterAll(() => renderer.destroy())
+
+test('a label is measured once per font and text', () => {
+ const font = new ck.Font(null, 11)
+ try {
+ const width = cachedGlyphWidth(renderer, font, '1234')
+ expect(width).toBe(measureGlyphWidth(font, '1234'))
+ expect(cachedGlyphWidth(renderer, font, '1234')).toBe(width)
+ expect(renderer.glyphWidths.get(font)?.size).toBe(1)
+ } finally {
+ font.delete()
+ }
+})
diff --git a/packages/core/tests/canvas/overlays/outline.test.ts b/packages/core/tests/canvas/overlays/outline.test.ts
new file mode 100644
index 000000000..6c0403640
--- /dev/null
+++ b/packages/core/tests/canvas/overlays/outline.test.ts
@@ -0,0 +1,26 @@
+import { afterAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+
+import { dashEffect, withScreenStroke } from '#core/canvas/overlays/outline'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(8, 8), 'surface'))
+
+afterAll(() => renderer.destroy())
+
+test('a screen stroke reuses its dash across frames at one zoom and makes another per zoom', () => {
+ renderer.zoom = 1
+ const draw = () => withScreenStroke(renderer, { color: ck.BLACK, dash: [4, 2] }, () => undefined)
+ draw()
+ draw()
+ expect(renderer.dashEffects.size).toBe(1)
+ const first = dashEffect(renderer, 4, 2)
+ expect(dashEffect(renderer, 4, 2)).toBe(first)
+ renderer.zoom = 2
+ draw()
+ expect(renderer.dashEffects.size).toBe(2)
+})
diff --git a/packages/core/tests/canvas/renderer/fonts.test.ts b/packages/core/tests/canvas/renderer/fonts.test.ts
new file mode 100644
index 000000000..b32bcea87
--- /dev/null
+++ b/packages/core/tests/canvas/renderer/fonts.test.ts
@@ -0,0 +1,58 @@
+import { afterAll, expect, spyOn, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+import { fontManager } from '@open-pencil/core/text'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(8, 8), 'surface'))
+
+afterAll(() => renderer.destroy())
+
+test('forgetting a layer drops the fonts it was waiting for and its text picture state', () => {
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0], 'page')
+ const node = graph.createNode('TEXT', page.id, { text: 'hello' })
+ renderer.trackFontDemand(node, 'Inter|400')
+ renderer.textPictureGenerations.set(node.id, { data: new Uint8Array(1), generation: 0 })
+ expect(renderer.pendingFontNodes.has(node.id)).toBe(true)
+
+ renderer.forgetNode(node.id)
+
+ expect(renderer.pendingFontNodes.has(node.id)).toBe(false)
+ expect(renderer.textPictureGenerations.has(node.id)).toBe(false)
+})
+
+test("a text's font readiness is found once per layer until the layer or the fonts change", async () => {
+ // A loaded face reads as ready; a pending reading is asked again each frame and not kept.
+ await fontManager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0], 'page')
+ const node = expectDefined(
+ graph.getNode(graph.createNode('TEXT', page.id, { text: 'hello' }).id),
+ 'text'
+ )
+ // A reading that is found again is not decided again: the memo is written once.
+ const written = spyOn(renderer.textReadiness, 'set')
+ const first = renderer.nodeFontReadiness(node)
+ expect(renderer.textReadiness.get(node.id)?.readiness).toBe(first)
+ expect(renderer.nodeFontReadiness(node)).toBe(first)
+ expect(written).toHaveBeenCalledTimes(1)
+
+ // A change to the layer drops the memo; the next frame decides again.
+ renderer.invalidateNodePicture(node.id)
+ expect(renderer.textReadiness.has(node.id)).toBe(false)
+ expect(renderer.nodeFontReadiness(node)).toBe(first)
+
+ // So does a layer object replaced by an edit, and a font generation that moved on.
+ graph.updateNode(node.id, { text: 'hello there' })
+ const edited = expectDefined(graph.getNode(node.id), 'edited')
+ renderer.nodeFontReadiness(edited)
+ expect(renderer.textReadiness.get(node.id)?.node).toBe(edited)
+ renderer.fontGeneration += 1
+ renderer.nodeFontReadiness(edited)
+ expect(renderer.textReadiness.get(node.id)?.generation).toBe(renderer.fontGeneration)
+})
diff --git a/packages/core/tests/canvas/renderer/scene-geometry.test.ts b/packages/core/tests/canvas/renderer/scene-geometry.test.ts
new file mode 100644
index 000000000..b7c1e4797
--- /dev/null
+++ b/packages/core/tests/canvas/renderer/scene-geometry.test.ts
@@ -0,0 +1,21 @@
+import { afterAll, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+const ck = await initCanvasKit()
+const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(8, 8), 'surface'))
+
+afterAll(() => renderer.destroy())
+
+test('one scene geometry serves a frame and the next frame starts afresh', () => {
+ const graph = new SceneGraph()
+ const geometry = renderer.sceneGeometry(graph, null)
+ expect(renderer.sceneGeometry(graph, null)).toBe(geometry)
+ expect(renderer.sceneGeometry(new SceneGraph(), null)).not.toBe(geometry)
+ renderer.frameGeometry = null
+ expect(renderer.sceneGeometry(graph, null)).not.toBe(geometry)
+})
diff --git a/packages/core/tests/canvas/renderer/selection-theme.test.ts b/packages/core/tests/canvas/renderer/selection-theme.test.ts
index 2e8e09c96..558b490a5 100644
--- a/packages/core/tests/canvas/renderer/selection-theme.test.ts
+++ b/packages/core/tests/canvas/renderer/selection-theme.test.ts
@@ -41,7 +41,6 @@ test('long-lived selection paints and text follow a new selection theme', () =>
const expected = rgb(ck.Color4f(r, g, b, 1))
for (const paint of [
renderer.selectionPaint,
- renderer.parentOutlinePaint,
renderer.penHandlePaint,
renderer.penVertexStroke
]) {
@@ -60,3 +59,16 @@ test('an unset theme returns to the default', () => {
expect(rgb(renderer.selectionPaint.getColor())).toEqual(rgb(renderer.selColor()))
})
})
+
+test('chrome colours are allocated once per theme and again after it changes', () => {
+ withRenderer((renderer) => {
+ const blue = renderer.selColor()
+ expect(renderer.selColor()).toBe(blue)
+ expect(renderer.selColor(0.5)).not.toBe(blue)
+ expect(renderer.selColor(0.5)).toBe(renderer.selColor(0.5))
+ renderer.setSelectionTheme(GREEN_THEME)
+ const green = renderer.selColor()
+ expect(green).not.toBe(blue)
+ expect(rgb(green)).toEqual(rgb(ck.Color4f(0.08, 0.5, 0.24, 1)))
+ })
+})
diff --git a/packages/core/tests/canvas/renderer/tiles/controller.test.ts b/packages/core/tests/canvas/renderer/tiles/controller.test.ts
index 155c6ce6a..b1bcd7938 100644
--- a/packages/core/tests/canvas/renderer/tiles/controller.test.ts
+++ b/packages/core/tests/canvas/renderer/tiles/controller.test.ts
@@ -1,5 +1,7 @@
import { beforeAll, describe, expect, mock, test } from 'bun:test'
+import type { Surface } from 'canvaskit-wasm'
+
import { expectDefined } from '#core-tests/helpers/assert'
import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
@@ -43,6 +45,24 @@ function createGridScene() {
return { graph, surface, renderer, pageId: page.id }
}
+/** The red, green, and blue of the surface's pixel at `x`, `y`, after a flush. */
+function pixelAt(surface: Surface, x: number, y: number): number[] {
+ surface.flush()
+ const image = surface.makeImageSnapshot()
+ const pixels = expectDefined(
+ image.readPixels(x, y, {
+ width: 1,
+ height: 1,
+ colorType: ck.ColorType.RGBA_8888,
+ alphaType: ck.AlphaType.Unpremul,
+ colorSpace: ck.ColorSpace.SRGB
+ }),
+ 'pixel'
+ )
+ image.delete()
+ return Array.from(pixels as Uint8Array).slice(0, 3)
+}
+
describe('tile scheduling', () => {
test('fills the frame budget with tiles whose cost is not measured yet', () => {
const { graph, surface, renderer } = createGridScene()
@@ -89,7 +109,7 @@ describe('tile scheduling', () => {
}
})
- test('zooms over the previous level scaled and renders the exact level once the zoom pauses', () => {
+ test('zooms over the quantized step rendered mid-gesture and the exact level once it pauses', () => {
const { graph, surface, renderer, pageId } = createGridScene()
const controller = new TiledSceneController({ now: () => 0 })
try {
@@ -99,12 +119,15 @@ describe('tile scheduling', () => {
}
expect(result.covered).toBe(true)
- // The level moves: nothing renders, the level-1 tiles stand in scaled.
+ // The level moves: the quantized step above 1.3, √2, renders under the moving budget and
+ // stands in for the exact level with the level-1 tiles.
renderer.zoom = 1.3
renderer.navigationPhase = 'zoom'
const moving = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 1)
expect(moving.covered).toBe(false)
- expect(moving.metrics.interruptibleCompleted).toBe(0)
+ expect(moving.metrics.interruptibleCompleted).toBeGreaterThan(0)
+ expect(controller.isRendered({ pageId, level: 2 ** 0.5, x: 0, y: 0 })).toBe(true)
+ expect(controller.isRendered({ pageId, level: 1.3, x: 0, y: 0 })).toBe(false)
expect(moving.fallbackTileCount).toBeGreaterThan(0)
expect(moving.uncoveredAreaCount).toBe(0)
@@ -119,7 +142,48 @@ describe('tile scheduling', () => {
}
expect(settled.covered).toBe(true)
expect(settled.fallbackTileCount).toBe(0)
- void pageId
+ } finally {
+ controller.destroy()
+ renderer.destroy()
+ }
+ })
+
+ test('presents a new level once every visible tile exists, then tiles as they land', () => {
+ const { graph, surface, renderer } = createGridScene()
+ // Free while settling; afterwards 10 ms a reading, so an idle frame renders one tile.
+ let step = 0
+ let time = 0
+ const controller = new TiledSceneController({ now: () => (time += step) })
+ try {
+ for (let frame = 0; frame < 12; frame++) {
+ controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 0)
+ }
+ // At 1.3 the viewport is three by two tiles, all inside the settled level-1 area.
+ step = 10
+ renderer.zoom = 1.3
+ renderer.navigationPhase = 'zoom'
+ controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 1)
+ renderer.navigationPhase = 'idle'
+ const visibleTiles = 3 * 2
+ let settling = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 1)
+ let frames = 0
+ // The exact tiles rendered so far stay hidden: the whole viewport is still a stand-in.
+ for (; !settling.covered && frames < 60; frames++) {
+ expect(settling.fallbackTileCount).toBe(visibleTiles)
+ expect(settling.uncoveredAreaCount).toBe(0)
+ settling = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 1)
+ }
+ expect(frames).toBeGreaterThan(1)
+ expect(settling.covered).toBe(true)
+ expect(settling.fallbackTileCount).toBe(0)
+
+ // Committed, the level shows the tiles a pan reveals one by one over the stand-ins.
+ renderer.panX = -600
+ renderer.navigationPhase = 'pan'
+ const panning = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 2)
+ expect(panning.covered).toBe(false)
+ expect(panning.fallbackTileCount).toBeGreaterThan(0)
+ expect(panning.fallbackTileCount).toBeLessThan(visibleTiles)
} finally {
controller.destroy()
renderer.destroy()
@@ -200,10 +264,11 @@ describe('tile scheduling', () => {
for (let frame = 0; frame < 60 && idle.metrics.interruptibleCompleted === 0; frame++) {
idle = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 0)
}
- // The 1280 × 800 viewport at level 1 is three by two tiles of 512.
+ // The 1280 × 800 viewport at level 1 is three by two tiles of 512. The page is first
+ // shown whole, so the one tile stays hidden with the rest at the page colour.
const visibleTiles = 3 * 2
expect(idle.metrics.interruptibleCompleted).toBe(1)
- expect(idle.uncoveredAreaCount).toBe(visibleTiles - 1)
+ expect(idle.uncoveredAreaCount).toBe(visibleTiles)
// Panning, a job estimated over the budget is skipped and the holes stay page colour.
renderer.navigationPhase = 'pan'
@@ -212,8 +277,17 @@ describe('tile scheduling', () => {
// Every queued tile is too dear, and each is tried before the frame gives up.
expect(panning.metrics.skippedWithFallback).toBe(visibleTiles - 1)
expect(panning.fallbackTileCount).toBe(0)
- expect(panning.uncoveredAreaCount).toBe(visibleTiles - 1)
+ expect(panning.uncoveredAreaCount).toBe(visibleTiles)
expect(panning.pending).toBe(true)
+
+ // Idle again, the level presents once its last tile renders.
+ renderer.navigationPhase = 'idle'
+ let settled = panning
+ for (let frame = 0; frame < 60 && !settled.covered; frame++) {
+ settled = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 1)
+ expect(settled.uncoveredAreaCount).toBe(settled.covered ? 0 : visibleTiles)
+ }
+ expect(settled.covered).toBe(true)
} finally {
controller.destroy()
renderer.destroy()
@@ -295,8 +369,10 @@ describe('tiles with image previews', () => {
const decoded = new Promise<void>((resolve) => {
release = resolve
})
+ const edges: number[] = []
const decoder: ImagePreviewDecoder = {
decode: async (source, edge): Promise<ImagePreview> => {
+ edges.push(edge)
await decoded
return { bytes: new Uint8Array(source), originalWidth: edge, originalHeight: edge }
},
@@ -333,6 +409,16 @@ describe('tiles with image previews', () => {
}
expect(result.covered).toBe(true)
expect(centerPixel(renderer)).toEqual([255, 0, 0, 255])
+ expect(edges).toEqual([256])
+
+ // Four times closer, the tiles record the chunk again with a preview for their level.
+ renderer.zoom = 4
+ renderer.imageDetailScale = 4
+ result = controller.renderFrame(renderer, canvas, graph, 1, 1)
+ for (let frame = 0; frame < 10 && result.pending; frame++) {
+ result = controller.renderFrame(renderer, canvas, graph, 1, 1)
+ }
+ expect(edges).toEqual([256, 1024])
} finally {
renderer.destroy()
}
@@ -402,6 +488,86 @@ describe('tiles with image previews', () => {
}
})
+ test('a layer added to one page child keeps the tiles of the others', () => {
+ const { graph, surface, renderer, pageId } = createGridScene()
+ const controller = new TiledSceneController({ now: () => 0 })
+ try {
+ let result = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 0)
+ for (let frame = 0; frame < 30 && (result.pending || result.backgroundPending); frame++) {
+ result = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 0)
+ }
+ expect(result.covered).toBe(true)
+ const farTile = { pageId, level: 1, x: 2, y: 1 }
+ expect(controller.isRendered(farTile)).toBe(true)
+
+ // A new layer inside the first grid square: only its tile re-renders.
+ const first = expectDefined(graph.getChildren(pageId)[0], 'first square')
+ const added = graph.createNode('RECTANGLE', first.id, {
+ x: 10,
+ y: 10,
+ width: 20,
+ height: 20,
+ fills: color(1, 0, 0)
+ })
+ controller.invalidateStructure(added.id, first.id)
+ expect(controller.hasPendingWork()).toBe(true)
+ const changed = controller.renderFrame(renderer, surface.getCanvas(), graph, 2, 0)
+ expect(controller.isRendered(farTile)).toBe(true)
+ expect(changed.metrics.interruptibleCompleted + changed.metrics.mandatoryCompleted).toBe(1)
+ expect(changed.covered).toBe(true)
+
+ // Deleting it again touches only that tile too.
+ graph.deleteNode(added.id)
+ controller.invalidateStructure(added.id, first.id)
+ const deleted = controller.renderFrame(renderer, surface.getCanvas(), graph, 3, 0)
+ expect(controller.isRendered(farTile)).toBe(true)
+ expect(deleted.metrics.interruptibleCompleted + deleted.metrics.mandatoryCompleted).toBe(1)
+ expect(deleted.covered).toBe(true)
+ } finally {
+ controller.destroy()
+ renderer.destroy()
+ }
+ })
+
+ test('a layer moved between frames leaves no ghost behind and appears where it went', () => {
+ const { graph, surface, renderer, pageId } = createGridScene()
+ const controller = new TiledSceneController({ now: () => 0 })
+ try {
+ // Two small frames, each one retained chunk, so a move must rebuild both chunks.
+ const left = graph.createNode('FRAME', pageId, { x: 0, y: 400, width: 100, height: 100 })
+ const right = graph.createNode('FRAME', pageId, { x: 200, y: 400, width: 100, height: 100 })
+ const mover = graph.createNode('RECTANGLE', left.id, {
+ x: 10,
+ y: 10,
+ width: 40,
+ height: 40,
+ fills: color(1, 0, 0)
+ })
+ let result = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 0)
+ for (let frame = 0; frame < 30 && (result.pending || result.backgroundPending); frame++) {
+ result = controller.renderFrame(renderer, surface.getCanvas(), graph, 1, 0)
+ }
+ expect(pixelAt(surface, 30, 430)).toEqual([255, 0, 0])
+ expect(pixelAt(surface, 230, 430)).toEqual([255, 255, 255])
+
+ // Moved keeping its own coordinates, so it draws at the same offset in the other frame.
+ graph.insertChildAt(mover.id, right.id, 0)
+ // The editor reports a move to its new parent and to its old one.
+ controller.invalidateStructure(mover.id, right.id)
+ controller.invalidateStructure(mover.id, left.id)
+ let moved = controller.renderFrame(renderer, surface.getCanvas(), graph, 2, 0)
+ for (let frame = 0; frame < 30 && moved.pending; frame++) {
+ moved = controller.renderFrame(renderer, surface.getCanvas(), graph, 2, 0)
+ }
+ expect(moved.covered).toBe(true)
+ expect(pixelAt(surface, 30, 430)).toEqual([255, 255, 255])
+ expect(pixelAt(surface, 230, 430)).toEqual([255, 0, 0])
+ } finally {
+ controller.destroy()
+ renderer.destroy()
+ }
+ })
+
test('builds a pyramid of downsampled levels once the visible level settles', () => {
const { graph, surface, renderer, pageId } = createGridScene()
let step = 0
diff --git a/packages/core/tests/canvas/shadows/shape.test.ts b/packages/core/tests/canvas/shadows/shape.test.ts
index 80b3589b7..5c271d797 100644
--- a/packages/core/tests/canvas/shadows/shape.test.ts
+++ b/packages/core/tests/canvas/shadows/shape.test.ts
@@ -1,14 +1,14 @@
import { afterAll, describe, expect, test } from 'bun:test'
-import { expectDefined } from '#core-tests/helpers/assert'
-import { expectFigmaRow, renderRow, type FigmaRowScene } from '#core-tests/helpers/figma-rows'
-
import { SkiaRenderer } from '@open-pencil/core/canvas'
import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
import { SceneGraph } from '@open-pencil/scene-graph'
import { isolatesInnerShadows } from '#core/canvas/shadows'
+import { expectDefined } from '#core-tests/helpers/assert'
+import { expectFigmaRow, renderRow, type FigmaRowScene } from '#core-tests/helpers/figma-rows'
+
const ck = await initCanvasKit()
const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))
afterAll(() => renderer.destroy())
@@ -62,16 +62,18 @@ describe('fills and inner shadows take a layer of their own', () => {
width: 100,
height: 100,
fills: [{ ...RED, opacity: 1 }],
- vectorNetwork: {
- vertices: [],
- segments: [],
- regions: [{ windingRule: 'NONZERO', loops: [], fills: [{ ...RED, opacity: 1, blendMode }] }]
- },
+ fillGeometry: [
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: new Uint8Array(),
+ fills: [{ ...RED, opacity: 1, blendMode }]
+ }
+ ],
effects: [SHARP_INNER_SHADOW]
})
}
- test('unless a region of a vector fills with a blend', () => {
+ test('unless a path of a vector fills with a blend', () => {
expect(isolatesInnerShadows(vector('NORMAL'))).toBe(true)
expect(isolatesInnerShadows(vector('MULTIPLY'))).toBe(false)
})
diff --git a/packages/core/tests/canvas/strokes.test.ts b/packages/core/tests/canvas/strokes.test.ts
new file mode 100644
index 000000000..18d297975
--- /dev/null
+++ b/packages/core/tests/canvas/strokes.test.ts
@@ -0,0 +1,129 @@
+import { afterAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
+import { SceneGraph, type Stroke } from '@open-pencil/scene-graph'
+
+const ck = await initCanvasKit()
+const WIDTH = 200
+const HEIGHT = 120
+
+const RED: Stroke = {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 4,
+ align: 'CENTER'
+}
+
+const DASHED: Stroke = {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ weight: 2,
+ align: 'CENTER',
+ dashPattern: [4, 4]
+}
+
+type Second = 'SECTION' | 'BOOLEAN_OPERATION' | 'ELLIPSE'
+
+/** A page with an optional dashed shape, then `second` stroked in red; returns the page's pixels. */
+function renderPage(first: 'ELLIPSE' | 'RECTANGLE' | null, second: Second, stroke = RED) {
+ const graph = new SceneGraph()
+ const page = expectDefined(graph.getPages()[0], 'page')
+ if (first) {
+ graph.createNode(first, page.id, {
+ x: 0,
+ y: 0,
+ width: 40,
+ height: 40,
+ fills: [],
+ strokes: [DASHED]
+ })
+ }
+ const placement = { x: 60, y: 10, width: 100, height: 100, fills: [], strokes: [stroke] }
+ if (second === 'BOOLEAN_OPERATION') {
+ const boolean = graph.createNode('BOOLEAN_OPERATION', page.id, {
+ ...placement,
+ booleanOperation: 'UNION'
+ })
+ graph.createNode('RECTANGLE', boolean.id, { x: 0, y: 0, width: 100, height: 100, fills: [] })
+ } else {
+ graph.createNode(second, page.id, placement)
+ }
+ const surface = expectDefined(ck.MakeSurface(WIDTH, HEIGHT), 'surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ try {
+ renderer.pageId = page.id
+ renderer.renderSceneToCanvas(surface.getCanvas(), graph, page.id)
+ surface.flush()
+ const image = surface.makeImageSnapshot()
+ const pixels = image.readPixels(0, 0, {
+ width: WIDTH,
+ height: HEIGHT,
+ colorType: ck.ColorType.RGBA_8888,
+ alphaType: ck.AlphaType.Unpremul,
+ colorSpace: ck.ColorSpace.SRGB
+ })
+ image.delete()
+ return expectDefined(pixels, 'pixels')
+ } finally {
+ renderer.destroy()
+ }
+}
+
+function count(
+ pixels: Uint8Array | Float32Array,
+ keep: (r: number, g: number, b: number) => boolean
+) {
+ let total = 0
+ for (let index = 0; index < pixels.length; index += 4) {
+ const r = pixels[index] ?? 0
+ const g = pixels[index + 1] ?? 0
+ const b = pixels[index + 2] ?? 0
+ if (keep(r, g, b)) total++
+ }
+ return total
+}
+
+const isRed = (r: number, g: number) => r > 200 && g < 60
+
+describe('stroke paint state between nodes', () => {
+ afterAll(() => undefined)
+
+ test.each<Second>(['SECTION', 'BOOLEAN_OPERATION', 'ELLIPSE'])(
+ 'a %s strokes the same after a dashed ellipse or rectangle as alone',
+ (second) => {
+ const alone = count(renderPage(null, second), isRed)
+ expect(alone).toBeGreaterThan(0)
+ expect(count(renderPage('ELLIPSE', second), isRed)).toBe(alone)
+ expect(count(renderPage('RECTANGLE', second), isRed)).toBe(alone)
+ }
+ )
+
+ test('a boolean draws its own dash and its own gradient', () => {
+ const solid = count(renderPage(null, 'BOOLEAN_OPERATION'), isRed)
+ const dashed = count(
+ renderPage(null, 'BOOLEAN_OPERATION', { ...RED, dashPattern: [8, 8] }),
+ isRed
+ )
+ expect(dashed).toBeGreaterThan(0)
+ expect(dashed).toBeLessThan(solid * 0.7)
+
+ const gradient = renderPage(null, 'BOOLEAN_OPERATION', {
+ ...RED,
+ type: 'GRADIENT_LINEAR',
+ gradientStops: [
+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },
+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ })
+ expect(count(gradient, isRed)).toBeGreaterThan(0)
+ expect(count(gradient, (r, _g, b) => b > 200 && r < 60)).toBeGreaterThan(0)
+ })
+})
diff --git a/packages/core/tests/clipboard/figma/vector-region-fills.test.ts b/packages/core/tests/clipboard/figma/vector-region-fills.test.ts
deleted file mode 100644
index bd972e698..000000000
--- a/packages/core/tests/clipboard/figma/vector-region-fills.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { beforeAll, expect, test } from 'bun:test'
-import { join } from 'node:path'
-
-import { expectDefined } from '#core-tests/helpers/assert'
-import { FIXTURES } from '#core-tests/helpers/paths'
-
-import { buildFigmaClipboardHTML, importClipboardNodes } from '@open-pencil/core/clipboard'
-import { parseFigmaClipboard } from '@open-pencil/fig/clipboard'
-import { initCodec } from '@open-pencil/kiwi/fig/codec'
-import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-
-/**
- * A vector as Figma copies it, with three regions: red of its own, the layer's grey, and an empty
- * fill list. Figma's copy writes no fill geometry, so the regions alone carry their paints.
- */
-const FIXTURE = join(FIXTURES, 'clipboard/vector-region-fills.html')
-
-async function pasted(html: string): Promise<{ graph: SceneGraph; vector: SceneNode }> {
- const parsed = expectDefined(await parseFigmaClipboard(html))
- const graph = new SceneGraph()
- importClipboardNodes(parsed.nodes, graph, graph.getPages()[0].id, 0, 0, parsed.blobs)
- const vector = expectDefined([...graph.nodes.values()].find((node) => node.type === 'VECTOR'))
- return { graph, vector }
-}
-
-const regionColors = (vector: SceneNode) =>
- vector.vectorNetwork?.regions.map((region) => region.fills?.map((fill) => fill.color))
-
-beforeAll(initCodec)
-
-test("a pasted vector keeps each region's own paints", async () => {
- const { vector } = await pasted(await Bun.file(FIXTURE).text())
- expect(regionColors(vector)).toEqual([[{ r: 1, g: 0, b: 0, a: 1 }], undefined, []])
- expect(vector.fills[0]?.color).toEqual({ r: 0.5, g: 0.5, b: 0.5, a: 1 })
-})
-
-test('region paints survive our own copy and paste', async () => {
- const { graph, vector } = await pasted(await Bun.file(FIXTURE).text())
- const html = expectDefined(await buildFigmaClipboardHTML([vector], graph))
- expect(regionColors((await pasted(html)).vector)).toEqual(regionColors(vector))
-})
diff --git a/packages/core/tests/editor/graph/events/pictures.test.ts b/packages/core/tests/editor/graph/events/pictures.test.ts
index c92e979ab..18f5ea576 100644
--- a/packages/core/tests/editor/graph/events/pictures.test.ts
+++ b/packages/core/tests/editor/graph/events/pictures.test.ts
@@ -6,8 +6,12 @@ import { createGraphEventSubscription, type GraphEventRenderer } from '#core/edi
function createRenderer() {
const invalidated: string[] = []
- const renderer: GraphEventRenderer & { invalidated: string[] } = {
- invalidateVectorPath: () => undefined,
+ const paths: string[] = []
+ const renderer: GraphEventRenderer & { invalidated: string[]; paths: string[] } = {
+ invalidateVectorPath: (nodeId: string) => {
+ paths.push(nodeId)
+ },
+ forgetNode: () => undefined,
invalidateNodePicture: (nodeId: string) => {
invalidated.push(nodeId)
},
@@ -15,7 +19,8 @@ function createRenderer() {
invalidateNode: mock(),
invalidateStructure: mock()
},
- invalidated
+ invalidated,
+ paths
}
return renderer
}
@@ -61,6 +66,26 @@ describe('graph event picture invalidation integration', () => {
expect(renderer.invalidated).toContain(node.id)
})
+ test('a change inside a boolean operation drops its cached result', () => {
+ const { graph, renderer } = setup()
+ const page = graph.getPages()[0]
+ if (!page) throw new Error('Expected default page')
+ const boolean = graph.createNode('BOOLEAN_OPERATION', page.id, { booleanOperation: 'UNION' })
+ const child = graph.createNode('RECTANGLE', boolean.id, { width: 10, height: 10 })
+
+ renderer.paths.length = 0
+ renderer.invalidated.length = 0
+ graph.updateNode(child.id, { x: 5 })
+ expect(renderer.paths).toContain(boolean.id)
+ expect(renderer.invalidated).toContain(boolean.id)
+
+ renderer.paths.length = 0
+ renderer.invalidated.length = 0
+ graph.deleteNode(child.id)
+ expect(renderer.paths).toContain(boolean.id)
+ expect(renderer.invalidated).toContain(boolean.id)
+ })
+
test('isolation changes are evaluated against live tiled chunk topology', () => {
const { graph, renderer } = setup()
const page = graph.getPages()[0]
diff --git a/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts b/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts
index 407ad4537..e5102a65f 100644
--- a/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts
+++ b/packages/core/tests/figma-api/grouping/boolean-bounds.test.ts
@@ -9,6 +9,8 @@ import { initCanvasKit } from '@open-pencil/core/io/formats/raster'
import { SceneGraph } from '@open-pencil/scene-graph'
import type { Rect } from '@open-pencil/scene-graph/primitives'
+import { makeBooleanOperationPath } from '#core/canvas/boolean'
+
// Recorded with the same script in Figma desktop 126: a boolean operation takes the box of its
// result, and an empty result keeps its operands' box. Measuring needs a renderer.
@@ -88,6 +90,21 @@ describe('boolean operation bounds', () => {
const booleanNode = editor.graph.getNode(booleanId ?? '')
expect(booleanNode && box(booleanNode)).toEqual([20, 20, 30, 30])
expect(editor.graph.getAbsolutePosition(b.id)).toEqual({ x: 20, y: 20 })
+
+ // The operation itself changing drops the renderer's kept result: the next reading is
+ // built from the new operation.
+ const resultSize = () => {
+ const node = editor.graph.getNode(booleanId ?? '')
+ const path = node && makeBooleanOperationPath(renderer, node, editor.graph)
+ const bounds = path?.getBounds()
+ path?.delete()
+ return bounds && [bounds[2] - bounds[0], bounds[3] - bounds[1]].map(Math.round)
+ }
+ expect(resultSize()).toEqual([30, 30])
+ editor.updateNode(booleanId ?? '', { booleanOperation: 'UNION' })
+ expect(resultSize()).toEqual([70, 70])
+ // And the boolean takes the box of that result, as it does when an operand moves.
+ expect(booleanNode && box(booleanNode)).toEqual([0, 0, 70, 70])
} finally {
editor.dispose()
}
diff --git a/packages/core/tests/io/formats/svg/export.test.ts b/packages/core/tests/io/formats/svg/export.test.ts
index 3f813fc80..c779a84e9 100644
--- a/packages/core/tests/io/formats/svg/export.test.ts
+++ b/packages/core/tests/io/formats/svg/export.test.ts
@@ -387,27 +387,22 @@ describe('solid paint opacity exported to SVG', () => {
expect(opaqueSVG).not.toContain('fill-opacity')
})
- test("keeps each region's own fills of a vector, translucent and opaque", () => {
+ test('keeps each geometry fill of a vector, translucent and opaque', () => {
const svg = svgOf((graph, pageId) => [
graph.createNode('VECTOR', pageId, {
width: 40,
height: 40,
- vectorNetwork: {
- vertices: [],
- segments: [],
- regions: [
- {
- windingRule: 'NONZERO',
- loops: [],
- fills: [solid(0, 0, 0, 0.5, 0.5), solid(0, 0, 1, 1, 1)]
- },
- { windingRule: 'NONZERO', loops: [], fills: [solid(1, 0, 0, 1, 0.4)] }
- ]
- },
- // Fill geometry is one outline per region.
fillGeometry: [
- { windingRule: 'NONZERO', commandsBlob: moveTo(0, 0) },
- { windingRule: 'NONZERO', commandsBlob: moveTo(10, 0) }
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: moveTo(0, 0),
+ fills: [solid(0, 0, 0, 0.5, 0.5), solid(0, 0, 1, 1, 1)]
+ },
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: moveTo(10, 0),
+ fills: [solid(1, 0, 0, 1, 0.4)]
+ }
]
}).id
])
@@ -417,67 +412,6 @@ describe('solid paint opacity exported to SVG', () => {
'<path d="M10 0" fill="#FF0000" fill-opacity="0.4"/>'
])
})
-
- test("draws a pasted vector's regions from its network when it has no fill geometry", () => {
- const zero = { x: 0, y: 0 }
- const svg = svgOf((graph, pageId) => [
- graph.createNode('VECTOR', pageId, {
- width: 10,
- height: 10,
- fills: [solid(0.5, 0.5, 0.5, 1, 1)],
- vectorNetwork: {
- vertices: [
- { x: 0, y: 0 },
- { x: 10, y: 0 },
- { x: 0, y: 10 }
- ],
- segments: [
- { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
- { start: 1, end: 2, tangentStart: zero, tangentEnd: zero },
- { start: 2, end: 0, tangentStart: zero, tangentEnd: zero }
- ],
- regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2]], fills: [solid(1, 0, 0, 1, 1)] }]
- }
- }).id
- ])
- expect(paths(svg)).toEqual(['<path d="M0 0L10 0L0 10L0 0Z" fill="#FF0000"/>'])
- })
-
- test("traces a vector's painted regions when its fill geometry has fewer outlines", () => {
- const zero = { x: 0, y: 0 }
- const svg = svgOf((graph, pageId) => [
- graph.createNode('VECTOR', pageId, {
- width: 10,
- height: 10,
- fills: [solid(0.5, 0.5, 0.5, 1, 1)],
- vectorNetwork: {
- vertices: [
- { x: 0, y: 0 },
- { x: 10, y: 0 },
- { x: 0, y: 10 },
- { x: 10, y: 10 }
- ],
- segments: [
- { start: 0, end: 1, tangentStart: zero, tangentEnd: zero },
- { start: 1, end: 2, tangentStart: zero, tangentEnd: zero },
- { start: 2, end: 0, tangentStart: zero, tangentEnd: zero },
- { start: 1, end: 3, tangentStart: zero, tangentEnd: zero },
- { start: 3, end: 2, tangentStart: zero, tangentEnd: zero }
- ],
- regions: [
- { windingRule: 'NONZERO', loops: [[0, 1, 2]], fills: [solid(1, 0, 0, 1, 1)] },
- { windingRule: 'NONZERO', loops: [[3, 4, 1]], fills: [solid(0, 0, 1, 1, 1)] }
- ]
- },
- // An import skipped the second region's empty outline.
- fillGeometry: [{ windingRule: 'NONZERO', commandsBlob: moveTo(0, 0) }]
- }).id
- ])
- expect(paths(svg)).toEqual([
- '<path d="M0 0L10 0L0 10L0 0Z" fill="#FF0000"/>',
- '<path d="M10 0L10 10L0 10L10 0Z" fill="#0000FF"/>'
- ])
- })
})
describe('FigJam shapes exported to SVG', () => {
diff --git a/packages/docs/development/renderer-lifecycle.md b/packages/docs/development/renderer-lifecycle.md
index edcfdcde7..2ca95dbe8 100644
--- a/packages/docs/development/renderer-lifecycle.md
+++ b/packages/docs/development/renderer-lifecycle.md
@@ -4,9 +4,9 @@ The CanvasKit renderer keeps hot drawing loops direct, but its retained and tile
## Navigation and settlement
-The default renderer presents a committed retained backing while navigation is active. It must not rebuild that backing during pan, zoom, momentum, or settling, because reconstruction can collide with direction reversals and block input delivery. Once navigation becomes idle, it builds exact content incrementally and atomically replaces the committed backing.
+The retained renderer presents a committed retained backing while navigation is active. It must not rebuild that backing during pan, zoom, momentum, or settling, because reconstruction can collide with direction reversals and block input delivery. Once navigation becomes idle, it builds exact content incrementally and atomically replaces the committed backing.
-The tiled renderer is opt-in and does not use the retained backing. Tiles render at the exact device scale and are presented on whole device pixels, so a settled view is never resampled. It presents cached tiles whether or not navigation is active, covers a missing tile with the cached tiles of the nearest level scaled into place, and leaves areas no level covers at the page colour until their tiles render; it never draws the whole-scene picture, which a large document cannot afford. Panning keeps rasterizing under a smaller frame budget and runs at most one tile estimated past it; a zoom whose level moves rasterizes nothing and presents the pyramid, the page copy, and the earlier levels scaled, and a zoom that pauses renders the exact level under the moving budget; a tile whose chunk pictures are not all recorded records them until the frame's budget is spent and defers the rest; queued jobs for another level or an earlier navigation generation are discarded. Idle time builds, in order, the whole page at a level where it spans four tiles, the overscan ring, a pyramid of levels each downsampled from the four cached tiles twice as fine, and a scene-rendered backdrop four times coarser around the viewport, so a hole anywhere over the page finds a scaled stand-in; a missing tile draws the nearest level that covers it fully, found past any partial levels, with up to two nearer partial levels layered on top. The tile cache's byte budget follows the viewport, five viewports of tiles between 128 MB and 768 MB, and a frame of background work that evicts a tile of its own plan's levels stops the background stages until the level or the viewport changes, so a cache too small for the plan holds what it has rather than rendering in circles. The controller reports background work separately from visible work: settlement waits only for the visible tiles, while the frame loop keeps idle frames coming until the background stages are built. A tile over nothing holds no texture. Fonts arriving redraw only the text that waited for them. Visible exact coverage while idle is the settlement boundary; overscan remains background work.
+The tiled renderer is the default and does not use the retained backing; the retained renderer stays available through the rendering preference and the `renderer=retained` URL parameter. Tiles render at the exact device scale and are presented on whole device pixels, so a settled view is never resampled. It presents cached tiles whether or not navigation is active, covers a missing tile with the cached tiles of the nearest level scaled into place, and leaves areas no level covers at the page colour until their tiles render; it never draws the whole-scene picture, which a large document cannot afford. Panning keeps rasterizing under a smaller frame budget and runs at most one tile estimated past it; a zoom whose level moves renders, under that budget, the quantized step at or above the scale, whose tiles serve until the zoom crosses the next step and then stand in for the exact level scaled by a fifth at most, over the pyramid, the page copy, and the earlier levels; a zoom that pauses renders the exact level under the moving budget; a level is presented only once every visible tile of it exists, the nearest level standing in whole until then, or the page colour when the page is first shown, so a zoom or a page open ends with the viewport appearing in one frame, while a level once presented shows the tiles a pan reveals or an edit renews as they land; the background stages wait until the content has been still for 300 ms, so an edit in progress rebuilds the visible tiles alone and the coarse copies under it once it pauses; a tile whose chunk pictures are not all recorded records them until the frame's budget is spent and defers the rest; queued jobs for another level or an earlier navigation generation are discarded. Idle time builds, in order, the whole page at a level where it spans four tiles, the overscan ring, a pyramid of levels each downsampled from the four cached tiles twice as fine, and a scene-rendered backdrop four times coarser around the viewport, so a hole anywhere over the page finds a scaled stand-in; a missing tile draws the nearest level that covers its overlap with the page fully, found past any partial levels, with up to two nearer partial levels layered on top; the page copy is kept most recently used, so it is evicted last. A tile not rendered yet is estimated from its chunk count at the per-chunk time measured for its level, or for any level until its own is known. The tile cache's byte budget follows the viewport, five viewports of tiles between 128 MB and 768 MB, and a frame of background work that evicts a tile of its own plan's levels stops the background stages until the level or the viewport changes, so a cache too small for the plan holds what it has rather than rendering in circles. A layer added, removed, moved, or changed in kind rebuilds only the chunks of the smallest subtree that held it, slotted into the draw order between their neighbours, and drops the pictures and tiles those chunks touched; the page's own children added, removed, or reordered renumber the draw order of all chunks, and only a document loaded or replaced rebuilds the index from nothing. The controller reports background work separately from visible work: settlement waits only for the visible tiles, while the frame loop keeps idle frames coming until the background stages are built. A tile over nothing holds no texture. Fonts arriving redraw only the text that waited for them. Visible exact coverage while idle is the settlement boundary; overscan remains background work.
Generation rules:
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 33cf8acfa..0da1db9a9 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -43,7 +43,8 @@ import {
import {
alignGeometryWindingRules,
resolveGeometryPaths,
- resolveVectorNetwork
+ resolveVectorNetwork,
+ resolveVectorStyleOverrideFills
} from './vector/geometry'
import { decodeVectorNetworkBlob, textPathStartSegment, type StyleOverride } from './vector/network'
@@ -679,7 +680,7 @@ function convertVectorAndStrokeProps(nc: NodeChange, blobs: Uint8Array[]) {
const strokeCap = getVectorStrokeCap(nc)
const strokeJoin = getVectorStrokeJoin(nc, vectorNetwork)
const fillGeometry = alignGeometryWindingRules(
- resolveGeometryPaths(nc.fillGeometry, blobs),
+ resolveGeometryPaths(nc.fillGeometry, blobs, resolveVectorStyleOverrideFills(nc)),
vectorNetwork
)
return {
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index c8a569e9f..cd8c65937 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -365,16 +365,22 @@ function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Arra
}
const network = node.type === 'VECTOR' ? node.vectorNetwork : null
- const {
- table: styleOverrides,
- styleToId,
- regionStyleIds
- } = network
+ const { table: styleOverrides, styleToId } = network
? buildStyleOverrideTable(network)
- : { table: [] as StyleOverride[], styleToId: undefined, regionStyleIds: [] }
+ : { table: [] as StyleOverride[], styleToId: undefined }
+ // A fill geometry entry with its own paints gets a style override of its own.
+ const fillStyleIds = node.fillGeometry.map((geometry) => {
+ if (!geometry.fills || geometry.fills.length === 0) return 0
+ const styleID = styleOverrides.length + 1
+ styleOverrides.push({ styleID, fillPaints: geometry.fills.map(fillToKiwiPaint) })
+ return styleID
+ })
const vectorData: Record<string, unknown> = {}
if (network) {
+ // fillGeometry[i] is region i's fill when the counts match (see regenerateFillGeometry), and
+ // Figma gives both the same style ID: its edit mode refills regions from the network alone.
+ const regionStyleIds = network.regions.length === fillStyleIds.length ? fillStyleIds : undefined
const blobIdx = blobs.length
blobs.push(encodeVectorNetworkBlob(network, styleToId, regionStyleIds))
vectorData.vectorNetworkBlob = blobIdx
@@ -382,12 +388,10 @@ function serializeGeometry(node: SceneNode, nc: KiwiNodeChange, blobs: Uint8Arra
}
if (node.fillGeometry.length > 0) {
- // Fill geometry is the regions' outlines, one entry each, and Figma names the same style on both.
- const regionGeometry = node.fillGeometry.length === regionStyleIds.length
nc.fillGeometry = node.fillGeometry.map((geometry, index) => {
const blobIdx = blobs.length
blobs.push(geometry.commandsBlob)
- const styleID = regionGeometry ? regionStyleIds[index] : 0
+ const styleID = fillStyleIds[index]
return {
windingRule: toKiwiWindingRule(geometry.windingRule),
commandsBlob: blobIdx,
diff --git a/packages/fig/src/node-change/vector/geometry.ts b/packages/fig/src/node-change/vector/geometry.ts
index 75ccabd99..66ef29165 100644
--- a/packages/fig/src/node-change/vector/geometry.ts
+++ b/packages/fig/src/node-change/vector/geometry.ts
@@ -1,7 +1,9 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import type { GeometryPath, VectorNetwork } from '@open-pencil/scene-graph'
+import type { Fill, GeometryPath, VectorNetwork } from '@open-pencil/scene-graph'
+import { copyFills } from '@open-pencil/scene-graph/copy'
import type { Vector } from '@open-pencil/scene-graph/primitives'
+import { convertFills } from '../paint'
import { decodeVectorNetworkBlob, type StyleOverride } from './network'
/** Scene winding rules name the even-odd case EVENODD; the archive names it ODD. */
@@ -77,12 +79,32 @@ export function resolveVectorNetwork(nc: NodeChange, blobs: Uint8Array[]): Vecto
interface KiwiPath {
windingRule?: string
commandsBlob?: number
+ styleID?: number
+}
+
+export function resolveStyleOverrideFills(
+ styleOverrideTable: StyleOverride[] | undefined
+): ReadonlyMap<number, Fill[]> {
+ const fillsByStyleId = new Map<number, Fill[]>()
+ for (const override of styleOverrideTable ?? []) {
+ if (override.fillPaints && override.fillPaints.length > 0) {
+ fillsByStyleId.set(override.styleID, convertFills(override.fillPaints))
+ }
+ }
+ return fillsByStyleId
+}
+
+export function resolveVectorStyleOverrideFills(
+ source: Pick<NodeChange, 'vectorData'>
+): ReadonlyMap<number, Fill[]> {
+ const vectorData = source.vectorData as { styleOverrideTable?: StyleOverride[] } | undefined
+ return resolveStyleOverrideFills(vectorData?.styleOverrideTable)
}
-/** Geometry outlines; a vector's per-region paints are on its network's regions. */
export function resolveGeometryPaths(
paths: KiwiPath[] | undefined,
- blobs: Uint8Array[]
+ blobs: Uint8Array[],
+ fillsByStyleId?: ReadonlyMap<number, Fill[]>
): GeometryPath[] {
if (!paths || paths.length === 0) return []
const result: GeometryPath[] = []
@@ -91,7 +113,12 @@ export function resolveGeometryPaths(
continue
const blob = blobs[p.commandsBlob]
if (blob.length === 0) continue
- result.push({ windingRule: fromKiwiWindingRule(p.windingRule), commandsBlob: blob })
+ const fills = p.styleID ? fillsByStyleId?.get(p.styleID) : undefined
+ result.push({
+ windingRule: fromKiwiWindingRule(p.windingRule),
+ commandsBlob: blob,
+ fills: fills && fills.length > 0 ? copyFills(fills) : undefined
+ })
}
return result
}
diff --git a/packages/fig/src/node-change/vector/network.ts b/packages/fig/src/node-change/vector/network.ts
index e2e7760b9..3fea880b3 100644
--- a/packages/fig/src/node-change/vector/network.ts
+++ b/packages/fig/src/node-change/vector/network.ts
@@ -8,8 +8,6 @@ import type {
WindingRule
} from '@open-pencil/scene-graph'
-import { convertFills, fillToKiwiPaint } from '../paint'
-
export interface StyleOverride {
styleID: number
handleMirroring?: string
@@ -92,10 +90,8 @@ function readVectorNetworkBlob(
const regions: VectorRegion[] = []
for (let index = 0; index < regionCount; index++) {
// The low bit is the winding rule; the rest is the region's style ID, which names its fill.
- const word = view.getUint32(offset, true)
- const windingRule: WindingRule = (word & 1) === 1 ? 'NONZERO' : 'EVENODD'
- // An entry without paints is a region filled with nothing, not one that takes the layer's.
- const paints = styles.get(word >>> 1)?.fillPaints
+ const windingRule: WindingRule =
+ (view.getUint32(offset, true) & 1) === 1 ? 'NONZERO' : 'EVENODD'
offset += 4
const loopCount = view.getUint32(offset, true)
offset += 4
@@ -110,9 +106,7 @@ function readVectorNetworkBlob(
}
loops.push(loop)
}
- const region: VectorRegion = { windingRule, loops }
- if (paints) region.fills = convertFills(paints)
- regions.push(region)
+ regions.push({ windingRule, loops })
}
return { network: { vertices, segments, regions }, segmentStyles }
@@ -127,14 +121,9 @@ function vertexStyleKey(vertex: VectorVertex): string {
].join('|')
}
-/**
- * The style overrides a network's vertices and regions name: vertex entries are shared by equal
- * styles, and each region with paints of its own gets an entry, as Figma writes them.
- */
export function buildStyleOverrideTable(network: VectorNetwork): {
table: StyleOverride[]
styleToId: Map<string, number>
- regionStyleIds: number[]
} {
const styleToId = new Map<string, number>()
const table: StyleOverride[] = []
@@ -159,12 +148,7 @@ export function buildStyleOverrideTable(network: VectorNetwork): {
table.push(entry)
nextId++
}
- const regionStyleIds = network.regions.map((region) => {
- if (!region.fills) return 0
- table.push({ styleID: nextId, fillPaints: region.fills.map(fillToKiwiPaint) })
- return nextId++
- })
- return { table, styleToId, regionStyleIds }
+ return { table, styleToId }
}
/**
diff --git a/packages/fig/src/source-metadata.ts b/packages/fig/src/source-metadata.ts
index 5b11cd6a6..18c2e2390 100644
--- a/packages/fig/src/source-metadata.ts
+++ b/packages/fig/src/source-metadata.ts
@@ -103,7 +103,11 @@ const EDITED_RAW_FIELDS: Partial<Record<string, readonly string[]>> = {
variantPropSpecs: ['variantPropSpecs']
}
+const NO_STALE_FIELDS: ReadonlySet<string> = new Set()
+
export function staleFigmaRawFields(editedFields: readonly string[] = []): ReadonlySet<string> {
+ // Read for every layer the renderer draws, so an unedited layer allocates nothing.
+ if (editedFields.length === 0) return NO_STALE_FIELDS
return new Set(editedFields.flatMap((key) => EDITED_RAW_FIELDS[key] ?? []))
}
diff --git a/packages/fig/tests/node-change/vector/region-fills.test.ts b/packages/fig/tests/node-change/vector/region-fills.test.ts
index 813d05cfe..490e674a8 100644
--- a/packages/fig/tests/node-change/vector/region-fills.test.ts
+++ b/packages/fig/tests/node-change/vector/region-fills.test.ts
@@ -1,10 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import {
- decodeVectorNetworkBlob,
- sceneNodeToKiwi,
- type StyleOverride
-} from '#fig/node-change/index'
+import { sceneNodeToKiwi } from '#fig/node-change/index'
import { SceneGraph } from '@open-pencil/scene-graph'
@@ -51,12 +47,12 @@ describe('a vector whose regions have their own colors', () => {
],
segments: [line(0, 1), line(1, 2), line(2, 0), line(1, 3), line(3, 2)],
regions: [
- { windingRule: 'NONZERO', loops: [[0, 1, 2]], fills: [solid(1)] },
+ { windingRule: 'NONZERO', loops: [[0, 1, 2]] },
{ windingRule: 'EVENODD', loops: [[3, 4, 1]] }
]
},
fillGeometry: [
- { windingRule: 'NONZERO', commandsBlob: new Uint8Array([0]) },
+ { windingRule: 'NONZERO', commandsBlob: new Uint8Array([0]), fills: [solid(1)] },
{ windingRule: 'EVENODD', commandsBlob: new Uint8Array([0]) }
]
})
@@ -74,53 +70,3 @@ describe('a vector whose regions have their own colors', () => {
expect(regionStyleIds(blobs[vectorData.vectorNetworkBlob])).toEqual([fillStyle, 0])
})
})
-
-test('a region keeps its own paints, an empty list, or none through export and import', () => {
- const graph = new SceneGraph()
- const regions = [
- { windingRule: 'NONZERO' as const, loops: [[0, 1, 2]], fills: [solid(1)] },
- { windingRule: 'NONZERO' as const, loops: [[3, 4, 1]] },
- { windingRule: 'EVENODD' as const, loops: [[5, 6, 7]], fills: [] }
- ]
- const node = graph.createNode('VECTOR', graph.getPages()[0].id, {
- width: 30,
- height: 10,
- vectorNetwork: {
- vertices: [
- { x: 0, y: 0 },
- { x: 10, y: 0 },
- { x: 10, y: 10 },
- { x: 20, y: 0 },
- { x: 20, y: 10 },
- { x: 30, y: 0 }
- ],
- segments: [
- line(0, 1),
- line(1, 2),
- line(2, 0),
- line(1, 3),
- line(3, 2),
- line(3, 5),
- line(5, 4),
- line(4, 3)
- ],
- regions
- }
- })
- const blobs: Uint8Array[] = []
- const [change] = sceneNodeToKiwi(node, ROOT_GUID, 0, { value: 100 }, graph, blobs)
- const vectorData = change.vectorData as {
- vectorNetworkBlob: number
- styleOverrideTable: StyleOverride[]
- }
- const decoded = decodeVectorNetworkBlob(
- blobs[vectorData.vectorNetworkBlob],
- vectorData.styleOverrideTable
- )
-
- expect(decoded.regions.map((region) => region.fills?.map((fill) => fill.color.r))).toEqual([
- [1],
- undefined,
- []
- ])
-})
diff --git a/packages/fig/tests/vector-style-fills.test.ts b/packages/fig/tests/vector-style-fills.test.ts
new file mode 100644
index 000000000..f02195a15
--- /dev/null
+++ b/packages/fig/tests/vector-style-fills.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ resolveGeometryPaths,
+ resolveStyleOverrideFills,
+ sceneNodeToKiwi,
+ type StyleOverride
+} from '#fig/node-change/index'
+
+import type { Paint } from '@open-pencil/kiwi/fig/codec'
+import type { Fill } from '@open-pencil/scene-graph'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
+
+function solidFill(r: number, g: number, b: number): Fill {
+ return {
+ type: 'SOLID',
+ color: { r, g, b, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+}
+
+function moveCommandsBlob(x: number, y: number): Uint8Array {
+ const blob = new Uint8Array(10)
+ const view = new DataView(blob.buffer)
+ blob[0] = 1
+ view.setFloat32(1, x, true)
+ view.setFloat32(5, y, true)
+ return blob
+}
+
+function quadraticCommandsBlob(): Uint8Array {
+ const blob = new Uint8Array(18)
+ const view = new DataView(blob.buffer)
+ blob[0] = 3
+ view.setFloat32(1, 2, true)
+ view.setFloat32(5, 3, true)
+ view.setFloat32(9, 4, true)
+ view.setFloat32(13, 5, true)
+ return blob
+}
+
+describe('vector geometry style fills', () => {
+ test('resolves per-path paints without retaining transport style IDs', () => {
+ const orange: Paint = {
+ type: 'SOLID',
+ color: { r: 1, g: 0.32, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ const fillsByStyleId = resolveStyleOverrideFills([
+ { styleID: 4, fillPaints: [orange] },
+ { styleID: 7, handleMirroring: 'ANGLE' }
+ ])
+ const paths = resolveGeometryPaths(
+ [
+ { windingRule: 'NONZERO', commandsBlob: 0, styleID: 4 },
+ { windingRule: 'NONZERO', commandsBlob: 1, styleID: 0 }
+ ],
+ [moveCommandsBlob(0, 0), moveCommandsBlob(10, 0)],
+ fillsByStyleId
+ )
+
+ expect(paths[0]?.fills?.[0]?.color).toEqual(orange.color)
+ expect(paths[1]?.fills).toBeUndefined()
+ expect(paths[0]).not.toHaveProperty('styleID')
+ })
+
+ test('generates fresh style overrides when serializing current path fills', () => {
+ const graph = new SceneGraph()
+ const vector = graph.createNode('VECTOR', graph.getPages()[0].id, {
+ name: 'Multi-color vector',
+ width: 100,
+ height: 40,
+ fills: [solidFill(0.3, 0.06, 0.52)],
+ vectorNetwork: null,
+ fillGeometry: [
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: moveCommandsBlob(0, 0),
+ fills: [solidFill(1, 0.32, 0)]
+ },
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: moveCommandsBlob(50, 0),
+ fills: [solidFill(0, 0.6, 0.9)]
+ },
+ { windingRule: 'NONZERO', commandsBlob: moveCommandsBlob(75, 0) }
+ ]
+ })
+ const blobs: Uint8Array[] = []
+ const [change] = sceneNodeToKiwi(
+ vector,
+ { sessionID: 1, localID: 1 },
+ 0,
+ { value: 2 },
+ graph,
+ blobs
+ )
+ const vectorData = change.vectorData as { styleOverrideTable?: StyleOverride[] } | undefined
+
+ expect(change.fillGeometry?.map((path) => path.styleID)).toEqual([1, 2, undefined])
+ expect(vectorData?.styleOverrideTable?.map((override) => override.styleID)).toEqual([1, 2])
+ expect(vectorData?.styleOverrideTable?.[0]?.fillPaints?.[0]?.color?.r).toBeCloseTo(1)
+ expect(vectorData?.styleOverrideTable?.[1]?.fillPaints?.[0]?.color?.b).toBeCloseTo(0.9)
+ })
+
+ test('scaling geometry preserves independent path fills', () => {
+ const source = [
+ {
+ windingRule: 'NONZERO' as const,
+ commandsBlob: moveCommandsBlob(4, 5),
+ fills: [solidFill(1, 0.32, 0)]
+ },
+ { windingRule: 'NONZERO' as const, commandsBlob: quadraticCommandsBlob() }
+ ]
+ const scaled = scaleGeometryPaths(source, 2, 3)
+ const view = new DataView(scaled[0].commandsBlob.buffer)
+ const quadraticView = new DataView(scaled[1].commandsBlob.buffer)
+
+ expect(view.getFloat32(1, true)).toBe(8)
+ expect(view.getFloat32(5, true)).toBe(15)
+ expect([
+ quadraticView.getFloat32(1, true),
+ quadraticView.getFloat32(5, true),
+ quadraticView.getFloat32(9, true),
+ quadraticView.getFloat32(13, true)
+ ]).toEqual([4, 9, 8, 15])
+ expect(scaled[0].fills?.[0]?.color.r).toBe(1)
+ if (scaled[0].fills?.[0]) scaled[0].fills[0].color.r = 0
+ expect(source[0].fills?.[0]?.color.r).toBe(1)
+ })
+})
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index ee5a18153..ad91bfaec 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -23,10 +23,9 @@ import type {
LayoutGrid,
SceneNode,
Stroke,
- StyleRun,
- VectorNetwork,
- VectorRegion
+ StyleRun
} from './types'
+import { cloneVectorNetwork } from './vector-network'
// --- Individual copy functions ---
@@ -115,32 +114,17 @@ export function copyStyleRuns(runs: StyleRun[]): StyleRun[] {
return runs.map(copyStyleRun)
}
-/** A region, with new loops when given, keeping its own paints and fill style. */
-export function copyVectorRegion(
- region: VectorRegion,
- loops = region.loops.map((loop) => [...loop])
-): VectorRegion {
- const copy: VectorRegion = { windingRule: region.windingRule, loops }
- if (region.fills) copy.fills = copyFills(region.fills)
- if (region.fillStyleId) copy.fillStyleId = region.fillStyleId
- return copy
-}
-
-/** Deep-copy a VectorNetwork, stripping any Vue Proxy wrappers. */
-export function cloneVectorNetwork(vn: VectorNetwork): VectorNetwork {
+/** Keep path-level fills across copy/scale/transform (resize snapshots). */
+function withPathPaintMeta(path: GeometryPath, commandsBlob: Uint8Array): GeometryPath {
return {
- vertices: vn.vertices.map((v) => ({ ...v })),
- segments: vn.segments.map((s) => ({
- ...s,
- tangentStart: { ...s.tangentStart },
- tangentEnd: { ...s.tangentEnd }
- })),
- regions: vn.regions.map((r) => copyVectorRegion(r))
+ windingRule: path.windingRule,
+ commandsBlob,
+ ...(path.fills ? { fills: copyFills(path.fills) } : {})
}
}
export function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {
- return paths.map((p) => ({ windingRule: p.windingRule, commandsBlob: p.commandsBlob.slice() }))
+ return paths.map((p) => withPathPaintMeta(p, p.commandsBlob.slice()))
}
/**
@@ -186,10 +170,9 @@ export function transformGeometryPaths(
tx = 0,
ty = 0
): GeometryPath[] {
- return paths.map((g) => ({
- windingRule: g.windingRule,
- commandsBlob: transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty)
- }))
+ return paths.map((g) =>
+ withPathPaintMeta(g, transformGeometryBlob(g.commandsBlob, m00, m01, m10, m11, tx, ty))
+ )
}
/**
diff --git a/packages/scene-graph/src/instances/vector-geometry.ts b/packages/scene-graph/src/instances/vector-geometry.ts
index 43c5391cc..b2469b956 100644
--- a/packages/scene-graph/src/instances/vector-geometry.ts
+++ b/packages/scene-graph/src/instances/vector-geometry.ts
@@ -1,8 +1,8 @@
import { isEqual } from 'es-toolkit/predicate'
-import { cloneVectorNetwork, copyGeometryPaths, scaleGeometryPaths } from '../copy'
+import { copyGeometryPaths, scaleGeometryPaths } from '../copy'
import type { SceneNode, VectorNetwork } from '../types'
-import { transformVectorNetwork } from '../vector-network'
+import { cloneVectorNetwork, transformVectorNetwork } from '../vector-network'
/** How far apart two paths' points may be and still count as one path, in pixels. */
const PATH_TOLERANCE = 1e-3
diff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.ts
index 077319641..975530435 100644
--- a/packages/scene-graph/src/resize.ts
+++ b/packages/scene-graph/src/resize.ts
@@ -1,5 +1,4 @@
import {
- cloneVectorNetwork,
copyDerivedGlyphs,
copyGeometryPaths,
copyStroke,
@@ -9,6 +8,7 @@ import {
import { enforcedAspectRatio } from './layout/aspect-ratio'
import type { Rect } from './primitives'
import type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'
+import { cloneVectorNetwork } from './vector-network'
/**
* Drag-start state a live resize re-scales from. Path text needs more than the
diff --git a/packages/scene-graph/src/scaling/node.ts b/packages/scene-graph/src/scaling/node.ts
index f0ce64e57..12348c5a5 100644
--- a/packages/scene-graph/src/scaling/node.ts
+++ b/packages/scene-graph/src/scaling/node.ts
@@ -1,4 +1,4 @@
-import { cloneVectorNetwork, scaleGeometryPaths } from '../copy'
+import { scaleGeometryPaths } from '../copy'
import { scaledTextLength } from '../text/lengths'
import { TEXT_PARAGRAPH_SPACING_FIELDS } from '../text/paragraphs'
import {
@@ -11,6 +11,7 @@ import {
type StyleRun,
type TextParagraphStyle
} from '../types'
+import { cloneVectorNetwork } from '../vector-network'
function scaledOptional(value: number | null, scale: number): number | null {
return value == null ? null : value * scale
diff --git a/packages/scene-graph/src/transfer/nodes.ts b/packages/scene-graph/src/transfer/nodes.ts
index badbee54c..061dfcbd3 100644
--- a/packages/scene-graph/src/transfer/nodes.ts
+++ b/packages/scene-graph/src/transfer/nodes.ts
@@ -19,9 +19,8 @@ export function semanticTransferReferences(node: SceneNode): string[] {
node.effectStyleId,
node.gridStyleId
].filter((id): id is string => !!id),
- ...(node.vectorNetwork?.regions ?? []).flatMap((region) =>
- region.fillStyleId ? [region.fillStyleId] : []
- ),
+ ...node.fillGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
+ ...node.strokeGeometry.flatMap((path) => (path.fillStyleId ? [path.fillStyleId] : [])),
...Object.entries(node.componentPropertyAssignments).flatMap(([id, value]) => [id, value]),
...node.componentPropertyReferences.map((reference) => reference.propertyId),
...node.componentPropertyDefinitions.flatMap((definition) => [
@@ -108,8 +107,9 @@ export function prepareNodeTransfer(
const endpoint = result[field]
if (endpoint?.nodeId) endpoint.nodeId = refs.nodes.get(endpoint.nodeId) ?? endpoint.nodeId
}
- for (const region of result.vectorNetwork?.regions ?? [])
- if (region.fillStyleId) region.fillStyleId = style(region.fillStyleId)
+ for (const paths of [result.fillGeometry, result.strokeGeometry]) {
+ for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId)
+ }
result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
...structuredClone(definition),
id: property(definition.id),
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 05fdb4d28..97969c9e2 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -89,10 +89,6 @@ export interface VectorSegment {
export interface VectorRegion {
windingRule: WindingRule
loops: number[][]
- /** The region's own paints. Without them it draws the layer's fills, as in Figma. */
- fills?: Fill[]
- /** The shared fill style the region's paints come from. */
- fillStyleId?: string
}
export interface VectorNetwork {
@@ -104,6 +100,10 @@ export interface VectorNetwork {
export interface GeometryPath {
windingRule: WindingRule
commandsBlob: Uint8Array
+ /** Resolved paints for geometry using a format-specific style override. */
+ fills?: Fill[]
+ /** Shared fill style attached to this geometry region, when available. */
+ fillStyleId?: string
}
export type NodeType =
diff --git a/packages/scene-graph/src/vector-network.ts b/packages/scene-graph/src/vector-network.ts
index 28f9d4cf9..707ae1404 100644
--- a/packages/scene-graph/src/vector-network.ts
+++ b/packages/scene-graph/src/vector-network.ts
@@ -1,10 +1,9 @@
import { isEqual } from 'es-toolkit/predicate'
-import { copyVectorRegion } from './copy'
import type { Mat3 } from './matrix'
import type { VectorPathWindingRule } from './parse-path'
import type { Vector } from './primitives'
-import type { Fill, GeometryPath, VectorNetwork, VectorSegment, VectorVertex } from './types'
+import type { VectorNetwork, VectorSegment, VectorVertex } from './types'
/** Concatenate vector networks while preserving independent geometry. */
export function mergeVectorNetworks(networks: readonly VectorNetwork[]): VectorNetwork {
@@ -32,7 +31,7 @@ export function mergeVectorNetworks(networks: readonly VectorNetwork[]): VectorN
for (const segmentIndex of loop) shifted.push(segmentIndex + segmentOffset)
loops.push(shifted)
}
- regions.push(copyVectorRegion(region, loops))
+ regions.push({ windingRule: region.windingRule, loops })
}
vertexOffset += network.vertices.length
segmentOffset += network.segments.length
@@ -62,31 +61,13 @@ export function transformVectorNetwork(m: Mat3, vn: VectorNetwork): VectorNetwor
tangentStart: mapVector(s.tangentStart),
tangentEnd: mapVector(s.tangentEnd)
})),
- regions: vn.regions.map((r) => copyVectorRegion(r))
+ regions: vn.regions.map((r) => ({
+ windingRule: r.windingRule,
+ loops: r.loops.map((l) => [...l])
+ }))
}
}
-/** Whether any region has paints of its own, which it draws instead of the layer's fills. */
-export function hasRegionFills(network: VectorNetwork | null): boolean {
- return network?.regions.some((region) => region.fills !== undefined) ?? false
-}
-
-/**
- * Whether fill geometry is the regions' outlines, one each, as a file or an edit writes it. A
- * pasted vector has none, and an import skips empty outlines; their regions draw traced.
- */
-export function fillGeometryMatchesRegions(
- fillGeometry: readonly GeometryPath[],
- network: VectorNetwork
-): boolean {
- return fillGeometry.length === network.regions.length
-}
-
-/** The paints regions carry of their own. */
-export function regionFills(network: VectorNetwork | null): Fill[] {
- return network?.regions.flatMap((region) => region.fills ?? []) ?? []
-}
-
/** Structural equality of two VectorNetworks (order-sensitive, exact values). */
export function vectorNetworksEqual(a: VectorNetwork, b: VectorNetwork): boolean {
return (
@@ -96,6 +77,22 @@ export function vectorNetworksEqual(a: VectorNetwork, b: VectorNetwork): boolean
)
}
+/** Deep-copy a VectorNetwork, stripping any Vue Proxy wrappers. */
+export function cloneVectorNetwork(vn: VectorNetwork): VectorNetwork {
+ return {
+ vertices: vn.vertices.map((v) => ({ ...v })),
+ segments: vn.segments.map((s) => ({
+ ...s,
+ tangentStart: { ...s.tangentStart },
+ tangentEnd: { ...s.tangentEnd }
+ })),
+ regions: vn.regions.map((r) => ({
+ windingRule: r.windingRule,
+ loops: r.loops.map((l) => [...l])
+ }))
+ }
+}
+
/**
* Validate a VectorNetwork structure, returning an array of error messages.
* Empty array means the network is valid.
diff --git a/packages/scene-graph/tests/copy.test.ts b/packages/scene-graph/tests/copy.test.ts
index 7148e1f23..77b190eea 100644
--- a/packages/scene-graph/tests/copy.test.ts
+++ b/packages/scene-graph/tests/copy.test.ts
@@ -1,20 +1,12 @@
import { describe, test, expect } from 'bun:test'
-import type {
- Fill,
- Stroke,
- Effect,
- StyleRun,
- GeometryPath,
- VectorNetwork
-} from '@open-pencil/scene-graph'
+import type { Fill, Stroke, Effect, StyleRun, GeometryPath } from '@open-pencil/scene-graph'
import {
copyFill,
copyFills,
copyStroke,
copyEffect,
copyStyleRun,
- cloneVectorNetwork,
copyGeometryPaths,
scaleGeometryPaths
} from '@open-pencil/scene-graph/copy'
@@ -107,39 +99,48 @@ describe('copy helpers — mutation isolation', () => {
expect(original.style.fontWeight).toBe(700)
})
- test('copyGeometryPaths: blobs are independent', () => {
+ test('copyGeometryPaths: blobs and path fills are independent', () => {
const original: GeometryPath[] = [
- { windingRule: 'NONZERO', commandsBlob: new Uint8Array([1, 2, 3]) }
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: new Uint8Array([1, 2, 3]),
+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ }
]
const copy = copyGeometryPaths(original)
copy[0].commandsBlob[0] = 99
+ if (copy[0].fills?.[0]) copy[0].fills[0].color.r = 0
expect(original[0].commandsBlob[0]).toBe(1)
- expect(scaleGeometryPaths(original, 0.5, 0.5)[0]?.commandsBlob).not.toBe(
- original[0]?.commandsBlob
- )
+ expect(original[0].fills?.[0]?.color.r).toBe(1)
})
- test("cloneVectorNetwork keeps each region's own paints, independent of the source", () => {
+ test('copyGeometryPaths and scaleGeometryPaths keep path-level fills', () => {
+ // Resize snapshots use these helpers; dropping fills collapses multi-color
+ // vectors to a single node fill (gray blob).
const orange: Fill = {
type: 'SOLID',
color: { r: 1, g: 0.32, b: 0, a: 1 },
opacity: 1,
visible: true
}
- const original: VectorNetwork = {
- vertices: [],
- segments: [],
- regions: [
- { windingRule: 'NONZERO', loops: [[0, 1, 2]], fills: [orange], fillStyleId: 'style:1' },
- { windingRule: 'EVENODD', loops: [[3, 4, 5]] },
- { windingRule: 'NONZERO', loops: [[6, 7, 8]], fills: [] }
- ]
- }
+ const original: GeometryPath[] = [
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: new Uint8Array([1, 0, 0, 0, 0, 0, 0, 0, 0]),
+ fills: [orange]
+ },
+ { windingRule: 'EVENODD', commandsBlob: new Uint8Array([2, 3, 4]) }
+ ]
+
+ const copied = copyGeometryPaths(original)
+ expect(copied[0]?.fills?.[0]?.color.r).toBeCloseTo(1, 2)
+ expect(copied[1]?.fills).toBeUndefined()
+ expectDefined(copied[0]?.fills?.[0], 'copied path fill').color.r = 0
+ expect(original[0]?.fills?.[0]?.color.r).toBe(1)
- const copied = cloneVectorNetwork(original)
- expect(copied.regions).toEqual(original.regions)
- expectDefined(copied.regions[0]?.fills?.[0], 'copied region fill').color.r = 0
- expect(orange.color.r).toBe(1)
+ const scaled = scaleGeometryPaths(original, 0.5, 0.5)
+ expect(scaled[0]?.fills?.[0]?.color.g).toBeCloseTo(0.32, 2)
+ expect(scaled[0]?.commandsBlob).not.toBe(original[0]?.commandsBlob)
})
test('copyFills: array independence', () => {
diff --git a/packages/vue/src/controls/stroke/helpers.ts b/packages/vue/src/controls/stroke/helpers.ts
index 0f203efce..5f5208e0d 100644
--- a/packages/vue/src/controls/stroke/helpers.ts
+++ b/packages/vue/src/controls/stroke/helpers.ts
@@ -4,7 +4,7 @@ import { computed, type ComputedRef, type Ref } from 'vue'
import type { Editor } from '@open-pencil/core'
import { BLACK } from '@open-pencil/core/constants'
import type { SceneNode, Stroke, StrokeCap, StrokeJoin } from '@open-pencil/scene-graph'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/copy'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
import { MIXED } from '#vue/controls/node-props/use'
import type { MixedValue } from '#vue/controls/node-props/use'
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index a087ee836..010087469 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -7,12 +7,7 @@ import { resizedPathTextGlyphs, type Editor } from '@open-pencil/core'
import { computeAllLayouts } from '@open-pencil/core/layout'
import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/core/text'
import type { SceneNode, DerivedTextGlyph, TextPathData } from '@open-pencil/scene-graph'
-import {
- cloneVectorNetwork,
- copyDerivedGlyphs,
- copyGeometryPaths,
- copyStrokes
-} from '@open-pencil/scene-graph/copy'
+import { copyDerivedGlyphs, copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'
import { findInstanceAncestor, recordInstanceOverride } from '@open-pencil/scene-graph/instances'
import {
cloneInstanceOverrideState,
@@ -26,6 +21,7 @@ import {
type ResizeSnapshot
} from '@open-pencil/scene-graph/resize'
import { markSourceFieldsEdited } from '@open-pencil/scene-graph/source-metadata'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
import { calculateResizeRect } from '#vue/shared/input/resize/rect'
import { draggedSizing, layerSizing } from '#vue/shared/input/resize/sizing'
diff --git a/src/app/collab/node-codec.ts b/src/app/collab/node-codec.ts
index 441769572..86b7cf1f4 100644
--- a/src/app/collab/node-codec.ts
+++ b/src/app/collab/node-codec.ts
@@ -2,6 +2,7 @@ import { isPlainObject, omit } from 'es-toolkit'
import * as v from 'valibot'
import type { Fill, GeometryPath, SceneNode, SourceMetadata } from '@open-pencil/scene-graph'
+import { copyFills } from '@open-pencil/scene-graph/copy'
import {
deserializeInstanceOverrideState,
serializeInstanceOverrideState
@@ -82,7 +83,6 @@ export function decodeNodeFromYjs(ynode: YjsNodeLike): Partial<SceneNode> {
}
if ('fillGeometry' in props) props.fillGeometry = normalizeGeometryPaths(props.fillGeometry)
if ('strokeGeometry' in props) props.strokeGeometry = normalizeGeometryPaths(props.strokeGeometry)
- if ('vectorNetwork' in props) props.vectorNetwork = normalizeRegionFills(props.vectorNetwork)
props.textPicture = null
return props
}
@@ -118,34 +118,18 @@ function normalizeGeometryPaths(value: unknown): GeometryPath[] {
const paths: GeometryPath[] = []
for (const item of value) {
if (!isPlainObject(item) || !(item.commandsBlob instanceof Uint8Array)) continue
- paths.push({
+ const path: GeometryPath = {
windingRule: item.windingRule === 'EVENODD' ? 'EVENODD' : 'NONZERO',
commandsBlob: new Uint8Array(item.commandsBlob)
- })
+ }
+ const fills = normalizeFills(item.fills)
+ if (fills.length > 0) path.fills = copyFills(fills)
+ if (typeof item.fillStyleId === 'string') path.fillStyleId = item.fillStyleId
+ paths.push(path)
}
return paths
}
-/**
- * A remote network's region paints, keeping only the ones that are valid fills. Paints that are
- * not a list are none of the region's own, so it draws the layer's rather than nothing.
- */
-function normalizeRegionFills(value: unknown): unknown {
- if (!isPlainObject(value) || !Array.isArray(value.regions)) return value
- return {
- ...value,
- regions: value.regions.map((region: unknown) => {
- if (!isPlainObject(region) || !('fills' in region)) return region
- if (!Array.isArray(region.fills)) return omit(region, ['fills'])
- return { ...region, fills: normalizeFills(region.fills) }
- })
- }
-}
-
-function normalizeFills(value: unknown): Fill[] {
- return Array.isArray(value) ? value.filter((fill): fill is Fill => v.is(fillSchema, fill)) : []
-}
-
function normalizeVector(value: unknown): Vector | null {
const result = v.safeParse(vectorSchema, value)
return result.success ? result.output : null
@@ -156,6 +140,10 @@ function normalizeMatrix(value: unknown): Matrix | null {
return result.success ? result.output : null
}
+function normalizeFills(value: unknown): Fill[] {
+ return Array.isArray(value) ? value.filter((fill): fill is Fill => v.is(fillSchema, fill)) : []
+}
+
function arrayOrEmpty(value: unknown): unknown[] {
return Array.isArray(value) ? structuredClone(value) : []
}
diff --git a/src/app/editor/fonts/status.ts b/src/app/editor/fonts/status.ts
index e7007d82d..69cca49c5 100644
--- a/src/app/editor/fonts/status.ts
+++ b/src/app/editor/fonts/status.ts
@@ -1,7 +1,7 @@
import { computed, ref } from 'vue'
import { computeAllLayouts } from '@open-pencil/core/layout'
-import { documentFontStatus, fontManager, fontResolver } from '@open-pencil/core/text'
+import { DocumentFontUses, fontManager, fontResolver } from '@open-pencil/core/text'
import { useEditorEvent } from '@open-pencil/vue/editor/events'
import { useEditorStore } from '@/app/editor/active-store'
@@ -12,22 +12,39 @@ export function useDocumentFontStatus() {
const revision = ref(0)
const retrying = ref(false)
+ // The page's text faces, kept by layer: a keystroke updates one layer rather than walking
+ // a page of tens of thousands of layers again.
+ let uses = new DocumentFontUses(editor.graph, editor.state.currentPageId)
+
const refresh = () => {
revision.value++
}
+ const rebuild = () => {
+ uses = new DocumentFontUses(editor.graph, editor.state.currentPageId)
+ refresh()
+ }
+ const updateNode = (nodeId: string) => {
+ uses.update(nodeId)
+ refresh()
+ }
useEditorEvent('font:resolution-changed', refresh)
// Fonts a paste or script loads reach no resolver, so their arrival refreshes the status too.
useEditorEvent('font:loaded', refresh)
- useEditorEvent('graph:replaced', refresh)
- useEditorEvent('page:changed', refresh)
- useEditorEvent('node:created', refresh)
- useEditorEvent('node:updated', refresh)
- useEditorEvent('node:deleted', refresh)
+ useEditorEvent('graph:replaced', rebuild)
+ useEditorEvent('page:changed', rebuild)
+ useEditorEvent('node:created', (node) => updateNode(node.id))
+ useEditorEvent('node:updated', updateNode)
+ useEditorEvent('node:reparented', updateNode)
+ useEditorEvent('node:reordered', updateNode)
+ useEditorEvent('node:deleted', (nodeId) => {
+ uses.remove(nodeId)
+ refresh()
+ })
const status = computed(() => {
void revision.value
- return documentFontStatus(editor.graph, editor.state.currentPageId)
+ return uses.status()
})
async function retry() {
diff --git a/src/app/editor/pen/resume.ts b/src/app/editor/pen/resume.ts
index 710a62fb5..5b7480102 100644
--- a/src/app/editor/pen/resume.ts
+++ b/src/app/editor/pen/resume.ts
@@ -5,8 +5,8 @@ import type {
VectorSegment,
VectorVertex
} from '@open-pencil/scene-graph'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/copy'
import type { Vector } from '@open-pencil/scene-graph/primitives'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
export type PenState = EditorState
type PenStateInit = NonNullable<EditorState['penState']>
diff --git a/src/app/editor/vector/history.ts b/src/app/editor/vector/history.ts
index 7a594ed69..6f0da19bd 100644
--- a/src/app/editor/vector/history.ts
+++ b/src/app/editor/vector/history.ts
@@ -1,7 +1,6 @@
import type { Editor } from '@open-pencil/core'
import type { VectorNetwork } from '@open-pencil/scene-graph'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/copy'
-import { vectorNetworksEqual } from '@open-pencil/scene-graph/vector-network'
+import { cloneVectorNetwork, vectorNetworksEqual } from '@open-pencil/scene-graph/vector-network'
import type { NodeEditState, VectorEditState } from './types'
diff --git a/src/app/editor/vector/lifecycle.ts b/src/app/editor/vector/lifecycle.ts
index c732e5c73..3578a004e 100644
--- a/src/app/editor/vector/lifecycle.ts
+++ b/src/app/editor/vector/lifecycle.ts
@@ -1,9 +1,9 @@
import type { Editor } from '@open-pencil/core'
import { vectorChangesFromPagePath } from '@open-pencil/core/vector'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
-import { cloneVectorNetwork } from '@open-pencil/scene-graph/copy'
import { slotScope } from '@open-pencil/scene-graph/slots'
import {
+ cloneVectorNetwork,
transformVectorNetwork,
vectorNetworksEqual
} from '@open-pencil/scene-graph/vector-network'
diff --git a/src/app/runtime/config.ts b/src/app/runtime/config.ts
index 5be9fca60..6dc163efb 100644
--- a/src/app/runtime/config.ts
+++ b/src/app/runtime/config.ts
@@ -18,7 +18,7 @@ export interface AppRuntimeConfig {
export function parseAppRuntimeConfig(
search: string,
- preferredRenderer: SceneRendererMode = 'retained'
+ preferredRenderer: SceneRendererMode = 'tiled'
): AppRuntimeConfig {
const params = new URLSearchParams(search)
const renderer = params.get('renderer')
diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.ts
index 680b116cc..f7edf835a 100644
--- a/src/app/settings/preferences/store.ts
+++ b/src/app/settings/preferences/store.ts
@@ -129,7 +129,7 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {
snapping: { ...DEFAULT_SNAPPING_PREFERENCES }
},
navigation: { zoomSpeed: 1 },
- rendering: { canvasMode: 'retained' },
+ rendering: { canvasMode: 'tiled' },
designCheck: { showOnCanvas: true, preset: 'recommended', disabledRules: [] },
comments: {
showOnCanvas: true,
diff --git a/tests/e2e/canvas/frame-creation-preview.spec.ts b/tests/e2e/canvas/frame-creation-preview.spec.ts
index a92ca2a39..bd9ee3576 100644
--- a/tests/e2e/canvas/frame-creation-preview.spec.ts
+++ b/tests/e2e/canvas/frame-creation-preview.spec.ts
@@ -45,6 +45,8 @@ async function probeCreation(page: Page) {
if (!store || !element) throw new Error('Editor unavailable')
const renderer = store.canvasRenderers.find((r) => r.tracksSceneSettlement)
if (!renderer) throw new Error('Scene renderer unavailable')
+ // The retained renderer keeps its backing through the gesture; tiles keep their coverage.
+ const tiled = renderer.tiledSceneEnabled
const backing = renderer.sceneBacking
let committed = 0
let pointerId: number | undefined
@@ -65,8 +67,8 @@ async function probeCreation(page: Page) {
version: store.state.sceneVersion,
committed,
interactive: store.isInteractiveEditing(),
- hasBacking: backing !== null,
- sameBacking: renderer.sceneBacking === backing,
+ hasBacking: tiled ? renderer.tiledSceneCovered : backing !== null,
+ sameBacking: tiled ? renderer.tiledSceneCovered : renderer.sceneBacking === backing,
batching: store.undo.isBatching
}
},
diff --git a/tests/e2e/canvas/saved-glyph-visual.spec.ts b/tests/e2e/canvas/saved-glyph-visual.spec.ts
index 7d31ec8fb..92927cb09 100644
--- a/tests/e2e/canvas/saved-glyph-visual.spec.ts
+++ b/tests/e2e/canvas/saved-glyph-visual.spec.ts
@@ -251,6 +251,8 @@ test('typed emoji take a 1 em square and draw their image', async () => {
})
store.requestRender()
})
+ await editor.page.evaluate(() => window.openPencil?.test?.navigation?.waitForSettlement())
+ // Without the settlement hook the wait above returns at once: give the render its frames.
await editor.page.evaluate(
() =>
new Promise<void>((resolve) => {
diff --git a/tests/e2e/canvas/vector/editing.spec.ts b/tests/e2e/canvas/vector/editing.spec.ts
index 0b7d8c1f7..9ba1beeb5 100644
--- a/tests/e2e/canvas/vector/editing.spec.ts
+++ b/tests/e2e/canvas/vector/editing.spec.ts
@@ -61,7 +61,7 @@ test('vector edit overlay follows nested transforms and live path fills', async
fills: [blue],
fillGeometry: [
{ windingRule: 'NONZERO', commandsBlob: rectBlob(0, 0, 100, 100) },
- { windingRule: 'NONZERO', commandsBlob: rectBlob(100, 0, 100, 100) }
+ { windingRule: 'NONZERO', commandsBlob: rectBlob(100, 0, 100, 100), fills: [orange] }
],
vectorNetwork: {
vertices: [
@@ -86,7 +86,7 @@ test('vector edit overlay follows nested transforms and live path fills', async
],
regions: [
{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] },
- { windingRule: 'NONZERO', loops: [[4, 5, 6, 7]], fills: [orange] }
+ { windingRule: 'NONZERO', loops: [[4, 5, 6, 7]] }
]
}
})
diff --git a/tests/e2e/canvas/vector/style-fills.spec.ts b/tests/e2e/canvas/vector/style-fills.spec.ts
index de5e12ecb..38554a927 100644
--- a/tests/e2e/canvas/vector/style-fills.spec.ts
+++ b/tests/e2e/canvas/vector/style-fills.spec.ts
@@ -40,49 +40,20 @@ test('vector paths render their resolved style fills', async () => {
visible: true
}
],
- // Two rectangles side by side; the right one is orange of its own.
- vectorNetwork: {
- vertices: [
- { x: 0, y: 0 },
- { x: 260, y: 0 },
- { x: 260, y: 140 },
- { x: 0, y: 140 },
- { x: 440, y: 0 },
- { x: 440, y: 140 }
- ],
- segments: [
- [0, 1],
- [1, 2],
- [2, 3],
- [3, 0],
- [1, 4],
- [4, 5],
- [5, 2]
- ].map(([start, end]) => ({
- start,
- end,
- tangentStart: { x: 0, y: 0 },
- tangentEnd: { x: 0, y: 0 }
- })),
- regions: [
- { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] },
- {
- windingRule: 'NONZERO',
- loops: [[4, 5, 6, 1]],
- fills: [
- {
- type: 'SOLID',
- color: { r: 1, g: 0.32, b: 0, a: 1 },
- opacity: 1,
- visible: true
- }
- ]
- }
- ]
- },
fillGeometry: [
{ windingRule: 'NONZERO', commandsBlob: rectangleBlob(0, 0, 260, 140) },
- { windingRule: 'NONZERO', commandsBlob: rectangleBlob(260, 0, 180, 140) }
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: rectangleBlob(260, 0, 180, 140),
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0.32, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ }
]
})
diff --git a/tests/e2e/settings/general.spec.ts b/tests/e2e/settings/general.spec.ts
index 27e49aa75..cd9ff82ee 100644
--- a/tests/e2e/settings/general.spec.ts
+++ b/tests/e2e/settings/general.spec.ts
@@ -79,7 +79,8 @@ test('progressive tiled rendering preference persists and URL overrides take pre
await page.getByTestId('app-settings-trigger').click()
await page.getByTestId('settings-section-editor').click()
const tiled = page.getByRole('switch', { name: 'Progressive rendering' })
- await expect(tiled).not.toBeChecked()
+ // Progressive rendering is the default; switching it off selects the retained renderer.
+ await expect(tiled).toBeChecked()
await tiled.click()
await expect(page.getByText('Reload OpenPencil to apply this change.')).toBeVisible()
@@ -87,22 +88,21 @@ test('progressive tiled rendering preference persists and URL overrides take pre
await canvas.waitForInit()
await page.getByTestId('app-settings-trigger').click()
await page.getByTestId('settings-section-editor').click()
- await expect(tiled).toBeChecked()
+ await expect(tiled).not.toBeChecked()
await expect(
page.evaluate(() =>
- window.openPencil
- ?.getStore?.()
- .canvasRenderers.some(
- (renderer) => renderer.tracksSceneSettlement && renderer.tiledSceneEnabled
- )
+ window.openPencil?.getStore?.().canvasRenderers.map((renderer) => ({
+ scene: renderer.tracksSceneSettlement,
+ tiled: renderer.tiledSceneEnabled
+ }))
)
- ).resolves.toBe(true)
+ ).resolves.toEqual(expect.arrayContaining([{ scene: true, tiled: false }]))
- await page.goto('/?test&renderer=retained')
+ await page.goto('/?test&renderer=tiled')
await canvas.waitForInit()
await page.getByTestId('app-settings-trigger').click()
await page.getByTestId('settings-section-editor').click()
- await expect(tiled).toBeChecked()
+ await expect(tiled).not.toBeChecked()
await expect(
page.getByText(/current session renderer is controlled by a URL override/i)
).toBeVisible()
@@ -110,8 +110,8 @@ test('progressive tiled rendering preference persists and URL overrides take pre
page.evaluate(() =>
window.openPencil
?.getStore?.()
- .canvasRenderers.every(
- (renderer) => !renderer.tracksSceneSettlement || !renderer.tiledSceneEnabled
+ .canvasRenderers.some(
+ (renderer) => renderer.tracksSceneSettlement && renderer.tiledSceneEnabled
)
)
).resolves.toBe(true)
diff --git a/tests/engine/app/runtime/config.test.ts b/tests/engine/app/runtime/config.test.ts
index ed951cec4..f74d9ebe3 100644
--- a/tests/engine/app/runtime/config.test.ts
+++ b/tests/engine/app/runtime/config.test.ts
@@ -38,7 +38,7 @@ describe('app runtime configuration', () => {
recentFiles: false,
showChrome: true,
showRulers: true,
- sceneRenderer: 'retained',
+ sceneRenderer: 'tiled',
sceneRendererOverride: false,
collaborationTransport: 'default',
collaborationRelayURL: null
diff --git a/tests/engine/app/vector-edit-transforms.test.ts b/tests/engine/app/vector-edit-transforms.test.ts
index 7998d074d..115875ce6 100644
--- a/tests/engine/app/vector-edit-transforms.test.ts
+++ b/tests/engine/app/vector-edit-transforms.test.ts
@@ -114,7 +114,19 @@ describe('vector edit graph ownership', () => {
const editor = createEditor()
const page = expectDefined(editor.graph.getPages()[0])
const fillGeometry = regenerateFillGeometry(NETWORK, [
- { windingRule: 'NONZERO', commandsBlob: new Uint8Array() }
+ {
+ windingRule: 'NONZERO',
+ commandsBlob: new Uint8Array(),
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0.4, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ blendMode: 'NORMAL'
+ }
+ ]
+ }
])
const vector = editor.graph.createNode('VECTOR', page.id, {
width: 100,
diff --git a/tests/engine/collab/yjs-sync.test.ts b/tests/engine/collab/yjs-sync.test.ts
index e04384ffe..8689f0833 100644
--- a/tests/engine/collab/yjs-sync.test.ts
+++ b/tests/engine/collab/yjs-sync.test.ts
@@ -4,7 +4,7 @@ import { create as createPRNG } from 'lib0/prng'
import * as Y from 'yjs'
import { TestConnector, type TestYInstance } from 'yjs/testHelper'
-import type { Fill, GeometryPath, SceneNode, VectorNetwork } from '@open-pencil/scene-graph'
+import type { Fill, GeometryPath, SceneNode } from '@open-pencil/scene-graph'
import { SceneGraph } from '@open-pencil/scene-graph'
import { nodeVisualBounds } from '@open-pencil/scene-graph/geometry'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
@@ -89,63 +89,52 @@ describe('collab yjs-sync', () => {
doc.getMap<Y.Map<unknown>>('nodes').set('remote', ynode)
ynode.set('source', { format: 'fig', fig: { rawNodeFields: 'invalid' } })
ynode.set('fillGeometry', [
- { windingRule: 'EVENODD', commandsBlob: new Uint8Array([0]) },
+ {
+ windingRule: 'EVENODD',
+ commandsBlob: new Uint8Array([0]),
+ fills: [
+ null,
+ 'invalid',
+ {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ gradientStops: 'invalid'
+ },
+ {
+ type: 'NOISE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ noiseSize: 'invalid'
+ },
+ {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 0.8,
+ visible: true,
+ gradientStops: [
+ { color: { r: 1, g: 0, b: 0, a: 1 }, position: 0 },
+ { color: { r: 0, g: 0, b: 1, a: 1 }, position: 1 }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ },
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true
+ }
+ ]
+ },
{ windingRule: 'NONZERO', commandsBlob: 'invalid' }
])
- ynode.set('vectorNetwork', {
- vertices: [],
- segments: [],
- regions: [
- {
- windingRule: 'EVENODD',
- loops: [],
- fills: [
- null,
- 'invalid',
- {
- type: 'GRADIENT_LINEAR',
- color: { r: 0, g: 0, b: 0, a: 1 },
- opacity: 1,
- visible: true,
- gradientStops: 'invalid'
- },
- {
- type: 'NOISE',
- color: { r: 0, g: 0, b: 0, a: 1 },
- opacity: 1,
- visible: true,
- noiseSize: 'invalid'
- },
- {
- type: 'GRADIENT_LINEAR',
- color: { r: 0, g: 0, b: 0, a: 1 },
- opacity: 0.8,
- visible: true,
- gradientStops: [
- { color: { r: 1, g: 0, b: 0, a: 1 }, position: 0 },
- { color: { r: 0, g: 0, b: 1, a: 1 }, position: 1 }
- ],
- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- },
- {
- type: 'SOLID',
- color: { r: 1, g: 0, b: 0, a: 1 },
- opacity: 1,
- visible: true
- }
- ]
- },
- // Paints that are not a list leave the region drawing the layer's fills.
- { windingRule: 'NONZERO', loops: [], fills: null }
- ]
- })
ynode.set('strokeGeometry', 'invalid')
const props = decodeNodeFromYjs(ynode)
const source = props.source as SceneNode['source']
const fillGeometry = props.fillGeometry as GeometryPath[]
- const regions = (props.vectorNetwork as VectorNetwork).regions
- const fills = regions[0]?.fills
expect(source).toEqual({
...createDefaultSourceMetadata(),
@@ -153,8 +142,8 @@ describe('collab yjs-sync', () => {
})
expect(fillGeometry).toHaveLength(1)
expect(fillGeometry[0]?.commandsBlob).toBeInstanceOf(Uint8Array)
- expect(fills).toHaveLength(2)
- expect(fills?.[0]).toMatchObject({
+ expect(fillGeometry[0]?.fills).toHaveLength(2)
+ expect(fillGeometry[0]?.fills?.[0]).toMatchObject({
type: 'GRADIENT_LINEAR',
opacity: 0.8,
gradientStops: [
@@ -163,8 +152,7 @@ describe('collab yjs-sync', () => {
],
gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
})
- expect(fills?.[1]?.type).toBe('SOLID')
- expect(regions[1]).not.toHaveProperty('fills')
+ expect(fillGeometry[0]?.fills?.[1]?.type).toBe('SOLID')
expect(props.strokeGeometry).toEqual([])
})
diff --git a/tests/engine/render/canvas/arrow-heads-draw.test.ts b/tests/engine/render/canvas/arrow-heads-draw.test.ts
index d53eeed12..fbfd05100 100644
--- a/tests/engine/render/canvas/arrow-heads-draw.test.ts
+++ b/tests/engine/render/canvas/arrow-heads-draw.test.ts
@@ -48,11 +48,13 @@ function createHarness() {
},
fillPaint: {
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setAlphaf: mock(() => undefined),
setShader: mock(() => undefined)
},
strokePaint: {
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setStrokeWidth: mock(() => undefined),
setAlphaf: mock(() => undefined),
setStrokeCap: mock(() => undefined),
@@ -105,7 +107,7 @@ describe('drawArrowHeads', () => {
expect(corners[0][1]).toBeCloseTo(5 - 10 / SQRT3, 5)
expect(corners[1][0]).toBeCloseTo(0, 5)
expect(corners[1][1]).toBeCloseTo(5 + 10 / SQRT3, 5)
- expect(harness.renderer.fillPaint.setColor).toHaveBeenCalledWith(['color', 0.1, 0.2, 0.3, 1])
+ expect(harness.renderer.fillPaint.setColorComponents).toHaveBeenCalledWith(0.1, 0.2, 0.3, 1)
expect(harness.renderer.fillPaint.setAlphaf).toHaveBeenCalledWith(0.8)
expect(harness.drawPath).toHaveBeenCalledWith(harness.detached, harness.renderer.fillPaint)
expect(harness.detached.delete).toHaveBeenCalled()
diff --git a/tests/engine/render/canvas/boolean.test.ts b/tests/engine/render/canvas/boolean.test.ts
index 9cdb38f64..ca5b94f96 100644
--- a/tests/engine/render/canvas/boolean.test.ts
+++ b/tests/engine/render/canvas/boolean.test.ts
@@ -17,6 +17,7 @@ async function createRenderer(): Promise<SkiaRenderer> {
const ck = await initCanvasKit()
const renderer = {
ck,
+ nodePaths: new NodePathCaches(),
makeNodeShapePath(node) {
return makeNodeShapePath(asRenderer(this), node)
},
@@ -31,8 +32,7 @@ async function createRenderer(): Promise<SkiaRenderer> {
},
getFillGeometry() {
return null
- },
- nodePaths: new NodePathCaches()
+ }
} satisfies Partial<SkiaRenderer>
return asRenderer(renderer)
}
diff --git a/tests/engine/render/canvas/chunks/index.test.ts b/tests/engine/render/canvas/chunks/index.test.ts
index a91c8d3da..6d59fff46 100644
--- a/tests/engine/render/canvas/chunks/index.test.ts
+++ b/tests/engine/render/canvas/chunks/index.test.ts
@@ -81,6 +81,141 @@ describe('render chunk spatial index', () => {
}
})
+ test('composes translated square clips into one box and keeps shaped clips by ancestor', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ if (!page) throw new Error('Expected default page')
+ const outer = graph.createNode('FRAME', page.id, {
+ x: 10,
+ y: 10,
+ width: 100,
+ height: 100,
+ clipsContent: true
+ })
+ const inner = graph.createNode('FRAME', outer.id, {
+ x: 20,
+ y: 20,
+ width: 100,
+ height: 100,
+ clipsContent: true
+ })
+ // Enough layers that both frames split, so the leaves carry the clips of both ancestors.
+ for (let index = 0; index < 40; index++) {
+ graph.createNode('RECTANGLE', inner.id, { x: index, y: 0, width: 10, height: 10 })
+ }
+ const leafId = graph.getChildren(inner.id)[0]?.id ?? ''
+ const built = RenderChunkIndex.build(graph, page.id)
+ try {
+ const leaf = built.index.getChunksForNode(leafId)[0]
+ expect(leaf?.context.clipRect).toEqual({ minX: 30, minY: 30, maxX: 110, maxY: 110 })
+ expect(leaf?.context.ancestorClipIds).toEqual([])
+ } finally {
+ built.index.dispose()
+ }
+
+ graph.updateNode(inner.id, { rotation: 45 })
+ const rotated = RenderChunkIndex.build(graph, page.id)
+ try {
+ const leaf = rotated.index.getChunksForNode(leafId)[0]
+ expect(leaf?.context.clipRect).toEqual({ minX: 10, minY: 10, maxX: 110, maxY: 110 })
+ expect(leaf?.context.ancestorClipIds).toEqual([inner.id])
+ } finally {
+ rotated.index.dispose()
+ }
+ })
+
+ test('rebuilds one page child at a time and keeps the draw order of the others', () => {
+ const { graph, pageId } = graphWithNodes(40)
+ const first = graph.getChildren(pageId)[0]
+ if (!first) throw new Error('Expected a page child')
+ const second = graph.createNode('RECTANGLE', pageId, { x: 0, y: 100, width: 10, height: 10 })
+ const { index } = RenderChunkIndex.build(graph, pageId)
+ try {
+ const before = index.size()
+ expect(index.hasTop(first.id)).toBe(true)
+ const added = graph.createNode('RECTANGLE', first.id, { x: 900, y: 0, width: 10, height: 10 })
+ const { removed, added: rebuilt } = index.rebuildTop(graph, pageId, first.id)
+ expect(removed.length).toBe(before - 1)
+ expect(rebuilt.length).toBe(before)
+ expect(index.size()).toBe(before + 1)
+ expect(index.getChunksForNode(added.id)).toHaveLength(1)
+ expect(index.getChunksDependingOnNode(first.id).length).toBe(before)
+ // The second page child still draws after everything in the first.
+ const secondChunk = index.getChunksForNode(second.id)[0]
+ for (const chunk of rebuilt)
+ expect(chunk.painterOrder).toBeLessThan(secondChunk?.painterOrder ?? 0)
+
+ // Moving the second child first renumbers both subtrees.
+ graph.insertChildAt(second.id, pageId, 0)
+ index.renumber(graph, pageId)
+ const front = index.getChunksForNode(second.id)[0]
+ for (const chunk of index.getChunksDependingOnNode(first.id)) {
+ expect(chunk.painterOrder).toBeGreaterThan(front?.painterOrder ?? Infinity)
+ }
+
+ graph.deleteNode(second.id)
+ const gone = index.rebuildTop(graph, pageId, second.id)
+ expect(gone.added).toEqual([])
+ expect(index.hasTop(second.id)).toBe(false)
+ } finally {
+ index.dispose()
+ }
+ })
+
+ test('rebuilds only the child subtree on the way to a layer added under a split frame', () => {
+ const { graph, pageId } = graphWithNodes(40)
+ const frame = graph.getChildren(pageId)[0]
+ if (!frame) throw new Error('Expected a page child')
+ const siblings = graph.getChildren(frame.id)
+ const { index } = RenderChunkIndex.build(graph, pageId)
+ try {
+ const before = index.size()
+ const untouched = index.getChunksForNode(siblings[5]?.id ?? '')[0]
+ const added = graph.createNode('RECTANGLE', frame.id, { x: 500, y: 0, width: 10, height: 10 })
+ const rebuilt = index.rebuildFrom(graph, pageId, added.id)
+ expect(rebuilt?.removed).toEqual([])
+ expect(rebuilt?.added.map((chunk) => chunk.nodeId)).toEqual([added.id])
+ expect(index.size()).toBe(before + 1)
+ // Untouched siblings keep their chunks and draw before the layer appended after them.
+ expect(index.getChunksForNode(siblings[5]?.id ?? '')[0]).toBe(untouched)
+ const last = index.getChunksForNode(siblings[39]?.id ?? '')[0]
+ const addedChunk = index.getChunksForNode(added.id)[0]
+ expect(addedChunk?.painterOrder).toBeGreaterThan(last?.painterOrder ?? Infinity)
+ expect(
+ index.search({ minX: 500, minY: 0, maxX: 510, maxY: 10 }).map((c) => c.nodeId)
+ ).toContain(added.id)
+
+ graph.deleteNode(added.id)
+ const gone = index.rebuildFrom(graph, pageId, added.id)
+ expect(gone).toBeNull()
+ const fromParent = index.rebuildFrom(graph, pageId, frame.id)
+ expect(fromParent?.removed.map((chunk) => chunk.nodeId)).toContain(added.id)
+ } finally {
+ index.dispose()
+ }
+ })
+
+ test('numbers a split frame afresh once inserted layers exhaust the order between two', () => {
+ const { graph, pageId } = graphWithNodes(40)
+ const frame = graph.getChildren(pageId)[0]
+ if (!frame) throw new Error('Expected the frame')
+ const { index } = RenderChunkIndex.build(graph, pageId)
+ // Each layer lands between the first and the one before it: the same gap, halved each time.
+ for (let count = 0; count < 60; count++) {
+ const added = graph.createNode('RECTANGLE', frame.id, { x: 5, y: 5, width: 2, height: 2 })
+ graph.insertChildAt(added.id, frame.id, 1)
+ const changed = index.rebuildFrom(graph, pageId, added.id)
+ if (!changed) throw new Error('Expected a rebuild')
+ }
+ const orders = index
+ .search({ minX: -1e9, minY: -1e9, maxX: 1e9, maxY: 1e9 })
+ .filter((chunk) => chunk.nodeId !== frame.id)
+ .map((chunk) => chunk.painterOrder)
+ expect(orders.every((order, at) => at === 0 || order > (orders[at - 1] ?? -1))).toBe(true)
+ expect(orders).toHaveLength(100)
+ index.dispose()
+ })
+
test('keeps a small top-level subtree as one retained chunk', () => {
const { graph, pageId } = graphWithNodes(20)
const { index, stats } = RenderChunkIndex.build(graph, pageId)
diff --git a/tests/engine/render/canvas/chunks/record.test.ts b/tests/engine/render/canvas/chunks/record.test.ts
index 532978c46..9fdde9db1 100644
--- a/tests/engine/render/canvas/chunks/record.test.ts
+++ b/tests/engine/render/canvas/chunks/record.test.ts
@@ -5,11 +5,7 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas'
import type { RenderChunk } from '#core/canvas/renderer/chunks'
-import {
- deleteRecordedRenderChunks,
- recordRenderChunk,
- RenderChunkIndex
-} from '#core/canvas/renderer/chunks'
+import { recordRenderChunk, RenderChunkIndex } from '#core/canvas/renderer/chunks'
import { expectDefined } from '#tests/helpers/assert'
@@ -32,7 +28,7 @@ function renderPixels(renderer: SkiaRenderer, graph: SceneGraph, pageId: string,
const picture = recorded.find((entry) => entry.chunk.id === chunk.id)?.picture
if (picture) canvas.drawPicture(picture)
}
- deleteRecordedRenderChunks(recorded)
+ for (const entry of recorded) entry.picture.delete()
index.dispose()
} else {
renderer.renderSceneToCanvas(canvas, graph, pageId)
@@ -103,9 +99,15 @@ describe('recorded render chunks', () => {
id: `${node.id}:subtree`,
nodeId: node.id,
kind: 'subtree',
- context: { parentTransform: [1, 0, 0, 0, 1, 0, 0, 0, 1], ancestorClipIds: [] },
+ context: {
+ parentTransform: [1, 0, 0, 0, 1, 0, 0, 0, 1],
+ clipRect: null,
+ ancestorClipIds: []
+ },
interruptible: true,
painterOrder: 0,
+ topId: node.id,
+ localOrder: 0,
minX: 0,
minY: 0,
maxX: 10,
diff --git a/tests/engine/render/canvas/component-label-text.test.ts b/tests/engine/render/canvas/component-label-text.test.ts
deleted file mode 100644
index 92ec69c16..000000000
--- a/tests/engine/render/canvas/component-label-text.test.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import { ellipsizeLabelText } from '#core/canvas/labels/text'
-
-import { asDouble } from './helpers'
-
-const fixedWidthFont = asDouble<Parameters<typeof ellipsizeLabelText>[0]>({
- getGlyphIDs(text: string) {
- return [...text].map((_, index) => index)
- },
- getGlyphWidths(glyphs: number[]) {
- return glyphs.map(() => 10)
- }
-})
-
-describe('label text', () => {
- test('keeps labels that fit inside the component width', () => {
- expect(ellipsizeLabelText(fixedWidthFont, 'Button', 60)).toBe('Button')
- })
-
- test('ellipsizes labels that exceed the component width', () => {
- expect(ellipsizeLabelText(fixedWidthFont, 'Very long component', 55)).toBe('Very…')
- })
-
- test('returns only ellipsis when only the ellipsis fits', () => {
- expect(ellipsizeLabelText(fixedWidthFont, 'Component', 10)).toBe('…')
- })
-})
diff --git a/tests/engine/render/canvas/effects/helpers.ts b/tests/engine/render/canvas/effects/helpers.ts
index 31a1bc066..b863ff400 100644
--- a/tests/engine/render/canvas/effects/helpers.ts
+++ b/tests/engine/render/canvas/effects/helpers.ts
@@ -89,6 +89,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
setImageFilter = mock(() => undefined)
setAntiAlias = mock(() => undefined)
setColor = mock(() => undefined)
+ setColorComponents = mock(() => undefined)
setShader = mock(() => undefined)
setStyle = mock(() => undefined)
delete = mock(() => undefined)
@@ -100,6 +101,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
},
auxFill: {
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setMaskFilter: mock(() => undefined),
setImageFilter: mock(() => undefined),
setAlphaf: mock(() => undefined),
@@ -110,6 +112,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
auxStroke: {
setStrokeWidth: mock(() => undefined),
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setPathEffect: mock(() => undefined),
setAlphaf: mock(() => undefined),
setBlendMode: mock(() => undefined),
@@ -117,6 +120,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
},
fillPaint: {
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setAlphaf: mock(() => undefined),
setShader: mock(() => undefined),
getColor: mock(() => new Float32Array([0, 0, 0, 1])),
@@ -125,6 +129,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
},
strokePaint: {
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setShader: mock(() => undefined),
setStrokeWidth: mock(() => undefined),
setAlphaf: mock(() => undefined),
@@ -142,6 +147,7 @@ export function createMockRenderer(overrides: Partial<SkiaRenderer> = {}): SkiaR
},
effectLayerPaint: {
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setMaskFilter: mock(() => undefined),
setImageFilter: mock(() => undefined),
setColorFilter: mock(() => undefined),
diff --git a/tests/engine/render/canvas/picture-invalidation.test.ts b/tests/engine/render/canvas/picture-invalidation.test.ts
index 60dba68f6..0924efbda 100644
--- a/tests/engine/render/canvas/picture-invalidation.test.ts
+++ b/tests/engine/render/canvas/picture-invalidation.test.ts
@@ -19,6 +19,7 @@ test('full picture invalidation resets tiled font-dependent resources', () => {
textPreparationCache.clear = mock()
const renderer = asRenderer({
textPreparationCache,
+ textReadiness: new Map(),
scenePicture,
scenePictureVersion: 1,
scenePictureFontGeneration: 1,
@@ -52,6 +53,7 @@ test('node picture invalidation removes the changed node picture and keeps its p
textPreparationCache.deleteNode = mock()
const renderer = asRenderer({
textPreparationCache,
+ textReadiness: new Map(),
nodePictureCache: new Map([
['parent', parentPicture],
['child', childPicture]
diff --git a/tests/engine/render/canvas/renderer-lifecycle.test.ts b/tests/engine/render/canvas/renderer-lifecycle.test.ts
index cc5690cdb..0836b9cc3 100644
--- a/tests/engine/render/canvas/renderer-lifecycle.test.ts
+++ b/tests/engine/render/canvas/renderer-lifecycle.test.ts
@@ -2,8 +2,11 @@ import { expect, mock, test } from 'bun:test'
import type { Font, Paint, Surface } from 'canvaskit-wasm'
+import { createImageFilterCache, createMaskFilterCache } from '#core/canvas/effects'
import { createImageCache } from '#core/canvas/images/cache'
import { ImagePreviewCache } from '#core/canvas/images/previews'
+import type { NodeEditPaints } from '#core/canvas/node-edit-overlay'
+import { createDashEffectCache } from '#core/canvas/overlays/outline'
import { NodePathCaches } from '#core/canvas/paths/cache'
import type { SkiaRenderer } from '#core/canvas/renderer'
import { EffectRasterCache } from '#core/canvas/renderer/effect-raster-cache'
@@ -34,7 +37,6 @@ function createRenderer() {
fillPaint: deletable<Paint>(),
strokePaint: deletable<Paint>(),
selectionPaint: deletable<Paint>(),
- parentOutlinePaint: deletable<Paint>(),
snapPaint: deletable<Paint>(),
auxFill: deletable<Paint>(),
auxStroke: deletable<Paint>(),
@@ -45,7 +47,6 @@ function createRenderer() {
sizeFont: deletable<Font>(),
sectionTitleFont: deletable<Font>(),
componentLabelFont: deletable<Font>(),
- fontMgr: null,
fontProvider: null,
fontsLoaded: true,
rulerBgPaint: deletable<Paint>(),
@@ -60,8 +61,13 @@ function createRenderer() {
penHandlePaint: deletable<Paint>(),
penVertexFill: deletable<Paint>(),
penVertexStroke: deletable<Paint>(),
- imageFilterCache: new Map(),
- maskFilterCache: new Map(),
+ imageFilterCache: createImageFilterCache(),
+ dashEffects: createDashEffectCache(),
+ pixelGridShader: null,
+ maskFilterCache: createMaskFilterCache(),
+ nodeEditPaints: {
+ techStrokePaint: deletable<Paint>()
+ } as Partial<NodeEditPaints> as NodeEditPaints,
nodePictureCache: new Map(),
effectRasterCache: new EffectRasterCache(),
subtreePictureCache: new Map(),
@@ -70,7 +76,6 @@ function createRenderer() {
sceneBackingBuild: null,
tiledScene: asDouble<SkiaRenderer['tiledScene']>({ destroy: mock() }),
labelParagraphCache: asDouble<SkiaRenderer['labelParagraphCache']>({ clear: mock() }),
- _flashPaint: null,
profiler: { destroy: mock() } as Partial<SkiaRenderer['profiler']> as SkiaRenderer['profiler'],
surface: deletable<Surface>()
}
@@ -95,14 +100,12 @@ test('destroyRenderer releases tiled resources before deleting the main surface'
test('destroyRenderer deletes all renderer-owned paints and label fonts', () => {
const renderer = createRenderer()
- const parentOutlinePaint = renderer.parentOutlinePaint
const sectionTitleFont = renderer.sectionTitleFont
const componentLabelFont = renderer.componentLabelFont
const pencilStrokePaint = renderer.pencilStrokePaint
destroyRenderer(renderer)
- expect(parentOutlinePaint.delete).toHaveBeenCalled()
expect(pencilStrokePaint.delete).toHaveBeenCalled()
expect(sectionTitleFont?.delete).toHaveBeenCalled()
expect(componentLabelFont?.delete).toHaveBeenCalled()
diff --git a/tests/engine/render/canvas/schema-fill-fallback.test.ts b/tests/engine/render/canvas/schema-fill-fallback.test.ts
index 35a58be31..99f5cea9d 100644
--- a/tests/engine/render/canvas/schema-fill-fallback.test.ts
+++ b/tests/engine/render/canvas/schema-fill-fallback.test.ts
@@ -31,6 +31,7 @@ function createRenderer() {
fillPaint: {
setShader: mock(() => undefined),
setColor: mock(() => undefined),
+ setColorComponents: mock(() => undefined),
setAlphaf: mock(() => undefined),
setBlendMode: mock(() => undefined)
},
@@ -80,7 +81,7 @@ describe('schema fill fallback rendering', () => {
expect(renderer.fillPaint.setShader).toHaveBeenLastCalledWith(
expect.objectContaining({ id: 'pattern-shader' })
)
- expect(renderer.fillPaint.setColor).not.toHaveBeenCalledWith(['color', 0.2, 0.3, 0.4, 0.8])
+ expect(renderer.fillPaint.setColorComponents).not.toHaveBeenCalledWith(0.2, 0.3, 0.4, 0.8)
})
test.each(['PATTERN', 'NOISE', 'CUSTOM'] as const)(
@@ -95,7 +96,7 @@ describe('schema fill fallback rendering', () => {
}
expect(applyFill(renderer, fill, node, new SceneGraph())).toBe(true)
- expect(renderer.fillPaint.setColor).toHaveBeenCalledWith(['color', 0.2, 0.3, 0.4, 0.8])
+ expect(renderer.fillPaint.setColorComponents).toHaveBeenCalledWith(0.2, 0.3, 0.4, 0.8)
}
)
})
diff --git a/tests/engine/text/fonts/status.test.ts b/tests/engine/text/fonts/status.test.ts
index 8f2e8aa96..f89780eb3 100644
--- a/tests/engine/text/fonts/status.test.ts
+++ b/tests/engine/text/fonts/status.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, test } from 'bun:test'
-import { FontManager, documentFontStatus, UnsupportedFontFormatError } from '@open-pencil/core/text'
+import {
+ DocumentFontUses,
+ FontManager,
+ documentFontStatus,
+ UnsupportedFontFormatError
+} from '@open-pencil/core/text'
import { SceneGraph } from '@open-pencil/scene-graph'
function pageId(graph: SceneGraph): string {
@@ -210,3 +215,69 @@ describe('documentFontStatus', () => {
})
})
})
+
+describe('DocumentFontUses', () => {
+ test('follows a layer edited, added, moved off the page, and deleted', async () => {
+ const graph = new SceneGraph()
+ const manager = new FontManager()
+ await manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')
+ await manager.markLoaded('Example Sans', 'Regular', new ArrayBuffer(8), 'local')
+ const page = pageId(graph)
+ const title = graph.createNode('TEXT', page, {
+ name: 'Title',
+ text: 'Hello',
+ fontFamily: 'Inter',
+ fontWeight: 400
+ })
+ const uses = new DocumentFontUses(graph, page)
+ const families = () => uses.status(manager).faces.map((face) => face.family)
+ expect(families()).toEqual(['Inter'])
+
+ graph.updateNode(title.id, { fontFamily: 'Example Sans' })
+ uses.update(title.id)
+ expect(families()).toEqual(['Example Sans'])
+
+ const frame = graph.createNode('FRAME', page, { name: 'Frame' })
+ const caption = graph.createNode('TEXT', frame.id, {
+ name: 'Caption',
+ text: 'Hi',
+ fontFamily: 'Inter',
+ fontWeight: 400
+ })
+ uses.update(caption.id)
+ expect(families()).toEqual(['Example Sans', 'Inter'])
+
+ const otherPage = graph.addPage('Other')
+ graph.reparentNode(caption.id, otherPage.id)
+ uses.update(caption.id)
+ expect(families()).toEqual(['Example Sans'])
+
+ graph.deleteNode(title.id)
+ uses.remove(title.id)
+ expect(families()).toEqual([])
+
+ // A frame moved off the page takes the text it holds with it, reported as the frame.
+ graph.reparentNode(frame.id, otherPage.id)
+ graph.createNode('TEXT', frame.id, { text: 'Hi', fontFamily: 'Inter', fontWeight: 400 })
+ uses.update(frame.id)
+ expect(families()).toEqual([])
+ graph.reparentNode(frame.id, page)
+ uses.update(frame.id)
+ expect(families()).toEqual(['Inter'])
+ })
+
+ test('skips the text under an ancestor that was deleted', async () => {
+ const graph = new SceneGraph()
+ const manager = new FontManager()
+ await manager.markLoaded('Inter', 'Regular', new ArrayBuffer(8), 'bundled')
+ const page = pageId(graph)
+ const frame = graph.createNode('FRAME', page, { name: 'Frame' })
+ graph.createNode('TEXT', frame.id, { text: 'Hi', fontFamily: 'Inter', fontWeight: 400 })
+ const uses = new DocumentFontUses(graph, page)
+ expect(uses.status(manager).faces).toHaveLength(1)
+
+ graph.deleteNode(frame.id)
+ uses.remove(frame.id)
+ expect(uses.status(manager).faces).toEqual([])
+ })
+})
diff --git a/tests/engine/vector/fill-geometry-regen.test.ts b/tests/engine/vector/fill-geometry-regen.test.ts
index 944d7f1a3..10f7fa110 100644
--- a/tests/engine/vector/fill-geometry-regen.test.ts
+++ b/tests/engine/vector/fill-geometry-regen.test.ts
@@ -46,12 +46,25 @@ function decode(blob: Uint8Array): string[] {
return out
}
-const ENTRY: GeometryPath = { windingRule: 'NONZERO', commandsBlob: new Uint8Array([9, 9, 9]) }
+const ENTRY: GeometryPath = {
+ windingRule: 'NONZERO',
+ commandsBlob: new Uint8Array([9, 9, 9]),
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
+}
describe('regenerateFillGeometry', () => {
- test('rebuilds one outline per region, in region order', () => {
+ test('rebuilds region blobs positionally, preserving fills', () => {
const network = square()
const [g] = regenerateFillGeometry(network, [ENTRY])
+ expect(g.fills).toEqual(ENTRY.fills)
expect(g.windingRule).toBe('EVENODD') // taken from the region
expect(decode(g.commandsBlob)).toEqual(['M 0,0', 'L 10,0', 'L 10,10', 'L 0,10', 'L 0,0', 'Z'])
})
@@ -70,10 +83,18 @@ describe('regenerateFillGeometry', () => {
expect(decode(g.commandsBlob)[1]).toBe('C 10,0')
})
- test('rebuilds one outline per region however many entries it had', () => {
- const out = regenerateFillGeometry(square(), [ENTRY, { ...ENTRY }])
+ test('region/entry count mismatch rebuilds without stale styles', () => {
+ const network = square()
+ // Two style entries but only one region — mapping is unknown, so rebuild
+ // one path per region and drop the mismatched style metadata.
+ const out = regenerateFillGeometry(network, [ENTRY, { ...ENTRY }])
expect(out).toHaveLength(1)
- expect(decode(out[0].commandsBlob)).toEqual([
+ const path = out[0]
+ expect(path).toBeDefined()
+ if (!path) return
+ expect(path.fills).toBeUndefined()
+ expect(path.commandsBlob).not.toBe(ENTRY.commandsBlob)
+ expect(decode(path.commandsBlob)).toEqual([
'M 0,0',
'L 10,0',
'L 10,10',
diff --git a/tests/engine/vue/input/resize/geometry.test.ts b/tests/engine/vue/input/resize/geometry.test.ts
index e16666d75..a8db3e10d 100644
--- a/tests/engine/vue/input/resize/geometry.test.ts
+++ b/tests/engine/vue/input/resize/geometry.test.ts
@@ -2,8 +2,9 @@ import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
import type { Fill, GeometryPath, SceneNode, Stroke, VectorNetwork } from '@open-pencil/scene-graph'
-import { cloneVectorNetwork, copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'
+import { copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'
import { collectResizeDescendants } from '@open-pencil/scene-graph/resize'
+import { cloneVectorNetwork } from '@open-pencil/scene-graph/vector-network'
import { applyResize, commitResizePreview } from '#vue/shared/input/resize'
import type { DragResize } from '#vue/shared/input/types'
@@ -18,8 +19,6 @@ const RED: Fill = {
blendMode: 'NORMAL'
}
-const BLUE: Fill = { ...RED, color: { r: 0, g: 0, b: 1, a: 1 } }
-
const NETWORK: VectorNetwork = {
vertices: [
{ x: 0, y: 0 },
@@ -33,16 +32,9 @@ const NETWORK: VectorNetwork = {
{ start: 2, end: 3, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },
{ start: 3, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }
],
- // Two regions with paints of their own, so a resize that drops or swaps one shows.
- regions: [
- { windingRule: 'NONZERO', loops: [[0, 1, 2, 3]], fills: [RED] },
- { windingRule: 'EVENODD', loops: [[0, 1, 2, 3]], fills: [BLUE] }
- ]
+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1, 2, 3]] }]
}
-/** One fill outline per region. */
-const FILL_GEOMETRY = [movePath(10, 10), movePath(0, 10)]
-
const STROKE: Stroke = {
type: 'SOLID',
color: { r: 0, g: 0, b: 0, a: 1 },
@@ -55,13 +47,13 @@ const STROKE: Stroke = {
dashPattern: []
}
-function movePath(x: number, y: number): GeometryPath {
+function movePath(x: number, y: number, fills?: Fill[]): GeometryPath {
const commandsBlob = new Uint8Array(9)
const view = new DataView(commandsBlob.buffer)
commandsBlob[0] = 1
view.setFloat32(1, x, true)
view.setFloat32(5, y, true)
- return { windingRule: 'NONZERO', commandsBlob }
+ return { windingRule: 'NONZERO', commandsBlob, fills }
}
function pathPoint(path: GeometryPath | undefined) {
@@ -111,13 +103,10 @@ function expectGeometry(node: SceneNode, size: number) {
expect(node.width).toBe(size)
expect(node.height).toBe(size)
expect(node.vectorNetwork?.vertices[2]).toMatchObject({ x: size, y: size })
- expect(node.fillGeometry.map(pathPoint)).toEqual([
- [size, size],
- [0, size]
- ])
+ expect(pathPoint(node.fillGeometry[0])).toEqual([size, size])
if (size === 10) expect(pathPoint(node.strokeGeometry[0])).toEqual([5, 5])
else expect(node.strokeGeometry).toEqual([])
- expect(node.vectorNetwork?.regions.map((region) => region.fills)).toEqual([[RED], [BLUE]])
+ expect(node.fillGeometry[0]?.fills?.[0]?.color.r).toBe(1)
}
describe('vector resize geometry', () => {
@@ -128,7 +117,7 @@ describe('vector resize geometry', () => {
width: 10,
height: 10,
vectorNetwork: cloneVectorNetwork(NETWORK),
- fillGeometry: copyGeometryPaths(FILL_GEOMETRY),
+ fillGeometry: [movePath(10, 10, [RED])],
strokeGeometry: [movePath(5, 5)]
})
const drag = dragFor(vector)
@@ -152,7 +141,7 @@ describe('vector resize geometry', () => {
width: 10,
height: 10,
vectorNetwork: cloneVectorNetwork(NETWORK),
- fillGeometry: copyGeometryPaths(FILL_GEOMETRY),
+ fillGeometry: [movePath(10, 10, [RED])],
strokeGeometry: [movePath(5, 5)]
})
const descendants = collectResizeDescendants(editor.graph, group.id)
diff --git a/tests/fixtures/clipboard/vector-region-fills.html b/tests/fixtures/clipboard/vector-region-fills.html
deleted file mode 100644
index feb279caa..000000000
--- a/tests/fixtures/clipboard/vector-region-fills.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<meta charset="utf-8" /><span
- data-metadata="<!--(figmeta)eyJmaWxlS2V5IjoiczU0d0VVa1Z3cnlsYkpwYU9iT2YzOSIsInBhc3RlSUQiOjUwNzU5Nzk1MSwiZGF0YVR5cGUiOiJzY2VuZSIsImVkaXRvclR5cGUiOiJkZXNpZ24iLCJlbnZpcm9ubWVudCI6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XXGx8bOWIcwKP2gAmUF6MNhIRp7V/WDWFtd3FqxEOCki4QWjAmMAA93nogyYgEiaLlCeGBkZWJBJqhaUNCR2TGp61ur+YJIQo=(/figma)-->"
-></span
-><span style="white-space: pre-wrap"></span>
diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txt
index 521ea86e5..838b463da 100644
--- a/tools/checks/test-homes/engine-baseline.txt
+++ b/tools/checks/test-homes/engine-baseline.txt
@@ -301,7 +301,6 @@ tests/engine/render/canvas/chunks/context.test.ts
tests/engine/render/canvas/chunks/gold-preview.test.ts
tests/engine/render/canvas/chunks/index.test.ts
tests/engine/render/canvas/chunks/record.test.ts
-tests/engine/render/canvas/component-label-text.test.ts
tests/engine/render/canvas/corner-smoothing.test.ts
tests/engine/render/canvas/culling.test.ts
tests/engine/render/canvas/derived-text.test.ts