three-rb 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -2
  3. data/README.md +14 -6
  4. data/docs/browser-runtime.md +10 -6
  5. data/docs/cloudflare-pages.md +205 -0
  6. data/docs/implementation-plan.md +6 -4
  7. data/docs/loaded-assets-design.md +1 -1
  8. data/docs/next-work.md +26 -25
  9. data/docs/publishing.md +4 -1
  10. data/docs/release-readiness.md +11 -11
  11. data/docs/standalone-browser-app.md +8 -2
  12. data/examples/browser/README.md +5 -1
  13. data/examples/browser/composition/index.html +65 -4
  14. data/examples/browser/composition/main.rb +2 -2
  15. data/examples/browser/cube/README.md +3 -3
  16. data/examples/browser/cube/index.html +61 -6
  17. data/examples/browser/cubemap/assets/checker.svg +11 -0
  18. data/examples/browser/cubemap/index.html +60 -5
  19. data/examples/browser/cubemap/main.rb +1 -1
  20. data/examples/browser/dango/README.md +26 -0
  21. data/examples/browser/dango/boot.mjs +6 -0
  22. data/examples/browser/dango/index.html +197 -0
  23. data/examples/browser/dango/main.rb +278 -0
  24. data/examples/browser/dango/smoke_test.mjs +232 -0
  25. data/examples/browser/gltf/index.html +60 -5
  26. data/examples/browser/gltf/main.rb +2 -2
  27. data/examples/browser/picking/index.html +61 -6
  28. data/examples/browser/postprocessing/index.html +61 -6
  29. data/examples/browser/primitives/assets/checker.svg +11 -0
  30. data/examples/browser/primitives/index.html +61 -6
  31. data/examples/browser/primitives/main.rb +1 -1
  32. data/examples/browser/ruby/README.md +2 -0
  33. data/examples/browser/ruby/assets/helvetiker_regular.typeface.json +1 -0
  34. data/examples/browser/ruby/index.html +112 -8
  35. data/examples/browser/ruby/main.rb +2 -6
  36. data/examples/browser/serialization/assets/checker.svg +11 -0
  37. data/examples/browser/serialization/index.html +61 -6
  38. data/examples/browser/serialization/main.rb +1 -1
  39. data/examples/browser/shared/boot.mjs +116 -14
  40. data/examples/browser/shared/config.mjs +3 -0
  41. data/examples/browser/shared/smoke_test_helpers.mjs +13 -8
  42. data/examples/browser/textures/assets/checker.svg +11 -0
  43. data/examples/browser/textures/index.html +61 -6
  44. data/examples/browser/textures/main.rb +2 -2
  45. data/exe/three-rb +1 -0
  46. data/lib/three/backends/threejs/parameters.rb +4 -1
  47. data/lib/three/backends/threejs/ruby_wasm_adapter.rb +8 -2
  48. data/lib/three/generators/browser_example.rb +220 -12
  49. data/lib/three/version.rb +1 -1
  50. data/package.json +9 -5
  51. data/pnpm-lock.yaml +1235 -31
  52. metadata +19 -7
  53. /data/examples/browser/{assets → composition/assets}/checker.svg +0 -0
  54. /data/examples/browser/{assets → gltf/assets}/animated_triangle.gltf +0 -0
  55. /data/examples/browser/{assets → gltf/assets}/compressed_triangle.gltf +0 -0
  56. /data/examples/browser/{assets → gltf/assets}/triangle.gltf +0 -0
  57. /data/examples/browser/{assets → textures/assets}/studio.hdr +0 -0
@@ -11,13 +11,17 @@ import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
11
11
  import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";
12
12
  import { DotScreenPass } from "three/addons/postprocessing/DotScreenPass.js";
13
13
  import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
14
+ import { rubyWasmUrl } from "./config.mjs";
15
+
16
+ const WASM_DOWNLOAD_ATTEMPTS = 3;
17
+ const WASM_STALL_TIMEOUT_MS = 20000;
14
18
 
