spi3der 0.0.0-stage → 26.11.20001

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 (113) hide show
  1. package/APP.md +40 -0
  2. package/Dockerfile +4 -0
  3. package/MCP.md +149 -0
  4. package/PLAYER.md +136 -0
  5. package/README.md +35 -2
  6. package/api/mcp.mjs +31 -0
  7. package/api/store.mjs +158 -0
  8. package/bin/spi3der.mjs +20 -0
  9. package/emulator.html +17 -0
  10. package/engine/8fa668821759/bevel.js +265 -0
  11. package/engine/8fa668821759/camera.js +76 -0
  12. package/engine/8fa668821759/character.js +1019 -0
  13. package/engine/8fa668821759/check.js +83 -0
  14. package/engine/8fa668821759/csg.js +342 -0
  15. package/engine/8fa668821759/edit.js +48 -0
  16. package/engine/8fa668821759/galaxy.js +265 -0
  17. package/engine/8fa668821759/gl.js +798 -0
  18. package/engine/8fa668821759/gpu.js +1356 -0
  19. package/engine/8fa668821759/index.js +48 -0
  20. package/engine/8fa668821759/instances.js +41 -0
  21. package/engine/8fa668821759/joints.js +355 -0
  22. package/engine/8fa668821759/kernel-bytes.js +2 -0
  23. package/engine/8fa668821759/kernel.js +82 -0
  24. package/engine/8fa668821759/lathe.js +87 -0
  25. package/engine/8fa668821759/material.js +19 -0
  26. package/engine/8fa668821759/mesh.js +131 -0
  27. package/engine/8fa668821759/order.js +125 -0
  28. package/engine/8fa668821759/pick.js +85 -0
  29. package/engine/8fa668821759/place.js +17 -0
  30. package/engine/8fa668821759/planet.js +376 -0
  31. package/engine/8fa668821759/rig.js +417 -0
  32. package/engine/8fa668821759/saw.js +121 -0
  33. package/engine/8fa668821759/sky.js +428 -0
  34. package/engine/8fa668821759/svg.js +239 -0
  35. package/engine/8fa668821759/text.js +231 -0
  36. package/engine/8fa668821759/triangulate.js +72 -0
  37. package/engine/8fa668821759/types.js +2 -0
  38. package/engine/8fa668821759/vec.js +22 -0
  39. package/engine/8fa668821759/version.js +7 -0
  40. package/engine/8fa668821759/vrtsh.js +354 -0
  41. package/engine/8fa668821759/wire.js +346 -0
  42. package/favicon.svg +15 -0
  43. package/help.md +289 -0
  44. package/icons/apple-touch-icon.png +0 -0
  45. package/icons/favicon-32.png +0 -0
  46. package/icons/icon-192.png +0 -0
  47. package/icons/icon-512.png +0 -0
  48. package/icons/icon-maskable-512.png +0 -0
  49. package/icons/icon-maskable.svg +13 -0
  50. package/icons/icon.svg +15 -0
  51. package/index.html +13730 -0
  52. package/manifest.webmanifest +37 -0
  53. package/mcp/engine/bevel.js +265 -0
  54. package/mcp/engine/camera.js +76 -0
  55. package/mcp/engine/character.js +1019 -0
  56. package/mcp/engine/check.js +83 -0
  57. package/mcp/engine/csg.js +342 -0
  58. package/mcp/engine/edit.js +48 -0
  59. package/mcp/engine/galaxy.js +265 -0
  60. package/mcp/engine/gl.js +798 -0
  61. package/mcp/engine/gpu.js +1356 -0
  62. package/mcp/engine/index.js +48 -0
  63. package/mcp/engine/instances.js +41 -0
  64. package/mcp/engine/joints.js +355 -0
  65. package/mcp/engine/kernel-bytes.js +2 -0
  66. package/mcp/engine/kernel.js +82 -0
  67. package/mcp/engine/lathe.js +87 -0
  68. package/mcp/engine/material.js +19 -0
  69. package/mcp/engine/mesh.js +131 -0
  70. package/mcp/engine/order.js +125 -0
  71. package/mcp/engine/pick.js +85 -0
  72. package/mcp/engine/place.js +17 -0
  73. package/mcp/engine/planet.js +376 -0
  74. package/mcp/engine/rig.js +417 -0
  75. package/mcp/engine/saw.js +121 -0
  76. package/mcp/engine/sky.js +428 -0
  77. package/mcp/engine/svg.js +239 -0
  78. package/mcp/engine/text.js +231 -0
  79. package/mcp/engine/triangulate.js +72 -0
  80. package/mcp/engine/types.js +2 -0
  81. package/mcp/engine/vec.js +22 -0
  82. package/mcp/engine/version.js +7 -0
  83. package/mcp/engine/vrtsh.js +354 -0
  84. package/mcp/engine/wire.js +346 -0
  85. package/mcp/http.js +292 -0
  86. package/mcp/live.js +95 -0
  87. package/mcp/package.json +10 -0
  88. package/mcp/scene.js +1027 -0
  89. package/mcp/serve.js +87 -0
  90. package/mcp/server.js +97 -0
  91. package/media/face-of-spider.png +0 -0
  92. package/media/spider-paint-2015.png +0 -0
  93. package/media/spider-web.png +0 -0
  94. package/models/deepsky-lark.scene.json +1 -0
  95. package/models/deepsky.scene.json +1 -0
  96. package/models/globe.scene.json +1 -0
  97. package/models/lark-4.scene.json +1 -0
  98. package/models/lark.game.json +14 -0
  99. package/models/spider-build-v2.md +215 -0
  100. package/models/spider-build-v2.mjs +355 -0
  101. package/models/spider-build-v2.schema.json +1001 -0
  102. package/nginx.conf +12 -0
  103. package/package.json +46 -4
  104. package/player.html +274 -0
  105. package/sky.html +133 -0
  106. package/sky.md +285 -0
  107. package/src/demo.js +92 -0
  108. package/src/emulator/devices.js +22 -0
  109. package/src/emulator/xr.js +362 -0
  110. package/src/math.js +77 -0
  111. package/sw.js +37 -0
  112. package/xr-compare.html +332 -0
  113. package/xr-test.html +248 -0
