@celljs/ta-3d 0.0.0-stage → 4.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md ADDED
@@ -0,0 +1,11 @@
1
+ # Cell - Ta 3D
2
+
3
+ A pi package that comes with Ta (on by default; Settings → Extensions of the web client turns it off): 3D view. When a reply shows something solid, Ta draws it as a 3D scene to turn.
4
+
5
+ - **Scenes**: under the Ta service, every turn's system prompt gets a `<ta-3d>` section: to show a 3D model, a structure, a layout, a molecule or an object of parts, Ta writes a `ta-3d` block (JSON): shapes (box, sphere, cylinder, cone, torus, plane, capsule), lines through points, arrows and groups, each with a position, rotation, scale, color, opacity, metal, roughness and label, spinning (`spin`) or bobbing (`bob`) if asked.
6
+ - **Models of the workspace**: `{"shape": "model", "src": "models/robot.glb"}` loads a glTF 2.0 model of the conversation's directory (a .glb, or a .gltf of embedded files), scaled to `size`, centered, its first animation playing; through a relay and on a phone too (`files.loadable`). One that does not load is told of in the card, without its URL.
7
+ - **Seeing it**: lit, with a shadow on the ground, the camera fit to it; it turns slowly until dragged; a pinch (of a trackpad too) zooms, a wheel still scrolls the conversation; it sleeps while out of sight (`ui.Game3D`).
8
+ - **Data only**: a block holds data: colors are CSS colors, models paths of the workspace (no web addresses), at most 400 objects nested 6 deep.
9
+ - **Elsewhere**: functions and surfaces z = f(x, y) are `ta-plot`'s; external agents (ta-agents) get the section too.
10
+
11
+ The format is in `web-src/scene-spec.ts`, the prompt in `web-src/scene-prompt.ts`.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta 3D
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ta 自带的 pi 包(默认开启,可在 Web 客户端的 设置 → 扩展 关闭):3D 展示。回复里要展示立体的东西时,Ta 直接画成可以转动的 3D 场景。
4
+
5
+ - **场景**:在 Ta 服务下,每一轮的系统提示里多一段 `<ta-3d>`:要展示 3D 模型、结构、布局、分子、由部件拼成的物体时,写一个 `ta-3d` 代码块(JSON):基本形状(方块、球、圆柱、圆锥、圆环、平面、胶囊)、穿过一组点的线、箭头、分组,各自有位置、旋转、缩放、颜色、透明度、金属感、粗糙度、标签,还能自转(`spin`)和上下浮动(`bob`)。
6
+ - **工作区的模型**:`{"shape": "model", "src": "models/robot.glb"}` 加载对话目录里的 glTF 2.0 模型(.glb,或内嵌资源的 .gltf),按 `size` 缩放、居中,播放第一段动画;经中继和手机也能加载(`files.loadable`)。加载不了时卡片说明原因,不显示文件地址。
7
+ - **看**:有灯光和地面阴影,相机自动对准内容;慢慢自转,拖动就转、停止自转;双指(触控板捏合)缩放,滚轮仍滚动对话;看不见时休眠(`ui.Game3D`)。
8
+ - **只读数据**:块里只有数据,颜色只认 CSS 颜色,模型只认工作区路径(不加载网址),物体最多 400 个、嵌套最多 6 层。
9
+ - **别处**:函数和曲面 z = f(x, y) 归 `ta-plot`;外部 Agent(ta-agents)也会拿到这段写法。
10
+
11
+ 格式见 `web-src/scene-spec.ts`,提示词见 `web-src/scene-prompt.ts`。
@@ -0,0 +1,120 @@
1
+ // ../ta-protocol/esm/common/ta-extension-host.js
2
+ var TA_HOST_EVENT = "ta:host";
3
+ var TaHostUtil;
4
+ (function(TaHostUtil2) {
5
+ TaHostUtil2.WAIT_MS = 1000;
6
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
7
+ return new Promise((resolve) => {
8
+ let heard = false;
9
+ let answered = false;
10
+ const timer = setTimeout(() => resolve(undefined), waitMs);
11
+ const request = {
12
+ name,
13
+ heard: () => {
14
+ heard = true;
15
+ },
16
+ resolve: (answer) => {
17
+ answered = true;
18
+ clearTimeout(timer);
19
+ resolve(answer);
20
+ }
21
+ };
22
+ events.emit(TA_HOST_EVENT, request);
23
+ if (!heard && !answered) {
24
+ clearTimeout(timer);
25
+ resolve(undefined);
26
+ }
27
+ });
28
+ }
29
+ TaHostUtil2.reach = reach;
30
+ function marked(systemPrompt, mark) {
31
+ return role(systemPrompt).includes(mark);
32
+ }
33
+ TaHostUtil2.marked = marked;
34
+ function role(systemPrompt) {
35
+ if (!systemPrompt) {
36
+ return "";
37
+ }
38
+ const open = `<addendum>
39
+ `;
40
+ const start = systemPrompt.indexOf(open);
41
+ const context = systemPrompt.indexOf(`<project_context>
42
+ `);
43
+ if (start < 0 || context >= 0 && context < start) {
44
+ return "";
45
+ }
46
+ const end = systemPrompt.indexOf(`
47
+ </addendum>`, start);
48
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
49
+ }
50
+ TaHostUtil2.role = role;
51
+ })(TaHostUtil || (TaHostUtil = {}));
52
+ var TA_ASK_ENTRY = "ta-ask";
53
+ var TaAskUtil;
54
+ (function(TaAskUtil2) {
55
+ const LENGTH = 120;
56
+ function entry(question) {
57
+ const line = question.replace(/\s+/g, " ").trim();
58
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
59
+ }
60
+ TaAskUtil2.entry = entry;
61
+ function asking(entries) {
62
+ var _a;
63
+ for (let i = entries.length - 1;i >= 0; i--) {
64
+ const entry2 = entries[i];
65
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
66
+ return;
67
+ }
68
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
69
+ return read(entry2);
70
+ }
71
+ }
72
+ return;
73
+ }
74
+ TaAskUtil2.asking = asking;
75
+ function next(asked, entry2) {
76
+ var _a;
77
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
78
+ return;
79
+ }
80
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
81
+ }
82
+ TaAskUtil2.next = next;
83
+ function read(found) {
84
+ var _a;
85
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
86
+ if (typeof question !== "string" || !question.trim()) {
87
+ return;
88
+ }
89
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
90
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
91
+ }
92
+ })(TaAskUtil || (TaAskUtil = {}));
93
+
94
+ // web-src/scene-protocol.ts
95
+ var NAME = "@celljs/ta-3d";
96
+ var LANGUAGE = "ta-3d";
97
+
98
+ // web-src/scene-prompt.ts
99
+ var SCENE_PROMPT = `To show the user something in 3D (a 3D model of the workspace, a structure, a layout, a molecule, an object made of shapes, how parts fit together), write a fenced block of language ${LANGUAGE} holding JSON rather than describing it; Ta draws it, lit, with a shadow, turning slowly; the user turns it by dragging. Functions and surfaces z = f(x, y) go in a ta-plot block instead.
100
+ {"title"?: string, "objects": [...], "camera"?: {"position": [x, y, z], "target"?: [x, y, z]}, "rotate"?: false, "ground"?: false, "background"?: color}
101
+ An object: {"shape": "box" | "sphere" | "cylinder" | "cone" | "torus" | "plane" | "capsule" | "line" | "arrow" | "model" | "group", "position"?: [x, y, z], "rotation"?: [degrees about x, y, z], "scale"?: number | [x, y, z], "color"?: CSS color, "opacity"?, "metal"?: 0..1, "rough"?: 0..1, "wireframe"?, "label"?: short text over it, "spin"?: [degrees a second about x, y, z], "bob"?: height it bobs, "children"?: [objects, placed relative to it]}.
102
+ Sizes: box and plane "size": [width, height, depth] (or a number); sphere "radius"; cylinder, cone, capsule "radius" and "height"; torus "radius" and "tube"; line "points" (through them) and arrow "points" (from the first to the last), with a thin "radius"?.
103
+ A model is {"shape": "model", "src": "path/in/the/workspace.glb", "size"?: its largest side, default 1}: glTF 2.0, a .glb or a .gltf with embedded files, centered at its position, its first animation playing; check the file exists first. Y is up; keep the scene within a few units of the origin; the camera fits it when not given. Labels and title in the user's language, short.`;
104
+
105
+ // web-src/extension.ts
106
+ function activate(pi) {
107
+ let served;
108
+ const underServe = () => served ??= TaHostUtil.reach(pi.events, NAME).then((answer) => answer !== undefined);
109
+ pi.on("session_start", () => {
110
+ underServe();
111
+ });
112
+ pi.on("before_agent_start", async (event) => {
113
+ if (await underServe()) {
114
+ event.systemPromptOptions.sections = { ...event.systemPromptOptions.sections, [LANGUAGE]: SCENE_PROMPT };
115
+ }
116
+ });
117
+ }
118
+ export {
119
+ activate as default
120
+ };
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@celljs/ta-3d",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.15.2",
4
+ "description": "A pi package for Ta: 3D scenes and models of replies, drawn by the 3D engine of the page and turned by dragging",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "homepage": "https://github.com/cellbang/ta",
9
+ "bugs": {
10
+ "url": "https://github.com/cellbang/ta/issues"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/cellbang/cell.git"
15
+ },
16
+ "license": "MIT",
17
+ "files": [
18
+ "web",
19
+ "extension",
20
+ "!**/*.map"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -b && bun build web-src/index.tsx --format esm --target browser --outfile web/index.js && bun build web-src/extension.ts --format esm --target node --outfile extension/index.mjs",
24
+ "clean": "rm -rf lib web extension *.tsbuildinfo",
25
+ "test": "bun test ./lib",
26
+ "watch": "tsc -b -w --preserveWatchOutput"
27
+ },
28
+ "devDependencies": {
29
+ "@celljs/ta-protocol": "4.15.2",
30
+ "@celljs/ta-web": "4.15.2",
31
+ "@types/react": "^19.3.0",
32
+ "@types/three": "^0.187.0"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "pi": {
38
+ "title": {
39
+ "en": "3D view",
40
+ "zh-CN": "3D 展示",
41
+ "zh-TW": "3D 展示",
42
+ "ja-JP": "3D ビュー"
43
+ },
44
+ "summary": {
45
+ "en": "Shows what Ta describes in 3D in the reply: a model of the workspace (glTF), or a scene of shapes (a structure, a layout, a molecule), turned by dragging.",
46
+ "zh-CN": "回复里直接用 3D 展示:工作区里的模型(glTF),或用基本形状搭出的场景(结构、布局、分子),拖动就能转着看。",
47
+ "zh-TW": "回覆裡直接用 3D 展示:工作區裡的模型(glTF),或用基本形狀搭出的場景(結構、佈局、分子),拖動就能轉著看。",
48
+ "ja-JP": "返信の中で 3D で見せます:ワークスペースのモデル(glTF)や、基本形状で組んだシーン(構造、レイアウト、分子)を、ドラッグで回して見られます。"
49
+ },
50
+ "icon": "Box",
51
+ "web": [
52
+ "./web/index.js"
53
+ ],
54
+ "extensions": [
55
+ "./extension/index.mjs"
56
+ ]
57
+ }
58
+ }
package/web/index.js ADDED
@@ -0,0 +1,660 @@
1
+ // web-src/react.ts
2
+ var React;
3
+ function bind(react) {
4
+ React = react;
5
+ }
6
+
7
+ // ../ta-protocol/esm/common/language.js
8
+ var TaLanguageUtil;
9
+ (function(TaLanguageUtil2) {
10
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
11
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
12
+ function of(tag) {
13
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
14
+ if (/^zh(\b|-)/.test(said)) {
15
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
16
+ }
17
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
18
+ }
19
+ TaLanguageUtil2.of = of;
20
+ function server(env = typeof process === "undefined" ? {} : process.env) {
21
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
22
+ }
23
+ TaLanguageUtil2.server = server;
24
+ function pick(language, words) {
25
+ return words[of(language)];
26
+ }
27
+ TaLanguageUtil2.pick = pick;
28
+ function say(words) {
29
+ return words[server()];
30
+ }
31
+ TaLanguageUtil2.say = say;
32
+ function chinese(language) {
33
+ return of(language).startsWith("zh");
34
+ }
35
+ TaLanguageUtil2.chinese = chinese;
36
+ function cjk(language) {
37
+ return of(language) !== "en-US";
38
+ }
39
+ TaLanguageUtil2.cjk = cjk;
40
+ function list(language, items) {
41
+ return items.join(cjk(language) ? "、" : ", ");
42
+ }
43
+ TaLanguageUtil2.list = list;
44
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
45
+
46
+ // web-src/i18n.ts
47
+ var EN = {
48
+ building: "Building the scene…",
49
+ failed: "This scene cannot be shown: {reason}",
50
+ model: "{path} did not load: {reason}",
51
+ missing: "no such file",
52
+ unreadable: "not a glTF model it can read",
53
+ hint: "Drag to turn · pinch to zoom"
54
+ };
55
+ var ZH = {
56
+ building: "正在搭建场景…",
57
+ failed: "这个场景显示不出来:{reason}",
58
+ model: "{path} 没能加载:{reason}",
59
+ missing: "文件不存在",
60
+ unreadable: "不是能读取的 glTF 模型",
61
+ hint: "拖动旋转 · 双指缩放"
62
+ };
63
+ var ZH_TW = {
64
+ building: "正在搭建場景…",
65
+ failed: "這個場景顯示不出來:{reason}",
66
+ model: "{path} 沒能載入:{reason}",
67
+ missing: "檔案不存在",
68
+ unreadable: "不是能讀取的 glTF 模型",
69
+ hint: "拖動旋轉 · 雙指縮放"
70
+ };
71
+ var JA = {
72
+ building: "シーンを組み立て中…",
73
+ failed: "このシーンは表示できません:{reason}",
74
+ model: "{path} を読み込めませんでした:{reason}",
75
+ missing: "ファイルがありません",
76
+ unreadable: "読み込める glTF モデルではありません",
77
+ hint: "ドラッグで回転 · ピンチで拡大縮小"
78
+ };
79
+ var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
80
+ var SceneWords;
81
+ ((SceneWords) => {
82
+ function of(language) {
83
+ return TaLanguageUtil.pick(language, WORDS);
84
+ }
85
+ SceneWords.of = of;
86
+ function format(text, values) {
87
+ return text.replace(/\{(\w+)\}/g, (all, name) => values[name] ?? all);
88
+ }
89
+ SceneWords.format = format;
90
+ })(SceneWords ||= {});
91
+
92
+ // web-src/scene-spec.ts
93
+ var SHAPES = ["box", "sphere", "cylinder", "cone", "torus", "plane", "capsule", "line", "arrow", "model", "group"];
94
+ var MAX_OBJECTS = 400;
95
+ var MAX_DEPTH = 6;
96
+ var MAX_POINTS = 500;
97
+ var SceneSpec;
98
+ ((SceneSpec) => {
99
+ function read(code) {
100
+ const spec = object(JSON.parse(code));
101
+ if (!spec) {
102
+ throw new Error("A scene is a JSON object");
103
+ }
104
+ const count = { objects: 0 };
105
+ const objects = things(spec.objects, 0, count);
106
+ if (!objects.length) {
107
+ throw new Error("A scene has no objects");
108
+ }
109
+ const camera = object(spec.camera);
110
+ const position = camera ? vec(camera.position) : undefined;
111
+ const models = [];
112
+ let moving = false;
113
+ walk(objects, (thing) => {
114
+ if (thing.src) {
115
+ models.push(thing.src);
116
+ moving = true;
117
+ }
118
+ moving ||= thing.bob > 0 || thing.spin.some(Boolean);
119
+ });
120
+ const rotate = spec.rotate !== false;
121
+ return {
122
+ title: text(spec.title),
123
+ background: color(spec.background),
124
+ camera: position ? { position, target: vec(camera?.target) ?? [0, 0, 0] } : undefined,
125
+ rotate,
126
+ ground: spec.ground !== false,
127
+ objects,
128
+ moving: moving || rotate,
129
+ models
130
+ };
131
+ }
132
+ SceneSpec.read = read;
133
+ function walk(objects, visit) {
134
+ for (const thing of objects) {
135
+ visit(thing);
136
+ walk(thing.children, visit);
137
+ }
138
+ }
139
+ SceneSpec.walk = walk;
140
+ })(SceneSpec ||= {});
141
+ function things(value, depth, count) {
142
+ if (!Array.isArray(value) || depth > MAX_DEPTH) {
143
+ return [];
144
+ }
145
+ const read = [];
146
+ for (const item of value) {
147
+ const spec = object(item);
148
+ if (!spec || count.objects >= MAX_OBJECTS) {
149
+ continue;
150
+ }
151
+ count.objects++;
152
+ read.push(thing(spec, depth, count));
153
+ }
154
+ return read;
155
+ }
156
+ function thing(spec, depth, count) {
157
+ const children = things(spec.children, depth + 1, count);
158
+ const src = path(spec.src ?? spec.model);
159
+ const named = SHAPES.find((shape2) => shape2 === spec.shape);
160
+ const shape = named ?? (src ? "model" : children.length ? "group" : "box");
161
+ if (shape === "model" && !src) {
162
+ throw new Error("A model has no src");
163
+ }
164
+ const points = (Array.isArray(spec.points) ? spec.points : []).slice(0, MAX_POINTS).map(vec).filter((point) => !!point);
165
+ if ((shape === "line" || shape === "arrow") && points.length < 2) {
166
+ throw new Error(`A ${shape} needs two points`);
167
+ }
168
+ const scale = typeof spec.scale === "number" && spec.scale > 0 ? [spec.scale, spec.scale, spec.scale] : vec(spec.scale) ?? [1, 1, 1];
169
+ return {
170
+ shape,
171
+ size: size(spec.size),
172
+ radius: positive(spec.radius, 0.5),
173
+ height: positive(spec.height, 1),
174
+ tube: positive(spec.tube, 0.15),
175
+ position: vec(spec.position) ?? [0, 0, 0],
176
+ rotation: vec(spec.rotation) ?? [0, 0, 0],
177
+ scale,
178
+ color: color(spec.color),
179
+ opacity: Number.isFinite(spec.opacity) ? Math.min(Math.max(spec.opacity, 0.05), 1) : 1,
180
+ metal: unit(spec.metal, 0.1),
181
+ rough: unit(spec.rough, 0.5),
182
+ wireframe: !!spec.wireframe,
183
+ label: text(spec.label),
184
+ points,
185
+ src: shape === "model" ? src : undefined,
186
+ spin: vec(spec.spin) ?? [0, 0, 0],
187
+ bob: Number.isFinite(spec.bob) ? Math.min(Math.max(spec.bob, 0), 100) : 0,
188
+ children
189
+ };
190
+ }
191
+ function object(value) {
192
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
193
+ }
194
+ function text(value) {
195
+ return typeof value === "string" && value ? value.slice(0, 80) : undefined;
196
+ }
197
+ function color(value) {
198
+ return typeof value === "string" && /^(#[0-9a-f]{3,8}|[a-z]{3,20}|(rgb|hsl)a?\([\d\s.,%]+\))$/i.test(value.trim()) ? value.trim() : undefined;
199
+ }
200
+ function path(value) {
201
+ return typeof value === "string" && value && value.length < 500 && !/^[a-z][\w+.-]*:/i.test(value) ? value : undefined;
202
+ }
203
+ function vec(value) {
204
+ if (Array.isArray(value) && value.length === 3 && value.every(Number.isFinite)) {
205
+ return [value[0], value[1], value[2]];
206
+ }
207
+ return;
208
+ }
209
+ function size(value) {
210
+ if (typeof value === "number" && value > 0) {
211
+ return [value, value, value];
212
+ }
213
+ const read = vec(value);
214
+ return read && read.every((part) => part > 0) ? read : [1, 1, 1];
215
+ }
216
+ function positive(value, fallback) {
217
+ return typeof value === "number" && value > 0 && Number.isFinite(value) ? value : fallback;
218
+ }
219
+ function unit(value, fallback) {
220
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(value, 0), 1) : fallback;
221
+ }
222
+
223
+ // web-src/scene-view.ts
224
+ var PALETTE = ["#4f8cff", "#ff7a59", "#2bb673", "#b36bff", "#f5b400", "#00b8d9", "#e8578f", "#8a94a6"];
225
+ var DEGREE = Math.PI / 180;
226
+
227
+ class SceneView {
228
+ context;
229
+ scene;
230
+ host;
231
+ THREE;
232
+ root;
233
+ controls;
234
+ sun;
235
+ ground;
236
+ moving = [];
237
+ mixers = [];
238
+ labels = [];
239
+ fitted = true;
240
+ disposed = false;
241
+ constructor(context, scene, host) {
242
+ this.context = context;
243
+ this.scene = scene;
244
+ this.host = host;
245
+ const THREE = context.THREE;
246
+ this.THREE = THREE;
247
+ const { renderer, element } = context;
248
+ renderer.shadowMap.enabled = true;
249
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
250
+ if (scene.background) {
251
+ context.scene.background = new THREE.Color(scene.background);
252
+ }
253
+ const camera = context.camera;
254
+ camera.fov = 40;
255
+ camera.near = 0.01;
256
+ camera.far = 1000;
257
+ camera.updateProjectionMatrix();
258
+ this.controls = new context.OrbitControls(camera, element);
259
+ this.controls.enableDamping = true;
260
+ this.controls.enableZoom = false;
261
+ this.controls.autoRotateSpeed = 0.8;
262
+ this.controls.addEventListener("start", () => {
263
+ this.controls.autoRotate = false;
264
+ this.fitted = false;
265
+ });
266
+ element.addEventListener("wheel", this.wheel, { passive: false });
267
+ context.scene.add(new THREE.HemisphereLight(16777215, 5595248, 1.7));
268
+ this.sun = new THREE.DirectionalLight(16777215, 1.8);
269
+ this.sun.castShadow = true;
270
+ this.sun.shadow.mapSize.set(1024, 1024);
271
+ this.sun.shadow.bias = -0.0005;
272
+ context.scene.add(this.sun, this.sun.target);
273
+ const fill = new THREE.DirectionalLight(16777215, 0.5);
274
+ fill.position.set(-3, 1, -2);
275
+ context.scene.add(fill);
276
+ this.ground = new THREE.Mesh(new THREE.CircleGeometry(1, 48), new THREE.ShadowMaterial({ opacity: 0.18 }));
277
+ this.ground.rotation.x = -Math.PI / 2;
278
+ this.ground.receiveShadow = true;
279
+ this.ground.visible = scene.ground;
280
+ context.scene.add(this.ground);
281
+ this.root = new THREE.Group;
282
+ context.scene.add(this.root);
283
+ scene.objects.forEach((thing2, index) => {
284
+ this.root.add(this.build(thing2, PALETTE[index % PALETTE.length]));
285
+ });
286
+ if (scene.camera) {
287
+ this.fitted = false;
288
+ camera.position.set(...scene.camera.position);
289
+ this.controls.target.set(...scene.camera.target);
290
+ }
291
+ this.fit();
292
+ this.page(context.page);
293
+ }
294
+ build(thing2, inherited) {
295
+ const { THREE } = this;
296
+ const color2 = thing2.color ?? inherited;
297
+ let object2;
298
+ if (thing2.shape === "group" || thing2.shape === "model") {
299
+ const group = new THREE.Group;
300
+ object2 = group;
301
+ thing2.children.forEach((child, index) => {
302
+ group.add(this.build(child, child.color ? color2 : thing2.color ? color2 : PALETTE[(PALETTE.indexOf(inherited) + index) % PALETTE.length]));
303
+ });
304
+ if (thing2.shape === "model" && thing2.src) {
305
+ this.load(thing2, group);
306
+ }
307
+ } else if (thing2.shape === "line" || thing2.shape === "arrow") {
308
+ object2 = this.path(thing2, color2);
309
+ } else {
310
+ object2 = new THREE.Mesh(this.geometry(thing2), this.material(thing2, color2));
311
+ object2.castShadow = true;
312
+ object2.receiveShadow = true;
313
+ thing2.children.forEach((child) => {
314
+ object2.add(this.build(child, child.color ?? color2));
315
+ });
316
+ }
317
+ object2.position.set(...thing2.position);
318
+ object2.rotation.set(thing2.rotation[0] * DEGREE, thing2.rotation[1] * DEGREE, thing2.rotation[2] * DEGREE);
319
+ object2.scale.set(...thing2.scale);
320
+ if (thing2.label) {
321
+ const label = SceneView.label(THREE, thing2.label);
322
+ label.position.set(0, this.top(thing2), 0);
323
+ object2.add(label);
324
+ this.labels.push(label);
325
+ }
326
+ if (thing2.bob || thing2.spin.some(Boolean)) {
327
+ this.moving.push({ object: object2, spin: thing2.spin, bob: thing2.bob, y: thing2.position[1], phase: this.moving.length * 0.7 });
328
+ }
329
+ return object2;
330
+ }
331
+ geometry(thing2) {
332
+ const { THREE } = this;
333
+ const [w, h, d] = thing2.size;
334
+ switch (thing2.shape) {
335
+ case "sphere":
336
+ return new THREE.SphereGeometry(thing2.radius, 48, 32);
337
+ case "cylinder":
338
+ return new THREE.CylinderGeometry(thing2.radius, thing2.radius, thing2.height, 48);
339
+ case "cone":
340
+ return new THREE.ConeGeometry(thing2.radius, thing2.height, 48);
341
+ case "torus":
342
+ return new THREE.TorusGeometry(thing2.radius, thing2.tube, 24, 96);
343
+ case "capsule":
344
+ return new THREE.CapsuleGeometry(thing2.radius, thing2.height, 12, 32);
345
+ case "plane":
346
+ return new THREE.PlaneGeometry(w, d === 1 && h !== 1 ? h : d);
347
+ default:
348
+ return new THREE.BoxGeometry(w, h, d);
349
+ }
350
+ }
351
+ material(thing2, color2) {
352
+ return new this.THREE.MeshStandardMaterial({
353
+ color: color2,
354
+ metalness: thing2.metal,
355
+ roughness: thing2.rough,
356
+ transparent: thing2.opacity < 1,
357
+ opacity: thing2.opacity,
358
+ wireframe: thing2.wireframe,
359
+ side: thing2.shape === "plane" ? this.THREE.DoubleSide : this.THREE.FrontSide
360
+ });
361
+ }
362
+ path(thing2, color2) {
363
+ const { THREE } = this;
364
+ const points = thing2.points.map((point) => new THREE.Vector3(...point));
365
+ const material = this.material(thing2, color2);
366
+ if (thing2.shape === "line") {
367
+ const path2 = new THREE.CurvePath;
368
+ for (let i = 1;i < points.length; i++) {
369
+ path2.add(new THREE.LineCurve3(points[i - 1], points[i]));
370
+ }
371
+ const mesh = new THREE.Mesh(new THREE.TubeGeometry(path2, Math.min(points.length * 4, 2000), Math.min(thing2.radius, 0.03), 8), material);
372
+ mesh.castShadow = true;
373
+ return mesh;
374
+ }
375
+ const from = points[0];
376
+ const to = points[points.length - 1];
377
+ const length = from.distanceTo(to) || 1;
378
+ const radius = Math.min(thing2.radius, length * 0.035);
379
+ const head = Math.min(length * 0.3, radius * 7);
380
+ const arrow = new THREE.Group;
381
+ const shaft = new THREE.Mesh(new THREE.CylinderGeometry(radius, radius, length - head, 16), material);
382
+ shaft.position.y = (length - head) / 2;
383
+ const tip = new THREE.Mesh(new THREE.ConeGeometry(radius * 2.6, head, 24), material);
384
+ tip.position.y = length - head / 2;
385
+ shaft.castShadow = tip.castShadow = true;
386
+ arrow.add(shaft, tip);
387
+ arrow.position.copy(from);
388
+ arrow.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), to.clone().sub(from).normalize());
389
+ const holder = new THREE.Group;
390
+ holder.add(arrow);
391
+ return holder;
392
+ }
393
+ top(thing2) {
394
+ switch (thing2.shape) {
395
+ case "sphere":
396
+ case "torus":
397
+ return thing2.radius + 0.18;
398
+ case "cylinder":
399
+ case "cone":
400
+ return thing2.height / 2 + 0.18;
401
+ case "capsule":
402
+ return thing2.height / 2 + thing2.radius + 0.18;
403
+ case "line":
404
+ case "arrow":
405
+ return Math.max(...thing2.points.map((point) => point[1])) + 0.18;
406
+ default:
407
+ return thing2.size[1] / 2 + 0.18;
408
+ }
409
+ }
410
+ async load(thing2, holder) {
411
+ const src = thing2.src;
412
+ try {
413
+ const url = await this.host.modelUrl(src);
414
+ const loader = new this.context.GLTFLoader;
415
+ const gltf = await loader.loadAsync(url);
416
+ if (this.disposed) {
417
+ return;
418
+ }
419
+ const model = gltf.scene;
420
+ model.updateMatrixWorld(true);
421
+ const box = new this.THREE.Box3().setFromObject(model, true);
422
+ const extent = box.getSize(new this.THREE.Vector3);
423
+ const largest = Math.max(extent.x, extent.y, extent.z) || 1;
424
+ model.scale.multiplyScalar(Math.max(...thing2.size) / largest);
425
+ model.updateMatrixWorld(true);
426
+ const center = new this.THREE.Box3().setFromObject(model, true).getCenter(new this.THREE.Vector3);
427
+ model.position.sub(center);
428
+ model.traverse((child) => {
429
+ if (child.isMesh) {
430
+ child.castShadow = true;
431
+ child.receiveShadow = true;
432
+ }
433
+ });
434
+ holder.add(model);
435
+ if (gltf.animations.length) {
436
+ const mixer = new this.THREE.AnimationMixer(model);
437
+ mixer.clipAction(gltf.animations[0]).play();
438
+ this.mixers.push(mixer);
439
+ }
440
+ this.fit();
441
+ } catch (error) {
442
+ this.host.failed(src, error);
443
+ }
444
+ }
445
+ fit() {
446
+ const { THREE } = this;
447
+ this.root.updateMatrixWorld(true);
448
+ const box = new THREE.Box3;
449
+ this.root.traverse((child) => {
450
+ if (child.isMesh) {
451
+ box.expandByObject(child, true);
452
+ }
453
+ });
454
+ if (box.isEmpty()) {
455
+ box.set(new THREE.Vector3(-1, -1, -1), new THREE.Vector3(1, 1, 1));
456
+ }
457
+ const sphere = box.getBoundingSphere(new THREE.Sphere);
458
+ const radius = Math.max(sphere.radius, 0.1);
459
+ this.ground.position.set(sphere.center.x, box.min.y - radius * 0.002, sphere.center.z);
460
+ this.ground.scale.setScalar(radius * 2.2);
461
+ this.sun.position.copy(sphere.center).add(new THREE.Vector3(radius * 1.2, radius * 2.5, radius * 1.6));
462
+ this.sun.target.position.copy(sphere.center);
463
+ const shadow = this.sun.shadow.camera;
464
+ Object.assign(shadow, { left: -radius * 1.6, right: radius * 1.6, top: radius * 1.6, bottom: -radius * 1.6, near: 0.01, far: radius * 8 });
465
+ shadow.updateProjectionMatrix();
466
+ this.controls.minDistance = radius * 0.6;
467
+ this.controls.maxDistance = radius * 12;
468
+ if (!this.fitted) {
469
+ return;
470
+ }
471
+ const camera = this.context.camera;
472
+ const distance = radius / Math.sin(camera.fov * DEGREE / 2) * 1.08;
473
+ this.controls.target.copy(sphere.center);
474
+ camera.position.copy(sphere.center).add(new THREE.Vector3(1, 0.65, 1.25).normalize().multiplyScalar(distance));
475
+ camera.near = distance / 100;
476
+ camera.far = distance * 20;
477
+ camera.updateProjectionMatrix();
478
+ }
479
+ update(seconds, elapsed) {
480
+ for (const { object: object2, spin, bob, y, phase } of this.moving) {
481
+ object2.rotation.x += spin[0] * DEGREE * seconds;
482
+ object2.rotation.y += spin[1] * DEGREE * seconds;
483
+ object2.rotation.z += spin[2] * DEGREE * seconds;
484
+ if (bob) {
485
+ object2.position.y = y + Math.sin(elapsed * 2 + phase) * bob;
486
+ }
487
+ }
488
+ for (const mixer of this.mixers) {
489
+ mixer.update(seconds);
490
+ }
491
+ this.controls.update();
492
+ }
493
+ page(page) {
494
+ this.controls.autoRotate = this.scene.rotate && !page.reduceMotion;
495
+ const color2 = `#${page.colors.text.toString(16).padStart(6, "0")}`;
496
+ for (const label of this.labels) {
497
+ const old = label.material.map;
498
+ label.material.map = SceneView.texture(this.THREE, String(label.userData.text), color2);
499
+ old?.dispose();
500
+ }
501
+ }
502
+ dispose() {
503
+ this.disposed = true;
504
+ this.context.element.removeEventListener("wheel", this.wheel);
505
+ this.controls.dispose();
506
+ }
507
+ wheel = (event) => {
508
+ if (!event.ctrlKey) {
509
+ return;
510
+ }
511
+ event.preventDefault();
512
+ const { camera } = this.context;
513
+ const target = this.controls.target;
514
+ const offset = camera.position.clone().sub(target);
515
+ const distance = Math.min(Math.max(offset.length() * Math.exp(event.deltaY * 0.01), this.controls.minDistance), this.controls.maxDistance);
516
+ camera.position.copy(target).add(offset.setLength(distance));
517
+ this.fitted = false;
518
+ };
519
+ static label(THREE, text2) {
520
+ const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: SceneView.texture(THREE, text2, "#888888"), depthTest: false, transparent: true }));
521
+ sprite.userData.text = text2;
522
+ const image = sprite.material.map?.image;
523
+ const height = 0.16;
524
+ sprite.scale.set(height * image.width / image.height, height, 1);
525
+ sprite.renderOrder = 10;
526
+ return sprite;
527
+ }
528
+ static texture(THREE, text2, color2) {
529
+ const canvas = document.createElement("canvas");
530
+ const context = canvas.getContext("2d");
531
+ const font = "600 40px system-ui, sans-serif";
532
+ if (context) {
533
+ context.font = font;
534
+ }
535
+ canvas.width = Math.ceil((context?.measureText(text2).width ?? 40) + 16);
536
+ canvas.height = 56;
537
+ if (context) {
538
+ context.font = font;
539
+ context.fillStyle = color2;
540
+ context.textBaseline = "middle";
541
+ context.fillText(text2, 8, 28);
542
+ }
543
+ const texture = new THREE.CanvasTexture(canvas);
544
+ texture.colorSpace = THREE.SRGBColorSpace;
545
+ return texture;
546
+ }
547
+ }
548
+
549
+ // web-src/scene-card.tsx
550
+ function sceneCard(pi) {
551
+ const Markdown = pi.ui.Markdown;
552
+ function View({ scene }) {
553
+ const words = SceneWords.of(pi.ui.language);
554
+ const cwd = pi.ui.useCwd();
555
+ const [failed, setFailed] = React.useState([]);
556
+ const host = React.useMemo(() => ({
557
+ modelUrl: async (src) => pi.files.loadable(await pi.workspace.fileUrl(src, cwd)),
558
+ failed: (src, error) => {
559
+ const reason = /\b404\b|not found|ENOENT/i.test(String(error?.message ?? error)) ? words.missing : words.unreadable;
560
+ setFailed((list) => [...list, SceneWords.format(words.model, { path: src, reason })]);
561
+ }
562
+ }), [cwd, words]);
563
+ const setup = React.useCallback((context) => new SceneView(context, scene, host), [scene, host]);
564
+ const Game3D = pi.ui.Game3D;
565
+ return /* @__PURE__ */ React.createElement("div", {
566
+ className: "t3d-card"
567
+ }, scene.title ? /* @__PURE__ */ React.createElement("div", {
568
+ className: "t3d-title"
569
+ }, scene.title) : null, /* @__PURE__ */ React.createElement("div", {
570
+ className: "t3d-view"
571
+ }, Game3D ? /* @__PURE__ */ React.createElement(Game3D, {
572
+ setup
573
+ }) : null), failed.map((text2) => /* @__PURE__ */ React.createElement("div", {
574
+ key: text2,
575
+ className: "t3d-failed"
576
+ }, text2)), /* @__PURE__ */ React.createElement("div", {
577
+ className: "t3d-hint"
578
+ }, words.hint));
579
+ }
580
+ return function SceneBlock({ code, closed }) {
581
+ const words = SceneWords.of(pi.ui.language);
582
+ const read = React.useMemo(() => {
583
+ if (!closed) {
584
+ return;
585
+ }
586
+ try {
587
+ return { scene: SceneSpec.read(code) };
588
+ } catch (error) {
589
+ return { error: error instanceof Error ? error.message : String(error) };
590
+ }
591
+ }, [code, closed]);
592
+ if (!read) {
593
+ return /* @__PURE__ */ React.createElement("div", {
594
+ className: "t3d-card t3d-writing"
595
+ }, /* @__PURE__ */ React.createElement("span", {
596
+ className: "ta-spinner"
597
+ }), /* @__PURE__ */ React.createElement("span", null, words.building));
598
+ }
599
+ if (!read.scene) {
600
+ return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", {
601
+ className: "t3d-failed"
602
+ }, SceneWords.format(words.failed, { reason: read.error ?? "" })), /* @__PURE__ */ React.createElement(Markdown, {
603
+ text: `\`\`\`json
604
+ ${code}
605
+ \`\`\``
606
+ }));
607
+ }
608
+ return /* @__PURE__ */ React.createElement(View, {
609
+ scene: read.scene
610
+ });
611
+ };
612
+ }
613
+
614
+ // web-src/scene-protocol.ts
615
+ var LANGUAGE = "ta-3d";
616
+
617
+ // web-src/style.ts
618
+ var STYLE = `
619
+ /* A scene of a reply (\`\`\`ta-3d): a title, the view, what did not load, a hint under it. */
620
+ .t3d-card {
621
+ margin: 2px 0 12px;
622
+ padding: 12px;
623
+ max-width: 560px;
624
+ border: 1px solid var(--ta-border);
625
+ border-radius: 12px;
626
+ background: var(--ta-card);
627
+ color: var(--ta-text);
628
+ font-size: calc(13px * var(--ta-font-scale, 1));
629
+ line-height: 1.5;
630
+ }
631
+ .t3d-title { font-weight: 600; margin-bottom: 8px; }
632
+ .t3d-view { position: relative; width: 100%; aspect-ratio: 4 / 3; border-radius: 8px; overflow: hidden; cursor: grab; touch-action: none; }
633
+ .t3d-view:active { cursor: grabbing; }
634
+ .t3d-view > * { position: absolute; inset: 0; }
635
+ .t3d-hint, .t3d-failed { margin-top: 6px; color: var(--ta-muted); font-size: calc(12px * var(--ta-font-scale, 1)); }
636
+ .t3d-writing { display: flex; align-items: center; gap: 8px; color: var(--ta-muted); }
637
+ `;
638
+ function injectStyle() {
639
+ const element = document.createElement("style");
640
+ element.dataset.taPackage = "ta-3d";
641
+ element.textContent = STYLE;
642
+ document.head.appendChild(element);
643
+ return () => element.remove();
644
+ }
645
+
646
+ // web-src/index.tsx
647
+ function activate(pi) {
648
+ bind(pi.React);
649
+ if (!pi.registerCodeRenderer || !pi.ui.Game3D) {
650
+ return () => {
651
+ return;
652
+ };
653
+ }
654
+ const removeStyle = injectStyle();
655
+ pi.registerCodeRenderer(LANGUAGE, sceneCard(pi));
656
+ return removeStyle;
657
+ }
658
+ export {
659
+ activate as default
660
+ };