Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

15.4 KB
Raw Blame
import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type {
  PreviewStateController,
  SamPreviewState,
} from '@workbench/canvas-engine/controllers/previewStateController';
import type { RasterController } from '@workbench/canvas-engine/controllers/rasterController';
import type { RenderController } from '@workbench/canvas-engine/controllers/renderController';
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
import type { OverlayStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { EngineStores } from '@workbench/canvas-engine/engineStores';
import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';
import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { FrameDamage, Mat2d, Rect } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';

import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { isLeafDrawableForScreen } from '@workbench/canvas-engine/document-model/screenComposition';
import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';
import { isOverlayStack } from '@workbench/canvas-engine/document/layerStacks';
import { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { intersect } from '@workbench/canvas-engine/math/rect';
import {
  compositeDocument,
  reusePreparation,
  shouldSmoothAtZoom,
  type CompositeOptions,
  type CompositePreparation,
} from '@workbench/canvas-engine/render/compositor';
import { calculateActiveFrameLayerIds, committedLeafBounds } from '@workbench/canvas-engine/render/frameDemand';
import { FULL_DAMAGE } from '@workbench/canvas-engine/types';

import type { FloatingSelectionFrame } from './floatingSelectionFrame';
import type { LayerTransformOverrides } from './overlayFrame';

export interface CreateCompositeFrameDeps {
  readonly layerCache: LayerCacheStore;
  readonly derivedSurfaceCache: DerivedSurfaceCache;
  readonly backend: RasterBackend;
  readonly diagnostics: CanvasDiagnostics;
  readonly raster: Pick<RasterController, 'beginFrame' | 'enforceBudget'>;
  readonly maskScratch: Pick<RenderController, 'getMaskScratch' | 'releaseMaskScratch'>;
  readonly previews: PreviewStateController;
  readonly stores: EngineStores;
  readonly viewport: Viewport;
  readonly transformOverrides: LayerTransformOverrides;
  readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;
  readonly getGroupSurface: NonNullable<CompositeOptions['groupSurface']>;
  readonly getMaskPatternTile: (style: string, color: string) => RasterSurface | null;
  readonly getCheckerboardTile: () => RasterSurface;
  /** The control layer shown as its kept original, if any. */
  readonly getControlView: () => CompositeOptions['controlView'];
  /** Starts (or joins) the rasterization of a layer whose cache is stale. */
  readonly rasterizeLayer: (layer: CanvasLayerContract, doc: CanvasDocumentContractV3) => void;
  /**
   * Whether a pointer gesture, transform session or floating selection in progress edits a control layer, a mask or a
   * region. Those stacks then draw above a shown preview, so the user never edits blind, and the regenerate tint draws
   * again with its raster layer, under the preview. The frame after the edit ends hides them again.
   */
  readonly isEditingStagingHiddenStack: () => boolean;
}

/**
 * While a staged or progress preview shows, or the user toggled the staged result off to compare, the screen draws
 * raster layers only: control layers, masks and regions stop covering and tinting it, so the result reads as it would
 * be accepted and the canvas under it reads the same way. Generation still reads every stack.
 */
const STAGING_OVERLAY_STACKS: Readonly<Record<OverlayStackKind, boolean>> = {
  control: false,
  vector: true,
  inpaint_mask: false,
  regional_guidance: false,
};

/**
 * Whether `nodeId` sits in a stack the staging view hides: a control layer, a mask or a region, or a group in those
 * stacks. An edit of it shows those stacks again ({@link CreateCompositeFrameDeps.isEditingStagingHiddenStack}).
 */
export const isInStagingHiddenStack = (doc: CanvasDocumentContractV3, nodeId: string | null): boolean => {
  const stack = nodeId ? getDocumentIndex(doc).byId.get(nodeId)?.stack : undefined;
  return stack !== undefined && isOverlayStack(stack) && !STAGING_OVERLAY_STACKS[stack];
};

/**
 * The selected control layer, mask or region a shown preview hides, when the screen would draw it with the stack shown.
 * A gesture on it reveals the stack (and a brush refuses a layer whose pixels are not loaded yet), so the frame keeps
 * it resident while hidden and on screen. A selected group needs nothing up front: brush and shapes paint a new layer,
 * move drags whatever caches exist.
 */
const stagingHiddenSelectedLeaf = (doc: CanvasDocumentContractV3): SemanticLeaf | null => {
  const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
  return leaf &&
    isOverlayStack(leaf.stack) &&
    !STAGING_OVERLAY_STACKS[leaf.stack] &&
    isLeafDrawableForScreen(leaf, false)
    ? leaf
    : null;
};

export interface CompositeFrame {
  /** Composites the document onto the screen surface and enforces the surface budget. */
  draw(
    screen: RasterSurface,
    doc: CanvasDocumentContractV3,
    view: Mat2d,
    floatFrame: FloatingSelectionFrame | null,
    samPreview: SamPreviewState | null,
    /** What must be repainted; absent repaints everything. */
    damage?: FrameDamage
  ): void;
}

interface LeafBoundsMemo {
  readonly layer: SemanticLeaf['layer'];
  readonly matrix: Mat2d;
  readonly live: Rect | undefined;
  readonly bounds: Rect | null;
  // Legacy gradients without an extent are document-sized.
  readonly documentWidth: number;
  readonly documentHeight: number;
}

const sameOptionalRect = (a: Rect | undefined, b: Rect | undefined): boolean =>
  a === b || (!!a && !!b && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height);

/**
 * Composite only for pixel/order/view changes. Rasterize demanded visible layers and protect them during post-draw
 * eviction. SAM isolation restricts drawing and clipping to its layer/rect, suppressing unrelated previews, floats,
 * control views and transform overrides.
 */
export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFrame => {
  const { derivedSurfaceCache, diagnostics, layerCache, previews, raster, stores, transformOverrides, viewport } = deps;

  /**
   * Create missing caches and rasterize stale ones, but never resize existing entries here: unflushed paint may exceed
   * persisted bounds. Rasterization owns bounds changes.
   */
  const ensureLayerCaches = (
    doc: CanvasDocumentContractV3,
    frame: CompositePreparation,
    activeFrameLayerIds: ReadonlySet<string>
  ): void => {
    for (const { layer } of frame.leaves) {
      if (activeFrameLayerIds.has(layer.id)) {
        ensureLayerCache(doc, layer);
      }
    }
  };

  const ensureLayerCache = (doc: CanvasDocumentContractV3, layer: CanvasLayerContract): void => {
    if (!isLayerContributing(layer) || !renderableSourceOf(layer) || !isRenderableLayer(layer)) {
      return;
    }
    const entry = layerCache.getOrCreateRect(layer.id, getSourceContentRect(layer, doc));
    if (entry.stale) {
      deps.rasterizeLayer(layer, doc);
    }
  };

  /** The document-space rect currently on screen, which bounds what the frame demands. */
  const visibleDocumentRect = (screen: RasterSurface): Rect => {
    const viewportSize = viewport.getViewportSize();
    const dpr = viewport.getDpr();
    const cssWidth = viewportSize.width > 0 ? viewportSize.width : screen.width / dpr;
    const cssHeight = viewportSize.height > 0 ? viewportSize.height : screen.height / dpr;
    const topLeft = viewport.screenToDocument({ x: 0, y: 0 });
    const bottomRight = viewport.screenToDocument({ x: cssWidth, y: cssHeight });
    return {
      height: Math.abs(bottomRight.y - topLeft.y),
      width: Math.abs(bottomRight.x - topLeft.x),
      x: Math.min(topLeft.x, bottomRight.x),
      y: Math.min(topLeft.y, bottomRight.y),
    };
  };

  // The frame description is reused until the document, isolation or override contents change; each leaf's bounds until
  // its contract, placement, live cache extent or the document size does.
  let preparation: CompositePreparation | null = null;
  // A bounded or empty repaint reads only part of the working set; the usage window stays open from the last full
  // repaint so artifacts it skipped are not evicted as unused.
  let fullFrameUsage: ReturnType<typeof raster.beginFrame> | null = null;
  let boundsMemo = new Map<string, LeafBoundsMemo>();

  const describeFrame = (
    doc: CanvasDocumentContractV3,
    isolationLayerId: string | null,
    overrides: CompositeOptions['transformOverrides'],
    showOverlayStacks: CompositeOptions['showOverlayStacks']
  ): CompositePreparation => {
    const plan = reusePreparation(preparation, doc, {
      backend: deps.backend,
      groupSurface: deps.getGroupSurface,
      isolationLayerId,
      showOverlayStacks,
      transformOverrides: overrides,
    });
    preparation = plan;
    const nextMemo = new Map<string, LeafBoundsMemo>();
    const bounds = plan.leaves.map((leaf, index) => {
      const matrix = plan.matrices[index]!;
      const live = layerCache.peek(leaf.id)?.rect;
      const previous = boundsMemo.get(leaf.id);
      const memo =
        previous &&
        previous.layer === leaf.layer &&
        previous.matrix === matrix &&
        previous.documentWidth === doc.width &&
        previous.documentHeight === doc.height &&
        sameOptionalRect(previous.live, live)
          ? previous
          : {
              bounds: committedLeafBounds(leaf, matrix, doc, live),
              documentHeight: doc.height,
              documentWidth: doc.width,
              layer: leaf.layer,
              live: live && { ...live },
              matrix,
            };
      nextMemo.set(leaf.id, memo);
      return memo.bounds;
    });
    boundsMemo = nextMemo;
    return { ...plan, bounds };
  };

  /** Evict after drawing; the frame's demanded layers and the artifacts it read form the working set. */
  const enforceBudget = (
    activeFrameLayerIds: ReadonlySet<string>,
    usage: ReturnType<typeof raster.beginFrame>
  ): void => {
    const { evictedBaseLayerIds } = raster.enforceBudget(activeFrameLayerIds, usage);
    for (const id of evictedBaseLayerIds) {
      stores.thumbnailVersion.delete(id);
      stores.thumbnailStatus.delete(id);
    }
  };

  return {
    draw: (screen, doc, view, floatFrame, samPreview, damage) => {
      const stagedPreview = previews.getStaged();
      const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;
      const overrides = !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null;
      // A shown or toggled-off preview hides every overlay stack and the regenerate tint, unless one is being edited.
      const staging = previews.hidesStagingOverlays() && !deps.isEditingStagingHiddenStack();
      const showOverlayStacks = staging ? STAGING_OVERLAY_STACKS : undefined;
      const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides, showOverlayStacks);
      // Snapshot filter previews only when active, avoiding an empty map allocation every frame.
      const layerPreviews = !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null;
      const visibleRect = visibleDocumentRect(screen);
      const activeFrameLayerIds = calculateActiveFrameLayerIds({
        document: doc,
        preparation: frame,
        viewport: visibleRect,
      });
      // A previewed layer draws through its cache entry even when only the preview is on screen.
      for (const layerId of layerPreviews?.keys() ?? []) {
        activeFrameLayerIds.add(layerId);
      }
      ensureLayerCaches(doc, frame, activeFrameLayerIds);
      // The selected overlay leaf stays loaded and unevicted while hidden, ready for a gesture to reveal and edit,
      // under the same on-screen rule as the leaves the frame draws. No transform override moves a hidden leaf.
      const hiddenSelected = staging && !isolatedGuard ? stagingHiddenSelectedLeaf(doc) : null;
      const hiddenBounds = hiddenSelected
        ? committedLeafBounds(
            hiddenSelected,
            hiddenSelected.worldTransform,
            doc,
            layerCache.peek(hiddenSelected.id)?.rect
          )
        : null;
      if (hiddenSelected && hiddenBounds && intersect(hiddenBounds, visibleRect)) {
        activeFrameLayerIds.add(hiddenSelected.id);
        ensureLayerCache(doc, hiddenSelected.layer);
      }
      const frameDamage = isolatedGuard ? FULL_DAMAGE : (damage ?? FULL_DAMAGE);
      const usage = raster.beginFrame();
      if (frameDamage.kind === 'full' || !fullFrameUsage) {
        fullFrameUsage = usage;
      }

      let usedMaskScratch = false;
      compositeDocument(screen, doc, layerCache, view, {
        damage: frameDamage,
        adjustedSurface: deps.getAdjustedSurface,
        groupSurface: deps.getGroupSurface,
        backend: deps.backend,
        checkerboardTile: stores.checkerboard.get() ? deps.getCheckerboardTile() : null,
        clipRect: isolatedGuard && samPreview ? samPreview.rect : null,
        controlView: isolatedGuard ? null : deps.getControlView(),
        derivedSurfaces: derivedSurfaceCache,
        diagnostics,
        floatingSelection: isolatedGuard ? null : (floatFrame?.composite ?? null),
        imageSmoothing: shouldSmoothAtZoom(viewport.getZoom()),
        isolationLayerId: isolatedGuard?.layerId ?? null,
        layerPreviews,
        maskPatternTile: deps.getMaskPatternTile,
        preparation: frame,
        // Screen frames are display-time: the region tint may draw, except over a staged result.
        regionOverlays: !staging,
        screenMask: {
          dpr: viewport.getDpr(),
          getScratch: (width, height) => {
            usedMaskScratch = true;
            return deps.maskScratch.getMaskScratch(width, height);
          },
        },
        showOverlayStacks,
        // Candidates and progress frames alike land at the rect pinned at submission, never the live bbox.
        stagedPreview:
          !isolatedGuard && stagedPreview
            ? {
                opacity: stagedPreview.placement.opacity,
                rect: {
                  height: stagedPreview.placement.height,
                  width: stagedPreview.placement.width,
                  x: stagedPreview.placement.x,
                  y: stagedPreview.placement.y,
                },
                surface: stagedPreview.surface,
              }
            : null,
        skipLayerId: stores.textEditSession.get()?.layerId ?? null,
        transformOverrides: overrides,
      });

      // A bounded repaint can miss a pattern that is still on screen.
      if (frameDamage.kind === 'full' && !usedMaskScratch) {
        deps.maskScratch.releaseMaskScratch();
      }
      enforceBudget(activeFrameLayerIds, fullFrameUsage);
    },
  };
};