Record audio tracks
This commit is contained in:
@@ -0,0 +1,543 @@
|
||||
// Animation system models: Frame, Keyframe, AnimationCurve, AnimationData
|
||||
|
||||
import { context, config, pointerList, startProps } from '../state.js';
|
||||
|
||||
// Helper function for UUID generation
|
||||
function uuidv4() {
|
||||
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) =>
|
||||
(
|
||||
+c ^
|
||||
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))
|
||||
).toString(16),
|
||||
);
|
||||
}
|
||||
|
||||
class Frame {
|
||||
constructor(frameType = "normal", uuid = undefined) {
|
||||
this.keys = {};
|
||||
this.shapes = [];
|
||||
this.frameType = frameType;
|
||||
this.keyTypes = new Set()
|
||||
if (!uuid) {
|
||||
this.idx = uuidv4();
|
||||
} else {
|
||||
this.idx = uuid;
|
||||
}
|
||||
pointerList[this.idx] = this;
|
||||
}
|
||||
get exists() {
|
||||
return true;
|
||||
}
|
||||
saveState() {
|
||||
startProps[this.idx] = structuredClone(this.keys);
|
||||
}
|
||||
copy(idx) {
|
||||
let newFrame = new Frame(
|
||||
this.frameType,
|
||||
idx.slice(0, 8) + this.idx.slice(8),
|
||||
);
|
||||
newFrame.keys = structuredClone(this.keys);
|
||||
newFrame.shapes = [];
|
||||
for (let shape of this.shapes) {
|
||||
newFrame.shapes.push(shape.copy(idx));
|
||||
}
|
||||
return newFrame;
|
||||
}
|
||||
static fromJSON(json, Shape = null) {
|
||||
if (!json) {
|
||||
return undefined
|
||||
}
|
||||
// Shape parameter passed in to avoid circular dependency
|
||||
// Will be provided by the calling code that has access to both modules
|
||||
const frame = new Frame(json.frameType, json.idx);
|
||||
frame.keyTypes = new Set(json.keyTypes)
|
||||
frame.keys = json.keys;
|
||||
if (Shape) {
|
||||
for (let i in json.shapes) {
|
||||
const shape = json.shapes[i];
|
||||
frame.shapes.push(Shape.fromJSON(shape));
|
||||
}
|
||||
}
|
||||
|
||||
return frame;
|
||||
}
|
||||
toJSON(randomizeUuid = false) {
|
||||
const json = {};
|
||||
json.type = "Frame";
|
||||
json.frameType = this.frameType;
|
||||
json.keyTypes = Array.from(this.keyTypes)
|
||||
if (randomizeUuid) {
|
||||
json.idx = uuidv4();
|
||||
} else {
|
||||
json.idx = this.idx;
|
||||
}
|
||||
json.keys = structuredClone(this.keys);
|
||||
json.shapes = [];
|
||||
for (let shape of this.shapes) {
|
||||
json.shapes.push(shape.toJSON(randomizeUuid));
|
||||
}
|
||||
return json;
|
||||
}
|
||||
addShape(shape, sendToBack) {
|
||||
if (sendToBack) {
|
||||
this.shapes.unshift(shape);
|
||||
} else {
|
||||
this.shapes.push(shape);
|
||||
}
|
||||
}
|
||||
removeShape(shape) {
|
||||
let shapeIndex = this.shapes.indexOf(shape);
|
||||
if (shapeIndex >= 0) {
|
||||
this.shapes.splice(shapeIndex, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TempFrame {
|
||||
constructor() {}
|
||||
get exists() {
|
||||
return false;
|
||||
}
|
||||
get idx() {
|
||||
return "tempFrame";
|
||||
}
|
||||
get keys() {
|
||||
return {};
|
||||
}
|
||||
get shapes() {
|
||||
return [];
|
||||
}
|
||||
get frameType() {
|
||||
return "temp";
|
||||
}
|
||||
copy() {
|
||||
return this;
|
||||
}
|
||||
addShape() {}
|
||||
removeShape() {}
|
||||
}
|
||||
|
||||
const tempFrame = new TempFrame();
|
||||
|
||||
// Animation system classes
|
||||
class Keyframe {
|
||||
constructor(time, value, interpolation = "linear", uuid = undefined) {
|
||||
this.time = time;
|
||||
this.value = value;
|
||||
this.interpolation = interpolation; // 'linear', 'bezier', 'step', 'hold'
|
||||
// For bezier interpolation
|
||||
this.easeIn = { x: 0.42, y: 0 }; // Default ease-in control point
|
||||
this.easeOut = { x: 0.58, y: 1 }; // Default ease-out control point
|
||||
if (!uuid) {
|
||||
this.idx = uuidv4();
|
||||
} else {
|
||||
this.idx = uuid;
|
||||
}
|
||||
}
|
||||
|
||||
static fromJSON(json) {
|
||||
const keyframe = new Keyframe(json.time, json.value, json.interpolation, json.idx);
|
||||
if (json.easeIn) keyframe.easeIn = json.easeIn;
|
||||
if (json.easeOut) keyframe.easeOut = json.easeOut;
|
||||
return keyframe;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
idx: this.idx,
|
||||
time: this.time,
|
||||
value: this.value,
|
||||
interpolation: this.interpolation,
|
||||
easeIn: this.easeIn,
|
||||
easeOut: this.easeOut
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class AnimationCurve {
|
||||
constructor(parameter, uuid = undefined, parentAnimationData = null) {
|
||||
this.parameter = parameter; // e.g., "x", "y", "rotation", "scale_x", "exists"
|
||||
this.keyframes = []; // Always kept sorted by time
|
||||
this.parentAnimationData = parentAnimationData; // Reference to parent AnimationData for duration updates
|
||||
if (!uuid) {
|
||||
this.idx = uuidv4();
|
||||
} else {
|
||||
this.idx = uuid;
|
||||
}
|
||||
}
|
||||
|
||||
addKeyframe(keyframe) {
|
||||
// Time resolution based on framerate - half a frame's duration
|
||||
// This can be exposed via UI later
|
||||
const framerate = context.config?.framerate || 24;
|
||||
const timeResolution = (1 / framerate) / 2;
|
||||
|
||||
// Check if there's already a keyframe within the time resolution
|
||||
const existingKeyframe = this.getKeyframeAtTime(keyframe.time, timeResolution);
|
||||
|
||||
if (existingKeyframe) {
|
||||
// Update the existing keyframe's value instead of adding a new one
|
||||
existingKeyframe.value = keyframe.value;
|
||||
existingKeyframe.interpolation = keyframe.interpolation;
|
||||
if (keyframe.easeIn) existingKeyframe.easeIn = keyframe.easeIn;
|
||||
if (keyframe.easeOut) existingKeyframe.easeOut = keyframe.easeOut;
|
||||
} else {
|
||||
// Add new keyframe
|
||||
this.keyframes.push(keyframe);
|
||||
// Keep sorted by time
|
||||
this.keyframes.sort((a, b) => a.time - b.time);
|
||||
}
|
||||
|
||||
// Update animation duration after adding keyframe
|
||||
if (this.parentAnimationData) {
|
||||
this.parentAnimationData.updateDuration();
|
||||
}
|
||||
}
|
||||
|
||||
removeKeyframe(keyframe) {
|
||||
const index = this.keyframes.indexOf(keyframe);
|
||||
if (index >= 0) {
|
||||
this.keyframes.splice(index, 1);
|
||||
|
||||
// Update animation duration after removing keyframe
|
||||
if (this.parentAnimationData) {
|
||||
this.parentAnimationData.updateDuration();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getKeyframeAtTime(time, timeResolution = 0) {
|
||||
if (this.keyframes.length === 0) return null;
|
||||
|
||||
// If no tolerance, use exact match with binary search
|
||||
if (timeResolution === 0) {
|
||||
let left = 0;
|
||||
let right = this.keyframes.length - 1;
|
||||
|
||||
while (left <= right) {
|
||||
const mid = Math.floor((left + right) / 2);
|
||||
if (this.keyframes[mid].time === time) {
|
||||
return this.keyframes[mid];
|
||||
} else if (this.keyframes[mid].time < time) {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// With tolerance, find the closest keyframe within timeResolution
|
||||
let left = 0;
|
||||
let right = this.keyframes.length - 1;
|
||||
let closest = null;
|
||||
let closestDist = Infinity;
|
||||
|
||||
// Binary search to find the insertion point
|
||||
while (left <= right) {
|
||||
const mid = Math.floor((left + right) / 2);
|
||||
const dist = Math.abs(this.keyframes[mid].time - time);
|
||||
|
||||
if (dist < closestDist) {
|
||||
closestDist = dist;
|
||||
closest = this.keyframes[mid];
|
||||
}
|
||||
|
||||
if (this.keyframes[mid].time < time) {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Also check adjacent keyframes for closest match
|
||||
if (left < this.keyframes.length) {
|
||||
const dist = Math.abs(this.keyframes[left].time - time);
|
||||
if (dist < closestDist) {
|
||||
closestDist = dist;
|
||||
closest = this.keyframes[left];
|
||||
}
|
||||
}
|
||||
if (right >= 0) {
|
||||
const dist = Math.abs(this.keyframes[right].time - time);
|
||||
if (dist < closestDist) {
|
||||
closestDist = dist;
|
||||
closest = this.keyframes[right];
|
||||
}
|
||||
}
|
||||
|
||||
return closestDist < timeResolution ? closest : null;
|
||||
}
|
||||
|
||||
// Find the two keyframes that bracket the given time
|
||||
getBracketingKeyframes(time) {
|
||||
if (this.keyframes.length === 0) return { prev: null, next: null };
|
||||
if (this.keyframes.length === 1) return { prev: this.keyframes[0], next: this.keyframes[0] };
|
||||
|
||||
// Binary search to find the last keyframe at or before time
|
||||
let left = 0;
|
||||
let right = this.keyframes.length - 1;
|
||||
let prevIndex = -1;
|
||||
|
||||
while (left <= right) {
|
||||
const mid = Math.floor((left + right) / 2);
|
||||
if (this.keyframes[mid].time <= time) {
|
||||
prevIndex = mid; // This could be our answer
|
||||
left = mid + 1; // But check if there's a better one to the right
|
||||
} else {
|
||||
right = mid - 1; // Time is too large, search left
|
||||
}
|
||||
}
|
||||
|
||||
// If time is before all keyframes
|
||||
if (prevIndex === -1) {
|
||||
return { prev: this.keyframes[0], next: this.keyframes[0], t: 0 };
|
||||
}
|
||||
|
||||
// If time is after all keyframes
|
||||
if (prevIndex === this.keyframes.length - 1) {
|
||||
return { prev: this.keyframes[prevIndex], next: this.keyframes[prevIndex], t: 1 };
|
||||
}
|
||||
|
||||
const prev = this.keyframes[prevIndex];
|
||||
const next = this.keyframes[prevIndex + 1];
|
||||
const t = (time - prev.time) / (next.time - prev.time);
|
||||
|
||||
return { prev, next, t };
|
||||
}
|
||||
|
||||
interpolate(time) {
|
||||
if (this.keyframes.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { prev, next, t } = this.getBracketingKeyframes(time);
|
||||
|
||||
if (!prev || !next) {
|
||||
return null;
|
||||
}
|
||||
if (prev === next) {
|
||||
return prev.value;
|
||||
}
|
||||
|
||||
// Handle different interpolation types
|
||||
switch (prev.interpolation) {
|
||||
case "step":
|
||||
case "hold":
|
||||
return prev.value;
|
||||
|
||||
case "linear":
|
||||
// Simple linear interpolation
|
||||
if (typeof prev.value === "number" && typeof next.value === "number") {
|
||||
return prev.value + (next.value - prev.value) * t;
|
||||
}
|
||||
return prev.value;
|
||||
|
||||
case "bezier":
|
||||
// Cubic bezier interpolation using control points
|
||||
if (typeof prev.value === "number" && typeof next.value === "number") {
|
||||
// Use ease-in/ease-out control points
|
||||
const easedT = this.cubicBezierEase(t, prev.easeOut, next.easeIn);
|
||||
return prev.value + (next.value - prev.value) * easedT;
|
||||
}
|
||||
return prev.value;
|
||||
|
||||
case "zero":
|
||||
// Return 0 for the entire interval (used for inactive segments)
|
||||
return 0;
|
||||
|
||||
default:
|
||||
return prev.value;
|
||||
}
|
||||
}
|
||||
|
||||
// Cubic bezier easing function
|
||||
cubicBezierEase(t, easeOut, easeIn) {
|
||||
// Simplified cubic bezier for 0,0 -> easeOut -> easeIn -> 1,1
|
||||
const u = 1 - t;
|
||||
return 3 * u * u * t * easeOut.y +
|
||||
3 * u * t * t * easeIn.y +
|
||||
t * t * t;
|
||||
}
|
||||
|
||||
// Display color for this curve in timeline (based on parameter type) - Phase 4
|
||||
get displayColor() {
|
||||
// Auto-determined from parameter name
|
||||
if (this.parameter.endsWith('.x')) return '#7a00b3' // purple
|
||||
if (this.parameter.endsWith('.y')) return '#ff00ff' // magenta
|
||||
if (this.parameter.endsWith('.rotation')) return '#5555ff' // blue
|
||||
if (this.parameter.endsWith('.scale_x')) return '#ffaa00' // orange
|
||||
if (this.parameter.endsWith('.scale_y')) return '#ffff55' // yellow
|
||||
if (this.parameter.endsWith('.exists')) return '#55ff55' // green
|
||||
if (this.parameter.endsWith('.zOrder')) return '#55ffff' // cyan
|
||||
if (this.parameter.endsWith('.frameNumber')) return '#ff5555' // red
|
||||
return '#ffffff' // default white
|
||||
}
|
||||
|
||||
static fromJSON(json) {
|
||||
const curve = new AnimationCurve(json.parameter, json.idx);
|
||||
for (let kfJson of json.keyframes || []) {
|
||||
curve.keyframes.push(Keyframe.fromJSON(kfJson));
|
||||
}
|
||||
return curve;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
idx: this.idx,
|
||||
parameter: this.parameter,
|
||||
keyframes: this.keyframes.map(kf => kf.toJSON())
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class AnimationData {
|
||||
constructor(parentLayer = null, uuid = undefined) {
|
||||
this.curves = {}; // parameter name -> AnimationCurve
|
||||
this.duration = 0; // Duration in seconds (max time of all keyframes)
|
||||
this.parentLayer = parentLayer; // Reference to parent Layer for updating segment keyframes
|
||||
if (!uuid) {
|
||||
this.idx = uuidv4();
|
||||
} else {
|
||||
this.idx = uuid;
|
||||
}
|
||||
}
|
||||
|
||||
getCurve(parameter) {
|
||||
return this.curves[parameter];
|
||||
}
|
||||
|
||||
getOrCreateCurve(parameter) {
|
||||
if (!this.curves[parameter]) {
|
||||
this.curves[parameter] = new AnimationCurve(parameter, undefined, this);
|
||||
}
|
||||
return this.curves[parameter];
|
||||
}
|
||||
|
||||
addKeyframe(parameter, keyframe) {
|
||||
const curve = this.getOrCreateCurve(parameter);
|
||||
curve.addKeyframe(keyframe);
|
||||
}
|
||||
|
||||
removeKeyframe(parameter, keyframe) {
|
||||
const curve = this.curves[parameter];
|
||||
if (curve) {
|
||||
curve.removeKeyframe(keyframe);
|
||||
}
|
||||
}
|
||||
|
||||
removeCurve(parameter) {
|
||||
delete this.curves[parameter];
|
||||
}
|
||||
|
||||
setCurve(parameter, curve) {
|
||||
// Set parent reference for duration tracking
|
||||
curve.parentAnimationData = this;
|
||||
this.curves[parameter] = curve;
|
||||
// Update duration after adding curve with keyframes
|
||||
this.updateDuration();
|
||||
}
|
||||
|
||||
interpolate(parameter, time) {
|
||||
const curve = this.curves[parameter];
|
||||
if (!curve) return null;
|
||||
return curve.interpolate(time);
|
||||
}
|
||||
|
||||
// Get all animated values at a given time
|
||||
getValuesAtTime(time) {
|
||||
const values = {};
|
||||
for (let parameter in this.curves) {
|
||||
values[parameter] = this.curves[parameter].interpolate(time);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the duration based on all keyframes
|
||||
* Called automatically when keyframes are added/removed
|
||||
*/
|
||||
updateDuration() {
|
||||
// Calculate max time from all keyframes in all curves
|
||||
let maxTime = 0;
|
||||
for (let parameter in this.curves) {
|
||||
const curve = this.curves[parameter];
|
||||
if (curve.keyframes && curve.keyframes.length > 0) {
|
||||
const lastKeyframe = curve.keyframes[curve.keyframes.length - 1];
|
||||
maxTime = Math.max(maxTime, lastKeyframe.time);
|
||||
}
|
||||
}
|
||||
|
||||
// Update this AnimationData's duration
|
||||
this.duration = maxTime;
|
||||
|
||||
// If this layer belongs to a nested group, update the segment keyframes in the parent
|
||||
if (this.parentLayer && this.parentLayer.parentObject) {
|
||||
this.updateParentSegmentKeyframes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update segment keyframes in parent layer when this layer's duration changes
|
||||
* This ensures that nested group segments automatically resize when internal animation is added
|
||||
*/
|
||||
updateParentSegmentKeyframes() {
|
||||
const parentObject = this.parentLayer.parentObject;
|
||||
|
||||
// Get the layer that contains this nested object (parentObject.parentLayer)
|
||||
if (!parentObject.parentLayer || !parentObject.parentLayer.animationData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parentLayer = parentObject.parentLayer;
|
||||
|
||||
// Get the frameNumber curve for this nested object using the correct naming convention
|
||||
const curveName = `child.${parentObject.idx}.frameNumber`;
|
||||
const frameNumberCurve = parentLayer.animationData.getCurve(curveName);
|
||||
|
||||
if (!frameNumberCurve || frameNumberCurve.keyframes.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the last keyframe to match the new duration
|
||||
const lastKeyframe = frameNumberCurve.keyframes[frameNumberCurve.keyframes.length - 1];
|
||||
const newFrameValue = Math.ceil(this.duration * config.framerate) + 1; // +1 because frameNumber is 1-indexed
|
||||
const newTime = this.duration;
|
||||
|
||||
// Only update if the time or value actually changed
|
||||
if (lastKeyframe.value !== newFrameValue || lastKeyframe.time !== newTime) {
|
||||
lastKeyframe.value = newFrameValue;
|
||||
lastKeyframe.time = newTime;
|
||||
|
||||
// Re-sort keyframes in case the time change affects order
|
||||
frameNumberCurve.keyframes.sort((a, b) => a.time - b.time);
|
||||
|
||||
// Don't recursively call updateDuration to avoid infinite loop
|
||||
}
|
||||
}
|
||||
|
||||
static fromJSON(json, parentLayer = null) {
|
||||
const animData = new AnimationData(parentLayer, json.idx);
|
||||
for (let param in json.curves || {}) {
|
||||
const curve = AnimationCurve.fromJSON(json.curves[param]);
|
||||
curve.parentAnimationData = animData; // Restore parent reference
|
||||
animData.curves[param] = curve;
|
||||
}
|
||||
// Recalculate duration after loading all curves
|
||||
animData.updateDuration();
|
||||
return animData;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
const curves = {};
|
||||
for (let param in this.curves) {
|
||||
curves[param] = this.curves[param].toJSON();
|
||||
}
|
||||
return {
|
||||
idx: this.idx,
|
||||
curves: curves
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { Frame, TempFrame, tempFrame, Keyframe, AnimationCurve, AnimationData };
|
||||
@@ -0,0 +1,912 @@
|
||||
// GraphicsObject model: Main container for layers and animation
|
||||
|
||||
import { context, config, pointerList, startProps } from '../state.js';
|
||||
import { Layer, AudioTrack } from './layer.js';
|
||||
import { TempShape } from './shapes.js';
|
||||
import { AnimationCurve, Keyframe } from './animation.js';
|
||||
import { Widget } from '../widgets.js';
|
||||
|
||||
// Helper function for UUID generation
|
||||
function uuidv4() {
|
||||
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) =>
|
||||
(
|
||||
+c ^
|
||||
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))
|
||||
).toString(16),
|
||||
);
|
||||
}
|
||||
|
||||
// Forward declarations for dependencies that will be injected
|
||||
let growBoundingBox = null;
|
||||
let getRotatedBoundingBox = null;
|
||||
let multiplyMatrices = null;
|
||||
let uuidToColor = null;
|
||||
|
||||
// Initialize function to be called from main.js
|
||||
export function initializeGraphicsObjectDependencies(deps) {
|
||||
growBoundingBox = deps.growBoundingBox;
|
||||
getRotatedBoundingBox = deps.getRotatedBoundingBox;
|
||||
multiplyMatrices = deps.multiplyMatrices;
|
||||
uuidToColor = deps.uuidToColor;
|
||||
}
|
||||
|
||||
class GraphicsObject extends Widget {
|
||||
constructor(uuid) {
|
||||
super(0, 0)
|
||||
this.rotation = 0; // in radians
|
||||
this.scale_x = 1;
|
||||
this.scale_y = 1;
|
||||
if (!uuid) {
|
||||
this.idx = uuidv4();
|
||||
} else {
|
||||
this.idx = uuid;
|
||||
}
|
||||
pointerList[this.idx] = this;
|
||||
this.name = this.idx;
|
||||
|
||||
this.currentFrameNum = 0; // LEGACY: kept for backwards compatibility
|
||||
this.currentTime = 0; // New: continuous time for AnimationData curves
|
||||
this.currentLayer = 0;
|
||||
this._activeAudioTrack = null; // Reference to active audio track (if any)
|
||||
this.children = [new Layer(uuid + "-L1", this)];
|
||||
// this.layers = [new Layer(uuid + "-L1")];
|
||||
this.audioTracks = [];
|
||||
// this.children = []
|
||||
|
||||
this.shapes = [];
|
||||
|
||||
// Parent reference for nested objects (set when added to a layer)
|
||||
this.parentLayer = null
|
||||
|
||||
// Timeline display settings (Phase 3)
|
||||
this.showSegment = true // Show segment bar in timeline
|
||||
this.curvesMode = 'hidden' // 'hidden' | 'minimized' | 'expanded'
|
||||
this.curvesHeight = 150 // Height in pixels when curves are expanded
|
||||
|
||||
this._globalEvents.add("mousedown")
|
||||
this._globalEvents.add("mousemove")
|
||||
this._globalEvents.add("mouseup")
|
||||
}
|
||||
static fromJSON(json) {
|
||||
const graphicsObject = new GraphicsObject(json.idx);
|
||||
graphicsObject.x = json.x;
|
||||
graphicsObject.y = json.y;
|
||||
graphicsObject.rotation = json.rotation;
|
||||
graphicsObject.scale_x = json.scale_x;
|
||||
graphicsObject.scale_y = json.scale_y;
|
||||
graphicsObject.name = json.name;
|
||||
graphicsObject.currentFrameNum = json.currentFrameNum;
|
||||
graphicsObject.currentLayer = json.currentLayer;
|
||||
graphicsObject.children = [];
|
||||
if (json.parent in pointerList) {
|
||||
graphicsObject.parent = pointerList[json.parent]
|
||||
}
|
||||
for (let layer of json.layers) {
|
||||
graphicsObject.layers.push(Layer.fromJSON(layer, graphicsObject));
|
||||
}
|
||||
// Handle audioTracks (may not exist in older files)
|
||||
if (json.audioTracks) {
|
||||
for (let audioTrack of json.audioTracks) {
|
||||
graphicsObject.audioTracks.push(AudioTrack.fromJSON(audioTrack));
|
||||
}
|
||||
}
|
||||
return graphicsObject;
|
||||
}
|
||||
toJSON(randomizeUuid = false) {
|
||||
const json = {};
|
||||
json.type = "GraphicsObject";
|
||||
json.x = this.x;
|
||||
json.y = this.y;
|
||||
json.rotation = this.rotation;
|
||||
json.scale_x = this.scale_x;
|
||||
json.scale_y = this.scale_y;
|
||||
if (randomizeUuid) {
|
||||
json.idx = uuidv4();
|
||||
json.name = this.name + " copy";
|
||||
} else {
|
||||
json.idx = this.idx;
|
||||
json.name = this.name;
|
||||
}
|
||||
json.currentFrameNum = this.currentFrameNum;
|
||||
json.currentLayer = this.currentLayer;
|
||||
json.layers = [];
|
||||
json.parent = this.parent?.idx
|
||||
for (let layer of this.layers) {
|
||||
json.layers.push(layer.toJSON(randomizeUuid));
|
||||
}
|
||||
json.audioTracks = [];
|
||||
for (let audioTrack of this.audioTracks) {
|
||||
json.audioTracks.push(audioTrack.toJSON(randomizeUuid));
|
||||
}
|
||||
return json;
|
||||
}
|
||||
get activeLayer() {
|
||||
// If an audio track is active, return it instead of a visual layer
|
||||
if (this._activeAudioTrack !== null) {
|
||||
return this._activeAudioTrack;
|
||||
}
|
||||
return this.layers[this.currentLayer];
|
||||
}
|
||||
set activeLayer(layer) {
|
||||
// Allow setting activeLayer to an AudioTrack or a regular Layer
|
||||
if (layer instanceof AudioTrack) {
|
||||
this._activeAudioTrack = layer;
|
||||
} else {
|
||||
// It's a regular layer - find its index and set currentLayer
|
||||
this._activeAudioTrack = null;
|
||||
const layerIndex = this.children.indexOf(layer);
|
||||
if (layerIndex !== -1) {
|
||||
this.currentLayer = layerIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
// get children() {
|
||||
// return this.activeLayer.children;
|
||||
// }
|
||||
get layers() {
|
||||
return this.children
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the total duration of this GraphicsObject's animation
|
||||
* Returns the maximum duration across all layers
|
||||
*/
|
||||
get duration() {
|
||||
let maxDuration = 0;
|
||||
|
||||
// Check visual layers
|
||||
for (let layer of this.layers) {
|
||||
if (layer.animationData && layer.animationData.duration > maxDuration) {
|
||||
maxDuration = layer.animationData.duration;
|
||||
}
|
||||
}
|
||||
|
||||
// Check audio tracks
|
||||
for (let audioTrack of this.audioTracks) {
|
||||
for (let clip of audioTrack.clips) {
|
||||
const clipEnd = clip.startTime + clip.duration;
|
||||
if (clipEnd > maxDuration) {
|
||||
maxDuration = clipEnd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return maxDuration;
|
||||
}
|
||||
get allLayers() {
|
||||
return [...this.audioTracks, ...this.layers];
|
||||
}
|
||||
get maxFrame() {
|
||||
return (
|
||||
Math.max(
|
||||
...this.layers.map((layer) => {
|
||||
return (
|
||||
layer.frames.findLastIndex((frame) => frame !== undefined) || -1
|
||||
);
|
||||
}),
|
||||
) + 1
|
||||
);
|
||||
}
|
||||
get segmentColor() {
|
||||
return uuidToColor(this.idx);
|
||||
}
|
||||
/**
|
||||
* Set the current playback time in seconds
|
||||
*/
|
||||
setTime(time) {
|
||||
time = Math.max(0, time);
|
||||
this.currentTime = time;
|
||||
|
||||
// Update legacy currentFrameNum for any remaining code that needs it
|
||||
this.currentFrameNum = Math.floor(time * config.framerate);
|
||||
|
||||
// Update layer frameNum for legacy code
|
||||
for (let layer of this.layers) {
|
||||
layer.frameNum = this.currentFrameNum;
|
||||
}
|
||||
}
|
||||
|
||||
advanceFrame() {
|
||||
const frameDuration = 1 / config.framerate;
|
||||
this.setTime(this.currentTime + frameDuration);
|
||||
}
|
||||
|
||||
decrementFrame() {
|
||||
const frameDuration = 1 / config.framerate;
|
||||
this.setTime(Math.max(0, this.currentTime - frameDuration));
|
||||
}
|
||||
bbox() {
|
||||
let bbox;
|
||||
|
||||
// NEW: Include shapes from AnimationData system
|
||||
let currentTime = this.currentTime || 0;
|
||||
for (let layer of this.layers) {
|
||||
for (let shape of layer.shapes) {
|
||||
// Check if shape exists at current time
|
||||
let existsValue = layer.animationData.interpolate(`shape.${shape.shapeId}.exists`, currentTime);
|
||||
if (existsValue !== null && existsValue > 0) {
|
||||
if (!bbox) {
|
||||
bbox = structuredClone(shape.boundingBox);
|
||||
} else {
|
||||
growBoundingBox(bbox, shape.boundingBox);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Include children
|
||||
if (this.children.length > 0) {
|
||||
if (!bbox) {
|
||||
bbox = structuredClone(this.children[0].bbox());
|
||||
}
|
||||
for (let child of this.children) {
|
||||
growBoundingBox(bbox, child.bbox());
|
||||
}
|
||||
}
|
||||
|
||||
if (bbox == undefined) {
|
||||
bbox = { x: { min: 0, max: 0 }, y: { min: 0, max: 0 } };
|
||||
}
|
||||
bbox.x.max *= this.scale_x;
|
||||
bbox.y.max *= this.scale_y;
|
||||
bbox.x.min += this.x;
|
||||
bbox.x.max += this.x;
|
||||
bbox.y.min += this.y;
|
||||
bbox.y.max += this.y;
|
||||
return bbox;
|
||||
}
|
||||
|
||||
draw(context, calculateTransform=false) {
|
||||
let ctx = context.ctx;
|
||||
ctx.save();
|
||||
if (calculateTransform) {
|
||||
this.transformCanvas(ctx)
|
||||
} else {
|
||||
ctx.translate(this.x, this.y);
|
||||
ctx.rotate(this.rotation);
|
||||
ctx.scale(this.scale_x, this.scale_y);
|
||||
}
|
||||
// if (this.currentFrameNum>=this.maxFrame) {
|
||||
// this.currentFrameNum = 0;
|
||||
// }
|
||||
if (
|
||||
context.activeAction &&
|
||||
context.activeAction.selection &&
|
||||
this.idx in context.activeAction.selection
|
||||
)
|
||||
return;
|
||||
|
||||
for (let layer of this.layers) {
|
||||
if (context.activeObject == this && !layer.visible) continue;
|
||||
|
||||
// Draw activeShape (shape being drawn in progress) for active layer only
|
||||
if (layer === context.activeLayer && layer.activeShape) {
|
||||
let cxt = {...context};
|
||||
layer.activeShape.draw(cxt);
|
||||
}
|
||||
|
||||
// NEW: Use AnimationData system to draw shapes with shape tweening/morphing
|
||||
let currentTime = this.currentTime || 0;
|
||||
|
||||
// Group shapes by shapeId (multiple Shape objects can share a shapeId for tweening)
|
||||
const shapesByShapeId = new Map();
|
||||
for (let shape of layer.shapes) {
|
||||
if (shape instanceof TempShape) continue;
|
||||
if (!shapesByShapeId.has(shape.shapeId)) {
|
||||
shapesByShapeId.set(shape.shapeId, []);
|
||||
}
|
||||
shapesByShapeId.get(shape.shapeId).push(shape);
|
||||
}
|
||||
|
||||
// Process each logical shape (shapeId) and determine what to draw
|
||||
let visibleShapes = [];
|
||||
for (let [shapeId, shapes] of shapesByShapeId) {
|
||||
// Check if this logical shape exists at current time
|
||||
const existsCurveKey = `shape.${shapeId}.exists`;
|
||||
let existsValue = layer.animationData.interpolate(existsCurveKey, currentTime);
|
||||
|
||||
if (existsValue === null || existsValue <= 0) {
|
||||
console.log(`[Widget.draw] Skipping shape ${shapeId} - not visible`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get z-order
|
||||
let zOrder = layer.animationData.interpolate(`shape.${shapeId}.zOrder`, currentTime);
|
||||
|
||||
// Get shapeIndex curve and surrounding keyframes
|
||||
const shapeIndexCurve = layer.animationData.getCurve(`shape.${shapeId}.shapeIndex`);
|
||||
if (!shapeIndexCurve || !shapeIndexCurve.keyframes || shapeIndexCurve.keyframes.length === 0) {
|
||||
// No shapeIndex curve, just show shape with index 0
|
||||
const shape = shapes.find(s => s.shapeIndex === 0);
|
||||
if (shape) {
|
||||
visibleShapes.push({
|
||||
shape,
|
||||
zOrder: zOrder || 0,
|
||||
selected: context.shapeselection.includes(shape)
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find surrounding keyframes using AnimationCurve's built-in method
|
||||
const { prev: prevKf, next: nextKf, t: interpolationT } = shapeIndexCurve.getBracketingKeyframes(currentTime);
|
||||
|
||||
// Get interpolated value
|
||||
let shapeIndexValue = shapeIndexCurve.interpolate(currentTime);
|
||||
if (shapeIndexValue === null) shapeIndexValue = 0;
|
||||
|
||||
// Sort shape versions by shapeIndex
|
||||
shapes.sort((a, b) => a.shapeIndex - b.shapeIndex);
|
||||
|
||||
// Determine whether to morph based on whether interpolated value equals a keyframe value
|
||||
const atPrevKeyframe = prevKf && Math.abs(shapeIndexValue - prevKf.value) < 0.001;
|
||||
const atNextKeyframe = nextKf && Math.abs(shapeIndexValue - nextKf.value) < 0.001;
|
||||
|
||||
if (atPrevKeyframe || atNextKeyframe) {
|
||||
// No morphing - display the shape at the keyframe value
|
||||
const targetValue = atNextKeyframe ? nextKf.value : prevKf.value;
|
||||
const shape = shapes.find(s => s.shapeIndex === targetValue);
|
||||
if (shape) {
|
||||
visibleShapes.push({
|
||||
shape,
|
||||
zOrder: zOrder || 0,
|
||||
selected: context.shapeselection.includes(shape)
|
||||
});
|
||||
}
|
||||
} else if (prevKf && nextKf && prevKf.value !== nextKf.value) {
|
||||
// Morph between shapes specified by surrounding keyframes
|
||||
const shape1 = shapes.find(s => s.shapeIndex === prevKf.value);
|
||||
const shape2 = shapes.find(s => s.shapeIndex === nextKf.value);
|
||||
|
||||
if (shape1 && shape2) {
|
||||
// Use the interpolated shapeIndexValue to calculate blend factor
|
||||
// This respects the bezier easing curve
|
||||
const t = (shapeIndexValue - prevKf.value) / (nextKf.value - prevKf.value);
|
||||
console.log(`[Widget.draw] Morphing from shape ${prevKf.value} to ${nextKf.value}, shapeIndexValue=${shapeIndexValue}, t=${t}`);
|
||||
const morphedShape = shape1.lerpShape(shape2, t);
|
||||
visibleShapes.push({
|
||||
shape: morphedShape,
|
||||
zOrder: zOrder || 0,
|
||||
selected: context.shapeselection.includes(shape1) || context.shapeselection.includes(shape2)
|
||||
});
|
||||
} else if (shape1) {
|
||||
visibleShapes.push({
|
||||
shape: shape1,
|
||||
zOrder: zOrder || 0,
|
||||
selected: context.shapeselection.includes(shape1)
|
||||
});
|
||||
} else if (shape2) {
|
||||
visibleShapes.push({
|
||||
shape: shape2,
|
||||
zOrder: zOrder || 0,
|
||||
selected: context.shapeselection.includes(shape2)
|
||||
});
|
||||
}
|
||||
} else if (nextKf) {
|
||||
// Only next keyframe exists, show that shape
|
||||
const shape = shapes.find(s => s.shapeIndex === nextKf.value);
|
||||
if (shape) {
|
||||
visibleShapes.push({
|
||||
shape,
|
||||
zOrder: zOrder || 0,
|
||||
selected: context.shapeselection.includes(shape)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by zOrder
|
||||
visibleShapes.sort((a, b) => a.zOrder - b.zOrder);
|
||||
|
||||
// Draw sorted shapes
|
||||
for (let { shape, selected } of visibleShapes) {
|
||||
let cxt = {...context}
|
||||
if (selected) {
|
||||
cxt.selected = true
|
||||
}
|
||||
shape.draw(cxt);
|
||||
}
|
||||
|
||||
// Draw child objects using AnimationData curves
|
||||
for (let child of layer.children) {
|
||||
if (child == context.activeObject) continue;
|
||||
let idx = child.idx;
|
||||
|
||||
// Use AnimationData to get child's transform
|
||||
let childX = layer.animationData.interpolate(`child.${idx}.x`, currentTime);
|
||||
let childY = layer.animationData.interpolate(`child.${idx}.y`, currentTime);
|
||||
let childRotation = layer.animationData.interpolate(`child.${idx}.rotation`, currentTime);
|
||||
let childScaleX = layer.animationData.interpolate(`child.${idx}.scale_x`, currentTime);
|
||||
let childScaleY = layer.animationData.interpolate(`child.${idx}.scale_y`, currentTime);
|
||||
let childFrameNumber = layer.animationData.interpolate(`child.${idx}.frameNumber`, currentTime);
|
||||
|
||||
if (childX !== null && childY !== null) {
|
||||
child.x = childX;
|
||||
child.y = childY;
|
||||
child.rotation = childRotation || 0;
|
||||
child.scale_x = childScaleX || 1;
|
||||
child.scale_y = childScaleY || 1;
|
||||
|
||||
// Set child's currentTime based on its frameNumber
|
||||
// frameNumber 1 = time 0, frameNumber 2 = time 1/framerate, etc.
|
||||
if (childFrameNumber !== null) {
|
||||
child.currentTime = (childFrameNumber - 1) / config.framerate;
|
||||
}
|
||||
|
||||
ctx.save();
|
||||
child.draw(context);
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this == context.activeObject) {
|
||||
// Draw selection rectangles for selected items
|
||||
if (context.mode == "select") {
|
||||
for (let item of context.selection) {
|
||||
if (!item) continue;
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
let bbox = getRotatedBoundingBox(item);
|
||||
ctx.rect(
|
||||
bbox.x.min,
|
||||
bbox.y.min,
|
||||
bbox.x.max - bbox.x.min,
|
||||
bbox.y.max - bbox.y.min,
|
||||
);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
// Draw drag selection rectangle
|
||||
if (context.selectionRect) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.rect(
|
||||
context.selectionRect.x1,
|
||||
context.selectionRect.y1,
|
||||
context.selectionRect.x2 - context.selectionRect.x1,
|
||||
context.selectionRect.y2 - context.selectionRect.y1,
|
||||
);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
} else if (context.mode == "transform") {
|
||||
let bbox = undefined;
|
||||
for (let item of context.selection) {
|
||||
if (bbox == undefined) {
|
||||
bbox = getRotatedBoundingBox(item);
|
||||
} else {
|
||||
growBoundingBox(bbox, getRotatedBoundingBox(item));
|
||||
}
|
||||
}
|
||||
if (bbox != undefined) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
let xdiff = bbox.x.max - bbox.x.min;
|
||||
let ydiff = bbox.y.max - bbox.y.min;
|
||||
ctx.rect(bbox.x.min, bbox.y.min, xdiff, ydiff);
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = "#000000";
|
||||
let rectRadius = 5;
|
||||
for (let i of [
|
||||
[0, 0],
|
||||
[0.5, 0],
|
||||
[1, 0],
|
||||
[1, 0.5],
|
||||
[1, 1],
|
||||
[0.5, 1],
|
||||
[0, 1],
|
||||
[0, 0.5],
|
||||
]) {
|
||||
ctx.beginPath();
|
||||
ctx.rect(
|
||||
bbox.x.min + xdiff * i[0] - rectRadius,
|
||||
bbox.y.min + ydiff * i[1] - rectRadius,
|
||||
rectRadius * 2,
|
||||
rectRadius * 2,
|
||||
);
|
||||
ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
if (context.activeCurve) {
|
||||
ctx.strokeStyle = "magenta";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(
|
||||
context.activeCurve.current.points[0].x,
|
||||
context.activeCurve.current.points[0].y,
|
||||
);
|
||||
ctx.bezierCurveTo(
|
||||
context.activeCurve.current.points[1].x,
|
||||
context.activeCurve.current.points[1].y,
|
||||
context.activeCurve.current.points[2].x,
|
||||
context.activeCurve.current.points[2].y,
|
||||
context.activeCurve.current.points[3].x,
|
||||
context.activeCurve.current.points[3].y,
|
||||
);
|
||||
ctx.stroke();
|
||||
}
|
||||
if (context.activeVertex) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
let curves = {
|
||||
...context.activeVertex.current.startCurves,
|
||||
...context.activeVertex.current.endCurves,
|
||||
};
|
||||
// I don't understand why I can't use a for...of loop here
|
||||
for (let idx in curves) {
|
||||
let curve = curves[idx];
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(curve.points[0].x, curve.points[0].y);
|
||||
ctx.bezierCurveTo(
|
||||
curve.points[1].x,
|
||||
curve.points[1].y,
|
||||
curve.points[2].x,
|
||||
curve.points[2].y,
|
||||
curve.points[3].x,
|
||||
curve.points[3].y,
|
||||
);
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.fillStyle = "#000000aa";
|
||||
ctx.beginPath();
|
||||
let vertexSize = 15 / context.zoomLevel;
|
||||
ctx.rect(
|
||||
context.activeVertex.current.point.x - vertexSize / 2,
|
||||
context.activeVertex.current.point.y - vertexSize / 2,
|
||||
vertexSize,
|
||||
vertexSize,
|
||||
);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
/*
|
||||
draw(ctx) {
|
||||
super.draw(ctx)
|
||||
if (this==context.activeObject) {
|
||||
if (context.mode == "select") {
|
||||
for (let item of context.selection) {
|
||||
if (!item) continue;
|
||||
// Check if this is a child object and if it exists at current time
|
||||
if (item.idx) {
|
||||
const existsValue = this.activeLayer.animationData.interpolate(
|
||||
`object.${item.idx}.exists`,
|
||||
this.currentTime
|
||||
);
|
||||
if (existsValue === null || existsValue <= 0) continue;
|
||||
}
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
let bbox = getRotatedBoundingBox(item);
|
||||
ctx.rect(
|
||||
bbox.x.min,
|
||||
bbox.y.min,
|
||||
bbox.x.max - bbox.x.min,
|
||||
bbox.y.max - bbox.y.min,
|
||||
);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
if (context.selectionRect) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.rect(
|
||||
context.selectionRect.x1,
|
||||
context.selectionRect.y1,
|
||||
context.selectionRect.x2 - context.selectionRect.x1,
|
||||
context.selectionRect.y2 - context.selectionRect.y1,
|
||||
);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
} else if (context.mode == "transform") {
|
||||
let bbox = undefined;
|
||||
for (let item of context.selection) {
|
||||
if (bbox == undefined) {
|
||||
bbox = getRotatedBoundingBox(item);
|
||||
} else {
|
||||
growBoundingBox(bbox, getRotatedBoundingBox(item));
|
||||
}
|
||||
}
|
||||
if (bbox != undefined) {
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "#00ffff";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
let xdiff = bbox.x.max - bbox.x.min;
|
||||
let ydiff = bbox.y.max - bbox.y.min;
|
||||
ctx.rect(bbox.x.min, bbox.y.min, xdiff, ydiff);
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = "#000000";
|
||||
let rectRadius = 5;
|
||||
for (let i of [
|
||||
[0, 0],
|
||||
[0.5, 0],
|
||||
[1, 0],
|
||||
[1, 0.5],
|
||||
[1, 1],
|
||||
[0.5, 1],
|
||||
[0, 1],
|
||||
[0, 0.5],
|
||||
]) {
|
||||
ctx.beginPath();
|
||||
ctx.rect(
|
||||
bbox.x.min + xdiff * i[0] - rectRadius,
|
||||
bbox.y.min + ydiff * i[1] - rectRadius,
|
||||
rectRadius * 2,
|
||||
rectRadius * 2,
|
||||
);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
transformCanvas(ctx) {
|
||||
if (this.parent) {
|
||||
this.parent.transformCanvas(ctx)
|
||||
}
|
||||
ctx.translate(this.x, this.y);
|
||||
ctx.scale(this.scale_x, this.scale_y);
|
||||
ctx.rotate(this.rotation);
|
||||
}
|
||||
transformMouse(mouse) {
|
||||
// Apply the transformation matrix to the mouse position
|
||||
let matrix = this.generateTransformMatrix();
|
||||
let { x, y } = mouse;
|
||||
|
||||
return {
|
||||
x: matrix[0][0] * x + matrix[0][1] * y + matrix[0][2],
|
||||
y: matrix[1][0] * x + matrix[1][1] * y + matrix[1][2]
|
||||
};
|
||||
}
|
||||
generateTransformMatrix() {
|
||||
// Start with the parent's transform matrix if it exists
|
||||
let parentMatrix = this.parent ? this.parent.generateTransformMatrix() : [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
|
||||
|
||||
// Calculate the rotation matrix components
|
||||
const cos = Math.cos(this.rotation);
|
||||
const sin = Math.sin(this.rotation);
|
||||
|
||||
// Scaling matrix
|
||||
const scaleMatrix = [
|
||||
[1/this.scale_x, 0, 0],
|
||||
[0, 1/this.scale_y, 0],
|
||||
[0, 0, 1]
|
||||
];
|
||||
|
||||
// Rotation matrix (inverse rotation for transforming back)
|
||||
const rotationMatrix = [
|
||||
[cos, -sin, 0],
|
||||
[sin, cos, 0],
|
||||
[0, 0, 1]
|
||||
];
|
||||
|
||||
// Translation matrix (inverse translation to adjust for object's position)
|
||||
const translationMatrix = [
|
||||
[1, 0, -this.x],
|
||||
[0, 1, -this.y],
|
||||
[0, 0, 1]
|
||||
];
|
||||
|
||||
// Multiply translation * rotation * scaling to get the current object's final transformation matrix
|
||||
let tempMatrix = multiplyMatrices(translationMatrix, rotationMatrix);
|
||||
let objectMatrix = multiplyMatrices(tempMatrix, scaleMatrix);
|
||||
|
||||
// Now combine with the parent's matrix (parent * object)
|
||||
let finalMatrix = multiplyMatrices(parentMatrix, objectMatrix);
|
||||
|
||||
return finalMatrix;
|
||||
}
|
||||
handleMouseEvent(eventType, x, y) {
|
||||
for (let i in this.layers) {
|
||||
if (i==this.currentLayer) {
|
||||
this.layers[i]._globalEvents.add("mousedown")
|
||||
this.layers[i]._globalEvents.add("mousemove")
|
||||
this.layers[i]._globalEvents.add("mouseup")
|
||||
} else {
|
||||
this.layers[i]._globalEvents.delete("mousedown")
|
||||
this.layers[i]._globalEvents.delete("mousemove")
|
||||
this.layers[i]._globalEvents.delete("mouseup")
|
||||
}
|
||||
}
|
||||
super.handleMouseEvent(eventType, x, y)
|
||||
}
|
||||
addObject(object, x = 0, y = 0, time = undefined, layer=undefined) {
|
||||
if (time == undefined) {
|
||||
time = this.currentTime || 0;
|
||||
}
|
||||
if (layer==undefined) {
|
||||
layer = this.activeLayer
|
||||
}
|
||||
|
||||
layer.children.push(object)
|
||||
object.parent = this;
|
||||
object.parentLayer = layer;
|
||||
object.x = x;
|
||||
object.y = y;
|
||||
let idx = object.idx;
|
||||
|
||||
// Add animation curves for the object's position/transform in the layer
|
||||
let xCurve = new AnimationCurve(`child.${idx}.x`);
|
||||
xCurve.addKeyframe(new Keyframe(time, x, 'linear'));
|
||||
layer.animationData.setCurve(`child.${idx}.x`, xCurve);
|
||||
|
||||
let yCurve = new AnimationCurve(`child.${idx}.y`);
|
||||
yCurve.addKeyframe(new Keyframe(time, y, 'linear'));
|
||||
layer.animationData.setCurve(`child.${idx}.y`, yCurve);
|
||||
|
||||
let rotationCurve = new AnimationCurve(`child.${idx}.rotation`);
|
||||
rotationCurve.addKeyframe(new Keyframe(time, 0, 'linear'));
|
||||
layer.animationData.setCurve(`child.${idx}.rotation`, rotationCurve);
|
||||
|
||||
let scaleXCurve = new AnimationCurve(`child.${idx}.scale_x`);
|
||||
scaleXCurve.addKeyframe(new Keyframe(time, 1, 'linear'));
|
||||
layer.animationData.setCurve(`child.${idx}.scale_x`, scaleXCurve);
|
||||
|
||||
let scaleYCurve = new AnimationCurve(`child.${idx}.scale_y`);
|
||||
scaleYCurve.addKeyframe(new Keyframe(time, 1, 'linear'));
|
||||
layer.animationData.setCurve(`child.${idx}.scale_y`, scaleYCurve);
|
||||
|
||||
// Add exists curve (object visibility)
|
||||
let existsCurve = new AnimationCurve(`object.${idx}.exists`);
|
||||
existsCurve.addKeyframe(new Keyframe(time, 1, 'hold'));
|
||||
layer.animationData.setCurve(`object.${idx}.exists`, existsCurve);
|
||||
|
||||
// Initialize frameNumber curve with two keyframes defining the segment
|
||||
// The segment length is based on the object's internal animation duration
|
||||
let frameNumberCurve = new AnimationCurve(`child.${idx}.frameNumber`);
|
||||
|
||||
// Get the object's animation duration (max time across all its layers)
|
||||
const objectDuration = object.duration || 0;
|
||||
const framerate = config.framerate;
|
||||
|
||||
// Calculate the last frame number (frameNumber 1 = time 0, so add 1)
|
||||
const lastFrameNumber = Math.max(1, Math.ceil(objectDuration * framerate) + 1);
|
||||
|
||||
// Calculate the end time for the segment (minimum 1 frame duration)
|
||||
const segmentDuration = Math.max(objectDuration, 1 / framerate);
|
||||
const endTime = time + segmentDuration;
|
||||
|
||||
// Start keyframe: frameNumber 1 at the current time, linear interpolation
|
||||
frameNumberCurve.addKeyframe(new Keyframe(time, 1, 'linear'));
|
||||
|
||||
// End keyframe: last frame at end time, zero interpolation (inactive after this)
|
||||
frameNumberCurve.addKeyframe(new Keyframe(endTime, lastFrameNumber, 'zero'));
|
||||
|
||||
layer.animationData.setCurve(`child.${idx}.frameNumber`, frameNumberCurve);
|
||||
}
|
||||
removeChild(childObject) {
|
||||
let idx = childObject.idx;
|
||||
for (let layer of this.layers) {
|
||||
layer.children = layer.children.filter(child => child.idx !== idx);
|
||||
for (let frame of layer.frames) {
|
||||
if (frame) {
|
||||
delete frame[idx];
|
||||
}
|
||||
}
|
||||
}
|
||||
// this.children.splice(this.children.indexOf(childObject), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update this object's frameNumber curve in its parent layer based on child content
|
||||
* This is called when shapes/children are added/modified within this object
|
||||
*/
|
||||
updateFrameNumberCurve() {
|
||||
// Find parent layer that contains this object
|
||||
if (!this.parent || !this.parent.animationData) return;
|
||||
|
||||
const parentLayer = this.parent;
|
||||
const frameNumberKey = `child.${this.idx}.frameNumber`;
|
||||
|
||||
// Collect all keyframe times from this object's content
|
||||
let allKeyframeTimes = new Set();
|
||||
|
||||
// Check all layers in this object
|
||||
for (let layer of this.layers) {
|
||||
if (!layer.animationData) continue;
|
||||
|
||||
// Get keyframes from all shape curves
|
||||
for (let shape of layer.shapes) {
|
||||
const existsKey = `shape.${shape.shapeId}.exists`;
|
||||
const existsCurve = layer.animationData.curves[existsKey];
|
||||
if (existsCurve && existsCurve.keyframes) {
|
||||
for (let kf of existsCurve.keyframes) {
|
||||
allKeyframeTimes.add(kf.time);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get keyframes from all child object curves
|
||||
for (let child of layer.children) {
|
||||
const childFrameNumberKey = `child.${child.idx}.frameNumber`;
|
||||
const childFrameNumberCurve = layer.animationData.curves[childFrameNumberKey];
|
||||
if (childFrameNumberCurve && childFrameNumberCurve.keyframes) {
|
||||
for (let kf of childFrameNumberCurve.keyframes) {
|
||||
allKeyframeTimes.add(kf.time);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (allKeyframeTimes.size === 0) return;
|
||||
|
||||
// Sort times
|
||||
const times = Array.from(allKeyframeTimes).sort((a, b) => a - b);
|
||||
const firstTime = times[0];
|
||||
const lastTime = times[times.length - 1];
|
||||
|
||||
// Calculate frame numbers (1-based)
|
||||
const framerate = this.framerate || 24;
|
||||
const firstFrame = Math.floor(firstTime * framerate) + 1;
|
||||
const lastFrame = Math.floor(lastTime * framerate) + 1;
|
||||
|
||||
// Update or create frameNumber curve in parent layer
|
||||
let frameNumberCurve = parentLayer.animationData.curves[frameNumberKey];
|
||||
if (!frameNumberCurve) {
|
||||
frameNumberCurve = new AnimationCurve(frameNumberKey);
|
||||
parentLayer.animationData.setCurve(frameNumberKey, frameNumberCurve);
|
||||
}
|
||||
|
||||
// Clear existing keyframes and add new ones
|
||||
frameNumberCurve.keyframes = [];
|
||||
frameNumberCurve.addKeyframe(new Keyframe(firstTime, firstFrame, 'hold'));
|
||||
frameNumberCurve.addKeyframe(new Keyframe(lastTime, lastFrame, 'hold'));
|
||||
}
|
||||
|
||||
addLayer(layer) {
|
||||
this.children.push(layer);
|
||||
}
|
||||
removeLayer(layer) {
|
||||
this.children.splice(this.children.indexOf(layer), 1);
|
||||
}
|
||||
saveState() {
|
||||
startProps[this.idx] = {
|
||||
x: this.x,
|
||||
y: this.y,
|
||||
rotation: this.rotation,
|
||||
scale_x: this.scale_x,
|
||||
scale_y: this.scale_y,
|
||||
};
|
||||
}
|
||||
copy(idx) {
|
||||
let newGO = new GraphicsObject(idx.slice(0, 8) + this.idx.slice(8));
|
||||
newGO.x = this.x;
|
||||
newGO.y = this.y;
|
||||
newGO.rotation = this.rotation;
|
||||
newGO.scale_x = this.scale_x;
|
||||
newGO.scale_y = this.scale_y;
|
||||
newGO.parent = this.parent;
|
||||
pointerList[this.idx] = this;
|
||||
|
||||
newGO.layers = [];
|
||||
for (let layer of this.layers) {
|
||||
newGO.layers.push(layer.copy(idx));
|
||||
}
|
||||
for (let audioTrack of this.audioTracks) {
|
||||
newGO.audioTracks.push(audioTrack.copy(idx));
|
||||
}
|
||||
|
||||
return newGO;
|
||||
}
|
||||
}
|
||||
|
||||
export { GraphicsObject };
|
||||
+1213
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
// Root object initialization
|
||||
// Creates and configures the root GraphicsObject and context properties
|
||||
|
||||
import { context } from '../state.js';
|
||||
import { GraphicsObject } from './graphics-object.js';
|
||||
|
||||
/**
|
||||
* Creates and initializes the root GraphicsObject.
|
||||
* Sets up context properties for active object and layer access.
|
||||
*
|
||||
* @returns {GraphicsObject} The root graphics object
|
||||
*/
|
||||
export function createRoot() {
|
||||
const root = new GraphicsObject("root");
|
||||
|
||||
// Define getter for active object (top of stack)
|
||||
Object.defineProperty(context, "activeObject", {
|
||||
get: function () {
|
||||
return this.objectStack.at(-1);
|
||||
},
|
||||
});
|
||||
|
||||
// Define getter for active layer (active layer of top object)
|
||||
Object.defineProperty(context, "activeLayer", {
|
||||
get: function () {
|
||||
return this.objectStack.at(-1).activeLayer;
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize object stack with root
|
||||
context.objectStack = [root];
|
||||
|
||||
return root;
|
||||
}
|
||||
@@ -0,0 +1,752 @@
|
||||
// Shape models: BaseShape, TempShape, Shape
|
||||
|
||||
import { context, pointerList } from '../state.js';
|
||||
import { Bezier } from '../bezier.js';
|
||||
import { Quadtree } from '../quadtree.js';
|
||||
|
||||
// Helper function for UUID generation
|
||||
function uuidv4() {
|
||||
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) =>
|
||||
(
|
||||
+c ^
|
||||
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))
|
||||
).toString(16),
|
||||
);
|
||||
}
|
||||
|
||||
// Forward declarations for dependencies that will be injected
|
||||
let growBoundingBox = null;
|
||||
let lerp = null;
|
||||
let lerpColor = null;
|
||||
let uuidToColor = null;
|
||||
let simplifyPolyline = null;
|
||||
let fitCurve = null;
|
||||
let createMissingTexturePattern = null;
|
||||
let debugQuadtree = null;
|
||||
let d3 = null;
|
||||
|
||||
// Initialize function to be called from main.js
|
||||
export function initializeShapeDependencies(deps) {
|
||||
growBoundingBox = deps.growBoundingBox;
|
||||
lerp = deps.lerp;
|
||||
lerpColor = deps.lerpColor;
|
||||
uuidToColor = deps.uuidToColor;
|
||||
simplifyPolyline = deps.simplifyPolyline;
|
||||
fitCurve = deps.fitCurve;
|
||||
createMissingTexturePattern = deps.createMissingTexturePattern;
|
||||
debugQuadtree = deps.debugQuadtree;
|
||||
d3 = deps.d3;
|
||||
}
|
||||
|
||||
class BaseShape {
|
||||
constructor(startx, starty) {
|
||||
this.startx = startx;
|
||||
this.starty = starty;
|
||||
this.curves = [];
|
||||
this.regions = [];
|
||||
this.boundingBox = {
|
||||
x: { min: startx, max: starty },
|
||||
y: { min: starty, max: starty },
|
||||
};
|
||||
}
|
||||
recalculateBoundingBox() {
|
||||
this.boundingBox = undefined;
|
||||
for (let curve of this.curves) {
|
||||
if (!this.boundingBox) {
|
||||
this.boundingBox = curve.bbox();
|
||||
}
|
||||
growBoundingBox(this.boundingBox, curve.bbox());
|
||||
}
|
||||
}
|
||||
draw(context) {
|
||||
let ctx = context.ctx;
|
||||
ctx.lineWidth = this.lineWidth;
|
||||
ctx.lineCap = "round";
|
||||
|
||||
// Create a repeating pattern for indicating selected shapes
|
||||
if (!this.patternCanvas) {
|
||||
this.patternCanvas = document.createElement('canvas');
|
||||
this.patternCanvas.width = 2;
|
||||
this.patternCanvas.height = 2;
|
||||
let patternCtx = this.patternCanvas.getContext('2d');
|
||||
// Draw the pattern:
|
||||
// black, transparent,
|
||||
// transparent, white
|
||||
patternCtx.fillStyle = 'black';
|
||||
patternCtx.fillRect(0, 0, 1, 1);
|
||||
patternCtx.clearRect(1, 0, 1, 1);
|
||||
patternCtx.clearRect(0, 1, 1, 1);
|
||||
patternCtx.fillStyle = 'white';
|
||||
patternCtx.fillRect(1, 1, 1, 1);
|
||||
}
|
||||
let pattern = ctx.createPattern(this.patternCanvas, 'repeat'); // repeat the pattern across the canvas
|
||||
|
||||
if (this.filled) {
|
||||
ctx.beginPath();
|
||||
if (this.fillImage && this.fillImage instanceof Element) {
|
||||
let pat;
|
||||
if (this.fillImage instanceof Element ||
|
||||
Object.keys(this.fillImage).length !== 0) {
|
||||
pat = ctx.createPattern(this.fillImage, "no-repeat");
|
||||
} else {
|
||||
pat = createMissingTexturePattern(ctx)
|
||||
}
|
||||
ctx.fillStyle = pat;
|
||||
} else {
|
||||
ctx.fillStyle = this.fillStyle;
|
||||
}
|
||||
if (context.debugColor) {
|
||||
ctx.fillStyle = context.debugColor;
|
||||
}
|
||||
if (this.curves.length > 0) {
|
||||
ctx.moveTo(this.curves[0].points[0].x, this.curves[0].points[0].y);
|
||||
for (let curve of this.curves) {
|
||||
ctx.bezierCurveTo(
|
||||
curve.points[1].x,
|
||||
curve.points[1].y,
|
||||
curve.points[2].x,
|
||||
curve.points[2].y,
|
||||
curve.points[3].x,
|
||||
curve.points[3].y,
|
||||
);
|
||||
}
|
||||
}
|
||||
ctx.fill();
|
||||
if (context.selected) {
|
||||
ctx.fillStyle = pattern
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
function drawCurve(curve, selected) {
|
||||
ctx.strokeStyle = curve.color;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(curve.points[0].x, curve.points[0].y);
|
||||
ctx.bezierCurveTo(
|
||||
curve.points[1].x,
|
||||
curve.points[1].y,
|
||||
curve.points[2].x,
|
||||
curve.points[2].y,
|
||||
curve.points[3].x,
|
||||
curve.points[3].y,
|
||||
);
|
||||
ctx.stroke();
|
||||
if (selected) {
|
||||
ctx.strokeStyle = pattern
|
||||
ctx.stroke()
|
||||
}
|
||||
}
|
||||
if (this.stroked && !context.debugColor) {
|
||||
for (let curve of this.curves) {
|
||||
drawCurve(curve, context.selected)
|
||||
|
||||
// // Debug, show curve control points
|
||||
// ctx.beginPath()
|
||||
// ctx.arc(curve.points[1].x,curve.points[1].y, 5, 0, 2*Math.PI)
|
||||
// ctx.arc(curve.points[2].x,curve.points[2].y, 5, 0, 2*Math.PI)
|
||||
// ctx.arc(curve.points[3].x,curve.points[3].y, 5, 0, 2*Math.PI)
|
||||
// ctx.fill()
|
||||
}
|
||||
}
|
||||
if (context.activeCurve && this==context.activeCurve.shape) {
|
||||
drawCurve(context.activeCurve.current, true)
|
||||
}
|
||||
if (context.activeVertex && this==context.activeVertex.shape) {
|
||||
const curves = {
|
||||
...context.activeVertex.current.startCurves,
|
||||
...context.activeVertex.current.endCurves
|
||||
}
|
||||
for (let i in curves) {
|
||||
let curve = curves[i]
|
||||
drawCurve(curve, true)
|
||||
}
|
||||
ctx.fillStyle = "#000000aa";
|
||||
ctx.beginPath();
|
||||
let vertexSize = 15 / context.zoomLevel;
|
||||
ctx.rect(
|
||||
context.activeVertex.current.point.x - vertexSize / 2,
|
||||
context.activeVertex.current.point.y - vertexSize / 2,
|
||||
vertexSize,
|
||||
vertexSize,
|
||||
);
|
||||
ctx.fill();
|
||||
}
|
||||
// Debug, show quadtree
|
||||
if (debugQuadtree && this.quadtree && !context.debugColor) {
|
||||
this.quadtree.draw(ctx);
|
||||
}
|
||||
}
|
||||
lerpShape(shape2, t) {
|
||||
if (this.curves.length == 0) return this;
|
||||
let path1 = [
|
||||
{
|
||||
type: "M",
|
||||
x: this.curves[0].points[0].x,
|
||||
y: this.curves[0].points[0].y,
|
||||
},
|
||||
];
|
||||
for (let curve of this.curves) {
|
||||
path1.push({
|
||||
type: "C",
|
||||
x1: curve.points[1].x,
|
||||
y1: curve.points[1].y,
|
||||
x2: curve.points[2].x,
|
||||
y2: curve.points[2].y,
|
||||
x: curve.points[3].x,
|
||||
y: curve.points[3].y,
|
||||
});
|
||||
}
|
||||
let path2 = [];
|
||||
if (shape2.curves.length > 0) {
|
||||
path2.push({
|
||||
type: "M",
|
||||
x: shape2.curves[0].points[0].x,
|
||||
y: shape2.curves[0].points[0].y,
|
||||
});
|
||||
for (let curve of shape2.curves) {
|
||||
path2.push({
|
||||
type: "C",
|
||||
x1: curve.points[1].x,
|
||||
y1: curve.points[1].y,
|
||||
x2: curve.points[2].x,
|
||||
y2: curve.points[2].y,
|
||||
x: curve.points[3].x,
|
||||
y: curve.points[3].y,
|
||||
});
|
||||
}
|
||||
}
|
||||
const interpolator = d3.interpolatePathCommands(path1, path2);
|
||||
let current = interpolator(t);
|
||||
let curves = [];
|
||||
let start = current.shift();
|
||||
let { x, y } = start;
|
||||
let bezier;
|
||||
for (let curve of current) {
|
||||
bezier = new Bezier(
|
||||
x,
|
||||
y,
|
||||
curve.x1,
|
||||
curve.y1,
|
||||
curve.x2,
|
||||
curve.y2,
|
||||
curve.x,
|
||||
curve.y,
|
||||
)
|
||||
bezier.color = lerpColor(this.strokeStyle, shape2.strokeStyle)
|
||||
curves.push(bezier);
|
||||
x = curve.x;
|
||||
y = curve.y;
|
||||
}
|
||||
let lineWidth = lerp(this.lineWidth, shape2.lineWidth, t);
|
||||
let strokeStyle = lerpColor(
|
||||
this.strokeStyle,
|
||||
shape2.strokeStyle,
|
||||
t,
|
||||
);
|
||||
let fillStyle;
|
||||
if (!this.fillImage) {
|
||||
fillStyle = lerpColor(this.fillStyle, shape2.fillStyle, t);
|
||||
}
|
||||
return new TempShape(
|
||||
start.x,
|
||||
start.y,
|
||||
curves,
|
||||
lineWidth,
|
||||
this.stroked,
|
||||
this.filled,
|
||||
strokeStyle,
|
||||
fillStyle,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class TempShape extends BaseShape {
|
||||
constructor(
|
||||
startx,
|
||||
starty,
|
||||
curves,
|
||||
lineWidth,
|
||||
stroked,
|
||||
filled,
|
||||
strokeStyle,
|
||||
fillStyle,
|
||||
) {
|
||||
super(startx, starty);
|
||||
this.curves = curves;
|
||||
this.lineWidth = lineWidth;
|
||||
this.stroked = stroked;
|
||||
this.filled = filled;
|
||||
this.strokeStyle = strokeStyle;
|
||||
this.fillStyle = fillStyle;
|
||||
this.inProgress = false;
|
||||
this.recalculateBoundingBox();
|
||||
}
|
||||
}
|
||||
|
||||
class Shape extends BaseShape {
|
||||
constructor(startx, starty, context, parent, uuid = undefined, shapeId = undefined) {
|
||||
super(startx, starty);
|
||||
this.parent = parent; // Reference to parent Layer (required)
|
||||
this.vertices = [];
|
||||
this.triangles = [];
|
||||
this.fillStyle = context.fillStyle;
|
||||
this.fillImage = context.fillImage;
|
||||
this.strokeStyle = context.strokeStyle;
|
||||
this.lineWidth = context.lineWidth;
|
||||
this.filled = context.fillShape;
|
||||
this.stroked = context.strokeShape;
|
||||
this.quadtree = new Quadtree(
|
||||
{ x: { min: 0, max: 500 }, y: { min: 0, max: 500 } },
|
||||
4,
|
||||
);
|
||||
if (!uuid) {
|
||||
this.idx = uuidv4();
|
||||
} else {
|
||||
this.idx = uuid;
|
||||
}
|
||||
if (!shapeId) {
|
||||
this.shapeId = uuidv4();
|
||||
} else {
|
||||
this.shapeId = shapeId;
|
||||
}
|
||||
this.shapeIndex = 0; // Default shape version index for tweening
|
||||
pointerList[this.idx] = this;
|
||||
this.regionIdx = 0;
|
||||
this.inProgress = true;
|
||||
|
||||
// Timeline display settings (Phase 3)
|
||||
this.showSegment = true // Show segment bar in timeline
|
||||
this.curvesMode = 'hidden' // 'hidden' | 'minimized' | 'expanded'
|
||||
this.curvesHeight = 150 // Height in pixels when curves are expanded
|
||||
}
|
||||
static fromJSON(json, parent) {
|
||||
let fillImage = undefined;
|
||||
if (json.fillImage && Object.keys(json.fillImage).length !== 0) {
|
||||
let img = new Image();
|
||||
img.src = json.fillImage.src
|
||||
fillImage = img
|
||||
} else {
|
||||
fillImage = {}
|
||||
}
|
||||
const shape = new Shape(
|
||||
json.startx,
|
||||
json.starty,
|
||||
{
|
||||
fillStyle: json.fillStyle,
|
||||
fillImage: fillImage,
|
||||
strokeStyle: json.strokeStyle,
|
||||
lineWidth: json.lineWidth,
|
||||
fillShape: json.filled,
|
||||
strokeShape: json.stroked,
|
||||
},
|
||||
parent,
|
||||
json.idx,
|
||||
json.shapeId,
|
||||
);
|
||||
for (let curve of json.curves) {
|
||||
shape.addCurve(Bezier.fromJSON(curve));
|
||||
}
|
||||
for (let region of json.regions) {
|
||||
const curves = [];
|
||||
for (let curve of region.curves) {
|
||||
curves.push(Bezier.fromJSON(curve));
|
||||
}
|
||||
shape.regions.push({
|
||||
idx: region.idx,
|
||||
curves: curves,
|
||||
fillStyle: region.fillStyle,
|
||||
filled: region.filled,
|
||||
});
|
||||
}
|
||||
// Load shapeIndex if present (for shape tweening)
|
||||
if (json.shapeIndex !== undefined) {
|
||||
shape.shapeIndex = json.shapeIndex;
|
||||
}
|
||||
return shape;
|
||||
}
|
||||
toJSON(randomizeUuid = false) {
|
||||
const json = {};
|
||||
json.type = "Shape";
|
||||
json.startx = this.startx;
|
||||
json.starty = this.starty;
|
||||
json.fillStyle = this.fillStyle;
|
||||
if (this.fillImage instanceof Element) {
|
||||
json.fillImage = {
|
||||
src: this.fillImage.src
|
||||
}
|
||||
}
|
||||
json.strokeStyle = this.fillStyle;
|
||||
json.lineWidth = this.lineWidth;
|
||||
json.filled = this.filled;
|
||||
json.stroked = this.stroked;
|
||||
if (randomizeUuid) {
|
||||
json.idx = uuidv4();
|
||||
} else {
|
||||
json.idx = this.idx;
|
||||
}
|
||||
json.shapeId = this.shapeId;
|
||||
json.shapeIndex = this.shapeIndex; // For shape tweening
|
||||
json.curves = [];
|
||||
for (let curve of this.curves) {
|
||||
json.curves.push(curve.toJSON(randomizeUuid));
|
||||
}
|
||||
json.regions = [];
|
||||
for (let region of this.regions) {
|
||||
const curves = [];
|
||||
for (let curve of region.curves) {
|
||||
curves.push(curve.toJSON(randomizeUuid));
|
||||
}
|
||||
json.regions.push({
|
||||
idx: region.idx,
|
||||
curves: curves,
|
||||
fillStyle: region.fillStyle,
|
||||
filled: region.filled,
|
||||
});
|
||||
}
|
||||
return json;
|
||||
}
|
||||
get segmentColor() {
|
||||
return uuidToColor(this.idx);
|
||||
}
|
||||
addCurve(curve) {
|
||||
if (curve.color == undefined) {
|
||||
curve.color = context.strokeStyle;
|
||||
}
|
||||
this.curves.push(curve);
|
||||
this.quadtree.insert(curve, this.curves.length - 1);
|
||||
growBoundingBox(this.boundingBox, curve.bbox());
|
||||
}
|
||||
addLine(x, y) {
|
||||
let lastpoint;
|
||||
if (this.curves.length) {
|
||||
lastpoint = this.curves[this.curves.length - 1].points[3];
|
||||
} else {
|
||||
lastpoint = { x: this.startx, y: this.starty };
|
||||
}
|
||||
let midpoint = { x: (x + lastpoint.x) / 2, y: (y + lastpoint.y) / 2 };
|
||||
let curve = new Bezier(
|
||||
lastpoint.x,
|
||||
lastpoint.y,
|
||||
midpoint.x,
|
||||
midpoint.y,
|
||||
midpoint.x,
|
||||
midpoint.y,
|
||||
x,
|
||||
y,
|
||||
);
|
||||
curve.color = context.strokeStyle;
|
||||
this.quadtree.insert(curve, this.curves.length - 1);
|
||||
this.curves.push(curve);
|
||||
}
|
||||
bbox() {
|
||||
return this.boundingBox;
|
||||
}
|
||||
clear() {
|
||||
this.curves = [];
|
||||
this.quadtree.clear();
|
||||
}
|
||||
copy(idx) {
|
||||
let newShape = new Shape(
|
||||
this.startx,
|
||||
this.starty,
|
||||
{},
|
||||
this.parent,
|
||||
idx.slice(0, 8) + this.idx.slice(8),
|
||||
this.shapeId,
|
||||
);
|
||||
newShape.startx = this.startx;
|
||||
newShape.starty = this.starty;
|
||||
for (let curve of this.curves) {
|
||||
let newCurve = new Bezier(
|
||||
curve.points[0].x,
|
||||
curve.points[0].y,
|
||||
curve.points[1].x,
|
||||
curve.points[1].y,
|
||||
curve.points[2].x,
|
||||
curve.points[2].y,
|
||||
curve.points[3].x,
|
||||
curve.points[3].y,
|
||||
);
|
||||
newCurve.color = curve.color;
|
||||
newShape.addCurve(newCurve);
|
||||
}
|
||||
// TODO
|
||||
// for (let vertex of this.vertices) {
|
||||
|
||||
// }
|
||||
newShape.updateVertices();
|
||||
newShape.fillStyle = this.fillStyle;
|
||||
if (this.fillImage instanceof Element) {
|
||||
newShape.fillImage = this.fillImage.cloneNode(true)
|
||||
} else {
|
||||
newShape.fillImage = this.fillImage;
|
||||
}
|
||||
newShape.strokeStyle = this.strokeStyle;
|
||||
newShape.lineWidth = this.lineWidth;
|
||||
newShape.filled = this.filled;
|
||||
newShape.stroked = this.stroked;
|
||||
|
||||
return newShape;
|
||||
}
|
||||
fromPoints(points, error = 30) {
|
||||
console.log(error);
|
||||
this.curves = [];
|
||||
let curves = fitCurve.fitCurve(points, error);
|
||||
for (let curve of curves) {
|
||||
let bezier = new Bezier(
|
||||
curve[0][0],
|
||||
curve[0][1],
|
||||
curve[1][0],
|
||||
curve[1][1],
|
||||
curve[2][0],
|
||||
curve[2][1],
|
||||
curve[3][0],
|
||||
curve[3][1],
|
||||
);
|
||||
this.curves.push(bezier);
|
||||
this.quadtree.insert(bezier, this.curves.length - 1);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
simplify(mode = "corners") {
|
||||
this.quadtree.clear();
|
||||
this.inProgress = false;
|
||||
// Mode can be corners, smooth or auto
|
||||
if (mode == "corners") {
|
||||
let points = [{ x: this.startx, y: this.starty }];
|
||||
for (let curve of this.curves) {
|
||||
points.push(curve.points[3]);
|
||||
}
|
||||
// points = points.concat(this.curves)
|
||||
let newpoints = simplifyPolyline(points, 10, false);
|
||||
this.curves = [];
|
||||
let lastpoint = newpoints.shift();
|
||||
let midpoint;
|
||||
for (let point of newpoints) {
|
||||
midpoint = {
|
||||
x: (lastpoint.x + point.x) / 2,
|
||||
y: (lastpoint.y + point.y) / 2,
|
||||
};
|
||||
let bezier = new Bezier(
|
||||
lastpoint.x,
|
||||
lastpoint.y,
|
||||
midpoint.x,
|
||||
midpoint.y,
|
||||
midpoint.x,
|
||||
midpoint.y,
|
||||
point.x,
|
||||
point.y,
|
||||
);
|
||||
this.curves.push(bezier);
|
||||
this.quadtree.insert(bezier, this.curves.length - 1);
|
||||
lastpoint = point;
|
||||
}
|
||||
} else if (mode == "smooth") {
|
||||
let error = 30;
|
||||
let points = [[this.startx, this.starty]];
|
||||
for (let curve of this.curves) {
|
||||
points.push([curve.points[3].x, curve.points[3].y]);
|
||||
}
|
||||
this.fromPoints(points, error);
|
||||
} else if (mode == "verbatim") {
|
||||
// Just keep existing shape
|
||||
}
|
||||
let epsilon = 0.01;
|
||||
let newCurves = [];
|
||||
let intersectMap = {};
|
||||
for (let i = 0; i < this.curves.length - 1; i++) {
|
||||
// for (let j=i+1; j<this.curves.length; j++) {
|
||||
for (let j of this.quadtree.query(this.curves[i].bbox())) {
|
||||
if (i >= j) continue;
|
||||
let intersects = this.curves[i].intersects(this.curves[j]);
|
||||
if (intersects.length) {
|
||||
intersectMap[i] ||= [];
|
||||
intersectMap[j] ||= [];
|
||||
for (let intersect of intersects) {
|
||||
let [t1, t2] = intersect.split("/");
|
||||
intersectMap[i].push(parseFloat(t1));
|
||||
intersectMap[j].push(parseFloat(t2));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let lst in intersectMap) {
|
||||
for (let i = 1; i < intersectMap[lst].length; i++) {
|
||||
if (
|
||||
Math.abs(intersectMap[lst][i] - intersectMap[lst][i - 1]) < epsilon
|
||||
) {
|
||||
intersectMap[lst].splice(i, 1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let i = this.curves.length - 1; i >= 0; i--) {
|
||||
if (i in intersectMap) {
|
||||
intersectMap[i].sort().reverse();
|
||||
let remainingFraction = 1;
|
||||
let remainingCurve = this.curves[i];
|
||||
for (let t of intersectMap[i]) {
|
||||
let split = remainingCurve.split(t / remainingFraction);
|
||||
remainingFraction = t;
|
||||
newCurves.push(split.right);
|
||||
remainingCurve = split.left;
|
||||
}
|
||||
newCurves.push(remainingCurve);
|
||||
} else {
|
||||
newCurves.push(this.curves[i]);
|
||||
}
|
||||
}
|
||||
for (let curve of newCurves) {
|
||||
curve.color = context.strokeStyle;
|
||||
}
|
||||
newCurves.reverse();
|
||||
this.curves = newCurves;
|
||||
}
|
||||
update() {
|
||||
this.recalculateBoundingBox();
|
||||
this.updateVertices();
|
||||
if (this.curves.length) {
|
||||
this.startx = this.curves[0].points[0].x;
|
||||
this.starty = this.curves[0].points[0].y;
|
||||
}
|
||||
return [this];
|
||||
}
|
||||
getClockwiseCurves(point, otherPoints) {
|
||||
// Returns array of {x, y, idx, angle}
|
||||
|
||||
let points = [];
|
||||
for (let point of otherPoints) {
|
||||
points.push({ ...this.vertices[point].point, idx: point });
|
||||
}
|
||||
// Add an angle property to each point using tan(angle) = y/x
|
||||
const angles = points.map(({ x, y, idx }) => {
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
idx,
|
||||
angle: (Math.atan2(y - point.y, x - point.x) * 180) / Math.PI,
|
||||
};
|
||||
});
|
||||
// Sort your points by angle
|
||||
const pointsSorted = angles.sort((a, b) => a.angle - b.angle);
|
||||
return pointsSorted;
|
||||
}
|
||||
translate(x, y) {
|
||||
this.quadtree.clear()
|
||||
let j=0;
|
||||
for (let curve of this.curves) {
|
||||
for (let i in curve.points) {
|
||||
const point = curve.points[i];
|
||||
curve.points[i] = { x: point.x + x, y: point.y + y };
|
||||
}
|
||||
this.quadtree.insert(curve, j)
|
||||
j++;
|
||||
}
|
||||
this.update();
|
||||
}
|
||||
updateVertices() {
|
||||
this.vertices = [];
|
||||
let utils = Bezier.getUtils();
|
||||
let epsilon = 1.5; // big epsilon whoa
|
||||
let tooClose;
|
||||
let i = 0;
|
||||
|
||||
let region = {
|
||||
idx: `${this.idx}-r${this.regionIdx++}`,
|
||||
curves: [],
|
||||
fillStyle: context.fillStyle,
|
||||
filled: context.fillShape,
|
||||
};
|
||||
pointerList[region.idx] = region;
|
||||
this.regions = [region];
|
||||
for (let curve of this.curves) {
|
||||
this.regions[0].curves.push(curve);
|
||||
}
|
||||
if (this.regions[0].curves.length) {
|
||||
if (
|
||||
utils.dist(
|
||||
this.regions[0].curves[0].points[0],
|
||||
this.regions[0].curves[this.regions[0].curves.length - 1].points[3],
|
||||
) < epsilon
|
||||
) {
|
||||
this.regions[0].filled = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Generate vertices
|
||||
for (let curve of this.curves) {
|
||||
for (let index of [0, 3]) {
|
||||
tooClose = false;
|
||||
for (let vertex of this.vertices) {
|
||||
if (utils.dist(curve.points[index], vertex.point) < epsilon) {
|
||||
tooClose = true;
|
||||
vertex[["startCurves", , , "endCurves"][index]][i] = curve;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!tooClose) {
|
||||
if (index == 0) {
|
||||
this.vertices.push({
|
||||
point: curve.points[index],
|
||||
startCurves: { [i]: curve },
|
||||
endCurves: {},
|
||||
});
|
||||
} else {
|
||||
this.vertices.push({
|
||||
point: curve.points[index],
|
||||
startCurves: {},
|
||||
endCurves: { [i]: curve },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
let shapes = [this];
|
||||
this.vertices.forEach((vertex, i) => {
|
||||
for (let i = 0; i < Math.min(10, this.regions.length); i++) {
|
||||
let region = this.regions[i];
|
||||
let regionVertexCurves = [];
|
||||
let vertexCurves = { ...vertex.startCurves, ...vertex.endCurves };
|
||||
if (Object.keys(vertexCurves).length == 1) {
|
||||
// endpoint
|
||||
continue;
|
||||
} else if (Object.keys(vertexCurves).length == 2) {
|
||||
// path vertex, don't need to do anything
|
||||
continue;
|
||||
} else if (Object.keys(vertexCurves).length == 3) {
|
||||
// T junction. Region doesn't change but might need to update curves?
|
||||
// Skip for now.
|
||||
continue;
|
||||
} else if (Object.keys(vertexCurves).length == 4) {
|
||||
// Intersection, split region in 2
|
||||
for (let i in vertexCurves) {
|
||||
let curve = vertexCurves[i];
|
||||
if (region.curves.includes(curve)) {
|
||||
regionVertexCurves.push(curve);
|
||||
}
|
||||
}
|
||||
let start = region.curves.indexOf(regionVertexCurves[1]);
|
||||
let end = region.curves.indexOf(regionVertexCurves[3]);
|
||||
if (end > start) {
|
||||
let newRegion = {
|
||||
idx: `${this.idx}-r${this.regionIdx++}`, // TODO: generate this deterministically so that undo/redo works
|
||||
curves: region.curves.splice(start, end - start),
|
||||
fillStyle: region.fillStyle,
|
||||
filled: true,
|
||||
};
|
||||
pointerList[newRegion.idx] = newRegion;
|
||||
this.regions.push(newRegion);
|
||||
}
|
||||
} else {
|
||||
// not sure how to handle vertices with more than 4 curves
|
||||
console.log(
|
||||
`Unexpected vertex with ${Object.keys(vertexCurves).length} curves!`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { BaseShape, TempShape, Shape };
|
||||
Reference in New Issue
Block a user