Skip to content

Visualize Your Ideas With Code

feat(core): presentation mode (#486)

Jacobc4f2e48ae6c6
diff --git a/packages/core/src/app/Exporter.ts b/packages/core/src/app/Exporter.ts
index af2c3138..fcdbaed6 100644
--- a/packages/core/src/app/Exporter.ts
+++ b/packages/core/src/app/Exporter.ts
@@ -1,4 +1,4 @@
-import {RendererResult, RendererSettings} from './Renderer';
+import type {RendererResult, RendererSettings} from './Renderer';
/**
* The main interface for implementing custom exporters.
diff --git a/packages/core/src/app/ImageExporter.ts b/packages/core/src/app/ImageExporter.ts
index 4e890121..02a856fa 100644
--- a/packages/core/src/app/ImageExporter.ts
+++ b/packages/core/src/app/ImageExporter.ts
@@ -1,7 +1,7 @@
-import {CanvasOutputMimeType} from '../types';
-import {Exporter} from './Exporter';
-import {Logger} from './Logger';
-import {RendererSettings} from './Renderer';
+import type {RendererSettings} from './Renderer';
+import type {Exporter} from './Exporter';
+import type {Logger} from './Logger';
+import type {CanvasOutputMimeType} from '../types';
const EXPORT_FRAME_LIMIT = 256;
const EXPORT_RETRY_DELAY = 1000;
diff --git a/packages/core/src/app/PlaybackManager.ts b/packages/core/src/app/PlaybackManager.ts
index bb213148..db10a50f 100644
--- a/packages/core/src/app/PlaybackManager.ts
+++ b/packages/core/src/app/PlaybackManager.ts
@@ -1,10 +1,11 @@
-import {Scene, SceneDescriptionReload} from '../scenes';
+import type {Scene, SceneDescriptionReload, Slide} from '../scenes';
import {ValueDispatcher} from '../events';
export enum PlaybackState {
Playing,
Rendering,
Paused,
+ Presenting,
}
/**
@@ -44,6 +45,7 @@ export class PlaybackManager {
public fps = 30;
public duration = 0;
public finished = false;
+ public slides: Slide[] = [];
public previousScene: Scene | null = null;
public state = PlaybackState.Paused;
@@ -56,6 +58,9 @@ export class PlaybackManager {
}
public set currentScene(scene: Scene) {
+ if (!scene) {
+ throw new Error('Invalid scene.');
+ }
this.currentSceneReference ??= new ValueDispatcher<Scene>(scene);
this.currentSceneReference.current = scene;
}
@@ -100,6 +105,48 @@ export class PlaybackManager {
return this.finished;
}
+ public async goBack() {
+ let target = this.currentScene.slides.getCurrent();
+ if (target && this.currentScene.slides.isWaiting()) {
+ const index = this.slides.indexOf(target);
+ target = this.slides[index - 1];
+ }
+
+ await this.seekSlide(target);
+ }
+
+ public async goForward() {
+ const current = this.currentScene.slides.getCurrent();
+ const index = this.slides.indexOf(current!);
+ await this.seekSlide(this.slides[index + 1]);
+ }
+
+ public async goTo(slideId: string) {
+ await this.seekSlide(this.slides.find(slide => slide.id === slideId));
+ }
+
+ private async seekSlide(slide: Slide | null = null) {
+ if (!slide) return;
+ const {id, scene} = slide;
+
+ if (this.currentScene !== scene || this.currentScene.slides.didHappen(id)) {
+ this.previousScene = null;
+ this.currentScene = scene;
+ this.frame = this.currentScene.firstFrame;
+ this.currentScene.slides.setTarget(id);
+ await this.currentScene.reset();
+ }
+
+ this.finished = false;
+ this.currentScene.slides.setTarget(id);
+ while (!this.currentScene.slides.isWaitingFor(id) && !this.finished) {
+ this.finished = await this.next();
+ }
+ this.currentScene.slides.setTarget(null);
+
+ return this.finished;
+ }
+
public async reset() {
this.previousScene = null;
this.currentScene = this.scenes.current[0];
@@ -113,6 +160,7 @@ export class PlaybackManager {
public async recalculate() {
this.previousScene = null;
+ this.slides = [];
const speed = this.speed;
this.frame = 0;
@@ -124,6 +172,7 @@ export class PlaybackManager {
await scene.recalculate(frame => {
this.frame = frame;
});
+ this.slides.push(...scene.slides.onChanged.current);
scenes.push(scene);
}
} finally {
@@ -145,7 +194,7 @@ export class PlaybackManager {
this.frame += this.speed;
if (this.currentScene.isFinished()) {
- return false;
+ return true;
}
await this.currentScene.next();
diff --git a/packages/core/src/app/Player.ts b/packages/core/src/app/Player.ts
index 8385914a..99f8cfa0 100644
--- a/packages/core/src/app/Player.ts
+++ b/packages/core/src/app/Player.ts
@@ -189,8 +189,8 @@ export class Player {
if (recalculate) {
this.playback.reload();
this.frame.current = frame;
- await this.requestRecalculation();
- this.requestSeek(frame);
+ this.requestRecalculation();
+ this.requestedSeek = frame;
}
}
@@ -414,9 +414,14 @@ export class Player {
}
}
+ // Pause if a new slide has just started.
+ if (!state.paused && this.playback.currentScene.slides.isWaiting()) {
+ this.togglePlayback(false);
+ state.paused = true;
+ }
+
// Draw the project
await this.render.dispatch();
-
this.frame.current = this.playback.frame;
this.request();
diff --git a/packages/core/src/app/Presenter.ts b/packages/core/src/app/Presenter.ts
new file mode 100644
index 00000000..477a4972
--- /dev/null
+++ b/packages/core/src/app/Presenter.ts
@@ -0,0 +1,281 @@
+import type {Project} from './Project';
+import type {Logger} from './Logger';
+import type {Scene, Slide} from '../scenes';
+import {PlaybackManager, PlaybackState} from './PlaybackManager';
+import {Stage, StageSettings} from './Stage';
+import {ValueDispatcher} from '../events';
+import {Vector2} from '../types';
+import {PlaybackStatus} from './PlaybackStatus';
+import {Semaphore} from '../utils';
+import {ReadOnlyTimeEvents} from '../scenes/timeEvents';
+
+export interface PresenterSettings extends StageSettings {
+ name: string;
+ fps: number;
+ slide: string | null;
+}
+
+export interface PresenterInfo extends Record<string, unknown> {
+ currentSlideId: string | null;
+ nextSlideId: string | null;
+ hasNext: boolean;
+ hasPrevious: boolean;
+ isWaiting: boolean;
+ count: number;
+ index: number | null;
+}
+
+export enum PresenterState {
+ Initial,
+ Working,
+ Aborting,
+}
+
+const NextSlide = Symbol('@motion-canvas/core/app/NextSlide');
+const PreviousSlide = Symbol('@motion-canvas/core/app/PreviousSlide');
+
+export class Presenter {
+ public get onStateChanged() {
+ return this.state.subscribable;
+ }
+ private readonly state = new ValueDispatcher(PresenterState.Initial);
+
+ public get onInfoChanged() {
+ return this.info.subscribable;
+ }
+ private readonly info = new ValueDispatcher<PresenterInfo>({
+ currentSlideId: null,
+ nextSlideId: null,
+ hasNext: false,
+ hasPrevious: false,
+ isWaiting: false,
+ index: null,
+ count: 0,
+ });
+
+ public get onSlidesChanged() {
+ return this.slides.subscribable;
+ }
+ private readonly slides = new ValueDispatcher<Slide[]>([]);
+
+ public readonly stage = new Stage();
+
+ private readonly lock = new Semaphore();
+ public readonly playback: PlaybackManager;
+ private readonly status: PlaybackStatus;
+ private readonly logger: Logger;
+ private abortController: AbortController | null = null;
+ private renderTime = 0;
+ private requestId: number | null = null;
+ private requestedResume = false;
+ private requestedSlide:
+ | string
+ | typeof NextSlide
+ | typeof PreviousSlide
+ | null = null;
+
+ public constructor(private project: Project) {
+ this.logger = project.logger;
+ this.playback = new PlaybackManager();
+ this.status = new PlaybackStatus(this.playback);
+ const scenes: Scene[] = [];
+ for (const description of project.scenes) {
+ const scene = new description.klass({
+ ...description,
+ meta: description.meta.clone(),
+ logger: this.logger,
+ playback: this.status,
+ size: new Vector2(1920, 1080),
+ timeEventsClass: ReadOnlyTimeEvents,
+ });
+ scenes.push(scene);
+ }
+ this.playback.setup(scenes);
+ }
+
+ /**
+ * Present the animation.
+ *
+ * @param settings - The presentation settings.
+ */
+ public async present(settings: PresenterSettings) {
+ if (this.state.current !== PresenterState.Initial) return;
+ await this.lock.acquire();
+ this.state.current = PresenterState.Working;
+ try {
+ this.abortController = new AbortController();
+ await this.run(settings, this.abortController.signal);
+ } catch (e: any) {
+ this.project.logger.error(e);
+ }
+
+ this.state.current = PresenterState.Initial;
+ this.lock.release();
+ }
+
+ /**
+ * Abort the ongoing presentation process.
+ */
+ public abort() {
+ if (this.state.current === PresenterState.Initial) return;
+ this.abortController?.abort();
+ this.state.current = PresenterState.Aborting;
+ }
+
+ /**
+ * Resume the presentation if waiting for the next slide.
+ */
+ public resume() {
+ this.requestedResume = true;
+ }
+
+ public requestFirstSlide() {
+ const first = this.playback.slides[0];
+ if (first) {
+ this.requestedSlide = first.id;
+ }
+ }
+
+ public requestLastSlide() {
+ const last = this.playback.slides.at(-1);
+ if (last) {
+ this.requestedSlide = last.id;
+ }
+ }
+
+ public requestPreviousSlide() {
+ this.requestedSlide = PreviousSlide;
+ }
+
+ public requestNextSlide() {
+ this.requestedSlide = NextSlide;
+ }
+
+ public requestSlide(id: string) {
+ this.requestedSlide = id;
+ }
+
+ private async run(settings: PresenterSettings, signal: AbortSignal) {
+ this.stage.configure(settings);
+ this.playback.fps = settings.fps;
+
+ await this.reloadScenes(settings.size);
+ if (signal.aborted) return;
+ this.playback.state = PlaybackState.Playing;
+ await this.playback.recalculate();
+ if (signal.aborted) return;
+ this.slides.current = this.playback.slides;
+ this.playback.state = PlaybackState.Presenting;
+ await this.playback.reset();
+ if (signal.aborted) return;
+
+ if (settings.slide) {
+ await this.playback.goTo(settings.slide);
+ if (signal.aborted) return;
+ }
+
+ await new Promise(resolve => {
+ signal.addEventListener('abort', resolve);
+ this.request();
+ });
+ }
+
+ private async reloadScenes(size: Vector2) {
+ for (let i = 0; i < this.project.scenes.length; i++) {
+ const description = this.project.scenes[i];
+ const scene = this.playback.onScenesRecalculated.current[i];
+ scene.reload({
+ config: description.onReplaced.current.config,
+ size: size,
+ });
+ scene.meta.set(description.meta.get());
+ }
+ }
+
+ private async loop() {
+ const slide = this.requestedSlide;
+ const resume = this.requestedResume;
+ this.requestedResume = false;
+ this.requestedSlide = null;
+
+ // Resume the presentation
+ if (resume) {
+ this.playback.currentScene.slides.resume();
+ }
+
+ // Seek to the given slide
+ if (slide !== null) {
+ this.logger.profile('slide time');
+ this.playback.state = PlaybackState.Playing;
+ if (slide === PreviousSlide) {
+ await this.playback.goBack();
+ } else if (slide === NextSlide) {
+ await this.playback.goForward();
+ } else {
+ await this.playback.goTo(slide);
+ }
+ this.logger.profile('slide time');
+ }
+
+ // Move forward one frame
+ else if (!this.playback.finished) {
+ this.playback.state = PlaybackState.Presenting;
+ await this.playback.progress();
+ }
+
+ // Draw the project
+ await this.stage.render(
+ this.playback.currentScene,
+ this.playback.previousScene,
+ );
+
+ if (!this.abortController?.signal.aborted) {
+ this.updateInfo();
+ this.request();
+ }
+ }
+
+ private request() {
+ if (this.abortController?.signal.aborted) {
+ return;
+ }
+
+ this.requestId ??= requestAnimationFrame(async time => {
+ this.requestId = null;
+ if (time - this.renderTime >= 1000 / (this.status.fps + 5)) {
+ this.renderTime = time;
+ try {
+ await this.loop();
+ } catch (e: any) {
+ this.logger.error(e);
+ this.abortController?.abort();
+ }
+ } else {
+ this.request();
+ }
+ });
+ }
+
+ private updateInfo() {
+ const slides = this.playback.currentScene.slides;
+ const currentSlide = slides.getCurrent() ?? null;
+ const index = this.playback.slides.indexOf(currentSlide!);
+
+ const info: PresenterInfo = {
+ currentSlideId: currentSlide?.id ?? null,
+ nextSlideId: this.playback.slides[index + 1]?.id ?? null,
+ hasNext: index !== null && index < this.playback.slides.length - 1,
+ hasPrevious: index !== null && index > 0,
+ isWaiting: slides.isWaiting(),
+ count: this.playback.slides.length,
+ index,
+ };
+
+ for (const [key, value] of Object.entries(info)) {
+ if (this.info.current[key] !== value) {
+ this.info.current = info;
+ break;
+ }
+ }
+ }
+}
diff --git a/packages/core/src/app/Renderer.ts b/packages/core/src/app/Renderer.ts
index 273bf947..af791075 100644
--- a/packages/core/src/app/Renderer.ts
+++ b/packages/core/src/app/Renderer.ts
@@ -1,10 +1,10 @@
-import {Project} from './Project';
+import type {Project} from './Project';
+import type {Exporter} from './Exporter';
+import type {Scene} from '../scenes';
import {PlaybackManager, PlaybackState} from './PlaybackManager';
import {Stage, StageSettings} from './Stage';
-import {Scene} from '../scenes';
import {EventDispatcher, ValueDispatcher} from '../events';
import {ImageExporter} from './ImageExporter';
-import {Exporter} from './Exporter';
import {CanvasOutputMimeType, Vector2} from '../types';
import {PlaybackStatus} from './PlaybackStatus';
import {Semaphore} from '../utils';
diff --git a/packages/core/src/app/index.ts b/packages/core/src/app/index.ts
index f960e49c..ac25aa04 100644
--- a/packages/core/src/app/index.ts
+++ b/packages/core/src/app/index.ts
@@ -10,6 +10,7 @@ export * from './Logger';
export * from './PlaybackManager';
export * from './PlaybackStatus';
export * from './Player';
+export * from './Presenter';
export * from './Project';
export * from './ProjectMetadata';
export * from './Renderer';
diff --git a/packages/core/src/meta/MetaFile.ts b/packages/core/src/meta/MetaFile.ts
index da59a472..0e08c89b 100644
--- a/packages/core/src/meta/MetaFile.ts
+++ b/packages/core/src/meta/MetaFile.ts
@@ -1,5 +1,5 @@
+import type {MetaField} from './MetaField';
import {Semaphore, useLogger} from '../utils';
-import {MetaField} from './MetaField';
/**
* Represents the meta file of a given entity.
diff --git a/packages/core/src/meta/index.ts b/packages/core/src/meta/index.ts
index 5cd82d66..cd545b46 100644
--- a/packages/core/src/meta/index.ts
+++ b/packages/core/src/meta/index.ts
@@ -4,9 +4,9 @@
* @packageDocumentation
*/
+export * from './ObjectMetaField';
export * from './ColorMetaField';
export * from './MetaField';
export * from './MetaFile';
-export * from './ObjectMetaField';
export * from './RangeMetaField';
export * from './Vector2MetaField';
diff --git a/packages/core/src/scenes/GeneratorScene.ts b/packages/core/src/scenes/GeneratorScene.ts
index 7cc41c6e..8aa9c409 100644
--- a/packages/core/src/scenes/GeneratorScene.ts
+++ b/packages/core/src/scenes/GeneratorScene.ts
@@ -25,6 +25,7 @@ import {SceneState} from './SceneState';
import {Random} from './Random';
import {DependencyContext} from '../signals';
import {SceneMetadata} from './SceneMetadata';
+import {Slides} from './Slides';
export interface ThreadGeneratorFactory<T> {
(view: T): ThreadGenerator;
@@ -43,6 +44,7 @@ export abstract class GeneratorScene<T>
public readonly logger: Logger;
public readonly meta: SceneMetadata;
public readonly timeEvents: TimeEvents;
+ public readonly slides: Slides;
public readonly variables: Variables;
public random: Random;
public creationStack?: string;
@@ -127,6 +129,7 @@ export abstract class GeneratorScene<T>
decorate(this.runnerFactory, threadable(this.name));
this.timeEvents = new description.timeEventsClass(this);
this.variables = new Variables(this);
+ this.slides = new Slides(this);
this.random = new Random(this.meta.seed.get());
}
diff --git a/packages/core/src/scenes/Scene.ts b/packages/core/src/scenes/Scene.ts
index 920eb2c4..019eb2a2 100644
--- a/packages/core/src/scenes/Scene.ts
+++ b/packages/core/src/scenes/Scene.ts
@@ -10,6 +10,7 @@ import type {Vector2} from '../types';
import type {LifecycleEvents} from './LifecycleEvents';
import type {Random} from './Random';
import type {SceneMetadata} from './SceneMetadata';
+import type {Slides} from './Slides';
/**
* The constructor used when creating new scenes.
@@ -133,6 +134,7 @@ export interface Scene<T = unknown> {
*/
readonly playback: PlaybackStatus;
readonly timeEvents: TimeEvents;
+ readonly slides: Slides;
readonly logger: Logger;
readonly variables: Variables;
readonly random: Random;
diff --git a/packages/core/src/scenes/Slides.ts b/packages/core/src/scenes/Slides.ts
new file mode 100644
index 00000000..47c08f8b
--- /dev/null
+++ b/packages/core/src/scenes/Slides.ts
@@ -0,0 +1,145 @@
+import type {Scene} from './Scene';
+import {PlaybackState} from '../app/PlaybackManager';
+import {ValueDispatcher} from '../events';
+
+export interface Slide {
+ id: string;
+ name: string;
+ time: number;
+ scene: Scene;
+}
+
+export class Slides {
+ public get onChanged() {
+ return this.slides.subscribable;
+ }
+ private readonly slides = new ValueDispatcher<Slide[]>([]);
+
+ private readonly lookup = new Map<string, Slide>();
+ private readonly collisionLookup = new Set<string>();
+ private current: Slide | null = null;
+ private canResume = false;
+ private waitsForId: string | null = null;
+ private targetId: string | null = null;
+
+ public constructor(private readonly scene: Scene) {
+ this.scene.onReloaded.subscribe(this.handleReload);
+ this.scene.onReset.subscribe(this.handleReset);
+ this.scene.onRecalculated.subscribe(this.handleRecalculated);
+ }
+
+ public setTarget(target: string | null) {
+ this.targetId = target;
+ }
+
+ public resume() {
+ this.canResume = true;
+ }
+
+ public isWaitingFor(slide: string) {
+ return this.waitsForId === slide;
+ }
+
+ public isWaiting() {
+ return this.waitsForId !== null;
+ }
+
+ public didHappen(slide: string) {
+ if (this.current === null) {
+ return false;
+ }
+
+ for (const key of this.lookup.keys()) {
+ if (key === slide) {
+ return true;
+ }
+ if (key === this.current?.id) {
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ public getCurrent() {
+ return this.current;
+ }
+
+ public register(name: string, initialTime: number) {
+ if (this.waitsForId !== null) {
+ throw new Error(
+ `The animation already waits for a slide: ${this.waitsForId}.`,
+ );
+ }
+
+ const id = this.toId(name);
+ if (this.scene.playback.state !== PlaybackState.Presenting) {
+ if (!this.lookup.has(id)) {
+ this.lookup.set(id, {
+ id,
+ name,
+ time: initialTime,
+ scene: this.scene,
+ });
+ }
+
+ if (this.collisionLookup.has(name)) {
+ this.scene.logger.warn({
+ message: `A slide named "${name}" already exists.`,
+ stack: new Error().stack,
+ });
+ } else {
+ this.collisionLookup.add(name);
+ }
+ }
+
+ this.waitsForId = id;
+ this.current = this.lookup.get(id) ?? null;
+ this.canResume = false;
+ }
+
+ public shouldWait(name: string): boolean {
+ const id = this.toId(name);
+ if (this.waitsForId !== id) {
+ throw new Error(
+ `The animation waits for a different slide: ${this.waitsForId}.`,
+ );
+ }
+ const data = this.lookup.get(id);
+ if (!data) {
+ throw new Error(`Could not find the "${name}" slide.`);
+ }
+
+ let canResume = this.canResume;
+ if (this.scene.playback.state !== PlaybackState.Presenting) {
+ canResume = id !== this.targetId;
+ }
+
+ if (canResume) {
+ this.waitsForId = null;
+ }
+ return !canResume;
+ }
+
+ private handleReload = () => {
+ this.lookup.clear();
+ this.collisionLookup.clear();
+ this.current = null;
+ this.waitsForId = null;
+ this.targetId = null;
+ };
+
+ private handleReset = () => {
+ this.collisionLookup.clear();
+ this.current = null;
+ this.waitsForId = null;
+ };
+
+ private handleRecalculated = () => {
+ this.slides.current = [...this.lookup.values()];
+ };
+
+ private toId(name: string) {
+ return `${this.scene.name}:${name}`;
+ }
+}
diff --git a/packages/core/src/scenes/index.ts b/packages/core/src/scenes/index.ts
index acbeff04..1d13251e 100644
--- a/packages/core/src/scenes/index.ts
+++ b/packages/core/src/scenes/index.ts
@@ -10,6 +10,7 @@ export * from './Random';
export * from './Scene';
export * from './SceneMetadata';
export * from './SceneState';
+export * from './Slides';
export * from './Threadable';
export * from './Variables';
export * from './LifecycleEvents';
diff --git a/packages/core/src/utils/beginSlide.ts b/packages/core/src/utils/beginSlide.ts
new file mode 100644
index 00000000..8f7c9feb
--- /dev/null
+++ b/packages/core/src/utils/beginSlide.ts
@@ -0,0 +1,14 @@
+import type {ThreadGenerator} from '../threading';
+import {useScene} from './useScene';
+import {useThread} from './useThread';
+
+export function* beginSlide(name: string): ThreadGenerator {
+ const {slides} = useScene();
+ const thread = useThread();
+ slides.register(name, thread.fixed);
+ yield;
+
+ while (slides.shouldWait(name)) {
+ yield;
+ }
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 44d1bbdc..617b155c 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -4,6 +4,7 @@
* @packageDocumentation
*/
+export * from './beginSlide';
export * from './capitalize';
export * from './debug';
export * from './deprecate';