mini-three-adapter 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +85 -0
- package/LICENSE +21 -0
- package/README.md +158 -2
- package/dist/build/rollup.d.ts +8 -0
- package/dist/build/rollup.js +393 -0
- package/dist/build/rollup.js.map +1 -0
- package/dist/build/vite.d.ts +15 -0
- package/dist/build/vite.js +395 -0
- package/dist/build/vite.js.map +1 -0
- package/dist/chunk-34RWHAW4.js +128 -0
- package/dist/chunk-34RWHAW4.js.map +1 -0
- package/dist/chunk-3UGQWFH3.js +1246 -0
- package/dist/chunk-3UGQWFH3.js.map +1 -0
- package/dist/chunk-4UEBRAK6.js +711 -0
- package/dist/chunk-4UEBRAK6.js.map +1 -0
- package/dist/chunk-LB3WL24R.js +91 -0
- package/dist/chunk-LB3WL24R.js.map +1 -0
- package/dist/chunk-MTBMOFAL.js +132 -0
- package/dist/chunk-MTBMOFAL.js.map +1 -0
- package/dist/chunk-QYQQ5J6E.js +3 -0
- package/dist/chunk-QYQQ5J6E.js.map +1 -0
- package/dist/chunk-V6TY7KAL.js +7 -0
- package/dist/chunk-V6TY7KAL.js.map +1 -0
- package/dist/chunk-WLRQDTSZ.js +145 -0
- package/dist/chunk-WLRQDTSZ.js.map +1 -0
- package/dist/chunk-Z7AMDRN3.js +66 -0
- package/dist/chunk-Z7AMDRN3.js.map +1 -0
- package/dist/core/index.d.ts +101 -0
- package/dist/core/index.js +7 -0
- package/dist/core/index.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/platforms/browser.d.ts +23 -0
- package/dist/platforms/browser.js +7 -0
- package/dist/platforms/browser.js.map +1 -0
- package/dist/platforms/wechat-game.d.ts +31 -0
- package/dist/platforms/wechat-game.js +8 -0
- package/dist/platforms/wechat-game.js.map +1 -0
- package/dist/platforms/wechat-miniprogram.d.ts +26 -0
- package/dist/platforms/wechat-miniprogram.js +8 -0
- package/dist/platforms/wechat-miniprogram.js.map +1 -0
- package/dist/plugin-core-BuqW9C-L.d.ts +127 -0
- package/dist/polyfills/index.d.ts +291 -0
- package/dist/polyfills/index.js +4 -0
- package/dist/polyfills/index.js.map +1 -0
- package/dist/runtime-7uUOoFhC.d.ts +263 -0
- package/dist/scope.d.ts +146 -0
- package/dist/scope.js +4 -0
- package/dist/scope.js.map +1 -0
- package/dist/types-BzK0LQMa.d.ts +153 -0
- package/dist/wx-types-NMNyrsWO.d.ts +150 -0
- package/docs/01-design-principles.md +105 -0
- package/docs/02-architecture.md +126 -0
- package/docs/03-module-map.md +99 -0
- package/docs/04-api-reference.md +291 -0
- package/docs/05-build-plugin.md +146 -0
- package/docs/06-platform-notes.md +108 -0
- package/docs/07-integration-guide.md +211 -0
- package/docs/08-extension-guide.md +101 -0
- package/docs/09-testing-and-release.md +206 -0
- package/docs/10-ai-playbook.md +140 -0
- package/docs/11-compat-matrix.md +94 -0
- package/docs/README.md +41 -0
- package/docs/adr/0001-scoped-globals.md +41 -0
- package/docs/adr/0002-unified-runtime-lifecycle.md +40 -0
- package/docs/adr/0003-ast-rewrite.md +51 -0
- package/docs/adr/0004-in-place-patching.md +42 -0
- package/docs/adr/0005-webgl2-only.md +44 -0
- package/docs/adr/0006-zero-three-dependency.md +43 -0
- package/docs/adr/README.md +28 -0
- package/llms.txt +65 -0
- package/package.json +117 -4
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# 05 · 构建插件原理与配置
|
|
2
|
+
|
|
3
|
+
> 插件是「不 fork three」这一路线成立的关键。它只在 **Node 构建期**运行,产物不会进入小游戏运行时。
|
|
4
|
+
|
|
5
|
+
## 5.1 为什么必须改写三方模块
|
|
6
|
+
|
|
7
|
+
微信小游戏没有 `window` / `document` / `Image` / `URL` 等全局([官方 Adapter 文档](https://developers.weixin.qq.com/minigame/dev/guide/runtime/adapter.html))。three 及其 addons 会直接引用这些自由变量。两种办法:
|
|
8
|
+
|
|
9
|
+
1. 把这些 shim 挂到 `globalThis`(官方 `weapp-adapter` 路线)→ 简单但不可逆、H5 双端冲突。
|
|
10
|
+
2. 在编译期把三方模块中的**自由引用**改成 `__m3().window` → 运行时由 `MiniThreeScope` 提供。
|
|
11
|
+
|
|
12
|
+
本项目选 2,并额外用 AST 作用域分析保证精确。
|
|
13
|
+
|
|
14
|
+
## 5.2 改写流程(`src/build/scope-rewrite.ts`)
|
|
15
|
+
|
|
16
|
+
```mermaid
|
|
17
|
+
flowchart TD
|
|
18
|
+
A["transform(code, id)"] --> B{"include(id)?"}
|
|
19
|
+
B -->|否| Z["返回 null"]
|
|
20
|
+
B -->|是| C["@babel/parser<br/>sourceType: unambiguous<br/>TS/JSX 插件"]
|
|
21
|
+
C --> D["traverse: ReferencedIdentifier"]
|
|
22
|
+
D --> E{"name ∈ DEFAULT_GLOBAL_NAMES?"}
|
|
23
|
+
E -->|否| D
|
|
24
|
+
E -->|是| F{"非计算属性键 / 成员属性?"}
|
|
25
|
+
F -->|是| D
|
|
26
|
+
F -->|否| G{"path.scope.hasBinding(name, true)?"}
|
|
27
|
+
G -->|是(局部/import/参数)| D
|
|
28
|
+
G -->|否(真正的自由全局)| H["MagicString.overwrite<br/>name → __m3().name"]
|
|
29
|
+
H --> I["prepend:<br/>import { getActiveScope as __m3 } from 'mini-three-adapter/scope'"]
|
|
30
|
+
I --> J["返回 { code, map }"]
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
关键正确性保证:
|
|
34
|
+
|
|
35
|
+
| 场景 | 处理 |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `function f(window) { return window.x }` | `hasBinding` 命中 → **不改写** |
|
|
38
|
+
| `const o = { window: 1 }` | 非计算属性键 → 不改写 |
|
|
39
|
+
| `foo.window` | 成员属性 → 不改写 |
|
|
40
|
+
| `import { window as w } from 'x'` | import 绑定 → 不改写 |
|
|
41
|
+
| `typeof window !== 'undefined'` | 改写成 `typeof __m3().window !== 'undefined'`,结果 `'object'`,three 走浏览器分支(正是我们想要的) |
|
|
42
|
+
| `URL.createObjectURL(blob)` | `URL` 与 `Blob` 都改写 |
|
|
43
|
+
| 解析失败 | 记录 `parseFailures` + `ctx.warn`,**原样返回**,绝不产出半改写代码 |
|
|
44
|
+
|
|
45
|
+
`globalThis` **故意不在**默认清单里:three 会用它挂调试钩子(`__THREE_DEVTOOLS__` 等),改写会破坏这些逻辑。
|
|
46
|
+
|
|
47
|
+
`forceUndef: ['createImageBitmap']`:这些名字同样被改写,但作用域里恒为 `undefined`,于是 three 的 `typeof createImageBitmap !== 'undefined'` 判定为假,自动走非 Blob 分支。宿主环境提供了该 API 却没有原生 `Blob` 实现时,这个开关可以让 three 绕开不可用的代码路径。
|
|
48
|
+
|
|
49
|
+
## 5.3 默认 include 规则
|
|
50
|
+
|
|
51
|
+
命中以下路径(Vite/Rollup 的 `id` 会被规范化为 `/`):
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
/node_modules/three/...
|
|
55
|
+
/node_modules/three@<version>/...
|
|
56
|
+
/node_modules/three-stdlib/...
|
|
57
|
+
/node_modules/@react-three/...
|
|
58
|
+
/node_modules/@tresjs/...
|
|
59
|
+
/node_modules/.vite/deps/three* # Vite 预打包产物兜底
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
应用代码默认**不改写**。若确实需要,设 `includeUserCode: true`(会跳过 `mini-three-adapter` 自身)。
|
|
63
|
+
`vite.ts` 的 `config()` 额外设置 `optimizeDeps.exclude`,避免 Vite 把 three 预打包成一个不透明显式的 blob。
|
|
64
|
+
|
|
65
|
+
## 5.4 WebGPU 策略
|
|
66
|
+
|
|
67
|
+
微信小游戏没有 WebGPU,而 three r180+ 主推 `three/webgpu`。插件检测到 `from 'three/webgpu'` 时:
|
|
68
|
+
|
|
69
|
+
| `webgpu` | 行为 |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `'warn'`(默认) | 构建告警,记入 `report.webgpuWarnings` |
|
|
72
|
+
| `'error'` | 直接失败,强制改用 `WebGLRenderer` |
|
|
73
|
+
| `'rewrite'` | 把 `three/webgpu` → `three`、`WebGPURenderer` → `WebGLRenderer`(**仅适用于未使用 TSL/NodeMaterial 的简单场景**) |
|
|
74
|
+
| `'ignore'` | 不处理 |
|
|
75
|
+
|
|
76
|
+
> `'rewrite'` 是有损的:`MeshStandardNodeMaterial`、TSL、`PostProcessing` 没有 WebGLRenderer 等价物,不能靠重命名解决。复杂 WebGPU 项目应改用 WebGL 构建目标。
|
|
77
|
+
|
|
78
|
+
## 5.5 资源收集(`src/build/assets.ts`)
|
|
79
|
+
|
|
80
|
+
```mermaid
|
|
81
|
+
flowchart LR
|
|
82
|
+
A["扫描模块内字符串字面量<br/>*.wasm / *.wasm.br / *.bin / *.js"] --> B["按关键字过滤<br/>draco/ktx2/basis/meshopt/rhino3dm/zstd/ammo/worker/decoder/transcoder/lottie/sdf"]
|
|
83
|
+
B --> C["在 roots 中按 basename 索引查找"]
|
|
84
|
+
C --> D["collectAssets(): entries + files + missing"]
|
|
85
|
+
D --> E["generateBundle(): emitFile 每个资源"]
|
|
86
|
+
D --> F["emitFile('mini-three-assets.json')"]
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
默认搜索目录:`node_modules/three/examples/jsm/libs`、`node_modules/three/examples/jsm`、`node_modules/three-stdlib`、`public`、`static`,以及用户 `roots`。
|
|
90
|
+
|
|
91
|
+
`mini-three-assets.json` 内容:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
{
|
|
95
|
+
"generatedBy": "mini-three-adapter",
|
|
96
|
+
"outputDir": "assets/three",
|
|
97
|
+
"entries": [{ "reference": "draco_decoder_gltf.wasm", "source": "...", "destination": "assets/three/draco_decoder_gltf.wasm", "kind": "wasm" }],
|
|
98
|
+
"gameJsonSuggestion": {
|
|
99
|
+
"workers": { "path": "assets/three", "isSubpackage": true },
|
|
100
|
+
"subpackages": [{ "name": "three-assets", "root": "assets/three/" }]
|
|
101
|
+
},
|
|
102
|
+
"decoderPaths": { "draco": "assets/three/" },
|
|
103
|
+
"build": { "modulesScanned": 12, "rewrites": 87, "missingAssets": [] }
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
约定与限制:
|
|
108
|
+
|
|
109
|
+
- 微信 Worker 配置只支持**一个目录**,所以 worker 与 wasm 统一输出到同一个 `outputDir`。
|
|
110
|
+
- `brotli: true` 时若存在 `xxx.wasm.br` 会一并拷贝;`WXWebAssembly.instantiate` 支持 `.wasm.br`([官方文档](https://developers.weixin.qq.com/minigame/dev/guide/performance/perf-webassembly.html))。
|
|
111
|
+
- Worker 分包需先 `wx.preDownloadSubpackage({ packageType: 'workers' })` 再 `wx.createWorker()`,且**并发最多 1 个 Worker**。
|
|
112
|
+
- 找不到资源时只告警并记入 `missingAssets`,不阻断构建——decoder 可能由业务自行放置。
|
|
113
|
+
|
|
114
|
+
运行时设置 decoder 路径示例:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
|
|
118
|
+
const draco = new DRACOLoader();
|
|
119
|
+
draco.setDecoderPath('assets/three/'); // 与 manifest.decoderPaths.draco 一致
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## 5.6 Vite / Rollup 差异
|
|
123
|
+
|
|
124
|
+
| | Vite | Rollup |
|
|
125
|
+
| --- | --- | --- |
|
|
126
|
+
| 入口 | `mini-three-adapter/vite`(default export `miniThree`) | `mini-three-adapter/rollup`(named `miniThree`) |
|
|
127
|
+
| 额外 hook | `config()` 设置 `optimizeDeps.exclude` | 无 |
|
|
128
|
+
| `enforce` | `'pre'` | `'pre'` |
|
|
129
|
+
| 资源输出 | `generateBundle` 内 `emitFile` | 同 |
|
|
130
|
+
| 高级 API | 通过 `/rollup` 子路径获取 | 直接导出 |
|
|
131
|
+
|
|
132
|
+
## 5.7 调试构建问题
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
const plugin = miniThree({ debug: true, report: true });
|
|
136
|
+
// 构建后(在 CI 或插件宿主中)
|
|
137
|
+
console.log(plugin.api.report());
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
| 现象 | 查哪里 |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| three 里仍出现裸 `window` | `report.modulesScanned` 是否为 0 → 调整 `include`;检查 Vite 是否预打包 |
|
|
143
|
+
| 局部变量被误改 | `report.globalsSeen`;补 `tests/scope-rewrite.test.ts` 用例 |
|
|
144
|
+
| 解析报错 | `report.parseFailures`,考虑给 `rewrite` 加语法插件或 `exclude` 该模块 |
|
|
145
|
+
| worker/wasm 没进包 | `report.assetReferences` / `missingAssets`;补 `roots` |
|
|
146
|
+
| 包体过大 | 参照 `gameJsonSuggestion` 分包;`manualChunks` 见 [`examples/wechat-minigame/vite.config.ts`](../examples/wechat-minigame/vite.config.ts) |
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# 06 · 微信小游戏平台差异、已知坑与诊断
|
|
2
|
+
|
|
3
|
+
> 平台规范:[微信开放文档 · Adapter](https://developers.weixin.qq.com/minigame/dev/guide/runtime/adapter.html)、[渲染](https://developers.weixin.qq.com/minigame/dev/guide/base-ability/render.html)、[WXWebAssembly](https://developers.weixin.qq.com/minigame/dev/guide/performance/perf-webassembly.html)、[iOS 高性能模式](https://developers.weixin.qq.com/minigame/dev/guide/game-engine/unity-webgl-transform/Design/iOSOptimization.html),以及小游戏配置(game.json)说明。
|
|
4
|
+
|
|
5
|
+
## 6.1 运行时基本事实
|
|
6
|
+
|
|
7
|
+
| 事实 | 对本适配层的约束 |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| iOS = JavaScriptCore,Android = V8;**无 DOM/BOM**,无全局 `document`/`window` | 必须由 `MiniThreeScope` 提供 shim |
|
|
10
|
+
| 基础库不附带 DOM 兼容层,需由应用自行引入 | 适配层不假设宿主已存在任何兼容对象 |
|
|
11
|
+
| 首次 `wx.createCanvas()` 得到唯一**上屏画布**,后续均为离屏 | `getScreenCanvas()` 必须只调用一次并缓存;能力探测只能用 `createOffscreenCanvas` |
|
|
12
|
+
| `Canvas.getContext('webgl2')` 返回标准 WebGL2 上下文 | three ≥ r163 需要 WebGL2;默认 `defaultContextType: 'webgl2'` |
|
|
13
|
+
| `wx.setPreferredFramesPerSecond` 可锁帧 | `createWeChatGameRuntime({ preferredFps })` |
|
|
14
|
+
| 基础库 2.13.0+ `WXWebAssembly`,2.15.0+ Worker 内可用;支持 `.wasm` / `.wasm.br` | 插件 `brotli` 选项、资产分包 |
|
|
15
|
+
| Worker 并发上限 **1**,目录只能放 JS,分包需先 `preDownloadSubpackage` | 所有 worker/wasm 输出到一个 `outputDir` |
|
|
16
|
+
| iOS 高性能+ 建议用于 WebGL2 / 内存压力大的游戏 | `game.json` 的 `iOSHighPerformance+`;见 §6.5 |
|
|
17
|
+
|
|
18
|
+
## 6.2 导入顺序(最容易踩的坑)
|
|
19
|
+
|
|
20
|
+
ESM 静态导入会在模块体执行之前求值。若入口文件顶部写了 `import * as THREE from 'three'`,而 `createRuntime()` 在下面才执行,则 three 模块初始化期间读到的仍是占位作用域。
|
|
21
|
+
|
|
22
|
+
**推荐**:入口只导入适配层,用动态 import 加载场景:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createWeChatGameRuntime } from 'mini-three-adapter/wechat-game';
|
|
26
|
+
const runtime = await createWeChatGameRuntime();
|
|
27
|
+
const { startScene } = await import('./scene.js'); // scene.js 里才 import three
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
**兜底**:`createWeChatGameRuntime({ installGlobals: true })`,把 shim 显式挂到 `globalThis`(可逆),适合无法改导入结构的老项目。
|
|
31
|
+
|
|
32
|
+
诊断:占位作用域在真正取属性时会抛
|
|
33
|
+
`Scoped global "xxx" was read before a runtime was created`,直接提示上述两种解法。
|
|
34
|
+
|
|
35
|
+
## 6.3 已知坑位与处理
|
|
36
|
+
|
|
37
|
+
| 症状 | 原因 | 本项目处理 |
|
|
38
|
+
| --- | --- | --- |
|
|
39
|
+
| `createImageBitmap` 相关报错 | PC 小程序提供了该函数却没有原生 `Blob` | `scope.createImageBitmap = undefined`,插件 `forceUndef` 保证 three 走降级分支 |
|
|
40
|
+
| `PMREMGenerator.fromScene` 返回纯黑贴图 | 部分设备 WebGL 深度缓冲未清除 | 不在运行时改写 `WebGLRenderer.render`。应用层按需:每次 render 后 `renderer.clearDepth()`,或配置 `renderer.autoClearDepth`。见下方代码 |
|
|
41
|
+
| 开发者工具报 `Unexpected token` | `node_modules` 里用了较新语法 | 构建 `target: 'es2019'`(消除 `?.` / `??`);必要时开发者工具开启「将 JS 编译成 ES5」或加 Babel |
|
|
42
|
+
| 多指触摸卡死 / 包围盒历史数据报错 | 事件桥缓存的包围盒在多指场景失效 | `PointerBridge` 用 pointerId 状态机 + 单一缓存 rect,`touchcancel` 会清理指针 |
|
|
43
|
+
| `getExtension` 返回数字而非对象 | 部分 Android 基础库 | `normalizeWebGL: true`(默认)把数值/布尔归一成对象或 `null`,并补 `drawingBufferWidth/Height` |
|
|
44
|
+
| `instanceof HTMLCanvasElement` 为 false | wx canvas 不是 DOM 类实例 | `Symbol.hasInstance` + `WeakSet` 注册表 |
|
|
45
|
+
| 用 `new Proxy(canvas)` 后渲染异常 | 微信内部 WeakMap 按对象身份校验 | **禁止** Proxy / 克隆 / 改原型,只 `defineProperty`(ADR-0004) |
|
|
46
|
+
| 重复调用 `wx.createCanvas()` 导致黑屏 | 第二个画布是离屏的,不显示 | `getScreenCanvas()` 缓存;额外画布一律走 `createOffscreenCanvas` / `runtime.createCanvas()` |
|
|
47
|
+
| WebGPU 相关 API 报错 | 小游戏无 WebGPU | 插件 `webgpu` 策略;默认告警 |
|
|
48
|
+
| three 版本升级后控件失效 | r170+ 用 `three/addons/`,`outputColorSpace` 取代 `outputEncoding` | 示例与 `rendererHints` 使用新 API;插件 include 覆盖两种路径 |
|
|
49
|
+
|
|
50
|
+
深度缓冲补丁(应用层显式启用):
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
renderer.setAnimationLoop(() => {
|
|
54
|
+
renderer.render(scene, camera);
|
|
55
|
+
// 仅当遇到 PMREM / 后处理黑屏时开启,会有额外开销
|
|
56
|
+
if (needsDepthWorkaround) renderer.clearDepth();
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## 6.4 尺寸 / DPR / 安全区
|
|
61
|
+
|
|
62
|
+
- `windowInfo.pixelRatio = min(rawPixelRatio, pixelRatioCap)`,默认上限 2(避免 3~4 倍 DPR 造成 GPU 压力)。
|
|
63
|
+
- `runtime.on('resize', ...)` 里同步更新 `camera.aspect`、`renderer.setSize(w, h, false)`、`renderer.setPixelRatio(...)`。
|
|
64
|
+
- 小程序里 `getCanvasRect()` 通过 `createSelectorQuery().fields({node, rect, size})` 异步获取;`runtime.resize()` 会重新查询并更新事件桥的 rect 缓存。
|
|
65
|
+
- 若基础库没有 `wx.onWindowResize`,`WindowInfoStore` 会告警,业务需主动 `await runtime.resize()`。
|
|
66
|
+
- `safeArea` 在 `WindowInfo.safeArea` 中透出(若平台提供)。
|
|
67
|
+
|
|
68
|
+
## 6.5 包体、分包与高性能模式
|
|
69
|
+
|
|
70
|
+
- 官方文档标注单个主包/分包 ≤ 4MB、总包 ≤ 8MB(**以控制台当前额度为准**)。
|
|
71
|
+
- three 本体建议用 `manualChunks` 拆成独立 chunk 并放入分包;示例见 [`examples/wechat-minigame/vite.config.ts`](../examples/wechat-minigame/vite.config.ts)。
|
|
72
|
+
- `mini-three-assets.json` 会给出 `game.json` 建议:worker 目录设为 `{ path: 'assets/three', isSubpackage: true }`,并在创建 Worker 前调用 `wx.preDownloadSubpackage({ packageType: 'workers' })`。
|
|
73
|
+
- `.wasm.br` + Brotli 是官方推荐的减包手段。
|
|
74
|
+
- iOS 高性能模式(`iOSHighPerformance: true`)下内存限制更严,代码分包基本是必须的;高性能+(`iOSHighPerformance+: true`)把渲染移回微信进程,官方明确建议使用 WebGL2 且内存压力大的游戏开启,开启后需验证进程内存、渲染兼容性与帧耗时。
|
|
75
|
+
|
|
76
|
+
## 6.6 能力探测与降级
|
|
77
|
+
|
|
78
|
+
`runtime.report()` 输出:
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
mini-three-adapter capability report
|
|
82
|
+
platform : wechat-game
|
|
83
|
+
baseLibraryVersion : unknown
|
|
84
|
+
WebGL2 / WebGL1 : true / true
|
|
85
|
+
offscreenCanvas : true
|
|
86
|
+
worker / wasm : false / true (brotli: true)
|
|
87
|
+
nativeImage : true
|
|
88
|
+
triggerGC : true
|
|
89
|
+
getWindowInfo : true (resize events: true)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
- `probeContext()` 用 `wx.createOffscreenCanvas({type:'webgl2'})` 探测并主动 `WEBGL_lose_context` 释放,**不会**占用上屏画布。
|
|
93
|
+
- 探测结果可用 `capabilities` 选项覆盖(用于测试或已知机型分级)。
|
|
94
|
+
- `webgl2: false` 时会告警,但**不会静默降级到 WebGL1**——three ≥ r163 本来就要求 WebGL2,静默降级只会延后报错。
|
|
95
|
+
- `wx.createImage` 不存在时回退 `OffscreenCanvas.createImage()`;`triggerGC` 存在与否会影响 image 创建路径的选择。
|
|
96
|
+
|
|
97
|
+
## 6.7 诊断命令 / 日志
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
const runtime = await createWeChatGameRuntime({
|
|
101
|
+
logLevel: 'debug',
|
|
102
|
+
reporter: (level, message, payload) => myLogger(level, message, payload),
|
|
103
|
+
});
|
|
104
|
+
console.log(runtime.report());
|
|
105
|
+
runtime.on('contextlost', () => console.warn('WebGL context lost, rebuild resources'));
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`warnOnce(key, ...)` 保证每帧的重复问题只报一次;`plugin.api.report()` 给出构建期统计。
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# 07 · 接入与集成指南
|
|
2
|
+
|
|
3
|
+
> 面向「已有一个小游戏 / 小程序项目,现在要接入 3D 场景」的场景。本文给出从安装到真机验收的完整接入顺序,不涉及任何其他库。
|
|
4
|
+
|
|
5
|
+
## 7.1 接入前提
|
|
6
|
+
|
|
7
|
+
| 条件 | 说明 |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| 构建工具 | Vite 或 Rollup(构建插件需要 hook 到模块转换阶段) |
|
|
10
|
+
| three 版本 | `>= 0.163.0`,推荐 `0.187.x` |
|
|
11
|
+
| 运行环境 | 微信小游戏基础库支持 `getContext('webgl2')`;小程序使用 `<canvas type="webgl2">` |
|
|
12
|
+
| TypeScript | 推荐;`@types/three` 与项目 TS 版本配套 |
|
|
13
|
+
|
|
14
|
+
## 7.2 安装
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm i mini-three-adapter three
|
|
18
|
+
npm i -D vite @types/three
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`three` 是 optional peer,不会被打进适配层;业务项目自行决定版本。
|
|
22
|
+
|
|
23
|
+
## 7.3 配置构建插件
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// vite.config.ts
|
|
27
|
+
import { defineConfig } from 'vite';
|
|
28
|
+
import miniThree from 'mini-three-adapter/vite';
|
|
29
|
+
|
|
30
|
+
export default defineConfig({
|
|
31
|
+
plugins: [
|
|
32
|
+
miniThree({
|
|
33
|
+
webgpu: 'warn',
|
|
34
|
+
assets: { outputDir: 'assets/three', brotli: true },
|
|
35
|
+
roots: ['public/decoders'],
|
|
36
|
+
}),
|
|
37
|
+
],
|
|
38
|
+
build: {
|
|
39
|
+
target: 'es2019',
|
|
40
|
+
minify: false,
|
|
41
|
+
lib: { entry: 'src/main.ts', formats: ['es'], fileName: () => 'game.js' },
|
|
42
|
+
rollupOptions: {
|
|
43
|
+
output: {
|
|
44
|
+
entryFileNames: 'game.js',
|
|
45
|
+
chunkFileNames: 'chunks/[name]-[hash].js',
|
|
46
|
+
manualChunks(id) {
|
|
47
|
+
if (id.includes('/node_modules/three/')) return 'three';
|
|
48
|
+
return undefined;
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
要点:
|
|
57
|
+
|
|
58
|
+
- `target: 'es2019'` 让可选链 / 空值合并降级,避免开发者工具语法报错。
|
|
59
|
+
- `optimizeDeps.exclude` 由插件的 `config()` 自动设置,确保 AST 重写见到 three 的原始 ESM 模块图。
|
|
60
|
+
- `manualChunks` 把 three 拆成独立 chunk,便于放进分包。
|
|
61
|
+
- Rollup 项目改用 `import { miniThree } from 'mini-three-adapter/rollup'`。
|
|
62
|
+
|
|
63
|
+
## 7.4 入口改造(**最关键的一步**)
|
|
64
|
+
|
|
65
|
+
ESM 静态导入会在模块体执行前求值。three 及其 addons 在模块初始化时会读取作用域对象,因此必须**先创建 runtime,再让场景模块加载**:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// src/main.ts —— 只导入适配层,不在这里导入 three
|
|
69
|
+
import { createWeChatGameRuntime } from 'mini-three-adapter/wechat-game';
|
|
70
|
+
|
|
71
|
+
async function bootstrap(): Promise<void> {
|
|
72
|
+
const runtime = await createWeChatGameRuntime({
|
|
73
|
+
pixelRatioCap: 2,
|
|
74
|
+
logLevel: 'warn',
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
console.log(runtime.report());
|
|
78
|
+
|
|
79
|
+
const { startScene } = await import('./scene.js'); // scene.js 内才 import three
|
|
80
|
+
startScene(runtime);
|
|
81
|
+
|
|
82
|
+
runtime.on('dispose', () => console.info('runtime disposed'));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
void bootstrap().catch((error: unknown) => console.error('bootstrap failed', error));
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
// src/scene.ts
|
|
90
|
+
import * as THREE from 'three';
|
|
91
|
+
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
|
92
|
+
import type { MiniThreeRuntime } from 'mini-three-adapter';
|
|
93
|
+
|
|
94
|
+
export function startScene(runtime: MiniThreeRuntime): void {
|
|
95
|
+
const renderer = new THREE.WebGLRenderer(runtime.rendererHints);
|
|
96
|
+
renderer.setPixelRatio(runtime.windowInfo.pixelRatio);
|
|
97
|
+
renderer.setSize(runtime.windowInfo.width, runtime.windowInfo.height, false);
|
|
98
|
+
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
|
99
|
+
|
|
100
|
+
const scene = new THREE.Scene();
|
|
101
|
+
const camera = new THREE.PerspectiveCamera(
|
|
102
|
+
60, runtime.windowInfo.width / runtime.windowInfo.height, 0.1, 100,
|
|
103
|
+
);
|
|
104
|
+
camera.position.z = 3;
|
|
105
|
+
scene.add(new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshNormalMaterial()));
|
|
106
|
+
|
|
107
|
+
const controls = new OrbitControls(camera, renderer.domElement);
|
|
108
|
+
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, camera); });
|
|
109
|
+
|
|
110
|
+
runtime.on('resize', (info) => {
|
|
111
|
+
camera.aspect = info.width / info.height;
|
|
112
|
+
camera.updateProjectionMatrix();
|
|
113
|
+
renderer.setPixelRatio(info.pixelRatio);
|
|
114
|
+
renderer.setSize(info.width, info.height, false);
|
|
115
|
+
});
|
|
116
|
+
runtime.on('dispose', () => {
|
|
117
|
+
renderer.setAnimationLoop(null);
|
|
118
|
+
controls.dispose();
|
|
119
|
+
renderer.dispose();
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
若项目结构无法改成动态导入,可在创建 runtime 时打开 `installGlobals: true`,把 shim 显式挂到 `globalThis`;该注入是可逆的,`runtime.dispose()` 会还原。
|
|
125
|
+
|
|
126
|
+
## 7.5 小程序项目的额外接线
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// pages/index/index.ts
|
|
130
|
+
import { createWeChatMiniProgramRuntime, type MiniThreeRuntime } from 'mini-three-adapter';
|
|
131
|
+
|
|
132
|
+
Page({
|
|
133
|
+
runtime: null as MiniThreeRuntime | null,
|
|
134
|
+
|
|
135
|
+
async onReady(): Promise<void> {
|
|
136
|
+
const runtime = await createWeChatMiniProgramRuntime({
|
|
137
|
+
selector: '#gl',
|
|
138
|
+
selectorCtx: this, // 自定义组件内必须传组件实例
|
|
139
|
+
queryDelay: 0,
|
|
140
|
+
pixelRatioCap: 2,
|
|
141
|
+
});
|
|
142
|
+
this.runtime = runtime;
|
|
143
|
+
const { startScene } = await import('./scene.js');
|
|
144
|
+
startScene(runtime);
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
onTouch(event: WechatMiniprogram.TouchEvent): void {
|
|
148
|
+
this.runtime?.handleTouch(event);
|
|
149
|
+
},
|
|
150
|
+
|
|
151
|
+
onUnload(): void {
|
|
152
|
+
this.runtime?.dispose();
|
|
153
|
+
this.runtime = null;
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
```html
|
|
159
|
+
<!-- pages/index/index.wxml -->
|
|
160
|
+
<canvas
|
|
161
|
+
type="webgl2"
|
|
162
|
+
id="gl"
|
|
163
|
+
bindtouchstart="onTouch"
|
|
164
|
+
bindtouchmove="onTouch"
|
|
165
|
+
bindtouchend="onTouch"
|
|
166
|
+
bindtouchcancel="onTouch"
|
|
167
|
+
bindtap="onTouch"
|
|
168
|
+
/>
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
小游戏不需要这一步:`watchTouch` 会自动订阅 `wx.onTouch*`。
|
|
172
|
+
|
|
173
|
+
## 7.6 三端接线差异
|
|
174
|
+
|
|
175
|
+
| 平台 | runtime 工厂 | 触摸事件 | 画布来源 |
|
|
176
|
+
| --- | --- | --- | --- |
|
|
177
|
+
| 微信小游戏 | `createWeChatGameRuntime()` | 自动 | 唯一上屏画布,自动获取并缓存 |
|
|
178
|
+
| 微信小程序 | `createWeChatMiniProgramRuntime({ selector, selectorCtx })` | WXML 转发到 `handleTouch` | `createSelectorQuery` 异步取节点 |
|
|
179
|
+
| 浏览器 / H5 | `createBrowserRuntime({ canvas })` | 自动 | 真实 DOM canvas |
|
|
180
|
+
|
|
181
|
+
三端返回的都是同一个 `MiniThreeRuntime`,因此 `scene.ts` 可以完全复用。
|
|
182
|
+
|
|
183
|
+
## 7.7 分包与资源配置
|
|
184
|
+
|
|
185
|
+
构建后检查产物中的 `mini-three-assets.json`,把其中 `gameJsonSuggestion` 的内容合并到 `game.json`:
|
|
186
|
+
|
|
187
|
+
```json
|
|
188
|
+
{
|
|
189
|
+
"workers": { "path": "assets/three", "isSubpackage": true },
|
|
190
|
+
"subpackages": [{ "name": "three-assets", "root": "assets/three/" }]
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
- Worker 分包需要先调用 `wx.preDownloadSubpackage({ packageType: 'workers' })`,成功后再 `wx.createWorker()`。
|
|
195
|
+
- decoder 路径与 `manifest.decoderPaths` 保持一致,例如 `draco.setDecoderPath('assets/three/')`。
|
|
196
|
+
- `assets.brotli: true` 时会一并输出 `.wasm.br`,`WXWebAssembly.instantiate` 支持该后缀。
|
|
197
|
+
- `report.missingAssets` 中的条目需要业务把对应文件放进 `roots` 指定目录。
|
|
198
|
+
|
|
199
|
+
完整可运行工程见 [`examples/wechat-minigame/`](../examples/wechat-minigame/vite.config.ts)、[`examples/wechat-miniprogram/`](../examples/wechat-miniprogram/pages/index/index.wxml)、[`examples/h5/`](../examples/h5/index.html)。
|
|
200
|
+
|
|
201
|
+
## 7.8 接入检查清单
|
|
202
|
+
|
|
203
|
+
- [ ] 安装 `mini-three-adapter` + `three >= 0.163.0`,配置 `miniThree()` 插件。
|
|
204
|
+
- [ ] 入口改为「先 `createXxxRuntime()`,再动态 `import('./scene.js')`」。
|
|
205
|
+
- [ ] 渲染器使用 `runtime.rendererHints`、`setAnimationLoop`、`outputColorSpace`。
|
|
206
|
+
- [ ] 小程序 WXML 的 `bindtouch*` 转发到 `runtime.handleTouch`。
|
|
207
|
+
- [ ] `resize` / `visibilitychange` / `dispose` 事件都已接线并释放 three 资源。
|
|
208
|
+
- [ ] `game.json` 配好 worker 目录与分包,检查 `mini-three-assets.json` 的 `missingAssets` 为空。
|
|
209
|
+
- [ ] 构建报告 `plugin.api.report()` 中 `parseFailures` 为空、`webgpuWarnings` 已确认。
|
|
210
|
+
- [ ] 真机验证 WebGL2 出图、多指触摸、横竖屏切换、前后台恢复。
|
|
211
|
+
- [ ] 保存 `runtime.report()` 能力报告,登记到 [`docs/11-compat-matrix.md`](./11-compat-matrix.md)。
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# 08 · 扩展指南
|
|
2
|
+
|
|
3
|
+
> 面向人和 AI:三种最常见的扩展(新平台 / 新 polyfill / 新资源规则)各自的最小改动集与验收标准。
|
|
4
|
+
|
|
5
|
+
## 8.1 新增一个平台
|
|
6
|
+
|
|
7
|
+
**原则**:平台差异只允许出现在 `src/platforms/`。`core/` 不认识任何平台。
|
|
8
|
+
|
|
9
|
+
1. 在 `src/platforms/<name>.ts` 实现 `PlatformBinding`(`src/core/platform.ts`)。
|
|
10
|
+
2. 复用 `wechat-common.ts` 里能复用的部分;若新平台 API 差异大,就在 `wx-types.ts` 里补结构化类型或新建 `<name>-types.ts`。
|
|
11
|
+
3. 导出 `create<Name>Binding()` 与 `create<Name>Runtime()`(后者调用 `createRuntime(() => binding, options)`)。
|
|
12
|
+
4. 在 `src/index.ts` 导出;在 `package.json` 的 `exports` 加子路径。
|
|
13
|
+
5. 在 `Capabilities['platform']`(`src/types.ts`)加字面量;在 `docs/11-compat-matrix.md` 登记。
|
|
14
|
+
6. 补 `tests/<name>.test.ts`,用 mock 宿主验证:画布补丁、scope、触摸、resize、dispose。
|
|
15
|
+
7. 加 `examples/<name>/` 最小可运行示例。
|
|
16
|
+
|
|
17
|
+
模板:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import type { PlatformBinding } from '../core/platform';
|
|
21
|
+
import { createRuntime, type MiniThreeRuntime, type RuntimeOptions } from '../core/runtime';
|
|
22
|
+
import { detectCapabilities } from '../core/capabilities';
|
|
23
|
+
|
|
24
|
+
export function createFooBinding(options: FooOptions): PlatformBinding {
|
|
25
|
+
const host = resolveFoo(options.host);
|
|
26
|
+
return {
|
|
27
|
+
kind: 'browser', // 或扩展 Capabilities['platform'] 字面量
|
|
28
|
+
wx: undefined,
|
|
29
|
+
rawCanvas: host.canvas,
|
|
30
|
+
capabilities: detectCapabilities(host.wxLike, 'browser'),
|
|
31
|
+
imageFactory: createImageFactory(host.wxLike),
|
|
32
|
+
getCanvasRect: () => host.rect(),
|
|
33
|
+
createOffscreenCanvas: (w, h, type) => host.offscreen(w, h, type),
|
|
34
|
+
watchTouch: (handler) => host.onTouch(handler),
|
|
35
|
+
watchVisibility: (handler) => host.onVisibility(handler),
|
|
36
|
+
requestAnimationFrame: (cb) => host.raf(cb),
|
|
37
|
+
cancelAnimationFrame: (id) => host.caf(id),
|
|
38
|
+
now: () => host.now(),
|
|
39
|
+
dispose: () => host.close(),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createFooRuntime(options: FooOptions & RuntimeOptions = {}): Promise<MiniThreeRuntime> {
|
|
44
|
+
return createRuntime(() => createFooBinding(options), options);
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**验收**:`npm run check` 通过;`dispose()` 后所有监听被移除;`getCanvasRect()` 在尺寸变化后能通过 `runtime.resize()` 生效;不得调用 `wx.createCanvas()` 超过一次。
|
|
49
|
+
|
|
50
|
+
## 8.2 新增一个 polyfill / 全局 shim
|
|
51
|
+
|
|
52
|
+
three 报 `X is not defined` 或 `X is not a constructor` 时,按以下顺序改:
|
|
53
|
+
|
|
54
|
+
1. `src/polyfills/` 新建实现文件(自包含,不 import `core/*`)。
|
|
55
|
+
2. 在 `src/polyfills/index.ts` 导出。
|
|
56
|
+
3. 在 `src/scope.ts` 的 `MiniThreeScope` 接口里加字段,并加入 `GLOBAL_KEYS`(这样 `installGlobals()` 也会带上它)。
|
|
57
|
+
4. 在 `src/core/runtime.ts` 的 scope 组装区赋值(或按平台条件赋值)。
|
|
58
|
+
5. 在 `src/build/scope-rewrite.ts` 的 `DEFAULT_GLOBAL_NAMES` 加入标识符。
|
|
59
|
+
6. 补测试:`tests/polyfills.test.ts`(实现)+ `tests/scope-rewrite.test.ts`(改写)+ `tests/runtime.test.ts`(scope 中存在)。
|
|
60
|
+
7. 更新 `docs/04-api-reference.md` 与 `docs/03-module-map.md`。
|
|
61
|
+
|
|
62
|
+
> 若某个 API 在小程序里**不可用且必须让 three 走降级分支**,把值设为 `undefined` 并加入 `DEFAULT_FORCE_UNDEF`,不要伪造一个半实现(参考 `createImageBitmap`)。
|
|
63
|
+
|
|
64
|
+
## 8.3 新增 DOM 属性 / `instanceof` 支持
|
|
65
|
+
|
|
66
|
+
1. `src/core/element.ts` 的 `patchElement()`:加 `define(instance, key, descriptor)`。若需要响应式(随 rect 变化),用闭包 `rect` 的 getter。
|
|
67
|
+
2. canvas 专属属性放到 `src/core/canvas.ts` 的 `extra` 描述符里。
|
|
68
|
+
3. 若 three 用 `x instanceof SomeCtor` 判断,复用已有 `*Shim`,或 `createMockClass()` 新建一个并在补丁时加入 `instanceOf` 列表。
|
|
69
|
+
4. 若 three 用 `new SomeCtor()`,提供一个真正返回平台对象的构造器(参考 `createOffscreenCanvasCtor`)。
|
|
70
|
+
5. 补 `tests/runtime.test.ts` 断言。
|
|
71
|
+
|
|
72
|
+
**禁止**:`Object.setPrototypeOf`、Proxy 包装、返回克隆对象(会破坏微信内部 WeakMap 校验,见 ADR-0004)。
|
|
73
|
+
|
|
74
|
+
## 8.4 新增资源类型 / override 规则
|
|
75
|
+
|
|
76
|
+
1. `src/build/assets.ts`:
|
|
77
|
+
- `ASSET_PATTERN` 加入新扩展名;
|
|
78
|
+
- `DECODER_KEYWORDS` 加入新关键字;
|
|
79
|
+
- `defaultRoots()` 加入该库的资源目录;
|
|
80
|
+
- `classify()` 加入新 kind;
|
|
81
|
+
- `decoderPaths` 生成逻辑加入新 key。
|
|
82
|
+
2. 若某个 addon 需要替换 import 路径,在 `src/build/plugin-core.ts` 的 `transform` 里加一条**显式、可配置、可关闭**的映射规则,并写进 `docs/05`。不要做成隐式全局替换。
|
|
83
|
+
3. 在 `tests/plugin.test.ts` 加资产扫描用例。
|
|
84
|
+
4. 更新 `examples/*/vite.config.ts` 的 `roots` 示例与 `docs/05`。
|
|
85
|
+
|
|
86
|
+
## 8.5 新增构建期能力
|
|
87
|
+
|
|
88
|
+
- 新 hook 放在 `src/build/plugin-core.ts`;保持 Rollup/Vite 双兼容(只用 `transform` / `resolveId` / `generateBundle` / `config`)。
|
|
89
|
+
- 所有新行为都要有对应**开关**与默认值,且默认不得改变已有产物语义。
|
|
90
|
+
- 统计信息加入 `BuildReport`,方便 CI 与 AI 读取。
|
|
91
|
+
- 参考 ADR 流程:若改变架构不变量,先写 `docs/adr/NNNN-*.md`。
|
|
92
|
+
|
|
93
|
+
## 8.6 扩展的评审清单
|
|
94
|
+
|
|
95
|
+
- [ ] 是否违反 [架构不变量](./02-architecture.md#25-架构不变量ai-必读不得破坏)?
|
|
96
|
+
- [ ] `src/` 是否引入了 `three` 的运行时 import?
|
|
97
|
+
- [ ] 新订阅 / 定时器 / 全局写入是否都登记到 `disposers`?
|
|
98
|
+
- [ ] 是否新增了同步 `wx.createCanvas()` 调用?
|
|
99
|
+
- [ ] 类型是否 strict 通过(`noUncheckedIndexedAccess`)?
|
|
100
|
+
- [ ] 行为是否可被测试(能注入 mock 宿主)?
|
|
101
|
+
- [ ] `docs/03`、`docs/04`、`CHANGELOG.md` 是否同步?
|