@taptap/maker 0.0.37-beta.3 → 0.0.37-beta.5

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.
@@ -0,0 +1,143 @@
1
+ # 转换规范与用例
2
+
3
+ ## 1. 从活动入口建立范围
4
+
5
+ ### 1.1 先确定项目显示契约
6
+
7
+ 转换前读取游戏根目录的 `.project/project.json`。优先使用
8
+ `taptap_publish.screen_orientation` 判断 `landscape` / `portrait`,再从项目 UI 根节点、屏幕布局包装或
9
+ `scripts/` 中确认设计宽高。项目配置是预览和导出验收的输入,不是可选备注:横屏项目的页面根节点通常应为
10
+ `1920×1080` 一类的宽屏尺寸,不能直接套用编辑器的竖屏默认值。若配置缺失或损坏,报告中明确标记,保留人工确认,不要静默猜测。
11
+
12
+ 沿路由、页面创建和 `UI.SetRoot` 等真实调用追踪,阅读直接依赖的 UIFactory、Theme、ScreenLayout 和 UI 加载包装。记录:
13
+
14
+ | 源页面 / 调用 | 输出文件 | 初始状态 | 动态部分 / 不支持部分 |
15
+ | ----------------------- | -------------------------- | ---------------- | --------------------- |
16
+ | 示例:Settings.CreateUI | assets/ui/settings.ui.json | 默认关闭确认弹窗 | 点击、音量数据留 Lua |
17
+
18
+ 目录名为 legacy/debug 不等于未使用;以调用关系为证据。不运行未知 Lua 来“自动求值”。
19
+ 初始化后的 `SetStyle`、`SetText`、`AddChild` 会改变最终树,不能只翻译第一段构造代码。
20
+ 已有导出还要对照路由与源码差异:文件名未变不代表绘制入口未变,共享主题和子状态页面也属于依赖。
21
+ 逐页核对背景、装饰、固定控件、文字、动态容器和弹层;清单只登记实际输出的文件。
22
+
23
+ ## 2. 拆分边界
24
+
25
+ - 页面壳:背景、固定控件、空动态容器、弹层挂点。
26
+ - 组件:已有明确复用边界时提取;同图片出现两次不构成强制抽象理由。
27
+ - 动态模板:列表行、关卡格子等单个实例的结构。数量、排序、刷新、状态仍由 Lua 决定。
28
+ - 固定菜单、配置页签、固定格位应按原布局输出;不能把所有 Lua 循环都当成存档驱动的动态列表。
29
+ - 行为:回调、绑定、动画、游戏数据、运行时插入留在 Lua。NanoVG 的纯绘图层可以按
30
+ [NanoVG 指引](nanovg.md) 提取为绘制指令;不能把任意绘图函数或动态行为序列化成字符串。
31
+
32
+ 默认提取不修改 Lua。明确说明游戏尚未消费 JSON。接入模式才替换视觉构造代码,不能留下新旧两棵重叠树。
33
+
34
+ ## 3. 坐标、默认值与资源
35
+
36
+ - 设计尺寸从项目配置和布局包装推导。保留视口根与设计内容层的区别,不重复应用缩放。
37
+ - 百分比、flex、最小/最大尺寸、定位参照父节点保持原义。不得将一次运行的测量值当通用布局。
38
+ - 只移除已证明由调用方继续负责的外层包装。说明安全区、缩放、居中由哪一层承担。
39
+ - 核对工厂和主题的最终默认值,尤其 Label/Button padding、字号、文字颜色、背景和边框。显式保存视觉必需值,但不凭空改设计。
40
+ - 图片为相对 `assets/` 的游戏资源路径,例如 `image/button.png`。保留大小写和中文,不能用编辑器域名、机器绝对路径或临时 blob URL。
41
+ - 保持透明底 `false`、显隐和裁切;不要为了预览“更完整”改变它们。
42
+ - 九宫格只在源实现确实使用时保存为 `backgroundFit: "sliced"` 和 `[上,右,下,左]`,不能由文件名推断数值。
43
+ - 原项目如果使用 UUID、资源元文件或字体资源,沿原索引核对,不伪造 `.meta`。脚本不检查这些索引。
44
+ - 颜色转换先核对源通道范围:0..1 与 0..255 不能混用。透明度和字体单位也不能只换字段名。
45
+ - 使用目标 Widget 支持的属性名,例如 `borderRadius`、`fontColor`;源绘图函数的参数名不能直接当作 Widget 属性。将绝对绘图坐标放进子节点时须减去父级原点,组件实例的尺寸不能任意缩小而保留原子节点坐标。
46
+
47
+ 节点格式是 `type` + 属性 + `children`。复用源 ID;需要行为绑定的节点补稳定 ID。
48
+ 同一个加载实例内 ID 唯一;独立加载的模板实例可以重复内部 ID,查找时必须使用正确实例。
49
+ 不要写 `_uid`、`_rect` 等编辑器缓存字段。
50
+
51
+ ## 4. 静态页面示例
52
+
53
+ 源代码(假设项目这里直接使用这些 Widget 属性,无额外工厂默认值):
54
+
55
+ ```lua
56
+ local root = UI.Panel { width = 720, height = 1280 }
57
+ local back = UI.Button {
58
+ id = "back", position = "absolute", left = 24, top = 32,
59
+ width = 96, height = 48, text = "Back",
60
+ onClick = function() NavigateBack() end
61
+ }
62
+ root:AddChild(back)
63
+ ```
64
+
65
+ 对应 `assets/ui/example.ui.json`:
66
+
67
+ ```json
68
+ {
69
+ "type": "Panel",
70
+ "width": 720,
71
+ "height": 1280,
72
+ "children": [
73
+ {
74
+ "type": "Button",
75
+ "id": "back",
76
+ "position": "absolute",
77
+ "left": 24,
78
+ "top": 32,
79
+ "width": 96,
80
+ "height": 48,
81
+ "text": "Back"
82
+ }
83
+ ]
84
+ }
85
+ ```
86
+
87
+ 这里的 720×1280 只是示例,不是约束。接入时按项目加载包装加载文件,检查返回值,
88
+ 使用该实例 `Find("back")` 重新绑定回调。具体绑定 API 以项目 Widget/加载器为准。
89
+ 验收:改 JSON 后游戏确实变化;返回按钮只触发一次;重复进入和销毁无重复订阅。
90
+
91
+ ## 5. 动态列表示例
92
+
93
+ 源代码:
94
+
95
+ ```lua
96
+ for _, item in ipairs(items) do
97
+ list:AddChild(CreateItemRow(item))
98
+ end
99
+ ```
100
+
101
+ 页面只保留有 ID 的列表容器及原布局。行结构输出为 `assets/ui/item_row.ui.json`:
102
+
103
+ ```json
104
+ {
105
+ "type": "Panel",
106
+ "width": 280,
107
+ "height": 64,
108
+ "children": [{ "type": "Label", "id": "title", "text": "$title:Sample" }]
109
+ }
110
+ ```
111
+
112
+ 运行时仍由 Lua 循环加载行模板、传入 props 并挂到容器。不要把 items 的现有存档内容烘焙成固定 children。
113
+ 单独模板中内部 ID `title` 可重复出现在不同实例,通过 row 实例查找。
114
+
115
+ 重要:本次核对的 UILoader 仅在 `LoadFromFile(resourceId, props)` 提供 props 时执行参数替换。
116
+ `UI.LoadJSON("ui/item_row.ui.json")` 不可假定会展开默认值;通常需要传 `{}` 或真实参数,
117
+ 但应先阅读目标项目的 `UI.LoadJSON` 包装确认语义。缺参数不能靠编辑器看起来正常来放行。
118
+
119
+ 验收至少覆盖空列表、单条、多条、长文字;空页面容器是预期,不是丢 UI。
120
+
121
+ 导出后必须重新运行检查脚本,并按项目配置打开编辑器预览。至少逐页确认:根尺寸方向、页面壳、模板引用、资源引用和预期空态。
122
+ `$repeat` 的预览实例只是编辑器辅助,不代表引擎已经拿到业务数据;报告要区分“静态结构正确”和“运行时列表已验证”。
123
+
124
+ ## 6. 自定义组件和 Slot
125
+
126
+ 注册组件需要目标引擎的 `RegisterComponent` 及相应模板资源。
127
+ 核对根 props 合并、默认值和命名/默认 Slot 的替换规则;不要猜测自定义 type 是内置控件。
128
+
129
+ 当前浏览器预览不是完整的组件注册与 Slot 运行时。优先保留真实类型并报告预览限制,
130
+ 打开模板本身检查样式;不要为消除预览警告把组件改成 Panel。
131
+ 模板文件是独立视觉真源;只有明确授权且有消费链路时才引入组件注册。
132
+
133
+ ## 7. 交付检查用例
134
+
135
+ | 场景 | 应有结果 |
136
+ | ---------------------- | --------------------------------------------- |
137
+ | 已有 JSON 被用户改过 | 对照差异,保留编辑,不全量重新生成覆盖 |
138
+ | 源节点初始化后设置图片 | 输出包含最终静态图片;动态切图逻辑仍留 Lua |
139
+ | 隐藏弹窗 | 保持隐藏,另行验证显示状态,不默认展开 |
140
+ | 多宽高比 flex 布局 | 保留约束,不用单一截图坐标替代 |
141
+ | 缺图、重复 ID | 检查报错,定位文件和 JSON Pointer,修复后重跑 |
142
+ | 未注册自定义控件 | 区分引擎注册缺失与编辑器不支持,不能静默降级 |
143
+ | UI 只是提取未接入 | 交付明确“只影响编辑器”;不声称游戏已使用 |
@@ -0,0 +1,74 @@
1
+ # 检查与预览排错
2
+
3
+ ## 检查范围
4
+
5
+ 从 skill 目录运行(替换游戏路径):
6
+
7
+ ```bash
8
+ node scripts/check-ui.cjs --project "/path/to/game" --format json
9
+ node scripts/check-ui.cjs --project "/path/to/game" --file assets/ui/settings.ui.json
10
+ ```
11
+
12
+ 扫描 `assets/` 内 `.ui.json`,不处理 `.ui.json.meta`;不会写任何项目文件。
13
+ 文件上限 4 MiB,单文档最多 10000 节点、深度 128;超过限制不是通过。
14
+ 目录符号链接不递归,报告警告。显式文件和资源不能越出 assets。
15
+
16
+ 退出码:`0` 执行的规则无错误,`1` 有文档错误或无 UI,`2` 参数/环境失败。
17
+ 使用 `--format json` 时,成功扫描后的结果输出到 stdout;环境失败信息在 stderr。
18
+ 一个 JSON 解析失败不会阻止检查其他可读文件。
19
+
20
+ 已检查:
21
+
22
+ - JSON 可解析、节点对象、type 非空、children 为数组。
23
+ - 同文档静态 ID 重复、内部字段、回调字段。
24
+ - 部分布局数值与枚举、显隐布尔值、透明度、九宫格数组。
25
+ - 图片与 `$repeat.template` 路径安全和文件存在。
26
+ - `.project/project.json` 的屏幕方向;页面根宽高与项目方向一致性。
27
+ - `assets/ui/ui-export-manifest.ui.json` 的页面、组件、模板清单覆盖;目录中未登记文件会提示清单可能过期,清单登记的缺失文件会报错。
28
+
29
+ 未全面检查:引擎字段全集、主题默认值、布局/字体度量、图片解码、meta/字体索引、组件/Slot 展开、
30
+ Lua 行为绑定、源页面覆盖、JSON 重复键以及引擎画面等价。
31
+ 模板参数、编辑器专属 `$repeat` 和非基础控件会提示人工核对。
32
+ 未知字段不等于受支持字段,不报错不表示语义正确。
33
+
34
+ 浏览器“检查 UI”使用相同规则,但只检查**当前内存文档**,资源存在性依据项目资源索引。
35
+ 点击问题可定位源节点;复制诊断报告给 AI。它不替代全项目检查,也不会自动保存修改。
36
+
37
+ ## 报告如何处理
38
+
39
+ 诊断包含 `code`、`severity`、`file`、`pointer`、`message`。
40
+ 例如 `/children/2/backgroundImage` 是 JSON Pointer,不是第 2 行代码。
41
+ 修复时根据文件与指针定位,再核对源 Lua;不要只按错误码批量替换。
42
+
43
+ | 现象 / 代码 | 先检查 | 修复边界 |
44
+ |---|---|---|
45
+ | UI_NO_FILES | 选的是包含 assets 的游戏根目录吗? | 无文件才走提取;不要扫描 meta 当 UI |
46
+ | UI_JSON_PARSE | 编码、尾逗号、文件截断、大小 | 修复合法 JSON,保留用户原修改 |
47
+ | UI_RESOURCE_MISSING/PATH | assets 相对路径、大小写、文件是否随项目存在 | 不改为网站路径或复制别的项目图片凑数 |
48
+ | `UI_COMPONENT_MISSING/TYPE` | `component` 相对路径、组件文件是否存在、根 props 覆盖规则 | 先修引用或核对组件注册;不要把组件静默降级成 Panel |
49
+ | UI_DUPLICATE_ID | 同一实例的行为绑定目标 | 修改 ID 同时对照调用方;跨实例不盲目改名 |
50
+ | UI_LENGTH/ENUM | 源布局和目标加载器支持 | 不随意把百分比改成固定像素 |
51
+ | UI_TEMPLATE_CONTEXT | 调用 props、默认值、实际加载模式 | 编辑器默认值显示正常不代表 Lua 正常 |
52
+ | UI_PREVIEW_TYPE | 组件注册、模板、Slot 和引擎版本 | 预览不支持与引擎不支持分开报告 |
53
+ | UI_EDITOR_REPEAT | 是否已有运行时循环实例化 | 保留 Lua 数据驱动,不把预览列表当引擎能力 |
54
+ | 无报错但画面空 | 根尺寸、祖先显隐/裁切、opacity、动态内容 | 先判断预期状态,再修确定的错误 |
55
+ | `UI_PROJECT_CONFIG_MISSING/PARSE` | 项目根目录、`.project/project.json` 编码和 JSON 结构 | 补齐或修复配置后重跑;未确认方向时不要交付视觉结论 |
56
+ | `UI_DESIGN_ORIENTATION` | 页面根 `width/height` 与 `screen_orientation` | 回到源布局确认设计尺寸;不要只交换宽高掩盖坐标语义 |
57
+ | `UI_MANIFEST_STALE/MISSING_FILE/PARSE` | 导出 manifest 与 `assets/ui` 实际文件 | 先确认是否为旧导出或有意未发布;不要为了消除警告删除模板 |
58
+ | 页面缺部分控件 | 工厂默认值、初始化后的 AddChild/SetStyle | 补遗漏的静态结构,不展开业务运行态 |
59
+ | 文字换行/大小差异 | 字体资源、主题、字号单位、父容器约束 | 保留字体度量差异说明,需运行时对照 |
60
+ | 改 JSON 不影响游戏 | 活动入口是否仍创建旧 Lua 树 | 明确尚未接入,取得授权后迁移 |
61
+ | 图片索引存在但画布裂图 | 图片解码、格式、预览控制台 | 归类资源解码或编辑器问题,不伪造路径 |
62
+
63
+ ## 最小交付报告
64
+
65
+ ```text
66
+ 模式:仅提取 / 检查 / 诊断 / 已接入
67
+ 活动页面及输出:源文件 -> UI 文件(含未覆盖的页面及原因)
68
+ 静态检查:检查 N 文件,E 错误,W 警告;附命令及原始报告位置
69
+ 警告处理:每类问题的判断,不能直接删除警告
70
+ 编辑器:实际打开哪些页面/模板,检查哪些状态
71
+ 引擎:实际运行哪些状态;未运行明确说明
72
+ 仍留 Lua:行为、动画、动态节点和自绘
73
+ 下一步:需要用户操作或尚未验证的范围
74
+ ```
@@ -0,0 +1,109 @@
1
+ # NanoVG 提取与回放
2
+
3
+ NanoVG 是即时绘制 API,原 Lua 函数没有可直接序列化的控件树。
4
+ 编辑器用 NanoVG 节点保存命名图层内的绘制指令,保留原始坐标、曲线、渐变和绘制顺序。
5
+ 这是视觉数据,不是 Lua 程序,不会自动提取业务热区或动画。
6
+
7
+ ## 文档格式
8
+
9
+ ```json
10
+ {
11
+ "type": "NanoVG",
12
+ "id": "border",
13
+ "position": "absolute",
14
+ "left": 20,
15
+ "top": 30,
16
+ "width": 240,
17
+ "height": 160,
18
+ "viewBox": [0, 0, 240, 160],
19
+ "commands": [
20
+ ["beginPath"],
21
+ ["roundedRect", 2, 2, 236, 156, 12],
22
+ ["fillPaint", { "kind": "linearGradient", "args": [0, 0, 240, 160, "#164e63", "#22a899"] }],
23
+ ["fill"],
24
+ ["strokeColor", "#a7f3d0"],
25
+ ["strokeWidth", 2],
26
+ ["stroke"]
27
+ ]
28
+ }
29
+ ```
30
+
31
+ 节点可与 Panel、Label、Button 混用。viewBox 定义局部坐标;改节点尺寸会整体缩放,
32
+ 不重算原绘图函数。背景样式写在指令中;通用节点属性控制布局、透明度、变换。
33
+ 节点树中的 NanoVG 类型名使用青色区分,不添加重复后缀,也不改文档 ID。
34
+ 属性面板点击「应用」后一次进入撤销历史;CLI ui patch 用 set 修改 commands/viewBox,
35
+ 沿用 revision 冲突保护和原子保存。
36
+
37
+ ui capabilities --json 列出完整指令签名。每条指令为数组,第一项是去掉 nvg 前缀的 API 名,
38
+ 其余参数去掉 context。颜色是 0..255 RGBA 数组或 #RRGGBB / #RRGGBBAA。
39
+ paint 使用 {kind,args},支持 linearGradient、radialGradient、imagePattern;
40
+ 图片画刷的第六个参数是 assets 相对资源路径,不保存原生 image handle。
41
+ 单层最多 20000 条指令,save/restore 必须配对且最多嵌套 32 层;调用方仍须为外围 UI 保留原生栈空间。
42
+
43
+ ## 从 Lua 提取
44
+
45
+ 1. 读取活动页面及绘图函数,确认设计尺寸。按已有面板、装饰、标题等函数划分命名图层,
46
+ 保留稳定 ID;不要将整个游戏压成不可分选的截图。
47
+ 2. 使用 [MakerNanoVG.lua](../runtime/MakerNanoVG.lua),或通过 ui nanovg-adapter 取得同一源码。
48
+ 默认先在受控测试入口验证,不覆盖已有同名脚本。
49
+ 3. 在已创建字体/资源、已开始的 NanoVG 帧内,对审阅过的同步函数调用 capture。
50
+ 它临时包装全局 nvg 函数,结束或异常时恢复,不能跨协程、跨帧或嵌套执行。
51
+
52
+ ```lua
53
+ local Vector = require("ui.MakerNanoVG")
54
+ local layer = Vector.capture(vg, {
55
+ id = "gothic_panel", width = 760, height = 460, left = 120, top = 100,
56
+ images = { [nativeImage] = "image/panel.png" }, -- 仅用到已有图片时提供
57
+ fonts = { [fontId] = "sans" }, -- 仅用到 FontFaceId 时提供
58
+ }, function()
59
+ Theme.DrawPanel(vg, 12, 12, 730, 420, 0.9)
60
+ end)
61
+ -- 用项目已有 cjson/资源写入方式输出 layer 或装入页面 children。
62
+ ```
63
+
64
+ capture 从默认绘图状态和局部坐标开始,结束恢复原状态。回调内应设置颜色、画刷、字号,
65
+ 不能依赖外层 transform、scissor 或隐含样式。已有图片/字体句柄须提供映射;
66
+ 颜色和画刷在回调内创建。资源创建、销毁、未知 API 或无法映射的句柄会导致捕获失败。
67
+ 可分离资源初始化与绘图后再提取,不能自动改写游戏业务逻辑来强行通过。
68
+
69
+ 用 ui create --input-file 将结果写到新文件,检查后显式生成 meta。已有文档沿用 revision 比较,
70
+ 不重新生成覆盖编辑结果。逐层检查缩放、文字、裁剪,说明捕获的动态状态,不推断其他状态已覆盖。
71
+ 捕获前核对真实入场参数与动画终态,避免把尚未淡入的透明层误当作空页面。
72
+ 若只提取某个初态,在文档中记录 `exportState`;多阶段页面按实际子状态分别检查。
73
+ 存档数据区保持真实空态,另保留模板与绑定边界;不要伪造玩家数据填满页面。
74
+ 拆分捕获结果时保留绘制顺序和进入每层时的颜色、字体、变换、裁剪状态,不能在未配对的 save/restore 中间切层。
75
+
76
+ ## 引擎接入
77
+
78
+ 仅提取时保留游戏入口。明确接入时才替换原绘制调用,不能新旧重复绘制。
79
+ 原始 NanoVG 项目在现有 NanoVGRender / BeginFrame / EndFrame 中回放已解析节点:
80
+
81
+ ```lua
82
+ -- resolveImage(path, ctx) 复用项目图片缓存,返回原生句柄。
83
+ Vector.draw(vg, layer, layer.left, layer.top, layer.width, layer.height, resolveImage)
84
+ ```
85
+
86
+ draw 只画一个图层,不遍历普通 UI 节点,不管理帧、字体、资源、事件或存档。
87
+ 直接调用时由游戏负责显隐、动画、外围变换及热区,不能让图层移位后热区仍留在旧坐标。
88
+
89
+ 使用 urhox-libs/UI 时,在项目原 UI.LoadJSON 流程之前注册一次:
90
+
91
+ ```lua
92
+ local UI = require("urhox-libs/UI")
93
+ local Vector = require("ui.MakerNanoVG")
94
+ Vector.register(UI, resolveImage)
95
+ ```
96
+
97
+ 注册复用 Widget 的布局、变换与树遍历;仍须绑定交互。新增 JSON 不证明引擎已接入。
98
+ 字体名称由项目在当前 context 中创建,不能把浏览器兜底字体当原生字体。
99
+
100
+ ## 限制与验收
101
+
102
+ 支持路径、圆角/圆/椭圆/弧、贝塞尔曲线、描边、线性/径向渐变、图片画刷、单行及 textBox 多行文字、变换及裁剪。
103
+ textBox 指令为 `["textBox", x, y, width, text]`,宽度大于 0;浏览器按字体度量换行,保留显式换行,原生回放调用 nvgTextBox。
104
+ 未列入白名单的调用(箱形渐变、pathWinding 孔洞、混合、fontBlur、reset 系列等)
105
+ 会报错;不能删指令、用矩形或截图来掩盖差异。
106
+ Canvas 2D 与 NanoVG 的字体度量、抗锯齿、非等比描边、旋转裁剪可能不同。
107
+ 浏览器图片画刷暂按重复采样预览,原生图片边缘/重复模式由项目 image flags 决定。
108
+ 分别报告静态检查、浏览器视觉、Lua 调用测试和真实引擎视觉/交互验收。
109
+ 模拟 nvg 函数的捕获/回放测试不能代替真实引擎验收。
@@ -0,0 +1,289 @@
1
+ -- Maker NanoVG data adapter. No Lua source is stored in UI documents.
2
+ -- capture() is an explicit, synchronous development operation; hooks never survive it.
3
+ local M = {}
4
+ local unpack = table.unpack or unpack
5
+ local active = false
6
+ local signatures = {
7
+ save = "", restore = "", beginPath = "", closePath = "", fill = "", stroke = "",
8
+ moveTo = "nn", lineTo = "nn", bezierTo = "nnnnnn", quadTo = "nnnn", arcTo = "nnnnn",
9
+ rect = "nnnn", roundedRect = "nnnnn", roundedRectVarying = "nnnnnnnn",
10
+ circle = "nnn", ellipse = "nnnn", arc = "nnnnnn",
11
+ translate = "nn", scale = "nn", rotate = "n", skewX = "n", skewY = "n", transform = "nnnnnn",
12
+ scissor = "nnnn", intersectScissor = "nnnn",
13
+ fillColor = "c", strokeColor = "c", fillPaint = "p", strokePaint = "p",
14
+ strokeWidth = "n", miterLimit = "n", lineCap = "n", lineJoin = "n", globalAlpha = "n",
15
+ fontSize = "n", fontFace = "s", textAlign = "n", textLetterSpacing = "n", text = "nns", textBox = "nnns",
16
+ }
17
+ local paints = { linearGradient = "nnnncc", radialGradient = "nnnncc", imagePattern = "nnnnnsn" }
18
+
19
+ local function finite(n) return type(n) == "number" and n == n and math.abs(n) < math.huge end
20
+ local function color(value)
21
+ if type(value) == "string" then
22
+ assert((#value == 7 or #value == 9) and value:match("^#%x+$"), "Invalid NanoVG color")
23
+ return { tonumber(value:sub(2, 3), 16), tonumber(value:sub(4, 5), 16),
24
+ tonumber(value:sub(6, 7), 16), #value == 9 and tonumber(value:sub(8, 9), 16) or 255 }
25
+ end
26
+ assert(type(value) == "table" and #value == 4, "Expected RGBA color")
27
+ for i = 1, 4 do assert(finite(value[i]) and value[i] >= 0 and value[i] <= 255, "Invalid color channel") end
28
+ return value
29
+ end
30
+
31
+ local function validateArgs(args, sig)
32
+ assert(type(args) == "table" and #args == #sig, "Invalid NanoVG argument count")
33
+ for i = 1, #sig do
34
+ local kind, value = sig:sub(i, i), args[i]
35
+ if kind == "n" then assert(finite(value), "Expected finite NanoVG number")
36
+ elseif kind == "s" then assert(type(value) == "string", "Expected NanoVG string")
37
+ elseif kind == "c" then color(value)
38
+ else
39
+ assert(type(value) == "table" and paints[value.kind], "Unsupported NanoVG paint")
40
+ validateArgs(value.args, paints[value.kind])
41
+ end
42
+ end
43
+ end
44
+
45
+ local function validate(node)
46
+ assert(type(node) == "table" and node.type == "NanoVG", "Expected NanoVG node")
47
+ validateArgs(node.viewBox, "nnnn")
48
+ assert(node.viewBox[3] > 0 and node.viewBox[4] > 0, "Invalid NanoVG viewBox")
49
+ assert(type(node.commands) == "table" and #node.commands <= 20000, "Too many NanoVG commands")
50
+ local depth = 0
51
+ for _, cmd in ipairs(node.commands) do
52
+ assert(type(cmd) == "table" and signatures[cmd[1]], "Unsupported NanoVG command: " .. tostring(cmd[1]))
53
+ local args = {}; for i = 2, #cmd do args[#args + 1] = cmd[i] end
54
+ validateArgs(args, signatures[cmd[1]])
55
+ if cmd[1] == "textBox" then assert(args[3] > 0, "Text box width must be positive") end
56
+ if cmd[1] == "save" then depth = depth + 1 end
57
+ if cmd[1] == "restore" then depth = depth - 1 end
58
+ assert(depth >= 0 and depth <= 32, "Unbalanced NanoVG state stack (layer limit: 32)")
59
+ end
60
+ assert(depth == 0, "Unbalanced NanoVG state stack")
61
+ end
62
+ M.validate = validate
63
+
64
+ -- opts.images maps existing native image handles to assets-relative resource paths.
65
+ -- opts.fonts maps existing font IDs to names. Unknown APIs/opaque paints fail capture.
66
+ function M.capture(ctx, opts, draw)
67
+ assert(not active, "Nested NanoVG capture is not supported; capture separate named layers")
68
+ assert(type(opts) == "table" and type(draw) == "function", "capture requires options and a draw function")
69
+ local node = { type = "NanoVG", id = opts.id, position = "absolute", left = opts.left or 0,
70
+ top = opts.top or 0, width = opts.width, height = opts.height,
71
+ viewBox = opts.viewBox or { 0, 0, opts.width, opts.height }, commands = {} }
72
+ local originals, colors, paintValues = {}, {}, {}
73
+ local images, fonts = opts.images or {}, opts.fonts or {}
74
+ local depth, failure = 0, nil
75
+ local function remember(op, args)
76
+ assert(#node.commands < 20000, "NanoVG command limit exceeded")
77
+ local cmd = { op }; for _, value in ipairs(args) do cmd[#cmd + 1] = value end
78
+ node.commands[#node.commands + 1] = cmd
79
+ end
80
+ local function capturedColor(value)
81
+ assert(colors[value], "Color was created outside capture; create it inside the draw callback")
82
+ return colors[value]
83
+ end
84
+ local function wrap(name, fn)
85
+ if originals[name] then
86
+ _G[name] = function(...)
87
+ local result = { pcall(fn, ...) }
88
+ if not result[1] then failure = tostring(result[2]); error(failure) end
89
+ return unpack(result, 2)
90
+ end
91
+ end
92
+ end
93
+ for name, fn in pairs(_G) do
94
+ if type(fn) == "function" and name:match("^nvg[A-Z]") then originals[name] = fn end
95
+ end
96
+ assert(originals.nvgSave and originals.nvgRestore and originals.nvgReset, "NanoVG context is unavailable")
97
+ originals.nvgSave(ctx)
98
+ active = true
99
+ -- Refuse unrecorded drawing instead of returning a visually incomplete success.
100
+ for name in pairs(originals) do
101
+ local api = name
102
+ _G[api] = function()
103
+ failure = "Unsupported NanoVG capture API: " .. api
104
+ error(failure)
105
+ end
106
+ end
107
+ for op, sig in pairs(signatures) do
108
+ local operation, signature = op, sig
109
+ local name = "nvg" .. op:sub(1, 1):upper() .. op:sub(2)
110
+ wrap(name, function(vg, ...)
111
+ assert(vg == ctx, "A capture may only use its own NanoVG context")
112
+ local args = { ... }
113
+ for i = 1, #signature do
114
+ local kind = signature:sub(i, i)
115
+ if kind == "c" then args[i] = capturedColor(args[i])
116
+ elseif kind == "p" then
117
+ assert(paintValues[args[i]], "Paint was created outside capture")
118
+ args[i] = paintValues[args[i]]
119
+ end
120
+ end
121
+ validateArgs(args, signature)
122
+ if operation == "save" then assert(depth < 32, "NanoVG stack limit") end
123
+ if operation == "restore" then assert(depth > 0, "Unbalanced NanoVG restore") end
124
+ remember(operation, args)
125
+ local result = originals[name](vg, ...)
126
+ if operation == "save" then depth = depth + 1 end
127
+ if operation == "restore" then depth = depth - 1 end
128
+ return result
129
+ end)
130
+ end
131
+ for _, name in ipairs({ "nvgRGB", "nvgRGBA", "nvgRGBf", "nvgRGBAf" }) do
132
+ local api = name
133
+ wrap(api, function(...)
134
+ local a = { ... }; local factor = api:sub(-1) == "f" and 255 or 1
135
+ local rgba = { a[1] * factor, a[2] * factor, a[3] * factor, a[4] and a[4] * factor or 255 }
136
+ color(rgba)
137
+ local result = originals[api](...); colors[result] = rgba; return result
138
+ end)
139
+ end
140
+ for kind, sig in pairs(paints) do
141
+ local paintKind, signature = kind, sig
142
+ local name = "nvg" .. kind:sub(1, 1):upper() .. kind:sub(2)
143
+ wrap(name, function(vg, ...)
144
+ assert(vg == ctx, "NanoVG context mismatch")
145
+ local args = { ... }
146
+ if paintKind == "imagePattern" then
147
+ assert(images[args[6]], "Image handle requires opts.images mapping")
148
+ args[6] = images[args[6]]
149
+ else args[5] = capturedColor(args[5]); args[6] = capturedColor(args[6]) end
150
+ validateArgs(args, signature)
151
+ local result = originals[name](vg, ...)
152
+ paintValues[result] = { kind = paintKind, args = args }
153
+ return result
154
+ end)
155
+ end
156
+ wrap("nvgFontFaceId", function(vg, id)
157
+ assert(vg == ctx and fonts[id], "Font ID requires opts.fonts mapping")
158
+ remember("fontFace", { fonts[id] }); return originals.nvgFontFaceId(vg, id)
159
+ end)
160
+ for _, name in ipairs({ "nvgImageSize", "nvgTextBounds", "nvgTextMetrics" }) do
161
+ if originals[name] then _G[name] = originals[name] end
162
+ end
163
+ local ok, err = xpcall(function()
164
+ originals.nvgReset(ctx)
165
+ originals.nvgBeginPath(ctx)
166
+ draw()
167
+ assert(not failure, failure)
168
+ validate(node)
169
+ end, function(e) return tostring(e) end)
170
+ for name, fn in pairs(originals) do _G[name] = fn end
171
+ for _ = 1, depth do originals.nvgRestore(ctx) end
172
+ originals.nvgRestore(ctx)
173
+ active = false
174
+ if not ok then error(err) end
175
+ return node
176
+ end
177
+
178
+ local function nativeColor(value) return nvgRGBA(unpack(color(value))) end
179
+ local function multiply(a, b)
180
+ return { a[1]*b[1]+a[3]*b[2], a[2]*b[1]+a[4]*b[2], a[1]*b[3]+a[3]*b[4],
181
+ a[2]*b[3]+a[4]*b[4], a[1]*b[5]+a[3]*b[6]+a[5], a[2]*b[5]+a[4]*b[6]+a[6] }
182
+ end
183
+ local function inverse(m)
184
+ local d = m[1]*m[4]-m[2]*m[3]
185
+ if math.abs(d) < 1e-12 then return nil end
186
+ return { m[4]/d, -m[2]/d, -m[3]/d, m[1]/d,
187
+ (m[3]*m[6]-m[4]*m[5])/d, (m[2]*m[5]-m[1]*m[6])/d }
188
+ end
189
+
190
+ -- Draw a leaf inside the caller's active NanoVG frame. Layout belongs to the caller.
191
+ -- resolveImage(path, ctx) returns a cached native handle; this module owns no resources.
192
+ function M.draw(ctx, node, x, y, width, height, resolveImage, opacity)
193
+ validate(node)
194
+ local view, depth = node.viewBox, 0
195
+ local matrix, clips, stack = { 1, 0, 0, 1, 0, 0 }, {}, {}
196
+ nvgSave(ctx)
197
+ local ok, err = xpcall(function()
198
+ nvgTranslate(ctx, x or node.left or 0, y or node.top or 0)
199
+ nvgScale(ctx, (width or node.width or view[3]) / view[3], (height or node.height or view[4]) / view[4])
200
+ nvgTranslate(ctx, -view[1], -view[2])
201
+ nvgFillColor(ctx, nvgRGBA(255, 255, 255, 255)); nvgStrokeColor(ctx, nvgRGBA(0, 0, 0, 255))
202
+ nvgStrokeWidth(ctx, 1); nvgMiterLimit(ctx, 10); nvgLineCap(ctx, 0); nvgLineJoin(ctx, 4)
203
+ nvgFontSize(ctx, 16); nvgFontFace(ctx, "sans"); nvgTextAlign(ctx, 65)
204
+ nvgTextLetterSpacing(ctx, 0)
205
+ if opacity then nvgGlobalAlpha(ctx, opacity) end
206
+ nvgBeginPath(ctx)
207
+ local function clipped(fn, args)
208
+ if #clips == 0 then fn(ctx, unpack(args)); return end
209
+ local inv = inverse(matrix)
210
+ if not inv then return end
211
+ -- Apply layer scissors at paint time so replacing a local scissor cannot
212
+ -- discard an enclosing Widget/ScrollView clip.
213
+ nvgSave(ctx)
214
+ local painted, problem = pcall(function()
215
+ nvgTransform(ctx, unpack(inv))
216
+ for _, clip in ipairs(clips) do
217
+ local back = inverse(clip.matrix)
218
+ if not back then return end
219
+ nvgTransform(ctx, unpack(clip.matrix))
220
+ nvgIntersectScissor(ctx, unpack(clip.args))
221
+ nvgTransform(ctx, unpack(back))
222
+ end
223
+ nvgTransform(ctx, unpack(matrix))
224
+ fn(ctx, unpack(args))
225
+ end)
226
+ nvgRestore(ctx)
227
+ if not painted then error(problem) end
228
+ end
229
+ for _, cmd in ipairs(node.commands) do
230
+ local op, args = cmd[1], {}
231
+ for i = 2, #cmd do args[#args + 1] = cmd[i] end
232
+ if op == "fillColor" or op == "strokeColor" then args[1] = nativeColor(args[1]) end
233
+ if op == "globalAlpha" then args[1] = args[1] * (opacity or 1) end
234
+ if op == "fillPaint" or op == "strokePaint" then
235
+ local p, a = args[1], {}; for i, value in ipairs(args[1].args) do a[i] = value end
236
+ if p.kind == "imagePattern" then
237
+ assert(resolveImage, "Image paint requires resolveImage(path, ctx)")
238
+ a[6] = resolveImage(a[6], ctx)
239
+ assert(type(a[6]) == "number" and a[6] > 0, "NanoVG image could not be resolved")
240
+ else a[5] = nativeColor(a[5]); a[6] = nativeColor(a[6]) end
241
+ args[1] = _G["nvg" .. p.kind:sub(1, 1):upper() .. p.kind:sub(2)](ctx, unpack(a))
242
+ end
243
+ local fn = _G["nvg" .. op:sub(1, 1):upper() .. op:sub(2)]
244
+ assert(type(fn) == "function", "NanoVG runtime API missing: " .. op)
245
+ if op == "scissor" or op == "intersectScissor" then
246
+ local nextClips = {}
247
+ if op == "intersectScissor" then for i, clip in ipairs(clips) do nextClips[i] = clip end end
248
+ nextClips[#nextClips + 1] = { matrix = matrix, args = args }; clips = nextClips
249
+ elseif op == "fill" or op == "stroke" or op == "text" or op == "textBox" then clipped(fn, args)
250
+ else fn(ctx, unpack(args)) end
251
+ if op == "save" then depth = depth + 1; stack[depth] = { matrix = matrix, clips = clips } end
252
+ if op == "restore" then matrix = stack[depth].matrix; clips = stack[depth].clips; stack[depth] = nil; depth = depth - 1 end
253
+ local t
254
+ if op == "transform" then t = args
255
+ elseif op == "translate" then t = { 1, 0, 0, 1, args[1], args[2] }
256
+ elseif op == "scale" then t = { args[1], 0, 0, args[2], 0, 0 }
257
+ elseif op == "rotate" then
258
+ local c, s = math.cos(args[1]), math.sin(args[1]); t = { c, s, -s, c, 0, 0 }
259
+ elseif op == "skewX" then t = { 1, 0, math.tan(args[1]), 1, 0, 0 }
260
+ elseif op == "skewY" then t = { 1, math.tan(args[1]), 0, 1, 0, 0 } end
261
+ if t then matrix = multiply(matrix, t) end
262
+ end
263
+ end, function(e) return tostring(e) end)
264
+ for _ = 1, depth do nvgRestore(ctx) end
265
+ nvgRestore(ctx)
266
+ if not ok then error(err) end
267
+ end
268
+
269
+ -- Register the node before UI.LoadJSON; reuse the engine's layout, input and transforms.
270
+ function M.register(UI, resolveImage)
271
+ assert(not UI.NanoVG, "UI.NanoVG is already registered")
272
+ local Widget = require("urhox-libs/UI/Core/Widget")
273
+ local Vector = Widget:Extend("NanoVG")
274
+ function Vector:Render(ctx)
275
+ local layout = self:GetAbsoluteLayout()
276
+ local data = { type = "NanoVG", commands = self.props.commands, viewBox = self.props.viewBox }
277
+ local opacity, widget = 1, self
278
+ while widget do
279
+ local a = widget.renderProps_ and widget.renderProps_.opacity or widget.props.opacity or 1
280
+ opacity = opacity * math.max(0, math.min(1, a))
281
+ widget = widget.parent
282
+ end
283
+ M.draw(ctx, data, layout.x, layout.y, layout.w, layout.h, resolveImage, opacity)
284
+ end
285
+ UI.NanoVG = Vector
286
+ return Vector
287
+ end
288
+
289
+ return M