15
19
  export async function bootRubyExample({ main, clearColor }) {
16
20
  const setStatus = globalThis.__threeRbSetStatus || (() => {});
17
21
  const bootFailed = globalThis.__threeRbBootFailed || ((message) => console.error(message));
18
22
 
19
23
  try {
20
- setStatus("Loading ruby.wasm", "loading");
24
+ setStatus("Preparing browser runtime", "loading", 4);
21
25
  globalThis.THREE = THREE;
22
26
  globalThis.THREE_GLTF_LOADER = GLTFLoader;
23
27
  globalThis.THREE_DRACO_LOADER = DRACOLoader;
@@ -49,11 +53,16 @@ export async function bootRubyExample({ main, clearColor }) {
49
53
  composer.render();
50
54
  };
51
55
 
52
- const rubyModule = await compileWasm("/node_modules/@ruby/3.4-wasm-wasi/dist/ruby+stdlib.wasm");
56
+ const rubyModule = await compileWasm(rubyWasmUrl, {
57
+ onProgress: (percent) => setStatus(`Loading ruby.wasm ${percent}%`, "loading", percent),
58
+ onRetry: (attempt, attempts) =>
59
+ setStatus(`Retrying ruby.wasm download (${attempt}/${attempts})`, "loading", 4)
60
+ });
61
+ setStatus("Compiling ruby.wasm", "loading", 82);
53
62
  const { vm } = await DefaultRubyVM(rubyModule);
54
63
  globalThis.rubyVM = vm;
55
64
 
56
- setStatus("Starting Ruby VM", "loading");
65
+ setStatus("Starting Ruby VM", "loading", 88);
57
66
  await withNoStoreRubySourceFetch(async () => {
58
67
  await vm.evalAsync(`
59
68
  require "js/require_remote/relative_shim"
@@ -90,22 +99,115 @@ function shouldBypassCache(input) {
90
99
  if (pathname.startsWith("/lib/")) return true;
91
100
  if (!pathname.startsWith("/examples/browser/")) return false;
92
101
 
93
- return !pathname.startsWith("/examples/browser/assets/");
102
+ return !pathname.includes("/assets/");
94
103
  }
95
104
 
96
- async function compileWasm(url) {
97
- const response = fetch(url);
98
- if (WebAssembly.compileStreaming) {
105
+ async function compileWasm(url, { onProgress = () => {}, onRetry = () => {} } = {}) {
106
+ let lastError;
107
+
108
+ for (let attempt = 1; attempt <= WASM_DOWNLOAD_ATTEMPTS; attempt += 1) {
109
+ if (attempt > 1) onRetry(attempt, WASM_DOWNLOAD_ATTEMPTS);
110
+
99
111
  try {
100
- return await WebAssembly.compileStreaming(response);
101
- } catch (_error) {
102
- // Fall back when a static server does not provide application/wasm.
112
+ return await compileWasmOnce(url, onProgress);
113
+ } catch (error) {
114
+ lastError = error;
103
115
  }
104
116
  }
105
117
 
106
- const fallbackResponse = await fetch(url);
107
- if (!fallbackResponse.ok) {
108
- throw new Error(`Failed to load ruby.wasm: ${fallbackResponse.status} ${fallbackResponse.statusText}`);
118
+ const reason = lastError && lastError.message ? lastError.message : "Failed to load ruby.wasm";
119
+
120
+ throw new Error(`${reason}. Try reloading the page.`, { cause: lastError });
121
+ }
122
+
123
+ async function compileWasmOnce(url, onProgress) {
124
+ const controller = new AbortController();
125
+ const stall = watchForStall(controller, WASM_STALL_TIMEOUT_MS);
126
+
127
+ try {
128
+ const response = await fetch(url, { signal: controller.signal });
129
+ if (!response.ok) {
130
+ throw new Error(`Failed to load ruby.wasm: ${response.status} ${response.statusText}`);
131
+ }
132
+
133
+ // Decide before reading the body. Falling back after the download has
134
+ // started would fetch the whole file a second time.
135
+ const canStream =
136
+ typeof WebAssembly.compileStreaming === "function" &&
137
+ (response.headers.get("content-type") || "").includes("application/wasm");
138
+ const tracked = trackDownload(response, {
139
+ onProgress: (percent) => {
140
+ stall.reset();
141
+ if (percent !== null) onProgress(percent);
142
+ },
143
+ onSettled: () => stall.cancel()
144
+ });
145
+
146
+ if (canStream) return await WebAssembly.compileStreaming(tracked);
147
+
148
+ return await WebAssembly.compile(await tracked.arrayBuffer());
149
+ } finally {
150
+ stall.cancel();
151
+ }
152
+ }
153
+
154
+ // A download that stops mid-stream never rejects on its own, which left the
155
+ // status line stuck on "Loading ruby.wasm" with nothing to retry it.
156
+ function watchForStall(controller, timeout) {
157
+ let cancelled = false;
158
+ let timer = globalThis.setTimeout(abort, timeout);
159
+
160
+ function abort() {
161
+ controller.abort(new Error(`ruby.wasm stopped downloading for ${Math.round(timeout / 1000)} seconds`));
109
162
  }
110
- return WebAssembly.compile(await fallbackResponse.arrayBuffer());
163
+
164
+ return {
165
+ reset() {
166
+ if (cancelled) return;
167
+
168
+ globalThis.clearTimeout(timer);
169
+ timer = globalThis.setTimeout(abort, timeout);
170
+ },
171
+ cancel() {
172
+ cancelled = true;
173
+ globalThis.clearTimeout(timer);
174
+ }
175
+ };
176
+ }
177
+
178
+ function trackDownload(response, { onProgress, onSettled }) {
179
+ if (!response.body) {
180
+ onSettled();
181
+ return response;
182
+ }
183
+
184
+ const total = Number(response.headers.get("content-length"));
185
+ const measurable = Number.isFinite(total) && total > 0;
186
+ let loaded = 0;
187
+ const stream = new ReadableStream({
188
+ async start(controller) {
189
+ const reader = response.body.getReader();
190
+ try {
191
+ while (true) {
192
+ const { done, value } = await reader.read();
193
+ if (done) break;
194
+
195
+ loaded += value.byteLength;
196
+ onProgress(measurable ? Math.min(80, Math.round((loaded / total) * 80)) : null);
197
+ controller.enqueue(value);
198
+ }
199
+ controller.close();
200
+ } catch (error) {
201
+ controller.error(error);
202
+ } finally {
203
+ onSettled();
204
+ }
205
+ }
206
+ });
207
+
208
+ return new Response(stream, {
209
+ headers: response.headers,
210
+ status: response.status,
211
+ statusText: response.statusText
212
+ });
111
213
  }
@@ -0,0 +1,3 @@
1
+ export const rubyWasmUrl =
2
+ globalThis.__threeRbRubyWasmUrl ||
3
+ "/node_modules/@ruby/3.4-wasm-wasi/dist/ruby+stdlib.wasm";
@@ -17,7 +17,7 @@ const mimeTypes = new Map([
17
17
  ]);
18
18
 
19
19
  export function createDiagnostics() {
20
- return { errors: [], requests: [] };
20
+ return { errors: [], warnings: [], requests: [] };
21
21
  }
22
22
 
23
23
  export async function loadPlaywright() {
@@ -35,6 +35,10 @@ export async function createSmokePage(browser, diagnostics, options = {}) {
35
35
  const page = await browser.newPage({ viewport: options.viewport || { width: 960, height: 540 } });
36
36
  page.on("console", (message) => {
37
37
  if (message.type() === "error") diagnostics.errors.push(message.text());
38
+ // three.js prefixes its warnings, which flag API misuse such as unknown
39
+ // material properties. Chromium's GPU driver messages are left out: they
40
+ // vary by machine and the canvas readback in these tests triggers them.
41
+ if (message.type() === "warning" && message.text().startsWith("THREE.")) diagnostics.warnings.push(message.text());
38
42
  });
39
43
  page.on("pageerror", (error) => diagnostics.errors.push(error.message));
40
44
  page.on("requestfailed", (request) => {
@@ -105,7 +109,7 @@ export function assertNonBlankCanvas(canvas) {
105
109
  }
106
110
 
107
111
  export function assertNoDiagnostics(diagnostics) {
108
- if (diagnostics.errors.length > 0 || diagnostics.requests.length > 0) {
112
+ if (diagnostics.errors.length > 0 || diagnostics.warnings.length > 0 || diagnostics.requests.length > 0) {
109
113
  throw new Error(diagnosticMessage("browser diagnostics", diagnostics));
110
114
  }
111
115
  }
@@ -113,15 +117,16 @@ export function assertNoDiagnostics(diagnostics) {
113
117
  export function diagnosticMessage(message, diagnostics) {
114
118
  const sections = [message];
115
119
  if (diagnostics.errors.length > 0) sections.push(`console/page errors:\n${diagnostics.errors.join("\n")}`);
120
+ if (diagnostics.warnings.length > 0) sections.push(`three.js warnings:\n${diagnostics.warnings.join("\n")}`);
116
121
  if (diagnostics.requests.length > 0) sections.push(`network diagnostics:\n${diagnostics.requests.join("\n")}`);
117
122
  return sections.join("\n\n");
118
123
  }
119
124
 
120
- export function startServer() {
125
+ export function startServer(serverRoot = root) {
121
126
  const server = createServer(async (request, response) => {
122
127
  try {
123
128
  const pathname = decodeURIComponent(new URL(request.url, "http://127.0.0.1").pathname);
124
- const filePath = await resolveFile(pathname);
129
+ const filePath = await resolveFile(pathname, serverRoot);
125
130
  response.setHeader("Content-Type", mimeTypes.get(extname(filePath)) || "application/octet-stream");
126
131
  response.end(await readFile(filePath));
127
132
  } catch (error) {
@@ -139,11 +144,11 @@ export function startServer() {
139
144
  });
140
145
  }
141
146
 
142
- async function resolveFile(pathname) {
147
+ async function resolveFile(pathname, serverRoot) {
143
148
  const requested = pathname.endsWith("/") ? `${pathname}index.html` : pathname;
144
- const filePath = normalize(join(root, requested));
145
- const rel = relative(root, filePath);
146
- if (rel.startsWith("..")) throw new Error("request escaped repository root");
149
+ const filePath = normalize(join(serverRoot, requested));
150
+ const rel = relative(serverRoot, filePath);
151
+ if (rel.startsWith("..")) throw new Error("request escaped server root");
147
152
 
148
153
  const info = await stat(filePath);
149
154
  if (info.isDirectory()) return join(filePath, "index.html");
@@ -0,0 +1,11 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128">
2
+ <rect width="128" height="128" fill="#eef3f7"/>
3
+ <rect width="32" height="32" fill="#22313f"/>
4
+ <rect x="64" width="32" height="32" fill="#22313f"/>
5
+ <rect x="32" y="32" width="32" height="32" fill="#6ed69a"/>
6
+ <rect x="96" y="32" width="32" height="32" fill="#6ed69a"/>
7
+ <rect y="64" width="32" height="32" fill="#22313f"/>
8
+ <rect x="64" y="64" width="32" height="32" fill="#22313f"/>
9
+ <rect x="32" y="96" width="32" height="32" fill="#6ed69a"/>
10
+ <rect x="96" y="96" width="32" height="32" fill="#6ed69a"/>
11
+ </svg>
@@ -54,10 +54,12 @@
54
54
  position: absolute;
55
55
  top: 16px;
56
56
  left: 16px;
57
- display: flex;
57
+ display: grid;
58
+ grid-template-columns: auto minmax(0, 1fr);
58
59
  align-items: center;
59
60
  gap: 8px;
60
61
  max-width: calc(100% - 32px);
62
+ min-width: min(360px, calc(100% - 32px));
61
63
  padding: 8px 10px;
62
64
  border: 1px solid rgba(255, 255, 255, 0.14);
63
65
  border-radius: 6px;
@@ -87,6 +89,44 @@
87
89
  background: #f15b5b;
88
90
  box-shadow: 0 0 14px rgba(241, 91, 91, 0.72);
89
91
  }
92
+
93
+ .status-dot[data-state="loading"] {
94
+ animation: status-dot-pulse 1.2s ease-in-out infinite;
95
+ }
96
+
97
+ @keyframes status-dot-pulse {
98
+ 0%,
99
+ 100% {
100
+ opacity: 1;
101
+ transform: scale(1);
102
+ }
103
+
104
+ 50% {
105
+ opacity: 0.4;
106
+ transform: scale(0.75);
107
+ }
108
+ }
109
+
110
+ .progress {
111
+ grid-column: 1 / -1;
112
+ width: 100%;
113
+ height: 4px;
114
+ overflow: hidden;
115
+ border-radius: 999px;
116
+ background: rgba(255, 255, 255, 0.16);
117
+ }
118
+
119
+ .progress-bar {
120
+ width: 4%;
121
+ height: 100%;
122
+ border-radius: inherit;
123
+ background: linear-gradient(90deg, #55ace0, #60d394);
124
+ transition: width 180ms ease;
125
+ }
126
+
127
+ .progress[hidden] {
128
+ display: none;
129
+ }
90
130
  </style>
91
131
  <script type="importmap">
92
132
  {
@@ -101,10 +141,22 @@
101
141
  <script type="module">
102
142
  const status = document.querySelector("#status");
103
143
  const statusDot = document.querySelector("#status-dot");
144
+ const progress = document.querySelector("#progress");
145
+ const progressBar = document.querySelector("#progress-bar");
104
146
 
105
- globalThis.__threeRbSetStatus = (message, state) => {
147
+ globalThis.__threeRbSetStatus = (message, state, percent) => {
106
148
  if (status) status.textContent = message;
107
149
  if (statusDot) statusDot.dataset.state = state;
150
+ if (progress && progressBar) {
151
+ if (state === "running" || state === "error") {
152
+ progress.hidden = true;
153
+ } else {
154
+ progress.hidden = false;
155
+ if (Number.isFinite(percent)) {
156
+ progressBar.style.width = `${Math.max(4, Math.min(100, percent))}%`;
157
+ }
158
+ }
159
+ }
108
160
  };
109
161
 
110
162
  globalThis.__threeRbBootFailed = (message) => {
@@ -121,12 +173,12 @@
121
173
  });
122
174
 
123
175
  globalThis.setTimeout(() => {
124
- if (status && status.textContent === "Loading ruby.wasm") {
125
- status.textContent = "Still loading ruby.wasm";
176
+ if (status && statusDot && statusDot.dataset.state === "loading") {
177
+ status.textContent = "Still loading after 15 seconds. Try reloading the page.";
126
178
  }
127
179
  }, 15000);
128
180
 
129
- globalThis.__threeRbSetStatus("Loading ruby.wasm", "loading");
181
+ globalThis.__threeRbSetStatus("Loading ruby.wasm", "loading", 4);
130
182
  </script>
131
183
  <script type="module" src="./boot.mjs"></script>
132
184
  </head>
@@ -134,8 +186,11 @@
134
186
  <main class="viewport" id="viewport">
135
187
  <canvas id="scene" data-testid="scene-canvas"></canvas>
136
188
  <div class="hud" aria-live="polite">
137
- <span class="status-dot" id="status-dot"></span>
189
+ <span class="status-dot" id="status-dot" data-state="loading"></span>
138
190
  <span id="status" data-testid="status">Loading ruby.wasm</span>
191
+ <div class="progress" id="progress" aria-hidden="true">
192
+ <div class="progress-bar" id="progress-bar"></div>
193
+ </div>
139
194
  </div>
140
195
  </main>
141
196
  </body>
@@ -7,7 +7,7 @@ Three::Browser.run(starting: "Starting Ruby scene") do |app|
7
7
  camera = Three::OrthographicCamera.new(-2.5, 2.5, 1.6, -1.6, near: 0.1, far: 100)
8
8
  camera.position.z = 5
9
9
 
10
- environment_texture = Three::Loaders::RGBELoader.new.load("/examples/browser/assets/studio.hdr")
10
+ environment_texture = Three::Loaders::RGBELoader.new.load("/examples/browser/textures/assets/studio.hdr")
11
11
  scene.environment = environment_texture
12
12
 
13
13
  scene.add(Three::AmbientLight.new(0xffffff, 0.45))
@@ -16,7 +16,7 @@ Three::Browser.run(starting: "Starting Ruby scene") do |app|
16
16
  key_light.position.set(2.5, 3.0, 4.0)
17
17
  scene.add(key_light)
18
18
 
19
- texture = Three::Loaders::TextureLoader.new.load("/examples/browser/assets/checker.svg")
19
+ texture = Three::Loaders::TextureLoader.new.load("/examples/browser/textures/assets/checker.svg")
20
20
  texture.wrap_s = Three::RepeatWrapping
21
21
  texture.wrap_t = Three::RepeatWrapping
22
22
  texture.mag_filter = Three::NearestFilter
data/exe/three-rb CHANGED
@@ -14,6 +14,7 @@ def usage
14
14
 
15
15
  Example:
16
16
  three-rb browser examples/browser/quickstart
17
+ three-rb browser examples/browser/ruby
17
18
  TEXT
18
19
  end
19
20
 
@@ -31,7 +31,10 @@ module Three
31
31
  parameters[:iridescence] = material.iridescence if material.respond_to?(:iridescence)
32
32
  parameters[:iridescenceIOR] = material.iridescence_ior if material.respond_to?(:iridescence_ior)
33
33
  if material.respond_to?(:iridescence_thickness_range) && material.iridescence_thickness_range
34
- parameters[:iridescenceThicknessRange] = material.iridescence_thickness_range.dup
34
+ # three.js r187 replaced iridescenceThicknessRange with these two properties.
35
+ minimum, maximum = material.iridescence_thickness_range
36
+ parameters[:iridescenceThicknessMinimum] = minimum
37
+ parameters[:iridescenceThicknessMaximum] = maximum
35
38
  end
36
39
  parameters[:sheen] = material.sheen if material.respond_to?(:sheen)
37
40
  parameters[:sheenColor] = material.sheen_color.hex if material.respond_to?(:sheen_color)
@@ -345,7 +345,10 @@ module Three
345
345
  texture[:matrixAutoUpdate] = parameters[:matrix_auto_update] unless parameters[:matrix_auto_update].nil?
346
346
  texture[:matrix].call(:fromArray, js_array(parameters[:matrix])) if parameters[:matrix]
347
347
  texture.call(:updateMatrix) if parameters[:matrix_auto_update]
348
- texture[:needsUpdate] = true
348
+ # A loader texture has no image until its file arrives, and three.js
349
+ # warns on every frame it is flagged before then. The loader flags it
350
+ # once the image is in, and the upload reads the settings above.
351
+ texture[:needsUpdate] = true if js_present?(texture[:image])
349
352
  texture
350
353
  end
351
354
 
@@ -562,7 +565,10 @@ module Three
562
565
  end
563
566
 
564
567
  def new_mesh_toon_material(parameters)
565
- material = @three[:MeshToonMaterial].new(stringify_keys(parameters))
568
+ # MeshToonMaterial doesn't declare flatShading, so its constructor
569
+ # warns and drops it. The renderer still reads flatShading on any
570
+ # material, so update_material assigns it directly instead.
571
+ material = @three[:MeshToonMaterial].new(stringify_keys(parameters.except(:flatShading)))
566
572
  update_material(material, parameters)
567
573
  material
568
574
  end