vc.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function make_environment(...envs) {
  2. return new Proxy(envs, {
  3. get(target, prop, receiver) {
  4. for (let env of envs) {
  5. if (env.hasOwnProperty(prop)) {
  6. return env[prop];
  7. }
  8. }
  9. return (...args) => {console.error("NOT IMPLEMENTED: "+prop, args)}
  10. }
  11. });
  12. }
  13. const libm = {
  14. "atan2f": Math.atan2,
  15. "cosf": Math.cos,
  16. "sinf": Math.sin,
  17. "sqrtf": Math.sqrt,
  18. };
  19. async function startExample(elementId, wasmPath) {
  20. const app = document.getElementById(elementId);
  21. if (app === null) {
  22. console.error(`Could not find element ${elementId}. Skipping example ${wasmPath}...`);
  23. return;
  24. }
  25. app.width = 800;
  26. app.height = 600;
  27. const ctx = app.getContext("2d");
  28. const w = await WebAssembly.instantiateStreaming(fetch(wasmPath), {
  29. "env": make_environment(libm)
  30. });
  31. w.instance.exports.init();
  32. let prev = null;
  33. function first(timestamp) {
  34. prev = timestamp;
  35. window.requestAnimationFrame(loop);
  36. }
  37. function loop(timestamp) {
  38. const dt = timestamp - prev;
  39. prev = timestamp;
  40. const pixels = w.instance.exports.render(dt*0.001);
  41. const buffer = w.instance.exports.memory.buffer;
  42. const image = new ImageData(new Uint8ClampedArray(buffer, pixels, app.width*app.height*4), app.width);
  43. ctx.putImageData(image, 0, 0);
  44. window.requestAnimationFrame(loop);
  45. }
  46. window.requestAnimationFrame(first);
  47. }