Skip to content

Visualize Your Ideas With Code

refactor: separate scene rendering

aarthificial1692187fe917
diff --git a/package-lock.json b/package-lock.json
index 75a7fdfa..5e045458 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,7 +10,7 @@
"license": "ISC",
"dependencies": {
"@types/wicg-file-system-access": "^2020.9.5",
- "canvas": "^2.9.0",
+ "canvas": "^2.9.1",
"image-size": "^1.0.1",
"konva": "^8.3.2",
"mix-color": "^1.1.2",
@@ -44,14 +44,14 @@
}
},
"node_modules/@mapbox/node-pre-gyp": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.8.tgz",
- "integrity": "sha512-CMGKi28CF+qlbXh26hDe6NxCd7amqeAzEqnS6IHeO6LoaKyM/n+Xw3HT1COdq8cuioOdlKdqn/hCmqPUOMOywg==",
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.9.tgz",
+ "integrity": "sha512-aDF3S3rK9Q2gey/WAttUlISduDItz5BU3306M9Eyv6/oS40aMprnopshtlKTykxRNIBEZuRMaZAnbrQ4QtKGyw==",
"dependencies": {
- "detect-libc": "^1.0.3",
+ "detect-libc": "^2.0.0",
"https-proxy-agent": "^5.0.0",
"make-dir": "^3.1.0",
- "node-fetch": "^2.6.5",
+ "node-fetch": "^2.6.7",
"nopt": "^5.0.0",
"npmlog": "^5.0.1",
"rimraf": "^3.0.2",
@@ -794,9 +794,9 @@
}
},
"node_modules/canvas": {
- "version": "2.9.0",
- "resolved": "https://registry.npmjs.org/canvas/-/canvas-2.9.0.tgz",
- "integrity": "sha512-0l93g7uxp7rMyr7H+XRQ28A3ud0dKIUTIEkUe1Dxh4rjUYN7B93+SjC3r1PDKA18xcQN87OFGgUnyw7LSgNLSQ==",
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/canvas/-/canvas-2.9.1.tgz",
+ "integrity": "sha512-vSQti1uG/2gjv3x6QLOZw7TctfufaerTWbVe+NSduHxxLGB+qf3kFgQ6n66DSnuoINtVUjrLLIK2R+lxrBG07A==",
"hasInstallScript": true,
"dependencies": {
"@mapbox/node-pre-gyp": "^1.0.0",
@@ -1158,14 +1158,11 @@
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"node_modules/detect-libc": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz",
- "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=",
- "bin": {
- "detect-libc": "bin/detect-libc.js"
- },
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz",
+ "integrity": "sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w==",
"engines": {
- "node": ">=0.10"
+ "node": ">=8"
}
},
"node_modules/detect-node": {
@@ -3403,9 +3400,9 @@
]
},
"node_modules/simple-get": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.0.tgz",
- "integrity": "sha512-bCR6cP+aTdScaQCnQKbPKtJOKDp/hj9EDLJo3Nw4y1QksqaovlW/bnptB6/c1e+qmNIDHRK+oXFDdEqBT8WzUA==",
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz",
+ "integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==",
"dependencies": {
"decompress-response": "^4.2.0",
"once": "^1.3.1",
@@ -4313,14 +4310,14 @@
"dev": true
},
"@mapbox/node-pre-gyp": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.8.tgz",
- "integrity": "sha512-CMGKi28CF+qlbXh26hDe6NxCd7amqeAzEqnS6IHeO6LoaKyM/n+Xw3HT1COdq8cuioOdlKdqn/hCmqPUOMOywg==",
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.9.tgz",
+ "integrity": "sha512-aDF3S3rK9Q2gey/WAttUlISduDItz5BU3306M9Eyv6/oS40aMprnopshtlKTykxRNIBEZuRMaZAnbrQ4QtKGyw==",
"requires": {
- "detect-libc": "^1.0.3",
+ "detect-libc": "^2.0.0",
"https-proxy-agent": "^5.0.0",
"make-dir": "^3.1.0",
- "node-fetch": "^2.6.5",
+ "node-fetch": "^2.6.7",
"nopt": "^5.0.0",
"npmlog": "^5.0.1",
"rimraf": "^3.0.2",
@@ -4948,9 +4945,9 @@
"integrity": "sha512-csfD/GpHMqgEL3V3uIgosvh+SVIQvCh43SNu9HRbP1lnxkKm1kjDG4f32PP571JplkLjfS+mg2p1gxR7MYrrIA=="
},
"canvas": {
- "version": "2.9.0",
- "resolved": "https://registry.npmjs.org/canvas/-/canvas-2.9.0.tgz",
- "integrity": "sha512-0l93g7uxp7rMyr7H+XRQ28A3ud0dKIUTIEkUe1Dxh4rjUYN7B93+SjC3r1PDKA18xcQN87OFGgUnyw7LSgNLSQ==",
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/canvas/-/canvas-2.9.1.tgz",
+ "integrity": "sha512-vSQti1uG/2gjv3x6QLOZw7TctfufaerTWbVe+NSduHxxLGB+qf3kFgQ6n66DSnuoINtVUjrLLIK2R+lxrBG07A==",
"requires": {
"@mapbox/node-pre-gyp": "^1.0.0",
"nan": "^2.15.0",
@@ -5221,9 +5218,9 @@
"integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
},
"detect-libc": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz",
- "integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups="
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.1.tgz",
+ "integrity": "sha512-463v3ZeIrcWtdgIg6vI6XUncguvr2TnGl4SzDXinkt9mSLpBJKXT3mW6xT3VQdDN11+WVs29pgvivTc4Lp8v+w=="
},
"detect-node": {
"version": "2.1.0",
@@ -6832,9 +6829,9 @@
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="
},
"simple-get": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.0.tgz",
- "integrity": "sha512-bCR6cP+aTdScaQCnQKbPKtJOKDp/hj9EDLJo3Nw4y1QksqaovlW/bnptB6/c1e+qmNIDHRK+oXFDdEqBT8WzUA==",
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz",
+ "integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==",
"requires": {
"decompress-response": "^4.2.0",
"once": "^1.3.1",
diff --git a/package.json b/package.json
index 2e0fbdd8..614cfc37 100644
--- a/package.json
+++ b/package.json
@@ -12,7 +12,7 @@
},
"dependencies": {
"@types/wicg-file-system-access": "^2020.9.5",
- "canvas": "^2.9.0",
+ "canvas": "^2.9.1",
"image-size": "^1.0.1",
"konva": "^8.3.2",
"mix-color": "^1.1.2",
diff --git a/src/Project.ts b/src/Project.ts
index 62d43017..d55816a3 100644
--- a/src/Project.ts
+++ b/src/Project.ts
@@ -5,9 +5,8 @@ import {Rect} from 'konva/lib/shapes/Rect';
import {Layer} from 'konva/lib/Layer';
import {Vector2d} from 'konva/lib/types';
import {Konva} from 'konva/lib/Global';
-import {threads, ThreadsCallback} from './animations';
-import {Scene} from './Scene';
-import {PROJECT} from './symbols';
+import {ThreadsCallback} from './animations';
+import {Scene, SceneRunner} from './Scene';
Konva.autoDrawEnabled = false;
@@ -25,15 +24,17 @@ export class Project extends Stage {
public threadsCallback: ThreadsCallback;
public framesPerSeconds = 60;
public frame: number = 0;
+
public get time(): number {
return this.framesToSeconds(this.frame);
}
- private runner: Generator;
- private readonly scenes = new Set<Scene>();
+ private readonly sceneLookup: Record<string, Scene> = {};
+ private previousScene: Scene = null;
+ private currentScene: Scene = null;
public constructor(
- public runnerFactory: (project: Project) => Generator,
+ scenes: SceneRunner[],
size: ProjectSize = ProjectSize.FullHD,
config: Partial<StageConfig> = {},
) {
@@ -61,49 +62,102 @@ export class Project extends Stage {
const backgroundLayer = new Layer({name: 'background'});
backgroundLayer.add(this.background);
this.add(backgroundLayer);
- }
- public addScene(scene: Scene) {
- if (!this.scenes.has(scene)) {
- this.scenes.add(scene);
- this.add(scene);
+ for (const scene of scenes) {
+ const handle = new Scene(this, scene);
+ this.sceneLookup[scene.name] = handle;
+ handle.threadsCallback = (...args) => {
+ if (this.currentScene === handle) {
+ this.threadsCallback?.(...args);
+ }
+ };
}
}
- public removeScene(scene: Scene) {
- if (this.scenes.has(scene)) {
- this.scenes.delete(scene);
- scene.destroy();
+ public reload(runners: SceneRunner[]) {
+ for (const runner of runners) {
+ this.sceneLookup[runner.name]?.reload(runner);
}
}
- public start() {
- this.scenes.forEach(scene => scene.destroy());
- this.scenes.clear();
- this.frame = 0;
- this.runner = threads(
- () => this.runnerFactory(this),
- (runners, children, cancelled) =>
- this.threadsCallback?.(runners, children, cancelled),
- );
+ private async goToScene(scene: Scene) {
+ this.previousScene?.remove();
+ this.currentScene?.remove();
+
+ this.previousScene = null;
+ this.currentScene = scene;
+ await this.currentScene.reset();
+ this.add(this.currentScene);
}
public async next(speed: number = 1): Promise<boolean> {
- let result = this.runner.next();
- while (result.value) {
- if (typeof result.value.then === 'function') {
- const value = await result.value;
- result = this.runner.next(value);
- } else if (result.value === PROJECT) {
- result = this.runner.next(this);
- } else {
- console.log('Invalid value: ', result.value);
- result = this.runner.next();
+ if (this.previousScene) {
+ await this.previousScene.next();
+ if (
+ this.previousScene.isFinished() &&
+ (!this.currentScene || this.currentScene.isAfterTransitionIn())
+ ) {
+ this.previousScene.remove();
+ this.previousScene.lastFrame = this.frame;
+ this.previousScene = null;
+ }
+ }
+
+ if (this.currentScene) {
+ await this.currentScene.next();
+ if (this.currentScene.canTransitionOut()) {
+ this.previousScene = this.currentScene;
+ this.previousScene.transitionFrame = this.frame;
+ this.currentScene = this.getNextScene(this.previousScene);
+ if (this.currentScene) {
+ await this.currentScene.reset(this.previousScene);
+ this.currentScene.firstFrame = this.frame;
+ this.add(this.currentScene);
+ }
}
}
+
this.frame += speed;
- return result.done;
+ return !this.currentScene || this.currentScene.isFinished();
+ }
+
+ public async seek(frame: number, speed: number = 1): Promise<boolean> {
+ if (
+ frame <= this.frame ||
+ !this.currentScene ||
+ (this.currentScene.lastFrame !== null &&
+ this.currentScene.lastFrame <= frame)
+ ) {
+ const scene = this.findBestScene(frame);
+ if (scene !== this.currentScene) {
+ await this.goToScene(scene);
+ this.frame = this.currentScene.firstFrame ?? 0;
+ } else if (this.frame >= frame) {
+ this.previousScene?.remove();
+ await this.currentScene.reset();
+ this.frame = this.currentScene.firstFrame ?? 0;
+ }
+ }
+
+ let finished = false;
+ while (this.frame < frame && !finished) {
+ finished = await this.next(speed);
+ }
+
+ return finished;
+ }
+
+ private findBestScene(frame: number): Scene {
+ let lastScene = null;
+ for (const scene of Object.values(this.sceneLookup)) {
+ if (scene.transitionFrame === null || scene.transitionFrame > frame) {
+ return scene;
+ }
+ lastScene = scene;
+ }
+
+ return lastScene;
}
public secondsToFrames(seconds: number) {
@@ -113,4 +167,17 @@ export class Project extends Stage {
public framesToSeconds(frames: number) {
return frames / this.framesPerSeconds;
}
+
+ private getNextScene(scene?: Scene): Scene {
+ const scenes = Object.values(this.sceneLookup);
+ if (!scene) {
+ return scenes[0];
+ }
+
+ const index = scenes.findIndex(s => s === scene);
+ if (index < 0) {
+ return null;
+ }
+ return scenes[index + 1] ?? null;
+ }
}
diff --git a/src/Scene.ts b/src/Scene.ts
index 411c9c6d..8f15819a 100644
--- a/src/Scene.ts
+++ b/src/Scene.ts
@@ -1,84 +1,128 @@
+import type {Project} from './Project';
import {Layer, LayerConfig} from 'konva/lib/Layer';
-import {Project} from './Project';
-import {GeneratorHelper} from './helpers';
-import {cancel} from './animations';
+import {threads, ThreadsCallback} from './animations';
import {Debug} from './components';
import {Node} from 'konva/lib/Node';
import {Group} from 'konva/lib/Group';
import {Shape} from 'konva/lib/Shape';
+import {threadable} from './decorators';
+import {PROJECT} from './symbols';
export interface SceneRunner {
(layer: Scene, project: Project): Generator;
}
+export interface SceneTransition {
+ (next: Scene, previous?: Scene): Generator;
+}
+
export enum SceneState {
- Pending,
- Started,
+ Initial,
+ AfterTransitionIn,
+ CanTransitionOut,
Finished,
- Disposed,
}
export class Scene extends Layer {
- private state: SceneState = SceneState.Pending;
- private task: Generator;
+ public firstFrame: number = null;
+ public transitionFrame: number = null;
+ public lastFrame: number = null;
+ public threadsCallback: ThreadsCallback = null;
+
private readonly debugNode: Debug;
+ private previousScene: Scene = null;
+ private runner: Generator;
+ private state: SceneState = SceneState.Initial;
public constructor(
public readonly project: Project,
- private readonly runner: SceneRunner,
- config?: LayerConfig,
+ private runnerFactory: SceneRunner,
+ config: LayerConfig = {},
) {
- super(config);
+ super({
+ name: runnerFactory.name,
+ ...config,
+ });
this.debugNode = new Debug();
this.add(this.debugNode);
this.debugNode.hide();
}
- public run(): Generator {
- this.project.addScene(this);
- const scene = this;
- this.task = (function* () {
- yield* scene.runner(scene, scene.project);
- if (scene.state !== SceneState.Disposed) {
- scene.state = SceneState.Finished;
- }
- while (scene.state !== SceneState.Disposed) {
- yield;
- }
- })();
- GeneratorHelper.makeThreadable(this.task, `${this.name()} [scene]`);
+ public reload(runnerFactory: SceneRunner) {
+ this.runnerFactory = runnerFactory;
+ this.transitionFrame = null;
+ this.lastFrame = null;
+ }
- return this.task;
+ public async reset(previousScene: Scene = null) {
+ this.x(0).y(0);
+ this.debugNode.remove();
+ this.destroyChildren();
+ this.add(this.debugNode);
+ this.previousScene = previousScene;
+ this.runner = threads(
+ () => this.runnerFactory(this, this.project),
+ (...args) => this.threadsCallback?.(...args),
+ );
+ this.state = SceneState.Initial;
+ await this.next();
}
- public activate() {
- if (this.state === SceneState.Pending) {
- this.state = SceneState.Started;
+ public async next() {
+ let result = this.runner.next();
+ while (result.value) {
+ if (typeof result.value.then === 'function') {
+ const value = await result.value;
+ result = this.runner.next(value);
+ } else if (result.value === PROJECT) {
+ result = this.runner.next(this.project);
+ } else {
+ console.log('Invalid value: ', result.value);
+ result = this.runner.next();
+ }
+ }
+
+ if (result.done) {
+ this.state = SceneState.Finished;
}
}
- public *start(): Generator {
- while (this.state === SceneState.Pending) {
- yield;
+ @threadable()
+ public *transition(transitionRunner?: SceneTransition) {
+ if (transitionRunner) {
+ yield* transitionRunner(this, this.previousScene);
+ }
+ if (this.state === SceneState.Initial) {
+ this.state = SceneState.AfterTransitionIn;
+ } else {
+ console.warn(
+ `Scene ${this.name} transitioned in an unexpected state: `,
+ this.state,
+ );
}
}
- public *end(): Generator {
- while (this.state !== SceneState.Finished) {
- yield;
+ public canFinish() {
+ if (this.state === SceneState.AfterTransitionIn) {
+ this.state = SceneState.CanTransitionOut;
+ } else {
+ console.warn(
+ `Scene ${this.name} was marked as finished in an unexpected state: `,
+ this.state,
+ );
}
}
- public deactivate() {
- if (this.state === SceneState.Started) {
- this.state = SceneState.Finished;
- }
+ public isAfterTransitionIn(): boolean {
+ return this.state === SceneState.AfterTransitionIn;
+ }
+
+ public isFinished(): boolean {
+ return this.state === SceneState.Finished;
}
- public *dispose() {
- this.state = SceneState.Disposed;
- yield* cancel(this.task);
- this.project.removeScene(this);
+ public canTransitionOut(): boolean {
+ return this.state === SceneState.CanTransitionOut;
}
public add(...children: (Shape | Group)[]): this {
diff --git a/src/animations/threads.ts b/src/animations/threads.ts
index cb50fd1e..440c8787 100644
--- a/src/animations/threads.ts
+++ b/src/animations/threads.ts
@@ -24,7 +24,10 @@ export function* cancel(...tasks: Generator[]): Generator {
}
decorate(threads, threadable());
-export function* threads(factory: ThreadsFactory, callback?: ThreadsCallback): Generator {
+export function* threads(
+ factory: ThreadsFactory,
+ callback?: ThreadsCallback,
+): Generator {
let runners: Generator[] = [];
let cancelled = new Set<Generator>();
let values = new Map<Generator, any>();
diff --git a/src/hot.ts b/src/hot.ts
new file mode 100644
index 00000000..7ad414b9
--- /dev/null
+++ b/src/hot.ts
@@ -0,0 +1,21 @@
+import {Player} from './player/Player';
+
+export function hot(player: Player, root: typeof module) {
+ const update = (modules: string[]) => {
+ player.project.reload(
+ // @ts-ignore
+ modules.map(id => __webpack_require__(id).default),
+ );
+ player.requestSeek(player.project.frame);
+ };
+
+ const scenePaths = require.cache[root.id].children.filter(name =>
+ //@ts-ignore
+ name.match(/\.scene\.[jt]sx?/),
+ );
+
+ //@ts-ignore
+ root.hot.accept(scenePaths, update);
+ //@ts-ignore
+ module.hot.accept(scenePaths, update);
+}
diff --git a/src/player/Player.ts b/src/player/Player.ts
index af565a60..1b4423a1 100644
--- a/src/player/Player.ts
+++ b/src/player/Player.ts
@@ -1,10 +1,9 @@
-import {Project} from '../Project';
+import type {Project} from '../Project';
import {
PromiseSimpleEventDispatcher,
SimpleEventDispatcher,
} from 'strongly-typed-events';
-const MINIMUM_ANIMATION_DURATION = 1000;
const MAX_AUDIO_DESYNC = 1 / 50;
export interface PlayerState {
@@ -35,6 +34,7 @@ export class Player {
public get StateChanged() {
return this.stateChanged.asEvent();
}
+
public get RenderChanged() {
return this.renderChanged.asEvent();
}
@@ -45,6 +45,7 @@ export class Player {
private readonly audio: HTMLAudioElement = null;
private startTime: number;
+ private audioError = false;
private state: PlayerState = {
duration: 100,
@@ -105,41 +106,12 @@ export class Player {
this.request();
}
- private async reset(state: PlayerState): Promise<PlayerState> {
- this.project.start();
- state.finished = await this.project.next();
- while (this.project.frame < state.startFrame && !state.finished) {
- state.finished = await this.project.next();
- }
- this.project.draw();
- this.startTime = performance.now();
- if (this.audio) {
- this.audio.currentTime = Math.max(
- 0,
- this.project.framesToSeconds(state.startFrame - 3),
- );
- }
- state.frame = this.project.frame;
-
- this.updateState({
- finished: state.finished,
- frame: state.frame,
- });
-
- return state;
- }
-
- public reload(): void {
- this.requestReset();
- this.requestSeek(this.project.frame);
- }
-
public requestNextFrame(): void {
this.commands.seek = this.state.frame + 1;
}
public requestReset(): void {
- this.commands.reset = true;
+ this.commands.seek = 0;
}
public requestSeek(value: number): void {
@@ -164,22 +136,28 @@ export class Player {
private async run() {
let commands = this.consumeCommands();
let state = {...this.state};
- if (commands.seek >= state.startFrame) {
- state.startFrame = commands.seek;
+ if (state.finished && state.loop && commands.seek < 0) {
+ commands.seek = 0;
}
- if (
- commands.reset ||
- (state.finished && state.loop) ||
- (commands.seek >= 0 && state.frame > commands.seek)
- ) {
- state = await this.reset(state);
+
+ // Pause / play audio.
+ const audioPaused = state.paused || state.finished || state.render;
+ if (this.audio && this.audio.paused !== audioPaused) {
+ if (audioPaused) {
+ this.audio.pause();
+ } else {
+ try {
+ await this.audio.play();
+ this.syncAudio(-3);
+ this.audioError = false;
+ } catch (e) {
+ this.audioError = true;
+ }
+ }
}
- // rendering
+ // Rendering
if (state.render) {
- if (!this.audio?.paused) {
- this.audio?.pause();
- }
state.finished = await this.project.next();
this.project.draw();
await this.renderChanged.dispatch({
@@ -199,71 +177,46 @@ export class Player {
return;
}
- // synchronize audio.
- if (state.speed !== 1 && this.audio) {
- this.audio.currentTime = this.project.time;
- }
-
- // pause / play audio.
- const audioPaused = state.paused || state.finished;
- if (this.audio && this.audio.paused !== audioPaused) {
- if (audioPaused) {
- this.audio.pause();
- } else {
- this.audio.currentTime = Math.max(
- 0,
- this.project.framesToSeconds(this.project.frame - 3),
- );
- this.audio.play();
- }
+ // Seek to the given frame
+ if (commands.seek >= 0 || this.project.frame < state.startFrame) {
+ const seekFrame = Math.max(commands.seek, state.startFrame);
+ state.finished = await this.project.seek(seekFrame, state.speed);
+ this.syncAudio(-3);
}
-
- // do nothing if paused or is ahead of the audio.
- if (
- this.project.frame >= state.startFrame &&
- (state.paused ||
- (state.speed === 1 &&
- this.audio &&
- this.audio.currentTime < this.project.time))
+ // Do nothing if paused or is ahead of the audio.
+ else if (
+ state.paused ||
+ (state.speed === 1 &&
+ this.hasAudio() &&
+ this.audio.currentTime < this.project.time)
) {
this.request();
return;
}
-
- if (!state.finished) {
- state.finished = await this.project.next(state.speed);
- }
-
- // Start from certain frame
- if (this.project.frame < state.startFrame) {
- while (this.project.frame < state.startFrame && !state.finished) {
- state.finished = await this.project.next();
- }
- if (this.audio) {
- this.audio.currentTime = this.project.framesToSeconds(
- state.startFrame - 3,
- );
- }
- }
-
- // Synchronize animation with audio.
- if (
+ // Seek to synchronize animation with audio.
+ else if (
+ this.hasAudio() &&
state.speed === 1 &&
- this.audio?.currentTime - MAX_AUDIO_DESYNC > this.project.time
+ this.project.time < this.audio.currentTime - MAX_AUDIO_DESYNC
) {
- while (this.audio.currentTime > this.project.time && !state.finished) {
- state.finished = await this.project.next();
+ const seekFrame = this.project.secondsToFrames(this.audio.currentTime);
+ state.finished = await this.project.seek(seekFrame, state.speed);
+ }
+ // Simply move forward one frame
+ else {
+ state.finished = await this.project.next(state.speed);
+
+ // Synchronize audio.
+ if (state.speed !== 1) {
+ this.syncAudio();
}
}
+ // Draw the project
this.project.draw();
// handle finishing
if (state.finished) {
- if (state.loop || commands.seek >= 0) {
- this.requestReset();
- }
-
state.duration = this.project.frame;
}
@@ -273,20 +226,20 @@ export class Player {
frame: this.project.frame,
});
- // Prevent animation from restarting too quickly.
- const animationDuration = performance.now() - this.startTime;
- if (
- commands.seek < 0 &&
- state.finished &&
- animationDuration < MINIMUM_ANIMATION_DURATION
- ) {
- setTimeout(
- () => this.request(),
- MINIMUM_ANIMATION_DURATION - animationDuration,
- );
- } else {
- this.request();
- }
+ this.request();
+ }
+
+ private hasAudio(): boolean {
+ return this.audio && !this.audioError;
+ }
+
+ private syncAudio(frameOffset: number = 0) {
+ if (!this.audio) return;
+
+ this.audio.currentTime = Math.max(
+ 0,
+ this.project.framesToSeconds(this.project.frame + frameOffset),
+ );
}
private request() {
diff --git a/src/transitions/index.ts b/src/transitions/index.ts
new file mode 100644
index 00000000..a0e4331e
--- /dev/null
+++ b/src/transitions/index.ts
@@ -0,0 +1 @@
+export * from './slideTransition';
diff --git a/src/transitions/slideTransition.ts b/src/transitions/slideTransition.ts
new file mode 100644
index 00000000..8582e545
--- /dev/null
+++ b/src/transitions/slideTransition.ts
@@ -0,0 +1,31 @@
+import type {Project} from '../Project';
+import type {SceneTransition} from '../Scene';
+
+import {Direction, originPosition} from '../types';
+import {PROJECT} from '../symbols';
+import {easeInOutCubic, tween, vector2dTween} from '../tweening';
+
+export function slideTransition(
+ direction: Direction = Direction.Top,
+): SceneTransition {
+ return function* (next, previous) {
+ const project = (yield PROJECT) as Project;
+ const position = originPosition(
+ direction,
+ project.width(),
+ project.height(),
+ );
+ yield* tween(4, value => {
+ previous?.position(
+ vector2dTween(
+ {x: 0, y: 0},
+ {x: -position.x, y: -position.y},
+ easeInOutCubic(value),
+ ),
+ );
+ next.position(
+ vector2dTween(position, {x: 0, y: 0}, easeInOutCubic(value)),
+ );
+ });
+ };
+}
diff --git a/src/types/Origin.ts b/src/types/Origin.ts
index c410c804..cd00ec5c 100644
--- a/src/types/Origin.ts
+++ b/src/types/Origin.ts
@@ -49,7 +49,7 @@ export function flipOrigin(
return origin;
}
-export function originPosition(origin: Origin, width = 1 , height = 1): Vector2d {
+export function originPosition(origin: Origin | Direction, width = 1 , height = 1): Vector2d {
const position: Vector2d = {x: 0, y: 0};
if (origin === Origin.Middle) {