AI-native design editor. Open-source Figma alternative.
Shadow rendering performance: per-node SkPicture cache (#25)
Danila Poyarkova9a1f9ac1fa0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7ac316391..2342187c6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,9 @@### Performance+- Per-node SkPicture cache for effect rendering — unchanged shadow/blur nodes replay from cache on scene redraws+- Drop shadows use `MaskFilter` direct draw instead of `saveLayer` offscreen buffers+- Cached `ImageFilter`, `MaskFilter`, reusable effect paint — zero per-frame WASM allocations for effects- Optimize zoom/pan smoothness with `shallowReactive`, `useRafFn`, and input coalescing### Builddiff --git a/packages/core/src/renderer.ts b/packages/core/src/renderer.tsindex fd39b5a5e..1644ce9ca 100644--- a/packages/core/src/renderer.ts+++ b/packages/core/src/renderer.ts@@ -76,7 +76,8 @@ import type {FontWeight,TypefaceFontProvider,SkPicture,- ImageFilter+ ImageFilter,+ MaskFilter} from 'canvaskit-wasm'export interface RenderOverlays {@@ -128,6 +129,9 @@ export class SkiaRenderer {private opacityPaint: Paintprivate effectLayerPaint: Paintprivate imageFilterCache = new Map<string, ImageFilter>()+ private maskFilterCache = new Map<number, MaskFilter>()+ private _tmpColor = new Float32Array(4)+ private _tmpRect = new Float32Array(4)private textFont: Font | null = nullprivate labelFont: Font | null = nullprivate sizeFont: Font | null = null@@ -141,6 +145,7 @@ export class SkiaRenderer {private scenePicture: SkPicture | null = nullprivate scenePictureVersion = -1private scenePicturePageId: string | null = null+ private nodePictureCache = new Map<string, SkPicture>()private rulerBgPaint: Paintprivate rulerTickPaint: Paint@@ -165,6 +170,24 @@ export class SkiaRenderer {private worldViewport = { x: 0, y: 0, w: 0, h: 0 }+ private color4f(r: number, g: number, b: number, a: number): Float32Array {+ const c = this._tmpColor+ c[0] = r+ c[1] = g+ c[2] = b+ c[3] = a+ return c+ }++ private ltrb(l: number, t: number, r: number, b: number): Float32Array {+ const rc = this._tmpRect+ rc[0] = l+ rc[1] = t+ rc[2] = r+ rc[3] = b+ return rc+ }+private selColor(alpha = 1) {return this.ck.Color4f(SELECTION_COLOR.r, SELECTION_COLOR.g, SELECTION_COLOR.b, alpha)}@@ -302,7 +325,7 @@ export class SkiaRenderer {}this.fontsLoaded = true- this.invalidateScenePicture()+ this.invalidateAllPictures()}invalidateScenePicture(): void {@@ -311,6 +334,20 @@ export class SkiaRenderer {this.scenePictureVersion = -1}+ invalidateAllPictures(): void {+ this.invalidateScenePicture()+ for (const pic of this.nodePictureCache.values()) pic.delete()+ this.nodePictureCache.clear()+ }++ invalidateNodePicture(nodeId: string): void {+ const pic = this.nodePictureCache.get(nodeId)+ if (pic) {+ pic.delete()+ this.nodePictureCache.delete(nodeId)+ }+ }+hitTestSectionTitle(graph: SceneGraph, canvasX: number, canvasY: number): SceneNode | null {if (!this.sectionTitleFont) return null@@ -1360,6 +1397,43 @@ export class SkiaRenderer {}private renderShape(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {+ const hasEffects = node.effects.length > 0 && node.effects.some((e) => e.visible)++ if (hasEffects) {+ const cached = this.nodePictureCache.get(node.id)+ if (cached) {+ canvas.drawPicture(cached)+ return+ }++ const margin = this.effectOverflow(node)+ const bounds = this.ck.LTRBRect(-margin, -margin, node.width + margin, node.height + margin)+ const recorder = new this.ck.PictureRecorder()+ const recCanvas = recorder.beginRecording(bounds)+ this.renderShapeUncached(recCanvas, node, graph)+ const picture = recorder.finishRecordingAsPicture()+ recorder.delete()+ this.nodePictureCache.set(node.id, picture)+ canvas.drawPicture(picture)+ } else {+ this.renderShapeUncached(canvas, node, graph)+ }+ }++ private effectOverflow(node: SceneNode): number {+ let expand = 0+ for (const e of node.effects) {+ if (!e.visible) continue+ const blur = e.radius+ const spread = e.spread+ const ox = Math.abs(e.offset.x)+ const oy = Math.abs(e.offset.y)+ expand = Math.max(expand, blur + spread + ox, blur + spread + oy)+ }+ return expand+ }++ private renderShapeUncached(canvas: Canvas, node: SceneNode, graph: SceneGraph): void {const rect = this.ck.LTRBRect(0, 0, node.width, node.height)const hasRadius =@@ -1582,6 +1656,15 @@ export class SkiaRenderer {return filter}+ private getCachedMaskBlur(sigma: number): MaskFilter {+ let filter = this.maskFilterCache.get(sigma)+ if (!filter) {+ filter = this.ck.MaskFilter.MakeBlur(this.ck.BlurStyle.Normal, sigma, true)+ this.maskFilterCache.set(sigma, filter)+ }+ return filter+ }+private applyClippedBlur(canvas: Canvas,node: SceneNode,@@ -1712,40 +1795,42 @@ export class SkiaRenderer {if (pass === 'behind' && effect.type === 'DROP_SHADOW') {const sp = effect.spread- const shadowColor = this.ck.Color4f(- effect.color.r,- effect.color.g,- effect.color.b,- effect.color.a- )const sigma = effect.radius / 2- const dropFilter = this.getCachedDropShadow(- effect.offset.x,- effect.offset.y,- sigma,- shadowColor- )- this.effectLayerPaint.setImageFilter(dropFilter)-if (node.type === 'TEXT') {+ const shadowColor = this.ck.Color4f(+ effect.color.r,+ effect.color.g,+ effect.color.b,+ effect.color.a+ )+ const dropFilter = this.getCachedDropShadow(+ effect.offset.x,+ effect.offset.y,+ sigma,+ shadowColor+ )+ this.effectLayerPaint.setImageFilter(dropFilter)canvas.saveLayer(this.effectLayerPaint)this.renderText(canvas, node)canvas.restore()} else {- canvas.saveLayer(this.effectLayerPaint)- this.auxFill.setColor(this.ck.WHITE)+ this.auxFill.setColor(+ this.color4f(effect.color.r, effect.color.g, effect.color.b, effect.color.a)+ )+ this.auxFill.setMaskFilter(this.getCachedMaskBlur(sigma))this.auxFill.setImageFilter(null)+ canvas.save()+ canvas.translate(effect.offset.x, effect.offset.y)if (node.type === 'ELLIPSE') {- const spreadRect = this.ck.LTRBRect(-sp, -sp, node.width + sp, node.height + sp)- canvas.drawOval(spreadRect, this.auxFill)+ canvas.drawOval(this.ltrb(-sp, -sp, node.width + sp, node.height + sp), this.auxFill)} else if (hasRadius) {canvas.drawRRect(this.makeRRectWithSpread(node, sp), this.auxFill)} else {- const spreadRect = this.ck.LTRBRect(-sp, -sp, node.width + sp, node.height + sp)- canvas.drawRect(spreadRect, this.auxFill)+ canvas.drawRect(this.ltrb(-sp, -sp, node.width + sp, node.height + sp), this.auxFill)}canvas.restore()+ this.auxFill.setMaskFilter(null)}}@@ -2634,6 +2719,10 @@ export class SkiaRenderer {this.effectLayerPaint.delete()for (const filter of this.imageFilterCache.values()) filter.delete()this.imageFilterCache.clear()+ for (const filter of this.maskFilterCache.values()) filter.delete()+ this.maskFilterCache.clear()+ for (const pic of this.nodePictureCache.values()) pic.delete()+ this.nodePictureCache.clear()this.scenePicture?.delete()this.surface.delete()}diff --git a/src/demo.ts b/src/demo.tsindex 4ccc6213b..a99f12e7f 100644--- a/src/demo.ts+++ b/src/demo.ts@@ -1,6 +1,6 @@import { computeAllLayouts } from './engine/layout'-import type { Color, Fill, GradientStop } from './engine/scene-graph'+import type { Color, Effect, Fill, GradientStop } from './engine/scene-graph'import type { EditorStore } from './stores/editor'const WHITE: Color = { r: 1, g: 1, b: 1, a: 1 }@@ -703,6 +703,271 @@ export function createDemoShapes(store: EditorStore) {})}+ // ─── Section: Effects Showcase ──────────────────────────────────+ const effectsSectionId = store.createShape('SECTION', 60, 840, 920, 480)+ graph.updateNode(effectsSectionId, {+ name: 'Effects',+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]+ })++ function dropShadow(+ ox = 0,+ oy = 4,+ radius = 8,+ spread = 0,+ color: Color = { r: 0, g: 0, b: 0, a: 0.25 }+ ): Effect {+ return {+ type: 'DROP_SHADOW',+ color,+ offset: { x: ox, y: oy },+ radius,+ spread,+ visible: true+ }+ }++ function innerShadow(+ ox = 0,+ oy = 2,+ radius = 4,+ spread = 0,+ color: Color = { r: 0, g: 0, b: 0, a: 0.2 }+ ): Effect {+ return {+ type: 'INNER_SHADOW',+ color,+ offset: { x: ox, y: oy },+ radius,+ spread,+ visible: true+ }+ }++ function blurEffect(type: Effect['type'], radius: number): Effect {+ return {+ type,+ color: { r: 0, g: 0, b: 0, a: 0 },+ offset: { x: 0, y: 0 },+ radius,+ spread: 0,+ visible: true+ }+ }++ // Row 1: Drop shadows+ const shadowLabel = store.createShape('TEXT', 32, 48, 200, 20, effectsSectionId)+ graph.updateNode(shadowLabel, {+ name: 'Label',+ text: 'Drop Shadow',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })++ const shadowCard1 = store.createShape('FRAME', 32, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard1, {+ name: 'Subtle Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 2, 8, 0, { r: 0, g: 0, b: 0, a: 0.08 })]+ })+ const s1Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard1)+ graph.updateNode(s1Text, {+ name: 'Label',+ text: 'Subtle',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const shadowCard2 = store.createShape('FRAME', 220, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard2, {+ name: 'Medium Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 4, 16, 0, { r: 0, g: 0, b: 0, a: 0.15 })]+ })+ const s2Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard2)+ graph.updateNode(s2Text, {+ name: 'Label',+ text: 'Medium',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const shadowCard3 = store.createShape('FRAME', 408, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard3, {+ name: 'Heavy Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 8, 24, 0, { r: 0, g: 0, b: 0, a: 0.2 })]+ })+ const s3Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard3)+ graph.updateNode(s3Text, {+ name: 'Label',+ text: 'Heavy',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const shadowCard4 = store.createShape('FRAME', 596, 76, 160, 100, effectsSectionId)+ graph.updateNode(shadowCard4, {+ name: 'Spread Shadow',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [dropShadow(0, 4, 12, 8, { r: 0.23, g: 0.51, b: 0.96, a: 0.3 })]+ })+ const s4Text = store.createShape('TEXT', 16, 40, 128, 20, shadowCard4)+ graph.updateNode(s4Text, {+ name: 'Label',+ text: 'With Spread',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(BLUE)]+ })++ // Row 2: Inner shadows+ const innerLabel = store.createShape('TEXT', 32, 208, 200, 20, effectsSectionId)+ graph.updateNode(innerLabel, {+ name: 'Label',+ text: 'Inner Shadow',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })++ const innerCard1 = store.createShape('FRAME', 32, 236, 160, 100, effectsSectionId)+ graph.updateNode(innerCard1, {+ name: 'Inset Light',+ cornerRadius: 12,+ fills: [solid(GRAY_100)],+ effects: [innerShadow(0, 2, 6, 0, { r: 0, g: 0, b: 0, a: 0.12 })]+ })+ const i1Text = store.createShape('TEXT', 16, 40, 128, 20, innerCard1)+ graph.updateNode(i1Text, {+ name: 'Label',+ text: 'Inset',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ const innerCard2 = store.createShape('FRAME', 220, 236, 160, 100, effectsSectionId)+ graph.updateNode(innerCard2, {+ name: 'Inset with Spread',+ cornerRadius: 12,+ fills: [solid(GRAY_100)],+ effects: [innerShadow(0, 2, 8, 4, { r: 0, g: 0, b: 0, a: 0.15 })]+ })+ const i2Text = store.createShape('TEXT', 16, 40, 128, 20, innerCard2)+ graph.updateNode(i2Text, {+ name: 'Label',+ text: 'Inset + Spread',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ // Ellipse with inner shadow+ const innerEllipse = store.createShape('ELLIPSE', 408, 236, 100, 100, effectsSectionId)+ graph.updateNode(innerEllipse, {+ name: 'Inset Circle',+ fills: [+ gradient([+ { color: { r: 0.93, g: 0.94, b: 1, a: 1 }, position: 0 },+ { color: { r: 0.85, g: 0.86, b: 0.95, a: 1 }, position: 1 }+ ])+ ],+ effects: [innerShadow(0, 4, 12, 0, { r: 0.38, g: 0.35, b: 0.95, a: 0.3 })]+ })++ // Combined drop + inner shadow+ const comboCard = store.createShape('FRAME', 536, 236, 160, 100, effectsSectionId)+ graph.updateNode(comboCard, {+ name: 'Combined',+ cornerRadius: 12,+ fills: [solid(WHITE)],+ effects: [+ dropShadow(0, 4, 16, 0, { r: 0, g: 0, b: 0, a: 0.12 }),+ innerShadow(0, 1, 2, 0, { r: 0, g: 0, b: 0, a: 0.06 })+ ]+ })+ const comboText = store.createShape('TEXT', 16, 40, 128, 20, comboCard)+ graph.updateNode(comboText, {+ name: 'Label',+ text: 'Drop + Inner',+ fontSize: 13,+ fontWeight: 500,+ fills: [solid(GRAY_500)]+ })++ // Row 3: Text shadows & blurs+ const textFxLabel = store.createShape('TEXT', 32, 368, 200, 20, effectsSectionId)+ graph.updateNode(textFxLabel, {+ name: 'Label',+ text: 'Text Shadow & Blur',+ fontSize: 13,+ fontWeight: 600,+ fills: [solid(GRAY_500)]+ })++ // Text with drop shadow (renders on glyphs, not bounding box)+ const textShadow = store.createShape('TEXT', 32, 400, 200, 36, effectsSectionId)+ graph.updateNode(textShadow, {+ name: 'Text Shadow',+ text: 'Glyph Shadow',+ fontSize: 28,+ fontWeight: 700,+ fills: [solid(BLACK)],+ effects: [dropShadow(2, 2, 4, 0, { r: 0.23, g: 0.51, b: 0.96, a: 0.5 })]+ })++ // Text with inner shadow+ const textInner = store.createShape('TEXT', 260, 400, 200, 36, effectsSectionId)+ graph.updateNode(textInner, {+ name: 'Text Inner',+ text: 'Inner Glow',+ fontSize: 28,+ fontWeight: 700,+ fills: [solid(INDIGO)],+ effects: [innerShadow(0, -1, 3, 0, { r: 1, g: 1, b: 1, a: 0.6 })]+ })++ // Layer blur+ const blurRect = store.createShape('RECTANGLE', 500, 392, 120, 50, effectsSectionId)+ graph.updateNode(blurRect, {+ name: 'Layer Blur',+ cornerRadius: 10,+ fills: [+ gradient([+ { color: PURPLE, position: 0 },+ { color: BLUE, position: 1 }+ ])+ ],+ effects: [blurEffect('LAYER_BLUR', 4)]+ })++ // Background blur (glassmorphism card)+ const glassBg = store.createShape('FRAME', 652, 368, 200, 80, effectsSectionId)+ graph.updateNode(glassBg, {+ name: 'Glass Card',+ cornerRadius: 16,+ fills: [solid({ r: 1, g: 1, b: 1, a: 0.3 })],+ strokes: thinStroke({ r: 1, g: 1, b: 1, a: 0.4 }),+ effects: [blurEffect('BACKGROUND_BLUR', 16)]+ })+ const glassText = store.createShape('TEXT', 20, 30, 160, 20, glassBg)+ graph.updateNode(glassText, {+ name: 'Label',+ text: 'Glassmorphism',+ fontSize: 14,+ fontWeight: 600,+ fills: [solid(BLACK)]+ })+// Bind variables to some demo nodesgraph.bindVariable(sidebarId, 'fills/0/color', 'var-bg')graph.bindVariable(headerId, 'fills/0/color', 'var-bg')diff --git a/src/stores/editor.ts b/src/stores/editor.tsindex d03629e20..7a0df4b87 100644--- a/src/stores/editor.ts+++ b/src/stores/editor.ts@@ -864,6 +864,7 @@ export function createEditorStore() {if ('vectorNetwork' in changes) {_renderer?.invalidateVectorPath(id)}+ _renderer?.invalidateNodePicture(id)runLayoutForNode(id)syncIfInsideComponent(id)requestRender()diff --git a/tests/e2e/perf.spec.ts b/tests/e2e/perf.spec.tsindex 072ca45f3..43ded5416 100644--- a/tests/e2e/perf.spec.ts+++ b/tests/e2e/perf.spec.ts@@ -148,4 +148,87 @@ test.describe('Render performance', () => {expect(results.pan.avg).toBeLessThan(50)})++ test('benchmark: shadow rendering throughput', async () => {+ const SHADOW_NODES = 50+ const SHADOW_ITERS = 100++ const results = await helper.page.evaluate(+ ({ count, iterations }) => {+ const store = window.__OPEN_PENCIL_STORE__!+ const renderer = store.renderer!+ const graph = store.graph+ const pageId = store.state.currentPageId++ const shadowIds: string[] = []+ const cols = Math.ceil(Math.sqrt(count))+ for (let i = 0; i < count; i++) {+ const id = graph.createNode('RECTANGLE', pageId, {+ x: (i % cols) * 80,+ y: Math.floor(i / cols) * 80 + 2000,+ width: 60,+ height: 60,+ cornerRadius: 8,+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }],+ effects: [+ {+ type: 'DROP_SHADOW',+ color: { r: 0, g: 0, b: 0, a: 0.2 },+ offset: { x: 0, y: 4 },+ radius: 12,+ spread: 0,+ visible: true+ }+ ]+ })+ shadowIds.push(id)+ }++ function setupRenderer() {+ renderer.dpr = window.devicePixelRatio || 1+ renderer.panX = 0+ renderer.panY = -2000+ renderer.zoom = 1+ renderer.viewportWidth = 1280+ renderer.viewportHeight = 800+ renderer.showRulers = false+ renderer.pageColor = store.state.pageColor+ renderer.pageId = pageId+ }++ setupRenderer()+ renderer.render(graph, store.state.selectedIds, {}, store.state.sceneVersion)++ setupRenderer()+ const sceneStart = performance.now()+ for (let i = 0; i < iterations; i++) {+ const node = graph.getNode(shadowIds[i % shadowIds.length]!)+ if (node) graph.updateNode(node.id, { x: node.x + 0.1 })+ store.state.sceneVersion+++ renderer.render(graph, store.state.selectedIds, {}, store.state.sceneVersion)+ }+ const sceneMs = performance.now() - sceneStart++ for (const id of shadowIds) graph.deleteNode(id)++ return {+ scene: {+ ms: Math.round(sceneMs * 100) / 100,+ avg: Math.round((sceneMs / iterations) * 100) / 100+ }+ }+ },+ { count: SHADOW_NODES, iterations: SHADOW_ITERS }+ )++ console.log(+ `\n═══ SHADOW BENCHMARK (${SHADOW_NODES} shadow nodes, ${SHADOW_ITERS} iterations) ═══`+ )+ console.log(+ ` Scene change: ${results.scene.avg}ms/frame (${results.scene.ms}ms total)`+ )+ console.log(`═══════════════════════════════════════════════════════\n`)++ expect(results.scene.avg).toBeLessThan(50)+ })})