-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.ts
230 lines (211 loc) · 8.87 KB
/
index.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import GUI from 'lil-gui';
import * as Stats from 'stats.js';
import { threads } from 'wasm-feature-detect';
import { SelfCollisionDemo, SelfCollisionDemoConfig } from './src/self_collision_15';
import { ClothDemo, ClothDemoConfig } from './src/cloth_14';
import { HashDemo, HashDemoConfig } from './src/hashing_11';
import { Demo, Scene, Scene2DCanvas, Scene2DWebGL, Scene3D, SceneConfig, Scene2DConfig, Scene3DConfig, initThreeScene, resizeThreeScene } from './src/lib';
import { SoftBodiesDemo, SoftBodiesDemoConfig } from './src/softbodies_10';
import { SkinnedSoftbodyDemo, SkinnedSoftbodyDemoConfig } from './src/softbody_skinning_12';
import { FluidDemo, FluidDemoConfig } from './src/fluid_sim_17';
import { FlipDemo, FlipDemoConfig } from './src/flip_18';
import { BodyChainDemo, BodyChainDemoConfig } from './src/body_chain_challenge';
import { PositionBasedFluidDemo, PositionBasedFluidDemoConfig } from './src/fluid_2d_challenge';
import { ParallelClothDemo, ParallelClothDemoConfig } from './src/parallel_cloth_16';
import { FractalsDemo, FractalsDemoConfig } from './src/fractals_19';
import { HeightFieldWaterDemo, HeightFieldWaterDemoConfig } from './src/heightfield_water_20';
import { FireDemo, FireDemoConfig } from './src/fire_21';
import('./pkg').then(async rust_wasm => {
const { memory } = await rust_wasm.default();
const $ = (id: string) => document.getElementById(id);
let demos: Record<string, { title: string, config: SceneConfig, demo: any }> = {
'Chall-Body-Chain': {
title: 'Chain of 100 Bodies',
config: BodyChainDemoConfig,
demo: BodyChainDemo,
},
'Chall-2D-Fluid': {
title: '2D Particle Fluid',
config: PositionBasedFluidDemoConfig,
demo: PositionBasedFluidDemo,
},
'10-SoftBodies': {
title: 'Soft Body Simulation',
config: SoftBodiesDemoConfig,
demo: SoftBodiesDemo,
},
'11-Hashing': {
title: 'Spatial Hashing',
config: HashDemoConfig,
demo: HashDemo,
},
'12-SoftbodySkinning': {
title: 'Soft Body Skinning',
config: SkinnedSoftbodyDemoConfig,
demo: SkinnedSoftbodyDemo,
},
'14-Cloth': {
title: 'Cloth Simulation',
config: ClothDemoConfig,
demo: ClothDemo,
},
'15-SelfCollision': {
title: 'Cloth Self Collision Handling',
config: SelfCollisionDemoConfig,
demo: SelfCollisionDemo,
},
'16-ParallelCloth': {
title: 'Parallel Cloth Solver',
config: ParallelClothDemoConfig,
demo: ParallelClothDemo,
},
'17-FluidSimulation': {
title: 'Euler Fluid',
config: FluidDemoConfig,
demo: FluidDemo,
},
'18-Flip': {
title: 'Flip Fluid',
config: FlipDemoConfig,
demo: FlipDemo,
},
'19-Fractals': {
title: 'Fractals',
config: FractalsDemoConfig,
demo: FractalsDemo,
},
'20-HeightFieldWater': {
title: 'Height Field Water',
config: HeightFieldWaterDemoConfig,
demo: HeightFieldWaterDemo,
},
'21-Fire': {
title: 'Fire Simulation',
config: FireDemoConfig,
demo: FireDemo,
},
};
let canvas = $('canvas') as HTMLCanvasElement;
// check if required features are supported, else remove unsupported demos
if (!Boolean((window as any).chrome) || !(await threads()) || !HTMLCanvasElement.prototype.transferControlToOffscreen) {
console.log("Required features not supported for 16-ParallelCloth. Disabling selection.");
delete demos['16-ParallelCloth'];
}
const demoNames = Object.keys(demos);
let demo: Demo<any, any>;
let scene: Scene;
const replaceCanvas = () => {
// some demos modify text color for contrast; reset
document.getElementById('info').removeAttribute("style");
// replace canvas element so we can get a new rendering context
let newCanvas = document.createElement('canvas');
canvas.parentNode.replaceChild(newCanvas, canvas);
canvas = newCanvas;
}
const init2DScene = (config: Scene2DConfig): Scene2DCanvas | Scene2DWebGL => {
replaceCanvas();
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let context;
let kind = config.kind;
if (kind === "2DCanvas") {
context = canvas.getContext('2d', { desynchronized: true });
return { kind, width: canvas.width, height: canvas.height, context };
} else if (kind === "2DWebGL") {
context = canvas.getContext('webgl2', { antialias: true, desynchronized: true, powerPreference: "high-performance" });
return { kind, width: canvas.width, height: canvas.height, context };
} else {
throw "unreachable";
}
}
const init3DScene = (config: Scene3DConfig): Scene3D => {
replaceCanvas();
return initThreeScene(canvas, canvas, config, window.innerWidth, window.innerHeight, window.devicePixelRatio);
};
let resizeTimer: NodeJS.Timeout; // limit 2d resize events to once per 250ms
window.addEventListener('resize', () => {
if (scene.kind === "3D") {
if (scene.offscreen) {
// for offscreen, the worker owns the scene and must handle the resize event
demo.resize(window.innerWidth / window.devicePixelRatio, window.innerHeight / window.devicePixelRatio);
} else {
// for 3d, THREE.js can non-destructively update the renderer
resizeThreeScene(scene, window.innerWidth, window.innerHeight, true);
}
} else {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
// for 2d, we generally need to reload the demo
initDemo(props.demoSelection);
}, 250);
}
});
// attach perf stats window
const stats = new Stats();
stats.dom.style.position = 'absolute';
const simPanel = stats.addPanel(new Stats.Panel('MS (Sim)', '#ff8', '#221'));
let maxSimMs = 1;
stats.showPanel(stats.dom.children.length - 1); // ms per sim step
$('container').appendChild(stats.dom);
// populate controls window
const props = {
demoSelection: demoNames[Math.floor(Math.random() * demoNames.length)], // default to a random demo
reset: () => demo.reset(),
}
const gui = new GUI({ autoPlace: false });
gui.domElement.style.opacity = '0.9';
$('gui').appendChild(gui.domElement);
const generalFolder = gui.addFolder('General');
let demoFolder: GUI;
const initDemo = async (sid: string) => {
if (demoFolder) demoFolder.destroy();
demoFolder = gui.addFolder('Demo Settings');
const config = demos[sid].config;
if (config.kind === "3D" && config.offscreen === true) {
scene = { kind: "3D", offscreen: true };
} else if (config.kind === "3D") {
scene = init3DScene(config);
} else {
scene = init2DScene(config);
}
$('title').innerText = demos[sid].title;
// cleanup existing demo if required
if (demo?.free) {
demo.free();
}
if (config.kind === "3D" && config.offscreen) {
replaceCanvas();
canvas.width = window.innerWidth / window.devicePixelRatio;
canvas.height = window.innerHeight / window.devicePixelRatio;
demo = new demos[sid].demo(canvas.transferControlToOffscreen(), canvas, config, demoFolder, stats, simPanel);
} else {
demo = new demos[sid].demo(rust_wasm, memory, canvas, scene, demoFolder);
}
await demo.init();
}
generalFolder.add(props, 'demoSelection', demoNames).name('select demo').onFinishChange(await initDemo);
generalFolder.add(props, 'reset').name('reset simulation');
// default init
await initDemo(props.demoSelection);
// main loop
const animate = () => {
if (scene.kind === "3D" && scene.offscreen) {
requestAnimationFrame(animate); // noop for offscreen canvas, main loop in web worker
return;
};
stats.begin(); // collect perf data for stats.js
let simTimeMs = performance.now();
demo.update();
simTimeMs = performance.now() - simTimeMs;
if (scene.kind === "3D") {
scene.renderer.render(scene.scene, scene.camera);
} else {
demo.draw();
}
simPanel.update(simTimeMs, (maxSimMs = Math.max(maxSimMs, simTimeMs)));
stats.end();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
}).catch(console.error);
export { initThreeScene };