1
- import EventWorker from "./EventWorker.js" ;
2
1
import { DataSchema } from "./SharedData.js" ;
3
2
4
- function setListeners ( eventWorker , handlers , ctx = handlers ) {
5
- for ( const prop in handlers ) {
6
- eventWorker . setListener ( prop , handlers [ prop ] . bind ( ctx ) ) ;
7
- }
3
+ function setListeners ( /** @type {Worker } */ worker , handlers ) {
4
+ worker . onmessage = ( ev ) => {
5
+ if ( "topic" in ev . data && "data" in ev . data ) {
6
+ if ( ev . data . topic in handlers ) {
7
+ handlers [ ev . data . topic ] ( ...ev . data . data ) ;
8
+ } else {
9
+ throw new TypeError ( `No handler for ${ ev . data . topic } !` ) ;
10
+ }
11
+ } else {
12
+ throw new TypeError ( "Invalid message received!" ) ;
13
+ }
14
+ } ;
8
15
}
9
16
10
17
export default class RaylibJs {
@@ -18,7 +25,7 @@ export default class RaylibJs {
18
25
}
19
26
this . ctx = canvas . getContext ( "bitmaprenderer" ) ;
20
27
if ( this . worker === undefined ) {
21
- this . worker = new EventWorker ( "./raylib.js" , { type : "module" } ) ;
28
+ this . worker = new Worker ( "./raylib.js" , { type : "module" } ) ;
22
29
} else {
23
30
throw new Error ( "raylib.js worker already exists!" ) ;
24
31
}
@@ -32,15 +39,11 @@ export default class RaylibJs {
32
39
} ) ;
33
40
this . views = DataSchema . view ( shared ) ;
34
41
// bind listeners
35
- setListeners (
36
- this . worker ,
37
- {
38
- frame : this . #onFrame,
39
- window : this . #onWindow,
40
- requestAnimationFrame : this . #onRequestAnimationFrame,
41
- } ,
42
- this ,
43
- ) ;
42
+ setListeners ( this . worker , {
43
+ frame : this . #onFrame. bind ( this ) ,
44
+ window : this . #onWindow. bind ( this ) ,
45
+ requestAnimationFrame : this . #onRequestAnimationFrame. bind ( this ) ,
46
+ } ) ;
44
47
window . addEventListener ( "keydown" , ( e ) => {
45
48
const key = glfwKeyMapping [ e . code ] ;
46
49
this . views . keys [ ~ ~ ( key / 8 ) ] |= 1 << key % 8 ;
@@ -58,16 +61,8 @@ export default class RaylibJs {
58
61
} ) ;
59
62
60
63
// Initialize raylib.js worker
61
- return new Promise ( ( resolve ) => {
62
- this . worker . setListener ( "initialized" , ( ) => {
63
- this . worker . removeListener ( "initialized" ) ;
64
- // TODO: listen to real changss in boundingClientRect
65
- console . log ( "initialized" ) ;
66
- this . #setBoundingRect( ) ;
67
- resolve ( ) ;
68
- } ) ;
69
- this . worker . send ( "init" , { wasmPath, shared } ) ;
70
- } ) ;
64
+ this . #setBoundingRect( ) ;
65
+ this . worker . postMessage ( { wasmPath, shared } ) ;
71
66
}
72
67
73
68
stop ( ) {
0 commit comments