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

feat: add SceneWorker #12

Merged
merged 2 commits into from
Dec 28, 2023
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
80 changes: 80 additions & 0 deletions src/lib/SceneWorker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
const workerMessageHandler = (event: MessageEvent) => {
const id: number = event.data.id;
const functionName: string = event.data.functionName;
const functionArgs: any[] = event.data.functionArgs;
const transfer: Transferable[] = [];

try {
const fn = self[functionName];
const result = fn(...functionArgs);

if (ArrayBuffer.isView(result)) {
transfer.push(result.buffer);
} else if (result instanceof ArrayBuffer) {
transfer.push(result);
}

self.postMessage({ id, result, success: true }, { transfer });
} catch (error) {
self.postMessage({ id, result: error, success: false });
}
};

const contextToInlineUrl = (context: Record<any, any>) => {
const initializer = [];
for (const [rawKey, rawValue] of Object.entries(context)) {
let key = `'${rawKey.toString()}'`;

let value = rawValue;
if (typeof rawValue === 'function') {
value = rawValue.toString();
} else if (typeof rawValue === 'string' || typeof rawValue === 'object') {
value = JSON.stringify(rawValue);
}

initializer.push(`self[${key}] = `, value, ';', '\n\n');
}

initializer.push(`self['onmessage'] = `, workerMessageHandler.toString(), ';', '\n');

const blob = new Blob(initializer, { type: 'text/javascript' });
return URL.createObjectURL(blob);
};

class SceneWorker {
#worker: Worker;
#pending = new Map<number, { resolve: (value: any) => void; reject: (reason: any) => void }>();
#nextId = 0;

constructor(name: string, context: Record<any, any>) {
this.#worker = new Worker(contextToInlineUrl(context), { name });

this.#worker.onmessage = (event: MessageEvent) => {
const id: number = event.data.id;
const pending = this.#pending.get(id);

if (event.data.success) {
pending.resolve(event.data.result);
} else {
pending.reject(event.data.result);
}

this.#pending.delete(id);
};
}

call(name: string, ...args: any[]): Promise<any> {
const id = this.#nextId++;

const promise = new Promise((resolve, reject) => {
this.#pending.set(id, { resolve, reject });
});

this.#worker.postMessage({ id, functionName: name, functionArgs: args });

return promise;
}
}

export default SceneWorker;
export { SceneWorker };
1 change: 1 addition & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './controls/OrbitControls.js';
export * from './AssetManager.js';
export * from './FormatManager.js';
export * from './TextureManager.js';
export * from './SceneWorker.js';