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.

7.5 KB
Raw Blame
import type { CanvasBezierPointContract } from '@workbench/canvas-engine/contracts';
import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';

import { applyToPoint } from './mat2d';

export const isEmpty = (r: Rect): boolean => r.width <= 0 || r.height <= 0;

/** Intersection of two rects, or `null` if they don't overlap (or either is empty). */
export const intersect = (a: Rect, b: Rect): Rect | null => {
  if (isEmpty(a) || isEmpty(b)) {
    return null;
  }
  const x = Math.max(a.x, b.x);
  const y = Math.max(a.y, b.y);
  const right = Math.min(a.x + a.width, b.x + b.width);
  const bottom = Math.min(a.y + a.height, b.y + b.height);
  if (right <= x || bottom <= y) {
    return null;
  }
  return { x, y, width: right - x, height: bottom - y };
};

/**
 * Union (bounding box) of two rects. An empty rect is treated as contributing no area — the union of an empty rect and
 * a non-empty rect is the non-empty rect; the union of two empty rects is the first rect.
 */
export const union = (a: Rect, b: Rect): Rect => {
  if (isEmpty(a) && isEmpty(b)) {
    return a;
  }
  if (isEmpty(a)) {
    return b;
  }
  if (isEmpty(b)) {
    return a;
  }
  const x = Math.min(a.x, b.x);
  const y = Math.min(a.y, b.y);
  const right = Math.max(a.x + a.width, b.x + b.width);
  const bottom = Math.max(a.y + a.height, b.y + b.height);
  return { x, y, width: right - x, height: bottom - y };
};

/** True if `p` lies within `r`, inclusive of the min edges and exclusive of the max edges. */
export const containsPoint = (r: Rect, p: Vec2): boolean =>
  p.x >= r.x && p.x < r.x + r.width && p.y >= r.y && p.y < r.y + r.height;

/** Grows (or shrinks, for negative `margin`) a rect uniformly on all sides. */
export const expand = (r: Rect, margin: number): Rect => ({
  x: r.x - margin,
  y: r.y - margin,
  width: r.width + margin * 2,
  height: r.height + margin * 2,
});

/** Round outward to integer pixels so dirty patches fully cover changed bounds. */
export const roundOut = (r: Rect): Rect => {
  const x = Math.floor(r.x);
  const y = Math.floor(r.y);
  const right = Math.ceil(r.x + r.width);
  const bottom = Math.ceil(r.y + r.height);
  return { x, y, width: right - x, height: bottom - y };
};

/** Axis-aligned bounds of `r` after being transformed by `m`. */
export const transformBounds = (m: Mat2d, r: Rect): Rect => {
  const corners: Vec2[] = [
    { x: r.x, y: r.y },
    { x: r.x + r.width, y: r.y },
    { x: r.x, y: r.y + r.height },
    { x: r.x + r.width, y: r.y + r.height },
  ].map((p) => applyToPoint(m, p));

  const xs = corners.map((p) => p.x);
  const ys = corners.map((p) => p.y);
  const minX = Math.min(...xs);
  const maxX = Math.max(...xs);
  const minY = Math.min(...ys);
  const maxY = Math.max(...ys);

  return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
};

const area = (r: Rect): number => (isEmpty(r) ? 0 : r.width * r.height);

/** True if two rects overlap or touch within `slack` pixels (their `slack`-expanded bounds intersect). */
const isNearby = (a: Rect, b: Rect, slack: number): boolean => {
  const expandedA = slack === 0 ? a : expand(a, slack);
  return intersect(expandedA, b) !== null;
};

/**
 * Greedily merge overlapping/touching or nearby rects when combined area stays within twice their sum. Repeat to
 * stability; if still over `maxRegions`, union all to guarantee repaint coverage.
 */
