59 lines
2.4 KiB
TypeScript
59 lines
2.4 KiB
TypeScript
import type { ImageDocument } from "@core/document";
|
|
import type { Layer } from "@core/layer";
|
|
import type { ViewportState } from "@editor/state";
|
|
import { resolveTransformTargetBounds } from "@editor/transform-targets";
|
|
import { clearScreenRect } from "./clear-rect";
|
|
import type { ImageTextureRenderer } from "./image-textures";
|
|
import { documentRectToScreenRect } from "./screen-rect";
|
|
import type { RgbaColor, ScreenRect, WebGlRendererContext } from "./types";
|
|
|
|
const imageLayerColor: RgbaColor = [0.38, 0.42, 0.5, 1];
|
|
const imageLayerInsetColor: RgbaColor = [0.48, 0.54, 0.64, 1];
|
|
|
|
export function renderLayers(context: WebGlRendererContext, document: ImageDocument, viewport: ViewportState, imageTextureRenderer: ImageTextureRenderer) {
|
|
for (const artboard of document.artboards) {
|
|
if (!artboard.visible) continue;
|
|
const clipRect = documentRectToScreenRect(context.canvas, artboard.bounds, viewport);
|
|
for (const layer of artboard.layers) renderLayer(context, document, viewport, layer, imageTextureRenderer, clipRect);
|
|
}
|
|
}
|
|
|
|
function renderLayer(
|
|
context: WebGlRendererContext,
|
|
document: ImageDocument,
|
|
viewport: ViewportState,
|
|
layer: Layer,
|
|
imageTextureRenderer: ImageTextureRenderer,
|
|
clipRect: ScreenRect,
|
|
) {
|
|
if (!layer.visible) return;
|
|
|
|
if (layer.type === "group") {
|
|
for (const child of layer.children) renderLayer(context, document, viewport, child, imageTextureRenderer, clipRect);
|
|
return;
|
|
}
|
|
|
|
const bounds = resolveTransformTargetBounds(document, { type: "layer", id: layer.id });
|
|
if (!bounds) return;
|
|
|
|
const rect = documentRectToScreenRect(context.canvas, bounds, viewport);
|
|
const asset = document.assets.find((candidate) => candidate.id === layer.assetId);
|
|
if (asset && imageTextureRenderer.render(asset, rect, clipRect)) return;
|
|
|
|
const fallbackRect = intersectScreenRects(rect, clipRect);
|
|
if (!fallbackRect) return;
|
|
clearScreenRect(context, fallbackRect, imageLayerColor);
|
|
const insetRect = intersectScreenRects({ x: rect.x + 4, y: rect.y + 4, w: Math.max(0, rect.w - 8), h: Math.max(0, rect.h - 8) }, clipRect);
|
|
if (insetRect) clearScreenRect(context, insetRect, imageLayerInsetColor);
|
|
}
|
|
|
|
function intersectScreenRects(a: ScreenRect, b: ScreenRect): ScreenRect | undefined {
|
|
const x1 = Math.max(a.x, b.x);
|
|
const y1 = Math.max(a.y, b.y);
|
|
const x2 = Math.min(a.x + a.w, b.x + b.w);
|
|
const y2 = Math.min(a.y + a.h, b.y + b.h);
|
|
if (x2 <= x1 || y2 <= y1) return undefined;
|
|
|
|
return { x: x1, y: y1, w: x2 - x1, h: y2 - y1 };
|
|
}
|