比较提交

...
共修改 46 个文件,包含 1637 行新增和 242 行删除

没有与搜索条件相匹配的文件

+1 -1
查看文件
@@ -7,7 +7,7 @@
正式版本222项原生检查通过。FCP12.4实测第二HSL初始化为零、红色色相32且原层仍为零,原层椭圆与新增层矩形独立;正向99帧轨迹、双向100帧轨迹、新增层单帧2键及播放头移动通过。一次撤销/重做、正常退出重开后的完整预设均逐字节一致。远端独立恢复210文件,模型/模板和Metal着色器重建一致。
验收缺口:实际画面轮廓/工具栏可见,但自动化坐标点击未进入真实宿主点击回调,FCP直接拖动、旋转和钢笔手势尚未实机确认;原生模拟宿主的真实Metal叠加、命中、拖动提交、一次撤销及Esc检查通过。Motion、Intel、旧系统、变速/裁剪/非方像素工程未实测。
画面中心拖动已经由用户用实际鼠标确认,原生点击/拖动回调及原层蒙版坐标变化已核对,新增层蒙版坐标保持不变。旋转、缩放和钢笔手势尚未实机确认;原生模拟宿主的真实Metal叠加、命中、拖动提交、一次撤销及Esc检查通过。Motion、Intel、旧系统、变速/裁剪/非方像素工程未实测。
新增工具标量目前是静态作者值,蒙版轨迹按时间求值。跟踪不含透视、剪切。空间蒙版不能导出为Cube,需保存完整预设。旧模板实例若不显示画面控件,可先保存完整预设,再应用新版效果并载入;不自动覆盖旧效果。
+7
查看文件
@@ -0,0 +1,7 @@
新增工具现在紧接点击的模块插入,初始化参数独立;旧工程已有的末尾层保留原位置与画面。蒙版检视器扩大文字、数值框和按钮,滑杆分行显示。修复钢笔进入绘制态、实时预览、曲柄、闭合/取消/重画及提示文字方向。
跟踪参考Color Finale行为独立适配:实际钢笔路径范围、300特征、亚像素精炼、21×21光流,最高3840×2160分析采样。281项原生检查及18项独立CPU/Metal跟踪检查通过。FCP12.4实测相邻插入、独立参数、绘制态与面板、钢笔蒙版正向99键、一次撤销/重做及保存重开完整预设一致。
实际鼠标钢笔落点/闭合仍待用户确认:自动化输入没有进入FCP画面回调,原生OSC模拟检查单独通过。当前不含Color Finale全部能力,B样条、编组、人物/图像/外部蒙版和完整轨迹区段编辑等尚有差异;未做同一真实视频的完整轨迹等价对照。跟踪不含透视/剪切。详细证据见仓库交接文档和verification/HostMaskWorkflow1.4.1.json。
版本1.4.1(26),Apple Silicon,macOS14.6起;APP实际编译源码 `0eb56aed126c825ca89712ce90f8cc1c05b03d89`。APP公证 `1ddc5499-2da3-4d98-8b2d-09272b0ee326`、PKG公证 `9a5ff448-2ac1-444e-b993-2928cf8c333f` 均Accepted,票据/Gatekeeper和20项展开验包通过。包 `大鱼调色-1.4.1.pkg`,14,337,616字节,SHA-256 `0c167aba339bbfdd9c4cbd96aea384e2d43f6d498629ebaf7b1c18cbc6dca5c6`。发行标签保留完整源码和交付记录,APP编译节点与发行记录节点分别列明。唯一正式APP位置 `/Library/Plug-Ins/FxPlug/大鱼调色.app`;不含用户LUT、预设或媒体。
+16 -6
查看文件
@@ -1,6 +1,6 @@
# 大鱼调色
原生 FxPlug 4 调色器,当前正式安装版本 **1.4.0(24)**。唯一安装位置为 `/Library/Plug-Ins/FxPlug/大鱼调色.app`;Final Cut Pro 中从“效果 → 大鱼调色”添加。
原生 FxPlug 4 调色器,当前正式安装版本 **1.4.1(26)**。唯一安装位置为 `/Library/Plug-Ins/FxPlug/大鱼调色.app`;Final Cut Pro 中从“效果 → 大鱼调色”添加。
## 色彩管理与一级调色
@@ -24,21 +24,31 @@ LUT 缩略图浏览器使用宿主的独立可调整窗口:拖动标题栏移
## 每工具蒙版与再次添加工具
十二个模块标题均有“添加蒙版”和“再加一层”。新增工具在列表末尾按添加顺序执行,从本工具的初始化参数开始,拥有独立启停、折叠、复位、删除、LUT 和蒙版;不会复制原层当前设置。新增一级采用 Rec.709/Gamma 2.4 同域输入输出,新增肤色保护强度为零。
十二个模块标题均有“添加蒙版”和“再加一层”。新增工具紧接点击的原工具或新增工具插入,从本工具的初始化参数开始,拥有独立启停、折叠、复位、删除、LUT 和蒙版;不会复制原层当前设置。新增一级采用 Rec.709/Gamma 2.4 同域输入输出,新增肤色保护强度为零。
蒙版包括椭圆、矩形、钢笔、线性渐变、HSL 和亮度选区,支持相加、减去、相交、反转、羽化和强度。矩形、椭圆和闭合钢笔区域可正向、反向、双向或单帧跟踪。算法从“大鱼调色盘”固定源码适配,随本产品独立构建;不依赖安装父插件。完整预设 v4 保存新增工具、蒙版和逐帧轨迹,兼容旧预设。空间蒙版不能导出到 Cube,导出时会提示。
正式版 222 项原生检查通过。FCP 实测独立 HSL、蒙版数值编辑、正向/双向/单帧跟踪、一次撤销/重做及保存重开通过。画面轮廓与工具栏已经显示;自动化鼠标未触发真实宿主点击回调,因此画面直接拖动、旋转和钢笔手势尚未完成实机确认,原生模拟宿主的相关回归通过。新增工具标量目前为静态值,蒙版轨迹按时间求值。跟踪覆盖位置、旋转和独立宽高,不含透视、剪切。
蒙版检视器采用13pt参数文字和数值、32–36pt按钮、独立整行滑杆及两列跟踪操作。钢笔菜单直接进入绘制态,可点击放点、拖出曲柄、点首节点/Return/“完成绘制”闭合,Esc/取消保留原路径;支持重画、Delete回退和即时预览。跟踪改进实际路径搜索边界、300点特征、亚像素精炼和21×21光流,分析采样上限3840×2160。
正式版281项原生检查、独立CPU/Metal跟踪18项通过。FCP实测相邻插入、初始化与独立参数、大号面板、绘制态切换、钢笔蒙版正向99键、一次撤销/重做及保存重开完整预设一致。画面提示文字方向已修正。自动化鼠标没有触发FCP画面回调,实际鼠标钢笔落点/闭合仍待用户确认,不能将模拟宿主通过写成实机手势通过。1.4.0的中心拖动已有用户确认。新增工具标量仍为静态值,蒙版轨迹按时间求值,跟踪不含透视/剪切。
旧schema1末尾层保持原保存位置与渲染,避免改变旧工程外观;新添加的层使用schema2插入锚点。原生固定模块的既有处理顺序保留。当前实现参考本机Color Finale的行为和参数独立适配,并非全部功能完整移植;B样条、编组、人物/图像/外部蒙版及完整轨迹区段编辑等差异见专项清单。
旧模板实例可能保留关闭画面控件的状态;可先保存完整预设,再重新应用新版效果并载入预设。不会自动覆盖旧实例。实现与验收边界见 [实现说明](research/ToolMaskImplementation.md)、[宿主记录](verification/HostToolMasks.json) 和 [恢复核验](verification/ToolMaskRecovery.json)。
## 验证与恢复
- [本轮交接](大鱼调色FxPlug4交接.md)
- [1.4.1 正式版 281 项原生检查](verification/InstalledSelfTest.json)
- [插入、钢笔和跟踪工作流](research/MaskWorkflow1.4.1.md)
- [1.4.1 FCP验收及实际鼠标缺口](verification/HostMaskWorkflow1.4.1.json)
- [Color Finale对照和未迁移范围](research/ColorFinaleMasksFollowup.md)
- [1.4.1远端源码独立恢复](verification/MaskWorkflowRecovery.json)
- [每工具蒙版、跟踪、保存重开与用户实际拖动](verification/HostToolMasks.json)
- [1.4.0 发行标签独立恢复](verification/ToolMaskReleaseRecovery.json)
- [CST 来源与集成边界](research/CSTIntegration.md)
- [CST 固定源码节点与摘要](research/CSTIntegration.json)
- [蜘蛛盘与色轮来源和适配](research/SpiderAndBalanceIntegration.md)
- [201 项正式版原生与独立像素对照](verification/BrowserNative.json)
- [1.3.1 的 201 项原生与独立像素对照](verification/BrowserNative.json)
- [浏览器布局与最近使用专项检查](verification/BrowserCustomization.json)
- [大规模 LUT 加载与取消回归](verification/BrowserRegression.json)
- [204,683 项网格数学检查](verification/SpiderMath.json)
@@ -52,6 +62,6 @@ LUT 缩略图浏览器使用宿主的独立可调整窗口:拖动标题栏移
正式发行包由 PKG 工坊技能生成,包含 APP 与 FCP 模板,不含用户 LUT、预设或媒体。安装与发布证据分别保存在 [Package.json](verification/Package.json) 和 [Release.json](verification/Release.json);以其中记录的版本和成功状态为准。
正式安装包:[大鱼调色-1.4.0.pkg](../发行包/大鱼调色-1.4.0.pkg);APP及PKG均已公证、粘附票据并通过Gatekeeper,20项展开验包通过。[1.4.0 Release](https://dayu.media/git/dayu/dayu-color/releases/tag/v1.4.0-tool-masks-20261101)的实际发布和完整下载校验以Release.json为准。历史1.3.1及更早发行包和标签保留。
正式发行包:[大鱼调色-1.4.1.pkg](../发行包/大鱼调色-1.4.1.pkg);APP与PKG均已签名、公证、粘附票据和通过Gatekeeper,20项展开验包通过;Release下载核验以本轮Release.json记录为准。历史[1.4.0 Release](https://dayu.media/git/dayu/dayu-color/releases/tag/v1.4.0-tool-masks-20261101)及更早发行包和标签保留。
FCP 已验证 Sony 默认、可见复位、浮动浏览器、系统窗口缩放、两种布局、最近排序与关闭重开。原生检查单独覆盖几何/布局持久化和鼠标事件;自动化没有独立确认自由标题栏/边缘拖动。用户开始使用后保留其当前布局与选择,未为额外测试再次重启宿主。
1.3.1 的历史验收包含 Sony 默认、可见复位、浮动浏览器、系统窗口缩放、两种布局、最近排序与关闭重开。原生检查单独覆盖几何/布局持久化和鼠标事件;当时自动化没有独立确认自由标题栏/边缘拖动。1.4.0 另在独立合成工程中完成上文的宿主检查,用户确认中心拖动后保留其试调状态。
+14 -2
查看文件
@@ -1,6 +1,18 @@
# 大鱼调色恢复说明
## 当前 1.4.0(24):每工具蒙版与初始化叠层
## 当前 1.4.1(26):相邻插入、蒙版可读性与钢笔流程
APP实际编译 `0eb56aed126c825ca89712ce90f8cc1c05b03d89`,公证 `1ddc5499-2da3-4d98-8b2d-09272b0ee326` Accepted;票据、Gatekeeper、唯一正式安装和安装后281项原生检查通过。正式路径、Bundle ID和签名团队不变。PKG/Release以当前验证JSON的版本和成功状态为准。 本轮发行标签 `v1.4.1-mask-workflow-20261101`;包 `../发行包/大鱼调色-1.4.1.pkg`,14,337,616字节,SHA-256 `0c167aba339bbfdd9c4cbd96aea384e2d43f6d498629ebaf7b1c18cbc6dca5c6`。PKG公证 `9a5ff448-2ac1-444e-b993-2928cf8c333f` Accepted,票据/Gatekeeper与20项展开验包通过;本轮未再次执行系统安装器。
新层紧接点击源插入,schema2的after保存原模块或UUID锚点;旧schema1尾层不迁移,保留旧画面。渲染在原固定工具对应阶段执行新层,非只移动界面。保持无新增激活层时原融合路径、CST参考、肤色参考、黑白混合和原蜘蛛盘顺序。详见 `research/MaskWorkflow1.4.1.md`。
蒙版面板扩大文字/数值和按钮,钢笔有明确的绘制、完成、取消与重画状态;实时草稿不调用宿主API,完成后单次提交。跟踪采用实际路径范围、300特征、亚像素精炼、21×21光流,采样最高3840×2160。Color Finale只读研究与独立适配差异见 `research/ColorFinaleMasksFollowup.md`,并非完整移植所有原版蒙版能力。
FCP12.4相邻插入、独立初始化参数、面板/绘制态、钢笔蒙版正向99键、一次撤销/重做和冷重开完整预设一致;实际鼠标钢笔落点/闭合待用户确认,自动输入未进入OSC回调。原生281项和独立跟踪18项通过,不等同所有真实素材与手势均已验收。详见 `verification/HostMaskWorkflow1.4.1.json`。
从远端独立恢复224文件、full/strict fsck,并从恢复源码重建模型/模板及Metal,与正式版着色器一致,见 `verification/MaskWorkflowRecovery.json`。无LFS/子模块;临时clone已清理。中间25版及24版临时APP备份在26版验证后清理,历史正式PKG保留。
## 历史 1.4.0(24):每工具蒙版与初始化叠层
APP 实际编译 `dbf25fe6719f17075362538dad0404951102524d`,公证 `40fdaaaa-1821-4cc8-bec3-c5dc6d8b9f77`,Accepted;票据、Gatekeeper、唯一正式安装、222项原生检查及FCP保存重开通过。安装和实际宿主证据分别见 `verification/Delivery.json`、`verification/HostToolMasks.json`。正式包和Release以对应JSON记录的1.4.0状态为准,不套用历史1.3.1记录。
@@ -10,7 +22,7 @@ APP 实际编译 `dbf25fe6719f17075362538dad0404951102524d`,公证 `40fdaaaa-1
远端独立克隆该编译节点,210个提交文件逐字节核对、strict/full fsck通过;从恢复源码和本机SDK重建模型/模板及Metal,模板和正式着色器摘要完全一致,见 `verification/ToolMaskRecovery.json`。不含LFS或子模块。恢复临时目录已清理,签名证书私钥仍需独立恢复。
FCP实测独立HSL、每层椭圆/矩形、数值编辑、正向99键、双向100键、单帧2键、一次撤销/重做及冷重开完整预设一致。画面轮廓/工具栏可见;实机鼠标拖动/旋转/钢笔未验证,模拟宿主的原生OSC检查通过。旧模板实例可能保留关闭OSC的状态,可保存完整预设后重新应用新版效果再载入,不自动覆盖旧工程。
FCP实测独立HSL、每层椭圆/矩形、数值编辑、正向99键、双向100键、单帧2键、一次撤销/重做及冷重开完整预设一致。用户已实际确认中心拖动,原生hit/drag回调和原层坐标变化已核对,新增层蒙版坐标不变;旋转/缩放/钢笔尚未实机验证,模拟宿主的原生OSC检查通过。旧模板实例可能保留关闭OSC的状态,可保存完整预设后重新应用新版效果再载入,不自动覆盖旧工程。
## 历史 1.3.1(19):色轮复位、可调整浏览器与最近使用
+261
查看文件
@@ -0,0 +1,261 @@
{
"date": "2026-11-01",
"scope": "Read-only installed Color Finale 2.16.2(625) static analysis and independent Dayu tracking reconstruction; no target runtime/GUI",
"target": {
"path": "/Applications/ColorFinale.app/Contents/PlugIns/ColorFinale.pluginkit/Contents/MacOS/ColorFinale",
"sha256": "49121a6f5487060d322a59e7658166ab772e8a56f7dc1bcfa9d433a89436b30f",
"architecture": "arm64",
"provider": "Ghidra 12.1.4"
},
"baselineCommit": "745aa1626e1df368290fbbd47a716ff3ce9ca630",
"evidence": [
{
"evidence_id": "ev_6539e1080a6e0d9cf27d9cb3c26703110b8f50030981b18cc075356840849e08",
"operation": "analyze_function",
"procedure": "FTShapeTrackerView::addShapeForEvent:",
"address": "0x1000e2900",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_0f9372e98efac18d8f666dcf137addc2ecdaffdfdb153f0a31b3ecfc2ba8b9ca",
"operation": "analyze_function",
"procedure": "FTShapeTrackerView::setShapeEditMode:",
"address": "0x1000e1fcc",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_2dd4ac418346bd4d15d05f8145bb2a547ab531d742b4e8edfb3314fc49fdde0a",
"operation": "analyze_function",
"procedure": "FTOnScreenBezierShape::mouseDown:",
"address": "0x10009be0c",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_8aa635a486e91b5af36bc39d424964417e0b6b77706cb24218640ac253b426b6",
"operation": "analyze_function",
"procedure": "FTOnScreenBezierShape::mouseUp:",
"address": "0x10009c084",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_4c3864a55c7dc71ee02b67c4eed011dbe00a9d8072c275ff002607d22618c288",
"operation": "analyze_function",
"procedure": "FTOnScreenPathShape::closePath",
"address": "0x100033ec8",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_2fc54b9d31f2ac894aae0b560fee33284a155fe6505697c0a83be1af0bc0a8ea",
"operation": "analyze_function",
"procedure": "FTOnScreenPathShape::controlPoint:mouseDown:",
"address": "0x10003429c",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_d3bea253005ee2007c110f15d6658e542de8f2075d40585897b875f9b517ec2b",
"operation": "analyze_function",
"procedure": "FTOnScreenPathShape::keyDown:",
"address": "0x1000345c8",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_ba0c6d39ae45e26b8ade69f41f6fb8da934c526a686e64be89690b762a11e585",
"operation": "analyze_function",
"procedure": "FTShapeBezierControlPoint::controlPoint:mouseDragged:",
"address": "0x10009d178",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_ea178e24d10afea13fa74a0d70941648d1ca4c45005a1533df478c9212f6f9b7",
"operation": "analyze_function",
"procedure": "FTShapeTrackerControl::addToolbarButtons",
"address": "0x10001ef7c",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_dcd7aa770925f63c8c14c968ae6b417fda78685c7be7fa739a78209957d40e2d",
"operation": "analyze_function",
"procedure": "FTAreaTracker::track:trackerState:",
"address": "0x100035e40",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_e798c4e6e032e085812f81831ecc16196bd3c2278bf634961379669ee1308f7e",
"operation": "analyze_function",
"procedure": "FTAreaTracker::trackFrame:inScene:",
"address": "0x100036cbc",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_8bad5bbc4bd2890227567b9799cfc1e68c6d56631e67a73224d57971767664c4",
"operation": "analyze_function",
"procedure": "-[FTTrackerShape(FTOnScreenShape)_addKeyFrameForShape:atTime:]",
"address": "0x100047dc4",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_fe677a9c456fc8739e0c33edd513c3f6b94431c7fbb6f1194a78801f39f32072",
"operation": "analyze_function",
"procedure": "FTShapeTrackerControl::shapeTrackerView:geometryDidChangeForShapes:",
"address": "0x100025414",
"authority": "shipped-artifact",
"confidence": "observed"
},
{
"evidence_id": "ev_533595e2ddf4c96d5c82f3ce25c7ff44a3549f37d8b80e5b5b5a82360e283c77",
"operation": "analyze_function",
"procedure": "FTMaskShapeViewController::viewDidLoad",
"address": "0x10007f3b0",
"authority": "shipped-artifact",
"confidence": "observed"
}
],
"localOnlyEvidenceDirectory": "/Users/mac/Library/Caches/CodexBuilds/ColorResearch/dayu-mask-followup-20261101",
"sourceApplicationRuntimeDependency": false,
"proprietaryCodeOrResourcesCommitted": false,
"originalArtifactModified": false,
"completeMigrationClaim": false,
"limitations": [
"Static analysis is not live runtime acceptance.",
"Independent detector/gray conversion/LK/RANSAC safeguards do not exactly reproduce OpenCV results.",
"Interface Builder default 64-document coverage omitted mask nibs; exact full inspector pixel sizes are unknown.",
"B-spline, grouping/parent masks, image/person/external inputs, published masks and full keyframe-region editing are outside this fault-fix implementation.",
"No same-video, same-path, whole-trajectory comparison to the original product has been performed."
],
"independentVerification": {
"passResult": true,
"count": 18,
"checks": [
{
"name": "cpu-pen-texture-outside-creation-box-starts",
"pass": true,
"features": 117
},
{
"yErrorPixels": 0.03234100341796875,
"xErrorPixels": 0.007296752929676131,
"name": "cpu-extended-pen-region-subpixel-motion",
"pass": true
},
{
"name": "cpu-real-300-feature-capacity",
"pass": true,
"features": 300
},
{
"pass": true,
"rotation": 0.02499544620513916,
"scaleX": 1.025027871131897,
"scaleY": 0.9799908995628357,
"xErrorPixels": 0.0009307861328267109,
"yErrorPixels": 0.0005807876586860772,
"name": "cpu-translation-rotation-independent-xy-scale"
},
{
"name": "cpu-subpixel-refinement-and-redetection-remain-stationary",
"pass": true
},
{
"name": "cpu-unrelated-cut-is-not-trusted-motion",
"pass": true
},
{
"name": "cpu-flat-region-still-refuses-tracking",
"pass": true
},
{
"generatedFramesAndAnalysisMilliseconds": 43.247542,
"features": 300,
"name": "cpu-1080p-complete-frame-motion",
"pass": true
},
{
"generatedFramesAndAnalysisMilliseconds": 111.362708,
"features": 300,
"name": "cpu-3840x2160-complete-frame-motion",
"pass": true
},
{
"name": "metal-pen-texture-outside-creation-box-starts",
"pass": true,
"features": 117
},
{
"yErrorPixels": 0.03234100341796875,
"xErrorPixels": 0.007296752929676131,
"name": "metal-extended-pen-region-subpixel-motion",
"pass": true
},
{
"name": "metal-real-300-feature-capacity",
"pass": true,
"features": 300
},
{
"pass": true,
"rotation": 0.02499544620513916,
"scaleX": 1.025027871131897,
"scaleY": 0.9799908995628357,
"xErrorPixels": 0.0009307861328267109,
"yErrorPixels": 0.0005807876586860772,
"name": "metal-translation-rotation-independent-xy-scale"
},
{
"name": "metal-subpixel-refinement-and-redetection-remain-stationary",
"pass": true
},
{
"name": "metal-unrelated-cut-is-not-trusted-motion",
"pass": true
},
{
"name": "metal-flat-region-still-refuses-tracking",
"pass": true
},
{
"generatedFramesAndAnalysisMilliseconds": 31.447709,
"features": 300,
"name": "metal-1080p-complete-frame-motion",
"pass": true
},
{
"generatedFramesAndAnalysisMilliseconds": 88.904167,
"features": 300,
"name": "metal-3840x2160-complete-frame-motion",
"pass": true
}
],
"memoryRunPass": true,
"peakResidentBytes": 299597824,
"generatedImageOracles": true,
"baselineExtendedRegion": {
"started": false,
"features": 0
},
"newExtendedRegion": {
"started": true,
"features": 117
},
"appLaunched": false,
"scope": "Independent generated images, CPU tracker and optional real Metal optical flow. No app or GUI host launched."
},
"implementationSHA256": {
"大鱼调色/Plugin/MaskCore/DYTracker.hpp": "68d32e8704e737587729397b0e8dd856f40c26aff479af7a65e5a32c48e95d6b",
"大鱼调色/Plugin/DYToolFlow.inc.h": "f4426c1bc4a36a93561c9d43ea794b89c10767fb94cbc442b82563766b1856d8",
"大鱼调色/Plugin/DYTracking.metal": "e0c13390a952b13eb92081840069f79632c05326aaf1a0cc927200a84d4e4ac0",
"tools/verify_tool_tracking_followup.mm": "961c3ff4359bc06bf7b6d1f71b8fcfa40efee32d2f7722a0af9ba813971d7c64"
},
"independentShaderSHA256": "2899508dbcff3329531ec23f9fe13f30993ba5416bf7788697557f5d611783f8"
}
+44
查看文件
@@ -0,0 +1,44 @@
# Color Finale 蒙版与跟踪的本机复核(2026-11-01)
本轮针对用户报告的“层在最底部新增、蒙版控件太小、钢笔不可用”核对本机发行产物。目标为 ColorFinale 2.16.2(625)的 arm64 插件,完整文件 SHA-256 `49121a6f5487060d322a59e7658166ab772e8a56f7dc1bcfa9d433a89436b30f`,与此前归档研究一致。原程序始终只读,未执行或操作其 FCP 界面。静态观察不是运行行为验收,也不能据此声称整个原版功能已完整迁移。
这里只保存行为、接口、参数和 Evidence 索引,不保存原版反编译源码、二进制、图标或其他资源。新功能仍是本产品自己的源码与 Metal 实现,不依赖 Color Finale 安装。
## 钢笔状态与可迁移交互
| 本机静态观察 | 入口与 Evidence |
| --- | --- |
| 选择 Bezier 新建模式后,首次点击建立可编辑/选中的零尺寸路径,交给新路径处理该点击,随后进入独立的路径编辑模式 | `FTShapeTrackerView::addShapeForEvent:` `0x1000e2900`,`ev_6539e1080a6e0d9cf27d9cb3c26703110b8f50030981b18cc075356840849e08` |
| 新建与编辑路径是不同模式;离开路径编辑模式会尝试闭合当前路径 | `setShapeEditMode:` `0x1000e1fcc`,`ev_0f9372e98efac18d8f666dcf137addc2ecdaffdfdb153f0a31b3ecfc2ba8b9ca` |
| 编辑态可向未闭合路径追加锚点,也有在曲线上插点的分支;放置后可拖出共线双柄 | `FTOnScreenBezierShape::mouseDown:` `0x10009be0c`,`ev_2dd4ac418346bd4d15d05f8145bb2a547ab531d742b4e8edfb3314fc49fdde0a`;`FTShapeBezierControlPoint::controlPoint:mouseDragged:` `0x10009d178`,`ev_ba0c6d39ae45e26b8ade69f41f6fb8da934c526a686e64be89690b762a11e585` |
| 未闭合且至少三个点才允许闭合;点击首锚点会闭合 | `FTOnScreenPathShape::closePath` `0x100033ec8`,`ev_4c3864a55c7dc71ee02b67c4eed011dbe00a9d8072c275ff002607d22618c288`;`controlPoint:mouseDown:` `0x10003429c`,`ev_2fc54b9d31f2ac894aae0b560fee33284a155fe6505697c0a83be1af0bc0a8ea` |
| 原版未闭合路径接收 Return 或 Esc 时均尝试闭合;Delete 删除选中锚点 | `FTOnScreenPathShape::keyDown:` `0x1000345c8`,`ev_d3bea253005ee2007c110f15d6658e542de8f2075d40585897b875f9b517ec2b` |
| 画面工具栏有选择、路径编辑、矩形、椭圆、渐变边、B 样条、Bezier;预览按钮原生最小尺寸为30×22,另有8×8内边距 | `FTShapeTrackerControl::addToolbarButtons` `0x10001ef7c`,`ev_ea178e24d10afea13fa74a0d70941648d1ca4c45005a1533df478c9212f6f9b7` |
大鱼本轮保留明确的“Esc取消草稿”行为,与原版“Esc尝试结束闭合”不同。不能把新实现描述为所有快捷键均完全相同。当前产品旧钢笔入口未携带绘制态,且通知会清除绘制态;即使菜单项存在,也不能证明进入了放点模式。修复应同时覆盖绘制态、首点/Return结束、删除、草稿预览、提交和取消,以及再次选择已有路径的编辑。
形状属性控制器将 `feather`、`opacity`、`position`、`scale`、`rotation` 绑定到对应作者属性,见 `FTMaskShapeViewController::viewDidLoad` `0x10007f3b0`,Evidence `ev_533595e2ddf4c96d5c82f3ce25c7ff44a3549f37d8b80e5b5b5a82360e283c77`。完整检视器字号和运行时像素布局未取得充分静态证据;不能从符号名称推断其可读性。
## 跟踪差异与本轮改进
原版核心 `FTAreaTracker::track:trackerState:` `0x100035e40`,Evidence `ev_dcd7aa770925f63c8c14c968ae6b417fda78685c7be7fa739a78209957d40e2d`。逐帧作者状态 Evidence `ev_e798c4e6e032e085812f81831ecc16196bd3c2278bf634961379669ee1308f7e`(`0x100036cbc`)。原版每帧接收完整图像、最多3840×2160转换为8位灰度,将 position/rotation/scale 按 effectTime 写入作者键,不是渲染时临时估计。当前大鱼已经有精确时间键、相邻帧参考、丢失停止和这些变换输出;这些并非本轮才补齐。
| 项目 | 原版静态观察 | 大鱼1.4.0(24)与本轮选择 |
| --- | --- | --- |
| 区域 | 用形状点的凸包构造特征遮罩 | 原有实际多边形判断更贴合凹路径,但包围框和前置±0.5裁剪错误。本轮改为从实际路径顶点推导变换后搜索边界,保留实际多边形判断,修复默认框外钢笔纹理被裁掉的问题 |
| 特征 | 300点,quality0.03,最小距离10,blockSize3 | 原有180点、0.012相对阈值、按帧大小变化的间距、5×5邻域。本轮调整为300点、0.03、10像素、3×3;仍采用独立中心差分与2像素候选扫描,并不等同OpenCV检测器 |
| 角点精炼 | `cornerSubPix` 半窗10,20次/0.03 | 原有无亚像素精炼。本轮用独立加权梯度交点迭代,半窗10、20次/0.03,限制发散并保留初始点回退;不是复制OpenCV内部实现 |
| 光流 | LK21×21,maxLevel3即最多4级,30次/0.01;前后误差严格小于1 | 原有9×9、最多5级、20次。本轮CPU和Metal统一21×21、最多4级、30次/0.01;保留原有均值去除、RMSE及≤1.1像素前后检查,不声称数值全等 |
| 重检测 | 分析计数小于2或偶数时重检测并精炼 | 原有每5帧或少于60点补点。本轮每2帧或不足60时重选;新点少于12时保留仍可信旧点,后续仍须通过完整拟合/失效条件 |
| 拟合 | `estimateAffine2D` RANSAC2000次、阈值3、confidence0.99、refine10 | 本轮保留确定性400次、1.6/1.5阈值、3次最小二乘、至少8点/52%内点与非线状分布检查。阈值不能无验证地照搬,否则可能把错误帧当作成功 |
| 输出/失效 | 原版持久化位置、旋转和独立XY缩放,失败节点不再继续 | 大鱼保持QR分解位置/旋转/独立XY缩放,丢失停止、置信度和每步缩放/旋转保护。它比已观察到的原版分支更保守,不含透视或剪切输出 |
独立检查 `tools/verify_tool_tracking_followup.mm` 使用已知仿射变换生成图像,分别运行CPU和真实Metal后端。默认创建框外的钢笔区域在旧提交 `745aa1626e1df368290fbbd47a716ff3ce9ca630` 检出0点、无法启动;新版本检出117点,12帧亚像素移动末帧误差约X0.0073/Y0.0323像素。另覆盖300点实际传输、旋转与非等比缩放、静止重检测、换景拒绝、平坦区域拒绝,以及1920×1080/3840×2160完整帧。18项通过;4K生成两帧及分析本机记录约CPU111ms/Metal89ms,不是所有素材的性能承诺。
## “完整移植”的边界
本轮是可验证的独立重建与关键交互修复,不能宣称完整复制Color Finale蒙版系统。原版还观察到B样条、形状多选/编组、父蒙版、图像/人物/宿主外部蒙版、HSL取色增减与来源/模糊、发布蒙版/抠出、轨迹区域选择与按键区段编辑等体系;当前大鱼每工具六类蒙版不具备全部对应能力。`FTMaskDetailViewController` 的形状、HSL、图像、人物、FCP控制器方法库存见 Evidence `ev_0497fc6415b6b210fea8a052adf0f93483af228b44063dffd2c76d93a990cef1`。大鱼独立“亮度选区”不能据此称为已复刻原版某个独立Luma类;本次主插件范围没有取得该类的充分证据。
算法阈值及默认值对齐不是对真实视频的等价证明。本轮尚未取得原版与大鱼在同一真实视频、相同路径及分析范围下的完整轨迹对照,也未分析原版所有链接框架和动态形状UI。完整范围继续由差异清单追踪,不能把当前故障修复或合成检查通过替代这些开放项。
完整REA证据和恢复snapshot仅在本机研究缓存:`/Users/mac/Library/Caches/CodexBuilds/ColorResearch/dayu-mask-followup-20261101/`。当前REA目标已关闭,原产物未修改。Interface Builder decoder默认64文档首先遍历Sparkle,未覆盖后续蒙版nib;不能把该局限解释为蒙版UI不存在。新摘要保留此未知,不复制原版资源作为新产品界面。
+39
查看文件
@@ -0,0 +1,39 @@
# 1.4.1:就地插层、蒙版可读性和钢笔修复
基线为1.4.0(24)后的主分支 `745aa1626e1df368290fbbd47a716ff3ce9ca630`。本轮原生Release构建281项检查通过,独立跟踪18项检查通过。正式签名、公证、宿主和安装包状态分别以 `verification/Delivery.json`、宿主记录、`Package.json`、`Release.json` 为准;此说明不代替实机验收。
## 插入位置与运算
新建工具文档schema2的节点保存 `after` 锚点,可引用原工具或另一个工具UUID。点击原HSL或新增HSL的“再加一层”,新层立即排在该层之后。再次点击原层时插在原层与此前第二层之间;删除层重接后续节点。参数仍从初始化值开始,独立保存身份、折叠、启停、蒙版和资源。
schema1及没有after的既有1.4.0尾部层保留原位置和原数学,不在打开旧工程时偷偷改变调色;新层和旧尾部层的子层可并存。序号按当前显示位置生成,作者身份始终为UUID。
原固定融合链的操作顺序早于当前界面分组,不重新排列旧模块。活跃插入通过独立分段内核执行在原工具的实际阶段之后;基础调整在第二阶段后、CST在前段、蜘蛛盘在原末端。原始内核保留,没有活跃新增层时使用原融合路径,初始化新层像素精确直通。
分段保留首次CST后的原图,供原邻域、白点统计、亮度权重和蒙版取样;保留原uniform及旧输入LUT,只禁止后段再次CST。肤色参考保留在原HSL之前。部分黑白混合若被黑白/LUT锚点切开,在共同前缀后保留黑白与彩色两支,原肤色之后混合,再执行新增肤色与一次蜘蛛盘。可证明全零覆盖的额外工具直接复制输入,避免空蒙版额外裁切HDR/负值。
HSL与后续颜色分级、红通道曲线与HSL的独立非交换参照,以及Cube同序检查通过。CST、原三原色+白点统计/纹理、旧输入LUT、亮度选区、肤色、基础第二阶段、部分黑白混合和蜘蛛盘的零覆盖插层参照通过,分段半浮点最大差异约0.001465。此差异不适用于所有素材和参数组合的精度保证。
## 蒙版控件与钢笔
面板参数与数字为13pt,状态12pt;数值框88×32pt,滑条单独占一行,操作按钮32–36pt高,跟踪按钮两列三行。六种类型在220/300/420pt宽度的边界、不重叠、字号和目标尺寸检查通过。画面工具栏依据宿主backingScaleFactor绘制,短画面换列。
修复检视器添加钢笔未携带绘制态的问题,提供“重画钢笔”“完成绘制”“取消绘制”。点击放点、按住拖出共线双柄,鼠标移动显示下一段预览;至少三个点时点首节点、Return或完成按钮闭合。Delete回退未提交点,选中已闭合路径节点可删除(至少保留三点)。Esc/取消恢复原作者路径。绘制中禁用跟踪,完成或取消后恢复。
OSC回调只在锁内更新内存草稿,立即供下一次绘制读取;宿主参数提交留到回调结束后的主队列,形成一次撤销。连续手势排队保留,跨帧草稿、过期目标和迟到模式通知拒绝覆盖。绘制、命中和坐标缓存也有自身互斥。画面位图上下坐标与AppKit上下文方向保持一致,修正钢笔提示条文字翻转。原生检查覆盖检视器入口、默认形状外放点、即时预览、曲柄、首节点/Return闭合、完成/取消按钮、归档、连续手势和跨帧拒绝。
## Color Finale 对照与跟踪
本机Color Finale 2.16.2(625)只读静态证据、精确产物摘要和迁移边界见 `ColorFinaleMasksFollowup.md/.json`。没有复制原版反编译源码、二进制、图标或运行库作为产品依赖。
修复原跟踪器将钢笔区域预先裁到创建框±0.5的问题。特征搜索边界由实际变换后的路径推导,保留真实多边形判断;300特征、相对质量0.03、10像素间隔、亚像素精炼、21×21 LK、最多4级、30次迭代、每两帧重检测。继续保留现有严格仿射拟合、置信度、丢失停止和手工键优先。宿主实际分析采样上限3840×2160,兼顾像素长宽比。
默认框外钢笔纹理在旧版检出0点、无法启动,新版117点;12帧亚像素运动末帧误差约X0.0073/Y0.0323像素。独立CPU与真实Metal18项覆盖300点容量、旋转、独立缩放、静止、换景/低纹理拒绝及4K;本产品281项原生集成同时覆盖实际插件FxAnalyzer回调的精确帧序、撤销、取消和过期写入。
这些是有证据的独立重建与适配,不代表Color Finale全部蒙版系统已经完整迁移。B样条、多选/编组、图像/人物/外部蒙版、来源和轨迹区段编辑等差异见专项清单;未进行同一真实视频的完整原版轨迹等价对照。旧系统、Intel、Motion和非方像素/变速工程仍需实机覆盖。
## 正式宿主验收
1.4.1(26)APP公证Accepted,唯一正式安装与281项原生检查通过。FCP12.4在独立合成工程中验证:相邻插入、连续原层点击插入顺序、零参数新层与32色相既有层独立、放大面板、绘制态/跟踪禁用、提示文字方向、钢笔蒙版正向99键和一次撤销/重做。冷重开后完整预设逐字节相同。
CUA坐标输入未进入原生OSC回调;实际鼠标钢笔放点与闭合仍待用户确认。跟踪宿主验收使用现存默认闭合四点钢笔路径,不称为新手绘路径。真实鼠标中心拖动有1.4.0用户确认,但不扩大为本轮钢笔确认。记录见 `verification/HostMaskWorkflow1.4.1.json`。
+1 -1
查看文件
@@ -30,6 +30,6 @@
24版正式路径222项原生检查通过;新增OSC检查使用真实Metal叠加,验证透明背景、坐标命中、异步拖动写回、单次撤销和Esc取消。作者文档以不可变快照供OSC读取,不在绘制回调中进入主插件宿主API;添加蒙版先发布选择快照,再结束参数提交。轨迹查找使用CMTime二分定位,渲染快照仅替换各蒙版的当前参数,不重复序列化全部轨迹。
24版FCP12.4实测:第二HSL从0到32独立保存,原HSL保持0;原层椭圆中心X数值改为0.6,新增层矩形保持0.5;正向99键,一次Undo到0键,一次Redo到99键且完整预设逐字节一致;双向100键;新增层独立单帧2键,播放头由1帧到2帧。正常退出重开后,完整预设逐字节一致,分别保留100/2键。实际轮廓/工具栏可见;自动化坐标点击未进入真实宿主hit/event回调,因此FCP画面直接拖动、旋转和钢笔手势仍未实机确认,不能以模拟器通过代替。取消、过期目标和逆向精确节奏由原生模拟调度覆盖;Motion、Intel、变速/裁剪/非方像素未实测。
24版FCP12.4实测:第二HSL从0到32独立保存,原HSL保持0;原层椭圆中心X数值改为0.6,新增层矩形保持0.5;正向99键,一次Undo到0键,一次Redo到99键且完整预设逐字节一致;双向100键;新增层独立单帧2键,播放头由1帧到2帧。正常退出重开后,完整预设逐字节一致,分别保留100/2键。初验自动化坐标点击未进入真实宿主hit/event回调;随后用户已确认实际鼠标中心拖动正常,原生hit/mouseDown/mouseDragged日志也已捕获,原层中心变为0.378/0.379而新增层仍0.5/0.5。用户试调结果保留。旋转、缩放、钢笔手势未实机确认,不能以模拟器通过代替。取消、过期目标和逆向精确节奏由原生模拟调度覆盖;Motion、Intel、变速/裁剪/非方像素未实测。发行标签保存首次验收快照,用户后续实际鼠标确认保存在主分支当前记录,标签不移动。
20–23版是本次中间验收节点,不作为最终发行。模板10005现采用父库原生Boolean flags8589934592/default0/value1,pluginVersion0解析当前插件。既有FCP保存的旧模板实例可能保留10005=0;画面控件需保存完整预设后重新应用新版效果,旧实例调色数学不自动迁移或覆盖。
+2 -2
查看文件
@@ -3071,8 +3071,8 @@
"大鱼调色/Plugin/DYModel.h": "80e88add97deeac7a9dc47d12f68b0245905786297de2e6553b3da15c729da6e",
"大鱼调色/Plugin/DYModel.mm": "beadabb0773e911581dedc263f55a49e03dde6e6d1fc2329df18cb384710d234",
"大鱼调色/Plugin/DYSpiderState.h": "0c80747e41e8fc97762e301b011bd08c18865a825eaafde086ed79ace37b22f9",
"大鱼调色/Plugin/DYToolState.h": "a1b0e328faae5dce7bb8497186f028a45d2da4f1a87e1980cd30c7a59a098a9f",
"大鱼调色/Plugin/DYToolState.mm": "2d8aefba3ddd1ab06fe63025c29efc5e6a4e586ce33486c8aceb7352e8ed6099",
"大鱼调色/Plugin/DYToolState.h": "28088ec819307a60f2e52334fd807a514c3ff8a550bc0efbe7069b68a6242320",
"大鱼调色/Plugin/DYToolState.mm": "9ddc4b7509ad63fc24d1724359b4a218609f90b971eee57f6cdeda0c1b309129",
"大鱼调色/Plugin/DYUniforms.h": "8ef480025c739b29f55884ba0c7218e9d6fd8d80c46cfc72d6ee3da90215abe4",
"大鱼调色/Plugin/MaskCore/DYMask.h": "5b9aa44390d4a1fca1baf5e34cb9eefc8483c939a65cc2a0412b7b41fc85bc16",
"大鱼调色/Plugin/MaskCore/DYMaskOperator.h": "43fa701ad574f38ce0ab4f4d3900bb034edaaa1adc09821d2f4443ee2b687ba2",
+31 -1
查看文件
@@ -28,6 +28,36 @@ def masked_kernel(source):
f' %dyVector{value} = shufflevector <3 x float> %dyScalar{value}, <3 x float> undef, <3 x i32> zeroinitializer',
f' {target} = tail call <3 x float> @air.mix.v3f32(<3 x float> %v{before}, <3 x float> %dyRaw{value}, <3 x float> %dyVector{value}) #1']
body='\n'.join(lines)
# A second, explicitly ranged entry lets anchored extra tools interrupt the
# existing native instruction order. The historical entry above is unchanged.
segment = body.replace('@dy_gradeMasked(', '@dy_gradeSegment(', 1)
segment = segment.replace(') local_unnamed_addr #0 {', ', i32 %dyStageFirst, i32 %dyStageLast, <3 x float> %dyExternalSkinReference, <3 x float> %dyOriginalReference) local_unnamed_addr #0 {', 1)
for stage, (value, before, section) in enumerate(stages):
target = f' %dyScalar{value} = insertelement <3 x float> undef, float %dyWeight{section}, i64 0'
replacement = '\n'.join([
f' %dyAtOrAfter{value} = icmp ule i32 %dyStageFirst, {stage}',
f' %dyAtOrBefore{value} = icmp uge i32 %dyStageLast, {stage}',
f' %dyStageActive{value} = and i1 %dyAtOrAfter{value}, %dyAtOrBefore{value}',
f' %dyEffective{value} = select i1 %dyStageActive{value}, float %dyWeight{section}, float 0.000000e+00',
target.replace(f'%dyWeight{section}', f'%dyEffective{value}')])
assert target in segment
segment = segment.replace(target, replacement, 1)
skin_call = ' %dyRaw669 = tail call fast fastcc <3 x float> @_ZL19applySkinProtection'
assert skin_call in segment
segment = segment.replace(skin_call, ' %dyHasLocalSkinReference = icmp ule i32 %dyStageFirst, 5\n %dySkinReference = select i1 %dyHasLocalSkinReference, <3 x float> %v411, <3 x float> %dyExternalSkinReference\n'+skin_call, 1)
segment = segment.replace('(<3 x float> %v668, <3 x float> %v411,', '(<3 x float> %v668, <3 x float> %dySkinReference,', 1)
# Highlight/shadow spatial weighting uses the same original post-CST
# reference as the historical fused function, not a later segment's input.
original_luma = next(line for line in segment.splitlines() if line.startswith(' %v213 = '))
assert '@air.dot.v3f32(<3 x float> %v53,' in original_luma
segment = segment.replace(original_luma, original_luma.replace('<3 x float> %v53,', '<3 x float> %dyOriginalReference,'), 1)
clamp = next(line for line in segment.splitlines() if line.startswith(' %v672 = '))
segment = segment.replace(clamp, '\n'.join([
clamp.replace('%v672 = ', '%dyClamped672 = ', 1),
' %dyIncludesFinalFirst = icmp ule i32 %dyStageFirst, 11',
' %dyIncludesFinalLast = icmp uge i32 %dyStageLast, 11',
' %dyIncludesFinal = and i1 %dyIncludesFinalFirst, %dyIncludesFinalLast',
' %v672 = select i1 %dyIncludesFinal, <3 x float> %dyClamped672, <3 x float> %v669']), 1)
skin='''
define <3 x float> @dy_skinExtra(<3 x float> %color, <3 x float> %reference, %struct.DYUniforms addrspace(2)* %uniforms) {
entry:
@@ -35,4 +65,4 @@ entry:
ret <3 x float> %result
}
'''
return source+'\n'+body+'\n'+skin
return source+'\n'+body+'\n'+segment+'\n'+skin
+3 -3
查看文件
@@ -6,7 +6,7 @@ out=Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/fcp-qa');out.mkdi
media=out/'大鱼调色_蒙版合成运动.mov'
if not media.exists():
subprocess.run(['/opt/homebrew/bin/ffmpeg','-v','error','-f','lavfi','-i',"nullsrc=s=1080x640:r=25:d=4,geq=lum='128+70*sin(X/11)*cos(Y/9)+35*sin((X+Y)/4)':cb='128+35*sin(X/17)':cr='128+35*cos(Y/21)',crop=960:540:'40+10*t':'40+5*t'",'-c:v','prores_ks','-profile:v','2','-pix_fmt','yuv422p10le','-color_primaries','bt709','-color_trc','bt709','-colorspace','bt709',str(media)],check=True)
root=E.Element('fcpxml',version='1.12');res=E.SubElement(root,'resources');E.SubElement(res,'format',id='f1',width='960',height='540',frameDuration='1/25s',colorSpace='1-1-1 (Rec. 709)');a=E.SubElement(res,'asset',id='a1',name='合成运动纹理',start='0s',duration='4s',format='f1',hasVideo='1',videoSources='1');E.SubElement(a,'media-rep',kind='original-media',src=media.as_uri());template=Path('/Users/mac/Movies/Motion Templates.localized/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef');E.SubElement(res,'effect',id='fx',name='大鱼调色',uid='~/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef',src=template.as_uri());lib=E.SubElement(root,'library');event=E.SubElement(lib,'event',name='大鱼调色_1.4_23_蒙版与工具层验收')
for name in ['大鱼调色_1.4_23_独立工具与蒙版','大鱼调色_1.4_23_逐帧跟踪']:
root=E.Element('fcpxml',version='1.12');res=E.SubElement(root,'resources');E.SubElement(res,'format',id='f1',width='960',height='540',frameDuration='1/25s',colorSpace='1-1-1 (Rec. 709)');a=E.SubElement(res,'asset',id='a1',name='合成运动纹理',start='0s',duration='4s',format='f1',hasVideo='1',videoSources='1');E.SubElement(a,'media-rep',kind='original-media',src=media.as_uri());template=Path('/Users/mac/Movies/Motion Templates.localized/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef');E.SubElement(res,'effect',id='fx',name='大鱼调色',uid='~/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef',src=template.as_uri());lib=E.SubElement(root,'library');event=E.SubElement(lib,'event',name='大鱼调色_1.4.1_26_蒙版与工具层验收')
for name in ['大鱼调色_1.4.1_26_独立工具与蒙版','大鱼调色_1.4.1_26_逐帧跟踪']:
project=E.SubElement(event,'project',name=name);seq=E.SubElement(project,'sequence',format='f1',tcStart='0s',tcFormat='NDF',audioLayout='stereo',audioRate='48k',duration='4s');spine=E.SubElement(seq,'spine');clip=E.SubElement(spine,'asset-clip',ref='a1',name=name,offset='0s',start='0s',duration='4s');E.SubElement(clip,'filter-video',ref='fx',name='大鱼调色',enabled='1')
E.indent(root);xml=out/'大鱼调色_1.4_23_蒙版与工具层.fcpxml';xml.write_text('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE fcpxml>\n'+E.tostring(root,encoding='unicode')+'\n');print(xml)
E.indent(root);xml=out/'大鱼调色_1.4.1_26_蒙版与工具层.fcpxml';xml.write_text('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE fcpxml>\n'+E.tostring(root,encoding='unicode')+'\n');print(xml)
+105
查看文件
@@ -0,0 +1,105 @@
// Independent generated-image oracles for free-path ROI, subpixel motion,
// anisotropic transforms, feature capacity, and loss protection. No host UI.
#import <Foundation/Foundation.h>
#include "../大鱼调色/Plugin/MaskCore/DYTracker.hpp"
#include "../大鱼调色/Plugin/DYToolFlow.inc.h"
#include <chrono>
static float noise(int x,int y,uint32_t seed=0) {
uint32_t n=uint32_t(x)*73856093u^uint32_t(y)*19349663u^seed;
n^=n>>13;n*=1274126177u;n^=n>>16;
return .1f+.8f*float(n&65535)/65535.f;
}
static float scene(float x,float y,bool extended=false,uint32_t seed=0) {
if(extended&&(x<251||x>379||y<77||y>307))return .5f;
float gx=x/3.f,gy=y/3.f;int ix=int(std::floor(gx)),iy=int(std::floor(gy));
float dx=gx-ix,dy=gy-iy;
return (1-dy)*((1-dx)*noise(ix,iy,seed)+dx*noise(ix+1,iy,seed))+
dy*((1-dx)*noise(ix,iy+1,seed)+dx*noise(ix+1,iy+1,seed));
}
static dy::GrayFrame frame(int w,int h,double tx=0,double ty=0,double angle=0,
double sx=1,double sy=1,bool extended=false,uint32_t seed=0) {
dy::GrayFrame f{w,h,std::vector<float>(size_t(w)*h)};
double cx=w*(extended?.35:.5),cy=h*.5,c=cos(angle),s=sin(angle);
for(int y=0;y<h;y++)for(int x=0;x<w;x++) {
double dx=x-cx-tx,dy=y-cy-ty;
float u=float((c*dx+s*dy)/sx+cx),v=float((-s*dx+c*dy)/sy+cy);
f.pixels[y*w+x]=scene(u,v,extended,seed);
}
return f;
}
int main(int argc,const char*argv[]) {@autoreleasepool {
NSMutableArray *checks=[NSMutableArray array];bool all=true;
auto record=[&](NSString *name,bool pass,NSDictionary *extra=nil) {
NSMutableDictionary *d=[NSMutableDictionary dictionaryWithDictionary:extra?:@{}];
d[@"name"]=name;d[@"pass"]=@(pass);[checks addObject:d];all&=pass;
};
NSURL *library=argc>1?[NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]]:nil;
for(int mode=0;mode<(library?2:1);mode++) {
NSString *prefix=mode?@"metal":@"cpu";
auto setup=[&](dy::Tracker& tracker) {
if(!mode)return true;
NSError *error=nil;auto backend=DYToolCreateMetalFlow(library,&error);
if(!backend){record([prefix stringByAppendingString:@"-backend"],false,@{@"error":error.localizedDescription?:@"unavailable"});return false;}
tracker.setBackend(backend);return true;
};
{
dy::Tracker tracker;if(!setup(tracker))continue;
tracker.setMask({{.8f,-.5f},{1.8f,-.5f},{1.8f,.5f},{.8f,.5f}});
auto f=frame(512,384,0,0,0,1,1,true);
bool started=tracker.reset(f,{.35f,.5f,.2f,.45f,0});
record([prefix stringByAppendingString:@"-pen-texture-outside-creation-box-starts"],started,
@{@"features":@(tracker.result().features)});
bool passed=started;dy::TrackResult result;
for(int i=1;i<=12&&passed;i++) {result=tracker.track(frame(512,384,1.25*i,.5*i,0,1,1,true));passed=result.valid;}
double ex=fabs(result.cx-(.35+15./512))*512,ey=fabs(result.cy-(.5+6./384))*384;
record([prefix stringByAppendingString:@"-extended-pen-region-subpixel-motion"],passed&&ex<.65&&ey<.65,
@{@"xErrorPixels":@(ex),@"yErrorPixels":@(ey)});
}
{
dy::Tracker tracker;if(!setup(tracker))continue;
auto f=frame(640,480);bool started=tracker.reset(f,{.5,.5,.85,.85,0});
record([prefix stringByAppendingString:@"-real-300-feature-capacity"],started&&tracker.result().features==300,
@{@"features":@(tracker.result().features)});
auto result=tracker.track(frame(640,480,2.25,-1.5,.025,1.025,.98));
double ex=fabs(result.cx-(.5+2.25/640))*640,ey=fabs(result.cy-(.5-1.5/480))*480;
record([prefix stringByAppendingString:@"-translation-rotation-independent-xy-scale"],
started&&result.valid&&ex<.5&&ey<.5&&fabs(result.rotation-.025)<.004&&fabs(result.scaleX-1.025)<.005&&fabs(result.scaleY-.98)<.005,
@{@"xErrorPixels":@(ex),@"yErrorPixels":@(ey),@"rotation":@(result.rotation),@"scaleX":@(result.scaleX),@"scaleY":@(result.scaleY)});
}
{
dy::Tracker tracker;if(!setup(tracker))continue;
auto f=frame(640,480);bool passed=tracker.reset(f,{.5,.5,.65,.65,0});dy::TrackResult result;
for(int i=1;i<=6&&passed;i++){result=tracker.track(f);passed=result.valid;}
record([prefix stringByAppendingString:@"-subpixel-refinement-and-redetection-remain-stationary"],passed&&fabs(result.cx-.5)*640<.05&&fabs(result.cy-.5)*480<.05);
}
{
dy::Tracker tracker;if(!setup(tracker))continue;
auto f=frame(640,480);bool started=tracker.reset(f,{.5,.5,.7,.7,0});
auto result=tracker.track(frame(640,480,0,0,0,1,1,false,0x3344));
record([prefix stringByAppendingString:@"-unrelated-cut-is-not-trusted-motion"],started&&!result.valid&&!tracker.active());
dy::GrayFrame flat{640,480,std::vector<float>(640*480,.5f)};
record([prefix stringByAppendingString:@"-flat-region-still-refuses-tracking"],!tracker.reset(flat,{.5,.5,.7,.7,0}));
}
{
dy::Tracker tracker;if(!setup(tracker))continue;
auto t=std::chrono::steady_clock::now();auto f=frame(1920,1080);bool started=tracker.reset(f,{.5,.5,.5,.5,0});
auto result=tracker.track(frame(1920,1080,4,2));
double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-t).count();
record([prefix stringByAppendingString:@"-1080p-complete-frame-motion"],started&&result.valid&&fabs(result.cx-(.5+4./1920))*1920<.5&&fabs(result.cy-(.5+2./1080))*1080<.5,
@{@"generatedFramesAndAnalysisMilliseconds":@(ms),@"features":@(result.features)});
}
{
dy::Tracker tracker;if(!setup(tracker))continue;
auto t=std::chrono::steady_clock::now();auto f=frame(3840,2160);bool started=tracker.reset(f,{.5,.5,.5,.5,0});
auto result=tracker.track(frame(3840,2160,8,4));
double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-t).count();
record([prefix stringByAppendingString:@"-3840x2160-complete-frame-motion"],started&&result.valid&&fabs(result.cx-(.5+8./3840))*3840<.5&&fabs(result.cy-(.5+4./2160))*2160<.5,
@{@"generatedFramesAndAnalysisMilliseconds":@(ms),@"features":@(result.features)});
}
}
NSDictionary *report=@{@"pass":@(all),@"checks":checks,@"scope":@"Independent generated images, CPU tracker and optional real Metal optical flow. No app or GUI host launched.",@"sourceApplicationRuntimeDependency":@NO};
NSData *json=[NSJSONSerialization dataWithJSONObject:report options:NSJSONWritingPrettyPrinted error:nil];
fwrite(json.bytes,1,json.length,stdout);fputc('\n',stdout);return all?0:1;
}}
+9 -7
查看文件
@@ -2,16 +2,18 @@
"status": "verified",
"path": "/Library/Plug-Ins/FxPlug/大鱼调色.app",
"bundleID": "com.dayu.color",
"version": "1.4.0",
"build": "24",
"version": "1.4.1",
"build": "26",
"team": "B3W25FX5H5",
"notaryID": "40fdaaaa-1821-4cc8-bec3-c5dc6d8b9f77",
"notaryID": "1ddc5499-2da3-4d98-8b2d-09272b0ee326",
"notaryStatus": "Accepted",
"gatekeeper": "/Library/Plug-Ins/FxPlug/大鱼调色.app: accepted\nsource=Notarized Developer ID",
"sourceCommit": "dbf25fe6719f17075362538dad0404951102524d",
"sourceCommit": "0eb56aed126c825ca89712ce90f8cc1c05b03d89",
"templatePath": "/Users/mac/Movies/Motion Templates.localized/Effects.localized/大鱼调色/大鱼调色/大鱼调色.moef",
"templateSHA256": "9b8f6e407545429b77c1de88d4cceb738760771c5a7f1dbd9732bdcc95c23738",
"shaderSHA256": "df82ed0310281e854085063276ab161db7c623511751a1c1c63607b4072c8097",
"hostVerification": "verification/HostToolMasks.json",
"hostCanvasGestureVerification": "unverified-live-host; native simulator passed"
"shaderSHA256": "757b240921846ed06ca294a9bbfbd4aee5d41c6361a3918254a806187eb997ea",
"hostVerification": "verification/HostMaskWorkflow1.4.1.json",
"hostVerificationLimitations": [
"实际鼠标钢笔落点和闭合待用户确认;原生OSC模拟检查通过。"
]
}
+101
查看文件
@@ -0,0 +1,101 @@
{
"status": "verified-with-explicit-pen-gesture-gap",
"host": "Final Cut Pro 12.4",
"formalApp": "/Library/Plug-Ins/FxPlug/大鱼调色.app",
"fixtureProject": "大鱼调色_1.4.1_25_独立工具与蒙版",
"preliminaryBuild": "25",
"newDocumentSchema": 2,
"checks": [
{
"name": "native-inspector-add-layer-immediately-after-source",
"passed": true,
"evidence": "AX HSL base → HSL2 → HSL3 → Curve; schema2 after anchors match"
},
{
"name": "repeated-add-at-original-inserts-before-existing-child",
"passed": true,
"newLayerID": "276668CB-1409-43E2-8967-012378413F4E",
"oldLayerID": "B27B1FDF-EEEB-4307-8CE5-9F8128BB8F0D",
"newValues": {},
"oldValues": {
"hsl0_0": 32.0
}
},
{
"name": "larger-mask-inspector-readable-in-formal-FCP",
"passed": true,
"evidence": "Observed screenshot: full-width sliders, large values and separate drawing rows"
},
{
"name": "new-pen-enters-drawing-and-disables-tracking",
"passed": true,
"evidence": "Inspector drawing buttons enabled; tracking disabled; empty canvas draft and draw status"
},
{
"name": "cold-reopen-entire-preset-byte-exact",
"passed": true
},
{
"name": "upright-canvas-pen-hint-and-symbols",
"passed": true,
"evidence": "Final installed build 26 FCP screenshot"
},
{
"name": "native-FCP-bezier-forward-tracking",
"passed": true,
"keys": 99,
"mask": "Existing default closed 4-point Bezier; no claim of real-mouse drawn path"
},
{
"name": "single-undo-clears-track-and-redo-exactly-restores-full-preset",
"passed": true
}
],
"presetBefore": {
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/fcp-qa/workflow25-before-reopen.json",
"bytes": 8258,
"sha256": "9654ff3be150928e20f1b8536227bc39169997f36c6b82f91c3c945ef1fbcb0a"
},
"limitations": [
"CUA coordinate clicks do not enter the FCP native OSC hit/event callback. Actual-mouse pen placement/closure remains unconfirmed pending user reply. Native real-OSC simulated-host tests passed separately.",
"No claim of full Color Finale migration or same-real-video trajectory parity.",
"Old schema1 tail layers keep their saved position and rendering for compatibility."
],
"userMediaModified": false,
"finalBuild": "26",
"compiledSource": "0eb56aed126c825ca89712ce90f8cc1c05b03d89",
"formalXPCProcess": 8304,
"formalHostProcess": 8287,
"singlePluginKitPath": true,
"presets": {
"workflow26-after-reopen.json": {
"sha256": "9654ff3be150928e20f1b8536227bc39169997f36c6b82f91c3c945ef1fbcb0a",
"keys": 0,
"layers": 2,
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/fcp-qa/workflow26-after-reopen.json"
},
"workflow26-tracked.json": {
"sha256": "b7c76ab254a0f0edd7f3bd6cc116a6d56966212267834350d6b16adfe17c8873",
"keys": 99,
"layers": 2,
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/fcp-qa/workflow26-tracked.json"
},
"workflow26-undo.json": {
"sha256": "9654ff3be150928e20f1b8536227bc39169997f36c6b82f91c3c945ef1fbcb0a",
"keys": 0,
"layers": 2,
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/fcp-qa/workflow26-undo.json"
},
"workflow26-redo.json": {
"sha256": "b7c76ab254a0f0edd7f3bd6cc116a6d56966212267834350d6b16adfe17c8873",
"keys": 99,
"layers": 2,
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/fcp-qa/workflow26-redo.json"
}
},
"nativeChecks": {
"checks": 281,
"passResult": true,
"timingNote": "First build26 cache run had 280/281: external-activation-main-loop-responsive had 0 heartbeat /155.951ms; repeat, Release preflight, and installed runs all281 pass. Commit0eb56ae message prematurely said281pass before inspecting the initial run."
}
}
+26
查看文件
@@ -0,0 +1,26 @@
2026-11-01 22:38:15.062 Df 大鱼调色 XPC Service[2015:f58e1b] dayu_tool_osc_hit x=1043.19 y=497.04 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.122 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=982.30 y=678.64 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.140 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=969.16 y=688.19 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.160 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=969.16 y=688.19 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.306 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=905.88 y=707.31 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.325 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=878.42 y=667.88 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.356 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=870.06 y=648.77 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.376 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=859.31 y=612.93 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.395 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=858.12 y=592.62 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.410 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=858.12 y=586.65 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.504 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=859.31 y=580.67 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.692 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_hit x=859.31 y=580.67 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:15.702 Df 大鱼调色 XPC Service[2015:f58e1b] dayu_tool_osc_event type=1 part=1 x=859.31 y=580.67 plugin=1
2026-11-01 22:38:15.708 Df 大鱼调色 XPC Service[2015:f59ed4] dayu_tool_osc_event type=6 part=1 x=880.81 y=584.26 plugin=1
2026-11-01 22:38:15.760 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_event type=6 part=1 x=895.13 y=586.65 plugin=1
2026-11-01 22:38:15.826 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_event type=6 part=1 x=915.43 y=586.65 plugin=1
2026-11-01 22:38:15.843 Df 大鱼调色 XPC Service[2015:f58e1b] dayu_tool_osc_event type=6 part=1 x=916.63 y=586.65 plugin=1
2026-11-01 22:38:15.863 Df 大鱼调色 XPC Service[2015:f5c5a6] dayu_tool_osc_event type=6 part=1 x=919.01 y=586.65 plugin=1
2026-11-01 22:38:15.876 Df 大鱼调色 XPC Service[2015:f5c707] dayu_tool_osc_event type=6 part=1 x=921.40 y=586.65 plugin=1
2026-11-01 22:38:15.893 Df 大鱼调色 XPC Service[2015:f5c708] dayu_tool_osc_event type=6 part=1 x=921.40 y=585.45 plugin=1
2026-11-01 22:38:15.910 Df 大鱼调色 XPC Service[2015:f5c5a4] dayu_tool_osc_event type=6 part=1 x=923.79 y=585.45 plugin=1
2026-11-01 22:38:15.929 Df 大鱼调色 XPC Service[2015:f58e1b] dayu_tool_osc_event type=6 part=1 x=924.99 y=584.26 plugin=1
2026-11-01 22:38:16.009 Df 大鱼调色 XPC Service[2015:f5c5a6] dayu_tool_osc_event type=6 part=1 x=932.15 y=577.09 plugin=1
2026-11-01 22:38:16.026 Df 大鱼调色 XPC Service[2015:f5c5a6] dayu_tool_osc_event type=6 part=1 x=934.54 y=572.31 plugin=1
2026-11-01 22:38:17.140 Df 大鱼调色 XPC Service[2015:f59ed4] dayu_tool_osc_hit x=527.37 y=673.86 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
2026-11-01 22:38:17.158 Df 大鱼调色 XPC Service[2015:f5c708] dayu_tool_osc_hit x=546.48 y=610.54 height=1134.00 rect=-0.00,141.19,1514.00,851.63 mask=1 hit=1
+24 -4
查看文件
@@ -1,5 +1,5 @@
{
"status": "host-workflows-passed-with-manual-canvas-drag-unverified",
"status": "host-workflows-and-user-operated-center-drag-passed",
"version": "1.4.0",
"build": "24",
"host": "Final Cut Pro 12.4",
@@ -22,7 +22,8 @@
"extraLayerSingleFrameTwoKeys": true,
"singleFramePlayhead": "00:00:00:01 to 00:00:00:02",
"coldReopenCompletePresetByteExact": true,
"formalExecutablePathVerified": true
"formalExecutablePathVerified": true,
"liveCanvasCenterDragUserVerified": true
},
"presets": {
"independent": {
@@ -76,9 +77,28 @@
},
"nativeChecks": 222,
"limitations": [
"Live FCP displays the native mask outline and toolbar, but automated coordinate clicks did not enter the plugin hit/event callbacks. Live canvas drag/rotate/pen gestures are unverified. Direct native OSC regression verifies real Metal overlay, hit testing, queued drag write, one undo and Escape through a host simulator; this is not a live gesture result.",
"Live FCP center dragging is confirmed by the user and by native hit/mouseDown/mouseDragged logs; AX values changed on the intended original HSL mask while the extra HSL mask remained unchanged. Live rotation, resize and pen gestures remain unverified; direct native OSC simulator regressions pass.",
"Live FCP covers forward, bidirectional and single-frame tracking. Cancellation, stale-target rejection and backward cadence are additionally covered by native simulated host scheduling.",
"Motion, Intel, older systems, non-square-pixel/cropped/retimed projects are unverified. Tracking covers translation, rotation and independent XY scale, not perspective or shear.",
"Extra scalar tool values are static author data. Temporal mask tracks are supported. Spatial masks cannot be exported into Cube; complete presets preserve them."
]
],
"manualCanvasAcceptance": {
"confirmedBy": "User in this chat",
"confirmation": "Mask follows the actual mouse when dragged.",
"verifiedAt": "2026-11-01T14:39:11.615310+00:00",
"baseEllipseBefore": [
0.6,
0.5
],
"baseEllipseAfterAX": [
0.378,
0.379
],
"independentExtraRectangleAfterAX": [
0.5,
0.5
],
"nativeHitAndDragCallbacksObserved": true,
"userChangesPreserved": true
}
}
+317 -7
查看文件
@@ -1,6 +1,6 @@
{
"bundlePath": "/Library/Plug-Ins/FxPlug/大鱼调色.app/Contents/PlugIns/大鱼调色 XPC Service.pluginkit",
"checks": 222,
"checks": 281,
"gpu": "Apple M4",
"limitations": [
"Finite states and a 64x48 frame; live FCP discovery, inspector interaction, timeline persistence and real host export require separate acceptance.",
@@ -12,7 +12,7 @@
"error": "未提供错误信息",
"name": "runtime-directory",
"pass": true,
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime/620C8AC1-C8E5-4503-807C-965B588D8082"
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime/61021897-A6C6-4361-A981-22AAA9838782"
},
{
"descriptors": 234,
@@ -816,7 +816,7 @@
"error": "未提供错误信息",
"name": "renderer-export-33cube",
"pass": true,
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime/620C8AC1-C8E5-4503-807C-965B588D8082/diagnostic-export.cube"
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime/61021897-A6C6-4361-A981-22AAA9838782/diagnostic-export.cube"
},
{
"bytes": 1186074,
@@ -836,7 +836,7 @@
},
{
"heartbeats": 0,
"maximumGapMS": 90.16550006344914,
"maximumGapMS": 88.72558339498937,
"name": "external-activation-main-loop-responsive",
"pass": true
},
@@ -1109,13 +1109,243 @@
"name": "primary-mask-blends-cst-only-in-selected-region",
"pass": true
},
{
"name": "inserted-tool-documents-have-validated-anchors",
"pass": true
},
{
"name": "repeat-splices-immediately-after-clicked-base-or-extra",
"pass": true
},
{
"name": "inserted-tools-start-with-independent-initial-values",
"pass": true
},
{
"name": "inserted-order-secure-archive-roundtrip",
"pass": true
},
{
"name": "insertion-rejects-unknown-base-anchor",
"pass": true
},
{
"name": "insertion-rejects-cyclic-anchor",
"pass": true
},
{
"name": "delete-reconnects-child-without-moving-to-bottom",
"pass": true
},
{
"name": "new-native-card-is-laid-out-between-its-source-and-next-module",
"pass": true
},
{
"name": "schema-one-tail-layer-retains-tail-root-with-new-child",
"pass": true
},
{
"error": "未提供错误信息",
"name": "insertion-original-fused-oracle",
"pass": true
},
{
"error": "未提供错误信息",
"name": "insertion-neutral-child-render",
"pass": true
},
{
"name": "untouched-inserted-tool-preserves-original-fused-pixels-exactly",
"pass": true
},
{
"error": "",
"name": "insertion-base-hsl-reference",
"pass": true
},
{
"error": "",
"name": "insertion-extra-hsl-reference",
"pass": true
},
{
"error": "",
"name": "insertion-later-native-grading-reference",
"pass": true
},
{
"error": "未提供错误信息",
"name": "anchored-hsl-before-grading-render",
"pass": true
},
{
"changedComponents": 744,
"maxAbsoluteError": 0.00146484375,
"name": "anchored-hsl-executes-before-later-native-grading",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"error": "未提供错误信息",
"name": "historical-tail-hsl-render",
"pass": true
},
{
"changedComponents": 5323,
"maxAbsoluteError": 0.0623779296875,
"name": "anchored-hsl-is-not-only-a-visual-move-from-tail",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"error": "",
"name": "anchored-curve-first-reference",
"pass": true
},
{
"changedComponents": 2715,
"maxAbsoluteError": 0.34765625,
"name": "curve-anchor-reference-materially-adjusts-red-channel",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"error": "",
"name": "anchored-hsl-second-reference",
"pass": true
},
{
"error": "未提供错误信息",
"name": "two-native-anchor-render",
"pass": true
},
{
"changedComponents": 0,
"maxAbsoluteError": 0,
"name": "two-anchors-preserve-native-curve-before-hsl-operation-order",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"error": "",
"name": "wrong-hsl-before-curve-reference",
"pass": true
},
{
"error": "",
"name": "wrong-curve-after-hsl-reference",
"pass": true
},
{
"changedComponents": 2823,
"maxAbsoluteError": 0.03271484375,
"name": "anchor-reference-operations-are-noncommuting",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 0,
"maxAbsoluteError": 0,
"name": "anchored-primary-cst-runs-once-before-native-stages",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 1929,
"maxAbsoluteError": 0.0009765625,
"name": "anchored-split-retains-native-pre-hsl-skin-reference",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 2377,
"maxAbsoluteError": 0.0009765625,
"name": "anchored-prefix-preserves-whites-statistics-and-spatial-base-input",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 252,
"maxAbsoluteError": 0.0009765625,
"name": "anchored-legacy-input-lut-remains-available-to-spatial-neighbors",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 2240,
"maxAbsoluteError": 0.0009765625,
"name": "anchored-original-color-mask-keeps-post-cst-source-reference",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 2490,
"maxAbsoluteError": 0.00146484375,
"name": "anchored-split-preserves-second-base-chroma-stage",
"nonfiniteComponents": 0,
"nonzeroComponents": 9734,
"pass": true
},
{
"changedComponents": 173,
"maxAbsoluteError": 0.0009765625,
"name": "anchored-spider-remains-after-native-color-stages",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 2016,
"maxAbsoluteError": 0.0009765625,
"name": "anchored-bw-suffix-defers-color-mixture-until-after-native-skin",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 1974,
"maxAbsoluteError": 0.001220703125,
"name": "anchored-look-suffix-keeps-bw-mixture-before-single-spider",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"changedComponents": 0,
"maxAbsoluteError": 0,
"name": "zero-strength-extra-mask-preserves-hdr-and-negative-colors",
"nonfiniteComponents": 0,
"nonzeroComponents": 9832,
"pass": true
},
{
"error": "未提供错误信息",
"name": "inserted-cube-production-sample",
"pass": true
},
{
"error": "未提供错误信息",
"name": "cube-export-follows-identical-anchored-tool-order",
"pass": true
},
{
"name": "tracking-captures-real-full-input-texture",
"pass": true
},
{
"centerX": 0.5312505960464478,
"centerY": 0.5260424017906189,
"centerX": 0.5312501192092896,
"centerY": 0.52604079246521,
"error": "未提供错误信息",
"keyCount": 6,
"name": "host-callback-metal-tracking-six-exact-frames",
@@ -1171,8 +1401,88 @@
{
"name": "native-osc-escape-discards-draft-without-host-edit",
"pass": true
},
{
"name": "inspector-add-pen-enters-empty-drawing-mode",
"pass": true
},
{
"name": "pen-can-start-anywhere-in-image-outside-default-shape",
"pass": true
},
{
"name": "pen-point-snapshot-updates-before-main-queue-without-author-write",
"pass": true
},
{
"name": "pen-cursor-previews-next-segment-without-parameter-or-undo-writes",
"pass": true
},
{
"name": "pen-drag-creates-mirrored-cubic-handles",
"pass": true
},
{
"name": "pen-first-anchor-hit-closes-path-after-three-points",
"pass": true
},
{
"name": "pen-closed-cubic-path-persists-once-and-keeps-neighbor-mask",
"pass": true
},
{
"name": "pen-cubic-nodes-survive-secure-document-roundtrip",
"pass": true
},
{
"name": "pen-delete-removes-last-uncommitted-point",
"pass": true
},
{
"name": "pen-escape-cancels-without-overwriting-saved-curve",
"pass": true
},
{
"name": "pen-inspector-finish-commits-without-viewer-keyboard-focus",
"pass": true
},
{
"name": "pen-inspector-cancel-preserves-saved-curve-and-undo-count",
"pass": true
},
{
"name": "pen-return-closes-and-saves-native-path",
"pass": true
},
{
"name": "pen-finish-and-next-gesture-serialize-without-dropping-either",
"pass": true
},
{
"name": "pen-refuses-to-finish-stale-draft-after-playhead-moves",
"pass": true
},
{
"name": "native-pen-panel-routes-redraw-finish-and-cancel-to-own-mask",
"pass": true
},
{
"name": "pen-panel-disables-tracking-through-refresh-and-restores-after-own-finish",
"pass": true
},
{
"name": "mask-panel-readable-fields-and-button-targets-at-native-narrow-width",
"pass": true
},
{
"name": "six-mask-panel-layouts-fit-220-300-and-420-point-widths",
"pass": true
},
{
"name": "pen-drawing-actions-visible-only-for-bezier-mask",
"pass": true
}
],
"runtimePath": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime/620C8AC1-C8E5-4503-807C-965B588D8082",
"runtimePath": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/verification-runtime/61021897-A6C6-4361-A981-22AAA9838782",
"scope": "Native model and renderer integration with real Metal/IOSurface textures and fake FxPlug host selectors; no GUI or live host document."
}
+18
查看文件
@@ -0,0 +1,18 @@
{
"passResult": true,
"build": "26",
"removedEarlierBackup": [
"/Library/Plug-Ins/FxPlug/.dayu-color-previous-57969b9e8916483b9ac4e8aa4ac25f61.app"
],
"immediateBuild25Backup": "removed by tools/deliver.py after host verification",
"copiesInInspectedRoots": [
"/Library/Plug-Ins/FxPlug/大鱼调色.app"
],
"scope": [
"/Library/Plug-Ins/FxPlug",
"/Applications",
"/Users/mac/Library/Plug-Ins/FxPlug",
"/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/DerivedData/Build/Products/Release"
],
"historicalPackagesPreserved": true
}
+15
查看文件
@@ -0,0 +1,15 @@
{
"passResult": true,
"repository": "https://dayu.media/git/dayu/dayu-color.git",
"sourceCommit": "0eb56aed126c825ca89712ce90f8cc1c05b03d89",
"restoredFiles": 224,
"fsck": "full strict passed",
"rebuiltShaderSHA256": "757b240921846ed06ca294a9bbfbd4aee5d41c6361a3918254a806187eb997ea",
"templateRebuiltFromNativeModel": true,
"templateSHA256": "9b8f6e407545429b77c1de88d4cceb738760771c5a7f1dbd9732bdcc95c23738",
"LFS": false,
"submodules": false,
"cloneCleaned": true,
"formalShaderSHA256": "757b240921846ed06ca294a9bbfbd4aee5d41c6361a3918254a806187eb997ea",
"formalShaderMatches": true
}
+16 -16
查看文件
@@ -1,7 +1,7 @@
{
"package": "/Volumes/备份/大鱼调色/发行包/大鱼调色-1.4.0.pkg",
"sha256": "16a4958e28bc2a43c40e6131067eb03a49aecba5bbe3c0424bc7024fa532af38",
"bytes": 14250425,
"package": "/Volumes/备份/大鱼调色/发行包/大鱼调色-1.4.1.pkg",
"sha256": "0c167aba339bbfdd9c4cbd96aea384e2d43f6d498629ebaf7b1c18cbc6dca5c6",
"bytes": 14337616,
"testUnsigned": false,
"installationExecuted": false,
"checks": [
@@ -31,27 +31,27 @@
"source": "/Library/Plug-Ins/FxPlug/大鱼调色.app",
"payload": "Library/Plug-Ins/FxPlug/大鱼调色.app",
"bundleID": "com.dayu.color",
"version": "1.4.0",
"build": "24"
"version": "1.4.1",
"build": "26"
},
{
"source": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/pkg-inputs/大鱼调色",
"payload": "Library/Application Support/PKGForge/Payload/com.dayu.color.installer.994cb613-413c-4c58-8e23-fff445d88e9c/9D262E0D-82D6-436F-AF90-929F0C1FFE78/大鱼调色"
"payload": "Library/Application Support/PKGForge/Payload/com.dayu.color.installer.f2577d05-34d4-4ef1-aa6d-7e7aca56f716/4CA0FF20-56AD-40A6-9383-45374239C928/大鱼调色"
}
],
"signature": "Package \"大鱼调色-1.4.0.pkg\":\n Status: signed by a developer certificate issued by Apple for distribution\n Notarization: trusted by the Apple notary service\n Signed with a trusted timestamp on: 2026-11-01 14:34:31 +0000\n Certificate Chain:\n 1. Developer ID Installer: zhong luo (B3W25FX5H5)\n Expires: 2027-02-01 22:12:15 +0000\n SHA256 Fingerprint:\n C0 19 01 3C 67 88 8F 34 65 56 C5 91 3C E5 B6 12 4C 5D A6 DA F9 D8 \n DA 00 37 52 DF F0 F3 E6 00 B4\n ------------------------------------------------------------------------\n 2. Developer ID Certification Authority\n Expires: 2027-02-01 22:12:15 +0000\n SHA256 Fingerprint:\n 7A FC 9D 01 A6 2F 03 A2 DE 96 37 93 6D 4A FE 68 09 0D 2D E1 8D 03 \n F2 9C 88 CF B0 B1 BA 63 58 7F\n ------------------------------------------------------------------------\n 3. Apple Root CA\n Expires: 2035-02-09 21:40:36 +0000\n SHA256 Fingerprint:\n B0 B1 73 0E CB C7 FF 45 05 14 2C 49 F1 29 5E 6E DA 6B CA ED 7E 2C \n 68 C5 BE 91 B5 A1 10 01 F0 24",
"gatekeeper": "/Volumes/备份/大鱼调色/发行包/大鱼调色-1.4.0.pkg: accepted\nsource=Notarized Developer ID",
"signature": "Package \"大鱼调色-1.4.1.pkg\":\n Status: signed by a developer certificate issued by Apple for distribution\n Notarization: trusted by the Apple notary service\n Signed with a trusted timestamp on: 2026-11-01 15:38:31 +0000\n Certificate Chain:\n 1. Developer ID Installer: zhong luo (B3W25FX5H5)\n Expires: 2027-02-01 22:12:15 +0000\n SHA256 Fingerprint:\n C0 19 01 3C 67 88 8F 34 65 56 C5 91 3C E5 B6 12 4C 5D A6 DA F9 D8 \n DA 00 37 52 DF F0 F3 E6 00 B4\n ------------------------------------------------------------------------\n 2. Developer ID Certification Authority\n Expires: 2027-02-01 22:12:15 +0000\n SHA256 Fingerprint:\n 7A FC 9D 01 A6 2F 03 A2 DE 96 37 93 6D 4A FE 68 09 0D 2D E1 8D 03 \n F2 9C 88 CF B0 B1 BA 63 58 7F\n ------------------------------------------------------------------------\n 3. Apple Root CA\n Expires: 2035-02-09 21:40:36 +0000\n SHA256 Fingerprint:\n B0 B1 73 0E CB C7 FF 45 05 14 2C 49 F1 29 5E 6E DA 6B CA ED 7E 2C \n 68 C5 BE 91 B5 A1 10 01 F0 24",
"gatekeeper": "/Volumes/备份/大鱼调色/发行包/大鱼调色-1.4.1.pkg: accepted\nsource=Notarized Developer ID",
"pass": true,
"scope": "Expanded package structural and payload verification only; no installer scripts executed and no host quit or registration performed.",
"notarization": {
"id": "da6edea3-11f4-451b-aece-91916cca329a",
"createdDate": "2026-11-01T14:34:33.529Z",
"name": "大鱼调色-1.4.0.pkg",
"status": "Accepted",
"message": "Successfully received submission info"
"message": "Successfully received submission info",
"createdDate": "2026-11-01T15:38:33.055Z",
"name": "大鱼调色-1.4.1.pkg",
"id": "9a5ff448-2ac1-444e-b993-2928cf8c333f",
"status": "Accepted"
},
"appCompiledSource": "dbf25fe6719f17075362538dad0404951102524d",
"appBuild": "24",
"appCompiledSource": "0eb56aed126c825ca89712ce90f8cc1c05b03d89",
"appBuild": "26",
"packageBuilderRemote": "https://dayu.media/git/dayu/pkg-forge.git",
"packageBuilderCommit": "eb53707c0e67d8ddeab8c1270bb079f1050cfafe",
"templateSHA256": {
@@ -59,6 +59,6 @@
"large.png": "ab12611e8801cff86332ccc505a4cffa0c1120541c2efb9bb9908be2c9fe631a",
"small.png": "41fec3138aee904fc39d6982e6fde809243ffec55298dbfe966f4f48d89caf8a"
},
"installedAppHostAcceptance": "verification/HostToolMasks.json",
"installedAppHostAcceptance": "verification/HostMaskWorkflow1.4.1.json",
"installScope": "本轮仅生成并验包,未再次执行系统安装;正式 APP 已有独立宿主验收。"
}
+9 -32
查看文件
@@ -1,35 +1,12 @@
{
"passResult": true,
"status": "prepared-before-upload",
"tag": "v1.4.1-mask-workflow-20261101",
"repository": "dayu/dayu-color",
"repositoryID": 52,
"private": false,
"tag": "v1.3.1-browser-recents-20261101",
"releaseCommit": "281721bda11484c23f294b4f0d9e0b30ef829288",
"releaseID": 366,
"releaseURL": "https://dayu.media/git/dayu/dayu-color/releases/tag/v1.3.1-browser-recents-20261101",
"assetID": 12,
"assetName": "大鱼调色-1.3.1.pkg",
"downloadURL": "https://dayu.media/git/dayu/dayu-color/releases/download/v1.3.1-browser-recents-20261101/%E5%A4%A7%E9%B1%BC%E8%B0%83%E8%89%B2-1.3.1.pkg",
"bytes": 14073683,
"sha256": "954b10c581f31d23a8c417a6f37b24fae19939786dce8733b4d6f09c7ed3adae",
"existingAssetReused": true,
"verification": "Authenticated full download SHA-256 and byte count, then release/asset read-back.",
"credentialSource": "macOS Keychain: dayu-git-api",
"status": "published-and-download-verified",
"verifiedAt": "2026-11-01T13:00:20.219723+00:00",
"prePublishDraftDownload": {
"passResult": true,
"path": "/Volumes/备份/大鱼调色-1.3.1.pkg",
"bytes": 14073683,
"sha256": "954b10c581f31d23a8c417a6f37b24fae19939786dce8733b4d6f09c7ed3adae",
"sourceURL": "https://dayu.media/git/dayu/dayu-color/releases/download/v1.3.1-browser-recents-20261101/%E5%A4%A7%E9%B1%BC%E8%B0%83%E8%89%B2-1.3.1.pkg",
"source": "Completed authenticated Edge draft download; downloads view changed to completed and file verified at the saved download destination.",
"birthtime": 1793537923.88,
"releaseID": 366,
"assetID": 12,
"temporaryCopyRemoved": true
},
"actualAppCompiledSource": "dbb7ca4a995ef832178a32f35939aed7d3a85012",
"assetUploads": 1,
"credentialValueRecorded": false
"version": "1.4.1",
"build": "26",
"appCompiledSource": "0eb56aed126c825ca89712ce90f8cc1c05b03d89",
"package": "/Volumes/备份/大鱼调色/发行包/大鱼调色-1.4.1.pkg",
"bytes": 14337616,
"sha256": "0c167aba339bbfdd9c4cbd96aea384e2d43f6d498629ebaf7b1c18cbc6dca5c6",
"previousRelease": "https://dayu.media/git/dayu/dayu-color/releases/tag/v1.4.0-tool-masks-20261101"
}
+11
查看文件
@@ -0,0 +1,11 @@
{
"passResult": true,
"tag": "v1.4.0-tool-masks-20261101",
"commit": "fa7ef93714c93ba959276e21be60e5758f37e0ad",
"restoredFiles": 214,
"fsck": "full strict passed",
"packageSHA256": "16a4958e28bc2a43c40e6131067eb03a49aecba5bbe3c0424bc7024fa532af38",
"packageBytes": 14250425,
"sourceRecovery": "verification/ToolMaskRecovery.json",
"cloneCleaned": true
}
+3
查看文件
@@ -418,8 +418,11 @@ extern "C" int DYRunDiagnostics(void) { @autoreleasepool {
run.record(@"user-folder-all-luts-prepared-and-rendered",userCount>0&&allUserFrames,@{@"files":@(userCount),@"sourceFolder":userFolder,@"sourceFilesModified":@NO});
}
#include "DYToolDiagnostics.inc.h"
#include "DYToolInsertionDiagnostics.inc.h"
#include "DYToolTrackingDiagnostics.inc.h"
#include "DYToolCanvasDiagnostics.inc.h"
#include "DYToolPenDiagnostics.inc.h"
#include "DYMaskPanelDiagnostics.inc.h"
[gpu release];
} @catch(NSException *exception) {
run.record(@"diagnostic-exception",false,@{@"exception":exception.name?:@"unknown",@"message":exception.reason?:@"unknown"});
+48
查看文件
@@ -18,6 +18,12 @@ extern "C" half4 dy_gradeMasked(half4 sample, float2 uv, texture2d<half> source,
texture3d<float> hslMixer, texture3d<float> whiteBalance,
texture3d<float> colorGrading, constant DYUniforms& uniforms,
constant float& sceneLevel,float w0,float w1,float w2,float w3,float w4,float w5,float w6,float w7,float w8,float w9,float w10,float w11);
extern "C" half4 dy_gradeSegment(half4 sample, float2 uv, texture2d<half> source,
texture3d<float> preLUT, texture3d<float> look1, texture3d<float> look2,
texture3d<float> look3, texture3d<float> look4, texture3d<float> look5,
texture3d<float> hslMixer, texture3d<float> whiteBalance,
texture3d<float> colorGrading, constant DYUniforms& uniforms,
constant float& sceneLevel,float w0,float w1,float w2,float w3,float w4,float w5,float w6,float w7,float w8,float w9,float w10,float w11,uint stageFirst,uint stageLast,float3 skinReference,float3 originalReference);
struct DYRaster {
float4 position [[position]];
@@ -181,6 +187,48 @@ fragment half4 dyMaskedFragment(DYRaster in [[stage_in]],
return result;
}
fragment half4 dySegmentFragment(DYRaster in [[stage_in]],
texture2d<half> source [[texture(0)]],
texture3d<float> preLUT [[texture(1)]],
texture3d<float> look1 [[texture(2)]],
texture3d<float> look2 [[texture(3)]],
texture3d<float> look3 [[texture(4)]],
texture3d<float> look4 [[texture(5)]],
texture3d<float> look5 [[texture(6)]],
texture3d<float> hslMixer [[texture(7)]],
texture3d<float> whiteBalance [[texture(8)]],
texture3d<float> colorGrading [[texture(9)]],
constant DYUniforms& uniforms [[buffer(0)]],
constant float& sceneLevel [[buffer(1)]],
constant DYRenderOptions& options [[buffer(2)]],
constant DYUniforms& colorUniforms [[buffer(3)]],
device const float* spiderSamples [[buffer(4)]],
constant int2& spiderSize [[buffer(5)]],
device const DYToolMaskEntry* masks [[buffer(6)]],
constant DYToolMaskHeader& maskHeader [[buffer(7)]],
constant DYToolStageRange& stages [[buffer(8)]],
texture2d<half> skinReference [[texture(10)]],
texture2d<half> nativeSource [[texture(11)]]) {
constexpr sampler sampleFilter(coord::normalized, address::clamp_to_edge, filter::linear);
half4 sample = source.sample(sampleFilter, in.uv);
if (!(sample.a > half(0.0))) return half4(0.0h);
half4 originalSample=nativeSource.sample(sampleFilter,in.uv);
float weights[12];float3 encoded=dyToolEncode(float3(originalSample.rgb));
for(int i=0;i<12;i++)weights[i]=dyToolCoverage(in.uv,encoded,masks,maskHeader,i);
if(stages.suppressBlackWhite)weights[10]=0;
half4 reference=skinReference.sample(sampleFilter,in.uv);
float3 skinEncoded=dyToolEncode(reference.a>half(0)?float3(reference.rgb/reference.a):float3(0));
half4 result = dy_gradeSegment(sample, in.uv, nativeSource, preLUT, look1, look2, look3,
look4, look5, hslMixer, whiteBalance, colorGrading, uniforms, sceneLevel,weights[0],weights[1],weights[2],weights[3],weights[4],weights[5],weights[6],weights[7],weights[8],weights[9],weights[10],weights[11],uint(stages.first),uint(stages.last),skinEncoded,encoded);
if(stages.first<=9 && stages.last>=9 && options.blackWhiteMix>0.0f && options.blackWhiteMix<1.0f) {
half4 color=dy_gradeSegment(sample,in.uv,nativeSource,preLUT,look1,look2,look3,look4,look5,hslMixer,whiteBalance,colorGrading,colorUniforms,sceneLevel,weights[0],weights[1],weights[2],weights[3],weights[4],weights[5],weights[6],weights[7],weights[8],weights[9],weights[10],weights[11],uint(stages.first),uint(stages.last),skinEncoded,encoded);
result.rgb=mix(color.rgb,result.rgb,half(options.blackWhiteMix));
}
result.a = sample.a;
if (options.outputPremultiplied) result.rgb *= result.a;
return result;
}
// Optional boundary conversion. Use this before both statistics and grading
// when the host supplies premultiplied RGB; all neighborhood samples then see
// the same straight RGB representation. Source and destination must differ.
+7 -5
查看文件
@@ -86,6 +86,7 @@ static NSArray *DYAccessibleSubviews(NSView *view, BOOL visibleOnly) {
if(visibleOnly&&!NSIntersectsRect(child.frame,visible))continue;
[children addObject:child];
}
[children sortUsingComparator:^NSComparisonResult(NSView *a,NSView *b){if(NSMinY(a.frame)!=NSMinY(b.frame))return NSMinY(a.frame)<NSMinY(b.frame)?NSOrderedAscending:NSOrderedDescending;if(NSMinX(a.frame)!=NSMinX(b.frame))return NSMinX(a.frame)<NSMinX(b.frame)?NSOrderedAscending:NSOrderedDescending;return NSOrderedSame;}];
return NSAccessibilityUnignoredChildren(children);
}
@@ -404,7 +405,7 @@ static NSImage *DYWheelImage(void) {
NSMutableDictionary *_tabs;
NSInteger _visibleLooks;
BOOL _refreshing,_graphicUndoOpen;
BOOL _embedded;NSMutableDictionary *_stackViews;NSArray *_stackOrder;CGFloat _stackHeight;
BOOL _embedded;NSMutableDictionary *_stackViews;NSArray *_stackOrder;NSDictionary *_stackRoots;CGFloat _stackHeight;
DYSpiderPanel *_spiderPanel;
NSMutableDictionary *_assetLoads,*_assetLoadIDs;
NSUInteger _nextAssetLoadID;
@@ -469,7 +470,7 @@ static NSImage *DYWheelImage(void) {
for(id graphic in _graphics)if([graphic isKindOfClass:DYPrimaryBalanceWheel.class])[(DYPrimaryBalanceWheel*)graphic setDelegate:nil];
for(NSProgress *p in _assetLoads.allValues)[p cancel];[_assetLoads release];[_assetLoadIDs release];[_menuScan cancel];[_menuScan release];[_pendingAssetMenuCommand release];
[[NSNotificationCenter defaultCenter] removeObserver:self];
if(_embedded)[(id)_manager release];[_stackViews release];[_stackOrder release];
if(_embedded)[(id)_manager release];[_stackViews release];[_stackOrder release];[_stackRoots release];
[_brand release]; [_subtitle release]; [_resetAll release]; [_save release]; [_load release]; [_export release];
[_scroll release]; [_document release]; [_sections release]; [_cards release]; [_controls release]; [_assetButtons release]; [_graphics release]; [_sampler release];
[_browser close];[_browser release];[_renderer release];[_library release];[_themeButtons release];[_tabs release];
@@ -491,7 +492,7 @@ static NSImage *DYWheelImage(void) {
}
}
- (void)modelChanged:(NSNotification *)n {
if([NSThread isMainThread]) {[self refresh];if(!_embedded&&[n.userInfo[@"scrollToNewTool"]boolValue]){[self layoutSubtreeIfNeeded];[_document scrollPoint:NSMakePoint(0,MAX(0,_document.bounds.size.height-_scroll.contentSize.height))];}}
if([NSThread isMainThread]) {[self refresh];NSString *ID=n.userInfo[@"scrollToTool"];if(!_embedded&&ID.length&&_stackViews[ID]){[self layoutSubtreeIfNeeded];NSView *child=_stackViews[ID];[_document scrollPoint:NSMakePoint(0,MAX(0,child.frame.origin.y-8))];}}
else dispatch_async(dispatch_get_main_queue(),^{ [self refresh]; });
}
- (void)selectTheme:(NSButton *)button {DYSetThemeIndex(button.tag);}
@@ -623,7 +624,7 @@ static NSImage *DYWheelImage(void) {
NSString *nodeID=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:key];
DYToolMaskPanel *maskPanel=[[[DYToolMaskPanel alloc]initWithManager:host nodeID:nodeID]autorelease];[card addSubview:maskPanel];[body insertObject:maskPanel atIndex:0];record[@"maskPanel"]=maskPanel;
NSButton *mask=DYButton(@"",self,@selector(toolMask:));mask.tag=index;mask.bordered=NO;mask.image=[NSImage imageWithSystemSymbolName:@"circle.dashed.inset.filled" accessibilityDescription:@"添加蒙版"];mask.toolTip=@"添加本工具的独立蒙版";mask.accessibilityLabel=[section[@"title"]stringByAppendingString:@"添加蒙版"];[card addSubview:mask];record[@"maskButton"]=mask;
NSButton *repeat=DYButton(@"",self,@selector(repeatTool:));repeat.tag=index;repeat.bordered=NO;repeat.image=[NSImage imageWithSystemSymbolName:@"plus.square.on.square" accessibilityDescription:@"再加一层"];repeat.toolTip=@"在工具列表末尾添加一层初始化工具";repeat.accessibilityLabel=[section[@"title"]stringByAppendingString:@"再加一层"];[card addSubview:repeat];record[@"repeatButton"]=repeat;
NSButton *repeat=DYButton(@"",self,@selector(repeatTool:));repeat.tag=index;repeat.bordered=NO;repeat.image=[NSImage imageWithSystemSymbolName:@"plus.square.on.square" accessibilityDescription:@"再加一层"];repeat.toolTip=@"紧接当前工具插入一层初始化工具";repeat.accessibilityLabel=[section[@"title"]stringByAppendingString:@"再加一层"];[card addSubview:repeat];record[@"repeatButton"]=repeat;
if(_embedded){NSButton *remove=DYButton(@"删除此层",self,@selector(removeTool:));remove.identifier=@"removeTool";[card addSubview:remove];[body addObject:remove];}
[_cards addObject:record];
index++;
@@ -694,6 +695,7 @@ static NSImage *DYWheelImage(void) {
}
if([row.identifier isEqual:@"hslTabs"]){CGFloat width=row.bounds.size.width/9;NSInteger i=0;for(NSView *button in row.subviews)[button setFrame:NSMakeRect(i++*width,1,width-1,27)];}
}
y=[self layoutRepeatedToolsAfter:[@"base:" stringByAppendingString:key] y:y width:w];
}
for(NSDictionary *record in _controls.allValues) {
CGFloat rw=[record[@"row"]bounds].size.width,lw=MIN(103,MAX(77,rw*.34)),eyeWidth=record[@"itemEnabled"]?20:0;
@@ -708,7 +710,7 @@ static NSImage *DYWheelImage(void) {
[r[@"browse"]setHidden:input];[r[@"eye"]setFrame:NSMakeRect(0,5,18,20)];[r[@"browse"]setFrame:NSMakeRect(r[@"eye"]?20:0,4,20,24)];[r[@"label"]setFrame:NSMakeRect(input?2:r[@"eye"]?43:25,7,input?86:r[@"eye"]?51:69,18)];
[r[@"choose"]setFrame:NSMakeRect(97,3,MAX(65,rw-152),26)];[r[@"folder"]setFrame:NSMakeRect(rw-51,4,24,24)];[r[@"remove"]setFrame:NSMakeRect(rw-23,4,22,24)];
}
for(NSString *ID in _stackOrder){DYInspector *child=_stackViews[ID];child.frame=NSMakeRect(0,y,w,MAX(60,child->_stackHeight));[child layoutSubtreeIfNeeded];CGFloat height=MAX(60,child->_stackHeight);child.frame=NSMakeRect(0,y,w,height);y+=height;}
y=[self layoutRepeatedToolsAfter:@"tail" y:y width:w];
_stackHeight=y;[_document setFrameSize:NSMakeSize(_scroll.contentSize.width,MAX(y,_scroll.contentSize.height))];
}
- (id<FxCustomParameterActionAPI_v4>)actionAPI { return [_manager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]; }
+42 -20
查看文件
@@ -7,59 +7,81 @@
@end
@implementation DYToolMaskPanel {
id<PROAPIAccessing> _host;NSString *_nodeID,*_maskID;NSDictionary *_document;CMTime _time;
NSPopUpButton *_list,*_combine;NSButton *_eye,*_add,*_remove,*_invert,*_canvas,*_clear;NSMutableArray *_rows,*_tracking;NSTextField *_status;BOOL _refreshing;CGFloat _contentHeight;
NSPopUpButton *_list,*_combine;NSButton *_eye,*_add,*_remove,*_invert,*_canvas,*_clear,*_penRedraw,*_penFinish,*_penCancel;NSMutableArray *_rows,*_tracking;NSTextField *_trackingTitle,*_status;BOOL _refreshing,_drawing,_canvasActive;CGFloat _contentHeight;
}
@synthesize contentHeight=_contentHeight;
- (instancetype)initWithManager:(id<PROAPIAccessing>)manager nodeID:(NSString*)nodeID{
if((self=[super initWithFrame:NSZeroRect])){_host=manager;_nodeID=[nodeID copy];_rows=[NSMutableArray new];_tracking=[NSMutableArray new];self.identifier=@"toolMasks";
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(trackingStatus:) name:@"DYToolTrackingStatus" object:_host];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(canvasSelected:) name:@"DYToolCanvasSelection" object:_host];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(canvasState:) name:@"DYToolCanvasState" object:_host];
}return self;
}
- (void)buildControls{if(_list)return;
_list=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];_list.target=self;_list.action=@selector(selection:);_list.font=[NSFont systemFontOfSize:10];_list.accessibilityLabel=@"本层蒙版";[self addSubview:_list];
_eye=[DYButton(@"",self,@selector(enabled:))retain];_eye.image=[NSImage imageWithSystemSymbolName:@"eye" accessibilityDescription:@"蒙版启用"];_eye.bordered=NO;[_eye setButtonType:NSButtonTypePushOnPushOff];[self addSubview:_eye];
_list=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];_list.target=self;_list.action=@selector(selection:);_list.font=[NSFont systemFontOfSize:13 weight:NSFontWeightMedium];_list.controlSize=NSControlSizeRegular;_list.accessibilityLabel=@"本层蒙版";[self addSubview:_list];
_eye=[DYButton(@"",self,@selector(enabled:))retain];_eye.image=[NSImage imageWithSystemSymbolName:@"eye" accessibilityDescription:@"蒙版启用"];_eye.imageScaling=NSImageScaleProportionallyUpOrDown;_eye.bordered=NO;[_eye setButtonType:NSButtonTypePushOnPushOff];[self addSubview:_eye];
_add=[DYButton(@"+",self,@selector(add:))retain];_add.toolTip=@"再添加一个蒙版";_add.accessibilityLabel=_add.toolTip;[self addSubview:_add];
_remove=[DYButton(@"−",self,@selector(remove:))retain];_remove.toolTip=@"删除选中的蒙版";_remove.accessibilityLabel=_remove.toolTip;[self addSubview:_remove];
_combine=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];[_combine addItemsWithTitles:@[@"相加",@"减去",@"相交"]];_combine.target=self;_combine.action=@selector(combine:);_combine.accessibilityLabel=@"蒙版组合方式";[self addSubview:_combine];
_invert=[[NSButton checkboxWithTitle:@"反转" target:self action:@selector(inverted:)]retain];[self addSubview:_invert];
_combine=[[NSPopUpButton alloc]initWithFrame:NSZeroRect pullsDown:NO];[_combine addItemsWithTitles:@[@"相加",@"减去",@"相交"]];_combine.font=[NSFont systemFontOfSize:13];_combine.controlSize=NSControlSizeRegular;_combine.target=self;_combine.action=@selector(combine:);_combine.accessibilityLabel=@"蒙版组合方式";[self addSubview:_combine];
_invert=[[NSButton checkboxWithTitle:@"反转" target:self action:@selector(inverted:)]retain];_invert.font=[NSFont systemFontOfSize:13];_invert.controlSize=NSControlSizeRegular;[self addSubview:_invert];
_canvas=[DYButton(@"画面编辑",self,@selector(canvas:))retain];_canvas.toolTip=@"在宿主画面拖动中心、大小、旋转与钢笔节点;回车闭合钢笔";_canvas.accessibilityLabel=@"编辑本层蒙版画面控件";[self addSubview:_canvas];
_penRedraw=[DYButton(@"重画钢笔",self,@selector(redrawPen:))retain];_penRedraw.toolTip=@"从空白重画钢笔;完成前保留原路径,可随时取消";_penRedraw.accessibilityLabel=@"重画钢笔蒙版";[self addSubview:_penRedraw];
_penFinish=[DYButton(@"完成绘制",self,@selector(penCommand:))retain];_penFinish.toolTip=@"闭合当前钢笔路径并保存";_penFinish.accessibilityLabel=@"完成钢笔绘制";[self addSubview:_penFinish];
_penCancel=[DYButton(@"取消绘制",self,@selector(penCommand:))retain];_penCancel.toolTip=@"取消当前绘制,保留原蒙版路径";_penCancel.accessibilityLabel=@"取消钢笔绘制";[self addSubview:_penCancel];
_clear=[DYButton(@"清除轨迹",self,@selector(clear:))retain];[self addSubview:_clear];
NSArray *names=@[@"强度",@"羽化",@"中心 X",@"中心 Y",@"宽度",@"高度",@"旋转",@"渐变宽度",@"色相中心",@"色相范围",@"色相柔边",@"饱和度下限",@"饱和度上限",@"亮度下限",@"亮度上限",@"输入黑",@"输入白",@"输入伽马"];
for(NSInteger i=0;i<names.count;i++){NSTextField *label=[DYLabel(names[i],10)retain];NSSlider *slider=[[NSSlider alloc]initWithFrame:NSZeroRect];slider.tag=i;slider.target=self;slider.action=@selector(valueChanged:);slider.continuous=NO;slider.controlSize=NSControlSizeSmall;slider.accessibilityLabel=[names[i]stringByAppendingString:@"蒙版"];NSTextField *field=[[NSTextField alloc]initWithFrame:NSZeroRect];field.font=[NSFont monospacedDigitSystemFontOfSize:10 weight:NSFontWeightRegular];field.tag=i;field.target=self;field.action=@selector(valueChanged:);field.accessibilityLabel=[names[i]stringByAppendingString:@"蒙版数值"];field.alignment=NSTextAlignmentRight;[self addSubview:label];[self addSubview:slider];[self addSubview:field];[_rows addObject:@{@"label":label,@"slider":slider,@"field":field}];[label release];[slider release];[field release];}
NSArray *titles=@[@"◀ 单帧",@"◀ 跟踪",@"双向",@"跟踪 ▶",@"单帧 ▶",@"取消"];
for(int i=0;i<6;i++){NSButton *b=DYButton(titles[i],self,@selector(track:));b.tag=((int[]){-2,-1,0,1,2,9})[i];b.font=[NSFont systemFontOfSize:9];b.accessibilityLabel=@[@"反向跟踪一帧",@"反向蒙版跟踪",@"双向蒙版跟踪",@"正向蒙版跟踪",@"正向跟踪一帧",@"取消蒙版跟踪"][i];[self addSubview:b];[_tracking addObject:b];}
_status=[DYLabel(@"",10)retain];_status.maximumNumberOfLines=2;[self addSubview:_status];_contentHeight=0;
for(NSInteger i=0;i<names.count;i++){NSTextField *label=[DYLabel(names[i],13)retain];label.font=[NSFont systemFontOfSize:13 weight:NSFontWeightMedium];NSSlider *slider=[[NSSlider alloc]initWithFrame:NSZeroRect];slider.tag=i;slider.target=self;slider.action=@selector(valueChanged:);slider.continuous=NO;slider.controlSize=NSControlSizeRegular;slider.accessibilityLabel=[names[i]stringByAppendingString:@"蒙版"];NSTextField *field=[[NSTextField alloc]initWithFrame:NSZeroRect];field.cell=[[[DYNumberFieldCell alloc]initTextCell:@"0"]autorelease];field.font=[NSFont monospacedDigitSystemFontOfSize:13 weight:NSFontWeightMedium];field.textColor=DYInk();field.backgroundColor=DYThemeColor(@"field");field.bezeled=NO;field.bordered=NO;field.drawsBackground=NO;field.tag=i;field.target=self;field.action=@selector(valueChanged:);field.accessibilityLabel=[names[i]stringByAppendingString:@"蒙版数值"];field.alignment=NSTextAlignmentCenter;[self addSubview:label];[self addSubview:slider];[self addSubview:field];[_rows addObject:@{@"label":label,@"slider":slider,@"field":field}];[label release];[slider release];[field release];}
NSArray *titles=@[@"反向单帧",@"反向跟踪",@"双向跟踪",@"正向跟踪",@"正向单帧",@"取消跟踪"];
for(int i=0;i<6;i++){NSButton *b=DYButton(titles[i],self,@selector(track:));b.tag=((int[]){-2,-1,0,1,2,9})[i];b.font=[NSFont systemFontOfSize:13 weight:NSFontWeightMedium];b.controlSize=NSControlSizeRegular;b.accessibilityLabel=@[@"反向跟踪一帧",@"反向蒙版跟踪",@"双向蒙版跟踪",@"正向蒙版跟踪",@"正向跟踪一帧",@"取消蒙版跟踪"][i];[self addSubview:b];[_tracking addObject:b];}
for(NSButton *b in @[_eye,_add,_remove,_canvas,_clear,_penRedraw,_penFinish,_penCancel]){b.controlSize=NSControlSizeRegular;b.font=[NSFont systemFontOfSize:(b==_add||b==_remove)?18:13 weight:NSFontWeightMedium];}
_trackingTitle=[DYLabel(@"运动跟踪",13)retain];_trackingTitle.font=[NSFont systemFontOfSize:13 weight:NSFontWeightSemibold];[self addSubview:_trackingTitle];
_status=[DYLabel(@"",12)retain];_status.maximumNumberOfLines=3;_status.lineBreakMode=NSLineBreakByWordWrapping;[self addSubview:_status];_contentHeight=0;
}
- (void)dealloc{[NSNotificationCenter.defaultCenter removeObserver:self];[_nodeID release];[_maskID release];[_document release];[_list release];[_combine release];[_eye release];[_add release];[_remove release];[_invert release];[_canvas release];[_clear release];[_rows release];[_tracking release];[_status release];[super dealloc];}
- (void)dealloc{[NSNotificationCenter.defaultCenter removeObserver:self];[_nodeID release];[_maskID release];[_document release];[_list release];[_combine release];[_eye release];[_add release];[_remove release];[_invert release];[_canvas release];[_clear release];[_penRedraw release];[_penFinish release];[_penCancel release];[_rows release];[_tracking release];[_trackingTitle release];[_status release];[super dealloc];}
- (NSDictionary*)mask{for(NSDictionary *m in DYMasksForTool(_document,_nodeID))if([m[@"id"]isEqual:_maskID])return m;return nil;}
- (void)refreshWithDocument:(NSDictionary*)doc time:(CMTime)time{
_refreshing=YES;NSDictionary *saved=[doc copy];[_document release];_document=saved;_time=time;NSArray *masks=DYMasksForTool(doc,_nodeID);if(masks.count)[self buildControls];[_list removeAllItems];NSInteger selected=0,index=0;
for(NSDictionary *m in masks){DYMaskParameters p=DYMaskAtTime(m,time);[_list addItemWithTitle:[NSString stringWithFormat:@"%@ %ld",@[@"椭圆",@"矩形",@"钢笔",@"线性渐变",@"HSL 选区",@"亮度选区"][p.kind],(long)index+1]];if([m[@"id"]isEqual:_maskID])selected=index;index++;}
if(!masks.count){_contentHeight=0;_refreshing=NO;return;}[_list selectItemAtIndex:selected];[_maskID release];_maskID=[masks[selected][@"id"]copy];NSDictionary *m=[self mask];DYMaskParameters p=DYMaskAtTime(m,time);
if(!masks.count){_contentHeight=0;_drawing=_canvasActive=NO;_refreshing=NO;return;}[_list selectItemAtIndex:selected];if(![_maskID isEqual:masks[selected][@"id"]])_drawing=_canvasActive=NO;[_maskID release];_maskID=[masks[selected][@"id"]copy];NSDictionary *m=[self mask];DYMaskParameters p=DYMaskAtTime(m,time);if(p.kind!=DYMaskBezier)_drawing=NO;
_eye.state=[m[@"enabled"]boolValue]?NSControlStateValueOn:NSControlStateValueOff;_eye.image=[NSImage imageWithSystemSymbolName:[m[@"enabled"]boolValue]?@"eye":@"eye.slash" accessibilityDescription:@"启用蒙版"];[_combine selectItemAtIndex:[m[@"combine"]integerValue]];_invert.state=(p.flags&DYMaskInvert)?NSControlStateValueOn:NSControlStateValueOff;
float values[]={p.strength,p.feather,p.centerX,p.centerY,p.width,p.height,float(p.angle*180.f/M_PI),p.gradientWidth,p.hueCenterTurns*360.f,p.hueCoreHalfWidth*360.f,p.hueSoftWidth*360.f,p.saturationRange.low,p.saturationRange.high,p.lightnessRange.low,p.lightnessRange.high,p.inputBlack,p.inputWhite,p.inputGamma};
NSInteger visible=0;for(NSInteger i=0;i<_rows.count;i++){BOOL show=i==0||(i==1&&p.kind<3)||(i>=2&&i<=6&&p.kind<4)||(i==7&&p.kind==3)||(i>=8&&i<=14&&p.kind==4)||(i>=15&&p.kind>=4);NSDictionary *row=_rows[i];for(NSView *v in row.allValues)v.hidden=!show;if(!show)continue;visible++;double lo=0,hi=1;if(i==2||i==3)lo=-1,hi=2;if(i==4||i==5||i==7)lo=.001,hi=2;if(i==6)lo=-180,hi=180;if(i==8)hi=360;if(i==9||i==10)hi=180;if(i==15)hi=.99;if(i==16)lo=.01,hi=2;if(i==17)lo=.01,hi=4;NSSlider *slider=row[@"slider"];slider.minValue=lo;slider.maxValue=hi;slider.doubleValue=values[i];[row[@"field"]setStringValue:[NSString stringWithFormat:@"%.3f",values[i]]];}
BOOL shape=p.kind<3;for(NSButton *b in _tracking)b.hidden=!shape;_clear.hidden=!shape;_clear.enabled=[m[@"keys"]count]>0;
_status.stringValue=m[@"status"]?:([m[@"keys"]count]?[NSString stringWithFormat:@"%lu 个轨迹键 · 修改几何会在当前帧建立手工键",(unsigned long)[m[@"keys"]count]]:p.kind==2?@"钢笔:在画面工具栏选择钢笔重画,回车闭合;拖动节点和手柄。":@"各蒙版只影响当前工具层");
_contentHeight=108+visible*27+(shape?63:0)+36;[self setNeedsLayout:YES];_refreshing=NO;
BOOL shape=p.kind<3;for(NSButton *b in _tracking)b.hidden=!shape;_trackingTitle.hidden=!shape;_clear.hidden=!shape;_clear.enabled=[m[@"keys"]count]>0;
BOOL pen=p.kind==DYMaskBezier;_penRedraw.hidden=!pen;_penFinish.hidden=!pen;_penCancel.hidden=!pen;
[self updateDrawingControls];
_status.stringValue=m[@"status"]?:([m[@"keys"]count]?[NSString stringWithFormat:@"%lu 个轨迹键 · 修改几何会在当前帧建立手工键",(unsigned long)[m[@"keys"]count]]:pen?@"重画钢笔后,点击起点或“完成绘制”闭合;取消或 Esc 保留原路径。":@"各蒙版只影响当前工具层");
// Keep every scalar readable at the narrowest native inspector width. A
// label/value line and a separate full-width slider avoid compressed controls.
_contentHeight=136+(pen?84:0)+visible*58+(shape?184:0)+58;[self setNeedsLayout:YES];_refreshing=NO;
}
- (void)layout{
[super layout];CGFloat w=self.bounds.size.width;
_eye.frame=NSMakeRect(0,4,32,34);_list.frame=NSMakeRect(38,4,MAX(60,w-114),34);_add.frame=NSMakeRect(w-70,4,32,34);_remove.frame=NSMakeRect(w-32,4,32,34);
CGFloat combineWidth=MIN(112,MAX(90,w*.45));_combine.frame=NSMakeRect(0,46,combineWidth,34);_invert.frame=NSMakeRect(combineWidth+12,49,MAX(70,w-combineWidth-12),28);_canvas.frame=NSMakeRect(0,88,w,36);
CGFloat y=136;if(_penRedraw&&!_penRedraw.hidden){CGFloat bw=(w-8)/2;_penRedraw.frame=NSMakeRect(0,y,bw,34);_penFinish.frame=NSMakeRect(bw+8,y,bw,34);_penCancel.frame=NSMakeRect(0,y+40,w,34);y+=84;}for(NSDictionary *r in _rows){NSTextField *label=r[@"label"];if(label.hidden)continue;label.frame=NSMakeRect(2,y+6,MAX(60,w-100),22);[r[@"field"]setFrame:NSMakeRect(w-90,y,88,32)];[r[@"slider"]setFrame:NSMakeRect(0,y+32,w,24)];y+=58;}
if(_tracking.count&&![_tracking[0]isHidden]){_trackingTitle.frame=NSMakeRect(2,y+2,w-4,20);y+=28;CGFloat bw=(w-8)/2;const int order[]={0,4,1,3,2,5};for(int i=0;i<6;i++)[_tracking[order[i]]setFrame:NSMakeRect((i%2)*(bw+8),y+(i/2)*38,bw,34)];y+=114;_clear.frame=NSMakeRect(0,y,w,34);y+=42;}
_status.frame=NSMakeRect(2,y+2,w-4,52);
}
- (void)layout{[super layout];CGFloat w=self.bounds.size.width;_eye.frame=NSMakeRect(0,2,20,24);_list.frame=NSMakeRect(22,1,MAX(60,w-82),26);_add.frame=NSMakeRect(w-57,1,26,25);_remove.frame=NSMakeRect(w-29,1,26,25);_combine.frame=NSMakeRect(0,33,83,25);_invert.frame=NSMakeRect(88,34,58,23);_canvas.frame=NSMakeRect(w-94,33,94,25);CGFloat y=67;for(NSDictionary *r in _rows){NSTextField *label=r[@"label"];if(label.hidden)continue;label.frame=NSMakeRect(2,y+4,68,18);[r[@"slider"]setFrame:NSMakeRect(72,y+4,MAX(20,w-133),18)];[r[@"field"]setFrame:NSMakeRect(w-57,y+1,55,23)];y+=27;}if(_tracking.count&&![_tracking[0]isHidden]){CGFloat bw=(w-8)/3;for(int i=0;i<6;i++)[_tracking[i]setFrame:NSMakeRect((i%3)*(bw+4),y+(i/3)*28,bw,25)];y+=58;_clear.frame=NSMakeRect(0,y,w,25);y+=29;}_status.frame=NSMakeRect(2,y+2,w-4,33);}
- (void)edit:(NSString*)title block:(void (^)(NSMutableDictionary*,NSMutableDictionary*))block{
id<FxCustomParameterActionAPI_v4>a=[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_host,a.currentTime).document);NSMutableArray *masks=(id)DYMasksForTool(doc,_nodeID);NSMutableDictionary *mask=nil;for(NSMutableDictionary *m in masks)if([m[@"id"]isEqual:_maskID])mask=m;if(!mask)return;block(doc,mask);if(!DYValidToolDocument(doc)){NSBeep();return;}id<FxUndoAPI>undo=[_host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:title];DYWriteTools(_host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];}
- (void)add:(id)sender{[self addMenu:_add];}
- (void)addMenu:(NSView*)anchor{NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"添加蒙版"]autorelease];for(int i=0;i<6;i++){NSMenuItem *item=[menu addItemWithTitle:@[@"椭圆",@"矩形",@"钢笔",@"线性渐变",@"HSL 选区",@"亮度选区"][i] action:@selector(addKind:) keyEquivalent:@""];item.target=self;item.tag=i;}[menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0,anchor.bounds.size.height) inView:anchor];}
- (void)addKind:(NSMenuItem*)sender{
id<FxCustomParameterActionAPI_v4>a=[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_host,a.currentTime).document);NSMutableArray *masks=[[DYMasksForTool(doc,_nodeID)mutableCopy]autorelease];if(masks.count>=DYToolMaskLimit){NSBeep();return;}NSDictionary *mask=DYNewMask(sender.tag);[masks addObject:mask];if(!DYSetToolMasks(doc,_nodeID,masks))return;[_maskID release];_maskID=[mask[@"id"]copy];NSDictionary *staged=[doc copy];[_document release];_document=staged;[self canvas:nil];id<FxUndoAPI>undo=[_host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"添加工具蒙版"];DYWriteTools(_host,doc,a.currentTime);[undo endUndoGroup];[_maskID release];_maskID=[mask[@"id"]copy];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];[self canvas:nil];}
id<FxCustomParameterActionAPI_v4>a=[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_host,a.currentTime).document);NSMutableArray *masks=[[DYMasksForTool(doc,_nodeID)mutableCopy]autorelease];if(masks.count>=DYToolMaskLimit){NSBeep();return;}NSDictionary *mask=DYNewMask(sender.tag);[masks addObject:mask];if(!DYSetToolMasks(doc,_nodeID,masks))return;[_maskID release];_maskID=[mask[@"id"]copy];NSDictionary *staged=[doc copy];[_document release];_document=staged;[self sendCanvasDrawing:sender.tag==DYMaskBezier];id<FxUndoAPI>undo=[_host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"添加工具蒙版"];DYWriteTools(_host,doc,a.currentTime);[undo endUndoGroup];[_maskID release];_maskID=[mask[@"id"]copy];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];[self sendCanvasDrawing:sender.tag==DYMaskBezier];}
- (void)selection:(id)sender{NSArray *m=DYMasksForTool(_document,_nodeID);if(_list.indexOfSelectedItem<0||_list.indexOfSelectedItem>=m.count)return;[_maskID release];_maskID=[m[_list.indexOfSelectedItem][@"id"]copy];[self refreshWithDocument:_document time:_time];[self canvas:nil];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:_host];}
- (void)remove:(id)sender{[self edit:@"删除工具蒙版" block:^(NSMutableDictionary *doc,NSMutableDictionary *mask){NSMutableArray *masks=[[DYMasksForTool(doc,self->_nodeID)mutableCopy]autorelease];[masks removeObject:mask];DYSetToolMasks(doc,self->_nodeID,masks);}];[self canvas:nil];}
- (void)enabled:(NSButton*)sender{[self edit:@"启停蒙版" block:^(NSMutableDictionary *d,NSMutableDictionary *m){m[@"enabled"]=@(sender.state==NSControlStateValueOn);}];}
- (void)combine:(id)sender{[self edit:@"蒙版组合" block:^(NSMutableDictionary *d,NSMutableDictionary *m){m[@"combine"]=@(self->_combine.indexOfSelectedItem);}];}
- (void)inverted:(NSButton*)sender{[self edit:@"反转蒙版" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p;[m[@"parameters"]getBytes:&p length:sizeof(p)];if(sender.state)p.flags|=DYMaskInvert;else p.flags&=~DYMaskInvert;m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];}];}
- (void)valueChanged:(NSControl*)sender{if(_refreshing)return;double value=sender.doubleValue;if(!std::isfinite(value)){NSBeep();return;}NSInteger i=sender.tag;[self edit:@"调整工具蒙版" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p=DYMaskAtTime(m,self->_time);float *fields[]={&p.strength,&p.feather,&p.centerX,&p.centerY,&p.width,&p.height,&p.angle,&p.gradientWidth,&p.hueCenterTurns,&p.hueCoreHalfWidth,&p.hueSoftWidth,&p.saturationRange.low,&p.saturationRange.high,&p.lightnessRange.low,&p.lightnessRange.high,&p.inputBlack,&p.inputWhite,&p.inputGamma};*fields[i]=(i==6?value*M_PI/180:i>=8&&i<=10?value/360:value);if(p.kind==DYMaskHSLKey)p.flags|=DYMaskHueEnabled|DYMaskSaturationEnabled|DYMaskLightnessEnabled;if(!dyValidMaskParameters(p))return;if([m[@"keys"]count]&&i<8){NSMutableArray *keys=[[m[@"keys"]mutableCopy]autorelease];[keys filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary *key,NSDictionary *bindings){CMTime t=CMTimeMakeWithEpoch([key[@"value"]longLongValue],[key[@"scale"]intValue],[key[@"epoch"]longLongValue]);return CMTimeCompare(t,self->_time)!=0;}]];[keys addObject:DYMaskKey(self->_time,p,YES,1)];[keys sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){CMTime x=CMTimeMakeWithEpoch([a[@"value"]longLongValue],[a[@"scale"]intValue],[a[@"epoch"]longLongValue]),y=CMTimeMakeWithEpoch([b[@"value"]longLongValue],[b[@"scale"]intValue],[b[@"epoch"]longLongValue]);return (NSComparisonResult)CMTimeCompare(x,y);}];m[@"keys"]=keys;}else m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];}];}
- (void)canvasSelected:(NSNotification*)n{if([n.userInfo[@"node"]isEqual:_nodeID]&&[n.userInfo[@"mask"]length]){NSString *ID=[n.userInfo[@"mask"]copy];[_maskID release];_maskID=ID;}}
- (void)canvas:(id)sender{[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@"",@"document":_document?:@{}}];}
- (void)clear:(id)sender{[self edit:@"清除蒙版轨迹" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p=DYMaskAtTime(m,self->_time);m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];m[@"keys"]=@[];[m removeObjectForKey:@"status"];}];}
- (void)track:(NSButton*)sender{[self canvas:nil];[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolTrack" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@"",@"direction":@(sender.tag)}];}
- (void)updateDrawingControls{for(NSButton *button in _tracking)button.enabled=!_drawing;_clear.enabled=!_drawing&&[[self mask][@"keys"]count]>0;_penFinish.enabled=_drawing;_penCancel.enabled=_drawing;}
- (void)canvasSelected:(NSNotification*)n{_canvasActive=[n.userInfo[@"node"]isEqual:_nodeID]&&[n.userInfo[@"mask"]length];if(_canvasActive){NSString *ID=[n.userInfo[@"mask"]copy];[_maskID release];_maskID=ID;_drawing=[n.userInfo[@"draw"]boolValue];}else _drawing=NO;[self updateDrawingControls];}
- (void)canvasState:(NSNotification*)n{if(!_canvasActive||![n.userInfo[@"node"]isEqual:_nodeID]||![n.userInfo[@"mask"]isEqual:_maskID])return;_drawing=[n.userInfo[@"drawing"]boolValue];[self updateDrawingControls];}
- (void)sendCanvasDrawing:(BOOL)drawing{[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@"",@"document":_document?:@{},@"draw":@(drawing)}];}
- (void)canvas:(id)sender{[self sendCanvasDrawing:NO];}
- (void)redrawPen:(id)sender{[self sendCanvasDrawing:YES];}
- (void)penCommand:(NSButton*)sender{[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasCommand" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@"",@"command":sender==_penFinish?@"finish":@"cancel",@"timeValue":@(_time.value),@"timeScale":@(_time.timescale),@"timeEpoch":@(_time.epoch)}];}
- (void)clear:(id)sender{if(_drawing)return;[self edit:@"清除蒙版轨迹" block:^(NSMutableDictionary *d,NSMutableDictionary *m){DYMaskParameters p=DYMaskAtTime(m,self->_time);m[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];m[@"keys"]=@[];[m removeObjectForKey:@"status"];}];}
- (void)track:(NSButton*)sender{if(_drawing)return;[self canvas:nil];[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolTrack" object:_host userInfo:@{@"node":_nodeID,@"mask":_maskID?:@"",@"direction":@(sender.tag)}];}
- (void)trackingStatus:(NSNotification*)n{if([n.userInfo[@"node"]isEqual:_nodeID])_status.stringValue=n.userInfo[@"message"]?:@"";}
@end
@@ -0,0 +1,47 @@
// Native inspector geometry/readability and pen command routing, without a GUI
// document. Include inside DYDiagnostics' existing run/manager/renderer scope.
{
BOOL readable=YES,contained=YES,noOverlap=YES,penVisibility=YES;
DYToolDocument *empty=[[[DYToolDocument alloc]init]autorelease];
for(int kind=0;kind<6;kind++){
NSMutableDictionary *document=DYMutablePlist(empty.document);
document[@"baseMasks"][@"hsl"]=[NSMutableArray arrayWithObject:DYNewMask(kind)];
DYWriteTools(manager,document,kCMTimeZero);
DYInspector *inspector=[[[DYInspector alloc]initWithAPIManager:manager renderer:renderer]autorelease];
[inspector refresh];NSDictionary *hslCard=nil;
for(NSDictionary *card in [inspector valueForKey:@"_cards"])if([card[@"section"][@"key"]isEqual:@"hsl"])hslCard=card;
NSView *panel=hslCard[@"maskPanel"];
if(!panel){readable=contained=noOverlap=penVisibility=NO;continue;}
NSArray *rows=[panel valueForKey:@"_rows"],*tracking=[panel valueForKey:@"_tracking"];
NSButton *redraw=[panel valueForKey:@"_penRedraw"],*finish=[panel valueForKey:@"_penFinish"],*cancel=[panel valueForKey:@"_penCancel"];
penVisibility&=redraw.hidden==(kind!=DYMaskBezier)&&finish.hidden==redraw.hidden&&cancel.hidden==redraw.hidden;
for(NSNumber *width in @[@220,@300,@420]){
CGFloat height=[[panel valueForKey:@"contentHeight"]doubleValue];[panel setFrameSize:NSMakeSize(width.doubleValue,height)];[panel layoutSubtreeIfNeeded];
for(NSView *view in panel.subviews)if(!view.hidden)contained&=NSContainsRect(panel.bounds,view.frame)&&view.frame.size.width>0&&view.frame.size.height>0;
for(NSDictionary *row in rows){NSTextField *label=row[@"label"],*field=row[@"field"];NSSlider *slider=row[@"slider"];if(label.hidden)continue;
readable&=label.font.pointSize>=13&&field.font.pointSize>=13&&field.frame.size.width>=80&&field.frame.size.height>=30&&slider.frame.size.height>=24;
noOverlap&=!NSIntersectsRect(label.frame,field.frame)&&!NSIntersectsRect(label.frame,slider.frame)&&!NSIntersectsRect(field.frame,slider.frame);
}
for(NSButton *button in tracking)if(!button.hidden)readable&=button.font.pointSize>=13&&button.frame.size.width>=100&&button.frame.size.height>=32;
if(kind==DYMaskBezier)for(NSButton *button in @[redraw,finish,cancel])readable&=button.font.pointSize>=13&&button.frame.size.width>=100&&button.frame.size.height>=32;
}
if(kind==DYMaskBezier){
NSMutableArray *events=[NSMutableArray array];NSNotificationCenter *center=NSNotificationCenter.defaultCenter;
id selection=[center addObserverForName:@"DYToolCanvasSelection" object:manager queue:nil usingBlock:^(NSNotification *note){[events addObject:@{@"name":note.name,@"payload":note.userInfo?:@{}}];}];
id command=[center addObserverForName:@"DYToolCanvasCommand" object:manager queue:nil usingBlock:^(NSNotification *note){[events addObject:@{@"name":note.name,@"payload":note.userInfo?:@{}}];}];
[redraw performClick:nil];[finish performClick:nil];[cancel performClick:nil];
BOOL routed=events.count==3&&[events[0][@"payload"][@"draw"]boolValue]&&[events[0][@"payload"][@"node"]isEqual:@"base:hsl"]&&[events[0][@"payload"][@"document"]isEqual:document]&&[events[1][@"payload"][@"command"]isEqual:@"finish"]&&[events[2][@"payload"][@"command"]isEqual:@"cancel"];
for(NSDictionary *event in events)routed&=[event[@"payload"][@"mask"]isEqual:document[@"baseMasks"][@"hsl"][0][@"id"]];
routed&=[events.lastObject[@"payload"][@"timeScale"]intValue]==kCMTimeZero.timescale;
run.record(@"native-pen-panel-routes-redraw-finish-and-cancel-to-own-mask",routed);[center removeObserver:selection];[center removeObserver:command];
[inspector refresh];BOOL drawingProtected=[[panel valueForKey:@"_drawing"]boolValue];for(NSButton *button in tracking)drawingProtected&=!button.enabled;drawingProtected&=![[panel valueForKey:@"_clear"]isEnabled];
[center postNotificationName:@"DYToolCanvasState" object:manager userInfo:@{@"node":@"base:hsl",@"mask":@"different-mask",@"drawing":@NO}];drawingProtected&=[[panel valueForKey:@"_drawing"]boolValue];
[center postNotificationName:@"DYToolCanvasState" object:manager userInfo:@{@"node":@"base:hsl",@"mask":document[@"baseMasks"][@"hsl"][0][@"id"],@"drawing":@NO}];BOOL restored=![[panel valueForKey:@"_drawing"]boolValue];for(NSButton *button in tracking)restored&=button.enabled;restored&=!finish.enabled&&!cancel.enabled;
run.record(@"pen-panel-disables-tracking-through-refresh-and-restores-after-own-finish",drawingProtected&&restored);
}
}
run.record(@"mask-panel-readable-fields-and-button-targets-at-native-narrow-width",readable);
run.record(@"six-mask-panel-layouts-fit-220-300-and-420-point-widths",contained&&noOverlap);
run.record(@"pen-drawing-actions-visible-only-for-bezier-mask",penVisibility);
DYWriteTools(manager,empty.document,kCMTimeZero);
}
+15 -7
查看文件
@@ -130,13 +130,15 @@ static void bypassIdleSkin(DYUniforms *u){
}
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths error:(NSError**)err{return [self renderSource:src destination:dst uniforms:u paths:paths spider:nil error:err];}
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider error:(NSError**)err{return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:@{} error:err];}
- (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks error:(NSError**)err{@synchronized(self){@autoreleasepool{
- (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks error:(NSError**)err{return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:masks stageFirst:-1 stageLast:-1 skinReference:nil originalReference:nil captureOriginal:nullptr suppressBlackWhite:NO error:err];}
- (BOOL)renderLegacy:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData *)spider masks:(NSDictionary*)masks stageFirst:(NSInteger)stageFirst stageLast:(NSInteger)stageLast skinReference:(FxImageTile*)skinReference originalReference:(FxImageTile*)originalReference captureOriginal:(DYExportTile**)captureOriginal suppressBlackWhite:(BOOL)suppressBlackWhite error:(NSError**)err{@synchronized(self){@autoreleasepool{
BOOL segmented=stageFirst>=0;if(segmented&&(stageFirst>stageLast||stageLast>11))return fail(err,@"原生工具分段范围无效");
if(spider.length&&!DYSpiderMeshIsValid(spider))return fail(err,@"蜘蛛盘数据无效");
if(u.primarySectionEnabled<.5){u.inputSectionEnabled=0;u.cm.basisEnabled=0;u.cm.outputEnabled=0;}
[_activeLUTPaths release];_activeLUTPaths=[[NSSet alloc]initWithArray:paths.allValues?:@[]];
NSMutableDictionary*e=[self device:dst.deviceRegistryID error:err];if(!e)return NO;id<MTLDevice>d=e[@"device"];id<MTLTexture>input=[src metalTextureForDevice:d],output=[dst metalTextureForDevice:d];if(!input||!output)return fail(err,@"宿主图像纹理不可用");
BOOL useCM=managed(u,paths);bypassNeutralTools(&u);float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));if(bwMix<=0)u.blackWhiteSectionEnabled=0;
BOOL useCM=managed(u,paths)&&(!segmented||stageFirst==0);bypassNeutralTools(&u);float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));if(bwMix<=0)u.blackWhiteSectionEnabled=0;
NSArray*ts=[self textures:paths uniforms:&u entry:e error:err];if(!ts)return NO;bypassIdleSkin(&u);
// Only a deformed active mesh allocates samples; device entries retain the
// current buffer across frames. Neutral grids are exact identity at all densities.
@@ -147,8 +149,8 @@ static void bypassIdleSkin(DYUniforms *u){
}
if([e[@"spiderActive"]boolValue]){spiderBuffer=e[@"spiderBuffer"];spiderSize={ [e[@"spiderHues"]intValue],[e[@"spiderRings"]intValue]};}
}
DYToolMaskHeader maskHeader{};id<MTLBuffer>maskBuffer=masks.count?[self maskBuffer:masks tile:src device:d header:&maskHeader]:nil;BOOL hasMasks=maskHeader.count>0;if(hasMasks&&!maskBuffer)return fail(err,@"无法分配蒙版缓冲区");
NSMutableDictionary*ps=e[@"pipelines"];NSString*format=[NSString stringWithFormat:@"%lu-%d",(unsigned long)output.pixelFormat,hasMasks];id<MTLRenderPipelineState>pipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:hasMasks?@"dyMaskedFragment":@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];}
DYToolMaskHeader maskHeader{};id<MTLBuffer>maskBuffer=(masks.count||segmented)?[self maskBuffer:masks tile:src device:d header:&maskHeader]:nil;BOOL hasMasks=maskHeader.count>0;if((hasMasks||segmented)&&!maskBuffer)return fail(err,@"无法分配蒙版缓冲区");
NSMutableDictionary*ps=e[@"pipelines"];NSString*format=[NSString stringWithFormat:@"%lu-%d-%d",(unsigned long)output.pixelFormat,hasMasks,segmented];id<MTLRenderPipelineState>pipeline=ps[format];if(!pipeline){MTLRenderPipelineDescriptor*p=[MTLRenderPipelineDescriptor new];p.vertexFunction=[e[@"library"]newFunctionWithName:@"dyVertex"];p.fragmentFunction=[e[@"library"]newFunctionWithName:segmented?@"dySegmentFragment":hasMasks?@"dyMaskedFragment":@"dyFragment"];p.colorAttachments[0].pixelFormat=output.pixelFormat;pipeline=[d newRenderPipelineStateWithDescriptor:p error:err];[p.vertexFunction release];[p.fragmentFunction release];[p release];if(!pipeline)return NO;ps[format]=pipeline;[pipeline release];}
MTLTextureDescriptor*td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];td.storageMode=MTLStorageModePrivate;td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;id<MTLTexture>straight=[d newTextureWithDescriptor:td];if(!straight)return fail(err,@"无法分配调色缓冲区");
id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyUnpremultiply"]];[ce setTexture:input atIndex:0];[ce setTexture:straight atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];
if(useCM&&!identityCM(u)&&u.cm.mix>0){
@@ -157,15 +159,21 @@ static void bypassIdleSkin(DYUniforms *u){
ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyColorManagement"]];[ce setTexture:straight atIndex:0];[ce setTexture:converted atIndex:1];[ce setBytes:&cm length:sizeof(cm) atIndex:0];[ce setBytes:&u.cm.mix length:4 atIndex:1];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];if(hasMasks){id<MTLTexture>blended=[d newTextureWithDescriptor:td];if(!blended){[converted release];[straight release];return fail(err,@"无法分配一级蒙版缓冲区");}maskHeader.section=0;maskHeader.premultiplied=0;[self encodeBlend:straight after:converted output:blended masks:maskBuffer header:maskHeader entry:e commands:cb];[converted release];converted=blended;}[straight release];straight=converted;
}
}
// Keep the actual post-CST straight source alive across all native segments.
// Both native spatial helpers and whites statistics historically read this
// source; the current segment's center color is a different input.
id<MTLTexture>nativeSource=segmented&&originalReference?[originalReference metalTextureForDevice:d]:straight;
if(!nativeSource){[straight release];return fail(err,@"原生工具参考纹理不可用");}
if(segmented&&captureOriginal&&!*captureOriginal){DYExportTile *reference=[[DYExportTile alloc]initWithTexture:nativeSource registry:d.registryID];[reference setBounds:src.tilePixelBounds origin:src.imageOrigin];[reference setPixelAspect:src.pixelAspect];*captureOriginal=reference;}
float level=.5;id<MTLBuffer>scene=[d newBufferWithBytes:&level length:4 options:MTLResourceStorageModeShared];
if(!_exporting&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];}
BOOL preview=NO;@synchronized(_previewLock){preview=!_exporting&&CACurrentMediaTime()-_lastPreview>.5;}id<MTLBuffer>pb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];}
if(!_exporting&&(!segmented||(stageFirst<=2&&stageLast>=2))&&u.whites>0&&u.whitesEnabled>.5&&u.baseSectionEnabled>.5){ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyWhitesSceneStatistics"]];[ce setTexture:nativeSource atIndex:0];[ce setTexture:ts[7] atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];[ce setBuffer:scene offset:0 atIndex:1];[ce dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)];[ce endEncoding];}
BOOL preview=NO;@synchronized(_previewLock){preview=(!segmented||stageFirst==0)&&!_exporting&&CACurrentMediaTime()-_lastPreview>.5;}id<MTLBuffer>pb=nil;if(preview){pb=[d newBufferWithLength:320*180*16 options:MTLResourceStorageModeShared];ce=[cb computeCommandEncoder];[ce setComputePipelineState:e[@"dyInputAnalysis"]];[ce setTexture:straight atIndex:0];[ce setTexture:ts[0] atIndex:1];float inputStrength=u.inputSectionEnabled>.5?u.preLUTStrength:0;[ce setBytes:&inputStrength length:4 atIndex:1];[ce setBuffer:pb offset:0 atIndex:0];[ce dispatchThreads:MTLSizeMake(320,180,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[ce endEncoding];}
MTLRenderPassDescriptor*rp=[MTLRenderPassDescriptor renderPassDescriptor];rp.colorAttachments[0].texture=output;rp.colorAttachments[0].loadAction=MTLLoadActionDontCare;rp.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>re=[cb renderCommandEncoderWithDescriptor:rp];[re setRenderPipelineState:pipeline];
float w=output.width,h=output.height;FxRect s=src.tilePixelBounds,t=dst.tilePixelBounds;float sw=s.right-s.left,sh=s.top-s.bottom;float l=(t.left-s.left)/sw,r=(t.right-s.left)/sw,top=(s.top-t.top)/sh,bottom=(s.top-t.bottom)/sh;
if(src.imageOrigin==kFxImageOrigin_BOTTOM_LEFT){top=1-top;bottom=1-bottom;}
DYVertex2D vs[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};
if(dst.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(int i=0;i<4;i++)vs[i].position.y=-vs[i].position.y;
vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,bwMix,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];DYUniforms color=u;color.blackWhiteSectionEnabled=0;[re setFragmentBytes:&color length:sizeof(color) atIndex:3];if(spiderBuffer)[re setFragmentBuffer:spiderBuffer offset:0 atIndex:4];else{float empty[2]={0,0};[re setFragmentBytes:empty length:sizeof(empty) atIndex:4];}[re setFragmentBytes:&spiderSize length:sizeof(spiderSize) atIndex:5];if(hasMasks){[re setFragmentBuffer:maskBuffer offset:0 atIndex:6];[re setFragmentBytes:&maskHeader length:sizeof(maskHeader) atIndex:7];}[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
vector_uint2 vp={(unsigned)output.width,(unsigned)output.height};[re setVertexBytes:vs length:sizeof(vs) atIndex:0];[re setVertexBytes:&vp length:sizeof(vp) atIndex:1];[re setViewport:(MTLViewport){0,0,w,h,0,1}];[re setFragmentTexture:straight atIndex:0];for(NSUInteger i=0;i<ts.count;i++)[re setFragmentTexture:ts[i] atIndex:i+1];[re setFragmentBytes:&u length:sizeof(u) atIndex:0];[re setFragmentBuffer:scene offset:0 atIndex:1];DYRenderOptions options={1,bwMix,0,0};[re setFragmentBytes:&options length:sizeof(options) atIndex:2];DYUniforms color=u;color.blackWhiteSectionEnabled=0;[re setFragmentBytes:&color length:sizeof(color) atIndex:3];if(spiderBuffer)[re setFragmentBuffer:spiderBuffer offset:0 atIndex:4];else{float empty[2]={0,0};[re setFragmentBytes:empty length:sizeof(empty) atIndex:4];}[re setFragmentBytes:&spiderSize length:sizeof(spiderSize) atIndex:5];if(hasMasks||segmented){[re setFragmentBuffer:maskBuffer offset:0 atIndex:6];[re setFragmentBytes:&maskHeader length:sizeof(maskHeader) atIndex:7];}if(segmented){DYToolStageRange range={(int)stageFirst,(int)stageLast,(int)suppressBlackWhite};[re setFragmentBytes:&range length:sizeof(range) atIndex:8];[re setFragmentTexture:skinReference?[skinReference metalTextureForDevice:d]:input atIndex:10];[re setFragmentTexture:nativeSource atIndex:11];}[re drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[re endEncoding];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
if(ok&&pb){@synchronized(_previewLock){
[_preview release];_preview=[[NSData alloc]initWithBytes:pb.contents length:320*180*16];
// The analysis kernel reads physical texture rows. Its result remains intact
@@ -0,0 +1,80 @@
// OSC callbacks only mutate a locked in-memory draft. Host parameter writes are
// deferred until the gesture has finished and the callback has returned.
- (void)postToolCanvasStatus:(NSString*)message {
NSString *node=nil,*maskID=nil;uint64_t revision;@synchronized(self){node=[_selectedToolNode copy];maskID=[_selectedToolMask copy];revision=_toolCanvasRevision;}
dispatch_async(dispatch_get_main_queue(),^{BOOL drawing;@synchronized(self){if(revision!=self->_toolCanvasRevision||![node isEqual:self->_selectedToolNode]||![maskID isEqual:self->_selectedToolMask])return;drawing=self->_toolDrawingPen||self->_toolCanvasCommitPending;}if(message)[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolTrackingStatus" object:self->_apiManager userInfo:@{@"node":node?:@"",@"message":message}];[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasState" object:self->_apiManager userInfo:@{@"node":node?:@"",@"mask":maskID?:@"",@"drawing":@(drawing)}];});[node release];[maskID release];
}
- (void)discardToolCanvasDraft {
@synchronized(self){[_toolCanvasDraft release];_toolCanvasDraft=nil;[_toolCanvasOriginal release];_toolCanvasOriginal=nil;_toolDrawingPen=NO;_toolCanvasHasHover=NO;_toolCanvasEditTime=kCMTimeInvalid;++_toolCanvasRevision;}[self postToolCanvasStatus:nil];
}
- (void)commitToolCanvasDraftAtTime:(CMTime)eventTime {
NSDictionary *draft=nil,*original=nil;NSString *node=nil,*maskID=nil;CMTime time;uint64_t revision;
@synchronized(self){if(!_toolCanvasDraft||!_toolCanvasOriginal)return;if(!CMTIME_IS_NUMERIC(eventTime)||CMTimeCompare(eventTime,_toolCanvasEditTime)!=0){[self discardToolCanvasDraft];[self postToolCanvasStatus:@"播放头已移动,请重新绘制。"];return;}draft=[_toolCanvasDraft copy];original=[_toolCanvasOriginal copy];node=[_selectedToolNode copy];maskID=[_selectedToolMask copy];time=_toolCanvasEditTime;[self discardToolCanvasDraft];revision=_toolCanvasRevision;_toolCanvasCommitPending=YES;}
dispatch_async(dispatch_get_main_queue(),^{@try{
@synchronized(self){if(self->_trackingActive.load()||revision!=self->_toolCanvasRevision||![node isEqual:self->_selectedToolNode]||![maskID isEqual:self->_selectedToolMask])return;}
id<FxCustomParameterActionAPI_v4>a=[self->_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;BOOL changed=NO;
[a startAction:self];@try{
NSMutableDictionary *doc=DYMutablePlist(DYReadTools(self->_apiManager,time).document),*current=[self toolMask:maskID node:node document:doc];
if(!current||![current isEqual:original]){[self postToolCanvasStatus:@"蒙版已在其它位置修改,本次画面草稿未覆盖它。"];return;}
NSMutableDictionary *result=DYMutablePlist(draft);
if([current[@"keys"]count]){DYMaskParameters p=DYMaskAtTime(result,time);NSMutableArray *keys=[[current[@"keys"]mutableCopy]autorelease];NSIndexSet *same=[keys indexesOfObjectsPassingTest:^BOOL(NSDictionary *key,NSUInteger i,BOOL *stop){return CMTimeCompare(CMTimeMakeWithEpoch([key[@"value"]longLongValue],[key[@"scale"]intValue],[key[@"epoch"]longLongValue]),time)==0;}];[keys removeObjectsAtIndexes:same];[keys addObject:DYMaskKey(time,p,YES,1)];result[@"keys"]=@[];if(!DYMergeTracking(result,keys))return;}
if(DYValidToolMask(result)&&![current isEqual:result]){[current setDictionary:result];id<FxUndoAPI>undo=[self->_apiManager apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"编辑工具蒙版"];changed=DYWriteTools(self->_apiManager,doc,time);[undo endUndoGroup];if(changed){DYToolDocument *saved=[[[DYToolDocument alloc]init]autorelease];saved.document=doc;[self adoptToolCanvasDocument:saved.document];}}
}@finally{[a endAction:self];}
if(changed)[self postToolCanvasStatus:@"蒙版已保存 · 可一次撤销"];
[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self->_apiManager];
}@finally{@synchronized(self){self->_toolCanvasCommitPending=NO;}[self postToolCanvasStatus:nil];}});[draft release];[original release];[node release];[maskID release];
}
- (void)toolCanvasCommand:(NSNotification*)notification {
NSDictionary *info=notification.userInfo;@synchronized(self){if(![info[@"node"]isEqual:_selectedToolNode]||![info[@"mask"]isEqual:_selectedToolMask])return;}
CMTime time=CMTimeMakeWithEpoch([info[@"timeValue"]longLongValue],[info[@"timeScale"]intValue],[info[@"timeEpoch"]longLongValue]);
id<FxCustomParameterActionAPI_v4>a=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(a){[a startAction:self];@try{time=a.currentTime;}@finally{[a endAction:self];}}if(!CMTIME_IS_NUMERIC(time))return;NSString *command=info[@"command"];
if([command isEqual:@"finish"]||[command isEqual:@"cancel"])[self toolCanvasEvent:NSEventTypeKeyDown point:NSZeroPoint part:1 modifiers:0 key:[command isEqual:@"finish"]?13:27 time:time];
}
- (void)toolCanvasEvent:(NSEventType)type point:(NSPoint)point part:(NSInteger)part modifiers:(FxModifierKeys)modifiers key:(unichar)key time:(CMTime)time {
if(!CMTIME_IS_NUMERIC(time)||!std::isfinite(point.x)||!std::isfinite(point.y))return;
@synchronized(self){if(_trackingActive.load()||!_selectedToolNode||!_selectedToolMask)return;if(_toolCanvasCommitPending){NSString *node=[_selectedToolNode copy],*maskID=[_selectedToolMask copy];dispatch_async(dispatch_get_main_queue(),^{@synchronized(self){if(![node isEqual:self->_selectedToolNode]||![maskID isEqual:self->_selectedToolMask])return;}[self toolCanvasEvent:type point:point part:part modifiers:modifiers key:key time:time];});[node release];[maskID release];return;}
if(part>=10000&&type==NSEventTypeLeftMouseDown){
NSInteger item=part-10000;
if(item==7){_toolShowCoverage=!_toolShowCoverage;return;}
if(item==8||item==10){[self discardToolCanvasDraft];if(item==8)_toolCanvasHidden=YES;[self postToolCanvasStatus:@"已取消绘制,保留原蒙版。"];return;}
if(item==9){[self toolCanvasEvent:NSEventTypeKeyDown point:point part:1 modifiers:0 key:13 time:time];return;}
if(item==0){if(_toolDrawingPen&&[_toolCanvasDraft[@"nodes"]length]>=3*sizeof(DYBezierNode))[self commitToolCanvasDraftAtTime:time];else [self discardToolCanvasDraft];return;}
if(item<1||item>6)return;
NSString *node=[_selectedToolNode copy];[self discardToolCanvasDraft];
dispatch_async(dispatch_get_main_queue(),^{
@synchronized(self){if(self->_trackingActive.load()||![node isEqual:self->_selectedToolNode])return;}
id<FxCustomParameterActionAPI_v4>a=[self->_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;
[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(self->_apiManager,time).document);NSMutableArray *masks=[[DYMasksForTool(doc,node)mutableCopy]autorelease];if(masks.count>=DYToolMaskLimit)return;NSInteger kind=((int[]){0,2,1,0,3,4,5})[item];NSDictionary *mask=DYNewMask(kind);[masks addObject:mask];if(!DYSetToolMasks(doc,node,masks))return;
[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:self->_apiManager userInfo:@{@"node":node,@"mask":mask[@"id"],@"draw":@(kind==2),@"document":doc}];
id<FxUndoAPI>u=[self->_apiManager apiForProtocol:@protocol(FxUndoAPI)];[u startUndoGroup:@"添加工具蒙版"];DYWriteTools(self->_apiManager,doc,time);[u endUndoGroup];
}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self->_apiManager];
});[node release];return;
}
if(type==NSEventTypeKeyDown&&key==27){[self discardToolCanvasDraft];[self postToolCanvasStatus:@"已取消绘制,保留原蒙版。"];return;}
if(type==NSEventTypeKeyDown&&(key==13||key==10||key==3)&&_toolDrawingPen){if([_toolCanvasDraft[@"nodes"]length]<3*sizeof(DYBezierNode)){[self postToolCanvasStatus:@"至少放置三个点,再点首节点或完成绘制。"];return;}[self commitToolCanvasDraftAtTime:time];return;}
if(type==NSEventTypeKeyDown&&(key==8||key==127)&&_toolDrawingPen){NSMutableData *nodes=[[_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];if(nodes.length)[nodes setLength:nodes.length-sizeof(DYBezierNode)];if(nodes)_toolCanvasDraft[@"nodes"]=nodes;[self postToolCanvasStatus:@"已移除最后一个钢笔点,继续点击放置。"];return;}
if(type==NSEventTypeKeyDown&&(key==8||key==127)&&!_toolDrawingPen&&_toolDragPart>=1000){
NSDictionary *mask=[self toolMask:_selectedToolMask node:_selectedToolNode document:_toolCanvasDocument];DYMaskParameters parameters=DYMaskAtTime(mask,time);NSUInteger count=[mask[@"nodes"]length]/sizeof(DYBezierNode),index=(_toolDragPart-1000)/3;if(parameters.kind!=DYMaskBezier||index>=count)return;
if(count<=3){[self postToolCanvasStatus:@"闭合路径至少保留三个点;可使用重画钢笔重新绘制。"];return;}
[self toolCanvasEvent:NSEventTypeLeftMouseDown point:point part:_toolDragPart modifiers:modifiers key:0 time:time];NSMutableData *nodes=[[_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];[nodes replaceBytesInRange:NSMakeRange(index*sizeof(DYBezierNode),sizeof(DYBezierNode)) withBytes:NULL length:0];_toolCanvasDraft[@"nodes"]=nodes;[self commitToolCanvasDraftAtTime:time];return;
}
if(type==NSEventTypeMouseMoved){if(_toolDrawingPen){if(_toolCanvasDraft&&CMTimeCompare(time,_toolCanvasEditTime)!=0){[self discardToolCanvasDraft];return;}_toolCanvasHoverPoint=point;_toolCanvasHasHover=[_toolCanvasDraft[@"nodes"]length]>0;}return;}
if(type==NSEventTypeLeftMouseDown){
_toolCanvasHasHover=NO;
if(_toolDrawingPen&&part==1000&&[_toolCanvasDraft[@"nodes"]length]>=3*sizeof(DYBezierNode)){[self commitToolCanvasDraftAtTime:time];return;}
if(!_toolCanvasDraft){NSDictionary *mask=[self toolMask:_selectedToolMask node:_selectedToolNode document:_toolCanvasDocument];if(!mask)return;++_toolCanvasRevision;_toolCanvasOriginal=[DYMutablePlist(mask)retain];_toolCanvasDraft=[DYMutablePlist(mask)retain];_toolCanvasEditTime=time;_toolDragParameters=DYMaskAtTime(mask,time);_toolDragParameters.imageAspect=_toolSourceFrame.valid()?float(_toolSourceFrame.width)/_toolSourceFrame.height:1;_toolCanvasDraft[@"parameters"]=[NSData dataWithBytes:&_toolDragParameters length:sizeof(DYMaskParameters)];_toolCanvasDraft[@"keys"]=@[];if(_toolDrawingPen)_toolCanvasDraft[@"nodes"]=[NSData data];}
if(CMTimeCompare(time,_toolCanvasEditTime)!=0){[self discardToolCanvasDraft];[self postToolCanvasStatus:@"播放头已移动,请重新绘制。"];return;}
_toolDragStart=point;_toolDragPart=part;_toolDragParameters=DYMaskAtTime(_toolCanvasDraft,time);
if(_toolDrawingPen){DYMaskParameters p=_toolDragParameters;float a=p.imageAspect,dx=(point.x-p.centerX)*a,dy=point.y-p.centerY,c=cos(p.angle),s=sin(p.angle),x=(dx*c+dy*s)/(p.width*a),y=(-dx*s+dy*c)/p.height;DYBezierNode n={x,y,x,y,x,y};NSMutableData *nodes=[[_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];if(nodes.length>=32*sizeof(n)){[self postToolCanvasStatus:@"已达到32个钢笔点,请完成绘制。"];return;}[nodes appendBytes:&n length:sizeof(n)];_toolCanvasDraft[@"nodes"]=nodes;[self postToolCanvasStatus:[NSString stringWithFormat:@"钢笔已放置%lu个点 · 拖出曲柄;点首节点或完成绘制闭合。",(unsigned long)(nodes.length/sizeof(n))]];}return;
}
if(!_toolCanvasDraft)return;
if(CMTimeCompare(time,_toolCanvasEditTime)!=0){[self discardToolCanvasDraft];return;}
if(type==NSEventTypeLeftMouseDragged){_toolCanvasHasHover=NO;DYMaskParameters p=_toolDragParameters;float dx=point.x-_toolDragStart.x,dy=point.y-_toolDragStart.y;
if(_toolDrawingPen||_toolDragPart>=1000){NSMutableData *data=[[_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];NSUInteger count=data.length/sizeof(DYBezierNode);if(count){auto *nodes=(DYBezierNode*)data.mutableBytes;NSUInteger index=_toolDrawingPen?count-1:(_toolDragPart-1000)/3,handle=_toolDrawingPen?2:(_toolDragPart-1000)%3;float a=p.imageAspect,c=cos(p.angle),s=sin(p.angle),x=((point.x-p.centerX)*a*c+(point.y-p.centerY)*s)/(p.width*a),y=(-(point.x-p.centerX)*a*s+(point.y-p.centerY)*c)/p.height;if(index<count){if(handle==0){float mx=x-nodes[index].x,my=y-nodes[index].y;nodes[index].x=x;nodes[index].y=y;nodes[index].inX+=mx;nodes[index].inY+=my;nodes[index].outX+=mx;nodes[index].outY+=my;}else if(handle==1){nodes[index].inX=x;nodes[index].inY=y;}else{nodes[index].outX=x;nodes[index].outY=y;if(_toolDrawingPen){nodes[index].inX=2*nodes[index].x-x;nodes[index].inY=2*nodes[index].y-y;}}_toolCanvasDraft[@"nodes"]=data;}}}
else if(_toolDragPart==6)p.angle=atan2((point.y-p.centerY),(point.x-p.centerX)*p.imageAspect)+M_PI/2;
else if(_toolDragPart>=2&&_toolDragPart<=5){float a=p.imageAspect,c=cos(p.angle),s=sin(p.angle),x=(point.x-p.centerX)*a,y=point.y-p.centerY;p.width=MAX(.001f,2*fabs(x*c+y*s)/a);p.height=MAX(.001f,2*fabs(-x*s+y*c));}
else{p.centerX+=dx;p.centerY+=dy;}if(dyValidMaskParameters(p))_toolCanvasDraft[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];return;
}
if(type==NSEventTypeLeftMouseUp&&!_toolDrawingPen)[self commitToolCanvasDraftAtTime:time];
}
}
+4 -4
查看文件
@@ -34,20 +34,20 @@ public:
if(!ready()||!f.valid())return false;
info_={};info_.levels=1;info_.width[0]=f.width;info_.height[0]=f.height;
int total=f.width*f.height;
while(info_.levels<5&&info_.width[info_.levels-1]>=80&&info_.height[info_.levels-1]>=80) {
while(info_.levels<dy::TrackerPyramidLevels&&info_.width[info_.levels-1]>=80&&info_.height[info_.levels-1]>=80) {
int i=info_.levels++;info_.width[i]=info_.width[i-1]/2;info_.height[i]=info_.height[i-1]/2;
info_.offset[i]=total;total+=info_.width[i]*info_.height[i];
}
for(int i=0;i<2;i++){[frames_[i] release];frames_[i]=nil;}[points_ release];points_=nil;[results_ release];results_=nil;
for(int i=0;i<2;i++)frames_[i]=[device_ newBufferWithLength:total*sizeof(float) options:MTLResourceStorageModeShared];
points_=[device_ newBufferWithLength:180*sizeof(dy::FlowPoint) options:MTLResourceStorageModeShared];
results_=[device_ newBufferWithLength:180*sizeof(FlowOutput) options:MTLResourceStorageModeShared];
points_=[device_ newBufferWithLength:dy::TrackerFeatureLimit*sizeof(dy::FlowPoint) options:MTLResourceStorageModeShared];
results_=[device_ newBufferWithLength:dy::TrackerFeatureLimit*sizeof(FlowOutput) options:MTLResourceStorageModeShared];
if(!frames_[0]||!frames_[1]||!points_||!results_)return false;
previous_=0;memcpy(frames_[0].contents,f.pixels.data(),f.pixels.size()*sizeof(float));
id<MTLCommandBuffer>b=[queue_ commandBuffer];pyramid(b,frames_[0]);return finish(b);
}
bool advance(const dy::GrayFrame& f,const std::vector<dy::FlowPoint>& points,std::vector<dy::FlowMatch>& matches) override {
if(!f.valid()||f.width!=info_.width[0]||f.height!=info_.height[0]||points.empty()||points.size()>180)return false;
if(!f.valid()||f.width!=info_.width[0]||f.height!=info_.height[0]||points.empty()||points.size()>dy::TrackerFeatureLimit)return false;
int next=1-previous_;memcpy(frames_[next].contents,f.pixels.data(),f.pixels.size()*sizeof(float));
memcpy(points_.contents,points.data(),points.size()*sizeof(dy::FlowPoint));
id<MTLCommandBuffer>b=[queue_ commandBuffer];pyramid(b,frames_[next]);
+1
查看文件
@@ -2,3 +2,4 @@
#include "MaskCore/DYMaskOperator.h"
struct DYToolMaskEntry {DYResolvedMask mask;int section,combine;};
struct DYToolMaskHeader {unsigned count;float offsetX,offsetY,scaleX,scaleY;int section,premultiplied;};
struct DYToolStageRange {int first,last,suppressBlackWhite;};
+3 -1
查看文件
@@ -1,8 +1,10 @@
NSString *_toolSession,*_selectedToolNode,*_selectedToolMask;
NSTimer *_toolAnalysisTimer;
BOOL _toolCaptureEnabled,_toolCanvasHidden,_toolDrawingPen,_toolShowCoverage;
BOOL _toolCaptureEnabled,_toolCanvasHidden,_toolDrawingPen,_toolShowCoverage,_toolCanvasCommitPending;
NSMutableDictionary *_toolCanvasDraft,*_toolCanvasOriginal;NSDictionary *_toolCanvasDocument;
NSPoint _toolCanvasHoverPoint;BOOL _toolCanvasHasHover;
NSPoint _toolDragStart;DYMaskParameters _toolDragParameters;NSInteger _toolDragPart;
CMTime _toolCanvasEditTime;uint64_t _toolCanvasRevision;
dy::GrayFrame _toolSourceFrame,_trackingReferenceFrame;
CMTime _toolSourceTime,_trackingReferenceTime,_trackingFrameDuration,_trackingPreviousTime;
std::atomic_bool _trackingActive,_trackingFinishing,_trackingInFrame,_trackingCancelled;
+7 -32
查看文件
@@ -1,6 +1,6 @@
- (void)initializeToolHost {
_toolCaptureDevices=[NSMutableDictionary new];_toolCanvasDocument=[[[[DYToolDocument alloc]init]autorelease].document copy];_toolSourceTime=kCMTimeInvalid;
NSNotificationCenter *n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(toolCanvasSelection:) name:@"DYToolCanvasSelection" object:_apiManager];[n addObserver:self selector:@selector(toolTrackRequested:) name:@"DYToolTrack" object:_apiManager];
_toolCaptureDevices=[NSMutableDictionary new];_toolCanvasDocument=[[[[DYToolDocument alloc]init]autorelease].document copy];_toolSourceTime=kCMTimeInvalid;_toolCanvasEditTime=kCMTimeInvalid;
NSNotificationCenter *n=NSNotificationCenter.defaultCenter;[n addObserver:self selector:@selector(toolCanvasSelection:) name:@"DYToolCanvasSelection" object:_apiManager];[n addObserver:self selector:@selector(toolCanvasCommand:) name:@"DYToolCanvasCommand" object:_apiManager];[n addObserver:self selector:@selector(toolTrackRequested:) name:@"DYToolTrack" object:_apiManager];
}
- (void)tearDownToolHost {
[_toolAnalysisTimer invalidate];[_toolAnalysisTimer release];@synchronized(DYToolCanvasSessions()){if(_toolSession)[DYToolCanvasSessions()removeObjectForKey:_toolSession];}
@@ -15,7 +15,7 @@
- (dy::GrayFrame)toolGrayFrame:(FxImageTile*)tile error:(NSError**)error {
@synchronized(_toolCaptureDevices){FxRect b=tile.tilePixelBounds,image=tile.imagePixelBounds;if(b.left!=image.left||b.right!=image.right||b.bottom!=image.bottom||b.top!=image.top)return {};
NSNumber *key=@(tile.deviceRegistryID);NSMutableDictionary *entry=_toolCaptureDevices[key];if(!entry){NSArray *devices=MTLCopyAllDevices();id<MTLDevice>d=nil;for(id<MTLDevice>candidate in devices)if(candidate.registryID==tile.deviceRegistryID)d=candidate;if(d){id<MTLLibrary>library=[d newLibraryWithURL:[[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"]error:error];id<MTLFunction>function=[library newFunctionWithName:@"dyToolCapture"];id<MTLComputePipelineState>pipeline=function?[d newComputePipelineStateWithFunction:function error:error]:nil;id<MTLCommandQueue>queue=[d newCommandQueue];if(pipeline&&queue){entry=[NSMutableDictionary dictionaryWithDictionary:@{@"device":d,@"pipeline":pipeline,@"queue":queue}];_toolCaptureDevices[key]=entry;}[pipeline release];[queue release];[function release];[library release];}[devices release];if(!entry)return {};}
id<MTLTexture>texture=[tile metalTextureForDevice:entry[@"device"]];if(!texture)return {};unsigned width=(unsigned)MIN((NSUInteger)960,texture.width),height=(unsigned)MAX(16.,texture.height*width/(texture.width*MAX(.01,tile.pixelAspect)));if(width<16||height>4096)return {};
id<MTLTexture>texture=[tile metalTextureForDevice:entry[@"device"]];if(!texture)return {};double aspect=tile.pixelAspect;if(!std::isfinite(aspect)||aspect<=0)return {};aspect=MAX(.01,aspect);double displayHeight=texture.height/aspect,scale=MIN(1.,MIN(3840./texture.width,2160./displayHeight));unsigned width=(unsigned)floor(texture.width*scale),height=(unsigned)floor(displayHeight*scale);if(width<16||height<16||height>2160||width>3840)return {};
id<MTLBuffer>buffer=[entry[@"device"]newBufferWithLength:width*height*sizeof(float) options:MTLResourceStorageModeShared];if(!buffer)return {};vector_uint3 info={width,height,(unsigned)(tile.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)};id<MTLCommandBuffer>commands=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>encoder=[commands computeCommandEncoder];[encoder setComputePipelineState:entry[@"pipeline"]];[encoder setTexture:texture atIndex:0];[encoder setBuffer:buffer offset:0 atIndex:0];[encoder setBytes:&info length:sizeof(info) atIndex:1];[encoder dispatchThreads:MTLSizeMake(width,height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[encoder endEncoding];[commands commit];[commands waitUntilCompleted];dy::GrayFrame frame;if(commands.status==MTLCommandBufferStatusCompleted){frame={int(width),int(height),std::vector<float>(width*height)};memcpy(frame.pixels.data(),buffer.contents,width*height*sizeof(float));}[buffer release];return frame;
}
}
@@ -25,14 +25,14 @@
}
- (void)toolCanvasSelection:(NSNotification*)notification {
NSString *node=notification.userInfo[@"node"],*mask=notification.userInfo[@"mask"];if(!node||!mask)return;NSDictionary *document=notification.userInfo[@"document"];if(document&&DYValidToolDocument(document)){DYToolDocument *immutable=[[[DYToolDocument alloc]init]autorelease];immutable.document=document;[self adoptToolCanvasDocument:immutable.document];}os_log(OS_LOG_DEFAULT,"dayu_tool_canvas_selected");
@synchronized(self){if(_trackingActive.load()&&(![_trackingNode isEqual:node]||![_trackingMaskID isEqual:mask])){_trackingCancelled.store(true);_trackingDiscard=YES;}[_selectedToolNode release];_selectedToolNode=[node copy];[_selectedToolMask release];_selectedToolMask=[mask copy];_toolCanvasHidden=[notification.userInfo[@"hidden"]boolValue];_toolDrawingPen=[notification.userInfo[@"draw"]boolValue];[_toolCanvasDraft release];_toolCanvasDraft=nil;[_toolCanvasOriginal release];_toolCanvasOriginal=nil;}
@synchronized(self){if(_trackingActive.load()&&(![_trackingNode isEqual:node]||![_trackingMaskID isEqual:mask])){_trackingCancelled.store(true);_trackingDiscard=YES;}[_selectedToolNode release];_selectedToolNode=[node copy];[_selectedToolMask release];_selectedToolMask=[mask copy];_toolCanvasHidden=[notification.userInfo[@"hidden"]boolValue];_toolDrawingPen=[notification.userInfo[@"draw"]boolValue];++_toolCanvasRevision;_toolCanvasEditTime=kCMTimeInvalid;_toolDragPart=0;_toolCanvasHasHover=NO;[_toolCanvasDraft release];_toolCanvasDraft=nil;[_toolCanvasOriginal release];_toolCanvasOriginal=nil;}[self postToolCanvasStatus:_toolDrawingPen?@"钢笔:点击放点,拖出曲柄;点首节点或完成绘制闭合。":@"已选中本层蒙版"];
}
- (BOOL)toolCanvasVisible {@synchronized(self){return _selectedToolNode&&_selectedToolMask&&!_toolCanvasHidden;}}
- (NSDictionary*)toolCanvasMaskAtTime:(CMTime)time {
@synchronized(self){if(_toolCanvasHidden||!_selectedToolMask)return nil;NSDictionary *m=_toolCanvasDraft?:[self toolMask:_selectedToolMask node:_selectedToolNode document:_toolCanvasDocument];if(!m)return nil;DYMaskParameters p=DYMaskAtTime(m,time);return @{@"id":m[@"id"],@"parameters":[NSData dataWithBytes:&p length:sizeof(p)],@"nodes":m[@"nodes"]?:[NSData data],@"drawing":@(_toolDrawingPen),@"coverage":@(_toolShowCoverage)};}
@synchronized(self){if(_toolCanvasHidden||!_selectedToolMask)return nil;NSDictionary *m=_toolCanvasDraft?:[self toolMask:_selectedToolMask node:_selectedToolNode document:_toolCanvasDocument];if(!m)return nil;DYMaskParameters p=DYMaskAtTime(m,time);return @{@"id":m[@"id"],@"parameters":[NSData dataWithBytes:&p length:sizeof(p)],@"nodes":(_toolDrawingPen&&!_toolCanvasDraft)?[NSData data]:(m[@"nodes"]?:[NSData data]),@"drawing":@(_toolDrawingPen),@"hover":(_toolDrawingPen&&_toolCanvasHasHover)?@[@(_toolCanvasHoverPoint.x),@(_toolCanvasHoverPoint.y)]:@[],@"coverage":@(_toolShowCoverage)};}
}
- (void)toolTrackRequested:(NSNotification*)notification {
NSInteger direction=[notification.userInfo[@"direction"]integerValue];if(direction==9){_trackingCancelled.store(true);return;}if(_trackingActive.load()){[self toolStatus:@"请先取消当前跟踪"];return;}
NSInteger direction=[notification.userInfo[@"direction"]integerValue];if(direction==9){_trackingCancelled.store(true);return;}@synchronized(self){if(_toolDrawingPen||_toolCanvasCommitPending){[self postToolCanvasStatus:@"请先完成或取消钢笔绘制,再开始跟踪。"];return;}}if(_trackingActive.load()){[self toolStatus:@"请先取消当前跟踪"];return;}
id<FxCustomParameterActionAPI_v4>a=[_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{
id<FxAnalysisAPI>analysis=[_apiManager apiForProtocol:@protocol(FxAnalysisAPI)];FxAnalysisState state=[analysis analysisStateForEffect];if(!analysis||state==kFxAnalysisState_AnalysisRequested||state==kFxAnalysisState_AnalysisStarted){[self toolStatus:@"宿主未就绪,请等待当前分析结束"];return;}
CMTime time=a.currentTime;NSDictionary *doc=DYReadTools(_apiManager,time).document;NSDictionary *mask=[self toolMask:notification.userInfo[@"mask"] node:notification.userInfo[@"node"] document:doc];if(!mask||![mask[@"enabled"]boolValue]){[self toolStatus:@"请先选择当前工具的启用蒙版"];return;}DYMaskParameters seed=DYMaskAtTime(mask,time);if(seed.kind>DYMaskBezier||(seed.kind==DYMaskBezier&&[mask[@"nodes"]length]<3*sizeof(DYBezierNode))){[self toolStatus:@"跟踪需要矩形、椭圆或闭合钢笔区域"];return;}
@@ -82,29 +82,4 @@
});return YES;
}
- (void)toolCanvasEvent:(NSEventType)type point:(NSPoint)point part:(NSInteger)part modifiers:(FxModifierKeys)modifiers key:(unichar)key time:(CMTime)time {
// Host OSC callbacks hold model/render locks; editing happens after they unwind.
NSString *node=nil,*maskID=nil;@synchronized(self){node=[_selectedToolNode copy];maskID=[_selectedToolMask copy];}
dispatch_async(dispatch_get_main_queue(),^{if(self->_trackingActive.load()||![node isEqual:self->_selectedToolNode]||![maskID isEqual:self->_selectedToolMask])return;
if(type==NSEventTypeKeyDown&&key==27){@synchronized(self){[self->_toolCanvasDraft release];self->_toolCanvasDraft=nil;[self->_toolCanvasOriginal release];self->_toolCanvasOriginal=nil;self->_toolDrawingPen=NO;}return;}
if(part>=10000&&type==NSEventTypeLeftMouseDown){NSInteger item=part-10000;if(item==7){self->_toolShowCoverage=!self->_toolShowCoverage;return;}if(item==8){self->_toolCanvasHidden=YES;return;}if(item==0){self->_toolDrawingPen=NO;return;}
id<FxCustomParameterActionAPI_v4>a=[self->_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(self->_apiManager,time).document);NSMutableArray *masks=[[DYMasksForTool(doc,node)mutableCopy]autorelease];if(masks.count>=DYToolMaskLimit)return;NSInteger kind=((int[]){0,2,1,0,3,4,5})[MIN(6,item)];NSDictionary *m=DYNewMask(kind);[masks addObject:m];if(!DYSetToolMasks(doc,node,masks))return;id<FxUndoAPI>u=[self->_apiManager apiForProtocol:@protocol(FxUndoAPI)];[u startUndoGroup:@"添加工具蒙版"];DYWriteTools(self->_apiManager,doc,time);[u endUndoGroup];[self->_selectedToolMask release];self->_selectedToolMask=[m[@"id"]copy];self->_toolDrawingPen=kind==2;[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:self->_apiManager userInfo:@{@"node":node,@"mask":m[@"id"],@"draw":@(kind==2),@"document":doc}];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self->_apiManager];return;
}
BOOL commit=NO;
if(type==NSEventTypeLeftMouseDown){id<FxCustomParameterActionAPI_v4>a=[self->_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSDictionary *m=[self toolMask:maskID node:node document:DYReadTools(self->_apiManager,time).document];if(!m)return;@synchronized(self){if(!self->_toolCanvasDraft){self->_toolCanvasOriginal=[DYMutablePlist(m)retain];self->_toolCanvasDraft=[DYMutablePlist(m)retain];self->_toolDragParameters=DYMaskAtTime(m,time);self->_toolDragParameters.imageAspect=self->_toolSourceFrame.valid()?float(self->_toolSourceFrame.width)/self->_toolSourceFrame.height:1;self->_toolCanvasDraft[@"parameters"]=[NSData dataWithBytes:&self->_toolDragParameters length:sizeof(DYMaskParameters)];self->_toolCanvasDraft[@"keys"]=@[];if(self->_toolDrawingPen)self->_toolCanvasDraft[@"nodes"]=[NSData data];}self->_toolDragStart=point;self->_toolDragPart=part;self->_toolDragParameters=DYMaskAtTime(self->_toolCanvasDraft,time);
if(self->_toolDrawingPen){DYMaskParameters p=self->_toolDragParameters;float aspect=p.imageAspect;float dx=(point.x-p.centerX)*aspect,dy=point.y-p.centerY,c=cos(p.angle),s=sin(p.angle),x=(dx*c+dy*s)/(p.width*aspect),y=(-dx*s+dy*c)/p.height;DYBezierNode n={x,y,x,y,x,y};NSMutableData *nodes=[[self->_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];if(nodes.length<32*sizeof(n))[nodes appendBytes:&n length:sizeof(n)];self->_toolCanvasDraft[@"nodes"]=nodes;}}
}@finally{[a endAction:self];}return;
}
if(!self->_toolCanvasDraft)return;
if(type==NSEventTypeLeftMouseDragged){@synchronized(self){DYMaskParameters p=self->_toolDragParameters;float dx=point.x-self->_toolDragStart.x,dy=point.y-self->_toolDragStart.y;
if(self->_toolDrawingPen){NSMutableData *nodes=[[self->_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];if(nodes.length){auto *n=(DYBezierNode*)nodes.mutableBytes;NSUInteger last=nodes.length/sizeof(DYBezierNode)-1;float a=p.imageAspect,c=cos(p.angle),s=sin(p.angle),lx=((point.x-p.centerX)*a*c+(point.y-p.centerY)*s)/(p.width*a),ly=(-(point.x-p.centerX)*a*s+(point.y-p.centerY)*c)/p.height;n[last].outX=lx;n[last].outY=ly;n[last].inX=2*n[last].x-lx;n[last].inY=2*n[last].y-ly;self->_toolCanvasDraft[@"nodes"]=nodes;}}
else if(self->_toolDragPart>=1000){NSMutableData *nodes=[[self->_toolCanvasDraft[@"nodes"]mutableCopy]autorelease];NSUInteger index=(self->_toolDragPart-1000)/3,handle=(self->_toolDragPart-1000)%3;if(index<nodes.length/sizeof(DYBezierNode)){auto *n=(DYBezierNode*)nodes.mutableBytes;float a=p.imageAspect,c=cos(p.angle),s=sin(p.angle),lx=((point.x-p.centerX)*a*c+(point.y-p.centerY)*s)/(p.width*a),ly=(-(point.x-p.centerX)*a*s+(point.y-p.centerY)*c)/p.height;if(handle==0){float mx=lx-n[index].x,my=ly-n[index].y;n[index].x=lx;n[index].y=ly;n[index].inX+=mx;n[index].inY+=my;n[index].outX+=mx;n[index].outY+=my;}else if(handle==1){n[index].inX=lx;n[index].inY=ly;}else{n[index].outX=lx;n[index].outY=ly;}self->_toolCanvasDraft[@"nodes"]=nodes;}}
else if(self->_toolDragPart==6){p.angle=atan2((point.y-p.centerY),(point.x-p.centerX)*p.imageAspect)+M_PI/2;}
else if(self->_toolDragPart>=2&&self->_toolDragPart<=5){float a=p.imageAspect,c=cos(p.angle),s=sin(p.angle),x=(point.x-p.centerX)*a,y=point.y-p.centerY;p.width=MAX(.001f,2*fabs(x*c+y*s)/a);p.height=MAX(.001f,2*fabs(-x*s+y*c));}
else {p.centerX+=dx;p.centerY+=dy;}if(dyValidMaskParameters(p))self->_toolCanvasDraft[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];}return;
}
if(type==NSEventTypeLeftMouseUp&&!self->_toolDrawingPen)commit=YES;
if(type==NSEventTypeKeyDown&&(key==13||key==10)&&self->_toolDrawingPen){if([self->_toolCanvasDraft[@"nodes"]length]<3*sizeof(DYBezierNode))return;self->_toolDrawingPen=NO;commit=YES;}
if(commit){id<FxCustomParameterActionAPI_v4>a=[self->_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(self->_apiManager,time).document);NSMutableDictionary *current=[self toolMask:maskID node:node document:doc];if(current&&[current isEqual:self->_toolCanvasOriginal]){NSMutableDictionary *draft=DYMutablePlist(self->_toolCanvasDraft);if([current[@"keys"]count]){DYMaskParameters p=DYMaskAtTime(draft,time);NSMutableArray *keys=[[current[@"keys"]mutableCopy]autorelease];NSIndexSet *same=[keys indexesOfObjectsPassingTest:^BOOL(NSDictionary *k,NSUInteger i,BOOL *stop){return CMTimeCompare(CMTimeMakeWithEpoch([k[@"value"]longLongValue],[k[@"scale"]intValue],[k[@"epoch"]longLongValue]),time)==0;}];[keys removeObjectsAtIndexes:same];[keys addObject:DYMaskKey(time,p,YES,1)];draft[@"keys"]=@[];DYMergeTracking(draft,keys);}if(DYValidToolMask(draft)&&![current isEqual:draft]){[current setDictionary:draft];id<FxUndoAPI>undo=[self->_apiManager apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"编辑工具蒙版"];DYWriteTools(self->_apiManager,doc,time);[undo endUndoGroup];}}}@finally{[a endAction:self];}@synchronized(self){[self->_toolCanvasDraft release];self->_toolCanvasDraft=nil;[self->_toolCanvasOriginal release];self->_toolCanvasOriginal=nil;}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:self->_apiManager];}
});[node release];[maskID release];
}
#include "DYToolCanvasEditing.inc.h"
@@ -0,0 +1,44 @@
// Stable insertion identities, on-card layout and noncommuting render oracles.
{
DYToolDocument *empty=[[[DYToolDocument alloc]init]autorelease];NSMutableDictionary *doc=DYMutablePlist(empty.document);
NSDictionary *one=DYInsertTool(doc,@"hsl",@"base:hsl"),*two=DYInsertTool(doc,@"hsl",one[@"id"]),*newest=DYInsertTool(doc,@"hsl",@"base:hsl");NSArray *order=DYToolDisplayOrder(doc);NSUInteger hslIndex=[order indexOfObject:@"base:hsl"];
run.need(@"inserted-tool-documents-have-validated-anchors",DYValidToolDocument(doc)&&[doc[@"schema"]isEqual:@2]);
run.record(@"repeat-splices-immediately-after-clicked-base-or-extra",[order[hslIndex+1]isEqual:newest[@"id"]]&&[order[hslIndex+2]isEqual:one[@"id"]]&&[order[hslIndex+3]isEqual:two[@"id"]]&&[order[hslIndex+4]isEqual:@"base:curve"]);
run.record(@"inserted-tools-start-with-independent-initial-values",[one[@"values"]count]==0&&[two[@"values"]count]==0&&[newest[@"values"]count]==0&&![one[@"id"]isEqual:two[@"id"]]);
DYToolDocument *authored=[[[DYToolDocument alloc]init]autorelease];authored.document=doc;NSData *archive=[NSKeyedArchiver archivedDataWithRootObject:authored requiringSecureCoding:YES error:&error];DYToolDocument *restored=[NSKeyedUnarchiver unarchivedObjectOfClass:DYToolDocument.class fromData:archive error:&error];run.record(@"inserted-order-secure-archive-roundtrip",[restored isEqual:authored]&&[DYToolDisplayOrder(restored.document)isEqual:order]);
NSMutableDictionary *bad=DYMutablePlist(doc);bad[@"layers"][0][@"after"]=@"base:unknown";run.record(@"insertion-rejects-unknown-base-anchor",!DYValidToolDocument(bad));bad=DYMutablePlist(doc);bad[@"layers"][0][@"after"]=bad[@"layers"][0][@"id"];run.record(@"insertion-rejects-cyclic-anchor",!DYValidToolDocument(bad));
BOOL removed=DYRemoveTool(doc,one[@"id"]);order=DYToolDisplayOrder(doc);hslIndex=[order indexOfObject:@"base:hsl"];run.record(@"delete-reconnects-child-without-moving-to-bottom",removed&&DYValidToolDocument(doc)&&[order[hslIndex+1]isEqual:newest[@"id"]]&&[order[hslIndex+2]isEqual:two[@"id"]]);
DYWriteTools(manager,doc,kCMTimeZero);DYInspector *inspector=[[[DYInspector alloc]initWithAPIManager:manager renderer:renderer]autorelease];[inspector refresh];[inspector setFrameSize:NSMakeSize(360,780)];[inspector layoutSubtreeIfNeeded];NSDictionary *views=[inspector valueForKey:@"_stackViews"];NSArray *cards=[inspector valueForKey:@"_cards"];NSView *baseHSL=nil,*baseCurve=nil;for(NSDictionary *card in cards){if([card[@"section"][@"key"]isEqual:@"hsl"])baseHSL=card[@"view"];if([card[@"section"][@"key"]isEqual:@"curve"])baseCurve=card[@"view"];}NSView *newView=views[newest[@"id"]],*secondView=views[two[@"id"]];run.record(@"new-native-card-is-laid-out-between-its-source-and-next-module",newView&&secondView&&NSMinY(newView.frame)>=NSMaxY(baseHSL.frame)&&NSMinY(secondView.frame)>=NSMaxY(newView.frame)&&NSMinY(baseCurve.frame)>=NSMaxY(secondView.frame));
doc=DYMutablePlist(empty.document);NSMutableDictionary *legacy=DYMutablePlist(DYNewTool(@"hsl"));[doc[@"layers"]addObject:legacy];NSDictionary *child=DYInsertTool(doc,@"hsl",legacy[@"id"]);run.record(@"schema-one-tail-layer-retains-tail-root-with-new-child",[DYToolRootAnchor(doc,legacy[@"id"])isEqual:@"tail"]&&[DYToolRootAnchor(doc,child[@"id"])isEqual:@"tail"]&&[DYToolDisplayOrder(doc).lastObject isEqual:child[@"id"]]);
auto renderInserted=[&](NSDictionary *tools,DYUniforms u,NSString *name){NSError *failure=nil;BOOL ok=[renderer renderSource:source destination:destination uniforms:u paths:@{} spider:nil tools:tools error:&failure];run.need(name,ok,@{@"error":reason(failure)});return read(destination,gpu);};
auto upload=[&](DYDiagnosticTile *tile,const Pixels &pixels){[[tile metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,width,height) mipmapLevel:0 withBytes:pixels.data() bytesPerRow:width*8];};
upload(source,input);DYUniforms base=DYToolUniforms(@{@"type":@"hsl",@"values":@{@"hsl0_0":@28}});base.colorGradingSectionEnabled=1;base.colorGradingHueSatA.x=210;base.colorGradingHueSatA.y=42;base.colorGradingLuma.x=18;
Pixels original=renderInserted(empty.document,base,@"insertion-original-fused-oracle");doc=DYMutablePlist(empty.document);DYInsertTool(doc,@"hsl",@"base:hsl");Pixels idle=renderInserted(doc,base,@"insertion-neutral-child-render");run.record(@"untouched-inserted-tool-preserves-original-fused-pixels-exactly",difference(original,idle).maximum==0);
NSMutableDictionary *extra=(id)doc[@"layers"][0];extra[@"values"][@"hsl1_2"]=@55;DYUniforms baseHSLOnly=base;baseHSLOnly.colorGradingSectionEnabled=0;Pixels first=render(run,renderer,source,destination,gpu,baseHSLOnly,@{},@"insertion-base-hsl-reference");DYDiagnosticTile *intermediate=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:width height:height]autorelease];upload(intermediate,first);Pixels second=render(run,renderer,intermediate,destination,gpu,DYToolUniforms(extra),@{},@"insertion-extra-hsl-reference");upload(intermediate,second);DYUniforms grading=DYToolUniforms(@{@"type":@"grading"});grading.colorGradingHueSatA.x=210;grading.colorGradingHueSatA.y=42;grading.colorGradingLuma.x=18;Pixels expected=render(run,renderer,intermediate,destination,gpu,grading,@{},@"insertion-later-native-grading-reference");Pixels actual=renderInserted(doc,base,@"anchored-hsl-before-grading-render");run.record(@"anchored-hsl-executes-before-later-native-grading",difference(expected,actual).maximum<.004,measure(difference(expected,actual)));
NSMutableDictionary *tail=DYMutablePlist(doc);[tail[@"layers"][0]removeObjectForKey:@"after"];tail[@"schema"]=@1;Pixels oldTail=renderInserted(tail,base,@"historical-tail-hsl-render");run.record(@"anchored-hsl-is-not-only-a-visual-move-from-tail",difference(actual,oldTail).different>20,measure(difference(actual,oldTail)));
// Two anchors must follow the legacy native operation order, not insertion time.
doc=DYMutablePlist(empty.document);NSMutableDictionary *hsl=(id)DYInsertTool(doc,@"hsl",@"base:hsl");hsl[@"values"][@"hsl0_0"]=@35;NSMutableDictionary *curve=(id)DYInsertTool(doc,@"curve",@"base:curve");curve[@"values"][@"curveY4"]=@32;curve[@"values"][@"curveY5"]=@(-24);curve[@"values"][@"channel0X0"]=@.25;curve[@"values"][@"channel0X1"]=@.75;
DYUniforms neutralBase=DYToolUniforms(@{@"type":@"hsl"});first=render(run,renderer,source,destination,gpu,DYToolUniforms(curve),@{},@"anchored-curve-first-reference");run.record(@"curve-anchor-reference-materially-adjusts-red-channel",difference(first,input).different>20&&difference(first,input).maximum>.01,measure(difference(first,input)));upload(intermediate,first);expected=render(run,renderer,intermediate,destination,gpu,DYToolUniforms(hsl),@{},@"anchored-hsl-second-reference");actual=renderInserted(doc,neutralBase,@"two-native-anchor-render");run.record(@"two-anchors-preserve-native-curve-before-hsl-operation-order",difference(expected,actual).maximum<.004,measure(difference(expected,actual)));
first=render(run,renderer,source,destination,gpu,DYToolUniforms(hsl),@{},@"wrong-hsl-before-curve-reference");upload(intermediate,first);Pixels wrong=render(run,renderer,intermediate,destination,gpu,DYToolUniforms(curve),@{},@"wrong-curve-after-hsl-reference");run.record(@"anchor-reference-operations-are-noncommuting",difference(expected,wrong).different>20&&difference(expected,wrong).maximum>.005,measure(difference(expected,wrong)));
// A changed tool with a zero-strength mask forces the anchored scheduler but
// contributes no correction. Compare against the untouched fused operation to
// catch replayed CST, lost global-white statistics, a displaced spatial source,
// lost pre-HSL skin reference, or moving the original Spider before color work.
auto boundary=[&](NSString *name,DYUniforms u,NSString *anchor,NSData *mesh,NSDictionary *baseMasks=nil){
NSMutableDictionary *control=DYMutablePlist(empty.document),*baselineDocument=DYMutablePlist(empty.document);if(baseMasks){control[@"baseMasks"]=DYMutablePlist(baseMasks);baselineDocument[@"baseMasks"]=DYMutablePlist(baseMasks);}NSMutableDictionary *node=(id)DYInsertTool(control,@"hsl",anchor);node[@"values"][@"hsl0_0"]=@32;NSMutableDictionary *mask=DYMutablePlist(DYNewMask(DYMaskRectangle));DYMaskParameters p=DYMaskAtTime(mask,kCMTimeZero);p.strength=0;mask[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];[node[@"masks"]addObject:mask];NSError *failure=nil;
BOOL baselineOK=[renderer renderSource:source destination:destination uniforms:u paths:@{} spider:mesh tools:baselineDocument error:&failure];Pixels before=read(destination,gpu);BOOL insertedOK=[renderer renderSource:source destination:destination uniforms:u paths:@{} spider:mesh tools:control error:&failure];Pixels after=read(destination,gpu);Difference delta=difference(before,after);BOOL alpha=YES;for(NSUInteger i=0;i<width*height;i++)alpha&=before[i*4+3]==after[i*4+3];run.record(name,baselineOK&&insertedOK&&alpha&&delta.nonfinite==0&&delta.maximum<.006,measure(delta));
};
DYUniforms cstBoundary=defaults;cstBoundary.cm.configured=1;cstBoundary.cm.exposure=-.6;boundary(@"anchored-primary-cst-runs-once-before-native-stages",cstBoundary,@"base:primary",nil);
DYUniforms skinBoundary=base;skinBoundary.skinProtection.x=1;skinBoundary.skinProtection.y=85;skinBoundary.skinProtection.z=28;boundary(@"anchored-split-retains-native-pre-hsl-skin-reference",skinBoundary,@"base:hsl",nil);
DYUniforms textureBoundary=DYToolUniforms(@{@"type":@"base"});textureBoundary.whites=48;textureBoundary.texture=35;textureBoundary.clarity=25;textureBoundary.dehaze=15;textureBoundary.primariesSectionEnabled=1;textureBoundary.redPrimaryHue=20;textureBoundary.redPrimarySaturation=15;boundary(@"anchored-prefix-preserves-whites-statistics-and-spatial-base-input",textureBoundary,@"base:primaries",nil);
DYUniforms oldInputBoundary=textureBoundary;oldInputBoundary.primarySectionEnabled=1;oldInputBoundary.inputSectionEnabled=1;oldInputBoundary.cm.configured=-1;oldInputBoundary.inputProfile=17;oldInputBoundary.preLUTStrength=1;boundary(@"anchored-legacy-input-lut-remains-available-to-spatial-neighbors",oldInputBoundary,@"base:primaries",nil);
NSMutableDictionary *lumaMask=DYMutablePlist(DYNewMask(DYMaskLumaKey));DYMaskParameters luma=DYMaskAtTime(lumaMask,kCMTimeZero);luma.inputBlack=.25;luma.inputWhite=.8;lumaMask[@"parameters"]=[NSData dataWithBytes:&luma length:sizeof(luma)];boundary(@"anchored-original-color-mask-keeps-post-cst-source-reference",textureBoundary,@"base:primaries",nil,@{@"base":@[lumaMask]});
DYUniforms chromaBoundary=base;chromaBoundary.baseSectionEnabled=1;chromaBoundary.colorSectionEnabled=1;chromaBoundary.saturation=45;chromaBoundary.vibrance=20;boundary(@"anchored-split-preserves-second-base-chroma-stage",chromaBoundary,@"base:hsl",nil);
auto boundaryMesh=dy::neutralMesh();for(int i=0;i<dy::meshCount(boundaryMesh);i++){boundaryMesh.x[i]+=.04f;boundaryMesh.y[i]-=.02f;}NSData *meshData=[NSData dataWithBytes:&boundaryMesh length:sizeof(boundaryMesh)];DYUniforms spiderBoundary=base;spiderBoundary.spiderSectionEnabled=1;spiderBoundary.spiderMix=.8;boundary(@"anchored-spider-remains-after-native-color-stages",spiderBoundary,@"base:spider",meshData);
DYUniforms bwBoundary=skinBoundary;bwBoundary.blackWhiteSectionEnabled=1;bwBoundary.cm.blackWhiteMix=.45;boundary(@"anchored-bw-suffix-defers-color-mixture-until-after-native-skin",bwBoundary,@"base:blackwhite",nil);bwBoundary.spiderSectionEnabled=1;bwBoundary.spiderMix=.8;boundary(@"anchored-look-suffix-keeps-bw-mixture-before-single-spider",bwBoundary,@"base:look",meshData);
Pixels hdr=input;for(NSUInteger i=0;i<width*height;i++){float a=hdr[i*4+3];hdr[i*4]=a*1.35f;hdr[i*4+1]=a*.4f;hdr[i*4+2]=-a*.06f;}upload(source,hdr);boundary(@"zero-strength-extra-mask-preserves-hdr-and-negative-colors",neutralBase,@"base:primary",nil);upload(source,input);
NSURL *cubeURL=[NSURL fileURLWithPath:[runtime stringByAppendingPathComponent:@"inserted-tool-stack.cube"]];error=nil;BOOL exported=[renderer exportLUT:cubeURL uniforms:neutralBase paths:@{} spider:nil tools:doc error:&error];NSString *text=exported?[NSString stringWithContentsOfURL:cubeURL encoding:NSUTF8StringEncoding error:&error]:nil;std::vector<float>values;for(NSString *line in [text componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]){float r,g,b;if(sscanf(line.UTF8String,"%f %f %f",&r,&g,&b)==3){values.push_back(r);values.push_back(g);values.push_back(b);}}
float codes[3]={.5f,.25f,.75f};Pixels solid(input.size());for(NSUInteger i=0;i<width*height;i++){for(int c=0;c<3;c++)solid[i*4+c]=powf((codes[c]+.055f)/1.055f,2.4f);solid[i*4+3]=1;}upload(source,solid);actual=renderInserted(doc,neutralBase,@"inserted-cube-production-sample");BOOL matches=exported&&values.size()==33*33*33*3;for(int c=0;c<3&&matches;c++){float code=values[((24*33+8)*33+16)*3+c],linear=code<=.04045f?code/12.92f:powf((code+.055f)/1.055f,2.4f);matches&=fabs(linear-(float)actual[c])<.004;}run.record(@"cube-export-follows-identical-anchored-tool-order",matches,@{@"error":reason(error)});
upload(source,input);DYWriteTools(manager,empty.document,kCMTimeZero);
}
+8 -6
查看文件
@@ -1,19 +1,21 @@
- (void)synchronizeTools {
id<FxCustomParameterActionAPI_v4>a=[self actionAPI];if(!a)return;[a startAction:self];NSArray *layers=nil;@try{layers=[DYReadTools(_manager,a.currentTime).document[@"layers"]copy];}@finally{[a endAction:self];}
NSMutableArray *order=[NSMutableArray array];NSMutableDictionary *numbers=[NSMutableDictionary dictionary];
for(NSDictionary *node in layers){NSString *ID=node[@"id"],*type=node[@"type"];[order addObject:ID];NSInteger number=MAX(1,[numbers[type]integerValue])+1;numbers[type]=@(number);
id<FxCustomParameterActionAPI_v4>a=[self actionAPI];if(!a)return;[a startAction:self];NSDictionary *document=nil;@try{document=[DYReadTools(_manager,a.currentTime).document copy];}@finally{[a endAction:self];}
NSMutableArray *order=[NSMutableArray array];NSMutableDictionary *numbers=[NSMutableDictionary dictionary],*roots=[NSMutableDictionary dictionary];
for(NSString *orderedID in DYToolDisplayOrder(document)){NSDictionary *node=DYToolWithID(document,orderedID);if(!node)continue;NSString *ID=node[@"id"],*type=node[@"type"];[order addObject:ID];roots[ID]=DYToolRootAnchor(document,ID)?:@"tail";NSInteger number=MAX(1,[numbers[type]integerValue])+1;numbers[type]=@(number);
DYInspector *view=_stackViews[ID];if(!view){DYToolManager *manager=[[[DYToolManager alloc]initWithHost:_manager node:node]autorelease];view=[[[DYInspector alloc]initWithAPIManager:manager renderer:_renderer]autorelease];_stackViews[ID]=view;[_document addSubview:view];}
if(view->_cards.count){NSDictionary *section=view->_cards[0][@"section"];[view->_cards[0][@"header"]setTitle:[NSString stringWithFormat:@"%@ %ld",section[@"title"],(long)number]];}
[view refresh];[view setNeedsLayout:YES];
}
for(NSString *ID in [[_stackViews.allKeys copy]autorelease])if(![order containsObject:ID]){[_stackViews[ID]removeFromSuperview];[_stackViews removeObjectForKey:ID];}
[_stackOrder release];_stackOrder=[order copy];[layers release];[self setNeedsLayout:YES];
[_stackOrder release];_stackOrder=[order copy];[_stackRoots release];_stackRoots=[roots copy];[document release];[self setNeedsLayout:YES];
}
- (void)toolMask:(NSButton*)sender{if(sender.tag<0||sender.tag>=_cards.count)return;[(DYToolMaskPanel*)_cards[sender.tag][@"maskPanel"]addMenu:sender];}
- (void)repeatTool:(NSButton*)sender{
if(sender.tag<0||sender.tag>=_cards.count)return;id<PROAPIAccessing>host=_embedded?[(DYToolManager*)_manager host]:_manager;id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];
@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSMutableArray *layers=doc[@"layers"];if(layers.count>=DYToolLimit){[self showError:@"最多可添加 32 个独立工具层。"];return;}NSDictionary *node=DYNewTool(_cards[sender.tag][@"section"][@"key"]);if(!node)return;[layers addObject:node];id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"再加一层初始化工具"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host userInfo:@{@"scrollToNewTool":@YES}];
NSString *addedID=nil;@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);if([doc[@"layers"]count]>=DYToolLimit){[self showError:@"最多可添加 32 个独立工具层。"];return;}NSString *type=_cards[sender.tag][@"section"][@"key"],*anchor=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:type];NSDictionary *node=DYInsertTool(doc,type,anchor);if(!node)return;addedID=[node[@"id"]copy];id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"再加一层初始化工具"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host userInfo:@{@"scrollToTool":addedID?:@""}];[addedID release];
}
- (void)removeTool:(id)sender{if(!_embedded)return;id<PROAPIAccessing>host=[(DYToolManager*)_manager host];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSMutableArray *layers=doc[@"layers"];NSDictionary *node=DYToolWithID(doc,[(DYToolManager*)_manager nodeID]);if(!node)return;[layers removeObject:node];id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"删除独立工具层"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];});}
- (void)removeTool:(id)sender{if(!_embedded)return;id<PROAPIAccessing>host=[(DYToolManager*)_manager host];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);if(!DYRemoveTool(doc,[(DYToolManager*)_manager nodeID]))return;id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"删除独立工具层"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];});}
- (CGFloat)layoutRepeatedToolsAfter:(NSString*)anchor y:(CGFloat)y width:(CGFloat)w {if(_embedded)return y;for(NSString *ID in _stackOrder)if([_stackRoots[ID]isEqual:anchor]){DYInspector *child=_stackViews[ID];child.frame=NSMakeRect(0,y,w,MAX(60,child->_stackHeight));[child layoutSubtreeIfNeeded];CGFloat height=MAX(60,child->_stackHeight);child.frame=NSMakeRect(0,y,w,height);y+=height;}return y;}
- (void)resetRepeatedTool{if(!_embedded)return;id<PROAPIAccessing>host=[(DYToolManager*)_manager host];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSMutableDictionary *node=(id)DYToolWithID(doc,[(DYToolManager*)_manager nodeID]);if(!node)return;NSDictionary *fresh=DYNewTool(node[@"type"]);node[@"values"]=fresh[@"values"];node[@"paths"]=@{};[node removeObjectForKey:@"spider"];node[@"spiderLinked"]=@YES;id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];[undo startUndoGroup:@"还原独立工具层"];DYWriteTools(host,doc,a.currentTime);[undo endUndoGroup];}@finally{[a endAction:self];}[self postChanged];}
+26 -18
查看文件
@@ -4,9 +4,9 @@
@end
@implementation DYToolOSC {
id<MTLDevice> _device;id<MTLCommandQueue> _queue;CIContext *_context;
CGFloat _height;NSRect _imageRect;NSDictionary *_mask;NSMutableArray *_handles;NSBezierPath *_outline;NSInteger _lastRoute;NSUInteger _drawCount,_hitDiagnostics,_eventDiagnostics;
CGFloat _height,_uiScale;NSInteger _toolbarRows;NSRect _imageRect;NSDictionary *_mask;NSMutableArray *_handles;NSBezierPath *_outline;NSInteger _lastRoute;NSUInteger _drawCount,_hitDiagnostics,_eventDiagnostics;
}
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager{if((self=[super init])){_apiManager=manager;_handles=[NSMutableArray new];_lastRoute=-1;os_log(OS_LOG_DEFAULT,"dayu_tool_osc_init");}return self;}
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager{if((self=[super init])){_apiManager=manager;_handles=[NSMutableArray new];_lastRoute=-1;_uiScale=1;_toolbarRows=9;os_log(OS_LOG_DEFAULT,"dayu_tool_osc_init");}return self;}
- (void)dealloc{[_device release];[_queue release];[_context release];[_mask release];[_handles release];[_outline release];[super dealloc];}
- (FxDrawingCoordinates)drawingCoordinates{return kFxDrawingCoordinates_CANVAS;}
- (DYPlugIn*)pluginAtTime:(CMTime)time{NSString *value=nil;id<FxParameterRetrievalAPI_v6>get=[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];[get getStringParameterValue:&value fromParameter:DYCanvasSessionParameterID];@synchronized(DYToolCanvasSessions()){return [DYToolCanvasSessions()objectForKey:value];}}
@@ -14,42 +14,50 @@
float ca=cos(p.angle),sa=sin(p.angle),aspect=p.imageAspect;float px=x*p.width*aspect,py=y*p.height;float u=p.centerX+(px*ca-py*sa)/aspect,v=p.centerY+px*sa+py*ca;return NSMakePoint(_imageRect.origin.x+u*_imageRect.size.width,_imageRect.origin.y+v*_imageRect.size.height);
}
- (void)addHandle:(NSPoint)p part:(NSInteger)part{[_handles addObject:@{@"point":[NSValue valueWithPoint:p],@"part":@(part)}];}
- (void)drawOSCWithWidth:(NSInteger)width height:(NSInteger)height activePart:(NSInteger)activePart destinationImage:(FxImageTile*)destination atTime:(CMTime)time {@autoreleasepool{
- (NSRect)toolbarRectForItem:(NSInteger)item{CGFloat scale=_uiScale,x=MAX(8*scale,_imageRect.origin.x+12*scale),y=MAX(8*scale,_imageRect.origin.y+12*scale);NSInteger rows=MAX(1,_toolbarRows);return NSMakeRect(x+(item/rows)*38*scale,y+(item%rows)*39*scale,32*scale,34*scale);}
- (void)drawOSCWithWidth:(NSInteger)width height:(NSInteger)height activePart:(NSInteger)activePart destinationImage:(FxImageTile*)destination atTime:(CMTime)time {@synchronized(self){@autoreleasepool{
if(!_device||_device.registryID!=destination.deviceRegistryID){[_device release];_device=nil;NSArray *devices=MTLCopyAllDevices();for(id<MTLDevice>d in devices)if(d.registryID==destination.deviceRegistryID)_device=[d retain];[devices release];[_queue release];_queue=[_device newCommandQueue];[_context release];_context=_device?[[CIContext contextWithMTLDevice:_device options:@{kCIContextWorkingColorSpace:NSNull.null,kCIContextOutputColorSpace:NSNull.null}]retain]:nil;}
id<MTLTexture>texture=[destination metalTextureForDevice:_device];if(!texture||!_queue)return;id<MTLCommandBuffer>commands=[_queue commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=texture;pass.colorAttachments[0].loadAction=MTLLoadActionClear;pass.colorAttachments[0].storeAction=MTLStoreActionStore;pass.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,0);id<MTLRenderCommandEncoder>encoder=[commands renderCommandEncoderWithDescriptor:pass];[encoder endEncoding];
_height=destination.imagePixelBounds.top-destination.imagePixelBounds.bottom;CGFloat canvasWidth=destination.imagePixelBounds.right-destination.imagePixelBounds.left;
id<FxOnScreenControlAPI_v4>api=[_apiManager apiForProtocol:@protocol(FxOnScreenControlAPI_v4)];double lx=0,ly=0,ux=0,uy=0;[api convertPointFromSpace:kFxDrawingCoordinates_OBJECT fromX:0 fromY:0 toSpace:kFxDrawingCoordinates_CANVAS toX:&lx toY:&ly];[api convertPointFromSpace:kFxDrawingCoordinates_OBJECT fromX:1 fromY:1 toSpace:kFxDrawingCoordinates_CANVAS toX:&ux toY:&uy];_imageRect=NSMakeRect(lx,_height-uy,ux-lx,uy-ly);
id<FxOnScreenControlAPI_v4>api=[_apiManager apiForProtocol:@protocol(FxOnScreenControlAPI_v4)];double lx=0,ly=0,ux=0,uy=0;[api convertPointFromSpace:kFxDrawingCoordinates_OBJECT fromX:0 fromY:0 toSpace:kFxDrawingCoordinates_CANVAS toX:&lx toY:&ly];[api convertPointFromSpace:kFxDrawingCoordinates_OBJECT fromX:1 fromY:1 toSpace:kFxDrawingCoordinates_CANVAS toX:&ux toY:&uy];_imageRect=NSMakeRect(lx,_height-uy,ux-lx,uy-ly);_uiScale=[api respondsToSelector:@selector(backingScaleFactor)]?MAX(1.,MIN(3.,[api backingScaleFactor])):1.;_toolbarRows=MAX(1,MIN(11,(NSInteger)floor((_height-MAX(8*_uiScale,_imageRect.origin.y+12*_uiScale)-8*_uiScale)/(39*_uiScale))));
DYPlugIn *plugin=[self pluginAtTime:time];NSDictionary *mask=[plugin toolCanvasMaskAtTime:time];NSInteger route=(plugin?1:0)+(mask?2:0);if(route!=_lastRoute||_drawCount++<2){_lastRoute=route;os_log(OS_LOG_DEFAULT,"dayu_tool_osc_route plugin=%{public}d mask=%{public}d width=%{public}.2f height=%{public}.2f",plugin!=nil,mask!=nil,_imageRect.size.width,_imageRect.size.height);}[_mask release];_mask=[mask copy];[_handles removeAllObjects];[_outline release];_outline=nil;
if(mask&&canvasWidth>0&&_height>0&&canvasWidth<16384&&_height<16384&&_imageRect.size.width>0&&_imageRect.size.height>0){
NSBitmapImageRep *bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:(NSInteger)canvasWidth pixelsHigh:(NSInteger)_height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:(NSInteger)canvasWidth*4 bitsPerPixel:32]autorelease];memset(bitmap.bitmapData,0,bitmap.bytesPerRow*bitmap.pixelsHigh);[NSGraphicsContext saveGraphicsState];[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]];NSAffineTransform *flip=[NSAffineTransform transform];[flip translateXBy:0 yBy:_height];[flip scaleXBy:1 yBy:-1];[flip concat];
// Match AppKit text/image drawing to the top-down canvas CTM.
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:NSGraphicsContext.currentContext.CGContext flipped:YES]];
DYMaskParameters p;[mask[@"parameters"]getBytes:&p length:sizeof(p)];p.imageAspect=_imageRect.size.width/_imageRect.size.height;_outline=[[NSBezierPath bezierPath]retain];
if(p.kind==DYMaskBezier){NSData *data=mask[@"nodes"];auto *nodes=(const DYBezierNode*)data.bytes;NSUInteger count=data.length/sizeof(DYBezierNode);for(NSUInteger i=0;i<count;i++){NSPoint anchor=[self canvasPoint:nodes[i].x y:nodes[i].y parameters:p];if(i==0)[_outline moveToPoint:anchor];else{auto a=nodes[i-1],b=nodes[i];[_outline curveToPoint:anchor controlPoint1:[self canvasPoint:a.outX y:a.outY parameters:p] controlPoint2:[self canvasPoint:b.inX y:b.inY parameters:p]];}[self addHandle:anchor part:1000+i*3];for(int j=0;j<2;j++){NSPoint handle=[self canvasPoint:j?nodes[i].outX:nodes[i].inX y:j?nodes[i].outY:nodes[i].inY parameters:p];if(hypot(handle.x-anchor.x,handle.y-anchor.y)>3){NSBezierPath *line=[NSBezierPath bezierPath];[line moveToPoint:anchor];[line lineToPoint:handle];[[NSColor colorWithWhite:1 alpha:.55]setStroke];[line stroke];[self addHandle:handle part:1000+i*3+j+1];}}}
NSArray *hover=mask[@"hover"];if(count&&[mask[@"drawing"]boolValue]&&hover.count==2){NSPoint target=NSMakePoint(_imageRect.origin.x+[hover[0]doubleValue]*_imageRect.size.width,_imageRect.origin.y+[hover[1]doubleValue]*_imageRect.size.height);[_outline curveToPoint:target controlPoint1:[self canvasPoint:nodes[count-1].outX y:nodes[count-1].outY parameters:p] controlPoint2:target];}
if(count>=3&&![mask[@"drawing"]boolValue]){auto a=nodes[count-1],b=nodes[0];[_outline curveToPoint:[self canvasPoint:b.x y:b.y parameters:p] controlPoint1:[self canvasPoint:a.outX y:a.outY parameters:p] controlPoint2:[self canvasPoint:b.inX y:b.inY parameters:p]];[_outline closePath];}
}else if(p.kind<2){int count=p.kind==DYMaskEllipse?96:4;for(int i=0;i<count;i++){float angle=i*(2.f*M_PI/count),x=p.kind==DYMaskEllipse?.5f*cosf(angle):((float[]){-.5,.5,.5,-.5})[i],y=p.kind==DYMaskEllipse?.5f*sinf(angle):((float[]){-.5,-.5,.5,.5})[i];NSPoint point=[self canvasPoint:x y:y parameters:p];if(i==0)[_outline moveToPoint:point];else[_outline lineToPoint:point];}[_outline closePath];}
else if(p.kind==DYMaskLinearGradient){[_outline moveToPoint:[self canvasPoint:0 y:-2 parameters:p]];[_outline lineToPoint:[self canvasPoint:0 y:2 parameters:p]];}
if([mask[@"coverage"]boolValue]&&p.kind<3){[[NSColor colorWithCalibratedRed:1 green:.7 blue:.05 alpha:.2]setFill];[_outline fill];}
[[NSColor colorWithWhite:0 alpha:.8]setStroke];_outline.lineWidth=3.5;[_outline stroke];[[NSColor colorWithCalibratedRed:1 green:.8 blue:.15 alpha:1]setStroke];_outline.lineWidth=1.5;[_outline stroke];
if(p.kind<4){[self addHandle:[self canvasPoint:0 y:0 parameters:p] part:1];if(p.kind!=DYMaskBezier){for(int i=0;i<4;i++)[self addHandle:[self canvasPoint:((float[]){-.5,.5,.5,-.5})[i] y:((float[]){-.5,-.5,.5,.5})[i] parameters:p] part:2+i];}[self addHandle:[self canvasPoint:0 y:-.68 parameters:p] part:6];}
for(NSDictionary *handle in _handles){NSPoint point=[handle[@"point"]pointValue];NSRect rect=NSMakeRect(point.x-4,point.y-4,8,8);[[NSColor colorWithWhite:.1 alpha:1]setFill];[[NSBezierPath bezierPathWithOvalInRect:rect]fill];[NSColor.whiteColor setStroke];[[NSBezierPath bezierPathWithOvalInRect:rect]stroke];}
NSArray *symbols=@[@"cursorarrow",@"point.topleft.down.to.point.bottomright.curvepath",@"rectangle",@"circle",@"line.diagonal",@"eyedropper",@"circle.lefthalf.filled",@"eye",@"xmark"];
CGFloat toolbarX=MAX(8,_imageRect.origin.x+12),toolbarY=MAX(8,_imageRect.origin.y+12);for(NSInteger i=0;i<symbols.count;i++){NSRect cell=NSMakeRect(toolbarX,toolbarY+i*39,32,34);[[NSColor colorWithWhite:.12 alpha:.9]setFill];[[NSBezierPath bezierPathWithRoundedRect:cell xRadius:5 yRadius:5]fill];NSImage *icon=[NSImage imageWithSystemSymbolName:symbols[i] accessibilityDescription:nil];icon=[icon imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithPaletteColors:@[NSColor.whiteColor]]];[icon drawInRect:NSInsetRect(cell,7,7) fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1 respectFlipped:YES hints:nil];}
[[NSColor colorWithWhite:0 alpha:.8]setStroke];_outline.lineWidth=3.5*_uiScale;[_outline stroke];[[NSColor colorWithCalibratedRed:1 green:.8 blue:.15 alpha:1]setStroke];_outline.lineWidth=1.5*_uiScale;[_outline stroke];
if(p.kind<4&&![mask[@"drawing"]boolValue]){[self addHandle:[self canvasPoint:0 y:0 parameters:p] part:1];if(p.kind!=DYMaskBezier){for(int i=0;i<4;i++)[self addHandle:[self canvasPoint:((float[]){-.5,.5,.5,-.5})[i] y:((float[]){-.5,-.5,.5,.5})[i] parameters:p] part:2+i];}[self addHandle:[self canvasPoint:0 y:-.68 parameters:p] part:6];}
for(NSDictionary *handle in _handles){NSPoint point=[handle[@"point"]pointValue];NSRect rect=NSMakeRect(point.x-4*_uiScale,point.y-4*_uiScale,8*_uiScale,8*_uiScale);[[NSColor colorWithWhite:.1 alpha:1]setFill];[[NSBezierPath bezierPathWithOvalInRect:rect]fill];[NSColor.whiteColor setStroke];[[NSBezierPath bezierPathWithOvalInRect:rect]stroke];}
NSArray *symbols=@[@"cursorarrow",@"point.topleft.down.to.point.bottomright.curvepath",@"rectangle",@"circle",@"line.diagonal",@"eyedropper",@"circle.lefthalf.filled",@"eye",@"xmark",@"checkmark",@"xmark.circle"];
NSInteger buttonCount=[mask[@"drawing"]boolValue]?11:9;
for(NSInteger i=0;i<buttonCount;i++){NSRect cell=[self toolbarRectForItem:i];BOOL active=(i==1&&[mask[@"drawing"]boolValue])||(i==0&&![mask[@"drawing"]boolValue]);[[NSColor colorWithCalibratedRed:active?.08:.12 green:active?.34:.12 blue:active?.58:.12 alpha:.94]setFill];[[NSBezierPath bezierPathWithRoundedRect:cell xRadius:5*_uiScale yRadius:5*_uiScale]fill];NSImage *icon=[NSImage imageWithSystemSymbolName:symbols[i] accessibilityDescription:nil];icon=[icon imageWithSymbolConfiguration:[NSImageSymbolConfiguration configurationWithPaletteColors:@[NSColor.whiteColor]]];[icon drawInRect:NSInsetRect(cell,7*_uiScale,7*_uiScale) fromRect:NSZeroRect operation:NSCompositingOperationSourceOver fraction:1 respectFlipped:YES hints:nil];}
if([mask[@"drawing"]boolValue]){NSRect hint=NSMakeRect(MAX(12*_uiScale,_imageRect.origin.x+12*_uiScale),MIN(_height-36*_uiScale,NSMaxY(_imageRect)-36*_uiScale),MIN(460*_uiScale,canvasWidth-24*_uiScale),28*_uiScale);[[NSColor colorWithWhite:.08 alpha:.9]setFill];[[NSBezierPath bezierPathWithRoundedRect:hint xRadius:5*_uiScale yRadius:5*_uiScale]fill];[@"钢笔:点击放点,拖出曲柄;点首节点或 ✓ 闭合" drawInRect:NSInsetRect(hint,7*_uiScale,5*_uiScale) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:12*_uiScale],NSForegroundColorAttributeName:NSColor.whiteColor}];}
[NSGraphicsContext restoreGraphicsState];CIImage *overlay=[CIImage imageWithCGImage:bitmap.CGImage options:@{kCIImageColorSpace:NSNull.null}];overlay=[overlay imageByApplyingTransform:CGAffineTransformMakeTranslation(0,texture.height-_height)];[_context render:overlay toMTLTexture:texture commandBuffer:commands bounds:CGRectMake(0,0,texture.width,texture.height) colorSpace:nil];
}[commands commit];[commands waitUntilCompleted];
}}
}}}
- (NSInteger)partAtPoint:(NSPoint)point {
if(!_mask)return 0;CGFloat x=MAX(8,_imageRect.origin.x+12),y=MAX(8,_imageRect.origin.y+12);for(int i=0;i<9;i++)if(NSPointInRect(point,NSMakeRect(x,y+i*39,32,34)))return 10000+i;
for(NSDictionary *h in _handles){NSPoint p=[h[@"point"]pointValue];if(hypot(p.x-point.x,p.y-point.y)<=9)return [h[@"part"]integerValue];}
DYMaskParameters p;[_mask[@"parameters"]getBytes:&p length:sizeof(p)];if([_mask[@"drawing"]boolValue]||p.kind==DYMaskBezier||p.kind==DYMaskLinearGradient||[_outline containsPoint:point])return 1;return 0;
if(!_mask)return 0;BOOL drawing=[_mask[@"drawing"]boolValue];for(NSInteger i=0;i<(drawing?11:9);i++)if(NSPointInRect(point,[self toolbarRectForItem:i]))return 10000+i;
DYMaskParameters p;[_mask[@"parameters"]getBytes:&p length:sizeof(p)];p.imageAspect=_imageRect.size.width/MAX(1.,_imageRect.size.height);
if(drawing){NSData *data=_mask[@"nodes"];if(data.length>=3*sizeof(DYBezierNode)){const DYBezierNode *nodes=(const DYBezierNode*)data.bytes;NSPoint first=[self canvasPoint:nodes[0].x y:nodes[0].y parameters:p];if(hypot(point.x-first.x,point.y-first.y)<=10*_uiScale)return 1000;}return NSPointInRect(point,_imageRect)?1:0;}
for(NSDictionary *h in _handles){NSPoint q=[h[@"point"]pointValue];if(hypot(q.x-point.x,q.y-point.y)<=9*_uiScale)return [h[@"part"]integerValue];}
if(p.kind==DYMaskBezier||p.kind==DYMaskLinearGradient||[_outline containsPoint:point])return 1;return 0;
}
- (void)hitTestOSCAtMousePositionX:(double)x mousePositionY:(double)y activePart:(NSInteger*)part atTime:(CMTime)time{NSInteger hit=[self partAtPoint:NSMakePoint(x,_height-y)];if(part)*part=hit;if(_hitDiagnostics++<16)os_log(OS_LOG_DEFAULT,"dayu_tool_osc_hit x=%{public}.2f y=%{public}.2f height=%{public}.2f rect=%{public}.2f,%{public}.2f,%{public}.2f,%{public}.2f mask=%{public}d hit=%{public}ld",x,y,_height,_imageRect.origin.x,_imageRect.origin.y,_imageRect.size.width,_imageRect.size.height,_mask!=nil,(long)hit);}
- (BOOL)event:(NSEventType)type x:(double)x y:(double)y part:(NSInteger)part modifiers:(FxModifierKeys)modifiers key:(unichar)key time:(CMTime)time {
- (void)hitTestOSCAtMousePositionX:(double)x mousePositionY:(double)y activePart:(NSInteger*)part atTime:(CMTime)time{@synchronized(self){NSDictionary *fresh=[[self pluginAtTime:time]toolCanvasMaskAtTime:time];[_mask release];_mask=[fresh copy];NSInteger hit=[self partAtPoint:NSMakePoint(x,_height-y)];if(part)*part=hit;if(_hitDiagnostics++<16)os_log(OS_LOG_DEFAULT,"dayu_tool_osc_hit x=%{public}.2f y=%{public}.2f height=%{public}.2f rect=%{public}.2f,%{public}.2f,%{public}.2f,%{public}.2f mask=%{public}d hit=%{public}ld",x,y,_height,_imageRect.origin.x,_imageRect.origin.y,_imageRect.size.width,_imageRect.size.height,_mask!=nil,(long)hit);}}
- (BOOL)event:(NSEventType)type x:(double)x y:(double)y part:(NSInteger)part modifiers:(FxModifierKeys)modifiers key:(unichar)key time:(CMTime)time {@synchronized(self){
DYPlugIn *plugin=[self pluginAtTime:time];if(_eventDiagnostics++<12)os_log(OS_LOG_DEFAULT,"dayu_tool_osc_event type=%{public}ld part=%{public}ld x=%{public}.2f y=%{public}.2f plugin=%{public}d",(long)type,(long)part,x,y,plugin!=nil);if(!plugin||![plugin toolCanvasVisible]||_imageRect.size.width<=0||_imageRect.size.height<=0)return NO;NSPoint point=NSMakePoint((x-_imageRect.origin.x)/_imageRect.size.width,(_height-y-_imageRect.origin.y)/_imageRect.size.height);[plugin toolCanvasEvent:type point:point part:part modifiers:modifiers key:key time:time];return YES;
}
}}
- (void)mouseDownAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{if(update)*update=[self event:NSEventTypeLeftMouseDown x:x y:y part:part modifiers:m key:0 time:t];}
- (void)mouseDraggedAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{if(update)*update=[self event:NSEventTypeLeftMouseDragged x:x y:y part:part modifiers:m key:0 time:t];}
- (void)mouseUpAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{if(update)*update=[self event:NSEventTypeLeftMouseUp x:x y:y part:part modifiers:m key:0 time:t];}
- (void)keyDownAtPositionX:(double)x positionY:(double)y keyPressed:(unsigned short)key modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update didHandle:(BOOL*)handled atTime:(CMTime)t{BOOL result=(key==27||key==13||key==10)&&[self event:NSEventTypeKeyDown x:x y:y part:1 modifiers:m key:key time:t];if(update)*update=result;if(handled)*handled=result;}
- (void)mouseMovedAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{[[_apiManager apiForProtocol:@protocol(FxOnScreenControlAPI_v4)]setCursor:part?NSCursor.crosshairCursor:NSCursor.arrowCursor];if(update)*update=NO;}
- (void)keyDownAtPositionX:(double)x positionY:(double)y keyPressed:(unsigned short)key modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update didHandle:(BOOL*)handled atTime:(CMTime)t{BOOL result=(key==27||key==13||key==10||key==3||key==8||key==127)&&[self event:NSEventTypeKeyDown x:x y:y part:1 modifiers:m key:key time:t];if(update)*update=result;if(handled)*handled=result;}
- (void)mouseMovedAtPositionX:(double)x positionY:(double)y activePart:(NSInteger)part modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{NSDictionary *mask=[[self pluginAtTime:t]toolCanvasMaskAtTime:t];BOOL drawing=[mask[@"drawing"]boolValue];NSCursor *cursor=part>=10000?NSCursor.pointingHandCursor:(drawing||part>=1000)?NSCursor.crosshairCursor:part?NSCursor.openHandCursor:NSCursor.arrowCursor;[[_apiManager apiForProtocol:@protocol(FxOnScreenControlAPI_v4)]setCursor:cursor];if(drawing)[self event:NSEventTypeMouseMoved x:x y:y part:part modifiers:m key:0 time:t];if(update)*update=drawing;}
- (void)mouseEnteredAtPositionX:(double)x positionY:(double)y modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{if(update)*update=NO;}
- (void)mouseExitedAtPositionX:(double)x positionY:(double)y modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update atTime:(CMTime)t{if(update)*update=NO;}
- (void)keyUpAtPositionX:(double)x positionY:(double)y keyPressed:(unsigned short)key modifiers:(FxModifierKeys)m forceUpdate:(BOOL*)update didHandle:(BOOL*)handled atTime:(CMTime)t{if(update)*update=NO;if(handled)*handled=NO;}
@@ -0,0 +1,31 @@
// Exercises the inspector entry, real native OSC events and persisted path data.
{
DYDiagnosticManager *base=[[[DYDiagnosticManager alloc]init]autorelease];DYCreateParameters(base,&error);DYToolCanvasProbe *host=[[[DYToolCanvasProbe alloc]init]autorelease];host->_base=base;host->_time=kCMTimeZero;
NSMutableDictionary *doc=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);NSDictionary *other=DYNewMask(DYMaskEllipse);doc[@"baseMasks"][@"hsl"]=[NSMutableArray arrayWithObject:other];DYWriteTools(base,doc,kCMTimeZero);
id<DYToolCanvasHostProbe>plugin=(id)[[NSClassFromString(@"DYPlugIn")alloc]initWithAPIManager:host];[plugin scheduleToolCanvasRegistration];NSData *state=nil;[plugin pluginState:&state atTime:kCMTimeZero quality:(FxQuality)0 error:&error];
auto drain=[](){double end=NSProcessInfo.processInfo.systemUptime+.1;while(NSProcessInfo.processInfo.systemUptime<end)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.005]];};drain();
id panel=[[[NSClassFromString(@"DYToolMaskPanel")alloc]initWithManager:host nodeID:@"base:hsl"]autorelease];[panel refreshWithDocument:DYReadTools(base,kCMTimeZero).document time:kCMTimeZero];NSMenuItem *item=[[[NSMenuItem alloc]initWithTitle:@"钢笔" action:nil keyEquivalent:@""]autorelease];item.tag=2;[panel performSelector:@selector(addKind:) withObject:item];
NSDictionary *author=DYReadTools(base,kCMTimeZero).document,*mask=[author[@"baseMasks"][@"hsl"]lastObject];NSString *maskID=mask[@"id"];NSDictionary *snapshot=[plugin toolCanvasMaskAtTime:kCMTimeZero];
run.record(@"inspector-add-pen-enters-empty-drawing-mode",[snapshot[@"drawing"]boolValue]&&[snapshot[@"nodes"]length]==0&&[snapshot[@"id"]isEqual:maskID]);
id<FxOnScreenControl_v4>osc=(id)[[NSClassFromString(@"DYToolOSC")alloc]initWithAPIManager:host];DYDiagnosticTile *overlay=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:640 height:400]autorelease];[osc drawOSCWithWidth:640 height:400 activePart:0 destinationImage:overlay atTime:kCMTimeZero];
NSInteger part=0;[osc hitTestOSCAtMousePositionX:152 mousePositionY:307 activePart:&part atTime:kCMTimeZero];run.record(@"pen-can-start-anywhere-in-image-outside-default-shape",part==1);
int undo=base->_undoStarts;BOOL update=NO;
auto click=[&](double x,double y){[osc mouseDownAtPositionX:x positionY:y activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];[osc mouseUpAtPositionX:x positionY:y activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];};
click(152,307);snapshot=[plugin toolCanvasMaskAtTime:kCMTimeZero];run.record(@"pen-point-snapshot-updates-before-main-queue-without-author-write",[snapshot[@"nodes"]length]==sizeof(DYBezierNode)&&base->_undoStarts==undo&&[DYReadTools(base,kCMTimeZero).document isEqual:author]);
[osc mouseMovedAtPositionX:240 positionY:280 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];snapshot=[plugin toolCanvasMaskAtTime:kCMTimeZero];run.record(@"pen-cursor-previews-next-segment-without-parameter-or-undo-writes",update&&[snapshot[@"hover"]count]==2&&base->_undoStarts==undo&&[DYReadTools(base,kCMTimeZero).document isEqual:author]);
[osc mouseDownAtPositionX:488 positionY:307 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];[osc mouseDraggedAtPositionX:509 positionY:290 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];[osc mouseUpAtPositionX:509 positionY:290 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];click(320,118);
snapshot=[plugin toolCanvasMaskAtTime:kCMTimeZero];NSData *nodes=snapshot[@"nodes"];const DYBezierNode *v=(const DYBezierNode*)nodes.bytes;BOOL handles=nodes.length==3*sizeof(DYBezierNode)&&fabs(v[1].inX+v[1].outX-2*v[1].x)<1e-5&&fabs(v[1].inY+v[1].outY-2*v[1].y)<1e-5&&fabs(v[1].outX-v[1].x)>.01;run.record(@"pen-drag-creates-mirrored-cubic-handles",handles);
[osc drawOSCWithWidth:640 height:400 activePart:0 destinationImage:overlay atTime:kCMTimeZero];[osc hitTestOSCAtMousePositionX:152 mousePositionY:307 activePart:&part atTime:kCMTimeZero];run.record(@"pen-first-anchor-hit-closes-path-after-three-points",part==1000);[osc mouseDownAtPositionX:152 positionY:307 activePart:part modifiers:0 forceUpdate:&update atTime:kCMTimeZero];drain();
author=DYReadTools(base,kCMTimeZero).document;mask=[author[@"baseMasks"][@"hsl"]lastObject];run.record(@"pen-closed-cubic-path-persists-once-and-keeps-neighbor-mask",[mask[@"nodes"]length]==3*sizeof(DYBezierNode)&&base->_undoStarts==undo+1&&[author[@"baseMasks"][@"hsl"][0]isEqual:other]&&![[plugin toolCanvasMaskAtTime:kCMTimeZero][@"drawing"]boolValue]);
NSData *archive=[NSKeyedArchiver archivedDataWithRootObject:DYReadTools(base,kCMTimeZero) requiringSecureCoding:YES error:&error];DYToolDocument *restored=[NSKeyedUnarchiver unarchivedObjectOfClass:DYToolDocument.class fromData:archive error:&error];run.record(@"pen-cubic-nodes-survive-secure-document-roundtrip",[restored.document isEqual:author]);
auto redraw=[&](){[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:host userInfo:@{@"node":@"base:hsl",@"mask":maskID,@"document":DYReadTools(base,kCMTimeZero).document,@"draw":@YES}];};
redraw();click(180,280);click(420,280);BOOL handled=NO;[osc keyDownAtPositionX:420 positionY:280 keyPressed:127 modifiers:0 forceUpdate:&update didHandle:&handled atTime:kCMTimeZero];run.record(@"pen-delete-removes-last-uncommitted-point",handled&&[[plugin toolCanvasMaskAtTime:kCMTimeZero][@"nodes"]length]==sizeof(DYBezierNode));
[osc keyDownAtPositionX:180 positionY:280 keyPressed:27 modifiers:0 forceUpdate:&update didHandle:&handled atTime:kCMTimeZero];drain();run.record(@"pen-escape-cancels-without-overwriting-saved-curve",[DYReadTools(base,kCMTimeZero).document isEqual:author]&&base->_undoStarts==undo+1);
redraw();click(180,280);click(450,260);click(330,145);[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasCommand" object:host userInfo:@{@"node":@"base:hsl",@"mask":maskID,@"command":@"finish",@"timeValue":@0,@"timeScale":@1,@"timeEpoch":@0}];drain();NSDictionary *buttonSaved=DYReadTools(base,kCMTimeZero).document;run.record(@"pen-inspector-finish-commits-without-viewer-keyboard-focus",![buttonSaved isEqual:author]&&base->_undoStarts==undo+2&&[[buttonSaved[@"baseMasks"][@"hsl"]lastObject][@"nodes"]length]==3*sizeof(DYBezierNode));
redraw();click(160,270);[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasCommand" object:host userInfo:@{@"node":@"base:hsl",@"mask":maskID,@"command":@"cancel",@"timeValue":@0,@"timeScale":@1,@"timeEpoch":@0}];drain();run.record(@"pen-inspector-cancel-preserves-saved-curve-and-undo-count",[DYReadTools(base,kCMTimeZero).document isEqual:buttonSaved]&&base->_undoStarts==undo+2);
redraw();click(190,280);click(460,280);click(300,150);[osc keyDownAtPositionX:300 positionY:150 keyPressed:13 modifiers:0 forceUpdate:&update didHandle:&handled atTime:kCMTimeZero];drain();run.record(@"pen-return-closes-and-saves-native-path",handled&&base->_undoStarts==undo+3&&![[plugin toolCanvasMaskAtTime:kCMTimeZero][@"drawing"]boolValue]);
// Finish and the next drag can arrive before the main queue gets a turn.
redraw();click(170,275);click(445,275);click(300,140);int queuedUndo=base->_undoStarts;[osc keyDownAtPositionX:300 positionY:140 keyPressed:13 modifiers:0 forceUpdate:&update didHandle:&handled atTime:kCMTimeZero];[osc mouseDownAtPositionX:320 positionY:212.5 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];[osc mouseDraggedAtPositionX:348 positionY:196.75 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];[osc mouseUpAtPositionX:348 positionY:196.75 activePart:1 modifiers:0 forceUpdate:&update atTime:kCMTimeZero];drain();NSDictionary *queuedDoc=DYReadTools(base,kCMTimeZero).document;DYMaskParameters moved=DYMaskAtTime([queuedDoc[@"baseMasks"][@"hsl"]lastObject],kCMTimeZero);run.record(@"pen-finish-and-next-gesture-serialize-without-dropping-either",base->_undoStarts==queuedUndo+2&&fabs(moved.centerX-.55)<1e-5&&fabs(moved.centerY-.55)<1e-5);
redraw();click(170,275);click(445,275);click(300,140);[osc keyDownAtPositionX:300 positionY:140 keyPressed:13 modifiers:0 forceUpdate:&update didHandle:&handled atTime:CMTimeMake(1,25)];drain();run.record(@"pen-refuses-to-finish-stale-draft-after-playhead-moves",[DYReadTools(base,kCMTimeZero).document isEqual:queuedDoc]&&base->_undoStarts==queuedUndo+2&&![[plugin toolCanvasMaskAtTime:CMTimeMake(1,25)][@"drawing"]boolValue]);
[osc release];[plugin release];
}
+66 -12
查看文件
@@ -21,23 +21,77 @@
float w=b.width,h=b.height;DYVertex2D v[]={{{w/2,-h/2},{r,bottom}},{{-w/2,-h/2},{l,bottom}},{{w/2,h/2},{r,top}},{{-w/2,h/2},{l,top}}};if(dest.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)for(auto &vertex:v)vertex.position.y=-vertex.position.y;
vector_uint2 size={(unsigned)b.width,(unsigned)b.height};id<MTLCommandBuffer>cb=[e[@"queue"]commandBuffer];MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor];pass.colorAttachments[0].texture=b;pass.colorAttachments[0].loadAction=MTLLoadActionDontCare;pass.colorAttachments[0].storeAction=MTLStoreActionStore;id<MTLRenderCommandEncoder>encoder=[cb renderCommandEncoderWithDescriptor:pass];[encoder setRenderPipelineState:pipeline];[encoder setVertexBytes:v length:sizeof(v) atIndex:0];[encoder setVertexBytes:&size length:sizeof(size) atIndex:1];[encoder setFragmentTexture:a atIndex:0];[encoder drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];[encoder endEncoding];[cb commit];[cb waitUntilCompleted];return cb.status==MTLCommandBufferStatusCompleted?YES:fail(error,cb.error.localizedDescription);
}
// Extra skin keeps the source reference used by the prior release. All other
// extra tools reuse the same isolated native tool path and their own mask group.
- (BOOL)renderExtraTool:(NSDictionary*)node source:(FxImageTile*)source original:(FxImageTile*)original destination:(FxImageTile*)destination entry:(NSMutableDictionary*)entry error:(NSError**)error {
// Prove a constant-zero aggregate conservatively. In particular a first
// subtract mask of strength zero is full coverage, not an empty selection.
// Skipping only this isolated operation preserves HDR/negative pixels that
// the legacy grading entry would otherwise clip even at zero stage coverage.
BOOL found=NO;float low=1,high=1;for(NSDictionary *mask in node[@"masks"]){if(![mask[@"enabled"]boolValue])continue;DYMaskParameters p=DYMaskAtTime(mask,kCMTimeInvalid);float a=0,b=p.strength==0?0:1;NSInteger combine=[mask[@"combine"]integerValue];if(!found){low=combine==1?1-b:a;high=combine==1?1-a:b;found=YES;}else if(combine==1){low*=1-b;high*=1-a;}else if(combine==2){low*=a;high*=b;}else{low=1-(1-low)*(1-a);high=1-(1-high)*(1-b);}}
if(found&&high==0)return [self copyTile:source to:destination entry:entry error:error];
DYUniforms layer=DYToolUniforms(node);NSString *type=node[@"type"];
if(![type isEqual:@"skin"])return [self renderLegacy:source destination:destination uniforms:layer paths:node[@"paths"] spider:node[@"spider"] masks:@{type:node[@"masks"]} error:error];
id<MTLDevice>d=entry[@"device"];id<MTLTexture>before=[source metalTextureForDevice:d],input=[original metalTextureForDevice:d],after=[destination metalTextureForDevice:d];
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyToolSkin"]];[ce setTexture:before atIndex:0];[ce setTexture:input atIndex:1];[ce setTexture:after atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(after.width,after.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);
if(![node[@"masks"]count])return YES;
MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:after.width height:after.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;id<MTLTexture>blend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配新增工具蒙版缓冲区");
DYToolMaskHeader h{};h.section=3;id<MTLBuffer>buffer=[self maskBuffer:@{type:node[@"masks"]} tile:source device:d header:&h];cb=[entry[@"queue"]commandBuffer];[self encodeBlend:before after:after output:blend masks:buffer header:h entry:entry commands:cb];[cb commit];[cb waitUntilCompleted];BOOL ok=cb.status==MTLCommandBufferStatusCompleted;
DYExportTile *blended=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[blended setBounds:source.tilePixelBounds origin:source.imageOrigin];[blended setPixelAspect:source.pixelAspect];[blend release];if(ok)ok=[self copyTile:blended to:destination entry:entry error:error];else fail(error,cb.error.localizedDescription);[blended release];return ok;
}
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){@autoreleasepool{
if(!tools)return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:@{} error:error];if(!DYValidToolDocument(tools))return fail(error,@"工具或蒙版数据损坏,未更改原工程");
NSArray *layers=tools[@"layers"];BOOL active=NO;for(NSDictionary *n in layers)active|=!DYToolIsNeutral(n);
NSArray *layers=tools[@"layers"];BOOL active=NO,anchored=NO;for(NSDictionary *node in layers)if(!DYToolIsNeutral(node)){active=YES;anchored|=![DYToolRootAnchor(tools,node[@"id"])isEqual:@"tail"];}
// No active extra tool keeps the exact historical fused path, including HDR.
if(!active)return [self renderLegacy:src destination:dst uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error];
NSMutableDictionary *entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>input=[src metalTextureForDevice:d];
NSMutableDictionary *entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>input=[src metalTextureForDevice:d];if(!input)return fail(error,@"宿主图像纹理不可用");
MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:input.width height:input.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;
id<MTLTexture>current=[d newTextureWithDescriptor:desc];if(!current)return fail(error,@"无法分配工具图层缓冲区");DYExportTile *tile=[[DYExportTile alloc]initWithTexture:current registry:d.registryID];[tile setBounds:src.tilePixelBounds origin:src.imageOrigin];[tile setPixelAspect:src.pixelAspect];[current release];
DYExportTile *tile=nil,*skinReference=nil,*originalReference=nil;NSArray *order=DYToolDisplayOrder(tools);NSMutableDictionary *groups=[NSMutableDictionary dictionary];for(NSString *ID in order){NSDictionary *node=DYToolWithID(tools,ID);if(!node||DYToolIsNeutral(node))continue;NSString *root=DYToolRootAnchor(tools,ID);if(!groups[root])groups[root]=[NSMutableArray array];[groups[root]addObject:node];}
auto makeTile=[&](){id<MTLTexture>texture=[d newTextureWithDescriptor:desc];if(!texture)return (DYExportTile*)nil;DYExportTile *result=[[DYExportTile alloc]initWithTexture:texture registry:d.registryID];[result setBounds:src.tilePixelBounds origin:src.imageOrigin];[result setPixelAspect:src.pixelAspect];[texture release];return result;};
auto replace=[&](DYExportTile *next){[tile release];tile=next;};
auto apply=[&](NSString *anchor){for(NSDictionary *node in groups[anchor]){@autoreleasepool{DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配新增工具缓冲区");BOOL ok=[self renderExtraTool:node source:tile original:src destination:next entry:entry error:error];if(!ok){[next release];return NO;}replace(next);}}return YES;};
@try{
if(![self renderLegacy:src destination:tile uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error])return NO;
for(NSDictionary *node in layers){@autoreleasepool{if(DYToolIsNeutral(node))continue;DYUniforms layer=DYToolUniforms(node);NSString *type=node[@"type"];
id<MTLTexture>next=[d newTextureWithDescriptor:desc];if(!next)return fail(error,@"无法分配新增工具缓冲区");DYExportTile *nextTile=[[[DYExportTile alloc]initWithTexture:next registry:d.registryID]autorelease];[nextTile setBounds:src.tilePixelBounds origin:src.imageOrigin];[nextTile setPixelAspect:src.pixelAspect];[next release];
if([type isEqual:@"skin"]){id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];[ce setComputePipelineState:entry[@"dyToolSkin"]];[ce setTexture:[tile metalTextureForDevice:d] atIndex:0];[ce setTexture:input atIndex:1];[ce setTexture:[nextTile metalTextureForDevice:d] atIndex:2];[ce setBytes:&layer length:sizeof(layer) atIndex:0];[ce dispatchThreads:MTLSizeMake(input.width,input.height,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];[cb commit];[cb waitUntilCompleted];if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);
if([node[@"masks"]count]){id<MTLTexture>blend=[d newTextureWithDescriptor:desc];DYToolMaskHeader h{};h.section=3;id<MTLBuffer>buffer=[self maskBuffer:@{type:node[@"masks"]} tile:tile device:d header:&h];cb=[entry[@"queue"]commandBuffer];[self encodeBlend:[tile metalTextureForDevice:d] after:[nextTile metalTextureForDevice:d] output:blend masks:buffer header:h entry:entry commands:cb];[cb commit];[cb waitUntilCompleted];DYExportTile *blended=[[[DYExportTile alloc]initWithTexture:blend registry:d.registryID]autorelease];[blended setBounds:src.tilePixelBounds origin:src.imageOrigin];[blended setPixelAspect:src.pixelAspect];[blend release];nextTile=blended;if(cb.status!=MTLCommandBufferStatusCompleted)return fail(error,cb.error.localizedDescription);}
}else if(![self renderLegacy:tile destination:nextTile uniforms:layer paths:node[@"paths"] spider:node[@"spider"] masks:@{type:node[@"masks"]} error:error])return NO;
[nextTile retain];[tile release];tile=nextTile;
}}return [self copyTile:tile to:dst entry:entry error:error];
}@finally{[tile release];}
if(!anchored){DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配工具图层缓冲区");BOOL ok=[self renderLegacy:src destination:next uniforms:u paths:paths spider:spider masks:tools[@"baseMasks"] error:error];if(!ok){[next release];return NO;}replace(next);}
else {
// Preserve the actual native stage order, which predates the visual cards.
// Basic adjustment spans stages 2/8, so its insertion point is after stage 8.
// CST precedes stage 0; Spider stays after all twelve fused color stages.
NSArray *anchors=@[@"base:primary",@"base:primaries",@"",@"base:curve",@"base:levels",@"base:balance",@"base:hsl",@"base:grading",@"base:base",@"base:blackwhite",@"base:look",@"base:skin"];
float bwMix=fmaxf(0,fminf(1,u.cm.blackWhiteMix));BOOL splitBW=u.blackWhiteSectionEnabled>.5&&bwMix>0&&bwMix<1&&([groups[@"base:blackwhite"]count]||[groups[@"base:look"]count]);
NSInteger first=0;
for(NSInteger last=0;last<(splitBW?9:12);last++)if(last==5||last==(splitBW?8:11)||[groups[anchors[last]]count]){@autoreleasepool{
DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配原生工具分段缓冲区");DYUniforms segment=u;
BOOL ok=[self renderLegacy:tile?:src destination:next uniforms:segment paths:paths spider:nil masks:tools[@"baseMasks"] stageFirst:first stageLast:last skinReference:skinReference originalReference:originalReference captureOriginal:first==0?&originalReference:nullptr suppressBlackWhite:NO error:error];if(!ok){[next release];return NO;}replace(next);
if(!apply(anchors[last]))return NO;
// Skin protects the native pre-HSL result, including tools inserted before it.
if(last==5){[skinReference release];skinReference=[tile retain];}first=last+1;
}}
if(splitBW){
// Native partial B&W mixes two complete color branches after native skin,
// before Spider. Keep that fork if a B&W/Look insertion splits stages 9-11.
// Only the suffix is duplicated; CST, statistics and the prefix stay shared.
DYExportTile *prefix=[tile retain],*bwTile=nil;
@try{
for(int branch=0;branch<2;branch++){
if(branch==1)replace([prefix retain]);DYUniforms branchUniforms=u;branchUniforms.cm.blackWhiteMix=1;NSInteger begin=9;
for(NSInteger end=9;end<12;end++)if(end==11||[groups[anchors[end]]count]){@autoreleasepool{
DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配黑白混合分支缓冲区");BOOL ok=[self renderLegacy:tile destination:next uniforms:branchUniforms paths:paths spider:nil masks:tools[@"baseMasks"] stageFirst:begin stageLast:end skinReference:skinReference originalReference:originalReference captureOriginal:nullptr suppressBlackWhite:branch==1 error:error];if(!ok){[next release];return NO;}replace(next);if(end<11&&!apply(anchors[end]))return NO;begin=end+1;
}}
if(branch==0)bwTile=[tile retain];
}
DYExportTile *mixed=makeTile();if(!mixed)return fail(error,@"无法分配黑白混合缓冲区");DYToolMaskEntry constant{};constant.section=0;constant.combine=0;constant.mask.parameters=dyDefaultMaskParameters();constant.mask.parameters.kind=DYMaskRectangle;constant.mask.parameters.width=constant.mask.parameters.height=4000;constant.mask.parameters.feather=0;constant.mask.parameters.outputBlack=constant.mask.parameters.outputWhite=1;constant.mask.parameters.strength=bwMix;
id<MTLBuffer>weight=[[d newBufferWithBytes:&constant length:sizeof(constant) options:MTLResourceStorageModeShared]autorelease];if(!weight){[mixed release];return fail(error,@"无法分配黑白混合权重");}DYToolMaskHeader h{};h.count=1;h.section=0;h.premultiplied=1;h.scaleX=h.scaleY=1;id<MTLCommandBuffer>commands=[entry[@"queue"]commandBuffer];[self encodeBlend:[tile metalTextureForDevice:d] after:[bwTile metalTextureForDevice:d] output:[mixed metalTextureForDevice:d] masks:weight header:h entry:entry commands:commands];[commands commit];[commands waitUntilCompleted];if(commands.status!=MTLCommandBufferStatusCompleted){[mixed release];return fail(error,commands.error.localizedDescription);}replace(mixed);
}@finally{[prefix release];[bwTile release];}
// An extra skin tool follows the original skin and B&W mixture once.
if(!apply(@"base:skin"))return NO;
}
if(u.spiderSectionEnabled>.5&&u.spiderMix>0&&spider.length){DYUniforms sp=DYToolUniforms(@{@"type":@"spider"});sp.spiderSectionEnabled=u.spiderSectionEnabled;sp.spiderMix=u.spiderMix;DYExportTile *next=makeTile();if(!next)return fail(error,@"无法分配蜘蛛盘缓冲区");BOOL ok=[self renderLegacy:tile destination:next uniforms:sp paths:@{} spider:spider masks:@{@"spider":tools[@"baseMasks"][@"spider"]?:@[]} error:error];if(!ok){[next release];return NO;}replace(next);}
if(!apply(@"base:spider"))return NO;
}
// Schema 1 extra layers (and children inserted after those layers) retain
// their old end-of-chain order. Saving does not silently migrate old looks.
if(!apply(@"tail"))return NO;return [self copyTile:tile to:dst entry:entry error:error];
}@finally{[originalReference release];[skinReference release];[tile release];}
}}}
- (BOOL)exportLUT:(NSURL*)url uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){
for(NSArray *masks in [tools[@"baseMasks"]allValues])if(masks.count)return fail(error,@"当前调色含空间蒙版或跟踪,Cube 无法保存这些信息。请先保存完整预设,或移除蒙版后导出。");for(NSDictionary *node in tools[@"layers"])if([node[@"masks"]count])return fail(error,@"新增工具含蒙版,无法完整导出为 Cube。请保存完整预设。");
+6
查看文件
@@ -10,6 +10,12 @@ enum { DYToolsParameterID=9002, DYCanvasSessionParameterID=9003, DYToolLimit=32,
NSArray *DYToolTypes(void);
NSDictionary *DYToolSection(NSString *type);
NSDictionary *DYNewTool(NSString *type);
// New documents splice a UUID after the clicked base/extra tool. Schema 1
// layers without an anchor retain their historical end-of-chain semantics.
NSDictionary *DYInsertTool(NSMutableDictionary *document,NSString *type,NSString *afterID);
BOOL DYRemoveTool(NSMutableDictionary *document,NSString *nodeID);
NSArray *DYToolDisplayOrder(NSDictionary *document);
NSString *DYToolRootAnchor(NSDictionary *document,NSString *nodeID);
NSDictionary *DYNewMask(NSInteger kind);
BOOL DYValidToolDocument(NSDictionary *document);
BOOL DYValidToolMask(NSDictionary *mask);
+11 -2
查看文件
@@ -24,13 +24,17 @@ BOOL DYValidToolMask(NSDictionary *mask){
static BOOL validMasks(id masks,NSMutableSet *ids){if(![masks isKindOfClass:NSArray.class]||[masks count]>DYToolMaskLimit)return NO;for(NSDictionary *m in masks){if(!DYValidToolMask(m)||[ids containsObject:m[@"id"]])return NO;[ids addObject:m[@"id"]];}return YES;}
BOOL DYValidToolDocument(NSDictionary *doc){
if(![NSPropertyListSerialization propertyList:doc isValidForFormat:NSPropertyListBinaryFormat_v1_0])return NO;
if(![doc isKindOfClass:NSDictionary.class]||![doc[@"schema"]isEqual:@1]||![doc[@"layers"]isKindOfClass:NSArray.class]||[doc[@"layers"]count]>DYToolLimit||![doc[@"baseMasks"]isKindOfClass:NSDictionary.class]||[doc[@"baseMasks"]count]>DYToolTypes().count)return NO;
if(![doc isKindOfClass:NSDictionary.class]||(![doc[@"schema"]isEqual:@1]&&![doc[@"schema"]isEqual:@2])||![doc[@"layers"]isKindOfClass:NSArray.class]||[doc[@"layers"]count]>DYToolLimit||![doc[@"baseMasks"]isKindOfClass:NSDictionary.class]||[doc[@"baseMasks"]count]>DYToolTypes().count)return NO;
NSMutableSet *ids=[NSMutableSet set];for(NSString *key in doc[@"baseMasks"]){if(![DYToolTypes()containsObject:key]||!validMasks(doc[@"baseMasks"][key],ids))return NO;}
NSMutableDictionary *descriptors=[NSMutableDictionary dictionary];for(NSDictionary *d in DYDescriptors())descriptors[d[@"key"]]=d;
for(NSDictionary *node in doc[@"layers"]){if(![node isKindOfClass:NSDictionary.class]||!validID(node[@"id"])||[ids containsObject:node[@"id"]]||![DYToolTypes()containsObject:node[@"type"]]||![node[@"values"]isKindOfClass:NSDictionary.class]||[node[@"values"]count]>descriptors.count||![node[@"paths"]isKindOfClass:NSDictionary.class]||[node[@"paths"]count]>6||!validMasks(node[@"masks"],ids))return NO;[ids addObject:node[@"id"]];
for(NSString *key in node[@"values"]){NSDictionary *d=descriptors[key];id v=node[@"values"][key];if(!d||!finiteNumber(v)||[v doubleValue]<[d[@"min"]doubleValue]||[v doubleValue]>[d[@"max"]doubleValue]||(d[@"values"]&&![d[@"values"]containsObject:@((int)llround([v doubleValue]))]))return NO;}
for(id key in node[@"paths"]){id p=node[@"paths"][key];if(![@[@"input",@"look0",@"look1",@"look2",@"look3",@"look4"]containsObject:key]||![p isKindOfClass:NSString.class]||[p length]>8192||![p isAbsolutePath]||![[p pathExtension].lowercaseString isEqual:@"cube"])return NO;}if(node[@"spider"]&&(![node[@"spider"]isKindOfClass:NSData.class]||!DYSpiderMeshIsValid(node[@"spider"])))return NO;
}NSUInteger totalKeys=0;for(NSArray *masks in [doc[@"baseMasks"]allValues])for(NSDictionary *mask in masks)totalKeys+=[mask[@"keys"]count];for(NSDictionary *node in doc[@"layers"])for(NSDictionary *mask in node[@"masks"])totalKeys+=[mask[@"keys"]count];if(totalKeys>65536)return NO;NSData *bounded=[NSPropertyListSerialization dataWithPropertyList:doc format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];return bounded&&bounded.length<=24*1024*1024;
}
// Anchors are stable identities, never an array index or a translated title.
// Reject unknown anchors/cycles so layout, rendering and undo share one order.
for(NSDictionary *node in doc[@"layers"]){id after=node[@"after"];if(!after)continue;if(![doc[@"schema"]isEqual:@2]||![after isKindOfClass:NSString.class])return NO;NSMutableSet *seen=[NSMutableSet setWithObject:node[@"id"]];while(after){if([after hasPrefix:@"base:"]){if(![DYToolTypes()containsObject:[after substringFromIndex:5]])return NO;break;}if([seen containsObject:after])return NO;[seen addObject:after];NSDictionary *parent=DYToolWithID(doc,after);if(!parent)return NO;after=parent[@"after"];}}
NSUInteger totalKeys=0;for(NSArray *masks in [doc[@"baseMasks"]allValues])for(NSDictionary *mask in masks)totalKeys+=[mask[@"keys"]count];for(NSDictionary *node in doc[@"layers"])for(NSDictionary *mask in node[@"masks"])totalKeys+=[mask[@"keys"]count];if(totalKeys>65536)return NO;NSData *bounded=[NSPropertyListSerialization dataWithPropertyList:doc format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil];return bounded&&bounded.length<=24*1024*1024;
}
@implementation DYToolDocument
+ (BOOL)supportsSecureCoding{return YES;}
@@ -47,6 +51,11 @@ BOOL DYValidToolDocument(NSDictionary *doc){
DYToolDocument *DYReadTools(id<PROAPIAccessing>m,CMTime t){DYToolDocument *d=nil;[[(id)m apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getCustomParameterValue:&d fromParameter:DYToolsParameterID atTime:t];return [d isKindOfClass:DYToolDocument.class]?d:[[[DYToolDocument alloc]init]autorelease];}
BOOL DYWriteTools(id<PROAPIAccessing>m,NSDictionary *d,CMTime t){if(!DYValidToolDocument(d))return NO;DYToolDocument *v=[[[DYToolDocument alloc]init]autorelease];v.document=d;return [[m apiForProtocol:@protocol(FxParameterSettingAPI_v6)]setCustomParameterValue:v toParameter:DYToolsParameterID atTime:t];}
NSDictionary *DYToolWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *n in doc[@"layers"])if([n[@"id"]isEqual:ID])return n;return nil;}
static void DYAppendToolChildren(NSDictionary *doc,NSString *parent,NSMutableArray *order,NSMutableSet *seen){for(NSDictionary *node in doc[@"layers"])if([node[@"after"]isEqual:parent]&&![seen containsObject:node[@"id"]]){[seen addObject:node[@"id"]];[order addObject:node[@"id"]];DYAppendToolChildren(doc,node[@"id"],order,seen);}}
NSArray *DYToolDisplayOrder(NSDictionary *doc){NSMutableArray *order=[NSMutableArray array];NSMutableSet *seen=[NSMutableSet set];for(NSString *type in DYToolTypes()){NSString *base=[@"base:" stringByAppendingString:type];[order addObject:base];DYAppendToolChildren(doc,base,order,seen);}for(NSDictionary *node in doc[@"layers"])if(!node[@"after"]&&![seen containsObject:node[@"id"]]){[seen addObject:node[@"id"]];[order addObject:node[@"id"]];DYAppendToolChildren(doc,node[@"id"],order,seen);}return order;}
NSString *DYToolRootAnchor(NSDictionary *doc,NSString *ID){NSMutableSet *seen=[NSMutableSet set];NSDictionary *node=DYToolWithID(doc,ID);while(node[@"after"]){NSString *after=node[@"after"];if([after hasPrefix:@"base:"])return after;if([seen containsObject:after])return nil;[seen addObject:after];node=DYToolWithID(doc,after);}return @"tail";}
NSDictionary *DYInsertTool(NSMutableDictionary *doc,NSString *type,NSString *after){if(!DYValidToolDocument(doc)||[doc[@"layers"]count]>=DYToolLimit)return nil;if(!([after hasPrefix:@"base:"]&&[DYToolTypes()containsObject:[after substringFromIndex:5]])&&!DYToolWithID(doc,after))return nil;NSDictionary *fresh=DYNewTool(type);if(!fresh)return nil;NSMutableDictionary *node=DYMutablePlist(fresh);node[@"after"]=after;NSMutableArray *layers=doc[@"layers"];for(NSMutableDictionary *old in layers)if([old[@"after"]isEqual:after])old[@"after"]=node[@"id"];NSUInteger index=0;NSDictionary *parent=DYToolWithID(doc,after);if(parent)index=[layers indexOfObjectIdenticalTo:parent]+1;[layers insertObject:node atIndex:MIN(index,layers.count)];doc[@"schema"]=@2;return node;}
BOOL DYRemoveTool(NSMutableDictionary *doc,NSString *ID){NSMutableDictionary *node=(id)DYToolWithID(doc,ID);if(!node)return NO;NSString *after=node[@"after"];for(NSMutableDictionary *child in doc[@"layers"])if([child[@"after"]isEqual:ID]){if(after)child[@"after"]=after;else[child removeObjectForKey:@"after"];}[doc[@"layers"]removeObject:node];return YES;}
NSArray *DYMasksForTool(NSDictionary *doc,NSString *ID){return [ID hasPrefix:@"base:"]?doc[@"baseMasks"][[ID substringFromIndex:5]]?:@[]:DYToolWithID(doc,ID)[@"masks"]?:@[];}
BOOL DYSetToolMasks(NSMutableDictionary *doc,NSString *ID,NSArray *masks){if([ID hasPrefix:@"base:"]){NSString *type=[ID substringFromIndex:5];if(![DYToolTypes()containsObject:type])return NO;doc[@"baseMasks"][type]=masks;}else{NSMutableDictionary *n=(id)DYToolWithID(doc,ID);if(!n)return NO;n[@"masks"]=masks;}return YES;}
DYMaskParameters DYMaskAtTime(NSDictionary *mask,CMTime time){DYMaskParameters p=dyDefaultMaskParameters();readParameters(mask[@"parameters"],&p);NSArray *keys=mask[@"keys"];if(!keys.count||!CMTIME_IS_NUMERIC(time))return p;if(keyTime(keys[0]).epoch!=time.epoch)return p;NSUInteger low=0,high=keys.count;while(low<high){NSUInteger mid=low+(high-low)/2;if(CMTimeCompare(keyTime(keys[mid]),time)<0)low=mid+1;else high=mid;}NSDictionary *left=keys[low?low-1:0],*right=keys[MIN(low,keys.count-1)];DYMaskParameters a,b;readParameters(left[@"parameters"],&a);readParameters(right[@"parameters"],&b);double duration=CMTimeGetSeconds(CMTimeSubtract(keyTime(right),keyTime(left)));float w=duration>0?fmax(0,fmin(1,CMTimeGetSeconds(CMTimeSubtract(time,keyTime(left)))/duration)):0;
@@ -27,6 +27,8 @@
@interface DYToolCanvasProbe : DYToolTrackingProbe @end
@implementation DYToolCanvasProbe
- (double)backingScaleFactor{return 1;}
- (void)setCursor:(NSCursor*)cursor{}
- (id)apiForProtocol:(Protocol*)p{if([NSStringFromProtocol(p)isEqual:@"FxOnScreenControlAPI_v4"])return self;return [super apiForProtocol:p];}
- (BOOL)convertPointFromSpace:(FxDrawingCoordinates)from fromX:(double)x fromY:(double)y toSpace:(FxDrawingCoordinates)to toX:(double*)outX toY:(double*)outY{if(outX)*outX=40+x*560;if(outY)*outY=55+y*315;return YES;}
@end
+13 -13
查看文件
@@ -7,12 +7,12 @@ kernel void dyTrackPyramid(device float*f[[buffer(0)]],constant PyramidInfo&i[[b
for(int y=-1;y<=1;y++)for(int x=-1;x<=1;x++)sum+=f[i.offset[level-1]+clamp(int(p.y)*2+y,0,sh-1)*sw+clamp(int(p.x)*2+x,0,sw-1)]*(x==0?2.f:1.f)*(y==0?2.f:1.f);
f[i.offset[level]+p.y*w+p.x]=sum/16.f;
}
inline bool inside(float2 p,int w,int h){return all(p>=6.f)&&p.x<w-7&&p.y<h-7;}
inline bool inside(float2 p,int w,int h){return all(p>=12.f)&&p.x<w-13&&p.y<h-13;}
inline float pixel(device const float*f,int w,float2 p) {
int2 a=int2(p);float2 d=p-float2(a);int idx=a.y*w+a.x;
return mix(mix(f[idx],f[idx+1],d.x),mix(f[idx+w],f[idx+w+1],d.x),d.y);
}
// One SIMD group per feature: lanes cooperatively reduce the 9x9 patch.
// One SIMD group per feature: lanes cooperatively reduce the 21x21 patch.
// Forward and backward checks stay in the same dispatch and reuse the resident pyramids.
bool trackFlow(device const float*prev,device const float*next,constant PyramidInfo&i,float2 p,float2 guess,thread float2&q,thread float&error,uint lane) {
int level=i.levels-1;for(;level>0;level--){float s=float(1<<level);if(inside(p/s,i.width[level],i.height[level])&&inside(guess/s,i.width[level],i.height[level]))break;}
@@ -20,24 +20,24 @@ bool trackFlow(device const float*prev,device const float*next,constant PyramidI
for(;level>=0;level--) {
float2 pp=p/float(1<<level);int w=i.width[level],h=i.height[level];if(!inside(pp,w,h))return false;
device const float*a=prev+i.offset[level];device const float*b=next+i.offset[level];
float ref[3],gx[3],gy[3],mean=0,hxx=0,hxy=0,hyy=0;
for(uint j=0;j<3;j++) {
uint k=lane+j*32;ref[j]=gx[j]=gy[j]=0;if(k>=81)continue;
float2 pos=pp+float2(int(k%9)-4,int(k/9)-4);ref[j]=pixel(a,w,pos);mean+=ref[j];
float ref[14],gx[14],gy[14],mean=0,hxx=0,hxy=0,hyy=0;
for(uint j=0;j<14;j++) {
uint k=lane+j*32;ref[j]=gx[j]=gy[j]=0;if(k>=441)continue;
float2 pos=pp+float2(int(k%21)-10,int(k/21)-10);ref[j]=pixel(a,w,pos);mean+=ref[j];
gx[j]=.5f*(pixel(a,w,pos+float2(1,0))-pixel(a,w,pos-float2(1,0)));
gy[j]=.5f*(pixel(a,w,pos+float2(0,1))-pixel(a,w,pos-float2(0,1)));
hxx+=gx[j]*gx[j];hxy+=gx[j]*gy[j];hyy+=gy[j]*gy[j];
}
mean=simd_sum(mean)/81;hxx=simd_sum(hxx);hxy=simd_sum(hxy);hyy=simd_sum(hyy);
mean=simd_sum(mean)/441;hxx=simd_sum(hxx);hxy=simd_sum(hxy);hyy=simd_sum(hyy);
float det=hxx*hyy-hxy*hxy;if(det<1e-8f||hxx+hyy<1e-5f)return false;
for(int iteration=0;iteration<20;iteration++) {
if(!inside(q,w,h))return false;float target[3],tm=0;
for(uint j=0;j<3;j++){uint k=lane+j*32;target[j]=k<81?pixel(b,w,q+float2(int(k%9)-4,int(k/9)-4)):0;tm+=target[j];}
tm=simd_sum(tm)/81;float bx=0,by=0,sse=0;
for(uint j=0;j<3;j++)if(lane+j*32<81){float e=ref[j]-mean-target[j]+tm;bx+=gx[j]*e;by+=gy[j]*e;sse+=e*e;}
for(int iteration=0;iteration<30;iteration++) {
if(!inside(q,w,h))return false;float target[14],tm=0;
for(uint j=0;j<14;j++){uint k=lane+j*32;target[j]=k<441?pixel(b,w,q+float2(int(k%21)-10,int(k/21)-10)):0;tm+=target[j];}
tm=simd_sum(tm)/441;float bx=0,by=0,sse=0;
for(uint j=0;j<14;j++)if(lane+j*32<441){float e=ref[j]-mean-target[j]+tm;bx+=gx[j]*e;by+=gy[j]*e;sse+=e*e;}
bx=simd_sum(bx);by=simd_sum(by);sse=simd_sum(sse);
float2 delta=float2(hyy*bx-hxy*by,hxx*by-hxy*bx)/det;if(!all(isfinite(delta))||length(delta)>8)return false;
q+=delta;error=sqrt(sse/81);if(dot(delta,delta)<.0001f)break;
q+=delta;error=sqrt(sse/441);if(dot(delta,delta)<.0001f)break;
}
if(level>0)q*=2;
}
+3 -3
查看文件
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>XPC!</string>
<key>CFBundleShortVersionString</key>
<string>1.4.0</string>
<string>1.4.1</string>
<key>CFBundleVersion</key>
<string>24</string>
<string>26</string>
<key>NSHumanReadableCopyright</key>
<string></string>
<key>PlugInKit</key>
@@ -71,7 +71,7 @@
<key>uuid</key>
<string>1C17B73B-F229-4C09-A434-EAF6DFF5F22A</string>
<key>version</key>
<string>1.4.0</string>
<string>1.4.1</string>
</dict>
<dict>
<key>className</key>
+82 -33
查看文件
@@ -13,6 +13,12 @@
namespace dy {
// Capacity is shared by the independent detector and its Metal transport.
constexpr size_t TrackerFeatureLimit = 300;
constexpr int TrackerPyramidLevels = 4;
constexpr int TrackerPatchRadius = 10;
constexpr int TrackerIterations = 30;
struct GrayFrame {
int width = 0, height = 0;
std::vector<float> pixels;
@@ -107,7 +113,7 @@ class Tracker {
}
static Pyramid makePyramid(const GrayFrame& f) {
Pyramid p{f};
while (p.size() < 5 && p.back().width >= 80 && p.back().height >= 80) {
while (p.size() < TrackerPyramidLevels && p.back().width >= 80 && p.back().height >= 80) {
const auto& src = p.back();
GrayFrame dst{src.width/2, src.height/2, {}};
dst.pixels.resize(static_cast<size_t>(dst.width)*dst.height);
@@ -126,7 +132,7 @@ class Tracker {
}
static bool flow(const Pyramid& prev, const Pyramid& next, P p, P guess, P& q, float& rmse) {
constexpr int radius=4, side=radius*2+1, count=side*side;
constexpr int radius=TrackerPatchRadius, side=radius*2+1, count=side*side;
int level=static_cast<int>(std::min(prev.size(),next.size()))-1;
for (;level>0;--level) {
float s=static_cast<float>(1<<level);
@@ -152,7 +158,7 @@ class Tracker {
mean/=count;
double det=hxx*hyy-hxy*hxy;
if (det < 1e-8 || (hxx+hyy) < 1e-5) return false;
for (int iteration=0;iteration<20;++iteration) {
for (int iteration=0;iteration<TrackerIterations;++iteration) {
if (!inside(next[level],q,radius+2)) return false;
float target[count],targetMean=0;
k=0;
@@ -177,39 +183,73 @@ class Tracker {
return inside(next[0],q,radius+2) && rmse<.12f;
}
std::vector<P> detect(const GrayFrame& frame, const std::vector<P>& existing) const {
static P refineCorner(const GrayFrame& frame, P initial) {
constexpr int radius=10;
P point=initial;
for(int iteration=0;iteration<20;++iteration) {
if(!inside(frame,point,radius+2))return initial;
double xx=0,xy=0,yy=0,bx=0,by=0;
for(int y=-radius;y<=radius;++y)for(int x=-radius;x<=radius;++x) {
float px=point.x+x,py=point.y+y;
double gx=.5*(sample(frame,px+1,py)-sample(frame,px-1,py));
double gy=.5*(sample(frame,px,py+1)-sample(frame,px,py-1));
double weight=std::exp(-double(x*x+y*y)/(radius*radius));
double a=weight*gx*gx,b=weight*gx*gy,c=weight*gy*gy;
xx+=a;xy+=b;yy+=c;bx+=a*x+b*y;by+=b*x+c*y;
}
double det=xx*yy-xy*xy;
if(!std::isfinite(det)||det<1e-10)break;
float dx=float((yy*bx-xy*by)/det),dy=float((xx*by-xy*bx)/det);
if(!std::isfinite(dx)||!std::isfinite(dy))return initial;
point.x+=dx;point.y+=dy;
if(distance(point,initial)>radius)return initial;
if(dx*dx+dy*dy<=.03f*.03f)break;
}
return inside(frame,point,radius+2)?point:initial;
}
std::vector<P> detect(const GrayFrame& frame) const {
struct Candidate {P p;float score;};
std::vector<Candidate> candidates;
float halfW=initialROI_.width*width_*.5f;
float halfH=initialROI_.height*height_*.5f;
float c=std::cos(initialROI_.angle),s=std::sin(initialROI_.angle);
double det=cumulative_.determinant();
float bound=0;
for(float x:{-halfW,halfW})for(float y:{-halfH,halfH}){
if(!std::isfinite(det)||det<=0)return {};
float left=float(width_),right=0,top=float(height_),bottom=0;
auto boundPoint=[&](P local){
float x=local.x*2*halfW,y=local.y*2*halfH;
auto p=cumulative_.map({initialROI_.cx*width_+c*x-s*y,initialROI_.cy*height_+s*x+c*y});
bound=std::max(bound,distance(p,center_));
}
int minX=std::max(8,static_cast<int>(center_.x-bound));
int maxX=std::min(width_-9,static_cast<int>(center_.x+bound));
int minY=std::max(8,static_cast<int>(center_.y-bound));
int maxY=std::min(height_-9,static_cast<int>(center_.y+bound));
left=std::min(left,p.x);right=std::max(right,p.x);top=std::min(top,p.y);bottom=std::max(bottom,p.y);
};
// A free pen path is not constrained to its creation-time width/height.
// Bound the actual path, including points beyond local +/-0.5.
if(mask_.size()>=3)for(P p:mask_)boundPoint(p);
else for(float x:{-.5f,.5f})for(float y:{-.5f,.5f})boundPoint({x,y});
constexpr int border=TrackerPatchRadius+3;
if(width_<=border*2||height_<=border*2)return {};
int minX=int(std::clamp(std::floor(left),float(border),float(width_-border)));
int maxX=int(std::clamp(std::ceil(right),float(border),float(width_-border)));
int minY=int(std::clamp(std::floor(top),float(border),float(height_-border)));
int maxY=int(std::clamp(std::ceil(bottom),float(border),float(height_-border)));
auto inRegion=[&](P point){
float dx=point.x-center_.x,dy=point.y-center_.y;
float oldX=float((cumulative_.d*dx-cumulative_.b*dy)/det);
float oldY=float((-cumulative_.c*dx+cumulative_.a*dy)/det);
float u=(c*oldX+s*oldY)/(2*halfW),v=(-s*oldX+c*oldY)/(2*halfH);
if(mask_.size()<3)return std::abs(u)<=.5f&&std::abs(v)<=.5f;
bool inside=false;
for(size_t i=0,j=mask_.size()-1;i<mask_.size();j=i++) {
P a=mask_[j],b=mask_[i];
if((a.y>v)!=(b.y>v))if(u<(b.x-a.x)*(v-a.y)/(b.y-a.y)+a.x)inside=!inside;
}
return inside;
};
float best=0;
for (int y=minY;y<maxY;y+=2) for (int x=minX;x<maxX;x+=2) {
float dx=x-center_.x,dy=y-center_.y;
float oldX=float((cumulative_.d*dx-cumulative_.b*dy)/det);
float oldY=float((-cumulative_.c*dx+cumulative_.a*dy)/det);dx=oldX;dy=oldY;
float u=(c*dx+s*dy)/(2*halfW),v=(-s*dx+c*dy)/(2*halfH);
if (std::abs(u)>.5f || std::abs(v)>.5f) continue;
if(mask_.size()>=3) {
bool inside=false;
for(size_t i=0,j=mask_.size()-1;i<mask_.size();j=i++) {
P a=mask_[j],b=mask_[i];
if((a.y>v)!=(b.y>v))if(u<(b.x-a.x)*(v-a.y)/(b.y-a.y)+a.x)inside=!inside;
}
if(!inside)continue;
}
if(!inRegion({float(x),float(y)}))continue;
double xx=0,xy=0,yy=0;
for (int j=-2;j<=2;++j) for (int i=-2;i<=2;++i) {
for (int j=-1;j<=1;++j) for (int i=-1;i<=1;++i) {
int idx=(y+j)*width_+x+i;
float gx=(frame.pixels[idx+1]-frame.pixels[idx-1])*.5f;
float gy=(frame.pixels[idx+width_]-frame.pixels[idx-width_])*.5f;
@@ -217,16 +257,20 @@ class Tracker {
}
float score=static_cast<float>((xx+yy-std::sqrt((xx-yy)*(xx-yy)+4*xy*xy))*.5);
best=std::max(best,score);
if (score>.0003f) candidates.push_back({{static_cast<float>(x),static_cast<float>(y)},score});
if (score>1e-7f) candidates.push_back({{static_cast<float>(x),static_cast<float>(y)},score});
}
std::sort(candidates.begin(),candidates.end(),[](const auto& a,const auto& b){return a.score>b.score;});
std::vector<P> selected=existing;
float minSpacing=std::max(6.f,std::min(width_,height_)*.014f);
std::vector<P> selected;selected.reserve(TrackerFeatureLimit);
constexpr float minSpacing=10.f;
for (const auto& candidate:candidates) {
if (candidate.score < best*.012f || selected.size()>=180) break;
if (candidate.score < best*.03f || selected.size()>=TrackerFeatureLimit) break;
bool near=false;
for (const auto& p:selected) if (distance(p,candidate.p)<minSpacing) {near=true;break;}
if (!near) selected.push_back(candidate.p);
if(near)continue;
P refined=refineCorner(frame,candidate.p);
if(!inRegion(refined))continue;
for(const auto& p:selected)if(distance(p,refined)<minSpacing){near=true;break;}
if(!near)selected.push_back(refined);
}
return selected;
}
@@ -300,7 +344,7 @@ public:
roi.width<=0 || roi.height<=0 || roi.width>8 || roi.height>8 || roi.cx<0 || roi.cx>1 || roi.cy<0 || roi.cy>1) return false;
width_=frame.width;height_=frame.height;initialROI_=roi;
center_={roi.cx*width_,roi.cy*height_};
points_=detect(frame,{});
points_=detect(frame);
result_.features=static_cast<int>(points_.size());result_.inliers=result_.features;
if (points_.size()<12) return false;
if(backend_){if(!backend_->reset(frame))return false;}else previous_=makePyramid(frame);active_=true;result_.valid=true;result_.confidence=1;
@@ -352,7 +396,12 @@ public:
result_.confidence=confidence;result_.inliers=static_cast<int>(inliers.size());result_.valid=true;
points_.clear();
for (int i:inliers) points_.push_back(matches[i].q);
if (++frameIndex_%5==0 || points_.size()<60) points_=detect(frame,points_);
if (++frameIndex_%2==0 || points_.size()<60) {
auto refreshed=detect(frame);
// Keep a still-trusted set when a refresh finds insufficient new
// corners; the next fit must continue to satisfy all loss guards.
if(refreshed.size()>=12)points_=std::move(refreshed);
}
previous_=std::move(next);
return result_;
}
+2 -2
查看文件
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.4.0</string>
<string>1.4.1</string>
<key>CFBundleVersion</key>
<string>24</string>
<string>26</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
+16 -2
查看文件
@@ -1,4 +1,18 @@
# 大鱼调色:1.4.0(24)蒙版、跟踪与可重复工具交接
# 大鱼调色:1.4.1(26)相邻插入、蒙版面板和钢笔修复交接
当前正式版为1.4.1(26)。APP编译源码 `0eb56aed126c825ca89712ce90f8cc1c05b03d89` 已推送;公证 `1ddc5499-2da3-4d98-8b2d-09272b0ee326` Accepted,正式位置 `/Library/Plug-Ins/FxPlug/大鱼调色.app`。PKG和Release结果以本版本验证记录为准。
新添加工具紧接点击处插入,重复点击原层也插在原层与既有子层之间;参数初始化且相互独立。schema2保存after锚点,实际渲染也插入对应阶段;旧schema1末尾工具保持原位置与画面。蒙版参数和数值为13pt、按钮32–36pt、滑杆单独整行,跟踪按钮两列并保留完整中文。
钢笔入口现可进入空白草稿绘制态,放点/拖柄、首点或Return/面板完成闭合、Delete回退、取消/重画、即时预览、单次撤销及连续手势已实现。修正画面提示文字上下翻转。同步内存草稿与延后作者提交分离,避免宿主回调内读写、过期目标与跨帧草稿覆盖。
跟踪按Color Finale只读行为证据独立适配实际路径范围、300特征、亚像素精炼、21×21光流及最高4K灰度帧,保留严格失效与过期写入保护。独立CPU/Metal18项通过。不能称为完整Color Finale移植;B样条、编组、人物/图像/外部蒙版、完整轨迹区段编辑等仍有差异,未做同一真实视频的完整轨迹等价对照。
正式版281项原生检查通过。FCP12.4实测相邻插入/初始化独立参数、大号面板/绘制态、钢笔蒙版正向99键、一次撤销和重做、保存重开完整预设逐字节一致。**实际鼠标钢笔落点与闭合仍待用户确认**,自动化鼠标未触发画面回调;模拟宿主的原生OSC回归通过,不混同实机手势。1.4.0用户确认的中心拖动历史保留。
入口:[本轮实现](research/MaskWorkflow1.4.1.md)、[Color Finale证据与差异](research/ColorFinaleMasksFollowup.md)、[实际宿主记录](verification/HostMaskWorkflow1.4.1.json)、[远端独立恢复](verification/MaskWorkflowRecovery.json)、[副本清理](verification/MaskWorkflowCleanup.json)、[恢复与构建](RECOVERY.md)。正式包和下载核验见Package.json/Release.json。
## 以下为1.4.0(24)的历史交接
更新日期:2026-11-01,Asia/Shanghai。当前 APP 已完成正式签名、公证、票据、唯一安装与宿主工作流检查;PKG/Release 状态以本仓库相应验证记录为准。
@@ -12,7 +26,7 @@
实际编译源码 `dbf25fe6719f17075362538dad0404951102524d` 已推送。APP公证 `40fdaaaa-1821-4cc8-bec3-c5dc6d8b9f77` Accepted;正式位置仍为 `/Library/Plug-Ins/FxPlug/大鱼调色.app`,Bundle ID仍为 `com.dayu.color`。Release前后均通过222项原生检查。FCP12.4独立合成工程实测HSL第二层0→32而原层0,独立椭圆/矩形、数值编辑、正向99键、双向100键、新增层单帧2键与播放头前进;一次撤销/重做及正常退出重开后完整预设逐字节一致。
**实机画面直接拖动、旋转和钢笔手势尚未确认。** 轮廓和工具栏可见,但验收工具的坐标点击没有进入真实宿主hit/event回调。原生模拟宿主已用真实Metal叠加验证命中、拖动写回、一次撤销与Esc,不能把它当成实机手势通过。后续先确认真实鼠标输入,再判断是否存在OSC宿主差异。Motion、Intel、变速/裁剪/非方像素工程未实测;跟踪不含透视/剪切。新增工具标量为静态作者值,只有蒙版轨迹随时间求值;空间蒙版拒绝Cube导出,应保存完整预设。
**用户已确认实际鼠标可拖动蒙版中心。** 初次自动化坐标点击未进入宿主回调,随后用户实测“可以拖动,蒙版随鼠标移动”;真实hit/mouseDown/mouseDragged日志已捕获,原层中心由0.6/0.5变成0.378/0.379,新增层矩形仍为0.5/0.5。用户试调结果保留,不再自动复位或重启宿主。旋转、缩放和钢笔手势未实机确认,原生模拟宿主相关检查通过;不要扩大为所有手势都已实测。Motion、Intel、变速/裁剪/非方像素工程未实测;跟踪不含透视/剪切。新增工具标量为静态作者值,只有蒙版轨迹随时间求值;空间蒙版拒绝Cube导出,应保存完整预设。
旧模板实例可能保留关闭OSC的10005值,可先存完整预设,再应用新版效果并载入;不自动覆盖旧效果。当前模板使用父库Boolean发布契约,最新插件解析。中间20–23版均未发布最终包,旧生成APP备份在24版宿主确认后清理。远端独立恢复210文件、strict/full fsck、模型模板和着色器重建一致,临时clone已清理。