Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Engine hooks #21

Merged
merged 1 commit into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/few-schools-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ineka/engine": minor
---

Added hooks to execute code at engine's key locations
26 changes: 26 additions & 0 deletions src/core/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export class Engine {
fullscreen: true,
container: 'body',
framerate: null,
hooks: {
beforeStep: async () => { },
afterStep: async () => { },
},
...options,
}
this._container = document.querySelector(this._options.container as string) as HTMLElement
Expand Down Expand Up @@ -98,6 +102,17 @@ export class Engine {
* to fix the timestep for fixed update loops (useful for physics and user interactions).
*/
protected step(now: number): void {
// Call beforeStep hook
try {
if (!this.options.hooks || !this.options.hooks.beforeStep) {
throw new EngineError(this, 'ENGINE:FAILURE', 'No beforeStep hook given to engine.')
}
this.options.hooks.beforeStep()
}
catch (err) {
console.error(err)
}

if (!this.rootNode) {
throw new EngineError(this, 'ENGINE:FAILURE', 'No root node given to engine, cannot run.')
}
Expand All @@ -118,6 +133,17 @@ export class Engine {
system.step(this.time.delta)
})
this.rootNode.step(this.time.delta)
// Call afterStep hook
try {
if (!this.options.hooks || !this.options.hooks.afterStep) {
throw new EngineError(this, 'ENGINE:FAILURE', 'No afterStep hook given to engine.')
}
this.options.hooks.afterStep()
}
catch (err) {
console.error(err)
}

// Request next step
requestAnimationFrame(this.step.bind(this))
}
Expand Down
16 changes: 16 additions & 0 deletions src/types/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,20 @@ export interface EngineOptions {
* @default null
*/
framerate?: number | null

/**
* Hooks are functions that are called at specific points in the engine's runtime.
*/
hooks?: {
/**
* Called before the engine's step loop.
* @default async () => { }
*/
beforeStep: () => Promise<void>
/**
* Called after the engine's step loop.
* @default async () => { }
*/
afterStep: () => Promise<void>
}
}