export const mergeDirtyRects = (rects: Rect[], maxRegions = 4): Rect[] => {
  const nonEmpty = rects.filter((r) => !isEmpty(r));
  if (nonEmpty.length <= 1) {
    return nonEmpty;
  }

  let current = nonEmpty.slice();
  const avgDimension = current.reduce((sum, r) => sum + (r.width + r.height) / 2, 0) / current.length;
  const slack = avgDimension * 0.1;

  const findMergeablePair = (rectList: Rect[]): [number, number] | null => {
    for (let i = 0; i < rectList.length; i++) {
      for (let j = i + 1; j < rectList.length; j++) {
        const a = rectList[i];
        const b = rectList[j];
        if (!a || !b) {
          continue;
        }
        const overlaps = intersect(a, b) !== null;
        const merged = union(a, b);
        const wasteOk = area(merged) <= (area(a) + area(b)) * 2;
        if (overlaps || (isNearby(a, b, slack) && wasteOk)) {
          return [i, j];
        }
      }
    }
    return null;
  };

  let pair = findMergeablePair(current);
  while (pair !== null && current.length > 1) {
    const [i, j] = pair;
    const a = current[i] as Rect;
    const b = current[j] as Rect;
    const next = current.filter((_, idx) => idx !== i && idx !== j);
    next.push(union(a, b));
    current = next;
    pair = findMergeablePair(current);
  }

  if (current.length > maxRegions) {
    return [current.reduce((acc, r) => union(acc, r))];
  }

  return current;
};

type RenderableBezierPoint = Pick<CanvasBezierPointContract, 'anchor' | 'inHandle' | 'outHandle'>;

export const evaluateBezierSegment = (from: RenderableBezierPoint, to: RenderableBezierPoint, t: number): Vec2 => {
  const p0 = from.anchor;
  const p1 = from.outHandle ?? from.anchor;
  const p2 = to.inHandle ?? to.anchor;
  const p3 = to.anchor;
  const mt = 1 - t;
  const mt2 = mt * mt;
  const t2 = t * t;

  return {
    x: mt2 * mt * p0.x + 3 * mt2 * t * p1.x + 3 * mt * t2 * p2.x + t2 * t * p3.x,
    y: mt2 * mt * p0.y + 3 * mt2 * t * p1.y + 3 * mt * t2 * p2.y + t2 * t * p3.y,
  };
};

export const getBezierPathBounds = (points: RenderableBezierPoint[], isClosed: boolean): Rect => {
  if (points.length === 0) {
    return { x: 0, y: 0, width: 0, height: 0 };
  }
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  const include = (point: Vec2) => {
    minX = Math.min(minX, point.x);
    minY = Math.min(minY, point.y);
    maxX = Math.max(maxX, point.x);
    maxY = Math.max(maxY, point.y);
  };
  points.forEach((point) => include(point.anchor));
  for (let i = 0; i < (isClosed ? points.length : points.length - 1); i++) {
    const from = points[i]!;
    const to = points[(i + 1) % points.length]!;
    const p1 = from.outHandle ?? from.anchor;
    const p2 = to.inHandle ?? to.anchor;
    for (const axis of ['x', 'y'] as const) {
      // Roots of the cubic's derivative, with the common factor of three removed.
      const a = -from.anchor[axis] + 3 * p1[axis] - 3 * p2[axis] + to.anchor[axis];
      const b = 2 * (from.anchor[axis] - 2 * p1[axis] + p2[axis]);
      const c = p1[axis] - from.anchor[axis];
      const roots: number[] = [];
      if (Math.abs(a) < 1e-12) {
        if (Math.abs(b) >= 1e-12) {
          roots.push(-c / b);
        }
      } else {
        const discriminant = b * b - 4 * a * c;
        if (discriminant >= 0) {
          const sqrt = Math.sqrt(discriminant);
          roots.push((-b + sqrt) / (2 * a), (-b - sqrt) / (2 * a));
        }
      }
      for (const t of roots) {
        if (t > 0 && t < 1) {
          include(evaluateBezierSegment(from, to, t));
        }
      }
    }
  }
  return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
};

/** Axis-aligned bounds of an outline polygon; an empty polygon yields a zero-size rect. */
export const polygonBounds = (polygon: readonly Vec2[]): Rect => {
  if (polygon.length === 0) {
    return { height: 0, width: 0, x: 0, y: 0 };
  }
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  for (const p of polygon) {
    if (p.x < minX) {
      minX = p.x;
    }
    if (p.y < minY) {
      minY = p.y;
    }
    if (p.x > maxX) {
      maxX = p.x;
    }
    if (p.y > maxY) {
      maxY = p.y;
    }
  }
  return { height: maxY - minY, width: maxX - minX, x: minX, y: minY };
};