feat: WIP unified workspace shared mask objects and OpenCV tracker core
这个提交包含在:
1 父节点
78e53b3889
当前提交
ca352248c1
36 个文件已更改
+5298
-164
没有与搜索条件相匹配的文件
+11
@@ -0,0 +1,11 @@
|
||||
Copyright (C) 2000-2020, Intel Corporation, all rights reserved.
|
||||
Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
|
||||
Copyright (C) 2009-2016, NVIDIA Corporation, all rights reserved.
|
||||
Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
|
||||
Copyright (C) 2015-2020, OpenCV Foundation, all rights reserved.
|
||||
Copyright (C) 2008-2016, Itseez Inc., all rights reserved.
|
||||
Copyright (C) 2019-2020, Xperience AI, all rights reserved.
|
||||
Copyright (C) 2019-2020, Shenzhen Institute of Artificial Intelligence and
|
||||
Robotics for Society, all rights reserved.
|
||||
|
||||
Third party copyrights are property of their respective owners.
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
# OpenCV 区域跟踪运行库
|
||||
|
||||
大鱼调色使用官方 OpenCV **4.5.1** 的 `core`、`imgproc`、`video`、`calib3d`(以及自动依赖`features2d`、`flann`)构建独立 arm64 静态库。版本选择依据是本机被研究产品的公开框架版本信息;不复制或链接该产品的框架、代码或资源。OpenCV 来源、完整提交、tag object、88,266,905 字节源码归档及 SHA-256 均在 [source-lock.json](source-lock.json)。Apache2许可原文保留在[LICENSE](LICENSE),旧源文件BSD等通知保留在[COPYRIGHT](COPYRIGHT)及[SOURCE-NOTICES.txt](SOURCE-NOTICES.txt),三份均应随APP分发。
|
||||
|
||||
运行 `python3 tools/build_tracking_opencv.py`;产物只在 `/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/`。脚本核对下载字节数和完整SHA-256,构建Release arm64/min macOS14.6,禁用共享库、额外应用、Python/Java、媒体编解码和不需要模块。无需Homebrew OpenCV、Color Finale或用户素材。脚本持有独立构建锁,可在Xcode前置阶段重复调用;编译日志、源码恢复档、构建身份及库摘要在该缓存。
|
||||
|
||||
`include/`与`libs/`指向本产品缓存中的安装结果;`link.rsp`包括自建`libDayuOpenCVTracker.a`及所需官方静态库。插件只需包含`MaskCore/DYOpenCVTracker.hpp`,使用`dy::OpenCVTracker`的`setMask/reset/track/result/active/stop`接口,并链接`@<固定缓存>/link.rsp`;该类不使用自研Metal光流backend。官方源码不作为巨型Git对象提交,灾难恢复时从锁定的公开完整提交下载并验证,下载失败应明确停止构建,不能静默切回不同算法。
|
||||
|
||||
桥接实现为本产品独立代码`tools/tracking/DYOpenCVTracker.cpp`。跟踪配置及与参考产品的保护差异见`research/ColorFinaleWorkspaceEvidence-20261105.md`;同API、版本和参数不代表同真实视频的逐帧等价。形状/时间/共享蒙版/作者Undo由产品宿主层负责。运行库保留纯CPU可重入对象,不设置全局OpenCV线程或RNG状态,以免干扰同宿主其他插件。
|
||||
|
||||
恢复核验:构建后检查`build-report.json`中的源码hash和静态库hash,编译运行`tools/tracking/verify_opencv_tracker.cpp`的已知运动测试。正式交付还须执行本产品已公证安装版本的实际FxAnalyzer测试;独立算法测试不替代宿主验收。
|
||||
+3889
文件差异过大,未显示。
加载差异
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"repository": "https://github.com/opencv/opencv.git",
|
||||
"version": "4.5.1",
|
||||
"tag": "4.5.1",
|
||||
"tagObject": "3e80752d72a4b78820a732087217668e67701981",
|
||||
"commit": "1363496c1106606684d40447f5d1149b2c66a9f8",
|
||||
"archiveURL": "https://codeload.github.com/opencv/opencv/tar.gz/1363496c1106606684d40447f5d1149b2c66a9f8",
|
||||
"archiveBytes": 88266905,
|
||||
"archiveSHA256": "4356b76721786bff66536ecd1a36ac2e397b13a4ee1dec41f362fa2459e903db",
|
||||
"license": "Apache-2.0",
|
||||
"modules": ["core", "imgproc", "video", "calib3d"],
|
||||
"automaticModuleDependencies": ["features2d", "flann"]
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
# Color Finale 工作区与区域跟踪证据(2026-11-05)
|
||||
|
||||
## 身份、边界和证据保留
|
||||
|
||||
本机 `/Applications/ColorFinale.app` 为2.16.2(625),主插件 `Contents/PlugIns/ColorFinale.pluginkit/Contents/MacOS/ColorFinale` 完整SHA-256为 `49121a6f5487060d322a59e7658166ab772e8a56f7dc1bcfa9d433a89436b30f`。2026-11-05重新核验,原文件只读。Ghidra12.1.4/arm64的分析profile为 `c991deeff48f794414bcbf9d15409d809db80062959eb2c963195db4cd97614a`,复用11月1日snapshot并补充本轮查询。静态调用链是发行产物观察,不是原版运行时逐项验收;用户提供的截图仅支持其中可见结构。
|
||||
|
||||
完整证据与反编译中间产物仅存本机 `/Users/mac/Library/Caches/CodexBuilds/ColorResearch/workspace-20261105/`;仓库仅保留事实、接口、实施合同和证据ID,不复制商用二进制、图标、nib或反编译实现。
|
||||
|
||||
## 工作区逻辑链
|
||||
|
||||
1. 顶栏工具动作 `addLayerWithType:`(`0x1000769cc`,`ev_9e1abf39aeee8571405645352af5b24cc00d4c08a4920a7b638266fee983960b`)创建对应工具节点,统一进入 `insertLayer:`。
|
||||
2. `insertLayer:`(`0x100076bac`,`ev_7e4a2dd8c5ccc4fe7cfd6a5c7f3589c1f68a2f2f54e6e06ef1a8e750058a018c`)读取第一项选择:无选择则根索引0;普通层则当前索引;组选中则组内0。在一个命名Undo组中插入。
|
||||
3. 插入block(`0x100076dd4`,`ev_aa0e9a9146fcb8527d086b91a39c51bf8fbe7a5c180686d5bcd2cdda16c69f17`)执行beginUpdates、必要展开组、insertLayer、选择新层、endUpdates、storeAdjustments,再更新右区和键盘焦点。
|
||||
4. `setActiveViewControllerForLayer:`(`0x100077758`,`ev_a0d38bcebc4979e7a77baa47c173fcaa6aae4640992709a18bbd8ea7db048613`)先检查当前层蒙版是否selected且enabled:满足则切蒙版控制器并updateScene;否则按工具类型切曲线、色轮、HSL、LUT等控制器,再setNode到当前真实对象。
|
||||
5. `setActiveViewController:`(`0x100077a98`,`ev_eacade9dcaa7e283df2af98aa0dc6ab2ec69cb48b6cad8c6fd84a4d35bc065df`)卸载旧控制器并清空其node,再把新控制器view放入同一viewHost。不是叠加多份浮动参数窗。
|
||||
6. `storeAdjustments`(`0x1000760f0`,`ev_2a855e029cca778e55e861367fffd6cb9adf4d7e52914841ffc3beb51285fae7`)从layersViewModel.rootNode取得实际文档,经apiManager.performActions提交。检查器、工作区和渲染不应各建一份作者数据。
|
||||
|
||||
官方[图层工作区文档](https://docs.colorfinale.com/docs/layers/)同时确认:可调大小浮窗、横排工具、点击新增独立图层、左列选层、右区编辑、图层眼睛和右键菜单、底部强度/混合/蒙版/删除。原版文档所称默认新层在顶部与上面的无选择/当前选择/组内插入分支相容。文档描述不是本机运行验证。
|
||||
|
||||
## 蒙版编辑与共享对象
|
||||
|
||||
`addLayerMask:`(`0x1000f0c30`,`ev_cada231cd5850104fb9806190f532f919e4d82e2c2026a771d5cdf010b81594a`)对选择层中无蒙版者建立FTFxNodeMask,已有者保留;统一作者更新。`maskSelectionDidChange:`及block(`0x100078480/0x100078514`,`ev_a42abc5cdccfdba24fa750e3b2ceb178d949b89445c985c314cb1e7b382a31e1`、`ev_c4bbaccfaa18337b20e24cf38373237af45fc5817c199f0b6507ff3c9d8f6237`)经宿主action保存并切右区。
|
||||
|
||||
`FTMaskDetailViewController::updateControls`(`0x100015a98`,`ev_030904608107bf6f0220345798ac4adfbf2fa726ae0387dfc6ca1851fde04c0f`)按真实蒙版类型选择形状、图像、HSL、人物、FCP子控制器,解绑非当前节点。仅可动画形状展示跟踪区;自动跟踪时关闭冲突属性与关键帧操作。属性编辑包含羽化、强度、位置、缩放、旋转,另有反转与组合模式。
|
||||
|
||||
官方[蒙版文档](https://docs.colorfinale.com/docs/masks/masks/)确认在工作区右区替换调色控件,画布叠加小工具栏;面板加号与画布直接绘制为两个入口;同层可有多个形状,支持Add/Subtract/Intersect。官方[跟踪文档](https://docs.colorfinale.com/docs/masks/tracking/)确认前后区域跟踪与关键帧操作;[显示模式](https://docs.colorfinale.com/docs/masks/fourmaskdisplaymode/)描述结果、输入、输入叠蒙版与黑白合成;[形状编组](https://docs.colorfinale.com/docs/masks/grouping-mask-shapes/)描述多选组变换。
|
||||
|
||||
本轮用户进一步要求“画布左侧常驻蒙版工具”“先画/先选模块”“同一蒙版关联多个模块并共享形状和轨迹”。这是大鱼的新需求;当前证据不能直接声称Color Finale提供完全相同的跨任意模块共享引用操作。实施合同应是文档scene中唯一maskID对象+模块maskRef,而非复制mask字典;一次修改应影响全部引用,删除某模块仅移除引用,孤立对象清理需保留可独立选择的已画蒙版。形状、轨迹和手工关键帧都属于该共享对象;当前模块选择、右区页签、布局和画布显示属于界面状态。
|
||||
|
||||
## 窗口边界
|
||||
|
||||
`FTRemoteColorCorrectionWindowController::initWithMinSize:maxSize:containerViewController:`(`0x10010aa0c`,`ev_df055fd889e786ea4e4cdca060207f8ffbe73be5445d5e1f198b9ba6fa9e447e`)建立不透明white约0.122的FxRemoteWindow及contentViewController。`showPanelForPlugin:`(`0x10010af60`,`ev_df9a209ebfdd992dcab10802f1535537ab2992b57ac83a960e49e1977045a6f1`)绑定当前plugin,必要时关闭重开以更新尺寸,否则激活已有窗。`updateWindowSize` block(`0x10010a7b0`,`ev_1afe52ae28a67dc775a4f5f5164aeb351790ae4eded25783b840335240072b44`)读取三档layersPanelSize并设min/max约1/1.25/1.5倍率。
|
||||
|
||||
现有证据支持自由调整的独立浮窗。没有证据证明第三方FxPlug可以嵌入FCP检视器内部;“检视器下方窄条、不挡画面”应作为本产品默认摆放/尺寸目标,通过公开FxRemoteWindow API与实际宿主验证实现,不能声称已原生停靠FCP。
|
||||
|
||||
## 可复现的开放算法配置
|
||||
|
||||
本机原版opencv2.framework Info.plist为4.5.1。该框架只读核对版本,不复制、不链接;大鱼可由官方OpenCV4.5.1源码独立构建。官方tag peeled commit:`1363496c1106606684d40447f5d1149b2c66a9f8`(tag object `3e80752d72a4b78820a732087217668e67701981`)。
|
||||
|
||||
核心观察来自 `FTAreaTracker::track:trackerState:`(`0x100035e40`,`ev_dcd7aa770925f63c8c14c968ae6b417fda78685c7be7fa739a78209957d40e2d`),逐帧来自`trackFrame:inScene:`(`0x100036cbc`,`ev_e798c4e6e032e085812f81831ecc16196bd3c2278bf634961379669ee1308f7e`),分析入口`effectAnalysis:analyzeFrame:session:error:`(`0x10005b47c`,`ev_1dd68409d431d9e81875b6032a81dd89f7f237ea5501d3db1d7ca92ba32e6323`)。
|
||||
|
||||
| 阶段 | 可独立重建的调用合同 |
|
||||
| --- | --- |
|
||||
| 完整帧 | 宿主tiles收齐完整帧;IOSurface转换,分析最大3840×2160;转8bit灰度。原版调用cvtColor代码11,按OpenCV颜色枚举对应RGBA2GRAY;需匹配实际源通道序,不能对BGRA盲用 |
|
||||
| 形状区域 | 形状像素顶点转int,convexHull(clockwise=false,returnPoints=true),fillPoly(mask8UC1,255,LINE_AA,shift0) |
|
||||
| 特征重选 | 全局分析计数<2或偶数帧;goodFeaturesToTrack(max300,q.03,minDistance10,blockSize3,Harris=false,k.04) |
|
||||
| 亚像素 | cornerSubPix(winSize10×10,zeroZone(-1,-1),COUNT|EPS,20,.03) |
|
||||
| 光流 | 相邻灰度帧前后calcOpticalFlowPyrLK,21×21,maxLevel3,COUNT|EPS30/.01,flags0,minEigThreshold1e-4 |
|
||||
| 筛点 | 成功status并FB欧氏距离严格<1像素;有效点不足4失败;位移≥max(w,h)×.01的点若严格超过当前有效点半数,使用该子集 |
|
||||
| 仿射 | 前后点先减当前形状中心;estimateAffine2D(RANSAC=8,reprojection3,maxIters2000,confidence.99,refine10) |
|
||||
| 作者输出 | sx=hypot(a,c),theta=atan2(c,a),sy=det/sx;每步围绕旧中心更新形状,center加拟合平移,theta累加,sx/sy逐步相乘;输出position按分析w/h归一化、rotation、scaleXY,并用effectTime持久化 |
|
||||
|
||||
公开API参考:[特征与亚像素](https://docs.opencv.org/4.5.1/dd/d1a/group__imgproc__feature.html)、[金字塔LK](https://docs.opencv.org/4.5.1/dc/d6b/group__video__track.html)、[仿射RANSAC](https://docs.opencv.org/4.5.1/d9/d0c/group__calib3d.html)。本表是参数/行为合同,不包含原版实现源码。
|
||||
|
||||
原报告“空仿射矩阵必失败”需修正:当前反编译中empty分支只跳过变换,而后仍可返回1,未独立汇编/运行复核,不能把该静默成功视为正确行为。大鱼应明确在空fit、非法数值、反射、离画及置信不足时停止并保留可信段;该保护差异必须记录。
|
||||
|
||||
## 迁移与验证缺口
|
||||
|
||||
需要从旧自研特征/LK/RANSAC切到独立编译的OpenCV管线,不能只把阈值改成相同数字;300点与21窗口本身不建立算法等价。必须补齐灰度系数/8位量化、分析分辨率、凸包区域、周期重选、运动主体筛选、中心化拟合与逐步QR作者输出。既有宿主冻结目标、精确CMTime、一次撤销、手工键保留、取消可信段、旧实例隔离继续沿用。
|
||||
|
||||
同视频同路径同范围的原版/大鱼完整轨迹尚未运行对照;图像通道/色彩空间、OpenCV编译优化、分块帧调度与数值细节可能影响结果。静态重建、合成运动检查及正式宿主测试应各自报告,不得宣称逐帧或逐像素完全等价。
|
||||
|
||||
## 本轮独立实现结果
|
||||
|
||||
`dy::OpenCVTracker`现使用独立编译的官方4.5.1库,12项已知运动检查通过(`verification/TrackingOpenCV-20261105.json`):300点、旋转及双轴缩放、框外路径12帧亚像素、周期重选静止、换景、平坦区、运动多数子集、实例隔离、坏帧几何保留、非有限输入及完整4K。中心误差约0.0033px(旋转/缩放)、0.0148px(12帧路径)、0.00011px(4K平移);这些是生成素材结果,不是实拍或原版轨迹对照。只依赖系统zlib/Accelerate/libc++/System,插件运行不需要研究目标或另一APP。宿主接入、共享mask作者同步、正式版本实际跟踪仍由主任务验收。
|
||||
@@ -0,0 +1,72 @@
|
||||
# 统一工作区、共享蒙版和现有跟踪链路审计
|
||||
|
||||
2026-11-05,Asia/Shanghai。审计基线 `b33b963`;以下源码观察来自本产品,不是 Color Finale 运行证据。本文件记录本次负责的 `DYToolState.h/.mm`、`DYMaskPanel.inc.h` 和 `DYSharedMaskDiagnostics.inc.h`,正式构建与宿主结果由主交付记录另行补齐。
|
||||
|
||||
## 已有链路与复用接口
|
||||
|
||||
- 原始固定工具身份为 `base:<type>`,独立层是 UUID;`DYInsertTool(document,type,afterID)` 使用 `after` 稳定锚点,不能以列表序号寻址。`DYToolManager` 代理独立 UUID 参数,不支持把 `base:type` 伪造成 UUID。固定工具需直接使用 root host manager。
|
||||
- `DYToolDisplayOrder` 是界面目录与锚点树顺序。旧基础渲染的实际执行顺序保留在 `DYToolRender.inc.h` 的 `anchors`:一级、三原色、曲线、色阶、平衡、HSL、颜色分级、基础、黑白、LUT、肤色,随后蜘蛛盘和尾部工具。目录顺序与旧基础运算顺序不同;本次界面调整不能默默改写旧颜色链。
|
||||
- `DYModelChanged` 通知对象是 root host。原主检查器主动调用 `synchronizeTools` 刷新子检查器。工作区直接嵌入的 `DYInspector` 必须由工作区监听 root host 再主动 `refresh`,因为原 embedded 检查器自身监听的是其 `DYToolManager`。
|
||||
- `DYToolCanvasSelection`:对象 root host;userInfo `node`、`mask`、可选 `document`、`draw`、`hidden`。用于选择蒙版、切换钢笔绘制与隐藏轮廓。
|
||||
- `DYToolCanvasCommand`:对象 root host;`node`、`mask`、`command=finish/cancel` 与精确 `timeValue/timeScale/timeEpoch`。
|
||||
- `DYToolTrack`:对象 root host;`node`、`mask`、`direction=-2/-1/0/1/2/9`,分别反向单帧、反向、双向、正向、正向单帧、取消。
|
||||
- 基线 `DYToolTrackingStatus` 回传 `node/message`,共享库应同时带mask以免两个共享对象切换后旧状态覆盖新项;面板已兼容按可选mask过滤。`DYToolCanvasState` 回传 `node/mask/drawing`。选择身份、开合和排版属于显示状态,不应额外写一次调色撤销。
|
||||
|
||||
## 当前跟踪实现的真实范围
|
||||
|
||||
`DYToolHostMethods.inc.h` 的 `toolTrackRequested:` 在主队列宿主 action 冻结当前 UUID、完整蒙版、参考 CMTime 和方向;通过 `FxAnalysisAPI` 启动 GPU 分析。`desiredAnalysisTimeRange:` 和 `setupAnalysisForTimeRange:` 使用宿主精确帧长;`analyzeFrame:` 对连续时间逐帧复核,不以移动播放头或 320×180 LUT 预览代替实际源帧。
|
||||
|
||||
`toolGrayFrame:error:` 要求完整宿主 image bounds,支持源图原点、像素长宽比,限制显示比例分析图到 1280×720,不放大小图。`dyToolCapture` 在降采样前对源覆盖范围低通;颜色输入解除预乘,经显示编码形成 luma。这是分析图,调色输出保持原分辨率。
|
||||
|
||||
算法源码为本产品 `MaskCore/DYTracker.hpp` 与 `DYTracking.metal`:最多 300 个 Shi–Tomasi 类角点,最小间隔 10px、相对阈值 3%、亚像素细化;最多 4 层金字塔,21×21 patch,每层最多 30 次 LK 类迭代;正反光流误差 ≤1.1px;确定性 400 次三点仿射 RANSAC,3px 细化容差,至少 8 内点、52% 一致性,拒绝近线状分布。置信度综合保留比例与中值残差,低于0.3停止;另检查单步缩放、旋转、累计尺度和中心是否出画。
|
||||
|
||||
输出是中心、旋转、独立 X/Y 缩放;内部累计仿射包含更多自由度,但最终蒙版参数不保存完整剪切/透视,也不是非刚性逐钢笔节点描边。不能把这一实现称为 Color Finale 算法完全等价,需由独立逆向证据和对照实验另行证明。
|
||||
|
||||
收尾通过 `_trackingFinishing.exchange(true)` 与 generation 防重入;双向共用同一参考起点,最终只提交一次。`DYMergeTracking` 保留手工键和范围外旧轨迹。写回时检查当前完整蒙版等于冻结蒙版,避免覆盖外部编辑;正常取消、丢失与单帧结束使用 SDK `kFxError_UserCancelled` 明确结束宿主任务。单帧后先把源时间转换成时间线时间,再请求播放头移动。上述旧问题的修复不应被新 UI 绕开。
|
||||
|
||||
## 本次共享对象模型
|
||||
|
||||
作者文档继续兼容 schema1/2;schema3 增加 `sharedMasks`,最多64个唯一蒙版对象。原 `baseMasks[type]`、`node.masks` 可混合旧完整蒙版与单字段引用 `{sharedID: UUID}`,维持组合顺序。同一共享对象可以被多个模块引用,单模块禁止重复引用;悬空引用、引用夹带字段、重复真实 UUID 均拒绝。每模块16项、单蒙版16384键、全作者65536键与24MiB上限保留;全作者键数对共享对象只计一次。
|
||||
|
||||
`DYMasksForTool(document,nodeID)` 返回解引用对象本身。可变文档中,两个模块返回的是同一个可变共享字典;画布草稿提交、数字编辑、跟踪写回修改这一个对象,因此所有关联模块同步。特殊 `nodeID=@"shared"` 直接选择共享库,支持先画蒙版再指定模块。
|
||||
|
||||
新增函数:
|
||||
|
||||
| 接口 | 行为 |
|
||||
| --- | --- |
|
||||
| `DYSharedMasks` / `DYSharedMaskWithID` | 读取全局库及唯一对象 |
|
||||
| `DYAddSharedMask` | 新建未关联共享对象,返回实际库中字典 |
|
||||
| `DYSetSharedMaskAssigned` | 给 `base:type` 或 UUID 增删引用,解除单层不删除对象 |
|
||||
| `DYToolIDsForSharedMask` | 列出所有关联工具身份 |
|
||||
| `DYRemoveSharedMask` | 删除对象及所有引用,保留工具层 |
|
||||
| `DYShareToolMask` | 将旧独立蒙版提升成唯一共享对象,保留原UUID与全部数据 |
|
||||
| `DYResolvedToolDocument` | 一次性展开为临时schema2渲染文档,单引用确定性UUID;不供编辑 |
|
||||
| `DYToolRenderSnapshot` | 先展开、再按指定CMTime求值;所有渲染副本删除轨迹作者键 |
|
||||
|
||||
渲染副本的 `sourceSharedID` 保留源身份。确定性临时UUID由共享ID与工具ID派生,以满足旧schema2全局UUID唯一校验,并使快照及缓存稳定;它不是另一个作者蒙版。没有时间参数的 `DYResolvedToolDocument` 清空展开共享副本的keys,与既有直接渲染读取基础参数的行为一致;有时间的宿主渲染必须经过 `DYToolRenderSnapshot`。
|
||||
|
||||
## 外部必须适配的位置
|
||||
|
||||
以下为基线文件/方法位置,后续行号随编辑变化;检索键可用 `rg 'baseMasks|\[@"masks"\]' '大鱼调色/Plugin'`:
|
||||
|
||||
| 文件与基线行 | 原读取 | 必要适配 |
|
||||
| --- | --- | --- |
|
||||
| `DYToolHostMethods.inc.h:11` `adoptToolCanvasDocument:` | 直接遍历baseMasks/node.masks寻找启用对象 | 使用 `DYMasksForTool`,并包括全局共享库;已有所选共享节点应保持 |
|
||||
| 同文件`:24` `toolMask:node:document:` | 已使用DYMasksForTool | 无需改为复制对象;此处必须返回可变文档真实对象 |
|
||||
| 同文件`:28` `toolCanvasSelection:` | 所选node改变即取消并丢弃跟踪 | 从关联层切到shared库是相同蒙版但node变化;可保守取消,若要求跨入口不中断,比较唯一共享ID而非仅node |
|
||||
| `DYToolCanvasEditing.inc.h` 画布添加种类 | 直接DYNewMask并加入层列表 | 新全局入口用DYAddSharedMask;可选模块用DYSetSharedMaskAssigned关联 |
|
||||
| `DYInspector.mm:858` `refresh` | 直接baseMasks数量判断可见 | 引用数组本身仍有数量,但详情/显示蒙版名称必须解引用 |
|
||||
| `DYToolRender.inc.h:44` `renderToolsSource:...` | baseMasks及node.masks传Metal | 先验证作者文档,再DYResolvedToolDocument;正常pluginState已为展开快照 |
|
||||
| 同文件`:101` `exportLUT:...tools:` | 引用数组count用于拒绝空间导出 | 只拒绝实际关联蒙版;未分配的全局库不影响画面、不必阻止Cube |
|
||||
| `DYPrimaryRender.inc.h`、`DYManagedRender.inc.h` 主render方法 | 固定一级/film及附加层直接取masks | 入门先验证作者,再展开引用;不要把refs传给maskBuffer读取parameters |
|
||||
| `DYPlugIn.mm:33` `pluginState` | DYToolRenderSnapshot | 已由本次共享模型统一解决,无需另外复制作者对象 |
|
||||
|
||||
## 紧凑蒙版编辑器
|
||||
|
||||
`DYToolMaskPanel` 实现 `DYWorkspaceMaskEditing`,公开 `workspaceMode`、`contentHeight`、`selectedMaskID`、`refreshWithDocument:time:`、`addMenu:` 和 `selectMaskID:`。workspaceMode在≥560pt宽时把参数网格与跟踪操作分为两列,860pt以上单行头部;600–1200pt宽适应,低高度交由外层滚动容器。窄检查器保留原有竖排尺寸;小于560pt时contentHeight也返回完整竖排高度,实际377pt编辑列不会因误用多列高度截掉跟踪区域。`contentHeight` 按当前宽度动态返回,外层应先设宽、再读取高度、再设置文档视图高度。
|
||||
|
||||
选中同一个、已经活跃的蒙版不会重发canvas选择,不会在每次刷新时取消钢笔草稿;首次选中默认首项仍激活画布。空库清空旧maskID,避免保留已删除对象。shared模式的删除提示包含全部关联,操作仍走既有单次Undo宿主写入。此面板不单独复制跟踪算法或作者状态。
|
||||
|
||||
## 验证范围
|
||||
|
||||
新增 `DYSharedMaskDiagnostics.inc.h`:先画后关联、两模块同一对象、编辑与轨迹同步、安全归档、确定性独立渲染绑定、悬空/重复/伪复制拒绝、单层解除和全局删除、旧蒙版提升、64库/16引用独立上限、共享键预算只计一次,以及六种蒙版在377/600/860/1200pt布局内的可见控件边界与交叠。`DYToolState.mm`、包含新面板的 `DYInspector.mm`、包含新诊断的 `DYDiagnostics.mm` 已通过本机clang语法检查,只有既存弃用和动态probe警告。运行结果待主交付的正式安装自检记录;本文件不预写运行“通过”。
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the pinned public OpenCV tracking runtime outside the source checkout."""
|
||||
from pathlib import Path
|
||||
import argparse, contextlib, fcntl, hashlib, json, os, shutil, subprocess, tarfile, urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CACHE = Path('/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv')
|
||||
LOCK = json.loads((ROOT/'ThirdParty/OpenCV/source-lock.json').read_text())
|
||||
|
||||
def sha(path):
|
||||
h=hashlib.sha256()
|
||||
with path.open('rb') as f:
|
||||
while chunk:=f.read(1024*1024):h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def run(args, log):
|
||||
with log.open('a') as out:
|
||||
subprocess.run([str(x) for x in args],check=True,stdout=out,stderr=subprocess.STDOUT)
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--resources',type=Path);ap.add_argument('--jobs',type=int,default=min(4,os.cpu_count() or 2));args=ap.parse_args()
|
||||
CACHE.mkdir(parents=True,exist_ok=True)
|
||||
with (CACHE/'build.lock').open('w') as exclusive:
|
||||
fcntl.flock(exclusive,fcntl.LOCK_EX)
|
||||
download=CACHE/'opencv-4.5.1.tar.gz'
|
||||
if not download.exists():
|
||||
prior=CACHE.parent/'opencv-tracking/opencv-4.5.1.tar.gz'
|
||||
if prior.exists() and sha(prior)==LOCK['archiveSHA256']:shutil.move(str(prior),download)
|
||||
else:
|
||||
partial=download.with_suffix('.download')
|
||||
with urllib.request.urlopen(LOCK['archiveURL'],timeout=90) as response, partial.open('wb') as out:
|
||||
shutil.copyfileobj(response,out)
|
||||
if partial.stat().st_size!=LOCK['archiveBytes'] or sha(partial)!=LOCK['archiveSHA256']:
|
||||
raise RuntimeError('OpenCV download identity mismatch; unverified file retained')
|
||||
partial.replace(download)
|
||||
if download.stat().st_size!=LOCK['archiveBytes'] or sha(download)!=LOCK['archiveSHA256']:
|
||||
raise RuntimeError('OpenCV cached source identity mismatch')
|
||||
source=CACHE/('opencv-'+LOCK['commit'])
|
||||
if not source.exists():
|
||||
with tarfile.open(download,'r:gz') as archive:
|
||||
for member in archive.getmembers():
|
||||
target=(CACHE/member.name).resolve()
|
||||
if not target.is_relative_to(CACHE.resolve()) or member.issym() or member.islnk():
|
||||
raise RuntimeError('Unexpected source archive path/link')
|
||||
archive.extractall(CACHE)
|
||||
build=CACHE/'build';prefix=CACHE/'install';log=CACHE/'build.log'
|
||||
sdk=Path(subprocess.check_output(['xcrun','--show-sdk-path'],text=True).strip())
|
||||
config=[
|
||||
'-DCMAKE_POLICY_VERSION_MINIMUM=3.5','-DCMAKE_BUILD_TYPE=Release',
|
||||
'-DCMAKE_OSX_ARCHITECTURES=arm64','-DCMAKE_OSX_DEPLOYMENT_TARGET=14.6',
|
||||
'-DBUILD_LIST='+','.join(LOCK['modules']),'-DBUILD_SHARED_LIBS=OFF',
|
||||
'-DBUILD_TESTS=OFF','-DBUILD_PERF_TESTS=OFF','-DBUILD_EXAMPLES=OFF',
|
||||
'-DBUILD_opencv_apps=OFF','-DBUILD_DOCS=OFF','-DBUILD_JAVA=OFF',
|
||||
'-DBUILD_opencv_python2=OFF','-DBUILD_opencv_python3=OFF',
|
||||
'-DBUILD_opencv_js=OFF','-DBUILD_opencv_gapi=OFF','-DBUILD_opencv_dnn=OFF',
|
||||
'-DWITH_IPP=OFF','-DWITH_ITT=OFF','-DWITH_OPENCL=OFF','-DWITH_TBB=OFF','-DWITH_CAROTENE=OFF',
|
||||
'-DWITH_OPENMP=OFF','-DWITH_LAPACK=OFF','-DWITH_EIGEN=OFF',
|
||||
'-DWITH_VTK=OFF','-DWITH_ADE=OFF','-DWITH_FFMPEG=OFF','-DWITH_GSTREAMER=OFF',
|
||||
'-DWITH_AVFOUNDATION=OFF','-DWITH_QUIRC=OFF','-DWITH_PROTOBUF=OFF',
|
||||
'-DWITH_JPEG=OFF','-DWITH_PNG=OFF','-DWITH_TIFF=OFF','-DWITH_WEBP=OFF',
|
||||
'-DWITH_OPENEXR=OFF','-DWITH_JASPER=OFF','-DWITH_OPENJPEG=OFF',
|
||||
'-DBUILD_ZLIB=OFF','-DZLIB_INCLUDE_DIR='+str(sdk/'usr/include'),
|
||||
'-DZLIB_LIBRARY='+str(sdk/'usr/lib/libz.tbd'),
|
||||
'-DZLIB_LIBRARY_RELEASE='+str(sdk/'usr/lib/libz.tbd'),
|
||||
'-DOPENCV_FORCE_3RDPARTY_BUILD=OFF','-DOPENCV_GENERATE_PKGCONFIG=OFF',
|
||||
'-DCMAKE_CXX_STANDARD=17','-DCMAKE_CXX_VISIBILITY_PRESET=hidden',
|
||||
'-DCMAKE_VISIBILITY_INLINES_HIDDEN=ON','-DCMAKE_INSTALL_PREFIX='+str(prefix)]
|
||||
configuration=hashlib.sha256(json.dumps(config).encode()).hexdigest()
|
||||
marker=CACHE/'opencv-build.json'
|
||||
if not marker.exists() or json.loads(marker.read_text()).get('configuration')!=configuration:
|
||||
run(['cmake','-S',source,'-B',build,*config],log)
|
||||
run(['cmake','--build',build,'--parallel',args.jobs],log)
|
||||
run(['cmake','--install',build],log)
|
||||
marker.write_text(json.dumps({'configuration':configuration,'commit':LOCK['commit'],'archiveSHA256':LOCK['archiveSHA256']},indent=2)+'\n')
|
||||
include=CACHE/'include';libs=CACHE/'libs';libs.mkdir(exist_ok=True)
|
||||
if include.is_symlink():include.unlink()
|
||||
if not include.exists():include.symlink_to(prefix/'include/opencv4',target_is_directory=True)
|
||||
libraryNames=['calib3d','features2d','flann','video','imgproc','core']
|
||||
for name in libraryNames:
|
||||
src=prefix/'lib'/('libopencv_'+name+'.a');dest=libs/src.name
|
||||
if not src.exists():raise RuntimeError('Required OpenCV library absent: '+str(src))
|
||||
if dest.is_symlink():dest.unlink()
|
||||
if not dest.exists():dest.symlink_to(src)
|
||||
bridge=ROOT/'tools/tracking/DYOpenCVTracker.cpp';obj=libs/'DYOpenCVTracker.o';runtime=libs/'libDayuOpenCVTracker.a'
|
||||
identity=hashlib.sha256(bridge.read_bytes()+(ROOT/'大鱼调色/Plugin/MaskCore/DYOpenCVTracker.hpp').read_bytes()+marker.read_bytes()).hexdigest()
|
||||
bridgeMarker=CACHE/'bridge-build.json'
|
||||
if not runtime.exists() or not bridgeMarker.exists() or json.loads(bridgeMarker.read_text()).get('identity')!=identity:
|
||||
run(['xcrun','clang++','-std=c++17','-arch','arm64','-mmacosx-version-min=14.6','-O3','-fvisibility=hidden',
|
||||
'-I'+str(include),'-c',bridge,'-o',obj],log)
|
||||
run(['xcrun','libtool','-static','-o',runtime,obj],log)
|
||||
bridgeMarker.write_text(json.dumps({'identity':identity,'runtimeSHA256':sha(runtime)},indent=2)+'\n')
|
||||
# Absolute arguments contain no spaces in the fixed build-cache path.
|
||||
response=[str(runtime),*[str(libs/('libopencv_'+name+'.a')) for name in libraryNames],'-lz','-framework','Accelerate']
|
||||
(CACHE/'link.rsp').write_text('\n'.join(response)+'\n')
|
||||
report={'version':LOCK['version'],'commit':LOCK['commit'],'archiveSHA256':LOCK['archiveSHA256'],
|
||||
'header':str(include),'linkResponse':str(CACHE/'link.rsp'),'libraries':[
|
||||
{'path':x,'bytes':Path(x).stat().st_size,'sha256':sha(Path(x))} for x in response if x.endswith('.a')],
|
||||
'sourceApplicationDependency':False}
|
||||
(CACHE/'build-report.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
if args.resources:
|
||||
args.resources.mkdir(parents=True,exist_ok=True)
|
||||
for name in ['LICENSE','COPYRIGHT','SOURCE-NOTICES.txt','source-lock.json']:
|
||||
shutil.copy2(ROOT/'ThirdParty/OpenCV'/name,args.resources/name)
|
||||
print('OpenCV '+LOCK['version']+' public source runtime ready: '+str(CACHE/'link.rsp'))
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,137 @@
|
||||
// Independent reconstruction using the public OpenCV API. No commercial source.
|
||||
#include "../../大鱼调色/Plugin/MaskCore/DYOpenCVTracker.hpp"
|
||||
#include <opencv2/core.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <opencv2/video/tracking.hpp>
|
||||
#include <opencv2/calib3d.hpp>
|
||||
|
||||
namespace dy {
|
||||
struct OpenCVTracker::Impl {
|
||||
cv::Mat previous;
|
||||
std::vector<cv::Point2f> points, polygon;
|
||||
std::vector<FlowPoint> mask;
|
||||
TrackerROI seed{};
|
||||
TrackResult value{};
|
||||
cv::Point2f center{};
|
||||
int frameIndex=0, width=0, height=0;
|
||||
bool running=false;
|
||||
|
||||
static cv::Mat gray8(const GrayFrame& f) {
|
||||
if(!f.valid())return {};
|
||||
cv::Mat out(f.height,f.width,CV_8UC1);
|
||||
for(size_t i=0;i<f.pixels.size();++i) {
|
||||
float x=f.pixels[i];
|
||||
if(!std::isfinite(x))return {};
|
||||
out.data[i]=cv::saturate_cast<uchar>(x*255.f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
void detect() {
|
||||
std::vector<cv::Point> vertices,hull;
|
||||
for(auto p:polygon)vertices.emplace_back(int(p.x),int(p.y));
|
||||
points.clear();
|
||||
if(vertices.size()<3)return;
|
||||
cv::convexHull(vertices,hull,false,true);
|
||||
cv::Mat area=cv::Mat::zeros(height,width,CV_8UC1);
|
||||
cv::fillPoly(area,std::vector<std::vector<cv::Point>>{hull},cv::Scalar(255),cv::LINE_AA);
|
||||
cv::goodFeaturesToTrack(previous,points,300,.03,10.,area,3,false,.04);
|
||||
if(!points.empty())cv::cornerSubPix(previous,points,{10,10},{-1,-1},
|
||||
{cv::TermCriteria::COUNT|cv::TermCriteria::EPS,20,.03});
|
||||
}
|
||||
TrackResult fail(TrackFailure why) {
|
||||
running=false;value.valid=false;value.confidence=0;value.failure=why;return value;
|
||||
}
|
||||
};
|
||||
|
||||
OpenCVTracker::OpenCVTracker():impl_(std::make_shared<Impl>()){}
|
||||
OpenCVTracker::~OpenCVTracker()=default;
|
||||
void OpenCVTracker::setMask(std::vector<FlowPoint> p){impl_->mask=std::move(p);}
|
||||
const char* OpenCVTracker::version(){return CV_VERSION;}
|
||||
TrackResult OpenCVTracker::result()const{return impl_->value;}
|
||||
bool OpenCVTracker::active()const{return impl_->running;}
|
||||
void OpenCVTracker::stop(){impl_->running=false;impl_->value.valid=false;}
|
||||
|
||||
bool OpenCVTracker::reset(const GrayFrame& f,TrackerROI roi) {
|
||||
auto& t=*impl_;t.running=false;t.frameIndex=1;t.points.clear();t.polygon.clear();
|
||||
t.value={roi.cx,roi.cy,1,0,0,0,0,false};
|
||||
if(!f.valid()||!std::isfinite(roi.cx)||!std::isfinite(roi.cy)||
|
||||
!std::isfinite(roi.width)||!std::isfinite(roi.height)||!std::isfinite(roi.angle)||
|
||||
roi.cx<0||roi.cx>1||roi.cy<0||roi.cy>1||roi.width<=0||roi.height<=0||roi.width>8||roi.height>8) {
|
||||
t.fail(TrackFailure::InvalidFrame);return false;
|
||||
}
|
||||
try {
|
||||
t.width=f.width;t.height=f.height;t.seed=roi;t.center={roi.cx*f.width,roi.cy*f.height};
|
||||
t.previous=Impl::gray8(f);if(t.previous.empty()){t.fail(TrackFailure::InvalidFrame);return false;}
|
||||
auto outline=t.mask;
|
||||
if(outline.empty())outline={{-.5f,-.5f},{.5f,-.5f},{.5f,.5f},{-.5f,.5f}};
|
||||
float c=std::cos(roi.angle),s=std::sin(roi.angle);
|
||||
for(auto p:outline){float x=p.x*roi.width*f.width,y=p.y*roi.height*f.height;
|
||||
if(!std::isfinite(x)||!std::isfinite(y)){t.fail(TrackFailure::InvalidFrame);return false;}
|
||||
t.polygon.emplace_back(t.center.x+c*x-s*y,t.center.y+s*x+c*y);}
|
||||
t.detect();t.value.features=int(t.points.size());t.value.inliers=t.value.features;
|
||||
if(t.points.size()<4){t.fail(TrackFailure::InsufficientTexture);return false;}
|
||||
t.running=true;t.value.valid=true;t.value.confidence=1;return true;
|
||||
} catch(const cv::Exception&){t.fail(TrackFailure::Backend);return false;}
|
||||
}
|
||||
|
||||
TrackResult OpenCVTracker::track(const GrayFrame& f) {
|
||||
auto& t=*impl_;
|
||||
if(!t.running||!f.valid()||f.width!=t.width||f.height!=t.height)return t.fail(TrackFailure::InvalidFrame);
|
||||
try {
|
||||
auto next=Impl::gray8(f);if(next.empty())return t.fail(TrackFailure::InvalidFrame);
|
||||
// The reset detected the seed (index zero). Advancing frames redetect
|
||||
// on indices 1,2,4… in the corresponding previous image.
|
||||
if(t.frameIndex<2||t.frameIndex%2==0)t.detect();
|
||||
t.value.features=int(t.points.size());t.value.matches=0;t.value.inliers=0;t.value.medianError=0;
|
||||
if(t.points.size()<4)return t.fail(TrackFailure::InsufficientTexture);
|
||||
std::vector<cv::Point2f> forward,backward;
|
||||
std::vector<uchar> fs,bs;std::vector<float> fe,be;
|
||||
cv::TermCriteria termination(cv::TermCriteria::COUNT|cv::TermCriteria::EPS,30,.01);
|
||||
cv::calcOpticalFlowPyrLK(t.previous,next,t.points,forward,fs,fe,{21,21},3,termination,0,1e-4);
|
||||
cv::calcOpticalFlowPyrLK(next,t.previous,forward,backward,bs,be,{21,21},3,termination,0,1e-4);
|
||||
std::vector<cv::Point2f> src,dst,movingSrc,movingDst;
|
||||
const float motionThreshold=std::max(t.width,t.height)*.01f;
|
||||
for(size_t i=0;i<t.points.size();++i) {
|
||||
// Checking both statuses also rejects a failed backward solve.
|
||||
if(!fs[i]||!bs[i]||cv::norm(backward[i]-t.points[i])>=1.)continue;
|
||||
src.push_back(t.points[i]);dst.push_back(forward[i]);
|
||||
if(cv::norm(forward[i]-t.points[i])>=motionThreshold){movingSrc.push_back(t.points[i]);movingDst.push_back(forward[i]);}
|
||||
}
|
||||
if(movingSrc.size()>src.size()/2){src.swap(movingSrc);dst.swap(movingDst);}
|
||||
t.value.matches=int(src.size());
|
||||
if(src.size()<4)return t.fail(TrackFailure::InsufficientMatches);
|
||||
for(size_t i=0;i<src.size();++i){src[i]-=t.center;dst[i]-=t.center;}
|
||||
cv::Mat inliers;
|
||||
cv::Mat affine=cv::estimateAffine2D(src,dst,inliers,cv::RANSAC,3.,2000,.99,10);
|
||||
if(affine.empty())return t.fail(TrackFailure::IncoherentMotion);
|
||||
double a=affine.at<double>(0,0),b=affine.at<double>(0,1),tx=affine.at<double>(0,2);
|
||||
double c=affine.at<double>(1,0),d=affine.at<double>(1,1),ty=affine.at<double>(1,2);
|
||||
double det=a*d-b*c,sx=std::hypot(a,c),sy=det/sx,angle=std::atan2(c,a);
|
||||
if(!cv::checkRange(affine)||!(det>0)||!(sx>0)||!(sy>0))return t.fail(TrackFailure::InvalidTransform);
|
||||
std::vector<float> errors;int accepted=0;
|
||||
for(size_t i=0;i<src.size();++i)if(inliers.at<uchar>(int(i))){
|
||||
++accepted;cv::Point2f q(float(a*src[i].x+b*src[i].y+tx),float(c*src[i].x+d*src[i].y+ty));
|
||||
errors.push_back(float(cv::norm(q-dst[i])));}
|
||||
t.value.inliers=accepted;
|
||||
if(accepted<4)return t.fail(TrackFailure::IncoherentMotion);
|
||||
std::nth_element(errors.begin(),errors.begin()+errors.size()/2,errors.end());
|
||||
t.value.medianError=errors[errors.size()/2];
|
||||
float confidence=std::clamp(float(accepted)/float(src.size())*std::exp(-t.value.medianError/3.f),0.f,1.f);
|
||||
// Product guards are deliberate: no silent successful empty/degenerate fit.
|
||||
double totalX=t.value.scaleX*sx,totalY=t.value.scaleY*sy;
|
||||
auto center=t.center+cv::Point2f(float(tx),float(ty));
|
||||
if(!std::isfinite(totalX)||!std::isfinite(totalY)||totalX<.1||totalX>10||totalY<.1||totalY>10||
|
||||
sx<.5||sx>2||sy<.5||sy>2||std::abs(angle)>.6)return t.fail(TrackFailure::InvalidTransform);
|
||||
if(confidence<.3f)return t.fail(TrackFailure::LowConfidence);
|
||||
if(center.x<0||center.x>=t.width||center.y<0||center.y>=t.height)return t.fail(TrackFailure::OutsideFrame);
|
||||
float cosA=float(std::cos(angle)),sinA=float(std::sin(angle));
|
||||
for(auto& p:t.polygon){auto q=p-t.center;p={center.x+float(sx)*q.x*cosA-float(sy)*q.y*sinA,
|
||||
center.y+float(sx)*q.x*sinA+float(sy)*q.y*cosA};}
|
||||
t.center=center;t.value.cx=center.x/t.width;t.value.cy=center.y/t.height;
|
||||
t.value.scaleX=float(totalX);t.value.scaleY=float(totalY);t.value.scale=std::sqrt(t.value.scaleX*t.value.scaleY);
|
||||
t.value.rotation+=float(angle);t.value.confidence=confidence;t.value.valid=true;t.value.failure=TrackFailure::None;
|
||||
t.points.clear();for(size_t i=0;i<dst.size();++i)t.points.push_back(dst[i]+(center-cv::Point2f(float(tx),float(ty))));
|
||||
t.previous=next;++t.frameIndex;return t.value;
|
||||
}catch(const cv::Exception&){return t.fail(TrackFailure::Backend);}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#include "../../大鱼调色/Plugin/MaskCore/DYOpenCVTracker.hpp"
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <chrono>
|
||||
|
||||
// Known analytic motion is the oracle. No target app or runtime is used.
|
||||
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 texture(float x,float y,uint32_t seed=0) {
|
||||
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,uint32_t seed=0) {
|
||||
dy::GrayFrame f{w,h,std::vector<float>(size_t(w)*h)};
|
||||
double cx=w*.5,cy=h*.5,c=std::cos(angle),s=std::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;
|
||||
f.pixels[y*w+x]=texture(float((c*dx+s*dy)/sx+cx),float((-s*dx+c*dy)/sy+cy),seed);
|
||||
}return f;
|
||||
}
|
||||
int main() {
|
||||
int failed=0,count=0;std::cout<<"{\"version\":\""<<dy::OpenCVTracker::version()<<"\",\"checks\":[";
|
||||
auto check=[&](const char*name,bool ok,double error=0){if(count++)std::cout<<",";failed+=!ok;
|
||||
std::cout<<"{\"name\":\""<<name<<"\",\"pass\":"<<(ok?"true":"false")<<",\"error\":"<<error<<"}";};
|
||||
check("pinned-public-opencv-version",std::string(dy::OpenCVTracker::version())=="4.5.1");
|
||||
{
|
||||
dy::OpenCVTracker t;auto f=frame(640,480);bool started=t.reset(f,{.5,.5,.85,.85,0});
|
||||
check("300-feature-capacity",started&&t.result().features==300,t.result().features);
|
||||
auto r=t.track(frame(640,480,2.25,-1.5,.025,1.025,.98));
|
||||
double error=std::hypot((r.cx-.5)*640-2.25,(r.cy-.5)*480+1.5);
|
||||
check("translation-rotation-independent-xy-scale",started&&r.valid&&error<.5&&std::abs(r.rotation-.025)<.004&&
|
||||
std::abs(r.scaleX-1.025)<.005&&std::abs(r.scaleY-.98)<.005,error);
|
||||
}
|
||||
{
|
||||
dy::OpenCVTracker t;auto f=frame(512,384);t.setMask({{.8f,-.5f},{1.8f,-.5f},{1.8f,.5f},{.8f,.5f}});
|
||||
bool ok=t.reset(f,{.35,.5,.2,.45,0});dy::TrackResult r=t.result();
|
||||
for(int i=1;i<=12&&ok;++i){r=t.track(frame(512,384,1.25*i,.5*i));ok=r.valid;}
|
||||
double error=std::hypot((r.cx-.35)*512-15,(r.cy-.5)*384-6);
|
||||
check("free-path-outside-creation-box-12-frame-subpixel",ok&&error<.7,error);
|
||||
}
|
||||
{
|
||||
dy::OpenCVTracker t;auto f=frame(640,480);bool ok=t.reset(f,{.5,.5,.65,.65,0});
|
||||
for(int i=0;i<8&&ok;++i)ok=t.track(f).valid;
|
||||
auto r=t.result();double error=std::hypot((r.cx-.5)*640,(r.cy-.5)*480);
|
||||
check("periodic-redetection-keeps-static-position",ok&&error<.05,error);
|
||||
r=t.track(frame(640,480,0,0,0,1,1,0x3344));
|
||||
check("unrelated-cut-stops-with-last-trusted-position",!r.valid&&!t.active()&&std::abs(r.cx-.5)*640<.05);
|
||||
dy::GrayFrame flat{640,480,std::vector<float>(640*480,.5f)};
|
||||
check("flat-mask-rejected",!t.reset(flat,{.5,.5,.7,.7,0}));
|
||||
}
|
||||
{
|
||||
dy::OpenCVTracker t;auto f=frame(640,480);bool ok=t.reset(f,{.5,.5,.9,.9,0});
|
||||
auto moving=f;
|
||||
for(int y=0;y<480;++y)for(int x=0;x<640;++x)
|
||||
moving.pixels[y*640+x]=texture(float(x-(x<460?8:0)),float(y));
|
||||
auto r=t.track(moving);double error=std::abs((r.cx-.5)*640-8);
|
||||
check("moving-majority-prefers-subject-over-static-background",ok&&r.valid&&error<.5&&r.matches<r.features*.85,error);
|
||||
}
|
||||
{
|
||||
dy::OpenCVTracker a,b;auto f=frame(640,480);bool ok=a.reset(f,{.3,.4,.3,.3,0})&&b.reset(f,{.7,.6,.3,.3,0});
|
||||
auto x=a.track(frame(640,480,5,2));auto y=b.track(frame(640,480,-3,-4));
|
||||
check("independent-tracker-objects-do-not-share-motion",ok&&x.valid&&y.valid&&std::abs((x.cx-.3)*640-5)<.5&&std::abs((y.cx-.7)*640+3)<.5);
|
||||
auto old=a.result();x=a.track({});check("invalid-frame-preserves-authored-geometry",!x.valid&&x.cx==old.cx&&x.cy==old.cy&&x.rotation==old.rotation);
|
||||
f.pixels[10]=std::numeric_limits<float>::quiet_NaN();
|
||||
check("nonfinite-source-rejected",!a.reset(f,{.5,.5,.4,.4,0}));
|
||||
}
|
||||
{
|
||||
auto begin=std::chrono::steady_clock::now();dy::OpenCVTracker t;bool ok=t.reset(frame(3840,2160),{.5,.5,.5,.5,0});
|
||||
auto r=t.track(frame(3840,2160,8,4));double error=std::hypot((r.cx-.5)*3840-8,(r.cy-.5)*2160-4);
|
||||
check("4k-complete-source-frame",ok&&r.valid&&error<.5,error);
|
||||
auto ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-begin).count();
|
||||
std::cerr<<"4K generated images plus tracking: "<<ms<<"ms\n";
|
||||
}
|
||||
std::cout<<"],\"pass\":"<<(failed?"false":"true")<<",\"count\":"<<count<<",\"runtimeTargetAppUsed\":false}\n";return failed?1:0;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"version": "4.5.1",
|
||||
"checks": [
|
||||
{
|
||||
"name": "pinned-public-opencv-version",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "300-feature-capacity",
|
||||
"pass": true,
|
||||
"error": 300
|
||||
},
|
||||
{
|
||||
"name": "translation-rotation-independent-xy-scale",
|
||||
"pass": true,
|
||||
"error": 0.00329193
|
||||
},
|
||||
{
|
||||
"name": "free-path-outside-creation-box-12-frame-subpixel",
|
||||
"pass": true,
|
||||
"error": 0.014753
|
||||
},
|
||||
{
|
||||
"name": "periodic-redetection-keeps-static-position",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "unrelated-cut-stops-with-last-trusted-position",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "flat-mask-rejected",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "moving-majority-prefers-subject-over-static-background",
|
||||
"pass": true,
|
||||
"error": 0.00237274
|
||||
},
|
||||
{
|
||||
"name": "independent-tracker-objects-do-not-share-motion",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "invalid-frame-preserves-authored-geometry",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "nonfinite-source-rejected",
|
||||
"pass": true,
|
||||
"error": 0
|
||||
},
|
||||
{
|
||||
"name": "4k-complete-source-frame",
|
||||
"pass": true,
|
||||
"error": 0.000107325
|
||||
}
|
||||
],
|
||||
"pass": true,
|
||||
"count": 12,
|
||||
"runtimeTargetAppUsed": false,
|
||||
"scope": "Known analytic generated images, public-source OpenCV 4.5.1. No FCP, target application, or user video runtime exercised.",
|
||||
"measuredTimingNote": "4K generated images plus tracking: 195.212ms",
|
||||
"checkedAt": "2026-11-04T19:14:24.907484+00:00",
|
||||
"build": {
|
||||
"version": "4.5.1",
|
||||
"commit": "1363496c1106606684d40447f5d1149b2c66a9f8",
|
||||
"archiveSHA256": "4356b76721786bff66536ecd1a36ac2e397b13a4ee1dec41f362fa2459e903db",
|
||||
"header": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/include",
|
||||
"linkResponse": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/link.rsp",
|
||||
"libraries": [
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libDayuOpenCVTracker.a",
|
||||
"bytes": 28520,
|
||||
"sha256": "2990cbe91559c7c9550d7b92accd50661273f0487d594b16ddf81dd6a946905b"
|
||||
},
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libopencv_calib3d.a",
|
||||
"bytes": 2529512,
|
||||
"sha256": "af39b65e6a15e552432c43a63ee9e151d12137e1f7566434e40a146093cb3b31"
|
||||
},
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libopencv_features2d.a",
|
||||
"bytes": 1007936,
|
||||
"sha256": "342a344f149c577dde10ea94b98b6823aafc4ba2971e19da31c07baed396a22f"
|
||||
},
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libopencv_flann.a",
|
||||
"bytes": 703176,
|
||||
"sha256": "f2b46997cf2dd0e6dfe66426331f9c04f73257118ce24849c33bd81937e21a37"
|
||||
},
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libopencv_video.a",
|
||||
"bytes": 594296,
|
||||
"sha256": "acb2e2b8f1e82679ed1e95eae8757439a1f980fa02aef11fed28d318617fb50c"
|
||||
},
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libopencv_imgproc.a",
|
||||
"bytes": 4144320,
|
||||
"sha256": "6986f20cfb856a09c1809d0a7f0879127172fc7c9e917d66935503e5e8e55338"
|
||||
},
|
||||
{
|
||||
"path": "/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/libs/libopencv_core.a",
|
||||
"bytes": 3866200,
|
||||
"sha256": "537b5dcdc596924d6fcc5299e9e463dc490ff7102c51f078a2da999d5e73e680"
|
||||
}
|
||||
],
|
||||
"sourceApplicationDependency": false
|
||||
},
|
||||
"sourceSHA256": {
|
||||
"tools/tracking/DYOpenCVTracker.cpp": "050450ed2ee5516e804c96fc9bd21a73a4deb288f0333442c1114d35023e2fb8",
|
||||
"tools/tracking/verify_opencv_tracker.cpp": "8e42b42fefd8fd25551b462f9cdb036ce617d3f1b4dabcd1e0acee2e0d050b5a",
|
||||
"大鱼调色/Plugin/MaskCore/DYOpenCVTracker.hpp": "f490aa33442bb49217b1cca55b0ffce724e8ffaf8e17d7afc53f6e468c86ec76",
|
||||
"ThirdParty/OpenCV/source-lock.json": "b60ac93510cd2380980722ecc6c1379d3f13446cda1608560b93b7db8fc21309"
|
||||
},
|
||||
"systemRuntimeDependencies": [
|
||||
"\t/usr/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.12)",
|
||||
"\t/System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate (compatibility version 1.0.0, current version 4.0.0)",
|
||||
"\t/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 2200.27.0)",
|
||||
"\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1359.0.0)"
|
||||
]
|
||||
}
|
||||
@@ -327,6 +327,7 @@
|
||||
shellPath = /bin/sh;
|
||||
shellScript = (
|
||||
"set -eu",
|
||||
"/usr/bin/python3 \"$SRCROOT/tools/build_tracking_opencv.py\" --resources \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/ThirdParty/OpenCV\"",
|
||||
"/usr/bin/python3 \"$SRCROOT/ColorManagement/build_runtime.py\" \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH\"",
|
||||
"/usr/bin/python3 \"$SRCROOT/tools/build_kernels.py\" --output \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/default.metallib\" --intermediates \"$DERIVED_FILE_DIR/DayuKernels\"",
|
||||
"/usr/bin/python3 - \"$SRCROOT/大鱼调色/Plugin/Resources\" \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH\" <<'PYBUILD'",
|
||||
@@ -381,6 +382,7 @@
|
||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
||||
OTHER_LDFLAGS = (
|
||||
"@/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/cms-runtime/bridge-link.rsp",
|
||||
"@/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/link.rsp",
|
||||
"$(inherited)",
|
||||
"-framework",
|
||||
Metal,
|
||||
@@ -417,6 +419,7 @@
|
||||
MACOSX_DEPLOYMENT_TARGET = 14.6;
|
||||
OTHER_LDFLAGS = (
|
||||
"@/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/cms-runtime/bridge-link.rsp",
|
||||
"@/Users/mac/Library/Caches/CodexBuilds/com.dayu.color/tracking-opencv/link.rsp",
|
||||
"$(inherited)",
|
||||
"-framework",
|
||||
Metal,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
@interface DYColorWorkspace : NSObject
|
||||
- (instancetype)initWithManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer library:(DYLUTLibrary *)library title:(NSString *)title;
|
||||
- (void)showRelativeToView:(NSView *)anchor;
|
||||
- (void)showPage:(NSString *)page maskKind:(NSNumber *)kind;
|
||||
- (void)close;
|
||||
@property(nonatomic,readonly) BOOL visible;
|
||||
@property(nonatomic,readonly) NSString *lastError;
|
||||
|
||||
+46
-24
@@ -4,9 +4,17 @@
|
||||
#import "DYLUTLibrary.h"
|
||||
#import "DYTheme.h"
|
||||
#import "DYToolState.h"
|
||||
#import "DYInspector.h"
|
||||
#import "DYManagedColor.h"
|
||||
#include "DYScopeMath.hpp"
|
||||
#include <cmath>
|
||||
|
||||
static NSButton *DYWorkspaceButton(NSString *title,id target,SEL action){NSButton *b=[DYThemeButton buttonWithTitle:title target:target action:action];b.bezelStyle=NSBezelStyleRounded;b.font=[NSFont systemFontOfSize:11];b.accessibilityLabel=title;return b;}
|
||||
@interface DYWorkspaceList:NSView @end
|
||||
@implementation DYWorkspaceList
|
||||
- (BOOL)isFlipped{return YES;}
|
||||
@end
|
||||
|
||||
@class DYWorkspaceRoot;
|
||||
@interface DYColorWorkspace (Internal)
|
||||
- (void)layoutWorkspace;
|
||||
@@ -65,7 +73,7 @@
|
||||
}
|
||||
@end
|
||||
|
||||
@interface DYColorWorkspace (){
|
||||
@interface DYColorWorkspace () <NSTableViewDataSource,NSTableViewDelegate,NSSplitViewDelegate>{
|
||||
id<PROAPIAccessing> _manager;
|
||||
DYRenderer *_renderer;DYLUTLibrary *_library;DYLUTBrowser *_browser;
|
||||
DYWorkspaceRoot *_root;NSView *_scopePane,*_lutPane;
|
||||
@@ -78,15 +86,21 @@
|
||||
NSString *_title,*_lastError;
|
||||
BOOL _visible,_opening,_closed,_closing;
|
||||
NSUInteger _session,_selectionID;
|
||||
NSView *_toolPane,*_editorHost,*_toolbar,*_maskPane;NSScrollView *_toolbarScroll,*_layerScroll,*_maskScroll,*_assignmentScroll;
|
||||
NSSplitView *_split;NSTableView *_layerTable;DYInspector *_toolEditor;NSView<DYWorkspaceMaskEditing> *_maskEditor;
|
||||
NSTextField *_selectionTitle;NSButton *_addMask,*_deleteLayer;
|
||||
NSArray *_layerRows;NSDictionary *_toolDocument;NSString *_selectedNode,*_selectedMask,*_maskNode,*_editorNode;
|
||||
id<PROAPIAccessing> _lutTarget;CMTime _toolTime;BOOL _refreshingStack,_sizingSplit;CGFloat _splitFraction;
|
||||
}
|
||||
@end
|
||||
@implementation DYColorWorkspace
|
||||
#include "DYWorkspaceTools.inc.h"
|
||||
- (instancetype)initWithManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer library:(DYLUTLibrary *)library title:(NSString *)title{
|
||||
if((self=[super init])){
|
||||
_manager=[manager retain];_renderer=[renderer retain];_library=[library retain];_title=[(title.length?title:@"大鱼调色")copy];_lifetime=[DYWorkspaceLifetime new];_lifetime.owner=self;
|
||||
_root=[[DYWorkspaceRoot alloc]initWithFrame:NSMakeRect(0,0,1000,650)];_root.identifier=@"DYColorWorkspace";_root.owner=self;_root.accessibilityLabel=@"大鱼调色辅助工作区";
|
||||
_root=[[DYWorkspaceRoot alloc]initWithFrame:NSMakeRect(0,0,1120,360)];_root.identifier=@"DYColorWorkspace";_root.owner=self;_root.accessibilityLabel=@"大鱼调色控制面板";
|
||||
_heading=[[DYThemeLabel alloc]init];_heading.stringValue=[NSString stringWithFormat:@"%@ · 辅助工作区",_title];_heading.font=[NSFont systemFontOfSize:14 weight:NSFontWeightSemibold];[_root addSubview:_heading];
|
||||
_pages=[[NSSegmentedControl alloc]init];_pages.segmentCount=2;[_pages setLabel:@"示波器" forSegment:0];[_pages setLabel:@"风格1 LUT" forSegment:1];_pages.selectedSegment=0;_pages.target=self;_pages.action=@selector(pageChanged:);_pages.accessibilityLabel=@"辅助工作区页面";[_root addSubview:_pages];
|
||||
_pages=[[NSSegmentedControl alloc]init];_pages.segmentCount=4;for(NSInteger i=0;i<4;i++)[_pages setLabel:@[@"调整",@"蒙版",@"LUT",@"示波器"][i]forSegment:i];_pages.selectedSegment=0;_pages.target=self;_pages.action=@selector(pageChanged:);_pages.accessibilityLabel=@"控制面板页面";[_root addSubview:_pages];
|
||||
_close=[[DYThemeButton alloc]init];_close.title=@"关闭";_close.target=self;_close.action=@selector(closePressed:);_close.bezelStyle=NSBezelStyleRounded;[_root addSubview:_close];
|
||||
_scopePane=[[DYWorkspaceRoot alloc]init];_scopePane.clipsToBounds=YES;[_root addSubview:_scopePane];_lutPane=[[NSView alloc]init];[_root addSubview:_lutPane];_lutPane.hidden=YES;
|
||||
_scopeMode=[[DYThemePopUpButton alloc]init];[_scopeMode addItemsWithTitles:@[@"亮度波形",@"RGB 分列",@"直方图"]];_scopeMode.target=self;_scopeMode.action=@selector(scopeModeChanged:);_scopeMode.accessibilityLabel=@"示波器类型";[_scopePane addSubview:_scopeMode];
|
||||
@@ -98,12 +112,14 @@
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(scopeChanged:) name:@"DYScopeDidChange" object:_renderer];
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(previewChanged:) name:@"DYPreviewDidChange" object:_renderer];
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(themeChanged:) name:DYThemeDidChange object:nil];
|
||||
[self buildToolWorkspace];
|
||||
[self updatePalette];[self scopeChanged:nil];[self layoutWorkspace];
|
||||
}return self;
|
||||
}
|
||||
- (void)dealloc{
|
||||
[self close];_lifetime.owner=nil;[NSNotificationCenter.defaultCenter removeObserver:self];_root.owner=nil;
|
||||
[_manager release];[_renderer release];[_library release];[_browser release];[_root release];[_scopePane release];[_lutPane release];[_plot release];[_heading release];[_description release];[_status release];[_lutExplanation release];[_pages release];[_scopeMode release];[_close release];[_hostScopes release];[_title release];[_lastError release];[_lifetime release];[super dealloc];
|
||||
[_manager release];[_renderer release];[_library release];[_browser release];[_root release];[_scopePane release];[_lutPane release];[_plot release];[_heading release];[_description release];[_status release];[_lutExplanation release];[_pages release];[_scopeMode release];[_close release];[_hostScopes release];[_title release];[_lastError release];[_lifetime release];
|
||||
[_toolPane release];[_editorHost release];[_toolbar release];[_maskPane release];[_toolbarScroll release];[_layerScroll release];[_maskScroll release];[_assignmentScroll release];[_split release];[_layerTable release];[_toolEditor release];[_maskEditor release];[_selectionTitle release];[_addMask release];[_deleteLayer release];[_layerRows release];[_toolDocument release];[_selectedNode release];[_selectedMask release];[_maskNode release];[_editorNode release];[(id)_lutTarget release];[super dealloc];
|
||||
}
|
||||
- (BOOL)visible{return _visible||_opening;}
|
||||
- (NSString *)lastError{return _lastError;}
|
||||
@@ -123,8 +139,8 @@
|
||||
void(^reply)(FxXPView *,NSError *)=^(FxXPView *parent,NSError *error){void(^attach)(void)=^{DYColorWorkspace *owner=token.owner;if(!owner||owner->_closed||owner->_session!=session)return;owner->_opening=NO;
|
||||
if(!parent){[owner reportError:error.localizedDescription?:@"宿主未能创建辅助窗口"];return;}[owner attachToParent:parent];
|
||||
};if(NSThread.isMainThread)attach();else dispatch_sync(dispatch_get_main_queue(),attach);};
|
||||
if(sizable)[sizable remoteWindowWithMinimumSize:NSMakeSize(760,520) maximumSize:NSMakeSize(1800,1200) reply:reply];
|
||||
else if(remote)[remote remoteWindowOfSize:NSMakeSize(1000,650) reply:reply];
|
||||
if(sizable)[sizable remoteWindowWithMinimumSize:NSMakeSize(720,300) maximumSize:NSMakeSize(2400,1200) reply:reply];
|
||||
else if(remote)[remote remoteWindowOfSize:NSMakeSize(1120,360) reply:reply];
|
||||
else{_opening=NO;[self reportError:@"当前宿主未提供外部工具窗口接口"];}
|
||||
}@finally{[action endAction:self];}
|
||||
}
|
||||
@@ -132,7 +148,7 @@
|
||||
if(_remoteParent!=parent){if(_remoteParent)for(NSNotificationName name in @[NSViewFrameDidChangeNotification,NSViewBoundsDidChangeNotification])[NSNotificationCenter.defaultCenter removeObserver:self name:name object:_remoteParent];_remoteParent=parent;
|
||||
parent.postsFrameChangedNotifications=YES;parent.postsBoundsChangedNotifications=YES;for(NSNotificationName name in @[NSViewFrameDidChangeNotification,NSViewBoundsDidChangeNotification])[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(parentChanged:) name:name object:parent];
|
||||
}
|
||||
[_root removeFromSuperview];_root.frame=parent.bounds;_root.autoresizingMask=NSViewWidthSizable|NSViewHeightSizable;[parent addSubview:_root];_visible=YES;_root.hidden=NO;[_renderer setScopeEnabled:_pages.selectedSegment==0];[self scopeChanged:nil];[self parentChanged:nil];
|
||||
[_root removeFromSuperview];_root.frame=parent.bounds;_root.autoresizingMask=NSViewWidthSizable|NSViewHeightSizable;[parent addSubview:_root];_visible=YES;_root.hidden=NO;[self refreshToolWorkspace:nil];[self pageChanged:nil];[self parentChanged:nil];
|
||||
DYWorkspaceLifetime *token=_lifetime;NSUInteger session=_session;dispatch_async(dispatch_get_main_queue(),^{DYColorWorkspace *owner=token.owner;if(!owner||owner->_closed||owner->_session!=session)return;NSWindow *window=owner->_root.window;
|
||||
if(window!=owner->_presentationWindow){if(owner->_presentationWindow)[NSNotificationCenter.defaultCenter removeObserver:owner name:NSWindowWillCloseNotification object:owner->_presentationWindow];[owner->_presentationWindow release];owner->_presentationWindow=[window retain];if(window)[NSNotificationCenter.defaultCenter addObserver:owner selector:@selector(remoteClosed:) name:NSWindowWillCloseNotification object:window];}
|
||||
[owner parentChanged:nil];
|
||||
@@ -145,12 +161,17 @@
|
||||
}
|
||||
- (void)layoutWorkspace{
|
||||
CGFloat w=_root.bounds.size.width,h=_root.bounds.size.height;
|
||||
_heading.frame=NSMakeRect(18,14,MAX(100,w-360),23);_pages.frame=NSMakeRect(MAX(150,w-320),12,228,27);_close.frame=NSMakeRect(MAX(0,w-80),12,64,27);
|
||||
_scopePane.frame=NSMakeRect(0,52,w,MAX(1,h-52));_lutPane.frame=NSMakeRect(0,80,w,MAX(1,h-80));_lutExplanation.frame=NSMakeRect(18,52,MAX(1,w-36),24);
|
||||
_heading.frame=NSMakeRect(12,9,MAX(100,w-430),23);_heading.stringValue=@"大鱼调色 · 控制面板";_pages.frame=NSMakeRect(MAX(150,w-398),7,306,27);_close.frame=NSMakeRect(MAX(0,w-80),7,64,27);
|
||||
_toolbarScroll.frame=NSMakeRect(8,39,MAX(1,w-16),40);
|
||||
_split.frame=NSMakeRect(0,80,w,MAX(1,h-80));[self layoutToolWorkspace];
|
||||
_scopePane.frame=_editorHost.bounds;_lutPane.frame=NSMakeRect(0,25,_editorHost.bounds.size.width,MAX(1,_editorHost.bounds.size.height-25));_lutExplanation.frame=NSMakeRect(8,2,MAX(1,_editorHost.bounds.size.width-16),22);
|
||||
w=_scopePane.bounds.size.width;
|
||||
CGFloat ph=_scopePane.bounds.size.height;_scopeMode.frame=NSMakeRect(18,0,160,27);_hostScopes.frame=NSMakeRect(184,0,122,27);_description.frame=NSMakeRect(320,4,MAX(1,w-338),22);_plot.frame=NSMakeRect(18,39,MAX(1,w-36),MAX(1,ph-114));_status.frame=NSMakeRect(18,MAX(40,ph-64),MAX(1,w-36),58);
|
||||
}
|
||||
- (void)pageChanged:(id)sender{
|
||||
BOOL lut=_pages.selectedSegment==1;_scopePane.hidden=lut;_lutPane.hidden=!lut;_lutExplanation.hidden=!lut;[_renderer setScopeEnabled:_visible&&!lut];if(lut)[self ensureBrowser];else[self scopeChanged:nil];
|
||||
if(_pages.selectedSegment==2)[self bindLUTTarget];
|
||||
NSInteger page=_pages.selectedSegment;_scopePane.hidden=page!=3;_lutPane.hidden=page!=2;_lutExplanation.hidden=page!=2;_toolEditor.hidden=page!=0;_maskPane.hidden=page!=1;
|
||||
[_renderer setScopeEnabled:_visible&&page==3];if(page==2)[self ensureBrowser];if(page==3)[self scopeChanged:nil];[self layoutWorkspace];
|
||||
}
|
||||
- (void)toggleHostScopes:(id)sender{
|
||||
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];NSError *error=nil;BOOL done=NO;if(action){[action startAction:self];@try{id<FxCommandAPI> commands=[_manager apiForProtocol:@protocol(FxCommandAPI)];done=[commands performCommand:kFxCommand_ToggleWaveforms error:&error];}@finally{[action endAction:self];}}
|
||||
@@ -165,27 +186,27 @@
|
||||
_status.stringValue=[NSString stringWithFormat:@"%@\n%@ · 有效 %@ · 透明 %@ · 非有限 %@ · 超出 −10%%/110%% %@/%@",([data[@"converted"]boolValue]?@"最终画面 · sRGB 显示参考;非 HDR / IRE 精密测量":@"空间未知:显示宿主 RGB 数值参考;不用于 HDR / IRE 测量"),frame,data[@"valid"],data[@"transparent"],data[@"nonfinite"],data[@"below"],data[@"above"]];
|
||||
}else _status.stringValue=@"示波器采集当前效果的最终输出。播放、移动时间线或调整颜色后更新;透明像素不计入。";
|
||||
}
|
||||
- (void)previewChanged:(NSNotification *)notification{if(_visible&&_pages.selectedSegment==1)[_browser updatePreview:[_renderer lookLUTPreview]];}
|
||||
- (void)previewChanged:(NSNotification *)notification{if(_visible&&_pages.selectedSegment==2)[_browser updatePreview:[_renderer lookLUTPreview]];}
|
||||
- (void)themeChanged:(NSNotification *)notification{[self updatePalette];}
|
||||
- (void)updatePalette{
|
||||
[_root setNeedsDisplay:YES];for(NSTextField *label in @[_heading,_description,_status,_lutExplanation])label.textColor=DYThemeColor(label==_heading?@"text":@"secondary");[_browser updatePalette:DYThemePalette()];
|
||||
}
|
||||
- (void)ensureBrowser{
|
||||
if(_browser.visible)return;[_browser release];_browser=nil;id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action){[self reportError:@"宿主暂时无法读取风格1"];return;}
|
||||
NSString *selected=nil;[action startAction:self];@try{selected=[DYReadAssets(_manager,action.currentTime).paths[@"look0"]copy];}@finally{[action endAction:self];}
|
||||
if(_browser.visible)return;[_browser release];_browser=nil;id<FxCustomParameterActionAPI_v4> action=[[self lutManager] apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!action){[self reportError:@"宿主暂时无法读取风格1"];return;}
|
||||
NSString *selected=nil;[action startAction:self];@try{selected=[DYReadAssets([self lutManager],action.currentTime).paths[@"look0"]copy];}@finally{[action endAction:self];}
|
||||
DYWorkspaceLifetime *token=_lifetime;
|
||||
_browser=[[DYLUTBrowser alloc]initWithLibrary:_library preview:[_renderer lookLUTPreview] selectedPath:selected palette:DYThemePalette() selection:^NSProgress *(NSString *path,void(^completion)(NSError *)){DYColorWorkspace *owner=token.owner;if(owner&&!owner->_closed)return [owner selectLUT:path completion:completion];if(completion)completion([NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]);return nil;}];[selected release];
|
||||
[_browser embedInView:_lutPane close:^{DYColorWorkspace *owner=token.owner;if(owner&&!owner->_closing&&!owner->_closed){owner->_pages.selectedSegment=0;[owner pageChanged:nil];}}];
|
||||
}
|
||||
- (NSDictionary *)selectionContextAtTime:(CMTime)time{
|
||||
id<PROAPIAccessing> host=[_manager isKindOfClass:DYToolManager.class]?[(DYToolManager*)_manager host]:_manager;
|
||||
DYAssetState *local=DYReadAssets(_manager,time),*global=DYReadAssets(host,time);DYUniforms uniforms;DYReadUniforms(host,time,&uniforms);
|
||||
id<PROAPIAccessing> host=[[self lutManager] isKindOfClass:DYToolManager.class]?[(DYToolManager*)[self lutManager] host]:[self lutManager];
|
||||
DYAssetState *local=DYReadAssets([self lutManager],time),*global=DYReadAssets(host,time);DYUniforms uniforms;DYReadUniforms(host,time,&uniforms);
|
||||
NSMutableDictionary *cm=[NSMutableDictionary dictionary];for(NSDictionary *descriptor in DYDescriptors()){NSString *key=descriptor[@"key"];NSInteger offset=[descriptor[@"offset"]integerValue];if(offset>=0&&([key hasPrefix:@"cm"]||[key isEqual:@"inputProfile"]||[key isEqual:@"inputSectionEnabled"]))cm[key]=@(*(float*)((uint8_t*)&uniforms+offset));}
|
||||
NSDictionary *state=@{@"look":local.paths[@"look0"]?:NSNull.null,@"colorManagement":global.colorManagement?:NSNull.null,@"inputPath":global.paths[@"input"]?:NSNull.null,@"colorParameters":cm};
|
||||
return @{@"time":[NSData dataWithBytes:&time length:sizeof(time)],@"state":state};
|
||||
}
|
||||
- (NSDictionary *)selectionContext{
|
||||
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(!action)return nil;NSDictionary *context=nil;[action startAction:self];@try{context=[[self selectionContextAtTime:action.currentTime]copy];}@finally{[action endAction:self];}return [context autorelease];
|
||||
id<FxCustomParameterActionAPI_v4> action=[[self lutManager] apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!action)return nil;NSDictionary *context=nil;[action startAction:self];@try{context=[[self selectionContextAtTime:action.currentTime]copy];}@finally{[action endAction:self];}return [context autorelease];
|
||||
}
|
||||
- (NSProgress *)selectLUT:(NSString *)path completion:(void(^)(NSError *))completion{
|
||||
[_selectionTask cancel];[_selectionTask release];_selectionTask=nil;NSUInteger selection=++_selectionID,session=_session;DYWorkspaceLifetime *token=_lifetime;NSDictionary *expected=[self selectionContext];
|
||||
@@ -200,24 +221,24 @@
|
||||
if(path.length&&(!path.isAbsolutePath||![[path.pathExtension lowercaseString]isEqual:@"cube"])){
|
||||
if(error)*error=[NSError errorWithDomain:@"com.dayu.color.workspace" code:1 userInfo:@{NSLocalizedDescriptionKey:@"LUT 必须是完整路径的 .cube 文件,原来的选择已保留"}];return NO;
|
||||
}
|
||||
id<FxCustomParameterActionAPI_v4> action=[self actionAPI];BOOL written=NO;NSString *failure=nil;if(!action)failure=@"宿主暂时无法应用 LUT,请重新选择当前效果后重试";
|
||||
else{id<FxCustomParameterActionAPI_v4> outer=[_manager isKindOfClass:DYToolManager.class]?[[(DYToolManager*)_manager host]apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]:nil;
|
||||
id<FxCustomParameterActionAPI_v4> action=[[self lutManager] apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];BOOL written=NO;NSString *failure=nil;if(!action)failure=@"宿主暂时无法应用 LUT,请重新选择当前效果后重试";
|
||||
else{id<FxCustomParameterActionAPI_v4> outer=[[self lutManager] isKindOfClass:DYToolManager.class]?[[(DYToolManager*)[self lutManager] host]apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)]:nil;
|
||||
if(outer)[outer startAction:self];[action startAction:self];id<FxUndoAPI> undo=nil;BOOL grouped=NO;NSDictionary *wantedPaths=nil;CMTime commitTime=kCMTimeInvalid;@try{
|
||||
CMTime time=action.currentTime,original=kCMTimeInvalid;NSData *encodedTime=expected[@"time"];if(encodedTime.length==sizeof(original))memcpy(&original,encodedTime.bytes,sizeof(original));
|
||||
if(!CMTIME_IS_NUMERIC(time)||!CMTIME_IS_NUMERIC(original)||CMTimeCompare(time,original)!=0)failure=@"播放头已改变,未将先前的 LUT 选择写到新画面;请重新选择";
|
||||
else if(![[self selectionContextAtTime:time][@"state"]isEqual:expected[@"state"]])failure=@"载入期间风格1或色彩管理已改变,已保留最新设置;请重新选择 LUT";
|
||||
if(!failure&&[_manager isKindOfClass:DYToolManager.class]){DYToolManager *node=(DYToolManager*)_manager;if(![node.type isEqual:@"look"]||!DYToolWithID(DYReadTools(node.host,time).document,node.nodeID)){failure=@"此风格图层已删除或不再可编辑,未修改其它图层";}}
|
||||
if(!failure&&![_manager isKindOfClass:DYToolManager.class]&&DYBaseToolRemoved(DYReadTools(_manager,time).document,@"look"))failure=@"基础风格工具已移除,请先恢复风格工具;未修改其它图层";
|
||||
if(!failure){DYAssetState *assets=[[DYReadAssets(_manager,time)copy]autorelease];if(!assets)assets=[[[DYAssetState alloc]init]autorelease];NSMutableDictionary *paths=[[assets.paths mutableCopy]autorelease]?:[NSMutableDictionary dictionary];if(path.length)paths[@"look0"]=path;else[paths removeObjectForKey:@"look0"];assets.paths=paths;
|
||||
wantedPaths=assets.paths;commitTime=time;undo=[_manager apiForProtocol:@protocol(FxUndoAPI)];grouped=[undo startUndoGroup:@"选择风格1 LUT"];written=DYWriteAssets(_manager,assets,time);if(!written)failure=@"宿主未接受此 LUT,原来的选择已保留";
|
||||
if(!failure&&[[self lutManager] isKindOfClass:DYToolManager.class]){DYToolManager *node=(DYToolManager*)[self lutManager];if(![node.type isEqual:@"look"]||!DYToolWithID(DYReadTools(node.host,time).document,node.nodeID)){failure=@"此风格图层已删除或不再可编辑,未修改其它图层";}}
|
||||
if(!failure&&![[self lutManager] isKindOfClass:DYToolManager.class]&&DYBaseToolRemoved(DYReadTools([self lutManager],time).document,@"look"))failure=@"基础风格工具已移除,请先恢复风格工具;未修改其它图层";
|
||||
if(!failure){DYAssetState *assets=[[DYReadAssets([self lutManager],time)copy]autorelease];if(!assets)assets=[[[DYAssetState alloc]init]autorelease];NSMutableDictionary *paths=[[assets.paths mutableCopy]autorelease]?:[NSMutableDictionary dictionary];if(path.length)paths[@"look0"]=path;else[paths removeObjectForKey:@"look0"];assets.paths=paths;
|
||||
wantedPaths=assets.paths;commitTime=time;undo=[[self lutManager] apiForProtocol:@protocol(FxUndoAPI)];grouped=[undo startUndoGroup:@"选择风格1 LUT"];written=DYWriteAssets([self lutManager],assets,time);if(!written)failure=@"宿主未接受此 LUT,原来的选择已保留";
|
||||
}
|
||||
}@finally{if(outer){[action endAction:self];
|
||||
// DYToolManager stages custom assets and commits its host document in
|
||||
// endAction. Its earlier setter BOOL does not report that final write.
|
||||
// Read the actual target while the outer host action still grants access.
|
||||
if(written){DYToolManager *node=(DYToolManager*)_manager;NSDictionary *stored=DYToolWithID(DYReadTools(node.host,commitTime).document,node.nodeID);if(!stored||![stored[@"paths"]isEqual:wantedPaths]){written=NO;failure=@"宿主未保存此风格图层的 LUT,原来的选择已保留;请重试";}}
|
||||
if(written){DYToolManager *node=(DYToolManager*)[self lutManager];NSDictionary *stored=DYToolWithID(DYReadTools(node.host,commitTime).document,node.nodeID);if(!stored||![stored[@"paths"]isEqual:wantedPaths]){written=NO;failure=@"宿主未保存此风格图层的 LUT,原来的选择已保留;请重试";}}
|
||||
if(grouped)[undo endUndoGroup];[outer endAction:self];}else{if(grouped)[undo endUndoGroup];[action endAction:self];}}}
|
||||
if(written){if(path.length)[_library recordUsedPath:path];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:[_manager isKindOfClass:DYToolManager.class]?[(DYToolManager*)_manager host]:_manager];}
|
||||
if(written){if(path.length)[_library recordUsedPath:path];[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:[[self lutManager] isKindOfClass:DYToolManager.class]?[(DYToolManager*)[self lutManager] host]:[self lutManager]];}
|
||||
else if(error)*error=[NSError errorWithDomain:@"com.dayu.color.workspace" code:1 userInfo:@{NSLocalizedDescriptionKey:failure?:@"LUT 操作未完成"}];return written;
|
||||
}
|
||||
- (void)closePressed:(id)sender{[self close];}
|
||||
@@ -225,6 +246,7 @@
|
||||
- (void)close{
|
||||
if(_closed)return;BOOL hadPresentation=_visible||_opening||_remoteParent;_closed=YES;_visible=NO;_opening=NO;_session++;_selectionID++;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil;[_renderer setScopeEnabled:NO];
|
||||
BOOL wasClosing=_closing;_closing=YES;[_browser close];[_browser release];_browser=nil;
|
||||
[_toolEditor removeFromSuperview];[_toolEditor release];_toolEditor=nil;[_editorNode release];_editorNode=nil;_maskScroll.documentView=nil;[_maskEditor release];_maskEditor=nil;[_maskNode release];_maskNode=nil;
|
||||
if(_remoteParent)for(NSNotificationName name in @[NSViewFrameDidChangeNotification,NSViewBoundsDidChangeNotification])[NSNotificationCenter.defaultCenter removeObserver:self name:name object:_remoteParent];_remoteParent=nil;
|
||||
if(_presentationWindow)[NSNotificationCenter.defaultCenter removeObserver:self name:NSWindowWillCloseNotification object:_presentationWindow];[_presentationWindow release];_presentationWindow=nil;[_root removeFromSuperview];
|
||||
if(hadPresentation&&!wasClosing){id<FxCustomParameterActionAPI_v4> action=[self actionAPI];if(action){[action startAction:self];@try{id<FxRemoteWindowAPI_v3> api=[_manager apiForProtocol:@protocol(FxRemoteWindowAPI_v3)];[api closeRemoteWindow];}@finally{[action endAction:self];}}}_closing=wasClosing;
|
||||
|
||||
@@ -501,6 +501,7 @@ 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 "DYSharedMaskDiagnostics.inc.h"
|
||||
#include "DYWorkspaceDiagnostics.inc.h"
|
||||
#include "DYToolInsertionDiagnostics.inc.h"
|
||||
#include "DYToolDeletionDiagnostics.inc.h"
|
||||
|
||||
@@ -2,9 +2,21 @@
|
||||
#import <FxPlug/FxPlugSDK.h>
|
||||
@class DYRenderer;
|
||||
|
||||
@protocol DYWorkspaceMaskEditing <NSObject>
|
||||
@property(nonatomic) BOOL workspaceMode;
|
||||
@property(nonatomic,readonly) CGFloat contentHeight;
|
||||
@property(nonatomic,readonly) NSString *selectedMaskID;
|
||||
- (void)refreshWithDocument:(NSDictionary *)document time:(CMTime)time;
|
||||
- (void)addMenu:(NSView *)anchor;
|
||||
- (void)selectMaskID:(NSString *)maskID;
|
||||
@end
|
||||
NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing> manager,NSString *nodeID);
|
||||
|
||||
/// Per-instance custom inspector. All host reads and edits are bracketed actions.
|
||||
@interface DYInspector : NSView
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager;
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer;
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer workspaceType:(NSString *)type;
|
||||
- (void)refresh;
|
||||
- (void)removeWorkspaceTool;
|
||||
@end
|
||||
+51
-21
@@ -162,9 +162,12 @@ static NSArray *DYAccessibleSubviews(NSView *view, BOOL visibleOnly) {
|
||||
- (void)scrollWheel:(NSEvent*)event{if(!self.hasVerticalScroller){[self.nextResponder scrollWheel:event];return;}[super scrollWheel:event];}
|
||||
@end
|
||||
|
||||
@interface DYCard : DYFlippedView @end
|
||||
@interface DYCard : DYFlippedView
|
||||
@property(nonatomic) BOOL workspaceMode;
|
||||
@end
|
||||
@implementation DYCard
|
||||
- (void)drawRect:(NSRect)rect {
|
||||
if(_workspaceMode)return;
|
||||
NSBezierPath *path=[NSBezierPath bezierPathWithRoundedRect:NSInsetRect(self.bounds,.5,.5) xRadius:11 yRadius:11];
|
||||
if(DYThemeUsesRelief())DYDrawSoftControl(NSInsetRect(self.bounds,3,3),12,NO,NO,NO);
|
||||
else{DYDrawThemeSurface(path,YES);[DYThemeColor(@"border")setStroke];path.lineWidth=1;[path stroke];}
|
||||
@@ -234,11 +237,13 @@ static NSArray *DYPresentationSections(void) {
|
||||
NSData *_histogram;
|
||||
NSButton *_histogramToggle;
|
||||
NSInteger _channel;
|
||||
BOOL _fixedWorkspaceChannel;
|
||||
NSString *_dragXKey,*_dragYKey;
|
||||
}
|
||||
@property(nonatomic,assign) id<DYGraphicDelegate> delegate;
|
||||
- (void)setValues:(NSDictionary *)values;
|
||||
- (void)setHistogram:(NSData *)histogram;
|
||||
- (void)setFixedWorkspaceChannel:(NSInteger)channel;
|
||||
@end
|
||||
|
||||
@implementation DYCurvePanel
|
||||
@@ -256,10 +261,11 @@ static NSArray *DYPresentationSections(void) {
|
||||
- (BOOL)acceptsFirstResponder { return YES; }
|
||||
- (void)setValues:(NSDictionary *)values { [_values release];_values=[values copy];[self setNeedsDisplay:YES]; }
|
||||
- (void)layout { [super layout];_channels.frame=NSMakeRect(12,4,MAX(100,self.bounds.size.width-112),24);_histogramToggle.frame=NSMakeRect(self.bounds.size.width-88,5,80,22); }
|
||||
- (void)setFixedWorkspaceChannel:(NSInteger)channel {_fixedWorkspaceChannel=YES;_channel=channel;_channels.hidden=YES;_histogramToggle.hidden=YES;}
|
||||
- (void)setHistogram:(NSData *)histogram {if(_histogram==histogram)return;[_histogram release];_histogram=[histogram copy];const DYHistogram *h=_histogram.length==sizeof(DYHistogram)?(const DYHistogram*)_histogram.bytes:nullptr;_histogramToggle.accessibilityValueDescription=h&&h->samples?[NSString stringWithFormat:@"分析画面,%u 个有效采样",h->samples]:@"等待画面;请移动播放头";[self setNeedsDisplay:YES];}
|
||||
- (void)histogramToggled:(id)sender {[self setNeedsDisplay:YES];}
|
||||
- (void)channelChanged:(NSSegmentedControl *)sender { _channel=sender.selectedSegment;[self setNeedsDisplay:YES]; }
|
||||
- (NSRect)plotRect { return NSMakeRect(16,37,MAX(50,self.bounds.size.width-32),MAX(50,self.bounds.size.height-76)); }
|
||||
- (NSRect)plotRect { return _fixedWorkspaceChannel?NSMakeRect(8,8,MAX(50,self.bounds.size.width-16),MAX(50,self.bounds.size.height-42)):NSMakeRect(16,37,MAX(50,self.bounds.size.width-32),MAX(50,self.bounds.size.height-76)); }
|
||||
- (NSArray *)slots {
|
||||
NSMutableArray *result=[NSMutableArray array];
|
||||
NSInteger n=_channel==0?4:2;
|
||||
@@ -333,7 +339,7 @@ static NSArray *DYPresentationSections(void) {
|
||||
for(NSDictionary *point in points) {NSPoint q=[self positionOfPoint:point];[color setFill];[[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(q.x-4,q.y-4,8,8)] fill];[DYInk() setStroke];[[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(q.x-4,q.y-4,8,8)] stroke];}
|
||||
NSDictionary *axis=@{NSFontAttributeName:[NSFont monospacedDigitSystemFontOfSize:8 weight:NSFontWeightRegular],NSForegroundColorAttributeName:DYThemeColor(@"secondary")};
|
||||
[@"0" drawAtPoint:NSMakePoint(NSMinX(r),NSMaxY(r)+2) withAttributes:axis];[@"128" drawAtPoint:NSMakePoint(NSMidX(r)-7,NSMaxY(r)+2) withAttributes:axis];[@"255" drawAtPoint:NSMakePoint(NSMaxX(r)-14,NSMaxY(r)+2) withAttributes:axis];
|
||||
[@"点击添加 · 拖动调整 · 双击删除" drawAtPoint:NSMakePoint(16,self.bounds.size.height-16) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:9],NSForegroundColorAttributeName:DYThemeColor(@"secondary")}];
|
||||
[(_fixedWorkspaceChannel?@[@"主控",@"红色",@"绿色",@"蓝色"][_channel]:@"点击添加 · 拖动调整 · 双击删除") drawAtPoint:NSMakePoint(16,self.bounds.size.height-16) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:10],NSForegroundColorAttributeName:DYThemeColor(@"secondary")}];
|
||||
}
|
||||
- (void)sendValues:(NSDictionary *)values {
|
||||
NSMutableDictionary *merged=[[_values mutableCopy] autorelease];[merged addEntriesFromDictionary:values];[self setValues:merged];
|
||||
@@ -363,6 +369,11 @@ static NSArray *DYPresentationSections(void) {
|
||||
- (void)keyDown:(NSEvent *)event { if(event.keyCode==51&&_dragXKey)[self sendValues:@{_dragXKey:@(-1),_dragYKey:@0}];else[super keyDown:event]; }
|
||||
@end
|
||||
|
||||
@interface DYWorkspaceCurveStrip : DYFlippedView @end
|
||||
@implementation DYWorkspaceCurveStrip
|
||||
- (void)layout {[super layout];CGFloat width=self.bounds.size.width/4;NSInteger i=0;for(NSView *v in self.subviews)v.frame=NSMakeRect(i++*width,0,width,self.bounds.size.height);}
|
||||
@end
|
||||
|
||||
static NSImage *DYWheelImage(void) {
|
||||
static NSImage *image;static dispatch_once_t once;
|
||||
dispatch_once(&once,^{
|
||||
@@ -438,6 +449,10 @@ static NSImage *DYWheelImage(void) {
|
||||
|
||||
#include "DYNewPanels.inc.h"
|
||||
#include "DYMaskPanel.inc.h"
|
||||
NSView<DYWorkspaceMaskEditing> *DYCreateWorkspaceMaskEditor(id<PROAPIAccessing> manager,NSString *nodeID) {
|
||||
DYToolMaskPanel *panel=[[[DYToolMaskPanel alloc]initWithManager:manager nodeID:nodeID]autorelease];
|
||||
panel.workspaceMode=YES;return (NSView<DYWorkspaceMaskEditing> *)panel;
|
||||
}
|
||||
|
||||
@interface DYInspector () <DYGraphicDelegate> {
|
||||
id<PROAPIAccessing> _manager;
|
||||
@@ -463,7 +478,7 @@ static NSImage *DYWheelImage(void) {
|
||||
NSInteger _visibleLooks;
|
||||
NSButton *_colorSettings;BOOL _colorSettingsExpanded;
|
||||
BOOL _refreshing,_graphicUndoOpen;
|
||||
BOOL _embedded;NSMutableDictionary *_stackViews;NSArray *_stackOrder;NSDictionary *_stackRoots;CGFloat _stackHeight;
|
||||
BOOL _embedded,_workspaceEditor;NSMutableDictionary *_stackViews;NSArray *_stackOrder;NSDictionary *_stackRoots;CGFloat _stackHeight;
|
||||
DYSpiderPanel *_spiderPanel;
|
||||
NSMutableDictionary *_assetLoads,*_assetLoadIDs;
|
||||
NSUInteger _nextAssetLoadID;
|
||||
@@ -476,15 +491,19 @@ static NSImage *DYWheelImage(void) {
|
||||
|
||||
@implementation DYInspector
|
||||
#include "DYToolInspector.inc.h"
|
||||
- (void)removeWorkspaceTool {if(!_workspaceEditor||!_cards.count)return;NSButton *source=[[[NSButton alloc]init]autorelease];source.tag=0;[self removeTool:source];}
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager {
|
||||
return [self initWithAPIManager:manager renderer:nil];
|
||||
}
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer {
|
||||
return [self initWithAPIManager:manager renderer:renderer workspaceType:nil];
|
||||
}
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager renderer:(DYRenderer *)renderer workspaceType:(NSString *)workspaceType {
|
||||
uint64_t beta=DYBetaSpanBegin(@"inspector_create",nil);
|
||||
if((self=[super initWithFrame:NSMakeRect(0,0,360,780)])) {
|
||||
_assetLoads=[NSMutableDictionary new];_assetLoadIDs=[NSMutableDictionary new];_manager=manager; _renderer=[renderer retain];_library=[DYLUTLibrary new];_tabs=[NSMutableDictionary new];_visibleLooks=1;
|
||||
_embedded=[manager isKindOfClass:DYToolManager.class];if(_embedded)[(id)_manager retain];
|
||||
NSArray *presentation=DYPresentationSections();if(_embedded){NSMutableArray *filtered=[NSMutableArray array];for(NSDictionary *s in presentation)if([s[@"key"]isEqual:[(DYToolManager*)manager type]])[filtered addObject:s];presentation=filtered;}
|
||||
_workspaceEditor=workspaceType.length>0;_embedded=[manager isKindOfClass:DYToolManager.class];if(_embedded)[(id)_manager retain];
|
||||
NSArray *presentation=DYPresentationSections();if(_embedded||_workspaceEditor){NSMutableArray *filtered=[NSMutableArray array];for(NSDictionary *s in presentation)if([s[@"key"]isEqual:_workspaceEditor?workspaceType:[(DYToolManager*)manager type]])[filtered addObject:s];presentation=filtered;}
|
||||
_sections=[presentation copy];_stackViews=[NSMutableDictionary new];_stackOrder=[@[]copy];
|
||||
_cards=[[NSMutableArray alloc] init]; _controls=[[NSMutableDictionary alloc] init];
|
||||
_assetButtons=[[NSMutableDictionary alloc] init]; _graphics=[[NSMutableArray alloc] init];
|
||||
@@ -504,16 +523,16 @@ static NSImage *DYWheelImage(void) {
|
||||
_export=[DYButton(@"导出 LUT",self,@selector(exportLUT:)) retain];
|
||||
_colorSettings=[DYButton(@"颜色设置",self,@selector(toggleColorSettings:))retain];[_colorSettings setButtonType:NSButtonTypePushOnPushOff];_colorSettings.toolTip=@"展开或收起高级颜色设置;默认使用原有流程";_colorSettings.accessibilityLabel=@"颜色设置";_colorSettings.accessibilityValue=@"已收起";
|
||||
_save.identifier=@"primaryAction";
|
||||
_workspaceButton=[DYButton(@"◫ 工作区 · 示波器 / LUT",self,@selector(openWorkspace:))retain];_workspaceButton.accessibilityLabel=@"打开示波器与 LUT 工作区";
|
||||
_workspaceButton=[DYButton(@"控制面板",self,@selector(openWorkspace:))retain];_workspaceButton.accessibilityLabel=@"打开调色控制面板";
|
||||
_addModule=[[DYThemePopUpButton alloc]initWithFrame:NSZeroRect pullsDown:YES];_addModule.font=[NSFont systemFontOfSize:11];_addModule.accessibilityLabel=@"添加模块";[_addModule addItemWithTitle:@"+ 添加模块"];
|
||||
for(NSDictionary *section in DYPresentationSections()){NSMenuItem *item=[[[NSMenuItem alloc]initWithTitle:section[@"title"] action:@selector(addModule:) keyEquivalent:@""]autorelease];item.target=self;item.representedObject=section[@"key"];[_addModule.menu addItem:item];}
|
||||
for(NSView *v in @[_brand,_subtitle,_websiteLink,_resetAll,_save,_load,_export,_colorSettings,_addModule,_workspaceButton]){[self addSubview:v];v.hidden=_embedded;}
|
||||
for(NSView *v in @[_brand,_subtitle,_websiteLink,_resetAll,_save,_load,_export,_colorSettings,_addModule,_workspaceButton]){[self addSubview:v];v.hidden=_embedded||_workspaceEditor;}
|
||||
NSMutableArray *themes=[NSMutableArray array];for(NSInteger i=0;i<DYThemeNames().count;i++){
|
||||
NSButton *b=DYButton(DYThemeNames()[i],self,@selector(selectTheme:));[b setButtonType:NSButtonTypePushOnPushOff];b.tag=i+7;b.identifier=@"appearanceToggle";
|
||||
b.toolTip=[DYThemeNames()[i] stringByAppendingString:@"主题"];b.accessibilityLabel=b.toolTip;[self addSubview:b];b.hidden=_embedded;[themes addObject:b];
|
||||
b.toolTip=[DYThemeNames()[i] stringByAppendingString:@"主题"];b.accessibilityLabel=b.toolTip;[self addSubview:b];b.hidden=_embedded||_workspaceEditor;[themes addObject:b];
|
||||
}_themeButtons=[themes copy];
|
||||
_scroll=[[DYInspectorScrollView alloc] initWithFrame:NSZeroRect];
|
||||
_scroll.hasVerticalScroller=!_embedded; _scroll.hasHorizontalScroller=NO; _scroll.drawsBackground=NO;
|
||||
_scroll.hasVerticalScroller=!_embedded||_workspaceEditor; _scroll.hasHorizontalScroller=NO; _scroll.drawsBackground=NO;
|
||||
_scroll.autohidesScrollers=YES; _scroll.borderType=NSNoBorder;
|
||||
_scroll.clipsToBounds=YES;_scroll.wantsLayer=YES;_scroll.layer.masksToBounds=YES;
|
||||
_scroll.contentView.clipsToBounds=YES;
|
||||
@@ -522,13 +541,13 @@ static NSImage *DYWheelImage(void) {
|
||||
_document=[[DYFlippedView alloc] initWithFrame:NSMakeRect(0,0,360,1000)];
|
||||
_document.accessibilityLabel=@"调色参数";_document.identifier=@"inspectorBackground";
|
||||
_scroll.documentView=_document; [self addSubview:_scroll];
|
||||
if(!_embedded){_managedPanel=[[DYManagedColorPanel alloc]initWithManager:_manager renderer:_renderer assetTarget:self];_managedPanel.hidden=YES;[_document addSubview:_managedPanel];}
|
||||
if(!_embedded&&!_workspaceEditor){_managedPanel=[[DYManagedColorPanel alloc]initWithManager:_manager renderer:_renderer assetTarget:self];_managedPanel.hidden=YES;[_document addSubview:_managedPanel];}
|
||||
[self buildCards];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modelChanged:) name:@"DYModelChanged" object:_manager];
|
||||
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(themeChanged:) name:DYThemeDidChange object:nil];
|
||||
[NSWorkspace.sharedWorkspace.notificationCenter addObserver:self selector:@selector(themeChanged:) name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
|
||||
if(!_embedded)[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(revealViewerTool:) name:@"DYViewerToolRequested" object:_manager];
|
||||
if(!_embedded)[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openWorkspace:) name:@"DYColorWorkspaceRequested" object:_manager];
|
||||
if(!_embedded&&!_workspaceEditor)[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(revealViewerTool:) name:@"DYViewerToolRequested" object:_manager];
|
||||
if(!_embedded&&!_workspaceEditor)[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(openWorkspace:) name:@"DYColorWorkspaceRequested" object:_manager];
|
||||
if(_renderer)[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(previewChanged:) name:@"DYPreviewDidChange" object:_renderer];
|
||||
[self themeChanged:nil];
|
||||
[self setAccessibilityLabel:@"大鱼调色检查器"];
|
||||
@@ -575,10 +594,11 @@ static NSImage *DYWheelImage(void) {
|
||||
[_document scrollPoint:NSZeroPoint];NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);
|
||||
}
|
||||
- (void)openWorkspace:(id)sender {
|
||||
if(_embedded||!self.window||!_renderer)return;
|
||||
if(_embedded||_workspaceEditor||!self.window||!_renderer)return;
|
||||
[_browser close];
|
||||
if(!_workspace)_workspace=[[DYColorWorkspace alloc]initWithManager:_manager renderer:_renderer library:_library title:@"大鱼调色 · 当前片段"];
|
||||
[_workspace showRelativeToView:self];
|
||||
if([sender isKindOfClass:NSNotification.class])[_workspace showPage:[sender userInfo][@"page"]?:@"tools" maskKind:[sender userInfo][@"maskKind"]];
|
||||
}
|
||||
- (void)openWebsite:(id)sender {[[NSWorkspace sharedWorkspace]openURL:[NSURL URLWithString:@"https://dayu.media"]];}
|
||||
- (void)redrawTree:(NSView *)view { [view setNeedsDisplay:YES];for(NSView *child in view.subviews)[self redrawTree:child]; }
|
||||
@@ -602,6 +622,7 @@ static NSImage *DYWheelImage(void) {
|
||||
NSInteger index=0;
|
||||
for(NSDictionary *section in _sections) {
|
||||
DYCard *card=[[[DYCard alloc] initWithFrame:NSZeroRect] autorelease];
|
||||
card.workspaceMode=_workspaceEditor;
|
||||
card.accessibilityLabel=section[@"title"];card.identifier=section[@"key"];
|
||||
[_document addSubview:card];
|
||||
DYHeader *header=[[[DYHeader alloc] initWithFrame:NSZeroRect] autorelease];
|
||||
@@ -651,7 +672,8 @@ static NSImage *DYWheelImage(void) {
|
||||
NSSegmentedControl *tabs=[NSSegmentedControl segmentedControlWithLabels:[key isEqual:@"mixer"]?@[@"红输出",@"绿输出",@"蓝输出"]:@[@"减色",@"晕光",@"辉光",@"颗粒",@"暗角",@"印片"] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(tabChanged:)];tabs.identifier=key;tabs.selectedSegment=0;tabs.controlSize=NSControlSizeSmall;tabs.accessibilityLabel=[section[@"title"]stringByAppendingString:@"分组"];[card addSubview:tabs];[body addObject:tabs];
|
||||
}
|
||||
if([key isEqual:@"curve"]) {
|
||||
DYCurvePanel *graph=[[[DYCurvePanel alloc]initWithFrame:NSZeroRect]autorelease];graph.delegate=self;[graph setHistogram:[_renderer histogram]];graph.identifier=@"curveGraph";[card addSubview:graph];[body addObject:graph];[_graphics addObject:graph];
|
||||
if(_workspaceEditor){DYWorkspaceCurveStrip *strip=[[[DYWorkspaceCurveStrip alloc]init]autorelease];strip.identifier=@"curveGraph";for(NSInteger channel=0;channel<4;channel++){DYCurvePanel *graph=[[[DYCurvePanel alloc]init]autorelease];graph.delegate=self;[graph setFixedWorkspaceChannel:channel];[graph setHistogram:[_renderer histogram]];[strip addSubview:graph];[_graphics addObject:graph];}[card addSubview:strip];[body addObject:strip];}
|
||||
else {DYCurvePanel *graph=[[[DYCurvePanel alloc]initWithFrame:NSZeroRect]autorelease];graph.delegate=self;[graph setHistogram:[_renderer histogram]];graph.identifier=@"curveGraph";[card addSubview:graph];[body addObject:graph];[_graphics addObject:graph];}
|
||||
}
|
||||
if([key isEqual:@"grading"]) {
|
||||
DYWheelPanel *wheels=[[[DYWheelPanel alloc]initWithFrame:NSZeroRect]autorelease];wheels.delegate=self;wheels.identifier=@"gradingWheels";[card addSubview:wheels];[body addObject:wheels];[_graphics addObject:wheels];
|
||||
@@ -737,6 +759,7 @@ static NSImage *DYWheelImage(void) {
|
||||
return row;
|
||||
}
|
||||
- (BOOL)showRow:(NSView *)row section:(NSString *)section {
|
||||
if(_workspaceEditor&&[row.identifier isEqual:@"toolMasks"])return NO;
|
||||
if([row.identifier isEqual:@"toolMasks"])return [(DYToolMaskPanel*)row contentHeight]>0;
|
||||
NSString *key=row.identifier?:@"";NSInteger tab=[_tabs[section]integerValue];
|
||||
if(!_embedded&&[section isEqual:@"base"]&&[key isEqual:@"skinEnabled"])for(NSDictionary *card in _cards)if([card[@"section"][@"key"]isEqual:@"skin"])return ![card[@"removed"]boolValue];
|
||||
@@ -758,14 +781,14 @@ static NSImage *DYWheelImage(void) {
|
||||
- (void)layout {
|
||||
[super layout];
|
||||
CGFloat w=MAX(280,self.bounds.size.width),h=self.bounds.size.height;
|
||||
_brand.frame=NSMakeRect(16,14,112,26);_subtitle.frame=NSMakeRect(130,21,40,13);_subtitle.hidden=_embedded||w<380;
|
||||
_brand.frame=NSMakeRect(16,14,112,26);_subtitle.frame=NSMakeRect(130,21,40,13);_subtitle.hidden=_embedded||_workspaceEditor||w<380;
|
||||
for(NSInteger i=0;i<_themeButtons.count;i++)[_themeButtons[i]setFrame:NSMakeRect(w-130+i*47,16,44,25)];
|
||||
_resetAll.frame=NSMakeRect(w-33,16,23,24);
|
||||
_websiteLink.frame=NSMakeRect(16,41,w-32,20);
|
||||
CGFloat gap=7;BOOL compact=w<320;CGFloat bw=(w-32-gap*(compact?1:3))/(compact?2:4);
|
||||
NSArray *actions=@[_save,_load,_export,_colorSettings];for(NSUInteger i=0;i<actions.count;i++)[actions[i]setFrame:NSMakeRect(16+(bw+gap)*(compact?i%2:i),74+(compact?i/2*34:0),bw,27)];
|
||||
CGFloat top=(compact?178:144)+34;_workspaceButton.frame=NSMakeRect(16,top-70,w-32,27);_addModule.frame=NSMakeRect(16,top-36,w-32,27);
|
||||
_scroll.frame=_embedded?NSMakeRect(0,0,w,h):NSMakeRect(0,top,w,MAX(80,h-top));
|
||||
_scroll.frame=(_embedded||_workspaceEditor)?NSMakeRect(0,0,w,h):NSMakeRect(0,top,w,MAX(80,h-top));
|
||||
CGFloat cw=MAX(244,_scroll.contentSize.width-32),y=8;
|
||||
if(_managedPanel&&!_managedPanel.hidden){_managedPanel.frame=NSMakeRect(28,y,cw-24,_managedPanel.contentHeight);y+=_managedPanel.contentHeight+12;}
|
||||
for(NSMutableDictionary *c in _cards) {
|
||||
@@ -776,7 +799,8 @@ static NSImage *DYWheelImage(void) {
|
||||
[c[@"enabled"]setFrame:NSMakeRect(12,12,20,20)];
|
||||
BOOL narrow=cw<300;CGFloat titleWidth=MIN(cw-(narrow?60:171),MAX(94,[[(NSButton *)c[@"header"]title]sizeWithAttributes:@{NSFontAttributeName:[NSFont boldSystemFontOfSize:12]}].width+36));
|
||||
[c[@"header"]setFrame:NSMakeRect(42,8,titleWidth,28)];
|
||||
CGFloat headerHeight=narrow?69:43,buttonY=narrow?38:10;
|
||||
CGFloat headerHeight=_workspaceEditor?0:narrow?69:43,buttonY=narrow?38:10;
|
||||
if(_workspaceEditor)for(NSString *name in @[@"header",@"enabled",@"reset",@"repeatButton",@"removeButton",@"maskButton",@"maskBadge"])[c[name]setHidden:YES];
|
||||
card.frame=NSMakeRect(16,y,cw,headerHeight+(contentHeight>0?contentHeight+8:0));y+=card.frame.size.height+12;
|
||||
[c[@"reset"]setFrame:NSMakeRect(cw-34,buttonY,24,24)];
|
||||
[c[@"repeatButton"]setFrame:NSMakeRect(cw-62,buttonY,24,24)];[c[@"removeButton"]setFrame:NSMakeRect(cw-90,buttonY,24,24)];[c[@"maskButton"]setFrame:NSMakeRect(cw-118,buttonY,24,24)];[c[@"maskBadge"]setFrame:NSMakeRect(cw-111,buttonY-7,18,16)];
|
||||
@@ -793,6 +817,12 @@ 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)];}
|
||||
}
|
||||
if(_workspaceEditor){CGFloat available=cw-24,columns=MAX(1,floor(available/280)),columnWidth=available/columns,wy=0;NSInteger column=0;
|
||||
for(NSView *row in body){if(row.hidden)continue;BOOL full=[row.identifier hasPrefix:@"heading:"]||[row.identifier hasSuffix:@"Graph"]||[row.identifier hasSuffix:@"Tabs"]||[row.identifier hasSuffix:@"Controls"]||[row.identifier isEqual:@"gradingWheels"]||[row.identifier isEqual:@"primaryBalance"]||[row isKindOfClass:NSSegmentedControl.class];
|
||||
if(full){if(column){wy+=32;column=0;}CGFloat rh=[self heightForRow:row];if([row.identifier isEqual:@"curveGraph"])rh=MAX(180,MIN(300,available/4+26));row.frame=NSMakeRect(12,wy,available,rh);wy+=rh;}
|
||||
else {row.frame=NSMakeRect(12+column*columnWidth,wy,columnWidth-8,31);if(++column>=(NSInteger)columns){column=0;wy+=32;}}
|
||||
}if(column)wy+=32;card.frame=NSMakeRect(16,card.frame.origin.y,cw,wy+8);y=NSMaxY(card.frame)+8;
|
||||
}
|
||||
y=[self layoutRepeatedToolsAfter:[@"base:" stringByAppendingString:key] y:y width:w];
|
||||
}
|
||||
for(NSDictionary *record in _controls.allValues) {
|
||||
@@ -843,7 +873,7 @@ static NSImage *DYWheelImage(void) {
|
||||
BOOL enabled=v>=.5||extraValue>=.5;
|
||||
DYInspectorToken *token=nil;[get getCustomParameterValue:&token fromParameter:DYInspectorParameterID atTime:t];
|
||||
NSNumber *saved=[token isKindOfClass:DYInspectorToken.class]?token.folds[c[@"section"][@"key"]]:nil;
|
||||
BOOL collapsed=saved?saved.boolValue:[c[@"collapsed"]boolValue];groupingChanged|=collapsed!=[c[@"collapsed"]boolValue];c[@"collapsed"]=@(collapsed);
|
||||
BOOL collapsed=_workspaceEditor?NO:saved?saved.boolValue:[c[@"collapsed"]boolValue];groupingChanged|=collapsed!=[c[@"collapsed"]boolValue];c[@"collapsed"]=@(collapsed);
|
||||
[c[@"header"]setState:collapsed?NSControlStateValueOff:NSControlStateValueOn];
|
||||
[c[@"header"]setToolTip:collapsed?@"展开界面,不改变启用状态;双击还原本组":@"折叠界面,保持当前效果;双击还原本组"];
|
||||
[c[@"header"]setAccessibilityHelp:[c[@"header"]toolTip]];[c[@"header"]setNeedsDisplay:YES];
|
||||
@@ -857,7 +887,7 @@ static NSImage *DYWheelImage(void) {
|
||||
if(!_embedded){DYInspectorToken *token=nil;[get getCustomParameterValue:&token fromParameter:DYInspectorParameterID atTime:t];visible=[@[@"primary",@"base",@"spider",@"hsl"]containsObject:type]||[token.folds[[@"visible:" stringByAppendingString:type]]boolValue];
|
||||
if(!visible){for(NSDictionary*d in DYBaseToolDescriptors(type)){double value=[d[@"default"]doubleValue];[get getFloatValue:&value fromParameter:[d[@"pid"]unsignedIntValue]atTime:t];if(std::isfinite(value)&&fabs(value-[d[@"default"]doubleValue])>1e-6){visible=YES;break;}}if([tools[@"baseMasks"][type]count])visible=YES;if([type isEqual:@"look"])for(NSString *assetKey in DYReadAssets(_manager,t).paths)if([assetKey hasPrefix:@"look"])visible=YES;}
|
||||
}
|
||||
BOOL removed=!_embedded&&(DYBaseToolRemoved(tools,type)||!visible);groupingChanged|=[card[@"removed"]boolValue]!=removed;((NSMutableDictionary *)card)[@"removed"]=@(removed);
|
||||
BOOL removed=!_embedded&&(DYBaseToolRemoved(tools,type)||(!_workspaceEditor&&!visible));groupingChanged|=[card[@"removed"]boolValue]!=removed;((NSMutableDictionary *)card)[@"removed"]=@(removed);
|
||||
[card[@"maskPanel"]refreshWithDocument:tools time:t];
|
||||
NSString *nodeID=_embedded?[(DYToolManager*)_manager nodeID]:[@"base:" stringByAppendingString:card[@"section"][@"key"]];NSUInteger count=[DYMasksForTool(tools,nodeID) count];
|
||||
[(DYMaskCountBadge*)card[@"maskBadge"]setCount:count];NSString *hint=count?[NSString stringWithFormat:@"已有 %lu 个蒙版;点击添加独立蒙版",(unsigned long)count]:@"添加本工具的独立蒙版";
|
||||
@@ -882,7 +912,7 @@ static NSImage *DYWheelImage(void) {
|
||||
} @finally { [action endAction:self]; _refreshing=NO; }
|
||||
// Remote layout/accessibility can re-enter the host. Let the parameter
|
||||
// action and current callback unwind before notifying the remote view.
|
||||
if(!_embedded)[self synchronizeTools];
|
||||
if(!_embedded&&!_workspaceEditor)[self synchronizeTools];
|
||||
DYBetaSpanEnd(beta,nil);
|
||||
if(groupingChanged)dispatch_async(dispatch_get_main_queue(),^{NSAccessibilityPostNotification(self,NSAccessibilityLayoutChangedNotification);});
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
NSDictionary*context=DYHostColorContext(src,dst,primaries);@synchronized(_previewLock){[_colorContext release];_colorContext=[context copy];}
|
||||
if(!state.count)return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
|
||||
if(!DYManagedColorValid(state,error))return NO;if(!tools)tools=@{@"schema":@2,@"layers":@[],@"baseMasks":@{}};if(!DYValidToolDocument(tools))return fail(error,@"调色层或蒙版数据无效。");
|
||||
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
|
||||
if(DYPrimaryColorState(state))return [self renderPrimarySource:src destination:dst uniforms:u paths:paths spider:spider tools:tools hostPrimaries:primaries error:error];
|
||||
NSMutableDictionary*entry=[self device:dst.deviceRegistryID error:error];if(!entry)return NO;id<MTLDevice>d=entry[@"device"];id<MTLTexture>source=[src metalTextureForDevice:d];if(!source)return fail(error,@"色彩管理输入纹理不可用。");
|
||||
uint64_t pixels=uint64_t(source.width)*source.height;if(!pixels||pixels>64ull*1024*1024||pixels*16*8>MAX(768ull*1024*1024,MIN(2ull*1024*1024*1024,d.recommendedMaxWorkingSetSize/2)))return fail(error,@"当前画面超过色彩管理内存预算。");
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
// Native per-tool mask editor, shared by original and repeated tool cards.
|
||||
@interface DYToolMaskPanel : DYFlippedView
|
||||
@interface DYToolMaskPanel : DYFlippedView<DYWorkspaceMaskEditing>
|
||||
@property(nonatomic,readonly) CGFloat contentHeight;
|
||||
@property(nonatomic) BOOL workspaceMode;
|
||||
@property(nonatomic,readonly) NSString *selectedMaskID;
|
||||
- (instancetype)initWithManager:(id<PROAPIAccessing>)manager nodeID:(NSString*)nodeID;
|
||||
- (void)refreshWithDocument:(NSDictionary*)document time:(CMTime)time;
|
||||
- (void)addMenu:(NSView*)anchor;
|
||||
- (void)selectMaskID:(NSString*)maskID;
|
||||
@end
|
||||
@implementation DYToolMaskPanel {
|
||||
id<PROAPIAccessing> _host;NSString *_nodeID,*_maskID;NSDictionary *_document;CMTime _time;
|
||||
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;
|
||||
NSPopUpButton *_list,*_combine;NSButton *_eye,*_add,*_remove,*_invert,*_canvas,*_clear,*_penRedraw,*_penFinish,*_penCancel;NSMutableArray *_rows,*_tracking;NSTextField *_trackingTitle,*_status;BOOL _refreshing,_drawing,_canvasActive,_workspaceMode;CGFloat _contentHeight;
|
||||
}
|
||||
@synthesize workspaceMode=_workspaceMode;
|
||||
- (NSString*)selectedMaskID{return _maskID;}
|
||||
- (void)setWorkspaceMode:(BOOL)workspaceMode{if(_workspaceMode==workspaceMode)return;_workspaceMode=workspaceMode;[self setNeedsLayout:YES];}
|
||||
- (CGFloat)workspaceHeightForWidth:(CGFloat)width{
|
||||
if(!_contentHeight)return 0;CGFloat w=MAX(560,width),header=w>=860?48:88;BOOL shape=_tracking.count&&![_tracking[0]isHidden],pen=_penRedraw&&!_penRedraw.hidden;NSUInteger count=0;for(NSDictionary *row in _rows)if(![row[@"label"]isHidden])count++;
|
||||
CGFloat side=shape?MIN(240,MAX(190,w*.27)):0,left=w-16-(shape?side+20:0);NSInteger columns=shape?2:MIN(3,MAX(1,NSInteger(left/172)));CGFloat scalar=ceil(double(count)/columns)*50;
|
||||
CGFloat actions=(pen?80:0)+(shape?174:0)+60;return header+(shape?MAX(scalar,actions):scalar+68)+8;
|
||||
}
|
||||
- (CGFloat)contentHeight{return _workspaceMode&&self.bounds.size.width>=560?[self workspaceHeightForWidth:self.bounds.size.width]:_contentHeight;}
|
||||
- (void)selectMaskID:(NSString*)maskID{
|
||||
if([_maskID isEqual:maskID]){if(!_canvasActive)[self canvas:nil];return;}BOOL found=NO;for(NSDictionary *mask in DYMasksForTool(_document,_nodeID))if([mask[@"id"]isEqual:maskID]){found=YES;break;}if(!found)return;
|
||||
[_maskID release];_maskID=[maskID copy];_drawing=_canvasActive=NO;[self refreshWithDocument:_document time:_time];[self canvas:nil];
|
||||
}
|
||||
@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];
|
||||
@@ -42,7 +57,7 @@
|
||||
- (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;_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;
|
||||
if(!masks.count){_contentHeight=0;_drawing=_canvasActive=NO;[_maskID release];_maskID=nil;_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]]];}
|
||||
@@ -50,12 +65,25 @@
|
||||
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 保留原路径。":@"各蒙版只影响当前工具层");
|
||||
if([_nodeID isEqual:@"shared"]){_list.accessibilityLabel=@"共享蒙版";_add.toolTip=@"添加共享蒙版";_remove.toolTip=@"删除此共享蒙版及其模块关联,可撤销";if(!m[@"status"]&&!pen&&![m[@"keys"]count])_status.stringValue=[NSString stringWithFormat:@"共享给 %lu 个模块 · 编辑与跟踪同步更新所有关联模块",(unsigned long)DYToolIDsForSharedMask(doc,_maskID).count];}
|
||||
// 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;
|
||||
if(_workspaceMode&&w>=560){
|
||||
CGFloat x=8,y=8;BOOL wide=w>=860,shape=_tracking.count&&![_tracking[0]isHidden],pen=_penRedraw&&!_penRedraw.hidden;
|
||||
CGFloat first=wide?MAX(180,w-470):w-128;_eye.frame=NSMakeRect(x,y,28,30);x+=36;_list.frame=NSMakeRect(x,y,first,30);x+=first+6;_add.frame=NSMakeRect(x,y,30,30);x+=34;_remove.frame=NSMakeRect(x,y,30,30);x+=40;
|
||||
if(!wide){x=8;y=48;}_combine.frame=NSMakeRect(x,y,106,30);x+=116;_invert.frame=NSMakeRect(x,y+2,76,26);x+=86;_canvas.frame=NSMakeRect(x,y,MAX(100,w-x-8),30);
|
||||
CGFloat top=wide?48:88,side=shape?MIN(240,MAX(190,w*.27)):0,left=w-16-(shape?side+20:0);NSInteger columns=shape?2:MIN(3,MAX(1,NSInteger(left/172)));CGFloat cell=(left-(columns-1)*16)/columns;NSUInteger index=0;
|
||||
for(NSDictionary *row in _rows){NSTextField *label=row[@"label"];if(label.hidden)continue;CGFloat rx=8+(index%columns)*(cell+16),ry=top+(index/columns)*50;label.frame=NSMakeRect(rx,ry+3,MAX(62,cell-80),21);[row[@"field"]setFrame:NSMakeRect(rx+cell-76,ry,76,25)];[row[@"slider"]setFrame:NSMakeRect(rx,ry+25,cell,21)];index++;}
|
||||
CGFloat ax=shape?w-side-8:8,aw=shape?side:left,ay=top;
|
||||
if(pen){CGFloat bw=(aw-8)/2;_penRedraw.frame=NSMakeRect(ax,ay,bw,30);_penFinish.frame=NSMakeRect(ax+bw+8,ay,bw,30);_penCancel.frame=NSMakeRect(ax,ay+36,aw,30);ay+=80;}
|
||||
if(shape){_trackingTitle.frame=NSMakeRect(ax,ay+2,aw,20);ay+=28;CGFloat bw=(aw-8)/2;const int order[]={0,4,1,3,2,5};for(int i=0;i<6;i++)[_tracking[order[i]]setFrame:NSMakeRect(ax+(i%2)*(bw+8),ay+(i/2)*34,bw,30)];ay+=106;_clear.frame=NSMakeRect(ax,ay,aw,30);ay+=40;}
|
||||
else ay=top+ceil(double(index)/columns)*50+8;
|
||||
_status.frame=NSMakeRect(ax,ay+2,aw,54);return;
|
||||
}
|
||||
_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;}
|
||||
@@ -67,7 +95,7 @@
|
||||
- (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 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];}
|
||||
id<FxCustomParameterActionAPI_v4>a=[_host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{NSMutableDictionary *doc=DYMutablePlist(DYReadTools(_host,a.currentTime).document);BOOL shared=[_nodeID isEqual:@"shared"];NSMutableArray *masks=[[DYMasksForTool(doc,_nodeID)mutableCopy]autorelease];if(masks.count>=(shared?DYSharedMaskLimit:DYToolMaskLimit)){NSBeep();return;}NSDictionary *mask=shared?DYAddSharedMask(doc,sender.tag):DYNewMask(sender.tag);if(!mask)return;if(!shared){[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:shared?@"添加共享蒙版":@"添加工具蒙版"];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);}];}
|
||||
@@ -83,5 +111,5 @@
|
||||
- (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"]?:@"";}
|
||||
- (void)trackingStatus:(NSNotification*)n{if([n.userInfo[@"node"]isEqual:_nodeID]&&(!n.userInfo[@"mask"]||[n.userInfo[@"mask"]isEqual:_maskID]))_status.stringValue=n.userInfo[@"message"]?:@"";}
|
||||
@end
|
||||
@@ -11,6 +11,7 @@
|
||||
#import <CoreImage/CoreImage.h>
|
||||
#import <os/log.h>
|
||||
#include "MaskCore/DYTracker.hpp"
|
||||
#include "MaskCore/DYOpenCVTracker.hpp"
|
||||
#include <atomic>
|
||||
#include "DYViewerParameterBridge.inc.h"
|
||||
#include "DYToolHostDeclarations.inc.h"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Opt-in V3. The root primary owns input/working/output; V1/V2 stay frozen.
|
||||
- (BOOL)renderPrimarySource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools hostPrimaries:(NSInteger)primaries error:(NSError**)error {
|
||||
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
|
||||
// The main eye bypasses the whole primary/CST module. Other tools retain
|
||||
// their established unmanaged host workflow rather than inheriting a Log tag.
|
||||
if(u.primarySectionEnabled<.5||DYBaseToolRemoved(tools,@"primary"))return [self renderSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Shared author identity and disposable render bindings must stay separate.
|
||||
{
|
||||
NSMutableDictionary *doc=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);
|
||||
NSMutableDictionary *shared=(id)DYAddSharedMask(doc,DYMaskRectangle);NSString *maskID=shared[@"id"];
|
||||
run.need(@"shared-mask-can-be-authored-before-any-module-assignment",shared&&DYValidToolDocument(doc)&&DYSharedMasks(doc).count==1&&DYMasksForTool(doc,@"shared").firstObject==shared&&DYMasksForTool(doc,@"base:hsl").count==0);
|
||||
NSDictionary *layer=DYInsertTool(doc,@"curve",@"base:curve");NSString *layerID=layer[@"id"];
|
||||
BOOL assigned=DYSetSharedMaskAssigned(doc,maskID,@"base:hsl",YES)&&DYSetSharedMaskAssigned(doc,maskID,layerID,YES);
|
||||
run.record(@"shared-mask-two-module-bindings-retain-one-author-object",assigned&&DYValidToolDocument(doc)&&DYSharedMasks(doc).count==1&&DYMasksForTool(doc,@"base:hsl").firstObject==DYMasksForTool(doc,layerID).firstObject&&DYToolIDsForSharedMask(doc,maskID).count==2&&[doc[@"baseMasks"][@"hsl"][0][@"sharedID"]isEqual:maskID]&&[doc[@"schema"]isEqual:@3]);
|
||||
DYMaskParameters p=DYMaskAtTime(shared,kCMTimeZero);p.centerX=.31;shared[@"parameters"]=[NSData dataWithBytes:&p length:sizeof(p)];DYMaskParameters q=DYMaskAtTime(DYMasksForTool(doc,layerID).firstObject,kCMTimeZero);
|
||||
run.record(@"editing-one-shared-mask-updates-all-linked-modules",fabs(q.centerX-.31)<1e-6&&DYSharedMasks(doc).count==1);
|
||||
DYMaskParameters moved=p;moved.centerX=.71;DYMergeTracking(shared,@[DYMaskKey(kCMTimeZero,p,YES,1),DYMaskKey(CMTimeMake(2,24),moved,NO,.9)]);
|
||||
q=DYMaskAtTime(DYMasksForTool(doc,layerID).firstObject,CMTimeMake(1,24));
|
||||
run.record(@"shared-tracking-is-single-timeline-for-every-module",fabs(q.centerX-.51)<1e-6&&[DYMasksForTool(doc,@"base:hsl").firstObject[@"keys"]count]==2);
|
||||
DYToolDocument *author=[[[DYToolDocument alloc]init]autorelease];author.document=doc;NSData *encoded=[NSKeyedArchiver archivedDataWithRootObject:author requiringSecureCoding:YES error:&error];DYToolDocument *decoded=[NSKeyedUnarchiver unarchivedObjectOfClass:DYToolDocument.class fromData:encoded error:&error];
|
||||
run.record(@"shared-mask-archive-roundtrip-keeps-unique-object-and-links",[decoded isEqual:author]&&DYSharedMasks(decoded.document).count==1&&DYToolIDsForSharedMask(decoded.document,maskID).count==2);
|
||||
NSDictionary *snapshot=DYToolRenderSnapshot(doc,CMTimeMake(1,24)),*again=DYToolRenderSnapshot(doc,CMTimeMake(1,24));NSDictionary *base=DYMasksForTool(snapshot,@"base:hsl").firstObject,*extra=DYMasksForTool(snapshot,layerID).firstObject;
|
||||
run.record(@"shared-render-snapshot-freezes-all-bindings-with-stable-private-identities",DYValidToolDocument(snapshot)&&[snapshot isEqual:again]&&![base[@"id"]isEqual:extra[@"id"]]&&[base[@"sourceSharedID"]isEqual:maskID]&&[extra[@"sourceSharedID"]isEqual:maskID]&&[base[@"keys"]count]==0&&[extra[@"keys"]count]==0&&fabs(DYMaskAtTime(base,kCMTimeZero).centerX-.51)<1e-6&&[shared[@"keys"]count]==2);
|
||||
NSMutableDictionary *bad=DYMutablePlist(doc);bad[@"baseMasks"][@"hsl"]=[NSMutableArray arrayWithObjects:@{@"sharedID":maskID},@{@"sharedID":maskID},nil];run.record(@"shared-mask-rejects-duplicate-binding-in-one-module",!DYValidToolDocument(bad));
|
||||
bad=DYMutablePlist(doc);bad[@"baseMasks"][@"hsl"]=[NSMutableArray arrayWithObject:@{@"sharedID":NSUUID.UUID.UUIDString}];run.record(@"shared-mask-rejects-dangling-reference",!DYValidToolDocument(bad));
|
||||
bad=DYMutablePlist(doc);bad[@"baseMasks"][@"hsl"]=[NSMutableArray arrayWithObject:DYMutablePlist(shared)];run.record(@"shared-mask-rejects-copied-author-object-with-same-identity",!DYValidToolDocument(bad));
|
||||
bad=DYMutablePlist(doc);bad[@"schema"]=@2;run.record(@"legacy-document-cannot-silently-contain-shared-references",!DYValidToolDocument(bad));
|
||||
BOOL detached=DYSetSharedMaskAssigned(doc,maskID,@"base:hsl",NO);run.record(@"unlinking-one-module-keeps-shared-mask-and-other-module",detached&&DYMasksForTool(doc,@"base:hsl").count==0&&DYMasksForTool(doc,layerID).count==1&&DYSharedMasks(doc).count==1&&DYValidToolDocument(doc));
|
||||
BOOL removed=DYRemoveSharedMask(doc,maskID);run.record(@"deleting-shared-mask-removes-all-references-without-deleting-modules",removed&&DYSharedMasks(doc).count==0&&DYMasksForTool(doc,layerID).count==0&&DYToolWithID(doc,layerID)&&DYValidToolDocument(doc));
|
||||
NSMutableDictionary *legacy=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);NSDictionary *old=DYNewMask(DYMaskEllipse);legacy[@"baseMasks"][@"curve"]=[NSMutableArray arrayWithObject:old];NSDictionary *promoted=DYShareToolMask(legacy,@"base:curve",old[@"id"]);
|
||||
run.record(@"sharing-legacy-mask-moves-one-object-without-changing-geometry-or-identity",promoted&&[promoted isEqual:old]&&DYSharedMasks(legacy).count==1&&DYMasksForTool(legacy,@"base:curve").firstObject==promoted&&DYValidToolDocument(legacy));
|
||||
BOOL removedBase=DYSetBaseToolRemoved(legacy,@"curve",YES);run.record(@"removing-base-module-detaches-reference-and-preserves-shared-object",removedBase&&DYValidToolDocument(legacy)&&DYSharedMasks(legacy).count==1&&DYToolIDsForSharedMask(legacy,old[@"id"]).count==0);
|
||||
NSMutableDictionary *limits=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);BOOL sixteen=YES;for(int i=0;i<DYSharedMaskLimit;i++){NSDictionary *item=DYAddSharedMask(limits,DYMaskEllipse);if(i<DYToolMaskLimit)sixteen&=DYSetSharedMaskAssigned(limits,item[@"id"],@"base:hsl",YES);}NSDictionary *seventeenth=DYSharedMasks(limits)[DYToolMaskLimit];
|
||||
run.record(@"shared-library-and-per-module-reference-limits-remain-independent",sixteen&&DYSharedMasks(limits).count==DYSharedMaskLimit&&DYMasksForTool(limits,@"base:hsl").count==DYToolMaskLimit&&!DYAddSharedMask(limits,DYMaskRectangle)&&!DYSetSharedMaskAssigned(limits,seventeenth[@"id"],@"base:hsl",YES)&&DYValidToolDocument(limits));
|
||||
// More than 65,536 referenced keys, but only 7,000 uniquely authored keys.
|
||||
NSMutableDictionary *many=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);NSMutableDictionary *timeline=(id)DYAddSharedMask(many,DYMaskRectangle);NSMutableArray *keys=[NSMutableArray arrayWithCapacity:7000];for(int i=0;i<7000;i++)[keys addObject:DYMaskKey(CMTimeMake(i,24),p,NO,.9)];timeline[@"keys"]=keys;BOOL allBindings=YES;for(NSString *type in [DYToolTypes()subarrayWithRange:NSMakeRange(0,10)])allBindings&=DYSetSharedMaskAssigned(many,timeline[@"id"],[@"base:" stringByAppendingString:type],YES);
|
||||
run.record(@"shared-key-budget-counts-author-object-once-regardless-of-bindings",allBindings&&DYValidToolDocument(many)&&DYValidToolDocument(DYToolRenderSnapshot(many,CMTimeMake(50,24)))&&DYValidToolDocument(DYResolvedToolDocument(many)));
|
||||
BOOL compactFits=YES,compactRows=YES;
|
||||
for(int kind=0;kind<6;kind++){
|
||||
NSMutableDictionary *state=DYMutablePlist([[[DYToolDocument alloc]init]autorelease].document);NSDictionary *mask=DYAddSharedMask(state,kind);NSView<DYWorkspaceMaskEditing> *editor=DYCreateWorkspaceMaskEditor(manager,@"shared");[editor refreshWithDocument:state time:kCMTimeZero];[editor selectMaskID:mask[@"id"]];
|
||||
for(NSNumber *width in @[@377,@600,@860,@1200]){[editor setFrameSize:NSMakeSize(width.doubleValue,500)];[editor setFrameSize:NSMakeSize(width.doubleValue,editor.contentHeight)];[editor layoutSubtreeIfNeeded];for(NSView *view in editor.subviews)if(!view.hidden)compactFits&=NSContainsRect(editor.bounds,view.frame)&&view.frame.size.width>0&&view.frame.size.height>0;for(NSDictionary *row in [editor valueForKey:@"_rows"]){NSView *label=row[@"label"],*field=row[@"field"],*slider=row[@"slider"];if(label.hidden)continue;compactRows&=!NSIntersectsRect(label.frame,field.frame)&&!NSIntersectsRect(label.frame,slider.frame)&&!NSIntersectsRect(field.frame,slider.frame)&&field.frame.size.width>=70&&slider.frame.size.width>=140;}}
|
||||
}
|
||||
run.record(@"workspace-six-mask-editors-fit-377-600-860-1200-point-widths",compactFits&&compactRows);
|
||||
}
|
||||
@@ -15,5 +15,5 @@
|
||||
NSDictionary *_trackingFrozenMask;NSMutableDictionary *_trackingCandidate;
|
||||
NSMutableArray *_trackingSamples;
|
||||
DYMaskParameters _trackingSeed;
|
||||
dy::Tracker _toolTracker;
|
||||
dy::OpenCVTracker _toolTracker;
|
||||
NSMutableDictionary *_toolCaptureDevices;
|
||||
@@ -9,7 +9,7 @@
|
||||
[_toolCanvasDocument release];[_toolSession release];[_selectedToolNode release];[_selectedToolMask release];[_toolCanvasDraft release];[_toolCanvasOriginal release];[_trackingNode release];[_trackingMaskID release];[_trackingFrozenMask release];[_trackingCandidate release];[_trackingSamples release];[_trackingMessage release];[_toolCaptureDevices release];
|
||||
}
|
||||
- (void)adoptToolCanvasDocument:(NSDictionary*)document {
|
||||
if(!document)return;@synchronized(self){[_toolCanvasDocument release];_toolCanvasDocument=[document copy];if([self toolMask:_selectedToolMask node:_selectedToolNode document:document])return;NSString *node=nil,*maskID=nil;for(NSString *type in DYToolTypes())for(NSDictionary *mask in document[@"baseMasks"][type])if(!node&&[mask[@"enabled"]boolValue]){node=[@"base:" stringByAppendingString:type];maskID=mask[@"id"];}for(NSDictionary *layer in document[@"layers"])for(NSDictionary *mask in layer[@"masks"])if(!node&&[mask[@"enabled"]boolValue]){node=layer[@"id"];maskID=mask[@"id"];}[_selectedToolNode release];_selectedToolNode=[node copy];[_selectedToolMask release];_selectedToolMask=[maskID copy];}
|
||||
if(!document)return;@synchronized(self){[_toolCanvasDocument release];_toolCanvasDocument=[document copy];if([self toolMask:_selectedToolMask node:_selectedToolNode document:document])return;NSString *node=nil,*maskID=nil;for(NSString *type in DYToolTypes())for(NSDictionary *mask in DYMasksForTool(document,[@"base:" stringByAppendingString:type]))if(!node&&[mask[@"enabled"]boolValue]){node=[@"base:" stringByAppendingString:type];maskID=mask[@"id"];}for(NSDictionary *layer in document[@"layers"])for(NSDictionary *mask in DYMasksForTool(document,layer[@"id"]))if(!node&&[mask[@"enabled"]boolValue]){node=layer[@"id"];maskID=mask[@"id"];}[_selectedToolNode release];_selectedToolNode=[node copy];[_selectedToolMask release];_selectedToolMask=[maskID copy];}
|
||||
}
|
||||
- (void)scheduleToolCanvasRegistration {
|
||||
_toolCaptureEnabled=YES;dispatch_async(dispatch_get_main_queue(),^{id<FxCustomParameterActionAPI_v4>a=[self->_apiManager apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;[a startAction:self];@try{if(!self->_toolSession){NSString *session=NSUUID.UUID.UUIDString;id<FxParameterSettingAPI_v6>s=[self->_apiManager apiForProtocol:@protocol(FxParameterSettingAPI_v6)];BOOL accepted=[s setStringParameterValue:session toParameter:DYCanvasSessionParameterID];os_log(OS_LOG_DEFAULT,"dayu_tool_canvas_registered accepted=%{public}d",(int)accepted);{self->_toolSession=[session copy];@synchronized(DYToolCanvasSessions()){[DYToolCanvasSessions()setObject:self forKey:session];}}}}@finally{[a endAction:self];}});
|
||||
@@ -17,13 +17,13 @@
|
||||
- (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 {};double aspect=tile.pixelAspect;if(!std::isfinite(aspect)||aspect<=0)return {};aspect=MAX(.01,aspect);double displayHeight=texture.height/aspect,scale=MIN(1.,MIN(1280./texture.width,720./displayHeight));unsigned width=(unsigned)floor(texture.width*scale),height=(unsigned)floor(displayHeight*scale);if(width<16||height<16||height>720||width>1280)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;
|
||||
}
|
||||
}
|
||||
- (NSMutableDictionary*)toolMask:(NSString*)maskID node:(NSString*)nodeID document:(NSDictionary*)doc {for(NSMutableDictionary *m in DYMasksForTool(doc,nodeID))if([m[@"id"]isEqual:maskID])return m;return nil;}
|
||||
- (void)toolStatus:(NSString*)message {
|
||||
NSString *node=[[_trackingNode?:_selectedToolNode copy]autorelease];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolTrackingStatus" object:self->_apiManager userInfo:@{@"node":node?:@"",@"message":message?:@""}];});
|
||||
NSString *node=[[_trackingNode?:_selectedToolNode copy]autorelease],*mask=[[_trackingMaskID?:_selectedToolMask copy]autorelease];dispatch_async(dispatch_get_main_queue(),^{[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolTrackingStatus" object:self->_apiManager userInfo:@{@"node":node?:@"",@"mask":mask?:@"",@"message":message?:@""}];});
|
||||
}
|
||||
- (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");
|
||||
@@ -67,7 +67,7 @@
|
||||
CMTime lo=_trackingBackward?input.start:ref,hi=_trackingBackward?CMTimeAdd(ref,step):end;if(_trackingSingle){if(_trackingBackward){lo=CMTimeSubtract(ref,step);if(CMTimeCompare(lo,input.start)<0)lo=input.start;}else hi=CMTimeAdd(ref,CMTimeMultiply(step,2));}if(CMTimeCompare(hi,end)>0)hi=end;if(_trackingBackward&&CMTimeCompare(ref,input.start)==0&&!_trackingBoth){[_trackingMessage release];_trackingMessage=[@"已到片段边界,未产生新轨迹" copy];}*out=CMTimeRangeFromTimeToTime(lo,hi);return out->duration.value>0;
|
||||
}
|
||||
- (BOOL)setupAnalysisForTimeRange:(CMTimeRange)range frameDuration:(CMTime)duration error:(NSError**)error {
|
||||
if(!CMTIME_IS_NUMERIC(duration)||duration.value<=0||duration.epoch!=0)return [self stopToolAnalysis:@"宿主分析帧长无效" error:error];_trackingFrameDuration=duration;_trackingPreviousTime=kCMTimeInvalid;_trackingFlip=NO;[_trackingSamples removeAllObjects];auto backend=DYToolCreateMetalFlow([[NSBundle bundleForClass:self.class]URLForResource:@"default" withExtension:@"metallib"],error);if(!backend)return [self stopToolAnalysis:@"Metal 跟踪后端无法启动" error:error];_toolTracker.setBackend(backend);
|
||||
if(!CMTIME_IS_NUMERIC(duration)||duration.value<=0||duration.epoch!=0)return [self stopToolAnalysis:@"宿主分析帧长无效" error:error];_trackingFrameDuration=duration;_trackingPreviousTime=kCMTimeInvalid;_trackingFlip=NO;[_trackingSamples removeAllObjects];
|
||||
std::vector<dy::FlowPoint>polygon;NSData *nodes=_trackingCandidate[@"nodes"];if(_trackingSeed.kind==DYMaskBezier){auto path=dyFlattenMask((const DYBezierNode*)nodes.bytes,nodes.length/sizeof(DYBezierNode));for(int i=0;i<path.count;i++)polygon.push_back({path.x[i],path.y[i]});}else if(_trackingSeed.kind==DYMaskRectangle)polygon={{-.5f,-.5f},{.5f,-.5f},{.5f,.5f},{-.5f,.5f}};else for(int i=0;i<128;i++){float angle=i*(2.f*M_PI/128);polygon.push_back({.5f*std::cos(angle),.5f*std::sin(angle)});}_toolTracker.setMask(std::move(polygon));return YES;
|
||||
}
|
||||
- (BOOL)analyzeFrame:(FxImageTile*)tile atTime:(CMTime)time error:(NSError**)error {
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
}
|
||||
- (BOOL)renderToolsSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){return DYRenderWithPool(error,[&]()->BOOL{
|
||||
if(!tools)tools=@{@"schema":@1,@"layers":@[],@"baseMasks":@{}};if(!DYValidToolDocument(tools))return fail(error,@"工具或蒙版数据损坏,未更改原工程");
|
||||
if(tools[@"sharedMasks"])tools=DYResolvedToolDocument(tools);
|
||||
DYApplyRemovedBaseTools(&u,tools);paths=DYVisibleBaseToolPaths(paths,tools);if(DYBaseToolRemoved(tools,@"spider"))spider=nil;
|
||||
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.
|
||||
|
||||
+13
-1
@@ -2,7 +2,7 @@
|
||||
#import "DYModel.h"
|
||||
#include "MaskCore/DYMaskOperator.h"
|
||||
|
||||
enum { DYToolsParameterID=9002, DYCanvasSessionParameterID=9003, DYToolLimit=32, DYToolMaskLimit=16, DYToolKeyLimit=16384 };
|
||||
enum { DYToolsParameterID=9002, DYCanvasSessionParameterID=9003, DYToolLimit=32, DYToolMaskLimit=16, DYToolKeyLimit=16384, DYSharedMaskLimit=64 };
|
||||
// Immutable property-list author state. Host float IDs and the legacy ABI stay fixed.
|
||||
@interface DYToolDocument : NSObject<NSSecureCoding,NSCopying,FxCustomParameterInterpolation_v2>
|
||||
@property(nonatomic,copy) NSDictionary *document;
|
||||
@@ -31,6 +31,18 @@ BOOL DYWriteTools(id<PROAPIAccessing> manager,NSDictionary *document,CMTime time
|
||||
NSArray *DYMasksForTool(NSDictionary *document,NSString *nodeID);
|
||||
NSDictionary *DYToolWithID(NSDictionary *document,NSString *nodeID);
|
||||
BOOL DYSetToolMasks(NSMutableDictionary *document,NSString *nodeID,NSArray *masks);
|
||||
// Schema 3 owns each shared mask once. Tool arrays store {sharedID: UUID};
|
||||
// nodeID "shared" selects the library even before any tool is assigned.
|
||||
NSArray *DYSharedMasks(NSDictionary *document);
|
||||
NSDictionary *DYSharedMaskWithID(NSDictionary *document,NSString *maskID);
|
||||
NSDictionary *DYAddSharedMask(NSMutableDictionary *document,NSInteger kind);
|
||||
BOOL DYSetSharedMaskAssigned(NSMutableDictionary *document,NSString *maskID,NSString *nodeID,BOOL assigned);
|
||||
NSArray *DYToolIDsForSharedMask(NSDictionary *document,NSString *maskID);
|
||||
BOOL DYRemoveSharedMask(NSMutableDictionary *document,NSString *maskID);
|
||||
NSDictionary *DYShareToolMask(NSMutableDictionary *document,NSString *nodeID,NSString *maskID);
|
||||
// Disposable render document. References become stable per-binding UUIDs;
|
||||
// editing must always use the original author document, never this expansion.
|
||||
NSDictionary *DYResolvedToolDocument(NSDictionary *document);
|
||||
DYMaskParameters DYMaskAtTime(NSDictionary *mask,CMTime time);
|
||||
NSDictionary *DYMaskKey(CMTime time,DYMaskParameters parameters,BOOL manual,float confidence);
|
||||
BOOL DYMergeTracking(NSMutableDictionary *mask,NSArray *samples);
|
||||
|
||||
+48
-9
@@ -3,6 +3,7 @@
|
||||
#include "DYFilmMath.h"
|
||||
#include <set>
|
||||
#import <objc/runtime.h>
|
||||
#import <CommonCrypto/CommonDigest.h>
|
||||
|
||||
NSArray *DYToolTypes(void){return @[@"primary",@"spider",@"base",@"skin",@"look",@"hsl",@"curve",@"grading",@"primaries",@"levels",@"blackwhite",@"balance",@"mixer",@"film",@"lens"];}
|
||||
NSDictionary *DYToolSection(NSString *type){for(NSDictionary *s in DYSections())if([s[@"key"]isEqual:type])return s;return nil;}
|
||||
@@ -70,22 +71,26 @@ BOOL DYValidToolMask(NSDictionary *mask){
|
||||
NSArray *keys=mask[@"keys"];if(![keys isKindOfClass:NSArray.class]||keys.count>DYToolKeyLimit)return NO;CMTime last=kCMTimeInvalid;
|
||||
for(NSDictionary *k in keys){if(![k isKindOfClass:NSDictionary.class]||!finiteNumber(k[@"value"])||!finiteNumber(k[@"scale"])||!finiteNumber(k[@"epoch"])||!finiteNumber(k[@"manual"])||!finiteNumber(k[@"confidence"])||[k[@"confidence"]doubleValue]<0||[k[@"confidence"]doubleValue]>1)return NO;CMTime t=keyTime(k);DYMaskParameters q;if(!CMTIME_IS_NUMERIC(t)||!readParameters(k[@"parameters"],&q)||q.kind!=p.kind||(CMTIME_IS_NUMERIC(last)&&(last.epoch!=t.epoch||CMTimeCompare(last,t)>=0)))return NO;last=t;}return YES;
|
||||
}
|
||||
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;}
|
||||
static BOOL validMasks(id masks,NSMutableSet *ids,NSSet *sharedIDs,BOOL references){
|
||||
if(![masks isKindOfClass:NSArray.class]||[masks count]>DYToolMaskLimit)return NO;NSMutableSet *links=[NSMutableSet set];
|
||||
for(NSDictionary *m in masks){if(![m isKindOfClass:NSDictionary.class])return NO;id shared=m[@"sharedID"];if(shared){if(!references||m.count!=1||![sharedIDs containsObject:shared]||[links containsObject:shared])return NO;[links addObject:shared];continue;}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[@"schema"]isEqual:@2])||![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[@"schema"]isEqual:@3])||![doc[@"layers"]isKindOfClass:NSArray.class]||[doc[@"layers"]count]>DYToolLimit||![doc[@"baseMasks"]isKindOfClass:NSDictionary.class]||[doc[@"baseMasks"]count]>DYToolTypes().count)return NO;
|
||||
BOOL references=[doc[@"schema"]isEqual:@3];id shared=doc[@"sharedMasks"];NSMutableSet *sharedIDs=[NSMutableSet set],*ids=[NSMutableSet set];if(shared){if(!references||![shared isKindOfClass:NSArray.class]||[shared count]>DYSharedMaskLimit)return NO;for(NSDictionary *mask in shared){if(!DYValidToolMask(mask)||[ids containsObject:mask[@"id"]]||mask[@"sharedID"])return NO;[ids addObject:mask[@"id"]];[sharedIDs addObject:mask[@"id"]];}}
|
||||
id removed=doc[@"removedBase"];if(removed){if(![removed isKindOfClass:NSArray.class]||[removed count]>DYToolTypes().count)return NO;NSMutableSet *unique=[NSMutableSet set];for(id type in removed){if(![type isKindOfClass:NSString.class]||![DYToolTypes()containsObject:type]||[unique containsObject:type]||[doc[@"baseMasks"][type]count])return NO;[unique addObject:type];}}
|
||||
NSMutableSet *ids=[NSMutableSet set];for(NSString *key in doc[@"baseMasks"]){if(![DYToolTypes()containsObject:key]||!validMasks(doc[@"baseMasks"][key],ids))return NO;}
|
||||
for(NSString *key in doc[@"baseMasks"]){if(![DYToolTypes()containsObject:key]||!validMasks(doc[@"baseMasks"][key],ids,sharedIDs,references))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(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)return NO;[ids addObject:node[@"id"]];if(!validMasks(node[@"masks"],ids,sharedIDs,references))return NO;
|
||||
if(node[@"primaryFollow"]&&(![node[@"type"]isEqual:@"primary"]||!finiteNumber(node[@"primaryFollow"])||[node[@"primaryFollow"]doubleValue]!=floor([node[@"primaryFollow"]doubleValue])||[node[@"primaryFollow"]integerValue]<0||[node[@"primaryFollow"]integerValue]>7))return NO;
|
||||
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;
|
||||
}
|
||||
// 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;
|
||||
for(NSDictionary *node in doc[@"layers"]){id after=node[@"after"];if(!after)continue;if([doc[@"schema"]isEqual:@1]||![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(NSDictionary *mask in shared)totalKeys+=[mask[@"keys"]count];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;}
|
||||
@@ -105,16 +110,50 @@ NSDictionary *DYToolWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *n i
|
||||
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;}
|
||||
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)];if(![doc[@"schema"]isEqual:@3])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;}
|
||||
NSArray *DYSharedMasks(NSDictionary *doc){return [doc[@"sharedMasks"]isKindOfClass:NSArray.class]?doc[@"sharedMasks"]:@[];}
|
||||
NSDictionary *DYSharedMaskWithID(NSDictionary *doc,NSString *ID){for(NSDictionary *mask in DYSharedMasks(doc))if([mask[@"id"]isEqual:ID])return mask;return nil;}
|
||||
static NSArray *DYRawMasksForTool(NSDictionary *doc,NSString *ID){return [ID hasPrefix:@"base:"]?doc[@"baseMasks"][[ID substringFromIndex:5]]?:@[]:DYToolWithID(doc,ID)[@"masks"]?:@[];}
|
||||
NSArray *DYMasksForTool(NSDictionary *doc,NSString *ID){
|
||||
if([ID isEqual:@"shared"])return DYSharedMasks(doc);NSArray *raw=DYRawMasksForTool(doc,ID);BOOL references=NO;for(NSDictionary *mask in raw)references|=mask[@"sharedID"]!=nil;if(!references)return raw;
|
||||
NSMutableArray *resolved=[NSMutableArray arrayWithCapacity:raw.count];for(NSDictionary *mask in raw){NSDictionary *object=mask[@"sharedID"]?DYSharedMaskWithID(doc,mask[@"sharedID"]):mask;if(object)[resolved addObject:object];}return resolved;
|
||||
}
|
||||
static BOOL DYStoreRawMasks(NSMutableDictionary *doc,NSString *ID,NSArray *masks){if([ID hasPrefix:@"base:"]){NSString *type=[ID substringFromIndex:5];if(![DYToolTypes()containsObject:type]||DYBaseToolRemoved(doc,type))return NO;doc[@"baseMasks"][type]=masks;}else{NSMutableDictionary *node=(id)DYToolWithID(doc,ID);if(!node)return NO;node[@"masks"]=masks;}return YES;}
|
||||
BOOL DYSetToolMasks(NSMutableDictionary *doc,NSString *ID,NSArray *masks){
|
||||
if(![masks isKindOfClass:NSArray.class])return NO;
|
||||
if([ID isEqual:@"shared"]){if(masks.count>DYSharedMaskLimit)return NO;NSMutableSet *kept=[NSMutableSet set];for(NSDictionary *mask in masks){if(!DYValidToolMask(mask)||[kept containsObject:mask[@"id"]])return NO;[kept addObject:mask[@"id"]];}for(NSDictionary *old in [[DYSharedMasks(doc)copy]autorelease])if(![kept containsObject:old[@"id"]])DYRemoveSharedMask(doc,old[@"id"]);doc[@"schema"]=@3;doc[@"sharedMasks"]=[NSMutableArray arrayWithArray:masks];return YES;}
|
||||
if(masks.count>DYToolMaskLimit)return NO;NSMutableArray *raw=[NSMutableArray arrayWithCapacity:masks.count];NSMutableSet *seen=[NSMutableSet set];for(NSDictionary *mask in masks){NSString *shared=mask[@"sharedID"]?:mask[@"id"];if(!shared||[seen containsObject:shared])return NO;[seen addObject:shared];if(DYSharedMaskWithID(doc,shared))[raw addObject:@{@"sharedID":shared}];else if(mask[@"sharedID"]||!DYValidToolMask(mask))return NO;else[raw addObject:mask];}return DYStoreRawMasks(doc,ID,raw);
|
||||
}
|
||||
NSDictionary *DYAddSharedMask(NSMutableDictionary *doc,NSInteger kind){
|
||||
if(!DYValidToolDocument(doc)||DYSharedMasks(doc).count>=DYSharedMaskLimit)return nil;NSDictionary *fresh=DYNewMask(kind);if(!fresh)return nil;NSMutableDictionary *mask=DYMutablePlist(fresh);NSMutableArray *shared=[NSMutableArray arrayWithArray:DYSharedMasks(doc)];[shared addObject:mask];doc[@"schema"]=@3;doc[@"sharedMasks"]=shared;return mask;
|
||||
}
|
||||
BOOL DYSetSharedMaskAssigned(NSMutableDictionary *doc,NSString *maskID,NSString *nodeID,BOOL assigned){
|
||||
if(!DYSharedMaskWithID(doc,maskID)||[nodeID isEqual:@"shared"])return NO;if([nodeID hasPrefix:@"base:"]){NSString *type=[nodeID substringFromIndex:5];if(![DYToolTypes()containsObject:type]||DYBaseToolRemoved(doc,type))return NO;}else if(!DYToolWithID(doc,nodeID))return NO;
|
||||
NSMutableArray *raw=[NSMutableArray arrayWithArray:DYRawMasksForTool(doc,nodeID)];NSUInteger index=[raw indexOfObjectPassingTest:^BOOL(NSDictionary *entry,NSUInteger i,BOOL *stop){return [entry[@"sharedID"]isEqual:maskID];}];if(assigned){if(index!=NSNotFound)return YES;if(raw.count>=DYToolMaskLimit)return NO;[raw addObject:@{@"sharedID":maskID}];}else if(index!=NSNotFound)[raw removeObjectAtIndex:index];return DYStoreRawMasks(doc,nodeID,raw);
|
||||
}
|
||||
NSArray *DYToolIDsForSharedMask(NSDictionary *doc,NSString *maskID){NSMutableArray *nodes=[NSMutableArray array];for(NSString *ID in DYToolDisplayOrder(doc))for(NSDictionary *entry in DYRawMasksForTool(doc,ID))if([entry[@"sharedID"]isEqual:maskID]){[nodes addObject:ID];break;}return nodes;}
|
||||
BOOL DYRemoveSharedMask(NSMutableDictionary *doc,NSString *maskID){
|
||||
if(!DYSharedMaskWithID(doc,maskID))return NO;for(NSString *ID in DYToolIDsForSharedMask(doc,maskID))if(!DYSetSharedMaskAssigned(doc,maskID,ID,NO))return NO;NSMutableArray *shared=[NSMutableArray arrayWithArray:DYSharedMasks(doc)];NSIndexSet *indices=[shared indexesOfObjectsPassingTest:^BOOL(NSDictionary *mask,NSUInteger i,BOOL *stop){return [mask[@"id"]isEqual:maskID];}];[shared removeObjectsAtIndexes:indices];doc[@"sharedMasks"]=shared;return YES;
|
||||
}
|
||||
NSDictionary *DYShareToolMask(NSMutableDictionary *doc,NSString *nodeID,NSString *maskID){
|
||||
NSDictionary *shared=DYSharedMaskWithID(doc,maskID);if(shared)return shared;if([nodeID isEqual:@"shared"]||!DYValidToolDocument(doc)||DYSharedMasks(doc).count>=DYSharedMaskLimit)return nil;
|
||||
NSMutableArray *raw=[NSMutableArray arrayWithArray:DYRawMasksForTool(doc,nodeID)];NSUInteger index=[raw indexOfObjectPassingTest:^BOOL(NSDictionary *mask,NSUInteger i,BOOL *stop){return [mask[@"id"]isEqual:maskID];}];if(index==NSNotFound)return nil;NSMutableDictionary *mask=DYMutablePlist(raw[index]);NSMutableArray *library=[NSMutableArray arrayWithArray:DYSharedMasks(doc)];[library addObject:mask];raw[index]=@{@"sharedID":maskID};if(!DYStoreRawMasks(doc,nodeID,raw))return nil;doc[@"schema"]=@3;doc[@"sharedMasks"]=library;return mask;
|
||||
}
|
||||
static NSString *DYResolvedMaskID(NSString *maskID,NSString *nodeID){NSData *input=[[NSString stringWithFormat:@"%@/%@",maskID,nodeID]dataUsingEncoding:NSUTF8StringEncoding];unsigned char digest[CC_SHA256_DIGEST_LENGTH];CC_SHA256(input.bytes,(CC_LONG)input.length,digest);digest[6]=(digest[6]&0x0f)|0x50;digest[8]=(digest[8]&0x3f)|0x80;return [[[NSUUID alloc]initWithUUIDBytes:digest]autorelease].UUIDString;}
|
||||
static NSDictionary *DYExpandSharedMasks(NSDictionary *doc,BOOL keepKeys){
|
||||
if(![doc[@"schema"]isEqual:@3])return doc;NSMutableDictionary *out=[[doc mutableCopy]autorelease],*base=[NSMutableDictionary dictionary];
|
||||
auto resolve=[&](NSString *nodeID){NSMutableArray *masks=[NSMutableArray array];for(NSDictionary *entry in DYRawMasksForTool(doc,nodeID)){if(entry[@"sharedID"]){NSDictionary *shared=DYSharedMaskWithID(doc,entry[@"sharedID"]);if(!shared)continue;NSMutableDictionary *copy=[[shared mutableCopy]autorelease];copy[@"sourceSharedID"]=shared[@"id"];copy[@"id"]=DYResolvedMaskID(shared[@"id"],nodeID);if(!keepKeys)copy[@"keys"]=@[];[masks addObject:copy];}else[masks addObject:entry];}return masks;};
|
||||
for(NSString *type in doc[@"baseMasks"])base[type]=resolve([@"base:" stringByAppendingString:type]);out[@"baseMasks"]=base;NSMutableArray *layers=[NSMutableArray array];for(NSDictionary *node in doc[@"layers"]){NSMutableDictionary *copy=[[node mutableCopy]autorelease];copy[@"masks"]=resolve(node[@"id"]);[layers addObject:copy];}out[@"layers"]=layers;out[@"schema"]=@2;[out removeObjectForKey:@"sharedMasks"];return out;
|
||||
}
|
||||
NSDictionary *DYResolvedToolDocument(NSDictionary *doc){return DYExpandSharedMasks(doc,NO);}
|
||||
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;
|
||||
// Only temporal geometry/feather/strength interpolate; key selection and levels stay authored.
|
||||
float *v=&p.centerX,*av=&a.centerX,*bv=&b.centerX;for(int i=0;i<8;i++)v[i]=av[i]+(bv[i]-av[i])*w;return p;}
|
||||
NSDictionary *DYMaskKey(CMTime t,DYMaskParameters p,BOOL manual,float confidence){return @{@"value":@(t.value),@"scale":@(t.timescale),@"epoch":@(t.epoch),@"parameters":parameterData(p),@"manual":@(manual),@"confidence":@(confidence)};}
|
||||
BOOL DYMergeTracking(NSMutableDictionary *m,NSArray *samples){if(!samples.count)return YES;NSMutableArray *all=[NSMutableArray array];CMTime lo=keyTime(samples.firstObject),hi=keyTime(samples.lastObject);if(CMTimeCompare(lo,hi)>0)std::swap(lo,hi);for(NSDictionary *key in m[@"keys"])if([key[@"manual"]boolValue]||CMTimeCompare(keyTime(key),lo)<0||CMTimeCompare(keyTime(key),hi)>0)[all addObject:key];for(NSDictionary *key in samples){BOOL manual=NO;for(NSDictionary *old in all)if(CMTimeCompare(keyTime(old),keyTime(key))==0){manual=YES;break;}if(!manual)[all addObject:key];}[all sortUsingComparator:^NSComparisonResult(NSDictionary *a,NSDictionary *b){return (NSComparisonResult)CMTimeCompare(keyTime(a),keyTime(b));}];NSMutableDictionary *candidate=DYMutablePlist(m);candidate[@"keys"]=all;if(!DYValidToolMask(candidate))return NO;m[@"keys"]=all;return YES;}
|
||||
NSDictionary *DYToolRenderSnapshot(NSDictionary *doc,CMTime t){
|
||||
doc=DYExpandSharedMasks(doc,YES);
|
||||
auto resolve=[&](NSArray *masks){NSMutableArray *result=[NSMutableArray arrayWithCapacity:masks.count];for(NSDictionary *mask in masks){NSMutableDictionary *m=[[mask mutableCopy]autorelease];m[@"parameters"]=parameterData(DYMaskAtTime(mask,t));m[@"keys"]=@[];[result addObject:m];}return result;};
|
||||
NSMutableDictionary *out=[[doc mutableCopy]autorelease],*base=[NSMutableDictionary dictionary];for(NSString *type in doc[@"baseMasks"])base[type]=resolve(doc[@"baseMasks"][type]);out[@"baseMasks"]=base;NSMutableArray *layers=[NSMutableArray array];for(NSDictionary *node in doc[@"layers"]){NSMutableDictionary *layer=[[node mutableCopy]autorelease];layer[@"masks"]=resolve(node[@"masks"]);[layers addObject:layer];}out[@"layers"]=layers;return out;
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@
|
||||
{
|
||||
const NSUInteger w=3840,h=2160;DYDiagnosticTile *fine=[[[DYDiagnosticTile alloc]initWithDevice:gpu width:w height:h]autorelease];Pixels pixels(w*h*4);
|
||||
for(NSUInteger y=0;y<h;y++)for(NSUInteger x=0;x<w;x++){float encoded=x%3==1?.8f:.2f,linear=powf((encoded+.055f)/1.055f,2.4f);auto i=(y*w+x)*4;pixels[i]=pixels[i+1]=pixels[i+2]=linear;pixels[i+3]=1;}
|
||||
[[fine metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,w,h) mipmapLevel:0 withBytes:pixels.data() bytesPerRow:w*8];auto gray=[plugin toolGrayFrame:fine error:nil];double maximum=0;for(float v:gray.pixels)maximum=std::max(maximum,fabs(v-.4));
|
||||
run.record(@"tracking-4k-frame-lowpass-before-normalized-motion-grid",gray.valid()&&gray.width==1280&&gray.height==720&&maximum<.002,@{@"width":@(gray.width),@"height":@(gray.height),@"maximumError":@(maximum)});
|
||||
[[fine metalTextureForDevice:gpu]replaceRegion:MTLRegionMake2D(0,0,w,h) mipmapLevel:0 withBytes:pixels.data() bytesPerRow:w*8];auto gray=[plugin toolGrayFrame:fine error:nil];double maximum=0;for(NSUInteger y=0;y<(NSUInteger)gray.height;y++)for(NSUInteger x=0;x<(NSUInteger)gray.width;x++){float expected=x%3==1?.8f:.2f;maximum=std::max(maximum,fabs(gray.pixels[y*gray.width+x]-expected));}
|
||||
run.record(@"tracking-4k-frame-preserves-full-detail-for-opencv",gray.valid()&&gray.width==3840&&gray.height==2160&&maximum<.002,@{@"width":@(gray.width),@"height":@(gray.height),@"maximumError":@(maximum)});
|
||||
}
|
||||
[plugin release];
|
||||
}
|
||||
@@ -55,6 +55,6 @@ kernel void dyTrackFlow(device const float*prev[[buffer(0)]],device const float*
|
||||
// This analysis-only image never changes the full-resolution color render.
|
||||
kernel void dyToolCapture(texture2d<float> source [[texture(0)]],device float* pixels [[buffer(0)]],constant uint3& info [[buffer(1)]],uint2 pos [[thread_position_in_grid]]){
|
||||
if(pos.x>=info.x||pos.y>=info.y)return;constexpr sampler f(coord::normalized,address::clamp_to_edge,filter::linear);uint2 taps=clamp(uint2(ceil(float2(source.get_width(),source.get_height())/float2(info.xy))),uint2(1),uint2(8));float sum=0;
|
||||
for(uint y=0;y<taps.y;y++)for(uint x=0;x<taps.x;x++){float2 uv=(float2(pos)+(float2(x,y)+.5f)/float2(taps))/float2(info.xy);if(info.z)uv.y=1-uv.y;float4 sample=source.sample(f,uv);float3 linear=sample.a>0?sample.rgb/sample.a:float3(0);float3 encoded=select(1.055f*pow(max(linear,float3(0)),float3(1.f/2.4f))-.055f,linear*12.92f,linear<=.0031308f);sum+=dot(clamp(encoded,0.f,1.f),float3(.2126f,.7152f,.0722f));}
|
||||
for(uint y=0;y<taps.y;y++)for(uint x=0;x<taps.x;x++){float2 uv=(float2(pos)+(float2(x,y)+.5f)/float2(taps))/float2(info.xy);if(info.z)uv.y=1-uv.y;float4 sample=source.sample(f,uv);float3 linear=sample.a>0?sample.rgb/sample.a:float3(0);float3 encoded=select(1.055f*pow(max(linear,float3(0)),float3(1.f/2.4f))-.055f,linear*12.92f,linear<=.0031308f);sum+=dot(clamp(encoded,0.f,1.f),float3(.299f,.587f,.114f));}
|
||||
pixels[pos.y*info.x+pos.x]=sum/float(taps.x*taps.y);
|
||||
}
|
||||
@@ -18,27 +18,29 @@ static const NSInteger DYViewerPartBase=20000;
|
||||
@end
|
||||
@implementation DYViewerControls {
|
||||
DYViewerParameterBridge *_bridge;NSMutableArray *_panels,*_areas;DYViewerParameterPanel *_capture;
|
||||
NSRect _viewport,_rail;NSSize _size;CGFloat _scale;CMTime _time;NSInteger _pressed,_hover,_railPage;BOOL _hasViewport;
|
||||
NSRect _viewport,_rail;NSSize _size;CGFloat _scale;CMTime _time;NSInteger _pressed,_hover,_railPage;BOOL _hasViewport,_pendingSkinPreview;
|
||||
}
|
||||
@synthesize bridge=_bridge;
|
||||
- (instancetype)init{if((self=[super init])){_panels=[NSMutableArray new];_areas=[NSMutableArray new];_scale=1;_time=kCMTimeInvalid;}return self;}
|
||||
- (void)dealloc{[self finishCapture];[_bridge release];[_panels release];[_areas release];[super dealloc];}
|
||||
- (void)setBridge:(DYViewerParameterBridge*)bridge{if(bridge==_bridge)return;[self finishCapture];for(DYViewerParameterPanel*p in _panels)p.bridge=nil;[_panels removeAllObjects];[_bridge release];_bridge=[bridge retain];}
|
||||
- (void)setBridge:(DYViewerParameterBridge*)bridge{if(bridge==_bridge)return;[self finishCapture];for(DYViewerParameterPanel*p in _panels)p.bridge=nil;[_panels removeAllObjects];[_bridge release];_bridge=[bridge retain];_pendingSkinPreview=NO;}
|
||||
- (void)setViewport:(NSRect)viewport{_viewport=viewport;_hasViewport=YES;}
|
||||
- (void)prepareWithSize:(NSSize)size scale:(CGFloat)scale atTime:(CMTime)time{
|
||||
_size=size;_time=time;NSRect bounds=NSMakeRect(0,0,size.width,size.height),v=_hasViewport?NSIntersectionRect(_viewport,bounds):bounds;_viewport=v;
|
||||
_size=size;_time=time;
|
||||
if(_pendingSkinPreview){NSDictionary *snapshot=[_bridge snapshotAtTime:time];if(snapshot&&[self skinNodeInSnapshot:snapshot]){_pendingSkinPreview=NO;[self toggleSkinPreview];}}
|
||||
NSRect bounds=NSMakeRect(0,0,size.width,size.height),v=_hasViewport?NSIntersectionRect(_viewport,bounds):bounds;_viewport=v;
|
||||
_scale=MAX(.6,MIN(MAX(1.,scale),MIN(v.size.width/420.,v.size.height/350.)));CGFloat s=_scale;
|
||||
for(DYViewerParameterPanel*p in [[_panels copy]autorelease]){if(!p.visible){if(p==_capture){[p finishCapture];_capture=nil;}p.bridge=nil;[_panels removeObjectIdenticalTo:p];continue;}[p setViewport:v];[p prepareWithSize:size scale:s atTime:time];}
|
||||
if(_capture&&![_capture capturing])_capture=nil;
|
||||
[_areas removeAllObjects];if(!_bridge||v.size.width<100||v.size.height<80)return;
|
||||
NSInteger toolCount=DYToolTypes().count;NSInteger cap=MAX(1,MIN(toolCount,(NSInteger)floor((v.size.height-72*s)/(30*s))));if(cap<toolCount)cap=MAX(1,MIN(toolCount-1,(NSInteger)floor((v.size.height-96*s)/(30*s))));NSInteger pages=(toolCount+cap-1)/cap;_railPage=MAX(0,_railPage)%pages;
|
||||
CGFloat x=NSMinX(v)+8*s,y=NSMinY(v)+8*s,w=40*s;
|
||||
_rail=NSMakeRect(x,y,w,(30*MIN(cap,toolCount-_railPage*cap)+54+(pages>1?24:0))*s);
|
||||
NSArray*titles=@[@"一级",@"蜘蛛",@"基础",@"肤色",@"LUT",@"HSL",@"曲线",@"分级",@"原色",@"色阶",@"黑白",@"平衡",@"通道",@"胶片",@"畸变"];
|
||||
for(NSInteger j=0;j<cap&&j+_railPage*cap<toolCount;j++){NSInteger i=j+_railPage*cap;[_areas addObject:@{@"part":@(20020+i),@"kind":@"tool",@"toolType":DYToolTypes()[i],@"title":titles[i],@"rect":[NSValue valueWithRect:NSMakeRect(x+4*s,y+5*s+j*30*s,w-8*s,26*s)]}];}
|
||||
CGFloat end=NSMaxY(_rail)-47*s;if(pages>1){[_areas addObject:@{@"part":@20003,@"kind":@"railPage",@"title":@"↕",@"rect":[NSValue valueWithRect:NSMakeRect(x+4*s,end-24*s,w-8*s,22*s)]}];}
|
||||
[_areas addObject:@{@"part":@20001,@"kind":@"workspace",@"title":@"◫",@"rect":[NSValue valueWithRect:NSMakeRect(x+4*s,end,w-8*s,26*s)]}];
|
||||
[_areas addObject:@{@"part":@20002,@"kind":@"hidePanels",@"title":@"收",@"rect":[NSValue valueWithRect:NSMakeRect(x+4*s,end+27*s,w-8*s,18*s)]}];
|
||||
// Only tools that benefit from direct image interaction belong on the canvas.
|
||||
NSArray *types=@[@"curve",@"lens",@"skin",@"look"],*titles=@[@"曲线",@"畸变",@"肤色",@"LUT"];
|
||||
CGFloat railScale=MIN(s,MAX(.3,v.size.height/280.));CGFloat x=NSMinX(v)+8*railScale,y=NSMinY(v)+8*railScale,w=36*railScale;
|
||||
_rail=NSMakeRect(x,y,w,196*railScale);
|
||||
for(NSInteger i=0;i<3;i++)[_areas addObject:@{@"part":@(20010+i),@"kind":@"mask",@"index":@([@[@1,@0,@2][i]integerValue]),@"title":@[@"矩形",@"椭圆",@"钢笔"][i],@"rect":[NSValue valueWithRect:NSMakeRect(x,y+i*28*railScale,w,25*railScale)]}];
|
||||
for(NSInteger i=0;i<4;i++)[_areas addObject:@{@"part":@(20020+i),@"kind":@"tool",@"toolType":types[i],@"title":titles[i],@"rect":[NSValue valueWithRect:NSMakeRect(x,y+(i+3)*28*railScale,w,25*railScale)]}];
|
||||
CGFloat buttonWidth=MIN(100*s,v.size.width-16*s),buttonHeight=MIN(27*s,MAX(16.,v.size.height*.16));
|
||||
[_areas addObject:@{@"part":@20001,@"kind":@"workspace",@"title":@"控制面板",@"rect":[NSValue valueWithRect:NSMakeRect(NSMidX(v)-buttonWidth/2,NSMaxY(v)-buttonHeight-8*railScale,buttonWidth,buttonHeight)]}];
|
||||
}
|
||||
- (NSInteger)partAtPoint:(NSPoint)p{
|
||||
if(!_bridge||!std::isfinite(p.x)||!std::isfinite(p.y)||!NSPointInRect(p,_viewport))return 0;
|
||||
@@ -47,20 +49,42 @@ static const NSInteger DYViewerPartBase=20000;
|
||||
return 0;
|
||||
}
|
||||
- (BOOL)headerAtPoint:(NSPoint)p{if(NSPointInRect(p,_rail))return NO;for(DYViewerParameterPanel*panel in [_panels reverseObjectEnumerator]){NSInteger part=[panel partAtPoint:p];if(part)return part==20000;}return NO;}
|
||||
- (NSString*)skinNodeInSnapshot:(NSDictionary*)snapshot{
|
||||
NSDictionary *doc=snapshot[@"document"];if(!doc)return nil;NSString *node=snapshot[@"selectedNode"];
|
||||
if([node isEqual:@"base:skin"]&&!DYBaseToolRemoved(doc,@"skin"))return node;
|
||||
if([DYToolWithID(doc,node)[@"type"]isEqual:@"skin"])return node;
|
||||
if(!DYBaseToolRemoved(doc,@"skin"))return @"base:skin";
|
||||
for(NSString *ID in DYToolDisplayOrder(doc))if([DYToolWithID(doc,ID)[@"type"]isEqual:@"skin"])return ID;return nil;
|
||||
}
|
||||
- (BOOL)skinPreviewEnabled{
|
||||
NSDictionary *snapshot=[_bridge snapshotAtTime:_time];NSString *node=[self skinNodeInSnapshot:snapshot];if(!node)return NO;DYUniforms u;
|
||||
if([node hasPrefix:@"base:"]){NSData *raw=snapshot[@"uniforms"];if(raw.length!=sizeof(u))return NO;[raw getBytes:&u length:sizeof(u)];}else u=DYToolUniforms(DYToolWithID(snapshot[@"document"],node));return u.skinVisualize>.5;
|
||||
}
|
||||
- (void)toggleSkinPreview{
|
||||
NSDictionary *snapshot=[_bridge snapshotAtTime:_time];if(!snapshot)return;NSString *node=[self skinNodeInSnapshot:snapshot];
|
||||
if(!node){_pendingSkinPreview=YES;[_bridge requestTool:@"skin"];return;}
|
||||
DYUniforms u;if([node hasPrefix:@"base:"]){NSData *raw=snapshot[@"uniforms"];if(raw.length!=sizeof(u))return;[raw getBytes:&u length:sizeof(u)];}else u=DYToolUniforms(DYToolWithID(snapshot[@"document"],node));
|
||||
for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:@"skinVisualize"]){[_bridge beginParameter:d node:node value:u.skinVisualize atTime:_time];[_bridge changeValue:u.skinVisualize>.5?0:1];[_bridge endGesture];break;}
|
||||
}
|
||||
- (void)draw{
|
||||
if(!_areas.count)return;[NSGraphicsContext saveGraphicsState];NSRectClip(_viewport);CGFloat s=_scale;NSColor*ink=DYThemeColor(@"text"),*accent=DYThemeColor(@"accent");for(DYViewerParameterPanel*p in _panels)[p draw];DYDrawThemeSurface([NSBezierPath bezierPathWithRoundedRect:_rail xRadius:8*s yRadius:8*s],YES);
|
||||
for(NSDictionary*a in _areas){NSRect r=[a[@"rect"]rectValue];BOOL selected=NO;for(DYViewerParameterPanel*p in _panels)if([p.toolType isEqual:a[@"toolType"]])selected=YES;
|
||||
BOOL hover=_hover==[a[@"part"]integerValue];DYDrawSoftControl(r,5*s,NO,selected||hover,_pressed==[a[@"part"]integerValue]);
|
||||
if(!_areas.count)return;[NSGraphicsContext saveGraphicsState];NSRectClip(_viewport);CGFloat s=_scale;for(DYViewerParameterPanel*p in _panels)[p draw];
|
||||
for(NSDictionary*a in _areas){NSRect r=[a[@"rect"]rectValue];BOOL selected=[a[@"toolType"]isEqual:@"skin"]&&[self skinPreviewEnabled];for(DYViewerParameterPanel*p in _panels)if([p.toolType isEqual:a[@"toolType"]])selected=YES;
|
||||
BOOL hover=_hover==[a[@"part"]integerValue];
|
||||
// Text and its narrow shadow stay readable without tinting the review image.
|
||||
NSMutableParagraphStyle*style=[[[NSMutableParagraphStyle alloc]init]autorelease];style.alignment=NSTextAlignmentCenter;
|
||||
[a[@"title"]drawInRect:NSInsetRect(r,1*s,4*s) withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:([a[@"kind"]isEqual:@"workspace"]?16:10)*s weight:NSFontWeightMedium],NSForegroundColorAttributeName:selected?accent:ink,NSParagraphStyleAttributeName:style}];
|
||||
NSShadow *shadow=[[[NSShadow alloc]init]autorelease];shadow.shadowColor=[NSColor colorWithWhite:0 alpha:.95];shadow.shadowBlurRadius=2;shadow.shadowOffset=NSMakeSize(0,-1);
|
||||
CGFloat fontSize=MIN(11*s,r.size.height*.44);NSDictionary *attributes=@{NSFontAttributeName:[NSFont systemFontOfSize:fontSize weight:selected||hover?NSFontWeightBold:NSFontWeightMedium],NSForegroundColorAttributeName:selected||hover?NSColor.systemCyanColor:NSColor.whiteColor,NSParagraphStyleAttributeName:style,NSShadowAttributeName:shadow};
|
||||
[a[@"title"]drawInRect:NSInsetRect(r,1,MAX(1.,(r.size.height-fontSize-3)/2)) withAttributes:attributes];
|
||||
if(selected){NSBezierPath *mark=[NSBezierPath bezierPath];[mark moveToPoint:NSMakePoint(NSMinX(r),NSMidY(r)-3*s)];[mark lineToPoint:NSMakePoint(NSMinX(r),NSMidY(r)+3*s)];[NSColor.systemCyanColor setStroke];mark.lineWidth=2*s;[mark stroke];}
|
||||
}
|
||||
for(NSDictionary*a in _areas)if(_hover==[a[@"part"]integerValue]){NSString*help=[a[@"kind"]isEqual:@"workspace"]?@"打开示波器与 LUT 工作区":[a[@"kind"]isEqual:@"hidePanels"]?@"收起所有画布面板":a[@"toolType"]?DYToolSection(a[@"toolType"])[@"title"]:@"下一组工具";NSRect r=[a[@"rect"]rectValue];NSRect tip=NSMakeRect(NSMaxX(_rail)+6*s,NSMinY(r),MIN(200*s,NSMaxX(_viewport)-NSMaxX(_rail)-10*s),25*s);if(tip.size.width>40*s){DYDrawThemeSurface([NSBezierPath bezierPathWithRoundedRect:tip xRadius:4*s yRadius:4*s],YES);[help drawInRect:NSInsetRect(tip,6*s,5*s)withAttributes:@{NSFontAttributeName:[NSFont systemFontOfSize:10*s],NSForegroundColorAttributeName:ink}];}break;}
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
}
|
||||
- (void)activateTool:(NSString*)type{
|
||||
if([type isEqual:@"look"]){[_bridge requestWorkspacePage:@"lut"];return;}
|
||||
if([type isEqual:@"skin"]){[self toggleSkinPreview];return;}
|
||||
for(DYViewerParameterPanel*p in [[_panels copy]autorelease])if([p.toolType isEqual:type]){[p finishCapture];p.bridge=nil;[_panels removeObjectIdenticalTo:p];return;}
|
||||
[_bridge requestTool:type];DYViewerParameterPanel*p=[[[DYViewerParameterPanel alloc]init]autorelease];p.toolType=type;p.bridge=_bridge;
|
||||
CGFloat x=(_rail.size.width+24*_scale)/MAX(1.,_viewport.size.width),offset=(_panels.count%4)*22*_scale;
|
||||
CGFloat x=(_rail.size.width+24*_scale)/MAX(1.,_viewport.size.width),offset=0;
|
||||
[p setInitialPosition:NSMakePoint(x+offset/MAX(1.,_viewport.size.width),(8*_scale+offset)/MAX(1.,_viewport.size.height))];[_panels addObject:p];
|
||||
}
|
||||
- (BOOL)event:(NSEventType)type point:(NSPoint)p atTime:(CMTime)time{
|
||||
@@ -72,7 +96,7 @@ static const NSInteger DYViewerPartBase=20000;
|
||||
if(!hit)return NO;_pressed=hit;return YES;
|
||||
}
|
||||
if(!_pressed)return NO;
|
||||
if(type==NSEventTypeLeftMouseUp){NSInteger pressed=_pressed;_pressed=0;if(hit==pressed){for(NSDictionary*a in _areas)if([a[@"part"]integerValue]==hit){NSString*kind=a[@"kind"];if([kind isEqual:@"tool"])[self activateTool:a[@"toolType"]];else if([kind isEqual:@"workspace"])[_bridge requestWorkspace];else if([kind isEqual:@"hidePanels"]){for(DYViewerParameterPanel*panel in _panels){[panel finishCapture];panel.bridge=nil;}[_panels removeAllObjects];}else if([kind isEqual:@"railPage"])_railPage++;break;}}[self prepareWithSize:_size scale:_scale atTime:time];}
|
||||
if(type==NSEventTypeLeftMouseUp){NSInteger pressed=_pressed;_pressed=0;if(hit==pressed){for(NSDictionary*a in _areas)if([a[@"part"]integerValue]==hit){NSString*kind=a[@"kind"];if([kind isEqual:@"tool"])[self activateTool:a[@"toolType"]];else if([kind isEqual:@"mask"])[_bridge requestMask:[a[@"index"]integerValue]];else if([kind isEqual:@"workspace"])[_bridge requestWorkspace];else if([kind isEqual:@"hidePanels"]){for(DYViewerParameterPanel*panel in _panels){[panel finishCapture];panel.bridge=nil;}[_panels removeAllObjects];}else if([kind isEqual:@"railPage"])_railPage++;break;}}[self prepareWithSize:_size scale:_scale atTime:time];}
|
||||
return YES;
|
||||
}
|
||||
- (BOOL)capturing{return _pressed||[_capture capturing];}
|
||||
|
||||
@@ -1,84 +1,75 @@
|
||||
{
|
||||
DYDiagnosticManager*base=[[[DYDiagnosticManager alloc]init]autorelease];DYCreateParameters(base,&error);
|
||||
DYToolCanvasProbe*host=[[[DYToolCanvasProbe alloc]init]autorelease];host->_base=base;host->_time=kCMTimeZero;
|
||||
id<DYViewerParameterProbe>bridge=(id)[[NSClassFromString(@"DYViewerParameterBridge")alloc]initWithAPIManager:host];
|
||||
id<DYViewerControlsProbe>controls=(id)[NSClassFromString(@"DYViewerControls")new];controls.bridge=bridge;
|
||||
NSSize size=NSMakeSize(1280,720);
|
||||
DYDiagnosticManager *base=[[[DYDiagnosticManager alloc]init]autorelease];DYCreateParameters(base,&error);
|
||||
DYToolCanvasProbe *host=[[[DYToolCanvasProbe alloc]init]autorelease];host->_base=base;host->_time=kCMTimeZero;
|
||||
id<DYViewerParameterProbe> bridge=(id)[[NSClassFromString(@"DYViewerParameterBridge")alloc]initWithAPIManager:host];
|
||||
id<DYViewerControlsProbe> controls=(id)[NSClassFromString(@"DYViewerControls")new];controls.bridge=bridge;NSSize size=NSMakeSize(1280,720);
|
||||
auto drain=[](){double end=NSProcessInfo.processInfo.systemUptime+.04;while(NSProcessInfo.processInfo.systemUptime<end)[[NSRunLoop mainRunLoop]runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.002]];};
|
||||
auto publish=[&](){DYUniforms u;DYReadUniforms(host,host->_time,&u);[bridge publishUniforms:&u document:DYReadTools(host,host->_time).document atTime:host->_time];[controls prepareWithSize:size scale:1 atTime:host->_time];};
|
||||
auto areaFor=[&](id owner,NSString*kind,NSString*key)->NSDictionary*{for(NSDictionary*a in [owner valueForKey:@"areas"])if([a[@"kind"]isEqual:kind]&&(!key||[a[@"descriptor"][@"key"]isEqual:key]||[a[@"toolType"]isEqual:key]||[a[@"nodeID"]isEqual:key]))return [[a copy]autorelease];return nil;};
|
||||
auto click=[&](NSDictionary*a){if(!a)return;NSRect r=[a[@"rect"]rectValue];NSPoint p=NSMakePoint(NSMidX(r),NSMidY(r));[controls event:NSEventTypeLeftMouseDown point:p atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:p atTime:host->_time];};
|
||||
auto panelFor=[&](NSString*type)->id{for(id panel in [controls valueForKey:@"panels"])if([[panel valueForKey:@"toolType"]isEqual:type])return panel;return nil;};
|
||||
auto value=[&](NSString*key)->double{for(NSDictionary*d in DYDescriptors())if([d[@"key"]isEqual:key])return [base->_values[d[@"pid"]]doubleValue];return NAN;};
|
||||
publish();int undo=base->_undoStarts;NSDictionary*initial=[[base->_values copy]autorelease];
|
||||
NSMutableSet*types=[NSMutableSet set];CGFloat x=-1,lastY=-1;BOOL vertical=YES;
|
||||
for(NSDictionary*a in [controls valueForKey:@"areas"])if([a[@"kind"]isEqual:@"tool"]){NSRect r=[a[@"rect"]rectValue];if(x>=0)vertical&=r.origin.x==x&&r.origin.y>lastY;x=r.origin.x;lastY=r.origin.y;[types addObject:a[@"toolType"]];}
|
||||
run.record(@"viewer-vertical-rail-exposes-all-tools-without-a-parameter-panel",vertical&&types.count==DYToolTypes().count&&[[controls valueForKey:@"panels"]count]==0);
|
||||
BOOL allOpen=YES;for(NSString*type in DYToolTypes()){click(areaFor(controls,@"tool",type));allOpen&=panelFor(type)!=nil;}
|
||||
run.record(@"viewer-tools-open-independent-panels-without-editing-the-grade",allOpen&&[[controls valueForKey:@"panels"]count]==DYToolTypes().count&&[initial isEqual:base->_values]&&base->_undoStarts==undo);
|
||||
click(areaFor(controls,@"hidePanels",nil));click(areaFor(controls,@"tool",@"base"));id panel=panelFor(@"base");
|
||||
NSRect before=[[panel valueForKey:@"panel"]rectValue],header=[areaFor(panel,@"open",nil)[@"rect"]rectValue];NSPoint hp=NSMakePoint(NSMidX(header),NSMidY(header));
|
||||
[controls event:NSEventTypeLeftMouseDown point:hp atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(hp.x+90,hp.y+20) atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:NSMakePoint(hp.x+140,hp.y+30) atTime:host->_time];NSRect after=[[panel valueForKey:@"panel"]rectValue];
|
||||
run.record(@"viewer-dragging-header-moves-panel-with-final-release-point-and-no-undo",fabs(after.origin.x-before.origin.x-140)<1e-5&&fabs(after.origin.y-before.origin.y-30)<1e-5&&![controls capturing]&&[initial isEqual:base->_values]&&base->_undoStarts==undo);
|
||||
NSDictionary*exposure=areaFor(panel,@"slider",@"exposure");NSRect row=[exposure[@"rect"]rectValue],track=NSMakeRect(row.origin.x+5,row.origin.y+28,row.size.width-10,4);NSPoint knob=NSMakePoint(NSMidX(track),NSMidY(track)),label=NSMakePoint(row.origin.x+10,row.origin.y+5);
|
||||
[controls event:NSEventTypeLeftMouseDown point:label atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:label atTime:host->_time];drain();
|
||||
[controls event:NSEventTypeLeftMouseDown point:knob atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(knob.x+1,knob.y+1)atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:NSMakePoint(knob.x+1,knob.y+1)atTime:host->_time];drain();
|
||||
run.record(@"viewer-label-and-knob-deadzone-do-not-create-edits",value(@"exposure")==0&&base->_undoStarts==undo);
|
||||
[controls event:NSEventTypeLeftMouseDown point:NSMakePoint(knob.x+5,knob.y)atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(knob.x+5+track.size.width*.1,knob.y)atTime:host->_time];drain();
|
||||
run.record(@"viewer-slider-preserves-grab-offset-and-updates-live",fabs(value(@"exposure")-1)<1e-5&&[controls capturing]&&base->_undoStarts==undo+1&&base->_undoEnds==undo);
|
||||
[controls event:NSEventTypeLeftMouseUp point:NSMakePoint(-100,1000)atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-slider-captures-outside-and-closes-one-undo",value(@"exposure")==-5&&![controls capturing]&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);click(areaFor(panel,@"reset",@"exposure"));drain();publish();
|
||||
click(areaFor(panel,@"headerBool",@"baseEnabled"));drain();publish();run.record(@"viewer-base-tone-and-color-eyes-remain-independent",value(@"baseEnabled")==0&&value(@"colorEnabled")==1);click(areaFor(panel,@"headerBool",@"baseEnabled"));drain();publish();
|
||||
// Empty panels cannot close the shared bridge gesture owned by a live panel.
|
||||
NSMutableDictionary*removedDoc=DYMutablePlist(DYReadTools(host,host->_time).document);DYSetBaseToolRemoved(removedDoc,@"film",YES);DYWriteTools(host,removedDoc,host->_time);publish();click(areaFor(controls,@"tool",@"film"));[panelFor(@"film")setValue:[NSValue valueWithPoint:NSMakePoint(.72,.1)]forKey:@"position"];publish();
|
||||
// Base is still visible; raise it by an inert label down/up.
|
||||
exposure=areaFor(panel,@"slider",@"exposure");row=[exposure[@"rect"]rectValue];label=NSMakePoint(row.origin.x+10,row.origin.y+5);[controls event:NSEventTypeLeftMouseDown point:label atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:label atTime:host->_time];
|
||||
track=NSMakeRect(row.origin.x+5,row.origin.y+28,row.size.width-10,4);knob=NSMakePoint(NSMidX(track),NSMidY(track));undo=base->_undoStarts;
|
||||
[controls event:NSEventTypeLeftMouseDown point:knob atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(knob.x+track.size.width*.1,knob.y)atTime:host->_time];drain();publish();[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(knob.x+track.size.width*.2,knob.y)atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:NSMakePoint(knob.x+track.size.width*.3,knob.y)atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-empty-removed-tool-never-terminates-another-panels-live-gesture",fabs(value(@"exposure")-3)<1e-5&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);
|
||||
click(areaFor(controls,@"tool",@"film"));click(areaFor(panel,@"reset",@"exposure"));drain();publish();
|
||||
auto areaFor=[&](id owner,NSString *kind,NSString *key)->NSDictionary *{for(NSDictionary *a in [owner valueForKey:@"areas"])if([a[@"kind"]isEqual:kind]&&(!key||[a[@"descriptor"][@"key"]isEqual:key]||[a[@"toolType"]isEqual:key]||[a[@"nodeID"]isEqual:key]))return [[a copy]autorelease];return nil;};
|
||||
auto click=[&](NSDictionary *a){if(!a)return;NSRect r=[a[@"rect"]rectValue];NSPoint p=NSMakePoint(NSMidX(r),NSMidY(r));[controls event:NSEventTypeLeftMouseDown point:p atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:p atTime:host->_time];};
|
||||
auto panelFor=[&](NSString *type)->id{for(id panel in [controls valueForKey:@"panels"])if([[panel valueForKey:@"toolType"]isEqual:type])return panel;return nil;};
|
||||
auto value=[&](NSString *key)->double{for(NSDictionary *d in DYDescriptors())if([d[@"key"]isEqual:key])return [base->_values[d[@"pid"]]doubleValue];return NAN;};
|
||||
publish();int undo=base->_undoStarts;NSDictionary *initial=[[base->_values copy]autorelease];
|
||||
NSMutableSet *types=[NSMutableSet set];NSInteger masks=0;CGFloat x=-1,lastY=-1;BOOL vertical=YES;
|
||||
for(NSDictionary *a in [controls valueForKey:@"areas"]){if([a[@"kind"]isEqual:@"mask"])masks++;if([a[@"kind"]isEqual:@"tool"]){NSRect r=[a[@"rect"]rectValue];if(x>=0)vertical&=r.origin.x==x&&r.origin.y>lastY;x=r.origin.x;lastY=r.origin.y;[types addObject:a[@"toolType"]];}}
|
||||
run.record(@"viewer-rail-has-only-four-image-tools-and-three-persistent-mask-shapes",vertical&&[types isEqual:[NSSet setWithArray:@[@"curve",@"lens",@"skin",@"look"]]]&&masks==3&&[[controls valueForKey:@"panels"]count]==0);
|
||||
NSDictionary *workspace=areaFor(controls,@"workspace",nil);NSRect workspaceRect=[workspace[@"rect"]rectValue];
|
||||
run.record(@"viewer-control-panel-entry-is-labelled-and-anchored-at-bottom",[workspace[@"title"]isEqual:@"控制面板"]&&NSMidY(workspaceRect)>size.height*.9);
|
||||
__block NSInteger workspaceRequests=0;__block NSString *requestedPage=nil;__block NSInteger requestedMask=-1;
|
||||
id observer=[NSNotificationCenter.defaultCenter addObserverForName:@"DYColorWorkspaceRequested" object:host queue:nil usingBlock:^(NSNotification *notification){workspaceRequests++;[requestedPage release];requestedPage=[notification.userInfo[@"page"]copy];if(notification.userInfo[@"maskKind"])requestedMask=[notification.userInfo[@"maskKind"]integerValue];}];
|
||||
click(areaFor(controls,@"tool",@"look"));drain();
|
||||
run.record(@"viewer-lut-entry-opens-browser-page-without-canvas-parameter-card",workspaceRequests==1&&[requestedPage isEqual:@"lut"]&&!panelFor(@"look")&&[initial isEqual:base->_values]&&base->_undoStarts==undo);
|
||||
click(workspace);drain();run.record(@"viewer-bottom-control-panel-opens-tools-workspace",workspaceRequests==2&&[requestedPage isEqual:@"tools"]);
|
||||
BOOL maskRoutes=YES;for(NSDictionary *a in [[[controls valueForKey:@"areas"]copy]autorelease])if([a[@"kind"]isEqual:@"mask"]){click(a);drain();maskRoutes&=[requestedPage isEqual:@"masks"]&&requestedMask==[a[@"index"]integerValue];}
|
||||
run.record(@"viewer-persistent-mask-entries-route-shapes-to-shared-workspace",maskRoutes&&base->_undoStarts==undo);
|
||||
[NSNotificationCenter.defaultCenter removeObserver:observer];[requestedPage release];
|
||||
click(areaFor(controls,@"tool",@"skin"));drain();publish();
|
||||
run.record(@"viewer-skin-entry-toggles-actual-protection-preview-without-parameter-card",value(@"skinVisualize")==1&&!panelFor(@"skin")&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);
|
||||
click(areaFor(controls,@"tool",@"skin"));drain();publish();run.record(@"viewer-skin-preview-toggle-restores-review-image",value(@"skinVisualize")==0&&!panelFor(@"skin"));
|
||||
click(areaFor(controls,@"tool",@"curve"));id curve=panelFor(@"curve");
|
||||
run.record(@"viewer-curve-opens-an-editable-graph-beside-existing-panel",curve&&panelFor(@"base")&&areaFor(curve,@"curvePlot",nil)&&!areaFor(curve,@"slider",nil));
|
||||
run.record(@"viewer-curve-is-graph-only-without-title-catalog-or-parameter-page",curve&&areaFor(curve,@"curvePlot",nil)&&!areaFor(curve,@"open",nil)&&!areaFor(curve,@"catalog",nil)&&!areaFor(curve,@"graphMode",nil)&&!areaFor(curve,@"slider",nil));
|
||||
NSRect plot=[areaFor(curve,@"curvePlot",nil)[@"rect"]rectValue];NSPoint point=NSMakePoint(plot.origin.x+.43*plot.size.width,plot.origin.y+.18*plot.size.height);undo=base->_undoStarts;
|
||||
[controls event:NSEventTypeLeftMouseDown point:point atTime:host->_time];NSString*xKey=[[[curve valueForKey:@"captured"][@"xKey"]copy]autorelease],*yKey=[[[curve valueForKey:@"captured"][@"yKey"]copy]autorelease];drain();
|
||||
[controls event:NSEventTypeLeftMouseDown point:point atTime:host->_time];NSString *xKey=[[[curve valueForKey:@"captured"][@"xKey"]copy]autorelease],*yKey=[[[curve valueForKey:@"captured"][@"yKey"]copy]autorelease];drain();
|
||||
[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(plot.origin.x+.54*plot.size.width,plot.origin.y+.23*plot.size.height)atTime:host->_time];drain();
|
||||
run.record(@"viewer-curve-point-is-live-xy-not-a-scalar-only-control",xKey&&yKey&&fabs(value(xKey)-.54)<1e-5&&fabs(value(yKey)-23)<1e-4&&base->_undoStarts==undo+1&&base->_undoEnds==undo);
|
||||
[controls event:NSEventTypeLeftMouseUp point:NSMakePoint(plot.origin.x+.61*plot.size.width,plot.origin.y+.3*plot.size.height)atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-curve-final-release-commits-both-axes-with-one-undo",fabs(value(xKey)-.61)<1e-5&&fabs(value(yKey)-9)<1e-4&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);
|
||||
undo=base->_undoStarts;NSDictionary*deleteArea=areaFor(curve,@"deletePoint",nil);click(deleteArea);drain();publish();
|
||||
undo=base->_undoStarts;NSDictionary *deleteArea=areaFor(curve,@"deletePoint",nil);click(deleteArea);drain();publish();
|
||||
run.record(@"viewer-curve-delete-deactivates-the-selected-slot",deleteArea&&value(xKey)==-1&&value(yKey)==0&&base->_undoStarts==undo+1);
|
||||
NSDictionary*red=nil;for(NSDictionary*a in [curve valueForKey:@"areas"])if([a[@"kind"]isEqual:@"channel"]&&[a[@"index"]integerValue]==1)red=[[a copy]autorelease];undo=base->_undoStarts;click(red);drain();
|
||||
NSDictionary *red=nil;for(NSDictionary *a in [curve valueForKey:@"areas"])if([a[@"kind"]isEqual:@"channel"]&&[a[@"index"]integerValue]==1)red=[[a copy]autorelease];undo=base->_undoStarts;click(red);drain();
|
||||
run.record(@"viewer-curve-channel-switch-is-view-state-with-no-undo",[[curve valueForKey:@"channel"]integerValue]==1&&base->_undoStarts==undo);
|
||||
click(areaFor(controls,@"tool",@"grading"));id grading=panelFor(@"grading");NSDictionary*wheel=areaFor(grading,@"wheel",nil);NSRect wr=[wheel[@"rect"]rectValue];NSPoint wp=NSMakePoint(NSMidX(wr)+wr.size.width*.2,NSMidY(wr));undo=base->_undoStarts;
|
||||
[controls event:NSEventTypeLeftMouseDown point:wp atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:NSMakePoint(NSMidX(wr),NSMidY(wr)-wr.size.width*.3)atTime:host->_time];[controls event:NSEventTypeLeftMouseUp point:NSMakePoint(NSMidX(wr),NSMidY(wr)-wr.size.width*.4)atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-grading-wheel-edits-hue-and-saturation-in-one-gesture",wheel&&fabs(value(@"grade0_0")-90)<1e-5&&fabs(value(@"grade0_1")-80)<1e-4&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1&&[[controls valueForKey:@"panels"]count]==3);
|
||||
click(areaFor(grading,@"graphMode",nil));run.record(@"viewer-graph-panel-retains-precise-parameter-view",areaFor(grading,@"slider",nil)&&!areaFor(grading,@"wheel",nil));
|
||||
NSRect modeRect=[areaFor(grading,@"graphMode",nil)[@"rect"]rectValue],nextRect=[areaFor(grading,@"next",nil)[@"rect"]rectValue];run.record(@"viewer-graph-mode-and-page-buttons-never-overlap",!NSIntersectsRect(modeRect,nextRect));
|
||||
click(areaFor(grading,@"close",nil));run.record(@"viewer-closing-one-panel-preserves-other-graph-and-controls",!panelFor(@"grading")&&panelFor(@"curve")&&panelFor(@"base"));
|
||||
// A repeated curve layer selects its UUID, rather than redirecting writes to root.
|
||||
NSMutableDictionary*doc=DYMutablePlist(DYReadTools(host,host->_time).document);NSDictionary*layer=DYInsertTool(doc,@"curve",@"base:curve");NSString*layerID=[[layer[@"id"]copy]autorelease];DYWriteTools(host,doc,host->_time);publish();
|
||||
// Raise curve with an inert header click twice (collapse/reopen), then layer menu.
|
||||
click(areaFor(curve,@"open",nil));click(areaFor(curve,@"open",nil));click(areaFor(curve,@"catalog",nil));NSDictionary*module=areaFor(curve,@"module",layerID);click(module);
|
||||
run.record(@"viewer-floating-editor-layer-menu-selects-only-its-tool-type",module&&[[curve valueForKey:@"nodeID"]isEqual:layerID]&&[[curve valueForKey:@"nodes"]count]==2);
|
||||
click(areaFor(controls,@"tool",@"lens"));id lens=panelFor(@"lens");
|
||||
run.record(@"viewer-lens-is-transparent-grid-and-direct-handles-without-parameter-card",lens&&areaFor(lens,@"lensCenter",nil)&&areaFor(lens,@"lensStrength",nil)&&!areaFor(lens,@"slider",nil)&&!areaFor(lens,@"open",nil)&&[controls partAtPoint:NSMakePoint(900,600)]==0);
|
||||
NSRect center=[areaFor(lens,@"lensCenter",nil)[@"rect"]rectValue];NSPoint start=NSMakePoint(NSMidX(center),NSMidY(center)),end=NSMakePoint(start.x+size.width*.1,start.y+size.height*.08);undo=base->_undoStarts;
|
||||
[controls event:NSEventTypeLeftMouseDown point:start atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:end atTime:host->_time];drain();[controls event:NSEventTypeLeftMouseUp point:end atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-lens-center-drags-both-normalized-axes-in-one-undo",fabs(value(@"lensCenterX")-.6)<1e-5&&fabs(value(@"lensCenterY")-.58)<1e-5&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);
|
||||
NSRect strength=[areaFor(lens,@"lensStrength",nil)[@"rect"]rectValue];start=NSMakePoint(NSMidX(strength),NSMidY(strength));end=NSMakePoint(start.x+size.width*.125,start.y);undo=base->_undoStarts;
|
||||
[controls event:NSEventTypeLeftMouseDown point:start atTime:host->_time];[controls event:NSEventTypeLeftMouseDragged point:end atTime:host->_time];drain();[controls event:NSEventTypeLeftMouseUp point:end atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-lens-strength-handle-writes-existing-radial-parameter",fabs(value(@"lensStrength")-50)<1e-5&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);
|
||||
click(areaFor(controls,@"tool",@"lens"));run.record(@"viewer-repeated-image-tool-entry-closes-only-that-overlay",!panelFor(@"lens")&&panelFor(@"curve"));
|
||||
NSMutableDictionary *doc=DYMutablePlist(DYReadTools(host,host->_time).document);NSString *layerID=[[DYInsertTool(doc,@"curve",@"base:curve")[@"id"]copy]autorelease];DYWriteTools(host,doc,host->_time);
|
||||
[NSNotificationCenter.defaultCenter postNotificationName:@"DYWorkspaceToolSelection" object:host userInfo:@{@"node":layerID}];drain();publish();
|
||||
run.record(@"viewer-curve-follows-workspace-selected-uuid-of-the-same-type",[[curve valueForKey:@"nodeID"]isEqual:layerID]);
|
||||
NSDictionary *baseBeforeIndependent=[[base->_values copy]autorelease];plot=[areaFor(curve,@"curvePlot",nil)[@"rect"]rectValue];point=NSMakePoint(NSMinX(plot)+plot.size.width*.5,NSMinY(plot)+plot.size.height*.5);undo=base->_undoStarts;
|
||||
[controls event:NSEventTypeLeftMouseDown point:point atTime:host->_time];NSString *independentX=[[[curve valueForKey:@"captured"][@"xKey"]copy]autorelease];drain();NSPoint independentEnd=NSMakePoint(NSMinX(plot)+plot.size.width*.42,NSMinY(plot)+plot.size.height*.65);[controls event:NSEventTypeLeftMouseDragged point:independentEnd atTime:host->_time];drain();[controls event:NSEventTypeLeftMouseUp point:independentEnd atTime:host->_time];drain();publish();
|
||||
NSDictionary *firstValues=[[DYToolWithID(DYReadTools(host,host->_time).document,layerID)[@"values"]copy]autorelease];
|
||||
run.record(@"viewer-selected-curve-uuid-writes-own-points-and-preserves-base",independentX&&fabs([firstValues[independentX]doubleValue]-.42)<1e-5&&[baseBeforeIndependent isEqual:base->_values]&&base->_undoStarts==undo+1&&base->_undoEnds==undo+1);
|
||||
doc=DYMutablePlist(DYReadTools(host,host->_time).document);NSString *secondID=[[DYInsertTool(doc,@"curve",layerID)[@"id"]copy]autorelease];DYWriteTools(host,doc,host->_time);[NSNotificationCenter.defaultCenter postNotificationName:@"DYWorkspaceToolSelection" object:host userInfo:@{@"node":secondID}];drain();publish();plot=[areaFor(curve,@"curvePlot",nil)[@"rect"]rectValue];point=NSMakePoint(NSMinX(plot)+plot.size.width*.5,NSMinY(plot)+plot.size.height*.5);
|
||||
[controls event:NSEventTypeLeftMouseDown point:point atTime:host->_time];NSString *secondX=[[[curve valueForKey:@"captured"][@"xKey"]copy]autorelease];drain();NSPoint secondEnd=NSMakePoint(NSMinX(plot)+plot.size.width*.7,NSMinY(plot)+plot.size.height*.2);[controls event:NSEventTypeLeftMouseDragged point:secondEnd atTime:host->_time];drain();[controls event:NSEventTypeLeftMouseUp point:secondEnd atTime:host->_time];drain();publish();
|
||||
run.record(@"viewer-second-same-type-uuid-does-not-overwrite-first-or-base",secondX&&fabs([DYToolWithID(DYReadTools(host,host->_time).document,secondID)[@"values"][secondX]doubleValue]-.7)<1e-5&&[firstValues isEqual:DYToolWithID(DYReadTools(host,host->_time).document,layerID)[@"values"]]&&[baseBeforeIndependent isEqual:base->_values]);
|
||||
[NSNotificationCenter.defaultCenter postNotificationName:@"DYWorkspaceToolSelection" object:host userInfo:@{@"node":layerID}];drain();publish();
|
||||
plot=[areaFor(curve,@"curvePlot",nil)[@"rect"]rectValue];point=NSMakePoint(NSMidX(plot),NSMidY(plot));[controls event:NSEventTypeLeftMouseDown point:point atTime:host->_time];[controls prepareWithSize:size scale:1 atTime:CMTimeMake(1,24)];
|
||||
run.record(@"viewer-playhead-change-clears-graphic-capture",![controls capturing]);
|
||||
run.record(@"viewer-missing-next-frame-snapshot-preserves-selected-independent-layer",[[curve valueForKey:@"nodeID"]isEqual:layerID]&&!areaFor(curve,@"curvePlot",nil));
|
||||
host->_time=CMTimeMake(1,24);publish();run.record(@"viewer-new-frame-restores-the-same-independent-editor-target",[[curve valueForKey:@"nodeID"]isEqual:layerID]&&areaFor(curve,@"curvePlot",nil));host->_time=kCMTimeZero;publish();
|
||||
doc=DYMutablePlist(DYReadTools(host,host->_time).document);DYRemoveTool(doc,layerID);DYWriteTools(host,doc,host->_time);publish();run.record(@"viewer-deleted-layer-falls-back-to-surviving-same-tool",[[curve valueForKey:@"nodeID"]isEqual:@"base:curve"]);
|
||||
click(areaFor(controls,@"hidePanels",nil));BOOL bounded=YES;
|
||||
for(NSSize next:{NSMakeSize(120,80),NSMakeSize(180,200),NSMakeSize(320,240),NSMakeSize(1000,462),NSMakeSize(1280,720)})for(CGFloat scale:{1.,2.}){[controls setViewport:NSMakeRect(0,0,next.width,next.height)];[controls prepareWithSize:next scale:scale atTime:host->_time];for(NSDictionary*a in [controls valueForKey:@"areas"])bounded&=NSContainsRect(NSMakeRect(0,0,next.width,next.height),[a[@"rect"]rectValue]);bounded&=[controls partAtPoint:NSMakePoint(-1,20)]==0&&[controls partAtPoint:NSMakePoint(next.width+1,20)]==0&&[controls partAtPoint:NSMakePoint(30,next.height+1)]==0;}
|
||||
click(areaFor(controls,@"tool",@"curve"));BOOL bounded=YES;
|
||||
for(NSSize next:{NSMakeSize(120,80),NSMakeSize(180,200),NSMakeSize(320,240),NSMakeSize(1000,462),NSMakeSize(1280,720)})for(CGFloat scale:{1.,2.}){[controls setViewport:NSMakeRect(0,0,next.width,next.height)];[controls prepareWithSize:next scale:scale atTime:host->_time];for(NSDictionary *a in [controls valueForKey:@"areas"])bounded&=NSContainsRect(NSMakeRect(0,0,next.width,next.height),[a[@"rect"]rectValue]);bounded&=[controls partAtPoint:NSMakePoint(-1,20)]==0&&[controls partAtPoint:NSMakePoint(next.width+1,20)]==0&&[controls partAtPoint:NSMakePoint(30,next.height+1)]==0;}
|
||||
run.record(@"viewer-small-and-retina-canvases-never-hit-outside-visible-image",bounded);
|
||||
[controls setViewport:NSMakeRect(0,0,180,200)];[controls prepareWithSize:NSMakeSize(180,200)scale:1 atTime:host->_time];click(areaFor(controls,@"tool",@"base"));NSDictionary*railEntry=areaFor(controls,@"tool",@"base");NSRect entryRect=[railEntry[@"rect"]rectValue];run.record(@"viewer-vertical-entry-remains-reachable-above-overlapping-small-panel",[controls partAtPoint:NSMakePoint(NSMidX(entryRect),NSMidY(entryRect))]==[railEntry[@"part"]integerValue]);
|
||||
click(areaFor(controls,@"hidePanels",nil));
|
||||
|
||||
[controls setViewport:NSMakeRect(40,30,1160,650)];[controls prepareWithSize:size scale:1 atTime:host->_time];NSRect rail=[[controls valueForKey:@"rail"]rectValue];run.record(@"viewer-rail-is-anchored-to-image-and-not-letterbox",NSContainsRect(NSMakeRect(40,30,1160,650),rail)&&[controls partAtPoint:NSMakePoint(NSMidX(rail),20)]==0);
|
||||
// Offscreen drawing checks the actual OSC renderer, without opening an APP.
|
||||
[controls setViewport:NSMakeRect(0,0,1280,720)];[controls prepareWithSize:size scale:1 atTime:host->_time];
|
||||
for(NSString*type in @[@"hsl",@"curve",@"spider"]){click(areaFor(controls,@"tool",type));id p=panelFor(type);CGFloat px=[type isEqual:@"hsl"]?.05:[type isEqual:@"curve"]?.32:.59;[p setValue:[NSValue valueWithPoint:NSMakePoint(px,.1)]forKey:@"position"];}
|
||||
[controls prepareWithSize:size scale:1 atTime:host->_time];
|
||||
NSBitmapImageRep*bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:1280 pixelsHigh:720 bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:1280*4 bitsPerPixel:32]autorelease];
|
||||
[NSGraphicsContext saveGraphicsState];[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]];NSAffineTransform*flip=[NSAffineTransform transform];[flip translateXBy:0 yBy:720];[flip scaleXBy:1 yBy:-1];[flip concat];[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:NSGraphicsContext.currentContext.CGContext flipped:YES]];
|
||||
[[NSColor colorWithCalibratedWhite:.2 alpha:1]setFill];NSRectFill(NSMakeRect(0,0,1280,720));[controls draw];[NSGraphicsContext restoreGraphicsState];NSString*png=[runtime stringByAppendingPathComponent:@"viewer-workspace.png"];
|
||||
run.record(@"viewer-real-osc-draws-curves-hsl-and-spider-offscreen",[[bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}]writeToFile:png atomically:YES],@{@"path":png});
|
||||
[controls setViewport:NSMakeRect(0,0,1280,720)];[controls prepareWithSize:size scale:1 atTime:host->_time];click(areaFor(controls,@"tool",@"curve"));
|
||||
NSBitmapImageRep *bitmap=[[[NSBitmapImageRep alloc]initWithBitmapDataPlanes:NULL pixelsWide:1280 pixelsHigh:720 bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:1280*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:720];[flip scaleXBy:1 yBy:-1];[flip concat];[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:NSGraphicsContext.currentContext.CGContext flipped:YES]];[controls draw];[NSGraphicsContext restoreGraphicsState];NSString *png=[runtime stringByAppendingPathComponent:@"viewer-workspace.png"];
|
||||
run.record(@"viewer-real-osc-draws-minimal-curve-on-clear-canvas",[[bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}]writeToFile:png atomically:YES]&&bitmap.bitmapData[(300*1280+600)*4+3]==0,@{@"path":png});
|
||||
[controls finishCapture];controls.bridge=nil;[bridge invalidate];drain();[controls release];[bridge release];
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Methods of DYViewerParameterPanel. Geometry is shared by drawing and input.
|
||||
- (BOOL)graphicKind:(NSString*)kind{return [@[@"curvePlot",@"wheel",@"hslPlot",@"spiderPlot"]containsObject:kind];}
|
||||
- (BOOL)graphicKind:(NSString*)kind{return [@[@"curvePlot",@"wheel",@"hslPlot",@"spiderPlot",@"lensFrame",@"lensCenter",@"lensStrength"]containsObject:kind];}
|
||||
- (NSData*)spiderData {if(_spiderDraft)return _spiderDraft;return [_nodeID hasPrefix:@"base:"]?_snapshot[@"spider"]:[self node][@"layer"][@"spider"];}
|
||||
- (void)beginSpiderData {[_bridge beginSpider:[self spiderData] node:_nodeID enabled:[self graphicValue:@"spiderEnabled"] atTime:_time];}
|
||||
- (void)spiderAction:(NSInteger)action {
|
||||
@@ -40,6 +40,18 @@
|
||||
- (NSPoint)curvePosition:(NSDictionary*)p rect:(NSRect)r{return NSMakePoint(r.origin.x+[p[@"x"]doubleValue]*r.size.width,r.origin.y+(1-[p[@"y"]doubleValue])*r.size.height);}
|
||||
- (void)drawGraphic:(NSDictionary*)area{
|
||||
CGFloat s=_scale;NSRect r=[area[@"rect"]rectValue];NSColor*ink=DYThemeColor(@"text"),*accent=DYThemeColor(@"accent");
|
||||
if([@[@"curve",@"lens"]containsObject:_toolType]){ink=NSColor.whiteColor;accent=NSColor.systemCyanColor;NSShadow *shadow=[[[NSShadow alloc]init]autorelease];shadow.shadowColor=[NSColor colorWithWhite:0 alpha:.9];shadow.shadowBlurRadius=2;shadow.shadowOffset=NSZeroSize;[shadow set];}
|
||||
if([area[@"kind"]isEqual:@"lensFrame"]){
|
||||
NSBezierPath *grid=[NSBezierPath bezierPath];grid.lineWidth=.6*s;
|
||||
for(int i=1;i<8;i++){CGFloat x=NSMinX(r)+r.size.width*i/8.,y=NSMinY(r)+r.size.height*i/8.;[grid moveToPoint:NSMakePoint(x,NSMinY(r))];[grid lineToPoint:NSMakePoint(x,NSMaxY(r))];[grid moveToPoint:NSMakePoint(NSMinX(r),y)];[grid lineToPoint:NSMakePoint(NSMaxX(r),y)];}[[NSColor colorWithWhite:1 alpha:.3]setStroke];[grid stroke];return;
|
||||
}
|
||||
if([area[@"kind"]isEqual:@"lensCenter"]||[area[@"kind"]isEqual:@"lensStrength"]){
|
||||
BOOL center=[area[@"kind"]isEqual:@"lensCenter"];NSPoint point=NSMakePoint(NSMidX(r),NSMidY(r));NSBezierPath *mark=[NSBezierPath bezierPath];mark.lineWidth=1.4*s;
|
||||
[mark moveToPoint:NSMakePoint(point.x-7*s,point.y)];[mark lineToPoint:NSMakePoint(point.x+7*s,point.y)];
|
||||
if(center){[mark moveToPoint:NSMakePoint(point.x,point.y-7*s)];[mark lineToPoint:NSMakePoint(point.x,point.y+7*s)];}else{[mark moveToPoint:NSMakePoint(point.x-3*s,point.y-4*s)];[mark lineToPoint:NSMakePoint(point.x-7*s,point.y)];[mark lineToPoint:NSMakePoint(point.x-3*s,point.y+4*s)];[mark moveToPoint:NSMakePoint(point.x+3*s,point.y-4*s)];[mark lineToPoint:NSMakePoint(point.x+7*s,point.y)];[mark lineToPoint:NSMakePoint(point.x+3*s,point.y+4*s)];}
|
||||
[accent setStroke];[mark stroke];if(_hover==[area[@"part"]integerValue]||_pressed==[area[@"part"]integerValue]){NSString *hint=center?@"光学中心":[NSString stringWithFormat:@"畸变 %.1f",[self graphicValue:@"lensStrength"]];[self text:hint rect:NSMakeRect(point.x-50*s,point.y+12*s,100*s,18*s)size:10 color:ink alignment:NSTextAlignmentCenter];}return;
|
||||
}
|
||||
|
||||
if([area[@"kind"]isEqual:@"hslPlot"]){
|
||||
[NSGraphicsContext saveGraphicsState];NSRectClip(r);[[ink colorWithAlphaComponent:.18]setStroke];NSBezierPath *mid=[NSBezierPath bezierPath];[mid moveToPoint:NSMakePoint(NSMinX(r),NSMidY(r))];[mid lineToPoint:NSMakePoint(NSMaxX(r),NSMidY(r))];[mid stroke];
|
||||
NSBezierPath *curve=[NSBezierPath bezierPath];curve.lineWidth=1.5*s;
|
||||
@@ -68,7 +80,7 @@
|
||||
NSPoint p=NSMakePoint(NSMidX(r)+cos(angle)*rad,NSMidY(r)-sin(angle)*rad);[NSColor.blackColor setStroke];NSBezierPath*knob=[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(p.x-5*s,p.y-5*s,10*s,10*s)];knob.lineWidth=3*s;[knob stroke];[NSColor.whiteColor setStroke];knob.lineWidth=1.4*s;[knob stroke];
|
||||
return;
|
||||
}
|
||||
[[ink colorWithAlphaComponent:.06]setFill];[[NSBezierPath bezierPathWithRect:r]fill];[NSGraphicsContext saveGraphicsState];NSRectClip(r);
|
||||
[NSGraphicsContext saveGraphicsState];NSRectClip(r);
|
||||
NSData *rawHistogram=_snapshot[@"histogram"];const DYHistogram *hist=rawHistogram.length==sizeof(DYHistogram)?(const DYHistogram*)rawHistogram.bytes:nullptr;
|
||||
if(hist&&hist->samples){uint32_t peak=1;for(int c=0;c<4;c++)if(_channel==0||c==_channel)for(int b=0;b<256;b++)peak=MAX(peak,hist->bins[c][b]);NSArray *colors=@[ink,NSColor.systemRedColor,NSColor.systemGreenColor,NSColor.systemBlueColor];for(int c=3;c>=0;c--){if(_channel&&c!=_channel)continue;NSBezierPath *area=[NSBezierPath bezierPath];[area moveToPoint:NSMakePoint(NSMinX(r),NSMaxY(r))];for(int b=0;b<256;b++)[area lineToPoint:NSMakePoint(NSMinX(r)+b/255.*r.size.width,NSMaxY(r)-sqrt(hist->bins[c][b]/double(peak))*r.size.height*.86)];[area lineToPoint:NSMakePoint(NSMaxX(r),NSMaxY(r))];[area closePath];[[colors[c]colorWithAlphaComponent:c==0?.08:.2]setFill];[area fill];}}
|
||||
[[ink colorWithAlphaComponent:.16]setStroke];NSBezierPath*grid=[NSBezierPath bezierPath];grid.lineWidth=.5*s;
|
||||
@@ -83,10 +95,14 @@
|
||||
for(int sample=0;sample<=256;sample++){double x=sample/256.;while(segment+2<p.size()&&x>p[segment+1].x)segment++;double width=MAX(.0001,p[segment+1].x-p[segment].x),t=MAX(0.,MIN(1.,(x-p[segment].x)/width)),t2=t*t,t3=t2*t;double y=(2*t3-3*t2+1)*p[segment].y+(t3-2*t2+t)*width*m[segment]+(-2*t3+3*t2)*p[segment+1].y+(t3-t2)*width*m[segment+1];NSPoint q=NSMakePoint(r.origin.x+x*r.size.width,r.origin.y+(1-MAX(0.,MIN(1.,y)))*r.size.height);if(sample==0)[curve moveToPoint:q];else[curve lineToPoint:q];}
|
||||
NSColor*color=_channel==0?accent:_channel==1?NSColor.systemRedColor:_channel==2?NSColor.systemGreenColor:NSColor.systemBlueColor;[color setStroke];[curve stroke];
|
||||
for(NSDictionary*point in points){NSPoint q=[self curvePosition:point rect:r];BOOL selected=[point[@"xKey"]isEqual:_selectedX];[color setFill];NSBezierPath*dot=[NSBezierPath bezierPathWithOvalInRect:NSMakeRect(q.x-4*s,q.y-4*s,8*s,8*s)];[dot fill];[(selected?NSColor.whiteColor:ink)setStroke];dot.lineWidth=(selected?2:1)*s;[dot stroke];}
|
||||
[NSGraphicsContext restoreGraphicsState];[self text:@"0 输入 → 1" rect:NSMakeRect(r.origin.x,NSMaxY(r)+2*s,r.size.width,14*s)size:8 color:ink alignment:NSTextAlignmentCenter];
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
}
|
||||
- (void)beginGraphicAt:(NSPoint)p{
|
||||
if(!_snapshot||![self node])return;NSMutableDictionary*c=[[_captured mutableCopy]autorelease];NSRect r=[c[@"rect"]rectValue];NSString*xKey=nil,*yKey=nil;
|
||||
if([c[@"kind"]isEqual:@"lensCenter"]||[c[@"kind"]isEqual:@"lensStrength"]){
|
||||
BOOL center=[c[@"kind"]isEqual:@"lensCenter"];NSArray *keys=center?@[@"lensCenterX",@"lensCenterY"]:@[@"lensStrength"];NSMutableArray *descriptors=[NSMutableArray array];NSMutableDictionary *values=[NSMutableDictionary dictionary];for(NSString *key in keys){[descriptors addObject:[self descriptorForKey:key]];values[key]=@([self graphicValue:key]);}c[@"lensStart"]=values;[_captured release];_captured=[c copy];[_bridge beginParameters:descriptors node:_nodeID values:values atTime:_time];return;
|
||||
}
|
||||
|
||||
if([c[@"kind"]isEqual:@"spiderPlot"]){auto mesh=DYSpiderMesh([self spiderData]);double best=12*_scale;NSInteger chosen=-1;for(int i=0;i<dy::meshCount(mesh);i++){double distance=hypot(p.x-(r.origin.x+mesh.x[i]*r.size.width),p.y-(r.origin.y+mesh.y[i]*r.size.height));if(distance<best){best=distance;chosen=i;}}if(chosen<0)return;_selectedSpider=chosen;c[@"meshStart"]=[NSData dataWithBytes:&mesh length:sizeof(mesh)];[_captured release];_captured=[c copy];[self beginSpiderData];return;}
|
||||
if([c[@"kind"]isEqual:@"hslPlot"]){NSInteger color=MAX(0,MIN(7,(NSInteger)((p.x-r.origin.x)/r.size.width*8)));NSString *key=[NSString stringWithFormat:@"hsl%ld_%ld",(long)_hslAxis,(long)color];c[@"hslKey"]=key;[_captured release];_captured=[c copy];[_bridge beginParameter:[self descriptorForKey:key]node:_nodeID value:[self graphicValue:key]atTime:_time];return;}
|
||||
if([c[@"kind"]isEqual:@"curvePlot"]){NSDictionary*nearest=nil;double distance=12*_scale;for(NSDictionary*point in [self curvePoints]){NSPoint q=[self curvePosition:point rect:r];double d=hypot(q.x-p.x,q.y-p.y);if(d<distance){distance=d;nearest=point;}}
|
||||
@@ -98,6 +114,13 @@
|
||||
if([c[@"newPoint"]boolValue]||[c[@"kind"]isEqual:@"wheel"])[self updateGraphicAt:p];
|
||||
}
|
||||
- (void)updateGraphicAt:(NSPoint)p{
|
||||
if([_captured[@"kind"]isEqual:@"lensCenter"]||[_captured[@"kind"]isEqual:@"lensStrength"]){
|
||||
NSDictionary *start=_captured[@"lensStart"];if(!start)return;NSDictionary *values;
|
||||
if([_captured[@"kind"]isEqual:@"lensCenter"]){values=@{@"lensCenterX":@(MAX(0.,MIN(1.,[start[@"lensCenterX"]doubleValue]+(p.x-_down.x)/MAX(1.,_viewport.size.width)))),@"lensCenterY":@(MAX(0.,MIN(1.,[start[@"lensCenterY"]doubleValue]+(p.y-_down.y)/MAX(1.,_viewport.size.height))))};}
|
||||
else values=@{@"lensStrength":@(MAX(-100.,MIN(100.,[start[@"lensStrength"]doubleValue]+(p.x-_down.x)/MAX(1.,_viewport.size.width)*400)))};
|
||||
[_draftValues addEntriesFromDictionary:values];[_bridge changeValues:values];return;
|
||||
}
|
||||
|
||||
if([_captured[@"kind"]isEqual:@"spiderPlot"]){NSData *start=_captured[@"meshStart"];if(!start||_selectedSpider<0)return;NSRect r=[_captured[@"rect"]rectValue];auto mesh=DYSpiderMesh(start);std::bitset<dy::SpiderMeshCapacity> selected;selected[_selectedSpider]=true;auto moved=dy::moveMesh(mesh,selected,(p.x-_down.x)/r.size.width,(p.y-_down.y)/r.size.height);[_spiderDraft release];_spiderDraft=[[NSData alloc]initWithBytes:&moved length:sizeof(moved)];[_bridge changeSpider:_spiderDraft];return;}
|
||||
if([_captured[@"kind"]isEqual:@"hslPlot"]){NSString *key=_captured[@"hslKey"];if(!key)return;NSRect r=[_captured[@"rect"]rectValue];double v=MAX(-100.,MIN(100.,(NSMidY(r)-p.y)/r.size.height*200));_draftValues[key]=@(v);[_bridge changeValue:v];return;}
|
||||
NSString*xKey=_captured[@"xKey"],*yKey=_captured[@"yKey"];if(!xKey||!yKey)return;NSRect r=[_captured[@"rect"]rectValue];double x,y;
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
// Call before the owning plug-in releases this object during teardown.
|
||||
- (void)invalidate;
|
||||
- (void)requestWorkspace;
|
||||
- (void)requestWorkspacePage:(NSString *)page;
|
||||
- (void)requestMask:(NSInteger)kind;
|
||||
- (void)requestTool:(NSString*)type;
|
||||
- (void)publishAssets:(DYAssetState*)assets histogram:(NSData*)histogram atTime:(CMTime)time;
|
||||
- (void)beginSpider:(NSData*)mesh node:(NSString*)node enabled:(double)enabled atTime:(CMTime)time;
|
||||
@@ -55,7 +57,7 @@ static BOOL DYViewerSanitizeValue(NSDictionary *d,double input,double *output) {
|
||||
|
||||
@implementation DYViewerParameterBridge {
|
||||
id<PROAPIAccessing> _apiManager;
|
||||
NSDictionary *_snapshot,*_sourceDocument;
|
||||
NSDictionary *_snapshot,*_sourceDocument;NSString *_selectedNode;
|
||||
CMTime _snapshotTime;
|
||||
BOOL _invalidated,_validationScheduled;
|
||||
uint64_t _requestSequence,_requestedGesture;
|
||||
@@ -70,13 +72,13 @@ static BOOL DYViewerSanitizeValue(NSDictionary *d,double input,double *output) {
|
||||
BOOL _writerUndoOpen,_writerSpider; NSData *_writerLastMesh;
|
||||
}
|
||||
- (instancetype)initWithAPIManager:(id<PROAPIAccessing>)manager {
|
||||
if((self=[super init])){_apiManager=manager;_snapshotTime=kCMTimeInvalid;_writerTime=kCMTimeInvalid;}return self;
|
||||
if((self=[super init])){_apiManager=manager;_snapshotTime=kCMTimeInvalid;_writerTime=kCMTimeInvalid;[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(workspaceSelected:) name:@"DYWorkspaceToolSelection" object:manager];}return self;
|
||||
}
|
||||
- (void)dealloc {
|
||||
// invalidate enqueues closure before the owner releases its final reference;
|
||||
// the queued block keeps the bridge alive until its host group is closed.
|
||||
NSCAssert(!_writerUndoOpen,@"Viewer parameter group must be closed before teardown");
|
||||
[_snapshot release];[_sourceDocument release];[_writerHost release];[_writerTarget release];
|
||||
[NSNotificationCenter.defaultCenter removeObserver:self];[_selectedNode release];[_snapshot release];[_sourceDocument release];[_writerHost release];[_writerTarget release];
|
||||
[_writerDescriptors release];[_writerLastValues release];[_writerCompanions release];[_writerNode release];[_writerType release];[super dealloc];
|
||||
}
|
||||
- (void)publishAssets:(DYAssetState*)assets histogram:(NSData*)histogram atTime:(CMTime)time {
|
||||
@@ -90,7 +92,19 @@ static BOOL DYViewerSanitizeValue(NSDictionary *d,double input,double *output) {
|
||||
dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYViewerToolRequested" object:manager userInfo:@{@"type":type}];});
|
||||
}
|
||||
- (void)requestWorkspace{
|
||||
dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!_invalidated)manager=_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYColorWorkspaceRequested" object:manager];});
|
||||
[self requestWorkspacePage:@"tools"];
|
||||
}
|
||||
- (void)requestWorkspacePage:(NSString *)page {
|
||||
if(![@[@"tools",@"lut",@"scopes",@"masks"]containsObject:page])return;
|
||||
dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYColorWorkspaceRequested" object:manager userInfo:@{@"page":page}];});
|
||||
}
|
||||
- (void)requestMask:(NSInteger)kind {
|
||||
if(kind<0||kind>2)return;
|
||||
dispatch_async(dispatch_get_main_queue(),^{id manager=nil;@synchronized(self){if(!self->_invalidated)manager=self->_apiManager;}if(manager)[NSNotificationCenter.defaultCenter postNotificationName:@"DYColorWorkspaceRequested" object:manager userInfo:@{@"page":@"masks",@"maskKind":@(kind)}];});
|
||||
}
|
||||
- (void)workspaceSelected:(NSNotification *)note {
|
||||
NSString *node=note.userInfo[@"node"];if(![node isKindOfClass:NSString.class])return;
|
||||
@synchronized(self){[_selectedNode release];_selectedNode=[node copy];}
|
||||
}
|
||||
- (void)publishUniforms:(const DYUniforms*)uniforms document:(NSDictionary*)document atTime:(CMTime)time {
|
||||
if(!uniforms||!document||!CMTIME_IS_NUMERIC(time))return;
|
||||
@@ -122,6 +136,7 @@ static BOOL DYViewerSanitizeValue(NSDictionary *d,double input,double *output) {
|
||||
- (NSDictionary*)snapshotAtTime:(CMTime)time {
|
||||
@synchronized(self){
|
||||
if(_invalidated||!CMTIME_IS_NUMERIC(time)||!CMTIME_IS_NUMERIC(_snapshotTime)||CMTimeCompare(time,_snapshotTime)!=0)return nil;
|
||||
if(_selectedNode.length){NSMutableDictionary *snapshot=[[_snapshot mutableCopy]autorelease];snapshot[@"selectedNode"]=_selectedNode;return snapshot;}
|
||||
return [[_snapshot retain]autorelease];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,13 +53,32 @@
|
||||
NSInteger count=[counts[type]integerValue];counts[type]=@(count+1);if(!base)title=[title stringByAppendingFormat:@" · %ld",(long)(count+1)];
|
||||
[nodes addObject:@{@"id":ID,@"type":type,@"title":title,@"layer":layer?:@{}}];
|
||||
}[_nodes release];_nodes=[nodes copy];
|
||||
NSString *selected=_snapshot[@"selectedNode"];for(NSDictionary *candidate in _nodes)if([candidate[@"id"]isEqual:selected]&&![_nodeID isEqual:selected]){[self finishCapture];[_nodeID release];_nodeID=[selected copy];[_selectedX release];_selectedX=nil;break;}
|
||||
if(![self node]){[self finishCapture];[_nodeID release];_nodeID=_nodes.count?[_nodes[0][@"id"]copy]:nil;_page=0;[_selectedX release];_selectedX=nil;}}
|
||||
NSString*type=[self node][@"type"]?:_toolType;NSMutableArray*rows=[NSMutableArray array];
|
||||
// These are the existing public scalar controls, never hidden curve-slot metadata.
|
||||
NSArray*sections=[type isEqual:@"base"]?@[@"base",@"color"]:type?@[type]:@[];
|
||||
if(doc)for(NSString*part in sections)for(NSDictionary*d in DYToolSection(part)[@"rows"]){NSString*k=d[@"key"];if(!d[@"pid"]||[k hasPrefix:@"cmbypass"]||[k isEqual:@"copyAutoGrade"]||([type isEqual:@"curve"]&&![k hasPrefix:@"curveY"]))continue;[rows addObject:d];}
|
||||
[_rows release];_rows=[rows copy];[_areas removeAllObjects];if(!_bridge||size.width<120||size.height<80)return;
|
||||
CGFloat s=_scale,margin=8*s,w=MIN(300*s,size.width-2*margin);_capacity=MAX(1,MIN(5,(NSInteger)floor((size.height-124*s)/(46*s))));
|
||||
CGFloat s=_scale,margin=8*s,w=MIN(300*s,size.width-2*margin);
|
||||
// Direct image tools have no panel surface, title, catalog or parameter page.
|
||||
if([@[@"curve",@"lens"]containsObject:type]){
|
||||
if([type isEqual:@"lens"]){
|
||||
_panel=viewport;if(!_snapshot||![self node])return;
|
||||
NSPoint center=NSMakePoint(NSMinX(viewport)+[self graphicValue:@"lensCenterX"]*size.width,NSMinY(viewport)+[self graphicValue:@"lensCenterY"]*size.height);
|
||||
NSPoint strength=NSMakePoint(NSMinX(viewport)+size.width*.78,NSMinY(viewport)+size.height*.5);
|
||||
[self addArea:viewport part:22400 kind:@"lensFrame" title:@"" descriptor:nil index:0];
|
||||
[self addArea:NSMakeRect(center.x-11*s,center.y-11*s,22*s,22*s) part:22401 kind:@"lensCenter" title:@"" descriptor:nil index:0];
|
||||
[self addArea:NSMakeRect(strength.x-11*s,strength.y-11*s,22*s,22*s) part:22402 kind:@"lensStrength" title:@"" descriptor:nil index:0];return;
|
||||
}
|
||||
w=MIN(260*s,size.width-2*margin);CGFloat h=MIN(214*s,size.height-2*margin),x=viewport.origin.x+margin,top=viewport.origin.y+margin;
|
||||
if(_positioned){x=MAX(viewport.origin.x+margin,MIN(NSMaxX(viewport)-margin-w,viewport.origin.x+_position.x*size.width));top=MAX(viewport.origin.y+margin,MIN(NSMaxY(viewport)-margin-h,viewport.origin.y+_position.y*size.height));}
|
||||
_panel=NSMakeRect(x,top,w,h);if(!_snapshot||![self node]||w<100*s||h<65*s)return;
|
||||
for(NSInteger c=0;c<4;c++)[self addArea:NSMakeRect(x+c*24*s,top,23*s,18*s)part:22010+c kind:@"channel" title:@[@"Y",@"R",@"G",@"B"][c] descriptor:nil index:c];
|
||||
[self addArea:NSMakeRect(x,top+22*s,w,MAX(24*s,h-22*s))part:22000 kind:@"curvePlot" title:@"" descriptor:nil index:0];
|
||||
if(_selectedX)[self addArea:NSMakeRect(NSMaxX(_panel)-19*s,top,19*s,18*s)part:22020 kind:@"deletePoint" title:@"×" descriptor:nil index:0];return;
|
||||
}
|
||||
_capacity=MAX(1,MIN(5,(NSInteger)floor((size.height-124*s)/(46*s))));
|
||||
_catalogCapacity=MAX(1,MIN(7,(NSInteger)floor((size.height-124*s)/(32*s))));
|
||||
_page=MIN(MAX(0,_page),MAX(0,((NSInteger)_rows.count-1)/_capacity));_catalogPage=MIN(MAX(0,_catalogPage),MAX(0,((NSInteger)_nodes.count-1)/_catalogCapacity));
|
||||
BOOL graph=_graphMode&&([@[@"curve",@"grading",@"hsl",@"spider"]containsObject:type]);
|
||||
@@ -103,7 +122,7 @@
|
||||
- (void)draw{
|
||||
if(!_areas.count)return;[NSGraphicsContext saveGraphicsState];NSRectClip(NSIntersectionRect(_panel,NSMakeRect(0,0,_size.width,_size.height)));CGFloat s=_scale;NSColor*ink=DYThemeColor(@"text")?:NSColor.whiteColor,*accent=DYThemeColor(@"accent")?:NSColor.systemCyanColor;
|
||||
NSBezierPath*panel=[NSBezierPath bezierPathWithRoundedRect:_panel xRadius:9*s yRadius:9*s];BOOL solid=NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceTransparency;
|
||||
[[DYThemeColor(@"surface")?:DYThemeColor(@"background")?:NSColor.blackColor colorWithAlphaComponent:solid?1:.66]setFill];[panel fill];[[ink colorWithAlphaComponent:.32]setStroke];panel.lineWidth=s;[panel stroke];
|
||||
BOOL minimal=[@[@"curve",@"lens"]containsObject:_toolType];if(minimal){ink=NSColor.whiteColor;accent=NSColor.systemCyanColor;NSShadow *shadow=[[[NSShadow alloc]init]autorelease];shadow.shadowColor=[NSColor colorWithWhite:0 alpha:.95];shadow.shadowBlurRadius=2;shadow.shadowOffset=NSZeroSize;[shadow set];}if(!minimal){[[DYThemeColor(@"surface")?:DYThemeColor(@"background")?:NSColor.blackColor colorWithAlphaComponent:solid?1:.66]setFill];[panel fill];[[ink colorWithAlphaComponent:.32]setStroke];panel.lineWidth=s;[panel stroke];}
|
||||
for(NSDictionary*a in _areas){NSRect r=[a[@"rect"]rectValue];NSInteger part=[a[@"part"]integerValue];NSString*kind=a[@"kind"];BOOL pressed=_pressed==part,hover=_hover==part;NSDictionary*d=a[@"descriptor"];
|
||||
if([self graphicKind:kind]){[self drawGraphic:a];continue;}
|
||||
if([kind isEqual:@"slider"]){double v=[self valueForDescriptor:d],lo=[d[@"min"]doubleValue],hi=[d[@"max"]doubleValue];CGFloat ratio=hi>lo?MAX(0.,MIN(1.,(v-lo)/(hi-lo))):0;NSRect track=[self trackForArea:a];
|
||||
@@ -113,15 +132,15 @@
|
||||
DYDrawSoftControl(NSMakeRect(track.origin.x+ratio*track.size.width-6*s,NSMidY(track)-6*s,12*s,12*s),6*s,NO,hover||pressed,pressed);
|
||||
}else{
|
||||
BOOL selected=(([kind isEqual:@"channel"]&&[a[@"index"]integerValue]==_channel)||([kind isEqual:@"hslAxis"]&&[a[@"index"]integerValue]==_hslAxis))||([kind isEqual:@"module"]&&[a[@"nodeID"]isEqual:_nodeID])||([kind isEqual:@"tool"]&&[a[@"toolType"]isEqual:[self node][@"type"]]);BOOL on=([kind isEqual:@"bool"]||[kind isEqual:@"headerBool"])&&[self valueForDescriptor:d]>.5;
|
||||
DYDrawSoftControl(r,5*s,NO,hover||selected||on,pressed);NSString*title=a[@"title"];
|
||||
if(!minimal)DYDrawSoftControl(r,5*s,NO,hover||selected||on,pressed);NSString*title=a[@"title"];
|
||||
if(d&&![kind isEqual:@"reset"]){NSString*value=[self valueText:d value:[self valueForDescriptor:d]];title=[kind isEqual:@"headerBool"]?(title.length?title:([self valueForDescriptor:d]>.5?@"●":@"○")):[NSString stringWithFormat:@"%@ %@%@",title,value,[kind isEqual:@"choice"]?@" ›":@""];}
|
||||
[self text:title rect:NSInsetRect(r,5*s,5*s) size:[kind isEqual:@"open"]?12:11 color:[kind isEqual:@"toolUnavailable"]?[ink colorWithAlphaComponent:.35]:ink alignment:NSTextAlignmentCenter];
|
||||
[self text:title rect:NSInsetRect(r,5*s,5*s) size:[kind isEqual:@"open"]?12:11 color:[kind isEqual:@"toolUnavailable"]?[ink colorWithAlphaComponent:.35]:(minimal&&(selected||hover||pressed)?accent:ink) alignment:NSTextAlignmentCenter];
|
||||
}
|
||||
}
|
||||
if(_open){NSString*hint=_catalog?@"选择当前工具的图层":(_graphMode&&[_toolType isEqual:@"curve"])?@"点击加点 · 拖动调整":(_graphMode&&[_toolType isEqual:@"grading"])?@"拖动色轮 · 参数查看亮度":@"拖动调节 · ↺ 还原";if(_graphMode&&[_toolType isEqual:@"hsl"])hint=@"拖动色点 · 参数精调";if(_graphMode&&[_toolType isEqual:@"spider"])hint=@"拖点联动 · 固定与还原选中点";if(_hover==20000||_movingPanel)hint=@"拖动标题移动 · 单击折叠";[self text:hint rect:NSMakeRect(_panel.origin.x+40*s,NSMaxY(_panel)-22*s,_panel.size.width-168*s,18*s) size:9 color:ink alignment:NSTextAlignmentCenter];}
|
||||
if(_open&&!minimal){NSString*hint=_catalog?@"选择当前工具的图层":(_graphMode&&[_toolType isEqual:@"curve"])?@"点击加点 · 拖动调整":(_graphMode&&[_toolType isEqual:@"grading"])?@"拖动色轮 · 参数查看亮度":@"拖动调节 · ↺ 还原";if(_graphMode&&[_toolType isEqual:@"hsl"])hint=@"拖动色点 · 参数精调";if(_graphMode&&[_toolType isEqual:@"spider"])hint=@"拖点联动 · 固定与还原选中点";if(_hover==20000||_movingPanel)hint=@"拖动标题移动 · 单击折叠";[self text:hint rect:NSMakeRect(_panel.origin.x+40*s,NSMaxY(_panel)-22*s,_panel.size.width-168*s,18*s) size:9 color:ink alignment:NSTextAlignmentCenter];}
|
||||
[NSGraphicsContext restoreGraphicsState];
|
||||
}
|
||||
- (NSInteger)partAtPoint:(NSPoint)p{if(!_visible||!std::isfinite(p.x)||!std::isfinite(p.y)||!_bridge||!NSPointInRect(p,NSIntersectionRect(_panel,NSMakeRect(0,0,_size.width,_size.height))))return 0;for(NSDictionary*a in [_areas reverseObjectEnumerator])if(![a[@"kind"]isEqual:@"toolUnavailable"]&&NSPointInRect(p,[a[@"rect"]rectValue]))return [a[@"part"]integerValue];return _open&&NSPointInRect(p,_panel)?20006:0;}
|
||||
- (NSInteger)partAtPoint:(NSPoint)p{if(!_visible||!std::isfinite(p.x)||!std::isfinite(p.y)||!_bridge||!NSPointInRect(p,NSIntersectionRect(_panel,NSMakeRect(0,0,_size.width,_size.height))))return 0;for(NSDictionary*a in [_areas reverseObjectEnumerator])if(![@[@"toolUnavailable",@"lensFrame"]containsObject:a[@"kind"]]&&NSPointInRect(p,[a[@"rect"]rectValue]))return [a[@"part"]integerValue];return ![@[@"curve",@"lens"]containsObject:_toolType]&&_open&&NSPointInRect(p,_panel)?20006:0;}
|
||||
- (NSDictionary*)areaForPart:(NSInteger)part{for(NSDictionary*a in _areas)if([a[@"part"]integerValue]==part)return a;return nil;}
|
||||
- (void)applySliderPoint:(NSPoint)p{
|
||||
NSRect t=[self trackForArea:_captured];NSDictionary*d=_captured[@"descriptor"];double ratio=MAX(0.,MIN(1.,(p.x-_knobOffset-t.origin.x)/MAX(1.,t.size.width)));_draftValue=[d[@"min"]doubleValue]+ratio*([d[@"max"]doubleValue]-[d[@"min"]doubleValue]);[_bridge changeValue:_draftValue];
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// The host document owns all edits. This controller stores only selection/layout.
|
||||
- (id<PROAPIAccessing>)rootHost {return [_manager isKindOfClass:DYToolManager.class]?[(DYToolManager*)_manager host]:_manager;}
|
||||
- (id<PROAPIAccessing>)lutManager {return _lutTarget?:_manager;}
|
||||
- (void)buildToolWorkspace {
|
||||
_splitFraction=.21;_toolTime=kCMTimeInvalid;
|
||||
_toolbarScroll=[[NSScrollView alloc]init];_toolbarScroll.hasHorizontalScroller=YES;_toolbarScroll.autohidesScrollers=YES;_toolbarScroll.drawsBackground=NO;
|
||||
_toolbar=[[DYWorkspaceList alloc]initWithFrame:NSMakeRect(0,0,1200,34)];_toolbarScroll.documentView=_toolbar;[_root addSubview:_toolbarScroll];
|
||||
CGFloat x=0;for(NSString *type in DYToolTypes()) {NSString *title=DYToolSection(type)[@"title"]?:type;NSButton *button=DYWorkspaceButton(title,self,@selector(addWorkspaceTool:));button.identifier=type;button.toolTip=[@"添加独立模块:" stringByAppendingString:title];CGFloat width=MAX(58,MIN(150,[title sizeWithAttributes:@{NSFontAttributeName:button.font}].width+22));button.frame=NSMakeRect(x,0,width,28);[_toolbar addSubview:button];x+=width+4;}_toolbar.frame=NSMakeRect(0,0,x,30);
|
||||
_split=[[NSSplitView alloc]init];_split.vertical=YES;_split.dividerStyle=NSSplitViewDividerStyleThin;_split.delegate=self;_split.accessibilityLabel=@"调整图层与参数宽度";[_root addSubview:_split];
|
||||
_toolPane=[[DYWorkspaceList alloc]init];_editorHost=[[DYWorkspaceList alloc]init];_editorHost.clipsToBounds=YES;[_split addSubview:_toolPane];[_split addSubview:_editorHost];
|
||||
_layerScroll=[[NSScrollView alloc]init];_layerScroll.hasVerticalScroller=YES;_layerScroll.autohidesScrollers=YES;_layerScroll.drawsBackground=NO;[_toolPane addSubview:_layerScroll];
|
||||
_layerTable=[[NSTableView alloc]init];NSTableColumn *column=[[[NSTableColumn alloc]initWithIdentifier:@"layer"]autorelease];column.title=@"模块与蒙版";[_layerTable addTableColumn:column];_layerTable.headerView=nil;_layerTable.rowHeight=30;_layerTable.dataSource=self;_layerTable.delegate=self;_layerTable.backgroundColor=DYThemeColor(@"background");_layerTable.columnAutoresizingStyle=NSTableViewLastColumnOnlyAutoresizingStyle;_layerTable.accessibilityLabel=@"模块与共享蒙版";_layerScroll.documentView=_layerTable;
|
||||
_addMask=[DYWorkspaceButton(@"+ 蒙版",self,@selector(addWorkspaceMask:))retain];[_toolPane addSubview:_addMask];
|
||||
_deleteLayer=[DYWorkspaceButton(@"删除",self,@selector(deleteWorkspaceSelection:))retain];[_toolPane addSubview:_deleteLayer];
|
||||
_selectionTitle=[[DYThemeLabel alloc]init];_selectionTitle.font=[NSFont systemFontOfSize:12 weight:NSFontWeightSemibold];[_editorHost addSubview:_selectionTitle];
|
||||
_maskPane=[[DYWorkspaceList alloc]init];_maskPane.clipsToBounds=YES;[_editorHost addSubview:_maskPane];_maskPane.hidden=YES;
|
||||
_maskScroll=[[NSScrollView alloc]init];_maskScroll.hasVerticalScroller=YES;_maskScroll.autohidesScrollers=YES;_maskScroll.drawsBackground=NO;[_maskPane addSubview:_maskScroll];
|
||||
_assignmentScroll=[[NSScrollView alloc]init];_assignmentScroll.hasVerticalScroller=YES;_assignmentScroll.autohidesScrollers=YES;_assignmentScroll.drawsBackground=NO;_assignmentScroll.accessibilityLabel=@"共享蒙版生效模块";[_maskPane addSubview:_assignmentScroll];
|
||||
[_scopePane removeFromSuperview];[_editorHost addSubview:_scopePane];[_lutPane removeFromSuperview];[_editorHost addSubview:_lutPane];[_lutExplanation removeFromSuperview];[_editorHost addSubview:_lutExplanation];
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(refreshToolWorkspace:) name:DYModelChanged object:[self rootHost]];
|
||||
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(workspaceCanvasSelection:) name:@"DYToolCanvasSelection" object:[self rootHost]];
|
||||
}
|
||||
- (void)layoutToolWorkspace {
|
||||
if(!_split||_sizingSplit)return;_sizingSplit=YES;
|
||||
CGFloat w=_split.bounds.size.width,h=_split.bounds.size.height,left=MAX(174,MIN(w-320,w*_splitFraction));
|
||||
_toolPane.frame=NSMakeRect(0,0,left,h);_editorHost.frame=NSMakeRect(left+_split.dividerThickness,0,MAX(1,w-left-_split.dividerThickness),h);
|
||||
_layerScroll.frame=NSMakeRect(0,0,left,MAX(1,h-35));_addMask.frame=NSMakeRect(6,MAX(0,h-32),MAX(80,left-76),28);_deleteLayer.frame=NSMakeRect(MAX(92,left-66),MAX(0,h-32),60,28);
|
||||
CGFloat ew=_editorHost.bounds.size.width;_selectionTitle.frame=NSMakeRect(12,5,MAX(1,ew-24),22);_toolEditor.frame=NSMakeRect(0,29,ew,MAX(1,h-29));
|
||||
_maskPane.frame=NSMakeRect(0,29,ew,MAX(1,h-29));CGFloat aw=MIN(230,MAX(160,ew*.25));_assignmentScroll.frame=NSMakeRect(ew-aw,0,aw,_maskPane.bounds.size.height);_maskScroll.frame=NSMakeRect(0,0,MAX(1,ew-aw-8),_maskPane.bounds.size.height);
|
||||
if(_maskEditor){_maskEditor.frame=NSMakeRect(0,0,_maskScroll.contentSize.width,MAX(_maskScroll.contentSize.height,_maskEditor.contentHeight));[_maskEditor layoutSubtreeIfNeeded];_maskEditor.frame=NSMakeRect(0,0,_maskScroll.contentSize.width,MAX(_maskScroll.contentSize.height,_maskEditor.contentHeight));}
|
||||
_sizingSplit=NO;
|
||||
}
|
||||
- (CGFloat)splitView:(NSSplitView*)split constrainSplitPosition:(CGFloat)position ofSubviewAt:(NSInteger)index {return MAX(174,MIN(split.bounds.size.width-320,position));}
|
||||
- (void)splitViewDidResizeSubviews:(NSNotification*)notification {if(_sizingSplit)return;_splitFraction=MAX(.12,MIN(.45,_toolPane.frame.size.width/MAX(1,_split.bounds.size.width)));[self layoutWorkspace];}
|
||||
- (BOOL)workspaceBaseVisible:(NSString*)type document:(NSDictionary*)document time:(CMTime)time {
|
||||
if(DYBaseToolRemoved(document,type))return NO;
|
||||
if([@[@"primary",@"spider",@"base",@"hsl"]containsObject:type])return YES;
|
||||
id<PROAPIAccessing>host=[self rootHost];id<FxParameterRetrievalAPI_v6>get=[host apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)];DYInspectorToken *token=nil;[get getCustomParameterValue:&token fromParameter:DYInspectorParameterID atTime:time];if([token.folds[[@"visible:" stringByAppendingString:type]]boolValue]||DYMasksForTool(document,[@"base:" stringByAppendingString:type]).count)return YES;
|
||||
for(NSDictionary*d in DYBaseToolDescriptors(type)){double value=[d[@"default"]doubleValue];[get getFloatValue:&value fromParameter:[d[@"pid"]unsignedIntValue]atTime:time];if(std::isfinite(value)&&fabs(value-[d[@"default"]doubleValue])>1e-6)return YES;}
|
||||
if([type isEqual:@"look"])for(NSString *key in DYReadAssets(host,time).paths)if([key hasPrefix:@"look"])return YES;return NO;
|
||||
}
|
||||
- (void)refreshToolWorkspace:(NSNotification*)note {
|
||||
if(!_visible&&!_opening)return;
|
||||
if(!NSThread.isMainThread){DYWorkspaceLifetime *token=_lifetime;dispatch_async(dispatch_get_main_queue(),^{[token.owner refreshToolWorkspace:note];});return;}
|
||||
if(_refreshingStack)return;_refreshingStack=YES;
|
||||
id<PROAPIAccessing>host=[self rootHost];id<FxCustomParameterActionAPI_v4>action=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!action){_refreshingStack=NO;return;}
|
||||
NSMutableArray *rows=[NSMutableArray array];NSMutableSet *assignedMasks=[NSMutableSet set];NSDictionary *document=nil;
|
||||
[action startAction:self];@try {
|
||||
_toolTime=action.currentTime;document=[DYReadTools(host,_toolTime).document copy];
|
||||
// Legacy base operators keep their real insertion-stage order. UUID children
|
||||
// use the same traversal as the renderer, including cross-type insertion.
|
||||
NSArray *bases=@[@"primary",@"primaries",@"curve",@"levels",@"balance",@"hsl",@"grading",@"base",@"blackwhite",@"look",@"skin",@"spider",@"mixer",@"film",@"lens"];
|
||||
NSArray *display=DYToolDisplayOrder(document);NSMutableArray *ordered=[NSMutableArray array];
|
||||
for(NSString*type in bases){NSString*base=[@"base:" stringByAppendingString:type];[ordered addObject:base];for(NSString*ID in display)if(DYToolWithID(document,ID)&&[DYToolRootAnchor(document,ID)isEqual:base])[ordered addObject:ID];}
|
||||
for(NSString*ID in display)if(DYToolWithID(document,ID)&&[DYToolRootAnchor(document,ID)isEqual:@"tail"])[ordered addObject:ID];
|
||||
for(NSString*ID in [ordered reverseObjectEnumerator]){NSDictionary*node=DYToolWithID(document,ID);NSString*type=node?node[@"type"]:[ID substringFromIndex:5];if(!node&&![self workspaceBaseVisible:type document:document time:_toolTime])continue;
|
||||
NSString*title=DYToolSection(type)[@"title"]?:type;[rows addObject:@{@"node":ID,@"type":type,@"title":title,@"kind":@"tool"}];
|
||||
for(NSDictionary*mask in DYMasksForTool(document,ID)){[assignedMasks addObject:mask[@"id"]];DYMaskParameters p=DYMaskAtTime(mask,_toolTime);NSString*name=@[@"椭圆",@"矩形",@"钢笔",@"渐变",@"HSL",@"亮度"][p.kind];[rows addObject:@{@"node":ID,@"mask":mask[@"id"],@"title":[@" ◩ " stringByAppendingString:name],@"kind":@"mask"}];}
|
||||
}
|
||||
for(NSDictionary*mask in DYSharedMasks(document))if(![assignedMasks containsObject:mask[@"id"]]){DYMaskParameters p=DYMaskAtTime(mask,_toolTime);[rows addObject:@{@"node":@"shared",@"mask":mask[@"id"],@"title":[@"◩ 未分配 · " stringByAppendingString:@[@"椭圆",@"矩形",@"钢笔",@"渐变",@"HSL",@"亮度"][p.kind]],@"kind":@"mask"}];}
|
||||
}@finally{[action endAction:self];}
|
||||
[_toolDocument release];_toolDocument=document;[_layerRows release];_layerRows=[rows copy];[_layerTable reloadData];
|
||||
NSString *requested=note.userInfo[@"scrollToTool"];if(requested.length){[_selectedNode release];_selectedNode=[requested copy];[_selectedMask release];_selectedMask=nil;}
|
||||
NSInteger selected=-1;for(NSUInteger i=0;i<_layerRows.count;i++){NSDictionary*row=_layerRows[i];if([row[@"node"]isEqual:_selectedNode]&&(_selectedMask?[row[@"mask"]isEqual:_selectedMask]:!row[@"mask"])){selected=i;break;}}
|
||||
if(selected<0&&_layerRows.count){selected=0;NSDictionary*first=_layerRows[0];[_selectedNode release];_selectedNode=[first[@"node"]copy];[_selectedMask release];_selectedMask=[first[@"mask"]copy];}
|
||||
if(selected>=0)[_layerTable selectRowIndexes:[NSIndexSet indexSetWithIndex:selected]byExtendingSelection:NO];else {[_selectedNode release];_selectedNode=nil;[_selectedMask release];_selectedMask=nil;}
|
||||
_refreshingStack=NO;[self rebuildWorkspaceEditor];
|
||||
}
|
||||
- (NSInteger)numberOfRowsInTableView:(NSTableView*)table {return _layerRows.count;}
|
||||
- (NSView*)tableView:(NSTableView*)table viewForTableColumn:(NSTableColumn*)column row:(NSInteger)row {
|
||||
NSDictionary*item=_layerRows[row];NSTableCellView*cell=[[[NSTableCellView alloc]init]autorelease];NSTextField*label=[DYThemeLabel labelWithString:item[@"title"]];label.font=[NSFont systemFontOfSize:item[@"mask"]?11:12];label.frame=NSMakeRect(8,5,MAX(20,column.width-48),20);label.autoresizingMask=NSViewWidthSizable;[cell addSubview:label];cell.textField=label;
|
||||
NSButton*eye=DYWorkspaceButton(@"",self,@selector(toggleWorkspaceRow:));eye.image=[NSImage imageWithSystemSymbolName:@"eye" accessibilityDescription:@"启用或旁路"];eye.bordered=NO;eye.tag=row;eye.frame=NSMakeRect(column.width-30,2,26,26);eye.autoresizingMask=NSViewMinXMargin;eye.accessibilityLabel=[item[@"title"]stringByAppendingString:@"启用或旁路"];[cell addSubview:eye];return cell;
|
||||
}
|
||||
- (void)tableViewSelectionDidChange:(NSNotification*)note {
|
||||
if(_refreshingStack)return;NSInteger row=_layerTable.selectedRow;if(row<0||row>=_layerRows.count)return;NSDictionary*item=_layerRows[row];[_selectedNode release];_selectedNode=[item[@"node"]copy];[_selectedMask release];_selectedMask=[item[@"mask"]copy];_pages.selectedSegment=_selectedMask?1:0;[self rebuildWorkspaceEditor];[self pageChanged:nil];
|
||||
}
|
||||
- (void)rebuildWorkspaceEditor {
|
||||
NSDictionary*node=DYToolWithID(_toolDocument,_selectedNode);NSString*type=node?node[@"type"]:[_selectedNode hasPrefix:@"base:"]?[_selectedNode substringFromIndex:5]:nil;
|
||||
_selectionTitle.stringValue=_selectedMask?@"共享蒙版 · 编辑与跟踪":DYToolSection(type)[@"title"]?:@"从上方添加模块";
|
||||
if(![_editorNode isEqual:_selectedNode]){[_toolEditor removeFromSuperview];[_toolEditor release];_toolEditor=nil;[_editorNode release];_editorNode=[_selectedNode copy];if(type){id<PROAPIAccessing>target=node?[[[DYToolManager alloc]initWithHost:[self rootHost]node:node]autorelease]:[self rootHost];_toolEditor=[[DYInspector alloc]initWithAPIManager:target renderer:_renderer workspaceType:type];[_editorHost addSubview:_toolEditor positioned:NSWindowBelow relativeTo:_maskPane];}}
|
||||
[_toolEditor refresh];
|
||||
if(_selectedNode.length&&![_selectedNode isEqual:@"shared"])[NSNotificationCenter.defaultCenter postNotificationName:@"DYWorkspaceToolSelection" object:[self rootHost]userInfo:@{@"node":_selectedNode}];
|
||||
if(_selectedMask){BOOL shared=DYSharedMaskWithID(_toolDocument,_selectedMask)!=nil;NSString*maskNode=shared?@"shared":_selectedNode;if(![_maskNode isEqual:maskNode]){[_maskEditor release];_maskEditor=nil;[_maskNode release];_maskNode=[maskNode copy];_maskEditor=[DYCreateWorkspaceMaskEditor([self rootHost],maskNode)retain];_maskScroll.documentView=_maskEditor;}[_maskEditor refreshWithDocument:_toolDocument time:_toolTime];[_maskEditor selectMaskID:_selectedMask];}
|
||||
else {_maskScroll.documentView=nil;[_maskEditor release];_maskEditor=nil;[_maskNode release];_maskNode=nil;}
|
||||
[self rebuildMaskAssignments];[self pageChanged:nil];
|
||||
}
|
||||
- (void)showPage:(NSString*)page maskKind:(NSNumber*)kind {
|
||||
NSArray*pages=@[@"tools",@"masks",@"lut",@"scopes"];NSUInteger index=[pages indexOfObject:page];if(index==NSNotFound)index=0;
|
||||
if(kind){[self createWorkspaceMask:kind.integerValue];return;}
|
||||
if(index==2){NSDictionary*node=DYToolWithID(_toolDocument,_selectedNode);if(![node[@"type"]isEqual:@"look"]&&![_selectedNode isEqual:@"base:look"]){for(NSDictionary*row in _layerRows)if([row[@"type"]isEqual:@"look"]){[_selectedNode release];_selectedNode=[row[@"node"]copy];break;}}[self bindLUTTarget];}
|
||||
_pages.selectedSegment=index;[self pageChanged:nil];
|
||||
}
|
||||
- (void)bindLUTTarget {
|
||||
NSDictionary*node=DYToolWithID(_toolDocument,_selectedNode);id<PROAPIAccessing>target=[node[@"type"]isEqual:@"look"]?[[[DYToolManager alloc]initWithHost:[self rootHost]node:node]autorelease]:[self rootHost];
|
||||
NSString*old=[_lutTarget isKindOfClass:DYToolManager.class]?[(DYToolManager*)_lutTarget nodeID]:@"base:look",*next=[target isKindOfClass:DYToolManager.class]?[(DYToolManager*)target nodeID]:@"base:look";
|
||||
if([old isEqual:next]&&_lutTarget)return;_selectionID++;[_selectionTask cancel];[_selectionTask release];_selectionTask=nil;[_browser close];[_browser release];_browser=nil;[(id)_lutTarget release];_lutTarget=[(id)target retain];
|
||||
}
|
||||
- (void)addWorkspaceTool:(NSButton*)sender {
|
||||
NSString*type=sender.identifier;if(![DYToolTypes()containsObject:type])return;id<PROAPIAccessing>host=[self rootHost];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;NSString*added=nil;
|
||||
[a startAction:self];@try{NSMutableDictionary*doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSString*anchor=(DYToolWithID(doc,_selectedNode)||[_selectedNode hasPrefix:@"base:"])?_selectedNode:[@"base:" stringByAppendingString:type];NSMutableDictionary*node=(id)DYInsertTool(doc,type,anchor);if(!node){[self reportError:@"模块达到上限,未添加"];return;}if(DYPrimaryColorState(DYReadAssets(host,a.currentTime).colorManagement)){DYUniforms u;DYReadUniforms(host,a.currentTime,&u);DYSeedPrimaryWorkingSpace(node,u.cm.workingTransfer,u.cm.workingGamut);}id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];BOOL grouped=[undo startUndoGroup:@"添加调色模块"];if(DYWriteTools(host,doc,a.currentTime))added=[node[@"id"]copy];if(grouped)[undo endUndoGroup];}@finally{[a endAction:self];}
|
||||
if(added){_pages.selectedSegment=0;[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host userInfo:@{@"scrollToTool":added}];[added release];}
|
||||
}
|
||||
- (void)addWorkspaceMask:(NSView*)sender {NSMenu*menu=[[[NSMenu alloc]initWithTitle:@"添加共享蒙版"]autorelease];for(NSInteger kind=0;kind<6;kind++){NSMenuItem*item=[menu addItemWithTitle:@[@"椭圆",@"矩形",@"钢笔",@"线性渐变",@"HSL 选区",@"亮度选区"][kind]action:@selector(addWorkspaceMaskKind:)keyEquivalent:@""];item.target=self;item.tag=kind;}[menu popUpMenuPositioningItem:nil atLocation:NSMakePoint(0,sender.bounds.size.height)inView:sender];}
|
||||
- (void)addWorkspaceMaskKind:(NSMenuItem*)sender {[self createWorkspaceMask:sender.tag];}
|
||||
- (void)createWorkspaceMask:(NSInteger)kind {
|
||||
id<PROAPIAccessing>host=[self rootHost];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;NSString*ID=nil;
|
||||
[a startAction:self];@try{NSMutableDictionary*doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);NSDictionary*mask=DYAddSharedMask(doc,kind);if(!mask)return;NSString*node=_selectedNode;if(node.length&&![node isEqual:@"shared"])DYSetSharedMaskAssigned(doc,mask[@"id"],node,YES);id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];BOOL grouped=[undo startUndoGroup:@"创建共享蒙版"];if(DYWriteTools(host,doc,a.currentTime))ID=[mask[@"id"]copy];if(grouped)[undo endUndoGroup];}@finally{[a endAction:self];}
|
||||
if(!ID)return;[_selectedMask release];_selectedMask=ID;if(!_selectedNode){_selectedNode=[@"shared" copy];}_pages.selectedSegment=1;[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];
|
||||
[NSNotificationCenter.defaultCenter postNotificationName:@"DYToolCanvasSelection" object:host userInfo:@{@"node":@"shared",@"mask":ID,@"document":_toolDocument?:@{},@"draw":@(kind==2)}];
|
||||
}
|
||||
- (void)rebuildMaskAssignments {
|
||||
DYWorkspaceList*list=[[[DYWorkspaceList alloc]init]autorelease];CGFloat y=8;NSTextField*heading=[DYThemeLabel labelWithString:_selectedMask?@"应用到模块":@"选择或绘制一个蒙版"];heading.font=[NSFont systemFontOfSize:12 weight:NSFontWeightSemibold];heading.frame=NSMakeRect(8,y,210,24);[list addSubview:heading];y+=30;
|
||||
NSArray*assigned=DYToolIDsForSharedMask(_toolDocument,_selectedMask);
|
||||
for(NSDictionary*row in _layerRows)if([row[@"kind"]isEqual:@"tool"]){NSButton*check=[NSButton checkboxWithTitle:row[@"title"]target:self action:@selector(maskAssignmentChanged:)];check.identifier=row[@"node"];check.state=[assigned containsObject:row[@"node"]]?NSControlStateValueOn:NSControlStateValueOff;check.enabled=_selectedMask.length>0;check.frame=NSMakeRect(8,y,210,28);check.accessibilityLabel=[@"蒙版应用到 " stringByAppendingString:row[@"title"]];[list addSubview:check];y+=30;}
|
||||
list.frame=NSMakeRect(0,0,220,y+8);_assignmentScroll.documentView=list;
|
||||
}
|
||||
- (void)maskAssignmentChanged:(NSButton*)sender {
|
||||
if(!_selectedMask)return;id<PROAPIAccessing>host=[self rootHost];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;BOOL written=NO;
|
||||
[a startAction:self];@try{NSMutableDictionary*doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);if(!DYSharedMaskWithID(doc,_selectedMask))DYShareToolMask(doc,_selectedNode,_selectedMask);if(!DYSetSharedMaskAssigned(doc,_selectedMask,sender.identifier,sender.state==NSControlStateValueOn))return;id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];BOOL grouped=[undo startUndoGroup:@"关联共享蒙版模块"];written=DYWriteTools(host,doc,a.currentTime);if(grouped)[undo endUndoGroup];}@finally{[a endAction:self];}
|
||||
if(written)[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];else [self reportError:@"宿主未保存蒙版关联,原设置已保留"];
|
||||
}
|
||||
- (void)workspaceCanvasSelection:(NSNotification*)note {
|
||||
if(!_visible||_refreshingStack||![note.userInfo[@"mask"]length])return;NSString*mask=note.userInfo[@"mask"];if([mask isEqual:_selectedMask])return;[_selectedMask release];_selectedMask=[mask copy];if(![note.userInfo[@"node"]isEqual:@"shared"]){[_selectedNode release];_selectedNode=[note.userInfo[@"node"]copy];}_pages.selectedSegment=1;[self rebuildWorkspaceEditor];
|
||||
}
|
||||
- (void)toggleWorkspaceRow:(NSButton*)sender {
|
||||
if(sender.tag<0||sender.tag>=_layerRows.count)return;NSDictionary*row=_layerRows[sender.tag];NSString*ID=row[@"node"];id<PROAPIAccessing>host=[self rootHost];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;BOOL changed=NO;
|
||||
[a startAction:self];id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];BOOL grouped=[undo startUndoGroup:@"启用或旁路模块与蒙版"];@try{NSMutableDictionary*doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);
|
||||
if(row[@"mask"]){NSMutableDictionary*mask=nil;for(NSMutableDictionary*m in DYMasksForTool(doc,ID))if([m[@"id"]isEqual:row[@"mask"]])mask=m;if(mask){mask[@"enabled"]=@(![mask[@"enabled"]boolValue]);changed=DYWriteTools(host,doc,a.currentTime);}}
|
||||
else {NSDictionary*node=DYToolWithID(doc,ID);NSString*type=node?node[@"type"]:[ID substringFromIndex:5];NSDictionary*section=DYToolSection(type);id<PROAPIAccessing>target=node?[[[DYToolManager alloc]initWithHost:host node:node]autorelease]:host;id<FxCustomParameterActionAPI_v4>action=[target apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];[action startAction:self];@try{double value=0;[[target apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:&value fromParameter:[section[@"enabled"]unsignedIntValue]atTime:a.currentTime];id<FxParameterSettingAPI_v6>set=[target apiForProtocol:@protocol(FxParameterSettingAPI_v6)];NSMutableArray*flags=[NSMutableArray array];if(section[@"enabled"])[flags addObject:section[@"enabled"]];if(section[@"extraEnabled"])[flags addObject:section[@"extraEnabled"]];[flags addObjectsFromArray:section[@"enableParameters"]?:@[]];for(NSNumber*pid in flags)changed=[set setFloatValue:value>=.5?0:1 toParameter:pid.unsignedIntValue atTime:a.currentTime]||changed;}@finally{[action endAction:self];}}
|
||||
}@finally{if(grouped)[undo endUndoGroup];[a endAction:self];}if(changed)[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];
|
||||
}
|
||||
- (void)deleteWorkspaceSelection:(id)sender {
|
||||
if(!_selectedMask){[_toolEditor removeWorkspaceTool];return;}
|
||||
id<PROAPIAccessing>host=[self rootHost];id<FxCustomParameterActionAPI_v4>a=[host apiForProtocol:@protocol(FxCustomParameterActionAPI_v4)];if(!a)return;BOOL changed=NO;
|
||||
[a startAction:self];@try{NSMutableDictionary*doc=DYMutablePlist(DYReadTools(host,a.currentTime).document);if(DYSharedMaskWithID(doc,_selectedMask))changed=DYRemoveSharedMask(doc,_selectedMask);else{NSMutableArray*masks=[[DYMasksForTool(doc,_selectedNode)mutableCopy]autorelease];[masks filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary*m,NSDictionary*b){return ![m[@"id"]isEqual:self->_selectedMask];}]];changed=DYSetToolMasks(doc,_selectedNode,masks);}if(changed){id<FxUndoAPI>undo=[host apiForProtocol:@protocol(FxUndoAPI)];BOOL grouped=[undo startUndoGroup:@"删除蒙版对象"];changed=DYWriteTools(host,doc,a.currentTime);if(grouped)[undo endUndoGroup];}}@finally{[a endAction:self];}if(changed){[_selectedMask release];_selectedMask=nil;[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include "DYTracker.hpp"
|
||||
|
||||
namespace dy {
|
||||
// OpenCV is built from the pinned public source, never loaded from another app.
|
||||
// Coordinates and authored results match the existing host-analysis contract.
|
||||
class OpenCVTracker {
|
||||
struct Impl;
|
||||
std::shared_ptr<Impl> impl_;
|
||||
public:
|
||||
OpenCVTracker();
|
||||
~OpenCVTracker();
|
||||
OpenCVTracker(const OpenCVTracker&) = delete;
|
||||
OpenCVTracker& operator=(const OpenCVTracker&) = delete;
|
||||
void setMask(std::vector<FlowPoint>);
|
||||
bool reset(const GrayFrame&, TrackerROI);
|
||||
TrackResult track(const GrayFrame&);
|
||||
TrackResult result() const;
|
||||
bool active() const;
|
||||
void stop();
|
||||
static const char* version();
|
||||
};
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户