package/APP.md ADDED
@@ -0,0 +1,40 @@
1
+ # five-percent: developer handover
2
+
3
+ Entry for the **Meta VR Start Developer Competition 2026** (the project is called *Fifth Percent*; the competition page is https://start-developer-competition-26.devpost.com/). Related to [3Draft](https://github.com/Pengeszikra/3Draft) (minimalist 3D engine and editor) and [Spider-Paint](https://github.com/Pengeszikra/Spider-Paint) (its viewer as a PWA): the models and the engine can feed the VR experience. Two collaborators (models) take turns on the project, so keep this file true. The owner speaks Hungarian to the assistant; code, docs and commits are English.
4
+
5
+ Branch: `main`. Status: the competition entry is being handed in. The app is **Spider Paint** (`index.html`), copied here with only the scenes Fifth Percent ships (see `scripts/from-spider.mjs`); beside it, a **dependency-free WebXR emulator** and its demo scene (`emulator.html`).
6
+
7
+ ## Layout
8
+
9
+ | File | Role |
10
+ |---|---|
11
+ | `src/emulator/xr.js` | installs a working `navigator.xr` (`immersive-vr`) in a normal desktop browser: sessions, `local` / `local-floor` / `viewer` spaces, `XRFrame.getViewerPose` with two views, `XRWebGLLayer` (both eyes side by side in the canvas), `XRRigidTransform`, two tracked-pointer controllers with `select` / `squeeze` events and an xr-standard gamepad |
12
+ | `src/emulator/devices.js` | Meta Quest 3 and 2 profiles: per-eye FOV, eye distance, resolution, refresh rates |
13
+ | `src/math.js` | small vector/matrix helpers (no libraries) |
14
+ | `index.html`, `engine/`, `models/`, `player.html`, `sky.html`, `api/`, `icons/`, `media/`, `sw.js`, … | the app: Spider Paint, **generated** by `npm run sync` (never edit them here; change 3Draft, release Spider Paint, sync again) |
15
+ | `scripts/from-spider.mjs` | the sync: copies Spider Paint and keeps only the scenes in its `SCENES` list (and their model files); trims the scene list, the Exa menu and the service worker's offline list; sets the starting scene (`START`, `game:lark`), VR with the hands only (`XR_HANDS_ONLY`) and VR at once on a headset (`XR_AUTO`, `?novr` turns it off) |
16
+ | `src/demo.js` + `emulator.html` | the emulator's demo scene; renders **only through the WebXR API**, so it also runs on a real headset |
17
+ | `tests/math.mjs` | maths unit tests |
18
+ | `tests/smoke.mjs` | headless Chromium test of the emulator (Playwright) |
19
+ | `tests/serve.mjs` | tiny static server used by `npm start` |
20
+
21
+ ## Commands
22
+
23
+ ```sh
24
+ npm start # static server: / is the app, emulator.html?emulate the emulator demo
25
+ npm run sync # Spider Paint (../spider-paint) into this repo, with the shipped scenes only
26
+ npm test # tests/math.mjs && tests/smoke.mjs (needs a Chromium that Playwright can launch)
27
+ ```
28
+
29
+ `?emulate` installs the emulator before the app code runs; without it the page uses the real `navigator.xr` (a headset). Application code must never import from `src/emulator`, only call the standard WebXR API, so the emulator can later be swapped for IWER without touching the app.
30
+
31
+ Emulator controls: **WASD** walk, **R/F** up/down, **arrows** or right-drag look, **click** right trigger, **Shift+click** left trigger, **Space** squeeze (Shift+Space left), the mouse position aims the hands. Scripted control for tests: `window.__xrEmulator.setHead({position, yaw, pitch})`, `.setController(hand, {position, orientation})`, `.click(hand, 'trigger')`, `.thumbstick(hand, x, y)`.
32
+
33
+ ## Conventions
34
+
35
+ - **No npm dependencies** for the pages (Playwright is only the test browser, supplied by the environment); the one dependency, `@vercel/blob`, is for the Vercel function `api/store.mjs`. Plain ES modules, no bundler, no build step.
36
+ - Headless WebGL: launch Chromium with `--use-gl=swiftshader --enable-unsafe-swiftshader --ignore-gpu-blocklist`.
37
+ - Keep the emulator faithful to the WebXR spec names so code written against it runs on a Quest unchanged; add a test in `tests/smoke.mjs` for every emulator feature.
38
+ - Using 3Draft models: a 3Draft mesh is `{ positions: Vec3[], faces: [{ v, color?, mat? }] }`, y up, faces planar and convex, CCW from outside. The app carries the engine beside it (`engine/<commit>/`, from the sync).
39
+ - Do not decide the app's concept alone: propose, let the owner confirm.
40
+ - When done, leave the tree committed and pushed, tests green, and state in your last message what changed and what is half done.
package/Dockerfile ADDED
@@ -0,0 +1,4 @@
1
+ FROM nginx:alpine
2
+ COPY nginx.conf /etc/nginx/conf.d/default.conf
3
+ COPY . /usr/share/nginx/html/
4
+ EXPOSE 8080
package/MCP.md ADDED
@@ -0,0 +1,149 @@
1
+ # Spider Paint MCP
2
+
3
+ This file is for the AI (and the person setting it up). Spider Paint carries an MCP server: `mcp/server.js`, stdio, no dependencies, Node 18+. Through it an AI builds 3D models with tools, looks at them as SVG renders, and steers the live viewer in the browser: the Spider Paint page and, when a 3Draft checkout sits beside this repo, the 3Draft viewer too. The server, its tools and the engine (`mcp/engine/`) are copied from 3Draft by `scripts/sync.mjs`, so it runs from this repo alone.
4
+
5
+ ## Public endpoint (Gemini, ChatGPT, any web MCP client)
6
+
7
+ **`https://spider-paint.vercel.app/api/mcp`** is a public Streamable HTTP MCP server: no install, no sign-in (choose "no authentication" where a client asks). It is `api/mcp.mjs`, a Vercel function around `mcp/http.js`, and it is stateless: it writes no files and cannot steer an open viewer, so every result carries an `open_url` link that opens the scene in Spider Paint.
8
+
9
+ - **Gemini:** Customize → Connectors → **+ Custom** → MCP Server URL: `https://spider-paint.vercel.app/api/mcp` → Next.
10
+ - **ChatGPT:** Settings → Apps / Connectors → create a custom connector (developer mode) with the same URL, authentication: none.
11
+ - **Claude:** Settings → Connectors → Add custom connector, same URL.
12
+
13
+ Tools:
14
+
15
+ | tool | what it does |
16
+ | --- | --- |
17
+ | `build_model` | runs model steps (`add_box`, `add_extrusion`, `add_mesh`, `add_character`, `transform` (also rotate_x / rotate_z, pivot), `place_on` (like G G: puts an object onto a surface), `sense` / `sensing` (the cursor's feel from the camera, with distances; which objects it feels), `extrude_face`, `move_vertices`, `boolean`, `recolor`, `remove`, `list`, `inspect`, …) and returns the objects, an SVG render and an `open_url` (`/#scene=…`, the whole scene packed into the link); pass that link back as `from` to keep building |
18
+ | `sky_scene` | a 3draft-sky catalogue (stars, planets, orbits) → a `#sky=…` link, optionally `target` to lock onto one body |
19
+ | `find` | searches the Deep Sky catalogue (stars, galaxies, nebulae, planets) → name, kind, distance and a `?scene=deepsky&target=…` link |
20
+ | `examples` | the bundled scenes with their links |
21
+ | `sky_guide` | the sky catalogue guide (sky.md) |
22
+
23
+ Links hold the scene in the URL fragment (deflate-raw, base64url), so they never reach a server; very large scenes (over ~200 KB of link) are refused.
24
+
25
+ ## Set up
26
+
27
+ From the Spider Paint folder:
28
+
29
+ ```
30
+ codex mcp add spider-paint -- node "$(pwd)/mcp/server.js"
31
+ claude mcp add spider-paint -- node "$(pwd)/mcp/server.js"
32
+ ```
33
+
34
+ Claude Desktop (`claude_desktop_config.json`):
35
+
36
+ ```json
37
+ { "mcpServers": { "spider-paint": { "command": "node", "args": ["/absolute/path/to/Spider-Paint/mcp/server.js"] } } }
38
+ ```
39
+
40
+ Then ask the AI for the `viewer` tool's URL and open it. Environment:
41
+
42
+ | variable | default | |
43
+ |---|---|---|
44
+ | `3DRAFT_PORT` | 5173 | the live viewer's port (the next free one up to +9 if taken) |
45
+ | `3DRAFT_LIVE` | on | `0`: no live viewer, tools only |
46
+ | `3DRAFT_DIR` | `../3Draft` or `../3draft` | a 3Draft checkout to serve at `/3draft/app/` |
47
+
48
+ `node mcp/serve.js` serves the same pages without the MCP scene (PORT, default 5173). Everything listens on 127.0.0.1 only.
49
+
50
+ ## The viewers
51
+
52
+ - `http://localhost:5173/?live`: Spider Paint. `?live` turns on the link: it shows the MCP scene and follows the `view_*` commands.
53
+ - `http://localhost:5173/3draft/app/`: the 3Draft viewer (only when a 3Draft checkout was found). It listens to the same link.
54
+
55
+ Every open viewer gets every change and every command. The viewers do not write back into the MCP scene: what the person edits by hand in the page stays in the page. The `viewer` tool lists the URLs and how many tabs are open.
56
+
57
+ ## How to work (for the AI)
58
+
59
+ 1. **Model** with `add_box`, `add_extrusion`, `add_mesh`, then shape with `extrude_face`, `move_vertices`, `boolean`, `transform`, `recolor`. Feel the scene like the viewer's cursor with `sense` (through a pixel of a render: the first surface, everything behind it, the distances); leave objects out with `sensing` (or `exclude` for one call) to place behind or into them. Make mechanisms with `group` (objects that move as one) and `connect` (glue, pivot, hinge, rail, spring: the holder carries the held part, which moves only as the joint allows; `move_joint` turns or slides it inside its limits, `joints` reports their state). Put things on each other with `place_on` (the viewer's G G: the foot onto the surface straight down at [x, z], upright or turned to the surface) and figures in with `add_character`. Name objects after what they are (`seat`, `leg_fl`): every later tool finds them by name.
60
+ 2. **Look** after every few changes: `render` (an SVG sheet of four views by default; read it), `inspect` (closed, planar, convex, faces counter-clockwise from outside), `pick` (a pixel of a render -> object, face, 3D point, normal).
61
+ 3. **Show** it: `viewer` gives the URL for the person. `view_target` aims the viewer at an object, `view_camera` places the eye, `view_state` tells you what the person sees.
62
+ 4. **Keep** it: `export` (JSON text, or a `.json` file inside the server's working directory), `import`.
63
+
64
+ The engine: flat-coloured convex faces, no textures (except screens, below). Y is up, the ground is y = 0. Faces are listed counter-clockwise seen from outside.
65
+
66
+ ### Screens: an image, a scene or a web page on a face
67
+
68
+ `set_screen` turns four-cornered faces of an object into a screen in the viewer. Give exactly one of:
69
+
70
+ | | What the face shows | Where it shows |
71
+ |---|---|---|
72
+ | `image` | a picture (`.png .jpg .jpeg .webp .gif .avif .svg`) laid on the face as a texture, cut to the face's shape (not stretched) | the WebGL2 / WebGPU view, **in VR too**; depth tested like the face |
73
+ | `scene` | a 3Draft scene file (`.json`) played on the face, turning round its middle | the same, in VR too |
74
+ | `url` | a web page in an iframe over the face | the desktop only (not in VR, no depth); sites that forbid framing stay blank |
75
+
76
+ - Only **four-cornered** faces show a screen, seen from the front (the side the face's counter-clockwise winding faces).
77
+ Without `face` every four-cornered face of the object becomes the screen (a box: all six sides); for one side give its
78
+ face index (`get_mesh`; an `add_box`'s faces are +z, −z, +x, −x, +y, −y: its front, facing +z, is face 0).
79
+ - An image is read with `fetch`, so its server must allow cross-origin reading (**CORS**): the Spider site's own files
80
+ (`media/…`, relative addresses) do, many image hosts do not. When it is refused the
81
+ desktop shows the picture as a page (an iframe) instead, and the viewer says so.
82
+ - The screen is a material (`material`, default `screen-<object>`; faces that share it share the screen) kept in the
83
+ scene's `palette`: `export` / `import` keep it, and the viewer adds it to its palette. Call `set_screen` without
84
+ image / scene / url to make the faces plain again.
85
+ - The person can do the same in the viewer: the palette (P), a material's **url** field takes a page, an image or a scene.
86
+
87
+ ```json
88
+ { "tool": "add_box", "arguments": { "name": "poster", "size": [1.6, 0.9, 0.04], "at": [0, 1.4, 0], "color": "#202020" } }
89
+ { "tool": "get_mesh", "arguments": { "name": "poster" } }
90
+ { "tool": "set_screen", "arguments": { "name": "poster", "face": 0, "image": "https://spider-paint.vercel.app/media/spider-web.png" } }
91
+ ```
92
+
93
+ ### Steering the viewer
94
+
95
+ - `view_example` loads one of the viewer's scenes into the browser (beside the MCP objects, or alone with `replace: true`): `deepsky` (1000 galaxies, 11 colliding systems, 400 black holes, 3000 stars), `stars` (500 nearest), `milkyway` (30 000 super-stars), `stars-plain`, `globe`, `bridge`, `ex27`, `betterman`, and in Spider Paint `human`, `tr74`, `station-screen`. These live in the browser only: `render`, `inspect`, `list` do not see them.
96
+ - `view_target` finds by name like the viewer's Enter search: case and accents do not matter; the whole name ranks first, then the start, a word start, any part. It also takes a kind (`planet`, `black hole`, `spiral galaxy`, `white dwarf`, `hot gas giant`): the nearest one of that kind. It works on everything shown, also the example scenes (`andromeda`, `sirius`, `sgr a`).
97
+ - `view_camera`: `eye` [x, y, z], `yaw` (0 looks towards -z, positive turns towards +x), `pitch` (positive looks down, as in Spider Build), `roll` (starship bank), all in degrees. It lets the target go. In the star maps 1 unit = 1 light year and the Sun is at the origin.
98
+ - `view_vehicle`: `starship` (space flight; speeds in ly/s, braking program, orbit), `car` (drives on the ground), `none` (the model camera).
99
+ - `view_state` returns the viewer's last report (every 2 s): vehicle, eye, yaw / pitch / roll, target, speed, orbit, object count, scene, view mode, and the report's age. `null` when no viewer is open.
100
+
101
+ - `view_sky` makes a whole space scene from a **sky catalogue** (format `3draft-sky`): stars, planets, moons, exoplanets, black holes and galaxies in astronomers' units (RA / Dec, distance or parallax, spectral type, AU, Earth radii…). The server turns it into a scene and the viewer shows it; the result lists what was left out and why. The format, how every kind of object is drawn, example prompts and where to find the data are in the **sky guide**: `sky.md` (shown as a page at `/sky.html`, linked from the viewer's help and its sky group).
102
+
103
+ A command reaches only viewers that are open: the result's `sent_to` says how many.
104
+
105
+ ### What the person can do in the viewer
106
+
107
+ Enter: find a target by name. Tab: next target. W/S, A/D, R/F: speed forward, sideways, up. [ / ő and ] / ú: roll. 0 / ö: orbit. Space: stop. Esc: let go. `?` opens the full help (help.md).
108
+
109
+ ## Tools
110
+
111
+ <!-- tools:start -->
112
+ | tool | arguments (bold: required) | what it does |
113
+ |---|---|---|
114
+ | `add_box` | **name**, size, at, color, replace | Add an axis-aligned box. `at` is the CENTER, so its bottom is at at[1] - size[1] / 2. Y is up, the ground is y = 0. Units are arbitrary but keep them consistent. |
115
+ | `add_extrusion` | **name**, **polygon**, **height**, y, color, replace | Add a prism: a CONVEX footprint polygon on the ground plane, given as [[x, z], ...] in any winding, extruded up by `height` from `y`. Use it for triangles, hexagons, wedges, roofs, columns. Concave shapes must be split into several convex extrusions. |
116
+ | `add_mesh` | **name**, **positions**, **faces**, color, replace | Add a raw mesh: `positions` [[x,y,z],...] and `faces` [{ v: [indices], color }]. Each face must be planar, convex and listed COUNTER-CLOCKWISE seen from outside (right-hand rule: the normal points out). Run inspect afterwards. |
117
+ | `transform` | **name**, scale, rotate_x, rotate_z, rotate_y, pivot, move | Scale, then rotate round X, then round Z, then round Y, then move an object. Scale and rotations are about the center of its bounding box (or about `pivot`). Rotations are degrees, counter-clockwise looking from the + end of the axis towards the origin (right-hand rule): rotate_y 90 turns +x into -z, rotate_x 90 turns +y into +z, rotate_z 90 turns +x into +y. |
118
+ | `place_on` | **name**, onto, at, point, normal, from, dir, x, y, view, yaw, pitch, size, exclude, include, align, turn, gap | Put an object down on the surface of others, like the viewer's G G: its foot (the middle of the bottom of its bounding box; for a character the middle of where it stands) goes onto the surface point, and with align "normal" its up turns to the surface normal (a thing on a slope, a ball, a wall). Say where with `at` [x, z] (dropped straight down there: the highest surface under that spot), or a pixel `x`, `y` of a render (the ray from the camera, like the viewer's cursor; view / yaw / pitch / size as render), or `point` (+ `normal`) from sense / pick, or a ray (`from` + `dir`). Default: straight down at the object's own x, z. It lands on the sensing set (see sensing) without itself, or on `onto`; exclude / include change the set for this call (exclude a wall to place behind it). Returns the new bounds and the surface it landed on with its distance along the ray. |
119
+ | `add_character` | **name**, preset, seed, spec, pose, at, yaw, onto, replace | Add a character from the viewer's character builder: a stylized figure (about 1.6-1.9 tall, the units are metres) in a few meshes merged into one object, its feet on y = 0 at `at`, facing `yaw`. Presets: scientist, mechanic, crew (Space 1999 style uniform), astronaut. `seed` makes a random variation of the preset, `spec` overrides any field of the builder's spec (base: "male" \| "female", body: { height, build, shoulders, head }, face: { shape, skin }, hair: { style, mat }, outfit: { kind, main, second, helmet }, prop). Pose: stand, sit (the seat under the hips at about 0.44) or walk (one stride). Give `onto` (and `at`) to stand it on a surface, as place_on. |
120
+ | `sense` | view, yaw, pitch, size, x, y, from, dir, exclude, include, limit | Feel the scene along a ray, as the viewer's cursor does from the camera: through pixel (x, y) of a render (same view and size as render), or from `from` along `dir`. Returns the first surface (object, face, point, normal, distance from the eye or `from`) and `hits`: everything along the ray, nearest first, with `outside` true where the ray enters an object and false where it leaves it, so you can see what is behind and how thick it is. Only the sensing set counts (see sensing); exclude / include change it for this call. Use the point and normal with place_on (point + normal), or give place_on the same pixel. |
121
+ | `sensing` | ignore, sense, only, reset | The sensing set: which objects sense, pick and place_on feel (the viewer's cursor feels everything; here you choose). New objects are sensed. ignore takes objects out (e.g. a wall to place things behind it, a box to place into it), sense puts them back, only senses just these, reset senses everything again. Returns the sensed and the ignored objects. |
122
+ | `group` | **name**, objects, rename | Make a group: the objects move as one (in the viewer a G on any of them takes the whole group; the user groups a B selection with Ctrl+G). `objects` join the group `name` (leaving any group they were in); `rename` gives the group a new name. Returns every group. |
123
+ | `ungroup` | **name** | Break a group up: its objects move on their own again (joints stay). |
124
+ | `connect` | **type**, **a**, **b**, name, at, at_b, contact, edge, axis, path, slider, limit, limits, rest_length, stiffness, damping, ends, spring_object, spring_line | Join two objects with a joint (the basic mechanics). `a` holds, `b` is held: moving a carries b along; b itself moves only as the joint allows (move_joint here, a drag in the viewer). Kinds: glue (a and b move together; `contact`: the touching point, line or face as points), pivot (b turns about the point `at`, a ball joint; `limits` { x: [min, max], y, z } degrees round the world axes from the pose now), hinge (b turns about a line: `edge` [i, j], two vertex indices of b, e.g. a door's vertical side, or `axis` [[x,y,z], [x,y,z]]; `limit` [min, max] degrees, positive counter-clockwise looking from the second point towards the first), rail (b slides along the polyline `path` of a, its point `slider` (default its vertex nearest the rail) on the rail; `limit` [min, max] distance along the rail from its start), spring (b hangs on a spring from `at` on a to `at_b` on b; `rest_length` (default the distance now), `stiffness` (default 40), `damping` (default 3), `ends` [glue \| pivot, glue \| pivot]; `spring_object`: an object to stretch between the ends, its line `spring_line` [i, j] (default its longest side); the viewer animates it). Every geometry is in world coordinates now and then sticks to the objects. Returns the joint and its state. |
125
+ | `disconnect` | **name** | Take a joint away (by its name; see joints). |
126
+ | `joints` | – | The joints and groups now: each joint's kind, holder (a), held part (b), its limits and its state (a hinge's angle, a pivot's angles, a rail's position, a spring's length) with its geometry in world coordinates. |
127
+ | `move_joint` | **name**, angle, angles, position | Move a held part as its joint allows, kept inside the limits: a hinge to `angle` (degrees from the pose it was connected in), a pivot to `angles` [x, y, z] (degrees round the world axes), a rail to `position` (distance along the rail). What b holds moves along. Returns the state reached (clamped). |
128
+ | `get_mesh` | **name** | Read an object's geometry so you can shape it: the vertices (index = position in the list) and the faces with their vertex indices, color, center and outward normal. Use it to find the face or vertex indices for extrude_face and move_vertices. |
129
+ | `extrude_face` | **name**, **face**, distance, scale, color | Shape an object by pushing one of its faces out, like a modeller. The face is replaced (same index) by a copy moved `distance` along its outward normal and scaled by `scale` about its center, joined to the old edges by new side faces. distance > 0 and scale 1: a prism grows out (a wing, a chimney, a step). distance > 0 and scale < 1: a taper (roof, tower top, frustum). distance 0 and scale < 1: an inset (a panel or window frame; extrude it again, negative, for a recess). distance < 0: a dent into the solid (a niche, a door recess). The result is a closed solid again; chain calls on the returned `cap` face. |
130
+ | `move_vertices` | **name**, **indices**, **by** | Move the vertices with the given indices by [dx, dy, dz] (see get_mesh for the indices): shear, lean, pinch a roof ridge, raise a corner. Faces keep their vertices, so moving only some corners of a face can make it non-planar; the result reports that. Move all the corners of a face together to keep it flat. |
131
+ | `boolean` | **a**, **b**, **op**, name, keep | Boolean of two closed solids: union, subtract (a minus b: a door, a window, a hole) or intersect. Both objects must be closed solids with outward faces (inspect says so). The result is a new closed solid; faces keep their colors and a face cut into a solid takes the color of the cutting face. By default a and b are replaced by the result; `keep: true` keeps them. |
132
+ | `recolor` | **name**, **color**, face | Change the color of a whole object, or of one face when `face` is given. |
133
+ | `set_screen` | **name**, face, image, scene, url, material, color | Make faces of an object a screen in the viewer: give exactly one of `image` (a picture, .png .jpg .jpeg .webp .gif .avif .svg: laid on the face as a texture, cut to the face's shape, depth tested and seen in VR too; its server must allow cross-origin reading (CORS), else the desktop shows it as a page), `scene` (a 3Draft scene file .3draft / .json, played on the face turning round its middle) or `url` (a web page, shown in an iframe over the face on the desktop; not in VR, sites that forbid framing stay blank). Only four-cornered faces show it; seen from the front (the side the face's CCW winding faces). Without `face` every four-cornered face of the object becomes the screen (a box: all six sides), so for one side give its face index (get_mesh). The screen is a material (`material`, default "screen-<object>") kept in the scene's palette (export / import keep it); give none of image / scene / url to make the faces plain again. |
134
+ | `remove` | **name** | Remove one object. |
135
+ | `clear` | – | Remove every object. |
136
+ | `list` | – | List the objects with their face counts and axis-aligned bounds (min / max corners). |
137
+ | `inspect` | name | Check an object (or all when name is omitted): closed shell, faces CCW from outside, planar, convex. Returns plain-text notes about what to fix. Run it after add_mesh. |
138
+ | `render` | view, yaw, pitch, size, points | Render the scene as a flat-colored SVG with edges and points (text, deterministic). Default is a 2x2 sheet of front, side, top and perspective. Each <polygon data-face=".."> is one face, <circle data-v=".."> a vertex. Look at it to judge the model, then fix and render again. |
139
+ | `pick` | view, yaw, pitch, size, **x**, **y**, exclude, include | What is at pixel (x, y) of a render? Uses the same camera and size as render. Returns the object, its face index, the 3D point, the surface normal and the distance. Use it to find coordinates to place or stack things. Only the sensing set counts (see sensing; exclude / include for this call); sense also lists what lies behind. |
140
+ | `export` | path | Return the scene as JSON, or write it to `path` (relative, inside the server working directory, ending in .3draft (the 3Draft scene file) or .json). |
141
+ | `import` | json, path | Replace the scene with a JSON scene, given as `json` text or read from `path` (same rules as export). |
142
+ | `view_target` | **name** | Make the open viewer target an object by name (as the viewer's Enter search: case and accents do not matter; the whole name, then the start, a word start, any part). In a star map the starship turns to it and the braking program stops it at the surface when you fly there. Works on everything the viewer shows, also the loaded example scenes (stars, galaxies), not only the MCP objects. |
143
+ | `view_camera` | **eye**, yaw, pitch, roll | Put the open viewer's eye at a point, looking along yaw / pitch (degrees; yaw 0 looks towards -z, positive yaw turns towards +x, positive pitch looks down, as in the Spider Build format). In a star map the units are light years (the Sun at the origin). `roll` (degrees) banks the starship. |
144
+ | `view_vehicle` | **vehicle** | Switch the open viewer's vehicle: "starship" (space flight, light years), "car" (drives on the ground), or "none" (the ordinary model camera). |
145
+ | `view_example` | **name**, replace | Load one of the viewer's bundled scenes into the open viewer (beside the MCP objects, or instead of everything with replace: true). The names are the viewer's scene list, e.g. deepsky (1000 galaxies, 400 black holes, 3000 stars), stars, milkyway, stars-plain, sky:trappist-1 (a sky catalogue), globe, bridge, ex27, betterman (Spider Paint also: human, tr74, station-screen). It is shown in the browser only: render and inspect do not see it. |
146
+ | `view_sky` | sky, path, replace, save | Make a space scene from a sky catalogue and show it in the open viewer (the format is app/sky.md, "3draft-sky"): stars, planets, moons, dwarf planets, exoplanets, black holes and galaxies in astronomers' units. A place is ra / dec (degrees, or "hh mm ss" / "±dd mm ss" strings, or ra_h hours) with dist + unit (ly, pc, kpc, Mpc, AU, kly, Mly, Gly) or parallax (mas), or at [x, y, z] in scene light years (the Sun at the origin, y = equatorial north). A star: spect (e.g. "G2V", "M5.5Ve", "DA"), temp (K), lum (L☉) or absmag or vmag, radius (R☉). A planet / moon goes round another object with around (its name), a (AU) or a_km, optional incl / node / angle (degrees), radius_earth / radius_km / radius_jup, teq (K, else from the star), surface (a planet shader recipe), ring, orbit: true (draw the orbit). A black hole: mass (M☉), radius_ly (drawn size). A galaxy: kind (spiral, elliptical, irregular, dwarf, interacting, early), diameter_kly or radius_ly, incl / pa, arms, bar. Any object: name, info (shown under the name when targeted), category (the find box's kind), color. start: { near: name, distance: ly } or { eye, yaw, pitch }. Returns the counts and notes about anything left out; save writes the made scene as a .3draft file the viewer opens (f↑). |
147
+ | `view_state` | – | What the open viewer shows now (it reports every 2 seconds): vehicle, eye, yaw / pitch / roll (degrees), the target, the speed, the object count, the loaded scene. null when no viewer is open. |
148
+ | `viewer` | – | The URL of the live viewer: a browser page that shows this scene and updates after every change you make. Tell the user to open it. Returns null when the live viewer is off. |
149
+ <!-- tools:end -->
package/PLAYER.md ADDED
@@ -0,0 +1,136 @@
1
+ # Spider Player
2
+
3
+ A bare 3D player to embed in any web page. It shows one thing and has **no UI of its own**: no buttons, no panels, no
4
+ captions on screen, no keyboard or mouse handling. The page around it controls it with URL parameters and `postMessage`
5
+ commands, and it reports back with events.
6
+
7
+ - A **scene** (a 3Draft scene file, `.3draft`; older ones `.scene.json`) turns slowly on a turntable round its middle.
8
+ - A **story** (a Spider Build v2 file, `.build.json`) plays on its own timeline: the model is built step by step and the
9
+ recorded camera moves with it. It loops by default.
10
+ - The background is **transparent** (the page shows through) or a colour you give.
11
+
12
+ It loads only the renderer (WebGL2), the scene loading and the story format: about 180–200 kB, **50–60 kB gzipped**,
13
+ instead of the whole editor. The scene files themselves are usually the bigger download.
14
+
15
+ **Address:** `https://spider-paint.vercel.app/player.html` (in the 3Draft repository: `app/player.html`).
16
+
17
+ ## Embedding
18
+
19
+ ```html
20
+ <iframe
21
+ src="https://spider-paint.vercel.app/player.html?scene=models/lark-4.scene.json&bg=transparent&spin=20"
22
+ style="width: 640px; height: 400px; border: 0; background: transparent"
23
+ allowtransparency="true"
24
+ title="LARK-4"></iframe>
25
+ ```
26
+
27
+ The player fills the frame (any size or aspect ratio) and keeps the whole model in view across the shorter side.
28
+ A transparent background works when the iframe itself has no background (as above); the page's own colours show round the model.
29
+
30
+ ### Where scenes come from
31
+
32
+ - the Spider site's own models: `models/lark-4.scene.json`, `models/bridge.scene.json`, `models/lark-4.build.json`, …;
33
+ - the online store: `scene=/api/store?name=<name>` (a scene saved with ☁ in Spider Paint);
34
+ - any other address that allows cross-origin reading (CORS), e.g. a raw GitHub file
35
+ (`https://raw.githubusercontent.com/<user>/<repo>/main/x.scene.json`).
36
+
37
+ A relative address is relative to the player page.
38
+
39
+ ## URL parameters
40
+
41
+ | Parameter | Default | Meaning |
42
+ |---|---|---|
43
+ | `scene` (or `src`) | — | the scene (`.3draft`, or an older `.scene.json`) or story (`.build.json`) to load |
44
+ | `bg` | `transparent` | `transparent`, or a colour: `1a1a2e`, `#1a1a2e`, `fff` |
45
+ | `spin` | `20` | the turntable's speed, degrees per second; `0` stands still, negative turns the other way |
46
+ | `yaw` | `30` | the turntable's starting angle round the vertical, degrees |
47
+ | `pitch` | `20` | how far the camera looks down on the model, degrees (−89 … 89) |
48
+ | `zoom` | `1` | `2` = twice as close, `0.5` = twice as far |
49
+ | `autoplay` | `1` | a story starts playing at once (`0`: it waits for `play`) |
50
+ | `loop` | `1` | a story starts again at its end (`0`: it stops on its last frame) |
51
+ | `speed` | `1` | a story's playback speed (0 … 16) |
52
+ | `camera` | `auto` | `auto`: a story uses its recorded camera, a scene the turntable; `orbit`: the turntable for a story too |
53
+ | `smooth` | `1` | smooth shading of curved surfaces (`0`: every face flat) |
54
+ | `studio` | `1` | three studio lights that follow the camera (`0`: one fixed sun) |
55
+ | `origin` | `*` | the embedding page's origin (e.g. `https://example.com`): events are posted only to that origin |
56
+
57
+ ## Commands (the page → the player)
58
+
59
+ Send a message to the iframe's window. Every command is an object with `target: 'spider-player'` and a `cmd`; an `id` of
60
+ your own comes back with the answer.
61
+
62
+ ```js
63
+ const player = document.querySelector('iframe').contentWindow;
64
+ const send = (cmd, extra = {}) => player.postMessage({ target: 'spider-player', cmd, ...extra }, '*');
65
+
66
+ send('load', { url: 'models/bridge.scene.json' });
67
+ send('spin', { value: 45 });
68
+ send('background', { value: '#101820' });
69
+ send('seek', { t: 12000, id: 'jump-1' });
70
+ ```
71
+
72
+ | `cmd` | Fields | Does |
73
+ |---|---|---|
74
+ | `load` | `url` (address) or `data` (the scene / story object itself) | loads another scene or story in place of the current one |
75
+ | `play` | — | plays the story (from the start if it is at its end) |
76
+ | `pause` | — | stops the story where it is |
77
+ | `toggle` | — | play ↔ pause |
78
+ | `seek` | `t` (ms) | jumps to that moment of the story |
79
+ | `speed` | `value` (0 … 16) | playback speed |
80
+ | `loop` | `value` (true / false) | start again at the end, or stop there |
81
+ | `camera` | `value`: `auto` / `orbit` | a story's recorded camera, or the turntable round the model |
82
+ | `spin` | `value` (°/s) | the turntable's speed (0: still) |
83
+ | `yaw` | `value` (°) | the turntable's angle now |
84
+ | `pitch` | `value` (°, −89 … 89) | how far the camera looks down |
85
+ | `zoom` | `value` (0.05 … 50) | closer / farther |
86
+ | `background` | `value`: `transparent` or a colour | the background |
87
+ | `smooth` | `value` (true / false) | smooth shading |
88
+ | `studio` | `value` (true / false) | studio lights |
89
+ | `state` | — | only answers with the state |
90
+
91
+ `play`, `pause`, `toggle` and `seek` work on a story only; on a scene they answer with an `error`.
92
+
93
+ ## Events (the player → the page)
94
+
95
+ Every event is a message with `source: 'spider-player'` and a `type`.
96
+
97
+ ```js
98
+ addEventListener('message', (e) => {
99
+ const m = e.data;
100
+ if (m?.source !== 'spider-player') return;
101
+ if (m.type === 'caption') subtitles.textContent = m.text;
102
+ if (m.type === 'time') progress.value = m.t / m.durationMs;
103
+ if (m.type === 'error') console.warn(m.message);
104
+ });
105
+ ```
106
+
107
+ | `type` | Fields | When |
108
+ |---|---|---|
109
+ | `ready` | the state | the player has started (and loaded the URL's `scene`, if there was one) |
110
+ | `loaded` | the state | a scene or story has been loaded |
111
+ | `state` | the state, `cmd`, `id` | the answer to every command that worked |
112
+ | `error` | `message`, `cmd`, `id` | a command failed, a file could not be loaded, or WebGL2 is missing |
113
+ | `time` | `t`, `durationMs` (ms) | while a story plays, four times a second |
114
+ | `caption` | `text`, `cues` ([{ `channel`, `text` }]) | a story's narration changed (`text` is empty when there is none); show it yourself if you want subtitles |
115
+ | `ended` | `loop` | a story reached its end (with `loop` it goes on from the start) |
116
+
117
+ **The state:** `{ url, kind: 'scene' | 'story', playing, t, durationMs, speed, loop, camera, spin, yaw, pitch, zoom,
118
+ background, objects, title }`.
119
+
120
+ ## On the same page (no iframe)
121
+
122
+ When the player page is opened directly (or from the same origin), the same commands are a function call and the same
123
+ events are a DOM event:
124
+
125
+ ```js
126
+ await spiderPlayer.send({ cmd: 'pause' }); // → the state, or throws the error
127
+ spiderPlayer.state();
128
+ addEventListener('spider-player', (e) => console.log(e.detail)); // { source, type, ... }
129
+ ```
130
+
131
+ ## What it does not do
132
+
133
+ - No sound: a story's audio cues are not played (their text comes as `caption` events).
134
+ - Star maps and sky backdrops (`deepsky`, a story's sky environment) are not drawn: it is a player for models.
135
+ - Image, page and scene screens on faces (material `image` / `url` / `scene`) are not shown; the faces keep their colour.
136
+ - No VR, no editing, no picking with the mouse.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # spi3Der
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Interactive 3D creation and exploration, powered by **3Draft**. Based on the 2026 Fifth Percent competition sprint.
4
+
5
+ The editor opens with **no scene** and **does not request VR** until you choose Enter XR. WebXR/Meta Quest and ViRtuSH hand interactions remain available. The scene picker offers **Globe**, **Deep Sky** and **Fifth Percent VR (LARK + Deep Sky)**. Model-format tooling is retained.
6
+
7
+ ## Run locally
8
+
9
+ ```sh
10
+ npm install
11
+ npm start
12
+ # or, after publishing to npm:
13
+ npx spi3der
14
+ ```
15
+
16
+ Open http://localhost:5173. No application build system is needed.
17
+
18
+ ## Cloud Run (static)
19
+
20
+ ```sh
21
+ gcloud run deploy spi3der --source . --region europe-west1 --allow-unauthenticated
22
+ ```
23
+
24
+ The Dockerfile serves the browser application from nginx on port 8080, with correct ES module MIME types. **Note:** this static Cloud Run container does not execute Vercel API functions under `api/` (the scene store and MCP endpoint); deploy those functions separately, or provide a Node API server, if you need them on the same origin.
25
+
26
+ ## npm
27
+
28
+ The package name is `spi3der`, with a CLI that hosts the app locally. The package is configured for `npm pack` / `npm publish` but is **not automatically published**. The source project has no license declaration; the npm metadata intentionally uses `UNLICENSED` until the author decides on a license.
29
+
30
+ ## Compatibility
31
+
32
+ - `?scene=globe`, `?scene=deepsky` or `?scene=game:lark` explicitly loads a scene.
33
+ - `?autovr` explicitly enables the previous automatic headset VR offer.
34
+ - Desktop starts empty; use **Enter XR** to enter VR manually.
35
+
36
+ Original source: https://github.com/Pengeszikra/five-percent
package/api/mcp.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // The public MCP endpoint: https://spider-paint.vercel.app/api/mcp (Streamable HTTP, stateless, no auth).
2
+ // A Vercel Node function around mcp/http.js (synced from 3Draft). Static files it reads (sky.md, the Deep Sky
3
+ // catalogue) are fetched from the site itself.
4
+ import { handleHttp } from '../mcp/http.js';
5
+
6
+ const readBody = (req) => new Promise((resolve, reject) => {
7
+ if (typeof req.body === 'string') return resolve(req.body);
8
+ if (req.body && typeof req.body === 'object' && !Buffer.isBuffer(req.body)) return resolve(JSON.stringify(req.body));
9
+ if (Buffer.isBuffer(req.body)) return resolve(req.body.toString('utf8'));
10
+ let data = '';
11
+ req.setEncoding('utf8');
12
+ req.on('data', (c) => { data += c; });
13
+ req.on('end', () => resolve(data));
14
+ req.on('error', reject);
15
+ });
16
+
17
+ export default async function handler(req, res) {
18
+ const proto = String(req.headers['x-forwarded-proto'] ?? 'https').split(',')[0];
19
+ const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? 'spider-paint.vercel.app').split(',')[0];
20
+ const origin = `${proto}://${host}`;
21
+ const fetchText = async (path) => {
22
+ const r = await fetch(origin + path);
23
+ if (!r.ok) throw new Error(`${path}: HTTP ${r.status}`);
24
+ return r.text();
25
+ };
26
+ const body = req.method === 'POST' ? await readBody(req) : '';
27
+ const out = await handleHttp({ method: req.method, body, origin, fetchText });
28
+ for (const [k, v] of Object.entries(out.headers ?? {})) res.setHeader(k, v);
29
+ res.statusCode = out.status;
30
+ res.end(out.body ?? '');
31
+ }
package/api/store.mjs ADDED
@@ -0,0 +1,158 @@
1
+ // The store: scenes and models kept online, for every device (https://spider-paint.vercel.app/api/store).
2
+ // A Vercel Blob store behind this function: connect a Blob store (public or private) to the Vercel project (Storage → Create → Blob → connect:
3
+ // it sets BLOB_READ_WRITE_TOKEN) and set SPIDER_KEY (any secret) in the project's environment variables.
4
+ // GET /api/store the list: { items: [{ name, size, at }] }
5
+ // GET /api/store?name=<name> one scene (JSON)
6
+ // PUT /api/store?name=<name> save it (body: the scene JSON; header x-spider-key: SPIDER_KEY)
7
+ // DELETE /api/store?name=<name> take it out (header x-spider-key)
8
+ // Reading is open; writing needs the key. Names: letters, digits, space, - _ . (up to 60).
9
+ import { put, list, del, get } from '@vercel/blob';
10
+
11
+ const PREFIX = 'store/';
12
+ // the store's token: BLOB_READ_WRITE_TOKEN, or <PREFIX>_READ_WRITE_TOKEN when the store was connected with a custom prefix
13
+ // A store connected the new way has no token: the SDK signs in with the project's OIDC token and BLOB_STORE_ID by itself, and
14
+ // that wins over an old read-write token (left by an earlier store) when both are there.
15
+ const RW_TOKEN = () => process.env.BLOB_READ_WRITE_TOKEN || Object.entries(process.env).find(([k, v]) => /_READ_WRITE_TOKEN$/.test(k) && /^vercel_blob_rw_/.test(v ?? ''))?.[1] || '';
16
+ const OIDC = () => Boolean(process.env.BLOB_STORE_ID);
17
+ const TOKEN = () => (OIDC() ? undefined : RW_TOKEN() || undefined);
18
+ const HAS_STORE = () => OIDC() || Boolean(RW_TOKEN());
19
+ const clean = (name) => String(name ?? '').trim().replace(/[^\p{L}\p{N} _.-]/gu, '').slice(0, 60);
20
+ const pathOf = (name) => `${PREFIX}${encodeURIComponent(name)}.json`;
21
+ const nameOf = (pathname) => decodeURIComponent(pathname.slice(PREFIX.length).replace(/\.json$/, ''));
22
+
23
+ const readBody = (req) => new Promise((resolve, reject) => {
24
+ if (typeof req.body === 'string') return resolve(req.body);
25
+ if (Buffer.isBuffer(req.body)) return resolve(req.body.toString('utf8'));
26
+ if (req.body && typeof req.body === 'object') return resolve(JSON.stringify(req.body));
27
+ let data = '';
28
+ req.setEncoding('utf8');
29
+ req.on('data', (c) => { data += c; });
30
+ req.on('end', () => resolve(data));
31
+ req.on('error', reject);
32
+ });
33
+
34
+ const send = (res, status, obj) => {
35
+ res.statusCode = status;
36
+ res.setHeader('content-type', 'application/json; charset=utf-8');
37
+ res.setHeader('cache-control', 'no-store');
38
+ res.setHeader('access-control-allow-origin', '*');
39
+ res.setHeader('access-control-allow-headers', 'content-type, x-spider-key');
40
+ res.setHeader('access-control-allow-methods', 'GET, PUT, DELETE, OPTIONS');
41
+ res.end(typeof obj === 'string' ? obj : JSON.stringify(obj));
42
+ };
43
+
44
+ const findBlob = async (name) => {
45
+ const want = pathOf(name);
46
+ let cursor;
47
+ do {
48
+ const page = await list({ prefix: PREFIX, cursor, token: TOKEN() });
49
+ const hit = page.blobs.find((b) => b.pathname === want);
50
+ if (hit) return hit;
51
+ cursor = page.hasMore ? page.cursor : undefined;
52
+ } while (cursor);
53
+ return null;
54
+ };
55
+
56
+ // the store may be public or private (Vercel asks when it is made): the first save tries the one known (SPIDER_BLOB_ACCESS, or
57
+ // what the last save found), and on the store's "cannot use public / private access" answer saves the other way
58
+ let access = process.env.SPIDER_BLOB_ACCESS === 'private' ? 'private' : process.env.SPIDER_BLOB_ACCESS === 'public' ? 'public' : null;
59
+ const isPrivate = (blob) => /\.private\.blob\./.test(blob.url ?? '') || access === 'private';
60
+ const putEither = async (path, body) => {
61
+ const opts = (a) => ({ access: a, contentType: 'application/json', addRandomSuffix: false, allowOverwrite: true, token: TOKEN() });
62
+ const first = access ?? 'public';
63
+ try {
64
+ const b = await put(path, body, opts(first));
65
+ access = first;
66
+ return b;
67
+ } catch (err) {
68
+ if (!/(public|private) access on a (private|public) store/i.test(err?.message ?? '')) throw err;
69
+ const other = first === 'public' ? 'private' : 'public';
70
+ const b = await put(path, body, opts(other));
71
+ access = other;
72
+ return b;
73
+ }
74
+ };
75
+
76
+ export default async function handler(req, res) {
77
+ try {
78
+ if (req.method === 'OPTIONS') return send(res, 204, '');
79
+ if (!HAS_STORE()) return send(res, 503, { error: 'no Blob store token in this deployment yet: connect the Blob store to the project (Production too) and redeploy', seen: Object.keys(process.env).filter((k) => /BLOB|READ_WRITE|SPIDER|OIDC/.test(k)) });
80
+ const url = new URL(req.url, 'http://x');
81
+ const name = clean(url.searchParams.get('name'));
82
+ // debug reports from the headset (the VR's right-hand debug function): written without the key, kept apart under debug/
83
+ // (not in the scene list), at most 4 MB each; read with ?debug=list and ?debug=<name>
84
+ const dbg = url.searchParams.get('debug');
85
+ if (req.method === 'GET' && dbg) {
86
+ if (dbg === 'list') {
87
+ const items = [];
88
+ let cursor;
89
+ do {
90
+ const page = await list({ prefix: 'debug/', cursor, token: TOKEN() });
91
+ for (const b of page.blobs) items.push({ name: b.pathname.slice(6).replace(/\.json$/, ''), size: b.size, at: b.uploadedAt });
92
+ cursor = page.hasMore ? page.cursor : undefined;
93
+ } while (cursor);
94
+ items.sort((a, b) => b.at.localeCompare?.(a.at) ?? 0);
95
+ return send(res, 200, { items });
96
+ }
97
+ const n = clean(dbg);
98
+ const { blobs } = await list({ prefix: `debug/${n}.json`, token: TOKEN() });
99
+ const blob = blobs.find((b) => b.pathname === `debug/${n}.json`);
100
+ if (!blob) return send(res, 404, { error: `no debug report "${n}"` });
101
+ if (isPrivate(blob)) {
102
+ const got = await get(blob.pathname, { access: 'private', useCache: false, token: TOKEN() });
103
+ return send(res, 200, await new Response(got.stream).text());
104
+ }
105
+ const r = await fetch(`${blob.url}?v=${Date.now()}`);
106
+ return send(res, r.ok ? 200 : 502, await r.text());
107
+ }
108
+ if ((req.method === 'PUT' || req.method === 'POST') && /^debug-/.test(name)) {
109
+ const body = await readBody(req);
110
+ if (body.length > 4e6) return send(res, 413, { error: 'a debug report is at most 4 MB' });
111
+ const data = JSON.parse(body);
112
+ if (data?.format !== '3draft-debug') return send(res, 400, { error: 'not a debug report' });
113
+ const b = await putEither(`debug/${name}.json`, body);
114
+ return send(res, 200, { ok: true, name, size: body.length, url: b.url });
115
+ }
116
+ if (req.method === 'GET' && !name) {
117
+ const items = [];
118
+ let cursor;
119
+ do {
120
+ const page = await list({ prefix: PREFIX, cursor, token: TOKEN() });
121
+ for (const b of page.blobs) items.push({ name: nameOf(b.pathname), size: b.size, at: b.uploadedAt });
122
+ cursor = page.hasMore ? page.cursor : undefined;
123
+ } while (cursor);
124
+ items.sort((a, b) => a.name.localeCompare(b.name));
125
+ return send(res, 200, { items, via: OIDC() ? 'oidc' : 'token' }); // (via: how this deployment reaches its store)
126
+ }
127
+ if (!name) return send(res, 400, { error: 'name?' });
128
+ if (req.method === 'GET') {
129
+ const blob = await findBlob(name);
130
+ if (!blob) return send(res, 404, { error: `no "${name}" in the store` });
131
+ if (isPrivate(blob)) {
132
+ // a private store: read through the SDK (with the token), the latest version
133
+ const got = await get(blob.pathname, { access: 'private', useCache: false, token: TOKEN() });
134
+ if (!got || got.statusCode !== 200) return send(res, 502, { error: `could not read "${name}" from the private store` });
135
+ return send(res, 200, await new Response(got.stream).text());
136
+ }
137
+ const r = await fetch(`${blob.url}?v=${Date.now()}`);
138
+ return send(res, r.ok ? 200 : 502, await r.text());
139
+ }
140
+ const key = process.env.SPIDER_KEY;
141
+ if (!key || req.headers['x-spider-key'] !== key) return send(res, 401, { error: 'the key is missing or wrong' });
142
+ if (req.method === 'PUT' || req.method === 'POST') {
143
+ const body = await readBody(req);
144
+ const data = JSON.parse(body);
145
+ if (!Array.isArray(data?.objects)) return send(res, 400, { error: 'not a scene (no objects)' });
146
+ const b = await putEither(pathOf(name), body);
147
+ return send(res, 200, { ok: true, name, size: body.length, url: b.url });
148
+ }
149
+ if (req.method === 'DELETE') {
150
+ const blob = await findBlob(name);
151
+ if (blob) await del(blob.url, { token: TOKEN() });
152
+ return send(res, 200, { ok: true, name, gone: Boolean(blob) });
153
+ }
154
+ return send(res, 405, { error: 'GET, PUT or DELETE' });
155
+ } catch (err) {
156
+ return send(res, 500, { error: String(err?.message ?? err) });
157
+ }
158
+ }
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { createServer } from 'node:http';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { resolve, join, sep, extname, dirname } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');
7
+ const port=Number(process.env.PORT || process.argv[2] || 5173);
8
+ const types={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.webmanifest':'application/manifest+json','.md':'text/plain; charset=utf-8','.css':'text/css; charset=utf-8','.wasm':'application/wasm'};
9
+ createServer(async(req,res)=>{
10
+ if(req.method!=='GET'&&req.method!=='HEAD'){res.writeHead(405).end();return;}
11
+ try{
12
+ const url=new URL(req.url,'http://localhost');
13
+ const rel=decodeURIComponent(url.pathname).replace(/^\/+/, '') || 'index.html';
14
+ const file=resolve(root,rel);
15
+ if(file!==root&&!file.startsWith(root+sep))throw Error('path traversal');
16
+ const data=await readFile(file);
17
+ res.writeHead(200,{'Content-Type':types[extname(file)]||'application/octet-stream','X-Content-Type-Options':'nosniff'});
18
+ res.end(req.method==='HEAD'?'':data);
19
+ }catch{res.writeHead(404).end('Not found');}
20
+ }).listen(port,()=>console.log('spi3Der: http://localhost:'+port));
package/emulator.html ADDED
@@ -0,0 +1,17 @@
1
+ <!doctype html>
2
+ <meta charset="utf-8">
3
+ <title>five-percent · XR emulator demo</title>
4
+ <meta name="viewport" content="width=device-width,initial-scale=1">
5
+ <style>
6
+ html, body { margin: 0; height: 100%; background: #101418; color: #cfd8dc; font: 14px system-ui, sans-serif; }
7
+ canvas { display: block; width: 100%; height: 100%; }
8
+ #ui { position: fixed; left: 12px; top: 12px; max-width: 360px; line-height: 1.4; }
9
+ button { font: inherit; padding: 6px 12px; }
10
+ #log { opacity: .7; white-space: pre; }
11
+ </style>
12
+ <canvas id="c"></canvas>
13
+ <div id="ui">
14
+ <button id="enter">Enter VR (emulated)</button>
15
+ <div id="log">WASD walk · R/F up/down · arrows or right-drag look · click = trigger · Shift+click = left · Space = squeeze</div>
16
+ </div>
17
+ <script type="module" src="./src/demo.js"></script>