Skip to content

Commit

Permalink
feat: added hooks to engine step loop
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinEspinas committed Oct 16, 2024
1 parent 9da26cb commit 8e4cafc
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
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>
}
}

0 comments on commit 8e4cafc

Please sign in to comment.