@coda-console/resource-manager 0.9.2 → 0.9.4
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.md +1 -1
- package/lib/draft.mjs +22 -48
- package/lib/root.mjs +19 -47
- package/main.mjs +5 -1
- package/package.json +7 -5
- package/view/inspect3d.mjs +674 -0
- package/view/preview.mjs +8 -3
- package/view/style.css +17 -2
- package/view/viewer3d.mjs +69 -9
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
|
|
|
14
14
|
- **Mac 的键盘**:点一下目录树或图标视图让它拿到焦点(Tab 也能进来),↑ ↓ 移动选中(图标视图按行列走),列表里 → 展开、← 收起或选中所在的文件夹,图标视图里 ← → 选左右的条目;⌘↓ 同双击(打开、展开、进入);⌘↑ 在图标视图里回上一层,在预览里返回目录树或图标视图;⌘F 聚焦搜索框。搜索框里 ↓ 进结果,Esc 清空;结果里 Esc 回搜索框。不做多选、按字母跳转,Return 和空格也没绑定。读屏的 `aria-activedescendant` 没做(见 `docs/backlog.md`)。
|
|
15
15
|
- 文本预览(带行号,可跨行选中复制,最多读 1 MiB)。
|
|
16
16
|
- **图片、音频、视频预览**(`0.9.0`):经 Coda 开放的本机流式服务,边播边取,不分块传、没有大小上限,音视频可拖动进度。图片:PNG、JPEG、GIF、WebP、SVG、AVIF、HEIC、BMP、TIFF;音频:MP3、M4A、AAC、WAV、FLAC、OGG(Opus)、AIFF、CAF;视频:MP4、M4V、MOV、WebM。用系统自带的播放控件;元信息行写目录、大小,音视频加时长。能不能放取决于这台设备的浏览器内核(Mac 和 iPhone 不同),放不了的写「这台设备放不了这种格式」;MKV、AVI 播放器不支持,直接写「这种格式不能预览」,只给大小和修改时间。不缓存,每次都向模块要。刷新不打断播放:文件变了,元信息行写「文件已变化」,点头部「重载」才换。旧版本的 Coda 没有这个服务:图片退回分块读取(最多 8 MiB),音视频不预览。
|
|
17
|
-
- **3D 模型预览**(`0.9.1`):用 [three.js](https://threejs.org/) 在页面里画,字节同样经本机流式服务取。格式:glb、glTF(外部 `.bin` 和贴图按相对路径取)、STL(二进制和 ASCII)、OBJ(按 `mtllib` 找同目录的 `.mtl` 和贴图)、PLY(含顶点色和点云)、3MF。自动取景,单指转、双指缩放平移(Mac
|
|
17
|
+
- **3D 模型预览**(`0.9.1`,检视模式 `0.9.3`):用 [three.js](https://threejs.org/) 在页面里画,字节同样经本机流式服务取。格式:glb、glTF(外部 `.bin` 和贴图按相对路径取)、STL(二进制和 ASCII)、OBJ(按 `mtllib` 找同目录的 `.mtl` 和贴图)、PLY(含顶点色和点云)、3MF。自动取景,单指转、双指缩放平移(Mac 拖动和滚轮),「复位视角」回到取景的位置;带环境光,金属材质不发黑。头部提供「检视」选择(Mac 和 iPhone 都有,默认「材质」,切换不重新下载解析、不移动相机、支持蒙皮动画,换文件或关预览回到默认):形体(线框叠加、世界空间法线与背面翻面标记)、材质单通道(基色、粗糙度、金属度、自发光、环境遮蔽、透明度,无 PBR 的格式置灰)、UV 通道着色(按模型实际存在的 `uv`~`uv3` 列出,支持棋盘格、按实际范围归一化且区分正负色相的数值着色、沿 U 方向条纹,提供低/中/高三档密度并在元信息行追加通道名与 U/V 实际范围)。glb、glTF 有动画时自动循环播放第一段,有「播放/暂停」,多于一段时可选播哪一段;只在播放时连续渲染,切到后台、关预览、换文件都会停,系统开了「减弱动态效果」时不自动播放。元信息行写目录、大小、面数(点云写点数)和动画段数。glTF、OBJ、STL、PLY 内容是文本时,头部有「3D / 文本」切换,文本走普通的文本预览(二进制的没有切换)。超过 64 MiB 的模型先问「仍然加载」。用了 Draco、meshopt、KTX2 压缩的 glTF 不能预览;这台设备没有 WebGL 时写「这台设备不能显示 3D 模型」。文件变了不打断,元信息行写「文件已变化」,点头部「重载」才换。解析在主线程,很大的模型打开时页面会卡一下。
|
|
18
18
|
- 代码按语言上色:三十多种常见语言,只按文件名和扩展名认,不猜内容,深浅各一套配色;认不出的显示纯文本。超过 128 KiB 的文件不上色,说明区注明「不高亮」。用的是近似的语法规则,不是语法检查,个别文件会认错(如 `.h` 一律按 C++,`.m` 一律按 Objective-C),不保证完整支持。
|
|
19
19
|
- Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
|
|
20
20
|
- 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
|
package/lib/draft.mjs
CHANGED
|
@@ -1,57 +1,31 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// 把文字追加到会话的输入框草稿:经 coda/thread@1 的操作 append-draft。
|
|
2
|
+
// 宿主在同一事务里读草稿、按 line 插入分隔符并保存,保留现有附件、按 10 万字上限校验;
|
|
3
|
+
// 原样传 text,避免与宿主的分隔符叠加造成连续追加多出空格或空行。
|
|
4
4
|
import { DRAFT_LIMIT, ErrorCode, fail } from '../view/protocol.mjs';
|
|
5
5
|
|
|
6
|
-
const RETRIES = 2; // 版本不符后用服务端的内容重拼,最多再试这么多次
|
|
7
|
-
|
|
8
|
-
// block 为 false(路径、位置):接在现有文字后面,前后各留一个空格(已有空白或为空时前面不加)。
|
|
9
|
-
// block 为 true(内容):另起一行,结尾换行;文字本身已以换行结尾的不再多加,免得多出空行。只能追加到末尾。
|
|
10
|
-
export function compose(current, text, block) {
|
|
11
|
-
if (block) return `${current}${current === '' || current.endsWith('\n') ? '' : '\n'}${text}${text.endsWith('\n') ? '' : '\n'}`;
|
|
12
|
-
return `${current}${current === '' || /\s$/.test(current) ? '' : ' '}${text} `;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
// 接口路径只在这里写:测试和 harness 的假接口也从这里取。
|
|
16
|
-
export const draftPath = session => `threads/${encodeURIComponent(session)}/draft`;
|
|
17
|
-
// 反过来:路径是草稿接口的返回会话,不是返回 null。
|
|
18
|
-
export function draftSession(path) {
|
|
19
|
-
const match = /^threads\/([^/]+)\/draft$/.exec(path);
|
|
20
|
-
return match ? decodeURIComponent(match[1]) : null;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
6
|
const failed = () => fail(ErrorCode.DRAFT_FAILED, '读写草稿失败');
|
|
7
|
+
const tooLong = () => fail(ErrorCode.DRAFT_TOO_LONG, '草稿太长,放不下');
|
|
24
8
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
if (
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
return { text: draft.text, revision: draft.revision, ids };
|
|
9
|
+
function isTooLong(error) {
|
|
10
|
+
const code = typeof error?.code === 'string' ? error.code.toLowerCase() : '';
|
|
11
|
+
if (code === ErrorCode.DRAFT_TOO_LONG || code === ErrorCode.TOO_LARGE || code === 'too_long' || code === 'payload_too_large') return true;
|
|
12
|
+
const message = typeof error?.message === 'string' ? error.message : '';
|
|
13
|
+
return /too[_ ]?long|limit|上限|太长|过长|超出|超过/i.test(message);
|
|
31
14
|
}
|
|
32
15
|
|
|
33
|
-
// 追加成功返回 true;valid()
|
|
34
|
-
//
|
|
35
|
-
// 失败抛 draft_failed
|
|
36
|
-
export async function addText(coda, session, { text, block }, { valid = () => true } = {}) {
|
|
16
|
+
// 追加成功返回 true;valid() 变假或 signal 已中止(会话换了、视图关了)静默结束,返回 false:不写、不报。
|
|
17
|
+
// block 为 true(内容)时传 line: true,false(路径、位置)时传 line: false。
|
|
18
|
+
// 失败抛 draft_failed,拼完超过上限抛 draft_too_long,不截断。
|
|
19
|
+
export async function addText(coda, session, { text, block }, { valid = () => true, signal } = {}) {
|
|
37
20
|
if (typeof text !== 'string' || text.includes('\0') || typeof block !== 'boolean') throw failed();
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
for (let attempt = 0; ; attempt++) {
|
|
47
|
-
const next = compose(draft.text, text, block);
|
|
48
|
-
if (next.length > DRAFT_LIMIT) throw fail(ErrorCode.DRAFT_TOO_LONG, '草稿太长,放不下');
|
|
49
|
-
const saved = await call({ text: next, attachments: draft.ids, revision: draft.revision });
|
|
50
|
-
if (!valid()) return false;
|
|
51
|
-
const reply = parseDraft(saved?.draft); // 成功和版本不符的回答都带 draft;没有或形状不对,不能当成已写入
|
|
52
|
-
if (!saved.conflict) return true;
|
|
53
|
-
if (attempt >= RETRIES) throw failed();
|
|
54
|
-
draft = reply;
|
|
55
|
-
if (!valid()) return false;
|
|
21
|
+
if (text.length > DRAFT_LIMIT) throw tooLong();
|
|
22
|
+
if (!valid() || signal?.aborted) return false;
|
|
23
|
+
try {
|
|
24
|
+
await coda.call({ kind: 'coda/thread@1', id: session }, 'append-draft', { text, line: block }, signal ? { signal } : undefined);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (!valid() || signal?.aborted) return false;
|
|
27
|
+
if (isTooLong(error)) throw tooLong();
|
|
28
|
+
throw failed();
|
|
56
29
|
}
|
|
30
|
+
return valid() && !signal?.aborted;
|
|
57
31
|
}
|
package/lib/root.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 从会话取根目录:经 coda/thread@1 的只读查询 workspace 取 { path, project: { id, name }, state }。
|
|
2
2
|
import { realpath, stat } from 'node:fs/promises';
|
|
3
3
|
import { RootState } from '../view/protocol.mjs';
|
|
4
4
|
|
|
@@ -7,15 +7,10 @@ export const NO_ROOT = Object.freeze({ state: RootState.NONE, path: null, projec
|
|
|
7
7
|
// project 不是根目录的身份(保存、恢复、换根都只看路径),但变了页面要重画标题,所以算进来。
|
|
8
8
|
export const sameRoot = (a, b) => a?.state === b?.state && a?.path === b?.path && (a?.project ?? null) === (b?.project ?? null);
|
|
9
9
|
|
|
10
|
-
//
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
// 取不到(没有 id、接口失败、列表里没有这个 id、名字为空)都是 null,页面退回显示文件夹名;这里从不抛:
|
|
15
|
-
// queryRoot 抛出的意思是「保留上一次的根目录」,项目名取不到不该触发它。
|
|
16
|
-
// 项目列表按机器缓存(WeakMap:一个 coda 一份),很少变:超过 MAX_AGE 或查不到这个 id 时重取,两次请求之间至少隔 MISS_AGE(接口失败也算一次),不会反复请求;同时发起的查询共用一次请求。
|
|
17
|
-
const MAX_AGE = 60_000, MISS_AGE = 5_000, NAME_LIMIT = 256;
|
|
18
|
-
const caches = new WeakMap(); // coda → { names: Map(id → name) | null, at: 上次请求的时间, pending: 在途的请求 | null }
|
|
10
|
+
// Coda 的 worktree 目录以 UUID 命名,只看目录名认不出项目,所以给页面带上项目名;普通目录的目录名本身就能认出,project 留 null。
|
|
11
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
12
|
+
const NAME_LIMIT = 256;
|
|
13
|
+
const baseName = path => path.split('/').filter(Boolean).pop() ?? '';
|
|
19
14
|
|
|
20
15
|
// 名字:去掉首尾空白,空的、含控制字符的不用,太长的按码点截断。
|
|
21
16
|
function cleanName(name) {
|
|
@@ -25,47 +20,24 @@ function cleanName(name) {
|
|
|
25
20
|
return Array.from(text).slice(0, NAME_LIMIT).join('');
|
|
26
21
|
}
|
|
27
22
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
try {
|
|
31
|
-
const reply = await coda.api('agents');
|
|
32
|
-
const names = new Map();
|
|
33
|
-
for (const project of Array.isArray(reply?.projects) ? reply.projects : []) {
|
|
34
|
-
if (typeof project?.id === 'string' && project.id) names.set(project.id, cleanName(project.name));
|
|
35
|
-
}
|
|
36
|
-
cache.names = names;
|
|
37
|
-
} catch { /* 取不到:保留上一次的列表,名字退回文件夹名 */ }
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async function projectNameOf(coda, projectId, now) {
|
|
41
|
-
if (typeof projectId !== 'string' || !projectId) return null;
|
|
42
|
-
try {
|
|
43
|
-
let cache = caches.get(coda);
|
|
44
|
-
if (!cache) caches.set(coda, cache = { names: null, at: -Infinity, pending: null });
|
|
45
|
-
const age = now() - cache.at, stale = !cache.names || age >= MAX_AGE || (!cache.names.has(projectId) && age >= MISS_AGE);
|
|
46
|
-
if (stale) await (cache.pending ??= fetchNames(coda, cache, now).finally(() => { cache.pending = null; }));
|
|
47
|
-
else if (cache.pending) await cache.pending;
|
|
48
|
-
return cache.names?.get(projectId) ?? null;
|
|
49
|
-
} catch {
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// checkout.state 是 preparing、ready、failed。failed 没有可看的目录,按 none;
|
|
55
|
-
// ready 但目录已不在(归档后工作树被回收)是 gone。
|
|
23
|
+
// workspace.state 取 preparing、ready、failed、gone 之一,path 只在 ready 时有值。
|
|
24
|
+
// failed 没有可看的目录,按 none;ready 但目录已不在(归档后工作树被回收)按 gone。
|
|
56
25
|
// 查询失败(接口出错、读目录权限)直接抛出,由调用方保留上一次的结果。
|
|
57
|
-
export async function queryRoot(coda, session
|
|
26
|
+
export async function queryRoot(coda, session) {
|
|
58
27
|
if (!session) return NO_ROOT;
|
|
59
|
-
const detail = await coda.
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
if (
|
|
63
|
-
if (
|
|
28
|
+
const detail = await coda.query({ kind: 'coda/thread@1', id: session }, 'workspace', {});
|
|
29
|
+
if (!detail || typeof detail !== 'object') return NO_ROOT;
|
|
30
|
+
if (detail.state === 'preparing') return { state: RootState.PREPARING, path: null, project: null };
|
|
31
|
+
if (detail.state === 'gone') return { state: RootState.GONE, path: typeof detail.path === 'string' && detail.path ? detail.path : null, project: null };
|
|
32
|
+
if (detail.state !== 'ready' || typeof detail.path !== 'string' || !detail.path) return NO_ROOT;
|
|
64
33
|
try {
|
|
65
|
-
const real = await realpath(
|
|
66
|
-
if ((await stat(real)).isDirectory())
|
|
34
|
+
const real = await realpath(detail.path);
|
|
35
|
+
if ((await stat(real)).isDirectory()) {
|
|
36
|
+
const project = UUID.test(baseName(real)) ? cleanName(detail.project?.name) : null;
|
|
37
|
+
return { state: RootState.READY, path: real, project };
|
|
38
|
+
}
|
|
67
39
|
} catch (error) {
|
|
68
40
|
if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error;
|
|
69
41
|
}
|
|
70
|
-
return { state: RootState.GONE, path:
|
|
42
|
+
return { state: RootState.GONE, path: detail.path, project: null };
|
|
71
43
|
}
|
package/main.mjs
CHANGED
|
@@ -39,6 +39,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
|
|
|
39
39
|
const s = {
|
|
40
40
|
session: sessionOf(view.context), generation: 1, root: NO_ROOT, sent: null,
|
|
41
41
|
hello: false, closed: false, rootSeq: 0, poll: null,
|
|
42
|
+
abort: new AbortController(), // 绑定当前会话代次与视图生命周期,换会话或关闭时中止在途的草稿写入
|
|
42
43
|
listing: makeListing(), // 这个视图共用的并发上限和快照;视图关闭、换会话、根目录变化时丢弃
|
|
43
44
|
};
|
|
44
45
|
const turns = new Map();
|
|
@@ -102,6 +103,8 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
|
|
|
102
103
|
|
|
103
104
|
function switchSession(session) {
|
|
104
105
|
stopPoll();
|
|
106
|
+
s.abort.abort();
|
|
107
|
+
s.abort = new AbortController();
|
|
105
108
|
s.session = session ?? null;
|
|
106
109
|
s.generation++;
|
|
107
110
|
resetReads();
|
|
@@ -134,7 +137,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
|
|
|
134
137
|
},
|
|
135
138
|
async [Type.ADD_TEXT](message, { generation }) {
|
|
136
139
|
if (!s.session) throw fail(ErrorCode.NO_ROOT, '没有会话');
|
|
137
|
-
return await addText(coda, s.session, message, { valid: () => !stale(generation) }) ? {} : null;
|
|
140
|
+
return await addText(coda, s.session, message, { valid: () => !stale(generation), signal: s.abort.signal }) ? {} : null;
|
|
138
141
|
},
|
|
139
142
|
};
|
|
140
143
|
// 回答依赖根目录的:读完回来根目录换了,不能带旧根目录的内容。
|
|
@@ -206,6 +209,7 @@ function serve(coda, view, sessionOf, { makeListing, sizeLimits, searchLimits, m
|
|
|
206
209
|
|
|
207
210
|
view.onClose(async () => {
|
|
208
211
|
s.closed = true;
|
|
212
|
+
s.abort.abort();
|
|
209
213
|
resetReads();
|
|
210
214
|
stopPoll();
|
|
211
215
|
try { await (await watching)?.dispose(); } catch { /* 已经取消 */ }
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "@coda-console/resource-manager",
|
|
4
4
|
"displayName": "资源管理器",
|
|
5
5
|
"description": "会话旁的只读文件浏览器:浏览会话工作目录,预览文本、图片、音频、视频和 3D 模型,把路径交给对话。",
|
|
6
|
-
"version": "0.9.
|
|
6
|
+
"version": "0.9.4",
|
|
7
7
|
"categories": ["工作流程"],
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"repository": {
|
|
@@ -14,14 +14,16 @@
|
|
|
14
14
|
"files": ["main.mjs", "lib", "view"],
|
|
15
15
|
"scripts": {
|
|
16
16
|
"test": "node --test test/*.test.mjs",
|
|
17
|
-
"
|
|
17
|
+
"test:webgl": "node test/harness/inspect3d.mjs",
|
|
18
|
+
"check:coda": "npx --yes @coda-console/plugin-check@0.8.31 . --manifest"
|
|
18
19
|
},
|
|
20
|
+
"engines": { "coda": 3 },
|
|
19
21
|
"main": "main.mjs",
|
|
20
|
-
"uses": { "coda/thread@1": ["read"] },
|
|
22
|
+
"uses": { "coda/thread@1": ["read", "workspace", "append-draft"] },
|
|
21
23
|
"contributes": {
|
|
22
24
|
"views": [
|
|
23
|
-
{ "id": "files", "title": "资源管理器", "entry": "view/index.html", "in": ["side"], "icon": "folder" },
|
|
24
|
-
{ "id": "file", "title": "文件", "entry": "view/file.html" }
|
|
25
|
+
{ "id": "files", "title": "资源管理器", "entry": "view/index.html", "in": ["side"], "icon": "folder", "frame": "canvas" },
|
|
26
|
+
{ "id": "file", "title": "文件", "entry": "view/file.html", "frame": "canvas" }
|
|
25
27
|
]
|
|
26
28
|
}
|
|
27
29
|
}
|
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
// 3D 模型检视模式(不碰 DOM):线框与法线、材质单通道、UV 通道着色。
|
|
2
|
+
// 所有检视材质在切换模式或 dispose 时只释放自己,绝不释放原材质持有的贴图与几何体。
|
|
3
|
+
|
|
4
|
+
export const UV_CHANNELS = ['uv', 'uv1', 'uv2', 'uv3'];
|
|
5
|
+
|
|
6
|
+
export const PBR_CHANNELS = [
|
|
7
|
+
{ id: 'baseColor', label: '基色' },
|
|
8
|
+
{ id: 'roughness', label: '粗糙度' },
|
|
9
|
+
{ id: 'metalness', label: '金属度' },
|
|
10
|
+
{ id: 'emissive', label: '自发光' },
|
|
11
|
+
{ id: 'ao', label: '环境遮蔽' },
|
|
12
|
+
{ id: 'opacity', label: '透明度' },
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export const UV_MODES = [
|
|
16
|
+
{ id: 'checker', label: '棋盘格' },
|
|
17
|
+
{ id: 'value', label: '数值' },
|
|
18
|
+
{ id: 'stripes', label: '方向条纹' },
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
export const UV_DENSITIES = [
|
|
22
|
+
{ id: 'low', label: '低', value: 8 },
|
|
23
|
+
{ id: 'mid', label: '中', value: 16 },
|
|
24
|
+
{ id: 'high', label: '高', value: 32 },
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
const OVERLAY_FLAG = '__inspectOverlay';
|
|
28
|
+
const PBR_FORMATS = new Set(['glb', 'gltf']);
|
|
29
|
+
|
|
30
|
+
const fmtNum = n => {
|
|
31
|
+
if (!Number.isFinite(n)) return '0';
|
|
32
|
+
const clean = Math.abs(n) < 1e-6 ? 0 : Number(n.toFixed(3));
|
|
33
|
+
return Object.is(clean, -0) ? '0' : String(clean);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// UV 检视模式追加到元信息行的文本:通道名、U 和 V 的实际范围。
|
|
37
|
+
export const formatUvMeta = info => `${info.name} U[${fmtNum(info.minU)}, ${fmtNum(info.maxU)}] V[${fmtNum(info.minV)}, ${fmtNum(info.maxV)}]`;
|
|
38
|
+
|
|
39
|
+
// 扫描模型能力:是否有网格(线框)、是否有法线、是否有 PBR 材质、有哪些 UV 通道及各通道在全模型上的实际 min/max。
|
|
40
|
+
// 同时支持 Mesh 与 Points(如点云 PLY)。
|
|
41
|
+
export function analyzeModel(root, ext) {
|
|
42
|
+
let hasWireframe = false;
|
|
43
|
+
let hasNormal = false;
|
|
44
|
+
let hasPBR = false;
|
|
45
|
+
const stats = new Map();
|
|
46
|
+
const isPbrFormat = PBR_FORMATS.has(ext);
|
|
47
|
+
|
|
48
|
+
root.traverse(o => {
|
|
49
|
+
if ((!o.isMesh && !o.isPoints) || o.userData?.[OVERLAY_FLAG]) return;
|
|
50
|
+
if (o.isMesh) {
|
|
51
|
+
hasWireframe = true;
|
|
52
|
+
hasNormal = true;
|
|
53
|
+
if (isPbrFormat) {
|
|
54
|
+
for (const m of [o.material].flat()) {
|
|
55
|
+
if (m && !m.userData?.__neutral) { hasPBR = true; break; }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} else if (o.isPoints && o.geometry?.getAttribute?.('normal')) {
|
|
59
|
+
hasNormal = true;
|
|
60
|
+
}
|
|
61
|
+
const geometry = o.geometry;
|
|
62
|
+
if (!geometry?.getAttribute) return;
|
|
63
|
+
for (const name of UV_CHANNELS) {
|
|
64
|
+
const attr = geometry.getAttribute(name);
|
|
65
|
+
if (!attr || attr.count === 0) continue;
|
|
66
|
+
let entry = stats.get(name);
|
|
67
|
+
if (!entry) {
|
|
68
|
+
entry = { name, minU: Infinity, maxU: -Infinity, minV: Infinity, maxV: -Infinity, count: 0 };
|
|
69
|
+
stats.set(name, entry);
|
|
70
|
+
}
|
|
71
|
+
for (let i = 0; i < attr.count; i++) {
|
|
72
|
+
const u = attr.getX(i), v = attr.getY(i);
|
|
73
|
+
if (!Number.isFinite(u) || !Number.isFinite(v)) continue;
|
|
74
|
+
if (u < entry.minU) entry.minU = u;
|
|
75
|
+
if (u > entry.maxU) entry.maxU = u;
|
|
76
|
+
if (v < entry.minV) entry.minV = v;
|
|
77
|
+
if (v > entry.maxV) entry.maxV = v;
|
|
78
|
+
entry.count++;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const uvChannels = UV_CHANNELS
|
|
84
|
+
.map(name => stats.get(name))
|
|
85
|
+
.filter(entry => entry && entry.count > 0)
|
|
86
|
+
.map(({ name, minU, maxU, minV, maxV }) => ({ name, minU, maxU, minV, maxV }));
|
|
87
|
+
|
|
88
|
+
return { hasWireframe, hasNormal, hasPBR, uvChannels };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 顶点变换公共片段:支持静态网格、SkinnedMesh 蒙皮、MorphTarget 变形、InstancedMesh 实例化。
|
|
92
|
+
const SKINNED_VERTEX_HEAD = `
|
|
93
|
+
#include <common>
|
|
94
|
+
#include <morphtarget_pars_vertex>
|
|
95
|
+
#include <skinning_pars_vertex>
|
|
96
|
+
`;
|
|
97
|
+
|
|
98
|
+
const SKINNED_POSITION_BODY = `
|
|
99
|
+
#include <begin_vertex>
|
|
100
|
+
#include <morphtarget_vertex>
|
|
101
|
+
#include <skinning_vertex>
|
|
102
|
+
#include <project_vertex>
|
|
103
|
+
`;
|
|
104
|
+
|
|
105
|
+
const uvChannelName = tex => UV_CHANNELS[tex?.channel ?? 0] ?? 'uv';
|
|
106
|
+
const uvAttrDecl = name => (name === 'uv' ? '' : `attribute vec2 ${name};\n`);
|
|
107
|
+
|
|
108
|
+
// 世界空间法线检视材质:正面按 normal * 0.5 + 0.5 上色;背面用醒目洋红斜条纹标识翻面。
|
|
109
|
+
function makeNormalMaterial(THREE) {
|
|
110
|
+
return new THREE.ShaderMaterial({
|
|
111
|
+
side: THREE.DoubleSide,
|
|
112
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
113
|
+
varying vec3 vWorldNormal;
|
|
114
|
+
varying vec3 vWorldPos;
|
|
115
|
+
void main() {
|
|
116
|
+
#include <beginnormal_vertex>
|
|
117
|
+
#include <morphnormal_vertex>
|
|
118
|
+
#include <skinbase_vertex>
|
|
119
|
+
#include <skinnormal_vertex>
|
|
120
|
+
vec3 worldN = objectNormal;
|
|
121
|
+
#ifdef USE_INSTANCING
|
|
122
|
+
mat3 im = mat3(instanceMatrix);
|
|
123
|
+
worldN /= max(vec3(dot(im[0], im[0]), dot(im[1], im[1]), dot(im[2], im[2])), vec3(1e-12));
|
|
124
|
+
worldN = im * worldN;
|
|
125
|
+
#endif
|
|
126
|
+
mat3 mm = mat3(modelMatrix);
|
|
127
|
+
worldN /= max(vec3(dot(mm[0], mm[0]), dot(mm[1], mm[1]), dot(mm[2], mm[2])), vec3(1e-12));
|
|
128
|
+
vWorldNormal = mm * worldN;
|
|
129
|
+
${SKINNED_POSITION_BODY}
|
|
130
|
+
vec4 wp = vec4(transformed, 1.0);
|
|
131
|
+
#ifdef USE_INSTANCING
|
|
132
|
+
wp = instanceMatrix * wp;
|
|
133
|
+
#endif
|
|
134
|
+
vWorldPos = (modelMatrix * wp).xyz;
|
|
135
|
+
}`,
|
|
136
|
+
fragmentShader: `
|
|
137
|
+
varying vec3 vWorldNormal;
|
|
138
|
+
varying vec3 vWorldPos;
|
|
139
|
+
void main() {
|
|
140
|
+
if (!gl_FrontFacing) {
|
|
141
|
+
float stripe = step(0.5, fract((gl_FragCoord.x + gl_FragCoord.y) / 10.0));
|
|
142
|
+
vec3 backCol = mix(vec3(0.32, 0.03, 0.22), vec3(1.0, 0.12, 0.58), stripe);
|
|
143
|
+
gl_FragColor = vec4(backCol, 1.0);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
float len = length(vWorldNormal);
|
|
147
|
+
vec3 n = len > 1e-5 ? vWorldNormal / len : normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
|
|
148
|
+
gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);
|
|
149
|
+
}`,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// 材质单通道(平涂无光照):根据通道和原材质构造 ShaderMaterial,支持贴图 UV 通道与纹理变换、顶点色和蒙皮。
|
|
154
|
+
function makePbrChannelMaterial(THREE, channel, origMat, geometry) {
|
|
155
|
+
const side = origMat?.side ?? THREE.FrontSide;
|
|
156
|
+
const hasGeoUv = name => Boolean(geometry?.getAttribute?.(name));
|
|
157
|
+
const useTex = tex => {
|
|
158
|
+
if (!tex?.isTexture) return null;
|
|
159
|
+
const ch = uvChannelName(tex);
|
|
160
|
+
if (!hasGeoUv(ch)) return null;
|
|
161
|
+
tex.updateMatrix?.();
|
|
162
|
+
return { tex, ch, matrix: tex.matrix.clone() };
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
if (channel === 'baseColor') {
|
|
166
|
+
const t = useTex(origMat?.map);
|
|
167
|
+
const useVC = Boolean(origMat?.vertexColors && geometry?.getAttribute?.('color'));
|
|
168
|
+
const color = origMat?.color ? origMat.color.clone() : new THREE.Color(1, 1, 1);
|
|
169
|
+
return new THREE.ShaderMaterial({
|
|
170
|
+
side,
|
|
171
|
+
vertexColors: useVC,
|
|
172
|
+
uniforms: {
|
|
173
|
+
uColor: { value: color },
|
|
174
|
+
uHasMap: { value: t ? 1 : 0 },
|
|
175
|
+
uMap: { value: t?.tex ?? null },
|
|
176
|
+
uMapMatrix: { value: t?.matrix ?? new THREE.Matrix3() },
|
|
177
|
+
},
|
|
178
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
179
|
+
#include <color_pars_vertex>
|
|
180
|
+
${t ? uvAttrDecl(t.ch) : ''}
|
|
181
|
+
uniform mat3 uMapMatrix;
|
|
182
|
+
varying vec2 vTexUv;
|
|
183
|
+
void main() {
|
|
184
|
+
#include <color_vertex>
|
|
185
|
+
${t ? `vTexUv = (uMapMatrix * vec3(${t.ch}, 1.0)).xy;` : 'vTexUv = vec2(0.0);'}
|
|
186
|
+
#include <skinbase_vertex>
|
|
187
|
+
${SKINNED_POSITION_BODY}
|
|
188
|
+
}`,
|
|
189
|
+
fragmentShader: `
|
|
190
|
+
#include <color_pars_fragment>
|
|
191
|
+
uniform vec3 uColor;
|
|
192
|
+
uniform int uHasMap;
|
|
193
|
+
uniform sampler2D uMap;
|
|
194
|
+
varying vec2 vTexUv;
|
|
195
|
+
void main() {
|
|
196
|
+
vec3 col = uColor;
|
|
197
|
+
if (uHasMap == 1) col *= texture2D(uMap, vTexUv).rgb;
|
|
198
|
+
#if defined(USE_COLOR) || defined(USE_COLOR_ALPHA)
|
|
199
|
+
col *= vColor.rgb;
|
|
200
|
+
#endif
|
|
201
|
+
gl_FragColor = vec4(col, 1.0);
|
|
202
|
+
#include <colorspace_fragment>
|
|
203
|
+
}`,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (channel === 'emissive') {
|
|
208
|
+
const t = useTex(origMat?.emissiveMap);
|
|
209
|
+
const emissive = origMat?.emissive ? origMat.emissive.clone() : new THREE.Color(0, 0, 0);
|
|
210
|
+
const intensity = origMat?.emissiveIntensity ?? 1.0;
|
|
211
|
+
emissive.multiplyScalar(intensity);
|
|
212
|
+
return new THREE.ShaderMaterial({
|
|
213
|
+
side,
|
|
214
|
+
uniforms: {
|
|
215
|
+
uEmissive: { value: emissive },
|
|
216
|
+
uHasMap: { value: t ? 1 : 0 },
|
|
217
|
+
uMap: { value: t?.tex ?? null },
|
|
218
|
+
uMapMatrix: { value: t?.matrix ?? new THREE.Matrix3() },
|
|
219
|
+
},
|
|
220
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
221
|
+
${t ? uvAttrDecl(t.ch) : ''}
|
|
222
|
+
uniform mat3 uMapMatrix;
|
|
223
|
+
varying vec2 vTexUv;
|
|
224
|
+
void main() {
|
|
225
|
+
${t ? `vTexUv = (uMapMatrix * vec3(${t.ch}, 1.0)).xy;` : 'vTexUv = vec2(0.0);'}
|
|
226
|
+
#include <skinbase_vertex>
|
|
227
|
+
${SKINNED_POSITION_BODY}
|
|
228
|
+
}`,
|
|
229
|
+
fragmentShader: `
|
|
230
|
+
uniform vec3 uEmissive;
|
|
231
|
+
uniform int uHasMap;
|
|
232
|
+
uniform sampler2D uMap;
|
|
233
|
+
varying vec2 vTexUv;
|
|
234
|
+
void main() {
|
|
235
|
+
vec3 col = uEmissive;
|
|
236
|
+
if (uHasMap == 1) col *= texture2D(uMap, vTexUv).rgb;
|
|
237
|
+
gl_FragColor = vec4(col, 1.0);
|
|
238
|
+
#include <colorspace_fragment>
|
|
239
|
+
}`,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
if (channel === 'opacity') {
|
|
244
|
+
const baseT = useTex(origMat?.map);
|
|
245
|
+
const alphaT = useTex(origMat?.alphaMap);
|
|
246
|
+
const opacity = origMat?.opacity ?? 1.0;
|
|
247
|
+
const decls = new Set();
|
|
248
|
+
if (baseT && baseT.ch !== 'uv') decls.add(`attribute vec2 ${baseT.ch};`);
|
|
249
|
+
if (alphaT && alphaT.ch !== 'uv') decls.add(`attribute vec2 ${alphaT.ch};`);
|
|
250
|
+
return new THREE.ShaderMaterial({
|
|
251
|
+
side,
|
|
252
|
+
uniforms: {
|
|
253
|
+
uOpacity: { value: opacity },
|
|
254
|
+
uHasBase: { value: baseT ? 1 : 0 },
|
|
255
|
+
uBaseMap: { value: baseT?.tex ?? null },
|
|
256
|
+
uBaseMatrix: { value: baseT?.matrix ?? new THREE.Matrix3() },
|
|
257
|
+
uHasAlpha: { value: alphaT ? 1 : 0 },
|
|
258
|
+
uAlphaMap: { value: alphaT?.tex ?? null },
|
|
259
|
+
uAlphaMatrix: { value: alphaT?.matrix ?? new THREE.Matrix3() },
|
|
260
|
+
},
|
|
261
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
262
|
+
${[...decls].join('\n')}
|
|
263
|
+
uniform mat3 uBaseMatrix;
|
|
264
|
+
uniform mat3 uAlphaMatrix;
|
|
265
|
+
varying vec2 vBaseUv;
|
|
266
|
+
varying vec2 vAlphaUv;
|
|
267
|
+
void main() {
|
|
268
|
+
${baseT ? `vBaseUv = (uBaseMatrix * vec3(${baseT.ch}, 1.0)).xy;` : 'vBaseUv = vec2(0.0);'}
|
|
269
|
+
${alphaT ? `vAlphaUv = (uAlphaMatrix * vec3(${alphaT.ch}, 1.0)).xy;` : 'vAlphaUv = vec2(0.0);'}
|
|
270
|
+
#include <skinbase_vertex>
|
|
271
|
+
${SKINNED_POSITION_BODY}
|
|
272
|
+
}`,
|
|
273
|
+
fragmentShader: `
|
|
274
|
+
uniform float uOpacity;
|
|
275
|
+
uniform int uHasBase;
|
|
276
|
+
uniform sampler2D uBaseMap;
|
|
277
|
+
uniform int uHasAlpha;
|
|
278
|
+
uniform sampler2D uAlphaMap;
|
|
279
|
+
varying vec2 vBaseUv;
|
|
280
|
+
varying vec2 vAlphaUv;
|
|
281
|
+
void main() {
|
|
282
|
+
float a = uOpacity;
|
|
283
|
+
if (uHasBase == 1) a *= texture2D(uBaseMap, vBaseUv).a;
|
|
284
|
+
if (uHasAlpha == 1) a *= texture2D(uAlphaMap, vAlphaUv).g;
|
|
285
|
+
float v = clamp(a, 0.0, 1.0);
|
|
286
|
+
gl_FragColor = vec4(vec3(v), 1.0);
|
|
287
|
+
}`,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// roughness (.g), metalness (.b), ao (.r) 都是单标量 + 单贴图灰度通道。
|
|
292
|
+
const spec = channel === 'roughness'
|
|
293
|
+
? { scalar: origMat?.roughness ?? 1.0, tex: origMat?.roughnessMap, swizzle: 'g', isAo: false }
|
|
294
|
+
: channel === 'metalness'
|
|
295
|
+
? { scalar: origMat?.metalness ?? 0.0, tex: origMat?.metalnessMap, swizzle: 'b', isAo: false }
|
|
296
|
+
: { scalar: origMat?.aoMapIntensity ?? 1.0, tex: origMat?.aoMap, swizzle: 'r', isAo: true };
|
|
297
|
+
const t = useTex(spec.tex);
|
|
298
|
+
return new THREE.ShaderMaterial({
|
|
299
|
+
side,
|
|
300
|
+
uniforms: {
|
|
301
|
+
uScalar: { value: spec.scalar },
|
|
302
|
+
uHasMap: { value: t ? 1 : 0 },
|
|
303
|
+
uMap: { value: t?.tex ?? null },
|
|
304
|
+
uMapMatrix: { value: t?.matrix ?? new THREE.Matrix3() },
|
|
305
|
+
},
|
|
306
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
307
|
+
${t ? uvAttrDecl(t.ch) : ''}
|
|
308
|
+
uniform mat3 uMapMatrix;
|
|
309
|
+
varying vec2 vTexUv;
|
|
310
|
+
void main() {
|
|
311
|
+
${t ? `vTexUv = (uMapMatrix * vec3(${t.ch}, 1.0)).xy;` : 'vTexUv = vec2(0.0);'}
|
|
312
|
+
#include <skinbase_vertex>
|
|
313
|
+
${SKINNED_POSITION_BODY}
|
|
314
|
+
}`,
|
|
315
|
+
fragmentShader: `
|
|
316
|
+
uniform float uScalar;
|
|
317
|
+
uniform int uHasMap;
|
|
318
|
+
uniform sampler2D uMap;
|
|
319
|
+
varying vec2 vTexUv;
|
|
320
|
+
void main() {
|
|
321
|
+
float v = ${spec.isAo ? 'uHasMap == 1 ? mix(1.0, texture2D(uMap, vTexUv).r, uScalar) : 1.0' : `uScalar * (uHasMap == 1 ? texture2D(uMap, vTexUv).${spec.swizzle} : 1.0)`};
|
|
322
|
+
v = clamp(v, 0.0, 1.0);
|
|
323
|
+
gl_FragColor = vec4(vec3(v), 1.0);
|
|
324
|
+
}`,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// UV 通道着色材质:支持棋盘格(0)、数值(1,按模型 min/max 归一化且负值区分色相)、方向条纹(2,沿 U 方向)。
|
|
329
|
+
function makeUvMaterial(THREE, channelInfo, uvMode, density) {
|
|
330
|
+
const modeIndex = uvMode === 'value' ? 1 : uvMode === 'stripes' ? 2 : 0;
|
|
331
|
+
return new THREE.ShaderMaterial({
|
|
332
|
+
side: THREE.DoubleSide,
|
|
333
|
+
uniforms: {
|
|
334
|
+
uMode: { value: modeIndex },
|
|
335
|
+
uDensity: { value: density },
|
|
336
|
+
uMin: { value: new THREE.Vector2(channelInfo.minU, channelInfo.minV) },
|
|
337
|
+
uMax: { value: new THREE.Vector2(channelInfo.maxU, channelInfo.maxV) },
|
|
338
|
+
},
|
|
339
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
340
|
+
${uvAttrDecl(channelInfo.name)}
|
|
341
|
+
varying vec2 vUvVal;
|
|
342
|
+
void main() {
|
|
343
|
+
vUvVal = ${channelInfo.name};
|
|
344
|
+
#include <skinbase_vertex>
|
|
345
|
+
${SKINNED_POSITION_BODY}
|
|
346
|
+
}`,
|
|
347
|
+
fragmentShader: `
|
|
348
|
+
uniform int uMode;
|
|
349
|
+
uniform float uDensity;
|
|
350
|
+
uniform vec2 uMin;
|
|
351
|
+
uniform vec2 uMax;
|
|
352
|
+
varying vec2 vUvVal;
|
|
353
|
+
void main() {
|
|
354
|
+
if (uMode == 0) {
|
|
355
|
+
vec2 cell = floor(vUvVal * uDensity);
|
|
356
|
+
float parity = mod(cell.x + cell.y, 2.0);
|
|
357
|
+
vec3 col = mix(vec3(0.22, 0.24, 0.28), vec3(0.86, 0.88, 0.90), parity);
|
|
358
|
+
gl_FragColor = vec4(col, 1.0);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (uMode == 1) {
|
|
362
|
+
vec2 span = max(uMax - uMin, vec2(1e-6));
|
|
363
|
+
vec2 norm = clamp((vUvVal - uMin) / span, 0.0, 1.0);
|
|
364
|
+
vec3 col;
|
|
365
|
+
if (vUvVal.x < 0.0 && vUvVal.y < 0.0) {
|
|
366
|
+
col = vec3(0.14, 0.52 + 0.38 * norm.y, 0.72 + 0.28 * norm.x);
|
|
367
|
+
} else if (vUvVal.x < 0.0) {
|
|
368
|
+
col = vec3(0.12, 0.26 + 0.54 * norm.y, 0.65 + 0.35 * norm.x);
|
|
369
|
+
} else if (vUvVal.y < 0.0) {
|
|
370
|
+
col = vec3(0.55 + 0.45 * norm.x, 0.14, 0.65 + 0.35 * norm.y);
|
|
371
|
+
} else {
|
|
372
|
+
col = vec3(norm.x, norm.y, 0.12);
|
|
373
|
+
}
|
|
374
|
+
gl_FragColor = vec4(col, 1.0);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
float fv = fract(vUvVal.y * uDensity);
|
|
378
|
+
float fw = max(fwidth(vUvVal.y * uDensity), 0.01);
|
|
379
|
+
float line = 1.0 - smoothstep(0.08 - fw, 0.08 + fw, min(fv, 1.0 - fv));
|
|
380
|
+
vec3 col = mix(vec3(0.18, 0.22, 0.28), vec3(0.95, 0.78, 0.22), line);
|
|
381
|
+
gl_FragColor = vec4(col, 1.0);
|
|
382
|
+
}`,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// 线框叠加材质:与原网格同走 GL_TRIANGLES 光栅化,按重心坐标 + fwidth 绘制屏幕空间 1px 抗锯齿边线,
|
|
387
|
+
// 配合 LessEqualDepth、零深度偏移:共面片元深度与原面逐 bit 一致(倾斜共面连续不断线),
|
|
388
|
+
// 且保留原面未偏移的遮挡深度,同一模型内近贴合的双层斜面也绝不穿透前景。
|
|
389
|
+
function makeWireframeMaterial(THREE, side) {
|
|
390
|
+
return new THREE.ShaderMaterial({
|
|
391
|
+
side,
|
|
392
|
+
transparent: true,
|
|
393
|
+
depthTest: true,
|
|
394
|
+
depthWrite: false,
|
|
395
|
+
depthFunc: THREE.LessEqualDepth,
|
|
396
|
+
uniforms: {
|
|
397
|
+
uColor: { value: new THREE.Color(0x111827) },
|
|
398
|
+
uOpacity: { value: 0.6 },
|
|
399
|
+
},
|
|
400
|
+
vertexShader: `${SKINNED_VERTEX_HEAD}
|
|
401
|
+
attribute vec3 aBary;
|
|
402
|
+
varying vec3 vBary;
|
|
403
|
+
void main() {
|
|
404
|
+
vBary = aBary;
|
|
405
|
+
#include <skinbase_vertex>
|
|
406
|
+
${SKINNED_POSITION_BODY}
|
|
407
|
+
}`,
|
|
408
|
+
fragmentShader: `
|
|
409
|
+
uniform vec3 uColor;
|
|
410
|
+
uniform float uOpacity;
|
|
411
|
+
varying vec3 vBary;
|
|
412
|
+
void main() {
|
|
413
|
+
vec3 d = fwidth(vBary);
|
|
414
|
+
vec3 a3 = smoothstep(vec3(0.0), d * 1.25, vBary);
|
|
415
|
+
float edge = 1.0 - min(min(a3.x, a3.y), a3.z);
|
|
416
|
+
if (edge < 0.05) discard;
|
|
417
|
+
gl_FragColor = vec4(uColor, uOpacity * edge);
|
|
418
|
+
}`,
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// 构造带重心坐标 aBary 的非索引几何体副本(不改动原 geometry,退出线框或 dispose 时由检视器释放)。
|
|
423
|
+
function makeBarycentricGeometry(THREE, geometry) {
|
|
424
|
+
const wireGeo = geometry.index ? geometry.toNonIndexed() : geometry.clone();
|
|
425
|
+
const count = wireGeo.attributes.position?.count ?? 0;
|
|
426
|
+
const bary = new Float32Array(count * 3);
|
|
427
|
+
for (let i = 0; i < count; i++) {
|
|
428
|
+
const corner = i % 3;
|
|
429
|
+
bary[i * 3 + corner] = 1;
|
|
430
|
+
}
|
|
431
|
+
wireGeo.setAttribute('aBary', new THREE.BufferAttribute(bary, 3));
|
|
432
|
+
return wireGeo;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// 为一个网格创建与原网格同步变形的线框叠加对象(共享 skeleton / morph / instanceMatrix,使用独立重心几何体)。
|
|
436
|
+
function makeWireOverlay(THREE, mesh, wireGeo, wireMat) {
|
|
437
|
+
let overlay;
|
|
438
|
+
if (mesh.isSkinnedMesh) {
|
|
439
|
+
overlay = new THREE.SkinnedMesh(wireGeo, wireMat);
|
|
440
|
+
overlay.bindMode = mesh.bindMode;
|
|
441
|
+
overlay.bind(mesh.skeleton, mesh.bindMatrix);
|
|
442
|
+
} else if (mesh.isInstancedMesh) {
|
|
443
|
+
overlay = new THREE.InstancedMesh(wireGeo, wireMat, mesh.count);
|
|
444
|
+
overlay.instanceMatrix = mesh.instanceMatrix;
|
|
445
|
+
} else {
|
|
446
|
+
overlay = new THREE.Mesh(wireGeo, wireMat);
|
|
447
|
+
}
|
|
448
|
+
if (mesh.morphTargetInfluences) {
|
|
449
|
+
overlay.morphTargetInfluences = mesh.morphTargetInfluences;
|
|
450
|
+
overlay.morphTargetDictionary = mesh.morphTargetDictionary;
|
|
451
|
+
}
|
|
452
|
+
overlay.raycast = () => {};
|
|
453
|
+
overlay.renderOrder = (mesh.renderOrder ?? 0) + 1;
|
|
454
|
+
overlay.userData = { [OVERLAY_FLAG]: true };
|
|
455
|
+
return overlay;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// 点云法线检视材质(Points):按世界空间点法线 normal * 0.5 + 0.5 上色。
|
|
459
|
+
function makePointsNormalMaterial(THREE, pointSize = 2) {
|
|
460
|
+
return new THREE.ShaderMaterial({
|
|
461
|
+
uniforms: { uPointSize: { value: Math.max(2, pointSize) } },
|
|
462
|
+
vertexShader: `
|
|
463
|
+
uniform float uPointSize;
|
|
464
|
+
varying vec3 vWorldNormal;
|
|
465
|
+
void main() {
|
|
466
|
+
mat3 mm = mat3(modelMatrix);
|
|
467
|
+
vec3 worldN = normal / max(vec3(dot(mm[0], mm[0]), dot(mm[1], mm[1]), dot(mm[2], mm[2])), vec3(1e-12));
|
|
468
|
+
vWorldNormal = mm * worldN;
|
|
469
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
470
|
+
gl_PointSize = uPointSize;
|
|
471
|
+
}`,
|
|
472
|
+
fragmentShader: `
|
|
473
|
+
varying vec3 vWorldNormal;
|
|
474
|
+
void main() {
|
|
475
|
+
float len = length(vWorldNormal);
|
|
476
|
+
vec3 n = len > 1e-5 ? vWorldNormal / len : vec3(0.0, 1.0, 0.0);
|
|
477
|
+
gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);
|
|
478
|
+
}`,
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// 点云 UV 检视材质(Points):棋盘格、数值归一化(区分正负色相)、方向条纹(点元无屏幕导数,按固定带宽度取线)。
|
|
483
|
+
function makePointsUvMaterial(THREE, channelInfo, uvMode, density, pointSize = 2) {
|
|
484
|
+
const modeIndex = uvMode === 'value' ? 1 : uvMode === 'stripes' ? 2 : 0;
|
|
485
|
+
return new THREE.ShaderMaterial({
|
|
486
|
+
uniforms: {
|
|
487
|
+
uMode: { value: modeIndex },
|
|
488
|
+
uDensity: { value: density },
|
|
489
|
+
uPointSize: { value: Math.max(2, pointSize) },
|
|
490
|
+
uMin: { value: new THREE.Vector2(channelInfo.minU, channelInfo.minV) },
|
|
491
|
+
uMax: { value: new THREE.Vector2(channelInfo.maxU, channelInfo.maxV) },
|
|
492
|
+
},
|
|
493
|
+
vertexShader: `
|
|
494
|
+
${uvAttrDecl(channelInfo.name)}
|
|
495
|
+
uniform float uPointSize;
|
|
496
|
+
varying vec2 vUvVal;
|
|
497
|
+
void main() {
|
|
498
|
+
vUvVal = ${channelInfo.name};
|
|
499
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
500
|
+
gl_PointSize = uPointSize;
|
|
501
|
+
}`,
|
|
502
|
+
fragmentShader: `
|
|
503
|
+
uniform int uMode;
|
|
504
|
+
uniform float uDensity;
|
|
505
|
+
uniform vec2 uMin;
|
|
506
|
+
uniform vec2 uMax;
|
|
507
|
+
varying vec2 vUvVal;
|
|
508
|
+
void main() {
|
|
509
|
+
if (uMode == 0) {
|
|
510
|
+
vec2 cell = floor(vUvVal * uDensity);
|
|
511
|
+
float parity = mod(cell.x + cell.y, 2.0);
|
|
512
|
+
gl_FragColor = vec4(mix(vec3(0.22, 0.24, 0.28), vec3(0.86, 0.88, 0.90), parity), 1.0);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (uMode == 1) {
|
|
516
|
+
vec2 span = max(uMax - uMin, vec2(1e-6));
|
|
517
|
+
vec2 norm = clamp((vUvVal - uMin) / span, 0.0, 1.0);
|
|
518
|
+
vec3 col;
|
|
519
|
+
if (vUvVal.x < 0.0 && vUvVal.y < 0.0) {
|
|
520
|
+
col = vec3(0.14, 0.52 + 0.38 * norm.y, 0.72 + 0.28 * norm.x);
|
|
521
|
+
} else if (vUvVal.x < 0.0) {
|
|
522
|
+
col = vec3(0.12, 0.26 + 0.54 * norm.y, 0.65 + 0.35 * norm.x);
|
|
523
|
+
} else if (vUvVal.y < 0.0) {
|
|
524
|
+
col = vec3(0.55 + 0.45 * norm.x, 0.14, 0.65 + 0.35 * norm.y);
|
|
525
|
+
} else {
|
|
526
|
+
col = vec3(norm.x, norm.y, 0.12);
|
|
527
|
+
}
|
|
528
|
+
gl_FragColor = vec4(col, 1.0);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
float fv = fract(vUvVal.y * uDensity);
|
|
532
|
+
float line = step(min(fv, 1.0 - fv), 0.12);
|
|
533
|
+
gl_FragColor = vec4(mix(vec3(0.18, 0.22, 0.28), vec3(0.95, 0.78, 0.22), line), 1.0);
|
|
534
|
+
}`,
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// 创建模型检视控制器:记住原始材质(同时支持 Mesh 与 Points),管理检视材质与叠加对象的生命周期。
|
|
539
|
+
export function createInspector(THREE, root, ext) {
|
|
540
|
+
const caps = analyzeModel(root, ext);
|
|
541
|
+
const uvMap = new Map(caps.uvChannels.map(info => [info.name, info]));
|
|
542
|
+
const originals = new Map();
|
|
543
|
+
root.traverse(o => {
|
|
544
|
+
if ((o.isMesh || o.isPoints) && !o.userData?.[OVERLAY_FLAG]) originals.set(o, o.material);
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
const ownedMaterials = new Set();
|
|
548
|
+
const ownedGeometries = new Set();
|
|
549
|
+
const overlays = [];
|
|
550
|
+
let state = { mode: 'material', uvMode: 'checker', uvDensity: 16 };
|
|
551
|
+
let disposed = false;
|
|
552
|
+
|
|
553
|
+
const track = mat => { ownedMaterials.add(mat); return mat; };
|
|
554
|
+
const trackGeo = geo => { ownedGeometries.add(geo); return geo; };
|
|
555
|
+
|
|
556
|
+
function clearInspect() {
|
|
557
|
+
for (const { parent, overlay } of overlays) parent.remove(overlay);
|
|
558
|
+
overlays.length = 0;
|
|
559
|
+
for (const [obj, material] of originals) obj.material = material;
|
|
560
|
+
for (const mat of ownedMaterials) mat.dispose();
|
|
561
|
+
ownedMaterials.clear();
|
|
562
|
+
for (const geo of ownedGeometries) geo.dispose();
|
|
563
|
+
ownedGeometries.clear();
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function apply(next = {}) {
|
|
567
|
+
if (disposed) return { meta: '' };
|
|
568
|
+
const mode = next.mode ?? state.mode;
|
|
569
|
+
const uvMode = next.uvMode ?? state.uvMode;
|
|
570
|
+
const uvDensity = next.uvDensity ?? state.uvDensity;
|
|
571
|
+
|
|
572
|
+
// 校验不可用选项:无网格、无法线、无 PBR 或无对应 UV 通道时回退到材质。
|
|
573
|
+
let resolved = mode;
|
|
574
|
+
if (resolved === 'wireframe' && !caps.hasWireframe) resolved = 'material';
|
|
575
|
+
if (resolved === 'normal' && !caps.hasNormal) resolved = 'material';
|
|
576
|
+
if (resolved.startsWith('pbr:') && !caps.hasPBR) resolved = 'material';
|
|
577
|
+
if (resolved.startsWith('uv:') && !uvMap.has(resolved.slice(3))) resolved = 'material';
|
|
578
|
+
|
|
579
|
+
state = { mode: resolved, uvMode, uvDensity };
|
|
580
|
+
clearInspect();
|
|
581
|
+
|
|
582
|
+
if (resolved === 'material') return { meta: '' };
|
|
583
|
+
|
|
584
|
+
if (resolved === 'wireframe') {
|
|
585
|
+
const matBySide = new Map();
|
|
586
|
+
const wireMatFor = orig => {
|
|
587
|
+
const list = [orig].flat().filter(Boolean);
|
|
588
|
+
const side = list.length === 1 ? (list[0].side ?? THREE.FrontSide) : THREE.DoubleSide;
|
|
589
|
+
if (!matBySide.has(side)) matBySide.set(side, track(makeWireframeMaterial(THREE, side)));
|
|
590
|
+
return matBySide.get(side);
|
|
591
|
+
};
|
|
592
|
+
for (const [obj, orig] of originals) {
|
|
593
|
+
if (!obj.isMesh || !obj.geometry?.attributes?.position) continue;
|
|
594
|
+
const wireGeo = trackGeo(makeBarycentricGeometry(THREE, obj.geometry));
|
|
595
|
+
const overlay = makeWireOverlay(THREE, obj, wireGeo, wireMatFor(orig));
|
|
596
|
+
obj.add(overlay);
|
|
597
|
+
overlays.push({ parent: obj, overlay });
|
|
598
|
+
}
|
|
599
|
+
return { meta: '' };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
if (resolved === 'normal') {
|
|
603
|
+
let meshMat = null, pointsFallback = null;
|
|
604
|
+
for (const [obj, orig] of originals) {
|
|
605
|
+
if (obj.isMesh) {
|
|
606
|
+
if (!meshMat) meshMat = track(makeNormalMaterial(THREE));
|
|
607
|
+
obj.material = meshMat;
|
|
608
|
+
} else if (obj.isPoints) {
|
|
609
|
+
if (obj.geometry?.getAttribute?.('normal')) {
|
|
610
|
+
obj.material = track(makePointsNormalMaterial(THREE, orig?.size));
|
|
611
|
+
} else {
|
|
612
|
+
if (!pointsFallback) pointsFallback = track(new THREE.PointsMaterial({ size: Math.max(1, orig?.size ?? 1), sizeAttenuation: false, color: 0x666666 }));
|
|
613
|
+
obj.material = pointsFallback;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return { meta: '' };
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (resolved.startsWith('pbr:')) {
|
|
621
|
+
const channel = resolved.slice(4);
|
|
622
|
+
for (const [obj, orig] of originals) {
|
|
623
|
+
if (!obj.isMesh) continue;
|
|
624
|
+
if (Array.isArray(orig)) {
|
|
625
|
+
obj.material = orig.map(m => track(makePbrChannelMaterial(THREE, channel, m, obj.geometry)));
|
|
626
|
+
} else {
|
|
627
|
+
obj.material = track(makePbrChannelMaterial(THREE, channel, orig, obj.geometry));
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return { meta: '' };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (resolved.startsWith('uv:')) {
|
|
634
|
+
const channelName = resolved.slice(3);
|
|
635
|
+
const info = uvMap.get(channelName);
|
|
636
|
+
let meshUvMat = null, meshFallback = null, pointsFallback = null;
|
|
637
|
+
for (const [obj, orig] of originals) {
|
|
638
|
+
const hasAttr = Boolean(obj.geometry?.getAttribute?.(channelName));
|
|
639
|
+
if (obj.isMesh) {
|
|
640
|
+
if (hasAttr) {
|
|
641
|
+
if (!meshUvMat) meshUvMat = track(makeUvMaterial(THREE, info, uvMode, uvDensity));
|
|
642
|
+
obj.material = meshUvMat;
|
|
643
|
+
} else {
|
|
644
|
+
if (!meshFallback) meshFallback = track(new THREE.MeshBasicMaterial({ color: 0x666666, side: THREE.DoubleSide }));
|
|
645
|
+
obj.material = meshFallback;
|
|
646
|
+
}
|
|
647
|
+
} else if (obj.isPoints) {
|
|
648
|
+
if (hasAttr) {
|
|
649
|
+
obj.material = track(makePointsUvMaterial(THREE, info, uvMode, uvDensity, orig?.size));
|
|
650
|
+
} else {
|
|
651
|
+
if (!pointsFallback) pointsFallback = track(new THREE.PointsMaterial({ size: Math.max(1, orig?.size ?? 1), sizeAttenuation: false, color: 0x666666 }));
|
|
652
|
+
obj.material = pointsFallback;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return { meta: formatUvMeta(info) };
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return { meta: '' };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
return {
|
|
663
|
+
caps,
|
|
664
|
+
get state() { return { ...state }; },
|
|
665
|
+
get ownedCount() { return ownedMaterials.size; },
|
|
666
|
+
apply,
|
|
667
|
+
dispose() {
|
|
668
|
+
if (disposed) return;
|
|
669
|
+
disposed = true;
|
|
670
|
+
clearInspect();
|
|
671
|
+
originals.clear();
|
|
672
|
+
},
|
|
673
|
+
};
|
|
674
|
+
}
|
package/view/preview.mjs
CHANGED
|
@@ -78,10 +78,11 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
78
78
|
const body = h('div', { class: 'pbody', tabindex: '-1' }); // 可聚焦:关查找条后焦点回正文
|
|
79
79
|
const modes = [['3d', '3D'], ['text', '文本']].map(([value, label]) => ({ value, button: h('button', { class: 'link', onclick: () => setMode(value) }, label) }));
|
|
80
80
|
const modeBar = h('div', { class: 'pmode', role: 'group', 'aria-label': '显示方式', hidden: true }, ...modes.map(({ button }) => button));
|
|
81
|
+
const inspectSlot = h('div', { class: 'pinspect-slot', hidden: true });
|
|
81
82
|
let gutterEl = null;
|
|
82
83
|
const find = createFind({ body, gutterWidth: () => gutterEl?.offsetWidth ?? 0 });
|
|
83
84
|
const extra = actions.map(({ label, icon: glyph, run }) => { const button = action(label, glyph, () => path !== null && run(path, button)); return button; });
|
|
84
|
-
el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), modeBar, retryButton,
|
|
85
|
+
el.replaceChildren(h('div', { class: 'phead' }, ...(back ? [action('返回', 'back', back)] : []), fileIcon, h('div', { class: 'grow' }, name, meta), inspectSlot, modeBar, retryButton,
|
|
85
86
|
...(copyInHead ? [action('复制路径', 'copy', copyPath)] : []), ...extra), find.el, body);
|
|
86
87
|
find.done.addEventListener('click', () => { find.close(); body.focus(); });
|
|
87
88
|
// 查找条的键盘:Esc 关(从查找条里关,焦点回正文;焦点在正文里,焦点留在正文);⌘G、⇧⌘G 下一个、上一个。输入法组字中的按键不管,菜单消费掉的 Esc 不再处理。
|
|
@@ -133,7 +134,7 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
133
134
|
player.pause?.(); player.removeAttribute('src'); player.load?.();
|
|
134
135
|
player = null;
|
|
135
136
|
};
|
|
136
|
-
const revoke = () => { stopMedia(); viewer?.dispose(); viewer = null; if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
|
|
137
|
+
const revoke = () => { stopMedia(); viewer?.dispose(); viewer = null; inspectSlot.replaceChildren(); inspectSlot.hidden = true; if (objectUrl) URL.revokeObjectURL(objectUrl); objectUrl = null; };
|
|
137
138
|
const notice = (title, detail, action) => body.replaceChildren(h('div', { class: 'empty' },
|
|
138
139
|
h('p', {}, title), detail ? h('p', { class: 'secondary' }, detail) : null,
|
|
139
140
|
action ? h('button', { class: 'link', onclick: action.run }, action.label) : null));
|
|
@@ -221,7 +222,11 @@ export function mountPreview(el, { read, copy, actions = [], copyInHead = true,
|
|
|
221
222
|
shown = { size, mtimeMs };
|
|
222
223
|
const parts = mediaMeta(size), title = `修改于 ${formatTime(mtimeMs)}`;
|
|
223
224
|
setMeta(line(parts), title);
|
|
224
|
-
const mine = viewer = mountModel({ body, token: key, path, size, version: `${size}-${mtimeMs}`, onMeta: extra => {
|
|
225
|
+
const mine = viewer = mountModel({ body, head: inspectSlot, token: key, path, size, version: `${size}-${mtimeMs}`, onMeta: extra => {
|
|
226
|
+
if (viewer !== mine) return;
|
|
227
|
+
const full = line([...parts, ...extra]);
|
|
228
|
+
setMetaText(full, extra.length > 2 && extra[2] ? `${extra[2]} · ${title}` : title);
|
|
229
|
+
} });
|
|
225
230
|
}
|
|
226
231
|
|
|
227
232
|
// 媒体文件(按扩展名):返回 true 表示已经处理(显示、提示或已作废),false 表示这个文件走分块读取(宿主没有流式服务时的图片和模型,模型选了看文本时)。
|
package/view/style.css
CHANGED
|
@@ -179,10 +179,14 @@ button.icon svg { display: block; }
|
|
|
179
179
|
.media { display: grid; place-items: start center; padding: 12px; }
|
|
180
180
|
.media video { width: 100%; max-height: 70vh; border-radius: var(--coda-radius, 6px); background: #000; }
|
|
181
181
|
.media audio { width: 100%; }
|
|
182
|
-
/* 3D 模型(第 21 节):正文不滚动,整块是画布;状态、复位和动画控制浮在画布上。「3D /
|
|
182
|
+
/* 3D 模型(第 21 节):正文不滚动,整块是画布;状态、复位和动画控制浮在画布上。「3D / 文本」切换和「检视」选择在头部。 */
|
|
183
183
|
.pmode { flex: none; display: flex; gap: 2px; }
|
|
184
184
|
.pmode button { padding: 2px 8px; border-radius: var(--coda-radius, 6px); }
|
|
185
185
|
.pmode button[aria-pressed="true"] { background: var(--coda-selection, var(--hover)); font-weight: 600; }
|
|
186
|
+
.pinspect-slot { flex: none; display: flex; align-items: center; }
|
|
187
|
+
.pinspect-slot[hidden] { display: none; }
|
|
188
|
+
.pinspect { max-width: 112px; padding: 3px 6px; border-radius: var(--coda-radius, 6px); border: 1px solid var(--line); background: var(--coda-card, var(--coda-background, #fff)); color: var(--coda-foreground, #1d1d1f); font: inherit; font-size: .92em; }
|
|
189
|
+
.pinspect[hidden] { display: none; }
|
|
186
190
|
.pbody.model { display: flex; flex-direction: column; overflow: hidden; }
|
|
187
191
|
.mview { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
|
188
192
|
.mstage { position: relative; flex: 1 1 auto; min-height: 160px; overflow: hidden; background: var(--coda-secondary-background, rgba(127,127,127,.08)); }
|
|
@@ -190,8 +194,16 @@ button.icon svg { display: block; }
|
|
|
190
194
|
.mstatus { position: absolute; inset: 0; display: grid; align-content: center; justify-items: center; gap: 6px; padding: 20px; text-align: center; pointer-events: none; }
|
|
191
195
|
.mstatus[hidden] { display: none; }
|
|
192
196
|
.mstatus button { pointer-events: auto; }
|
|
193
|
-
.mbtn, .mclip { padding: 4px 10px; border-radius: var(--coda-radius, 6px); background: var(--coda-card, var(--coda-background, #fff)); border: 1px solid var(--line); color: var(--coda-accent, #0a84ff); }
|
|
197
|
+
.mbtn, .mclip, .mdensity { padding: 4px 10px; border-radius: var(--coda-radius, 6px); background: var(--coda-card, var(--coda-background, #fff)); border: 1px solid var(--line); color: var(--coda-accent, #0a84ff); font: inherit; }
|
|
194
198
|
.mreset { position: absolute; top: 8px; right: 8px; }
|
|
199
|
+
.muvbar { position: absolute; top: 8px; left: 8px; right: 92px; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; pointer-events: none; }
|
|
200
|
+
.muvbar > * { pointer-events: auto; }
|
|
201
|
+
.muvbar[hidden], .mdensity[hidden] { display: none; }
|
|
202
|
+
.muvmodes { display: inline-flex; gap: 2px; padding: 2px; border-radius: var(--coda-radius, 6px); background: var(--coda-card, var(--coda-background, #fff)); border: 1px solid var(--line); }
|
|
203
|
+
.muvmodes button { padding: 2px 8px; border: 0; background: transparent; color: var(--coda-foreground, #1d1d1f); }
|
|
204
|
+
.muvmodes button[aria-pressed="true"] { background: var(--coda-selection, var(--hover)); color: var(--coda-accent, #0a84ff); font-weight: 600; }
|
|
205
|
+
.muvrange { flex: none; padding: 4px 12px; border-bottom: 1px solid var(--line); background: var(--coda-background, #fff); white-space: normal; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
|
|
206
|
+
.muvrange[hidden] { display: none; }
|
|
195
207
|
.mbar { position: absolute; left: 8px; bottom: 8px; display: flex; gap: 8px; }
|
|
196
208
|
.mbar[hidden], .mclip[hidden] { display: none; }
|
|
197
209
|
.image { display: grid; place-items: start center; padding: 12px; }
|
|
@@ -300,6 +312,9 @@ button.icon svg { display: block; }
|
|
|
300
312
|
.coda-ios .bar button.icon { padding: 0; justify-content: center; }
|
|
301
313
|
.coda-ios .phead, .coda-ios .ghead { padding: 4px 12px; gap: 4px; }
|
|
302
314
|
.coda-ios .phead button, .coda-ios .ghead button { padding: 0 8px; }
|
|
315
|
+
.coda-ios .pinspect { min-height: 36px; max-width: 104px; font-size: max(14px, .9em); }
|
|
316
|
+
.coda-ios .mdensity { min-height: 36px; }
|
|
317
|
+
.coda-ios .muvmodes button { min-height: 36px; min-width: 44px; padding: 0 8px; }
|
|
303
318
|
.coda-ios .preview:not(.info) .pbody { padding-bottom: var(--safe-bottom); } /* 资源页里没有底部工具条:最后一行不被 Home 指示条盖住 */
|
|
304
319
|
.coda-ios .code { font-size: .8em; } /* 窄屏多看些:17 点下约 13.6 点 */
|
|
305
320
|
.coda-ios .menu button { padding: 0 10px; }
|
package/view/viewer3d.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// 释放登记在 held 里,建一个登记一个,中途失败、中途切走也释放得干净。
|
|
5
5
|
import { h } from './dom.mjs';
|
|
6
6
|
import { formatSize } from './format.mjs';
|
|
7
|
+
import { PBR_CHANNELS, UV_DENSITIES, UV_MODES, createInspector } from './inspect3d.mjs';
|
|
7
8
|
import { BIG_FILE, Z_UP, createPlayback, directoryUrl, extensionOf, gltfJson, joinRelative, mtllibOf, plyFaceCount, serviceUrl, unsupportedExtensions } from './model3d.mjs';
|
|
8
9
|
|
|
9
10
|
const VENDOR = './vendor/three';
|
|
@@ -34,28 +35,45 @@ const browser = {
|
|
|
34
35
|
reducedMotion: () => typeof matchMedia !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches, // 拿不到 matchMedia 按减弱处理,同页面其他动画
|
|
35
36
|
};
|
|
36
37
|
|
|
37
|
-
// 在 body 里挂一个模型视图。size 是文件大小(超过 64 MiB 先问);onMeta(parts):把「N 面」「K
|
|
38
|
+
// 在 body 里挂一个模型视图。head 是预览头部里留给检视选择的槽(可选);size 是文件大小(超过 64 MiB 先问);onMeta(parts):把「N 面」「K 段动画」及检视元信息交给预览头部的元信息行。
|
|
38
39
|
// 返回 { cancel, dispose }:cancel 只停加载和动画循环(预览逻辑关闭时),dispose 释放一切(画面退场后)。
|
|
39
|
-
export function mountViewer({ body, token, path, size, version, onMeta = () => {}, env = {} }) {
|
|
40
|
+
export function mountViewer({ body, head = null, token, path, size, version, onMeta = () => {}, env = {} }) {
|
|
40
41
|
const { engine, fetch: get, raf, caf, now, paint, hasWebGL, reducedMotion } = { ...browser, ...env };
|
|
41
42
|
const ext = extensionOf(path);
|
|
42
43
|
|
|
43
44
|
const status = h('div', { class: 'mstatus' });
|
|
44
45
|
const resetButton = h('button', { class: 'mbtn mreset', hidden: true }, '复位视角');
|
|
46
|
+
const inspectSelect = h('select', { class: 'pinspect', 'aria-label': '检视', hidden: true });
|
|
47
|
+
const uvModeButtons = UV_MODES.map(({ id, label }) => ({ id, button: h('button', { class: 'mbtn', 'aria-pressed': String(id === 'checker') }, label) }));
|
|
48
|
+
const densitySelect = h('select', { class: 'mdensity', 'aria-label': '密度' },
|
|
49
|
+
...UV_DENSITIES.map(({ label, value }) => h('option', { value: String(value), selected: value === 16 && '' }, `密度 ${label}`)));
|
|
50
|
+
densitySelect.value = '16';
|
|
51
|
+
const uvBar = h('div', { class: 'muvbar', hidden: true },
|
|
52
|
+
h('div', { class: 'muvmodes', role: 'group', 'aria-label': 'UV 显示方式' }, ...uvModeButtons.map(({ button }) => button)),
|
|
53
|
+
densitySelect);
|
|
54
|
+
const uvRange = h('div', { class: 'muvrange caption secondary', hidden: true });
|
|
45
55
|
const playButton = h('button', { class: 'mbtn' }, '暂停');
|
|
46
56
|
const clipSelect = h('select', { class: 'mclip', 'aria-label': '动画' });
|
|
47
57
|
const bar = h('div', { class: 'mbar', hidden: true }, playButton, clipSelect);
|
|
48
|
-
const stage = h('div', { class: 'mstage' }, status, resetButton, bar);
|
|
58
|
+
const stage = h('div', { class: 'mstage' }, status, ...(head ? [] : [inspectSelect]), uvBar, resetButton, bar);
|
|
49
59
|
body.classList.add('model');
|
|
50
|
-
body.replaceChildren(h('div', { class: 'mview' }, stage));
|
|
60
|
+
body.replaceChildren(h('div', { class: 'mview' }, uvRange, stage));
|
|
51
61
|
|
|
52
62
|
const abort = new AbortController();
|
|
53
63
|
let dead = false, disposed = false, gate = null, playback = null, requestRender = () => {}, sync = () => {};
|
|
54
|
-
const held = { wrapper: null, canvas: null, renderer: null, controls: null, observer: null, frame: 0, mixer: null, envTarget: null, manager: null };
|
|
64
|
+
const held = { wrapper: null, inspector: null, canvas: null, renderer: null, controls: null, observer: null, frame: 0, mixer: null, envTarget: null, manager: null };
|
|
55
65
|
const stopFrame = () => { if (held.frame) caf(held.frame); held.frame = 0; };
|
|
56
66
|
// dead:停止(cancel)或失败(release)之后的终态:requestRender 和帧不再排帧(停止时画面留着,只是不再画),playback 也停了,其余入口(可见性、sync)自然落空。
|
|
57
67
|
const onVisibility = () => { playback?.setVisible(!document.hidden); sync(); if (!document.hidden) requestRender(); };
|
|
58
68
|
document.addEventListener('visibilitychange', onVisibility);
|
|
69
|
+
const clearInspectUI = () => {
|
|
70
|
+
uvBar.hidden = true;
|
|
71
|
+
uvRange.hidden = true;
|
|
72
|
+
uvRange.textContent = '';
|
|
73
|
+
inspectSelect.hidden = true;
|
|
74
|
+
inspectSelect.replaceChildren();
|
|
75
|
+
if (head) { head.replaceChildren(); head.hidden = true; }
|
|
76
|
+
};
|
|
59
77
|
const release = () => {
|
|
60
78
|
dead = true;
|
|
61
79
|
playback?.stop();
|
|
@@ -66,15 +84,18 @@ export function mountViewer({ body, token, path, size, version, onMeta = () => {
|
|
|
66
84
|
held.controls?.dispose();
|
|
67
85
|
if (held.mixer) { held.mixer.stopAllAction(); held.mixer.uncacheRoot(held.mixer.getRoot()); }
|
|
68
86
|
held.envTarget?.dispose();
|
|
87
|
+
held.inspector?.dispose();
|
|
69
88
|
if (held.wrapper) disposeObject(held.wrapper);
|
|
70
89
|
held.renderer?.dispose();
|
|
71
90
|
held.renderer?.forceContextLoss();
|
|
72
91
|
if (held.canvas) { held.canvas.width = held.canvas.height = 0; held.canvas.remove(); } // 连画布的后备存储一起还掉(iOS 上不还会攒着)
|
|
73
|
-
|
|
92
|
+
clearInspectUI();
|
|
93
|
+
Object.assign(held, { wrapper: null, inspector: null, canvas: null, renderer: null, controls: null, observer: null, mixer: null, envTarget: null, manager: null });
|
|
74
94
|
};
|
|
75
95
|
const say = (text, ...extra) => { status.hidden = false; status.replaceChildren(h('p', {}, text), ...extra.filter(Boolean)); }; // 真 DOM 的 replaceChildren 会把 null 变成文字「null」
|
|
76
96
|
const fail = (title, detail) => {
|
|
77
|
-
resetButton.hidden = bar.hidden = true;
|
|
97
|
+
resetButton.hidden = bar.hidden = uvBar.hidden = uvRange.hidden = inspectSelect.hidden = true;
|
|
98
|
+
if (head) { head.replaceChildren(); head.hidden = true; }
|
|
78
99
|
say(title, detail ? h('p', { class: 'secondary caption' }, detail) : null);
|
|
79
100
|
};
|
|
80
101
|
|
|
@@ -242,8 +263,43 @@ export function mountViewer({ body, token, path, size, version, onMeta = () => {
|
|
|
242
263
|
held.manager = manager;
|
|
243
264
|
manager.onLoad = () => requestRender(); // 贴图晚到(obj 的 mtl 里的贴图):到了就重画
|
|
244
265
|
|
|
266
|
+
const baseMeta = [stats.triangles > 0 || stats.points === 0 ? `${count(stats.triangles)} 面` : `${count(stats.points)} 个点`, clips.length ? `${clips.length} 段动画` : ''];
|
|
267
|
+
// 检视模式:按模型能力填充选项(无网格时线框置灰;无法线时法线置灰;无 PBR 时材质通道置灰;只列出模型里实际存在的 UV 通道)。
|
|
268
|
+
const inspector = held.inspector = createInspector(THREE, wrapper, ext);
|
|
269
|
+
const { hasWireframe, hasNormal, hasPBR, uvChannels } = inspector.caps;
|
|
270
|
+
inspectSelect.replaceChildren(
|
|
271
|
+
h('option', { value: 'material' }, '材质'),
|
|
272
|
+
h('optgroup', { label: '形体' },
|
|
273
|
+
h('option', { value: 'wireframe', disabled: !hasWireframe && '' }, '线框'),
|
|
274
|
+
h('option', { value: 'normal', disabled: !hasNormal && '' }, '法线')),
|
|
275
|
+
h('optgroup', { label: '材质通道' },
|
|
276
|
+
...PBR_CHANNELS.map(({ id, label }) => h('option', { value: `pbr:${id}`, disabled: !hasPBR && '' }, label))),
|
|
277
|
+
...(uvChannels.length ? [h('optgroup', { label: 'UV 通道' },
|
|
278
|
+
...uvChannels.map(({ name }) => h('option', { value: `uv:${name}` }, `UV:${name}`)))] : []),
|
|
279
|
+
);
|
|
280
|
+
inspectSelect.value = 'material';
|
|
281
|
+
const applyInspect = next => {
|
|
282
|
+
const { meta } = inspector.apply(next);
|
|
283
|
+
const { mode: activeMode, uvMode, uvDensity } = inspector.state;
|
|
284
|
+
inspectSelect.value = activeMode;
|
|
285
|
+
const inUv = activeMode.startsWith('uv:');
|
|
286
|
+
uvBar.hidden = !inUv;
|
|
287
|
+
uvRange.hidden = !meta;
|
|
288
|
+
uvRange.textContent = meta;
|
|
289
|
+
densitySelect.hidden = uvMode === 'value';
|
|
290
|
+
densitySelect.value = String(uvDensity);
|
|
291
|
+
for (const { id, button } of uvModeButtons) button.setAttribute('aria-pressed', String(uvMode === id));
|
|
292
|
+
onMeta(meta ? [...baseMeta, meta] : baseMeta);
|
|
293
|
+
requestRender();
|
|
294
|
+
};
|
|
295
|
+
inspectSelect.addEventListener('change', () => applyInspect({ mode: inspectSelect.value }));
|
|
296
|
+
for (const { id, button } of uvModeButtons) button.addEventListener('click', () => applyInspect({ uvMode: id }));
|
|
297
|
+
densitySelect.addEventListener('change', () => applyInspect({ uvDensity: Number(densitySelect.value) }));
|
|
298
|
+
inspectSelect.hidden = false;
|
|
299
|
+
if (head) { head.replaceChildren(inspectSelect); head.hidden = false; }
|
|
300
|
+
|
|
245
301
|
renderer.render(scene, camera);
|
|
246
|
-
onMeta(
|
|
302
|
+
onMeta(baseMeta);
|
|
247
303
|
status.hidden = true;
|
|
248
304
|
resetButton.hidden = false;
|
|
249
305
|
resetButton.addEventListener('click', () => { fit(); requestRender(); });
|
|
@@ -272,7 +328,11 @@ export function mountViewer({ body, token, path, size, version, onMeta = () => {
|
|
|
272
328
|
|
|
273
329
|
// 按格式解析成 three 的对象。返回 { object, animations };失败抛 Friendly 或原样的错误。
|
|
274
330
|
async function parseModel({ THREE, engine, manager, bytes, ext, token, path, download }) {
|
|
275
|
-
const neutral = () =>
|
|
331
|
+
const neutral = () => {
|
|
332
|
+
const m = new THREE.MeshStandardMaterial({ color: 0xb8bcc4, roughness: 0.65, metalness: 0.05, side: THREE.DoubleSide });
|
|
333
|
+
m.userData.__neutral = true;
|
|
334
|
+
return m;
|
|
335
|
+
};
|
|
276
336
|
const exact = view => (view.byteOffset === 0 && view.byteLength === view.buffer.byteLength ? view.buffer : view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
|
|
277
337
|
const done = (object, animations = []) => ({ object, animations });
|
|
278
338
|
|