paralaif commited on
Commit
dd53693
·
verified ·
1 Parent(s): 73ee9bd

Tiny Scene: text to animated three.js scenes with a 4.85M Transformer

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ docs/example.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ node_modules/
2
+ .venv/
3
+ __pycache__/
4
+ ml/backup_v1/
5
+ ml/train.log
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 paralaif
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ - es
6
+ library_name: pytorch
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - threejs
10
+ - text-to-3d
11
+ - 3d
12
+ - animation
13
+ - webgl
14
+ - browser
15
+ - tiny
16
+ - trained-from-scratch
17
+ ---
18
+
19
+ # Tiny Scene
20
+
21
+ Text → animated 3D scene in **three.js**, driven by a tiny Transformer trained from scratch that runs entirely in the browser.
22
+
23
+ ![Example scene built from one prompt and two edits](docs/example.png)
24
+
25
+ Inspired by [WVY-Blender-5m](https://huggingface.co/StarpowerTechnology/WVY-Blender-5m): same idea (a small model translates a sentence into a compact scene language, and procedural code builds the result), but the builder is three.js instead of Blender. No code or weights from that repository are reused.
26
+
27
+ ```
28
+ "a red fox jumping over a blue car in the desert at sunset"
29
+ │ model (4.85 M parameters, ~0.3 s on CPU, plain JavaScript)
30
+ ▼
31
+ <new> loc=desert time=sunset <ent> type=fox color=red act=jump rel=over <ent> type=car color=blue
32
+ │ interpreter + procedural builder (three.js, no custom shaders)
33
+ ▼
34
+ real-time animated scene, editable with more sentences
35
+ ```
36
+
37
+ ## Try it
38
+
39
+ Download the repository and serve the `web/` folder with any static server, for example:
40
+
41
+ ```bash
42
+ python3 -m http.server 8080 --directory web
43
+ ```
44
+
45
+ Open <http://localhost:8080>. Type in English or Spanish:
46
+
47
+ | Kind | Examples |
48
+ |---|---|
49
+ | New scene | `an alien riding a horse on the moon` · `tres pingüinos caminando en la nieve mientras nieva` |
50
+ | Edit | `make the fox green` · `add a giant tree` · `remove the car` · `make it rain` · `zoom out` · `orbit the camera` |
51
+ | Ask | `what can you do?` · `how do i enable shadows` · `what objects do you know` |
52
+
53
+ Drag to orbit the view. **Export .glb** saves the current frame (opens in Blender); animations are procedural and are not exported.
54
+
55
+ The page also accepts `?q=first prompt;second prompt&t=3` to run prompts on load and freeze time at that second.
56
+
57
+ The interface labels are in Spanish; the model understands both languages.
58
+
59
+ ## What it can do
60
+
61
+ | | |
62
+ |---|---|
63
+ | Objects (54) | animals, characters, vehicles and props: dog, dragon, robot, astronaut, car, rocket, UFO, tree, tower… |
64
+ | Actions (17) | idle, walk, run, jump, spin, dance, fly, float, sit, sleep, wave, bounce, roll, circle, shake, swim, drive |
65
+ | Relations (8) | on, over, near, behind, front, around, ride, chase |
66
+ | Places (15) | field, desert, snow, beach, forest, city, space, moon, ocean, room, mountain, farm, road, park, studio |
67
+ | Time and weather | day, night, sunset, dawn · clear, rain, snow, fog, storm |
68
+ | Camera | shots close, medium, wide, top, low · moves static, orbit, zoomin, zoomout, pan, follow |
69
+ | Attributes | 14 colours, 4 sizes (plus "bigger / smaller"), count 2–6, speed |
70
+ | Questions | 24 topics about three.js and the app itself; the model picks language and topic, and the answer is stored in `web/model/qa.json` |
71
+
72
+ ## How it works
73
+
74
+ ```
75
+ ml/ lexicon.py scene-language vocabulary and the English and Spanish words for it
76
+ gen.py generator of (sentence → tokens) pairs, with typos and dropped accents
77
+ model.py decoder-only Transformer (6 layers, d=256, 8 heads, context 208)
78
+ train.py trains on pairs generated on the fly and exports to web/model/
79
+ infer.py command-line inference
80
+ web/ js/nn/model.js the same Transformer in plain JavaScript, with a KV cache
81
+ js/lang/scenelang.js tokens → scene JSON, and applying edits
82
+ js/scene/ creatures.js, things.js (objects), animate.js (poses),
83
+ layout.js (placement and relations), environment.js, stage.js
84
+ tests/ check_scene.mjs builds every object × action and place × time × weather combination
85
+ check_model.mjs JS ↔ PyTorch parity and hand-written prompts
86
+ check_export.mjs .glb export in a real browser
87
+ ```
88
+
89
+ - **Input**: the sentence is split into characters (50 symbols), which makes it tolerant to typos. **Output**: fixed scene-language tokens. Total vocabulary: 235.
90
+ - **Data**: there is no dataset on disk. `gen.py` produces endless random pairs from templates; every batch is new.
91
+ - **Weights**: `web/model/weights.bin` is 9.7 MB in float16 (used by the browser). `ml/model.pt` is the float32 PyTorch checkpoint.
92
+
93
+ ## Results
94
+
95
+ Included model: 4,852,480 parameters, 14,000 steps with batches of 256 (3.58 M pairs), 18 minutes on an RTX 5060 Ti.
96
+
97
+ | Test | Result |
98
+ |---|---|
99
+ | New generator sentences, clean (3,000) | 99.93 % exact outputs |
100
+ | New generator sentences, with typos (3,000) | 99.70 % |
101
+ | Hand-written sentences outside the templates (59, `tests/natural.json`) | 58 exact |
102
+ | JavaScript vs PyTorch (300 sentences) | 300 identical |
103
+ | Time per sentence in JavaScript (Node, one thread) | ~235 ms |
104
+ | Scenes built without errors (object × action, place × time × weather, relations) | 1,478 of 1,478 |
105
+
106
+ The first two rows measure sentences with the same grammar as training, so they are optimistic. The third is the most honest, but it is small, and two of its early failures (`a wide shot of…`, an object mentioned after the place) led to adding templates and retraining; the first version scored 57.
107
+
108
+ ## Retrain
109
+
110
+ ```bash
111
+ uv venv .venv && uv pip install --python .venv/bin/python torch numpy
112
+ ```
113
+
114
+ ```bash
115
+ npm install
116
+ ```
117
+
118
+ ```bash
119
+ npm run train
120
+ ```
121
+
122
+ ```bash
123
+ npm test
124
+ ```
125
+
126
+ To add an object: an entry in `_TYPES` in `ml/lexicon.py`, a builder in `web/js/scene/things.js` or `creatures.js`, then retrain. `npm test` fails if the vocabulary names something three.js cannot build.
127
+
128
+ ## Limitations
129
+
130
+ - It only understands the vocabulary above. Anything unknown is replaced by the closest match or ignored (`a little girl flying a kite` gives a small woman flying).
131
+ - It does not generate new geometry: every object is hand-modelled from primitives.
132
+ - Edits refer to objects by type (`the dog`), not by colour or position; with two different dogs, both change.
133
+ - A place has no colour (`in a blue house` is read as a dog and a blue house).
134
+ - Known miss: `i'd like the bear to be sleeping` adds a delete that was not asked for.
135
+ - Long sentences with three objects and many modifiers are where it fails most.
136
+
137
+ ## Credits
138
+
139
+ three.js (MIT license) is bundled in `web/vendor/`; its license is in `web/vendor/LICENSE`.
docs/example.png ADDED

Git LFS Details

  • SHA256: ef7824ba351e43395a9a2d9abfc7f95f930caf3fc0cd7ef980598cf27e4d00d3
  • Pointer size: 131 Bytes
  • Size of remote file: 144 kB
ml/gen.py ADDED
@@ -0,0 +1,617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic (prompt -> scene language) pairs in English and Spanish.
2
+
3
+ sample(rng) returns (prompt_text, [target tokens]). Three kinds of targets:
4
+ <new> ... a full scene
5
+ <edit> <set|add|del|env|cam> ... operations on the current scene
6
+ <qa> lang=.. topic=.. a three.js question
7
+ """
8
+ import random
9
+ import unicodedata
10
+
11
+ from lexicon import (ACT, AROUND_ACTS, CAM, COLOR, LOC, MOTION, OVER_ACTS, REL, SHOT, SIZE, SPD, TIME,
12
+ TYPES, WEATHER)
13
+ from qa_topics import Q_EN, Q_ES, SUF_EN, SUF_ES, TOPICS
14
+
15
+ TYPE_KEYS, COLOR_KEYS, SIZE_KEYS, ACT_KEYS = list(TYPES), list(COLOR), list(SIZE), list(ACT)
16
+ NUM = {"en": {2: "two", 3: "three", 4: "four", 5: "five", 6: "six"},
17
+ "es": {2: "dos", 3: "tres", 4: "cuatro", 5: "cinco", 6: "seis"}}
18
+ MAX_PROMPT = 160
19
+
20
+
21
+ # ------------------------------------------------------------------ helpers
22
+ def agree(s, g, pl):
23
+ return s.replace("{o}", {("m", 0): "o", ("f", 0): "a", ("m", 1): "os", ("f", 1): "as"}[(g, int(pl))])
24
+
25
+
26
+ def es_form(forms, g, pl):
27
+ return forms[(0 if g == "m" else 1) + (2 if pl else 0)]
28
+
29
+
30
+ def an(word):
31
+ w = word.lower()
32
+ return "an" if (w[0] in "aeio" or (w[0] == "u" and not w.startswith("uf"))) else "a"
33
+
34
+
35
+ def es_join(prep, np):
36
+ """'encima de' + 'el coche' -> 'encima del coche'; 'a' + 'el perro' -> 'al perro'."""
37
+ if np.startswith("el "):
38
+ if prep.endswith(" de") or prep == "de":
39
+ return prep[:-2] + "del " + np[3:]
40
+ if prep.endswith(" a") or prep == "a":
41
+ return prep[:-1] + "al " + np[3:]
42
+ return f"{prep} {np}"
43
+
44
+
45
+ def rand_ent(r, act=True, n=True):
46
+ e = {"type": r.choice(TYPE_KEYS)}
47
+ if r.random() < 0.45:
48
+ e["color"] = r.choice(COLOR_KEYS)
49
+ if r.random() < 0.2:
50
+ e["size"] = r.choice(SIZE_KEYS)
51
+ if n and r.random() < 0.15:
52
+ e["n"] = r.randint(2, 6)
53
+ if act and r.random() < 0.6:
54
+ e["act"] = r.choice(ACT_KEYS)
55
+ if e["act"] in MOTION and r.random() < 0.2:
56
+ e["spd"] = r.choice(["slow", "fast"])
57
+ return e
58
+
59
+
60
+ def ent_tokens(e, head="<ent>"):
61
+ t = [head, "type=" + e["type"]]
62
+ for k in ("color", "size", "n", "act", "spd", "rel"):
63
+ if k in e:
64
+ t.append(f"{k}={e[k]}")
65
+ return t
66
+
67
+
68
+ # ------------------------------------------------------------------ noun phrases
69
+ def np_en(r, e, det=None, act=True):
70
+ sing, plur = r.choice(TYPES[e["type"]].en)
71
+ n = e.get("n")
72
+ pl = n is not None
73
+ adjs = []
74
+ if "size" in e:
75
+ adjs.append(r.choice(SIZE[e["size"]].en))
76
+ if "color" in e:
77
+ adjs.append(r.choice(COLOR[e["color"]].en))
78
+ pre, post = None, ""
79
+ a = e.get("act") if act else None
80
+ if a:
81
+ A = ACT[a]
82
+ adv = " " + r.choice(SPD[e["spd"]].en) if "spd" in e else ""
83
+ ing = r.choice(A.ing)
84
+ x = r.random()
85
+ if x < 0.13 and " " not in ing and not adv:
86
+ pre = ing
87
+ elif x < 0.70:
88
+ post = f" {ing}{adv}"
89
+ elif x < 0.82:
90
+ post = f" that {'are' if pl else 'is'} {ing}{adv}"
91
+ elif x < 0.90:
92
+ post = f" {'are' if pl else 'is'} {ing}{adv}"
93
+ else:
94
+ post = f" {r.choice(A.base) if pl else r.choice(A.s3)}{adv}"
95
+ words = ([pre] if pre else []) + adjs + [plur if pl else sing]
96
+ if pl:
97
+ d = r.choice([NUM["en"][n], NUM["en"][n], str(n)])
98
+ if det == "the":
99
+ d = "the " + d if r.random() < 0.5 else "the"
100
+ else:
101
+ if det is None:
102
+ det = r.choices(["a", "the", "one", ""], [0.78, 0.12, 0.05, 0.05])[0]
103
+ d = an(words[0]) if det == "a" else det
104
+ return (d + " " if d else "") + " ".join(words) + post
105
+
106
+
107
+ def np_es(r, e, det=None, act=True):
108
+ sing, plur, g = r.choice(TYPES[e["type"]].es)
109
+ n = e.get("n")
110
+ pl = n is not None
111
+ adjs = []
112
+ if "color" in e:
113
+ adjs.append(es_form(r.choice(COLOR[e["color"]].es), g, pl))
114
+ if "size" in e:
115
+ adjs.append(es_form(r.choice(SIZE[e["size"]].es), g, pl))
116
+ if len(adjs) == 2 and r.random() < 0.25:
117
+ adjs.reverse()
118
+ post = ""
119
+ a = e.get("act") if act else None
120
+ if a:
121
+ A = ACT[a]
122
+ adv = " " + r.choice(SPD[e["spd"]].es) if "spd" in e else ""
123
+ ger = agree(r.choice(A.ger), g, pl)
124
+ x = r.random()
125
+ if x < 0.62:
126
+ post = f" {ger}{adv}"
127
+ elif x < 0.88:
128
+ post = f" que {agree(r.choice(A.e3p if pl else A.e3), g, pl)}{adv}"
129
+ else:
130
+ post = f" que {'están' if pl else 'está'} {ger}{adv}"
131
+ if pl:
132
+ d = r.choice([NUM["es"][n], NUM["es"][n], str(n)])
133
+ if det == "the":
134
+ art = "los" if g == "m" else "las"
135
+ d = f"{art} {d}" if r.random() < 0.5 else art
136
+ else:
137
+ if det is None:
138
+ det = r.choices(["a", "the", ""], [0.82, 0.13, 0.05])[0]
139
+ d = {"a": "un" if g == "m" else "una", "the": "el" if g == "m" else "la", "": ""}[det]
140
+ return (d + " " if d else "") + " ".join([plur if pl else sing] + adjs) + post, g, pl
141
+
142
+
143
+ def NP(r, lang, e, det=None, act=True):
144
+ return np_en(r, e, det, act) if lang == "en" else np_es(r, e, det, act)[0]
145
+
146
+
147
+ # ------------------------------------------------------------------ new scenes
148
+ PREFIX = {
149
+ "en": ["create ", "make ", "generate ", "show me ", "i want ", "i want to see ", "a scene with ", "scene of ",
150
+ "an animation of ", "draw ", "render ", "give me ", "build ", "animate "],
151
+ "es": ["crea ", "genera ", "haz ", "muéstrame ", "quiero ", "quiero ver ", "una escena con ", "escena de ",
152
+ "una animación de ", "dibuja ", "dame ", "construye ", "hazme ", "anima "],
153
+ }
154
+ CONJ = {"en": [" and ", " and ", ", ", " with ", " and also ", " plus "],
155
+ "es": [" y ", " y ", ", ", " con ", " y también ", " más "]}
156
+
157
+
158
+ def modifiers(r, lang, p=(0.55, 0.25, 0.2, 0.15, 0.15)):
159
+ """-> (list of phrases, dict of chosen keys)"""
160
+ out, keys = [], {}
161
+ for name, table, prob in (("loc", LOC, p[0]), ("time", TIME, p[1]), ("weather", WEATHER, p[2]),
162
+ ("shot", SHOT, p[3]), ("cam", CAM, p[4])):
163
+ if r.random() < prob:
164
+ k = r.choice(list(table))
165
+ keys[name] = k
166
+ out.append((name, r.choice(getattr(table[k], lang))))
167
+ return out, keys
168
+
169
+
170
+ SHOT_PRE = {
171
+ "en": {"close": ["close-up of", "a close-up of", "closeup of", "close up shot of"],
172
+ "medium": ["medium shot of", "a medium shot of"],
173
+ "wide": ["wide shot of", "a wide shot of", "wide angle shot of", "long shot of"],
174
+ "top": ["aerial view of", "top view of", "top-down view of", "bird's eye view of", "an aerial shot of"],
175
+ "low": ["low angle shot of", "a low angle view of"]},
176
+ "es": {"close": ["primer plano de", "un primer plano de", "plano cerrado de"],
177
+ "medium": ["plano medio de", "un plano medio de"],
178
+ "wide": ["plano general de", "un plano general de", "plano abierto de", "vista general de"],
179
+ "top": ["vista aérea de", "una vista aérea de", "vista cenital de", "toma aérea de"],
180
+ "low": ["ángulo bajo de", "contrapicado de", "vista desde abajo de"]},
181
+ }
182
+
183
+
184
+ def mod_tokens(keys):
185
+ return [f"{k}={keys[k]}" for k in ("loc", "time", "weather", "shot", "cam") if k in keys]
186
+
187
+
188
+ def new_scene(r, lang):
189
+ k = r.choices([1, 2, 3], [0.5, 0.4, 0.1])[0]
190
+ ents = []
191
+ while len(ents) < k:
192
+ e = rand_ent(r)
193
+ if all(e["type"] != o["type"] for o in ents):
194
+ ents.append(e)
195
+ rels = []
196
+ for i in range(k - 1):
197
+ rel = r.choice(list(REL)) if r.random() < 0.6 else None
198
+ a = ents[i]
199
+ if rel in ("ride", "chase"):
200
+ a.pop("act", None), a.pop("spd", None)
201
+ if rel == "chase":
202
+ ents[i + 1].pop("act", None), ents[i + 1].pop("spd", None)
203
+ elif rel == "over" and a.get("act") not in OVER_ACTS:
204
+ a["act"] = r.choice(OVER_ACTS)
205
+ elif rel == "around" and a.get("act") not in AROUND_ACTS:
206
+ a["act"] = r.choice(AROUND_ACTS)
207
+ if a.get("act") not in MOTION:
208
+ a.pop("spd", None)
209
+ if rel:
210
+ a["rel"] = rel
211
+ rels.append(rel)
212
+
213
+ segs = []
214
+ for i, e in enumerate(ents):
215
+ text = ""
216
+ if lang == "en":
217
+ s = np_en(r, e)
218
+ else:
219
+ s, g, pl = np_es(r, e)
220
+ if i:
221
+ rel = rels[i - 1]
222
+ if rel is None:
223
+ text += r.choice(CONJ[lang]) + s
224
+ else:
225
+ prep = r.choice(getattr(REL[rel], lang))
226
+ if lang == "es":
227
+ if rel == "on" and prep == "sobre" and ents[i - 1].get("act") in OVER_ACTS:
228
+ prep = "encima de"
229
+ prep = agree(prep, pg, ppl)
230
+ text += " " + es_join(prep, s)
231
+ else:
232
+ text += f" {prep} {s}"
233
+ else:
234
+ text = s
235
+ segs.append(text)
236
+ if lang == "es":
237
+ pg, ppl = g, pl
238
+
239
+ mods, keys = modifiers(r, lang)
240
+ r.shuffle(mods)
241
+ shot_pre = None
242
+ if "shot" in keys and r.random() < 0.3: # "a wide shot of a train ..."
243
+ mods = [m for m in mods if m[0] != "shot"]
244
+ shot_pre = r.choice(SHOT_PRE[lang][keys["shot"]])
245
+ mid = None
246
+ if k > 1 and rels[0] is None and "loc" in keys and r.random() < 0.25: # "a shark in the ocean and a duck"
247
+ mid = next(m for m in mods if m[0] == "loc")
248
+ mods = [m for m in mods if m is not mid]
249
+ segs[0] += " " + mid[1]
250
+ text = "".join(segs)
251
+ loc_first = [m for m in mods if m[0] == "loc"] if r.random() < 0.18 else []
252
+ rest = [m[1] for m in mods if m not in loc_first]
253
+ sep = r.choice([" ", " ", ", "])
254
+ if shot_pre:
255
+ text = es_join(shot_pre, text) if lang == "es" else f"{shot_pre} {text}"
256
+ if loc_first:
257
+ text = loc_first[0][1] + r.choice([", ", " ", ": "]) + text
258
+ if rest:
259
+ text += r.choice([" ", " ", ", "]) + sep.join(rest)
260
+ if r.random() < 0.3 and not shot_pre:
261
+ text = r.choice(PREFIX[lang]) + text
262
+ tokens = ["<new>"] + mod_tokens(keys)
263
+ for e in ents:
264
+ tokens += ent_tokens(e)
265
+ return text, tokens
266
+
267
+
268
+ # ------------------------------------------------------------------ edits
269
+ def ref_en(r, e):
270
+ sing, plur = r.choice(TYPES[e["type"]].en)
271
+ return "the " + (plur if r.random() < 0.12 else sing)
272
+
273
+
274
+ def ref_es(r, e):
275
+ sing, plur, g = r.choice(TYPES[e["type"]].es)
276
+ if r.random() < 0.12:
277
+ return ("los " if g == "m" else "las ") + plur, g, True
278
+ return ("el " if g == "m" else "la ") + sing, g, False
279
+
280
+
281
+ E = {}
282
+ E["color_en"] = ["make {ref} {c}", "paint {ref} {c}", "change {ref} to {c}", "turn {ref} {c}", "color {ref} {c}",
283
+ "{ref} should be {c}", "i want {ref} {c}", "change the color of {ref} to {c}", "{ref} in {c}",
284
+ "now {ref} is {c}", "make {ref} {c} instead", "can you make {ref} {c}", "{ref} {c}"]
285
+ E["color_it_en"] = ["make it {c}", "paint it {c}", "turn it {c}", "change it to {c}", "color it {c}", "make that {c}",
286
+ "i want it {c}", "now make it {c}"]
287
+ E["color_all_en"] = ["make everything {c}", "paint everything {c}", "all of them {c}", "make them all {c}",
288
+ "turn everything {c}", "color all of them {c}"]
289
+ E["color_es"] = ["haz {ref} {c}", "pinta {ref} de {cm}", "cambia {ref} a {cm}", "pon {ref} {c}", "que {ref} sea {c}",
290
+ "quiero {ref} {c}", "cambia el color de {ref} a {cm}", "{ref} {c}", "ahora {ref} es {c}",
291
+ "vuelve {ref} {c}", "{ref} de color {cm}", "puedes hacer {ref} {c}", "pon {ref} de color {cm}"]
292
+ E["color_it_es"] = ["hazlo {cm}", "hazla {cf}", "píntalo de {cm}", "ponlo {cm}", "cámbialo a {cm}", "píntala de {cm}",
293
+ "lo quiero {cm}", "ahora hazlo {cm}", "ponlo de color {cm}"]
294
+ E["color_all_es"] = ["haz todo {cm}", "pinta todo de {cm}", "todos {cmp}", "que todos sean {cmp}", "pon todo {cm}",
295
+ "todo de color {cm}"]
296
+
297
+ E["size_en"] = ["make {ref} {s}", "{ref} should be {s}", "i want {ref} {s}", "turn {ref} {s}"]
298
+ E["up_en"] = ["make {ref} bigger", "make {ref} larger", "enlarge {ref}", "grow {ref}", "{ref} bigger",
299
+ "increase the size of {ref}", "scale up {ref}"]
300
+ E["down_en"] = ["make {ref} smaller", "shrink {ref}", "{ref} smaller", "reduce the size of {ref}", "scale down {ref}"]
301
+ E["size_es"] = ["haz {ref} {s}", "que {ref} sea {s}", "pon {ref} {s}", "quiero {ref} {s}"]
302
+ E["up_es"] = ["haz {ref} más grande", "agranda {ref}", "{ref} más grande", "aumenta el tamaño de {ref}",
303
+ "haz crecer {ref}", "que {ref} sea más grande"]
304
+ E["down_es"] = ["haz {ref} más pequeñ{o}", "achica {ref}", "reduce {ref}", "encoge {ref}", "{ref} más pequeñ{o}",
305
+ "{ref} más chic{o}", "reduce el tamaño de {ref}"]
306
+
307
+ E["act_en"] = ["make {ref} {base}", "{ref} should {base}", "now {ref} {s3}", "{ref} {s3} now", "have {ref} {base}",
308
+ "let {ref} {base}", "{ref} is {ing} now", "i want {ref} to {base}", "{ref} {ing}",
309
+ "{ref} starts to {base}", "can {ref} {base}", "make {ref} start {ing}"]
310
+ E["act_es"] = ["haz que {ref} {subj}", "que {ref} {subj}", "ahora {ref} {e3}", "{ref} {e3} ahora",
311
+ "pon {aref} a {inf}", "quiero que {ref} {subj}", "{ref} {ger}", "que {ref} empiece a {inf}",
312
+ "{ref} debe {inf}", "haz {inf} {aref}", "ahora {ref} está {ger}"]
313
+
314
+ E["fast_en"] = ["make {ref} faster", "speed up {ref}", "{ref} faster", "make {ref} go faster", "{ref} should move faster"]
315
+ E["slow_en"] = ["make {ref} slower", "slow down {ref}", "{ref} slower", "make {ref} go slower", "{ref} should move slowly"]
316
+ E["normal_en"] = ["{ref} at normal speed", "reset the speed of {ref}", "make {ref} move at normal speed"]
317
+ E["fast_es"] = ["haz {ref} más rápido", "acelera {ref}", "{ref} más rápido", "que {ref} vaya más rápido",
318
+ "{ref} más veloz"]
319
+ E["slow_es"] = ["haz {ref} más lento", "{ref} más despacio", "frena {ref}", "que {ref} vaya más lento",
320
+ "{ref} más lento"]
321
+ E["normal_es"] = ["{ref} a velocidad normal", "reinicia la velocidad de {ref}", "que {ref} vaya a velocidad normal"]
322
+
323
+ E["add_en"] = ["add {np}", "add {np}", "put {np}", "add {np} too", "i also want {np}", "also {np}", "now add {np}",
324
+ "include {np}", "place {np}", "insert {np}", "add {np} as well", "put {np} there", "and {np}",
325
+ "can you add {np}", "throw in {np}"]
326
+ E["add_es"] = ["añade {np}", "agrega {np}", "pon {np}", "añade también {np}", "también {np}", "quiero también {np}",
327
+ "ahora añade {np}", "incluye {np}", "coloca {np}", "mete {np}", "suma {np}", "y {np}",
328
+ "puedes añadir {np}", "ponle {np}", "agrégale {np}"]
329
+ E["del_en"] = ["remove {ref}", "delete {ref}", "erase {ref}", "take away {ref}", "get rid of {ref}", "without {ref}",
330
+ "take {ref} out", "no {ref}", "i don't want {ref}", "drop {ref}", "remove {ref} please"]
331
+ E["del_es"] = ["quita {ref}", "elimina {ref}", "borra {ref}", "saca {ref}", "remueve {ref}", "sin {ref}",
332
+ "ya no quiero {ref}", "quita {aref}", "fuera {ref}", "no quiero {ref}", "elimina {aref}"]
333
+ E["del_it_en"] = ["remove it", "delete it", "erase it", "get rid of it", "take it away"]
334
+ E["del_it_es"] = ["quítalo", "bórralo", "elimínalo", "sácalo", "quítala"]
335
+ E["del_all_en"] = ["clear the scene", "remove everything", "delete everything", "start over", "empty the scene",
336
+ "clear all", "erase everything", "reset the scene"]
337
+ E["del_all_es"] = ["borra todo", "limpia la escena", "quita todo", "elimina todo", "empieza de nuevo",
338
+ "vacía la escena", "reinicia la escena"]
339
+
340
+ E["loc_en"] = ["now {p}", "move the scene {p}", "put them {p}", "now they are {p}", "set the scene {p}", "take them {p}",
341
+ "{p}", "change the location to {bare}", "switch to {bare}", "go to {bare}", "change the background to {bare}",
342
+ "change the place to {bare}", "move it {p}"]
343
+ E["loc_es"] = ["ahora {p}", "ponlos {p}", "que estén {p}", "que sea {p}", "{p}", "cambia el lugar a {bare}",
344
+ "cambia el fondo a {bare}", "cambia el escenario a {bare}", "llévalos a {bare}", "vamos a {bare}",
345
+ "mueve la escena a {bare}", "ponlo {p}"]
346
+ TIME_W = {
347
+ "en": {"day": ["day", "daytime", "noon"], "night": ["night", "nighttime", "midnight"],
348
+ "sunset": ["sunset", "dusk", "evening"], "dawn": ["dawn", "sunrise", "morning"]},
349
+ "es": {"day": ["el día", "el mediodía"], "night": ["la noche", "la medianoche"],
350
+ "sunset": ["el atardecer", "el anochecer"], "dawn": ["el amanecer", "la madrugada"]},
351
+ }
352
+ E["time_en"] = ["make it {w}", "change it to {w}", "switch to {w}", "set the time to {w}", "now it is {w}", "now {p}",
353
+ "i want it {p}", "{p}", "change the time to {w}", "turn it into {w}"]
354
+ E["time_es"] = ["que sea {p}", "hazlo {p}", "ponlo {p}", "ahora es {p}", "ahora {p}", "{p}", "cambia la hora a {w}",
355
+ "cambia a {w}", "pasa a {w}", "lo quiero {p}"]
356
+ TIME_X = {"es": {"night": ["que anochezca", "que se haga de noche", "oscurece la escena"],
357
+ "dawn": ["que amanezca"], "day": ["que se haga de día", "que salga el sol"], "sunset": ["que atardezca"]},
358
+ "en": {"night": ["make it dark", "turn off the sun"], "day": ["make it bright", "let the sun come out"],
359
+ "dawn": ["let the sun rise"], "sunset": ["let the sun set"]}}
360
+ WEATHER_E = {
361
+ "en": {"rain": ["make it rain", "add rain", "start the rain", "let it rain", "i want rain", "now it rains", "rain"],
362
+ "snow": ["make it snow", "add snow", "let it snow", "now it snows", "start snowing", "add snowfall"],
363
+ "fog": ["add fog", "make it foggy", "add some mist", "i want fog", "fog"],
364
+ "storm": ["add a storm", "make it stormy", "start a thunderstorm", "add lightning", "i want a storm"],
365
+ "clear": ["stop the rain", "remove the rain", "stop the snow", "remove the fog", "clear the weather",
366
+ "clear the sky", "no more rain", "make it sunny", "stop the storm", "good weather",
367
+ "remove the snow", "no more fog", "stop raining", "stop snowing"]},
368
+ "es": {"rain": ["que llueva", "haz que llueva", "pon lluvia", "añade lluvia", "agrega lluvia", "ahora llueve",
369
+ "quiero lluvia", "lluvia"],
370
+ "snow": ["que nieve", "haz que nieve", "pon nieve", "añade nieve", "ahora nieva", "que caiga nieve"],
371
+ "fog": ["pon niebla", "añade niebla", "agrega neblina", "que haya niebla", "niebla"],
372
+ "storm": ["pon una tormenta", "añade una tormenta", "que haya tormenta", "agrega rayos", "quiero una tormenta"],
373
+ "clear": ["para la lluvia", "quita la lluvia", "que deje de llover", "quita la nieve", "que deje de nevar",
374
+ "quita la niebla", "despeja el cielo", "quita la tormenta", "buen tiempo", "cielo despejado",
375
+ "que pare de llover", "ya no quiero lluvia", "que salga el sol y pare la lluvia"]},
376
+ }
377
+ SHOT_E = {
378
+ "en": {"in": ["zoom in", "closer", "get closer", "move the camera closer", "bring the camera closer",
379
+ "zoom in a bit", "come closer"],
380
+ "out": ["zoom out", "move the camera back", "farther", "pull back", "zoom out a little", "further away",
381
+ "move the camera away"],
382
+ "close": ["switch to a close-up", "make it a close-up", "show a close-up"],
383
+ "wide": ["make it a wide shot", "show the whole scene", "switch to a wide shot"],
384
+ "medium": ["normal view", "reset the camera", "default camera"],
385
+ "top": ["view from above", "show it from above", "camera from above", "look from above"],
386
+ "low": ["camera from below", "view from below", "look from below"]},
387
+ "es": {"in": ["acerca la cámara", "más cerca", "acércate", "haz zoom", "zoom in", "acerca un poco",
388
+ "acerca más la cámara"],
389
+ "out": ["aleja la cámara", "más lejos", "aléjate", "zoom out", "aleja un poco", "aleja más la cámara"],
390
+ "close": ["pon un primer plano", "cambia a primer plano", "muestra un primer plano"],
391
+ "wide": ["muestra toda la escena", "cambia a plano general", "pon un plano abierto"],
392
+ "medium": ["vista normal", "reinicia la cámara", "cámara por defecto"],
393
+ "top": ["cámara desde arriba", "míralo desde arriba", "vista desde arriba"],
394
+ "low": ["cámara desde abajo", "míralo desde abajo", "vista desde abajo"]},
395
+ }
396
+ CAM_E = {
397
+ "en": {"static": ["stop the camera", "keep the camera still", "fix the camera", "freeze the camera"],
398
+ "orbit": ["orbit the camera", "rotate the camera", "spin the camera around", "make the camera orbit",
399
+ "camera orbit"],
400
+ "zoomin": ["animate a zoom in", "keep zooming in", "make the camera zoom in slowly"],
401
+ "zoomout": ["animate a zoom out", "keep zooming out", "make the camera zoom out slowly"],
402
+ "pan": ["pan the camera", "camera pan", "make the camera pan"],
403
+ "follow": ["follow {ref}", "make the camera follow {ref}", "camera follows {ref}", "track {ref}",
404
+ "follow it", "follow them with the camera"]},
405
+ "es": {"static": ["detén la cámara", "para la cámara", "deja la cámara quieta", "fija la cámara"],
406
+ "orbit": ["gira la cámara", "orbita la cámara", "que la cámara gire", "rota la cámara",
407
+ "que la cámara orbite"],
408
+ "zoomin": ["que la cámara se acerque lentamente", "anima un zoom in", "sigue acercando la cámara"],
409
+ "zoomout": ["que la cámara se aleje lentamente", "anima un zoom out", "sigue alejando la cámara"],
410
+ "pan": ["panea la cámara", "haz un paneo", "que la cámara panee", "mueve la cámara de lado"],
411
+ "follow": ["sigue {aref}", "que la cámara siga {aref}", "cámara siguiendo {aref}", "síguelo",
412
+ "síguelos con la cámara"]},
413
+ }
414
+
415
+
416
+ def bare(lang, p):
417
+ w = p.split(" ")
418
+ if w[0] in ("in", "on", "at", "en") and len(w) > 1:
419
+ return " ".join(w[1:])
420
+ return p
421
+
422
+
423
+ def edit_op(r, lang):
424
+ """-> (text, tokens) for one edit operation."""
425
+ kind = r.choices(["color", "size", "act", "spd", "add", "del", "loc", "time", "weather", "shot", "cam"],
426
+ [16, 8, 14, 5, 16, 12, 7, 6, 7, 6, 5])[0]
427
+ e = {"type": r.choice(TYPE_KEYS)}
428
+ if lang == "en":
429
+ ref, g, pl = ref_en(r, e), "m", False
430
+ aref = ref
431
+ else:
432
+ ref, g, pl = ref_es(r, e)
433
+ aref = es_join("a", ref)
434
+ f = lambda key: r.choice(E[f"{key}_{lang}"])
435
+
436
+ def fill(t, **kw):
437
+ t = t.replace("{ref}", ref).replace("{aref}", aref)
438
+ for k, v in kw.items():
439
+ t = t.replace("{" + k + "}", v)
440
+ if lang == "es":
441
+ t = agree(t, g, pl).replace(" de el ", " del ").replace(" a el ", " al ")
442
+ return t
443
+
444
+ if kind == "color":
445
+ c = r.choice(COLOR_KEYS)
446
+ who = r.choices(["ref", "it", "all"], [0.72, 0.18, 0.10])[0]
447
+ key = {"ref": "color", "it": "color_it", "all": "color_all"}[who]
448
+ if lang == "en":
449
+ text = fill(f(key), c=r.choice(COLOR[c].en))
450
+ else:
451
+ cf = r.choice(COLOR[c].es)
452
+ text = fill(f(key), c=es_form(cf, g, pl), cm=cf[0], cf=cf[1], cmp=cf[2])
453
+ ty = {"ref": e["type"], "it": "it", "all": "all"}[who]
454
+ return text, ["<set>", f"type={ty}", f"color={c}"]
455
+
456
+ if kind == "size":
457
+ s = r.choice(SIZE_KEYS + ["up", "up", "down", "down"])
458
+ if s in ("up", "down"):
459
+ text = fill(f(s))
460
+ elif lang == "en":
461
+ text = fill(f("size"), s=r.choice(SIZE[s].en))
462
+ else:
463
+ text = fill(f("size"), s=es_form(r.choice(SIZE[s].es), g, pl))
464
+ return text, ["<set>", f"type={e['type']}", f"size={s}"]
465
+
466
+ if kind == "act":
467
+ a = r.choice(ACT_KEYS)
468
+ A = ACT[a]
469
+ if lang == "en":
470
+ text = fill(f("act"), base=r.choice(A.base), s3=r.choice(A.base if pl else A.s3), ing=r.choice(A.ing))
471
+ else:
472
+ text = fill(f("act"), subj=r.choice(A.subjp if pl else A.subj), e3=r.choice(A.e3p if pl else A.e3),
473
+ inf=r.choice(A.inf), ger=r.choice(A.ger))
474
+ return text, ["<set>", f"type={e['type']}", f"act={a}"]
475
+
476
+ if kind == "spd":
477
+ s = r.choices(["fast", "slow", "normal"], [4, 4, 1])[0]
478
+ return fill(f(s)), ["<set>", f"type={e['type']}", f"spd={s}"]
479
+
480
+ if kind == "add":
481
+ ne = rand_ent(r)
482
+ if lang == "en":
483
+ if "n" not in ne and r.random() < 0.08:
484
+ sing = r.choice(TYPES[ne["type"]].en)[0]
485
+ return f"add another {sing}", ["<add>", f"type={ne['type']}"]
486
+ np = np_en(r, ne, det=None if "n" in ne else "a")
487
+ else:
488
+ if "n" not in ne and r.random() < 0.08:
489
+ sing, _, g2 = r.choice(TYPES[ne["type"]].es)
490
+ return f"{r.choice(['añade', 'agrega', 'pon'])} {'otro' if g2 == 'm' else 'otra'} {sing}", \
491
+ ["<add>", f"type={ne['type']}"]
492
+ np = np_es(r, ne, det=None if "n" in ne else "a")[0]
493
+ return f("add").replace("{np}", np), ent_tokens(ne, "<add>")
494
+
495
+ if kind == "del":
496
+ who = r.choices(["ref", "it", "all"], [0.72, 0.08, 0.20])[0]
497
+ if who == "ref":
498
+ return fill(f("del")), ["<del>", f"type={e['type']}"]
499
+ return f(f"del_{who}"), ["<del>", f"type={who}"]
500
+
501
+ if kind == "loc":
502
+ k = r.choice(list(LOC))
503
+ p = r.choice(getattr(LOC[k], lang))
504
+ return fill(f("loc"), p=p, bare=bare(lang, p)).replace(" a el ", " al "), ["<env>", f"loc={k}"]
505
+
506
+ if kind == "time":
507
+ k = r.choice(list(TIME))
508
+ if r.random() < 0.2:
509
+ return r.choice(TIME_X[lang][k]), ["<env>", f"time={k}"]
510
+ p = r.choice(getattr(TIME[k], lang))
511
+ return fill(f("time"), p=p, w=r.choice(TIME_W[lang][k])).replace(" a el ", " al "), ["<env>", f"time={k}"]
512
+
513
+ if kind == "weather":
514
+ k = r.choice(list(WEATHER))
515
+ if r.random() < 0.2:
516
+ return r.choice(getattr(WEATHER[k], lang)), ["<env>", f"weather={k}"]
517
+ return r.choice(WEATHER_E[lang][k]), ["<env>", f"weather={k}"]
518
+
519
+ if kind == "shot":
520
+ k = r.choice(list(SHOT_E[lang]))
521
+ if k in SHOT and r.random() < 0.4:
522
+ return r.choice(getattr(SHOT[k], lang)), ["<cam>", f"shot={k}"]
523
+ return r.choice(SHOT_E[lang][k]), ["<cam>", f"shot={k}"]
524
+
525
+ k = r.choice(list(CAM))
526
+ if r.random() < 0.35:
527
+ return r.choice(getattr(CAM[k], lang)), ["<cam>", f"cam={k}"]
528
+ return fill(r.choice(CAM_E[lang][k])), ["<cam>", f"cam={k}"]
529
+
530
+
531
+ def edit(r, lang):
532
+ n = 1 if r.random() < 0.82 else 2
533
+ texts, tokens = [], ["<edit>"]
534
+ for _ in range(n):
535
+ t, k = edit_op(r, lang)
536
+ texts.append(t)
537
+ tokens += k
538
+ join = {"en": [" and ", ", ", " and then ", ". "], "es": [" y ", ", ", " y luego ", ". "]}[lang]
539
+ text = r.choice(join).join(texts)
540
+ if r.random() < 0.08:
541
+ text = {"en": ["please ", "now ", "ok ", "can you "], "es": ["por favor ", "ahora ", "ok ", "puedes "]}[lang][r.randrange(4)] + text
542
+ if r.random() < 0.06:
543
+ text += {"en": " please", "es": " por favor"}[lang]
544
+ return text, tokens
545
+
546
+
547
+ # ------------------------------------------------------------------ questions
548
+ def qa(r, lang):
549
+ key = r.choice(list(TOPICS))
550
+ en, es, qen, qes = TOPICS[key][:4]
551
+ terms = (en if lang == "en" else es).split("|")
552
+ extra = (qen if lang == "en" else qes).split("|")
553
+ if r.random() < 0.45:
554
+ text = r.choice(extra)
555
+ else:
556
+ text = r.choice(Q_EN if lang == "en" else Q_ES).replace("{t}", r.choice(terms))
557
+ if lang == "es":
558
+ text = text.replace(" de el ", " del ")
559
+ if "three" not in text and key not in ("help", "objects", "actions", "about"):
560
+ text += r.choice(SUF_EN if lang == "en" else SUF_ES)
561
+ if r.random() < 0.5:
562
+ text += "?"
563
+ return text, ["<qa>", f"lang={lang}", f"topic={key}"]
564
+
565
+
566
+ # ------------------------------------------------------------------ noise
567
+ def strip_accents(s):
568
+ return "".join(c for c in unicodedata.normalize("NFD", s.replace("ñ", "\0"))
569
+ if unicodedata.category(c) != "Mn").replace("\0", "ñ")
570
+
571
+
572
+ def typo(r, s):
573
+ idx = [i for i, c in enumerate(s) if c.isalpha()]
574
+ if len(idx) < 4:
575
+ return s
576
+ i = r.choice(idx)
577
+ k = r.random()
578
+ if k < 0.3 and i + 1 < len(s) and s[i + 1].isalpha():
579
+ return s[:i] + s[i + 1] + s[i] + s[i + 2:]
580
+ if k < 0.6:
581
+ return s[:i] + s[i + 1:]
582
+ if k < 0.8:
583
+ return s[:i] + s[i] + s[i:]
584
+ return s[:i] + r.choice("abcdefghijklmnopqrstuvwxyz") + s[i + 1:]
585
+
586
+
587
+ def noise(r, s, lang):
588
+ if lang == "es" and r.random() < 0.45:
589
+ s = strip_accents(s)
590
+ if r.random() < 0.22:
591
+ s = typo(r, s)
592
+ if r.random() < 0.3:
593
+ s = typo(r, s)
594
+ if r.random() < 0.05:
595
+ s = s.replace(",", "")
596
+ if r.random() < 0.06 and not s.endswith("?"):
597
+ s += "."
598
+ return s
599
+
600
+
601
+ def sample(r, clean=False):
602
+ while True:
603
+ lang = "en" if r.random() < 0.5 else "es"
604
+ kind = r.choices([new_scene, edit, qa], [0.55, 0.33, 0.12])[0]
605
+ text, tokens = kind(r, lang)
606
+ if not clean:
607
+ text = noise(r, text, lang)
608
+ if len(text) <= MAX_PROMPT:
609
+ return text, tokens
610
+
611
+
612
+ if __name__ == "__main__":
613
+ import sys
614
+ rr = random.Random(int(sys.argv[1]) if len(sys.argv) > 1 else 0)
615
+ for _ in range(int(sys.argv[2]) if len(sys.argv) > 2 else 40):
616
+ t, k = sample(rr)
617
+ print(f"{t}\n -> {' '.join(k)}")
ml/infer.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the trained model from the command line, or dump reference outputs for the JavaScript parity test.
2
+
3
+ python infer.py "a red fox jumping over a car in the desert"
4
+ python infer.py --parity ../tests/parity.json
5
+ """
6
+ import json
7
+ import random
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ import torch
12
+
13
+ import gen
14
+ import tok
15
+ from model import TinyGPT
16
+
17
+ HERE = Path(__file__).resolve().parent
18
+
19
+
20
+ def load(dev="cpu"):
21
+ cfg = json.loads((HERE.parent / "web" / "model" / "model.json").read_text())["config"]
22
+ m = TinyGPT(cfg["vocab"], cfg["ctx"], cfg["d"], cfg["layers"], cfg["heads"])
23
+ m.load_state_dict(torch.load(HERE / "model.pt", map_location=dev))
24
+ return m.to(dev).eval()
25
+
26
+
27
+ def run(model, text):
28
+ return [tok.VOCAB[i] for i in model.generate(tok.encode_prompt(text), tok.EOS)]
29
+
30
+
31
+ if __name__ == "__main__":
32
+ model = load()
33
+ if sys.argv[1] == "--parity":
34
+ r = random.Random(424242)
35
+ prompts = [gen.sample(r)[0] for _ in range(300)]
36
+ Path(sys.argv[2]).write_text(json.dumps([[p, run(model, p)] for p in prompts], ensure_ascii=False))
37
+ print("wrote", len(prompts))
38
+ else:
39
+ for p in sys.argv[1:]:
40
+ print(p, "\n ->", " ".join(run(model, p)))
ml/lexicon.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vocabulary of the scene language plus the English/Spanish words that name it.
2
+
3
+ Everything the model can say is listed here. The web builder must implement
4
+ every `type`, `act`, `loc`, ... key (tests/check_vocab.mjs verifies it).
5
+ """
6
+ from types import SimpleNamespace as NS
7
+
8
+
9
+ def _alts(s):
10
+ return [a.strip() for a in s.split("|")]
11
+
12
+
13
+ def _es4(s):
14
+ """'rojo/roja/rojos/rojas' or 'azul//azules/' -> (m, f, mp, fp)."""
15
+ p = (s.split("/") + ["", "", ""])[:4]
16
+ m, f, mp, fp = p
17
+ mp = mp or m + "s"
18
+ return (m, f or m, mp, fp or (f + "s" if f else mp))
19
+
20
+
21
+ # ---------------------------------------------------------------- colors
22
+ _COLORS = {
23
+ "red": ("red", "rojo/roja/rojos/rojas"),
24
+ "blue": ("blue", "azul//azules/"),
25
+ "green": ("green", "verde"),
26
+ "yellow": ("yellow", "amarillo/amarilla"),
27
+ "orange": ("orange", "naranja|anaranjado/anaranjada"),
28
+ "purple": ("purple|violet", "morado/morada|violeta|púrpura"),
29
+ "pink": ("pink", "rosa|rosado/rosada"),
30
+ "white": ("white", "blanco/blanca"),
31
+ "black": ("black", "negro/negra"),
32
+ "gray": ("gray|grey", "gris//grises/"),
33
+ "brown": ("brown", "marrón//marrones/|café//café/"),
34
+ "gold": ("gold|golden", "dorado/dorada"),
35
+ "silver": ("silver", "plateado/plateada"),
36
+ "cyan": ("cyan|turquoise", "cian//cian/|celeste|turquesa"),
37
+ }
38
+ COLOR = {k: NS(en=_alts(e), es=[_es4(x) for x in _alts(s)]) for k, (e, s) in _COLORS.items()}
39
+
40
+ _SIZES = {
41
+ "tiny": ("tiny|very small|miniature", "diminuto/diminuta|muy pequeño/muy pequeña|minúsculo/minúscula"),
42
+ "small": ("small|little", "pequeño/pequeña|chico/chica"),
43
+ "big": ("big|large", "grande"),
44
+ "giant": ("giant|huge|enormous|gigantic", "gigante|enorme|gigantesco/gigantesca"),
45
+ }
46
+ SIZE = {k: NS(en=_alts(e), es=[_es4(x) for x in _alts(s)]) for k, (e, s) in _SIZES.items()}
47
+
48
+ # ---------------------------------------------------------------- types
49
+ # en: 'singular/plural|...' es: 'singular/plural/gender|...'
50
+ _TYPES = {
51
+ "dog": ("dog/dogs|puppy/puppies", "perro/perros/m|perrito/perritos/m"),
52
+ "cat": ("cat/cats|kitten/kittens", "gato/gatos/m|gatito/gatitos/m"),
53
+ "horse": ("horse/horses", "caballo/caballos/m"),
54
+ "cow": ("cow/cows", "vaca/vacas/f"),
55
+ "pig": ("pig/pigs", "cerdo/cerdos/m|chancho/chanchos/m|puerco/puercos/m"),
56
+ "sheep": ("sheep/sheep", "oveja/ovejas/f"),
57
+ "fox": ("fox/foxes", "zorro/zorros/m"),
58
+ "bear": ("bear/bears", "oso/osos/m"),
59
+ "elephant": ("elephant/elephants", "elefante/elefantes/m"),
60
+ "giraffe": ("giraffe/giraffes", "jirafa/jirafas/f"),
61
+ "rabbit": ("rabbit/rabbits|bunny/bunnies", "conejo/conejos/m"),
62
+ "lion": ("lion/lions", "león/leones/m"),
63
+ "dragon": ("dragon/dragons", "dragón/dragones/m"),
64
+ "dinosaur": ("dinosaur/dinosaurs|dino/dinos", "dinosaurio/dinosaurios/m"),
65
+ "man": ("man/men|guy/guys", "hombre/hombres/m|señor/señores/m|chico/chicos/m"),
66
+ "woman": ("woman/women|lady/ladies|girl/girls", "mujer/mujeres/f|señora/señoras/f|chica/chicas/f"),
67
+ "robot": ("robot/robots", "robot/robots/m"),
68
+ "alien": ("alien/aliens", "alien/aliens/m|alienígena/alienígenas/m|extraterrestre/extraterrestres/m|marciano/marcianos/m"),
69
+ "astronaut": ("astronaut/astronauts", "astronauta/astronautas/m"),
70
+ "knight": ("knight/knights", "caballero/caballeros/m"),
71
+ "wizard": ("wizard/wizards|mage/mages", "mago/magos/m|hechicero/hechiceros/m"),
72
+ "bird": ("bird/birds", "pájaro/pájaros/m"),
73
+ "duck": ("duck/ducks", "pato/patos/m"),
74
+ "chicken": ("chicken/chickens|hen/hens", "gallina/gallinas/f|pollo/pollos/m"),
75
+ "fish": ("fish/fish", "pez/peces/m"),
76
+ "shark": ("shark/sharks", "tiburón/tiburones/m"),
77
+ "penguin": ("penguin/penguins", "pingüino/pingüinos/m"),
78
+ "snowman": ("snowman/snowmen", "muñeco de nieve/muñecos de nieve/m"),
79
+ "ghost": ("ghost/ghosts", "fantasma/fantasmas/m"),
80
+ "car": ("car/cars", "coche/coches/m|carro/carros/m|auto/autos/m"),
81
+ "truck": ("truck/trucks", "camión/camiones/m"),
82
+ "bus": ("bus/buses", "autobús/autobuses/m|bus/buses/m"),
83
+ "bike": ("bike/bikes|bicycle/bicycles", "bicicleta/bicicletas/f|bici/bicis/f"),
84
+ "skateboard": ("skateboard/skateboards", "patineta/patinetas/f|monopatín/monopatines/m|skate/skates/m"),
85
+ "boat": ("boat/boats|ship/ships", "barco/barcos/m|bote/botes/m"),
86
+ "plane": ("plane/planes|airplane/airplanes", "avión/aviones/m"),
87
+ "rocket": ("rocket/rockets", "cohete/cohetes/m"),
88
+ "train": ("train/trains", "tren/trenes/m"),
89
+ "ufo": ("ufo/ufos|flying saucer/flying saucers", "ovni/ovnis/m|platillo volador/platillos voladores/m"),
90
+ "helicopter": ("helicopter/helicopters", "helicóptero/helicópteros/m"),
91
+ "tree": ("tree/trees", "árbol/árboles/m"),
92
+ "house": ("house/houses", "casa/casas/f"),
93
+ "ball": ("ball/balls", "pelota/pelotas/f|balón/balones/m"),
94
+ "box": ("box/boxes|crate/crates", "caja/cajas/f"),
95
+ "chair": ("chair/chairs", "silla/sillas/f"),
96
+ "table": ("table/tables", "mesa/mesas/f"),
97
+ "rock": ("rock/rocks|stone/stones|boulder/boulders", "roca/rocas/f|piedra/piedras/f"),
98
+ "flower": ("flower/flowers", "flor/flores/f"),
99
+ "cactus": ("cactus/cactuses", "cactus/cactus/m"),
100
+ "mushroom": ("mushroom/mushrooms", "hongo/hongos/m|seta/setas/f"),
101
+ "tower": ("tower/towers", "torre/torres/f"),
102
+ "lamp": ("lamp/lamps|streetlight/streetlights", "lámpara/lámparas/f|farola/farolas/f"),
103
+ "bench": ("bench/benches", "banco/bancos/m|banca/bancas/f"),
104
+ "balloon": ("balloon/balloons", "globo/globos/m"),
105
+ }
106
+ TYPES = {
107
+ k: NS(en=[tuple(x.split("/")) for x in _alts(e)], es=[tuple(x.split("/")) for x in _alts(s)])
108
+ for k, (e, s) in _TYPES.items()
109
+ }
110
+
111
+ # ---------------------------------------------------------------- actions
112
+ # '{o}' is replaced by o/a/os/as to agree with the Spanish noun.
113
+ _A = lambda **k: NS(**{a: _alts(b) for a, b in k.items()})
114
+ ACT = {
115
+ "idle": _A(ing="standing|standing still|waiting", s3="stands|waits|stands still", base="stand still|wait|stop moving",
116
+ ger="esperando|sin moverse|quiet{o}|parad{o}", e3="espera|no se mueve", e3p="esperan|no se mueven",
117
+ inf="esperar|detenerse", subj="espere|se detenga|pare", subjp="esperen|se detengan"),
118
+ "walk": _A(ing="walking|strolling", s3="walks|strolls", base="walk|stroll",
119
+ ger="caminando|andando|paseando", e3="camina|anda|pasea", e3p="caminan|andan|pasean",
120
+ inf="caminar|andar|pasear", subj="camine|ande|pasee", subjp="caminen|anden"),
121
+ "run": _A(ing="running|sprinting", s3="runs|sprints", base="run|sprint",
122
+ ger="corriendo", e3="corre", e3p="corren", inf="correr", subj="corra", subjp="corran"),
123
+ "jump": _A(ing="jumping|hopping|leaping", s3="jumps|hops|leaps", base="jump|hop|leap",
124
+ ger="saltando|brincando", e3="salta|brinca", e3p="saltan|brincan",
125
+ inf="saltar|brincar", subj="salte|brinque", subjp="salten|brinquen"),
126
+ "spin": _A(ing="spinning|rotating|twirling", s3="spins|rotates|twirls", base="spin|rotate|twirl",
127
+ ger="girando|dando vueltas|rotando", e3="gira|da vueltas|rota", e3p="giran|dan vueltas",
128
+ inf="girar|dar vueltas|rotar", subj="gire|dé vueltas|rote", subjp="giren|den vueltas"),
129
+ "dance": _A(ing="dancing", s3="dances", base="dance",
130
+ ger="bailando", e3="baila", e3p="bailan", inf="bailar", subj="baile", subjp="bailen"),
131
+ "fly": _A(ing="flying|soaring", s3="flies|soars", base="fly|soar",
132
+ ger="volando", e3="vuela", e3p="vuelan", inf="volar", subj="vuele", subjp="vuelen"),
133
+ "float": _A(ing="floating|hovering|levitating", s3="floats|hovers|levitates", base="float|hover|levitate",
134
+ ger="flotando|levitando", e3="flota|levita", e3p="flotan|levitan",
135
+ inf="flotar|levitar", subj="flote|levite", subjp="floten|leviten"),
136
+ "sit": _A(ing="sitting|sitting down|seated", s3="sits|sits down", base="sit|sit down",
137
+ ger="sentad{o}", e3="se sienta|está sentad{o}", e3p="se sientan|están sentad{o}",
138
+ inf="sentarse", subj="se siente", subjp="se sienten"),
139
+ "sleep": _A(ing="sleeping|napping|asleep", s3="sleeps|naps", base="sleep|nap|go to sleep",
140
+ ger="durmiendo|dormid{o}", e3="duerme", e3p="duermen",
141
+ inf="dormir|dormirse", subj="duerma|se duerma", subjp="duerman"),
142
+ "wave": _A(ing="waving|waving hello|saying hi", s3="waves|waves hello|says hi", base="wave|wave hello|say hi",
143
+ ger="saludando|saludando con la mano", e3="saluda", e3p="saludan",
144
+ inf="saludar", subj="salude", subjp="saluden"),
145
+ "bounce": _A(ing="bouncing", s3="bounces", base="bounce",
146
+ ger="rebotando|botando", e3="rebota|bota", e3p="rebotan|botan",
147
+ inf="rebotar|botar", subj="rebote|bote", subjp="reboten"),
148
+ "roll": _A(ing="rolling", s3="rolls", base="roll",
149
+ ger="rodando", e3="rueda", e3p="ruedan", inf="rodar", subj="ruede", subjp="rueden"),
150
+ "circle": _A(ing="walking in circles|going in circles|moving in a circle|running in circles",
151
+ s3="walks in circles|goes in circles|moves in a circle", base="walk in circles|go in circles|move in a circle",
152
+ ger="caminando en círculos|andando en círculos|moviéndose en círculos|corriendo en círculos",
153
+ e3="camina en círculos|se mueve en círculos", e3p="caminan en círculos|se mueven en círculos",
154
+ inf="caminar en círculos|moverse en círculos", subj="camine en círculos|se mueva en círculos",
155
+ subjp="caminen en círculos|se muevan en círculos"),
156
+ "shake": _A(ing="shaking|trembling|shivering", s3="shakes|trembles|shivers", base="shake|tremble|shiver",
157
+ ger="temblando|sacudiéndose|vibrando", e3="tiembla|se sacude|vibra", e3p="tiemblan|se sacuden",
158
+ inf="temblar|sacudirse|vibrar", subj="tiemble|se sacuda|vibre", subjp="tiemblen|se sacudan"),
159
+ "swim": _A(ing="swimming", s3="swims", base="swim",
160
+ ger="nadando", e3="nada", e3p="nadan", inf="nadar", subj="nade", subjp="naden"),
161
+ "drive": _A(ing="driving|moving|moving forward|driving along", s3="drives|moves|moves forward", base="drive|move|move forward",
162
+ ger="conduciendo|avanzando|moviéndose|manejando", e3="avanza|se mueve|conduce", e3p="avanzan|se mueven",
163
+ inf="avanzar|moverse|conducir", subj="avance|se mueva|conduzca", subjp="avancen|se muevan"),
164
+ }
165
+ MOTION = ["walk", "run", "jump", "spin", "dance", "fly", "roll", "circle", "swim", "drive", "bounce"]
166
+ SPD = {
167
+ "slow": NS(en=["slowly", "very slowly", "slow"], es=["lentamente", "despacio", "lento", "muy despacio"]),
168
+ "fast": NS(en=["fast", "quickly", "very fast"], es=["rápido", "rápidamente", "muy rápido", "a toda velocidad"]),
169
+ }
170
+
171
+ # ---------------------------------------------------------------- relations
172
+ # preposition lists; verbs for ride/chase are handled in gen.py
173
+ REL = {
174
+ "on": NS(en=["on", "on top of"], es=["encima de", "arriba de", "sobre"]),
175
+ "over": NS(en=["over", "above"], es=["sobre", "por encima de"]),
176
+ "near": NS(en=["next to", "near", "beside", "close to", "by"], es=["al lado de", "junto a", "cerca de"]),
177
+ "behind": NS(en=["behind"], es=["detrás de", "atrás de"]),
178
+ "front": NS(en=["in front of"], es=["delante de", "frente a", "enfrente de"]),
179
+ "around": NS(en=["around"], es=["alrededor de"]),
180
+ "ride": NS(en=["riding", "riding on", "mounted on", "riding a top of"],
181
+ es=["montando", "montando a", "montando en", "montad{o} en", "cabalgando"]),
182
+ "chase": NS(en=["chasing", "running after", "following", "hunting"],
183
+ es=["persiguiendo a", "persiguiendo", "corriendo tras", "siguiendo a", "cazando a"]),
184
+ }
185
+ OVER_ACTS = ["jump", "fly", "float"]
186
+ AROUND_ACTS = ["walk", "run", "fly", "dance", "swim", "drive", "jump", "roll"]
187
+
188
+ # ---------------------------------------------------------------- scene modifiers
189
+ _P = lambda en, es: NS(en=_alts(en), es=_alts(es))
190
+ LOC = {
191
+ "field": _P("in a field|in a meadow|on the grass|in the countryside|on a grassy field",
192
+ "en el campo|en un prado|en la hierba|en el césped|en una pradera"),
193
+ "desert": _P("in the desert|in a desert|on the sand dunes", "en el desierto|en un desierto|en las dunas"),
194
+ "snow": _P("in the snow|in a snowy landscape|on a snowy field|in a winter landscape",
195
+ "en la nieve|en un paisaje nevado|en un campo nevado|en un paisaje de invierno"),
196
+ "beach": _P("on the beach|on a beach|at the beach|by the sea|on the shore",
197
+ "en la playa|en una playa|junto al mar|en la orilla"),
198
+ "forest": _P("in the forest|in a forest|in the woods|in the jungle", "en el bosque|en un bosque|en la selva"),
199
+ "city": _P("in the city|in a city|downtown|in a town|on a city street",
200
+ "en la ciudad|en una ciudad|en el centro|en un pueblo"),
201
+ "space": _P("in space|in outer space|among the stars|in the galaxy",
202
+ "en el espacio|en el espacio exterior|entre las estrellas|en la galaxia"),
203
+ "moon": _P("on the moon|on the lunar surface", "en la luna|en la superficie lunar"),
204
+ "ocean": _P("in the ocean|in the sea|at sea|on the water|in a lake",
205
+ "en el océano|en el mar|en el agua|en un lago|en altamar"),
206
+ "room": _P("in a room|in a house|inside a house|indoors|in the living room|in a bedroom",
207
+ "en una habitación|en un cuarto|en una casa|dentro de una casa|en la sala|en el salón"),
208
+ "mountain": _P("in the mountains|on a mountain|in a valley", "en las montañas|en la montaña|en un valle"),
209
+ "farm": _P("on a farm|at the farm|in a barnyard", "en una granja|en la granja|en un rancho"),
210
+ "road": _P("on a road|on the road|on a highway|on the street",
211
+ "en la carretera|en una carretera|en la calle|en una autopista|en el camino"),
212
+ "park": _P("in a park|in the park|in a garden|at the playground", "en un parque|en el parque|en un jardín"),
213
+ "studio": _P("in a studio|on a plain background|on an empty stage",
214
+ "en un estudio|con fondo liso|en un escenario vacío"),
215
+ }
216
+ TIME = {
217
+ "day": _P("during the day|in the daytime|at noon|on a sunny day", "de día|durante el día|al mediodía|en un día soleado"),
218
+ "night": _P("at night|at midnight|under the moonlight|in the dark",
219
+ "de noche|por la noche|a medianoche|bajo la luz de la luna"),
220
+ "sunset": _P("at sunset|at dusk|in the evening", "al atardecer|en el atardecer|al anochecer"),
221
+ "dawn": _P("at dawn|at sunrise|early in the morning", "al amanecer|en la madrugada|temprano en la mañana"),
222
+ }
223
+ WEATHER = {
224
+ "clear": _P("with clear skies|in good weather", "con cielo despejado|con buen tiempo"),
225
+ "rain": _P("in the rain|while it rains|on a rainy day|under the rain|raining",
226
+ "bajo la lluvia|mientras llueve|en un día lluvioso|lloviendo|con lluvia"),
227
+ "snow": _P("while it snows|snowing|in a snowfall|with falling snow",
228
+ "mientras nieva|nevando|con nieve cayendo|bajo una nevada"),
229
+ "fog": _P("in the fog|with fog|on a foggy day|in the mist",
230
+ "con niebla|en la niebla|en un día con niebla|entre la neblina"),
231
+ "storm": _P("during a storm|in a thunderstorm|with lightning|on a stormy day",
232
+ "durante una tormenta|en una tormenta|con rayos|con tormenta eléctrica"),
233
+ }
234
+ SHOT = {
235
+ "close": _P("close-up|close up shot|closeup|seen up close", "primer plano|de cerca|plano cerrado"),
236
+ "medium": _P("medium shot", "plano medio"),
237
+ "wide": _P("wide shot|wide angle|seen from far away|long shot", "plano general|plano abierto|desde lejos|gran angular"),
238
+ "top": _P("from above|aerial view|top view|bird's eye view|top-down view",
239
+ "desde arriba|vista aérea|vista cenital|desde el aire"),
240
+ "low": _P("low angle|from below|seen from the ground", "ángulo bajo|desde abajo|contrapicado"),
241
+ }
242
+ CAM = {
243
+ "static": _P("static camera|fixed camera|camera still", "cámara fija|cámara estática|cámara quieta"),
244
+ "orbit": _P("camera orbiting|orbit shot|camera circling around|rotating camera|360 view",
245
+ "cámara orbitando|la cámara gira alrededor|cámara giratoria|vista 360"),
246
+ "zoomin": _P("zooming in|camera zooms in|slow zoom in|camera moving closer",
247
+ "acercando la cámara|la cámara se acerca|zoom in lento|haciendo zoom"),
248
+ "zoomout": _P("zooming out|camera zooms out|camera pulling back|slow zoom out",
249
+ "alejando la cámara|la cámara se aleja|zoom out lento"),
250
+ "pan": _P("panning|camera panning|pan shot|camera moving sideways",
251
+ "paneo|cámara panorámica|la cámara se mueve de lado|paneando"),
252
+ "follow": _P("camera following|tracking shot|the camera follows|follow cam",
253
+ "la cámara sigue|cámara siguiendo|cámara de seguimiento|travelling"),
254
+ }
255
+
256
+ # ---------------------------------------------------------------- token inventory
257
+ CHARS = " abcdefghijklmnopqrstuvwxyz0123456789áéíóúñü,.'-?!"
258
+ SPECIAL = ["<pad>", "<bos>", "<sep>", "<eos>"]
259
+ STRUCT = ["<new>", "<edit>", "<qa>", "<ent>", "<set>", "<add>", "<del>", "<env>", "<cam>"]
260
+
261
+
262
+ def scene_tokens(topic_keys):
263
+ t = list(STRUCT)
264
+ t += [f"type={k}" for k in TYPES] + ["type=it", "type=all"]
265
+ t += [f"color={k}" for k in COLOR]
266
+ t += [f"size={k}" for k in SIZE] + ["size=up", "size=down"]
267
+ t += [f"n={i}" for i in range(2, 7)]
268
+ t += [f"act={k}" for k in ACT]
269
+ t += ["spd=slow", "spd=fast", "spd=normal"]
270
+ t += [f"rel={k}" for k in REL]
271
+ t += [f"loc={k}" for k in LOC]
272
+ t += [f"time={k}" for k in TIME]
273
+ t += [f"weather={k}" for k in WEATHER]
274
+ t += [f"shot={k}" for k in SHOT] + ["shot=in", "shot=out"]
275
+ t += [f"cam={k}" for k in CAM]
276
+ t += ["lang=en", "lang=es"]
277
+ t += [f"topic={k}" for k in topic_keys]
278
+ return t
ml/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdcfa61cc7d55d816951bb1febc6daeb574f2f04129ebda03666d6c3e665b653
3
+ size 19430427
ml/model.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small decoder-only Transformer (pre-LayerNorm GPT). web/js/nn/model.js mirrors this exactly."""
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+
7
+ class Block(nn.Module):
8
+ def __init__(self, d, heads):
9
+ super().__init__()
10
+ self.h = heads
11
+ self.ln1 = nn.LayerNorm(d)
12
+ self.qkv = nn.Linear(d, 3 * d)
13
+ self.proj = nn.Linear(d, d)
14
+ self.ln2 = nn.LayerNorm(d)
15
+ self.fc1 = nn.Linear(d, 4 * d)
16
+ self.fc2 = nn.Linear(4 * d, d)
17
+
18
+ def forward(self, x):
19
+ B, T, C = x.shape
20
+ q, k, v = self.qkv(self.ln1(x)).view(B, T, 3, self.h, C // self.h).permute(2, 0, 3, 1, 4)
21
+ a = F.scaled_dot_product_attention(q, k, v, is_causal=True)
22
+ x = x + self.proj(a.transpose(1, 2).reshape(B, T, C))
23
+ return x + self.fc2(F.gelu(self.fc1(self.ln2(x)), approximate="tanh"))
24
+
25
+
26
+ class TinyGPT(nn.Module):
27
+ def __init__(self, vocab, ctx, d=256, layers=6, heads=8):
28
+ super().__init__()
29
+ self.cfg = dict(vocab=vocab, ctx=ctx, d=d, layers=layers, heads=heads)
30
+ self.tok = nn.Embedding(vocab, d)
31
+ self.pos = nn.Embedding(ctx, d)
32
+ self.blocks = nn.ModuleList(Block(d, heads) for _ in range(layers))
33
+ self.ln_f = nn.LayerNorm(d)
34
+ self.apply(self._init)
35
+
36
+ @staticmethod
37
+ def _init(m):
38
+ if isinstance(m, (nn.Linear, nn.Embedding)):
39
+ nn.init.normal_(m.weight, std=0.02)
40
+ if getattr(m, "bias", None) is not None:
41
+ nn.init.zeros_(m.bias)
42
+
43
+ def forward(self, idx):
44
+ x = self.tok(idx) + self.pos(torch.arange(idx.shape[1], device=idx.device))
45
+ for b in self.blocks:
46
+ x = b(x)
47
+ return self.ln_f(x) @ self.tok.weight.T # tied output head
48
+
49
+ @torch.no_grad()
50
+ def generate(self, prompt_ids, eos, max_new=40):
51
+ idx = torch.tensor([prompt_ids], device=self.tok.weight.device)
52
+ out = []
53
+ for _ in range(max_new):
54
+ if idx.shape[1] >= self.cfg["ctx"]:
55
+ break
56
+ nxt = int(self(idx)[0, -1].argmax())
57
+ if nxt == eos:
58
+ break
59
+ out.append(nxt)
60
+ idx = torch.cat([idx, torch.tensor([[nxt]], device=idx.device)], 1)
61
+ return out
ml/qa_topics.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """three.js question topics. The model only predicts `lang` and `topic`; the app shows the stored answer."""
2
+
3
+ # key: (english terms, spanish terms, extra english questions, extra spanish questions, answer en, answer es)
4
+ TOPICS = {
5
+ "threejs": (
6
+ "three.js|threejs|three js|the three.js library",
7
+ "three.js|threejs|three js|la librería three.js",
8
+ "what is this library|what is webgl|why use three.js",
9
+ "qué es esta librería|qué es webgl|por qué usar three.js",
10
+ "three.js is a JavaScript library that draws 3D graphics in the browser on top of WebGL. You describe a scene with objects, lights and a camera, and a renderer draws it to a canvas every frame.",
11
+ "three.js es una librería de JavaScript que dibuja gráficos 3D en el navegador sobre WebGL. Describes una escena con objetos, luces y una cámara, y un renderer la dibuja en un canvas en cada fotograma.",
12
+ ),
13
+ "scene": (
14
+ "a scene|the scene|scenes|the scene graph",
15
+ "una escena|la escena|las escenas|el grafo de escena",
16
+ "how do i add objects to the scene|what is scene.add",
17
+ "cómo añado objetos a la escena|qué es scene.add",
18
+ "A THREE.Scene is the root container. Everything you want drawn (meshes, lights, groups) is added with scene.add(object), and removed with scene.remove(object).",
19
+ "THREE.Scene es el contenedor raíz. Todo lo que quieras dibujar (mallas, luces, grupos) se añade con scene.add(objeto) y se quita con scene.remove(objeto).",
20
+ ),
21
+ "camera": (
22
+ "a camera|the camera|cameras|a perspective camera|the field of view",
23
+ "una cámara|la cámara|las cámaras|una cámara en perspectiva|el campo de visión",
24
+ "how do i move the camera|what is fov|perspective or orthographic camera",
25
+ "cómo muevo la cámara|qué es el fov|cámara en perspectiva u ortográfica",
26
+ "The camera decides what is visible. PerspectiveCamera(fov, aspect, near, far) imitates a real lens; OrthographicCamera has no perspective. Move it with camera.position.set(x, y, z) and aim it with camera.lookAt(target).",
27
+ "La cámara decide qué se ve. PerspectiveCamera(fov, aspect, near, far) imita una lente real; OrthographicCamera no tiene perspectiva. Se mueve con camera.position.set(x, y, z) y se apunta con camera.lookAt(objetivo).",
28
+ ),
29
+ "renderer": (
30
+ "a renderer|the renderer|the webgl renderer|rendering",
31
+ "un renderer|el renderer|el renderizador|el renderizado",
32
+ "how do i render the scene|what is the render loop|what is setAnimationLoop",
33
+ "cómo renderizo la escena|qué es el bucle de render|qué es setAnimationLoop",
34
+ "WebGLRenderer draws a scene from a camera into a canvas: renderer.render(scene, camera). Call it every frame with renderer.setAnimationLoop(fn), and set the size with renderer.setSize(width, height).",
35
+ "WebGLRenderer dibuja una escena vista desde una cámara en un canvas: renderer.render(scene, camera). Se llama en cada fotograma con renderer.setAnimationLoop(fn), y el tamaño se fija con renderer.setSize(ancho, alto).",
36
+ ),
37
+ "mesh": (
38
+ "a mesh|the mesh|meshes|a 3d object",
39
+ "una malla|la malla|las mallas|un mesh|un objeto 3d",
40
+ "how do i create a cube|how do i make a sphere|how do i create an object",
41
+ "cómo creo un cubo|cómo hago una esfera|cómo creo un objeto",
42
+ "A Mesh is a visible object: geometry (the shape) plus material (the look). Example: new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 'red' })).",
43
+ "Un Mesh es un objeto visible: geometría (la forma) más material (el aspecto). Ejemplo: new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 'red' })).",
44
+ ),
45
+ "geometry": (
46
+ "a geometry|the geometry|geometries|buffer geometry|vertices",
47
+ "una geometría|la geometría|las geometrías|los vértices",
48
+ "which shapes are available|what primitives exist",
49
+ "qué formas hay disponibles|qué primitivas existen",
50
+ "A geometry holds the vertices of a shape. Built-in ones include BoxGeometry, SphereGeometry, CylinderGeometry, ConeGeometry, TorusGeometry and PlaneGeometry. Every object in this app is assembled from those primitives.",
51
+ "Una geometría guarda los vértices de una forma. Las incluidas son BoxGeometry, SphereGeometry, CylinderGeometry, ConeGeometry, TorusGeometry y PlaneGeometry, entre otras. Todos los objetos de esta app se arman con esas primitivas.",
52
+ ),
53
+ "material": (
54
+ "a material|the material|materials|mesh standard material",
55
+ "un material|el material|los materiales",
56
+ "how do i make something shiny|what is roughness|what is metalness|how do i make it transparent",
57
+ "cómo hago algo brillante|qué es roughness|qué es metalness|cómo lo hago transparente",
58
+ "A material defines how a surface looks. MeshBasicMaterial ignores light, MeshStandardMaterial reacts to it with roughness and metalness, and MeshToonMaterial gives a cartoon look. Set transparent: true and opacity for see-through surfaces.",
59
+ "Un material define cómo se ve una superficie. MeshBasicMaterial ignora la luz, MeshStandardMaterial reacciona a ella con roughness y metalness, y MeshToonMaterial da un aspecto de dibujo. Usa transparent: true y opacity para superficies translúcidas.",
60
+ ),
61
+ "light": (
62
+ "a light|the light|lights|lighting|a directional light|ambient light",
63
+ "una luz|la luz|las luces|la iluminación|una luz direccional|la luz ambiental",
64
+ "why is my scene black|why is everything dark|how do i light the scene",
65
+ "por qué mi escena está negra|por qué todo se ve oscuro|cómo ilumino la escena",
66
+ "Lights make standard materials visible. AmbientLight and HemisphereLight fill the whole scene, DirectionalLight acts like the sun, PointLight like a bulb and SpotLight like a torch. A black scene usually means there is no light.",
67
+ "Las luces hacen visibles los materiales estándar. AmbientLight y HemisphereLight rellenan toda la escena, DirectionalLight actúa como el sol, PointLight como una bombilla y SpotLight como una linterna. Una escena negra casi siempre significa que falta una luz.",
68
+ ),
69
+ "shadow": (
70
+ "a shadow|shadows|the shadow map|cast shadow",
71
+ "una sombra|las sombras|el mapa de sombras",
72
+ "why are there no shadows|how do i enable shadows",
73
+ "por qué no hay sombras|cómo activo las sombras",
74
+ "Shadows need three switches: renderer.shadowMap.enabled = true, light.castShadow = true, and on each mesh castShadow and/or receiveShadow = true. Tune light.shadow.mapSize and the shadow camera bounds for quality.",
75
+ "Las sombras necesitan tres interruptores: renderer.shadowMap.enabled = true, light.castShadow = true y, en cada malla, castShadow y/o receiveShadow = true. La calidad se ajusta con light.shadow.mapSize y los límites de la cámara de sombra.",
76
+ ),
77
+ "animation": (
78
+ "an animation|animation|animations|the animation loop|keyframes",
79
+ "una animación|la animación|las animaciones|el bucle de animación|los keyframes",
80
+ "how do i animate an object|how do i move an object|how do i rotate something over time",
81
+ "cómo animo un objeto|cómo muevo un objeto|cómo roto algo con el tiempo",
82
+ "The simplest animation changes position, rotation or scale every frame inside the render loop, using elapsed time. For keyframes use AnimationMixer with AnimationClip. This app animates everything procedurally from the time value.",
83
+ "La animación más simple cambia posición, rotación o escala en cada fotograma dentro del bucle de render, usando el tiempo transcurrido. Para keyframes se usa AnimationMixer con AnimationClip. Esta app anima todo de forma procedural a partir del tiempo.",
84
+ ),
85
+ "texture": (
86
+ "a texture|the texture|textures|an image on an object",
87
+ "una textura|la textura|las texturas|una imagen en un objeto",
88
+ "how do i load an image|how do i put a picture on a cube",
89
+ "cómo cargo una imagen|cómo pongo una foto en un cubo",
90
+ "A texture is an image mapped onto a surface. Load it with new THREE.TextureLoader().load(url) and assign it to material.map. CanvasTexture turns a 2D canvas drawing into a texture.",
91
+ "Una textura es una imagen aplicada a una superficie. Se carga con new THREE.TextureLoader().load(url) y se asigna a material.map. CanvasTexture convierte un dibujo de canvas 2D en textura.",
92
+ ),
93
+ "gltf": (
94
+ "gltf|a gltf file|glb|a 3d model|the gltf exporter",
95
+ "gltf|un archivo gltf|glb|un modelo 3d|el exportador gltf",
96
+ "how do i load a model|how do i export the scene|how do i import a model|can i open this in blender",
97
+ "cómo cargo un modelo|cómo exporto la escena|cómo importo un modelo|puedo abrir esto en blender",
98
+ "glTF (.gltf or .glb) is the standard 3D format for the web. Load models with GLTFLoader and save scenes with GLTFExporter. The export button here writes a .glb you can open in Blender.",
99
+ "glTF (.gltf o .glb) es el formato 3D estándar para la web. Los modelos se cargan con GLTFLoader y las escenas se guardan con GLTFExporter. El botón de exportar de esta app genera un .glb que puedes abrir en Blender.",
100
+ ),
101
+ "controls": (
102
+ "orbit controls|the controls|camera controls|mouse controls",
103
+ "orbit controls|los controles|los controles de cámara|los controles del ratón",
104
+ "how do i rotate the view with the mouse|how do i let the user move the camera",
105
+ "cómo giro la vista con el ratón|cómo dejo que el usuario mueva la cámara",
106
+ "OrbitControls lets the user orbit, zoom and pan with the mouse or touch: new OrbitControls(camera, renderer.domElement), then controls.update() every frame. Here you can drag the view at any time.",
107
+ "OrbitControls permite orbitar, hacer zoom y desplazar con el ratón o el dedo: new OrbitControls(camera, renderer.domElement) y luego controls.update() en cada fotograma. Aquí puedes arrastrar la vista en cualquier momento.",
108
+ ),
109
+ "raycaster": (
110
+ "a raycaster|the raycaster|raycasting|picking",
111
+ "un raycaster|el raycaster|raycasting",
112
+ "how do i click on an object|how do i detect clicks|how do i select an object with the mouse",
113
+ "cómo hago clic en un objeto|cómo detecto clics|cómo selecciono un objeto con el ratón",
114
+ "A Raycaster shoots a ray from the camera through the mouse position and returns the objects it hits: raycaster.setFromCamera(pointer, camera) followed by raycaster.intersectObjects(scene.children).",
115
+ "Un Raycaster lanza un rayo desde la cámara a través de la posición del ratón y devuelve los objetos que toca: raycaster.setFromCamera(pointer, camera) seguido de raycaster.intersectObjects(scene.children).",
116
+ ),
117
+ "fog": (
118
+ "scene fog|the fog object|fog in three.js|exponential fog",
119
+ "la niebla de la escena|el objeto fog|la niebla en three.js|la niebla exponencial",
120
+ "how does fog work|how do i fade distant objects",
121
+ "cómo funciona la niebla|cómo desvanezco los objetos lejanos",
122
+ "Fog fades distant objects into a colour: scene.fog = new THREE.Fog(color, near, far) or new THREE.FogExp2(color, density). Match the fog colour to the background so the horizon blends.",
123
+ "La niebla desvanece los objetos lejanos hacia un color: scene.fog = new THREE.Fog(color, near, far) o new THREE.FogExp2(color, densidad). Usa el mismo color que el fondo para que el horizonte se funda.",
124
+ ),
125
+ "performance": (
126
+ "performance|the frame rate|fps|optimization|draw calls",
127
+ "el rendimiento|los fps|la optimización|las draw calls",
128
+ "why is it slow|how do i make it faster|how do i optimize my scene",
129
+ "por qué va lento|cómo lo hago más rápido|cómo optimizo mi escena",
130
+ "To keep the frame rate high: reuse geometries and materials, merge static meshes or use InstancedMesh, limit shadow-casting lights, cap the pixel ratio at 2, and dispose of what you remove.",
131
+ "Para mantener los fps altos: reutiliza geometrías y materiales, fusiona mallas estáticas o usa InstancedMesh, limita las luces con sombra, limita el pixel ratio a 2 y libera con dispose lo que quites.",
132
+ ),
133
+ "group": (
134
+ "a group|groups|the hierarchy|parent and child objects|object3d",
135
+ "un grupo|los grupos|la jerarquía|objetos padre e hijo|object3d",
136
+ "how do i attach an object to another|how do i move several objects together",
137
+ "cómo uno un objeto a otro|cómo muevo varios objetos juntos",
138
+ "A Group (or any Object3D) can hold children with parent.add(child). Children inherit the parent's position, rotation and scale, which is how a leg swings from a hip or a rider follows a horse.",
139
+ "Un Group (o cualquier Object3D) puede tener hijos con padre.add(hijo). Los hijos heredan posición, rotación y escala del padre; así una pata gira desde la cadera o un jinete sigue a su caballo.",
140
+ ),
141
+ "color": (
142
+ "colors in three.js|the color class|three color|hex colors",
143
+ "los colores en three.js|la clase color|three color|los colores hexadecimales",
144
+ "how do i change the color of a material|how do i set a color in code",
145
+ "cómo cambio el color de un material|cómo pongo un color en código",
146
+ "THREE.Color accepts hex numbers (0xff0000), CSS strings ('red', '#ff0000') or HSL via setHSL. Change a material at any time with material.color.set('blue').",
147
+ "THREE.Color acepta números hexadecimales (0xff0000), cadenas CSS ('red', '#ff0000') o HSL con setHSL. Cambia un material en cualquier momento con material.color.set('blue').",
148
+ ),
149
+ "resize": (
150
+ "window resize|resizing|the aspect ratio|a responsive canvas",
151
+ "el cambio de tamaño de ventana|la relación de aspecto|un canvas adaptable",
152
+ "why is my scene stretched|how do i handle window resize|how do i make it fullscreen",
153
+ "por qué mi escena se ve estirada|cómo manejo el cambio de tamaño|cómo lo pongo en pantalla completa",
154
+ "On resize, update three things: camera.aspect = width / height, camera.updateProjectionMatrix(), and renderer.setSize(width, height). A stretched image means the aspect was not updated.",
155
+ "Al cambiar el tamaño hay que actualizar tres cosas: camera.aspect = ancho / alto, camera.updateProjectionMatrix() y renderer.setSize(ancho, alto). Una imagen estirada indica que no se actualizó el aspecto.",
156
+ ),
157
+ "particles": (
158
+ "particles|a particle system|points|the points material",
159
+ "las partículas|un sistema de partículas|points|el material de puntos",
160
+ "how do i make rain|how do i make snow in code|how do i create stars",
161
+ "cómo hago lluvia en código|cómo hago nieve en código|cómo creo estrellas",
162
+ "Particles are a THREE.Points object: one BufferGeometry with many positions and a PointsMaterial. Move the positions every frame and set needsUpdate. The rain, snow and stars here are built that way.",
163
+ "Las partículas son un objeto THREE.Points: una BufferGeometry con muchas posiciones y un PointsMaterial. Se mueven las posiciones en cada fotograma y se marca needsUpdate. La lluvia, la nieve y las estrellas de esta app están hechas así.",
164
+ ),
165
+ "help": (
166
+ "this app|this tool|the commands",
167
+ "esta app|esta herramienta|los comandos",
168
+ "help|what can you do|how do i use this|what can i ask|how does this work|what can i type|give me examples",
169
+ "ayuda|qué puedes hacer|cómo uso esto|qué puedo pedir|cómo funciona esto|qué puedo escribir|dame ejemplos",
170
+ "Describe a scene and I build it: \"a red fox jumping over a car in the desert at sunset\". Then edit it: \"make the fox blue\", \"add a tree\", \"remove the car\", \"make it rain\", \"zoom out\". You can also ask about three.js.",
171
+ "Describe una escena y la construyo: \"un zorro rojo saltando sobre un coche en el desierto al atardecer\". Luego edítala: \"haz el zorro azul\", \"añade un árbol\", \"quita el coche\", \"que llueva\", \"aleja la cámara\". También puedes preguntar sobre three.js.",
172
+ ),
173
+ "objects": (
174
+ "the available objects|the object list|the characters|the animals",
175
+ "los objetos disponibles|la lista de objetos|los personajes|los animales",
176
+ "what objects do you know|which objects can i use|what can you draw|list the objects|what animals are there",
177
+ "qué objetos conoces|qué objetos puedo usar|qué puedes dibujar|lista los objetos|qué animales hay",
178
+ "@objects",
179
+ "@objects",
180
+ ),
181
+ "actions": (
182
+ "the available actions|the action list|the movements",
183
+ "las acciones disponibles|la lista de acciones|los movimientos",
184
+ "what actions do you know|which actions can i use|what can the characters do|list the actions",
185
+ "qué acciones conoces|qué acciones puedo usar|qué pueden hacer los personajes|lista las acciones",
186
+ "@actions",
187
+ "@actions",
188
+ ),
189
+ "about": (
190
+ "this model|the model|the neural network|the ai",
191
+ "este modelo|el modelo|la red neuronal|la ia",
192
+ "who are you|what are you|how do you work|are you an ai|how big is the model|how were you trained",
193
+ "quién eres|qué eres|cómo funcionas|eres una ia|qué tan grande es el modelo|cómo te entrenaron",
194
+ "I am a tiny Transformer trained from scratch on synthetic prompts. I do not generate geometry: I translate your sentence into a compact scene language, and procedural three.js code builds and animates the result. I run entirely in your browser.",
195
+ "Soy un Transformer diminuto entrenado desde cero con frases sintéticas. No genero geometría: traduzco tu frase a un lenguaje de escena compacto, y código procedural de three.js construye y anima el resultado. Funciono por completo en tu navegador.",
196
+ ),
197
+ }
198
+
199
+ Q_EN = [
200
+ "what is {t}", "what's {t}", "what are {t}", "how do i use {t}", "how do i create {t}", "how do i add {t}",
201
+ "explain {t}", "tell me about {t}", "how does {t} work", "help with {t}", "what does {t} do",
202
+ "how to set up {t}", "how can i use {t}", "can you explain {t}", "{t}", "i have a question about {t}",
203
+ ]
204
+ Q_ES = [
205
+ "qué es {t}", "qué son {t}", "cómo uso {t}", "cómo creo {t}", "cómo añado {t}", "explica {t}",
206
+ "explícame {t}", "háblame de {t}", "cómo funciona {t}", "ayuda con {t}", "para qué sirve {t}",
207
+ "cómo se usa {t}", "cómo configuro {t}", "puedes explicar {t}", "{t}", "tengo una pregunta sobre {t}",
208
+ ]
209
+ SUF_EN = ["", "", "", " in three.js", " in threejs", " with three.js"]
210
+ SUF_ES = ["", "", "", " en three.js", " en threejs", " con three.js"]
ml/tok.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tokenizer: prompt is split into characters, the answer into scene-language tokens."""
2
+ import re
3
+
4
+ from lexicon import CHARS, SPECIAL, scene_tokens
5
+ from qa_topics import TOPICS
6
+
7
+ MAX_PROMPT = 160
8
+ CTX = 208
9
+
10
+ VOCAB = SPECIAL + list(CHARS) + scene_tokens(list(TOPICS))
11
+ ID = {t: i for i, t in enumerate(VOCAB)}
12
+ PAD, BOS, SEP, EOS = 0, 1, 2, 3
13
+ _OK = set(CHARS)
14
+
15
+
16
+ def normalize(text):
17
+ text = "".join(c for c in text.lower().replace("’", "'") if c in _OK)
18
+ return re.sub(r"\s+", " ", text).strip()[:MAX_PROMPT]
19
+
20
+
21
+ def encode_prompt(text):
22
+ return [BOS] + [ID[c] for c in normalize(text)] + [SEP]
23
+
24
+
25
+ def encode_pair(text, tokens):
26
+ p = encode_prompt(text)
27
+ return p, [ID[t] for t in tokens] + [EOS]
ml/train.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train the model on an endless stream of generated pairs, then export it for the browser.
2
+
3
+ python train.py --steps 12000
4
+ """
5
+ import argparse
6
+ import json
7
+ import random
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+ import gen
16
+ import tok
17
+ from lexicon import ACT, TYPES
18
+ from model import TinyGPT
19
+ from qa_topics import TOPICS
20
+
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+ OUT = ROOT / "web" / "model"
23
+
24
+
25
+ def batch(r, n, dev):
26
+ xs, ys = [], []
27
+ for _ in range(n):
28
+ text, tokens = gen.sample(r)
29
+ p, t = tok.encode_pair(text, tokens)
30
+ seq = p + t
31
+ xs.append(seq[:-1])
32
+ ys.append([-100] * (len(p) - 1) + t)
33
+ T = max(map(len, xs))
34
+ x = torch.zeros(n, T, dtype=torch.long)
35
+ y = torch.full((n, T), -100, dtype=torch.long)
36
+ for i, (a, b) in enumerate(zip(xs, ys)):
37
+ x[i, :len(a)] = torch.tensor(a)
38
+ y[i, :len(b)] = torch.tensor(b)
39
+ return x.to(dev), y.to(dev)
40
+
41
+
42
+ @torch.no_grad()
43
+ def exact_match(model, pairs):
44
+ """Greedy-decode every pair in one padded batch; a pair counts only if every token matches."""
45
+ model.eval()
46
+ dev = model.tok.weight.device
47
+ enc = [tok.encode_pair(t, k) for t, k in pairs]
48
+ order = sorted(range(len(enc)), key=lambda i: len(enc[i][0]))
49
+ ok = 0
50
+ for s in range(0, len(order), 256):
51
+ ids = order[s:s + 256]
52
+ seqs = [list(enc[i][0]) for i in ids]
53
+ done = [False] * len(ids)
54
+ outs = [[] for _ in ids]
55
+ for _ in range(40):
56
+ T = max(map(len, seqs))
57
+ x = torch.zeros(len(ids), T, dtype=torch.long, device=dev)
58
+ for j, q in enumerate(seqs):
59
+ x[j, :len(q)] = torch.tensor(q)
60
+ logits = model(x)
61
+ for j, q in enumerate(seqs):
62
+ if done[j]:
63
+ continue
64
+ n = int(logits[j, len(q) - 1].argmax())
65
+ if n == tok.EOS or len(q) >= tok.CTX - 1:
66
+ done[j] = True
67
+ else:
68
+ q.append(n)
69
+ outs[j].append(n)
70
+ if all(done):
71
+ break
72
+ ok += sum(outs[j] + [tok.EOS] == enc[i][1] for j, i in enumerate(ids))
73
+ model.train()
74
+ return ok / len(pairs)
75
+
76
+
77
+ def export(model, meta):
78
+ OUT.mkdir(parents=True, exist_ok=True)
79
+ tensors, blob, off = [], [], 0
80
+ for name, p in model.state_dict().items():
81
+ a = p.detach().float().cpu().numpy().astype(np.float16)
82
+ tensors.append({"name": name, "shape": list(a.shape), "offset": off})
83
+ blob.append(a.tobytes())
84
+ off += a.size
85
+ (OUT / "weights.bin").write_bytes(b"".join(blob))
86
+ (OUT / "model.json").write_text(json.dumps({
87
+ "config": model.cfg, "dtype": "float16", "vocab": tok.VOCAB, "max_prompt": tok.MAX_PROMPT,
88
+ "special": {"pad": tok.PAD, "bos": tok.BOS, "sep": tok.SEP, "eos": tok.EOS},
89
+ "tensors": tensors, "meta": meta}, ensure_ascii=False))
90
+ names = lambda table, lang: ", ".join((v.en[0][0] if lang == "en" else v.es[0][0]) for v in table.values())
91
+ acts = lambda lang: ", ".join((v.ing[0] if lang == "en" else v.ger[0].replace("{o}", "o")) for v in ACT.values())
92
+ fill = lambda s, lang: {"@objects": ("I know: " if lang == "en" else "Conozco: ") + names(TYPES, lang) + ".",
93
+ "@actions": ("Actions: " if lang == "en" else "Acciones: ") + acts(lang) + "."}.get(s, s)
94
+ (OUT / "qa.json").write_text(json.dumps(
95
+ {k: {"en": fill(v[4], "en"), "es": fill(v[5], "es")} for k, v in TOPICS.items()}, ensure_ascii=False, indent=1))
96
+
97
+
98
+ def main():
99
+ ap = argparse.ArgumentParser()
100
+ ap.add_argument("--steps", type=int, default=12000)
101
+ ap.add_argument("--bs", type=int, default=256)
102
+ ap.add_argument("--lr", type=float, default=1e-3)
103
+ ap.add_argument("--d", type=int, default=256)
104
+ ap.add_argument("--layers", type=int, default=6)
105
+ ap.add_argument("--heads", type=int, default=8)
106
+ a = ap.parse_args()
107
+
108
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
109
+ torch.manual_seed(0)
110
+ model = TinyGPT(len(tok.VOCAB), tok.CTX, a.d, a.layers, a.heads).to(dev)
111
+ n_params = sum(p.numel() for p in model.parameters())
112
+ print(f"device {dev} | vocab {len(tok.VOCAB)} | params {n_params:,}", flush=True)
113
+ opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=0.01, betas=(0.9, 0.98))
114
+ sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05)
115
+
116
+ er = random.Random(10_000_019)
117
+ held_noisy = [gen.sample(er) for _ in range(3000)]
118
+ held_clean = [gen.sample(er, clean=True) for _ in range(3000)]
119
+ (ROOT / "ml" / "heldout.jsonl").write_text(
120
+ "\n".join(json.dumps({"prompt": t, "target": " ".join(k)}, ensure_ascii=False) for t, k in held_clean))
121
+
122
+ r = random.Random(0)
123
+ t0 = time.time()
124
+ for step in range(1, a.steps + 1):
125
+ x, y = batch(r, a.bs, dev)
126
+ with torch.autocast(dev, dtype=torch.bfloat16, enabled=dev == "cuda"):
127
+ loss = F.cross_entropy(model(x).float().view(-1, len(tok.VOCAB)), y.view(-1), ignore_index=-100)
128
+ opt.zero_grad(set_to_none=True)
129
+ loss.backward()
130
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
131
+ opt.step()
132
+ sched.step()
133
+ if step % 250 == 0:
134
+ print(f"step {step:6d} loss {loss.item():.4f} {time.time() - t0:.0f}s", flush=True)
135
+ if step % 3000 == 0 or step == a.steps:
136
+ c, n = exact_match(model, held_clean[:1000]), exact_match(model, held_noisy[:1000])
137
+ print(f" exact match: clean {c:.3f} noisy {n:.3f}", flush=True)
138
+
139
+ clean, noisy = exact_match(model, held_clean), exact_match(model, held_noisy)
140
+ meta = {"params": n_params, "steps": a.steps, "batch": a.bs, "pairs_seen": a.steps * a.bs,
141
+ "heldout_exact_clean": round(clean, 4), "heldout_exact_noisy": round(noisy, 4),
142
+ "train_seconds": round(time.time() - t0)}
143
+ print("final", meta, flush=True)
144
+ torch.save(model.state_dict(), ROOT / "ml" / "model.pt")
145
+ export(model, meta)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
package-lock.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "tiny-scene-three",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "tiny-scene-three",
9
+ "version": "1.0.0",
10
+ "license": "ISC",
11
+ "dependencies": {
12
+ "three": "^0.170.0"
13
+ },
14
+ "devDependencies": {
15
+ "playwright-core": "^1.65.1"
16
+ }
17
+ },
18
+ "node_modules/playwright-core": {
19
+ "version": "1.65.1",
20
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
21
+ "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
22
+ "dev": true,
23
+ "license": "Apache-2.0",
24
+ "bin": {
25
+ "playwright-core": "cli.js"
26
+ },
27
+ "engines": {
28
+ "node": ">=20"
29
+ }
30
+ },
31
+ "node_modules/three": {
32
+ "version": "0.170.0",
33
+ "resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",
34
+ "integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ==",
35
+ "license": "MIT"
36
+ }
37
+ }
38
+ }
package.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "tiny-scene-three",
3
+ "version": "1.0.0",
4
+ "description": "Text to animated three.js scenes with a tiny Transformer trained from scratch",
5
+ "type": "module",
6
+ "scripts": {
7
+ "start": "python3 -m http.server 8080 --directory web",
8
+ "test": "node tests/check_scene.mjs && node tests/check_model.mjs",
9
+ "train": "cd ml && ../.venv/bin/python train.py"
10
+ },
11
+ "keywords": [],
12
+ "license": "MIT",
13
+ "dependencies": {
14
+ "three": "^0.170.0"
15
+ },
16
+ "devDependencies": {
17
+ "playwright-core": "^1.65.1"
18
+ },
19
+ "private": true
20
+ }
tests/check_export.mjs ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Checks the .glb export in a real browser: node tests/check_export.mjs
2
+ import fs from 'node:fs';
3
+ import http from 'node:http';
4
+ import path from 'node:path';
5
+ import { chromium } from 'playwright-core';
6
+
7
+ const WEB = new URL('../web/', import.meta.url).pathname;
8
+ const server = http.createServer((req, res) => {
9
+ const f = path.join(WEB, decodeURIComponent(req.url.split('?')[0]).replace(/\/$/, '/index.html'));
10
+ if (!fs.existsSync(f)) { res.writeHead(404); return res.end(); }
11
+ res.writeHead(200, { 'content-type': { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json' }[path.extname(f)] ?? 'application/octet-stream' });
12
+ fs.createReadStream(f).pipe(res);
13
+ }).listen(0);
14
+ const root = `${process.env.HOME}/.cache/ms-playwright`;
15
+ const exe = process.env.CHROME ?? fs.readdirSync(root).filter((d) => d.startsWith('chromium_headless_shell')).flatMap((d) => fs.readdirSync(`${root}/${d}`).map((s) => `${root}/${d}/${s}/chrome-headless-shell`)).find((p) => fs.existsSync(p));
16
+ const browser = await chromium.launch({ executablePath: exe, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'] });
17
+ const page = await browser.newPage();
18
+ await page.goto(`http://localhost:${server.address().port}/?q=${encodeURIComponent('a knight riding a dragon next to a tower')}`);
19
+ await page.waitForFunction(() => window.tinyScene?.ready, null, { timeout: 60000 });
20
+ const r = await page.evaluate(async () => {
21
+ const blob = await window.tinyScene.stage.exportGLB(), head = new Uint8Array(await blob.slice(0, 4).arrayBuffer());
22
+ return { bytes: blob.size, magic: String.fromCharCode(...head) };
23
+ });
24
+ console.log('glb export:', r, r.magic === 'glTF' && r.bytes > 10000 ? 'ok' : 'FAILED');
25
+ await browser.close();
26
+ server.close();
27
+ process.exit(r.magic === 'glTF' ? 0 : 1);
tests/check_model.mjs ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // 1) JavaScript inference must reproduce PyTorch token for token (tests/parity.json, from ml/infer.py --parity).
2
+ // 2) Hand-written prompts that are NOT produced by the training templates (tests/natural.json).
3
+ // node tests/check_model.mjs
4
+ import fs from 'node:fs';
5
+ import { TinyGPT } from '../web/js/nn/model.js';
6
+
7
+ const rd = (p) => fs.readFileSync(new URL(p, import.meta.url));
8
+ const buf = rd('../web/model/weights.bin');
9
+ const model = new TinyGPT(JSON.parse(rd('../web/model/model.json')), buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
10
+ console.log('model', model.meta.meta);
11
+
12
+ let fail = 0;
13
+ if (fs.existsSync(new URL('./parity.json', import.meta.url))) {
14
+ const ref = JSON.parse(rd('./parity.json'));
15
+ let same = 0, ms = 0;
16
+ for (const [prompt, want] of ref) {
17
+ const got = model.generate(prompt);
18
+ ms += got.ms;
19
+ if (got.tokens.join(' ') === want.join(' ')) same++;
20
+ else if (fail++ < 5) console.log('PARITY', JSON.stringify(prompt), '\n js:', got.tokens.join(' '), '\n py:', want.join(' '));
21
+ }
22
+ console.log(`parity with PyTorch: ${same}/${ref.length} identical, ${(ms / ref.length).toFixed(0)} ms per prompt`);
23
+ }
24
+
25
+ const nat = JSON.parse(rd('./natural.json'));
26
+ let ok = 0, total = 0;
27
+ for (const [prompt, want] of nat) {
28
+ const got = model.generate(prompt).tokens.join(' ');
29
+ if (want == null) { console.log(` (out of vocabulary) ${prompt}\n -> ${got}`); continue; }
30
+ total++;
31
+ if (got === want) ok++;
32
+ else console.log(` MISS ${prompt}\n got ${got}\n want ${want}`);
33
+ }
34
+ console.log(`hand-written prompts: ${ok}/${total} exact`);
35
+ process.exit(fail ? 1 : 0);
tests/check_scene.mjs ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Builds every object, action, place, time and weather the model can name and checks nothing breaks.
2
+ // node tests/check_scene.mjs
3
+ import fs from 'node:fs';
4
+ import * as THREE from 'three';
5
+ import { applyEdit, emptyScene, parse } from '../web/js/lang/scenelang.js';
6
+ import { BUILDERS, buildScene } from '../web/js/scene/layout.js';
7
+
8
+ const meta = JSON.parse(fs.readFileSync(new URL('../web/model/model.json', import.meta.url)));
9
+ const vals = (k) => meta.vocab.filter((t) => t.startsWith(k + '=')).map((t) => t.split('=')[1]);
10
+ const types = vals('type').filter((t) => t !== 'it' && t !== 'all'), acts = vals('act');
11
+ let fail = 0;
12
+ const bad = (msg) => { fail++; console.log('FAIL', msg); };
13
+
14
+ const missing = types.filter((t) => !BUILDERS[t]);
15
+ if (missing.length) bad('no builder for: ' + missing.join(', '));
16
+
17
+ function finite(root) {
18
+ let ok = true;
19
+ root.updateMatrixWorld(true);
20
+ root.traverse((o) => { for (const v of o.matrixWorld.elements) if (!Number.isFinite(v)) ok = false; });
21
+ return ok;
22
+ }
23
+ function run(sc, label) {
24
+ try {
25
+ const b = buildScene(sc);
26
+ for (const t of [0, 0.37, 1.9, 7.3, 31.4]) { b.update(t); if (!finite(b.root)) return bad(label + ' non-finite at t=' + t); }
27
+ if (!Number.isFinite(b.stageR) || b.box.isEmpty()) bad(label + ' bad bounds');
28
+ b.dispose();
29
+ } catch (e) { bad(label + ' threw ' + e.stack.split('\n').slice(0, 3).join(' | ')); }
30
+ }
31
+ const scene = (ents, extra = {}) => ({ ...emptyScene(), ...extra, ents: ents.map((e, i) => ({ id: 'e' + (i + 1), ...e })) });
32
+
33
+ let n = 0;
34
+ for (const type of types) for (const act of [undefined, ...acts]) { run(scene([{ type, act }]), `${type}/${act}`); n++; }
35
+ for (const loc of vals('loc')) for (const time of vals('time')) for (const weather of vals('weather')) {
36
+ run(scene([{ type: 'dog', act: 'walk' }, { type: 'boat' }], { loc, time, weather }), `${loc}/${time}/${weather}`); n++;
37
+ }
38
+ for (const rel of vals('rel')) for (const a of ['alien', 'fox', 'bird', 'ball', 'car']) for (const b of ['horse', 'skateboard', 'tree', 'ufo', 'chair']) {
39
+ run(scene([{ type: a, rel, ref: 'e2', act: rel === 'over' ? 'jump' : 'dance', n: 2 }, { type: b }]), `${a} ${rel} ${b}`); n++;
40
+ }
41
+ for (const size of vals('size')) run(scene([{ type: 'cow', size, n: 5, color: 'gold' }]), 'size ' + size), n++;
42
+
43
+ // scene language round trip
44
+ const p = parse('<new> loc=beach time=sunset <ent> type=fox color=red act=jump rel=over <ent> type=car color=blue'.split(' '));
45
+ if (p.kind !== 'new' || p.scene.ents.length !== 2 || p.scene.ents[0].ref !== 'e2') bad('parse new');
46
+ const e = parse('<edit> <set> type=fox color=green <add> type=tree n=2 <del> type=car <cam> shot=out <env> weather=rain'.split(' '));
47
+ const r = applyEdit(p.scene, e.ops);
48
+ if (r.scene.ents.length !== 2 || r.scene.ents[0].color !== 'green' || r.scene.ents[0].rel || r.scene.zoom !== 1 || r.scene.weather !== 'rain') bad('apply edit ' + JSON.stringify(r.scene));
49
+ if (applyEdit(p.scene, parse('<edit> <set> type=cow color=red'.split(' ')).ops).notes[0]?.code !== 'missing') bad('missing note');
50
+ run(r.scene, 'edited scene');
51
+
52
+ console.log(`${n} scenes built, ${types.length} types, ${acts.length} actions, three r${THREE.REVISION}: ${fail ? fail + ' FAILED' : 'all ok'}`);
53
+ process.exit(fail ? 1 : 0);
tests/natural.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ ["a red dog walking in a blue house", "<new> loc=room <ent> type=dog color=red act=walk"],
3
+ ["A robot dancing on a skateboard", "<new> <ent> type=robot act=dance rel=on <ent> type=skateboard"],
4
+ ["A fox jumping over a car", "<new> <ent> type=fox act=jump rel=over <ent> type=car"],
5
+ ["An alien riding a horse", "<new> <ent> type=alien rel=ride <ent> type=horse"],
6
+ ["un zorro rojo saltando sobre un coche azul en el desierto al atardecer", "<new> loc=desert time=sunset <ent> type=fox color=red act=jump rel=over <ent> type=car color=blue"],
7
+ ["tres pingüinos caminando en la nieve mientras nieva", "<new> loc=snow weather=snow <ent> type=penguin n=3 act=walk"],
8
+ ["un dragón volando sobre una torre con tormenta", "<new> weather=storm <ent> type=dragon act=fly rel=over <ent> type=tower"],
9
+ ["a robot dancing on a skateboard in the city at night", "<new> loc=city time=night <ent> type=robot act=dance rel=on <ent> type=skateboard"],
10
+ ["an alien riding a horse on the moon", "<new> loc=moon <ent> type=alien rel=ride <ent> type=horse"],
11
+ ["two cows sleeping on a farm at dawn", "<new> loc=farm time=dawn <ent> type=cow n=2 act=sleep"],
12
+ ["Quiero un astronauta flotando en el espacio", "<new> loc=space <ent> type=astronaut act=float"],
13
+ ["una jirafa gigante y un conejo diminuto en el parque", "<new> loc=park <ent> type=giraffe size=giant <ent> type=rabbit size=tiny"],
14
+ ["a dog chasing a cat in the park", "<new> loc=park <ent> type=dog rel=chase <ent> type=cat"],
15
+ ["un perro persiguiendo a un gato en la playa", "<new> loc=beach <ent> type=dog rel=chase <ent> type=cat"],
16
+ ["a knight next to a tower at sunset, camera orbiting", "<new> time=sunset cam=orbit <ent> type=knight rel=near <ent> type=tower"],
17
+ ["shark swimming in the ocean", "<new> loc=ocean <ent> type=shark act=swim"],
18
+ ["a yellow bus driving fast on the road", "<new> loc=road <ent> type=bus color=yellow act=drive spd=fast"],
19
+ ["un mago morado bailando en el bosque de noche", "<new> loc=forest time=night <ent> type=wizard color=purple act=dance"],
20
+ ["5 gallinas corriendo en una granja", "<new> loc=farm <ent> type=chicken n=5 act=run"],
21
+ ["a ghost floating in a room at night", "<new> loc=room time=night <ent> type=ghost act=float"],
22
+ ["un elefante rosa", "<new> <ent> type=elephant color=pink"],
23
+ ["snowman waving in the snow", "<new> loc=snow <ent> type=snowman act=wave"],
24
+ ["a wide shot of a train moving through the desert", "<new> loc=desert shot=wide <ent> type=train act=drive"],
25
+ ["there is a cat sitting on a table in a room", "<new> loc=room <ent> type=cat act=sit rel=on <ent> type=table"],
26
+ ["quiero ver un león corriendo detrás de una oveja", "<new> <ent> type=lion act=run rel=behind <ent> type=sheep"],
27
+ ["Make the dog blue", "<edit> <set> type=dog color=blue"],
28
+ ["add a tree", "<edit> <add> type=tree"],
29
+ ["remove the car", "<edit> <del> type=car"],
30
+ ["zoom out", "<edit> <cam> shot=out"],
31
+ ["haz el zorro verde", "<edit> <set> type=fox color=green"],
32
+ ["añade un árbol gigante", "<edit> <add> type=tree size=giant"],
33
+ ["que llueva", "<edit> <env> weather=rain"],
34
+ ["aleja la cámara", "<edit> <cam> shot=out"],
35
+ ["gira la cámara", "<edit> <cam> cam=orbit"],
36
+ ["ahora de noche", "<edit> <env> time=night"],
37
+ ["quita el coche", "<edit> <del> type=car"],
38
+ ["make the robot jump", "<edit> <set> type=robot act=jump"],
39
+ ["the horse should run faster", "<edit> <set> type=horse spd=fast"],
40
+ ["haz que el pingüino baile", "<edit> <set> type=penguin act=dance"],
41
+ ["add two red balloons", "<edit> <add> type=balloon color=red n=2"],
42
+ ["make it night and add fog", "<edit> <env> time=night <env> weather=fog"],
43
+ ["pon el dragón más grande", "<edit> <set> type=dragon size=up"],
44
+ ["move everything to the beach", "<edit> <env> loc=beach"],
45
+ ["cambia el fondo a una ciudad", "<edit> <env> loc=city"],
46
+ ["can you turn the cat orange please", "<edit> <set> type=cat color=orange"],
47
+ ["i'd like the bear to be sleeping", "<edit> <set> type=bear act=sleep"],
48
+ ["borra todo", "<edit> <del> type=all"],
49
+ ["stop the rain", "<edit> <env> weather=clear"],
50
+ ["¿qué puedes hacer?", "<qa> lang=es topic=help"],
51
+ ["what is a mesh?", "<qa> lang=en topic=mesh"],
52
+ ["cómo activo las sombras", "<qa> lang=es topic=shadow"],
53
+ ["how do i load a gltf model", "<qa> lang=en topic=gltf"],
54
+ ["why is my scene completely black", "<qa> lang=en topic=light"],
55
+ ["qué objetos conoces", "<qa> lang=es topic=objects"],
56
+ ["explícame los materiales", "<qa> lang=es topic=material"],
57
+ ["a prple elefant dansing in teh forest", "<new> loc=forest <ent> type=elephant color=purple act=dance"],
58
+ ["un prro rjo corriendo en la plya", "<new> loc=beach <ent> type=dog color=red act=run"],
59
+ ["a little girl flying a kite", null],
60
+ ["a dog and a cat and a bird", "<new> <ent> type=dog <ent> type=cat <ent> type=bird"],
61
+ ["the rocket is flying over the house at night with the camera following it", "<new> time=night cam=follow <ent> type=rocket act=fly rel=over <ent> type=house"]
62
+ ]
tests/parity.json ADDED
@@ -0,0 +1 @@
 
 
1
+ [["en la superficie lunar: un alienigena amarillo junto a un pato que duerme camara panoramica durante el dia", ["<new>", "loc=moon", "time=day", "cam=pan", "<ent>", "type=alien", "color=yellow", "rel=near", "<ent>", "type=duck", "act=sleep"]], ["genera en una ciudad un pato primer plano en el atardeecer en la niebla", ["<new>", "loc=city", "time=sunset", "weather=fog", "shot=close", "<ent>", "type=duck"]], ["unna bicileta de día, en las montañas", ["<new>", "loc=mountain", "time=day", "<ent>", "type=bike"]], ["the pink horse hoveing in front of a dio", ["<new>", "<ent>", "type=horse", "color=pink", "act=float", "rel=front", "<ent>", "type=dinosaur"]], ["cómo dejo que el usuario mueva la cámara con three.js?", ["<qa>", "lang=es", "topic=controls"]], ["a silver fox napping from above on the moon", ["<new>", "loc=moon", "shot=top", "<ent>", "type=fox", "color=silver", "act=sleep"]], ["escena de una casa amarilla en la selva y también el dinosaurio que salta, zoom out lento", ["<new>", "loc=forest", "cam=zoomout", "<ent>", "type=house", "color=yellow", "<ent>", "type=dinosaur", "act=jump"]], ["change the location to a highway", ["<edit>", "<env>", "loc=road"]], ["un pez siguiendo a un león", ["<new>", "<ent>", "type=fish", "rel=chase", "<ent>", "type=lion"]], ["el tiburon contrapicado", ["<new>", "shot=low", "<ent>", "type=shark"]], ["i want to see downtown a big white woman driving camera still", ["<new>", "loc=city", "cam=static", "<ent>", "type=woman", "color=white", "size=big", "act=drive"]], ["que son el objeto fog", ["<qa>", "lang=es", "topic=fog"]], ["noe rocck that is shivering, in the daytime", ["<new>", "time=day", "<ent>", "type=rock", "act=shake"]], ["can the bear move forward", ["<edit>", "<set>", "type=bear", "act=drive"]], ["the dragon rolling very fast around table", ["<new>", "<ent>", "type=dragon", "act=roll", "spd=fast", "rel=around", "<ent>", "type=table"]], ["a small green truck on a farm plus a cyan plane that is sprinting and a lamp is walking", ["<new>", "loc=farm", "<ent>", "type=truck", "color=green", "size=small", "<ent>", "type=plane", "color=cyan", "act=run", "<ent>", "type=lamp", "act=walk"]], ["quita la lluvia", ["<edit>", "<env>", "weather=clear"]], ["un pajaro rojo moviendoe con seis autobuses nadando", ["<new>", "<ent>", "type=bird", "color=red", "act=drive", "<ent>", "type=bus", "n=6", "act=swim"]], ["build six large golden streetlights beside a snowman standing and an astronaut shivering while it rains", ["<new>", "weather=rain", "<ent>", "type=lamp", "color=gold", "size=big", "n=6", "rel=near", "<ent>", "type=snowman", "act=idle", "<ent>", "type=astronaut", "act=shake"]], ["a black ghost, in outer space", ["<new>", "loc=space", "<ent>", "type=ghost", "color=black"]], ["como optmizo mi escena en threejs", ["<qa>", "lang=es", "topic=performance"]], ["un camion cian saludando", ["<new>", "<ent>", "type=truck", "color=cyan", "act=wave"]], ["el chanchc más grande por favor", ["<edit>", "<set>", "type=pig", "size=up"]], ["why use three.js.", ["<qa>", "lang=en", "topic=threejs"]], ["puedes explicar los colores en three.js?", ["<qa>", "lang=es", "topic=color"]], ["crea cuatro balones brincando sobre un skate anaranjado junto a un banco grande turquesa vibrando en un día con niebla", ["<new>", "weather=fog", "<ent>", "type=ball", "n=4", "act=jump", "rel=over", "<ent>", "type=skateboard", "color=orange", "rel=near", "<ent>", "type=bench", "color=cyan", "size=big", "act=shake"]], ["how do s ad gltf", ["<qa>", "lang=en", "topic=gltf"]], ["que objetos pedo usar?", ["<qa>", "lang=es", "topic=objects"]], ["que estén en la luna", ["<edit>", "<env>", "loc=moon"]], ["put a giant house there", ["<edit>", "<add>", "type=house", "size=giant"]], ["una sillw en un valle", ["<new>", "loc=mountain", "<ent>", "type=chair"]], ["quiero ver el avion grande montando una roca que corre lento detras de un bote", ["<new>", "<ent>", "type=plane", "size=big", "rel=ride", "<ent>", "type=rock", "act=run", "spd=slow", "rel=behind", "<ent>", "type=boat"]], ["un plano medio de una roca enorme", ["<new>", "shot=medium", "<ent>", "type=rock", "size=giant"]], ["quiero que el león salude", ["<edit>", "<set>", "type=lion", "act=wave"]], ["render a turquoise car zooming out", ["<new>", "cam=zoomout", "<ent>", "type=car", "color=cyan"]], ["saca el muñeco de nieve", ["<edit>", "<del>", "type=snowman"]], ["como selecciono un objeto con el raton?", ["<qa>", "lang=es", "topic=raycaster"]], ["genera un caballero y también un tiburón minúúsculo en la carretera", ["<new>", "loc=road", "<ent>", "type=knight", "<ent>", "type=shark", "size=tiny"]], ["6 benches in the woods", ["<new>", "loc=forest", "<ent>", "type=bench", "n=6"]], ["escena de una gallina grande nadando enfrennte de un caballo plateado grande en una autopista", ["<new>", "loc=road", "<ent>", "type=chicken", "size=big", "act=swim", "rel=front", "<ent>", "type=horse", "color=silver", "size=big"]], ["el conejo de color rosado", ["<edit>", "<set>", "type=rabbit", "color=pink"]], ["una casa paneo.", ["<new>", "cam=pan", "<ent>", "type=house"]], ["can you explain groups with three.js?", ["<qa>", "lang=en", "topic=group"]], ["un hechicero en el desierto", ["<new>", "loc=desert", "<ent>", "type=wizard"]], ["now delete the house", ["<edit>", "<del>", "type=house"]], ["un cactus verde muy pequeño que no se mueve y un platillo volador gris gigantesco, la camara se aleja bajo una nevada", ["<new>", "weather=snow", "cam=zoomout", "<ent>", "type=cactus", "color=green", "size=tiny", "act=idle", "<ent>", "type=ufo", "color=gray", "size=giant"]], ["un gatito gigante flotando encima de pájaro que rebota rápido nevando", ["<new>", "weather=snow", "<ent>", "type=cat", "size=giant", "act=float", "rel=on", "<ent>", "type=bird", "act=bounce", "spd=fast"]], ["una farola chica flotando", ["<new>", "<ent>", "type=lamp", "size=small", "act=float"]], ["una patineta blanca montando en un barco marrón avanzando lento en un parque con buen tiempo", ["<new>", "loc=park", "weather=clear", "<ent>", "type=skateboard", "color=white", "rel=ride", "<ent>", "type=boat", "color=brown", "act=drive", "spd=slow"]], ["3 green benches sitting down in outer space", ["<new>", "loc=space", "<ent>", "type=bench", "color=green", "n=3", "act=sit"]], ["on a plain background, one grey dinosaur going in circles", ["<new>", "loc=studio", "<ent>", "type=dinosaur", "color=gray", "act=circle"]], ["explica los colores headecimales", ["<qa>", "lang=es", "topic=color"]], ["ponle un avión gris.", ["<edit>", "<add>", "type=plane", "color=gray"]], ["un gato corriendo tras un cohete enorme negro, la cámara se mueve de lado", ["<new>", "cam=pan", "<ent>", "type=cat", "rel=chase", "<ent>", "type=rocket", "color=black", "size=giant"]], ["htreejs", ["<qa>", "lang=en", "topic=threejs"]], ["a silver shark in the rain", ["<new>", "weather=rain", "<ent>", "type=shark", "color=silver"]], ["haz el perrito gigante corriendo", ["<new>", "<ent>", "type=dog", "size=giant", "act=run"]], ["haz el astronauta mas lento por favor", ["<edit>", "<set>", "type=astronaut", "spd=slow"]], ["pon al helicóptero a detenerse y luego anima un zoom in", ["<edit>", "<set>", "type=helicopter", "act=idle", "<cam>", "cam=zoomin"]], ["en la galaxia, un cohete negro", ["<new>", "loc=space", "<ent>", "type=rocket", "color=black"]], ["make the flying saucer grey instead, make the trani little", ["<edit>", "<set>", "type=ufo", "color=gray", "<set>", "type=train", "size=small"]], ["the enormous yellow bear and a little brown dinosaur on a highway at dusk with clear skies", ["<new>", "loc=road", "time=sunset", "weather=clear", "<ent>", "type=bear", "color=yellow", "size=giant", "<ent>", "type=dinosaur", "color=brown", "size=small"]], ["una pelota morada gigantesca sacudiéndose delante del pingüino que duerme y un pez azul que gira.", ["<new>", "<ent>", "type=ball", "color=purple", "size=giant", "act=shake", "rel=front", "<ent>", "type=penguin", "act=sleep", "<ent>", "type=fish", "color=blue", "act=spin"]], ["a turquoise alien and also the brown duck is standing still plus a big bear that is sleeping on a mountain", ["<new>", "loc=mountain", "<ent>", "type=alien", "color=cyan", "<ent>", "type=duck", "color=brown", "act=idle", "<ent>", "type=bear", "size=big", "act=sleep"]], ["ayuda con three color", ["<qa>", "lang=es", "topic=color"]], ["un plano general de cohe bailando bajo la lluvia", ["<new>", "weather=rain", "shot=wide", "<ent>", "type=car", "act=dance"]], ["la fllor vibrando", ["<edit>", "<set>", "type=flower", "act=shake"]], ["a gold house on a road medium shot", ["<new>", "loc=road", "shot=medium", "<ent>", "type=house", "color=gold"]], ["en el salón, una bici bailando lento", ["<new>", "loc=room", "<ent>", "type=bike", "act=dance", "spd=slow"]], ["sin el tiburon", ["<edit>", "<del>", "type=shark"]], ["puedes que sea con fondo liso. quiero el tren violeta", ["<edit>", "<env>", "loc=studio", "<set>", "type=train", "color=purple"]], ["the golden bunny that is moving in a circle and four orange dragons, camera moving closer", ["<new>", "cam=zoomin", "<ent>", "type=rabbit", "color=gold", "act=circle", "<ent>", "type=dragon", "color=orange", "n=4"]], ["how does the ai work?", ["<qa>", "lang=en", "topic=about"]], ["un mago arriba de la patineta que esta quieta plano cerrado con nieve cayendo", ["<new>", "weather=snow", "shot=close", "<ent>", "type=wizard", "rel=on", "<ent>", "type=skateboard", "act=idle"]], ["change the kittten to white", ["<edit>", "<set>", "type=cat", "color=white"]], ["make the alien little", ["<edit>", "<set>", "type=alien", "size=small"]], ["a turquoise robot soaring around a tree driving along slowly plus a rocket on the lunar surface", ["<new>", "loc=moon", "<ent>", "type=robot", "color=cyan", "act=fly", "rel=around", "<ent>", "type=tree", "act=drive", "spd=slow", "<ent>", "type=rocket"]], ["make the skateboard brown", ["<edit>", "<set>", "type=skateboard", "color=brown"]], ["dibuja un coche", ["<new>", "<ent>", "type=car"]], ["a girl running in a room", ["<new>", "loc=room", "<ent>", "type=woman", "act=run"]], ["pon el marciano de color blanco", ["<edit>", "<set>", "type=alien", "color=white"]], ["give me flower in front of five bunnies", ["<new>", "<ent>", "type=flower", "rel=front", "<ent>", "type=rabbit", "n=5"]], ["a small violet shark that is running in the evening, in a snowy landscape.", ["<new>", "loc=snow", "time=sunset", "<ent>", "type=shark", "color=purple", "size=small", "act=run"]], ["add a swimming purple alimn", ["<edit>", "<add>", "type=alien", "color=purple", "act=swim"]], ["a sene with an orange knight is swimming and also a boat.", ["<new>", "<ent>", "type=knight", "color=orange", "act=swim", "<ent>", "type=boat"]], ["un chico plateado que esta bailando en un valle gran angular", ["<new>", "loc=mountain", "shot=wide", "<ent>", "type=man", "color=silver", "act=dance"]], ["en la superficie lwnar, una banca frente a señora saltando lloviendo", ["<new>", "loc=moon", "weather=rain", "<ent>", "type=bench", "rel=front", "<ent>", "type=woman", "act=jump"]], ["the man with claer skies in a snowy landscaape", ["<new>", "loc=snow", "weather=clear", "<ent>", "type=man"]], ["a golden guy bird's eye view", ["<new>", "shot=top", "<ent>", "type=man", "color=gold"]], ["add snowfall", ["<edit>", "<env>", "weather=snow"]], ["lo quiero naranja", ["<edit>", "<set>", "type=it", "color=orange"]], ["una flor violeta dormida", ["<new>", "<ent>", "type=flower", "color=purple", "act=sleep"]], ["a small crate driving alog very fast at dawn", ["<new>", "time=dawn", "<ent>", "type=box", "size=small", "act=drive", "spd=fast"]], ["anima dos aviones azules levitando encima de carro gris montando un pollo que saluda", ["<new>", "<ent>", "type=plane", "color=blue", "n=2", "act=float", "rel=on", "<ent>", "type=car", "color=gray", "rel=ride", "<ent>", "type=chicken", "act=wave"]], ["animate a duck waves hello on the moon at midnight.", ["<new>", "loc=moon", "time=night", "<ent>", "type=duck", "act=wave"]], ["can you have the elephant move forward", ["<edit>", "<set>", "type=elephant", "act=drive"]], ["paint the bird grey", ["<edit>", "<set>", "type=bird", "color=gray"]], ["pink fox running after the enormous golden car", ["<new>", "<ent>", "type=fox", "color=pink", "rel=chase", "<ent>", "type=car", "color=gold", "size=giant"]], ["dos caballeros rosados que estan andando detras de tres hechiceros corriendo, en el agua", ["<new>", "loc=ocean", "<ent>", "type=knight", "color=pink", "n=2", "act=walk", "rel=behind", "<ent>", "type=wizard", "n=3", "act=run"]], ["how can i use a geometry in three.js", ["<qa>", "lang=en", "topic=geometry"]], ["puedes añadir un helicóptero caminando", ["<edit>", "<add>", "type=helicopter", "act=walk"]], ["show me a green snowman at dusk on a farm during a storm", ["<new>", "loc=farm", "time=sunset", "weather=storm", "<ent>", "type=snowman", "color=green"]], ["the fox starts to wait", ["<edit>", "<set>", "type=fox", "act=idle"]], ["5 large blue flowesr and also a red helicopter behind a kitten at midnight", ["<new>", "time=night", "<ent>", "type=flower", "color=blue", "size=big", "n=5", "<ent>", "type=helicopter", "color=red", "rel=behind", "<ent>", "type=cat"]], ["una vaca morada montada en un elefante andando alrededor de un dragón negro grande corriendo en la playa", ["<new>", "loc=beach", "<ent>", "type=cow", "color=purple", "rel=ride", "<ent>", "type=elephant", "act=walk", "rel=around", "<ent>", "type=dragon", "color=black", "size=big", "act=run"]], ["un globo naranja más un elefante girando", ["<new>", "<ent>", "type=balloon", "color=orange", "<ent>", "type=elephant", "act=spin"]], ["todoss marrones", ["<edit>", "<set>", "type=all", "color=brown"]], ["a duck jumping above a lion, in the desert", ["<new>", "loc=desert", "<ent>", "type=duck", "act=jump", "rel=over", "<ent>", "type=lion"]], ["give me a white flower, on a farm", ["<new>", "loc=farm", "<ent>", "type=flower", "color=white"]], ["ahora el cnejo gira y luego en un dia soleado", ["<edit>", "<set>", "type=rabbit", "act=spin", "<env>", "time=day"]], ["haz el avión gris, cambia el color del elefante a violeta por favor", ["<edit>", "<set>", "type=plane", "color=gray", "<set>", "type=elephant", "color=purple"]], ["añade nieve", ["<edit>", "<env>", "weather=snow"]], ["que el perrito se duerma", ["<edit>", "<set>", "type=dog", "act=sleep"]], ["the dragon smaller", ["<edit>", "<set>", "type=dragon", "size=down"]], ["make the tower go slower", ["<edit>", "<set>", "type=tower", "spd=slow"]], ["dibuja un elefane marron que rueda detras del helicoptero dorado que saluda, desde abajo, al anochecer, en un bosque.", ["<new>", "loc=forest", "time=sunset", "shot=low", "<ent>", "type=elephant", "color=brown", "act=roll", "rel=behind", "<ent>", "type=helicopter", "color=gold", "act=wave"]], ["un coche frente a 3 tiburones negros caminando en circulos despacio", ["<new>", "<ent>", "type=car", "rel=front", "<ent>", "type=shark", "color=black", "n=3", "act=circle", "spd=slow"]], ["a gray robot", ["<new>", "<ent>", "type=robot", "color=gray"]], ["haz que la mujer pasee", ["<edit>", "<set>", "type=woman", "act=walk"]], ["acércte", ["<edit>", "<cam>", "shot=in"]], ["un zorro pequeño verde que salta rápido, con tormenta eléctrica", ["<new>", "weather=storm", "<ent>", "type=fox", "color=green", "size=small", "act=jump", "spd=fast"]], ["three balls dance slbw in tthe daytime", ["<new>", "time=day", "<ent>", "type=ball", "n=3", "act=dance", "spd=slow"]], ["ok vamos a juunvo al mar", ["<edit>", "<env>", "loc=beach"]], ["2 lámparas negras brincando muy despacio alrededor de una mesa anaranjada montada en un dragón grande saltando desde lejos en un día con niebla en altamar", ["<new>", "loc=ocean", "weather=fog", "shot=wide", "<ent>", "type=lamp", "color=black", "n=2", "act=jump", "spd=slow", "rel=around", "<ent>", "type=table", "color=orange", "rel=ride", "<ent>", "type=dragon", "size=big", "act=jump"]], ["construye en una granj, un balon orjo cerca de un fantasma enorme que esta corriendo en un dia con niebla, la camara se aleja", ["<new>", "loc=farm", "weather=fog", "cam=zoomout", "<ent>", "type=ball", "color=red", "rel=near", "<ent>", "type=ghost", "size=giant", "act=run"]], ["un gato gris sobre un caballero bailando", ["<new>", "<ent>", "type=cat", "color=gray", "rel=on", "<ent>", "type=knight", "act=dance"]], ["a big giraffe standing, aerial view, in the daytime, in the desert", ["<new>", "loc=desert", "time=day", "shot=top", "<ent>", "type=giraffe", "size=big", "act=idle"]], ["que sea en un bosque", ["<edit>", "<env>", "loc=forest"]], ["ahora pon otro pez", ["<edit>", "<add>", "type=fish"]], ["an orange house that is sprinting around one cow", ["<new>", "<ent>", "type=house", "color=orange", "act=run", "rel=around", "<ent>", "type=cow"]], ["un conejo cerca de una bicicleta plateada que brinca al anochecer, en un cuarto", ["<new>", "loc=room", "time=sunset", "<ent>", "type=rabbit", "rel=near", "<ent>", "type=bike", "color=silver", "act=jump"]], ["agrégale un dinosaurio marrón", ["<edit>", "<add>", "type=dinosaur", "color=brown"]], ["ayuda con el mapa de sombras en three.js", ["<qa>", "lang=es", "topic=shadow"]], ["the boat bounecs in the mist", ["<new>", "weather=fog", "<ent>", "type=boat", "act=bounce"]], ["medium shot", ["<edit>", "<cam>", "shot=medium"]], ["let the sheep fly", ["<edit>", "<set>", "type=sheep", "act=fly"]], ["change the color of th ablls to white", ["<edit>", "<set>", "type=ball", "color=white"]], ["pon a la banca a fltoar", ["<edit>", "<set>", "type=bench", "act=float"]], ["why is my scene black in trhee.js", ["<qa>", "lang=en", "topic=light"]], ["sigue acercando la cámara", ["<edit>", "<cam>", "cam=zoomin"]], ["cómo attivo las sombras con three.js?", ["<qa>", "lang=es", "topic=shadow"]], ["cómo muevo la cámara", ["<qa>", "lang=es", "topic=camera"]], ["anima cuatro puercos café rodando alrededor de la jirafa gris sentada", ["<new>", "<ent>", "type=pig", "color=brown", "n=4", "act=roll", "rel=around", "<ent>", "type=giraffe", "color=gray", "act=sit"]], ["a giant gray pig levitates the camera follows at dusk long shot", ["<new>", "time=sunset", "shot=wide", "cam=follow", "<ent>", "type=pig", "color=gray", "size=giant", "act=float"]], ["ok el conejo verde", ["<edit>", "<set>", "type=rabbit", "color=green"]], ["wide shot of a pink bicycle riding a robot on a black lady standing still, on a foggy day", ["<new>", "weather=fog", "shot=wide", "<ent>", "type=bike", "color=pink", "rel=ride", "<ent>", "type=robot", "rel=on", "<ent>", "type=woman", "color=black", "act=idle"]], ["clear the scene. camera from above", ["<edit>", "<del>", "type=all", "<cam>", "shot=top"]], ["la seta azul grande que se mueve en círculos, en una casa en el atardecer", ["<new>", "loc=room", "time=sunset", "<ent>", "type=mushroom", "color=blue", "size=big", "act=circle"]], ["an animation of a cow seated on a raniy day static camera", ["<new>", "weather=rain", "cam=static", "<ent>", "type=cow", "act=sit"]], ["three bikes walking in circles quickly", ["<new>", "<ent>", "type=bike", "n=3", "act=circle", "spd=fast"]], ["a huge helicopter", ["<new>", "<ent>", "type=helicopter", "size=giant"]], ["no more fog", ["<edit>", "<env>", "weather=clear"]], ["un muñeco de nieve grande caminando lento", ["<new>", "<ent>", "type=snowman", "size=big", "act=walk", "spd=slow"]], ["have the trais sit down", ["<edit>", "<set>", "type=train", "act=sit"]], ["how does the hierarchy work in threejs", ["<qa>", "lang=en", "topic=group"]], ["the red car walking", ["<new>", "<ent>", "type=car", "color=red", "act=walk"]], ["caja, en el bosque, vista 360", ["<new>", "loc=forest", "cam=orbit", "<ent>", "type=box"]], ["un platillo volador chico que está botando en un día lluvioso", ["<new>", "weather=rain", "<ent>", "type=ufo", "size=small", "act=bounce"]], ["los robots se sientan ahora. ya no quiero la farola", ["<edit>", "<set>", "type=robot", "act=sit", "<del>", "type=lamp"]], ["the controls im three.js?", ["<qa>", "lang=en", "topic=controls"]], ["un carro diminuto que está brincando detrás de un bus lloviendo", ["<new>", "weather=rain", "<ent>", "type=car", "size=tiny", "act=jump", "rel=behind", "<ent>", "type=bus"]], ["muestrame 2 dinosaurios gigantescos que estan corriendo alrededor de un arbol pequeño camara quieta", ["<new>", "cam=static", "<ent>", "type=dinosaur", "size=giant", "n=2", "act=run", "rel=around", "<ent>", "type=tree", "size=small"]], ["un dragon rojo pequeño montando al gato corriendo haciendo zoom, desde leejos, en un dia lluvioso, en la hierba", ["<new>", "loc=field", "weather=rain", "shot=wide", "cam=zoomin", "<ent>", "type=dragon", "color=red", "size=small", "rel=ride", "<ent>", "type=cat", "act=run"]], ["how do i make snow in code", ["<qa>", "lang=en", "topic=particles"]], ["cómo hago una esfera", ["<qa>", "lang=es", "topic=mesh"]], ["and a swimming rabbit.", ["<edit>", "<add>", "type=rabbit", "act=swim"]], ["crea la chica gigante blanca que esta bailando, en la selva", ["<new>", "loc=forest", "<ent>", "type=woman", "color=white", "size=giant", "act=dance"]], ["haz rodar al dragón. aumenta el tamaño del platillo volador.", ["<edit>", "<set>", "type=dragon", "act=roll", "<set>", "type=ufo", "size=up"]], ["hep with keyframes in thrreejs?", ["<qa>", "lang=en", "topic=animation"]], ["cómo pngo una foto en un cubo con three.js", ["<qa>", "lang=es", "topic=texture"]], ["un fantasma rojo cazando a 3 peces que vuelan sobre un chancho diminuto que esta saludando con la mano zoom out lento durante el dia en la sala", ["<new>", "loc=room", "time=day", "cam=zoomout", "<ent>", "type=ghost", "color=red", "rel=chase", "<ent>", "type=fish", "n=3", "act=fly", "rel=over", "<ent>", "type=pig", "size=tiny", "act=wave"]], ["cambia al anochecer", ["<edit>", "<env>", "time=sunset"]], ["animate two twirling red chairs in the fog, in a valley", ["<new>", "loc=mountain", "weather=fog", "<ent>", "type=chair", "color=red", "n=2", "act=spin"]], ["un bote siguiendo a un globo pequeño verde en el mar", ["<new>", "loc=ocean", "<ent>", "type=boat", "rel=chase", "<ent>", "type=balloon", "color=green", "size=small"]], ["trvvelling", ["<edit>", "<cam>", "cam=follow"]], ["que el avion empiece a dormir", ["<edit>", "<set>", "type=plane", "act=sleep"]], ["2 large grey sharks hunting a fox on a farm", ["<new>", "loc=farm", "<ent>", "type=shark", "color=gray", "size=big", "n=2", "rel=chase", "<ent>", "type=fox"]], ["four very small benches, the dinosaur that is driving along zooming in in good weather", ["<new>", "weather=clear", "cam=zoomin", "<ent>", "type=bench", "size=tiny", "n=4", "<ent>", "type=dinosaur", "act=drive"]], ["clear the scene", ["<edit>", "<del>", "type=all"]], ["laa chica rodando en un rancho", ["<new>", "loc=farm", "<ent>", "type=woman", "act=roll"]], ["a mushroom in a desert", ["<new>", "loc=desert", "<ent>", "type=mushroom"]], ["angulo bajo de un muñecco de nieve mas un helicoptero que saluda cerca de una vaca que esta volando", ["<new>", "shot=low", "<ent>", "type=snowman", "<ent>", "type=helicopter", "act=wave", "rel=near", "<ent>", "type=cow", "act=fly"]], ["3 ovnis pequeños bailando, con buen tiempo esde el aire", ["<new>", "weather=clear", "shot=top", "<ent>", "type=ufo", "size=small", "n=3", "act=dance"]], ["2 torres que tiemblan en el desierto por la noche.", ["<new>", "loc=desert", "time=night", "<ent>", "type=tower", "n=2", "act=shake"]], ["make it bright", ["<edit>", "<env>", "time=day"]], ["un avion conduciendo a toda velocidad frente a un zorro azul, en el bosque", ["<new>", "loc=forest", "<ent>", "type=plane", "act=drive", "spd=fast", "rel=front", "<ent>", "type=fox", "color=blue"]], ["i want a sitting airplane in the woods with the big lady in the rain", ["<new>", "loc=forest", "weather=rain", "<ent>", "type=plane", "act=sit", "<ent>", "type=woman", "size=big"]], ["cómo hago algo brillante con three.js?", ["<qa>", "lang=es", "topic=material"]], ["en el parque el caballero anaranjado minúsculo", ["<new>", "loc=park", "<ent>", "type=knight", "color=orange", "size=tiny"]], ["una banca chica dorada dormida detras de torre caminando en circulos muy rapido", ["<new>", "<ent>", "type=bench", "color=gold", "size=small", "act=sleep", "rel=behind", "<ent>", "type=tower", "act=circle", "spd=fast"]], ["how do i set a color in code in three.js", ["<qa>", "lang=en", "topic=color"]], ["how do i use the mesh ni threejss?", ["<qa>", "lang=en", "topic=mesh"]], ["construye una patineta dorada flotando por encima de seis caballeros turquesas que saltan en la playa al atardecer", ["<new>", "loc=beach", "time=sunset", "<ent>", "type=skateboard", "color=gold", "act=float", "rel=over", "<ent>", "type=knight", "color=cyan", "n=6", "act=jump"]], ["the gigantic penguin closeup", ["<new>", "shot=close", "<ent>", "type=penguin", "size=giant"]], ["en un paisaje nevado un señor verde que da vueltas a toda velocidad", ["<new>", "loc=snow", "<ent>", "type=man", "color=green", "act=spin", "spd=fast"]], ["2 elefantes, durante una tormenta", ["<new>", "weather=storm", "<ent>", "type=elephant", "n=2"]], ["on the lunar surface, a very small blue bird that is sleeping, raining in the evening", ["<new>", "loc=moon", "time=sunset", "weather=rain", "<ent>", "type=bird", "color=blue", "size=tiny", "act=sleep"]], ["encoge el arbol", ["<edit>", "<set>", "type=tree", "size=down"]], ["add some mist", ["<edit>", "<env>", "weather=fog"]], ["ahora los árboles es azules", ["<edit>", "<set>", "type=tree", "color=blue"]], ["unn leon en el mar", ["<new>", "loc=ocean", "<ent>", "type=lion"]], ["cambia el monopatín a turquesa", ["<edit>", "<set>", "type=skateboard", "color=cyan"]], ["an animation of a penguin is driving, wide angle", ["<new>", "shot=wide", "<ent>", "type=penguin", "act=drive"]], ["five tables behind a cyan bird during a storm", ["<new>", "weather=storm", "<ent>", "type=table", "n=5", "rel=behind", "<ent>", "type=bird", "color=cyan"]], ["include a trembling rocket", ["<edit>", "<add>", "type=rocket", "act=shake"]], ["now turn the pig oargne", ["<edit>", "<set>", "type=pig", "color=orange"]], ["ad snow", ["<edit>", "<env>", "weather=snow"]], ["how do i load an image?", ["<qa>", "lang=en", "topic=texture"]], ["the gray duck on the lunar surface", ["<new>", "loc=moon", "<ent>", "type=duck", "color=gray"]], ["a silver bus shaking behind a house shivering in the dark", ["<new>", "time=night", "<ent>", "type=bus", "color=silver", "act=shake", "rel=behind", "<ent>", "type=house", "act=shake"]], ["vista cenital de un conejo junto a cinco caballos al lado de seis magos plateados bailando al atardecer", ["<new>", "time=sunset", "shot=top", "<ent>", "type=rabbit", "rel=near", "<ent>", "type=horse", "n=5", "rel=near", "<ent>", "type=wizard", "color=silver", "n=6", "act=dance"]], ["ahora llueve", ["<edit>", "<env>", "weather=rain"]], ["que primitivas existen", ["<qa>", "lang=es", "topic=geometry"]], ["build a little bench is standing with a bouncing golden flower, in good weather in the forest close up shot follow cam under the moonlight", ["<new>", "loc=forest", "time=night", "weather=clear", "shot=close", "cam=follow", "<ent>", "type=bench", "size=small", "act=idle", "<ent>", "type=flower", "color=gold", "act=bounce"]], ["una animacion de platillo volador que esta sentado frente al helicoptero minusculo montando el skate amarillo en un paisaje nevado", ["<new>", "loc=snow", "<ent>", "type=ufo", "act=sit", "rel=front", "<ent>", "type=helicopter", "size=tiny", "rel=ride", "<ent>", "type=skateboard", "color=yellow"]], ["el fantasma dorado ne altamar", ["<new>", "loc=ocean", "<ent>", "type=ghost", "color=gold"]], ["zoom out a little", ["<edit>", "<cam>", "shot=out"]], ["gira la cámara", ["<edit>", "<cam>", "cam=orbit"]], ["on the lunar surface: one req astronaut camera pulling back", ["<new>", "loc=moon", "cam=zoomout", "<ent>", "type=astronaut", "color=red"]], ["a duck in a barnyard in the evening", ["<new>", "loc=farm", "time=sunset", "<ent>", "type=duck"]], ["ahora añade un hombre minúsculo que vuela", ["<edit>", "<add>", "type=man", "size=tiny", "act=fly"]], ["6 yellow dogs driving along in front of a swimming tree in the sea", ["<new>", "loc=ocean", "<ent>", "type=dog", "color=yellow", "n=6", "act=drive", "rel=front", "<ent>", "type=tree", "act=swim"]], ["el avion moviendose en circulos despacio atras de un helicoptero", ["<new>", "<ent>", "type=plane", "act=circle", "spd=slow", "rel=behind", "<ent>", "type=helicopter"]], ["un autobús rojo chico moviéndose en cícrulos rápidamente en una casa", ["<new>", "loc=room", "<ent>", "type=bus", "color=red", "size=small", "act=circle", "spd=fast"]], ["remove the astronaut please", ["<edit>", "<del>", "type=astronaut"]], ["change the time to day please", ["<edit>", "<env>", "time=day"]], ["una silla, en un jardín", ["<new>", "loc=park", "<ent>", "type=chair"]], ["un pez purpura minusculo la camara se mueve de lado", ["<new>", "cam=pan", "<ent>", "type=fish", "color=purple", "size=tiny"]], ["a gigantic pink giraffe on top of an enormous shark", ["<new>", "<ent>", "type=giraffe", "color=pink", "size=giant", "rel=on", "<ent>", "type=shark", "size=giant"]], ["la patineta volando", ["<edit>", "<set>", "type=skateboard", "act=fly"]], ["a huge puppy walks in the jungle", ["<new>", "loc=forest", "<ent>", "type=dog", "size=giant", "act=walk"]], ["xplícame points?", ["<qa>", "lang=es", "topic=particles"]], ["please also a miniature silver ghost rolling", ["<edit>", "<add>", "type=ghost", "color=silver", "size=tiny", "act=roll"]], ["en el parque tiburón plateaado gigantesco", ["<new>", "loc=park", "<ent>", "type=shark", "color=silver", "size=giant"]], ["explain the available objects", ["<qa>", "lang=en", "topic=objects"]], ["tengo una pegunta sobre este modelo", ["<qa>", "lang=es", "topic=about"]], ["dibuja cuatro autobuses, desde abajo", ["<new>", "shot=low", "<ent>", "type=bus", "n=4"]], ["2 extraterrestres pequeños que saltan muy despacio sobre un astronauta rosado en una granja", ["<new>", "loc=farm", "<ent>", "type=alien", "size=small", "n=2", "act=jump", "spd=slow", "rel=over", "<ent>", "type=astronaut", "color=pink"]], ["how can i use vertices in threejs?", ["<qa>", "lang=en", "topic=geometry"]], ["mas lejos y quiero una tormenta", ["<edit>", "<cam>", "shot=out", "<env>", "weather=storm"]], ["conejo conduciendo rápido en el atardecer", ["<new>", "time=sunset", "<ent>", "type=rabbit", "act=drive", "spd=fast"]], ["what are mouse controls in three.js", ["<qa>", "lang=en", "topic=controls"]], ["ahora incluye un dragon", ["<edit>", "<add>", "type=dragon"]], ["quiero una tormenta. hazlo plateado", ["<edit>", "<env>", "weather=storm", "<set>", "type=it", "color=silver"]], ["un zorro rosa moviéndose en círculos y una piedra negra que levita por encima de un carro", ["<new>", "<ent>", "type=fox", "color=pink", "act=circle", "<ent>", "type=rock", "color=black", "act=float", "rel=over", "<ent>", "type=car"]], ["ok añade tambien una seta cafe pequeña, y una mujer", ["<edit>", "<add>", "type=mushroom", "color=brown", "size=small", "<add>", "type=woman"]], ["the ball riding on four gray foxes", ["<new>", "<ent>", "type=ball", "rel=ride", "<ent>", "type=fox", "color=gray", "n=4"]], ["pasa al amanecer", ["<edit>", "<env>", "time=dawn"]], ["stop snowing", ["<edit>", "<env>", "weather=clear"]], ["i also want a cyan tree", ["<edit>", "<add>", "type=tree", "color=cyan"]], ["change it t dusk please", ["<edit>", "<env>", "time=sunset"]], ["una animacion do un muñeco de nieve amarillo delante de una flor celeste gigante temblando, camara de seguimiento, en un ccuarto", ["<new>", "loc=room", "cam=follow", "<ent>", "type=snowman", "color=yellow", "rel=front", "<ent>", "type=flower", "color=cyan", "size=giant", "act=shake"]], ["hazme un alienigena amarillo sentado y tambien un caballero moviendose junto a la casa gris en la nieve en un dia lluvioso", ["<new>", "loc=snow", "weather=rain", "<ent>", "type=alien", "color=yellow", "act=sit", "<ent>", "type=knight", "act=drive", "rel=near", "<ent>", "type=house", "color=gray"]], ["the brown shark sprints, a balloo moving in a circle behind a helicopter rotating, 360 view, in a studi", ["<new>", "loc=studio", "cam=orbit", "<ent>", "type=shark", "color=brown", "act=run", "<ent>", "type=balloon", "act=circle", "rel=behind", "<ent>", "type=helicopter", "act=spin"]], ["pon un oso", ["<edit>", "<add>", "type=bear"]], ["make two grey kknights twirl in the fog in a fores", ["<new>", "loc=forest", "weather=fog", "<ent>", "type=knight", "color=gray", "n=2", "act=spin"]], ["por favor el hombre vuela ahora.", ["<edit>", "<set>", "type=man", "act=fly"]], ["como creo estrellas", ["<qa>", "lang=es", "topic=particles"]], ["how do you owk", ["<qa>", "lang=en", "topic=about"]], ["makee the chicken go in circles plelse", ["<edit>", "<set>", "type=chicken", "act=circle"]], ["tell me about parent and child objects in threejs?", ["<qa>", "lang=en", "topic=group"]], ["tres gallinas azules que vuelan alrededor del conejo enorme plateado en el atardecer", ["<new>", "time=sunset", "<ent>", "type=chicken", "color=blue", "n=3", "act=fly", "rel=around", "<ent>", "type=rabbit", "color=silver", "size=giant"]], ["4 giant giraffes, wo rockets seate", ["<new>", "<ent>", "type=giraffe", "size=giant", "n=4", "<ent>", "type=rocket", "n=2", "act=sit"]], ["a violet train riding an orange cow sprints in a snowfall at night", ["<new>", "time=night", "weather=snow", "<ent>", "type=train", "color=purple", "rel=ride", "<ent>", "type=cow", "color=orange", "act=run"]], ["una mesa rodando en el atardecer", ["<new>", "time=sunset", "<ent>", "type=table", "act=roll"]], ["ponlo en una ciudad", ["<edit>", "<env>", "loc=city"]], ["limpia la escena", ["<edit>", "<del>", "type=all"]], ["in a barnyard, 4 houses rolling fast early in the morning while it rains", ["<new>", "loc=farm", "time=dawn", "weather=rain", "<ent>", "type=house", "n=4", "act=roll", "spd=fast"]], ["un pato rojo grande y una oveja en la madrugada", ["<new>", "time=dawn", "<ent>", "type=duck", "color=red", "size=big", "<ent>", "type=sheep"]], ["un elefante cerca de un helicóptero, tres dinosaurios que están paseando temprano en la mañana", ["<new>", "time=dawn", "<ent>", "type=elephant", "rel=near", "<ent>", "type=helicopter", "<ent>", "type=dinosaur", "n=3", "act=walk"]], ["mete seis caballos grandes avanzando", ["<edit>", "<add>", "type=horse", "size=big", "n=6", "act=drive"]], ["2 gatitos gigantes que se sientan", ["<new>", "<ent>", "type=cat", "size=giant", "n=2", "act=sit"]], ["ahora es en la madruada", ["<edit>", "<env>", "time=dawn"]], ["píntala de morado por favor.", ["<edit>", "<set>", "type=it", "color=purple"]], ["create a large violet cow plus 6 miniature black cactuses bouncing", ["<new>", "<ent>", "type=cow", "color=purple", "size=big", "<ent>", "type=cactus", "color=black", "size=tiny", "n=6", "act=bounce"]], ["turn it into sunset", ["<edit>", "<env>", "time=sunset"]], ["cener dos mesas", ["<new>", "<ent>", "type=table", "n=2"]], ["an animation of an enormous flower swimming on a city street and a big pink woman that is rolling around a big mushroom hopping, in good weather", ["<new>", "loc=city", "weather=clear", "<ent>", "type=flower", "size=giant", "act=swim", "<ent>", "type=woman", "color=pink", "size=big", "act=roll", "rel=around", "<ent>", "type=mushroom", "size=big", "act=jump"]], ["ponlo en una autopista", ["<edit>", "<env>", "loc=road"]], ["que son la red neuronal?", ["<qa>", "lang=es", "topic=about"]], ["escena de un gatito flotando por encima de carro de noche", ["<new>", "time=night", "<ent>", "type=cat", "act=float", "rel=over", "<ent>", "type=car"]], ["un helicóptero plateado montando un tiburón blanco que da vueltas", ["<new>", "<ent>", "type=helicopter", "color=silver", "rel=ride", "<ent>", "type=shark", "color=white", "act=spin"]], ["aerial view of a gold wizard asleep in a park", ["<new>", "loc=park", "shot=top", "<ent>", "type=wizard", "color=gold", "act=sleep"]], ["turn it into daytime", ["<edit>", "<env>", "time=day"]], ["camera circling around", ["<edit>", "<cam>", "cam=orbit"]], ["muestrame en el oceano la trore gigante sacudiendose con tormenta electrica", ["<new>", "loc=ocean", "weather=storm", "<ent>", "type=tower", "size=giant", "act=shake"]], ["get ridd of the ufo", ["<edit>", "<del>", "type=ufo"]], ["three turquoise skateboards soaring behind a walking wizard around a gold hen driving low angle", ["<new>", "shot=low", "<ent>", "type=skateboard", "color=cyan", "n=3", "act=fly", "rel=behind", "<ent>", "type=wizard", "act=walk", "rel=around", "<ent>", "type=chicken", "color=gold", "act=drive"]], ["now add a cyan robot", ["<edit>", "<add>", "type=robot", "color=cyan"]], ["ahora el skate es blanco", ["<edit>", "<set>", "type=skateboard", "color=white"]], ["haz dos skavs negros, al atardecer", ["<new>", "time=sunset", "<ent>", "type=skateboard", "color=black", "n=2"]], ["y un tren negro saludando", ["<edit>", "<add>", "type=train", "color=black", "act=wave"]], ["a large airplane is asleep with falling snow", ["<new>", "weather=snow", "<ent>", "type=plane", "size=big", "act=sleep"]], ["an animation of three red bears", ["<new>", "<ent>", "type=bear", "color=red", "n=3"]], ["enlarge the astronaut and then i want the ghost very small", ["<edit>", "<set>", "type=astronaut", "size=up", "<set>", "type=ghost", "size=tiny"]], ["en u estudio, un árbl plateado", ["<new>", "loc=studio", "<ent>", "type=tree", "color=silver"]], ["un cohete.", ["<new>", "<ent>", "type=rocket"]], ["a silverr ghost trembling long shot, at sunrise", ["<new>", "time=dawn", "shot=wide", "<ent>", "type=ghost", "color=silver", "act=shake"]], ["qué es las sombras?", ["<qa>", "lang=es", "topic=shadow"]], ["what actions do you know?", ["<qa>", "lang=en", "topic=actions"]]]
tests/shot.mjs ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Opens the app in headless Chromium, runs prompts and saves screenshots.
2
+ // node tests/shot.mjs <out-dir> "name=prompt one;prompt two@t" ...
3
+ import fs from 'node:fs';
4
+ import http from 'node:http';
5
+ import path from 'node:path';
6
+ import { chromium } from 'playwright-core';
7
+
8
+ const WEB = new URL('../web/', import.meta.url).pathname;
9
+ const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.bin': 'application/octet-stream' };
10
+ const server = http.createServer((req, res) => {
11
+ const f = path.join(WEB, decodeURIComponent(req.url.split('?')[0]).replace(/\/$/, '/index.html'));
12
+ if (!f.startsWith(WEB) || !fs.existsSync(f)) { res.writeHead(404); return res.end(); }
13
+ res.writeHead(200, { 'content-type': MIME[path.extname(f)] ?? 'application/octet-stream' });
14
+ fs.createReadStream(f).pipe(res);
15
+ }).listen(0);
16
+ const port = server.address().port;
17
+
18
+ const [out, ...jobs] = process.argv.slice(2);
19
+ fs.mkdirSync(out, { recursive: true });
20
+ const exe = process.env.CHROME ?? fs.readdirSync(`${process.env.HOME}/.cache/ms-playwright`).filter((d) => d.startsWith('chromium_headless_shell'))
21
+ .map((d) => `${process.env.HOME}/.cache/ms-playwright/${d}`).flatMap((d) => fs.readdirSync(d).flatMap((s) => [`${d}/${s}/chrome-headless-shell`, `${d}/${s}/headless_shell`])).find((p) => fs.existsSync(p));
22
+ const browser = await chromium.launch({ executablePath: exe, args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
23
+ const size = process.env.SIZE?.split('x').map(Number) ?? [1280, 760];
24
+ const page = await browser.newPage({ viewport: { width: size[0], height: size[1] } });
25
+ const errors = [];
26
+ page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
27
+ page.on('pageerror', (e) => errors.push(String(e)));
28
+
29
+ for (const job of jobs) {
30
+ const [name, rest] = job.split(/=(.*)/s), [q, t = '2.5'] = rest.split('@');
31
+ await page.goto(`http://localhost:${port}/?q=${encodeURIComponent(q)}&t=${t}`);
32
+ await page.waitForFunction(() => window.tinyScene?.ready, null, { timeout: 60000 }).catch(async () => {
33
+ console.log('NOT READY', await page.evaluate(() => document.getElementById('status')?.textContent), errors);
34
+ process.exit(1);
35
+ });
36
+ await page.waitForTimeout(700);
37
+ const info = await page.evaluate(() => ({ scene: window.tinyScene.scene, log: [...document.querySelectorAll('.msg.bot')].map((m) => m.innerText.replace(/\n+/g, ' | ')).slice(1) }));
38
+ await page.screenshot({ path: `${out}/${name}.png` });
39
+ console.log(name, '->', info.log.join(' || '));
40
+ }
41
+ if (errors.length) console.log('PAGE ERRORS:\n' + [...new Set(errors)].join('\n'));
42
+ await browser.close();
43
+ server.close();
web/index.html ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="es">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Tiny Scene</title>
7
+ <link rel="stylesheet" href="./style.css">
8
+ <script type="importmap">
9
+ { "imports": { "three": "./vendor/three.module.js", "three/addons/": "./vendor/addons/" } }
10
+ </script>
11
+ </head>
12
+ <body>
13
+ <main id="app">
14
+ <section id="view">
15
+ <canvas id="canvas"></canvas>
16
+ <div id="state" aria-live="polite"></div>
17
+ <div id="tools">
18
+ <button id="pause" title="Pausar o reanudar la animación">Pausa</button>
19
+ <button id="recenter" title="Volver al encuadre de la escena">Reencuadrar</button>
20
+ <button id="export" title="Descargar la escena como archivo .glb">Exportar .glb</button>
21
+ <button id="clear" title="Vaciar la escena">Vaciar</button>
22
+ </div>
23
+ </section>
24
+ <aside id="panel">
25
+ <header>
26
+ <h1>Tiny Scene</h1>
27
+ <p id="status">Cargando el modelo…</p>
28
+ </header>
29
+ <div id="log" aria-live="polite"></div>
30
+ <div id="examples"></div>
31
+ <form id="form" autocomplete="off">
32
+ <input id="prompt" type="text" placeholder="Describe una escena o pide un cambio…" maxlength="160" disabled>
33
+ <button id="send" type="submit" disabled>Enviar</button>
34
+ </form>
35
+ </aside>
36
+ </main>
37
+ <script type="module" src="./js/main.js"></script>
38
+ </body>
39
+ </html>
web/js/lang/scenelang.js ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Scene language: tokens from the model -> a scene description, or edits applied to the current one.
2
+
3
+ export const emptyScene = () => ({ loc: 'studio', time: 'day', weather: 'clear', shot: 'medium', cam: 'static', zoom: 0, ents: [], nextId: 1 });
4
+
5
+ const ENT_KEYS = new Set(['type', 'color', 'size', 'n', 'act', 'spd', 'rel']);
6
+ const SIZES = ['tiny', 'small', 'normal', 'big', 'giant'];
7
+
8
+ /** ['<new>', 'loc=beach', '<ent>', 'type=dog', ...] -> { kind, ... } */
9
+ export function parse(tokens) {
10
+ const head = tokens[0];
11
+ if (head === '<qa>') {
12
+ const kv = Object.fromEntries(tokens.slice(1).filter((t) => t.includes('=')).map((t) => t.split('=')));
13
+ return { kind: 'qa', lang: kv.lang ?? 'es', topic: kv.topic ?? 'help' };
14
+ }
15
+ if (head !== '<new>' && head !== '<edit>') return { kind: 'unknown' };
16
+ const blocks = [{ op: head, attrs: {} }];
17
+ for (const t of tokens.slice(1)) {
18
+ if (t.startsWith('<')) blocks.push({ op: t.slice(1, -1), attrs: {} });
19
+ else if (t.includes('=')) { const [k, v] = t.split('='); blocks[blocks.length - 1].attrs[k] = v; }
20
+ }
21
+ if (head === '<edit>') return { kind: 'edit', ops: blocks.slice(1).filter((b) => ['set', 'add', 'del', 'env', 'cam'].includes(b.op)) };
22
+
23
+ const scene = emptyScene();
24
+ for (const k of ['loc', 'time', 'weather', 'shot', 'cam']) if (blocks[0].attrs[k]) scene[k] = blocks[0].attrs[k];
25
+ for (const b of blocks.slice(1)) if (b.op === 'ent' && b.attrs.type) addEntity(scene, b.attrs);
26
+ scene.ents.forEach((e, i) => {
27
+ const next = scene.ents[i + 1];
28
+ if (e.rel && next) e.ref = next.id; else delete e.rel;
29
+ });
30
+ return { kind: 'new', scene };
31
+ }
32
+
33
+ function addEntity(scene, attrs) {
34
+ const e = { id: 'e' + scene.nextId++ };
35
+ for (const [k, v] of Object.entries(attrs)) if (ENT_KEYS.has(k)) e[k] = k === 'n' ? Number(v) : v;
36
+ if (e.spd === 'normal') delete e.spd;
37
+ scene.ents.push(e);
38
+ return e;
39
+ }
40
+
41
+ /** Returns { scene, notes } where notes lists what could not be applied. The input scene is not modified. */
42
+ export function applyEdit(current, ops) {
43
+ const scene = structuredClone(current), notes = [];
44
+ for (const { op, attrs } of ops) {
45
+ if (op === 'add') {
46
+ if (attrs.type && attrs.type !== 'it' && attrs.type !== 'all') addEntity(scene, attrs);
47
+ } else if (op === 'env') {
48
+ for (const k of ['loc', 'time', 'weather']) if (attrs[k]) scene[k] = attrs[k];
49
+ } else if (op === 'cam') {
50
+ if (attrs.shot === 'in') scene.zoom = Math.max(-4, scene.zoom - 1);
51
+ else if (attrs.shot === 'out') scene.zoom = Math.min(4, scene.zoom + 1);
52
+ else if (attrs.shot) { scene.shot = attrs.shot; scene.zoom = 0; }
53
+ if (attrs.cam) scene.cam = attrs.cam;
54
+ } else {
55
+ const t = attrs.type;
56
+ const hit = t === 'all' ? [...scene.ents] : t === 'it' ? scene.ents.slice(-1) : scene.ents.filter((e) => e.type === t);
57
+ if (!hit.length) { notes.push({ code: scene.ents.length ? 'missing' : 'empty', type: t }); continue; }
58
+ if (op === 'del') {
59
+ const gone = new Set(hit.map((e) => e.id));
60
+ scene.ents = scene.ents.filter((e) => !gone.has(e.id));
61
+ for (const e of scene.ents) if (gone.has(e.ref)) { delete e.rel; delete e.ref; }
62
+ } else {
63
+ for (const e of hit) {
64
+ if (attrs.color) e.color = attrs.color;
65
+ if (attrs.act) e.act = attrs.act;
66
+ if (attrs.n) e.n = Number(attrs.n);
67
+ if (attrs.spd) attrs.spd === 'normal' ? delete e.spd : (e.spd = attrs.spd);
68
+ if (attrs.size === 'up' || attrs.size === 'down') {
69
+ const i = Math.min(4, Math.max(0, SIZES.indexOf(e.size ?? 'normal') + (attrs.size === 'up' ? 1 : -1)));
70
+ i === 2 ? delete e.size : (e.size = SIZES[i]);
71
+ } else if (attrs.size) e.size = attrs.size;
72
+ }
73
+ }
74
+ }
75
+ }
76
+ return { scene, notes };
77
+ }
78
+
79
+ /** One-line description of an edit op, for the chat log. */
80
+ export const opText = ({ op, attrs }) => `${op} ${Object.entries(attrs).map(([k, v]) => `${k}=${v}`).join(' ')}`;
web/js/main.js ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Glue: prompt -> model -> scene language -> three.js scene.
2
+ import { applyEdit, emptyScene, parse } from './lang/scenelang.js';
3
+ import { TinyGPT } from './nn/model.js';
4
+ import { Stage } from './scene/stage.js';
5
+
6
+ const $ = (id) => document.getElementById(id);
7
+ const log = $('log'), input = $('prompt'), send = $('send'), status = $('status');
8
+ const params = new URLSearchParams(location.search);
9
+
10
+ const EXAMPLES = [
11
+ 'un zorro rojo saltando sobre un coche azul en el desierto al atardecer',
12
+ 'an alien riding a horse on the moon',
13
+ 'a robot dancing on a skateboard in the city at night',
14
+ 'tres pingüinos caminando en la nieve mientras nieva',
15
+ 'un dragón volando sobre una torre con tormenta',
16
+ 'haz el zorro verde', 'añade un árbol gigante', 'que llueva', 'aleja la cámara', 'gira la cámara',
17
+ '¿qué puedes hacer?',
18
+ ];
19
+ const LABEL = { loc: 'lugar', time: 'hora', weather: 'clima', shot: 'plano', cam: 'cámara' };
20
+
21
+ const stage = new Stage($('canvas'));
22
+ let scene = emptyScene(), model = null, qa = {};
23
+ const history = [];
24
+ let hpos = 0;
25
+ stage.setScene(scene);
26
+
27
+ function el(tag, cls, text) {
28
+ const e = document.createElement(tag);
29
+ if (cls) e.className = cls;
30
+ if (text != null) e.textContent = text;
31
+ return e;
32
+ }
33
+ function say(kind, build) {
34
+ const m = el('div', 'msg ' + kind);
35
+ build(m);
36
+ log.append(m);
37
+ log.scrollTop = log.scrollHeight;
38
+ return m;
39
+ }
40
+ function tokenRow(tokens) {
41
+ const row = el('div', 'tokens');
42
+ for (const t of tokens) row.append(el('code', t.startsWith('<') ? 's' : '', t));
43
+ return row;
44
+ }
45
+ function showState() {
46
+ const box = $('state');
47
+ box.replaceChildren();
48
+ for (const k of ['loc', 'time', 'weather', 'shot', 'cam']) {
49
+ const s = el('span');
50
+ s.append(el('b', '', LABEL[k]), scene[k]);
51
+ box.append(s);
52
+ }
53
+ for (const e of scene.ents) {
54
+ const s = el('span');
55
+ s.append(el('b', '', (e.n > 1 ? e.n + '× ' : '') + e.type), [e.color, e.size, e.act, e.spd, e.rel && `${e.rel}→`].filter(Boolean).join(' ') || '·');
56
+ box.append(s);
57
+ }
58
+ }
59
+
60
+ function run(text) {
61
+ const { tokens, ms } = model.generate(text);
62
+ const res = parse(tokens), notes = [];
63
+ let answer = null;
64
+ if (res.kind === 'new') {
65
+ scene = res.scene;
66
+ stage.setScene(scene, true);
67
+ } else if (res.kind === 'edit' && res.ops.length) {
68
+ const out = applyEdit(scene, res.ops);
69
+ for (const n of out.notes) notes.push(n.code === 'empty' ? 'La escena está vacía; describe primero una escena.' : `No hay ningún «${n.type}» en la escena.`);
70
+ scene = out.scene;
71
+ stage.setScene(scene, false);
72
+ } else if (res.kind === 'qa') {
73
+ answer = qa[res.topic]?.[res.lang] ?? qa.help?.es;
74
+ } else {
75
+ notes.push('No entendí la petición. Prueba con una frase más simple.');
76
+ }
77
+ showState();
78
+ say('bot', (m) => {
79
+ m.append(tokenRow(tokens));
80
+ if (answer) m.append(el('p', '', answer));
81
+ for (const n of notes) m.append(el('p', 'note', n));
82
+ m.append(el('div', 'meta', `${tokens.length} tokens · ${ms.toFixed(0)} ms`));
83
+ });
84
+ return { tokens, ms, kind: res.kind, notes };
85
+ }
86
+
87
+ function submit(text) {
88
+ text = text.trim();
89
+ if (!text || !model) return null;
90
+ history.push(text);
91
+ hpos = history.length;
92
+ say('user', (m) => { m.textContent = text; });
93
+ return run(text);
94
+ }
95
+
96
+ $('form').addEventListener('submit', (ev) => {
97
+ ev.preventDefault();
98
+ const text = input.value;
99
+ input.value = '';
100
+ send.disabled = true;
101
+ setTimeout(() => { submit(text); send.disabled = false; input.focus(); }, 15);
102
+ });
103
+ input.addEventListener('keydown', (ev) => {
104
+ if (ev.key === 'ArrowUp' && hpos > 0) { input.value = history[--hpos]; ev.preventDefault(); }
105
+ else if (ev.key === 'ArrowDown' && hpos < history.length) { input.value = history[++hpos] ?? ''; ev.preventDefault(); }
106
+ });
107
+ for (const ex of EXAMPLES) {
108
+ const b = el('button', '', ex);
109
+ b.type = 'button';
110
+ b.addEventListener('click', () => submit(ex));
111
+ $('examples').append(b);
112
+ }
113
+ $('pause').addEventListener('click', (ev) => { stage.paused = !stage.paused; ev.target.textContent = stage.paused ? 'Reanudar' : 'Pausa'; });
114
+ $('recenter').addEventListener('click', () => stage.frameCamera());
115
+ $('clear').addEventListener('click', () => { scene = emptyScene(); stage.setScene(scene, true); showState(); });
116
+ $('export').addEventListener('click', async () => {
117
+ const blob = await stage.exportGLB(), a = el('a');
118
+ a.href = URL.createObjectURL(blob);
119
+ a.download = 'tiny-scene.glb';
120
+ a.click();
121
+ setTimeout(() => URL.revokeObjectURL(a.href), 2000);
122
+ });
123
+
124
+ showState();
125
+ say('bot', (m) => m.append(el('p', 'hint', 'Describe una escena en español o inglés. Después puedes pedir cambios: colores, tamaños, acciones, clima, lugar o cámara. Arrastra para mover la vista.')));
126
+
127
+ try {
128
+ [model, qa] = await Promise.all([TinyGPT.load('./model/'), fetch('./model/qa.json').then((r) => r.json())]);
129
+ const mt = model.meta.meta ?? {};
130
+ status.textContent = `Modelo de ${(mt.params / 1e6).toFixed(2)} M de parámetros, corriendo en tu navegador.`;
131
+ input.disabled = send.disabled = false;
132
+ input.focus();
133
+ // ?q=prompt one;prompt two and ?t=seconds (freeze time) make the page scriptable for demos and tests
134
+ for (const q of (params.get('q') ?? '').split(';')) submit(q);
135
+ if (params.has('t')) { stage.t = Number(params.get('t')); stage.paused = true; if (scene.cam !== 'static') stage.frameCamera(); }
136
+ window.tinyScene = { model, stage, submit, get scene() { return scene; }, ready: true };
137
+ } catch (err) {
138
+ status.textContent = 'No se pudo cargar el modelo: ' + err.message;
139
+ }
web/js/nn/model.js ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The Transformer from ml/model.py, in plain JavaScript (no dependencies). Greedy decoding with a key/value cache.
2
+
3
+ function halfToFloat(u16) {
4
+ const out = new Float32Array(u16.length);
5
+ for (let i = 0; i < u16.length; i++) {
6
+ const h = u16[i], e = (h >> 10) & 31, f = h & 1023, s = h & 0x8000 ? -1 : 1;
7
+ out[i] = e === 0 ? s * f * 5.960464477539063e-8 : e === 31 ? (f ? NaN : s * Infinity) : s * (1 + f / 1024) * 2 ** (e - 15);
8
+ }
9
+ return out;
10
+ }
11
+
12
+ export class TinyGPT {
13
+ /** meta: parsed model.json, buffer: ArrayBuffer of weights.bin */
14
+ constructor(meta, buffer) {
15
+ this.meta = meta;
16
+ Object.assign(this, meta.config);
17
+ this.vocabList = meta.vocab;
18
+ this.id = new Map(meta.vocab.map((t, i) => [t, i]));
19
+ const all = meta.dtype === 'float16' ? halfToFloat(new Uint16Array(buffer)) : new Float32Array(buffer);
20
+ this.w = {};
21
+ for (const t of meta.tensors) this.w[t.name] = all.subarray(t.offset, t.offset + t.shape.reduce((a, b) => a * b, 1));
22
+ const d = this.d;
23
+ this.kc = Array.from({ length: this.layers }, () => new Float32Array(this.ctx * d));
24
+ this.vc = Array.from({ length: this.layers }, () => new Float32Array(this.ctx * d));
25
+ this.x = new Float32Array(d); this.h = new Float32Array(d); this.qkv = new Float32Array(3 * d);
26
+ this.att = new Float32Array(d); this.tmp = new Float32Array(d); this.ff = new Float32Array(4 * d);
27
+ this.sc = new Float32Array(this.ctx);
28
+ }
29
+
30
+ static async load(base = './model/') {
31
+ const [meta, buf] = await Promise.all([
32
+ fetch(base + 'model.json').then((r) => r.json()),
33
+ fetch(base + 'weights.bin').then((r) => r.arrayBuffer()),
34
+ ]);
35
+ return new TinyGPT(meta, buf);
36
+ }
37
+
38
+ normalize(text) {
39
+ let s = '';
40
+ for (const c of text.toLowerCase().replace(/’/g, "'")) if (c.length === 1 && this.id.has(c) && this.id.get(c) < 4 + 64) s += c;
41
+ return s.replace(/\s+/g, ' ').trim().slice(0, this.meta.max_prompt);
42
+ }
43
+
44
+ encode(text) {
45
+ const { bos, sep } = this.meta.special;
46
+ return [bos, ...[...this.normalize(text)].map((c) => this.id.get(c)), sep];
47
+ }
48
+
49
+ _linear(W, b, x, y, nOut, nIn) {
50
+ for (let o = 0, k = 0; o < nOut; o++) {
51
+ let s = b[o];
52
+ for (let i = 0; i < nIn; i++, k++) s += W[k] * x[i];
53
+ y[o] = s;
54
+ }
55
+ }
56
+
57
+ _norm(x, y, g, b) {
58
+ const d = this.d;
59
+ let m = 0, v = 0;
60
+ for (let i = 0; i < d; i++) m += x[i];
61
+ m /= d;
62
+ for (let i = 0; i < d; i++) { const c = x[i] - m; v += c * c; }
63
+ const inv = 1 / Math.sqrt(v / d + 1e-5);
64
+ for (let i = 0; i < d; i++) y[i] = (x[i] - m) * inv * g[i] + b[i];
65
+ }
66
+
67
+ /** Feed one token at position t; returns the hidden state (valid until the next call). */
68
+ _step(tok, t) {
69
+ const { d, heads, w, x, h, qkv, att, tmp, ff, sc } = this, dh = d / heads, scale = 1 / Math.sqrt(dh);
70
+ const te = w['tok.weight'], pe = w['pos.weight'];
71
+ for (let i = 0; i < d; i++) x[i] = te[tok * d + i] + pe[t * d + i];
72
+ for (let l = 0; l < this.layers; l++) {
73
+ const p = `blocks.${l}.`, K = this.kc[l], V = this.vc[l];
74
+ this._norm(x, h, w[p + 'ln1.weight'], w[p + 'ln1.bias']);
75
+ this._linear(w[p + 'qkv.weight'], w[p + 'qkv.bias'], h, qkv, 3 * d, d);
76
+ K.set(qkv.subarray(d, 2 * d), t * d);
77
+ V.set(qkv.subarray(2 * d), t * d);
78
+ for (let hd = 0; hd < heads; hd++) {
79
+ const o = hd * dh;
80
+ let mx = -Infinity;
81
+ for (let j = 0; j <= t; j++) {
82
+ let s = 0;
83
+ for (let i = 0, kb = j * d + o; i < dh; i++) s += qkv[o + i] * K[kb + i];
84
+ sc[j] = s *= scale;
85
+ if (s > mx) mx = s;
86
+ }
87
+ let z = 0;
88
+ for (let j = 0; j <= t; j++) z += sc[j] = Math.exp(sc[j] - mx);
89
+ for (let i = 0; i < dh; i++) att[o + i] = 0;
90
+ for (let j = 0; j <= t; j++) {
91
+ const pj = sc[j] / z;
92
+ for (let i = 0, vb = j * d + o; i < dh; i++) att[o + i] += pj * V[vb + i];
93
+ }
94
+ }
95
+ this._linear(w[p + 'proj.weight'], w[p + 'proj.bias'], att, tmp, d, d);
96
+ for (let i = 0; i < d; i++) x[i] += tmp[i];
97
+ this._norm(x, h, w[p + 'ln2.weight'], w[p + 'ln2.bias']);
98
+ this._linear(w[p + 'fc1.weight'], w[p + 'fc1.bias'], h, ff, 4 * d, d);
99
+ for (let i = 0; i < 4 * d; i++) { const v = ff[i]; ff[i] = 0.5 * v * (1 + Math.tanh(0.7978845608028654 * (v + 0.044715 * v * v * v))); }
100
+ this._linear(w[p + 'fc2.weight'], w[p + 'fc2.bias'], ff, tmp, d, 4 * d);
101
+ for (let i = 0; i < d; i++) x[i] += tmp[i];
102
+ }
103
+ this._norm(x, h, w['ln_f.weight'], w['ln_f.bias']);
104
+ return h;
105
+ }
106
+
107
+ _argmax(h) {
108
+ const te = this.w['tok.weight'], d = this.d;
109
+ let best = -Infinity, arg = 0;
110
+ for (let v = 0, k = 0; v < this.vocab; v++) {
111
+ let s = 0;
112
+ for (let i = 0; i < d; i++, k++) s += te[k] * h[i];
113
+ if (s > best) { best = s; arg = v; }
114
+ }
115
+ return arg;
116
+ }
117
+
118
+ /** text -> { tokens: ['<new>', 'loc=beach', ...], ms } */
119
+ generate(text, maxNew = 40) {
120
+ const t0 = performance.now(), ids = this.encode(text), out = [];
121
+ let h, t = 0;
122
+ for (const id of ids) h = this._step(id, t++);
123
+ while (out.length < maxNew && t < this.ctx) {
124
+ const next = this._argmax(h);
125
+ if (next === this.meta.special.eos) break;
126
+ out.push(this.vocabList[next]);
127
+ h = this._step(next, t++);
128
+ }
129
+ return { tokens: out, ms: performance.now() - t0 };
130
+ }
131
+ }
web/js/scene/animate.js ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Procedural animation: every pose is a pure function of time, so nothing drifts and any frame can be rebuilt.
2
+ import * as THREE from 'three';
3
+
4
+ const { sin, cos, abs, PI, min, max, floor, atan2, sqrt } = Math;
5
+ const clamp = (v, a, b) => min(b, max(a, v));
6
+ const smooth = (u) => u * u * (3 - 2 * u);
7
+
8
+ export const SPEED = { walk: 1.5, run: 4.2, drive: 5.5, swim: 1.7, roll: 2.4, circle: 1.6, fly: 4.0, jump: 1.6, dance: 1.2 };
9
+ export const LOCO = new Set(['walk', 'run', 'drive', 'swim', 'roll']);
10
+ export const SPD_MUL = { slow: 0.45, fast: 2.0 };
11
+
12
+ export function speedOf(inst, act) {
13
+ const f = clamp(sqrt((inst.rig.h * inst.scale) / 1.3), 0.55, 2.2);
14
+ return (SPEED[act] ?? 1.5) * f;
15
+ }
16
+
17
+ // ------------------------------------------------------------------ paths
18
+ function path(inst, T, s) {
19
+ const mo = inst.motion;
20
+ if (mo.kind === 'patrol') {
21
+ const leg = (2 * mo.A) / mo.v, tt = 0.7, P = 2 * (leg + tt);
22
+ let u = (T + leg / 2) % P;
23
+ if (u < leg) { s.x += -mo.A + mo.v * u; s.yaw = PI / 2; }
24
+ else if (u < leg + tt) { s.x += mo.A; s.yaw = PI / 2 - PI * smooth((u - leg) / tt); }
25
+ else if (u < 2 * leg + tt) { s.x += mo.A - mo.v * (u - leg - tt); s.yaw = -PI / 2; }
26
+ else { s.x -= mo.A; s.yaw = -PI / 2 + PI * smooth((u - 2 * leg - tt) / tt); }
27
+ s.dist = mo.v * T;
28
+ } else if (mo.kind === 'circle') {
29
+ const a = mo.ph + (mo.v / mo.R) * T;
30
+ s.x = mo.cx + inst.off.x + mo.R * cos(a);
31
+ s.z = mo.cz + inst.off.z + mo.R * sin(a);
32
+ s.yaw = atan2(-sin(a), cos(a));
33
+ s.dist = mo.v * T;
34
+ } else if (mo.kind === 'fly') {
35
+ if (inst.rig.vertical) {
36
+ s.y += mo.alt * (0.55 + 0.45 * sin(T * 0.8));
37
+ s.x += sin(T * 0.5) * 0.6;
38
+ } else {
39
+ const a = mo.ph + mo.w * T;
40
+ s.x = mo.cx + inst.off.x + mo.Rx * cos(a);
41
+ s.z = mo.cz + inst.off.z + mo.Rz * sin(a);
42
+ s.yaw = atan2(-mo.Rx * sin(a), mo.Rz * cos(a));
43
+ s.y += mo.alt + sin(T * 1.3) * 0.25;
44
+ s.roll = inst.rig.floaty ? 0 : 0.28;
45
+ }
46
+ s.dist = 4 * T;
47
+ } else if (mo.kind === 'hopover') {
48
+ const k = floor(T / mo.P), u = T / mo.P - k, dir = k % 2 ? -1 : 1;
49
+ if (u < 0.62) {
50
+ const a = u / 0.62;
51
+ s.x = mo.cx + inst.off.x + dir * (-mo.d + 2 * mo.d * a);
52
+ s.y += mo.H * 4 * a * (1 - a);
53
+ s.yaw = dir * PI / 2;
54
+ s.air = a;
55
+ } else {
56
+ s.x = mo.cx + inst.off.x + dir * mo.d;
57
+ s.yaw = dir * (PI / 2) * (1 - 2 * smooth((u - 0.62) / 0.38));
58
+ s.air = -1;
59
+ }
60
+ s.z = mo.cz + inst.off.z;
61
+ }
62
+ }
63
+
64
+ // ------------------------------------------------------------------ gaits
65
+ function gait(g, ph, amp, run, dist) {
66
+ const b = g.body, L = g.legs, A = g.arms, s1 = sin(ph);
67
+ if (g.kind === 'quad') {
68
+ if (run) {
69
+ L[0].rotation.x += s1 * amp; L[1].rotation.x += sin(ph + 0.4) * amp;
70
+ L[2].rotation.x += sin(ph + 2.4) * amp; L[3].rotation.x += sin(ph + 2.8) * amp;
71
+ b.rotation.x += sin(ph + 1) * 0.07;
72
+ b.position.y += (1 - cos(ph)) * 0.06 * g.leg;
73
+ } else {
74
+ L[0].rotation.x += s1 * amp; L[3].rotation.x += s1 * amp;
75
+ L[1].rotation.x -= s1 * amp; L[2].rotation.x -= s1 * amp;
76
+ b.position.y += (1 - cos(2 * ph)) * 0.02 * g.leg;
77
+ }
78
+ if (g.head) g.head.rotation.x += sin(2 * ph) * 0.04;
79
+ if (g.tail) g.tail.rotation.z += sin(ph) * 0.25;
80
+ } else if (g.kind === 'biped') {
81
+ L[0].rotation.x += s1 * amp; L[1].rotation.x -= s1 * amp;
82
+ if (A) { A[0].rotation.x -= s1 * amp * 0.8; A[1].rotation.x += s1 * amp * 0.8; }
83
+ b.position.y += (1 - cos(2 * ph)) * 0.025 * g.leg;
84
+ if (run) b.rotation.x += 0.16;
85
+ if (g.tail) g.tail.rotation.y += sin(ph) * 0.2;
86
+ } else if (g.kind === 'bird') {
87
+ L[0].rotation.x += s1 * amp; L[1].rotation.x -= s1 * amp;
88
+ if (g.upright) b.rotation.z += s1 * 0.13;
89
+ else if (g.head) g.head.position.z += sin(2 * ph) * 0.03;
90
+ b.position.y += abs(s1) * 0.02;
91
+ } else if (g.kind === 'fish') {
92
+ g.tail.rotation.y += sin(ph * 1.4) * 0.55;
93
+ b.rotation.y += sin(ph * 1.4 - 1) * 0.12;
94
+ } else if (g.kind === 'vehicle') {
95
+ const r = g.board ? 0.06 : 0.36;
96
+ if (g.wheels) for (const w of g.wheels) w.rotation.x += dist / r;
97
+ else b.rotation.z += sin(ph * 0.5) * 0.03;
98
+ } else {
99
+ b.rotation.z += s1 * 0.1;
100
+ b.position.y += abs(s1) * 0.07 * g.h;
101
+ if (A) { A[0].rotation.x += s1 * 0.5; A[1].rotation.x -= s1 * 0.5; }
102
+ }
103
+ }
104
+
105
+ /** Rotate `body` by `a` around the X axis through its centre, keeping that centre at height c2. */
106
+ function tumble(g, a, c2) {
107
+ const c = g.h / 2;
108
+ g.body.rotation.x += a;
109
+ g.body.position.y += c2 - c * cos(a);
110
+ g.body.position.z += -c * sin(a);
111
+ }
112
+
113
+ function flap(g, T, rate, amp) {
114
+ if (!g.wings) return false;
115
+ g.wings.forEach((w, i) => {
116
+ const sx = i ? -1 : 1;
117
+ if (g.kind === 'bird' && !g.upright) w.rotation.z = sx * sin(T * rate) * amp;
118
+ else w.rotation.z += sx * sin(T * rate) * amp;
119
+ });
120
+ return true;
121
+ }
122
+
123
+ // ------------------------------------------------------------------ poses
124
+ const POSE = {
125
+ idle(i, g, T, s) {
126
+ g.body.scale.y *= 1 + sin(T * 2) * 0.012;
127
+ if (g.tail && g.kind !== 'fish') g.tail.rotation.z += sin(T * 3) * 0.18;
128
+ if (g.head && g.kind !== 'prop') g.head.rotation.y += sin(T * 0.7) * 0.25;
129
+ if (g.sway) g.head.rotation.z += sin(T * 1.1) * 0.035;
130
+ if (g.kind === 'fish') { g.tail.rotation.y += sin(T * 3) * 0.3; s.y += sin(T * 1.2) * 0.06; }
131
+ if (g.floaty) { s.y += (g.hover ?? 0.3) * 0.5 + sin(T * 1.4) * 0.12; s.roll += sin(T * 0.9) * 0.04; }
132
+ if (g.trunk) g.trunk.rotation.x += sin(T * 1.3) * 0.12;
133
+ },
134
+ move(i, g, T, s, act) {
135
+ const stride = max(0.22, (g.leg ?? g.h * 0.35) * i.scale * 1.25);
136
+ const ph = (s.dist / stride) * (act === 'run' ? 0.8 : 1);
137
+ gait(g, ph, act === 'run' ? 0.85 : act === 'swim' ? 0.35 : 0.5, act === 'run', s.dist / i.scale);
138
+ if (g.kind === 'fish') s.y += sin(T * 1.2) * 0.06;
139
+ },
140
+ swim(i, g, T, s) {
141
+ POSE.move(i, g, T, s, 'swim');
142
+ if (g.kind === 'biped' && g.arms) {
143
+ g.body.rotation.x += 1.2;
144
+ g.body.position.y += g.leg * 0.25;
145
+ g.arms[0].rotation.x += PI + T * 5;
146
+ g.arms[1].rotation.x += T * 5;
147
+ }
148
+ if (!s.water) s.y += g.kind === 'fish' ? 0 : 0.2;
149
+ s.yaw += sin(T * 3) * 0.08;
150
+ },
151
+ roll(i, g, T, s) {
152
+ if (g.roller) { g.roller.rotation.x += s.dist / i.scale / g.round; return; }
153
+ if (g.kind === 'vehicle' && g.wheels) { gait(g, 0, 0, false, s.dist / i.scale); return; }
154
+ tumble(g, s.dist / i.scale / max(0.4, g.h * 0.5), max(g.h / 2, g.r * 0.75));
155
+ },
156
+ jump(i, g, T, s) {
157
+ let a = s.air;
158
+ if (a == null) {
159
+ const u = (T * 0.9) % 1;
160
+ a = u < 0.62 ? u / 0.62 : -1;
161
+ if (a >= 0) s.y += clamp(g.h * 0.8, 0.5, 2.2) * i.scale * 4 * a * (1 - a);
162
+ }
163
+ if (a < 0) { g.body.scale.y *= 0.9; return; }
164
+ const k = sin(a * PI);
165
+ if (g.kind === 'quad') {
166
+ g.legs[0].rotation.x -= k * 0.9; g.legs[1].rotation.x -= k * 0.9;
167
+ g.legs[2].rotation.x += k * 0.9; g.legs[3].rotation.x += k * 0.9;
168
+ g.body.rotation.x += (a - 0.5) * 0.5;
169
+ } else if (g.kind === 'biped' || g.kind === 'bird') {
170
+ g.legs[0].rotation.x -= k * 0.7; g.legs[1].rotation.x += k * 0.5;
171
+ if (g.arms) { g.arms[0].rotation.z += k * 2.4; g.arms[1].rotation.z -= k * 2.4; }
172
+ flap(g, T, 18, 0.7);
173
+ } else {
174
+ g.body.scale.y *= 1 + k * 0.08;
175
+ }
176
+ },
177
+ spin(i, g, T, s) { s.yaw += T * 2.6; POSE.idle(i, g, T, s); },
178
+ dance(i, g, T, s) {
179
+ const b = T * 2 * PI * 1.5;
180
+ g.body.position.y += abs(sin(b / 2)) * 0.1 * g.h;
181
+ g.body.rotation.z += sin(b / 2) * 0.12;
182
+ s.yaw += sin(b / 4) * 0.55;
183
+ if (g.arms) {
184
+ g.arms[0].rotation.z += 2.3 + sin(b) * 0.5;
185
+ g.arms[1].rotation.z -= 2.3 + sin(b + PI) * 0.5;
186
+ }
187
+ if (g.kind === 'quad') {
188
+ g.legs[0].rotation.x -= max(0, sin(b / 2)) * 0.9;
189
+ g.legs[1].rotation.x -= max(0, -sin(b / 2)) * 0.9;
190
+ } else if (g.legs) {
191
+ g.legs[0].rotation.x -= max(0, sin(b / 2)) * 0.5;
192
+ g.legs[1].rotation.x -= max(0, -sin(b / 2)) * 0.5;
193
+ }
194
+ if (g.head && g.kind !== 'prop') g.head.rotation.z += sin(b / 2 + 1) * 0.16;
195
+ if (g.tail && g.kind !== 'fish') g.tail.rotation.z += sin(b) * 0.4;
196
+ flap(g, T, 9, 0.6);
197
+ },
198
+ fly(i, g, T, s) {
199
+ const winged = flap(g, T, g.kind === 'bird' ? 16 : 6, g.kind === 'bird' ? 0.75 : 0.5);
200
+ if (g.kind === 'quad' && !winged) {
201
+ g.legs[0].rotation.x -= 1.2; g.legs[1].rotation.x -= 1.2; g.legs[2].rotation.x += 1.2; g.legs[3].rotation.x += 1.2;
202
+ } else if (g.kind === 'quad') {
203
+ for (const l of g.legs) l.rotation.x += 0.5;
204
+ } else if (g.kind === 'biped' && g.arms) {
205
+ g.body.rotation.x += 1.2;
206
+ g.body.position.y += g.leg * 0.2;
207
+ g.arms[0].rotation.x += PI - 0.2; g.arms[1].rotation.x += 0.4;
208
+ g.legs[0].rotation.x += sin(T * 2) * 0.1;
209
+ } else if (g.kind === 'bird') {
210
+ for (const l of g.legs) l.rotation.x += 1.2;
211
+ }
212
+ if (g.flame) { g.flame.visible = true; g.flame.scale.y = 1 + sin(T * 40) * 0.2; }
213
+ if (g.tail && g.kind !== 'fish') g.tail.rotation.z += sin(T * 4) * 0.15;
214
+ },
215
+ float(i, g, T, s) {
216
+ s.y += 0.5 + 0.35 * g.h * i.scale + sin(T * 1.3) * 0.22;
217
+ s.yaw += T * 0.35;
218
+ s.roll += sin(T * 0.8) * 0.12;
219
+ s.pitch += sin(T * 0.6 + 1) * 0.1;
220
+ if (g.arms) { g.arms[0].rotation.z += 0.6 + sin(T) * 0.2; g.arms[1].rotation.z -= 0.6 + sin(T + 1) * 0.2; }
221
+ if (g.legs) g.legs.forEach((l, k) => { l.rotation.x += sin(T * 1.1 + k) * 0.2; });
222
+ flap(g, T, 3, 0.2);
223
+ },
224
+ sit(i, g, T, s) {
225
+ if (g.kind === 'quad') {
226
+ const phi = clamp(Math.asin(clamp((g.leg - 0.3 * g.bodyH) / (2 * g.hipZ), 0.1, 0.65)), 0.15, 0.7);
227
+ g.body.rotation.x -= phi;
228
+ g.body.position.y -= g.leg * cos(phi) - g.hipZ * sin(phi) - g.bodyH * 0.3;
229
+ g.legs[0].rotation.x += phi; g.legs[1].rotation.x += phi;
230
+ g.legs[2].rotation.x += phi - PI / 2; g.legs[3].rotation.x += phi - PI / 2;
231
+ if (g.head) g.head.rotation.x += phi * 0.7;
232
+ if (g.tail) g.tail.rotation.z += sin(T * 4) * 0.25;
233
+ } else if (g.kind === 'biped') {
234
+ g.legs[0].rotation.x -= PI / 2; g.legs[1].rotation.x -= PI / 2;
235
+ g.body.position.y -= g.leg - 0.12;
236
+ if (g.arms) { g.arms[0].rotation.x -= 0.5; g.arms[1].rotation.x -= 0.5; }
237
+ if (g.head) g.head.rotation.y += sin(T * 0.7) * 0.3;
238
+ } else if (g.kind === 'bird') {
239
+ for (const l of g.legs) l.rotation.x -= PI / 2;
240
+ g.body.position.y -= g.leg * 0.9;
241
+ } else {
242
+ g.body.scale.y *= 0.93;
243
+ }
244
+ },
245
+ sleep(i, g, T, s) {
246
+ const br = 1 + sin(T * 1.6) * 0.025;
247
+ if (g.kind === 'quad') {
248
+ g.body.position.y -= g.leg * 0.9;
249
+ for (const l of g.legs) l.rotation.x -= PI / 2;
250
+ if (g.head) { g.head.rotation.x += 0.6; g.head.rotation.z += 0.3; }
251
+ g.body.scale.y *= br;
252
+ } else if (g.kind === 'biped') {
253
+ g.body.rotation.x -= PI / 2;
254
+ g.body.position.y += 0.18;
255
+ g.body.position.z += g.h * 0.5;
256
+ g.body.scale.z *= br;
257
+ } else if (g.kind === 'bird') {
258
+ for (const l of g.legs) l.rotation.x -= PI / 2;
259
+ g.body.position.y -= g.leg * 0.9;
260
+ if (g.head) g.head.rotation.x += 0.5;
261
+ } else {
262
+ s.roll += g.kind === 'prop' || g.kind === 'vehicle' ? 0.06 : 0.25;
263
+ g.body.scale.y *= br;
264
+ }
265
+ i.zzz = true;
266
+ },
267
+ wave(i, g, T, s) {
268
+ const w = sin(T * 8) * 0.35;
269
+ if (g.arms) g.arms[1].rotation.z -= 2.5 + w;
270
+ else if (g.kind === 'quad') { g.legs[1].rotation.x -= 1.5 + w; g.body.rotation.x -= 0.06; }
271
+ else if (g.wings) g.wings[1].rotation.z -= 1.0 + w * 2;
272
+ else g.body.rotation.z += sin(T * 5) * 0.16;
273
+ if (g.head && g.kind !== 'prop') g.head.rotation.z += 0.12;
274
+ if (g.tail && g.kind !== 'fish') g.tail.rotation.z += sin(T * 6) * 0.3;
275
+ },
276
+ bounce(i, g, T, s) {
277
+ const H = clamp(g.h * 0.7, 0.5, 1.8) * i.scale, k = abs(sin(T * PI * 1.3));
278
+ s.y += H * k;
279
+ const sq = max(0, 1 - k * 6) * 0.22;
280
+ g.body.scale.y *= 1 - sq;
281
+ g.body.scale.x *= 1 + sq * 0.6;
282
+ g.body.scale.z *= 1 + sq * 0.6;
283
+ },
284
+ shake(i, g, T, s) {
285
+ g.body.rotation.z += sin(T * 41) * 0.06;
286
+ g.body.position.x += sin(T * 53) * 0.03 * g.h;
287
+ if (g.head && g.kind !== 'prop') g.head.rotation.y += sin(T * 37) * 0.1;
288
+ if (g.arms) { g.arms[0].rotation.z += 0.3 + sin(T * 45) * 0.1; g.arms[1].rotation.z -= 0.3 + sin(T * 47) * 0.1; }
289
+ },
290
+ };
291
+ POSE.walk = POSE.run = POSE.drive = POSE.circle = POSE.move;
292
+
293
+ function ridePose(i, g, T) {
294
+ if (g.kind === 'biped') {
295
+ g.legs[0].rotation.z += 0.5; g.legs[1].rotation.z -= 0.5;
296
+ g.legs[0].rotation.x -= 0.5; g.legs[1].rotation.x -= 0.5;
297
+ if (g.arms) { g.arms[0].rotation.x -= 0.7; g.arms[1].rotation.x -= 0.7; }
298
+ return -g.leg * 0.7;
299
+ }
300
+ if (g.kind === 'quad') { POSE.sit(i, g, T, {}); return 0; }
301
+ if (g.kind === 'bird') { for (const l of g.legs) l.rotation.x -= PI / 2; return -g.leg * 0.9; }
302
+ return 0;
303
+ }
304
+
305
+ // ------------------------------------------------------------------ per-frame update
306
+ const _s = {};
307
+ export function updateInstance(inst, t, ctx = {}) {
308
+ const g = inst.rig, o = inst.obj;
309
+ for (const p of g.all) {
310
+ const r = p.userData.rest;
311
+ p.position.copy(r.p); p.rotation.copy(r.r); p.scale.copy(r.s);
312
+ }
313
+ if (g.flame) g.flame.visible = false;
314
+ const T = t * inst.spdMul + inst.phase, act = inst.act;
315
+ const s = _s;
316
+ s.x = inst.base.x; s.y = inst.base.y; s.z = inst.base.z;
317
+ s.yaw = inst.yaw0; s.roll = 0; s.pitch = 0; s.dist = 0; s.air = null; s.water = false;
318
+ inst.zzz = false;
319
+
320
+ if (inst.mount) {
321
+ s.x = inst.seat[0]; s.y = inst.seat[1]; s.z = inst.seat[2]; s.yaw = 0;
322
+ if (inst.mode === 'ride') {
323
+ s.y += ridePose(inst, g, T) * (inst.scale / inst.mount.scale);
324
+ if (act === 'wave' || act === 'dance' || act === 'shake') POSE[act](inst, g, T, {});
325
+ } else {
326
+ const loco = { walk: 1, run: 1, drive: 1, circle: 1, swim: 1, roll: 0 }[act];
327
+ if (loco) { s.dist = speedOf(inst, act) * T; POSE.move(inst, g, T, s, act); }
328
+ else if (act === 'fly') { POSE.fly(inst, g, T, s); s.y += (0.4 + sin(T * 1.5) * 0.1) / inst.mount.scale; }
329
+ else if (act !== 'roll') {
330
+ const y0 = s.y;
331
+ (POSE[act] ?? POSE.idle)(inst, g, T, s, act);
332
+ s.y = y0 + (s.y - y0) / inst.mount.scale;
333
+ }
334
+ }
335
+ } else {
336
+ path(inst, T, s);
337
+ if (ctx.waterY != null && (g.swims || act === 'swim')) {
338
+ const sink = g.floats ? 0.1 : g.kind === 'fish' ? (g.hover + 0.05) * inst.scale
339
+ : g.kind === 'bird' ? (g.leg + 0.04) * inst.scale : g.h * inst.scale * 0.55;
340
+ if (act !== 'fly' && act !== 'jump' && act !== 'bounce' && act !== 'float') {
341
+ s.y = ctx.waterY - sink + sin(T * 1.5) * 0.05;
342
+ s.water = true;
343
+ s.roll += g.floats ? sin(T * 1.1) * 0.05 : 0;
344
+ }
345
+ }
346
+ (POSE[act] ?? POSE.idle)(inst, g, T, s, act);
347
+ if (inst.motion.kind !== 'none' && act !== 'idle' && !POSE[act]) POSE.move(inst, g, T, s, 'walk');
348
+ }
349
+ if (g.spinners) {
350
+ const on = act === 'fly' || act === 'drive' || LOCO.has(act) || inst.motion.kind !== 'none';
351
+ for (const sp of g.spinners) if (on || sp.userData.always) sp.rotation[sp.userData.axis] += T * (sp.userData.always && !on ? 2 : 24);
352
+ }
353
+ o.position.set(s.x, s.y, s.z);
354
+ o.rotation.set(s.pitch, s.yaw, s.roll);
355
+ if (inst.sprites) updateZzz(inst, T);
356
+ }
357
+
358
+ // ------------------------------------------------------------------ sleeping "z z z"
359
+ let zTex = null;
360
+ function zTexture() {
361
+ if (zTex || typeof document === 'undefined') return zTex;
362
+ const c = document.createElement('canvas');
363
+ c.width = c.height = 64;
364
+ const x = c.getContext('2d');
365
+ x.font = 'bold 54px sans-serif';
366
+ x.textAlign = 'center';
367
+ x.textBaseline = 'middle';
368
+ x.lineWidth = 6;
369
+ x.strokeStyle = '#1c2540';
370
+ x.strokeText('z', 32, 30);
371
+ x.fillStyle = '#ffffff';
372
+ x.fillText('z', 32, 30);
373
+ zTex = new THREE.CanvasTexture(c);
374
+ return zTex;
375
+ }
376
+ export function addZzz(inst) {
377
+ const tex = zTexture();
378
+ if (!tex) return;
379
+ inst.sprites = [0, 1, 2].map(() => {
380
+ const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, transparent: true, depthWrite: false }));
381
+ inst.obj.add(sp);
382
+ return sp;
383
+ });
384
+ }
385
+ function updateZzz(inst, T) {
386
+ const g = inst.rig;
387
+ inst.sprites.forEach((sp, k) => {
388
+ const u = (T * 0.35 + k / 3) % 1;
389
+ sp.visible = inst.zzz;
390
+ const m = clamp(g.h, 0.6, 2), y0 = g.kind === 'biped' ? 0.45 : g.h * 0.45;
391
+ sp.position.set(0.15 + u * 0.3 * m + sin(u * 6) * 0.06, y0 + u * (0.5 + 0.35 * m), g.kind === 'biped' ? -g.h * 0.2 : 0.25);
392
+ sp.scale.setScalar((0.1 + u * 0.16) * m);
393
+ sp.material.opacity = sin(u * PI);
394
+ });
395
+ }
web/js/scene/creatures.js ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Animals and characters, assembled from primitives. Forward is +Z, up is +Y, feet at y = 0.
2
+ import * as THREE from 'three';
3
+ import { at, ball, box, cone, cyl, eyes, joint, mat, orb, rig, tint, torus } from './prims.js';
4
+
5
+ const DARK = 0x26262b, WHITE = 0xf4f4f0, SKIN = 0xe9b991;
6
+
7
+ // ------------------------------------------------------------------ four-legged animals
8
+ function quad(s, C) {
9
+ const root = new THREE.Group(), body = new THREE.Group();
10
+ root.add(body);
11
+ const c2 = s.c2 ?? tint(C, -0.1), nw = s.nw ?? s.W * 0.6, top = s.leg + s.H;
12
+ body.add(at(box(s.W, s.H, s.L, C), 0, s.leg + s.H / 2, 0));
13
+ const legs = [];
14
+ for (const [sx, sz] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) {
15
+ const leg = joint(sx * (s.W / 2 - s.lw / 2), s.leg, sz * (s.L / 2 - s.lw * 0.7),
16
+ at(box(s.lw, s.leg, s.lw, s.legC ?? c2), 0, -s.leg / 2, 0));
17
+ if (s.hoof) leg.add(at(box(s.lw * 1.06, s.leg * 0.16, s.lw * 1.06, s.hoof), 0, -s.leg * 0.92, 0));
18
+ body.add(leg);
19
+ legs.push(leg);
20
+ }
21
+ const ny = Math.sin(s.na) * s.neck, nz = Math.cos(s.na) * s.neck;
22
+ const head = joint(0, top - s.H * 0.25, s.L / 2 - nw * 0.3);
23
+ if (s.neck > 0.05) head.add(at(box(nw, s.neck + nw * 0.6, nw, C), 0, ny / 2, nz / 2, Math.PI / 2 - s.na));
24
+ const hg = joint(0, ny, nz);
25
+ head.add(hg);
26
+ const [hw, hh, hl] = s.hd, hc = s.headC ?? C;
27
+ hg.add(at(box(hw, hh, hl, hc), 0, hh * 0.15, hl * 0.25));
28
+ if (s.snout) {
29
+ const [sw, sh, sl] = s.snout;
30
+ hg.add(at(box(sw, sh, sl, s.snoutC ?? tint(hc, 0.1)), 0, -hh * 0.14, hl * 0.75 + sl / 2 - 0.02),
31
+ at(box(sw * 0.45, sh * 0.4, 0.04, s.noseC ?? 0x1c1c20), 0, -hh * 0.14 + sh * 0.22, hl * 0.75 + sl));
32
+ }
33
+ eyes(hg, hw / 2 + 0.004, hh * 0.32, hl * 0.42, s.eye ?? 0.045);
34
+ const ey = hh * 0.65, ec = s.earC ?? c2;
35
+ for (const sx of [1, -1]) {
36
+ if (s.ears === 'point') hg.add(at(cone(hw * 0.2, hh * (s.earH ?? 0.5), ec, null, 4), sx * hw * 0.3, ey + hh * 0.2, hl * 0.1));
37
+ else if (s.ears === 'round') hg.add(at(ball(hw * 0.2, ec), sx * hw * 0.42, ey, hl * 0.1));
38
+ else if (s.ears === 'long') hg.add(at(box(hw * 0.2, hh * 1.3, 0.05, ec), sx * hw * 0.25, ey + hh * 0.6, 0, -0.15, 0, -sx * 0.12));
39
+ else if (s.ears === 'floppy') hg.add(at(box(0.05, hh * 0.7, hl * 0.4, ec), sx * (hw / 2 + 0.02), hh * 0.1, hl * 0.1, 0, 0, sx * 0.15));
40
+ else if (s.ears === 'big') hg.add(at(box(0.08, hh * 0.9, hl * 0.9, ec), sx * (hw / 2 + 0.05), hh * 0.15, -hl * 0.05, 0, sx * 0.5, 0));
41
+ }
42
+ let tail = null;
43
+ if (s.tail) {
44
+ const t = s.tail;
45
+ tail = joint(0, top - s.H * 0.2, -s.L / 2 + 0.03, at(box(t.w, t.len, t.w, t.c ?? c2), 0, t.len / 2, 0));
46
+ if (t.tip) tail.add(at(box(t.w * 1.25, t.len * 0.3, t.w * 1.25, t.tip), 0, t.len * 0.9, 0));
47
+ tail.rotation.x = t.ang;
48
+ body.add(tail);
49
+ }
50
+ body.add(head);
51
+ const parts = { body, head, tail, legs };
52
+ s.extra?.({ body, hg, head, C, c2, s, top, parts, hw, hh, hl });
53
+ return rig(root, 'quad', {
54
+ h: top - s.H * 0.25 + ny + hh * 0.7, r: s.L / 2 + 0.25, top, seat: [0, top, -s.L * 0.08],
55
+ leg: s.leg, hipZ: s.L / 2 - s.lw * 0.7, bodyH: s.H, flyer: !!s.flyer,
56
+ }, parts);
57
+ }
58
+
59
+ const spots = (x, color, list) => {
60
+ for (const [w, h, d, px, py, pz] of list) x.body.add(at(box(w, h, d, color), px, py, pz));
61
+ };
62
+
63
+ const QUADS = {
64
+ dog: [0xb9783f, { L: 0.9, H: 0.38, W: 0.36, leg: 0.38, lw: 0.11, neck: 0.22, na: 1.0, nw: 0.2, hd: [0.3, 0.28, 0.3],
65
+ snout: [0.16, 0.13, 0.18], ears: 'floppy', tail: { len: 0.36, w: 0.07, ang: -0.9 } }],
66
+ cat: [0xe0964b, { L: 0.62, H: 0.26, W: 0.24, leg: 0.24, lw: 0.08, neck: 0.1, na: 1.0, nw: 0.14, hd: [0.26, 0.22, 0.22],
67
+ snout: [0.1, 0.07, 0.05], noseC: 0xe58a9a, ears: 'point', tail: { len: 0.5, w: 0.05, ang: -0.4 }, eye: 0.04 }],
68
+ horse: [0x8f5a36, { L: 1.7, H: 0.62, W: 0.5, leg: 1.0, lw: 0.15, neck: 0.7, na: 1.0, nw: 0.26, hd: [0.26, 0.3, 0.5],
69
+ snout: [0.2, 0.2, 0.22], ears: 'point', earH: 0.4, hoof: DARK, tail: { len: 0.9, w: 0.14, ang: -2.7, c: 0x3a2617 },
70
+ extra: (x) => x.head.add(at(box(0.08, 0.75, 0.2, 0x3a2617), 0, 0.42, 0.1, Math.PI / 2 - 1.0)) }],
71
+ cow: [0xf2efe8, { L: 1.6, H: 0.7, W: 0.62, leg: 0.65, lw: 0.17, neck: 0.3, na: 0.5, nw: 0.3, hd: [0.36, 0.36, 0.4],
72
+ snout: [0.3, 0.2, 0.16], snoutC: 0xf0a8b0, noseC: 0xc97f8a, ears: 'floppy', hoof: DARK,
73
+ tail: { len: 0.7, w: 0.06, ang: -2.85, tip: DARK },
74
+ extra: (x) => {
75
+ const t = x.top, k = tint(x.C, -0.62);
76
+ spots(x, k, [[0.4, 0.3, 0.5, 0.13, t - 0.14, 0.3], [0.35, 0.4, 0.45, -0.15, t - 0.3, -0.4], [0.2, 0.25, 0.3, 0.22, t - 0.45, -0.15]]);
77
+ x.body.add(at(box(0.3, 0.14, 0.3, 0xf0a8b0), 0, x.s.leg - 0.05, -0.35));
78
+ for (const sx of [1, -1]) x.hg.add(at(cone(0.05, 0.2, 0xe8e0c8, null, 5), sx * 0.16, 0.34, 0.05, 0, 0, -sx * 0.5));
79
+ } }],
80
+ pig: [0xf0a3ae, { L: 1.0, H: 0.52, W: 0.5, leg: 0.25, lw: 0.13, neck: 0.08, na: 0.3, nw: 0.3, hd: [0.4, 0.38, 0.3],
81
+ snout: [0.2, 0.16, 0.12], noseC: 0xc96f80, ears: 'point', earH: 0.35, tail: { len: 0.2, w: 0.05, ang: -0.8 } }],
82
+ sheep: [0xf2efe8, { L: 1.0, H: 0.55, W: 0.52, leg: 0.38, lw: 0.1, legC: 0x33302e, neck: 0.15, na: 0.8, nw: 0.2,
83
+ hd: [0.24, 0.26, 0.3], headC: 0x33302e, earC: 0x33302e, ears: 'floppy', tail: { len: 0.14, w: 0.12, ang: -1.6 },
84
+ extra: (x) => {
85
+ const y = x.s.leg + x.s.H / 2;
86
+ for (const [px, py, pz, r] of [[0, 0.12, 0.3, 0.36], [0.1, 0.16, -0.05, 0.38], [-0.1, 0.12, -0.35, 0.36], [0, 0.3, 0.05, 0.3], [0, 0.42, 0.52, 0.2]])
87
+ x.body.add(at(ball(r, x.C), px, y + py, pz));
88
+ } }],
89
+ fox: [0xe2702a, { L: 0.8, H: 0.28, W: 0.26, leg: 0.3, lw: 0.08, legC: 0x3a2a22, neck: 0.15, na: 0.9, nw: 0.16,
90
+ hd: [0.26, 0.22, 0.24], snout: [0.1, 0.08, 0.2], snoutC: WHITE, ears: 'point', earH: 0.7, earC: 0x3a2a22,
91
+ tail: { len: 0.55, w: 0.16, ang: -1.75, tip: WHITE } }],
92
+ bear: [0x6b4530, { L: 1.5, H: 0.8, W: 0.75, leg: 0.55, lw: 0.24, neck: 0.2, na: 0.5, nw: 0.4, hd: [0.5, 0.45, 0.42],
93
+ snout: [0.24, 0.2, 0.2], ears: 'round', tail: { len: 0.12, w: 0.14, ang: -1.5 } }],
94
+ elephant: [0x8f949c, { L: 2.4, H: 1.4, W: 1.2, leg: 1.2, lw: 0.38, neck: 0.25, na: 0.2, nw: 0.7, hd: [0.9, 1.0, 0.8],
95
+ ears: 'big', eye: 0.07, tail: { len: 0.7, w: 0.07, ang: -2.95, tip: DARK },
96
+ extra: (x) => {
97
+ let p = x.hg, len = 0.42, w = 0.3;
98
+ const trunk = joint(0, -0.15, 0.6);
99
+ x.hg.add(trunk);
100
+ p = trunk;
101
+ p.rotation.x = 1.2;
102
+ for (let i = 0; i < 4; i++) {
103
+ p.add(at(box(w, len, w, x.C), 0, len / 2, 0));
104
+ const n = joint(0, len, 0);
105
+ n.rotation.x = i === 2 ? -0.7 : 0.18;
106
+ p.add(n);
107
+ p = n; len *= 0.9; w *= 0.8;
108
+ }
109
+ x.parts.trunk = trunk;
110
+ for (const sx of [1, -1]) x.hg.add(at(cone(0.07, 0.6, 0xf3ecd8, null, 6), sx * 0.3, -0.35, 0.72, 1.9, 0, 0));
111
+ } }],
112
+ giraffe: [0xe8b84a, { L: 1.5, H: 0.7, W: 0.5, leg: 1.7, lw: 0.14, neck: 1.9, na: 1.25, nw: 0.26, hd: [0.24, 0.26, 0.5],
113
+ snout: [0.2, 0.16, 0.2], ears: 'floppy', hoof: DARK, tail: { len: 0.8, w: 0.06, ang: -2.85, tip: DARK },
114
+ extra: (x) => {
115
+ const k = tint(x.C, -0.3), t = x.top;
116
+ spots(x, k, [[0.3, 0.3, 0.3, 0.12, t - 0.2, 0.3], [0.3, 0.3, 0.4, -0.12, t - 0.3, -0.3], [0.2, 0.3, 0.3, 0.17, t - 0.45, -0.2], [0.25, 0.2, 0.3, -0.14, t - 0.1, 0.1]]);
117
+ for (let i = 0; i < 4; i++) x.head.add(at(box(0.28, 0.22, 0.2, k), i % 2 ? 0.02 : -0.02, 0.35 + i * 0.4, 0.1 + i * 0.13, Math.PI / 2 - 1.25));
118
+ for (const sx of [1, -1]) x.hg.add(at(cyl(0.03, 0.03, 0.18, k), sx * 0.07, 0.3, 0.1), at(ball(0.045, DARK), sx * 0.07, 0.4, 0.1));
119
+ } }],
120
+ rabbit: [0xeeeae4, { L: 0.42, H: 0.26, W: 0.24, leg: 0.14, lw: 0.08, neck: 0.06, na: 1.0, nw: 0.16, hd: [0.24, 0.22, 0.22],
121
+ snout: [0.1, 0.07, 0.05], noseC: 0xe58a9a, ears: 'long', earC: 0xeeeae4, c2: 0xe0dbd2, tail: { len: 0.1, w: 0.12, ang: -1.4, c: WHITE }, eye: 0.04 }],
122
+ lion: [0xd9a441, { L: 1.5, H: 0.55, W: 0.48, leg: 0.6, lw: 0.16, neck: 0.2, na: 0.7, nw: 0.3, hd: [0.4, 0.38, 0.36],
123
+ snout: [0.22, 0.16, 0.16], ears: 'round', tail: { len: 0.8, w: 0.06, ang: -2.3, tip: 0x5a3a1c },
124
+ extra: (x) => x.hg.add(at(ball(0.42, 0x8a5a24), 0, 0.05, -0.08, 0, 0, 0, [1, 1, 0.75])) }],
125
+ dragon: [0x3d9a55, { L: 2.0, H: 0.7, W: 0.6, leg: 0.6, lw: 0.2, neck: 0.9, na: 1.0, nw: 0.3, hd: [0.4, 0.36, 0.6],
126
+ snout: [0.3, 0.2, 0.3], flyer: true, tail: { len: 1.4, w: 0.22, ang: -1.8 }, eye: 0.06,
127
+ extra: (x) => {
128
+ const k = tint(x.C, -0.2), w = tint(x.C, 0.15);
129
+ for (const sx of [1, -1]) x.hg.add(at(cone(0.06, 0.3, 0xf3ecd8, null, 5), sx * 0.13, 0.36, 0, -0.5, 0, 0));
130
+ for (let i = 0; i < 5; i++) x.body.add(at(cone(0.09, 0.24, k, null, 4), 0, x.top + 0.1, 0.8 - i * 0.4));
131
+ x.parts.wings = [1, -1].map((sx) => {
132
+ const j = joint(sx * 0.28, x.top - 0.05, 0.3, at(box(1.7, 0.05, 0.9, w), sx * 0.85, 0, -0.1), at(box(0.9, 0.05, 0.6, w), sx * 1.9, 0, -0.3));
133
+ j.rotation.z = sx * 0.35;
134
+ x.body.add(j);
135
+ return j;
136
+ });
137
+ } }],
138
+ };
139
+
140
+ // ------------------------------------------------------------------ two-legged characters
141
+ function biped(o, C) {
142
+ const root = new THREE.Group(), body = new THREE.Group();
143
+ root.add(body);
144
+ const leg = o.leg ?? 0.78, [tw, th, td] = o.torso ?? [0.5, 0.62, 0.28], aw = o.aw ?? 0.14, al = o.arm ?? 0.6, lw = o.lw ?? 0.19;
145
+ const skin = o.skin ?? SKIN, pants = o.pants ?? 0x35445c, sleeve = o.sleeve ?? C;
146
+ body.add(at(box(tw, th, td, C), 0, leg + th / 2, 0));
147
+ const legs = [1, -1].map((sx) => {
148
+ const j = joint(sx * (tw / 2 - lw / 2), leg, 0, at(box(lw, leg, lw, pants), 0, -leg / 2, 0),
149
+ at(box(lw * 1.05, 0.1, lw * 1.5, o.shoes ?? DARK), 0, -leg + 0.05, lw * 0.25));
150
+ body.add(j);
151
+ return j;
152
+ });
153
+ const arms = [1, -1].map((sx) => {
154
+ const j = joint(sx * (tw / 2 + aw / 2), leg + th - aw * 0.4, 0, at(box(aw, al, aw, sleeve), 0, -al / 2 + aw * 0.4, 0),
155
+ at(box(aw * 1.05, aw * 1.1, aw * 1.05, o.hand ?? skin), 0, -al + aw * 0.2, 0));
156
+ body.add(j);
157
+ return j;
158
+ });
159
+ const hs = o.head ?? 0.34;
160
+ const head = joint(0, leg + th, 0);
161
+ if (!o.noHead) {
162
+ head.add(at(box(hs * 0.45, 0.1, hs * 0.45, skin), 0, 0.03, 0), at(box(hs, hs, hs, skin), 0, 0.06 + hs / 2, 0));
163
+ eyes(head, hs * 0.22, 0.06 + hs * 0.58, hs / 2 + 0.005, 0.035);
164
+ }
165
+ body.add(head);
166
+ const parts = { body, head, legs, arms };
167
+ o.extra?.({ body, head, arms, legs, C, leg, tw, th, td, hs, parts, al, aw });
168
+ return rig(root, 'biped', { h: leg + th + hs + 0.1 + (o.hat ?? 0), r: 0.45, top: leg + th + hs + 0.08, seat: [0, leg + th, -0.1], leg }, parts);
169
+ }
170
+
171
+ const BIPEDS = {
172
+ man: [0x3b76c4, { extra: (x) => x.head.add(at(box(0.36, 0.12, 0.36, 0x4a3323), 0, 0.37, -0.01), at(box(0.36, 0.2, 0.1, 0x4a3323), 0, 0.26, -0.14)) }],
173
+ woman: [0xd9486e, { pants: SKIN, lw: 0.15, torso: [0.44, 0.6, 0.26], aw: 0.12, extra: (x) => {
174
+ x.head.add(at(box(0.38, 0.14, 0.38, 0x6b3a1e), 0, 0.37, -0.01), at(box(0.38, 0.5, 0.12, 0x6b3a1e), 0, 0.14, -0.16));
175
+ x.body.add(at(cone(0.36, 0.5, x.C, null, 8), 0, x.leg - 0.12, 0));
176
+ } }],
177
+ robot: [0xaab3bd, { skin: 0xaab3bd, noHead: true, torso: [0.56, 0.62, 0.36], aw: 0.15, lw: 0.2, extra: (x) => {
178
+ const d = tint(x.C, -0.25);
179
+ for (const p of [...x.legs, ...x.arms]) p.children.forEach((m, i) => { m.material = mat(i ? d : tint(x.C, -0.1), { metal: 1 }); });
180
+ x.head.add(at(box(0.12, 0.08, 0.12, d), 0, 0.03, 0), at(box(0.42, 0.34, 0.36, x.C, { metal: 1 }), 0, 0.24, 0),
181
+ at(box(0.32, 0.1, 0.03, 0x4fe3ff, { emissive: 0x4fe3ff, glow: 1.4 }), 0, 0.27, 0.185),
182
+ at(cyl(0.012, 0.012, 0.2, d), 0, 0.5, 0), at(orb(0.04, 0xff5a4a, { emissive: 0xff5a4a }), 0, 0.62, 0));
183
+ x.body.add(at(box(0.3, 0.22, 0.03, d), 0, x.leg + x.th * 0.6, x.td / 2 + 0.01),
184
+ at(box(0.06, 0.06, 0.02, 0x7dff7a, { emissive: 0x7dff7a }), -0.07, x.leg + x.th * 0.62, x.td / 2 + 0.03),
185
+ at(box(0.06, 0.06, 0.02, 0xffd24a, { emissive: 0xffd24a }), 0.07, x.leg + x.th * 0.62, x.td / 2 + 0.03));
186
+ }, hat: 0.2 }],
187
+ alien: [0x6fcf5a, { noHead: true, torso: [0.36, 0.5, 0.22], leg: 0.6, aw: 0.09, lw: 0.11, arm: 0.6, extra: (x) => {
188
+ const c = x.C, suit = tint(c, -0.28);
189
+ x.body.children[0].material = mat(suit);
190
+ for (const p of x.legs) p.children[0].material = mat(suit);
191
+ for (const p of x.arms) p.children.forEach((m) => { m.material = mat(c); });
192
+ x.head.add(at(box(0.1, 0.1, 0.1, c), 0, 0.03, 0), at(ball(0.3, c), 0, 0.34, 0.02, 0, 0, 0, [1, 1.05, 0.95]),
193
+ at(orb(0.085, 0x101014), 0.12, 0.34, 0.24, 0, 0, 0.5, [1, 1.5, 0.6]), at(orb(0.085, 0x101014), -0.12, 0.34, 0.24, 0, 0, -0.5, [1, 1.5, 0.6]));
194
+ for (const sx of [1, -1]) x.head.add(at(cyl(0.012, 0.012, 0.26, c), sx * 0.12, 0.72, 0, 0, 0, -sx * 0.3), at(orb(0.04, 0xf2e85a, { emissive: 0xf2e85a }), sx * 0.16, 0.85, 0));
195
+ }, hat: 0.3 }],
196
+ astronaut: [0xf4f4f0, { noHead: true, pants: null, torso: [0.6, 0.66, 0.4], aw: 0.18, lw: 0.23, shoes: 0x8d9199, hand: 0x8d9199, extra: (x) => {
197
+ for (const p of x.legs) p.children[0].material = mat(tint(x.C, -0.06));
198
+ x.head.add(at(orb(0.3, x.C), 0, 0.3, 0), at(orb(0.24, 0x1d2b45, { metal: 1 }), 0, 0.3, 0.1, 0, 0, 0, [1, 0.85, 0.9]));
199
+ x.body.add(at(box(0.46, 0.6, 0.2, tint(x.C, -0.14)), 0, x.leg + x.th * 0.55, -0.3),
200
+ at(box(0.2, 0.14, 0.03, 0x2f6fde), 0.12, x.leg + x.th * 0.7, 0.21), at(box(0.1, 0.06, 0.03, 0xd63c33), -0.14, x.leg + x.th * 0.74, 0.21));
201
+ }, hat: 0.25 }],
202
+ knight: [0xc4c9d1, { noHead: true, pants: null, torso: [0.56, 0.64, 0.34], aw: 0.16, lw: 0.21, shoes: 0x55585e, extra: (x) => {
203
+ const m = { metal: 1 }, d = tint(x.C, -0.2);
204
+ x.body.children[0].material = mat(x.C, m);
205
+ for (const p of [...x.legs, ...x.arms]) p.children.forEach((q) => { q.material = mat(d, m); });
206
+ x.head.add(at(cyl(0.2, 0.2, 0.36, x.C, m, 8), 0, 0.22, 0), at(box(0.3, 0.05, 0.03, 0x101014), 0, 0.26, 0.19),
207
+ at(box(0.04, 0.2, 0.03, 0x101014), 0, 0.18, 0.19), at(box(0.06, 0.2, 0.36, 0xd63c33), 0, 0.5, -0.04));
208
+ x.arms[1].add(at(box(0.05, 0.9, 0.09, 0xdfe4ea, m), 0, -0.52, 0.5, Math.PI / 2), at(box(0.26, 0.05, 0.08, 0x6b4a2a), 0, -0.52, 0.1));
209
+ x.arms[0].add(at(box(0.06, 0.6, 0.48, 0x2f6fde), 0.11, -0.32, 0.05), at(box(0.02, 0.4, 0.1, 0xe2b23a), 0.145, -0.32, 0.05));
210
+ }, hat: 0.3 }],
211
+ wizard: [0x6a3fb5, { extra: (x) => {
212
+ const c = x.C, d = tint(c, -0.15);
213
+ x.body.add(at(cone(0.46, x.leg + 0.25, c, null, 9), 0, (x.leg + 0.25) / 2, 0));
214
+ x.head.add(at(cyl(0.34, 0.34, 0.04, d, null, 12), 0, 0.4, 0), at(cone(0.22, 0.6, c, null, 9), 0, 0.72, 0, -0.12),
215
+ at(box(0.28, 0.34, 0.1, WHITE), 0, 0.02, 0.17), at(box(0.36, 0.1, 0.36, WHITE), 0, 0.33, -0.02));
216
+ x.arms[1].add(at(cyl(0.03, 0.03, 1.6, 0x6b4a2a, null, 6), 0, -0.3, 0.12), at(orb(0.1, 0x66e0ff, { emissive: 0x66e0ff, glow: 1.6 }), 0, 0.56, 0.12));
217
+ }, hat: 0.65 }],
218
+ };
219
+
220
+ // ------------------------------------------------------------------ birds
221
+ function birdy(o, C) {
222
+ const root = new THREE.Group(), body = new THREE.Group();
223
+ root.add(body);
224
+ const s = o.s ?? 1, leg = (o.leg ?? 0.16) * s, r = 0.2 * s, up = o.upright;
225
+ const by = leg + r * (up ? 1.5 : 0.9);
226
+ body.add(at(ball(r, C), 0, by, 0, 0, 0, 0, up ? [1, 1.7, 0.95] : [0.95, 0.95, 1.4]));
227
+ if (o.belly) body.add(at(ball(r * 0.9, o.belly), 0, by - r * 0.05, r * 0.2, 0, 0, 0, up ? [0.9, 1.6, 0.85] : [0.8, 0.8, 1.2]));
228
+ const head = joint(0, by + r * (up ? 1.75 : 0.8), r * (up ? 0.1 : 1.05));
229
+ head.add(at(ball(r * 0.62, o.headC ?? C), 0, r * 0.3, 0));
230
+ head.add(o.bill
231
+ ? at(box(r * 0.5, r * 0.16, r * 0.6, o.beak ?? 0xf08a24), 0, r * 0.22, r * 0.8)
232
+ : at(cone(r * 0.2, r * 0.55, o.beak ?? 0xf0a024, null, 5), 0, r * 0.26, r * 0.8, Math.PI / 2));
233
+ eyes(head, r * 0.4, r * 0.48, r * 0.38, r * 0.11);
234
+ if (o.comb) head.add(at(box(r * 0.12, r * 0.4, r * 0.6, 0xd63c33), 0, r * 0.95, 0), at(box(r * 0.14, r * 0.3, r * 0.14, 0xd63c33), 0, -r * 0.05, r * 0.6));
235
+ body.add(head);
236
+ const wc = o.wingC ?? tint(C, -0.12);
237
+ const wings = [1, -1].map((sx) => {
238
+ const j = up
239
+ ? joint(sx * r * 0.95, by + r * 0.9, 0, at(box(r * 0.2, r * 1.7, r * 0.8, wc), sx * r * 0.08, -r * 0.8, 0))
240
+ : joint(sx * r * 0.8, by + r * 0.35, 0, at(box(r * 2.2, r * 0.14, r * 1.5, wc), sx * r * 1.05, 0, -r * 0.1));
241
+ if (!up) j.rotation.z = -sx * 1.25;
242
+ body.add(j);
243
+ return j;
244
+ });
245
+ const tail = joint(0, by + r * 0.1, -r * (up ? 0.8 : 1.3), at(box(r * 0.9, r * 0.14, r * 0.9, wc), 0, 0, -r * 0.3));
246
+ tail.rotation.x = up ? -0.9 : 0.35;
247
+ body.add(tail);
248
+ const legs = [1, -1].map((sx) => {
249
+ const j = joint(sx * r * 0.4, leg, 0, at(cyl(0.02 * s, 0.02 * s, leg, 0xf08a24, null, 5), 0, -leg / 2, 0),
250
+ at(box(r * 0.45, 0.03 * s, r * 0.7, 0xf08a24), 0, -leg + 0.015, r * 0.15));
251
+ body.add(j);
252
+ return j;
253
+ });
254
+ const h = by + r * (up ? 2.7 : 1.7);
255
+ return rig(root, 'bird', { h, r: r * 1.6, top: h, seat: [0, by + r * 0.9, 0], leg, flyer: !!o.flyer, upright: !!up, swims: !!o.swims },
256
+ { body, head, tail, legs, wings });
257
+ }
258
+ const BIRDS = {
259
+ bird: [0x4aa3df, { s: 1.3, flyer: true, belly: 0xf2e6c8 }],
260
+ duck: [0xf5d04a, { s: 1.5, bill: true, flyer: true, swims: true }],
261
+ chicken: [0xf4f4f0, { s: 1.6, comb: true, leg: 0.2 }],
262
+ penguin: [0x2a2a30, { s: 2.0, upright: true, belly: 0xf4f4f0, leg: 0.06, swims: true }],
263
+ };
264
+
265
+ // ------------------------------------------------------------------ fish
266
+ function fishy(o, C) {
267
+ const root = new THREE.Group(), body = new THREE.Group();
268
+ root.add(body);
269
+ const s = o.s, y = o.hover;
270
+ body.add(at(ball(0.3 * s, C), 0, y, 0, 0, 0, 0, [0.5, 0.75, 1.5]));
271
+ if (o.belly) body.add(at(ball(0.28 * s, o.belly), 0, y - 0.05 * s, 0.02, 0, 0, 0, [0.48, 0.62, 1.4]));
272
+ const fc = o.finC ?? tint(C, -0.15);
273
+ const tail = joint(0, y, -0.4 * s, at(box(0.04 * s, 0.4 * s, 0.26 * s, fc), 0, 0, -0.14 * s), at(box(0.04 * s, 0.14 * s, 0.14 * s, fc), 0, 0.2 * s, -0.26 * s), at(box(0.04 * s, 0.14 * s, 0.14 * s, fc), 0, -0.2 * s, -0.26 * s));
274
+ body.add(tail, at(cone(0.1 * s, (o.dorsal ?? 0.22) * s, fc, null, 4), 0, y + (0.2 + (o.dorsal ?? 0.22) / 2) * s, -0.02 * s, -0.35, 0, 0, [0.3, 1, 1]));
275
+ const fins = [1, -1].map((sx) => {
276
+ const j = joint(sx * 0.13 * s, y - 0.08 * s, 0.12 * s, at(box(0.22 * s, 0.03 * s, 0.14 * s, fc), sx * 0.11 * s, 0, 0));
277
+ j.rotation.z = -sx * 0.5;
278
+ body.add(j);
279
+ return j;
280
+ });
281
+ eyes(body, 0.13 * s, y + 0.05 * s, 0.26 * s, 0.035 * s);
282
+ if (o.mouth) body.add(at(box(0.2 * s, 0.03 * s, 0.14 * s, 0x7a1f24), 0, y - 0.1 * s, 0.34 * s));
283
+ return rig(root, 'fish', { h: y + 0.3 * s, r: 0.5 * s, top: y + 0.25 * s, seat: [0, y + 0.2 * s, 0], swims: true, hover: y },
284
+ { body, tail, wings: fins });
285
+ }
286
+ const FISH = {
287
+ fish: [0xf08a24, { s: 1.0, hover: 0.7, belly: 0xf7d9a8 }],
288
+ shark: [0x6e7f8f, { s: 3.2, hover: 1.2, belly: 0xe8ecef, dorsal: 0.3, mouth: true }],
289
+ };
290
+
291
+ // ------------------------------------------------------------------ one-offs
292
+ function snowman(C) {
293
+ const root = new THREE.Group(), body = new THREE.Group();
294
+ root.add(body);
295
+ const c = C ?? 0xc0392b;
296
+ body.add(at(ball(0.55, WHITE), 0, 0.5, 0), at(ball(0.4, WHITE), 0, 1.2, 0));
297
+ const head = joint(0, 1.5, 0, at(ball(0.28, WHITE), 0, 0.22, 0), at(cone(0.05, 0.3, 0xf08a24, null, 6), 0, 0.22, 0.38, Math.PI / 2),
298
+ at(cyl(0.3, 0.3, 0.03, DARK), 0, 0.44, 0), at(cyl(0.19, 0.19, 0.28, DARK), 0, 0.58, 0), at(cyl(0.195, 0.195, 0.06, c), 0, 0.49, 0));
299
+ eyes(head, 0.1, 0.3, 0.25, 0.035);
300
+ body.add(head, at(torus(0.26, 0.06, c), 0, 1.5, 0, Math.PI / 2), at(box(0.1, 0.34, 0.05, c), 0.16, 1.32, 0.28, 0.1),
301
+ at(orb(0.04, DARK), 0, 1.3, 0.38), at(orb(0.04, DARK), 0, 1.1, 0.4));
302
+ const arms = [1, -1].map((sx) => {
303
+ const j = joint(sx * 0.36, 1.3, 0, at(cyl(0.02, 0.02, 0.6, 0x6b4a2a, null, 5), 0, -0.3, 0));
304
+ j.rotation.z = sx * 2.1;
305
+ body.add(j);
306
+ return j;
307
+ });
308
+ return rig(root, 'blob', { h: 2.25, r: 0.6, top: 2.25, seat: [0, 2.2, 0] }, { body, head, arms });
309
+ }
310
+
311
+ function ghost(C) {
312
+ const root = new THREE.Group(), body = new THREE.Group();
313
+ root.add(body);
314
+ const c = C ?? WHITE, o = { opacity: 0.9 }, y = 0.55;
315
+ body.add(at(orb(0.42, c, o), 0, y + 0.9, 0), at(cyl(0.42, 0.46, 0.9, c, o, 14), 0, y + 0.45, 0));
316
+ for (let i = 0; i < 6; i++) body.add(at(cone(0.16, 0.3, c, o, 6), Math.cos(i * 1.047) * 0.3, y - 0.14, Math.sin(i * 1.047) * 0.3, Math.PI));
317
+ body.add(at(orb(0.07, 0x101014), 0.15, y + 0.95, 0.37, 0, 0, 0, [1, 1.4, 0.6]), at(orb(0.07, 0x101014), -0.15, y + 0.95, 0.37, 0, 0, 0, [1, 1.4, 0.6]),
318
+ at(orb(0.06, 0x101014), 0, y + 0.72, 0.42, 0, 0, 0, [1, 1.3, 0.5]));
319
+ const arms = [1, -1].map((sx) => {
320
+ const j = joint(sx * 0.4, y + 0.7, 0.05, at(orb(0.13, c, o), sx * 0.02, -0.16, 0, 0, 0, 0, [0.8, 1.6, 0.8]));
321
+ j.rotation.z = sx * 0.9;
322
+ body.add(j);
323
+ return j;
324
+ });
325
+ return rig(root, 'blob', { h: y + 1.35, r: 0.55, top: y + 1.3, seat: [0, y + 1.3, 0], hover: 0.25, floaty: true }, { body, arms });
326
+ }
327
+
328
+ function dinosaur(C) {
329
+ const root = new THREE.Group(), body = new THREE.Group();
330
+ root.add(body);
331
+ const c = C ?? 0x5c9a4a, d = tint(c, -0.12), l = tint(c, 0.16), leg = 1.3;
332
+ const torso = joint(0, leg + 0.35, 0, at(box(0.85, 0.95, 1.9, c), 0, 0, 0), at(box(0.6, 0.3, 1.5, l), 0, -0.4, 0.1));
333
+ torso.rotation.x = -0.28;
334
+ body.add(torso);
335
+ const head = joint(0, 0.5, 0.95);
336
+ head.rotation.x = 0.28;
337
+ head.add(at(box(0.5, 0.5, 0.5, c), 0, 0.2, 0), at(box(0.62, 0.42, 1.0, c), 0, 0.6, 0.45), at(box(0.54, 0.16, 0.85, l), 0, 0.3, 0.5, 0.18));
338
+ for (let i = 0; i < 5; i++) for (const sx of [1, -1]) head.add(at(cone(0.035, 0.1, WHITE, null, 4), sx * 0.24, 0.36, 0.2 + i * 0.16, Math.PI));
339
+ eyes(head, 0.315, 0.7, 0.55, 0.06, 0xf2c230);
340
+ torso.add(head);
341
+ let tail = joint(0, 0, -0.95), p = tail, len = 0.7, w = 0.6;
342
+ tail.rotation.x = 0.28 + 0.1;
343
+ for (let i = 0; i < 4; i++) {
344
+ p.add(at(box(w, w * 0.9, len, c), 0, 0, -len / 2));
345
+ const n = joint(0, 0, -len);
346
+ p.add(n);
347
+ p = n; w *= 0.68; len *= 0.95;
348
+ }
349
+ torso.add(tail);
350
+ const arms = [1, -1].map((sx) => {
351
+ const j = joint(sx * 0.4, -0.1, 0.8, at(box(0.11, 0.38, 0.11, d), 0, -0.19, 0), at(box(0.12, 0.1, 0.2, d), 0, -0.4, 0.06));
352
+ j.rotation.x = -0.9;
353
+ torso.add(j);
354
+ return j;
355
+ });
356
+ const legs = [1, -1].map((sx) => {
357
+ const j = joint(sx * 0.45, leg, -0.1, at(box(0.36, 0.7, 0.5, d), 0, -0.3, 0), at(box(0.24, 0.7, 0.26, d), 0, -0.9, 0.06), at(box(0.3, 0.14, 0.55, d), 0, -leg + 0.07, 0.2));
358
+ body.add(j);
359
+ return j;
360
+ });
361
+ return rig(root, 'biped', { h: 3.0, r: 1.5, top: leg + 0.9, seat: [0, leg + 0.85, -0.2], leg }, { body, head, tail, legs, arms });
362
+ }
363
+
364
+ export const CREATURES = {
365
+ ...Object.fromEntries(Object.entries(QUADS).map(([k, [c, s]]) => [k, (C) => quad(s, C ?? c)])),
366
+ ...Object.fromEntries(Object.entries(BIPEDS).map(([k, [c, s]]) => [k, (C) => biped(s, C ?? c)])),
367
+ ...Object.fromEntries(Object.entries(BIRDS).map(([k, [c, s]]) => [k, (C) => birdy(s, C ?? c)])),
368
+ ...Object.fromEntries(Object.entries(FISH).map(([k, [c, s]]) => [k, (C) => fishy(s, C ?? c)])),
369
+ snowman, ghost, dinosaur,
370
+ };
web/js/scene/environment.js ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Places, time of day and weather. Everything is plain three.js objects (no custom shaders).
2
+ import * as THREE from 'three';
3
+ import { at, ball, box, cone, cyl, group, mat, orb, rng, rockGeo, tint, torus } from './prims.js';
4
+ import { THINGS } from './things.js';
5
+
6
+ const { sin, cos, PI } = Math;
7
+ const HAS_DOM = typeof document !== 'undefined';
8
+
9
+ const SKY = {
10
+ day: { top: 0x4a90e2, hor: 0xcfe8ff, sun: 0xfff4e0, si: 2.6, hemi: 1.0, dir: [8, 14, 7] },
11
+ sunset: { top: 0x2b3a67, hor: 0xff9a56, sun: 0xffb27a, si: 1.7, hemi: 0.95, dir: [-15, 4.5, 3] },
12
+ dawn: { top: 0x6f8fd6, hor: 0xffd3b0, sun: 0xffd0b0, si: 2.0, hemi: 0.8, dir: [15, 5, 4] },
13
+ night: { top: 0x05070f, hor: 0x1a2444, sun: 0xa9bcff, si: 1.25, hemi: 0.75, dir: [-7, 13, 5] },
14
+ };
15
+ const WEATHER_TINT = { rain: [0x6f7c8a, 0.65], storm: [0x2e3540, 0.82], fog: [0xc9d1d6, 0.8], snow: [0xc3ccd6, 0.55], clear: [0, 0] };
16
+ const GROUND = {
17
+ field: 0x7fb650, desert: 0xe2c28a, snow: 0xeef3f7, beach: 0xead7a4, forest: 0x47743e, city: 0x53565e, moon: 0x8e9096,
18
+ ocean: 0x2c6fa8, room: 0xb98a5a, mountain: 0x78985e, farm: 0x86b857, road: 0x74ad4c, park: 0x76b455, studio: 0xdfe3ea,
19
+ };
20
+
21
+ const mix = (a, b, k) => new THREE.Color(a).lerp(new THREE.Color(b), k);
22
+
23
+ function gradient(top, hor) {
24
+ if (!HAS_DOM) return hor.clone();
25
+ const c = document.createElement('canvas');
26
+ c.width = 4; c.height = 256;
27
+ const x = c.getContext('2d'), g = x.createLinearGradient(0, 0, 0, 256);
28
+ g.addColorStop(0, '#' + top.getHexString());
29
+ g.addColorStop(0.62, '#' + hor.getHexString());
30
+ g.addColorStop(1, '#' + hor.getHexString());
31
+ x.fillStyle = g;
32
+ x.fillRect(0, 0, 4, 256);
33
+ const t = new THREE.CanvasTexture(c);
34
+ t.colorSpace = THREE.SRGBColorSpace;
35
+ return t;
36
+ }
37
+
38
+ function windows(lit) {
39
+ if (!HAS_DOM) return null;
40
+ const c = document.createElement('canvas');
41
+ c.width = 64; c.height = 128;
42
+ const x = c.getContext('2d'), r = rng(lit ? 7 : 3);
43
+ x.fillStyle = lit ? '#000' : '#fff';
44
+ x.fillRect(0, 0, 64, 128);
45
+ for (let j = 0; j < 10; j++) for (let i = 0; i < 4; i++) {
46
+ const on = r() < 0.55;
47
+ x.fillStyle = lit ? (on ? '#ffd98a' : '#000') : (on ? '#b9d4ee' : '#7f93a8');
48
+ x.fillRect(4 + i * 15, 5 + j * 12.4, 10, 8);
49
+ }
50
+ const t = new THREE.CanvasTexture(c);
51
+ t.colorSpace = THREE.SRGBColorSpace;
52
+ return t;
53
+ }
54
+
55
+ // ------------------------------------------------------------------ small scenery pieces
56
+ const pine = (snowy) => group(at(cyl(0.14, 0.2, 1.0, 0x6b4a2a, null, 6), 0, 0.5, 0), at(cone(1.1, 1.6, snowy ? 0xdfe9ee : 0x2f6b3f, null, 7), 0, 1.6, 0),
57
+ at(cone(0.85, 1.4, snowy ? 0xeef3f7 : 0x37794a, null, 7), 0, 2.5, 0), at(cone(0.55, 1.2, snowy ? 0xffffff : 0x3f8a55, null, 7), 0, 3.3, 0));
58
+ function palm() {
59
+ const g = group();
60
+ let y = 0, x = 0;
61
+ for (let i = 0; i < 6; i++) { g.add(at(cyl(0.13, 0.16, 0.62, 0x9a7650, null, 6), x, y + 0.3, 0, 0, 0, -0.07 * i)); y += 0.58; x += 0.045 * i; }
62
+ for (let i = 0; i < 7; i++) g.add(at(box(1.9, 0.05, 0.4, 0x3f9a4a), x + cos(i * 0.9) * 0.85, y - 0.12, sin(i * 0.9) * 0.85, 0, -i * 0.9, -0.35));
63
+ g.add(at(orb(0.13, 0x6b4a2a), x + 0.1, y - 0.15, 0.1), at(orb(0.13, 0x6b4a2a), x - 0.12, y - 0.18, 0));
64
+ return g;
65
+ }
66
+ const hill = (r, c) => at(orb(r, c), 0, -r * 0.22, 0, 0, 0, 0, [1, 0.3, 1]);
67
+ const peak = (r, h, c, snow) => group(at(cone(r, h, c, null, 7), 0, h / 2, 0), snow ? at(cone(r * 0.32, h * 0.32, 0xf7fafc, null, 7), 0, h * 0.842, 0) : group());
68
+ const cloud = () => group(at(ball(2.2, 0xffffff, { noShadow: 1 }), 0, 0, 0), at(ball(1.7, 0xffffff, { noShadow: 1 }), 2.2, -0.2, 0.3), at(ball(1.5, 0xffffff, { noShadow: 1 }), -2.1, -0.3, -0.2), at(ball(1.3, 0xffffff, { noShadow: 1 }), 0.8, 0.9, -0.3));
69
+ const bush = (c) => group(at(ball(0.5, c), 0, 0.35, 0), at(ball(0.38, tint(c, 0.05)), 0.4, 0.28, 0.1), at(ball(0.34, tint(c, -0.05)), -0.38, 0.25, -0.1));
70
+ const grass = (c) => group(at(cone(0.06, 0.4, c, { noShadow: 1 }, 4), 0, 0.2, 0), at(cone(0.05, 0.3, c, { noShadow: 1 }, 4), 0.1, 0.15, 0.05, 0, 0, -0.3), at(cone(0.05, 0.3, c, { noShadow: 1 }, 4), -0.1, 0.15, -0.03, 0, 0, 0.3));
71
+ const fence = () => group(at(box(0.1, 1.0, 0.1, 0x9a7650), -1, 0.5, 0), at(box(0.1, 1.0, 0.1, 0x9a7650), 1, 0.5, 0), at(box(2.1, 0.1, 0.06, 0xb08a60), 0, 0.75, 0), at(box(2.1, 0.1, 0.06, 0xb08a60), 0, 0.4, 0));
72
+ const hay = () => at(cyl(0.6, 0.6, 1.0, 0xe2c15a, null, 12), 0, 0.6, 0, 0, 0, PI / 2);
73
+ const barn = () => group(at(box(5, 3.2, 6, 0xb5372e), 0, 1.6, 0), at(cone(4.1, 2.0, 0x6e2a25, null, 4), 0, 4.2, 0, 0, PI / 4, 0, [1, 1, 1.2]),
74
+ at(box(1.8, 2.2, 0.1, 0xf4f4f0), 0, 1.1, 3.01), at(box(1.6, 2.0, 0.12, 0x8f2a23), 0, 1.05, 3.02), at(box(0.9, 0.7, 0.1, 0xf4f4f0), 0, 3.2, 3.01));
75
+
76
+ /** Drop `n` copies around the action area. `back` keeps them out of the camera's front wedge. */
77
+ function scatter(g, rand, n, r0, r1, make, back = true, s0 = 0.8, s1 = 1.4) {
78
+ for (let i = 0; i < n; i++) {
79
+ const a = back ? PI + (rand() * 2 - 1) * 1.95 : rand() * PI * 2, r = r0 + rand() * (r1 - r0);
80
+ const o = make(rand);
81
+ o.position.x += sin(a) * r;
82
+ o.position.z += cos(a) * r;
83
+ o.rotation.y = rand() * 6.28;
84
+ o.scale.multiplyScalar(s0 + rand() * (s1 - s0));
85
+ g.add(o);
86
+ }
87
+ }
88
+
89
+ // ------------------------------------------------------------------ main builder
90
+ export function buildEnvironment(sc, { R = 6, island = 0 } = {}) {
91
+ const loc = GROUND[sc.loc] || sc.loc === 'space' ? sc.loc : 'studio', time = SKY[sc.time] ? sc.time : 'day';
92
+ const weather = WEATHER_TINT[sc.weather] ? sc.weather : 'clear';
93
+ const g = new THREE.Group(), rand = rng(1234 + loc.length * 77), far = R + 3;
94
+ const outer = loc === 'space' || loc === 'moon', indoor = loc === 'room';
95
+ const sky = SKY[time], [wc, wk] = WEATHER_TINT[weather];
96
+ let top = new THREE.Color(sky.top), hor = new THREE.Color(sky.hor);
97
+ if (outer) { top = new THREE.Color(0x000004); hor = new THREE.Color(0x070a18); }
98
+ else if (loc === 'studio') { top = mix(0xaebbd0, sky.top, time === 'day' ? 0 : 0.75); hor = mix(0xeef1f5, sky.hor, time === 'day' ? 0 : 0.7); }
99
+ else if (indoor) { top = mix(0x3b2f2a, 0x0c0a10, time === 'night' ? 0.6 : 0); hor = top.clone(); }
100
+ if (wk && !outer && !indoor) {
101
+ const dark = time === 'night' ? 0.25 : 1;
102
+ top.lerp(new THREE.Color(wc).multiplyScalar(dark * 0.8), wk);
103
+ hor.lerp(new THREE.Color(wc).multiplyScalar(dark), wk);
104
+ }
105
+ const env = { group: g, background: gradient(top, hor), fog: null, waterY: null, zeroG: loc === 'space', tick: [], dispose: [] };
106
+ if (env.background.isTexture) env.dispose.push(env.background);
107
+
108
+ // lights
109
+ const dim = !outer && !indoor ? { rain: 0.6, storm: 0.4, fog: 0.7, snow: 0.8, clear: 1 }[weather] : 1;
110
+ const hemi = new THREE.HemisphereLight(mix(time === 'night' ? 0x6f86c9 : sky.hor, 0xffffff, time === 'night' ? 0.2 : 0.65), mix(GROUND[loc] ?? 0x888888, 0x222222, 0.4), (outer ? 0.35 : sky.hemi) * (0.6 + 0.4 * dim));
111
+ const sun = new THREE.DirectionalLight(outer ? 0xffffff : sky.sun, (outer ? 2.6 : sky.si) * dim * (indoor ? 0.45 : 1));
112
+ const sd = new THREE.Vector3(...(outer ? [9, 12, 6] : sky.dir)).normalize();
113
+ sun.position.copy(sd).multiplyScalar(60);
114
+ sun.castShadow = true;
115
+ const S = Math.max(14, R * 1.6 + 8);
116
+ Object.assign(sun.shadow.camera, { left: -S, right: S, top: S, bottom: -S, near: 1, far: 160 });
117
+ sun.shadow.mapSize.set(2048, 2048);
118
+ sun.shadow.bias = -0.0004;
119
+ sun.shadow.normalBias = 0.03;
120
+ g.add(hemi, sun, sun.target);
121
+ env.sun = sun; env.hemi = hemi;
122
+ if (indoor) {
123
+ const lampL = new THREE.PointLight(0xffd9a0, time === 'night' ? 60 : 35, 40, 1.5);
124
+ lampL.position.set(2, 6, 3);
125
+ g.add(lampL);
126
+ }
127
+
128
+ // fog blends the far ground into the horizon
129
+ if (!outer && !indoor) {
130
+ env.fog = weather === 'fog' ? new THREE.Fog(hor.getHex(), 3, Math.max(34, R * 5))
131
+ : new THREE.Fog(hor.getHex(), weather === 'clear' ? 70 : 35, weather === 'clear' ? 230 : 150);
132
+ }
133
+
134
+ // sun / moon disc and stars
135
+ if (!indoor) {
136
+ const disc = new THREE.Mesh(new THREE.SphereGeometry(time === 'night' ? 5 : 7, 16, 12),
137
+ new THREE.MeshBasicMaterial({ color: time === 'night' ? 0xf2f4ff : sky.sun, fog: false }));
138
+ disc.position.copy(sd).multiplyScalar(190);
139
+ if (outer) disc.scale.setScalar(0.5);
140
+ disc.visible = weather === 'clear' || weather === 'snow' || outer;
141
+ g.add(disc);
142
+ env.dispose.push(disc.geometry, disc.material);
143
+ }
144
+ if ((time === 'night' && !indoor && weather !== 'fog' && weather !== 'storm') || outer) {
145
+ const n = outer ? 1800 : 700, p = new Float32Array(n * 3);
146
+ for (let i = 0; i < n; i++) {
147
+ const a = rand() * 6.283, e = outer ? Math.acos(rand() * 2 - 1) : Math.acos(rand() * 0.95);
148
+ p.set([sin(e) * cos(a) * 200, cos(e) * 200, sin(e) * sin(a) * 200], i * 3);
149
+ }
150
+ const geo = new THREE.BufferGeometry();
151
+ geo.setAttribute('position', new THREE.BufferAttribute(p, 3));
152
+ const m = new THREE.PointsMaterial({ color: 0xffffff, size: 1.3, sizeAttenuation: true, fog: false });
153
+ g.add(new THREE.Points(geo, m));
154
+ env.dispose.push(geo, m);
155
+ }
156
+ if (!outer && !indoor && loc !== 'studio' && weather !== 'fog') {
157
+ const cl = group();
158
+ for (let i = 0; i < 7; i++) cl.add(at(cloud(), (rand() - 0.5) * 220, 32 + rand() * 14, -30 - rand() * 110, 0, 0, 0, 1.6 + rand() * 1.6));
159
+ if (weather !== 'clear' || time !== 'day') cl.traverse((o) => { if (o.isMesh) o.material = mat(time === 'night' ? 0x2a3350 : weather === 'clear' ? 0xffd9c0 : 0x8a939d, { basic: 1 }); });
160
+ g.add(cl);
161
+ env.tick.push((t) => { cl.position.x = ((t * 0.6) % 60) - 30; });
162
+ }
163
+
164
+ // ground
165
+ const gc = GROUND[loc];
166
+ if (loc === 'room') {
167
+ g.add(at(box(40, 0.2, 40, gc), 0, -0.1, 0));
168
+ const bz = -(R + 4), lx = -(R + 6), wall = 0xe9dcc6;
169
+ g.add(at(box(60, 14, 0.3, wall), 0, 7, bz), at(box(0.3, 14, 60, tint(wall, -0.05)), lx, 7, 0), at(box(60, 0.4, 0.4, 0xf4f4f0), 0, 0.2, bz + 0.2),
170
+ at(box(5, 3.6, 0.2, 0xf4f4f0), 3, 5.4, bz + 0.1), at(new THREE.Mesh(new THREE.BoxGeometry(4.6, 3.2, 0.22), new THREE.MeshBasicMaterial({ color: mix(sky.hor, sky.top, 0.4) })), 3, 5.4, bz + 0.12),
171
+ at(box(0.12, 3.2, 0.26, 0xf4f4f0), 3, 5.4, bz + 0.12), at(box(4.6, 0.12, 0.26, 0xf4f4f0), 3, 5.4, bz + 0.12),
172
+ at(box(3, 2.2, 0.15, 0x6b4a2a), -6, 5.2, bz + 0.1), at(box(2.6, 1.8, 0.17, 0x7fb6c9), -6, 5.2, bz + 0.12),
173
+ at(cyl(R + 1.5, R + 1.5, 0.04, 0xb5483a, null, 36), 0, 0.02, 0), at(cyl(R + 0.9, R + 0.9, 0.05, 0xe7d3a8, null, 36), 0, 0.025, 0));
174
+ } else if (loc !== 'space') {
175
+ const geo = new THREE.CircleGeometry(loc === 'studio' ? 120 : 260, 64);
176
+ const ground = new THREE.Mesh(geo, mat(loc === 'ocean' ? 0xd9c58f : gc));
177
+ ground.rotation.x = -PI / 2;
178
+ ground.position.y = loc === 'ocean' ? -1.2 : 0;
179
+ ground.receiveShadow = true;
180
+ g.add(ground);
181
+ env.dispose.push(geo);
182
+ }
183
+
184
+ const things = (name) => () => THINGS[name]();
185
+ const water = (z, depth, y) => {
186
+ const geo = new THREE.PlaneGeometry(520, depth, 64, Math.max(8, Math.round(depth / 8)));
187
+ geo.rotateX(-PI / 2);
188
+ const m = new THREE.MeshStandardMaterial({ color: 0x2f86c9, flatShading: true, roughness: 0.35, metalness: 0.1, transparent: true, opacity: 0.9 });
189
+ const mesh = new THREE.Mesh(geo, m);
190
+ mesh.position.set(0, y, z);
191
+ mesh.receiveShadow = true;
192
+ g.add(mesh);
193
+ env.dispose.push(geo, m);
194
+ const pos = geo.attributes.position, base = pos.array.slice();
195
+ env.tick.push((t) => {
196
+ for (let i = 0; i < pos.count; i++) {
197
+ const x = base[i * 3], zz = base[i * 3 + 2];
198
+ pos.array[i * 3 + 1] = sin(x * 0.35 + t * 1.3) * 0.09 + sin(zz * 0.5 + t * 0.9) * 0.07 + sin((x + zz) * 0.12 + t * 0.6) * 0.1;
199
+ }
200
+ pos.needsUpdate = true;
201
+ });
202
+ };
203
+
204
+ if (loc === 'field') {
205
+ scatter(g, rand, 9, far + 4, far + 45, things('tree'), true, 1, 1.7);
206
+ scatter(g, rand, 14, far, far + 30, () => bush(0x4f9a52));
207
+ scatter(g, rand, 40, 2, far + 14, () => THINGS.flower([0xf284b6, 0xf2c230, 0xf4f4f0, 0xd63c33, 0x8a4fd3][(rand() * 5) | 0]), false, 0.5, 0.9);
208
+ scatter(g, rand, 60, 1, far + 18, () => grass(0x5f9a3c), false);
209
+ scatter(g, rand, 6, 90, 150, () => hill(30 + rand() * 25, 0x6fa646), true, 1, 1);
210
+ } else if (loc === 'desert') {
211
+ scatter(g, rand, 10, far + 1, far + 40, things('cactus'), true, 1, 2.2);
212
+ scatter(g, rand, 12, far, far + 40, things('rock'), true, 0.8, 2.5);
213
+ scatter(g, rand, 9, 50, 150, () => hill(22 + rand() * 30, 0xd9b67a), false, 1, 1);
214
+ scatter(g, rand, 8, 4, far + 10, things('rock'), false, 0.2, 0.5);
215
+ } else if (loc === 'snow') {
216
+ scatter(g, rand, 16, far + 2, far + 50, () => pine(true), true, 1, 1.9);
217
+ scatter(g, rand, 8, 60, 150, () => hill(25 + rand() * 30, 0xe3ebf1), false, 1, 1);
218
+ scatter(g, rand, 6, far, far + 25, () => at(rockGeo(0.7, 0xf7fafc), 0, 0.2, 0, 0, 0, 0, [1.4, 0.6, 1.2]));
219
+ } else if (loc === 'beach') {
220
+ water(-(R + 9) - 150, 300, 0.3);
221
+ g.add(at(box(520, 0.06, 300, 0x2a78b8, { noShadow: 1 }), 0, 0.03, -(R + 9) - 150));
222
+ g.add(at(box(520, 0.1, 1.2, 0xffffff, { noShadow: 1 }), 0, 0.09, -(R + 8.8)));
223
+ for (let i = 0; i < 12; i++) {
224
+ const side = i % 2 ? 1 : -1;
225
+ g.add(at(palm(), side * (R + 3 + rand() * 34), 0, -(R + 5) + rand() * (R + 4), 0, rand() * 6.28, 0, 1.3 + rand() * 0.6));
226
+ }
227
+ scatter(g, rand, 6, far, far + 6, things('rock'), true, 0.6, 1.3);
228
+ const um = group(at(cyl(0.04, 0.04, 2.4, 0xf4f4f0, null, 6), 0, 1.2, 0), at(cone(1.5, 0.6, 0xd63c33, null, 8), 0, 2.5, 0), at(box(1.0, 0.04, 2.0, 0x2ec4d6), 1.2, 0.03, 0.2));
229
+ g.add(at(um, -(R + 4), 0, -1, 0, 0.4, 0.08));
230
+ } else if (loc === 'forest') {
231
+ scatter(g, rand, 34, far + 1.5, far + 42, (r) => (r() < 0.5 ? THINGS.tree() : pine(false)), true, 1.1, 2.0);
232
+ scatter(g, rand, 10, far + 20, far + 50, () => pine(false), false, 1.2, 2.0);
233
+ scatter(g, rand, 14, 2.5, far + 8, things('mushroom'), false, 0.5, 1.0);
234
+ scatter(g, rand, 16, far, far + 20, () => bush(0x356b3a));
235
+ scatter(g, rand, 50, 1, far + 10, () => grass(0x3a6b34), false);
236
+ } else if (loc === 'city') {
237
+ const day = windows(false), lit = windows(true), night = time === 'night' || time === 'sunset';
238
+ scatter(g, rand, 26, far + 9, far + 70, (r) => {
239
+ const w = 5 + r() * 5, h = 8 + r() * 26, c = [0x8d99a6, 0xa9957e, 0x7a8794, 0xb3a89a, 0x6f7c8f][(r() * 5) | 0];
240
+ const m = new THREE.MeshStandardMaterial({ color: c, map: day, flatShading: true, roughness: 0.8, emissive: night ? 0xffffff : 0, emissiveMap: night ? lit : null, emissiveIntensity: 0.9 });
241
+ const b = new THREE.Mesh(new THREE.BoxGeometry(w, h, w), m);
242
+ b.position.y = h / 2;
243
+ b.castShadow = b.receiveShadow = true;
244
+ env.dispose.push(b.geometry, m);
245
+ const o = group(b);
246
+ o.userData.keepRot = true;
247
+ return o;
248
+ }, true, 1, 1);
249
+ g.children.forEach((o) => {
250
+ if (!o.userData.keepRot) return;
251
+ o.rotation.y = Math.round(o.rotation.y / (PI / 2)) * (PI / 2);
252
+ if (Math.abs(o.position.z) < 14) o.position.z = -(16 + Math.abs(o.position.z));
253
+ });
254
+ if (day) env.dispose.push(day, lit);
255
+ g.add(at(box(400, 0.04, 9, 0x35373d, { noShadow: 1 }), 0, 0.02, 0), at(box(400, 0.2, 3, 0x9a9da3), 0, 0.1, -6), at(box(400, 0.2, 3, 0x9a9da3), 0, 0.1, 6));
256
+ for (let x = -120; x <= 120; x += 4) g.add(at(box(1.8, 0.05, 0.16, 0xf4f4f0, { noShadow: 1 }), x, 0.03, 0));
257
+ for (let x = -36; x <= 36; x += 12) g.add(at(THINGS.lamp(), x, 0.2, -5.4), at(THINGS.tree(), x + 6, 0.2, -6.4, 0, 0, 0, 0.8));
258
+ } else if (loc === 'space') {
259
+ const p1 = group(at(orb(14, 0xd98a4a), 0, 0, 0), at(torus(22, 1.2, 0xe8d0a0, { noShadow: 1 }), 0, 0, 0, PI / 2 - 0.3, 0, 0, [1, 1, 0.08]));
260
+ g.add(at(p1, -70, 30, -120, 0, 0, 0.3), at(orb(6, 0x6fb0e8), 60, -12, -90), at(orb(2.5, 0xc9ccd6), 30, 26, -60));
261
+ scatter(g, rand, 16, far + 4, far + 50, () => at(rockGeo(0.5 + rand() * 1.2, 0x7d7f88), 0, (rand() - 0.5) * 24, 0), false, 0.6, 1.6);
262
+ env.tick.push((t) => { p1.rotation.y = t * 0.02; });
263
+ } else if (loc === 'moon') {
264
+ scatter(g, rand, 30, 3, far + 60, () => group(at(torus(1.4, 0.22, 0x9ea0a6, { noShadow: 1 }), 0, 0.02, 0, PI / 2), at(cyl(1.3, 1.3, 0.03, 0x6f7177, { noShadow: 1 }, 14), 0, 0.015, 0)), true, 0.5, 2.6);
265
+ scatter(g, rand, 20, far, far + 50, () => THINGS.rock(0x8a8c92), false, 0.5, 2.5);
266
+ scatter(g, rand, 5, 70, 150, () => hill(20 + rand() * 20, 0x7f8187), true, 1, 1);
267
+ g.add(at(group(orb(11, 0x2f6fde), at(orb(11.05, 0x3fa34d), 0.6, 0.4, 0.3, 0, 0, 0, [0.9, 0.7, 0.95]), at(orb(11.3, 0xffffff, { opacity: 0.35 }), 0, 0, 0)), -50, 55, -150));
268
+ } else if (loc === 'ocean') {
269
+ water(0, 520, 0);
270
+ env.waterY = 0;
271
+ if (island > 0) {
272
+ g.add(at(cyl(island, island + 2.5, 1.4, 0xead7a4, null, 28), 0, -0.6, 0), at(palm(), -(island - 1.2), 0.08, -(island - 1.5), 0, 0, 0, 1.4));
273
+ }
274
+ scatter(g, rand, 5, far + 16 + island, far + 80, () => group(at(rockGeo(2.4, 0x6f7177), 0, 0.5, 0, 0.3, 0, 0, [1.3, 1, 1]), at(rockGeo(1.2, 0x7d7f88), 2.2, 0.2, 0.6)), true, 0.8, 2);
275
+ const buoy = at(group(at(cone(0.5, 1.2, 0xd63c33, null, 8), 0, 0.5, 0), at(orb(0.12, 0xffe24a, { emissive: 0xffe24a, glow: 2 }), 0, 1.2, 0)), R + 5, 0, -(R + 3));
276
+ g.add(buoy);
277
+ env.tick.push((t) => { buoy.position.y = sin(t * 1.4) * 0.1; buoy.rotation.z = sin(t * 1.1) * 0.12; });
278
+ } else if (loc === 'mountain') {
279
+ scatter(g, rand, 9, 110, 190, () => peak(40 + rand() * 30, 50 + rand() * 45, 0x6b7a86, true), true, 1, 1);
280
+ scatter(g, rand, 6, 70, 105, () => peak(26 + rand() * 14, 22 + rand() * 16, 0x5f7f58, false), true, 1, 1);
281
+ scatter(g, rand, 22, far + 2, far + 55, () => pine(false), true, 1.1, 2.1);
282
+ scatter(g, rand, 12, far, far + 30, things('rock'), true, 0.8, 3);
283
+ scatter(g, rand, 40, 1, far + 12, () => grass(0x5a8a48), false);
284
+ } else if (loc === 'farm') {
285
+ g.add(at(barn(), -(R + 9), 0, -(R + 10), 0, 0.5, 0));
286
+ for (let i = -7; i <= 7; i++) g.add(at(fence(), i * 2.1, 0, -(R + 5)));
287
+ scatter(g, rand, 6, far + 1, far + 9, () => hay(), true, 0.9, 1.2);
288
+ scatter(g, rand, 6, far + 12, far + 50, things('tree'), true, 1, 1.6);
289
+ scatter(g, rand, 50, 1, far + 15, () => grass(0x67a23f), false);
290
+ scatter(g, rand, 5, 90, 150, () => hill(28 + rand() * 22, 0x74ab49), true, 1, 1);
291
+ } else if (loc === 'road') {
292
+ g.add(at(box(520, 0.04, 9, 0x3c3e44, { noShadow: 1 }), 0, 0.02, 0), at(box(520, 0.05, 0.18, 0xf4f4f0, { noShadow: 1 }), 0, 0.03, 4.1), at(box(520, 0.05, 0.18, 0xf4f4f0, { noShadow: 1 }), 0, 0.03, -4.1));
293
+ for (let x = -150; x <= 150; x += 5) g.add(at(box(2.2, 0.05, 0.18, 0xf2c230, { noShadow: 1 }), x, 0.03, 0));
294
+ for (let x = -80; x <= 80; x += 10) g.add(at(THINGS.tree(), x + rand() * 3, 0, -(7.5 + rand() * 4), 0, rand() * 6, 0, 1 + rand() * 0.6));
295
+ scatter(g, rand, 10, far + 14, far + 60, things('tree'), true, 1, 1.7);
296
+ scatter(g, rand, 5, 90, 150, () => hill(28 + rand() * 22, 0x69a244), true, 1, 1);
297
+ } else if (loc === 'park') {
298
+ g.add(at(box(520, 0.04, 3.2, 0xd8c39a, { noShadow: 1 }), 0, 0.02, -(R + 2.5)), at(cyl(7, 7, 0.06, 0x3f93cf, { noShadow: 1 }, 24), R + 11, 0.03, -(R + 14)));
299
+ for (let x = -18; x <= 18; x += 12) g.add(at(THINGS.bench(), x, 0, -(R + 4.6)), at(THINGS.lamp(), x + 6, 0, -(R + 4.8)));
300
+ scatter(g, rand, 14, far + 5, far + 45, things('tree'), true, 1, 1.7);
301
+ scatter(g, rand, 12, far + 3, far + 25, () => bush(0x4f9a52));
302
+ scatter(g, rand, 26, 2, far + 10, () => THINGS.flower([0xf284b6, 0xf2c230, 0xf4f4f0][(rand() * 3) | 0]), false, 0.5, 0.9);
303
+ scatter(g, rand, 40, 1, far + 12, () => grass(0x5f9a3c), false);
304
+ }
305
+
306
+ // weather particles
307
+ if (!outer && !indoor && (weather === 'rain' || weather === 'storm' || weather === 'snow')) {
308
+ const snow = weather === 'snow', n = snow ? 1400 : weather === 'storm' ? 2600 : 1500, W = R * 2 + 26, H = 26;
309
+ const p = new Float32Array(n * (snow ? 3 : 6)), seed = new Float32Array(n * 3);
310
+ for (let i = 0; i < n * 3; i++) seed[i] = rand();
311
+ const geo = new THREE.BufferGeometry();
312
+ geo.setAttribute('position', new THREE.BufferAttribute(p, 3));
313
+ const obj = snow
314
+ ? new THREE.Points(geo, new THREE.PointsMaterial({ color: 0xffffff, size: 0.16, transparent: true, opacity: 0.95 }))
315
+ : new THREE.LineSegments(geo, new THREE.LineBasicMaterial({ color: 0xbfd6ea, transparent: true, opacity: 0.55 }));
316
+ obj.frustumCulled = false;
317
+ g.add(obj);
318
+ env.dispose.push(geo, obj.material);
319
+ const v = snow ? 1.7 : weather === 'storm' ? 34 : 26, slant = weather === 'storm' ? 0.35 : 0.08;
320
+ env.tick.push((t) => {
321
+ for (let i = 0; i < n; i++) {
322
+ const y = H - ((seed[i * 3 + 1] * H + t * v * (0.8 + seed[i * 3 + 2] * 0.4)) % H);
323
+ let x = (seed[i * 3] - 0.5) * W, z = (seed[i * 3 + 2] - 0.5) * W;
324
+ if (snow) {
325
+ x += sin(t * 0.9 + i) * 0.5;
326
+ p.set([x, y, z], i * 3);
327
+ } else {
328
+ x += (H - y) * slant;
329
+ p.set([x, y, z, x + slant * 0.7, y - 0.7, z], i * 6);
330
+ }
331
+ }
332
+ geo.attributes.position.needsUpdate = true;
333
+ });
334
+ if (weather === 'storm') {
335
+ const base = hemi.intensity;
336
+ env.tick.push((t) => {
337
+ const c = t % 5.3;
338
+ hemi.intensity = base + (c < 0.1 || (c > 0.2 && c < 0.27) ? 3.2 : 0);
339
+ });
340
+ }
341
+ }
342
+
343
+ env.update = (t) => { for (const f of env.tick) f(t); };
344
+ return env;
345
+ }
web/js/scene/layout.js ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Turns a scene description (plain JSON) into three.js objects, positions and motions.
2
+ import * as THREE from 'three';
3
+ import { LOCO, SPD_MUL, addZzz, speedOf, updateInstance } from './animate.js';
4
+ import { CREATURES } from './creatures.js';
5
+ import { buildEnvironment } from './environment.js';
6
+ import { PALETTE, hash, rng } from './prims.js';
7
+ import { THINGS } from './things.js';
8
+
9
+ export const BUILDERS = { ...CREATURES, ...THINGS };
10
+ export const SIZE_SCALE = { tiny: 0.4, small: 0.7, big: 1.5, giant: 2.6 };
11
+ const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
12
+
13
+ function makeGroup(ent) {
14
+ const rand = rng(hash(ent.id + ent.type));
15
+ const n = clamp(ent.n ?? 1, 1, 6), s0 = SIZE_SCALE[ent.size] ?? 1, color = ent.color ? PALETTE[ent.color] : undefined;
16
+ const build = BUILDERS[ent.type] ?? BUILDERS.box;
17
+ const G = { ent, insts: [], center: { x: 0, z: 0 }, deps: [], act: ent.act, R: 0 };
18
+ const cols = Math.ceil(Math.sqrt(n));
19
+ for (let i = 0; i < n; i++) {
20
+ const obj = build(color), rig = obj.userData.rig;
21
+ const scale = s0 * (n > 1 ? 0.9 + rand() * 0.2 : 1), d = rig.r * s0 * 2.15;
22
+ const col = i % cols, row = Math.floor(i / cols), inRow = Math.min(cols, n - row * cols);
23
+ const off = n > 1
24
+ ? { x: (col - (inRow - 1) / 2) * d + (rand() - 0.5) * d * 0.15, z: -(row - (Math.ceil(n / cols) - 1) / 2) * d * 0.9 + (rand() - 0.5) * d * 0.15 }
25
+ : { x: 0, z: 0 };
26
+ obj.scale.setScalar(scale);
27
+ G.insts.push({
28
+ ent, obj, rig, scale, off, base: new THREE.Vector3(), yaw0: (rig.kind === 'vehicle' ? 1.05 : 0.45) + (n > 1 ? (rand() - 0.5) * 0.5 : 0),
29
+ phase: n > 1 ? rand() * 1.5 : 0, spdMul: SPD_MUL[ent.spd] ?? 1, act: ent.act, motion: { kind: 'none' }, mount: null,
30
+ });
31
+ G.R = Math.max(G.R, Math.hypot(off.x, off.z) + rig.r * scale);
32
+ G.h = Math.max(G.h ?? 0, rig.h * scale);
33
+ }
34
+ return G;
35
+ }
36
+
37
+ function defaultMountAct(G) {
38
+ const g = G.insts[0].rig;
39
+ if (g.kind === 'quad' || g.kind === 'biped' || g.kind === 'bird') return 'walk';
40
+ if (g.kind === 'fish') return 'swim';
41
+ if (g.kind === 'vehicle') return g.flyer ? 'fly' : 'drive';
42
+ return undefined;
43
+ }
44
+
45
+ function motionFor(inst, act, c) {
46
+ const R = inst.rig.r * inst.scale;
47
+ if (LOCO.has(act)) {
48
+ const v = speedOf(inst, act);
49
+ return { kind: 'patrol', v, A: clamp(v * 1.6, 2.5, 7) };
50
+ }
51
+ if (act === 'circle') return { kind: 'circle', cx: c.x, cz: c.z, R: 2.2 + R, v: speedOf(inst, 'circle'), ph: 0 };
52
+ if (act === 'fly') {
53
+ const Rx = 4.5 + R;
54
+ return { kind: 'fly', cx: c.x, cz: c.z, Rx, Rz: 2.2 + R * 0.5, alt: Math.max(2.5, inst.rig.h * inst.scale * 1.3 + 1.2), w: speedOf(inst, 'fly') / Rx, ph: 0 };
55
+ }
56
+ return { kind: 'none' };
57
+ }
58
+
59
+ export function buildScene(sc) {
60
+ const root = new THREE.Group(), actors = new THREE.Group();
61
+ root.add(actors);
62
+ const groups = sc.ents.map(makeGroup), byId = new Map(groups.map((G) => [G.ent.id, G]));
63
+ const space = sc.loc === 'space';
64
+
65
+ // ---- relation graph
66
+ for (const G of groups) {
67
+ const T = G.ent.rel && byId.get(G.ent.ref);
68
+ if (T && T !== G) { G.target = T; G.rel = G.ent.rel; T.deps.push(G); }
69
+ }
70
+ for (const G of groups) { // break cycles
71
+ const seen = new Set([G]);
72
+ for (let T = G.target; T; T = T.target) {
73
+ if (seen.has(T)) { G.target.deps = G.target.deps.filter((d) => d !== G); G.target = G.rel = undefined; break; }
74
+ seen.add(T);
75
+ }
76
+ }
77
+ for (const G of groups) {
78
+ if (G.rel === 'ride' && !G.target.act) G.target.act = defaultMountAct(G.target);
79
+ if (G.rel === 'around' && !G.act) G.act = 'walk';
80
+ if (G.rel === 'over' && !['jump', 'fly', 'float', 'bounce'].includes(G.act)) G.act = 'jump';
81
+ if (G.rel === 'chase') {
82
+ G.act = 'run';
83
+ if (!LOCO.has(G.target.act) || G.target.act === 'swim') G.target.act = 'run';
84
+ G.target.chased = true;
85
+ }
86
+ }
87
+ for (const G of groups) {
88
+ if (!G.act) G.act = space ? 'float' : 'idle';
89
+ for (const i of G.insts) i.act = G.act;
90
+ }
91
+
92
+ // ---- how much room each free group needs, including whatever depends on it
93
+ const chaseR = (G, D) => Math.max(4, G.R + D.R + 2.5);
94
+ const reach = (G) => {
95
+ let r = G.R + (G.act === 'circle' ? 2.2 + G.R : 0);
96
+ for (const D of G.deps) {
97
+ if (D.rel === 'near' || D.rel === 'behind' || D.rel === 'front') r += 2 * reach(D) + 0.5;
98
+ else if (D.rel === 'around') r += 2 * D.R + 1;
99
+ else if (D.rel === 'over') r += D.R + 1;
100
+ else if (D.rel === 'chase') r = Math.max(r, chaseR(G, D) + Math.max(G.R, D.R));
101
+ }
102
+ return r;
103
+ };
104
+ const free = groups.filter((G) => !G.target);
105
+ const roams = (G) => LOCO.has(G.act) && !G.chased;
106
+ const row = free.filter((G) => !roams(G)), lanes = free.filter(roams);
107
+ const width = row.reduce((a, G) => a + 2 * reach(G), 0) + 0.9 * Math.max(0, row.length - 1);
108
+ let x = -width / 2, depth = row.reduce((a, G) => Math.max(a, reach(G)), 0);
109
+ for (const G of row) { const r = reach(G); G.center = { x: x + r, z: 0 }; x += 2 * r + 0.9; }
110
+ let front = depth, back = depth;
111
+ lanes.forEach((G, k) => {
112
+ const r = reach(G);
113
+ if (!row.length && k === 0) { G.center = { x: 0, z: 0 }; front = back = r; return; }
114
+ if (k % 2 === 0) { G.center = { x: 0, z: front + r + 0.5 }; front += 2 * r + 0.5; }
115
+ else { G.center = { x: 0, z: -(back + r + 0.5) }; back += 2 * r + 0.5; }
116
+ });
117
+
118
+ // ---- place dependents, targets first
119
+ const done = new Set();
120
+ const place = (G) => {
121
+ if (done.has(G)) return;
122
+ done.add(G);
123
+ const T = G.target;
124
+ if (T) {
125
+ place(T);
126
+ const c = T.center, gap = G.R + T.R;
127
+ T.side = (T.side ?? 0) + 1;
128
+ const sgn = T.side % 2 ? -1 : 1, k = Math.ceil(T.side / 2);
129
+ if (G.rel === 'near' && (LOCO.has(G.act) || LOCO.has(T.act))) G.center = { x: c.x, z: c.z - sgn * k * (gap + 0.5) }; // side by side lanes
130
+ else if (G.rel === 'near') G.center = { x: c.x + sgn * k * (gap + 0.4), z: c.z + 0.25 };
131
+ else if (G.rel === 'behind') G.center = { x: c.x + 0.3 * G.R, z: c.z - (gap + 0.5) };
132
+ else if (G.rel === 'front') G.center = { x: c.x - 0.3 * G.R, z: c.z + (gap + 0.5) };
133
+ else G.center = { x: c.x, z: c.z };
134
+ }
135
+ for (const i of G.insts) {
136
+ i.base.set(G.center.x + i.off.x, 0, G.center.z + i.off.z);
137
+ i.motion = motionFor(i, G.act, { x: G.center.x, z: G.center.z });
138
+ }
139
+ if (!T) return;
140
+ const c = T.center;
141
+ G.insts.forEach((i, k) => {
142
+ const r = i.rig.r * i.scale;
143
+ if (G.rel === 'ride' || G.rel === 'on') {
144
+ const m = T.insts[k];
145
+ if (!m) { i.base.set(c.x + T.R + r + 0.3 + k * 0.2, 0, c.z + 0.5 * k); i.motion = { kind: 'none' }; return; }
146
+ i.mount = m; i.mode = G.rel; i.seat = m.rig.seat; i.motion = { kind: 'none' };
147
+ i.obj.scale.setScalar(i.scale / m.scale);
148
+ (m.rig.body ?? m.obj).add(i.obj);
149
+ } else if (G.rel === 'around') {
150
+ const v = speedOf(i, G.act === 'fly' ? 'fly' : G.act);
151
+ const Rc = T.R + G.R + 0.9;
152
+ i.motion = G.act === 'fly'
153
+ ? { kind: 'fly', cx: c.x, cz: c.z, Rx: Rc, Rz: Rc, alt: Math.max(1.5, T.h * 0.6), w: v / Rc, ph: k * 0.6 }
154
+ : { kind: 'circle', cx: c.x, cz: c.z, R: Rc, v: LOCO.has(G.act) ? v : 1.6, ph: k * 0.5 };
155
+ i.off = { x: 0, z: 0 };
156
+ } else if (G.rel === 'over') {
157
+ if (G.act === 'jump' || G.act === 'bounce') {
158
+ i.act = 'jump';
159
+ i.motion = { kind: 'hopover', cx: c.x, cz: c.z, d: T.R + r + 0.7, H: T.h + 0.6 + i.rig.h * i.scale * 0.2, P: 1.7 + T.R * 0.25 };
160
+ } else {
161
+ const Rc = T.R + 1.4;
162
+ i.motion = { kind: 'fly', cx: c.x, cz: c.z, Rx: Rc, Rz: Rc * 0.75, alt: T.h + 1.0, w: 3.2 / Rc, ph: k * 0.7 };
163
+ i.act = G.act === 'float' ? 'fly' : G.act;
164
+ }
165
+ } else if (G.rel === 'chase') {
166
+ const Rc = chaseR(T, G), v = Math.min(speedOf(i, 'run'), speedOf(T.insts[0], T.act));
167
+ i.motion = { kind: 'circle', cx: c.x, cz: c.z, R: Rc, v, ph: 0 };
168
+ i.off = { x: i.off.x * 0.4, z: i.off.z * 0.4 };
169
+ for (const t of T.insts) { t.motion = { kind: 'circle', cx: c.x, cz: c.z, R: Rc, v, ph: 0.25 + (T.R + G.R + 0.8) / Rc }; t.off = { x: t.off.x * 0.4, z: t.off.z * 0.4 }; }
170
+ }
171
+ });
172
+ };
173
+ groups.forEach(place);
174
+
175
+ // ---- ocean: land things get an island, swimmers are pushed off it
176
+ const insts = groups.flatMap((G) => G.insts);
177
+ let island = 0;
178
+ if (sc.loc === 'ocean') {
179
+ const wet = (G) => G.insts[0].rig.swims || G.act === 'swim' || G.act === 'fly' || (G.insts[0].mount && wet(G.target));
180
+ const land = groups.filter((G) => !wet(G));
181
+ for (const G of land) island = Math.max(island, Math.hypot(G.center.x, G.center.z) + G.R + (G.insts[0].motion.A ?? G.insts[0].motion.R ?? 0) + 1.2);
182
+ if (island) {
183
+ let z = island + 0.5;
184
+ for (const G of groups) {
185
+ if (!wet(G) || G.target) continue;
186
+ const dz = z + G.R + 0.8 - G.center.z;
187
+ z += 2 * G.R + 1;
188
+ for (const D of [G, ...groups.filter((o) => o.target === G)]) {
189
+ D.center.z += dz;
190
+ for (const i of D.insts) { i.base.z += dz; if (i.motion.cz != null) i.motion.cz += dz; }
191
+ }
192
+ }
193
+ }
194
+ }
195
+ for (const i of insts) {
196
+ if (!i.mount) actors.add(i.obj);
197
+ if (i.act === 'sleep') addZzz(i);
198
+ }
199
+
200
+ // ---- measure where everything goes over time, to frame the camera and size the stage
201
+ const ctx = { waterY: sc.loc === 'ocean' ? 0 : null };
202
+ const box = new THREE.Box3(), fbox = new THREE.Box3(), p = new THREE.Vector3();
203
+ const focus = insts[0];
204
+ for (let k = 0; k < 48; k++) {
205
+ for (const i of insts) updateInstance(i, k * 0.41, ctx);
206
+ root.updateMatrixWorld(true);
207
+ for (const i of insts) {
208
+ i.obj.getWorldPosition(p);
209
+ const r = i.rig.r * i.scale, h = i.rig.h * i.scale;
210
+ for (const b of i === focus ? [box, fbox] : [box]) {
211
+ b.expandByPoint(new THREE.Vector3(p.x - r, Math.max(0, p.y - 0.2), p.z - r));
212
+ b.expandByPoint(new THREE.Vector3(p.x + r, p.y + h, p.z + r));
213
+ }
214
+ }
215
+ }
216
+ if (!insts.length) { box.set(new THREE.Vector3(-2, 0, -2), new THREE.Vector3(2, 2, 2)); fbox.copy(box); }
217
+ const stageR = Math.max(4, Math.abs(box.min.x), Math.abs(box.max.x), Math.abs(box.min.z), Math.abs(box.max.z));
218
+ const env = buildEnvironment(sc, { R: stageR, island });
219
+ root.add(env.group);
220
+ ctx.waterY = env.waterY;
221
+
222
+ return {
223
+ root, actors, env, insts, focus, box, fbox, stageR,
224
+ update(t) {
225
+ for (const i of insts) updateInstance(i, t, ctx);
226
+ env.update(t);
227
+ },
228
+ dispose() { for (const d of env.dispose) d.dispose?.(); },
229
+ };
230
+ }
web/js/scene/prims.js ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Low-poly building blocks shared by every object builder.
2
+ import * as THREE from 'three';
3
+
4
+ export const PALETTE = {
5
+ red: 0xd63c33, blue: 0x2f6fde, green: 0x3fa34d, yellow: 0xf2c230, orange: 0xf08a24, purple: 0x8a4fd3,
6
+ pink: 0xf284b6, white: 0xf4f4f0, black: 0x2a2a30, gray: 0x8d9199, brown: 0x8a5a3b, gold: 0xe2b23a,
7
+ silver: 0xc4c9d1, cyan: 0x2ec4d6,
8
+ };
9
+
10
+ const geos = new Map();
11
+ const mats = new Map();
12
+ const geo = (key, make) => geos.get(key) ?? (geos.set(key, make()), geos.get(key));
13
+
14
+ export function mat(color, o) {
15
+ o = o ?? {};
16
+ const key = `${color}|${o.emissive ?? ''}|${o.opacity ?? ''}|${o.metal ?? ''}|${o.basic ?? ''}|${o.side ?? ''}|${o.glow ?? ''}`;
17
+ if (mats.has(key)) return mats.get(key);
18
+ const m = o.basic
19
+ ? new THREE.MeshBasicMaterial({ color })
20
+ : new THREE.MeshStandardMaterial({
21
+ color, flatShading: true, roughness: o.metal ? 0.38 : 0.86, metalness: o.metal ? 0.35 : 0,
22
+ emissive: o.emissive ?? 0x000000, emissiveIntensity: o.emissive ? (o.glow ?? 1) : 0,
23
+ });
24
+ if (o.opacity != null) { m.transparent = true; m.opacity = o.opacity; m.depthWrite = false; }
25
+ if (o.side) m.side = THREE.DoubleSide;
26
+ mats.set(key, m);
27
+ return m;
28
+ }
29
+
30
+ function mk(g, color, o) {
31
+ const m = new THREE.Mesh(g, mat(color, o));
32
+ m.castShadow = !(o && (o.opacity != null || o.noShadow));
33
+ m.receiveShadow = true;
34
+ return m;
35
+ }
36
+ export const box = (w, h, d, c, o) => mk(geo(`b${w},${h},${d}`, () => new THREE.BoxGeometry(w, h, d)), c, o);
37
+ export const ball = (r, c, o) => mk(geo(`s${r}`, () => new THREE.IcosahedronGeometry(r, 1)), c, o);
38
+ export const orb = (r, c, o) => mk(geo(`o${r}`, () => new THREE.SphereGeometry(r, 14, 10)), c, o);
39
+ export const cyl = (rt, rb, h, c, o, seg = 10) =>
40
+ mk(geo(`c${rt},${rb},${h},${seg}`, () => new THREE.CylinderGeometry(rt, rb, h, seg)), c, o);
41
+ export const cone = (r, h, c, o, seg = 10) => mk(geo(`k${r},${h},${seg}`, () => new THREE.ConeGeometry(r, h, seg)), c, o);
42
+ export const torus = (R, r, c, o) => mk(geo(`t${R},${r}`, () => new THREE.TorusGeometry(R, r, 6, 14)), c, o);
43
+ export const rockGeo = (r, c, o) => mk(geo(`d${r}`, () => new THREE.DodecahedronGeometry(r, 0)), c, o);
44
+
45
+ /** Position/rotate/scale helper that returns the object so calls can be nested. */
46
+ export function at(obj, x = 0, y = 0, z = 0, rx = 0, ry = 0, rz = 0, s) {
47
+ obj.position.set(x, y, z);
48
+ obj.rotation.set(rx, ry, rz);
49
+ if (s != null) Array.isArray(s) ? obj.scale.set(...s) : obj.scale.setScalar(s);
50
+ return obj;
51
+ }
52
+
53
+ /** A pivot: children rotate around (x, y, z). */
54
+ export function joint(x, y, z, ...children) {
55
+ const g = new THREE.Group();
56
+ g.position.set(x, y, z);
57
+ for (const c of children) g.add(c);
58
+ return g;
59
+ }
60
+
61
+ export function group(...children) {
62
+ const g = new THREE.Group();
63
+ for (const c of children) g.add(c);
64
+ return g;
65
+ }
66
+
67
+ const _c = new THREE.Color();
68
+ /** Lighter (k > 0) or darker (k < 0) version of a hex colour. */
69
+ export function tint(hex, k) {
70
+ _c.setHex(hex);
71
+ const hsl = {};
72
+ _c.getHSL(hsl);
73
+ _c.setHSL(hsl.h, hsl.s, Math.min(0.97, Math.max(0.04, hsl.l + k)));
74
+ return _c.getHex();
75
+ }
76
+
77
+ export const eyes = (parent, x, y, z, r = 0.05, c = 0x151518) => {
78
+ parent.add(at(orb(r, c), x, y, z), at(orb(r, c), -x, y, z));
79
+ };
80
+
81
+ /** Deterministic random numbers so a scene looks the same every time it is rebuilt. */
82
+ export function rng(seed) {
83
+ let s = (seed >>> 0) || 1;
84
+ return () => {
85
+ s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0;
86
+ return s / 4294967296;
87
+ };
88
+ }
89
+ export const hash = (str) => { let h = 2166136261; for (const ch of str) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); return h >>> 0; };
90
+
91
+ /**
92
+ * Wrap finished parts into a rig the animator understands.
93
+ * parts: { body, head, tail, legs[], arms[], wings[], wheels[], spinners[], fins[] }
94
+ */
95
+ export function rig(root, kind, dims, parts = {}) {
96
+ const all = [];
97
+ for (const v of Object.values(parts)) for (const p of Array.isArray(v) ? v : [v]) if (p) all.push(p);
98
+ for (const p of all) p.userData.rest = { p: p.position.clone(), r: p.rotation.clone(), s: p.scale.clone() };
99
+ root.userData.rig = { kind, h: 1, r: 0.5, top: 1, seat: [0, 1, 0], ...dims, ...parts, all };
100
+ return root;
101
+ }
web/js/scene/stage.js ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Renderer, camera and the frame loop around a built scene.
2
+ import * as THREE from 'three';
3
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
4
+ import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
5
+ import { buildScene } from './layout.js';
6
+
7
+ const SHOT = { // distance factor, elevation (radians)
8
+ close: [0.72, 0.1], medium: [1.0, 0.2], wide: [1.75, 0.33], top: [1.25, 1.25], low: [0.95, 0.03],
9
+ };
10
+ const FOV = 38;
11
+
12
+ export class Stage {
13
+ constructor(canvas) {
14
+ this.canvas = canvas;
15
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: true });
16
+ this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
17
+ this.renderer.shadowMap.enabled = true;
18
+ this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
19
+ this.renderer.toneMapping = THREE.NeutralToneMapping;
20
+ this.scene = new THREE.Scene();
21
+ this.camera = new THREE.PerspectiveCamera(FOV, 1, 0.1, 600);
22
+ this.controls = new OrbitControls(this.camera, canvas);
23
+ this.controls.enableDamping = true;
24
+ this.controls.maxPolarAngle = Math.PI / 2 - 0.01;
25
+ this.t = 0; this.last = performance.now(); this.paused = false; this.built = null; this.sc = null;
26
+ this._p = new THREE.Vector3(); this._prev = new THREE.Vector3(); this._zoom = 1; this._pan = 0;
27
+ new ResizeObserver(() => this.resize()).observe(canvas.parentElement);
28
+ this.resize();
29
+ this.renderer.setAnimationLoop(() => this.frame());
30
+ }
31
+
32
+ resize() {
33
+ const el = this.canvas.parentElement, w = el.clientWidth || 800, h = el.clientHeight || 600;
34
+ this.renderer.setSize(w, h, false);
35
+ this.camera.aspect = w / h;
36
+ this.camera.updateProjectionMatrix();
37
+ }
38
+
39
+ /** Rebuild everything from a scene description. resetCamera=false keeps the user's current view. */
40
+ setScene(sc, resetCamera = true) {
41
+ const old = this.built, prevBox = old?.box;
42
+ if (old) { this.scene.remove(old.root); old.dispose(); }
43
+ const b = this.built = buildScene(sc);
44
+ this.sc = sc;
45
+ this.scene.add(b.root);
46
+ this.scene.background = b.env.background;
47
+ this.scene.fog = b.env.fog;
48
+ this.controls.maxPolarAngle = sc.loc === 'space' ? Math.PI : Math.PI / 2 - 0.01;
49
+ b.update(this.t);
50
+ b.root.updateMatrixWorld(true);
51
+ const view = `${sc.shot}|${sc.zoom}|${sc.cam}`;
52
+ const moved = !prevBox || prevBox.min.distanceTo(b.box.min) + prevBox.max.distanceTo(b.box.max) > 0.6;
53
+ if (resetCamera || view !== this._view || moved) this.frameCamera();
54
+ this._view = view;
55
+ this.controls.autoRotate = sc.cam === 'orbit';
56
+ this.controls.autoRotateSpeed = 2.2;
57
+ if (b.focus) b.focus.obj.getWorldPosition(this._prev);
58
+ }
59
+
60
+ frameCamera() {
61
+ const b = this.built, sc = this.sc;
62
+ const tight = (sc.shot === 'close' || sc.cam === 'follow') && b.focus;
63
+ const box = tight ? b.fbox.clone() : b.box;
64
+ if (sc.cam === 'follow' && b.focus) { // frame the subject itself, not its whole path
65
+ const g = b.focus.rig, s = b.focus.scale, p = b.focus.obj.getWorldPosition(new THREE.Vector3());
66
+ box.set(new THREE.Vector3(p.x - g.r * s * 1.6, p.y, p.z - g.r * s * 1.6), new THREE.Vector3(p.x + g.r * s * 1.6, p.y + g.h * s, p.z + g.r * s * 1.6));
67
+ }
68
+ const c = box.getCenter(new THREE.Vector3()), size = box.getSize(new THREE.Vector3());
69
+ const aspect = Math.max(0.6, this.camera.aspect);
70
+ const half = Math.max(size.y * 0.62, (Math.hypot(size.x, size.z) * 0.5) / aspect, 1.2) * 1.3;
71
+ const [k, el] = SHOT[sc.shot] ?? SHOT.medium;
72
+ const dist = (half / Math.tan((FOV * Math.PI) / 360)) * k * 1.22 ** (sc.zoom ?? 0);
73
+ const az = 0.42;
74
+ if (sc.shot === 'low') c.y = Math.max(c.y, size.y * 0.55);
75
+ this.controls.target.copy(c);
76
+ this.camera.position.set(c.x + dist * Math.sin(az) * Math.cos(el), Math.max(0.35, c.y + dist * Math.sin(el)), c.z + dist * Math.cos(az) * Math.cos(el));
77
+ if (sc.loc !== 'space' && sc.shot === 'low') this.camera.position.y = 0.4;
78
+ this.camera.near = Math.max(0.05, dist / 200);
79
+ this.camera.updateProjectionMatrix();
80
+ this._zoom = 1; this._pan = 0;
81
+ this.controls.update();
82
+ }
83
+
84
+ frame() {
85
+ const now = performance.now(), dt = Math.min(0.1, (now - this.last) / 1000);
86
+ this.last = now;
87
+ if (!this.paused) this.t += dt;
88
+ const b = this.built;
89
+ if (b) {
90
+ b.update(this.t);
91
+ const cam = this.sc.cam, tg = this.controls.target, cp = this.camera.position;
92
+ if (cam === 'follow' && b.focus) {
93
+ b.root.updateMatrixWorld(true);
94
+ b.focus.obj.getWorldPosition(this._p);
95
+ const d = this._p.clone().sub(this._prev);
96
+ d.y *= 0.3;
97
+ tg.add(d); cp.add(d);
98
+ this._prev.copy(this._p);
99
+ } else if (cam === 'pan') {
100
+ const x = Math.sin(this.t * 0.45) * b.stageR * 0.7, d = x - this._pan;
101
+ this._pan = x; tg.x += d; cp.x += d;
102
+ } else if (cam === 'zoomin' || cam === 'zoomout') {
103
+ const u = 0.5 - 0.5 * Math.cos(this.t * 0.55), z = cam === 'zoomin' ? 1 - 0.5 * u : 1 + 0.8 * u;
104
+ cp.sub(tg).multiplyScalar(z / this._zoom).add(tg);
105
+ this._zoom = z;
106
+ }
107
+ }
108
+ this.controls.update();
109
+ this.renderer.render(this.scene, this.camera);
110
+ }
111
+
112
+ /** Static snapshot of the current frame as a .glb (animations are procedural and are not exported). */
113
+ exportGLB() {
114
+ return new Promise((resolve, reject) => {
115
+ if (!this.built) return reject(new Error('empty scene'));
116
+ new GLTFExporter().parse(this.built.actors, (buf) => resolve(new Blob([buf], { type: 'model/gltf-binary' })), reject, { binary: true, onlyVisible: true });
117
+ });
118
+ }
119
+ }
web/js/scene/things.js ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Vehicles and props. Forward is +Z, up is +Y, resting on y = 0.
2
+ import * as THREE from 'three';
3
+ import { at, ball, box, cone, cyl, joint, orb, rig, rockGeo, tint, torus } from './prims.js';
4
+
5
+ const DARK = 0x26262b, WHITE = 0xf4f4f0, GLASS = 0x26405e, WOOD = 0x8a5a3b, HALF = Math.PI / 2;
6
+ const glow = (c, g = 1.2) => ({ emissive: c, glow: g });
7
+
8
+ function shell() {
9
+ const root = new THREE.Group(), body = new THREE.Group();
10
+ root.add(body);
11
+ return [root, body];
12
+ }
13
+ function wheel(x, y, z, r, w = 0.2) {
14
+ return joint(x, y, z, at(cyl(r, r, w, DARK, null, 12), 0, 0, 0, 0, 0, HALF), at(cyl(r * 0.5, r * 0.5, w + 0.02, 0xb8bcc4, null, 8), 0, 0, 0, 0, 0, HALF));
15
+ }
16
+ function spinner(axis, always, x, y, z, ...children) {
17
+ const j = joint(x, y, z, ...children);
18
+ j.userData.axis = axis;
19
+ j.userData.always = always;
20
+ return j;
21
+ }
22
+
23
+ // ------------------------------------------------------------------ vehicles
24
+ function car(C) {
25
+ const c = C ?? 0xd63c33, [root, body] = shell();
26
+ body.add(at(box(1.5, 0.5, 3.2, c), 0, 0.6, 0), at(box(1.3, 0.48, 1.7, tint(c, 0.08)), 0, 1.07, -0.15),
27
+ at(box(1.32, 0.34, 1.5, GLASS), 0, 1.07, -0.15), at(box(1.1, 0.34, 1.72, GLASS), 0, 1.07, -0.15),
28
+ at(box(0.3, 0.14, 0.04, 0xfff3c4, glow(0xfff3c4)), 0.5, 0.66, 1.6), at(box(0.3, 0.14, 0.04, 0xfff3c4, glow(0xfff3c4)), -0.5, 0.66, 1.6),
29
+ at(box(0.3, 0.12, 0.04, 0xff3b30, glow(0xff3b30, 0.8)), 0.5, 0.66, -1.6), at(box(0.3, 0.12, 0.04, 0xff3b30, glow(0xff3b30, 0.8)), -0.5, 0.66, -1.6),
30
+ at(box(1.56, 0.12, 0.2, DARK), 0, 0.4, 1.55), at(box(1.56, 0.12, 0.2, DARK), 0, 0.4, -1.55));
31
+ const wheels = [[0.74, 1.05], [-0.74, 1.05], [0.74, -1.05], [-0.74, -1.05]].map(([x, z]) => wheel(x, 0.34, z, 0.34));
32
+ body.add(...wheels);
33
+ return rig(root, 'vehicle', { h: 1.32, r: 1.8, top: 1.31, seat: [0, 1.31, -0.15] }, { body, wheels });
34
+ }
35
+
36
+ function truck(C) {
37
+ const c = C ?? 0x2f6fde, [root, body] = shell();
38
+ body.add(at(box(1.8, 0.25, 5.2, DARK), 0, 0.62, -0.2), at(box(1.8, 1.4, 1.4, c), 0, 1.4, 1.7), at(box(1.82, 0.5, 1.0, GLASS), 0, 1.72, 1.8),
39
+ at(box(1.5, 0.5, 1.42, GLASS), 0, 1.72, 1.7), at(box(1.9, 1.9, 3.5, 0xe6e8ec), 0, 1.7, -0.95), at(box(1.92, 0.2, 3.52, tint(c, -0.1)), 0, 1.2, -0.95),
40
+ at(box(0.3, 0.16, 0.04, 0xfff3c4, glow(0xfff3c4)), 0.6, 0.95, 2.41), at(box(0.3, 0.16, 0.04, 0xfff3c4, glow(0xfff3c4)), -0.6, 0.95, 2.41));
41
+ const wheels = [];
42
+ for (const z of [1.7, -0.6, -1.9]) for (const x of [0.85, -0.85]) wheels.push(wheel(x, 0.42, z, 0.42, 0.26));
43
+ body.add(...wheels);
44
+ return rig(root, 'vehicle', { h: 2.65, r: 2.9, top: 2.65, seat: [0, 2.65, -0.9] }, { body, wheels });
45
+ }
46
+
47
+ function bus(C) {
48
+ const c = C ?? 0xf2c230, [root, body] = shell();
49
+ body.add(at(box(1.9, 1.9, 5.2, c), 0, 1.4, 0), at(box(1.92, 0.6, 4.6, GLASS), 0, 1.75, -0.1), at(box(1.6, 0.7, 5.22, GLASS), 0, 1.7, 0),
50
+ at(box(1.94, 0.12, 5.24, tint(c, -0.18)), 0, 1.05, 0), at(box(0.6, 1.3, 0.04, tint(c, -0.3)), 0.95, 1.15, 1.6, 0, HALF, 0),
51
+ at(box(0.3, 0.16, 0.04, 0xfff3c4, glow(0xfff3c4)), 0.6, 0.75, 2.61), at(box(0.3, 0.16, 0.04, 0xfff3c4, glow(0xfff3c4)), -0.6, 0.75, 2.61));
52
+ const wheels = [[0.9, 1.7], [-0.9, 1.7], [0.9, -1.7], [-0.9, -1.7]].map(([x, z]) => wheel(x, 0.42, z, 0.42, 0.26));
53
+ body.add(...wheels);
54
+ return rig(root, 'vehicle', { h: 2.4, r: 2.9, top: 2.36, seat: [0, 2.36, 0] }, { body, wheels });
55
+ }
56
+
57
+ function bike(C) {
58
+ const c = C ?? 0xd63c33, [root, body] = shell();
59
+ const wheels = [0.56, -0.56].map((z) => joint(0, 0.36, z, at(torus(0.33, 0.035, DARK), 0, 0, 0, 0, HALF, 0),
60
+ at(box(0.02, 0.64, 0.02, 0xb8bcc4), 0, 0, 0), at(box(0.02, 0.02, 0.64, 0xb8bcc4), 0, 0, 0)));
61
+ const tube = (len, y, z, rx) => at(box(0.05, len, 0.05, c), 0, y, z, rx);
62
+ body.add(...wheels, tube(0.62, 0.62, -0.22, 0.3), tube(0.66, 0.84, 0.1, HALF + 0.05), tube(0.7, 0.58, 0.14, -0.85),
63
+ tube(0.5, 0.42, -0.36, HALF + 0.25), tube(0.62, 0.64, 0.46, -0.3), at(box(0.5, 0.04, 0.04, DARK), 0, 0.98, 0.38),
64
+ at(box(0.16, 0.05, 0.28, DARK), 0, 0.95, -0.3), at(box(0.3, 0.04, 0.06, DARK), 0, 0.34, -0.08));
65
+ return rig(root, 'vehicle', { h: 1.0, r: 0.95, top: 0.97, seat: [0, 0.97, -0.3], narrow: true }, { body, wheels });
66
+ }
67
+
68
+ function skateboard(C) {
69
+ const c = C ?? 0x8a4fd3, [root, body] = shell();
70
+ body.add(at(box(0.3, 0.04, 0.8, c), 0, 0.14, 0), at(box(0.3, 0.04, 0.2, c), 0, 0.17, 0.48, -0.35), at(box(0.3, 0.04, 0.2, c), 0, 0.17, -0.48, 0.35),
71
+ at(box(0.26, 0.04, 0.06, 0xb8bcc4), 0, 0.1, 0.3), at(box(0.26, 0.04, 0.06, 0xb8bcc4), 0, 0.1, -0.3));
72
+ const wheels = [[0.13, 0.3], [-0.13, 0.3], [0.13, -0.3], [-0.13, -0.3]].map(([x, z]) =>
73
+ joint(x, 0.06, z, at(cyl(0.06, 0.06, 0.06, 0xf4f4f0, null, 8), 0, 0, 0, 0, 0, HALF)));
74
+ body.add(...wheels);
75
+ return rig(root, 'vehicle', { h: 0.2, r: 0.6, top: 0.16, seat: [0, 0.16, 0], board: true }, { body, wheels });
76
+ }
77
+
78
+ function boat(C) {
79
+ const c = C ?? 0xf4f4f0, [root, body] = shell();
80
+ body.add(at(box(1.3, 0.55, 2.6, c), 0, 0.3, -0.2), at(cone(0.92, 1.2, c, null, 4), 0, 0.3, 1.7, HALF, Math.PI / 4, 0, [1, 1, 0.42]),
81
+ at(box(1.34, 0.12, 2.62, 0x2f6fde), 0, 0.5, -0.2), at(box(1.1, 0.06, 2.4, WOOD), 0, 0.59, -0.2),
82
+ at(box(0.8, 0.5, 0.9, tint(c, -0.08)), 0, 0.85, -0.8), at(box(0.82, 0.2, 0.7, GLASS), 0, 0.92, -0.8),
83
+ at(cyl(0.04, 0.04, 2.4, WOOD, null, 6), 0, 1.8, 0.3), at(box(0.03, 1.8, 1.1, WHITE, { side: 1 }), 0, 1.95, -0.3, 0, 0, 0),
84
+ at(cone(0.5, 0.35, 0xd63c33, null, 3), 0, 3.05, 0.1, 0, 0, HALF, [0.1, 1, 1]));
85
+ return rig(root, 'vehicle', { h: 3.2, r: 1.9, top: 0.62, seat: [0, 0.62, 0.4], swims: true, floats: true }, { body });
86
+ }
87
+
88
+ function plane(C) {
89
+ const c = C ?? 0xf4f4f0, k = tint(c, -0.45) === c ? 0xd63c33 : 0xd63c33, [root, body] = shell();
90
+ const y = 1.0;
91
+ body.add(at(cyl(0.36, 0.3, 2.6, c, null, 10), 0, y, 0, HALF), at(cone(0.3, 1.0, c, null, 10), 0, y, -1.8, -HALF),
92
+ at(cone(0.36, 0.5, k, null, 10), 0, y, 1.55, HALF), at(box(4.6, 0.08, 0.85, c), 0, y - 0.1, 0.3), at(box(4.62, 0.09, 0.2, k), 0, y - 0.1, 0.62),
93
+ at(box(1.6, 0.06, 0.5, c), 0, y + 0.05, -1.9), at(box(0.06, 0.7, 0.55, k), 0, y + 0.4, -1.9),
94
+ at(box(0.5, 0.26, 0.7, GLASS), 0, y + 0.3, 0.55), at(cyl(0.03, 0.03, 0.6, DARK, null, 5), 0.5, 0.5, 0.5), at(cyl(0.03, 0.03, 0.6, DARK, null, 5), -0.5, 0.5, 0.5));
95
+ const wheels = [wheel(0.5, 0.2, 0.5, 0.2, 0.1), wheel(-0.5, 0.2, 0.5, 0.2, 0.1), wheel(0, 0.14, -1.9, 0.14, 0.08)];
96
+ const prop = spinner('z', false, 0, y, 1.82, at(box(1.5, 0.12, 0.03, DARK), 0, 0, 0), at(box(0.12, 1.5, 0.03, DARK), 0, 0, 0));
97
+ body.add(...wheels, prop);
98
+ return rig(root, 'vehicle', { h: 1.75, r: 2.4, top: 1.36, seat: [0, 1.36, 0], flyer: true }, { body, wheels, spinners: [prop] });
99
+ }
100
+
101
+ function rocket(C) {
102
+ const c = C ?? 0xf4f4f0, [root, body] = shell();
103
+ body.add(at(cyl(0.45, 0.45, 2.2, c, null, 12), 0, 1.6, 0), at(cone(0.45, 0.9, 0xd63c33, null, 12), 0, 3.15, 0),
104
+ at(cyl(0.3, 0.42, 0.3, 0x55585e, null, 12), 0, 0.42, 0), at(orb(0.19, GLASS), 0, 2.1, 0.36), at(torus(0.2, 0.04, 0xb8bcc4), 0, 2.1, 0.4),
105
+ at(cyl(0.455, 0.455, 0.14, 0xd63c33, null, 12), 0, 1.0, 0));
106
+ for (let i = 0; i < 3; i++) {
107
+ const a = i * 2.094;
108
+ body.add(at(box(0.06, 0.9, 0.6, 0xd63c33), Math.sin(a) * 0.6, 0.6, Math.cos(a) * 0.6, 0, a, 0));
109
+ }
110
+ const flame = joint(0, 0.3, 0, at(cone(0.3, 1.0, 0xffb02e, { ...glow(0xff7a1a, 2), noShadow: 1 }, 8), 0, -0.5, 0, Math.PI), at(cone(0.16, 0.6, 0xfff1a8, { ...glow(0xfff1a8, 2), noShadow: 1 }, 8), 0, -0.3, 0, Math.PI));
111
+ flame.visible = false;
112
+ body.add(flame);
113
+ return rig(root, 'vehicle', { h: 3.6, r: 0.95, top: 3.6, seat: [0, 2.7, 0.45], flyer: true, vertical: true }, { body, flame });
114
+ }
115
+
116
+ function train(C) {
117
+ const c = C ?? 0x2f7d5b, d = tint(c, -0.16), [root, body] = shell();
118
+ body.add(at(box(1.4, 0.3, 3.6, DARK), 0, 0.6, 0), at(cyl(0.56, 0.56, 2.1, c, null, 12), 0, 1.3, 0.6, HALF), at(box(1.45, 1.4, 1.2, d), 0, 1.45, -1.15),
119
+ at(box(1.6, 0.1, 1.4, DARK), 0, 2.2, -1.15), at(box(1.47, 0.5, 0.7, GLASS), 0, 1.75, -1.15), at(cyl(0.16, 0.12, 0.6, DARK, null, 8), 0, 2.1, 1.2),
120
+ at(cyl(0.22, 0.16, 0.14, DARK, null, 8), 0, 2.45, 1.2), at(cyl(0.2, 0.2, 0.24, 0xe2b23a, null, 8), 0, 1.95, 0.3),
121
+ at(cone(0.8, 0.7, 0xd63c33, null, 4), 0, 0.5, 2.0, HALF, Math.PI / 4, 0, [1, 1, 0.5]), at(orb(0.14, 0xfff3c4, glow(0xfff3c4)), 0, 1.3, 1.66));
122
+ const wheels = [];
123
+ for (const z of [1.1, 0.2, -1.1]) for (const x of [0.72, -0.72]) wheels.push(wheel(x, 0.36, z, 0.36, 0.14));
124
+ for (const w of wheels) w.children[1].material = w.children[1].material.clone(), w.children[1].material.color.setHex(0xd63c33);
125
+ body.add(...wheels);
126
+ return rig(root, 'vehicle', { h: 2.55, r: 2.2, top: 2.25, seat: [0, 2.25, -1.15] }, { body, wheels });
127
+ }
128
+
129
+ function ufo(C) {
130
+ const c = C ?? 0xc4c9d1, [root, body] = shell(), y = 1.5;
131
+ body.add(at(orb(1.3, c, { metal: 1 }), 0, y, 0, 0, 0, 0, [1, 0.22, 1]), at(orb(0.9, tint(c, -0.15), { metal: 1 }), 0, y - 0.15, 0, 0, 0, 0, [1, 0.3, 1]),
132
+ at(orb(0.56, 0x7fe9ff, { opacity: 0.6 }), 0, y + 0.2, 0, 0, 0, 0, [1, 0.85, 1]));
133
+ const ring = spinner('y', true, 0, y, 0);
134
+ for (let i = 0; i < 8; i++) ring.add(at(orb(0.09, i % 2 ? 0x7dff7a : 0xffe24a, glow(i % 2 ? 0x7dff7a : 0xffe24a, 1.8)), Math.cos(i * 0.785) * 1.05, -0.05, Math.sin(i * 0.785) * 1.05));
135
+ body.add(ring);
136
+ return rig(root, 'vehicle', { h: y + 0.7, r: 1.4, top: y + 0.68, seat: [0, y + 0.66, 0], flyer: true, floaty: true, hover: 0.4 }, { body, spinners: [ring] });
137
+ }
138
+
139
+ function helicopter(C) {
140
+ const c = C ?? 0xd63c33, [root, body] = shell(), y = 1.05;
141
+ body.add(at(ball(0.75, c), 0, y, 0.2, 0, 0, 0, [0.9, 0.9, 1.3]), at(orb(0.6, GLASS), 0, y + 0.05, 0.62, 0, 0, 0, [0.85, 0.8, 0.9]),
142
+ at(box(0.2, 0.2, 2.2, c), 0, y + 0.2, -1.6), at(box(0.06, 0.6, 0.4, tint(c, -0.15)), 0, y + 0.45, -2.6), at(cyl(0.05, 0.05, 0.4, DARK, null, 6), 0, y + 0.8, 0.2));
143
+ for (const sx of [1, -1]) body.add(at(box(0.07, 0.07, 1.9, DARK), sx * 0.55, 0.06, 0.2), at(box(0.05, 0.5, 0.05, DARK), sx * 0.5, 0.3, 0.7, 0, 0, sx * 0.2), at(box(0.05, 0.5, 0.05, DARK), sx * 0.5, 0.3, -0.3, 0, 0, sx * 0.2));
144
+ const main = spinner('y', false, 0, y + 1.0, 0.2, at(box(4.4, 0.04, 0.2, DARK), 0, 0, 0), at(box(0.2, 0.04, 4.4, DARK), 0, 0, 0));
145
+ const rear = spinner('x', false, 0.08, y + 0.5, -2.6, at(box(0.03, 0.8, 0.1, DARK), 0, 0, 0), at(box(0.03, 0.1, 0.8, DARK), 0, 0, 0));
146
+ body.add(main, rear);
147
+ return rig(root, 'vehicle', { h: 2.1, r: 2.3, top: y + 1.05, seat: [0, y + 0.7, -0.3], flyer: true }, { body, spinners: [main, rear] });
148
+ }
149
+
150
+ // ------------------------------------------------------------------ props
151
+ function tree(C) {
152
+ const c = C ?? 0x3f9a4a, [root, body] = shell();
153
+ const crown = joint(0, 1.5, 0, at(ball(1.0, c), 0, 0.6, 0), at(ball(0.75, tint(c, 0.06)), 0.5, 1.2, 0.2), at(ball(0.7, tint(c, -0.06)), -0.5, 1.1, -0.3), at(ball(0.6, tint(c, 0.03)), 0, 1.75, 0));
154
+ body.add(at(cyl(0.16, 0.24, 1.7, 0x7a5233, null, 7), 0, 0.85, 0), crown);
155
+ return rig(root, 'prop', { h: 3.8, r: 1.2, top: 3.8, seat: [0, 3.7, 0], sway: true }, { body, head: crown });
156
+ }
157
+
158
+ function house(C) {
159
+ const c = C ?? 0xe8d9b8, [root, body] = shell();
160
+ body.add(at(box(3.2, 2.2, 3.0, c), 0, 1.1, 0), at(cone(2.55, 1.5, 0xb5483a, null, 4), 0, 2.95, 0, 0, Math.PI / 4, 0),
161
+ at(box(0.7, 1.3, 0.06, 0x6b4a2a), 0, 0.65, 1.51), at(orb(0.05, 0xe2b23a), 0.22, 0.65, 1.56),
162
+ at(box(0.7, 0.7, 0.06, 0xffe7a3, glow(0xffd76a, 0.5)), 1.0, 1.3, 1.51), at(box(0.7, 0.7, 0.06, 0xffe7a3, glow(0xffd76a, 0.5)), -1.0, 1.3, 1.51),
163
+ at(box(0.06, 0.7, 0.7, 0xffe7a3, glow(0xffd76a, 0.5)), 1.61, 1.3, 0), at(box(0.4, 1.0, 0.4, 0x9a5a48), 0.9, 3.0, -0.5));
164
+ return rig(root, 'prop', { h: 3.7, r: 2.4, top: 3.7, seat: [0, 3.6, 0] }, { body });
165
+ }
166
+
167
+ function ballProp(C) {
168
+ const c = C ?? 0xd63c33, [root, body] = shell();
169
+ const b = joint(0, 0.36, 0, orb(0.36, c), at(torus(0.362, 0.03, WHITE), 0, 0, 0, HALF), at(torus(0.362, 0.03, WHITE), 0, 0, 0, 0, HALF));
170
+ body.add(b);
171
+ return rig(root, 'prop', { h: 0.72, r: 0.42, top: 0.72, seat: [0, 0.72, 0], round: 0.36 }, { body, roller: b });
172
+ }
173
+
174
+ function crate(C) {
175
+ const c = C ?? 0xb98a4f, d = tint(c, -0.16), [root, body] = shell();
176
+ body.add(at(box(0.8, 0.8, 0.8, c), 0, 0.4, 0));
177
+ for (const s of [1, -1]) {
178
+ body.add(at(box(0.86, 0.1, 0.86, d), 0, 0.4 + s * 0.36, 0), at(box(0.1, 0.8, 0.86, d), s * 0.38, 0.4, 0));
179
+ body.add(at(box(0.9, 0.08, 0.04, d), 0, 0.4, s * 0.41, 0, 0, 0.72));
180
+ }
181
+ return rig(root, 'prop', { h: 0.82, r: 0.6, top: 0.82, seat: [0, 0.82, 0] }, { body });
182
+ }
183
+
184
+ function chair(C) {
185
+ const c = C ?? WOOD, d = tint(c, -0.1), [root, body] = shell();
186
+ body.add(at(box(0.52, 0.06, 0.52, c), 0, 0.48, 0), at(box(0.52, 0.6, 0.06, c), 0, 0.82, -0.23), at(box(0.52, 0.1, 0.07, d), 0, 1.1, -0.23));
187
+ for (const [x, z] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) body.add(at(box(0.06, 0.48, 0.06, d), x * 0.22, 0.24, z * 0.22));
188
+ return rig(root, 'prop', { h: 1.15, r: 0.42, top: 0.51, seat: [0, 0.51, 0.02], chair: true }, { body });
189
+ }
190
+
191
+ function table(C) {
192
+ const c = C ?? WOOD, d = tint(c, -0.1), [root, body] = shell();
193
+ body.add(at(box(1.5, 0.08, 0.95, c), 0, 0.78, 0));
194
+ for (const [x, z] of [[1, 1], [-1, 1], [1, -1], [-1, -1]]) body.add(at(box(0.09, 0.76, 0.09, d), x * 0.66, 0.38, z * 0.39));
195
+ return rig(root, 'prop', { h: 0.82, r: 0.9, top: 0.82, seat: [0, 0.82, 0] }, { body });
196
+ }
197
+
198
+ function rock(C) {
199
+ const c = C ?? 0x8d9199, [root, body] = shell();
200
+ body.add(at(rockGeo(0.6, c), 0, 0.42, 0, 0.3, 0.5, 0.1, [1.25, 0.85, 1.0]), at(rockGeo(0.3, tint(c, -0.06)), 0.6, 0.2, 0.3, 0.8, 0.2, 0.4));
201
+ return rig(root, 'prop', { h: 0.95, r: 0.85, top: 0.92, seat: [0, 0.9, 0] }, { body });
202
+ }
203
+
204
+ function flower(C) {
205
+ const c = C ?? 0xf284b6, [root, body] = shell();
206
+ const head = joint(0, 0.7, 0, at(orb(0.1, 0xf2c230), 0, 0, 0.03));
207
+ for (let i = 0; i < 6; i++) head.add(at(ball(0.11, c), Math.cos(i * 1.047) * 0.17, Math.sin(i * 1.047) * 0.17, 0, 0, 0, 0, [1, 1, 0.4]));
208
+ head.rotation.x = -0.5;
209
+ body.add(at(cyl(0.025, 0.03, 0.7, 0x3f9a4a, null, 6), 0, 0.35, 0), at(box(0.22, 0.02, 0.1, 0x3f9a4a), 0.11, 0.3, 0, 0, 0, 0.5), at(box(0.22, 0.02, 0.1, 0x3f9a4a), -0.11, 0.2, 0, 0, 0, -0.5), head);
210
+ return rig(root, 'prop', { h: 0.95, r: 0.32, top: 0.9, seat: [0, 0.9, 0], sway: true }, { body, head });
211
+ }
212
+
213
+ function cactus(C) {
214
+ const c = C ?? 0x4f9a52, [root, body] = shell();
215
+ body.add(at(cyl(0.24, 0.26, 1.5, c, null, 8), 0, 0.75, 0), at(ball(0.24, c), 0, 1.5, 0), at(orb(0.09, 0xf284b6), 0, 1.76, 0));
216
+ for (const [s, y, l] of [[1, 0.8, 0.6], [-1, 0.6, 0.45]]) {
217
+ body.add(at(cyl(0.12, 0.12, 0.4, c, null, 7), s * 0.36, y, 0, 0, 0, HALF), at(cyl(0.12, 0.12, l, c, null, 7), s * 0.52, y + l / 2, 0), at(ball(0.12, c), s * 0.52, y + l, 0));
218
+ }
219
+ return rig(root, 'prop', { h: 1.8, r: 0.7, top: 1.75, seat: [0, 1.75, 0] }, { body });
220
+ }
221
+
222
+ function mushroom(C) {
223
+ const c = C ?? 0xd63c33, [root, body] = shell();
224
+ const cap = joint(0, 0.42, 0, at(orb(0.42, c), 0, 0, 0, 0, 0, 0, [1, 0.62, 1]));
225
+ for (const [x, y, z] of [[0.2, 0.2, 0.15], [-0.18, 0.21, 0.1], [0, 0.26, -0.1], [0.05, 0.14, 0.32], [-0.26, 0.12, -0.2]]) cap.add(at(orb(0.06, WHITE), x, y, z, 0, 0, 0, [1, 0.5, 1]));
226
+ body.add(at(cyl(0.12, 0.16, 0.45, 0xf2ead8, null, 8), 0, 0.22, 0), cap);
227
+ return rig(root, 'prop', { h: 0.72, r: 0.45, top: 0.7, seat: [0, 0.68, 0] }, { body, head: cap });
228
+ }
229
+
230
+ function tower(C) {
231
+ const c = C ?? 0x9aa0a8, d = tint(c, -0.1), [root, body] = shell();
232
+ body.add(at(cyl(0.95, 1.1, 4.2, c, null, 10), 0, 2.1, 0), at(cyl(1.15, 1.15, 0.3, d, null, 10), 0, 4.3, 0), at(cone(1.0, 1.4, 0xb5483a, null, 10), 0, 5.4, 0),
233
+ at(box(0.6, 1.1, 0.1, 0x6b4a2a), 0, 0.55, 1.06), at(box(0.3, 0.5, 0.1, 0xffe7a3, glow(0xffd76a, 0.6)), 0, 2.8, 0.97));
234
+ for (let i = 0; i < 8; i++) body.add(at(box(0.36, 0.34, 0.26, d), Math.cos(i * 0.785) * 1.05, 4.6, Math.sin(i * 0.785) * 1.05, 0, -i * 0.785 + HALF, 0));
235
+ return rig(root, 'prop', { h: 6.1, r: 1.3, top: 4.45, seat: [0, 4.45, 0.4] }, { body });
236
+ }
237
+
238
+ function lamp(C) {
239
+ const c = C ?? 0x33363c, [root, body] = shell();
240
+ body.add(at(cyl(0.06, 0.09, 2.7, c, null, 8), 0, 1.35, 0), at(cyl(0.16, 0.2, 0.14, c, null, 8), 0, 0.07, 0), at(box(0.06, 0.06, 0.6, c), 0, 2.7, 0.27),
241
+ at(cone(0.22, 0.16, c, null, 8), 0, 2.72, 0.55), at(orb(0.13, 0xfff0b8, glow(0xffd76a, 2.2)), 0, 2.58, 0.55));
242
+ const light = new THREE.PointLight(0xffd9a0, 6, 9, 1.6);
243
+ light.position.set(0, 2.5, 0.55);
244
+ body.add(light);
245
+ return rig(root, 'prop', { h: 2.85, r: 0.5, top: 2.8, seat: [0, 2.8, 0] }, { body });
246
+ }
247
+
248
+ function bench(C) {
249
+ const c = C ?? WOOD, [root, body] = shell();
250
+ for (const z of [-0.14, 0, 0.14]) body.add(at(box(1.6, 0.05, 0.12, c), 0, 0.47, z));
251
+ for (const y of [0.7, 0.88]) body.add(at(box(1.6, 0.12, 0.05, c), 0, y, -0.24, -0.12));
252
+ for (const x of [0.7, -0.7]) body.add(at(box(0.07, 0.46, 0.44, DARK), x, 0.23, 0), at(box(0.07, 0.5, 0.06, DARK), x, 0.72, -0.24, -0.12));
253
+ return rig(root, 'prop', { h: 0.96, r: 0.9, top: 0.5, seat: [0, 0.5, 0.02], chair: true }, { body });
254
+ }
255
+
256
+ function balloon(C) {
257
+ const c = C ?? 0xd63c33, [root, body] = shell();
258
+ body.add(at(orb(0.36, c), 0, 1.9, 0, 0, 0, 0, [1, 1.2, 1]), at(cone(0.06, 0.1, c, null, 6), 0, 1.44, 0), at(cyl(0.006, 0.006, 1.1, 0xe6e8ec, { noShadow: 1 }, 4), 0, 0.88, 0));
259
+ return rig(root, 'prop', { h: 2.35, r: 0.42, top: 2.33, seat: [0, 2.33, 0], floaty: true, hover: 0.3 }, { body });
260
+ }
261
+
262
+ export const THINGS = {
263
+ car, truck, bus, bike, skateboard, boat, plane, rocket, train, ufo, helicopter,
264
+ tree, house, ball: ballProp, box: crate, chair, table, rock, flower, cactus, mushroom, tower, lamp, bench, balloon,
265
+ };
web/model/model.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"config": {"vocab": 235, "ctx": 208, "d": 256, "layers": 6, "heads": 8}, "dtype": "float16", "vocab": ["<pad>", "<bos>", "<sep>", "<eos>", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "á", "é", "í", "ó", "ú", "ñ", "ü", ",", ".", "'", "-", "?", "!", "<new>", "<edit>", "<qa>", "<ent>", "<set>", "<add>", "<del>", "<env>", "<cam>", "type=dog", "type=cat", "type=horse", "type=cow", "type=pig", "type=sheep", "type=fox", "type=bear", "type=elephant", "type=giraffe", "type=rabbit", "type=lion", "type=dragon", "type=dinosaur", "type=man", "type=woman", "type=robot", "type=alien", "type=astronaut", "type=knight", "type=wizard", "type=bird", "type=duck", "type=chicken", "type=fish", "type=shark", "type=penguin", "type=snowman", "type=ghost", "type=car", "type=truck", "type=bus", "type=bike", "type=skateboard", "type=boat", "type=plane", "type=rocket", "type=train", "type=ufo", "type=helicopter", "type=tree", "type=house", "type=ball", "type=box", "type=chair", "type=table", "type=rock", "type=flower", "type=cactus", "type=mushroom", "type=tower", "type=lamp", "type=bench", "type=balloon", "type=it", "type=all", "color=red", "color=blue", "color=green", "color=yellow", "color=orange", "color=purple", "color=pink", "color=white", "color=black", "color=gray", "color=brown", "color=gold", "color=silver", "color=cyan", "size=tiny", "size=small", "size=big", "size=giant", "size=up", "size=down", "n=2", "n=3", "n=4", "n=5", "n=6", "act=idle", "act=walk", "act=run", "act=jump", "act=spin", "act=dance", "act=fly", "act=float", "act=sit", "act=sleep", "act=wave", "act=bounce", "act=roll", "act=circle", "act=shake", "act=swim", "act=drive", "spd=slow", "spd=fast", "spd=normal", "rel=on", "rel=over", "rel=near", "rel=behind", "rel=front", "rel=around", "rel=ride", "rel=chase", "loc=field", "loc=desert", "loc=snow", "loc=beach", "loc=forest", "loc=city", "loc=space", "loc=moon", "loc=ocean", "loc=room", "loc=mountain", "loc=farm", "loc=road", "loc=park", "loc=studio", "time=day", "time=night", "time=sunset", "time=dawn", "weather=clear", "weather=rain", "weather=snow", "weather=fog", "weather=storm", "shot=close", "shot=medium", "shot=wide", "shot=top", "shot=low", "shot=in", "shot=out", "cam=static", "cam=orbit", "cam=zoomin", "cam=zoomout", "cam=pan", "cam=follow", "lang=en", "lang=es", "topic=threejs", "topic=scene", "topic=camera", "topic=renderer", "topic=mesh", "topic=geometry", "topic=material", "topic=light", "topic=shadow", "topic=animation", "topic=texture", "topic=gltf", "topic=controls", "topic=raycaster", "topic=fog", "topic=performance", "topic=group", "topic=color", "topic=resize", "topic=particles", "topic=help", "topic=objects", "topic=actions", "topic=about"], "max_prompt": 160, "special": {"pad": 0, "bos": 1, "sep": 2, "eos": 3}, "tensors": [{"name": "tok.weight", "shape": [235, 256], "offset": 0}, {"name": "pos.weight", "shape": [208, 256], "offset": 60160}, {"name": "blocks.0.ln1.weight", "shape": [256], "offset": 113408}, {"name": "blocks.0.ln1.bias", "shape": [256], "offset": 113664}, {"name": "blocks.0.qkv.weight", "shape": [768, 256], "offset": 113920}, {"name": "blocks.0.qkv.bias", "shape": [768], "offset": 310528}, {"name": "blocks.0.proj.weight", "shape": [256, 256], "offset": 311296}, {"name": "blocks.0.proj.bias", "shape": [256], "offset": 376832}, {"name": "blocks.0.ln2.weight", "shape": [256], "offset": 377088}, {"name": "blocks.0.ln2.bias", "shape": [256], "offset": 377344}, {"name": "blocks.0.fc1.weight", "shape": [1024, 256], "offset": 377600}, {"name": "blocks.0.fc1.bias", "shape": [1024], "offset": 639744}, {"name": "blocks.0.fc2.weight", "shape": [256, 1024], "offset": 640768}, {"name": "blocks.0.fc2.bias", "shape": [256], "offset": 902912}, {"name": "blocks.1.ln1.weight", "shape": [256], "offset": 903168}, {"name": "blocks.1.ln1.bias", "shape": [256], "offset": 903424}, {"name": "blocks.1.qkv.weight", "shape": [768, 256], "offset": 903680}, {"name": "blocks.1.qkv.bias", "shape": [768], "offset": 1100288}, {"name": "blocks.1.proj.weight", "shape": [256, 256], "offset": 1101056}, {"name": "blocks.1.proj.bias", "shape": [256], "offset": 1166592}, {"name": "blocks.1.ln2.weight", "shape": [256], "offset": 1166848}, {"name": "blocks.1.ln2.bias", "shape": [256], "offset": 1167104}, {"name": "blocks.1.fc1.weight", "shape": [1024, 256], "offset": 1167360}, {"name": "blocks.1.fc1.bias", "shape": [1024], "offset": 1429504}, {"name": "blocks.1.fc2.weight", "shape": [256, 1024], "offset": 1430528}, {"name": "blocks.1.fc2.bias", "shape": [256], "offset": 1692672}, {"name": "blocks.2.ln1.weight", "shape": [256], "offset": 1692928}, {"name": "blocks.2.ln1.bias", "shape": [256], "offset": 1693184}, {"name": "blocks.2.qkv.weight", "shape": [768, 256], "offset": 1693440}, {"name": "blocks.2.qkv.bias", "shape": [768], "offset": 1890048}, {"name": "blocks.2.proj.weight", "shape": [256, 256], "offset": 1890816}, {"name": "blocks.2.proj.bias", "shape": [256], "offset": 1956352}, {"name": "blocks.2.ln2.weight", "shape": [256], "offset": 1956608}, {"name": "blocks.2.ln2.bias", "shape": [256], "offset": 1956864}, {"name": "blocks.2.fc1.weight", "shape": [1024, 256], "offset": 1957120}, {"name": "blocks.2.fc1.bias", "shape": [1024], "offset": 2219264}, {"name": "blocks.2.fc2.weight", "shape": [256, 1024], "offset": 2220288}, {"name": "blocks.2.fc2.bias", "shape": [256], "offset": 2482432}, {"name": "blocks.3.ln1.weight", "shape": [256], "offset": 2482688}, {"name": "blocks.3.ln1.bias", "shape": [256], "offset": 2482944}, {"name": "blocks.3.qkv.weight", "shape": [768, 256], "offset": 2483200}, {"name": "blocks.3.qkv.bias", "shape": [768], "offset": 2679808}, {"name": "blocks.3.proj.weight", "shape": [256, 256], "offset": 2680576}, {"name": "blocks.3.proj.bias", "shape": [256], "offset": 2746112}, {"name": "blocks.3.ln2.weight", "shape": [256], "offset": 2746368}, {"name": "blocks.3.ln2.bias", "shape": [256], "offset": 2746624}, {"name": "blocks.3.fc1.weight", "shape": [1024, 256], "offset": 2746880}, {"name": "blocks.3.fc1.bias", "shape": [1024], "offset": 3009024}, {"name": "blocks.3.fc2.weight", "shape": [256, 1024], "offset": 3010048}, {"name": "blocks.3.fc2.bias", "shape": [256], "offset": 3272192}, {"name": "blocks.4.ln1.weight", "shape": [256], "offset": 3272448}, {"name": "blocks.4.ln1.bias", "shape": [256], "offset": 3272704}, {"name": "blocks.4.qkv.weight", "shape": [768, 256], "offset": 3272960}, {"name": "blocks.4.qkv.bias", "shape": [768], "offset": 3469568}, {"name": "blocks.4.proj.weight", "shape": [256, 256], "offset": 3470336}, {"name": "blocks.4.proj.bias", "shape": [256], "offset": 3535872}, {"name": "blocks.4.ln2.weight", "shape": [256], "offset": 3536128}, {"name": "blocks.4.ln2.bias", "shape": [256], "offset": 3536384}, {"name": "blocks.4.fc1.weight", "shape": [1024, 256], "offset": 3536640}, {"name": "blocks.4.fc1.bias", "shape": [1024], "offset": 3798784}, {"name": "blocks.4.fc2.weight", "shape": [256, 1024], "offset": 3799808}, {"name": "blocks.4.fc2.bias", "shape": [256], "offset": 4061952}, {"name": "blocks.5.ln1.weight", "shape": [256], "offset": 4062208}, {"name": "blocks.5.ln1.bias", "shape": [256], "offset": 4062464}, {"name": "blocks.5.qkv.weight", "shape": [768, 256], "offset": 4062720}, {"name": "blocks.5.qkv.bias", "shape": [768], "offset": 4259328}, {"name": "blocks.5.proj.weight", "shape": [256, 256], "offset": 4260096}, {"name": "blocks.5.proj.bias", "shape": [256], "offset": 4325632}, {"name": "blocks.5.ln2.weight", "shape": [256], "offset": 4325888}, {"name": "blocks.5.ln2.bias", "shape": [256], "offset": 4326144}, {"name": "blocks.5.fc1.weight", "shape": [1024, 256], "offset": 4326400}, {"name": "blocks.5.fc1.bias", "shape": [1024], "offset": 4588544}, {"name": "blocks.5.fc2.weight", "shape": [256, 1024], "offset": 4589568}, {"name": "blocks.5.fc2.bias", "shape": [256], "offset": 4851712}, {"name": "ln_f.weight", "shape": [256], "offset": 4851968}, {"name": "ln_f.bias", "shape": [256], "offset": 4852224}], "meta": {"params": 4852480, "steps": 14000, "batch": 256, "pairs_seen": 3584000, "heldout_exact_clean": 0.9993, "heldout_exact_noisy": 0.997, "train_seconds": 1075}}
web/model/qa.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "threejs": {
3
+ "en": "three.js is a JavaScript library that draws 3D graphics in the browser on top of WebGL. You describe a scene with objects, lights and a camera, and a renderer draws it to a canvas every frame.",
4
+ "es": "three.js es una librería de JavaScript que dibuja gráficos 3D en el navegador sobre WebGL. Describes una escena con objetos, luces y una cámara, y un renderer la dibuja en un canvas en cada fotograma."
5
+ },
6
+ "scene": {
7
+ "en": "A THREE.Scene is the root container. Everything you want drawn (meshes, lights, groups) is added with scene.add(object), and removed with scene.remove(object).",
8
+ "es": "THREE.Scene es el contenedor raíz. Todo lo que quieras dibujar (mallas, luces, grupos) se añade con scene.add(objeto) y se quita con scene.remove(objeto)."
9
+ },
10
+ "camera": {
11
+ "en": "The camera decides what is visible. PerspectiveCamera(fov, aspect, near, far) imitates a real lens; OrthographicCamera has no perspective. Move it with camera.position.set(x, y, z) and aim it with camera.lookAt(target).",
12
+ "es": "La cámara decide qué se ve. PerspectiveCamera(fov, aspect, near, far) imita una lente real; OrthographicCamera no tiene perspectiva. Se mueve con camera.position.set(x, y, z) y se apunta con camera.lookAt(objetivo)."
13
+ },
14
+ "renderer": {
15
+ "en": "WebGLRenderer draws a scene from a camera into a canvas: renderer.render(scene, camera). Call it every frame with renderer.setAnimationLoop(fn), and set the size with renderer.setSize(width, height).",
16
+ "es": "WebGLRenderer dibuja una escena vista desde una cámara en un canvas: renderer.render(scene, camera). Se llama en cada fotograma con renderer.setAnimationLoop(fn), y el tamaño se fija con renderer.setSize(ancho, alto)."
17
+ },
18
+ "mesh": {
19
+ "en": "A Mesh is a visible object: geometry (the shape) plus material (the look). Example: new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 'red' })).",
20
+ "es": "Un Mesh es un objeto visible: geometría (la forma) más material (el aspecto). Ejemplo: new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 'red' }))."
21
+ },
22
+ "geometry": {
23
+ "en": "A geometry holds the vertices of a shape. Built-in ones include BoxGeometry, SphereGeometry, CylinderGeometry, ConeGeometry, TorusGeometry and PlaneGeometry. Every object in this app is assembled from those primitives.",
24
+ "es": "Una geometría guarda los vértices de una forma. Las incluidas son BoxGeometry, SphereGeometry, CylinderGeometry, ConeGeometry, TorusGeometry y PlaneGeometry, entre otras. Todos los objetos de esta app se arman con esas primitivas."
25
+ },
26
+ "material": {
27
+ "en": "A material defines how a surface looks. MeshBasicMaterial ignores light, MeshStandardMaterial reacts to it with roughness and metalness, and MeshToonMaterial gives a cartoon look. Set transparent: true and opacity for see-through surfaces.",
28
+ "es": "Un material define cómo se ve una superficie. MeshBasicMaterial ignora la luz, MeshStandardMaterial reacciona a ella con roughness y metalness, y MeshToonMaterial da un aspecto de dibujo. Usa transparent: true y opacity para superficies translúcidas."
29
+ },
30
+ "light": {
31
+ "en": "Lights make standard materials visible. AmbientLight and HemisphereLight fill the whole scene, DirectionalLight acts like the sun, PointLight like a bulb and SpotLight like a torch. A black scene usually means there is no light.",
32
+ "es": "Las luces hacen visibles los materiales estándar. AmbientLight y HemisphereLight rellenan toda la escena, DirectionalLight actúa como el sol, PointLight como una bombilla y SpotLight como una linterna. Una escena negra casi siempre significa que falta una luz."
33
+ },
34
+ "shadow": {
35
+ "en": "Shadows need three switches: renderer.shadowMap.enabled = true, light.castShadow = true, and on each mesh castShadow and/or receiveShadow = true. Tune light.shadow.mapSize and the shadow camera bounds for quality.",
36
+ "es": "Las sombras necesitan tres interruptores: renderer.shadowMap.enabled = true, light.castShadow = true y, en cada malla, castShadow y/o receiveShadow = true. La calidad se ajusta con light.shadow.mapSize y los límites de la cámara de sombra."
37
+ },
38
+ "animation": {
39
+ "en": "The simplest animation changes position, rotation or scale every frame inside the render loop, using elapsed time. For keyframes use AnimationMixer with AnimationClip. This app animates everything procedurally from the time value.",
40
+ "es": "La animación más simple cambia posición, rotación o escala en cada fotograma dentro del bucle de render, usando el tiempo transcurrido. Para keyframes se usa AnimationMixer con AnimationClip. Esta app anima todo de forma procedural a partir del tiempo."
41
+ },
42
+ "texture": {
43
+ "en": "A texture is an image mapped onto a surface. Load it with new THREE.TextureLoader().load(url) and assign it to material.map. CanvasTexture turns a 2D canvas drawing into a texture.",
44
+ "es": "Una textura es una imagen aplicada a una superficie. Se carga con new THREE.TextureLoader().load(url) y se asigna a material.map. CanvasTexture convierte un dibujo de canvas 2D en textura."
45
+ },
46
+ "gltf": {
47
+ "en": "glTF (.gltf or .glb) is the standard 3D format for the web. Load models with GLTFLoader and save scenes with GLTFExporter. The export button here writes a .glb you can open in Blender.",
48
+ "es": "glTF (.gltf o .glb) es el formato 3D estándar para la web. Los modelos se cargan con GLTFLoader y las escenas se guardan con GLTFExporter. El botón de exportar de esta app genera un .glb que puedes abrir en Blender."
49
+ },
50
+ "controls": {
51
+ "en": "OrbitControls lets the user orbit, zoom and pan with the mouse or touch: new OrbitControls(camera, renderer.domElement), then controls.update() every frame. Here you can drag the view at any time.",
52
+ "es": "OrbitControls permite orbitar, hacer zoom y desplazar con el ratón o el dedo: new OrbitControls(camera, renderer.domElement) y luego controls.update() en cada fotograma. Aquí puedes arrastrar la vista en cualquier momento."
53
+ },
54
+ "raycaster": {
55
+ "en": "A Raycaster shoots a ray from the camera through the mouse position and returns the objects it hits: raycaster.setFromCamera(pointer, camera) followed by raycaster.intersectObjects(scene.children).",
56
+ "es": "Un Raycaster lanza un rayo desde la cámara a través de la posición del ratón y devuelve los objetos que toca: raycaster.setFromCamera(pointer, camera) seguido de raycaster.intersectObjects(scene.children)."
57
+ },
58
+ "fog": {
59
+ "en": "Fog fades distant objects into a colour: scene.fog = new THREE.Fog(color, near, far) or new THREE.FogExp2(color, density). Match the fog colour to the background so the horizon blends.",
60
+ "es": "La niebla desvanece los objetos lejanos hacia un color: scene.fog = new THREE.Fog(color, near, far) o new THREE.FogExp2(color, densidad). Usa el mismo color que el fondo para que el horizonte se funda."
61
+ },
62
+ "performance": {
63
+ "en": "To keep the frame rate high: reuse geometries and materials, merge static meshes or use InstancedMesh, limit shadow-casting lights, cap the pixel ratio at 2, and dispose of what you remove.",
64
+ "es": "Para mantener los fps altos: reutiliza geometrías y materiales, fusiona mallas estáticas o usa InstancedMesh, limita las luces con sombra, limita el pixel ratio a 2 y libera con dispose lo que quites."
65
+ },
66
+ "group": {
67
+ "en": "A Group (or any Object3D) can hold children with parent.add(child). Children inherit the parent's position, rotation and scale, which is how a leg swings from a hip or a rider follows a horse.",
68
+ "es": "Un Group (o cualquier Object3D) puede tener hijos con padre.add(hijo). Los hijos heredan posición, rotación y escala del padre; así una pata gira desde la cadera o un jinete sigue a su caballo."
69
+ },
70
+ "color": {
71
+ "en": "THREE.Color accepts hex numbers (0xff0000), CSS strings ('red', '#ff0000') or HSL via setHSL. Change a material at any time with material.color.set('blue').",
72
+ "es": "THREE.Color acepta números hexadecimales (0xff0000), cadenas CSS ('red', '#ff0000') o HSL con setHSL. Cambia un material en cualquier momento con material.color.set('blue')."
73
+ },
74
+ "resize": {
75
+ "en": "On resize, update three things: camera.aspect = width / height, camera.updateProjectionMatrix(), and renderer.setSize(width, height). A stretched image means the aspect was not updated.",
76
+ "es": "Al cambiar el tamaño hay que actualizar tres cosas: camera.aspect = ancho / alto, camera.updateProjectionMatrix() y renderer.setSize(ancho, alto). Una imagen estirada indica que no se actualizó el aspecto."
77
+ },
78
+ "particles": {
79
+ "en": "Particles are a THREE.Points object: one BufferGeometry with many positions and a PointsMaterial. Move the positions every frame and set needsUpdate. The rain, snow and stars here are built that way.",
80
+ "es": "Las partículas son un objeto THREE.Points: una BufferGeometry con muchas posiciones y un PointsMaterial. Se mueven las posiciones en cada fotograma y se marca needsUpdate. La lluvia, la nieve y las estrellas de esta app están hechas así."
81
+ },
82
+ "help": {
83
+ "en": "Describe a scene and I build it: \"a red fox jumping over a car in the desert at sunset\". Then edit it: \"make the fox blue\", \"add a tree\", \"remove the car\", \"make it rain\", \"zoom out\". You can also ask about three.js.",
84
+ "es": "Describe una escena y la construyo: \"un zorro rojo saltando sobre un coche en el desierto al atardecer\". Luego edítala: \"haz el zorro azul\", \"añade un árbol\", \"quita el coche\", \"que llueva\", \"aleja la cámara\". También puedes preguntar sobre three.js."
85
+ },
86
+ "objects": {
87
+ "en": "I know: dog, cat, horse, cow, pig, sheep, fox, bear, elephant, giraffe, rabbit, lion, dragon, dinosaur, man, woman, robot, alien, astronaut, knight, wizard, bird, duck, chicken, fish, shark, penguin, snowman, ghost, car, truck, bus, bike, skateboard, boat, plane, rocket, train, ufo, helicopter, tree, house, ball, box, chair, table, rock, flower, cactus, mushroom, tower, lamp, bench, balloon.",
88
+ "es": "Conozco: perro, gato, caballo, vaca, cerdo, oveja, zorro, oso, elefante, jirafa, conejo, león, dragón, dinosaurio, hombre, mujer, robot, alien, astronauta, caballero, mago, pájaro, pato, gallina, pez, tiburón, pingüino, muñeco de nieve, fantasma, coche, camión, autobús, bicicleta, patineta, barco, avión, cohete, tren, ovni, helicóptero, árbol, casa, pelota, caja, silla, mesa, roca, flor, cactus, hongo, torre, lámpara, banco, globo."
89
+ },
90
+ "actions": {
91
+ "en": "Actions: standing, walking, running, jumping, spinning, dancing, flying, floating, sitting, sleeping, waving, bouncing, rolling, walking in circles, shaking, swimming, driving.",
92
+ "es": "Acciones: esperando, caminando, corriendo, saltando, girando, bailando, volando, flotando, sentado, durmiendo, saludando, rebotando, rodando, caminando en círculos, temblando, nadando, conduciendo."
93
+ },
94
+ "about": {
95
+ "en": "I am a tiny Transformer trained from scratch on synthetic prompts. I do not generate geometry: I translate your sentence into a compact scene language, and procedural three.js code builds and animates the result. I run entirely in your browser.",
96
+ "es": "Soy un Transformer diminuto entrenado desde cero con frases sintéticas. No genero geometría: traduzco tu frase a un lenguaje de escena compacto, y código procedural de three.js construye y anima el resultado. Funciono por completo en tu navegador."
97
+ }
98
+ }
web/model/weights.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12621e5c2aeb9c2f7746080d3074e7c9f79ff94c48b24ee7da8a634bcdee98e9
3
+ size 9704960
web/style.css ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg: #12141a; --panel: #191c24; --line: #2a2f3b; --text: #e8eaf0; --dim: #969cab; --accent: #ffb454;
3
+ --chip: #242936; --user: #2b3550; --ok: #7ee0a1; --warn: #ffb454;
4
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
5
+ }
6
+ * { box-sizing: border-box; }
7
+ html, body { height: 100%; margin: 0; background: var(--bg); color: var(--text); }
8
+ #app { display: flex; height: 100dvh; }
9
+ #view { position: relative; flex: 1; min-width: 0; background: #0c0e13; }
10
+ #canvas { display: block; width: 100%; height: 100%; touch-action: none; }
11
+
12
+ #state { position: absolute; left: 12px; top: 12px; display: flex; flex-wrap: wrap; gap: 6px; max-width: calc(100% - 24px); pointer-events: none; }
13
+ #state span { background: rgba(14, 16, 22, .72); backdrop-filter: blur(6px); border: 1px solid rgba(255, 255, 255, .1); padding: 4px 9px; border-radius: 999px; font-size: 12px; }
14
+ #state b { font-weight: 600; color: var(--accent); margin-right: 4px; }
15
+ #tools { position: absolute; left: 12px; bottom: 12px; display: flex; flex-wrap: wrap; gap: 6px; }
16
+ button { font: inherit; color: var(--text); background: rgba(24, 27, 36, .82); border: 1px solid var(--line); border-radius: 8px; padding: 7px 12px; font-size: 13px; cursor: pointer; }
17
+ button:hover:not(:disabled) { border-color: var(--accent); }
18
+ button:disabled { opacity: .5; cursor: default; }
19
+
20
+ #panel { width: 390px; max-width: 100%; display: flex; flex-direction: column; background: var(--panel); border-left: 1px solid var(--line); }
21
+ #panel header { padding: 16px 18px 12px; border-bottom: 1px solid var(--line); }
22
+ h1 { margin: 0; font-size: 19px; letter-spacing: .2px; }
23
+ #status { margin: 4px 0 0; font-size: 12.5px; color: var(--dim); line-height: 1.4; }
24
+ #log { flex: 1; overflow-y: auto; padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; }
25
+ .msg { font-size: 14px; line-height: 1.45; max-width: 100%; overflow-wrap: anywhere; }
26
+ .msg.user { align-self: flex-end; background: var(--user); padding: 8px 12px; border-radius: 14px 14px 4px 14px; }
27
+ .msg.bot { align-self: stretch; }
28
+ .msg.bot p { margin: 0 0 6px; }
29
+ .msg.bot .note { color: var(--warn); }
30
+ .msg.bot .meta { font-size: 11.5px; color: var(--dim); }
31
+ .tokens { display: flex; flex-wrap: wrap; gap: 4px; margin: 2px 0 6px; }
32
+ .tokens code { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; background: var(--chip); border-radius: 5px; padding: 2px 6px; color: #cfd6e6; }
33
+ .tokens code.s { color: var(--accent); background: #2f2a20; }
34
+ .hint { color: var(--dim); font-size: 13.5px; }
35
+ #examples { display: flex; flex-wrap: wrap; gap: 6px; padding: 10px 16px; border-top: 1px solid var(--line); max-height: 132px; overflow-y: auto; }
36
+ #examples button { font-size: 12px; padding: 5px 9px; border-radius: 999px; background: var(--chip); text-align: left; }
37
+ #form { display: flex; gap: 8px; padding: 12px 16px 16px; }
38
+ #prompt { flex: 1; min-width: 0; font: inherit; font-size: 15px; color: var(--text); background: #0f1117; border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; }
39
+ #prompt:focus { outline: none; border-color: var(--accent); }
40
+ #send { background: var(--accent); color: #1c1407; border-color: var(--accent); font-weight: 600; }
41
+
42
+ @media (max-width: 820px) {
43
+ #app { flex-direction: column; }
44
+ #view { flex: none; height: 46dvh; }
45
+ #panel { width: 100%; flex: 1; min-height: 0; border-left: 0; border-top: 1px solid var(--line); }
46
+ #panel header { padding: 10px 16px 8px; }
47
+ #examples { max-height: 76px; }
48
+ }
web/vendor/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License
2
+
3
+ Copyright © 2010-2024 three.js authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
web/vendor/addons/controls/OrbitControls.js ADDED
@@ -0,0 +1,1523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ Controls,
3
+ MOUSE,
4
+ Quaternion,
5
+ Spherical,
6
+ TOUCH,
7
+ Vector2,
8
+ Vector3,
9
+ Plane,
10
+ Ray,
11
+ MathUtils
12
+ } from 'three';
13
+
14
+ // OrbitControls performs orbiting, dollying (zooming), and panning.
15
+ // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
16
+ //
17
+ // Orbit - left mouse / touch: one-finger move
18
+ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
19
+ // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
20
+
21
+ const _changeEvent = { type: 'change' };
22
+ const _startEvent = { type: 'start' };
23
+ const _endEvent = { type: 'end' };
24
+ const _ray = new Ray();
25
+ const _plane = new Plane();
26
+ const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
27
+
28
+ const _v = new Vector3();
29
+ const _twoPI = 2 * Math.PI;
30
+
31
+ const _STATE = {
32
+ NONE: - 1,
33
+ ROTATE: 0,
34
+ DOLLY: 1,
35
+ PAN: 2,
36
+ TOUCH_ROTATE: 3,
37
+ TOUCH_PAN: 4,
38
+ TOUCH_DOLLY_PAN: 5,
39
+ TOUCH_DOLLY_ROTATE: 6
40
+ };
41
+ const _EPS = 0.000001;
42
+
43
+ class OrbitControls extends Controls {
44
+
45
+ constructor( object, domElement = null ) {
46
+
47
+ super( object, domElement );
48
+
49
+ this.state = _STATE.NONE;
50
+
51
+ // Set to false to disable this control
52
+ this.enabled = true;
53
+
54
+ // "target" sets the location of focus, where the object orbits around
55
+ this.target = new Vector3();
56
+
57
+ // Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect
58
+ this.cursor = new Vector3();
59
+
60
+ // How far you can dolly in and out ( PerspectiveCamera only )
61
+ this.minDistance = 0;
62
+ this.maxDistance = Infinity;
63
+
64
+ // How far you can zoom in and out ( OrthographicCamera only )
65
+ this.minZoom = 0;
66
+ this.maxZoom = Infinity;
67
+
68
+ // Limit camera target within a spherical area around the cursor
69
+ this.minTargetRadius = 0;
70
+ this.maxTargetRadius = Infinity;
71
+
72
+ // How far you can orbit vertically, upper and lower limits.
73
+ // Range is 0 to Math.PI radians.
74
+ this.minPolarAngle = 0; // radians
75
+ this.maxPolarAngle = Math.PI; // radians
76
+
77
+ // How far you can orbit horizontally, upper and lower limits.
78
+ // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
79
+ this.minAzimuthAngle = - Infinity; // radians
80
+ this.maxAzimuthAngle = Infinity; // radians
81
+
82
+ // Set to true to enable damping (inertia)
83
+ // If damping is enabled, you must call controls.update() in your animation loop
84
+ this.enableDamping = false;
85
+ this.dampingFactor = 0.05;
86
+
87
+ // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
88
+ // Set to false to disable zooming
89
+ this.enableZoom = true;
90
+ this.zoomSpeed = 1.0;
91
+
92
+ // Set to false to disable rotating
93
+ this.enableRotate = true;
94
+ this.rotateSpeed = 1.0;
95
+
96
+ // Set to false to disable panning
97
+ this.enablePan = true;
98
+ this.panSpeed = 1.0;
99
+ this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
100
+ this.keyPanSpeed = 7.0; // pixels moved per arrow key push
101
+ this.zoomToCursor = false;
102
+
103
+ // Set to true to automatically rotate around the target
104
+ // If auto-rotate is enabled, you must call controls.update() in your animation loop
105
+ this.autoRotate = false;
106
+ this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
107
+
108
+ // The four arrow keys
109
+ this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
110
+
111
+ // Mouse buttons
112
+ this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
113
+
114
+ // Touch fingers
115
+ this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
116
+
117
+ // for reset
118
+ this.target0 = this.target.clone();
119
+ this.position0 = this.object.position.clone();
120
+ this.zoom0 = this.object.zoom;
121
+
122
+ // the target DOM element for key events
123
+ this._domElementKeyEvents = null;
124
+
125
+ // internals
126
+
127
+ this._lastPosition = new Vector3();
128
+ this._lastQuaternion = new Quaternion();
129
+ this._lastTargetPosition = new Vector3();
130
+
131
+ // so camera.up is the orbit axis
132
+ this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
133
+ this._quatInverse = this._quat.clone().invert();
134
+
135
+ // current position in spherical coordinates
136
+ this._spherical = new Spherical();
137
+ this._sphericalDelta = new Spherical();
138
+
139
+ this._scale = 1;
140
+ this._panOffset = new Vector3();
141
+
142
+ this._rotateStart = new Vector2();
143
+ this._rotateEnd = new Vector2();
144
+ this._rotateDelta = new Vector2();
145
+
146
+ this._panStart = new Vector2();
147
+ this._panEnd = new Vector2();
148
+ this._panDelta = new Vector2();
149
+
150
+ this._dollyStart = new Vector2();
151
+ this._dollyEnd = new Vector2();
152
+ this._dollyDelta = new Vector2();
153
+
154
+ this._dollyDirection = new Vector3();
155
+ this._mouse = new Vector2();
156
+ this._performCursorZoom = false;
157
+
158
+ this._pointers = [];
159
+ this._pointerPositions = {};
160
+
161
+ this._controlActive = false;
162
+
163
+ // event listeners
164
+
165
+ this._onPointerMove = onPointerMove.bind( this );
166
+ this._onPointerDown = onPointerDown.bind( this );
167
+ this._onPointerUp = onPointerUp.bind( this );
168
+ this._onContextMenu = onContextMenu.bind( this );
169
+ this._onMouseWheel = onMouseWheel.bind( this );
170
+ this._onKeyDown = onKeyDown.bind( this );
171
+
172
+ this._onTouchStart = onTouchStart.bind( this );
173
+ this._onTouchMove = onTouchMove.bind( this );
174
+
175
+ this._onMouseDown = onMouseDown.bind( this );
176
+ this._onMouseMove = onMouseMove.bind( this );
177
+
178
+ this._interceptControlDown = interceptControlDown.bind( this );
179
+ this._interceptControlUp = interceptControlUp.bind( this );
180
+
181
+ //
182
+
183
+ if ( this.domElement !== null ) {
184
+
185
+ this.connect();
186
+
187
+ }
188
+
189
+ this.update();
190
+
191
+ }
192
+
193
+ connect() {
194
+
195
+ this.domElement.addEventListener( 'pointerdown', this._onPointerDown );
196
+ this.domElement.addEventListener( 'pointercancel', this._onPointerUp );
197
+
198
+ this.domElement.addEventListener( 'contextmenu', this._onContextMenu );
199
+ this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } );
200
+
201
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
202
+ document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } );
203
+
204
+ this.domElement.style.touchAction = 'none'; // disable touch scroll
205
+
206
+ }
207
+
208
+ disconnect() {
209
+
210
+ this.domElement.removeEventListener( 'pointerdown', this._onPointerDown );
211
+ this.domElement.removeEventListener( 'pointermove', this._onPointerMove );
212
+ this.domElement.removeEventListener( 'pointerup', this._onPointerUp );
213
+ this.domElement.removeEventListener( 'pointercancel', this._onPointerUp );
214
+
215
+ this.domElement.removeEventListener( 'wheel', this._onMouseWheel );
216
+ this.domElement.removeEventListener( 'contextmenu', this._onContextMenu );
217
+
218
+ this.stopListenToKeyEvents();
219
+
220
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
221
+ document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } );
222
+
223
+ this.domElement.style.touchAction = 'auto';
224
+
225
+ }
226
+
227
+ dispose() {
228
+
229
+ this.disconnect();
230
+
231
+ }
232
+
233
+ getPolarAngle() {
234
+
235
+ return this._spherical.phi;
236
+
237
+ }
238
+
239
+ getAzimuthalAngle() {
240
+
241
+ return this._spherical.theta;
242
+
243
+ }
244
+
245
+ getDistance() {
246
+
247
+ return this.object.position.distanceTo( this.target );
248
+
249
+ }
250
+
251
+ listenToKeyEvents( domElement ) {
252
+
253
+ domElement.addEventListener( 'keydown', this._onKeyDown );
254
+ this._domElementKeyEvents = domElement;
255
+
256
+ }
257
+
258
+ stopListenToKeyEvents() {
259
+
260
+ if ( this._domElementKeyEvents !== null ) {
261
+
262
+ this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown );
263
+ this._domElementKeyEvents = null;
264
+
265
+ }
266
+
267
+ }
268
+
269
+ saveState() {
270
+
271
+ this.target0.copy( this.target );
272
+ this.position0.copy( this.object.position );
273
+ this.zoom0 = this.object.zoom;
274
+
275
+ }
276
+
277
+ reset() {
278
+
279
+ this.target.copy( this.target0 );
280
+ this.object.position.copy( this.position0 );
281
+ this.object.zoom = this.zoom0;
282
+
283
+ this.object.updateProjectionMatrix();
284
+ this.dispatchEvent( _changeEvent );
285
+
286
+ this.update();
287
+
288
+ this.state = _STATE.NONE;
289
+
290
+ }
291
+
292
+ update( deltaTime = null ) {
293
+
294
+ const position = this.object.position;
295
+
296
+ _v.copy( position ).sub( this.target );
297
+
298
+ // rotate offset to "y-axis-is-up" space
299
+ _v.applyQuaternion( this._quat );
300
+
301
+ // angle from z-axis around y-axis
302
+ this._spherical.setFromVector3( _v );
303
+
304
+ if ( this.autoRotate && this.state === _STATE.NONE ) {
305
+
306
+ this._rotateLeft( this._getAutoRotationAngle( deltaTime ) );
307
+
308
+ }
309
+
310
+ if ( this.enableDamping ) {
311
+
312
+ this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor;
313
+ this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor;
314
+
315
+ } else {
316
+
317
+ this._spherical.theta += this._sphericalDelta.theta;
318
+ this._spherical.phi += this._sphericalDelta.phi;
319
+
320
+ }
321
+
322
+ // restrict theta to be between desired limits
323
+
324
+ let min = this.minAzimuthAngle;
325
+ let max = this.maxAzimuthAngle;
326
+
327
+ if ( isFinite( min ) && isFinite( max ) ) {
328
+
329
+ if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI;
330
+
331
+ if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI;
332
+
333
+ if ( min <= max ) {
334
+
335
+ this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) );
336
+
337
+ } else {
338
+
339
+ this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ?
340
+ Math.max( min, this._spherical.theta ) :
341
+ Math.min( max, this._spherical.theta );
342
+
343
+ }
344
+
345
+ }
346
+
347
+ // restrict phi to be between desired limits
348
+ this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) );
349
+
350
+ this._spherical.makeSafe();
351
+
352
+
353
+ // move target to panned location
354
+
355
+ if ( this.enableDamping === true ) {
356
+
357
+ this.target.addScaledVector( this._panOffset, this.dampingFactor );
358
+
359
+ } else {
360
+
361
+ this.target.add( this._panOffset );
362
+
363
+ }
364
+
365
+ // Limit the target distance from the cursor to create a sphere around the center of interest
366
+ this.target.sub( this.cursor );
367
+ this.target.clampLength( this.minTargetRadius, this.maxTargetRadius );
368
+ this.target.add( this.cursor );
369
+
370
+ let zoomChanged = false;
371
+ // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
372
+ // we adjust zoom later in these cases
373
+ if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) {
374
+
375
+ this._spherical.radius = this._clampDistance( this._spherical.radius );
376
+
377
+ } else {
378
+
379
+ const prevRadius = this._spherical.radius;
380
+ this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale );
381
+ zoomChanged = prevRadius != this._spherical.radius;
382
+
383
+ }
384
+
385
+ _v.setFromSpherical( this._spherical );
386
+
387
+ // rotate offset back to "camera-up-vector-is-up" space
388
+ _v.applyQuaternion( this._quatInverse );
389
+
390
+ position.copy( this.target ).add( _v );
391
+
392
+ this.object.lookAt( this.target );
393
+
394
+ if ( this.enableDamping === true ) {
395
+
396
+ this._sphericalDelta.theta *= ( 1 - this.dampingFactor );
397
+ this._sphericalDelta.phi *= ( 1 - this.dampingFactor );
398
+
399
+ this._panOffset.multiplyScalar( 1 - this.dampingFactor );
400
+
401
+ } else {
402
+
403
+ this._sphericalDelta.set( 0, 0, 0 );
404
+
405
+ this._panOffset.set( 0, 0, 0 );
406
+
407
+ }
408
+
409
+ // adjust camera position
410
+ if ( this.zoomToCursor && this._performCursorZoom ) {
411
+
412
+ let newRadius = null;
413
+ if ( this.object.isPerspectiveCamera ) {
414
+
415
+ // move the camera down the pointer ray
416
+ // this method avoids floating point error
417
+ const prevRadius = _v.length();
418
+ newRadius = this._clampDistance( prevRadius * this._scale );
419
+
420
+ const radiusDelta = prevRadius - newRadius;
421
+ this.object.position.addScaledVector( this._dollyDirection, radiusDelta );
422
+ this.object.updateMatrixWorld();
423
+
424
+ zoomChanged = !! radiusDelta;
425
+
426
+ } else if ( this.object.isOrthographicCamera ) {
427
+
428
+ // adjust the ortho camera position based on zoom changes
429
+ const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 );
430
+ mouseBefore.unproject( this.object );
431
+
432
+ const prevZoom = this.object.zoom;
433
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
434
+ this.object.updateProjectionMatrix();
435
+
436
+ zoomChanged = prevZoom !== this.object.zoom;
437
+
438
+ const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 );
439
+ mouseAfter.unproject( this.object );
440
+
441
+ this.object.position.sub( mouseAfter ).add( mouseBefore );
442
+ this.object.updateMatrixWorld();
443
+
444
+ newRadius = _v.length();
445
+
446
+ } else {
447
+
448
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
449
+ this.zoomToCursor = false;
450
+
451
+ }
452
+
453
+ // handle the placement of the target
454
+ if ( newRadius !== null ) {
455
+
456
+ if ( this.screenSpacePanning ) {
457
+
458
+ // position the orbit target in front of the new camera position
459
+ this.target.set( 0, 0, - 1 )
460
+ .transformDirection( this.object.matrix )
461
+ .multiplyScalar( newRadius )
462
+ .add( this.object.position );
463
+
464
+ } else {
465
+
466
+ // get the ray and translation plane to compute target
467
+ _ray.origin.copy( this.object.position );
468
+ _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix );
469
+
470
+ // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
471
+ // extremely large values
472
+ if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) {
473
+
474
+ this.object.lookAt( this.target );
475
+
476
+ } else {
477
+
478
+ _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target );
479
+ _ray.intersectPlane( _plane, this.target );
480
+
481
+ }
482
+
483
+ }
484
+
485
+ }
486
+
487
+ } else if ( this.object.isOrthographicCamera ) {
488
+
489
+ const prevZoom = this.object.zoom;
490
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
491
+
492
+ if ( prevZoom !== this.object.zoom ) {
493
+
494
+ this.object.updateProjectionMatrix();
495
+ zoomChanged = true;
496
+
497
+ }
498
+
499
+ }
500
+
501
+ this._scale = 1;
502
+ this._performCursorZoom = false;
503
+
504
+ // update condition is:
505
+ // min(camera displacement, camera rotation in radians)^2 > EPS
506
+ // using small-angle approximation cos(x/2) = 1 - x^2 / 8
507
+
508
+ if ( zoomChanged ||
509
+ this._lastPosition.distanceToSquared( this.object.position ) > _EPS ||
510
+ 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS ||
511
+ this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) {
512
+
513
+ this.dispatchEvent( _changeEvent );
514
+
515
+ this._lastPosition.copy( this.object.position );
516
+ this._lastQuaternion.copy( this.object.quaternion );
517
+ this._lastTargetPosition.copy( this.target );
518
+
519
+ return true;
520
+
521
+ }
522
+
523
+ return false;
524
+
525
+ }
526
+
527
+ _getAutoRotationAngle( deltaTime ) {
528
+
529
+ if ( deltaTime !== null ) {
530
+
531
+ return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime;
532
+
533
+ } else {
534
+
535
+ return _twoPI / 60 / 60 * this.autoRotateSpeed;
536
+
537
+ }
538
+
539
+ }
540
+
541
+ _getZoomScale( delta ) {
542
+
543
+ const normalizedDelta = Math.abs( delta * 0.01 );
544
+ return Math.pow( 0.95, this.zoomSpeed * normalizedDelta );
545
+
546
+ }
547
+
548
+ _rotateLeft( angle ) {
549
+
550
+ this._sphericalDelta.theta -= angle;
551
+
552
+ }
553
+
554
+ _rotateUp( angle ) {
555
+
556
+ this._sphericalDelta.phi -= angle;
557
+
558
+ }
559
+
560
+ _panLeft( distance, objectMatrix ) {
561
+
562
+ _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
563
+ _v.multiplyScalar( - distance );
564
+
565
+ this._panOffset.add( _v );
566
+
567
+ }
568
+
569
+ _panUp( distance, objectMatrix ) {
570
+
571
+ if ( this.screenSpacePanning === true ) {
572
+
573
+ _v.setFromMatrixColumn( objectMatrix, 1 );
574
+
575
+ } else {
576
+
577
+ _v.setFromMatrixColumn( objectMatrix, 0 );
578
+ _v.crossVectors( this.object.up, _v );
579
+
580
+ }
581
+
582
+ _v.multiplyScalar( distance );
583
+
584
+ this._panOffset.add( _v );
585
+
586
+ }
587
+
588
+ // deltaX and deltaY are in pixels; right and down are positive
589
+ _pan( deltaX, deltaY ) {
590
+
591
+ const element = this.domElement;
592
+
593
+ if ( this.object.isPerspectiveCamera ) {
594
+
595
+ // perspective
596
+ const position = this.object.position;
597
+ _v.copy( position ).sub( this.target );
598
+ let targetDistance = _v.length();
599
+
600
+ // half of the fov is center to top of screen
601
+ targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 );
602
+
603
+ // we use only clientHeight here so aspect ratio does not distort speed
604
+ this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix );
605
+ this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix );
606
+
607
+ } else if ( this.object.isOrthographicCamera ) {
608
+
609
+ // orthographic
610
+ this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix );
611
+ this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix );
612
+
613
+ } else {
614
+
615
+ // camera neither orthographic nor perspective
616
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
617
+ this.enablePan = false;
618
+
619
+ }
620
+
621
+ }
622
+
623
+ _dollyOut( dollyScale ) {
624
+
625
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
626
+
627
+ this._scale /= dollyScale;
628
+
629
+ } else {
630
+
631
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
632
+ this.enableZoom = false;
633
+
634
+ }
635
+
636
+ }
637
+
638
+ _dollyIn( dollyScale ) {
639
+
640
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
641
+
642
+ this._scale *= dollyScale;
643
+
644
+ } else {
645
+
646
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
647
+ this.enableZoom = false;
648
+
649
+ }
650
+
651
+ }
652
+
653
+ _updateZoomParameters( x, y ) {
654
+
655
+ if ( ! this.zoomToCursor ) {
656
+
657
+ return;
658
+
659
+ }
660
+
661
+ this._performCursorZoom = true;
662
+
663
+ const rect = this.domElement.getBoundingClientRect();
664
+ const dx = x - rect.left;
665
+ const dy = y - rect.top;
666
+ const w = rect.width;
667
+ const h = rect.height;
668
+
669
+ this._mouse.x = ( dx / w ) * 2 - 1;
670
+ this._mouse.y = - ( dy / h ) * 2 + 1;
671
+
672
+ this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize();
673
+
674
+ }
675
+
676
+ _clampDistance( dist ) {
677
+
678
+ return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) );
679
+
680
+ }
681
+
682
+ //
683
+ // event callbacks - update the object state
684
+ //
685
+
686
+ _handleMouseDownRotate( event ) {
687
+
688
+ this._rotateStart.set( event.clientX, event.clientY );
689
+
690
+ }
691
+
692
+ _handleMouseDownDolly( event ) {
693
+
694
+ this._updateZoomParameters( event.clientX, event.clientX );
695
+ this._dollyStart.set( event.clientX, event.clientY );
696
+
697
+ }
698
+
699
+ _handleMouseDownPan( event ) {
700
+
701
+ this._panStart.set( event.clientX, event.clientY );
702
+
703
+ }
704
+
705
+ _handleMouseMoveRotate( event ) {
706
+
707
+ this._rotateEnd.set( event.clientX, event.clientY );
708
+
709
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
710
+
711
+ const element = this.domElement;
712
+
713
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
714
+
715
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
716
+
717
+ this._rotateStart.copy( this._rotateEnd );
718
+
719
+ this.update();
720
+
721
+ }
722
+
723
+ _handleMouseMoveDolly( event ) {
724
+
725
+ this._dollyEnd.set( event.clientX, event.clientY );
726
+
727
+ this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart );
728
+
729
+ if ( this._dollyDelta.y > 0 ) {
730
+
731
+ this._dollyOut( this._getZoomScale( this._dollyDelta.y ) );
732
+
733
+ } else if ( this._dollyDelta.y < 0 ) {
734
+
735
+ this._dollyIn( this._getZoomScale( this._dollyDelta.y ) );
736
+
737
+ }
738
+
739
+ this._dollyStart.copy( this._dollyEnd );
740
+
741
+ this.update();
742
+
743
+ }
744
+
745
+ _handleMouseMovePan( event ) {
746
+
747
+ this._panEnd.set( event.clientX, event.clientY );
748
+
749
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
750
+
751
+ this._pan( this._panDelta.x, this._panDelta.y );
752
+
753
+ this._panStart.copy( this._panEnd );
754
+
755
+ this.update();
756
+
757
+ }
758
+
759
+ _handleMouseWheel( event ) {
760
+
761
+ this._updateZoomParameters( event.clientX, event.clientY );
762
+
763
+ if ( event.deltaY < 0 ) {
764
+
765
+ this._dollyIn( this._getZoomScale( event.deltaY ) );
766
+
767
+ } else if ( event.deltaY > 0 ) {
768
+
769
+ this._dollyOut( this._getZoomScale( event.deltaY ) );
770
+
771
+ }
772
+
773
+ this.update();
774
+
775
+ }
776
+
777
+ _handleKeyDown( event ) {
778
+
779
+ let needsUpdate = false;
780
+
781
+ switch ( event.code ) {
782
+
783
+ case this.keys.UP:
784
+
785
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
786
+
787
+ this._rotateUp( _twoPI * this.rotateSpeed / this.domElement.clientHeight );
788
+
789
+ } else {
790
+
791
+ this._pan( 0, this.keyPanSpeed );
792
+
793
+ }
794
+
795
+ needsUpdate = true;
796
+ break;
797
+
798
+ case this.keys.BOTTOM:
799
+
800
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
801
+
802
+ this._rotateUp( - _twoPI * this.rotateSpeed / this.domElement.clientHeight );
803
+
804
+ } else {
805
+
806
+ this._pan( 0, - this.keyPanSpeed );
807
+
808
+ }
809
+
810
+ needsUpdate = true;
811
+ break;
812
+
813
+ case this.keys.LEFT:
814
+
815
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
816
+
817
+ this._rotateLeft( _twoPI * this.rotateSpeed / this.domElement.clientHeight );
818
+
819
+ } else {
820
+
821
+ this._pan( this.keyPanSpeed, 0 );
822
+
823
+ }
824
+
825
+ needsUpdate = true;
826
+ break;
827
+
828
+ case this.keys.RIGHT:
829
+
830
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
831
+
832
+ this._rotateLeft( - _twoPI * this.rotateSpeed / this.domElement.clientHeight );
833
+
834
+ } else {
835
+
836
+ this._pan( - this.keyPanSpeed, 0 );
837
+
838
+ }
839
+
840
+ needsUpdate = true;
841
+ break;
842
+
843
+ }
844
+
845
+ if ( needsUpdate ) {
846
+
847
+ // prevent the browser from scrolling on cursor keys
848
+ event.preventDefault();
849
+
850
+ this.update();
851
+
852
+ }
853
+
854
+
855
+ }
856
+
857
+ _handleTouchStartRotate( event ) {
858
+
859
+ if ( this._pointers.length === 1 ) {
860
+
861
+ this._rotateStart.set( event.pageX, event.pageY );
862
+
863
+ } else {
864
+
865
+ const position = this._getSecondPointerPosition( event );
866
+
867
+ const x = 0.5 * ( event.pageX + position.x );
868
+ const y = 0.5 * ( event.pageY + position.y );
869
+
870
+ this._rotateStart.set( x, y );
871
+
872
+ }
873
+
874
+ }
875
+
876
+ _handleTouchStartPan( event ) {
877
+
878
+ if ( this._pointers.length === 1 ) {
879
+
880
+ this._panStart.set( event.pageX, event.pageY );
881
+
882
+ } else {
883
+
884
+ const position = this._getSecondPointerPosition( event );
885
+
886
+ const x = 0.5 * ( event.pageX + position.x );
887
+ const y = 0.5 * ( event.pageY + position.y );
888
+
889
+ this._panStart.set( x, y );
890
+
891
+ }
892
+
893
+ }
894
+
895
+ _handleTouchStartDolly( event ) {
896
+
897
+ const position = this._getSecondPointerPosition( event );
898
+
899
+ const dx = event.pageX - position.x;
900
+ const dy = event.pageY - position.y;
901
+
902
+ const distance = Math.sqrt( dx * dx + dy * dy );
903
+
904
+ this._dollyStart.set( 0, distance );
905
+
906
+ }
907
+
908
+ _handleTouchStartDollyPan( event ) {
909
+
910
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
911
+
912
+ if ( this.enablePan ) this._handleTouchStartPan( event );
913
+
914
+ }
915
+
916
+ _handleTouchStartDollyRotate( event ) {
917
+
918
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
919
+
920
+ if ( this.enableRotate ) this._handleTouchStartRotate( event );
921
+
922
+ }
923
+
924
+ _handleTouchMoveRotate( event ) {
925
+
926
+ if ( this._pointers.length == 1 ) {
927
+
928
+ this._rotateEnd.set( event.pageX, event.pageY );
929
+
930
+ } else {
931
+
932
+ const position = this._getSecondPointerPosition( event );
933
+
934
+ const x = 0.5 * ( event.pageX + position.x );
935
+ const y = 0.5 * ( event.pageY + position.y );
936
+
937
+ this._rotateEnd.set( x, y );
938
+
939
+ }
940
+
941
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
942
+
943
+ const element = this.domElement;
944
+
945
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
946
+
947
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
948
+
949
+ this._rotateStart.copy( this._rotateEnd );
950
+
951
+ }
952
+
953
+ _handleTouchMovePan( event ) {
954
+
955
+ if ( this._pointers.length === 1 ) {
956
+
957
+ this._panEnd.set( event.pageX, event.pageY );
958
+
959
+ } else {
960
+
961
+ const position = this._getSecondPointerPosition( event );
962
+
963
+ const x = 0.5 * ( event.pageX + position.x );
964
+ const y = 0.5 * ( event.pageY + position.y );
965
+
966
+ this._panEnd.set( x, y );
967
+
968
+ }
969
+
970
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
971
+
972
+ this._pan( this._panDelta.x, this._panDelta.y );
973
+
974
+ this._panStart.copy( this._panEnd );
975
+
976
+ }
977
+
978
+ _handleTouchMoveDolly( event ) {
979
+
980
+ const position = this._getSecondPointerPosition( event );
981
+
982
+ const dx = event.pageX - position.x;
983
+ const dy = event.pageY - position.y;
984
+
985
+ const distance = Math.sqrt( dx * dx + dy * dy );
986
+
987
+ this._dollyEnd.set( 0, distance );
988
+
989
+ this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) );
990
+
991
+ this._dollyOut( this._dollyDelta.y );
992
+
993
+ this._dollyStart.copy( this._dollyEnd );
994
+
995
+ const centerX = ( event.pageX + position.x ) * 0.5;
996
+ const centerY = ( event.pageY + position.y ) * 0.5;
997
+
998
+ this._updateZoomParameters( centerX, centerY );
999
+
1000
+ }
1001
+
1002
+ _handleTouchMoveDollyPan( event ) {
1003
+
1004
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
1005
+
1006
+ if ( this.enablePan ) this._handleTouchMovePan( event );
1007
+
1008
+ }
1009
+
1010
+ _handleTouchMoveDollyRotate( event ) {
1011
+
1012
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
1013
+
1014
+ if ( this.enableRotate ) this._handleTouchMoveRotate( event );
1015
+
1016
+ }
1017
+
1018
+ // pointers
1019
+
1020
+ _addPointer( event ) {
1021
+
1022
+ this._pointers.push( event.pointerId );
1023
+
1024
+ }
1025
+
1026
+ _removePointer( event ) {
1027
+
1028
+ delete this._pointerPositions[ event.pointerId ];
1029
+
1030
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
1031
+
1032
+ if ( this._pointers[ i ] == event.pointerId ) {
1033
+
1034
+ this._pointers.splice( i, 1 );
1035
+ return;
1036
+
1037
+ }
1038
+
1039
+ }
1040
+
1041
+ }
1042
+
1043
+ _isTrackingPointer( event ) {
1044
+
1045
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
1046
+
1047
+ if ( this._pointers[ i ] == event.pointerId ) return true;
1048
+
1049
+ }
1050
+
1051
+ return false;
1052
+
1053
+ }
1054
+
1055
+ _trackPointer( event ) {
1056
+
1057
+ let position = this._pointerPositions[ event.pointerId ];
1058
+
1059
+ if ( position === undefined ) {
1060
+
1061
+ position = new Vector2();
1062
+ this._pointerPositions[ event.pointerId ] = position;
1063
+
1064
+ }
1065
+
1066
+ position.set( event.pageX, event.pageY );
1067
+
1068
+ }
1069
+
1070
+ _getSecondPointerPosition( event ) {
1071
+
1072
+ const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ];
1073
+
1074
+ return this._pointerPositions[ pointerId ];
1075
+
1076
+ }
1077
+
1078
+ //
1079
+
1080
+ _customWheelEvent( event ) {
1081
+
1082
+ const mode = event.deltaMode;
1083
+
1084
+ // minimal wheel event altered to meet delta-zoom demand
1085
+ const newEvent = {
1086
+ clientX: event.clientX,
1087
+ clientY: event.clientY,
1088
+ deltaY: event.deltaY,
1089
+ };
1090
+
1091
+ switch ( mode ) {
1092
+
1093
+ case 1: // LINE_MODE
1094
+ newEvent.deltaY *= 16;
1095
+ break;
1096
+
1097
+ case 2: // PAGE_MODE
1098
+ newEvent.deltaY *= 100;
1099
+ break;
1100
+
1101
+ }
1102
+
1103
+ // detect if event was triggered by pinching
1104
+ if ( event.ctrlKey && ! this._controlActive ) {
1105
+
1106
+ newEvent.deltaY *= 10;
1107
+
1108
+ }
1109
+
1110
+ return newEvent;
1111
+
1112
+ }
1113
+
1114
+ }
1115
+
1116
+ function onPointerDown( event ) {
1117
+
1118
+ if ( this.enabled === false ) return;
1119
+
1120
+ if ( this._pointers.length === 0 ) {
1121
+
1122
+ this.domElement.setPointerCapture( event.pointerId );
1123
+
1124
+ this.domElement.addEventListener( 'pointermove', this._onPointerMove );
1125
+ this.domElement.addEventListener( 'pointerup', this._onPointerUp );
1126
+
1127
+ }
1128
+
1129
+ //
1130
+
1131
+ if ( this._isTrackingPointer( event ) ) return;
1132
+
1133
+ //
1134
+
1135
+ this._addPointer( event );
1136
+
1137
+ if ( event.pointerType === 'touch' ) {
1138
+
1139
+ this._onTouchStart( event );
1140
+
1141
+ } else {
1142
+
1143
+ this._onMouseDown( event );
1144
+
1145
+ }
1146
+
1147
+ }
1148
+
1149
+ function onPointerMove( event ) {
1150
+
1151
+ if ( this.enabled === false ) return;
1152
+
1153
+ if ( event.pointerType === 'touch' ) {
1154
+
1155
+ this._onTouchMove( event );
1156
+
1157
+ } else {
1158
+
1159
+ this._onMouseMove( event );
1160
+
1161
+ }
1162
+
1163
+ }
1164
+
1165
+ function onPointerUp( event ) {
1166
+
1167
+ this._removePointer( event );
1168
+
1169
+ switch ( this._pointers.length ) {
1170
+
1171
+ case 0:
1172
+
1173
+ this.domElement.releasePointerCapture( event.pointerId );
1174
+
1175
+ this.domElement.removeEventListener( 'pointermove', this._onPointerMove );
1176
+ this.domElement.removeEventListener( 'pointerup', this._onPointerUp );
1177
+
1178
+ this.dispatchEvent( _endEvent );
1179
+
1180
+ this.state = _STATE.NONE;
1181
+
1182
+ break;
1183
+
1184
+ case 1:
1185
+
1186
+ const pointerId = this._pointers[ 0 ];
1187
+ const position = this._pointerPositions[ pointerId ];
1188
+
1189
+ // minimal placeholder event - allows state correction on pointer-up
1190
+ this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } );
1191
+
1192
+ break;
1193
+
1194
+ }
1195
+
1196
+ }
1197
+
1198
+ function onMouseDown( event ) {
1199
+
1200
+ let mouseAction;
1201
+
1202
+ switch ( event.button ) {
1203
+
1204
+ case 0:
1205
+
1206
+ mouseAction = this.mouseButtons.LEFT;
1207
+ break;
1208
+
1209
+ case 1:
1210
+
1211
+ mouseAction = this.mouseButtons.MIDDLE;
1212
+ break;
1213
+
1214
+ case 2:
1215
+
1216
+ mouseAction = this.mouseButtons.RIGHT;
1217
+ break;
1218
+
1219
+ default:
1220
+
1221
+ mouseAction = - 1;
1222
+
1223
+ }
1224
+
1225
+ switch ( mouseAction ) {
1226
+
1227
+ case MOUSE.DOLLY:
1228
+
1229
+ if ( this.enableZoom === false ) return;
1230
+
1231
+ this._handleMouseDownDolly( event );
1232
+
1233
+ this.state = _STATE.DOLLY;
1234
+
1235
+ break;
1236
+
1237
+ case MOUSE.ROTATE:
1238
+
1239
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
1240
+
1241
+ if ( this.enablePan === false ) return;
1242
+
1243
+ this._handleMouseDownPan( event );
1244
+
1245
+ this.state = _STATE.PAN;
1246
+
1247
+ } else {
1248
+
1249
+ if ( this.enableRotate === false ) return;
1250
+
1251
+ this._handleMouseDownRotate( event );
1252
+
1253
+ this.state = _STATE.ROTATE;
1254
+
1255
+ }
1256
+
1257
+ break;
1258
+
1259
+ case MOUSE.PAN:
1260
+
1261
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
1262
+
1263
+ if ( this.enableRotate === false ) return;
1264
+
1265
+ this._handleMouseDownRotate( event );
1266
+
1267
+ this.state = _STATE.ROTATE;
1268
+
1269
+ } else {
1270
+
1271
+ if ( this.enablePan === false ) return;
1272
+
1273
+ this._handleMouseDownPan( event );
1274
+
1275
+ this.state = _STATE.PAN;
1276
+
1277
+ }
1278
+
1279
+ break;
1280
+
1281
+ default:
1282
+
1283
+ this.state = _STATE.NONE;
1284
+
1285
+ }
1286
+
1287
+ if ( this.state !== _STATE.NONE ) {
1288
+
1289
+ this.dispatchEvent( _startEvent );
1290
+
1291
+ }
1292
+
1293
+ }
1294
+
1295
+ function onMouseMove( event ) {
1296
+
1297
+ switch ( this.state ) {
1298
+
1299
+ case _STATE.ROTATE:
1300
+
1301
+ if ( this.enableRotate === false ) return;
1302
+
1303
+ this._handleMouseMoveRotate( event );
1304
+
1305
+ break;
1306
+
1307
+ case _STATE.DOLLY:
1308
+
1309
+ if ( this.enableZoom === false ) return;
1310
+
1311
+ this._handleMouseMoveDolly( event );
1312
+
1313
+ break;
1314
+
1315
+ case _STATE.PAN:
1316
+
1317
+ if ( this.enablePan === false ) return;
1318
+
1319
+ this._handleMouseMovePan( event );
1320
+
1321
+ break;
1322
+
1323
+ }
1324
+
1325
+ }
1326
+
1327
+ function onMouseWheel( event ) {
1328
+
1329
+ if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return;
1330
+
1331
+ event.preventDefault();
1332
+
1333
+ this.dispatchEvent( _startEvent );
1334
+
1335
+ this._handleMouseWheel( this._customWheelEvent( event ) );
1336
+
1337
+ this.dispatchEvent( _endEvent );
1338
+
1339
+ }
1340
+
1341
+ function onKeyDown( event ) {
1342
+
1343
+ if ( this.enabled === false || this.enablePan === false ) return;
1344
+
1345
+ this._handleKeyDown( event );
1346
+
1347
+ }
1348
+
1349
+ function onTouchStart( event ) {
1350
+
1351
+ this._trackPointer( event );
1352
+
1353
+ switch ( this._pointers.length ) {
1354
+
1355
+ case 1:
1356
+
1357
+ switch ( this.touches.ONE ) {
1358
+
1359
+ case TOUCH.ROTATE:
1360
+
1361
+ if ( this.enableRotate === false ) return;
1362
+
1363
+ this._handleTouchStartRotate( event );
1364
+
1365
+ this.state = _STATE.TOUCH_ROTATE;
1366
+
1367
+ break;
1368
+
1369
+ case TOUCH.PAN:
1370
+
1371
+ if ( this.enablePan === false ) return;
1372
+
1373
+ this._handleTouchStartPan( event );
1374
+
1375
+ this.state = _STATE.TOUCH_PAN;
1376
+
1377
+ break;
1378
+
1379
+ default:
1380
+
1381
+ this.state = _STATE.NONE;
1382
+
1383
+ }
1384
+
1385
+ break;
1386
+
1387
+ case 2:
1388
+
1389
+ switch ( this.touches.TWO ) {
1390
+
1391
+ case TOUCH.DOLLY_PAN:
1392
+
1393
+ if ( this.enableZoom === false && this.enablePan === false ) return;
1394
+
1395
+ this._handleTouchStartDollyPan( event );
1396
+
1397
+ this.state = _STATE.TOUCH_DOLLY_PAN;
1398
+
1399
+ break;
1400
+
1401
+ case TOUCH.DOLLY_ROTATE:
1402
+
1403
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
1404
+
1405
+ this._handleTouchStartDollyRotate( event );
1406
+
1407
+ this.state = _STATE.TOUCH_DOLLY_ROTATE;
1408
+
1409
+ break;
1410
+
1411
+ default:
1412
+
1413
+ this.state = _STATE.NONE;
1414
+
1415
+ }
1416
+
1417
+ break;
1418
+
1419
+ default:
1420
+
1421
+ this.state = _STATE.NONE;
1422
+
1423
+ }
1424
+
1425
+ if ( this.state !== _STATE.NONE ) {
1426
+
1427
+ this.dispatchEvent( _startEvent );
1428
+
1429
+ }
1430
+
1431
+ }
1432
+
1433
+ function onTouchMove( event ) {
1434
+
1435
+ this._trackPointer( event );
1436
+
1437
+ switch ( this.state ) {
1438
+
1439
+ case _STATE.TOUCH_ROTATE:
1440
+
1441
+ if ( this.enableRotate === false ) return;
1442
+
1443
+ this._handleTouchMoveRotate( event );
1444
+
1445
+ this.update();
1446
+
1447
+ break;
1448
+
1449
+ case _STATE.TOUCH_PAN:
1450
+
1451
+ if ( this.enablePan === false ) return;
1452
+
1453
+ this._handleTouchMovePan( event );
1454
+
1455
+ this.update();
1456
+
1457
+ break;
1458
+
1459
+ case _STATE.TOUCH_DOLLY_PAN:
1460
+
1461
+ if ( this.enableZoom === false && this.enablePan === false ) return;
1462
+
1463
+ this._handleTouchMoveDollyPan( event );
1464
+
1465
+ this.update();
1466
+
1467
+ break;
1468
+
1469
+ case _STATE.TOUCH_DOLLY_ROTATE:
1470
+
1471
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
1472
+
1473
+ this._handleTouchMoveDollyRotate( event );
1474
+
1475
+ this.update();
1476
+
1477
+ break;
1478
+
1479
+ default:
1480
+
1481
+ this.state = _STATE.NONE;
1482
+
1483
+ }
1484
+
1485
+ }
1486
+
1487
+ function onContextMenu( event ) {
1488
+
1489
+ if ( this.enabled === false ) return;
1490
+
1491
+ event.preventDefault();
1492
+
1493
+ }
1494
+
1495
+ function interceptControlDown( event ) {
1496
+
1497
+ if ( event.key === 'Control' ) {
1498
+
1499
+ this._controlActive = true;
1500
+
1501
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
1502
+
1503
+ document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
1504
+
1505
+ }
1506
+
1507
+ }
1508
+
1509
+ function interceptControlUp( event ) {
1510
+
1511
+ if ( event.key === 'Control' ) {
1512
+
1513
+ this._controlActive = false;
1514
+
1515
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
1516
+
1517
+ document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
1518
+
1519
+ }
1520
+
1521
+ }
1522
+
1523
+ export { OrbitControls };
web/vendor/addons/exporters/GLTFExporter.js ADDED
@@ -0,0 +1,3456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ BufferAttribute,
3
+ ClampToEdgeWrapping,
4
+ Color,
5
+ DoubleSide,
6
+ InterpolateDiscrete,
7
+ InterpolateLinear,
8
+ NoColorSpace,
9
+ LinearFilter,
10
+ LinearMipmapLinearFilter,
11
+ LinearMipmapNearestFilter,
12
+ MathUtils,
13
+ Matrix4,
14
+ MirroredRepeatWrapping,
15
+ NearestFilter,
16
+ NearestMipmapLinearFilter,
17
+ NearestMipmapNearestFilter,
18
+ PropertyBinding,
19
+ RGBAFormat,
20
+ RepeatWrapping,
21
+ Scene,
22
+ Source,
23
+ SRGBColorSpace,
24
+ CompressedTexture,
25
+ Vector3,
26
+ Quaternion,
27
+ REVISION
28
+ } from 'three';
29
+
30
+ /**
31
+ * The KHR_mesh_quantization extension allows these extra attribute component types
32
+ *
33
+ * @see https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md#extending-mesh-attributes
34
+ */
35
+ const KHR_mesh_quantization_ExtraAttrTypes = {
36
+ POSITION: [
37
+ 'byte',
38
+ 'byte normalized',
39
+ 'unsigned byte',
40
+ 'unsigned byte normalized',
41
+ 'short',
42
+ 'short normalized',
43
+ 'unsigned short',
44
+ 'unsigned short normalized',
45
+ ],
46
+ NORMAL: [
47
+ 'byte normalized',
48
+ 'short normalized',
49
+ ],
50
+ TANGENT: [
51
+ 'byte normalized',
52
+ 'short normalized',
53
+ ],
54
+ TEXCOORD: [
55
+ 'byte',
56
+ 'byte normalized',
57
+ 'unsigned byte',
58
+ 'short',
59
+ 'short normalized',
60
+ 'unsigned short',
61
+ ],
62
+ };
63
+
64
+
65
+ class GLTFExporter {
66
+
67
+ constructor() {
68
+
69
+ this.textureUtils = null;
70
+
71
+ this.pluginCallbacks = [];
72
+
73
+ this.register( function ( writer ) {
74
+
75
+ return new GLTFLightExtension( writer );
76
+
77
+ } );
78
+
79
+ this.register( function ( writer ) {
80
+
81
+ return new GLTFMaterialsUnlitExtension( writer );
82
+
83
+ } );
84
+
85
+ this.register( function ( writer ) {
86
+
87
+ return new GLTFMaterialsTransmissionExtension( writer );
88
+
89
+ } );
90
+
91
+ this.register( function ( writer ) {
92
+
93
+ return new GLTFMaterialsVolumeExtension( writer );
94
+
95
+ } );
96
+
97
+ this.register( function ( writer ) {
98
+
99
+ return new GLTFMaterialsIorExtension( writer );
100
+
101
+ } );
102
+
103
+ this.register( function ( writer ) {
104
+
105
+ return new GLTFMaterialsSpecularExtension( writer );
106
+
107
+ } );
108
+
109
+ this.register( function ( writer ) {
110
+
111
+ return new GLTFMaterialsClearcoatExtension( writer );
112
+
113
+ } );
114
+
115
+ this.register( function ( writer ) {
116
+
117
+ return new GLTFMaterialsDispersionExtension( writer );
118
+
119
+ } );
120
+
121
+ this.register( function ( writer ) {
122
+
123
+ return new GLTFMaterialsIridescenceExtension( writer );
124
+
125
+ } );
126
+
127
+ this.register( function ( writer ) {
128
+
129
+ return new GLTFMaterialsSheenExtension( writer );
130
+
131
+ } );
132
+
133
+ this.register( function ( writer ) {
134
+
135
+ return new GLTFMaterialsAnisotropyExtension( writer );
136
+
137
+ } );
138
+
139
+ this.register( function ( writer ) {
140
+
141
+ return new GLTFMaterialsEmissiveStrengthExtension( writer );
142
+
143
+ } );
144
+
145
+ this.register( function ( writer ) {
146
+
147
+ return new GLTFMaterialsBumpExtension( writer );
148
+
149
+ } );
150
+
151
+ this.register( function ( writer ) {
152
+
153
+ return new GLTFMeshGpuInstancing( writer );
154
+
155
+ } );
156
+
157
+ }
158
+
159
+ register( callback ) {
160
+
161
+ if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
162
+
163
+ this.pluginCallbacks.push( callback );
164
+
165
+ }
166
+
167
+ return this;
168
+
169
+ }
170
+
171
+ unregister( callback ) {
172
+
173
+ if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
174
+
175
+ this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
176
+
177
+ }
178
+
179
+ return this;
180
+
181
+ }
182
+
183
+ setTextureUtils( utils ) {
184
+
185
+ this.textureUtils = utils;
186
+
187
+ return this;
188
+
189
+ }
190
+
191
+ /**
192
+ * Parse scenes and generate GLTF output
193
+ * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
194
+ * @param {Function} onDone Callback on completed
195
+ * @param {Function} onError Callback on errors
196
+ * @param {Object} options options
197
+ */
198
+ parse( input, onDone, onError, options ) {
199
+
200
+ const writer = new GLTFWriter();
201
+ const plugins = [];
202
+
203
+ for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
204
+
205
+ plugins.push( this.pluginCallbacks[ i ]( writer ) );
206
+
207
+ }
208
+
209
+ writer.setPlugins( plugins );
210
+ writer.setTextureUtils( this.textureUtils );
211
+ writer.writeAsync( input, onDone, options ).catch( onError );
212
+
213
+ }
214
+
215
+ parseAsync( input, options ) {
216
+
217
+ const scope = this;
218
+
219
+ return new Promise( function ( resolve, reject ) {
220
+
221
+ scope.parse( input, resolve, reject, options );
222
+
223
+ } );
224
+
225
+ }
226
+
227
+ }
228
+
229
+ //------------------------------------------------------------------------------
230
+ // Constants
231
+ //------------------------------------------------------------------------------
232
+
233
+ const WEBGL_CONSTANTS = {
234
+ POINTS: 0x0000,
235
+ LINES: 0x0001,
236
+ LINE_LOOP: 0x0002,
237
+ LINE_STRIP: 0x0003,
238
+ TRIANGLES: 0x0004,
239
+ TRIANGLE_STRIP: 0x0005,
240
+ TRIANGLE_FAN: 0x0006,
241
+
242
+ BYTE: 0x1400,
243
+ UNSIGNED_BYTE: 0x1401,
244
+ SHORT: 0x1402,
245
+ UNSIGNED_SHORT: 0x1403,
246
+ INT: 0x1404,
247
+ UNSIGNED_INT: 0x1405,
248
+ FLOAT: 0x1406,
249
+
250
+ ARRAY_BUFFER: 0x8892,
251
+ ELEMENT_ARRAY_BUFFER: 0x8893,
252
+
253
+ NEAREST: 0x2600,
254
+ LINEAR: 0x2601,
255
+ NEAREST_MIPMAP_NEAREST: 0x2700,
256
+ LINEAR_MIPMAP_NEAREST: 0x2701,
257
+ NEAREST_MIPMAP_LINEAR: 0x2702,
258
+ LINEAR_MIPMAP_LINEAR: 0x2703,
259
+
260
+ CLAMP_TO_EDGE: 33071,
261
+ MIRRORED_REPEAT: 33648,
262
+ REPEAT: 10497
263
+ };
264
+
265
+ const KHR_MESH_QUANTIZATION = 'KHR_mesh_quantization';
266
+
267
+ const THREE_TO_WEBGL = {};
268
+
269
+ THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
270
+ THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
271
+ THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
272
+ THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
273
+ THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
274
+ THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
275
+
276
+ THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
277
+ THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
278
+ THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
279
+
280
+ const PATH_PROPERTIES = {
281
+ scale: 'scale',
282
+ position: 'translation',
283
+ quaternion: 'rotation',
284
+ morphTargetInfluences: 'weights'
285
+ };
286
+
287
+ const DEFAULT_SPECULAR_COLOR = new Color();
288
+
289
+ // GLB constants
290
+ // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
291
+
292
+ const GLB_HEADER_BYTES = 12;
293
+ const GLB_HEADER_MAGIC = 0x46546C67;
294
+ const GLB_VERSION = 2;
295
+
296
+ const GLB_CHUNK_PREFIX_BYTES = 8;
297
+ const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
298
+ const GLB_CHUNK_TYPE_BIN = 0x004E4942;
299
+
300
+ //------------------------------------------------------------------------------
301
+ // Utility functions
302
+ //------------------------------------------------------------------------------
303
+
304
+ /**
305
+ * Compare two arrays
306
+ * @param {Array} array1 Array 1 to compare
307
+ * @param {Array} array2 Array 2 to compare
308
+ * @return {Boolean} Returns true if both arrays are equal
309
+ */
310
+ function equalArray( array1, array2 ) {
311
+
312
+ return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
313
+
314
+ return element === array2[ index ];
315
+
316
+ } );
317
+
318
+ }
319
+
320
+ /**
321
+ * Converts a string to an ArrayBuffer.
322
+ * @param {string} text
323
+ * @return {ArrayBuffer}
324
+ */
325
+ function stringToArrayBuffer( text ) {
326
+
327
+ return new TextEncoder().encode( text ).buffer;
328
+
329
+ }
330
+
331
+ /**
332
+ * Is identity matrix
333
+ *
334
+ * @param {Matrix4} matrix
335
+ * @returns {Boolean} Returns true, if parameter is identity matrix
336
+ */
337
+ function isIdentityMatrix( matrix ) {
338
+
339
+ return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
340
+
341
+ }
342
+
343
+ /**
344
+ * Get the min and max vectors from the given attribute
345
+ * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
346
+ * @param {Integer} start
347
+ * @param {Integer} count
348
+ * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
349
+ */
350
+ function getMinMax( attribute, start, count ) {
351
+
352
+ const output = {
353
+
354
+ min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
355
+ max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
356
+
357
+ };
358
+
359
+ for ( let i = start; i < start + count; i ++ ) {
360
+
361
+ for ( let a = 0; a < attribute.itemSize; a ++ ) {
362
+
363
+ let value;
364
+
365
+ if ( attribute.itemSize > 4 ) {
366
+
367
+ // no support for interleaved data for itemSize > 4
368
+
369
+ value = attribute.array[ i * attribute.itemSize + a ];
370
+
371
+ } else {
372
+
373
+ if ( a === 0 ) value = attribute.getX( i );
374
+ else if ( a === 1 ) value = attribute.getY( i );
375
+ else if ( a === 2 ) value = attribute.getZ( i );
376
+ else if ( a === 3 ) value = attribute.getW( i );
377
+
378
+ if ( attribute.normalized === true ) {
379
+
380
+ value = MathUtils.normalize( value, attribute.array );
381
+
382
+ }
383
+
384
+ }
385
+
386
+ output.min[ a ] = Math.min( output.min[ a ], value );
387
+ output.max[ a ] = Math.max( output.max[ a ], value );
388
+
389
+ }
390
+
391
+ }
392
+
393
+ return output;
394
+
395
+ }
396
+
397
+ /**
398
+ * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
399
+ * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
400
+ *
401
+ * @param {Integer} bufferSize The size the original buffer.
402
+ * @returns {Integer} new buffer size with required padding.
403
+ *
404
+ */
405
+ function getPaddedBufferSize( bufferSize ) {
406
+
407
+ return Math.ceil( bufferSize / 4 ) * 4;
408
+
409
+ }
410
+
411
+ /**
412
+ * Returns a buffer aligned to 4-byte boundary.
413
+ *
414
+ * @param {ArrayBuffer} arrayBuffer Buffer to pad
415
+ * @param {Integer} paddingByte (Optional)
416
+ * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
417
+ */
418
+ function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
419
+
420
+ const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
421
+
422
+ if ( paddedLength !== arrayBuffer.byteLength ) {
423
+
424
+ const array = new Uint8Array( paddedLength );
425
+ array.set( new Uint8Array( arrayBuffer ) );
426
+
427
+ if ( paddingByte !== 0 ) {
428
+
429
+ for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
430
+
431
+ array[ i ] = paddingByte;
432
+
433
+ }
434
+
435
+ }
436
+
437
+ return array.buffer;
438
+
439
+ }
440
+
441
+ return arrayBuffer;
442
+
443
+ }
444
+
445
+ function getCanvas() {
446
+
447
+ if ( typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined' ) {
448
+
449
+ return new OffscreenCanvas( 1, 1 );
450
+
451
+ }
452
+
453
+ return document.createElement( 'canvas' );
454
+
455
+ }
456
+
457
+ function getToBlobPromise( canvas, mimeType ) {
458
+
459
+ if ( canvas.toBlob !== undefined ) {
460
+
461
+ return new Promise( ( resolve ) => canvas.toBlob( resolve, mimeType ) );
462
+
463
+ }
464
+
465
+ let quality;
466
+
467
+ // Blink's implementation of convertToBlob seems to default to a quality level of 100%
468
+ // Use the Blink default quality levels of toBlob instead so that file sizes are comparable.
469
+ if ( mimeType === 'image/jpeg' ) {
470
+
471
+ quality = 0.92;
472
+
473
+ } else if ( mimeType === 'image/webp' ) {
474
+
475
+ quality = 0.8;
476
+
477
+ }
478
+
479
+ return canvas.convertToBlob( {
480
+
481
+ type: mimeType,
482
+ quality: quality
483
+
484
+ } );
485
+
486
+ }
487
+
488
+ /**
489
+ * Writer
490
+ */
491
+ class GLTFWriter {
492
+
493
+ constructor() {
494
+
495
+ this.plugins = [];
496
+
497
+ this.options = {};
498
+ this.pending = [];
499
+ this.buffers = [];
500
+
501
+ this.byteOffset = 0;
502
+ this.buffers = [];
503
+ this.nodeMap = new Map();
504
+ this.skins = [];
505
+
506
+ this.extensionsUsed = {};
507
+ this.extensionsRequired = {};
508
+
509
+ this.uids = new Map();
510
+ this.uid = 0;
511
+
512
+ this.json = {
513
+ asset: {
514
+ version: '2.0',
515
+ generator: 'THREE.GLTFExporter r' + REVISION
516
+ }
517
+ };
518
+
519
+ this.cache = {
520
+ meshes: new Map(),
521
+ attributes: new Map(),
522
+ attributesNormalized: new Map(),
523
+ materials: new Map(),
524
+ textures: new Map(),
525
+ images: new Map()
526
+ };
527
+
528
+ this.textureUtils = null;
529
+
530
+ }
531
+
532
+ setPlugins( plugins ) {
533
+
534
+ this.plugins = plugins;
535
+
536
+ }
537
+
538
+ setTextureUtils( utils ) {
539
+
540
+ this.textureUtils = utils;
541
+
542
+ }
543
+
544
+ /**
545
+ * Parse scenes and generate GLTF output
546
+ * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
547
+ * @param {Function} onDone Callback on completed
548
+ * @param {Object} options options
549
+ */
550
+ async writeAsync( input, onDone, options = {} ) {
551
+
552
+ this.options = Object.assign( {
553
+ // default options
554
+ binary: false,
555
+ trs: false,
556
+ onlyVisible: true,
557
+ maxTextureSize: Infinity,
558
+ animations: [],
559
+ includeCustomExtensions: false
560
+ }, options );
561
+
562
+ if ( this.options.animations.length > 0 ) {
563
+
564
+ // Only TRS properties, and not matrices, may be targeted by animation.
565
+ this.options.trs = true;
566
+
567
+ }
568
+
569
+ await this.processInputAsync( input );
570
+
571
+ await Promise.all( this.pending );
572
+
573
+ const writer = this;
574
+ const buffers = writer.buffers;
575
+ const json = writer.json;
576
+ options = writer.options;
577
+
578
+ const extensionsUsed = writer.extensionsUsed;
579
+ const extensionsRequired = writer.extensionsRequired;
580
+
581
+ // Merge buffers.
582
+ const blob = new Blob( buffers, { type: 'application/octet-stream' } );
583
+
584
+ // Declare extensions.
585
+ const extensionsUsedList = Object.keys( extensionsUsed );
586
+ const extensionsRequiredList = Object.keys( extensionsRequired );
587
+
588
+ if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList;
589
+ if ( extensionsRequiredList.length > 0 ) json.extensionsRequired = extensionsRequiredList;
590
+
591
+ // Update bytelength of the single buffer.
592
+ if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
593
+
594
+ if ( options.binary === true ) {
595
+
596
+ // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
597
+
598
+ const reader = new FileReader();
599
+ reader.readAsArrayBuffer( blob );
600
+ reader.onloadend = function () {
601
+
602
+ // Binary chunk.
603
+ const binaryChunk = getPaddedArrayBuffer( reader.result );
604
+ const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
605
+ binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
606
+ binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
607
+
608
+ // JSON chunk.
609
+ const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
610
+ const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
611
+ jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
612
+ jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
613
+
614
+ // GLB header.
615
+ const header = new ArrayBuffer( GLB_HEADER_BYTES );
616
+ const headerView = new DataView( header );
617
+ headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
618
+ headerView.setUint32( 4, GLB_VERSION, true );
619
+ const totalByteLength = GLB_HEADER_BYTES
620
+ + jsonChunkPrefix.byteLength + jsonChunk.byteLength
621
+ + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
622
+ headerView.setUint32( 8, totalByteLength, true );
623
+
624
+ const glbBlob = new Blob( [
625
+ header,
626
+ jsonChunkPrefix,
627
+ jsonChunk,
628
+ binaryChunkPrefix,
629
+ binaryChunk
630
+ ], { type: 'application/octet-stream' } );
631
+
632
+ const glbReader = new FileReader();
633
+ glbReader.readAsArrayBuffer( glbBlob );
634
+ glbReader.onloadend = function () {
635
+
636
+ onDone( glbReader.result );
637
+
638
+ };
639
+
640
+ };
641
+
642
+ } else {
643
+
644
+ if ( json.buffers && json.buffers.length > 0 ) {
645
+
646
+ const reader = new FileReader();
647
+ reader.readAsDataURL( blob );
648
+ reader.onloadend = function () {
649
+
650
+ const base64data = reader.result;
651
+ json.buffers[ 0 ].uri = base64data;
652
+ onDone( json );
653
+
654
+ };
655
+
656
+ } else {
657
+
658
+ onDone( json );
659
+
660
+ }
661
+
662
+ }
663
+
664
+
665
+ }
666
+
667
+ /**
668
+ * Serializes a userData.
669
+ *
670
+ * @param {THREE.Object3D|THREE.Material} object
671
+ * @param {Object} objectDef
672
+ */
673
+ serializeUserData( object, objectDef ) {
674
+
675
+ if ( Object.keys( object.userData ).length === 0 ) return;
676
+
677
+ const options = this.options;
678
+ const extensionsUsed = this.extensionsUsed;
679
+
680
+ try {
681
+
682
+ const json = JSON.parse( JSON.stringify( object.userData ) );
683
+
684
+ if ( options.includeCustomExtensions && json.gltfExtensions ) {
685
+
686
+ if ( objectDef.extensions === undefined ) objectDef.extensions = {};
687
+
688
+ for ( const extensionName in json.gltfExtensions ) {
689
+
690
+ objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
691
+ extensionsUsed[ extensionName ] = true;
692
+
693
+ }
694
+
695
+ delete json.gltfExtensions;
696
+
697
+ }
698
+
699
+ if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
700
+
701
+ } catch ( error ) {
702
+
703
+ console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
704
+ 'won\'t be serialized because of JSON.stringify error - ' + error.message );
705
+
706
+ }
707
+
708
+ }
709
+
710
+ /**
711
+ * Returns ids for buffer attributes.
712
+ * @param {Object} object
713
+ * @return {Integer}
714
+ */
715
+ getUID( attribute, isRelativeCopy = false ) {
716
+
717
+ if ( this.uids.has( attribute ) === false ) {
718
+
719
+ const uids = new Map();
720
+
721
+ uids.set( true, this.uid ++ );
722
+ uids.set( false, this.uid ++ );
723
+
724
+ this.uids.set( attribute, uids );
725
+
726
+ }
727
+
728
+ const uids = this.uids.get( attribute );
729
+
730
+ return uids.get( isRelativeCopy );
731
+
732
+ }
733
+
734
+ /**
735
+ * Checks if normal attribute values are normalized.
736
+ *
737
+ * @param {BufferAttribute} normal
738
+ * @returns {Boolean}
739
+ */
740
+ isNormalizedNormalAttribute( normal ) {
741
+
742
+ const cache = this.cache;
743
+
744
+ if ( cache.attributesNormalized.has( normal ) ) return false;
745
+
746
+ const v = new Vector3();
747
+
748
+ for ( let i = 0, il = normal.count; i < il; i ++ ) {
749
+
750
+ // 0.0005 is from glTF-validator
751
+ if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
752
+
753
+ }
754
+
755
+ return true;
756
+
757
+ }
758
+
759
+ /**
760
+ * Creates normalized normal buffer attribute.
761
+ *
762
+ * @param {BufferAttribute} normal
763
+ * @returns {BufferAttribute}
764
+ *
765
+ */
766
+ createNormalizedNormalAttribute( normal ) {
767
+
768
+ const cache = this.cache;
769
+
770
+ if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
771
+
772
+ const attribute = normal.clone();
773
+ const v = new Vector3();
774
+
775
+ for ( let i = 0, il = attribute.count; i < il; i ++ ) {
776
+
777
+ v.fromBufferAttribute( attribute, i );
778
+
779
+ if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
780
+
781
+ // if values can't be normalized set (1, 0, 0)
782
+ v.setX( 1.0 );
783
+
784
+ } else {
785
+
786
+ v.normalize();
787
+
788
+ }
789
+
790
+ attribute.setXYZ( i, v.x, v.y, v.z );
791
+
792
+ }
793
+
794
+ cache.attributesNormalized.set( normal, attribute );
795
+
796
+ return attribute;
797
+
798
+ }
799
+
800
+ /**
801
+ * Applies a texture transform, if present, to the map definition. Requires
802
+ * the KHR_texture_transform extension.
803
+ *
804
+ * @param {Object} mapDef
805
+ * @param {THREE.Texture} texture
806
+ */
807
+ applyTextureTransform( mapDef, texture ) {
808
+
809
+ let didTransform = false;
810
+ const transformDef = {};
811
+
812
+ if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
813
+
814
+ transformDef.offset = texture.offset.toArray();
815
+ didTransform = true;
816
+
817
+ }
818
+
819
+ if ( texture.rotation !== 0 ) {
820
+
821
+ transformDef.rotation = texture.rotation;
822
+ didTransform = true;
823
+
824
+ }
825
+
826
+ if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
827
+
828
+ transformDef.scale = texture.repeat.toArray();
829
+ didTransform = true;
830
+
831
+ }
832
+
833
+ if ( didTransform ) {
834
+
835
+ mapDef.extensions = mapDef.extensions || {};
836
+ mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
837
+ this.extensionsUsed[ 'KHR_texture_transform' ] = true;
838
+
839
+ }
840
+
841
+ }
842
+
843
+ async buildMetalRoughTextureAsync( metalnessMap, roughnessMap ) {
844
+
845
+ if ( metalnessMap === roughnessMap ) return metalnessMap;
846
+
847
+ function getEncodingConversion( map ) {
848
+
849
+ if ( map.colorSpace === SRGBColorSpace ) {
850
+
851
+ return function SRGBToLinear( c ) {
852
+
853
+ return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
854
+
855
+ };
856
+
857
+ }
858
+
859
+ return function LinearToLinear( c ) {
860
+
861
+ return c;
862
+
863
+ };
864
+
865
+ }
866
+
867
+ if ( metalnessMap instanceof CompressedTexture ) {
868
+
869
+ metalnessMap = await this.decompressTextureAsync( metalnessMap );
870
+
871
+ }
872
+
873
+ if ( roughnessMap instanceof CompressedTexture ) {
874
+
875
+ roughnessMap = await this.decompressTextureAsync( roughnessMap );
876
+
877
+ }
878
+
879
+ const metalness = metalnessMap ? metalnessMap.image : null;
880
+ const roughness = roughnessMap ? roughnessMap.image : null;
881
+
882
+ const width = Math.max( metalness ? metalness.width : 0, roughness ? roughness.width : 0 );
883
+ const height = Math.max( metalness ? metalness.height : 0, roughness ? roughness.height : 0 );
884
+
885
+ const canvas = getCanvas();
886
+ canvas.width = width;
887
+ canvas.height = height;
888
+
889
+ const context = canvas.getContext( '2d', {
890
+ willReadFrequently: true,
891
+ } );
892
+ context.fillStyle = '#00ffff';
893
+ context.fillRect( 0, 0, width, height );
894
+
895
+ const composite = context.getImageData( 0, 0, width, height );
896
+
897
+ if ( metalness ) {
898
+
899
+ context.drawImage( metalness, 0, 0, width, height );
900
+
901
+ const convert = getEncodingConversion( metalnessMap );
902
+ const data = context.getImageData( 0, 0, width, height ).data;
903
+
904
+ for ( let i = 2; i < data.length; i += 4 ) {
905
+
906
+ composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
907
+
908
+ }
909
+
910
+ }
911
+
912
+ if ( roughness ) {
913
+
914
+ context.drawImage( roughness, 0, 0, width, height );
915
+
916
+ const convert = getEncodingConversion( roughnessMap );
917
+ const data = context.getImageData( 0, 0, width, height ).data;
918
+
919
+ for ( let i = 1; i < data.length; i += 4 ) {
920
+
921
+ composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
922
+
923
+ }
924
+
925
+ }
926
+
927
+ context.putImageData( composite, 0, 0 );
928
+
929
+ //
930
+
931
+ const reference = metalnessMap || roughnessMap;
932
+
933
+ const texture = reference.clone();
934
+
935
+ texture.source = new Source( canvas );
936
+ texture.colorSpace = NoColorSpace;
937
+ texture.channel = ( metalnessMap || roughnessMap ).channel;
938
+
939
+ if ( metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel ) {
940
+
941
+ console.warn( 'THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match.' );
942
+
943
+ }
944
+
945
+ console.warn( 'THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures.' );
946
+
947
+ return texture;
948
+
949
+ }
950
+
951
+
952
+ async decompressTextureAsync( texture, maxTextureSize = Infinity ) {
953
+
954
+ if ( this.textureUtils === null ) {
955
+
956
+ throw new Error( 'THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.' );
957
+
958
+ }
959
+
960
+ return await this.textureUtils.decompress( texture, maxTextureSize );
961
+
962
+ }
963
+
964
+ /**
965
+ * Process a buffer to append to the default one.
966
+ * @param {ArrayBuffer} buffer
967
+ * @return {Integer}
968
+ */
969
+ processBuffer( buffer ) {
970
+
971
+ const json = this.json;
972
+ const buffers = this.buffers;
973
+
974
+ if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ];
975
+
976
+ // All buffers are merged before export.
977
+ buffers.push( buffer );
978
+
979
+ return 0;
980
+
981
+ }
982
+
983
+ /**
984
+ * Process and generate a BufferView
985
+ * @param {BufferAttribute} attribute
986
+ * @param {number} componentType
987
+ * @param {number} start
988
+ * @param {number} count
989
+ * @param {number} target (Optional) Target usage of the BufferView
990
+ * @return {Object}
991
+ */
992
+ processBufferView( attribute, componentType, start, count, target ) {
993
+
994
+ const json = this.json;
995
+
996
+ if ( ! json.bufferViews ) json.bufferViews = [];
997
+
998
+ // Create a new dataview and dump the attribute's array into it
999
+
1000
+ let componentSize;
1001
+
1002
+ switch ( componentType ) {
1003
+
1004
+ case WEBGL_CONSTANTS.BYTE:
1005
+ case WEBGL_CONSTANTS.UNSIGNED_BYTE:
1006
+
1007
+ componentSize = 1;
1008
+
1009
+ break;
1010
+
1011
+ case WEBGL_CONSTANTS.SHORT:
1012
+ case WEBGL_CONSTANTS.UNSIGNED_SHORT:
1013
+
1014
+ componentSize = 2;
1015
+
1016
+ break;
1017
+
1018
+ default:
1019
+
1020
+ componentSize = 4;
1021
+
1022
+ }
1023
+
1024
+ let byteStride = attribute.itemSize * componentSize;
1025
+
1026
+ if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
1027
+
1028
+ // Each element of a vertex attribute MUST be aligned to 4-byte boundaries
1029
+ // inside a bufferView
1030
+ byteStride = Math.ceil( byteStride / 4 ) * 4;
1031
+
1032
+ }
1033
+
1034
+ const byteLength = getPaddedBufferSize( count * byteStride );
1035
+ const dataView = new DataView( new ArrayBuffer( byteLength ) );
1036
+ let offset = 0;
1037
+
1038
+ for ( let i = start; i < start + count; i ++ ) {
1039
+
1040
+ for ( let a = 0; a < attribute.itemSize; a ++ ) {
1041
+
1042
+ let value;
1043
+
1044
+ if ( attribute.itemSize > 4 ) {
1045
+
1046
+ // no support for interleaved data for itemSize > 4
1047
+
1048
+ value = attribute.array[ i * attribute.itemSize + a ];
1049
+
1050
+ } else {
1051
+
1052
+ if ( a === 0 ) value = attribute.getX( i );
1053
+ else if ( a === 1 ) value = attribute.getY( i );
1054
+ else if ( a === 2 ) value = attribute.getZ( i );
1055
+ else if ( a === 3 ) value = attribute.getW( i );
1056
+
1057
+ if ( attribute.normalized === true ) {
1058
+
1059
+ value = MathUtils.normalize( value, attribute.array );
1060
+
1061
+ }
1062
+
1063
+ }
1064
+
1065
+ if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
1066
+
1067
+ dataView.setFloat32( offset, value, true );
1068
+
1069
+ } else if ( componentType === WEBGL_CONSTANTS.INT ) {
1070
+
1071
+ dataView.setInt32( offset, value, true );
1072
+
1073
+ } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
1074
+
1075
+ dataView.setUint32( offset, value, true );
1076
+
1077
+ } else if ( componentType === WEBGL_CONSTANTS.SHORT ) {
1078
+
1079
+ dataView.setInt16( offset, value, true );
1080
+
1081
+ } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
1082
+
1083
+ dataView.setUint16( offset, value, true );
1084
+
1085
+ } else if ( componentType === WEBGL_CONSTANTS.BYTE ) {
1086
+
1087
+ dataView.setInt8( offset, value );
1088
+
1089
+ } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
1090
+
1091
+ dataView.setUint8( offset, value );
1092
+
1093
+ }
1094
+
1095
+ offset += componentSize;
1096
+
1097
+ }
1098
+
1099
+ if ( ( offset % byteStride ) !== 0 ) {
1100
+
1101
+ offset += byteStride - ( offset % byteStride );
1102
+
1103
+ }
1104
+
1105
+ }
1106
+
1107
+ const bufferViewDef = {
1108
+
1109
+ buffer: this.processBuffer( dataView.buffer ),
1110
+ byteOffset: this.byteOffset,
1111
+ byteLength: byteLength
1112
+
1113
+ };
1114
+
1115
+ if ( target !== undefined ) bufferViewDef.target = target;
1116
+
1117
+ if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
1118
+
1119
+ // Only define byteStride for vertex attributes.
1120
+ bufferViewDef.byteStride = byteStride;
1121
+
1122
+ }
1123
+
1124
+ this.byteOffset += byteLength;
1125
+
1126
+ json.bufferViews.push( bufferViewDef );
1127
+
1128
+ // @TODO Merge bufferViews where possible.
1129
+ const output = {
1130
+
1131
+ id: json.bufferViews.length - 1,
1132
+ byteLength: 0
1133
+
1134
+ };
1135
+
1136
+ return output;
1137
+
1138
+ }
1139
+
1140
+ /**
1141
+ * Process and generate a BufferView from an image Blob.
1142
+ * @param {Blob} blob
1143
+ * @return {Promise<Integer>}
1144
+ */
1145
+ processBufferViewImage( blob ) {
1146
+
1147
+ const writer = this;
1148
+ const json = writer.json;
1149
+
1150
+ if ( ! json.bufferViews ) json.bufferViews = [];
1151
+
1152
+ return new Promise( function ( resolve ) {
1153
+
1154
+ const reader = new FileReader();
1155
+ reader.readAsArrayBuffer( blob );
1156
+ reader.onloadend = function () {
1157
+
1158
+ const buffer = getPaddedArrayBuffer( reader.result );
1159
+
1160
+ const bufferViewDef = {
1161
+ buffer: writer.processBuffer( buffer ),
1162
+ byteOffset: writer.byteOffset,
1163
+ byteLength: buffer.byteLength
1164
+ };
1165
+
1166
+ writer.byteOffset += buffer.byteLength;
1167
+ resolve( json.bufferViews.push( bufferViewDef ) - 1 );
1168
+
1169
+ };
1170
+
1171
+ } );
1172
+
1173
+ }
1174
+
1175
+ /**
1176
+ * Process attribute to generate an accessor
1177
+ * @param {BufferAttribute} attribute Attribute to process
1178
+ * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range
1179
+ * @param {Integer} start (Optional)
1180
+ * @param {Integer} count (Optional)
1181
+ * @return {Integer|null} Index of the processed accessor on the "accessors" array
1182
+ */
1183
+ processAccessor( attribute, geometry, start, count ) {
1184
+
1185
+ const json = this.json;
1186
+
1187
+ const types = {
1188
+
1189
+ 1: 'SCALAR',
1190
+ 2: 'VEC2',
1191
+ 3: 'VEC3',
1192
+ 4: 'VEC4',
1193
+ 9: 'MAT3',
1194
+ 16: 'MAT4'
1195
+
1196
+ };
1197
+
1198
+ let componentType;
1199
+
1200
+ // Detect the component type of the attribute array
1201
+ if ( attribute.array.constructor === Float32Array ) {
1202
+
1203
+ componentType = WEBGL_CONSTANTS.FLOAT;
1204
+
1205
+ } else if ( attribute.array.constructor === Int32Array ) {
1206
+
1207
+ componentType = WEBGL_CONSTANTS.INT;
1208
+
1209
+ } else if ( attribute.array.constructor === Uint32Array ) {
1210
+
1211
+ componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
1212
+
1213
+ } else if ( attribute.array.constructor === Int16Array ) {
1214
+
1215
+ componentType = WEBGL_CONSTANTS.SHORT;
1216
+
1217
+ } else if ( attribute.array.constructor === Uint16Array ) {
1218
+
1219
+ componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
1220
+
1221
+ } else if ( attribute.array.constructor === Int8Array ) {
1222
+
1223
+ componentType = WEBGL_CONSTANTS.BYTE;
1224
+
1225
+ } else if ( attribute.array.constructor === Uint8Array ) {
1226
+
1227
+ componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
1228
+
1229
+ } else {
1230
+
1231
+ throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type: ' + attribute.array.constructor.name );
1232
+
1233
+ }
1234
+
1235
+ if ( start === undefined ) start = 0;
1236
+ if ( count === undefined || count === Infinity ) count = attribute.count;
1237
+
1238
+ // Skip creating an accessor if the attribute doesn't have data to export
1239
+ if ( count === 0 ) return null;
1240
+
1241
+ const minMax = getMinMax( attribute, start, count );
1242
+ let bufferViewTarget;
1243
+
1244
+ // If geometry isn't provided, don't infer the target usage of the bufferView. For
1245
+ // animation samplers, target must not be set.
1246
+ if ( geometry !== undefined ) {
1247
+
1248
+ bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
1249
+
1250
+ }
1251
+
1252
+ const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
1253
+
1254
+ const accessorDef = {
1255
+
1256
+ bufferView: bufferView.id,
1257
+ byteOffset: bufferView.byteOffset,
1258
+ componentType: componentType,
1259
+ count: count,
1260
+ max: minMax.max,
1261
+ min: minMax.min,
1262
+ type: types[ attribute.itemSize ]
1263
+
1264
+ };
1265
+
1266
+ if ( attribute.normalized === true ) accessorDef.normalized = true;
1267
+ if ( ! json.accessors ) json.accessors = [];
1268
+
1269
+ return json.accessors.push( accessorDef ) - 1;
1270
+
1271
+ }
1272
+
1273
+ /**
1274
+ * Process image
1275
+ * @param {Image} image to process
1276
+ * @param {Integer} format of the image (RGBAFormat)
1277
+ * @param {Boolean} flipY before writing out the image
1278
+ * @param {String} mimeType export format
1279
+ * @return {Integer} Index of the processed texture in the "images" array
1280
+ */
1281
+ processImage( image, format, flipY, mimeType = 'image/png' ) {
1282
+
1283
+ if ( image !== null ) {
1284
+
1285
+ const writer = this;
1286
+ const cache = writer.cache;
1287
+ const json = writer.json;
1288
+ const options = writer.options;
1289
+ const pending = writer.pending;
1290
+
1291
+ if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
1292
+
1293
+ const cachedImages = cache.images.get( image );
1294
+
1295
+ const key = mimeType + ':flipY/' + flipY.toString();
1296
+
1297
+ if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
1298
+
1299
+ if ( ! json.images ) json.images = [];
1300
+
1301
+ const imageDef = { mimeType: mimeType };
1302
+
1303
+ const canvas = getCanvas();
1304
+
1305
+ canvas.width = Math.min( image.width, options.maxTextureSize );
1306
+ canvas.height = Math.min( image.height, options.maxTextureSize );
1307
+
1308
+ const ctx = canvas.getContext( '2d', {
1309
+ willReadFrequently: true,
1310
+ } );
1311
+
1312
+ if ( flipY === true ) {
1313
+
1314
+ ctx.translate( 0, canvas.height );
1315
+ ctx.scale( 1, - 1 );
1316
+
1317
+ }
1318
+
1319
+ if ( image.data !== undefined ) { // THREE.DataTexture
1320
+
1321
+ if ( format !== RGBAFormat ) {
1322
+
1323
+ console.error( 'GLTFExporter: Only RGBAFormat is supported.', format );
1324
+
1325
+ }
1326
+
1327
+ if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
1328
+
1329
+ console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
1330
+
1331
+ }
1332
+
1333
+ const data = new Uint8ClampedArray( image.height * image.width * 4 );
1334
+
1335
+ for ( let i = 0; i < data.length; i += 4 ) {
1336
+
1337
+ data[ i + 0 ] = image.data[ i + 0 ];
1338
+ data[ i + 1 ] = image.data[ i + 1 ];
1339
+ data[ i + 2 ] = image.data[ i + 2 ];
1340
+ data[ i + 3 ] = image.data[ i + 3 ];
1341
+
1342
+ }
1343
+
1344
+ ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
1345
+
1346
+ } else {
1347
+
1348
+ if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
1349
+ ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
1350
+ ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
1351
+ ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ) {
1352
+
1353
+ ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
1354
+
1355
+ } else {
1356
+
1357
+ throw new Error( 'THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.' );
1358
+
1359
+ }
1360
+
1361
+ }
1362
+
1363
+ if ( options.binary === true ) {
1364
+
1365
+ pending.push(
1366
+
1367
+ getToBlobPromise( canvas, mimeType )
1368
+ .then( blob => writer.processBufferViewImage( blob ) )
1369
+ .then( bufferViewIndex => {
1370
+
1371
+ imageDef.bufferView = bufferViewIndex;
1372
+
1373
+ } )
1374
+
1375
+ );
1376
+
1377
+ } else {
1378
+
1379
+ if ( canvas.toDataURL !== undefined ) {
1380
+
1381
+ imageDef.uri = canvas.toDataURL( mimeType );
1382
+
1383
+ } else {
1384
+
1385
+ pending.push(
1386
+
1387
+ getToBlobPromise( canvas, mimeType )
1388
+ .then( blob => new FileReader().readAsDataURL( blob ) )
1389
+ .then( dataURL => {
1390
+
1391
+ imageDef.uri = dataURL;
1392
+
1393
+ } )
1394
+
1395
+ );
1396
+
1397
+ }
1398
+
1399
+ }
1400
+
1401
+ const index = json.images.push( imageDef ) - 1;
1402
+ cachedImages[ key ] = index;
1403
+ return index;
1404
+
1405
+ } else {
1406
+
1407
+ throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' );
1408
+
1409
+ }
1410
+
1411
+ }
1412
+
1413
+ /**
1414
+ * Process sampler
1415
+ * @param {Texture} map Texture to process
1416
+ * @return {Integer} Index of the processed texture in the "samplers" array
1417
+ */
1418
+ processSampler( map ) {
1419
+
1420
+ const json = this.json;
1421
+
1422
+ if ( ! json.samplers ) json.samplers = [];
1423
+
1424
+ const samplerDef = {
1425
+ magFilter: THREE_TO_WEBGL[ map.magFilter ],
1426
+ minFilter: THREE_TO_WEBGL[ map.minFilter ],
1427
+ wrapS: THREE_TO_WEBGL[ map.wrapS ],
1428
+ wrapT: THREE_TO_WEBGL[ map.wrapT ]
1429
+ };
1430
+
1431
+ return json.samplers.push( samplerDef ) - 1;
1432
+
1433
+ }
1434
+
1435
+ /**
1436
+ * Process texture
1437
+ * @param {Texture} map Map to process
1438
+ * @return {Integer} Index of the processed texture in the "textures" array
1439
+ */
1440
+ async processTextureAsync( map ) {
1441
+
1442
+ const writer = this;
1443
+ const options = writer.options;
1444
+ const cache = this.cache;
1445
+ const json = this.json;
1446
+
1447
+ if ( cache.textures.has( map ) ) return cache.textures.get( map );
1448
+
1449
+ if ( ! json.textures ) json.textures = [];
1450
+
1451
+ // make non-readable textures (e.g. CompressedTexture) readable by blitting them into a new texture
1452
+ if ( map instanceof CompressedTexture ) {
1453
+
1454
+ map = await this.decompressTextureAsync( map, options.maxTextureSize );
1455
+
1456
+ }
1457
+
1458
+ let mimeType = map.userData.mimeType;
1459
+
1460
+ if ( mimeType === 'image/webp' ) mimeType = 'image/png';
1461
+
1462
+ const textureDef = {
1463
+ sampler: this.processSampler( map ),
1464
+ source: this.processImage( map.image, map.format, map.flipY, mimeType )
1465
+ };
1466
+
1467
+ if ( map.name ) textureDef.name = map.name;
1468
+
1469
+ await this._invokeAllAsync( async function ( ext ) {
1470
+
1471
+ ext.writeTexture && await ext.writeTexture( map, textureDef );
1472
+
1473
+ } );
1474
+
1475
+ const index = json.textures.push( textureDef ) - 1;
1476
+ cache.textures.set( map, index );
1477
+ return index;
1478
+
1479
+ }
1480
+
1481
+ /**
1482
+ * Process material
1483
+ * @param {THREE.Material} material Material to process
1484
+ * @return {Integer|null} Index of the processed material in the "materials" array
1485
+ */
1486
+ async processMaterialAsync( material ) {
1487
+
1488
+ const cache = this.cache;
1489
+ const json = this.json;
1490
+
1491
+ if ( cache.materials.has( material ) ) return cache.materials.get( material );
1492
+
1493
+ if ( material.isShaderMaterial ) {
1494
+
1495
+ console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
1496
+ return null;
1497
+
1498
+ }
1499
+
1500
+ if ( ! json.materials ) json.materials = [];
1501
+
1502
+ // @QUESTION Should we avoid including any attribute that has the default value?
1503
+ const materialDef = { pbrMetallicRoughness: {} };
1504
+
1505
+ if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
1506
+
1507
+ console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
1508
+
1509
+ }
1510
+
1511
+ // pbrMetallicRoughness.baseColorFactor
1512
+ const color = material.color.toArray().concat( [ material.opacity ] );
1513
+
1514
+ if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
1515
+
1516
+ materialDef.pbrMetallicRoughness.baseColorFactor = color;
1517
+
1518
+ }
1519
+
1520
+ if ( material.isMeshStandardMaterial ) {
1521
+
1522
+ materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
1523
+ materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
1524
+
1525
+ } else {
1526
+
1527
+ materialDef.pbrMetallicRoughness.metallicFactor = 0;
1528
+ materialDef.pbrMetallicRoughness.roughnessFactor = 1;
1529
+
1530
+ }
1531
+
1532
+ // pbrMetallicRoughness.metallicRoughnessTexture
1533
+ if ( material.metalnessMap || material.roughnessMap ) {
1534
+
1535
+ const metalRoughTexture = await this.buildMetalRoughTextureAsync( material.metalnessMap, material.roughnessMap );
1536
+
1537
+ const metalRoughMapDef = {
1538
+ index: await this.processTextureAsync( metalRoughTexture ),
1539
+ texCoord: metalRoughTexture.channel
1540
+ };
1541
+ this.applyTextureTransform( metalRoughMapDef, metalRoughTexture );
1542
+ materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
1543
+
1544
+ }
1545
+
1546
+ // pbrMetallicRoughness.baseColorTexture
1547
+ if ( material.map ) {
1548
+
1549
+ const baseColorMapDef = {
1550
+ index: await this.processTextureAsync( material.map ),
1551
+ texCoord: material.map.channel
1552
+ };
1553
+ this.applyTextureTransform( baseColorMapDef, material.map );
1554
+ materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
1555
+
1556
+ }
1557
+
1558
+ if ( material.emissive ) {
1559
+
1560
+ const emissive = material.emissive;
1561
+ const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
1562
+
1563
+ if ( maxEmissiveComponent > 0 ) {
1564
+
1565
+ materialDef.emissiveFactor = material.emissive.toArray();
1566
+
1567
+ }
1568
+
1569
+ // emissiveTexture
1570
+ if ( material.emissiveMap ) {
1571
+
1572
+ const emissiveMapDef = {
1573
+ index: await this.processTextureAsync( material.emissiveMap ),
1574
+ texCoord: material.emissiveMap.channel
1575
+ };
1576
+ this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
1577
+ materialDef.emissiveTexture = emissiveMapDef;
1578
+
1579
+ }
1580
+
1581
+ }
1582
+
1583
+ // normalTexture
1584
+ if ( material.normalMap ) {
1585
+
1586
+ const normalMapDef = {
1587
+ index: await this.processTextureAsync( material.normalMap ),
1588
+ texCoord: material.normalMap.channel
1589
+ };
1590
+
1591
+ if ( material.normalScale && material.normalScale.x !== 1 ) {
1592
+
1593
+ // glTF normal scale is univariate. Ignore `y`, which may be flipped.
1594
+ // Context: https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
1595
+ normalMapDef.scale = material.normalScale.x;
1596
+
1597
+ }
1598
+
1599
+ this.applyTextureTransform( normalMapDef, material.normalMap );
1600
+ materialDef.normalTexture = normalMapDef;
1601
+
1602
+ }
1603
+
1604
+ // occlusionTexture
1605
+ if ( material.aoMap ) {
1606
+
1607
+ const occlusionMapDef = {
1608
+ index: await this.processTextureAsync( material.aoMap ),
1609
+ texCoord: material.aoMap.channel
1610
+ };
1611
+
1612
+ if ( material.aoMapIntensity !== 1.0 ) {
1613
+
1614
+ occlusionMapDef.strength = material.aoMapIntensity;
1615
+
1616
+ }
1617
+
1618
+ this.applyTextureTransform( occlusionMapDef, material.aoMap );
1619
+ materialDef.occlusionTexture = occlusionMapDef;
1620
+
1621
+ }
1622
+
1623
+ // alphaMode
1624
+ if ( material.transparent ) {
1625
+
1626
+ materialDef.alphaMode = 'BLEND';
1627
+
1628
+ } else {
1629
+
1630
+ if ( material.alphaTest > 0.0 ) {
1631
+
1632
+ materialDef.alphaMode = 'MASK';
1633
+ materialDef.alphaCutoff = material.alphaTest;
1634
+
1635
+ }
1636
+
1637
+ }
1638
+
1639
+ // doubleSided
1640
+ if ( material.side === DoubleSide ) materialDef.doubleSided = true;
1641
+ if ( material.name !== '' ) materialDef.name = material.name;
1642
+
1643
+ this.serializeUserData( material, materialDef );
1644
+
1645
+ await this._invokeAllAsync( async function ( ext ) {
1646
+
1647
+ ext.writeMaterialAsync && await ext.writeMaterialAsync( material, materialDef );
1648
+
1649
+ } );
1650
+
1651
+ const index = json.materials.push( materialDef ) - 1;
1652
+ cache.materials.set( material, index );
1653
+ return index;
1654
+
1655
+ }
1656
+
1657
+ /**
1658
+ * Process mesh
1659
+ * @param {THREE.Mesh} mesh Mesh to process
1660
+ * @return {Integer|null} Index of the processed mesh in the "meshes" array
1661
+ */
1662
+ async processMeshAsync( mesh ) {
1663
+
1664
+ const cache = this.cache;
1665
+ const json = this.json;
1666
+
1667
+ const meshCacheKeyParts = [ mesh.geometry.uuid ];
1668
+
1669
+ if ( Array.isArray( mesh.material ) ) {
1670
+
1671
+ for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
1672
+
1673
+ meshCacheKeyParts.push( mesh.material[ i ].uuid );
1674
+
1675
+ }
1676
+
1677
+ } else {
1678
+
1679
+ meshCacheKeyParts.push( mesh.material.uuid );
1680
+
1681
+ }
1682
+
1683
+ const meshCacheKey = meshCacheKeyParts.join( ':' );
1684
+
1685
+ if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
1686
+
1687
+ const geometry = mesh.geometry;
1688
+
1689
+ let mode;
1690
+
1691
+ // Use the correct mode
1692
+ if ( mesh.isLineSegments ) {
1693
+
1694
+ mode = WEBGL_CONSTANTS.LINES;
1695
+
1696
+ } else if ( mesh.isLineLoop ) {
1697
+
1698
+ mode = WEBGL_CONSTANTS.LINE_LOOP;
1699
+
1700
+ } else if ( mesh.isLine ) {
1701
+
1702
+ mode = WEBGL_CONSTANTS.LINE_STRIP;
1703
+
1704
+ } else if ( mesh.isPoints ) {
1705
+
1706
+ mode = WEBGL_CONSTANTS.POINTS;
1707
+
1708
+ } else {
1709
+
1710
+ mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
1711
+
1712
+ }
1713
+
1714
+ const meshDef = {};
1715
+ const attributes = {};
1716
+ const primitives = [];
1717
+ const targets = [];
1718
+
1719
+ // Conversion between attributes names in threejs and gltf spec
1720
+ const nameConversion = {
1721
+ uv: 'TEXCOORD_0',
1722
+ uv1: 'TEXCOORD_1',
1723
+ uv2: 'TEXCOORD_2',
1724
+ uv3: 'TEXCOORD_3',
1725
+ color: 'COLOR_0',
1726
+ skinWeight: 'WEIGHTS_0',
1727
+ skinIndex: 'JOINTS_0'
1728
+ };
1729
+
1730
+ const originalNormal = geometry.getAttribute( 'normal' );
1731
+
1732
+ if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
1733
+
1734
+ console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
1735
+
1736
+ geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
1737
+
1738
+ }
1739
+
1740
+ // @QUESTION Detect if .vertexColors = true?
1741
+ // For every attribute create an accessor
1742
+ let modifiedAttribute = null;
1743
+
1744
+ for ( let attributeName in geometry.attributes ) {
1745
+
1746
+ // Ignore morph target attributes, which are exported later.
1747
+ if ( attributeName.slice( 0, 5 ) === 'morph' ) continue;
1748
+
1749
+ const attribute = geometry.attributes[ attributeName ];
1750
+ attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
1751
+
1752
+ // Prefix all geometry attributes except the ones specifically
1753
+ // listed in the spec; non-spec attributes are considered custom.
1754
+ const validVertexAttributes =
1755
+ /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
1756
+
1757
+ if ( ! validVertexAttributes.test( attributeName ) ) attributeName = '_' + attributeName;
1758
+
1759
+ if ( cache.attributes.has( this.getUID( attribute ) ) ) {
1760
+
1761
+ attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
1762
+ continue;
1763
+
1764
+ }
1765
+
1766
+ // Enforce glTF vertex attribute requirements:
1767
+ // - JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT
1768
+ // - Only custom attributes may be INT or UNSIGNED_INT
1769
+ modifiedAttribute = null;
1770
+ const array = attribute.array;
1771
+
1772
+ if ( attributeName === 'JOINTS_0' &&
1773
+ ! ( array instanceof Uint16Array ) &&
1774
+ ! ( array instanceof Uint8Array ) ) {
1775
+
1776
+ console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
1777
+ modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
1778
+
1779
+ } else if ( ( array instanceof Uint32Array || array instanceof Int32Array ) && ! attributeName.startsWith( '_' ) ) {
1780
+
1781
+ console.warn( `GLTFExporter: Attribute "${ attributeName }" converted to type FLOAT.` );
1782
+ modifiedAttribute = GLTFExporter.Utils.toFloat32BufferAttribute( attribute );
1783
+
1784
+ }
1785
+
1786
+ const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
1787
+
1788
+ if ( accessor !== null ) {
1789
+
1790
+ if ( ! attributeName.startsWith( '_' ) ) {
1791
+
1792
+ this.detectMeshQuantization( attributeName, attribute );
1793
+
1794
+ }
1795
+
1796
+ attributes[ attributeName ] = accessor;
1797
+ cache.attributes.set( this.getUID( attribute ), accessor );
1798
+
1799
+ }
1800
+
1801
+ }
1802
+
1803
+ if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
1804
+
1805
+ // Skip if no exportable attributes found
1806
+ if ( Object.keys( attributes ).length === 0 ) return null;
1807
+
1808
+ // Morph targets
1809
+ if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
1810
+
1811
+ const weights = [];
1812
+ const targetNames = [];
1813
+ const reverseDictionary = {};
1814
+
1815
+ if ( mesh.morphTargetDictionary !== undefined ) {
1816
+
1817
+ for ( const key in mesh.morphTargetDictionary ) {
1818
+
1819
+ reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
1820
+
1821
+ }
1822
+
1823
+ }
1824
+
1825
+ for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
1826
+
1827
+ const target = {};
1828
+ let warned = false;
1829
+
1830
+ for ( const attributeName in geometry.morphAttributes ) {
1831
+
1832
+ // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
1833
+ // Three.js doesn't support TANGENT yet.
1834
+
1835
+ if ( attributeName !== 'position' && attributeName !== 'normal' ) {
1836
+
1837
+ if ( ! warned ) {
1838
+
1839
+ console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
1840
+ warned = true;
1841
+
1842
+ }
1843
+
1844
+ continue;
1845
+
1846
+ }
1847
+
1848
+ const attribute = geometry.morphAttributes[ attributeName ][ i ];
1849
+ const gltfAttributeName = attributeName.toUpperCase();
1850
+
1851
+ // Three.js morph attribute has absolute values while the one of glTF has relative values.
1852
+ //
1853
+ // glTF 2.0 Specification:
1854
+ // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
1855
+
1856
+ const baseAttribute = geometry.attributes[ attributeName ];
1857
+
1858
+ if ( cache.attributes.has( this.getUID( attribute, true ) ) ) {
1859
+
1860
+ target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) );
1861
+ continue;
1862
+
1863
+ }
1864
+
1865
+ // Clones attribute not to override
1866
+ const relativeAttribute = attribute.clone();
1867
+
1868
+ if ( ! geometry.morphTargetsRelative ) {
1869
+
1870
+ for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
1871
+
1872
+ for ( let a = 0; a < attribute.itemSize; a ++ ) {
1873
+
1874
+ if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) );
1875
+ if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) );
1876
+ if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) );
1877
+ if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) );
1878
+
1879
+ }
1880
+
1881
+ }
1882
+
1883
+ }
1884
+
1885
+ target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
1886
+ cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] );
1887
+
1888
+ }
1889
+
1890
+ targets.push( target );
1891
+
1892
+ weights.push( mesh.morphTargetInfluences[ i ] );
1893
+
1894
+ if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
1895
+
1896
+ }
1897
+
1898
+ meshDef.weights = weights;
1899
+
1900
+ if ( targetNames.length > 0 ) {
1901
+
1902
+ meshDef.extras = {};
1903
+ meshDef.extras.targetNames = targetNames;
1904
+
1905
+ }
1906
+
1907
+ }
1908
+
1909
+ const isMultiMaterial = Array.isArray( mesh.material );
1910
+
1911
+ if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
1912
+
1913
+ let didForceIndices = false;
1914
+
1915
+ if ( isMultiMaterial && geometry.index === null ) {
1916
+
1917
+ const indices = [];
1918
+
1919
+ for ( let i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
1920
+
1921
+ indices[ i ] = i;
1922
+
1923
+ }
1924
+
1925
+ geometry.setIndex( indices );
1926
+
1927
+ didForceIndices = true;
1928
+
1929
+ }
1930
+
1931
+ const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
1932
+ const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
1933
+
1934
+ for ( let i = 0, il = groups.length; i < il; i ++ ) {
1935
+
1936
+ const primitive = {
1937
+ mode: mode,
1938
+ attributes: attributes,
1939
+ };
1940
+
1941
+ this.serializeUserData( geometry, primitive );
1942
+
1943
+ if ( targets.length > 0 ) primitive.targets = targets;
1944
+
1945
+ if ( geometry.index !== null ) {
1946
+
1947
+ let cacheKey = this.getUID( geometry.index );
1948
+
1949
+ if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
1950
+
1951
+ cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
1952
+
1953
+ }
1954
+
1955
+ if ( cache.attributes.has( cacheKey ) ) {
1956
+
1957
+ primitive.indices = cache.attributes.get( cacheKey );
1958
+
1959
+ } else {
1960
+
1961
+ primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
1962
+ cache.attributes.set( cacheKey, primitive.indices );
1963
+
1964
+ }
1965
+
1966
+ if ( primitive.indices === null ) delete primitive.indices;
1967
+
1968
+ }
1969
+
1970
+ const material = await this.processMaterialAsync( materials[ groups[ i ].materialIndex ] );
1971
+
1972
+ if ( material !== null ) primitive.material = material;
1973
+
1974
+ primitives.push( primitive );
1975
+
1976
+ }
1977
+
1978
+ if ( didForceIndices === true ) {
1979
+
1980
+ geometry.setIndex( null );
1981
+
1982
+ }
1983
+
1984
+ meshDef.primitives = primitives;
1985
+
1986
+ if ( ! json.meshes ) json.meshes = [];
1987
+
1988
+ await this._invokeAllAsync( function ( ext ) {
1989
+
1990
+ ext.writeMesh && ext.writeMesh( mesh, meshDef );
1991
+
1992
+ } );
1993
+
1994
+ const index = json.meshes.push( meshDef ) - 1;
1995
+ cache.meshes.set( meshCacheKey, index );
1996
+ return index;
1997
+
1998
+ }
1999
+
2000
+ /**
2001
+ * If a vertex attribute with a
2002
+ * [non-standard data type](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
2003
+ * is used, it is checked whether it is a valid data type according to the
2004
+ * [KHR_mesh_quantization](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)
2005
+ * extension.
2006
+ * In this case the extension is automatically added to the list of used extensions.
2007
+ *
2008
+ * @param {string} attributeName
2009
+ * @param {THREE.BufferAttribute} attribute
2010
+ */
2011
+ detectMeshQuantization( attributeName, attribute ) {
2012
+
2013
+ if ( this.extensionsUsed[ KHR_MESH_QUANTIZATION ] ) return;
2014
+
2015
+ let attrType = undefined;
2016
+
2017
+ switch ( attribute.array.constructor ) {
2018
+
2019
+ case Int8Array:
2020
+
2021
+ attrType = 'byte';
2022
+
2023
+ break;
2024
+
2025
+ case Uint8Array:
2026
+
2027
+ attrType = 'unsigned byte';
2028
+
2029
+ break;
2030
+
2031
+ case Int16Array:
2032
+
2033
+ attrType = 'short';
2034
+
2035
+ break;
2036
+
2037
+ case Uint16Array:
2038
+
2039
+ attrType = 'unsigned short';
2040
+
2041
+ break;
2042
+
2043
+ default:
2044
+
2045
+ return;
2046
+
2047
+ }
2048
+
2049
+ if ( attribute.normalized ) attrType += ' normalized';
2050
+
2051
+ const attrNamePrefix = attributeName.split( '_', 1 )[ 0 ];
2052
+
2053
+ if ( KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ] && KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ].includes( attrType ) ) {
2054
+
2055
+ this.extensionsUsed[ KHR_MESH_QUANTIZATION ] = true;
2056
+ this.extensionsRequired[ KHR_MESH_QUANTIZATION ] = true;
2057
+
2058
+ }
2059
+
2060
+ }
2061
+
2062
+ /**
2063
+ * Process camera
2064
+ * @param {THREE.Camera} camera Camera to process
2065
+ * @return {Integer} Index of the processed mesh in the "camera" array
2066
+ */
2067
+ processCamera( camera ) {
2068
+
2069
+ const json = this.json;
2070
+
2071
+ if ( ! json.cameras ) json.cameras = [];
2072
+
2073
+ const isOrtho = camera.isOrthographicCamera;
2074
+
2075
+ const cameraDef = {
2076
+ type: isOrtho ? 'orthographic' : 'perspective'
2077
+ };
2078
+
2079
+ if ( isOrtho ) {
2080
+
2081
+ cameraDef.orthographic = {
2082
+ xmag: camera.right * 2,
2083
+ ymag: camera.top * 2,
2084
+ zfar: camera.far <= 0 ? 0.001 : camera.far,
2085
+ znear: camera.near < 0 ? 0 : camera.near
2086
+ };
2087
+
2088
+ } else {
2089
+
2090
+ cameraDef.perspective = {
2091
+ aspectRatio: camera.aspect,
2092
+ yfov: MathUtils.degToRad( camera.fov ),
2093
+ zfar: camera.far <= 0 ? 0.001 : camera.far,
2094
+ znear: camera.near < 0 ? 0 : camera.near
2095
+ };
2096
+
2097
+ }
2098
+
2099
+ // Question: Is saving "type" as name intentional?
2100
+ if ( camera.name !== '' ) cameraDef.name = camera.type;
2101
+
2102
+ return json.cameras.push( cameraDef ) - 1;
2103
+
2104
+ }
2105
+
2106
+ /**
2107
+ * Creates glTF animation entry from AnimationClip object.
2108
+ *
2109
+ * Status:
2110
+ * - Only properties listed in PATH_PROPERTIES may be animated.
2111
+ *
2112
+ * @param {THREE.AnimationClip} clip
2113
+ * @param {THREE.Object3D} root
2114
+ * @return {number|null}
2115
+ */
2116
+ processAnimation( clip, root ) {
2117
+
2118
+ const json = this.json;
2119
+ const nodeMap = this.nodeMap;
2120
+
2121
+ if ( ! json.animations ) json.animations = [];
2122
+
2123
+ clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
2124
+
2125
+ const tracks = clip.tracks;
2126
+ const channels = [];
2127
+ const samplers = [];
2128
+
2129
+ for ( let i = 0; i < tracks.length; ++ i ) {
2130
+
2131
+ const track = tracks[ i ];
2132
+ const trackBinding = PropertyBinding.parseTrackName( track.name );
2133
+ let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
2134
+ const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
2135
+
2136
+ if ( trackBinding.objectName === 'bones' ) {
2137
+
2138
+ if ( trackNode.isSkinnedMesh === true ) {
2139
+
2140
+ trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
2141
+
2142
+ } else {
2143
+
2144
+ trackNode = undefined;
2145
+
2146
+ }
2147
+
2148
+ }
2149
+
2150
+ if ( ! trackNode || ! trackProperty ) {
2151
+
2152
+ console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
2153
+ continue;
2154
+
2155
+ }
2156
+
2157
+ const inputItemSize = 1;
2158
+ let outputItemSize = track.values.length / track.times.length;
2159
+
2160
+ if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
2161
+
2162
+ outputItemSize /= trackNode.morphTargetInfluences.length;
2163
+
2164
+ }
2165
+
2166
+ let interpolation;
2167
+
2168
+ // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
2169
+
2170
+ // Detecting glTF cubic spline interpolant by checking factory method's special property
2171
+ // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
2172
+ // valid value from .getInterpolation().
2173
+ if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
2174
+
2175
+ interpolation = 'CUBICSPLINE';
2176
+
2177
+ // itemSize of CUBICSPLINE keyframe is 9
2178
+ // (VEC3 * 3: inTangent, splineVertex, and outTangent)
2179
+ // but needs to be stored as VEC3 so dividing by 3 here.
2180
+ outputItemSize /= 3;
2181
+
2182
+ } else if ( track.getInterpolation() === InterpolateDiscrete ) {
2183
+
2184
+ interpolation = 'STEP';
2185
+
2186
+ } else {
2187
+
2188
+ interpolation = 'LINEAR';
2189
+
2190
+ }
2191
+
2192
+ samplers.push( {
2193
+ input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
2194
+ output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
2195
+ interpolation: interpolation
2196
+ } );
2197
+
2198
+ channels.push( {
2199
+ sampler: samplers.length - 1,
2200
+ target: {
2201
+ node: nodeMap.get( trackNode ),
2202
+ path: trackProperty
2203
+ }
2204
+ } );
2205
+
2206
+ }
2207
+
2208
+ json.animations.push( {
2209
+ name: clip.name || 'clip_' + json.animations.length,
2210
+ samplers: samplers,
2211
+ channels: channels
2212
+ } );
2213
+
2214
+ return json.animations.length - 1;
2215
+
2216
+ }
2217
+
2218
+ /**
2219
+ * @param {THREE.Object3D} object
2220
+ * @return {number|null}
2221
+ */
2222
+ processSkin( object ) {
2223
+
2224
+ const json = this.json;
2225
+ const nodeMap = this.nodeMap;
2226
+
2227
+ const node = json.nodes[ nodeMap.get( object ) ];
2228
+
2229
+ const skeleton = object.skeleton;
2230
+
2231
+ if ( skeleton === undefined ) return null;
2232
+
2233
+ const rootJoint = object.skeleton.bones[ 0 ];
2234
+
2235
+ if ( rootJoint === undefined ) return null;
2236
+
2237
+ const joints = [];
2238
+ const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
2239
+ const temporaryBoneInverse = new Matrix4();
2240
+
2241
+ for ( let i = 0; i < skeleton.bones.length; ++ i ) {
2242
+
2243
+ joints.push( nodeMap.get( skeleton.bones[ i ] ) );
2244
+ temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
2245
+ temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
2246
+
2247
+ }
2248
+
2249
+ if ( json.skins === undefined ) json.skins = [];
2250
+
2251
+ json.skins.push( {
2252
+ inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
2253
+ joints: joints,
2254
+ skeleton: nodeMap.get( rootJoint )
2255
+ } );
2256
+
2257
+ const skinIndex = node.skin = json.skins.length - 1;
2258
+
2259
+ return skinIndex;
2260
+
2261
+ }
2262
+
2263
+ /**
2264
+ * Process Object3D node
2265
+ * @param {THREE.Object3D} node Object3D to processNodeAsync
2266
+ * @return {Integer} Index of the node in the nodes list
2267
+ */
2268
+ async processNodeAsync( object ) {
2269
+
2270
+ const json = this.json;
2271
+ const options = this.options;
2272
+ const nodeMap = this.nodeMap;
2273
+
2274
+ if ( ! json.nodes ) json.nodes = [];
2275
+
2276
+ const nodeDef = {};
2277
+
2278
+ if ( options.trs ) {
2279
+
2280
+ const rotation = object.quaternion.toArray();
2281
+ const position = object.position.toArray();
2282
+ const scale = object.scale.toArray();
2283
+
2284
+ if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
2285
+
2286
+ nodeDef.rotation = rotation;
2287
+
2288
+ }
2289
+
2290
+ if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
2291
+
2292
+ nodeDef.translation = position;
2293
+
2294
+ }
2295
+
2296
+ if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
2297
+
2298
+ nodeDef.scale = scale;
2299
+
2300
+ }
2301
+
2302
+ } else {
2303
+
2304
+ if ( object.matrixAutoUpdate ) {
2305
+
2306
+ object.updateMatrix();
2307
+
2308
+ }
2309
+
2310
+ if ( isIdentityMatrix( object.matrix ) === false ) {
2311
+
2312
+ nodeDef.matrix = object.matrix.elements;
2313
+
2314
+ }
2315
+
2316
+ }
2317
+
2318
+ // We don't export empty strings name because it represents no-name in Three.js.
2319
+ if ( object.name !== '' ) nodeDef.name = String( object.name );
2320
+
2321
+ this.serializeUserData( object, nodeDef );
2322
+
2323
+ if ( object.isMesh || object.isLine || object.isPoints ) {
2324
+
2325
+ const meshIndex = await this.processMeshAsync( object );
2326
+
2327
+ if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
2328
+
2329
+ } else if ( object.isCamera ) {
2330
+
2331
+ nodeDef.camera = this.processCamera( object );
2332
+
2333
+ }
2334
+
2335
+ if ( object.isSkinnedMesh ) this.skins.push( object );
2336
+
2337
+ if ( object.children.length > 0 ) {
2338
+
2339
+ const children = [];
2340
+
2341
+ for ( let i = 0, l = object.children.length; i < l; i ++ ) {
2342
+
2343
+ const child = object.children[ i ];
2344
+
2345
+ if ( child.visible || options.onlyVisible === false ) {
2346
+
2347
+ const nodeIndex = await this.processNodeAsync( child );
2348
+
2349
+ if ( nodeIndex !== null ) children.push( nodeIndex );
2350
+
2351
+ }
2352
+
2353
+ }
2354
+
2355
+ if ( children.length > 0 ) nodeDef.children = children;
2356
+
2357
+ }
2358
+
2359
+ await this._invokeAllAsync( function ( ext ) {
2360
+
2361
+ ext.writeNode && ext.writeNode( object, nodeDef );
2362
+
2363
+ } );
2364
+
2365
+ const nodeIndex = json.nodes.push( nodeDef ) - 1;
2366
+ nodeMap.set( object, nodeIndex );
2367
+ return nodeIndex;
2368
+
2369
+ }
2370
+
2371
+ /**
2372
+ * Process Scene
2373
+ * @param {Scene} node Scene to process
2374
+ */
2375
+ async processSceneAsync( scene ) {
2376
+
2377
+ const json = this.json;
2378
+ const options = this.options;
2379
+
2380
+ if ( ! json.scenes ) {
2381
+
2382
+ json.scenes = [];
2383
+ json.scene = 0;
2384
+
2385
+ }
2386
+
2387
+ const sceneDef = {};
2388
+
2389
+ if ( scene.name !== '' ) sceneDef.name = scene.name;
2390
+
2391
+ json.scenes.push( sceneDef );
2392
+
2393
+ const nodes = [];
2394
+
2395
+ for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
2396
+
2397
+ const child = scene.children[ i ];
2398
+
2399
+ if ( child.visible || options.onlyVisible === false ) {
2400
+
2401
+ const nodeIndex = await this.processNodeAsync( child );
2402
+
2403
+ if ( nodeIndex !== null ) nodes.push( nodeIndex );
2404
+
2405
+ }
2406
+
2407
+ }
2408
+
2409
+ if ( nodes.length > 0 ) sceneDef.nodes = nodes;
2410
+
2411
+ this.serializeUserData( scene, sceneDef );
2412
+
2413
+ }
2414
+
2415
+ /**
2416
+ * Creates a Scene to hold a list of objects and parse it
2417
+ * @param {Array} objects List of objects to process
2418
+ */
2419
+ async processObjectsAsync( objects ) {
2420
+
2421
+ const scene = new Scene();
2422
+ scene.name = 'AuxScene';
2423
+
2424
+ for ( let i = 0; i < objects.length; i ++ ) {
2425
+
2426
+ // We push directly to children instead of calling `add` to prevent
2427
+ // modify the .parent and break its original scene and hierarchy
2428
+ scene.children.push( objects[ i ] );
2429
+
2430
+ }
2431
+
2432
+ await this.processSceneAsync( scene );
2433
+
2434
+ }
2435
+
2436
+ /**
2437
+ * @param {THREE.Object3D|Array<THREE.Object3D>} input
2438
+ */
2439
+ async processInputAsync( input ) {
2440
+
2441
+ const options = this.options;
2442
+
2443
+ input = input instanceof Array ? input : [ input ];
2444
+
2445
+ await this._invokeAllAsync( function ( ext ) {
2446
+
2447
+ ext.beforeParse && ext.beforeParse( input );
2448
+
2449
+ } );
2450
+
2451
+ const objectsWithoutScene = [];
2452
+
2453
+ for ( let i = 0; i < input.length; i ++ ) {
2454
+
2455
+ if ( input[ i ] instanceof Scene ) {
2456
+
2457
+ await this.processSceneAsync( input[ i ] );
2458
+
2459
+ } else {
2460
+
2461
+ objectsWithoutScene.push( input[ i ] );
2462
+
2463
+ }
2464
+
2465
+ }
2466
+
2467
+ if ( objectsWithoutScene.length > 0 ) {
2468
+
2469
+ await this.processObjectsAsync( objectsWithoutScene );
2470
+
2471
+ }
2472
+
2473
+ for ( let i = 0; i < this.skins.length; ++ i ) {
2474
+
2475
+ this.processSkin( this.skins[ i ] );
2476
+
2477
+ }
2478
+
2479
+ for ( let i = 0; i < options.animations.length; ++ i ) {
2480
+
2481
+ this.processAnimation( options.animations[ i ], input[ 0 ] );
2482
+
2483
+ }
2484
+
2485
+ await this._invokeAllAsync( function ( ext ) {
2486
+
2487
+ ext.afterParse && ext.afterParse( input );
2488
+
2489
+ } );
2490
+
2491
+ }
2492
+
2493
+ async _invokeAllAsync( func ) {
2494
+
2495
+ for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
2496
+
2497
+ await func( this.plugins[ i ] );
2498
+
2499
+ }
2500
+
2501
+ }
2502
+
2503
+ }
2504
+
2505
+ /**
2506
+ * Punctual Lights Extension
2507
+ *
2508
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
2509
+ */
2510
+ class GLTFLightExtension {
2511
+
2512
+ constructor( writer ) {
2513
+
2514
+ this.writer = writer;
2515
+ this.name = 'KHR_lights_punctual';
2516
+
2517
+ }
2518
+
2519
+ writeNode( light, nodeDef ) {
2520
+
2521
+ if ( ! light.isLight ) return;
2522
+
2523
+ if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
2524
+
2525
+ console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
2526
+ return;
2527
+
2528
+ }
2529
+
2530
+ const writer = this.writer;
2531
+ const json = writer.json;
2532
+ const extensionsUsed = writer.extensionsUsed;
2533
+
2534
+ const lightDef = {};
2535
+
2536
+ if ( light.name ) lightDef.name = light.name;
2537
+
2538
+ lightDef.color = light.color.toArray();
2539
+
2540
+ lightDef.intensity = light.intensity;
2541
+
2542
+ if ( light.isDirectionalLight ) {
2543
+
2544
+ lightDef.type = 'directional';
2545
+
2546
+ } else if ( light.isPointLight ) {
2547
+
2548
+ lightDef.type = 'point';
2549
+
2550
+ if ( light.distance > 0 ) lightDef.range = light.distance;
2551
+
2552
+ } else if ( light.isSpotLight ) {
2553
+
2554
+ lightDef.type = 'spot';
2555
+
2556
+ if ( light.distance > 0 ) lightDef.range = light.distance;
2557
+
2558
+ lightDef.spot = {};
2559
+ lightDef.spot.innerConeAngle = ( 1.0 - light.penumbra ) * light.angle;
2560
+ lightDef.spot.outerConeAngle = light.angle;
2561
+
2562
+ }
2563
+
2564
+ if ( light.decay !== undefined && light.decay !== 2 ) {
2565
+
2566
+ console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
2567
+ + 'and expects light.decay=2.' );
2568
+
2569
+ }
2570
+
2571
+ if ( light.target
2572
+ && ( light.target.parent !== light
2573
+ || light.target.position.x !== 0
2574
+ || light.target.position.y !== 0
2575
+ || light.target.position.z !== - 1 ) ) {
2576
+
2577
+ console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
2578
+ + 'make light.target a child of the light with position 0,0,-1.' );
2579
+
2580
+ }
2581
+
2582
+ if ( ! extensionsUsed[ this.name ] ) {
2583
+
2584
+ json.extensions = json.extensions || {};
2585
+ json.extensions[ this.name ] = { lights: [] };
2586
+ extensionsUsed[ this.name ] = true;
2587
+
2588
+ }
2589
+
2590
+ const lights = json.extensions[ this.name ].lights;
2591
+ lights.push( lightDef );
2592
+
2593
+ nodeDef.extensions = nodeDef.extensions || {};
2594
+ nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
2595
+
2596
+ }
2597
+
2598
+ }
2599
+
2600
+ /**
2601
+ * Unlit Materials Extension
2602
+ *
2603
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
2604
+ */
2605
+ class GLTFMaterialsUnlitExtension {
2606
+
2607
+ constructor( writer ) {
2608
+
2609
+ this.writer = writer;
2610
+ this.name = 'KHR_materials_unlit';
2611
+
2612
+ }
2613
+
2614
+ async writeMaterialAsync( material, materialDef ) {
2615
+
2616
+ if ( ! material.isMeshBasicMaterial ) return;
2617
+
2618
+ const writer = this.writer;
2619
+ const extensionsUsed = writer.extensionsUsed;
2620
+
2621
+ materialDef.extensions = materialDef.extensions || {};
2622
+ materialDef.extensions[ this.name ] = {};
2623
+
2624
+ extensionsUsed[ this.name ] = true;
2625
+
2626
+ materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
2627
+ materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
2628
+
2629
+ }
2630
+
2631
+ }
2632
+
2633
+ /**
2634
+ * Clearcoat Materials Extension
2635
+ *
2636
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
2637
+ */
2638
+ class GLTFMaterialsClearcoatExtension {
2639
+
2640
+ constructor( writer ) {
2641
+
2642
+ this.writer = writer;
2643
+ this.name = 'KHR_materials_clearcoat';
2644
+
2645
+ }
2646
+
2647
+ async writeMaterialAsync( material, materialDef ) {
2648
+
2649
+ if ( ! material.isMeshPhysicalMaterial || material.clearcoat === 0 ) return;
2650
+
2651
+ const writer = this.writer;
2652
+ const extensionsUsed = writer.extensionsUsed;
2653
+
2654
+ const extensionDef = {};
2655
+
2656
+ extensionDef.clearcoatFactor = material.clearcoat;
2657
+
2658
+ if ( material.clearcoatMap ) {
2659
+
2660
+ const clearcoatMapDef = {
2661
+ index: await writer.processTextureAsync( material.clearcoatMap ),
2662
+ texCoord: material.clearcoatMap.channel
2663
+ };
2664
+ writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap );
2665
+ extensionDef.clearcoatTexture = clearcoatMapDef;
2666
+
2667
+ }
2668
+
2669
+ extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
2670
+
2671
+ if ( material.clearcoatRoughnessMap ) {
2672
+
2673
+ const clearcoatRoughnessMapDef = {
2674
+ index: await writer.processTextureAsync( material.clearcoatRoughnessMap ),
2675
+ texCoord: material.clearcoatRoughnessMap.channel
2676
+ };
2677
+ writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap );
2678
+ extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
2679
+
2680
+ }
2681
+
2682
+ if ( material.clearcoatNormalMap ) {
2683
+
2684
+ const clearcoatNormalMapDef = {
2685
+ index: await writer.processTextureAsync( material.clearcoatNormalMap ),
2686
+ texCoord: material.clearcoatNormalMap.channel
2687
+ };
2688
+
2689
+ if ( material.clearcoatNormalScale.x !== 1 ) clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x;
2690
+
2691
+ writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap );
2692
+ extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
2693
+
2694
+ }
2695
+
2696
+ materialDef.extensions = materialDef.extensions || {};
2697
+ materialDef.extensions[ this.name ] = extensionDef;
2698
+
2699
+ extensionsUsed[ this.name ] = true;
2700
+
2701
+
2702
+ }
2703
+
2704
+ }
2705
+
2706
+ /**
2707
+ * Materials dispersion Extension
2708
+ *
2709
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_dispersion
2710
+ */
2711
+ class GLTFMaterialsDispersionExtension {
2712
+
2713
+ constructor( writer ) {
2714
+
2715
+ this.writer = writer;
2716
+ this.name = 'KHR_materials_dispersion';
2717
+
2718
+ }
2719
+
2720
+ async writeMaterialAsync( material, materialDef ) {
2721
+
2722
+ if ( ! material.isMeshPhysicalMaterial || material.dispersion === 0 ) return;
2723
+
2724
+ const writer = this.writer;
2725
+ const extensionsUsed = writer.extensionsUsed;
2726
+
2727
+ const extensionDef = {};
2728
+
2729
+ extensionDef.dispersion = material.dispersion;
2730
+
2731
+ materialDef.extensions = materialDef.extensions || {};
2732
+ materialDef.extensions[ this.name ] = extensionDef;
2733
+
2734
+ extensionsUsed[ this.name ] = true;
2735
+
2736
+ }
2737
+
2738
+ }
2739
+
2740
+ /**
2741
+ * Iridescence Materials Extension
2742
+ *
2743
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
2744
+ */
2745
+ class GLTFMaterialsIridescenceExtension {
2746
+
2747
+ constructor( writer ) {
2748
+
2749
+ this.writer = writer;
2750
+ this.name = 'KHR_materials_iridescence';
2751
+
2752
+ }
2753
+
2754
+ async writeMaterialAsync( material, materialDef ) {
2755
+
2756
+ if ( ! material.isMeshPhysicalMaterial || material.iridescence === 0 ) return;
2757
+
2758
+ const writer = this.writer;
2759
+ const extensionsUsed = writer.extensionsUsed;
2760
+
2761
+ const extensionDef = {};
2762
+
2763
+ extensionDef.iridescenceFactor = material.iridescence;
2764
+
2765
+ if ( material.iridescenceMap ) {
2766
+
2767
+ const iridescenceMapDef = {
2768
+ index: await writer.processTextureAsync( material.iridescenceMap ),
2769
+ texCoord: material.iridescenceMap.channel
2770
+ };
2771
+ writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap );
2772
+ extensionDef.iridescenceTexture = iridescenceMapDef;
2773
+
2774
+ }
2775
+
2776
+ extensionDef.iridescenceIor = material.iridescenceIOR;
2777
+ extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ];
2778
+ extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ];
2779
+
2780
+ if ( material.iridescenceThicknessMap ) {
2781
+
2782
+ const iridescenceThicknessMapDef = {
2783
+ index: await writer.processTextureAsync( material.iridescenceThicknessMap ),
2784
+ texCoord: material.iridescenceThicknessMap.channel
2785
+ };
2786
+ writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap );
2787
+ extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
2788
+
2789
+ }
2790
+
2791
+ materialDef.extensions = materialDef.extensions || {};
2792
+ materialDef.extensions[ this.name ] = extensionDef;
2793
+
2794
+ extensionsUsed[ this.name ] = true;
2795
+
2796
+ }
2797
+
2798
+ }
2799
+
2800
+ /**
2801
+ * Transmission Materials Extension
2802
+ *
2803
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
2804
+ */
2805
+ class GLTFMaterialsTransmissionExtension {
2806
+
2807
+ constructor( writer ) {
2808
+
2809
+ this.writer = writer;
2810
+ this.name = 'KHR_materials_transmission';
2811
+
2812
+ }
2813
+
2814
+ async writeMaterialAsync( material, materialDef ) {
2815
+
2816
+ if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
2817
+
2818
+ const writer = this.writer;
2819
+ const extensionsUsed = writer.extensionsUsed;
2820
+
2821
+ const extensionDef = {};
2822
+
2823
+ extensionDef.transmissionFactor = material.transmission;
2824
+
2825
+ if ( material.transmissionMap ) {
2826
+
2827
+ const transmissionMapDef = {
2828
+ index: await writer.processTextureAsync( material.transmissionMap ),
2829
+ texCoord: material.transmissionMap.channel
2830
+ };
2831
+ writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
2832
+ extensionDef.transmissionTexture = transmissionMapDef;
2833
+
2834
+ }
2835
+
2836
+ materialDef.extensions = materialDef.extensions || {};
2837
+ materialDef.extensions[ this.name ] = extensionDef;
2838
+
2839
+ extensionsUsed[ this.name ] = true;
2840
+
2841
+ }
2842
+
2843
+ }
2844
+
2845
+ /**
2846
+ * Materials Volume Extension
2847
+ *
2848
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
2849
+ */
2850
+ class GLTFMaterialsVolumeExtension {
2851
+
2852
+ constructor( writer ) {
2853
+
2854
+ this.writer = writer;
2855
+ this.name = 'KHR_materials_volume';
2856
+
2857
+ }
2858
+
2859
+ async writeMaterialAsync( material, materialDef ) {
2860
+
2861
+ if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
2862
+
2863
+ const writer = this.writer;
2864
+ const extensionsUsed = writer.extensionsUsed;
2865
+
2866
+ const extensionDef = {};
2867
+
2868
+ extensionDef.thicknessFactor = material.thickness;
2869
+
2870
+ if ( material.thicknessMap ) {
2871
+
2872
+ const thicknessMapDef = {
2873
+ index: await writer.processTextureAsync( material.thicknessMap ),
2874
+ texCoord: material.thicknessMap.channel
2875
+ };
2876
+ writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
2877
+ extensionDef.thicknessTexture = thicknessMapDef;
2878
+
2879
+ }
2880
+
2881
+ if ( material.attenuationDistance !== Infinity ) {
2882
+
2883
+ extensionDef.attenuationDistance = material.attenuationDistance;
2884
+
2885
+ }
2886
+
2887
+ extensionDef.attenuationColor = material.attenuationColor.toArray();
2888
+
2889
+ materialDef.extensions = materialDef.extensions || {};
2890
+ materialDef.extensions[ this.name ] = extensionDef;
2891
+
2892
+ extensionsUsed[ this.name ] = true;
2893
+
2894
+ }
2895
+
2896
+ }
2897
+
2898
+ /**
2899
+ * Materials ior Extension
2900
+ *
2901
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
2902
+ */
2903
+ class GLTFMaterialsIorExtension {
2904
+
2905
+ constructor( writer ) {
2906
+
2907
+ this.writer = writer;
2908
+ this.name = 'KHR_materials_ior';
2909
+
2910
+ }
2911
+
2912
+ async writeMaterialAsync( material, materialDef ) {
2913
+
2914
+ if ( ! material.isMeshPhysicalMaterial || material.ior === 1.5 ) return;
2915
+
2916
+ const writer = this.writer;
2917
+ const extensionsUsed = writer.extensionsUsed;
2918
+
2919
+ const extensionDef = {};
2920
+
2921
+ extensionDef.ior = material.ior;
2922
+
2923
+ materialDef.extensions = materialDef.extensions || {};
2924
+ materialDef.extensions[ this.name ] = extensionDef;
2925
+
2926
+ extensionsUsed[ this.name ] = true;
2927
+
2928
+ }
2929
+
2930
+ }
2931
+
2932
+ /**
2933
+ * Materials specular Extension
2934
+ *
2935
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
2936
+ */
2937
+ class GLTFMaterialsSpecularExtension {
2938
+
2939
+ constructor( writer ) {
2940
+
2941
+ this.writer = writer;
2942
+ this.name = 'KHR_materials_specular';
2943
+
2944
+ }
2945
+
2946
+ async writeMaterialAsync( material, materialDef ) {
2947
+
2948
+ if ( ! material.isMeshPhysicalMaterial || ( material.specularIntensity === 1.0 &&
2949
+ material.specularColor.equals( DEFAULT_SPECULAR_COLOR ) &&
2950
+ ! material.specularIntensityMap && ! material.specularColorMap ) ) return;
2951
+
2952
+ const writer = this.writer;
2953
+ const extensionsUsed = writer.extensionsUsed;
2954
+
2955
+ const extensionDef = {};
2956
+
2957
+ if ( material.specularIntensityMap ) {
2958
+
2959
+ const specularIntensityMapDef = {
2960
+ index: await writer.processTextureAsync( material.specularIntensityMap ),
2961
+ texCoord: material.specularIntensityMap.channel
2962
+ };
2963
+ writer.applyTextureTransform( specularIntensityMapDef, material.specularIntensityMap );
2964
+ extensionDef.specularTexture = specularIntensityMapDef;
2965
+
2966
+ }
2967
+
2968
+ if ( material.specularColorMap ) {
2969
+
2970
+ const specularColorMapDef = {
2971
+ index: await writer.processTextureAsync( material.specularColorMap ),
2972
+ texCoord: material.specularColorMap.channel
2973
+ };
2974
+ writer.applyTextureTransform( specularColorMapDef, material.specularColorMap );
2975
+ extensionDef.specularColorTexture = specularColorMapDef;
2976
+
2977
+ }
2978
+
2979
+ extensionDef.specularFactor = material.specularIntensity;
2980
+ extensionDef.specularColorFactor = material.specularColor.toArray();
2981
+
2982
+ materialDef.extensions = materialDef.extensions || {};
2983
+ materialDef.extensions[ this.name ] = extensionDef;
2984
+
2985
+ extensionsUsed[ this.name ] = true;
2986
+
2987
+ }
2988
+
2989
+ }
2990
+
2991
+ /**
2992
+ * Sheen Materials Extension
2993
+ *
2994
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
2995
+ */
2996
+ class GLTFMaterialsSheenExtension {
2997
+
2998
+ constructor( writer ) {
2999
+
3000
+ this.writer = writer;
3001
+ this.name = 'KHR_materials_sheen';
3002
+
3003
+ }
3004
+
3005
+ async writeMaterialAsync( material, materialDef ) {
3006
+
3007
+ if ( ! material.isMeshPhysicalMaterial || material.sheen == 0.0 ) return;
3008
+
3009
+ const writer = this.writer;
3010
+ const extensionsUsed = writer.extensionsUsed;
3011
+
3012
+ const extensionDef = {};
3013
+
3014
+ if ( material.sheenRoughnessMap ) {
3015
+
3016
+ const sheenRoughnessMapDef = {
3017
+ index: await writer.processTextureAsync( material.sheenRoughnessMap ),
3018
+ texCoord: material.sheenRoughnessMap.channel
3019
+ };
3020
+ writer.applyTextureTransform( sheenRoughnessMapDef, material.sheenRoughnessMap );
3021
+ extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef;
3022
+
3023
+ }
3024
+
3025
+ if ( material.sheenColorMap ) {
3026
+
3027
+ const sheenColorMapDef = {
3028
+ index: await writer.processTextureAsync( material.sheenColorMap ),
3029
+ texCoord: material.sheenColorMap.channel
3030
+ };
3031
+ writer.applyTextureTransform( sheenColorMapDef, material.sheenColorMap );
3032
+ extensionDef.sheenColorTexture = sheenColorMapDef;
3033
+
3034
+ }
3035
+
3036
+ extensionDef.sheenRoughnessFactor = material.sheenRoughness;
3037
+ extensionDef.sheenColorFactor = material.sheenColor.toArray();
3038
+
3039
+ materialDef.extensions = materialDef.extensions || {};
3040
+ materialDef.extensions[ this.name ] = extensionDef;
3041
+
3042
+ extensionsUsed[ this.name ] = true;
3043
+
3044
+ }
3045
+
3046
+ }
3047
+
3048
+ /**
3049
+ * Anisotropy Materials Extension
3050
+ *
3051
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy
3052
+ */
3053
+ class GLTFMaterialsAnisotropyExtension {
3054
+
3055
+ constructor( writer ) {
3056
+
3057
+ this.writer = writer;
3058
+ this.name = 'KHR_materials_anisotropy';
3059
+
3060
+ }
3061
+
3062
+ async writeMaterialAsync( material, materialDef ) {
3063
+
3064
+ if ( ! material.isMeshPhysicalMaterial || material.anisotropy == 0.0 ) return;
3065
+
3066
+ const writer = this.writer;
3067
+ const extensionsUsed = writer.extensionsUsed;
3068
+
3069
+ const extensionDef = {};
3070
+
3071
+ if ( material.anisotropyMap ) {
3072
+
3073
+ const anisotropyMapDef = { index: await writer.processTextureAsync( material.anisotropyMap ) };
3074
+ writer.applyTextureTransform( anisotropyMapDef, material.anisotropyMap );
3075
+ extensionDef.anisotropyTexture = anisotropyMapDef;
3076
+
3077
+ }
3078
+
3079
+ extensionDef.anisotropyStrength = material.anisotropy;
3080
+ extensionDef.anisotropyRotation = material.anisotropyRotation;
3081
+
3082
+ materialDef.extensions = materialDef.extensions || {};
3083
+ materialDef.extensions[ this.name ] = extensionDef;
3084
+
3085
+ extensionsUsed[ this.name ] = true;
3086
+
3087
+ }
3088
+
3089
+ }
3090
+
3091
+ /**
3092
+ * Materials Emissive Strength Extension
3093
+ *
3094
+ * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
3095
+ */
3096
+ class GLTFMaterialsEmissiveStrengthExtension {
3097
+
3098
+ constructor( writer ) {
3099
+
3100
+ this.writer = writer;
3101
+ this.name = 'KHR_materials_emissive_strength';
3102
+
3103
+ }
3104
+
3105
+ async writeMaterialAsync( material, materialDef ) {
3106
+
3107
+ if ( ! material.isMeshStandardMaterial || material.emissiveIntensity === 1.0 ) return;
3108
+
3109
+ const writer = this.writer;
3110
+ const extensionsUsed = writer.extensionsUsed;
3111
+
3112
+ const extensionDef = {};
3113
+
3114
+ extensionDef.emissiveStrength = material.emissiveIntensity;
3115
+
3116
+ materialDef.extensions = materialDef.extensions || {};
3117
+ materialDef.extensions[ this.name ] = extensionDef;
3118
+
3119
+ extensionsUsed[ this.name ] = true;
3120
+
3121
+ }
3122
+
3123
+ }
3124
+
3125
+
3126
+ /**
3127
+ * Materials bump Extension
3128
+ *
3129
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
3130
+ */
3131
+ class GLTFMaterialsBumpExtension {
3132
+
3133
+ constructor( writer ) {
3134
+
3135
+ this.writer = writer;
3136
+ this.name = 'EXT_materials_bump';
3137
+
3138
+ }
3139
+
3140
+ async writeMaterialAsync( material, materialDef ) {
3141
+
3142
+ if ( ! material.isMeshStandardMaterial || (
3143
+ material.bumpScale === 1 &&
3144
+ ! material.bumpMap ) ) return;
3145
+
3146
+ const writer = this.writer;
3147
+ const extensionsUsed = writer.extensionsUsed;
3148
+
3149
+ const extensionDef = {};
3150
+
3151
+ if ( material.bumpMap ) {
3152
+
3153
+ const bumpMapDef = {
3154
+ index: await writer.processTextureAsync( material.bumpMap ),
3155
+ texCoord: material.bumpMap.channel
3156
+ };
3157
+ writer.applyTextureTransform( bumpMapDef, material.bumpMap );
3158
+ extensionDef.bumpTexture = bumpMapDef;
3159
+
3160
+ }
3161
+
3162
+ extensionDef.bumpFactor = material.bumpScale;
3163
+
3164
+ materialDef.extensions = materialDef.extensions || {};
3165
+ materialDef.extensions[ this.name ] = extensionDef;
3166
+
3167
+ extensionsUsed[ this.name ] = true;
3168
+
3169
+ }
3170
+
3171
+ }
3172
+
3173
+ /**
3174
+ * GPU Instancing Extension
3175
+ *
3176
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
3177
+ */
3178
+ class GLTFMeshGpuInstancing {
3179
+
3180
+ constructor( writer ) {
3181
+
3182
+ this.writer = writer;
3183
+ this.name = 'EXT_mesh_gpu_instancing';
3184
+
3185
+ }
3186
+
3187
+ writeNode( object, nodeDef ) {
3188
+
3189
+ if ( ! object.isInstancedMesh ) return;
3190
+
3191
+ const writer = this.writer;
3192
+
3193
+ const mesh = object;
3194
+
3195
+ const translationAttr = new Float32Array( mesh.count * 3 );
3196
+ const rotationAttr = new Float32Array( mesh.count * 4 );
3197
+ const scaleAttr = new Float32Array( mesh.count * 3 );
3198
+
3199
+ const matrix = new Matrix4();
3200
+ const position = new Vector3();
3201
+ const quaternion = new Quaternion();
3202
+ const scale = new Vector3();
3203
+
3204
+ for ( let i = 0; i < mesh.count; i ++ ) {
3205
+
3206
+ mesh.getMatrixAt( i, matrix );
3207
+ matrix.decompose( position, quaternion, scale );
3208
+
3209
+ position.toArray( translationAttr, i * 3 );
3210
+ quaternion.toArray( rotationAttr, i * 4 );
3211
+ scale.toArray( scaleAttr, i * 3 );
3212
+
3213
+ }
3214
+
3215
+ const attributes = {
3216
+ TRANSLATION: writer.processAccessor( new BufferAttribute( translationAttr, 3 ) ),
3217
+ ROTATION: writer.processAccessor( new BufferAttribute( rotationAttr, 4 ) ),
3218
+ SCALE: writer.processAccessor( new BufferAttribute( scaleAttr, 3 ) ),
3219
+ };
3220
+
3221
+ if ( mesh.instanceColor )
3222
+ attributes._COLOR_0 = writer.processAccessor( mesh.instanceColor );
3223
+
3224
+ nodeDef.extensions = nodeDef.extensions || {};
3225
+ nodeDef.extensions[ this.name ] = { attributes };
3226
+
3227
+ writer.extensionsUsed[ this.name ] = true;
3228
+ writer.extensionsRequired[ this.name ] = true;
3229
+
3230
+ }
3231
+
3232
+ }
3233
+
3234
+ /**
3235
+ * Static utility functions
3236
+ */
3237
+ GLTFExporter.Utils = {
3238
+
3239
+ insertKeyframe: function ( track, time ) {
3240
+
3241
+ const tolerance = 0.001; // 1ms
3242
+ const valueSize = track.getValueSize();
3243
+
3244
+ const times = new track.TimeBufferType( track.times.length + 1 );
3245
+ const values = new track.ValueBufferType( track.values.length + valueSize );
3246
+ const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
3247
+
3248
+ let index;
3249
+
3250
+ if ( track.times.length === 0 ) {
3251
+
3252
+ times[ 0 ] = time;
3253
+
3254
+ for ( let i = 0; i < valueSize; i ++ ) {
3255
+
3256
+ values[ i ] = 0;
3257
+
3258
+ }
3259
+
3260
+ index = 0;
3261
+
3262
+ } else if ( time < track.times[ 0 ] ) {
3263
+
3264
+ if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
3265
+
3266
+ times[ 0 ] = time;
3267
+ times.set( track.times, 1 );
3268
+
3269
+ values.set( interpolant.evaluate( time ), 0 );
3270
+ values.set( track.values, valueSize );
3271
+
3272
+ index = 0;
3273
+
3274
+ } else if ( time > track.times[ track.times.length - 1 ] ) {
3275
+
3276
+ if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
3277
+
3278
+ return track.times.length - 1;
3279
+
3280
+ }
3281
+
3282
+ times[ times.length - 1 ] = time;
3283
+ times.set( track.times, 0 );
3284
+
3285
+ values.set( track.values, 0 );
3286
+ values.set( interpolant.evaluate( time ), track.values.length );
3287
+
3288
+ index = times.length - 1;
3289
+
3290
+ } else {
3291
+
3292
+ for ( let i = 0; i < track.times.length; i ++ ) {
3293
+
3294
+ if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
3295
+
3296
+ if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
3297
+
3298
+ times.set( track.times.slice( 0, i + 1 ), 0 );
3299
+ times[ i + 1 ] = time;
3300
+ times.set( track.times.slice( i + 1 ), i + 2 );
3301
+
3302
+ values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
3303
+ values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
3304
+ values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
3305
+
3306
+ index = i + 1;
3307
+
3308
+ break;
3309
+
3310
+ }
3311
+
3312
+ }
3313
+
3314
+ }
3315
+
3316
+ track.times = times;
3317
+ track.values = values;
3318
+
3319
+ return index;
3320
+
3321
+ },
3322
+
3323
+ mergeMorphTargetTracks: function ( clip, root ) {
3324
+
3325
+ const tracks = [];
3326
+ const mergedTracks = {};
3327
+ const sourceTracks = clip.tracks;
3328
+
3329
+ for ( let i = 0; i < sourceTracks.length; ++ i ) {
3330
+
3331
+ let sourceTrack = sourceTracks[ i ];
3332
+ const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
3333
+ const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
3334
+
3335
+ if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
3336
+
3337
+ // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
3338
+ tracks.push( sourceTrack );
3339
+ continue;
3340
+
3341
+ }
3342
+
3343
+ if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
3344
+ && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
3345
+
3346
+ if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
3347
+
3348
+ // This should never happen, because glTF morph target animations
3349
+ // affect all targets already.
3350
+ throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
3351
+
3352
+ }
3353
+
3354
+ console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
3355
+
3356
+ sourceTrack = sourceTrack.clone();
3357
+ sourceTrack.setInterpolation( InterpolateLinear );
3358
+
3359
+ }
3360
+
3361
+ const targetCount = sourceTrackNode.morphTargetInfluences.length;
3362
+ const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
3363
+
3364
+ if ( targetIndex === undefined ) {
3365
+
3366
+ throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
3367
+
3368
+ }
3369
+
3370
+ let mergedTrack;
3371
+
3372
+ // If this is the first time we've seen this object, create a new
3373
+ // track to store merged keyframe data for each morph target.
3374
+ if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
3375
+
3376
+ mergedTrack = sourceTrack.clone();
3377
+
3378
+ const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
3379
+
3380
+ for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
3381
+
3382
+ values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
3383
+
3384
+ }
3385
+
3386
+ // We need to take into consideration the intended target node
3387
+ // of our original un-merged morphTarget animation.
3388
+ mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
3389
+ mergedTrack.values = values;
3390
+
3391
+ mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
3392
+ tracks.push( mergedTrack );
3393
+
3394
+ continue;
3395
+
3396
+ }
3397
+
3398
+ const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
3399
+
3400
+ mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
3401
+
3402
+ // For every existing keyframe of the merged track, write a (possibly
3403
+ // interpolated) value from the source track.
3404
+ for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
3405
+
3406
+ mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
3407
+
3408
+ }
3409
+
3410
+ // For every existing keyframe of the source track, write a (possibly
3411
+ // new) keyframe to the merged track. Values from the previous loop may
3412
+ // be written again, but keyframes are de-duplicated.
3413
+ for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
3414
+
3415
+ const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
3416
+ mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
3417
+
3418
+ }
3419
+
3420
+ }
3421
+
3422
+ clip.tracks = tracks;
3423
+
3424
+ return clip;
3425
+
3426
+ },
3427
+
3428
+ toFloat32BufferAttribute: function ( srcAttribute ) {
3429
+
3430
+ const dstAttribute = new BufferAttribute( new Float32Array( srcAttribute.count * srcAttribute.itemSize ), srcAttribute.itemSize, false );
3431
+
3432
+ if ( ! srcAttribute.normalized && ! srcAttribute.isInterleavedBufferAttribute ) {
3433
+
3434
+ dstAttribute.array.set( srcAttribute.array );
3435
+
3436
+ return dstAttribute;
3437
+
3438
+ }
3439
+
3440
+ for ( let i = 0, il = srcAttribute.count; i < il; i ++ ) {
3441
+
3442
+ for ( let j = 0; j < srcAttribute.itemSize; j ++ ) {
3443
+
3444
+ dstAttribute.setComponent( i, j, srcAttribute.getComponent( i, j ) );
3445
+
3446
+ }
3447
+
3448
+ }
3449
+
3450
+ return dstAttribute;
3451
+
3452
+ }
3453
+
3454
+ };
3455
+
3456
+ export { GLTFExporter };
web/vendor/three.module.js ADDED
The diff for this file is too large to render. See raw diff