forked from manthrax/THREE-CSGMesh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
csg-worker.js
75 lines (66 loc) · 2.12 KB
/
csg-worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const CSG = require("./csg-lib.js");
let gWorkersStarted = false;
let gWorker;
let gWorkerUrl;
let taskId = 0;
let tasks={}
let spawnWorker=()=>{
const worker = new Worker(gWorkerUrl)
worker.onmessage = function(e) {
let rslt = JSON.parse(e.data)
let task = tasks[rslt.taskId]
delete tasks[rslt.taskId]
task.resolve(CSG.fromJSON(rslt.result))
//console.log('Message received from worker');
gWorker.busy = false;
}
return gWorker = {worker,busy:false};
}
let getWorker=()=>{
if(!gWorkersStarted){
gWorkersStarted = true;
return fetch('../csg-lib.js').then(function(response) {
return response.text().then(function(text) {
text = text.slice(0, text.lastIndexOf('export'));
const code = text + `
self.onmessage=(message)=>{
let task = JSON.parse(message.data)
//console.log("Got task:"+task.op+' '+task.taskId)
postMessage(JSON.stringify({
taskId:task.taskId,
result : CSG.fromJSON(task.a)[task.op](CSG.fromJSON(task.b))
}))
}
console.log('CSG worker started!')`
const blob = new Blob([code],{
type: 'application/javascript'
})
gWorkerUrl = URL.createObjectURL(blob);
}).then(()=>{
return spawnWorker()
})
});
}
if(gWorker && (!gWorker.busy)){
gWorker.busy = true;
return {then:(fn)=>{return fn(gWorker);}}
}
return{
then:function(){return this}
}
}
CSG.doAsync=(a,op,b)=>{
return getWorker().then((worker)=>{
let task={a,op,b,taskId}
tasks[taskId]=task;
taskId++;
task.result = new Promise((resolve,reject)=>{
task.resolve = resolve;
//console.log("posting to worker:")
worker.busy = true;
worker.worker.postMessage(JSON.stringify(task))
})
return task.result
})
}
module.exports = CSG;