Compare commits

..

198 Commits

Author SHA1 Message Date
ww-rm
94dabebf2b 修正文字说明 2025-04-09 15:34:03 +08:00
ww-rm
8e875d4f7e update changelog 2025-04-09 15:25:15 +08:00
ww-rm
86c383f2cf 默认使用libwebp_anim编码器 2025-04-09 15:24:48 +08:00
ww-rm
b404d8e79a 增加最后一帧参数 2025-04-09 15:24:31 +08:00
ww-rm
d32b480ef2 更新readme 2025-04-09 14:00:26 +08:00
ww-rm
3654825f27 补充文字说明 2025-04-09 13:52:59 +08:00
ww-rm
d7231e8a09 更新至版本v0.12.2 2025-04-09 13:43:21 +08:00
ww-rm
98161aaf2e update changelog 2025-04-09 13:40:34 +08:00
ww-rm
7a942b16bc 调整动图默认帧率 2025-04-09 13:40:11 +08:00
ww-rm
067719c69b 补充面板属性刷新 2025-04-09 13:36:34 +08:00
ww-rm
f3fce53b91 增加导出参数缓存 2025-04-09 13:19:25 +08:00
ww-rm
e35903f436 增加webp和avif动图格式 2025-04-09 13:19:17 +08:00
ww-rm
64cfe5fdd7 限定readonly 2025-04-09 01:09:57 +08:00
ww-rm
dbe586cff8 调整结构 2025-04-09 01:07:17 +08:00
ww-rm
3104733db0 补充调试参数 2025-04-08 15:00:42 +08:00
ww-rm
9d4bdd1028 标题栏增加版本号 2025-04-08 13:51:10 +08:00
ww-rm
f8030b1645 整合参数标签页 2025-04-08 13:44:30 +08:00
ww-rm
0a999ceb41 增加 SpinePropertyGrid 2025-04-08 13:21:29 +08:00
ww-rm
64bd9907cb 重构 2025-04-07 15:06:23 +08:00
ww-rm
580eaf990d 测试代码 2025-04-05 11:57:44 +08:00
ww-rm
5ab232a961 更新至v0.12.1 2025-04-05 11:56:53 +08:00
ww-rm
e596cd7ea4 update changelog 2025-04-05 11:56:13 +08:00
ww-rm
05c47a4daa 增加初始动画皮肤空位 2025-04-05 11:52:34 +08:00
ww-rm
5a8783b5f4 增加确定按钮 2025-04-05 11:18:54 +08:00
ww-rm
08bc171a72 修复分辨率调整时父容器尺寸获取错误bug 2025-04-05 10:38:17 +08:00
ww-rm
7372f5fe08 optimize 2025-04-05 10:31:30 +08:00
ww-rm
6f032bdd05 optimize 2025-04-05 10:10:04 +08:00
ww-rm
153d3603d2 optimize 2025-04-05 09:40:02 +08:00
ww-rm
95261e6907 optimize 2025-04-05 01:53:39 +08:00
ww-rm
17b344376d update readme 2025-04-05 01:39:59 +08:00
ww-rm
0ed4e44878 更新至v0.12.0 2025-04-05 01:22:14 +08:00
ww-rm
b42c1832f0 update changelog 2025-04-05 01:16:00 +08:00
ww-rm
058534ba67 修复部分资源泄漏 2025-04-05 01:14:59 +08:00
ww-rm
204dcd6498 增加3.8及以上版本多皮肤支持 2025-04-05 00:57:04 +08:00
ww-rm
2c846c0db9 补充update0 2025-04-04 20:10:29 +08:00
ww-rm
2faeb044e0 增加 readonly 限定 2025-04-04 17:36:52 +08:00
ww-rm
09c8e4f779 修复导出过程中的PMA问题 2025-04-04 17:21:30 +08:00
ww-rm
6994fa6be8 修复shader问题 2025-04-04 11:26:23 +08:00
ww-rm
cc7beb7670 增加SFMLExtension 2025-04-03 20:14:13 +08:00
ww-rm
510653732d 移除冗余引用 2025-04-03 19:46:01 +08:00
ww-rm
93e8178d67 增加部分实验性样例代码 2025-04-03 19:39:13 +08:00
ww-rm
cebc4864cc 封装原生操作 2025-04-03 18:22:55 +08:00
ww-rm
6ad0449376 修复内存泄漏 2025-04-03 18:19:12 +08:00
ww-rm
c33c977326 update changelog 2025-04-03 15:02:18 +08:00
ww-rm
f0299d365a 补充update0 2025-04-03 09:55:51 +08:00
ww-rm
6ecdca73f5 不提供时长时按所有轨道动画时长最大值导出 2025-04-03 00:30:55 +08:00
ww-rm
af6a709b2c 完善动画时间重置功能 2025-04-03 00:30:33 +08:00
ww-rm
d5c27450ef 修改pma默认值为false 2025-04-03 00:15:44 +08:00
ww-rm
d10269fb07 small change 2025-04-03 00:13:36 +08:00
ww-rm
53d987476e 增加多轨道动画编辑 2025-04-02 23:59:18 +08:00
ww-rm
8b7866d37f 增加多轨方法 2025-04-02 11:43:25 +08:00
ww-rm
bb529729b6 增加Tracks公开属性 2025-04-02 11:41:23 +08:00
ww-rm
b7735d9ba8 改成并集动画皮肤列表 2025-04-01 21:07:52 +08:00
ww-rm
ce744e2b84 update badges 2025-03-31 22:56:50 +08:00
ww-rm
631c92da3f update readme 2025-03-31 22:18:06 +08:00
ww-rm
b7063804e9 add badges 2025-03-31 22:04:31 +08:00
ww-rm
75d47c8419 修改提示文本 2025-03-31 20:55:37 +08:00
ww-rm
114fb05e80 调整布局 2025-03-31 19:28:32 +08:00
ww-rm
1fec65b37d 更新至v0.11.5 2025-03-31 17:42:54 +08:00
ww-rm
9498e8f334 update readme 2025-03-31 17:42:44 +08:00
ww-rm
83b8411929 update changelog 2025-03-31 17:34:48 +08:00
ww-rm
e9accd13b3 增加所有导出格式 2025-03-31 17:30:20 +08:00
ww-rm
9e27a19258 允许多标记 2025-03-31 14:37:47 +08:00
ww-rm
252f3a5bea 优化显示 2025-03-31 02:07:02 +08:00
ww-rm
e0626bb126 增加项数显示 2025-03-31 01:58:30 +08:00
ww-rm
7ff62c7f40 增加错误日志 2025-03-31 01:45:16 +08:00
ww-rm
4b07e02acb 增加线程安全 2025-03-31 01:44:41 +08:00
ww-rm
4654d1d9c2 优化多项操作卡顿问题 2025-03-30 20:52:22 +08:00
ww-rm
ce1f75e8a5 增加报错调试 2025-03-30 20:07:29 +08:00
ww-rm
4d9aebc758 修复预览图不显示问题 2025-03-30 20:06:13 +08:00
ww-rm
e814368ef3 移除rid 2025-03-30 19:30:58 +08:00
ww-rm
bbbb02500f 增加StringEnumConverter 2025-03-30 17:26:17 +08:00
ww-rm
404f255f14 update readme 2025-03-30 15:22:48 +08:00
ww-rm
7a15e0d38a 隐藏不可见成员 2025-03-30 13:54:17 +08:00
ww-rm
bfe669bdd9 增加FFMpegCore版本信息 2025-03-30 12:07:28 +08:00
ww-rm
c0553042fd 更新至v0.11.4 2025-03-30 11:59:52 +08:00
ww-rm
af8b02654b update readme 2025-03-30 11:59:37 +08:00
ww-rm
4779ec91d0 update changelog 2025-03-30 11:59:13 +08:00
ww-rm
14d7f4af0e 增加MP4导出格式 2025-03-30 11:56:20 +08:00
ww-rm
f9888b23dd 设置GIF默认背景颜色为纯白透明背景 2025-03-30 11:56:06 +08:00
ww-rm
411cdbb00f 设置默认颜色为纯黑透明背景 2025-03-30 11:55:52 +08:00
ww-rm
d859f07469 增加导出时输出ffmpeg参数 2025-03-29 23:48:56 +08:00
ww-rm
c111819093 增加背景颜色参数 2025-03-29 22:17:08 +08:00
ww-rm
aa8321d13c 整理代码结构 2025-03-29 21:15:34 +08:00
ww-rm
5e3bd972e5 移动GetVersion至SpineHelper 2025-03-29 17:04:26 +08:00
ww-rm
ad39a04fff 重命名SpineVersion 2025-03-29 16:59:28 +08:00
ww-rm
9a97e84296 解耦对MessageBox的依赖,提供单独的Shader初始化函数 2025-03-29 16:51:05 +08:00
ww-rm
1b7b0dcb13 解耦日志器 2025-03-29 16:30:32 +08:00
ww-rm
d365a5060b small change 2025-03-29 15:34:56 +08:00
ww-rm
b69589394a 提取ImplementationResolver实现 2025-03-29 15:12:50 +08:00
ww-rm
00f5791766 增加导出时任务栏图标显示 2025-03-28 20:53:48 +08:00
ww-rm
38cab2eda7 修复可能的预览图资源泄漏 2025-03-27 23:31:03 +08:00
ww-rm
0db4d6e4e0 small change 2025-03-27 19:45:56 +08:00
ww-rm
549712962f 去除多余组件 2025-03-27 10:11:44 +08:00
ww-rm
34b7002faf 增加背景颜色选项 2025-03-27 10:08:16 +08:00
ww-rm
0e6f47b23c 预修改适配对多轨道动画 2025-03-27 09:56:21 +08:00
ww-rm
a372a89b5e 增加update0 2025-03-27 09:09:22 +08:00
ww-rm
239847aee7 皮肤更换后使用SetSlotsToSetupPose而不是SetToSetupPose 2025-03-27 09:03:09 +08:00
ww-rm
813249c6a7 调整布局 2025-03-26 21:09:52 +08:00
ww-rm
293ab28bce 更新预览图 2025-03-26 20:49:22 +08:00
ww-rm
98e73cdec5 调整面板比例 2025-03-26 20:48:23 +08:00
ww-rm
6d34bb9d25 移除无用引用 2025-03-26 20:37:27 +08:00
ww-rm
479a5e4da9 更新至v0.11.3 2025-03-26 20:33:48 +08:00
ww-rm
4829454877 update changelog 2025-03-26 20:33:31 +08:00
ww-rm
28664f6387 增加隐藏控制 2025-03-26 20:30:55 +08:00
ww-rm
1a08a23a9c 批量添加完成自动选中最后一项 2025-03-26 20:24:27 +08:00
ww-rm
16f344ff1b 增加纹理调试 2025-03-26 19:55:43 +08:00
ww-rm
693ce0e2e8 调整属性分组和注释 2025-03-26 19:52:29 +08:00
ww-rm
e6f533ea65 优化属性分组显示顺序 2025-03-26 18:54:35 +08:00
ww-rm
fcc21d63b0 优化排列顺序 2025-03-26 18:39:30 +08:00
ww-rm
afc0ffcb67 Merge branch 'main' of github.com:ww-rm/SpineViewer 2025-03-26 18:25:56 +08:00
ww-rm
9ffb9840e1 去除限制 2025-03-26 18:25:48 +08:00
ww-rm
4766ccf1b6 互换模型和画面参数面板位置 2025-03-26 18:23:59 +08:00
ww-rm
16b75c80a3 Update README.en.md 2025-03-26 17:00:08 +08:00
ww-rm
880f063046 优化分割条可感知宽度 2025-03-26 16:20:12 +08:00
ww-rm
723c11b886 更新至v0.11.2 2025-03-26 15:54:19 +08:00
ww-rm
5e074b1cf7 update changelog 2025-03-26 15:54:06 +08:00
ww-rm
71d2fee36e 修复纹理加载异常 2025-03-26 15:53:27 +08:00
ww-rm
7dc701464f 优化缩放实现 2025-03-26 15:43:54 +08:00
ww-rm
fd876ef90f 补充皮肤切换后的刷新 2025-03-26 15:25:55 +08:00
ww-rm
0597852178 增加皮肤属性 2025-03-26 15:20:59 +08:00
ww-rm
81b1333091 small change 2025-03-26 15:20:49 +08:00
ww-rm
7baebd79a6 update changelog 2025-03-26 14:32:07 +08:00
ww-rm
951d0e30ae 更新至v0.11.1 2025-03-26 14:28:57 +08:00
ww-rm
711e172769 优化显示 2025-03-26 13:57:08 +08:00
ww-rm
faa60f0ea1 update readme 2025-03-26 13:37:12 +08:00
ww-rm
99d81c4329 增加GIF导出格式 2025-03-26 13:10:51 +08:00
ww-rm
17904326f3 修复tex跨线程问题 2025-03-26 13:10:45 +08:00
ww-rm
5ee74f39d8 增加逐个导出时使用自动时长 2025-03-26 13:07:23 +08:00
ww-rm
72f898ed60 增加导出事件绑定 2025-03-26 10:30:57 +08:00
ww-rm
157eab5bac 修复Update顺序错误 2025-03-26 10:08:56 +08:00
ww-rm
e1b0d0a2ad small change 2025-03-26 02:53:09 +08:00
ww-rm
2c050ba031 update readme 2025-03-26 02:51:02 +08:00
ww-rm
41518b16b4 更新至v0.11.0 2025-03-26 02:45:01 +08:00
ww-rm
72a16dc95f 导出单个时也在子目录输出 2025-03-26 02:44:30 +08:00
ww-rm
3404c64f55 update changelog 2025-03-26 02:40:21 +08:00
ww-rm
b9015422f8 增加注释 2025-03-26 02:37:37 +08:00
ww-rm
a7441b968d 增加快进功能 2025-03-26 02:31:07 +08:00
ww-rm
2d44be31f7 优化Bitmap获取过程 2025-03-25 23:34:35 +08:00
ww-rm
c2cf25bb2b 统一导出类结构 2025-03-25 23:25:04 +08:00
ww-rm
7c4c53dcb0 简化时间标记 2025-03-25 18:46:17 +08:00
ww-rm
aceb3b17c8 统一调用 2025-03-25 18:42:24 +08:00
ww-rm
adfcfdb1de 优化显示 2025-03-25 11:24:37 +08:00
ww-rm
da329723bc 修改提示弹窗 2025-03-25 10:49:36 +08:00
ww-rm
63eb53fa06 调整命名空间 2025-03-25 00:53:32 +08:00
ww-rm
d32c824515 设置只读参数 2025-03-25 00:31:30 +08:00
ww-rm
e9ee8c481c 去除多余注释 2025-03-25 00:21:07 +08:00
ww-rm
6d78e52605 增加开始暂停图标按钮 2025-03-25 00:08:50 +08:00
ww-rm
90136a5562 重构导出 2025-03-24 23:05:01 +08:00
ww-rm
1592767c8c 增加注释 2025-03-24 21:14:10 +08:00
ww-rm
afa6ce2113 增加画面开始暂停 2025-03-24 21:01:07 +08:00
ww-rm
50e6e414ee 调整文件夹结构 2025-03-24 18:49:36 +08:00
ww-rm
ba9b8edcdc 增加文件夹路径编辑器 2025-03-24 18:49:01 +08:00
ww-rm
d7a927475c 修改父类 2025-03-24 18:48:16 +08:00
ww-rm
afe210343f 增加适合模型文件的UIEditor 2025-03-24 18:43:51 +08:00
ww-rm
4e293daf62 更新至v0.10.9 2025-03-24 15:18:09 +08:00
ww-rm
f9d7fdc516 update readme 2025-03-24 15:17:42 +08:00
ww-rm
6a04f3955c 完善预览图导出参数 2025-03-24 15:15:59 +08:00
ww-rm
dce3b1780c update readme 2025-03-24 14:44:44 +08:00
ww-rm
f47f3e9db6 更新至v0.10.8 2025-03-24 14:42:21 +08:00
ww-rm
4ac74acaf7 update changelog 2025-03-24 14:42:11 +08:00
ww-rm
cf7588c288 update readme 2025-03-24 14:41:25 +08:00
ww-rm
ec7bdf4000 预览图增加仅导出选中 2025-03-24 14:33:09 +08:00
ww-rm
51cd97f782 调整布局 2025-03-24 13:48:05 +08:00
ww-rm
a16f2f096d 完善预览图导出 2025-03-24 13:47:56 +08:00
ww-rm
4e92f14551 完善文件转换功能 2025-03-24 01:58:53 +08:00
ww-rm
8f6cc9ff44 增加任意格式读取 2025-03-24 01:57:49 +08:00
ww-rm
f885df5c67 增加文件选择控件 2025-03-24 01:57:13 +08:00
ww-rm
0ccb110e36 fix bug 2025-03-24 00:20:53 +08:00
ww-rm
2c238dca9b 更新至v0.10.7 2025-03-24 00:17:02 +08:00
ww-rm
3e0aa53fca update changelog 2025-03-24 00:16:33 +08:00
ww-rm
12b4e44296 增加仅导出选中 2025-03-24 00:14:43 +08:00
ww-rm
9a2cf4aefe 增加region注释 2025-03-24 00:10:32 +08:00
ww-rm
0e2a116e0a 增加显示包围盒调试 2025-03-24 00:05:11 +08:00
ww-rm
7bf30eb54a 增加仅渲染选中模式 2025-03-24 00:01:28 +08:00
ww-rm
8dda8c8ff3 增加动画交集选择 2025-03-23 10:58:57 +08:00
ww-rm
988fdb22be 增加重载 2025-03-23 10:55:28 +08:00
ww-rm
1dd2c8fb4d fix bug 2025-03-23 10:19:50 +08:00
ww-rm
2b39384b28 重构以及增加注释 2025-03-23 01:34:44 +08:00
ww-rm
28d1275023 增加公开属性 2025-03-22 23:11:13 +08:00
ww-rm
979181fc3b small change 2025-03-22 21:12:47 +08:00
ww-rm
b374b88ad5 add writeskins 2025-03-22 21:08:14 +08:00
ww-rm
6643c19a20 remove useless member 2025-03-22 16:07:04 +08:00
ww-rm
7460874c81 增加注释 2025-03-22 12:38:17 +08:00
ww-rm
13dd7511f6 优化预览图获取 2025-03-21 20:35:39 +08:00
ww-rm
f153d251c8 增加预览图留白 2025-03-21 20:09:08 +08:00
ww-rm
3442ace981 更新至v0.10.6 2025-03-21 14:57:50 +08:00
ww-rm
547cebf5a9 update readme 2025-03-21 14:57:30 +08:00
ww-rm
7a24d22bc6 update changelog 2025-03-21 14:57:25 +08:00
ww-rm
8f5728afe4 fix bug 2025-03-21 14:45:45 +08:00
ww-rm
41b5ac2c61 优化渲染 2025-03-21 14:31:20 +08:00
ww-rm
694ca3bf25 refactor 2025-03-21 13:32:03 +08:00
ww-rm
674d314b55 增加文件夹查找 2025-03-21 13:24:18 +08:00
ww-rm
08a35cc5d1 增加ctrlV导入 2025-03-21 11:14:31 +08:00
ww-rm
176e5db4d9 fix bug 2025-03-21 01:40:42 +08:00
ww-rm
2535a9ebf9 增加运行时标识 2025-03-21 01:05:08 +08:00
ww-rm
8ff99ee925 small optimize 2025-03-21 00:27:38 +08:00
ww-rm
abc8218487 add log 2025-03-21 00:23:31 +08:00
111 changed files with 8189 additions and 6470 deletions

View File

@@ -1,32 +1,114 @@
# CHANGELOG
## v0.12.2
- 模型参数分标签显示
- 皮肤/动画列表使用右键菜单进行增删
- 标题栏显示版本号
- 增加 webp 和 avif 动图格式
- 增加导出参数缓存
- 动图默认帧率修改为 24 帧
- 增加保留最后一帧参数
## v0.12.1
- 优化使用体验, 提供初始皮肤/动画空位
- 修复预览画面分辨率调整时父容器尺寸获取错误
## v0.12.0
- 支持皮肤列表 (仅 3.8.x 及以上支持)
- 支持多轨道动画
- 动画和皮肤列表多选时改为取并集
- 修复导出时没有正确处理预乘像素的问题
## v0.11.5
- 导出格式全面支持
- 修复预览图不显示的问题
- 优化列表卡顿问题
- 模型列表增加数量显示
## v0.11.4
- 增加 MP4 导出格式
- 增加导出背景颜色参数
- 增加日志输出 FFMpeg 参数字符串
- 增加导出时任务栏图标执行动效
- 修复预览面板移动模型时物理效果不同步的问题
- 优化部分使用体验
## v0.11.3
- 增加模型隐藏设置属性
- 加宽面板分割条 (4 -> 8 像素)
- 优化属性面板分组显示
- 增加调试纹理
## v0.11.2
- 增加皮肤切换
- 优化模型缩放实现
- 修复部分情况纹理加载异常
## v0.11.1
- 增加 GIF 导出格式
- 增加逐个导出时可选自动时长
- 优化使用体验
## v0.11.0
- 完成导出系统, 支持完整的单帧和帧序列导出功能
- 预览画面增加快进功能
## v0.10.9
- 预览图导出增加名称后缀参数
## v0.10.8
- 完善预览图导出
- 优化骨骼文件选择
## v0.10.7
- 增加仅导出选中
- 增加模型调试属性
## v0.10.6
- 增加文件夹检测
- 增加从剪贴板添加(可复制本地文件/文件夹直接打开)
- 修复预览图导致的批量添加可能卡死
## v0.10.5
- <EFBFBD>޸<EFBFBD>һЩ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- 修复一些问题
## v0.10.4
- <EFBFBD>޸<EFBFBD>һЩ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- 修复一些问题
## v0.10.3
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Զ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><EFBFBD>ϷŴ<EFBFBD><EFBFBD><EFBFBD>
- 增加自动版本检测
- 增加文件拖放打开
## v0.10.2
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD><EFBFBD>Ҽ<EFBFBD><EFBFBD>˵<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ݼ<EFBFBD>
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԥ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD><EFBFBD><EFBFBD>ͼ<EFBFBD>л<EFBFBD>
- 增加列表右键菜单快捷键
- 增加预览缩略图复制
- 增加列表视图切换
## v0.10.1
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD>Ԥ<EFBFBD><EFBFBD>ͼ
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD>Ԥ<EFBFBD><EFBFBD>ͼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- 增加列表预览图
- 增加列表预览图导出
## v0.10.0
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˻<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɾ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԥ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʾ<EFBFBD><EFBFBD>Χ<EFBFBD><EFBFBD>ѡ<EFBFBD><EFBFBD>
- <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˹<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><EFBFBD><EFBFBD>ʽת<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ܣ<EFBFBD>Ŀǰ<EFBFBD><EFBFBD>֧<EFBFBD>ֲ<EFBFBD><EFBFBD>ְ汾<EFBFBD>IJ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- <EFBFBD>Ż<EFBFBD><EFBFBD>˲<EFBFBD><EFBFBD><EFBFBD>ʹ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
- 增加了画面和列表的选择联动,并删除了预览画面显示包围盒选项
- 增加了骨骼文件格式转换功能,目前仅支持部分版本的不完整功能
- 优化了部分使用体验

View File

@@ -1,70 +1,106 @@
# [SpineViewer](https://github.com/ww-rm/SpineViewer)
[![Build and Release](https://github.com/ww-rm/SpineViewer/actions/workflows/dotnet-desktop.yml/badge.svg)](https://github.com/ww-rm/SpineViewer/actions/workflows/dotnet-desktop.yml)
[![GitHub Release](https://img.shields.io/github/v/release/ww-rm/SpineViewer?logo=github&logoColor=959da5&label=Release&labelColor=3f4850)](https://github.com/ww-rm/SpineViewer/releases)
[![Downloads](https://img.shields.io/github/downloads/ww-rm/SpineViewer/total?logo=github&logoColor=959da5&label=Downloads&labelColor=3f4850)](https://github.com/ww-rm/SpineViewer/releases)
[中文](README.md) | [English](README.en.md)
A simple and user-friendly Spine file viewer and exporter.
*A WYSIWYG Spine file viewer and exporter.*
![previewer](img/preview.webp)
---
## Installation
Download the zip package from the [Releases](https://github.com/ww-rm/SpineViewer/releases) page.
The application requires the [.NET Desktop Runtime 8.0.x](https://dotnet.microsoft.com/en-us/download/dotnet/8.0).
Alternatively, you can download the zip package with the `SelfContained` suffix, which can run independently.
## Features
- Supports viewing Spine files of different versions:
- [x] `v2.1.x`
- [x] `v3.6.x`
- [x] `v3.7.x`
- [x] `v3.8.x`
- [x] `v4.0.x`
- [x] `v4.1.x`
- [x] `v4.2.x`
- [ ] `v4.3.x`
- Supports animation preview for multi-skeleton files
- Allows independent parameter settings for each skeleton
- Supports exporting animation as PNG frame sequences
- Provides export settings such as zoom and rotation
- More features coming soon...
## Usage
### Importing Skeletons
Use the **File** menu to select **Open** or **Batch Open** to import skeleton files.
### Adjusting Skeletons
Select one or more items in the **Model List** to display adjustable parameters in the **Model Parameters** panel.
Right-clicking in the **Model List** allows you to add, delete, or adjust list items. You can also drag items with the left mouse button to rearrange them.
### Adjusting the View
Mouse operations supported in the **Preview** window:
- Left-click to drag the skeleton
- Right-click to drag the view
- Scroll wheel to zoom in/out
Additionally, you can adjust export and preview parameters through the **View Parameters** panel.
In the **Functions** menu, you can reset and synchronize the animation time for all skeletons.
### Exporting Animations
Select **Export** from the **File** menu to export all loaded skeleton animations as PNG frame sequences, based on the current preview settings.
You can view the full duration of each animation in the **Model Parameters** of each skeleton.
:sparkles: v0.12.x New Feature: Support for multi-track animations and multi-skin list management :sparkles:
---
*If you find this project helpful, please give it a :star: and share it with others! :)*
## Installation
Head over to the [Release](https://github.com/ww-rm/SpineViewer/releases) page to download the zip package.
The software requires the dependency framework [.NET Desktop Runtime 8.0.x](https://dotnet.microsoft.com/en-us/download/dotnet/8.0).
Alternatively, you can download the package with the `SelfContained` suffix, which can run independently.
Exporting video formats such as GIF requires that ffmpeg is installed locally and added to your systems PATH. You can [click here to go to the FFmpeg-Windows download page](https://ffmpeg.org/download.html#build-windows) or directly download the latest version [ffmpeg-release-full.7z](https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z).
## Supported Export Formats
| Export Format | Suitable for Scenario |
| ------------ | ------------------------------------------------------------------------------------|
| Single Frame | Supports generating high-definition model snapshots; you can manually adjust the frame. |
| Frame Sequence | Supports png sequence output with transparency and lossless compression. |
| GIF | Ideal for generating preview animations. |
| MP4 | The most common video format with the best compatibility. |
| WebM | Suitable for browser-based playback and supports transparent backgrounds. |
| MKV | For more experimental use. |
| MOV | For more experimental use. |
| Custom Export | In addition to the above presets, you can provide any FFmpeg parameters to meet complex custom needs. |
## Supported Spine Versions
| Version | View & Export | Format Conversion | Version Conversion |
| :------: | :-------------------: | :------------------: | :-----------------: |
| `2.1.x` | :white_check_mark: | | |
| `3.1.x` | | | |
| `3.4.x` | | | |
| `3.5.x` | | | |
| `3.6.x` | :white_check_mark: | | |
| `3.7.x` | :white_check_mark: | | |
| `3.8.x` | :white_check_mark: | :white_check_mark: | |
| `4.1.x` | :white_check_mark: | | |
| `4.2.x` | :white_check_mark: | | |
| `4.3.x` | | | |
More versions are under development :rocket: :rocket: :rocket:
## How to Use
### Importing Skeleton Files
There are three ways to import skeleton files:
- Drag and drop or paste the skeleton file/directory into the model list.
- Batch open skeleton files from the File menu.
- Select a single model to open from the File menu.
### Adjusting the Preview
The model list supports context menus and some shortcuts, and you can multi-select to adjust parameters in bulk.
In addition to using the panel for parameter settings, the preview screen supports several mouse actions:
- Left-click to select and drag models; hold the `Ctrl` key for multi-selection (which is synchronized with the list on the left).
- Right-click to drag the overall view.
- Use the mouse wheel to zoom in and out.
- “Render Selected” mode: in this mode, the preview screen only shows the selected models and the selection state can only be changed from the list on the left.
The buttons below the preview allow you to adjust the timeline, acting as a simple media player.
### Exporting the Preview
Exporting follows the “What You See Is What You Get” principle the preview exactly reflects the output.
There are several key parameters for export:
- Render Selected Only: This option affects both the preview and export. If enabled, only the selected models will be considered during export while ignoring the others.
- Output Folder: This parameter is optional in some cases. If not provided, the output files will be saved in each models own folder; otherwise, all outputs will be saved to the specified folder.
- Single Export: By default, each model is exported separately (i.e., batch operation on the model list). If “Single Export” is selected, all the exported models will be rendered on the same canvas, producing only one output file.
### More Information
For detailed instructions and usage notes, please see the [Wiki](https://github.com/ww-rm/SpineViewer/wiki). If you encounter any issues or bugs, feel free to open an [Issue](https://github.com/ww-rm/SpineViewer/issues).
## Acknowledgements
- [spine-runtimes](https://github.com/EsotericSoftware/spine-runtimes)
- [SFML.Net](https://github.com/SFML/SFML.Net)
- [FFMpegCore](https://github.com/rosenbjerg/FFMpegCore)
---
*If you like this project, please give it a :star: and share it with others!*
[![Stargazers over time](https://starchart.cc/ww-rm/SpineViewer.svg?variant=adaptive)](https://starchart.cc/ww-rm/SpineViewer)

101
README.md
View File

@@ -1,15 +1,21 @@
# [SpineViewer](https://github.com/ww-rm/SpineViewer)
[![Build and Release](https://github.com/ww-rm/SpineViewer/actions/workflows/dotnet-desktop.yml/badge.svg)](https://github.com/ww-rm/SpineViewer/actions/workflows/dotnet-desktop.yml)
[![GitHub Release](https://img.shields.io/github/v/release/ww-rm/SpineViewer?logo=github&logoColor=959da5&label=Release&labelColor=3f4850)](https://github.com/ww-rm/SpineViewer/releases)
[![Downloads](https://img.shields.io/github/downloads/ww-rm/SpineViewer/total?logo=github&logoColor=959da5&label=Downloads&labelColor=3f4850)](https://github.com/ww-rm/SpineViewer/releases)
[中文](README.md) | [English](README.en.md)
一个简单好用的 Spine 文件查看&导出程序.
*所见即所得* 的 Spine 文件查看&导出程序.
![previewer](img/preview.webp)
---
:sparkles: v0.12.x 新增功能: 支持多轨道动画以及多皮肤列表管理 :sparkles:
---
## 安装
前往 [Release](https://github.com/ww-rm/SpineViewer/releases) 界面下载压缩包.
@@ -18,63 +24,82 @@
也可以下载带有 `SelfContained` 后缀的压缩包, 可以独立运行.
## 功能支持
导出 GIF 等视频格式需要在本地安装 ffmpeg 命令行, 并且添加至环境变量, [点击前往 FFmpeg-Windows 下载页面](https://ffmpeg.org/download.html#build-windows), 也可以点这个下载最新版本 [ffmpeg-release-full.7z](https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-full.7z).
| 版本 | 查看&导出 | 格式转换 |
| :---: | :---: | :---: |
| `2.1.x` | :white_check_mark: | |
| `3.1.x` | | |
| `3.4.x` | | |
| `3.5.x` | | |
| `3.6.x` | :white_check_mark: | |
| `3.7.x` | :white_check_mark: | |
| `3.8.x` | :white_check_mark: | :white_check_mark: |
| `4.1.x` | :white_check_mark: | |
| `4.2.x` | :white_check_mark: | |
| `4.3.x` | | |
## 导出格式支持
- 支持文件拖放打开
- 支持自动检测版本
- 支持列表缩略图预览
- 支持多骨骼文件动画预览
- 支持每个骨骼独立参数设置
- 支持动画PNG帧序列导出
- 支持缩放旋转等导出画面设置
- 支持对独立的骨骼文件进行格式转换
- Coming soon...
| 导出格式 | 适用场景 |
| --- | --- |
| 单帧画面 | 支持生成高清模型画面图像, 可手动调节需要的一帧. |
| 帧序列 | 支持 PNG 格式帧序列, 可保留透明通道且无损压缩. |
| GIF/WebP/AVIF | 适合生成预览动图. |
| MP4 | 最常见的视频格式, 兼容性最好. |
| WebM | 适合浏览器在线播放格式, 支持透明背景. |
| MKV/MOV | 适合折腾. |
| 自定义导出 | 除上述预设方案, 支持提供任意 FFmpeg 参数进行导出, 满足自定义复杂需求. |
## Spine 版本支持
| 版本 | 查看&导出 | 格式转换 | 版本转换 |
| :---: | :---: | :---: | :---: |
| `2.1.x` | :white_check_mark: | | |
| `3.1.x` | | | |
| `3.4.x` | | | |
| `3.5.x` | | | |
| `3.6.x` | :white_check_mark: | | |
| `3.7.x` | :white_check_mark: | | |
| `3.8.x` | :white_check_mark: | :white_check_mark: | |
| `4.1.x` | :white_check_mark: | | |
| `4.2.x` | :white_check_mark: | | |
| `4.3.x` | | | |
更多版本正在施工 :rocket: :rocket: :rocket:
## 使用方法
### 骨骼导入
**文件**菜单可以选择**打开**或者**批量打开**进行骨骼文件导入.
有 3 种模式导入骨骼文件:
或者直接把要打开的骨骼文件拖进列表, 这种方式只支持 `.json``.skel` 后缀的文件, 其他的会被忽略.
- 拖放/粘贴需要导入的骨骼文件/目录到模型列表
- 从文件菜单里批量打开骨骼文件
- 从文件菜单选择单个模型打开
### 骨骼调整
### 预览内容调整
在**模型列表**中选择一项或多项, 将会在**模型参数**面板显示可供调节的参数.
模型列表支持右键菜单以及部分快捷键, 并且可以多选进行模型参数的批量调整.
**模型列表**右键菜单可以对列表项进行增删调整, 也可以使用鼠标左键拖动调整顺序.
预览画面除了使用面板进行参数设置外, 支持部分鼠标动作:
### 画面调整
- 左键可以选择和拖拽模型, 按下 `Ctrl` 键可以实现多选, 与左侧列表选择是联动的.
- 右键对整体画面进行拖动.
- 滚轮进行画面缩放.
- 仅渲染选中模式, 在该模式下, 预览画面仅包含被选中的模型, 并且只能通过左侧列表改变选中状态.
**预览画面**支持的鼠标操作:
预览画面下方按钮支持对画面时间进行调整, 可以当作一个简易的播放器.
- 左键可以对骨骼进行拖动
- 右键对画面进行拖动
- 滚轮进行画面缩放
### 预览内容导出
除此之外, 也可以通过**画面参数**面板调节导出和预览时的画面参数.
导出遵循 "所见即所得" 原则, 即实时预览的画面就是你导出的画面.
在**功能**菜单中, 可以重置同步所有骨骼动画时间.
导出有以下几个关键参数:
### 动画导出
- 仅渲染选中. 这个参数不仅影响预览模式, 也影响导出, 如果仅渲染选中, 那么在导出时只有被选中的模型会被考虑, 忽略其他模型.
- 输出文件夹. 这个参数某些时候可选, 当不提供时, 则将输出产物输出到每个模型各自的模型文件夹, 否则输出产物全部输出到提供的输出文件夹.
- 导出单个. 默认是每个模型独立导出, 即对模型列表进行批量操作, 如果选择仅导出单个, 那么被导出的所有模型将在同一个画面上被渲染, 输出产物只有一份.
**文件**菜单中选择**导出**可以将目前加载的所有骨骼动画按照预览时的画面进行PNG帧序列导出.
### 更多
可以在每个骨骼的**模型参数**中查看动画完整时长.
更为详细的使用方法和说明见 [Wiki](https://github.com/ww-rm/SpineViewer/wiki), 有使用上的问题或者 BUG 可以提个 [Issue](https://github.com/ww-rm/SpineViewer/issues).
## Acknowledgements
- [spine-runtimes](https://github.com/EsotericSoftware/spine-runtimes)
- [SFML.Net](https://github.com/SFML/SFML.Net)
- [FFMpegCore](https://github.com/rosenbjerg/FFMpegCore)
---
*如果你觉得这个项目不错请给个 :star:, 并分享给更多人知道! :)*
[![Stargazers over time](https://starchart.cc/ww-rm/SpineViewer.svg?variant=adaptive)](https://starchart.cc/ww-rm/SpineViewer)

View File

@@ -41,8 +41,9 @@ namespace SpineRuntime21 {
public AnimationStateData Data { get { return data; } }
public float TimeScale { get { return timeScale; } set { timeScale = value; } }
public List<TrackEntry> Tracks => tracks;
public delegate void StartEndDelegate(AnimationState state, int trackIndex);
public delegate void StartEndDelegate(AnimationState state, int trackIndex);
public event StartEndDelegate Start;
public event StartEndDelegate End;

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>2.1.25</Version>

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>3.6.53</Version>

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>3.7.94</Version>

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>3.8.99</Version>

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>4.0.64</Version>

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>4.1.54</Version>

View File

@@ -5,7 +5,6 @@
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<TargetFramework>net8.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version>4.2.74</Version>

View File

@@ -0,0 +1,197 @@
namespace SpineViewer.Controls
{
partial class SkelFileListBox
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
tableLayoutPanel1 = new TableLayoutPanel();
flowLayoutPanel1 = new FlowLayoutPanel();
button_AddFolder = new Button();
button_AddFile = new Button();
label_Tip = new Label();
listBox = new ListBox();
contextMenuStrip = new ContextMenuStrip(components);
toolStripMenuItem_SelectAll = new ToolStripMenuItem();
toolStripMenuItem_Paste = new ToolStripMenuItem();
toolStripMenuItem_Remove = new ToolStripMenuItem();
folderBrowserDialog = new FolderBrowserDialog();
openFileDialog_Skel = new OpenFileDialog();
tableLayoutPanel1.SuspendLayout();
flowLayoutPanel1.SuspendLayout();
contextMenuStrip.SuspendLayout();
SuspendLayout();
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(flowLayoutPanel1, 0, 0);
tableLayoutPanel1.Controls.Add(listBox, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(0, 0);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Size = new Size(801, 394);
tableLayoutPanel1.TabIndex = 0;
//
// flowLayoutPanel1
//
flowLayoutPanel1.AutoSize = true;
flowLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowAndShrink;
flowLayoutPanel1.Controls.Add(button_AddFolder);
flowLayoutPanel1.Controls.Add(button_AddFile);
flowLayoutPanel1.Controls.Add(label_Tip);
flowLayoutPanel1.Dock = DockStyle.Fill;
flowLayoutPanel1.Location = new Point(3, 3);
flowLayoutPanel1.Name = "flowLayoutPanel1";
flowLayoutPanel1.Size = new Size(795, 40);
flowLayoutPanel1.TabIndex = 1;
//
// button_AddFolder
//
button_AddFolder.AutoSize = true;
button_AddFolder.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_AddFolder.Location = new Point(3, 3);
button_AddFolder.Name = "button_AddFolder";
button_AddFolder.Size = new Size(122, 34);
button_AddFolder.TabIndex = 0;
button_AddFolder.Text = "添加文件夹...";
button_AddFolder.UseVisualStyleBackColor = true;
button_AddFolder.Click += button_AddFolder_Click;
//
// button_AddFile
//
button_AddFile.AutoSize = true;
button_AddFile.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_AddFile.Location = new Point(131, 3);
button_AddFile.Name = "button_AddFile";
button_AddFile.Size = new Size(104, 34);
button_AddFile.TabIndex = 1;
button_AddFile.Text = "添加文件...";
button_AddFile.UseVisualStyleBackColor = true;
button_AddFile.Click += button_AddFile_Click;
//
// label_Tip
//
label_Tip.Anchor = AnchorStyles.Left;
label_Tip.AutoSize = true;
label_Tip.Location = new Point(241, 8);
label_Tip.Name = "label_Tip";
label_Tip.Size = new Size(139, 24);
label_Tip.TabIndex = 3;
label_Tip.Text = "已添加 0 个文件";
label_Tip.TextAlign = ContentAlignment.MiddleCenter;
//
// listBox
//
listBox.AllowDrop = true;
listBox.ContextMenuStrip = contextMenuStrip;
listBox.Dock = DockStyle.Fill;
listBox.FormattingEnabled = true;
listBox.HorizontalScrollbar = true;
listBox.ItemHeight = 24;
listBox.Location = new Point(3, 49);
listBox.Name = "listBox";
listBox.SelectionMode = SelectionMode.MultiExtended;
listBox.Size = new Size(795, 342);
listBox.TabIndex = 0;
listBox.DragDrop += listBox_DragDrop;
listBox.DragEnter += listBox_DragEnter;
//
// contextMenuStrip
//
contextMenuStrip.ImageScalingSize = new Size(24, 24);
contextMenuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_SelectAll, toolStripMenuItem_Paste, toolStripMenuItem_Remove });
contextMenuStrip.Name = "contextMenuStrip";
contextMenuStrip.Size = new Size(184, 94);
//
// toolStripMenuItem_SelectAll
//
toolStripMenuItem_SelectAll.Name = "toolStripMenuItem_SelectAll";
toolStripMenuItem_SelectAll.ShortcutKeys = Keys.Control | Keys.A;
toolStripMenuItem_SelectAll.Size = new Size(183, 30);
toolStripMenuItem_SelectAll.Text = "全选";
toolStripMenuItem_SelectAll.Click += toolStripMenuItem_SelectAll_Click;
//
// toolStripMenuItem_Paste
//
toolStripMenuItem_Paste.Name = "toolStripMenuItem_Paste";
toolStripMenuItem_Paste.ShortcutKeys = Keys.Control | Keys.V;
toolStripMenuItem_Paste.Size = new Size(183, 30);
toolStripMenuItem_Paste.Text = "粘贴";
toolStripMenuItem_Paste.Click += toolStripMenuItem_Paste_Click;
//
// toolStripMenuItem_Remove
//
toolStripMenuItem_Remove.Name = "toolStripMenuItem_Remove";
toolStripMenuItem_Remove.ShortcutKeys = Keys.Delete;
toolStripMenuItem_Remove.Size = new Size(183, 30);
toolStripMenuItem_Remove.Text = "移除";
toolStripMenuItem_Remove.Click += toolStripMenuItem_Remove_Click;
//
// openFileDialog_Skel
//
openFileDialog_Skel.AddExtension = false;
openFileDialog_Skel.AddToRecent = false;
openFileDialog_Skel.Filter = "skel 文件 (*.skel; *.json)|*.skel;*.json|二进制文件 (*.skel)|*.skel|文本文件 (*.json)|*.json|所有文件 (*.*)|*.*";
openFileDialog_Skel.Multiselect = true;
openFileDialog_Skel.Title = "批量选择skel文件";
//
// SkelFileListBox
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(tableLayoutPanel1);
Name = "SkelFileListBox";
Size = new Size(801, 394);
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
flowLayoutPanel1.ResumeLayout(false);
flowLayoutPanel1.PerformLayout();
contextMenuStrip.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private TableLayoutPanel tableLayoutPanel1;
private ListBox listBox;
private FlowLayoutPanel flowLayoutPanel1;
private Button button_AddFolder;
private Button button_AddFile;
private FolderBrowserDialog folderBrowserDialog;
private Label label_Tip;
private ContextMenuStrip contextMenuStrip;
private OpenFileDialog openFileDialog_Skel;
private ToolStripMenuItem toolStripMenuItem_SelectAll;
private ToolStripMenuItem toolStripMenuItem_Paste;
private ToolStripMenuItem toolStripMenuItem_Remove;
}
}

View File

@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using SpineViewer.Spine;
namespace SpineViewer.Controls
{
public partial class SkelFileListBox : UserControl
{
public SkelFileListBox()
{
InitializeComponent();
Items = listBox.Items;
}
/// <summary>
/// ListBox.Items
/// </summary>
public readonly ListBox.ObjectCollection Items;
/// <summary>
/// 从路径列表添加
/// </summary>
private void AddFromFileDrop(string[] paths)
{
foreach (var path in paths)
{
if (File.Exists(path))
{
if (SpineHelper.CommonSkelSuffix.Contains(Path.GetExtension(path).ToLower()))
listBox.Items.Add(Path.GetFullPath(path));
}
else if (Directory.Exists(path))
{
foreach (var file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
if (SpineHelper.CommonSkelSuffix.Contains(Path.GetExtension(file).ToLower()))
listBox.Items.Add(file);
}
}
}
}
private void button_AddFolder_Click(object sender, EventArgs e)
{
if (folderBrowserDialog.ShowDialog() != DialogResult.OK)
return;
var path = folderBrowserDialog.SelectedPath;
if (Directory.Exists(path))
{
foreach (var file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
if (SpineHelper.CommonSkelSuffix.Contains(Path.GetExtension(file).ToLower()))
listBox.Items.Add(file);
}
}
label_Tip.Text = $"已选择 {listBox.Items.Count} 个文件";
}
private void button_AddFile_Click(object sender, EventArgs e)
{
if (openFileDialog_Skel.ShowDialog() != DialogResult.OK)
return;
foreach (var p in openFileDialog_Skel.FileNames)
listBox.Items.Add(Path.GetFullPath(p));
label_Tip.Text = $"已选择 {listBox.Items.Count} 个文件";
}
private void listBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void listBox_DragDrop(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
return;
AddFromFileDrop((string[])e.Data.GetData(DataFormats.FileDrop));
label_Tip.Text = $"已选择 {listBox.Items.Count} 个文件";
}
private void toolStripMenuItem_SelectAll_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox.Items.Count; i++)
listBox.SelectedIndices.Add(i);
}
private void toolStripMenuItem_Paste_Click(object sender, EventArgs e)
{
if (!Clipboard.ContainsFileDropList())
return;
var fileDropList = Clipboard.GetFileDropList();
var paths = new string[fileDropList.Count];
fileDropList.CopyTo(paths, 0);
AddFromFileDrop(paths);
label_Tip.Text = $"已选择 {listBox.Items.Count} 个文件";
}
private void toolStripMenuItem_Remove_Click(object sender, EventArgs e)
{
var indices = new int[listBox.SelectedIndices.Count];
listBox.SelectedIndices.CopyTo(indices, 0);
for (int i = indices.Length - 1; i >= 0; i--)
listBox.Items.RemoveAt(indices[i]);
label_Tip.Text = $"已选择 {listBox.Items.Count} 个文件";
}
}
}

View File

@@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>556, 18</value>
</metadata>
<metadata name="folderBrowserDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>286, 21</value>
</metadata>
<metadata name="openFileDialog_Skel.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>31, 27</value>
</metadata>
</root>

View File

@@ -44,8 +44,9 @@
toolStripMenuItem_MoveTop = new ToolStripMenuItem();
toolStripMenuItem_MoveBottom = new ToolStripMenuItem();
toolStripSeparator3 = new ToolStripSeparator();
toolStripMenuItem_SelectAll = new ToolStripMenuItem();
toolStripMenuItem_CopyPreview = new ToolStripMenuItem();
toolStripMenuItem_AddFromClipboard = new ToolStripMenuItem();
toolStripMenuItem_SelectAll = new ToolStripMenuItem();
toolStripSeparator4 = new ToolStripSeparator();
toolStripMenuItem_ChangeView = new ToolStripMenuItem();
toolStripMenuItem_LargeIconView = new ToolStripMenuItem();
@@ -53,7 +54,13 @@
toolStripMenuItem_DetailsView = new ToolStripMenuItem();
imageList_LargeIcon = new ImageList(components);
imageList_SmallIcon = new ImageList(components);
timer_SelectedIndexChangedDebounce = new System.Windows.Forms.Timer(components);
statusStrip = new StatusStrip();
toolStripStatusLabel_CountInfo = new ToolStripStatusLabel();
tableLayoutPanel = new TableLayoutPanel();
contextMenuStrip.SuspendLayout();
statusStrip.SuspendLayout();
tableLayoutPanel.SuspendLayout();
SuspendLayout();
//
// listView
@@ -67,9 +74,10 @@
listView.GridLines = true;
listView.LargeImageList = imageList_LargeIcon;
listView.Location = new Point(0, 0);
listView.Margin = new Padding(0);
listView.Name = "listView";
listView.ShowItemToolTips = true;
listView.Size = new Size(336, 445);
listView.Size = new Size(336, 414);
listView.SmallImageList = imageList_SmallIcon;
listView.TabIndex = 1;
listView.UseCompatibleStateImageBehavior = false;
@@ -83,14 +91,14 @@
// columnHeader_Name
//
columnHeader_Name.Text = "名称";
columnHeader_Name.Width = 220;
columnHeader_Name.Width = 300;
//
// contextMenuStrip
//
contextMenuStrip.ImageScalingSize = new Size(24, 24);
contextMenuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_Add, toolStripMenuItem_Insert, toolStripMenuItem_Remove, toolStripSeparator1, toolStripMenuItem_BatchAdd, toolStripMenuItem_RemoveAll, toolStripSeparator2, toolStripMenuItem_MoveUp, toolStripMenuItem_MoveDown, toolStripMenuItem_MoveTop, toolStripMenuItem_MoveBottom, toolStripSeparator3, toolStripMenuItem_SelectAll, toolStripMenuItem_CopyPreview, toolStripSeparator4, toolStripMenuItem_ChangeView });
contextMenuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_Add, toolStripMenuItem_Insert, toolStripMenuItem_Remove, toolStripSeparator1, toolStripMenuItem_BatchAdd, toolStripMenuItem_RemoveAll, toolStripSeparator2, toolStripMenuItem_MoveUp, toolStripMenuItem_MoveDown, toolStripMenuItem_MoveTop, toolStripMenuItem_MoveBottom, toolStripSeparator3, toolStripMenuItem_CopyPreview, toolStripMenuItem_AddFromClipboard, toolStripMenuItem_SelectAll, toolStripSeparator4, toolStripMenuItem_ChangeView });
contextMenuStrip.Name = "contextMenuStrip";
contextMenuStrip.Size = new Size(329, 388);
contextMenuStrip.Size = new Size(329, 418);
contextMenuStrip.Closed += contextMenuStrip_Closed;
contextMenuStrip.Opening += contextMenuStrip_Opening;
//
@@ -177,14 +185,6 @@
toolStripSeparator3.Name = "toolStripSeparator3";
toolStripSeparator3.Size = new Size(325, 6);
//
// toolStripMenuItem_SelectAll
//
toolStripMenuItem_SelectAll.Name = "toolStripMenuItem_SelectAll";
toolStripMenuItem_SelectAll.ShortcutKeys = Keys.Control | Keys.A;
toolStripMenuItem_SelectAll.Size = new Size(328, 30);
toolStripMenuItem_SelectAll.Text = "全选";
toolStripMenuItem_SelectAll.Click += toolStripMenuItem_SelectAll_Click;
//
// toolStripMenuItem_CopyPreview
//
toolStripMenuItem_CopyPreview.Name = "toolStripMenuItem_CopyPreview";
@@ -193,6 +193,22 @@
toolStripMenuItem_CopyPreview.Text = "复制预览图 (256x256)";
toolStripMenuItem_CopyPreview.Click += toolStripMenuItem_CopyPreview_Click;
//
// toolStripMenuItem_AddFromClipboard
//
toolStripMenuItem_AddFromClipboard.Name = "toolStripMenuItem_AddFromClipboard";
toolStripMenuItem_AddFromClipboard.ShortcutKeys = Keys.Control | Keys.V;
toolStripMenuItem_AddFromClipboard.Size = new Size(328, 30);
toolStripMenuItem_AddFromClipboard.Text = "从剪贴板添加";
toolStripMenuItem_AddFromClipboard.Click += toolStripMenuItem_AddFromClipboard_Click;
//
// toolStripMenuItem_SelectAll
//
toolStripMenuItem_SelectAll.Name = "toolStripMenuItem_SelectAll";
toolStripMenuItem_SelectAll.ShortcutKeys = Keys.Control | Keys.A;
toolStripMenuItem_SelectAll.Size = new Size(328, 30);
toolStripMenuItem_SelectAll.Text = "全选";
toolStripMenuItem_SelectAll.Click += toolStripMenuItem_SelectAll_Click;
//
// toolStripSeparator4
//
toolStripSeparator4.Name = "toolStripSeparator4";
@@ -241,14 +257,56 @@
imageList_SmallIcon.ImageSize = new Size(48, 48);
imageList_SmallIcon.TransparentColor = Color.Transparent;
//
// timer_SelectedIndexChangedDebounce
//
timer_SelectedIndexChangedDebounce.Interval = 30;
timer_SelectedIndexChangedDebounce.Tick += timer_SelectedIndexChangedDebounce_Tick;
//
// statusStrip
//
statusStrip.Dock = DockStyle.Fill;
statusStrip.ImageScalingSize = new Size(24, 24);
statusStrip.Items.AddRange(new ToolStripItem[] { toolStripStatusLabel_CountInfo });
statusStrip.Location = new Point(0, 414);
statusStrip.Name = "statusStrip";
statusStrip.Size = new Size(336, 31);
statusStrip.SizingGrip = false;
statusStrip.TabIndex = 2;
statusStrip.Text = "statusStrip1";
//
// toolStripStatusLabel_CountInfo
//
toolStripStatusLabel_CountInfo.Name = "toolStripStatusLabel_CountInfo";
toolStripStatusLabel_CountInfo.Size = new Size(178, 24);
toolStripStatusLabel_CountInfo.Text = "已选择 0 项,共 0 项";
//
// tableLayoutPanel
//
tableLayoutPanel.ColumnCount = 1;
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel.Controls.Add(listView, 0, 0);
tableLayoutPanel.Controls.Add(statusStrip, 0, 1);
tableLayoutPanel.Dock = DockStyle.Fill;
tableLayoutPanel.Location = new Point(0, 0);
tableLayoutPanel.Name = "tableLayoutPanel";
tableLayoutPanel.RowCount = 2;
tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
tableLayoutPanel.RowStyles.Add(new RowStyle());
tableLayoutPanel.Size = new Size(336, 445);
tableLayoutPanel.TabIndex = 3;
//
// SpineListView
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(listView);
Controls.Add(tableLayoutPanel);
Name = "SpineListView";
Size = new Size(336, 445);
contextMenuStrip.ResumeLayout(false);
statusStrip.ResumeLayout(false);
statusStrip.PerformLayout();
tableLayoutPanel.ResumeLayout(false);
tableLayoutPanel.PerformLayout();
ResumeLayout(false);
}
@@ -277,5 +335,10 @@
private ToolStripMenuItem toolStripMenuItem_CopyPreview;
private ToolStripMenuItem toolStripMenuItem_SelectAll;
private ToolStripSeparator toolStripSeparator4;
private ToolStripMenuItem toolStripMenuItem_AddFromClipboard;
private System.Windows.Forms.Timer timer_SelectedIndexChangedDebounce;
private StatusStrip statusStrip;
private ToolStripStatusLabel toolStripStatusLabel_CountInfo;
private TableLayoutPanel tableLayoutPanel;
}
}

View File

@@ -12,24 +12,35 @@ using SpineViewer.Spine;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Specialized;
using NLog;
using SpineViewer.Extensions;
using SpineViewer.PropertyGridWrappers.Spine;
using SpineViewer.Utilities;
namespace SpineViewer.Controls
{
public partial class SpineListView : UserControl
{
[Category("自定义"), Description("用于显示骨骼属性的属性页")]
public PropertyGrid? PropertyGrid { get; set; }
/// <summary>
/// 日志器
/// </summary>
private readonly Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 获取数组快照, 访问时必须使用 lock 语句锁定对象本身
/// Spine 列表只读视图, 访问时必须使用 lock 语句锁定视图本身
/// </summary>
public readonly ReadOnlyCollection<Spine.Spine> Spines;
/// <summary>
/// Spine 列表, 访问时必须使用 lock 语句锁定 Spines
/// Spine 列表, 访问时必须使用 lock 语句锁定只读视图 Spines
/// </summary>
private readonly List<Spine.Spine> spines = [];
/// <summary>
/// 用于属性页显示模型参数的包装类
/// </summary>
private readonly Dictionary<string, SpineWrapper> spinePropertyWrappers = [];
public SpineListView()
{
InitializeComponent();
@@ -37,16 +48,63 @@ namespace SpineViewer.Controls
}
/// <summary>
/// listView.SelectedIndices
/// 显示骨骼信息的属性面板
/// </summary>
public ListView.SelectedIndexCollection SelectedIndices { get => listView.SelectedIndices; }
[Category("自定义"), Description("用于显示模型属性的组合属性页")]
public SpinePropertyGrid? SpinePropertyGrid { get; set; }
/// <summary>
/// 弹出添加对话框
/// 选中的索引
/// </summary>
public void Add()
public ListView.SelectedIndexCollection SelectedIndices => listView.SelectedIndices;
/// <summary>
/// 弹出添加对话框在末尾添加
/// </summary>
public void Add() => Insert();
/// <summary>
/// 弹出添加对话框在指定位置之前插入一项, 如果索引无效则在末尾添加
/// </summary>
private void Insert(int index = -1)
{
Insert();
var dialog = new Dialogs.OpenSpineDialog();
if (dialog.ShowDialog() != DialogResult.OK) return;
Insert(dialog.Result, index);
}
/// <summary>
/// 从结果在指定位置之前插入一项, 如果索引无效则在末尾添加
/// </summary>
private void Insert(Dialogs.OpenSpineDialogResult result, int index = -1)
{
try
{
var spine = Spine.Spine.New(result.Version, result.SkelPath, result.AtlasPath);
// 如果索引无效则在末尾添加
if (index < 0 || index > listView.Items.Count)
index = listView.Items.Count;
// 锁定外部的读操作
lock (Spines) { spines.Insert(index, spine); }
spinePropertyWrappers[spine.ID] = new(spine);
listView.SmallImageList.Images.Add(spine.ID, spine.Preview);
listView.LargeImageList.Images.Add(spine.ID, spine.Preview);
listView.Items.Insert(index, new ListViewItem(spine.Name, spine.ID) { ToolTipText = spine.SkelPath });
// 选中新增项
listView.SelectedIndices.Clear();
listView.SelectedIndices.Add(index);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to load {} {}", result.SkelPath, result.AtlasPath);
MessagePopup.Error(ex.ToString(), "骨骼加载失败");
}
logger.LogCurrentProcessMemoryUsage();
}
/// <summary>
@@ -55,67 +113,170 @@ namespace SpineViewer.Controls
public void BatchAdd()
{
var openDialog = new Dialogs.BatchOpenSpineDialog();
if (openDialog.ShowDialog() != DialogResult.OK)
return;
if (openDialog.ShowDialog() != DialogResult.OK) return;
BatchAdd(openDialog.Result);
}
/// <summary>
/// 从结果批量添加
/// </summary>
private void BatchAdd(Dialogs.BatchOpenSpineDialogResult result)
{
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += BatchAdd_Work;
progressDialog.RunWorkerAsync(openDialog.Result);
progressDialog.RunWorkerAsync(result);
progressDialog.ShowDialog();
}
/// <summary>
/// 弹出对话框导出列表预览图
/// 批量添加后台任务
/// </summary>
public void ExportPreviews()
private void BatchAdd_Work(object? sender, DoWorkEventArgs e)
{
lock (Spines)
var worker = sender as BackgroundWorker;
var arguments = e.Argument as Dialogs.BatchOpenSpineDialogResult;
var skelPaths = arguments.SkelPaths;
var version = arguments.Version;
int totalCount = skelPaths.Length;
int success = 0;
int error = 0;
worker.ReportProgress(0, $"已处理 0/{totalCount}");
for (int i = 0; i < totalCount; i++)
{
if (spines.Count <= 0)
if (worker.CancellationPending)
{
MessageBox.Show("请至少打开一个骨骼文件", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
e.Cancel = true;
break;
}
var skelPath = skelPaths[i];
try
{
var spine = Spine.Spine.New(version, skelPath);
var preview = spine.Preview;
lock (Spines) { spines.Add(spine); }
spinePropertyWrappers[spine.ID] = new(spine);
listView.Invoke(() =>
{
listView.SmallImageList.Images.Add(spine.ID, preview);
listView.LargeImageList.Images.Add(spine.ID, preview);
listView.Items.Add(new ListViewItem(spine.Name, spine.ID) { ToolTipText = spine.SkelPath });
});
success++;
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to load {}", skelPath);
error++;
}
worker.ReportProgress((int)((i + 1) * 100.0) / totalCount, $"已处理 {i + 1}/{totalCount}");
}
// 选中最后一项
listView.Invoke(() =>
{
if (listView.Items.Count > 0)
{
listView.SelectedIndices.Clear();
listView.SelectedIndices.Add(listView.Items.Count - 1);
}
});
if (error > 0)
logger.Warn("Batch load {} successfully, {} failed", success, error);
else
logger.Info("{} skel loaded successfully", success);
logger.LogCurrentProcessMemoryUsage();
}
/// <summary>
/// 从拖放/复制的路径列表添加
/// </summary>
private void AddFromFileDrop(IEnumerable<string> paths)
{
List<string> validPaths = [];
foreach (var path in paths)
{
if (File.Exists(path))
{
if (SpineHelper.CommonSkelSuffix.Contains(Path.GetExtension(path).ToLower()))
validPaths.Add(path);
}
else if (Directory.Exists(path))
{
foreach (var file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
if (SpineHelper.CommonSkelSuffix.Contains(Path.GetExtension(file).ToLower()))
validPaths.Add(file);
}
}
}
var saveDialog = new Dialogs.ExportPreviewDialog();
if (saveDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += ExportPreview_Work;
progressDialog.RunWorkerAsync(saveDialog);
progressDialog.ShowDialog();
if (validPaths.Count > 1)
{
if (validPaths.Count > 100)
{
if (MessagePopup.Quest($"共发现 {validPaths.Count} 个可加载骨骼,数量较多,是否一次性全部加载?") == DialogResult.Cancel)
return;
}
BatchAdd(new Dialogs.BatchOpenSpineDialogResult(SpineVersion.Auto, validPaths.ToArray()));
}
else if (validPaths.Count > 0)
{
Insert(new Dialogs.OpenSpineDialogResult(SpineVersion.Auto, validPaths[0]));
}
}
private void listView_SelectedIndexChanged(object sender, EventArgs e)
{
if (PropertyGrid is not null)
timer_SelectedIndexChangedDebounce.Stop();
timer_SelectedIndexChangedDebounce.Start();
}
private void timer_SelectedIndexChangedDebounce_Tick(object sender, EventArgs e)
{
timer_SelectedIndexChangedDebounce.Stop();
_listView_SelectedIndexChanged(listView, EventArgs.Empty);
}
private void _listView_SelectedIndexChanged(object sender, EventArgs e)
{
lock (Spines)
{
lock (Spines)
if (SpinePropertyGrid is not null)
{
if (listView.SelectedIndices.Count <= 0)
PropertyGrid.SelectedObject = null;
SpinePropertyGrid.SelectedSpines = null;
else if (listView.SelectedIndices.Count <= 1)
PropertyGrid.SelectedObject = spines[listView.SelectedIndices[0]];
SpinePropertyGrid.SelectedSpines = [spinePropertyWrappers[spines[listView.SelectedIndices[0]].ID]];
else
PropertyGrid.SelectedObjects = listView.SelectedIndices.Cast<int>().Select(index => spines[index]).ToArray();
// 标记选中的 Spine
for (int i = 0; i < spines.Count; i++)
spines[i].IsSelected = listView.SelectedIndices.Contains(i);
SpinePropertyGrid.SelectedSpines = listView.SelectedIndices.Cast<int>().Select(index => spinePropertyWrappers[spines[index].ID]).ToArray();
}
// 标记选中的 Spine
for (int i = 0; i < spines.Count; i++)
spines[i].IsSelected = listView.SelectedIndices.Contains(i);
}
// BUG: 图标显示的时候没法自动刷新顺序, 只能切换视图刷新, 不知道什么原理
listView.BeginUpdate();
var tmp = listView.View;
listView.View = View.List;
listView.View = tmp;
listView.EndUpdate();
// XXX: 图标显示的时候没法自动刷新顺序, 只能切换视图刷新, 不知道什么原理
if (listView.View == View.LargeIcon)
{
listView.BeginUpdate();
listView.View = View.List;
listView.View = View.LargeIcon;
listView.EndUpdate();
}
if (listView.SelectedItems.Count > 0)
listView.SelectedItems[0].EnsureVisible();
toolStripStatusLabel_CountInfo.Text = $"已选择 {listView.SelectedItems.Count} 项,共 {listView.Items.Count} 项";
}
private void listView_ItemDrag(object sender, ItemDragEventArgs e)
@@ -136,7 +297,7 @@ namespace SpineViewer.Controls
private void listView_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Serializable))
{
{
// 获取鼠标位置并确定目标索引
var point = listView.PointToClient(new(e.X, e.Y));
var targetItem = listView.GetItemAt(point.X, point.Y);
@@ -195,23 +356,7 @@ namespace SpineViewer.Controls
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var validPaths = ((string[])e.Data.GetData(DataFormats.FileDrop)).Where(
path => File.Exists(path) &&
(Path.GetExtension(path).Equals(".skel", StringComparison.OrdinalIgnoreCase) ||
Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase))
).ToArray();
if (validPaths.Length > 1)
{
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += BatchAdd_Work;
progressDialog.RunWorkerAsync(new Dialogs.BatchOpenSpineDialogResult(Spine.Version.Auto, validPaths));
progressDialog.ShowDialog();
}
else if (validPaths.Length > 0)
{
Insert(new Dialogs.OpenSpineDialogResult(Spine.Version.Auto, validPaths[0]));
}
AddFromFileDrop((string[])e.Data.GetData(DataFormats.FileDrop));
}
}
@@ -227,6 +372,7 @@ namespace SpineViewer.Controls
toolStripMenuItem_MoveDown.Enabled = selectedCount == 1 && selectedIndices[0] != itemsCount - 1;
toolStripMenuItem_MoveBottom.Enabled = selectedCount == 1 && selectedIndices[0] != itemsCount - 1;
toolStripMenuItem_RemoveAll.Enabled = itemsCount > 0;
toolStripMenuItem_CopyPreview.Enabled = selectedCount > 0;
// 视图选项
toolStripMenuItem_LargeIconView.Checked = listView.View == View.LargeIcon;
@@ -265,21 +411,24 @@ namespace SpineViewer.Controls
if (listView.SelectedIndices.Count > 1)
{
if (MessageBox.Show($"确定移除所选 {listView.SelectedIndices.Count} 项吗?", "操作确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
if (MessagePopup.Quest($"确定移除所选 {listView.SelectedIndices.Count} 项吗?") != DialogResult.OK)
return;
}
foreach (var i in listView.SelectedIndices.Cast<int>().OrderByDescending(x => x))
lock (Spines)
{
lock (Spines)
listView.BeginUpdate();
foreach (var i in listView.SelectedIndices.Cast<int>().OrderByDescending(x => x))
{
listView.Items.RemoveAt(i);
var spine = spines[i];
spines.RemoveAt(i);
spinePropertyWrappers.Remove(spine.ID);
listView.SmallImageList.Images.RemoveByKey(spine.ID);
listView.LargeImageList.Images.RemoveByKey(spine.ID);
spine.Dispose();
}
listView.Items.RemoveAt(i);
listView.EndUpdate();
}
}
@@ -347,12 +496,9 @@ namespace SpineViewer.Controls
{
lock (Spines)
{
lock (Spines)
{
var spine = spines[index];
spines.RemoveAt(index);
spines.Add(spine);
}
var spine = spines[index];
spines.RemoveAt(index);
spines.Add(spine);
}
var item = listView.Items[index];
listView.Items.RemoveAt(index);
@@ -365,20 +511,52 @@ namespace SpineViewer.Controls
if (listView.Items.Count <= 0)
return;
if (MessageBox.Show($"确认移除所有 {listView.Items.Count} 项吗?", "操作确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
if (MessagePopup.Quest($"确认移除所有 {listView.Items.Count} 项吗?") != DialogResult.OK)
return;
listView.Items.Clear();
lock (Spines)
{
foreach (var spine in spines)
spine.Dispose();
foreach (var spine in spines) spine.Dispose();
spines.Clear();
spinePropertyWrappers.Clear();
listView.SmallImageList.Images.Clear();
listView.LargeImageList.Images.Clear();
}
listView.Items.Clear();
if (PropertyGrid is not null)
PropertyGrid.SelectedObject = null;
if (SpinePropertyGrid is not null)
SpinePropertyGrid.SelectedSpines = null;
}
private void toolStripMenuItem_CopyPreview_Click(object sender, EventArgs e)
{
var fileDropList = new StringCollection();
var tempDir = Path.Combine(Path.GetTempPath(), Process.GetCurrentProcess().ProcessName);
Directory.CreateDirectory(tempDir);
lock (Spines)
{
foreach (int i in listView.SelectedIndices)
{
var a = Process.GetCurrentProcess();
var spine = spines[i];
var path = Path.Combine(tempDir, $"{spine.ID}.png");
spine.Preview.Save(path);
fileDropList.Add(path);
}
}
if (fileDropList.Count > 0)
Clipboard.SetFileDropList(fileDropList);
}
private void toolStripMenuItem_AddFromClipboard_Click(object sender, EventArgs e)
{
if (Clipboard.ContainsFileDropList())
{
var fileDropList = Clipboard.GetFileDropList();
var paths = new string[fileDropList.Count];
fileDropList.CopyTo(paths, 0);
AddFromFileDrop(paths);
}
}
private void toolStripMenuItem_SelectAll_Click(object sender, EventArgs e)
@@ -389,26 +567,6 @@ namespace SpineViewer.Controls
listView.EndUpdate();
}
private void toolStripMenuItem_CopyPreview_Click(object sender, EventArgs e)
{
var fileDropList = new StringCollection();
lock (Spines)
{
foreach (int i in listView.SelectedIndices)
{
var spine = spines[i];
var image = spine.Preview;
var path = Path.Combine(Program.TempDir, $"{spine.ID}.png");
using (var clone = new Bitmap(image))
clone.Save(path);
fileDropList.Add(path);
}
}
if (fileDropList.Count > 0)
Clipboard.SetFileDropList(fileDropList);
}
private void toolStripMenuItem_LargeIconView_Click(object sender, EventArgs e)
{
listView.View = View.LargeIcon;
@@ -423,160 +581,10 @@ namespace SpineViewer.Controls
{
listView.View = View.Details;
}
}
/// <summary>
/// 弹出添加对话框在指定位置之前插入一项
/// </summary>
private void Insert(int index = -1)
{
var dialog = new Dialogs.OpenSpineDialog();
if (dialog.ShowDialog() != DialogResult.OK)
return;
public class DefaultSpineConfig
{
Insert(dialog.Result, index);
}
private void Insert(Dialogs.OpenSpineDialogResult result, int index = -1)
{
try
{
var spine = Spine.Spine.New(result.Version, result.SkelPath, result.AtlasPath);
// 如果索引无效则在末尾添加
if (index < 0 || index > listView.Items.Count)
index = listView.Items.Count;
// 锁定外部的读操作
lock (Spines)
{
spines.Insert(index, spine);
listView.SmallImageList.Images.Add(spine.ID, spine.Preview);
listView.LargeImageList.Images.Add(spine.ID, spine.Preview);
}
listView.Items.Insert(index, new ListViewItem(spine.Name, spine.ID) { ToolTipText = spine.SkelPath });
// 选中新增项
listView.SelectedIndices.Clear();
listView.SelectedIndices.Add(index);
}
catch (Exception ex)
{
Program.Logger.Error(ex.ToString());
Program.Logger.Error("Failed to load {} {}", result.SkelPath, result.AtlasPath);
MessageBox.Show(ex.ToString(), "骨骼加载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Program.Logger.Info($"Current memory usage: {Program.Process.WorkingSet64 / 1024.0 / 1024.0:F2} MB");
}
private void BatchAdd_Work(object? sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
var arguments = e.Argument as Dialogs.BatchOpenSpineDialogResult;
var skelPaths = arguments.SkelPaths;
var version = arguments.Version;
int totalCount = skelPaths.Length;
int success = 0;
int error = 0;
worker.ReportProgress(0, $"已处理 0/{totalCount}");
for (int i = 0; i < totalCount; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
var skelPath = skelPaths[i];
try
{
var spine = Spine.Spine.New(version, skelPath);
var preview = spine.Preview;
lock (Spines) { spines.Add(spine); }
listView.Invoke(() =>
{
listView.SmallImageList.Images.Add(spine.ID, preview);
listView.LargeImageList.Images.Add(spine.ID, preview);
listView.Items.Add(new ListViewItem(spine.Name, spine.ID) { ToolTipText = spine.SkelPath });
});
success++;
}
catch (Exception ex)
{
Program.Logger.Error(ex.ToString());
Program.Logger.Error("Failed to load {}", skelPath);
error++;
}
worker.ReportProgress((int)((i + 1) * 100.0) / totalCount, $"已处理 {i + 1}/{totalCount}");
}
if (error > 0)
{
Program.Logger.Warn("Batch load {} successfully, {} failed", success, error);
}
else
{
Program.Logger.Info("{} skel loaded successfully", success);
}
Program.Logger.Info($"Current memory usage: {Program.Process.WorkingSet64 / 1024.0 / 1024.0:F2} MB");
}
private void ExportPreview_Work(object? sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
var arguments = e.Argument as Dialogs.ExportPreviewDialog;
var outputDir = arguments.OutputDir;
var width = arguments.PreviewWidth;
var height = arguments.PreviewHeight;
int success = 0;
int error = 0;
lock (Spines)
{
int totalCount = spines.Count;
worker.ReportProgress(0, $"已处理 0/{totalCount}");
for (int i = 0; i < totalCount; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
var spine = spines[i];
try
{
var preview = spine.GetPreview(width, height);
var savePath = Path.Combine(outputDir, $"{spine.Name}.png");
preview.SaveToFile(savePath);
success++;
}
catch (Exception ex)
{
Program.Logger.Error(ex.ToString());
Program.Logger.Error("Failed to save preview {}", spine.SkelPath);
error++;
}
worker.ReportProgress((int)((i + 1) * 100.0) / totalCount, $"已处理 {i + 1}/{totalCount}");
}
}
if (error > 0)
{
Program.Logger.Warn("Preview save {} successfully, {} failed", success, error);
}
else
{
Program.Logger.Info("{} preview saved successfully", success);
}
Program.Logger.Info($"Current memory usage: {Program.Process.WorkingSet64 / 1024.0 / 1024.0:F2} MB");
}
}
}

View File

@@ -126,4 +126,10 @@
<metadata name="imageList_SmallIcon.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>252, 19</value>
</metadata>
<metadata name="timer_SelectedIndexChangedDebounce.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>771, 24</value>
</metadata>
<metadata name="statusStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>1176, 24</value>
</metadata>
</root>

View File

@@ -28,13 +28,28 @@
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SpinePreviewer));
panel = new Panel();
tableLayoutPanel1 = new TableLayoutPanel();
panel_Container = new Panel();
flowLayoutPanel1 = new FlowLayoutPanel();
button_Stop = new Button();
imageList = new ImageList(components);
button_Restart = new Button();
button_Start = new Button();
button_ForwardStep = new Button();
button_ForwardFast = new Button();
toolTip = new ToolTip(components);
tableLayoutPanel1.SuspendLayout();
panel_Container.SuspendLayout();
flowLayoutPanel1.SuspendLayout();
SuspendLayout();
//
// panel
//
panel.BackColor = SystemColors.ControlDarkDark;
panel.Location = new Point(160, 160);
panel.Location = new Point(157, 136);
panel.Margin = new Padding(0);
panel.Name = "panel";
panel.Size = new Size(320, 320);
@@ -44,20 +59,165 @@
panel.MouseUp += panel_MouseUp;
panel.MouseWheel += panel_MouseWheel;
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(panel_Container, 0, 0);
tableLayoutPanel1.Controls.Add(flowLayoutPanel1, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(0, 0);
tableLayoutPanel1.Margin = new Padding(0);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Size = new Size(641, 636);
tableLayoutPanel1.TabIndex = 2;
//
// panel_Container
//
panel_Container.BackColor = SystemColors.ControlDark;
panel_Container.Controls.Add(panel);
panel_Container.Dock = DockStyle.Fill;
panel_Container.Location = new Point(0, 0);
panel_Container.Margin = new Padding(0);
panel_Container.Name = "panel_Container";
panel_Container.Size = new Size(641, 594);
panel_Container.TabIndex = 0;
//
// flowLayoutPanel1
//
flowLayoutPanel1.Anchor = AnchorStyles.None;
flowLayoutPanel1.AutoSize = true;
flowLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowAndShrink;
flowLayoutPanel1.Controls.Add(button_Stop);
flowLayoutPanel1.Controls.Add(button_Restart);
flowLayoutPanel1.Controls.Add(button_Start);
flowLayoutPanel1.Controls.Add(button_ForwardStep);
flowLayoutPanel1.Controls.Add(button_ForwardFast);
flowLayoutPanel1.Location = new Point(138, 594);
flowLayoutPanel1.Margin = new Padding(0);
flowLayoutPanel1.Name = "flowLayoutPanel1";
flowLayoutPanel1.Size = new Size(365, 42);
flowLayoutPanel1.TabIndex = 1;
//
// button_Stop
//
button_Stop.AutoSize = true;
button_Stop.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_Stop.ImageKey = "stop";
button_Stop.ImageList = imageList;
button_Stop.Location = new Point(3, 3);
button_Stop.Name = "button_Stop";
button_Stop.Padding = new Padding(15, 3, 15, 3);
button_Stop.Size = new Size(67, 36);
button_Stop.TabIndex = 0;
toolTip.SetToolTip(button_Stop, "停止播放并重置时间到初始");
button_Stop.UseVisualStyleBackColor = true;
button_Stop.Click += button_Stop_Click;
//
// imageList
//
imageList.ColorDepth = ColorDepth.Depth32Bit;
imageList.ImageStream = (ImageListStreamer)resources.GetObject("imageList.ImageStream");
imageList.TransparentColor = Color.Transparent;
imageList.Images.SetKeyName(0, "stop");
imageList.Images.SetKeyName(1, "restart");
imageList.Images.SetKeyName(2, "start");
imageList.Images.SetKeyName(3, "pause");
imageList.Images.SetKeyName(4, "forward-step");
imageList.Images.SetKeyName(5, "forward-fast");
//
// button_Restart
//
button_Restart.AutoSize = true;
button_Restart.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_Restart.ImageKey = "restart";
button_Restart.ImageList = imageList;
button_Restart.Location = new Point(76, 3);
button_Restart.Name = "button_Restart";
button_Restart.Padding = new Padding(15, 3, 15, 3);
button_Restart.Size = new Size(67, 36);
button_Restart.TabIndex = 1;
toolTip.SetToolTip(button_Restart, "从头开始播放");
button_Restart.UseVisualStyleBackColor = true;
button_Restart.Click += button_Restart_Click;
//
// button_Start
//
button_Start.AutoSize = true;
button_Start.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_Start.BackgroundImageLayout = ImageLayout.Center;
button_Start.ImageKey = "pause";
button_Start.ImageList = imageList;
button_Start.Location = new Point(149, 3);
button_Start.Name = "button_Start";
button_Start.Padding = new Padding(15, 3, 15, 3);
button_Start.Size = new Size(67, 36);
button_Start.TabIndex = 2;
toolTip.SetToolTip(button_Start, "开始/暂停");
button_Start.UseVisualStyleBackColor = true;
button_Start.Click += button_Start_Click;
//
// button_ForwardStep
//
button_ForwardStep.AutoSize = true;
button_ForwardStep.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_ForwardStep.ImageKey = "forward-step";
button_ForwardStep.ImageList = imageList;
button_ForwardStep.Location = new Point(222, 3);
button_ForwardStep.Name = "button_ForwardStep";
button_ForwardStep.Padding = new Padding(15, 3, 15, 3);
button_ForwardStep.Size = new Size(67, 36);
button_ForwardStep.TabIndex = 3;
toolTip.SetToolTip(button_ForwardStep, "快进 1 帧");
button_ForwardStep.UseVisualStyleBackColor = true;
button_ForwardStep.Click += button_ForwardStep_Click;
//
// button_ForwardFast
//
button_ForwardFast.AutoSize = true;
button_ForwardFast.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_ForwardFast.ImageKey = "forward-fast";
button_ForwardFast.ImageList = imageList;
button_ForwardFast.Location = new Point(295, 3);
button_ForwardFast.Name = "button_ForwardFast";
button_ForwardFast.Padding = new Padding(15, 3, 15, 3);
button_ForwardFast.Size = new Size(67, 36);
button_ForwardFast.TabIndex = 4;
toolTip.SetToolTip(button_ForwardFast, "快进 10 帧");
button_ForwardFast.UseVisualStyleBackColor = true;
button_ForwardFast.Click += button_ForwardFast_Click;
//
// SpinePreviewer
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = SystemColors.ControlDark;
Controls.Add(panel);
Controls.Add(tableLayoutPanel1);
Name = "SpinePreviewer";
Size = new Size(640, 640);
Size = new Size(641, 636);
SizeChanged += SpinePreviewer_SizeChanged;
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
panel_Container.ResumeLayout(false);
flowLayoutPanel1.ResumeLayout(false);
flowLayoutPanel1.PerformLayout();
ResumeLayout(false);
}
#endregion
private Panel panel;
private TableLayoutPanel tableLayoutPanel1;
private Panel panel_Container;
private FlowLayoutPanel flowLayoutPanel1;
private Button button_Stop;
private Button button_Start;
private ImageList imageList;
private ToolTip toolTip;
private Button button_ForwardStep;
private Button button_ForwardFast;
private Button button_Restart;
}
}

View File

@@ -9,51 +9,40 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Policy;
using System.Diagnostics;
using NLog.Targets;
using NLog;
using SpineViewer.Utilities;
namespace SpineViewer.Controls
{
public partial class SpinePreviewer : UserControl
{
/// <summary>
/// 包装类, 用于 PropertyGrid 显示
/// 日志器
/// </summary>
private class PreviewerProperty
private readonly Logger logger = LogManager.GetCurrentClassLogger();
public SpinePreviewer()
{
private readonly SpinePreviewer previewer;
InitializeComponent();
RenderWindow = new(panel.Handle);
RenderWindow.SetActive(false);
public PreviewerProperty(SpinePreviewer previewer) { this.previewer = previewer; }
[TypeConverter(typeof(SizeConverter))]
[Category("导出"), DisplayName("分辨率")]
public Size Resolution { get => previewer.Resolution; set => previewer.Resolution = value; }
[TypeConverter(typeof(PointFConverter))]
[Category("导出"), DisplayName("画面中心点")]
public PointF Center { get => previewer.Center; set => previewer.Center = value; }
[Category("导出"), DisplayName("缩放")]
public float Zoom { get => previewer.Zoom; set => previewer.Zoom = value; }
[Category("导出"), DisplayName("旋转")]
public float Rotation { get => previewer.Rotation; set => previewer.Rotation = value; }
[Category("导出"), DisplayName("水平翻转")]
public bool FlipX { get => previewer.FlipX; set => previewer.FlipX = value; }
[Category("导出"), DisplayName("垂直翻转")]
public bool FlipY { get => previewer.FlipY; set => previewer.FlipY = value; }
[Category("预览"), DisplayName("显示坐标轴")]
public bool ShowAxis { get => previewer.ShowAxis; set => previewer.ShowAxis = value; }
[Category("预览"), DisplayName("最大帧率")]
public uint MaxFps { get => previewer.MaxFps; set => previewer.MaxFps = value; }
// 设置默认参数
Resolution = new(2048, 2048);
Center = new(0, 0);
FlipY = true;
MaxFps = 30;
}
/// <summary>
/// 要绑定的 Spine 列表控件
/// </summary>
[Category("自定义"), Description("相关联的 SpineListView")]
public SpineListView? SpineListView { get; set; }
/// <summary>
/// 属性信息面板
/// </summary>
[Category("自定义"), Description("用于显示画面属性的属性页")]
public PropertyGrid? PropertyGrid
{
@@ -62,28 +51,12 @@ namespace SpineViewer.Controls
{
propertyGrid = value;
if (propertyGrid is not null)
propertyGrid.SelectedObject = new PreviewerProperty(this);
propertyGrid.SelectedObject = new PropertyGridWrappers.SpinePreviewerWrapper(this);
}
}
private PropertyGrid? propertyGrid;
public const float ZOOM_MAX = 1000f;
public const float ZOOM_MIN = 0.001f;
public const int BACKGROUND_CELL_SIZE = 10;
private static readonly SFML.Graphics.Color BackgroundColor = new(105, 105, 105);
private static readonly SFML.Graphics.Color AxisColor = new(220, 220, 220);
private static readonly SFML.Graphics.Color BoundsColor = new(120, 200, 0);
private readonly SFML.Graphics.VertexArray AxisVertex = new(SFML.Graphics.PrimitiveType.Lines, 2);
private readonly SFML.Graphics.VertexArray BoundsRect = new(SFML.Graphics.PrimitiveType.LineStrip, 5);
private readonly SFML.Graphics.RenderWindow RenderWindow;
private readonly SFML.System.Clock Clock = new();
private SFML.System.Vector2f? draggingSrc = null;
private Task? task = null;
private CancellationTokenSource? cancelToken = null;
#region
/// <summary>
/// 分辨率
@@ -98,8 +71,8 @@ namespace SpineViewer.Controls
if (value.Width <= 0) value.Width = 100;
if (value.Height <= 0) value.Height = 100;
float parentX = Width;
float parentY = Height;
float parentX = panel.Parent.Width;
float parentY = panel.Parent.Height;
float sizeX = value.Width;
float sizeY = value.Height;
@@ -121,7 +94,7 @@ namespace SpineViewer.Controls
RenderWindow.Size = new((uint)sizeX, (uint)sizeY);
// 将 view 的大小设置成于 resolution 相同的大小, 其余属性都不变
var view = RenderWindow.GetView();
using var view = RenderWindow.GetView();
var signX = Math.Sign(view.Size.X);
var signY = Math.Sign(view.Size.Y);
view.Size = new(value.Width * signX, value.Height * signY);
@@ -141,12 +114,13 @@ namespace SpineViewer.Controls
{
get
{
var center = RenderWindow.GetView().Center;
using var view = RenderWindow.GetView();
var center = view.Center;
return new(center.X, center.Y);
}
set
{
var view = RenderWindow.GetView();
using var view = RenderWindow.GetView();
view.Center = new(value.X, value.Y);
RenderWindow.SetView(view);
}
@@ -159,11 +133,15 @@ namespace SpineViewer.Controls
[Browsable(false)]
public float Zoom
{
get => resolution.Width / Math.Abs(RenderWindow.GetView().Size.X);
get
{
using var view = RenderWindow.GetView();
return resolution.Width / Math.Abs(view.Size.X);
}
set
{
value = Math.Clamp(value, ZOOM_MIN, ZOOM_MAX);
var view = RenderWindow.GetView();
value = Math.Clamp(value, 0.001f, 1000f);
using var view = RenderWindow.GetView();
var signX = Math.Sign(view.Size.X);
var signY = Math.Sign(view.Size.Y);
view.Size = new(resolution.Width / value * signX, resolution.Height / value * signY);
@@ -178,10 +156,14 @@ namespace SpineViewer.Controls
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public float Rotation
{
get => RenderWindow.GetView().Rotation;
get
{
using var view = RenderWindow.GetView();
return view.Rotation;
}
set
{
var view = RenderWindow.GetView();
using var view = RenderWindow.GetView();
view.Rotation = value;
RenderWindow.SetView(view);
}
@@ -194,10 +176,14 @@ namespace SpineViewer.Controls
[Browsable(false)]
public bool FlipX
{
get => RenderWindow.GetView().Size.X < 0;
get
{
using var view = RenderWindow.GetView();
return view.Size.X < 0;
}
set
{
var view = RenderWindow.GetView();
using var view = RenderWindow.GetView();
var size = view.Size;
if (size.X > 0 && value || size.X < 0 && !value)
size.X *= -1;
@@ -213,10 +199,14 @@ namespace SpineViewer.Controls
[Browsable(false)]
public bool FlipY
{
get => RenderWindow.GetView().Size.Y < 0;
get
{
using var view = RenderWindow.GetView();
return view.Size.Y < 0;
}
set
{
var view = RenderWindow.GetView();
using var view = RenderWindow.GetView();
var size = view.Size;
if (size.Y > 0 && value || size.Y < 0 && !value)
size.Y *= -1;
@@ -225,6 +215,13 @@ namespace SpineViewer.Controls
}
}
/// <summary>
/// 仅渲染选中
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public bool RenderSelectedOnly { get; set; } = false;
/// <summary>
/// 显示坐标轴
/// </summary>
@@ -241,41 +238,93 @@ namespace SpineViewer.Controls
private uint maxFps = 60;
/// <summary>
/// RenderWindow.View
/// 获取 View
/// </summary>
public SFML.Graphics.View GetView() => RenderWindow.GetView();
#endregion
#region
/// <summary>
/// 预览画面背景色
/// </summary>
private static readonly SFML.Graphics.Color BackgroundColor = new(105, 105, 105);
/// <summary>
/// 预览画面坐标轴颜色
/// </summary>
private static readonly SFML.Graphics.Color AxisColor = new(220, 220, 220);
/// <summary>
/// 坐标轴顶点缓冲区
/// </summary>
private readonly SFML.Graphics.VertexArray AxisVertex = new(SFML.Graphics.PrimitiveType.Lines, 2);
/// <summary>
/// 渲染窗口
/// </summary>
private readonly SFML.Graphics.RenderWindow RenderWindow;
/// <summary>
/// 帧间隔计时器
/// </summary>
private readonly SFML.System.Clock Clock = new();
/// <summary>
/// 渲染任务
/// </summary>
private Task? task = null;
private CancellationTokenSource? cancelToken = null;
/// <summary>
/// 是否更新画面
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false)]
public SFML.Graphics.View View { get => RenderWindow.GetView(); }
public SpinePreviewer()
public bool IsUpdating
{
InitializeComponent();
RenderWindow = new(panel.Handle);
RenderWindow.SetActive(false);
// 设置默认参数
Resolution = new(2048, 2048);
Center = new(0, 0);
FlipY = true;
MaxFps = 30;
get => isUpdating;
private set
{
if (value == isUpdating) return;
if (value)
{
button_Start.ImageKey = "pause";
}
else
{
button_Start.ImageKey = "start";
}
isUpdating = value;
}
}
private bool isUpdating = true;
/// <summary>
/// 开始预览
/// 快进时间量
/// </summary>
public void StartPreview()
private float forwardDelta = 0;
private object _forwardDeltaLock = new();
/// <summary>
/// 开始渲染
/// </summary>
public void StartRender()
{
if (task is not null)
return;
cancelToken = new();
task = Task.Run(RenderTask, cancelToken.Token);
IsUpdating = true;
}
/// <summary>
/// 停止预览
/// 停止渲染
/// </summary>
public void StopPreview()
public void StopRender()
{
IsUpdating = false;
if (task is null || cancelToken is null)
return;
cancelToken.Cancel();
@@ -284,13 +333,98 @@ namespace SpineViewer.Controls
task = null;
}
/// <summary>
/// 渲染任务
/// </summary>
private void RenderTask()
{
try
{
RenderWindow.SetActive(true);
float delta;
while (cancelToken is not null && !cancelToken.IsCancellationRequested)
{
delta = Clock.ElapsedTime.AsSeconds();
Clock.Restart();
// 停止更新的时候只是时间不前进, 但是坐标变换还是要更新, 否则无法移动对象
if (!IsUpdating) delta = 0;
// 加上要快进的量
lock (_forwardDeltaLock)
{
delta += forwardDelta;
forwardDelta = 0;
}
RenderWindow.Clear(BackgroundColor);
if (ShowAxis)
{
// 画一个很长的坐标轴, 用 1e9 比较合适
AxisVertex[0] = new(new(-1e9f, 0), AxisColor);
AxisVertex[1] = new(new(1e9f, 0), AxisColor);
RenderWindow.Draw(AxisVertex);
AxisVertex[0] = new(new(0, -1e9f), AxisColor);
AxisVertex[1] = new(new(0, 1e9f), AxisColor);
RenderWindow.Draw(AxisVertex);
}
// 渲染 Spine
if (SpineListView is not null)
{
lock (SpineListView.Spines)
{
var spines = SpineListView.Spines.Where(sp => !sp.IsHidden).ToArray();
for (int i = spines.Length - 1; i >= 0; i--)
{
if (cancelToken is not null && cancelToken.IsCancellationRequested)
break; // 提前中止
var spine = spines[i];
spine.Update(delta);
if (RenderSelectedOnly && !spine.IsSelected)
continue;
spine.IsDebug = true;
RenderWindow.Draw(spine);
spine.IsDebug = false;
}
}
}
RenderWindow.Display();
}
}
catch (Exception ex)
{
logger.Fatal(ex);
logger.Fatal("Render task stopped");
MessagePopup.Error(ex.ToString(), "预览画面已停止渲染");
}
finally
{
RenderWindow.SetActive(false);
}
}
#endregion
/// <summary>
/// 画面拖放对象世界坐标源点
/// </summary>
private SFML.System.Vector2f? draggingSrc = null;
private void SpinePreviewer_SizeChanged(object sender, EventArgs e)
{
if (RenderWindow is null)
return;
float parentX = Width;
float parentY = Height;
float parentX = panel.Parent.Width;
float parentY = panel.Parent.Height;
float sizeX = panel.Width;
float sizeY = panel.Height;
@@ -326,45 +460,64 @@ namespace SpineViewer.Controls
draggingSrc = RenderWindow.MapPixelToCoords(new(e.X, e.Y));
var src = new PointF(((SFML.System.Vector2f)draggingSrc).X, ((SFML.System.Vector2f)draggingSrc).Y);
if (SpineListView is not null)
{
lock (SpineListView.Spines)
{
var spines = SpineListView.Spines;
if (SpineListView is null)
return;
// 没有按下 Ctrl 键就只选中点击的那个, 所以先清空选中列表
lock (SpineListView.Spines)
{
var spines = SpineListView.Spines;
// 仅渲染选中模式禁止在画面里选择对象
if (RenderSelectedOnly)
{
// 只在被选中的对象里判断是否有效命中
bool hit = false;
foreach (int i in SpineListView.SelectedIndices)
{
if (spines[i].IsHidden) continue;
if (!spines[i].Bounds.Contains(src)) continue;
hit = true;
break;
}
// 如果没点到被选中的模型, 则不允许拖动
if (!hit) draggingSrc = null;
}
else
{
if ((ModifierKeys & Keys.Control) == 0)
{
// 没按 Ctrl 的情况下, 如果命中了已选中对象, 则就算普通命中
bool hit = false;
for (int i = 0; i < spines.Count; i++)
{
if (spines[i].Bounds.Contains(src))
{
hit = true;
if (spines[i].IsHidden) continue;
if (!spines[i].Bounds.Contains(src)) continue;
// 如果点到了没被选中的东西, 则清空原先选中的, 改为只选中这一次点的
if (!SpineListView.SelectedIndices.Contains(i))
{
SpineListView.SelectedIndices.Clear();
SpineListView.SelectedIndices.Add(i);
}
break;
hit = true;
// 如果点到了没被选中的东西, 则清空原先选中的, 改为只选中这一次点的
if (!SpineListView.SelectedIndices.Contains(i))
{
SpineListView.SelectedIndices.Clear();
SpineListView.SelectedIndices.Add(i);
}
break;
}
// 如果点了空白的地方, 就清空选中列表
if (!hit)
SpineListView.SelectedIndices.Clear();
if (!hit) SpineListView.SelectedIndices.Clear();
}
else
{
// 按下 Ctrl 的情况就执行多选, 并且点空白处也不会清空选中
for (int i = 0; i < spines.Count; i++)
{
if (spines[i].Bounds.Contains(src))
{
SpineListView.SelectedIndices.Add(i);
break;
}
if (spines[i].IsHidden) continue;
if (!spines[i].Bounds.Contains(src)) continue;
SpineListView.SelectedIndices.Add(i);
break;
}
}
}
@@ -392,10 +545,11 @@ namespace SpineViewer.Controls
{
lock (SpineListView.Spines)
{
foreach (var spine in SpineListView.Spines)
var spines = SpineListView.Spines;
foreach (int i in SpineListView.SelectedIndices)
{
if (spine.IsSelected)
spine.Position += delta;
if (spines[i].IsHidden) continue;
spines[i].Position += delta;
}
}
}
@@ -408,7 +562,7 @@ namespace SpineViewer.Controls
// 右键高优先级, 结束画面拖动模式
if ((e.Button & MouseButtons.Right) != 0)
{
SpineListView?.PropertyGrid?.Refresh();
SpineListView?.SpinePropertyGrid?.Refresh();
draggingSrc = null;
Cursor = Cursors.Default;
@@ -418,7 +572,7 @@ namespace SpineViewer.Controls
else if ((e.Button & MouseButtons.Left) != 0 && (MouseButtons & MouseButtons.Right) == 0)
{
draggingSrc = null;
SpineListView?.PropertyGrid?.Refresh();
SpineListView?.SpinePropertyGrid?.Refresh();
}
}
@@ -428,62 +582,57 @@ namespace SpineViewer.Controls
PropertyGrid?.Refresh();
}
private void RenderTask()
private void button_Stop_Click(object sender, EventArgs e)
{
try
IsUpdating = false;
if (SpineListView is not null)
{
RenderWindow.SetActive(true);
float delta;
while (cancelToken is not null && !cancelToken.IsCancellationRequested)
lock (SpineListView.Spines)
{
delta = Clock.ElapsedTime.AsSeconds();
Clock.Restart();
RenderWindow.Clear(BackgroundColor);
if (ShowAxis)
{
// 画一个很长的坐标轴, 用 1e9 比较合适
AxisVertex[0] = new(new(-1e9f, 0), AxisColor);
AxisVertex[1] = new(new(1e9f, 0), AxisColor);
RenderWindow.Draw(AxisVertex);
AxisVertex[0] = new(new(0, -1e9f), AxisColor);
AxisVertex[1] = new(new(0, 1e9f), AxisColor);
RenderWindow.Draw(AxisVertex);
}
// 渲染 Spine
if (SpineListView is not null)
{
lock (SpineListView.Spines)
{
foreach (var spine in SpineListView.Spines.Reverse())
{
spine.Update(delta);
RenderWindow.Draw(spine);
if (spine.IsSelected)
{
var bounds = spine.Bounds;
BoundsRect[0] = BoundsRect[4] = new(new(bounds.Left, bounds.Top), BoundsColor);
BoundsRect[1] = new(new(bounds.Right, bounds.Top), BoundsColor);
BoundsRect[2] = new(new(bounds.Right, bounds.Bottom), BoundsColor);
BoundsRect[3] = new(new(bounds.Left, bounds.Bottom), BoundsColor);
RenderWindow.Draw(BoundsRect);
}
}
}
}
RenderWindow.Display();
foreach (var spine in SpineListView.Spines)
spine.ResetAnimationsTime();
}
}
finally
}
private void button_Restart_Click(object sender, EventArgs e)
{
if (SpineListView is not null)
{
RenderWindow.SetActive(false);
lock (SpineListView.Spines)
{
foreach (var spine in SpineListView.Spines)
spine.ResetAnimationsTime();
}
}
IsUpdating = true;
}
private void button_Start_Click(object sender, EventArgs e)
{
IsUpdating = !IsUpdating;
}
private void button_ForwardStep_Click(object sender, EventArgs e)
{
lock (_forwardDeltaLock)
{
forwardDelta += 1f / maxFps;
}
}
}
private void button_ForwardFast_Click(object sender, EventArgs e)
{
lock (_forwardDeltaLock)
{
forwardDelta += 10f / maxFps;
}
}
//public void ClickStopButton() => button_Stop_Click(button_Stop, EventArgs.Empty);
//public void ClickRestartButton() => button_Restart_Click(button_Restart, EventArgs.Empty);
//public void ClickStartButton() => button_Start_Click(button_Start, EventArgs.Empty);
//public void ClickForwardStepButton() => button_ForwardStep_Click(button_ForwardStep, EventArgs.Empty);
//public void ClickForwardFastButton() => button_ForwardFast_Click(button_ForwardFast, EventArgs.Empty);
}
}

View File

@@ -117,4 +117,210 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="imageList.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<data name="imageList.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64">
<value>
AAEAAAD/////AQAAAAAAAAAMAgAAAEZTeXN0ZW0uV2luZG93cy5Gb3JtcywgQ3VsdHVyZT1uZXV0cmFs
LCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAmU3lzdGVtLldpbmRvd3MuRm9ybXMu
SW1hZ2VMaXN0U3RyZWFtZXIBAAAABERhdGEHAgIAAAAJAwAAAA8DAAAAHi0AAAJNU0Z0AUkBTAIBAQYB
AAFwAQABcAEAAR8BAAEYAQAE/wEhAQAI/wFCAU0BNgcAATYDAAEoAwABfAMAATADAAEBAQABIAYAAV0q
AAQCAy0BRQNbAc0DXQHoA1kBxgMyAU8DDwEUBAIYAAMOARIDQwF3A10BzwNbAc0DLQFFBAIYAANWAbID
XQHoA1wB1gNDAXcDFgEeBAIYAAMKAQ0DSQGFA14B4wNfAeUDUQGeAyQBNAMJAQsEARgAAwsBDgM7AWQD
XgHSA1YBsv8AEQAEAgMxAUwDYQHhAwAB/wMuAfkDYAHbA0QBewMeASoDBgEIFAADGAEhA1cBwgMhAfsD
YQHhAzEBTAQCGAADWQHDAwAB/wMhAfwDXAHrA0gBhAMWAR4YAAMLAQ4DTQGSAysB+QMPAf4DUAHyA1gB
ugM3AVoDEQEWAwIBAxQAAxcBHwNJAYYDXAHrA1kBw/8AEQAEAgMxAUwDYQHhAwAB/wMAAf8DHgH9A2AB
4ANQAZoDLgFGAxEBFgMGAQcEAQgAAxoBJANbAc0DAAH/A2EB4QMxAUwEAhgAA1kBwwMAAf8DAAH/AwAB
/wNbAdADPgFrAw8BEwMCAQMQAAMLAQ4DTQGSAysB+QMAAf8DAAH/AzkB9gNcAcsDRAF5Ax4BKgMGAQcM
AAQBAxgBIQNKAYsDWwHsA1kBw/8AEQAEAgMxAUwDYQHhAwAB/wMuAfkDXAHnA0MB9QNWAe4DWQG7A0MB
dwMoATsDDwEUBAEEAAMaASQDWwHNAwAB/wNhAeEDMQFMBAIYAANZAcMDIAH8A1AB8ANDAfUDLgH5A10B
zgNDAXcDGgEjAwIBAwwAAwsBDgNNAZIDKwH5AwEB/wMkAfoDOgH4Ay4B+QNdAeMDTgGYAyQBNQMGAQgE
AQQABAEDGAEhA0oBiwNbAewDWQHD/wARAAQCAzEBTANhAeEDAAH/A1wB2QM7AWMDWQG7Az0B9wM5AfgD
XAHnA1sBxQNBAXMDEwEZAwIBAwMaASQDWwHNAwAB/wNhAeEDMQFMBAIYAANZAcMDXAHrA1ABmgNVAbED
TQHzAyEB+wNbAeQDSwGPAxsBJQMDAQQIAAMLAQ4DTQGSAysB+QMfAf0DXAHZA1oBxwNDAfUDDwH+A1wB
6wNSAaMDJQE3AwMBBAQABAEDGAEhA0oBiwNbAewDWQHD/wARAAQCAzEBTANhAeEDAAH/A1sBzQMaASQD
FgEdA1UBrwMAAf8DAAH/AwAB/wMAAf8DVQGvAxYBHQMaASQDWwHNAwAB/wNhAeEDMQFMBAIYAANZAcMD
WwHkAzsBZQMHAQkDSQGGAyEB+wMAAf8DAAH/A1kBwQMdASkIAAMLAQ4DTQGSAysB+QMrAfkDTQGSAzkE
XgHiAwAB/wMAAf8DXQHjAzYBWAMFAQYEAAQBAxgBIQNKAYsDWwHsA1kBw/8AEQAEAgMxAUwDYQHhAwAB
/wNbAc0DGgEkAwIBAwMTARoDRgF/A1sB3gMhAfsDDwH+AzkB+ANZAbsDOwFjA1wB2QMAAf8DYQHhAzEB
TAQCGAADWQHDA1sB5AM7AWUDBwQJAQwDOgFhA18B1QNCAfUDLgH5A1sBygMyAU8DDwEUAw0BEQNNAZID
KwH5AysB+QNNAZIDEQEWAy0BRANaAb8DUgHvAyEB+wNdAdwDPwFuAxYBHgMEAQUDGAEhA0oBiwNbAewD
WQHD/wARAAQCAzEBTANhAeEDAAH/A1sBzQMaASQEAAQCAxMBGgM9AWcDWQHAA1IB7wMPAf4DPQH3A1wB
5wMuAfkDAAH/A2EB4QMxAUwEAhgAA1kBwwNbAeQDOwFlAwcBCQQAAwsBDgMxAU0DWAG9AzkB9gMuAfkD
YAHbA0QBeAMhAS8DTgGVAysB+QMrAfkDTQGSAwsBDgMGAQgDIAEuA00BkgNdAdwDQwH1A1oB6QNOAZYD
KAE8AyABLQNLAY0DWwHsA1kBw/8AEQAEAgMxAUwDYQHhAwAB/wNbAc0DGgEkCAAEAgMMARADLwFJA1IB
owNbAeQDPQH3Aw8B/gMAAf8DAAH/A2EB4QMxAUwEAhgAA1kBwwNbAeQDOwFlAwcBCQgAAxABFQM/AW0D
XAHWAyQB+gMeAf0DXAHWA0QBeQNUAasDIQH7AysB+QNNAZIDCwEOBAADAwEEAxsBJgNBAXMDWgHEA0UB
9ANWAe4DVQG0A0QBegNRAaIDVgHuA1kBw/8AEQAEAgMxAUwDYQHhAwAB/wNbAc0DGgEkEAADCAEKAyMB
MwNEAXkDVwG8A18B5QMkAfoDAAH/A2EB4QMxAUwEAhgAA1kBwwNbAeQDOwFlAwcBCQgAAwMBBAMaASQD
QgF0A14B0gMhAfsDOQH2A10B0QNgAeADHgH9AysB+QNNAZIDCwEOCAADAgEDAxIBFwM1AVUDWAG6A1UB
8QM5AfYDWwHeA2AB2wM5AfgDWQHD/wARAAQCAzEBTANhAeEDAAH/A1sBzQMaASQUAAMCAQMDDgESAyMB
MgM9AWgDXgHdAwAB/wNhAeEDMQFMBAIYAANZAcMDWwHkAzsBZQMHAQkMAAMCAQMDDwETAzQBUwNdAdED
OQH4Ax8B/AMfAf0DAAH/AysB+QNNAZIDCwEODAAEAQMJAQwDIwEzA1UBrgMgAf0DHgH9Ax8B/AMPAf4D
WQHD/wARAAQCAzEBTANhAeEDAAH/A1sBzQMaASQgAAMaASQDWwHNAwAB/wNhAeEDMQFMBAIYAANZAcMD
WwHkAzsBZQMHAQkYAAMPARQDVwG5AwAB/wMAAf8DAAH/AysB+QNNAZIDCwEOGAADRwGAA1wB7QMAAf8D
AAH/AwAB/wNZAcP/ABEABAIDMQFMA2EB4QMAAf8DWwHNAxoBJBQABAIDBwEJAxYBHQM1AVUDXAHZAwAB
/wNhAeEDMQFMBAIYAANZAcMDWwHkAzsBZQMHAQkMAAQBAw0BEQM0AVMDXQHRAy4B+QMQAf4DDwH+AwAB
/wMrAfkDTQGSAwsBDgwABAEDCQELAx4BKwNTAakDIAH9Ax4B/QMfAfwDDwH+A1kBw/8AEQAEAgMxAUwD
YQHhAwAB/wNbAc0DGgEkEAADBwEJAxsBJgM0AVMDTQGSA14B3QMuAfkDAAH/A2EB4QMxAUwEAhgAA1kB
wwNbAeQDOwFlAwcBCQgABAIDEAEVAzkBXgNbAc0DIQH7AyEB+wNcAecDVgHuAw8B/gMrAfkDTQGSAwsB
DggAAwIBAwMSARcDNQFVA1gBuANVAfEDOQH2A1sB3gNgAdsDOQH4A1kBw/8AEQAEAgMxAUwDYQHhAwAB
/wNbAc0DGgEkCAAEAgMMARADLgFGA00BkgNcAcgDXAHrAx4B/QMAAf8DAAH/A2EB4QMxAUwEAhgAA1kB
wwNbAeQDOwFlAwcBCQgAAwkBDAMxAU4DWAG3A00B8wMeAf0DXgHdA04BlgNZAb4DHwH8AysB+QNNAZID
CwEOBAADAwEEAxsBJgNBAXMDWgHEA0UB9ANWAe4DVQG0A0QBegNRAaIDVgHuA1kBw/8AEQAEAgMxAUwD
YQHhAwAB/wNbAc0DGgEkBAAEAgMTARoDPQFnA1oBvwNcAesDJAH6AzoB9gNcAecDLgH5AwAB/wNhAeED
MQFMBAIYAANZAcMDWwHkAzsBZQMHAQkEAAMLAQ4DLgFHA1UBrQNSAe8DOgH4A2AB2wNEAXoDJAE1A04B
mAMjAfoDKwH5A00BkgMLAQ4DBgEIAyABLgNNAZIDXQHcA0MB9QNaAekDTgGWAygBPAMgAS0DSwGNA1sB
7ANZAcP/ABEABAIDMQFMA2EB4QMAAf8DWwHNAxoBJAMCAQMDEwEaA0YBfwNbAd4DIQH7Aw8B/gM5AfgD
WQG7AzsBYwNcAdkDAAH/A2EB4QMxAUwEAhgAA1kBwwNbAeQDOwFlAwcECQEMAzoBYQNdAdQDRQH0Ay4B
+QNbAcoDMgFPAw8BFAMNAREDTQGSAysB+QMrAfkDTQGSAxEBFgMtAUQDWgG/A1IB7wMgAfwDYAHgA0AB
cQMXAR8DBAEFAxgBIQNKAYsDWwHsA1kBw/8AEQAEAgMxAUwDYQHhAwAB/wNbAc0DGgEkAxYBHQNVAa8D
AAH/AwAB/wMAAf8DAAH/A1UBrwMWAR0DGgEkA1sBzQMAAf8DYQHhAzEBTAQCGAADWQHDA1sB5AM7AWUD
BwEJA0kBhgMhAfsDAAH/AwAB/wNZAcEDHQEpCAADCwEOA00BkgMrAfkDKwH5A00BkgM5BF4B4gMAAf8D
AAH/A1gB7QNKAYsDGAEgCAEDGAEhA0oBiwNbAewDWQHD/wARAAQCAzEBTANhAeEDAAH/A1wB2QM7AWMD
WQG7Az0B9wMgAfwDRQH0A1wB2QNGAX4DEwEaAwIBAwMaASQDWwHNAwAB/wNhAeEDMQFMBAIYAANZAcMD
XAHrA1ABmgNVAbEDTQHzAyEB+wNfAeUDSwGPAxsBJQMDAQQIAAMLAQ4DTQGSAysB+QMhAfsDVgGzA0wB
jgNcAesDDwH+A1AB8ANXAbkDLgFHAwYBCAQABAEDGAEhA0oBiwNbAewDWQHD/wARAAQCAzEBTANhAeED
AAH/Ay4B+QNcAecDQwH1A1QB8QNbAdMDUQGkAzgBWwMTARkEAgQAAxoBJANbAc0DAAH/A2EB4QMxAUwE
AhgAA1kBwwMgAfwDUAHwA0MB9QMfAf0DXgHXA0YBfgMaASQDAgEDDAADCwEOA00BkgMrAfkDDwH+A00B
8wNWAe4DPQH3A10B4wNOAZgDJwE5AwgBCgQBBAAEAQMYASEDSgGLA1sB7ANZAcP/ABEABAIDMQFMA2EB
4QMAAf8DAAH/Ax4B/QNhAeEDUgGjAzsBYwMhAS8DCgENBAIIAAMaASQDWwHNAwAB/wNhAeEDMQFMBAIY
AANZAcMDAAH/AwAB/wMAAf8DXQHoA0oBiwMWAR0DBAEFEAADCwEOA00BkgMrAfkDAAH/AwAB/wM5AfYD
XAHLA0QBeQMeASoDBgEHDAAEAQMYASEDSgGLA1sB7ANZAcP/ABEABAIDMQFMA2EB4QMAAf8DLgH5A2AB
2wNFAXwDIQEwAwwBEAMDAQQQAAMaASMDXAHIAx8B/QNhAeEDMQFMBAIYAANZAcMDAAH/AyEB/ANcAesD
TgGXAyMBMwQCFAADCwEOA00BkgMrAfkDDwH+A1AB8gNYAboDNwFaAxEBFgMCAQMUAAMXAR8DSQGGA1wB
6wNZAcP/ABEABAIDLQFFA14B0gNQAfIDXQHJAzIBTwMQARUDAgEDGAADEwEaA1ABnwNbAeQDWwHQAy0B
RQQCGAADVQG0A1cB7gNfAdoDRAF4AxgBIAMDAQQYAAMKAQ0DSQGGA10B6ANaAekDUAGfAyQBNAMJAQsE
ARgAAwsBDgM7AWUDWwHTA1YBsv8AFQADAwEEAycBOgM/AW0DFAEbKAADDwETAzEBTgMdASkDAgEDHAAD
DgESAzEBTQMjATMDBAEFJAADBgEHAygBPAMoATwDBgEHJAAEAQMHAQkDCwEOAwIBA/8ABQADAgEDAw8B
FANJAYgDXwHlA10B6ANdAegDXQHoA10B6ANdAegDXQHoA10B6ANdAegDXQHoA10B6ANdAegDXQHoA10B
6ANdAegDXQHoA10B6ANdAegDXQHoA1sB5ANGAX4DBQEGBAEoAAMCAQMDDQERAx8BLAMtAUYDVwG5A10B
6ANdAegDXQHoA10B6ANdAegDXQHoA18B4wNZAb4DMgFPAw8BEwMCAQMwAAMTARkDRgF+A10B6ANdAegD
WQHBAzkBXgMmATgDDwEUBAJcAAM5AV8DXgHiA1wB5wNdAegDXQHoA10B6ANdAegDXQHcAzwBZgMGAQgD
BgEIAzwBZgNdAdwDXQHoA10B6ANdAegDXQHoA10B3ANQAZ0DJQE2IAADDAEQAzwBZgNdAc8DHgH9AyQB
+gNSAe8DWAHtA1gB7QNYAe0DWAHtA1gB7QNYAe0DWAHtA1gB7QNYAe0DWAHtA1gB7QNYAe0DWAHtA1gB
7QNSAe8DJAH6AyAB/ANWAbUDKwFCAwgBCiQABAIDGAEhA0ABcANaAb8DXQHfA1oB7QNSAe8DWwHsA14B
5gNfAeUDWAHqA1gB7QNQAfADOgH2A10B0QNDAXcDHgErAwYBBywAAz0BaQNbAd4DAQH/Ay4B+QNcAewD
WwHkA14B1wNEAXsDHgEqAwYBCFgAAz8BbAMfAf0DOQH4A1IB7wNYAe0DVgHuAyQB+gM5AfYDTwGbAx4B
KwMgAS0DUAGdAzkB9gMkAfoDVgHuA1gB7QNSAe8DPQH3A1AB8gM7AWUgAAMTARkDUAGcAz0B9wM6AfYD
XQHMA0sBjQNGAYADRgGAA0YBgANGAYADRgGAA0YBgANGAYADRgGAA0YBgANGAYADRgGAA0YBgANGAYAD
RgGAA0sBjwNcAdkDHgH9A1QB8QNOAZQDEgEYJAADBQEGAzEBTgNbAdADUAHyA14B4gNVAa4DSgGKA0YB
fwNDAXcDQwF2A0UBfANGAYADTwGbA14B3QNdAegDXwHaA04BlgMoATwDCQEMKAADRwGDAzkB+AMgAfwD
WwHTA1MBpgNcAdkDLgH5A2AB4ANQAZoDLQFEAwsBDlQAAz8BbAMgAfwDWwHTA0wBjgNGAYADSgGKA10B
3AMfAf0DXgHdAzoBYAM6AWIDXQHfAx4B/QNdAdwDSgGKA0YBgANMAY4DWwHTAyAB/AM/AWwgAAMUARsD
UgGlAx0B/QNbAdADPwFsAxgBIQMOARIDDgESAw4BEgMOARIDDgESAw4BEgMOARIDDgESAw4BEgMOARID
DgESAw4BEgMOARIDDgESAyABLgNXAbkDHgH9Ax0B/QNSAaUDFAEbJAADBQEGAzEBTQNaAccDXAHIA0AB
bwMlATcDEwEaAw4BEgMNAREDDAEQAw4BEgMOARIDHQEoAzoBYANLAY8DWwHYA14B5gNWAbYDMQFNAwYB
CCQAA0kBhgMhAfsDLgH5A1UBrgMqAUADPwFtA10B0QNDAfUDVgHuA1gBtwM2AVcDFgEdAwwBEAQCSAAD
PwFsAy4B+QNVAa4DIAEtAw4BEgMbASUDWQG+AwAB/wNYAe0DPwFtAz8BbQNYAe0DAAH/A1kBvgMbASUD
DgESAyABLQNVAa4DLgH5Az8BbCAAAxQBGwNSAaUDHQH9A1YBtgMoATwDCAEKOAADFgEeA1YBswMeAf0D
HQH9A1IBpQMUARskAAQBAw8BFAMjATMDIQEwAwsBDgMDAQQEARQABAIDBwEJAx4BKgNLAYwDXQHfAz0B
9wNTAakDKAE7JAADSQGGAyEB+wMuAfkDUwGnAxYBHgMMARADKgFAA1gBugNOAfMDRgH0A2AB2wNXAbwD
QgF0AxMBGQMCAQNEAAM/AWwDLgH5A1MBpwMVARwEAAMPARQDVwG5AwAB/wNYAe0DPwFtAz8BbQNYAe0D
AAH/A1cBuQMPARQEAAMVARwDUwGnAy4B+QM/AWwgAAMUARsDUgGlAx0B/QNVAbQDJgE4AwcBCTgAAxYB
HgNWAbMDHgH9Ax0B/QNSAaUDFAEbYAADFQEcA1MBpwMuAfkDIQH7A0kBhiQAA0kBhgMhAfsDLgH5A1MB
pwMVARwIAAMPARMDQwF2A1wB2QMfAf0DAAH/AwAB/wNVAa8DFgEdRAADPwFsAy4B+QNTAacDFQEcBAAD
DwEUA1cBuQMAAf8DWAHtAz8BbQM/AW0DWAHtAwAB/wNXAbkDDwEUBAADFQEcA1MBpwMuAfkDPwFsIAAD
FAEbA1IBpQMdAf0DVQG0AyYBOAMHAQk4AAMWAR4DVgGzAx4B/QMdAf0DUgGlAxQBG2AAAwIBAwMeASoD
VQG0Az0B9wNSAaADGwElAwUBBhwAA0kBhgMhAfsDLgH5A1MBpwMVARwIAAQCAwkBCwMYASADRAF6A2AB
2wM7AfcDPQH3A1kBuwMqAUADDgESAwUBBgQCNAADPwFsAy4B+QNTAacDFQEcBAADDwEUA1cBuQMAAf8D
WAHtAz8BbQM/AW0DWAHtAwAB/wNXAbkDDwEUBAADFQEcA1MBpwMuAfkDPwFsIAADFAEbA1IBpQMdAf0D
VQG0AyYBOAMHAQk4AAMWAR4DVgGzAx4B/QMdAf0DUgGlAxQBG2QAAw8BEwNAAW8DXQHUA1MB7wNMAZED
EgEYHAADSQGGAyEB+wMuAfkDUwGnAxUBHBAABAIDDQERAzYBVwNYAbcDWwHsA1UB8QNdAdEDRAF5AzMB
UAMbASYDBgEHMAADPwFsAy4B+QNTAacDFQEcBAADDwEUA1cBuQMAAf8DWAHtAz8BbQM/AW0DWAHtAwAB
/wNXAbkDDwEUBAADFQEcA1MBpwMuAfkDPwFsIAADFAEbA1IBpQMdAf0DVQG0AyYBOAMHAQk4AAMWAR4D
VgGzAx4B/QMdAf0DUgGlAxQBG2QAAwIBAwMPARMDUQGeAx0B/QNSAaUDFAEbHAADSQGGAyEB+wMuAfkD
UwGnAxUBHBgAAwsBDgMtAUQDSwGPA1sBxQNhAeEDYQHhA1sBzQNMAZADKAE7AwkBDCwAAz8BbAMuAfkD
UwGnAxUBHAQAAw8BFANXAbkDAAH/A1gB7QM/AW0DPwFtA1gB7QMAAf8DVwG5Aw8BFAQAAxUBHANTAacD
LgH5Az8BbCAAAxQBGwNSAaUDHQH9A1UBtAMmATgDBwEJOAADFgEeA1YBswMeAf0DHQH9A1IBpQMUARts
AANNAZMDHQH9A1IBpQMUARscAANJAYYDIQH7Ay4B+QNTAacDFQEcHAADBgEIAxkBIgMvAUkDQAFxA10B
zANNAfMDWgHpA1YBtgMtAUQsAAM/AWwDLgH5A1MBpwMVARwEAAMPARQDVwG5AwAB/wNYAe0DPwFtAz8B
bQNYAe0DAAH/A1cBuQMPARQEAAMVARwDUwGnAy4B+QM/AWwgAAMUARsDUgGlAx0B/QNVAbQDJgE4AwcB
CTgAAxYBHgNWAbMDHgH9Ax0B/QNSAaUDFAEbbAADTQGTAx0B/QNSAaUDFAEbHAADSQGGAyEB+wMuAfkD
UwGnAxUBHCAABAIDBAEFAwsBDgMwAUwDWQHBAzoB9gMsAfkDQQFyAwYBCCgAAz8BbAMuAfkDUwGnAxUB
HAQAAw8BFANXAbkDAAH/A1gB7QM/AW0DPwFtA1gB7QMAAf8DVwG5Aw8BFAQAAxUBHANTAacDLgH5Az8B
bCAAAxQBGwNSAaUDHQH9A1UBtAMmATgDBwEJOAADFgEeA1YBswMeAf0DHQH9A1IBpQMUARtsAANNAZMD
HQH9A1IBpQMUARscAANJAYYDIQH7Ay4B+QNTAacDFQEcMAADFQEcA1MBpwMuAfkDWwHTAzoBYSgAAz8B
bAMuAfkDUwGnAxUBHAQAAw8BFANXAbkDAAH/A1gB7QM/AW0DPwFtA1gB7QMAAf8DVwG5Aw8BFAQAAxUB
HANTAacDLgH5Az8BbCAAAxQBGwNSAaUDHQH9A1UBtAMmATgDBwEJOAADFgEeA1YBswMeAf0DHQH9A1IB
pQMUARsQAAQBAwQBBQMLAQ4DDwETAw8BEwMPARMDDwETAw8BEwMNAREDCQEMAwMBBAQBLAADTQGTAx0B
/QNSAaUDFAEbHAADSQGGAyEB+wMuAfkDUwGnAxUBHCAABAEDAgEDAwsBDgMwAUwDWQHBAzoB9gMsAfkD
QQFyAwYBCCgAAz8BbAMuAfkDUwGnAxUBHAQAAw8BFANXAbkDAAH/A1gB7QM/AW0DPwFtA1gB7QMAAf8D
VwG5Aw8BFAQAAxUBHANTAacDLgH5Az8BbCAAAxQBGwNSAaUDHQH9A1UBtAMmATgDBwEJOAADFgEeA1YB
swMeAf0DHQH9A1IBpQMUARsQAAMGAQgDJAE1Az4BawNGAX0DRgF+A0YBfgNGAX4DRgF+A0QBewM9AWkD
JAE0AwkBDCwAA00BkwMdAf0DUgGlAxQBGxwAA0kBhgMhAfsDLgH5A1MBpwMVARwcAAMGAQgDEgEXAyMB
MwM/AW4DWwHNAzoB9gNYAeoDVgG2Ay0BRCwAAz8BbAMuAfkDUwGnAxUBHAQAAw8BFANXAbkDAAH/A1gB
7QM/AW0DPwFtA1gB7QMAAf8DVwG5Aw8BFAQAAxUBHANTAacDLgH5Az8BbCAAAxQBGwNSAaUDHQH9A1UB
tAMmATgDBwEJOAADFgEeA1YBswMeAf0DHQH9A1IBpQMUARsQAAMQARUDRgF/A1wB2QNYAeoDXgHmA2EB
4QNgAeADXgHiA1wB5wNhAeEDUAGdAyEBMCQAAwIBAwMPARMDUQGeAx0B/QNSAaUDFAEbHAADSQGGAyEB
+wMuAfkDUwGnAxUBHBgAAwsBDgMtAUQDRgGBA1MBqQNdAd8DXQHoA18B2gNOAZYDKAE8AwkBDCwAAz8B
bAMuAfkDUwGnAxUBHAQAAw8BFANXAbkDAAH/A1gB7QM/AW0DPwFtA1gB7QMAAf8DVwG5Aw8BFAQAAxUB
HANTAacDLgH5Az8BbCAAAxQBGwNSAaUDHQH9A1UBtAMmATgDBwEJOAADFgEeA1YBswMeAf0DHQH9A1IB
pQMUARsQAAMTARoDTgGYA0IB9QMAAf8DYAHgA1YBtgNZAb4DXgHXAz0B9wMgAfwDWgHHAysBQiQAAw8B
EwNAAW8DXQHUA1MB7wNNAZIDEgEYHAADSQGGAyEB+wMuAfkDUwGnAxUBHBAABAIDDQERAzYBVwNYAbcD
WAHqA1wB7ANfAdUDSwGPAzoBYAMeASsDBgEHMAADPwFsAy4B+QNTAacDFQEcBAADDwEUA1cBuQMAAf8D
WAHtAz8BbQM/AW0DWAHtAwAB/wNXAbkDDwEUBAADFQEcA1MBpwMuAfkDPwFsIAADFAEbA1IBpQMdAf0D
VQG0AyYBOAMHAQk4AAMWAR4DVgGzAx4B/QMdAf0DUgGlAxQBGxAAAxQBGwNQAZoDOQH2AwAB/wNRAaQD
JAE0A0QBeANeAd0DPQH3A1sB3gM7AWMDDgESIAADAgEDAx4BKgNVAbQDPQH3A1EBoQMbASYDBQEGHAAD
SQGGAyEB+wMuAfkDUwGnAxUBHAwABAEDEwEZA0QBegNgAdsDOwH3Az0B9wNZAbsDKwFCAxMBGQMIAQoD
AgEDNAADPwFsAy4B+QNTAacDFQEcBAADDwEUA1cBuQMAAf8DWAHtAz8BbQM/AW0DWAHtAwAB/wNXAbkD
DwEUBAADFQEcA1MBpwMuAfkDPwFsIAADFAEbA1IBpQMdAf0DVQG0AyYBOAMHAQk4AAMWAR4DVgGzAx4B
/QMdAf0DUgGlAxQBGxAAAxQBGwNQAZoDOQH2AwAB/wNOAZUDMQFMA2EB4QMAAf8DWwHNAxoBJCgAAxUB
HANTAacDLgH5AyEB+wNJAYYkAANJAYYDIQH7Ay4B+QNTAacDFQEcDAADCwEOA00BkgMrAfkDAAH/AwAB
/wNVAa8DFgEdRAADPwFsAy4B+QNTAacDFQEcBAADDwEUA1cBuQMAAf8DWAHtAz8BbQM/AW0DWAHtAwAB
/wNXAbkDDwEUBAADFQEcA1MBpwMuAfkDPwFsIAADFAEbA1IBpQMdAf0DVgG2AygBPAMIAQo4AAMWAR4D
VgGzAx4B/QMdAf0DUgGlAxQBGxAAAxQBGwNQAZoDOQH2AwAB/wNDAfUDVAHvAyEB/AMRAf4DXQHMAx0B
KQQCGAAEAgMGAQcDDwETAzIBTwNZAcADQgH1A10B0QM6AWAkAANJAYYDIQH7Ay4B+QNTAacDFgEeAwwB
EAMqAUADVwG5A1oB6QNTAe8DWwHoA10BzwNGAX0DEwEaAwIBA0QAAz8BbAMuAfkDUwGnAxUBHAQAAw8B
FANXAbkDAAH/A1gB7QM/AW0DPwFtA1gB7QMAAf8DVwG5Aw8BFAQAAxUBHANTAacDLgH5Az8BbCAAAxQB
GwNSAaUDHQH9A1sB0AM/AWwDGAEhAw4BEgMOARIDDgESAw4BEgMOARIDDgESAw4BEgMOARIDDgESAw4B
EgMOARIDDgESAw4BEgMOARIDIAEuA1cBuQMeAf0DHQH9A1IBpQMUARsQAAMUARsDUAGaAzkB9gMAAf8D
AAH/AyMB+gNCAfUDHgH9A2AB4ANAAXEDHQEoAw4BEgMNAREDCQEMAwgBCgMLBA4BEgMcAScDOAFbA0QB
eQNaAccDYQHhA1YBtgM0AVQDDAEPJAADSQGGAyEB+wMuAfkDVQGuAyoBQAM/AW0DXQHRA0MB9QNWAe4D
WQG7A0QBeQMqAUADEQEWBAJIAAM/AWwDLgH5A1UBrgMgAS0DDgESAxsBJQNZAb4DAAH/A1gB7QM/AW0D
PwFtA1gB7QMAAf8DWQG+AxsBJQMOARIDIAEtA1UBrgMuAfkDPwFsIAADEwEaA1EBpAMfAfwDOQH2A10B
zANLAY0DRgGAA0YBgANGAYADRgGAA0YBgANGAYADRgGAA0YBgANGAYADRgGAA0YBgANGAYADRgGAA0YB
gANLAY8DXAHZAx4B/QNFAfQDTgGYAxMBGRAAAxIBGANLAYwDWAHtAwAB/wMgAf0DXAHZA1UBsQNdAd8D
QwH1A2AB4ANPAZsDRgGAA0QBegM5AV4DMwFQAz0BaANGAX4DUAGaA18B2gNbAeQDXwHaA08BmwMpAT4D
CgENKAADSQGGAyEB+wMgAfwDWwHTA1MBpgNcAdkDLgH5A2AB4ANQAZoDLQFFAxABFQMGAQcEAUwAAz8B
bAMgAfwDWwHTA0wBjgNGAYADSgGKA10B3AMeAf0DXQHfAzoBYgM6AWIDXQHfAx4B/QNdAdwDSgGKA0YB
gANMAY4DWwHTAyAB/AM/AWwgAAMSARcDSgGLA1oB6gMPAf4DJAH6A1IB7wNYAe0DWAHtA1gB7QNYAe0D
WAHtA1gB7QNYAe0DWAHtA1gB7QNYAe0DWAHtA1gB7QNYAe0DWAHtA1IB7wMkAfoDHgH9A1cBwgM0AVQD
CwEOEAADCAEKAy4BSANVAbEDXgHiA2AB2wNPAZsDLQFEA0MBdwNdAcwDYQHhA1gB6gNYAe0DWgHpA1sB
0wNcAcgDXwHaA1wB6wNOAfIDLgH5A14B0gNEAXgDIQEvAwcBCSwAA0IBdQNYAeoDAQH/Ay4B+QNQAfAD
XAHsA1wB2QNEAXsDHgEqAwYBCFgAAz8BbAMBAf8DLgH5A1IB7wNYAe0DVgHuAyQB+gM5AfYDUAGdAyAB
LQMgAS0DUAGdAzkB9gMkAfoDVgHuA1gB7QNSAe8DLgH5Aw8B/gM/AWwgAAMFAQYDGgEjA00BkwNgAeYD
WgHtAzwB9gM9AfcDPQH3Az0B9wM9AfcDPQH3Az0B9wM9AfcDPQH3Az0B9wM9AfcDPQH3Az0B9wM9AfcD
PQH3AzwB9gNaAe0DXwHlA0cBgwMKAQ0EAhAABAEDCAEKAx8BLAMuAUgDLQFEAxsBJQMHAQkDDwETAyMB
MgMuAUcDVwG5A10B6ANaAekDVwHuA1UB8QNcAewDWgHpA10B6ANbAdADNAFTAw8BEwMCAQMwAAMWAR4D
RwGDA1oB7QNVAfEDXwHVA0wBjgMrAUIDDwEUBAJcAAM6AWIDWgHpA1oB7QM8AfYDPQH3AzwB9gNcAewD
XQHcAzwBZgMGAQgDBgEIAzwBZgNdAdwDWgHtAzwB9gM9AfcDPAH2A1oB7QNgAeYDOgFiLAAEAQMjATMD
TgGXA1QBqwNUAasDVAGrA1QBqwNUAasDVAGrA1QBqwNUAasDVAGrA1QBqwNUAasDVAGrA1QBqwNUAasD
TgGXAyMBMwQBTAADCQELAzkBXQNHAYIDJwE6AwQBBUgABAIDIgExAzoBYQMPARRwAAMDAQQDKAE7A04B
mANUAasDUQGeAyEBLxQAAwMBBAMlATcDUAGfA1QBqwNOAZgDKAE7AwMBBBgAAUIBTQE+BwABPgMAASgD
AAF8AwABMAMAAQEBAAEBBgABAxYAA/8BAAH8AQMB8AE/AQMB8AEPAcAIAAH8AQEB8AE/AQMB8AEHAcAI
AAH8AQABMAE/AQAB8AEDAYAIAAH8AQABEAE/AQABcAEAAYAIAAH8AgABPwEAATABAAGACAAB/AIAAT8B
AAEwAQABgAgAAfwCAAE/DAAB/AEIAQABPwEICwAB/AEMAQABPwEMAQABIAkAAfwBDwEAAT8BDAEAATAJ
AAH8AQ8BgAE/AQ4BAAE4CQAB/AEPAfABPwEPAcABPwkAAfwBDwGAAT8BDgEAATgJAAH8AQ8BAAE/AQwB
AAEwCQAB/AEMAQABPwEMAQABIAkAAfwBCAEAAT8BCAsAAfwCAAE/DAAB/AIAAT8BAAEwCgAB/AIAAT8B
AAEwAQABgAgAAfwBAAEQAT8BAAFwAQABgAgAAfwBAAEwAT8BAAHwAQMBgAgAAfwBAAHwAT8BAQHwAQcB
wAgAAfwBAwHwAT8BAwHwAQ8BwAgAAf4BHwH4AX8BDwH4AX8BwAgAAeACAAEHAf4BAAEBAf8B4AEPAv8B
4AEAAQEB8AHgAgABBwH8AgAB/wHgAQcC/wHgAQABAQHwAeACAAEHAfwCAAF/AeABAwL/AeABAAEBAfAB
4AIAAQcB/AIAAT8B4AEAAX8B/wHgAQABAQHwAeABfwH+AQcB/AEHAcABPwHgAQABPwH/AeEBAAEhAfAB
4AF/Af4BBwL/AfgBPwHgAcABPwH/AeEBAAEhAfAB4AF/Af4BBwL/AfgBDwHgAcABAwH/AeEBAAEhAfAB
4AF/Af4BBwL/AfwBDwHgAfABAQH/AeEBAAEhAfAB4AF/Af4BBwL/AfwBDwHgAfwBAAH/AeEBAAEhAfAB
4AF/Af4BBwP/AQ8B4AH+AQAB/wHhAQABIQHwAeABfwH+AQcD/wEPAeAB/wEAAX8B4QEAASEB8AHgAX8B
/gEHA/8BDwHgAf8B8AF/AeEBAAEhAfAB4AF/Af4BBwGAAQcB/wEPAeAB/wEAAX8B4QEAASEB8AHgAX8B
/gEHAYABBwH/AQ8B4AH+AQAB/wHhAQABIQHwAeABfwH+AQcBgAEHAfwBDwHgAfwBAAH/AeEBAAEhAfAB
4AF/Af4BBwGAAQcB/AEPAeAB8AEBAf8B4QEAASEB8AHgAX8B/gEHAYABBwH4AQ8C4AEDAf8B4QEAASEB
8AHgAX8B/gEHAYABHwH4AT8C4AE/Af8B4QEAASEB8AHgAX8B/gEHAYABDwHAAT8B4AEAAT8B/wHhAQAB
IQHwAeACAAEHAYACAAE/AeABAAF/Af8B4AEAAQEB8AHgAgABBwGAAgABfwHgAQAC/wHgAQABAQHwAeAC
AAEHAYACAAH/AeABBwL/AeABAAEBAfAB4AIAAQcBgAEAAQEB/wHgAQ8C/wHgAQABAQHwAfwCAAE/Af8B
+AE/Af8B8AP/AfABPgEDAfAL
</value>
</data>
<metadata name="toolTip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>165, 17</value>
</metadata>
</root>

View File

@@ -0,0 +1,300 @@
namespace SpineViewer.Controls
{
partial class SpinePropertyGrid
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
tabControl = new TabControl();
tabPage_BaseInfo = new TabPage();
propertyGrid_BaseInfo = new PropertyGrid();
tabPage_Render = new TabPage();
propertyGrid_Render = new PropertyGrid();
tabPage_Transform = new TabPage();
propertyGrid_Transform = new PropertyGrid();
tabPage_Skin = new TabPage();
propertyGrid_Skin = new PropertyGrid();
contextMenuStrip_Skin = new ContextMenuStrip(components);
toolStripMenuItem_AddSkin = new ToolStripMenuItem();
toolStripMenuItem_RemoveSkin = new ToolStripMenuItem();
tabPage_Animation = new TabPage();
propertyGrid_Animation = new PropertyGrid();
contextMenuStrip_Animation = new ContextMenuStrip(components);
toolStripMenuItem_AddAnimation = new ToolStripMenuItem();
toolStripMenuItem_RemoveAnimation = new ToolStripMenuItem();
tabPage_Debug = new TabPage();
propertyGrid_Debug = new PropertyGrid();
tabControl.SuspendLayout();
tabPage_BaseInfo.SuspendLayout();
tabPage_Render.SuspendLayout();
tabPage_Transform.SuspendLayout();
tabPage_Skin.SuspendLayout();
contextMenuStrip_Skin.SuspendLayout();
tabPage_Animation.SuspendLayout();
contextMenuStrip_Animation.SuspendLayout();
tabPage_Debug.SuspendLayout();
SuspendLayout();
//
// tabControl
//
tabControl.Alignment = TabAlignment.Bottom;
tabControl.Controls.Add(tabPage_BaseInfo);
tabControl.Controls.Add(tabPage_Render);
tabControl.Controls.Add(tabPage_Transform);
tabControl.Controls.Add(tabPage_Skin);
tabControl.Controls.Add(tabPage_Animation);
tabControl.Controls.Add(tabPage_Debug);
tabControl.Dock = DockStyle.Fill;
tabControl.ItemSize = new Size(100, 35);
tabControl.Location = new Point(0, 0);
tabControl.Multiline = true;
tabControl.Name = "tabControl";
tabControl.Padding = new Point(0, 0);
tabControl.SelectedIndex = 0;
tabControl.Size = new Size(372, 448);
tabControl.SizeMode = TabSizeMode.FillToRight;
tabControl.TabIndex = 0;
//
// tabPage_BaseInfo
//
tabPage_BaseInfo.BackColor = SystemColors.Control;
tabPage_BaseInfo.Controls.Add(propertyGrid_BaseInfo);
tabPage_BaseInfo.Location = new Point(4, 4);
tabPage_BaseInfo.Margin = new Padding(0);
tabPage_BaseInfo.Name = "tabPage_BaseInfo";
tabPage_BaseInfo.Size = new Size(364, 370);
tabPage_BaseInfo.TabIndex = 0;
tabPage_BaseInfo.Text = "基本信息";
//
// propertyGrid_BaseInfo
//
propertyGrid_BaseInfo.Dock = DockStyle.Fill;
propertyGrid_BaseInfo.HelpVisible = false;
propertyGrid_BaseInfo.Location = new Point(0, 0);
propertyGrid_BaseInfo.Name = "propertyGrid_BaseInfo";
propertyGrid_BaseInfo.PropertySort = PropertySort.Alphabetical;
propertyGrid_BaseInfo.Size = new Size(364, 370);
propertyGrid_BaseInfo.TabIndex = 0;
propertyGrid_BaseInfo.ToolbarVisible = false;
//
// tabPage_Render
//
tabPage_Render.BackColor = SystemColors.Control;
tabPage_Render.Controls.Add(propertyGrid_Render);
tabPage_Render.Location = new Point(4, 4);
tabPage_Render.Margin = new Padding(0);
tabPage_Render.Name = "tabPage_Render";
tabPage_Render.Size = new Size(437, 405);
tabPage_Render.TabIndex = 1;
tabPage_Render.Text = "渲染";
//
// propertyGrid_Render
//
propertyGrid_Render.Dock = DockStyle.Fill;
propertyGrid_Render.HelpVisible = false;
propertyGrid_Render.Location = new Point(0, 0);
propertyGrid_Render.Name = "propertyGrid_Render";
propertyGrid_Render.PropertySort = PropertySort.Alphabetical;
propertyGrid_Render.Size = new Size(437, 405);
propertyGrid_Render.TabIndex = 1;
propertyGrid_Render.ToolbarVisible = false;
//
// tabPage_Transform
//
tabPage_Transform.BackColor = SystemColors.Control;
tabPage_Transform.Controls.Add(propertyGrid_Transform);
tabPage_Transform.Location = new Point(4, 4);
tabPage_Transform.Margin = new Padding(0);
tabPage_Transform.Name = "tabPage_Transform";
tabPage_Transform.Size = new Size(437, 405);
tabPage_Transform.TabIndex = 2;
tabPage_Transform.Text = "变换";
//
// propertyGrid_Transform
//
propertyGrid_Transform.Dock = DockStyle.Fill;
propertyGrid_Transform.HelpVisible = false;
propertyGrid_Transform.Location = new Point(0, 0);
propertyGrid_Transform.Name = "propertyGrid_Transform";
propertyGrid_Transform.PropertySort = PropertySort.Alphabetical;
propertyGrid_Transform.Size = new Size(437, 405);
propertyGrid_Transform.TabIndex = 1;
propertyGrid_Transform.ToolbarVisible = false;
//
// tabPage_Skin
//
tabPage_Skin.BackColor = SystemColors.Control;
tabPage_Skin.Controls.Add(propertyGrid_Skin);
tabPage_Skin.Location = new Point(4, 4);
tabPage_Skin.Margin = new Padding(0);
tabPage_Skin.Name = "tabPage_Skin";
tabPage_Skin.Size = new Size(437, 405);
tabPage_Skin.TabIndex = 3;
tabPage_Skin.Text = "皮肤";
//
// propertyGrid_Skin
//
propertyGrid_Skin.ContextMenuStrip = contextMenuStrip_Skin;
propertyGrid_Skin.Dock = DockStyle.Fill;
propertyGrid_Skin.HelpVisible = false;
propertyGrid_Skin.Location = new Point(0, 0);
propertyGrid_Skin.Name = "propertyGrid_Skin";
propertyGrid_Skin.PropertySort = PropertySort.NoSort;
propertyGrid_Skin.Size = new Size(437, 405);
propertyGrid_Skin.TabIndex = 1;
propertyGrid_Skin.ToolbarVisible = false;
//
// contextMenuStrip_Skin
//
contextMenuStrip_Skin.ImageScalingSize = new Size(24, 24);
contextMenuStrip_Skin.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_AddSkin, toolStripMenuItem_RemoveSkin });
contextMenuStrip_Skin.Name = "contextMenuStrip1";
contextMenuStrip_Skin.Size = new Size(117, 64);
contextMenuStrip_Skin.Opening += contextMenuStrip_Skin_Opening;
//
// toolStripMenuItem_AddSkin
//
toolStripMenuItem_AddSkin.Name = "toolStripMenuItem_AddSkin";
toolStripMenuItem_AddSkin.Size = new Size(116, 30);
toolStripMenuItem_AddSkin.Text = "添加";
toolStripMenuItem_AddSkin.Click += toolStripMenuItem_AddSkin_Click;
//
// toolStripMenuItem_RemoveSkin
//
toolStripMenuItem_RemoveSkin.Name = "toolStripMenuItem_RemoveSkin";
toolStripMenuItem_RemoveSkin.Size = new Size(116, 30);
toolStripMenuItem_RemoveSkin.Text = "移除";
toolStripMenuItem_RemoveSkin.Click += toolStripMenuItem_RemoveSkin_Click;
//
// tabPage_Animation
//
tabPage_Animation.BackColor = SystemColors.Control;
tabPage_Animation.Controls.Add(propertyGrid_Animation);
tabPage_Animation.Location = new Point(4, 4);
tabPage_Animation.Margin = new Padding(0);
tabPage_Animation.Name = "tabPage_Animation";
tabPage_Animation.Size = new Size(437, 405);
tabPage_Animation.TabIndex = 4;
tabPage_Animation.Text = "动画";
//
// propertyGrid_Animation
//
propertyGrid_Animation.ContextMenuStrip = contextMenuStrip_Animation;
propertyGrid_Animation.Dock = DockStyle.Fill;
propertyGrid_Animation.HelpVisible = false;
propertyGrid_Animation.Location = new Point(0, 0);
propertyGrid_Animation.Name = "propertyGrid_Animation";
propertyGrid_Animation.PropertySort = PropertySort.NoSort;
propertyGrid_Animation.Size = new Size(437, 405);
propertyGrid_Animation.TabIndex = 1;
propertyGrid_Animation.ToolbarVisible = false;
//
// contextMenuStrip_Animation
//
contextMenuStrip_Animation.ImageScalingSize = new Size(24, 24);
contextMenuStrip_Animation.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_AddAnimation, toolStripMenuItem_RemoveAnimation });
contextMenuStrip_Animation.Name = "contextMenuStrip1";
contextMenuStrip_Animation.Size = new Size(117, 64);
contextMenuStrip_Animation.Opening += contextMenuStrip_Animation_Opening;
//
// toolStripMenuItem_AddAnimation
//
toolStripMenuItem_AddAnimation.Name = "toolStripMenuItem_AddAnimation";
toolStripMenuItem_AddAnimation.Size = new Size(116, 30);
toolStripMenuItem_AddAnimation.Text = "添加";
toolStripMenuItem_AddAnimation.Click += toolStripMenuItem_AddAnimation_Click;
//
// toolStripMenuItem_RemoveAnimation
//
toolStripMenuItem_RemoveAnimation.Name = "toolStripMenuItem_RemoveAnimation";
toolStripMenuItem_RemoveAnimation.Size = new Size(116, 30);
toolStripMenuItem_RemoveAnimation.Text = "移除";
toolStripMenuItem_RemoveAnimation.Click += toolStripMenuItem_RemoveAnimation_Click;
//
// tabPage_Debug
//
tabPage_Debug.BackColor = SystemColors.Control;
tabPage_Debug.Controls.Add(propertyGrid_Debug);
tabPage_Debug.Location = new Point(4, 4);
tabPage_Debug.Name = "tabPage_Debug";
tabPage_Debug.Size = new Size(437, 405);
tabPage_Debug.TabIndex = 5;
tabPage_Debug.Text = "调试";
//
// propertyGrid_Debug
//
propertyGrid_Debug.Dock = DockStyle.Fill;
propertyGrid_Debug.HelpVisible = false;
propertyGrid_Debug.Location = new Point(0, 0);
propertyGrid_Debug.Name = "propertyGrid_Debug";
propertyGrid_Debug.PropertySort = PropertySort.NoSort;
propertyGrid_Debug.Size = new Size(437, 405);
propertyGrid_Debug.TabIndex = 2;
propertyGrid_Debug.ToolbarVisible = false;
//
// SpinePropertyGrid
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(tabControl);
Name = "SpinePropertyGrid";
Size = new Size(372, 448);
tabControl.ResumeLayout(false);
tabPage_BaseInfo.ResumeLayout(false);
tabPage_Render.ResumeLayout(false);
tabPage_Transform.ResumeLayout(false);
tabPage_Skin.ResumeLayout(false);
contextMenuStrip_Skin.ResumeLayout(false);
tabPage_Animation.ResumeLayout(false);
contextMenuStrip_Animation.ResumeLayout(false);
tabPage_Debug.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private TabControl tabControl;
private TabPage tabPage_BaseInfo;
private TabPage tabPage_Render;
private TabPage tabPage_Transform;
private TabPage tabPage_Skin;
private TabPage tabPage_Animation;
private PropertyGrid propertyGrid_BaseInfo;
private PropertyGrid propertyGrid_Render;
private PropertyGrid propertyGrid_Transform;
private PropertyGrid propertyGrid_Skin;
private PropertyGrid propertyGrid_Animation;
private ContextMenuStrip contextMenuStrip_Skin;
private ContextMenuStrip contextMenuStrip_Animation;
private ToolStripMenuItem toolStripMenuItem_AddSkin;
private ToolStripMenuItem toolStripMenuItem_RemoveSkin;
private ToolStripMenuItem toolStripMenuItem_AddAnimation;
private ToolStripMenuItem toolStripMenuItem_RemoveAnimation;
private TabPage tabPage_Debug;
private PropertyGrid propertyGrid_Debug;
}
}

View File

@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SpineViewer.PropertyGridWrappers.Spine;
using SpineViewer.Utilities;
namespace SpineViewer.Controls
{
public partial class SpinePropertyGrid : UserControl
{
public SpinePropertyGrid()
{
InitializeComponent();
}
/// <summary>
/// 设置选中的对象列表, 可以赋值 null 来清空选中, 行为与 PropertyGrid.SelectedObjects 类似
/// </summary>
public SpineWrapper[] SelectedSpines
{
get => selectedSpines ?? [];
set
{
if (value is null || value.Length <= 0)
{
selectedSpines = null;
propertyGrid_BaseInfo.SelectedObject = null;
propertyGrid_Render.SelectedObject = null;
propertyGrid_Transform.SelectedObject = null;
propertyGrid_Skin.SelectedObject = null;
propertyGrid_Animation.SelectedObject = null;
propertyGrid_Debug.SelectedObject = null;
}
else
{
selectedSpines = value;
propertyGrid_BaseInfo.SelectedObjects = value.Select(e => e.BaseInfo).ToArray();
propertyGrid_Render.SelectedObjects = value.Select(e => e.Render).ToArray();
propertyGrid_Transform.SelectedObjects = value.Select(e => e.Transform).ToArray();
propertyGrid_Skin.SelectedObjects = value.Select(e => e.Skin).ToArray();
propertyGrid_Animation.SelectedObjects = value.Select(e => e.Animation).ToArray();
propertyGrid_Debug.SelectedObjects = value.Select(e => e.Debug).ToArray();
}
}
}
private SpineWrapper[]? selectedSpines = null;
private void contextMenuStrip_Skin_Opening(object sender, CancelEventArgs e)
{
if (selectedSpines?.Length == 1)
{
toolStripMenuItem_AddSkin.Enabled = true;
toolStripMenuItem_RemoveSkin.Enabled = propertyGrid_Skin.SelectedGridItem.Value is SkinWrapper;
}
else
{
toolStripMenuItem_AddSkin.Enabled = false;
toolStripMenuItem_RemoveSkin.Enabled = false;
}
}
private void contextMenuStrip_Animation_Opening(object sender, CancelEventArgs e)
{
if (selectedSpines?.Length == 1)
{
toolStripMenuItem_AddAnimation.Enabled = true;
toolStripMenuItem_RemoveAnimation.Enabled = propertyGrid_Animation.SelectedGridItem.Value is TrackWrapper;
}
else
{
toolStripMenuItem_AddAnimation.Enabled = false;
toolStripMenuItem_RemoveAnimation.Enabled = false;
}
}
private void toolStripMenuItem_AddSkin_Click(object sender, EventArgs e)
{
if (selectedSpines?.Length != 1) return;
var spine = selectedSpines[0].Skin.Spine;
if (spine.SkinNames.Count <= 0)
{
MessagePopup.Info("没有可用的皮肤");
return;
}
spine.LoadSkin(spine.SkinNames[0]);
propertyGrid_Skin.Refresh();
}
private void toolStripMenuItem_RemoveSkin_Click(object sender, EventArgs e)
{
if (selectedSpines?.Length != 1) return;
if (propertyGrid_Skin.SelectedGridItem.Value is SkinWrapper wrapper)
{
selectedSpines[0].Skin.Spine.UnloadSkin(wrapper.Index);
propertyGrid_Skin.Refresh();
}
}
private void toolStripMenuItem_AddAnimation_Click(object sender, EventArgs e)
{
if (selectedSpines?.Length != 1) return;
var spine = selectedSpines[0].Animation.Spine;
spine.SetAnimation(spine.GetTrackIndices().Max() + 1, spine.AnimationNames[0]);
propertyGrid_Animation.Refresh();
}
private void toolStripMenuItem_RemoveAnimation_Click(object sender, EventArgs e)
{
if (selectedSpines?.Length != 1) return;
if (propertyGrid_Animation.SelectedGridItem.Value is TrackWrapper wrapper)
{
selectedSpines[0].Animation.Spine.ClearTrack(wrapper.Index);
propertyGrid_Animation.Refresh();
}
}
}
}

View File

@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip_Skin.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>29, 26</value>
</metadata>
<metadata name="contextMenuStrip_Animation.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>318, 25</value>
</metadata>
</root>

View File

@@ -1,4 +1,5 @@
using System;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
@@ -15,15 +16,19 @@ namespace SpineViewer.Dialogs
public AboutDialog()
{
InitializeComponent();
this.label_Version.Text = $"v{InformationalVersion}";
Text = $"关于 {ProgramName}";
label_Version.Text = $"v{InformationalVersion}";
}
public string ProgramName => Process.GetCurrentProcess().ProcessName;
public string InformationalVersion
=> Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
public string ProgramUrl
{
get
{
return Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
}
get => linkLabel_RepoUrl.Text;
set => linkLabel_RepoUrl.Text = value;
}
private void linkLabel_RepoUrl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
@@ -36,7 +41,7 @@ namespace SpineViewer.Dialogs
else
{
Clipboard.SetText(url);
MessageBox.Show(this, "链接已复制到剪贴板,请前往浏览器进行访问", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info("链接已复制到剪贴板,请前往浏览器进行访问");
}
}
}

View File

@@ -37,10 +37,7 @@
tableLayoutPanel2 = new TableLayoutPanel();
button_Ok = new Button();
button_Cancel = new Button();
listBox_FilePath = new ListBox();
button_SelectSkel = new Button();
label_Tip = new Label();
openFileDialog_Skel = new OpenFileDialog();
skelFileListBox = new SpineViewer.Controls.SkelFileListBox();
panel.SuspendLayout();
tableLayoutPanel1.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
@@ -53,7 +50,7 @@
panel.Location = new Point(0, 0);
panel.Name = "panel";
panel.Padding = new Padding(50, 15, 50, 10);
panel.Size = new Size(1126, 449);
panel.Size = new Size(1042, 472);
panel.TabIndex = 1;
//
// tableLayoutPanel1
@@ -62,22 +59,19 @@
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle());
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(label4, 0, 0);
tableLayoutPanel1.Controls.Add(label3, 0, 3);
tableLayoutPanel1.Controls.Add(comboBox_Version, 1, 3);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 4);
tableLayoutPanel1.Controls.Add(listBox_FilePath, 0, 2);
tableLayoutPanel1.Controls.Add(button_SelectSkel, 0, 1);
tableLayoutPanel1.Controls.Add(label_Tip, 1, 1);
tableLayoutPanel1.Controls.Add(label3, 0, 2);
tableLayoutPanel1.Controls.Add(comboBox_Version, 1, 2);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 3);
tableLayoutPanel1.Controls.Add(skelFileListBox, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(50, 15);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 5;
tableLayoutPanel1.RowCount = 3;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Size = new Size(1026, 424);
tableLayoutPanel1.Size = new Size(942, 447);
tableLayoutPanel1.TabIndex = 1;
//
// label4
@@ -88,7 +82,7 @@
label4.Location = new Point(15, 15);
label4.Margin = new Padding(15);
label4.Name = "label4";
label4.Size = new Size(996, 24);
label4.Size = new Size(912, 24);
label4.TabIndex = 14;
label4.Text = "说明批量导入只需要选择skel文件atlas文件需要在同目录下并且与skel文件名相同";
label4.TextAlign = ContentAlignment.MiddleCenter;
@@ -97,7 +91,7 @@
//
label3.Anchor = AnchorStyles.Right;
label3.AutoSize = true;
label3.Location = new Point(90, 307);
label3.Location = new Point(3, 343);
label3.Name = "label3";
label3.Size = new Size(50, 24);
label3.TabIndex = 12;
@@ -108,7 +102,7 @@
comboBox_Version.Anchor = AnchorStyles.Left;
comboBox_Version.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox_Version.FormattingEnabled = true;
comboBox_Version.Location = new Point(146, 303);
comboBox_Version.Location = new Point(59, 339);
comboBox_Version.Name = "comboBox_Version";
comboBox_Version.Size = new Size(182, 32);
comboBox_Version.Sorted = true;
@@ -124,18 +118,19 @@
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(button_Ok, 0, 0);
tableLayoutPanel2.Controls.Add(button_Cancel, 1, 0);
tableLayoutPanel2.Dock = DockStyle.Bottom;
tableLayoutPanel2.Location = new Point(3, 381);
tableLayoutPanel2.Dock = DockStyle.Fill;
tableLayoutPanel2.Location = new Point(3, 404);
tableLayoutPanel2.Margin = new Padding(3, 30, 3, 3);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 1;
tableLayoutPanel2.RowStyles.Add(new RowStyle());
tableLayoutPanel2.Size = new Size(1020, 40);
tableLayoutPanel2.Size = new Size(936, 40);
tableLayoutPanel2.TabIndex = 11;
//
// button_Ok
//
button_Ok.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_Ok.Location = new Point(368, 3);
button_Ok.Location = new Point(326, 3);
button_Ok.Margin = new Padding(3, 3, 30, 3);
button_Ok.Name = "button_Ok";
button_Ok.Size = new Size(112, 34);
@@ -147,7 +142,7 @@
// button_Cancel
//
button_Cancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button_Cancel.Location = new Point(540, 3);
button_Cancel.Location = new Point(498, 3);
button_Cancel.Margin = new Padding(30, 3, 3, 3);
button_Cancel.Name = "button_Cancel";
button_Cancel.Size = new Size(112, 34);
@@ -156,47 +151,14 @@
button_Cancel.UseVisualStyleBackColor = true;
button_Cancel.Click += button_Cancel_Click;
//
// listBox_FilePath
// skelFileListBox
//
tableLayoutPanel1.SetColumnSpan(listBox_FilePath, 2);
listBox_FilePath.Dock = DockStyle.Fill;
listBox_FilePath.FormattingEnabled = true;
listBox_FilePath.HorizontalScrollbar = true;
listBox_FilePath.ItemHeight = 24;
listBox_FilePath.Location = new Point(3, 97);
listBox_FilePath.Name = "listBox_FilePath";
listBox_FilePath.Size = new Size(1020, 200);
listBox_FilePath.TabIndex = 2;
//
// button_SelectSkel
//
button_SelectSkel.Anchor = AnchorStyles.None;
button_SelectSkel.Location = new Point(3, 57);
button_SelectSkel.Name = "button_SelectSkel";
button_SelectSkel.Size = new Size(137, 34);
button_SelectSkel.TabIndex = 1;
button_SelectSkel.Text = "选择文件...";
button_SelectSkel.UseVisualStyleBackColor = true;
button_SelectSkel.Click += button_SelectSkel_Click;
//
// label_Tip
//
label_Tip.AutoSize = true;
label_Tip.Dock = DockStyle.Fill;
label_Tip.Location = new Point(146, 54);
label_Tip.Name = "label_Tip";
label_Tip.Size = new Size(877, 40);
label_Tip.TabIndex = 0;
label_Tip.Text = "已选择 0 个文件";
label_Tip.TextAlign = ContentAlignment.MiddleLeft;
//
// openFileDialog_Skel
//
openFileDialog_Skel.AddExtension = false;
openFileDialog_Skel.AddToRecent = false;
openFileDialog_Skel.Filter = "skel 文件 (*.skel; *.json)|*.skel;*.json|二进制文件 (*.skel)|*.skel|文本文件 (*.json)|*.json|所有文件 (*.*)|*.*";
openFileDialog_Skel.Multiselect = true;
openFileDialog_Skel.Title = "批量选择skel文件";
tableLayoutPanel1.SetColumnSpan(skelFileListBox, 2);
skelFileListBox.Dock = DockStyle.Fill;
skelFileListBox.Location = new Point(3, 57);
skelFileListBox.Name = "skelFileListBox";
skelFileListBox.Size = new Size(936, 276);
skelFileListBox.TabIndex = 15;
//
// BatchOpenSpineDialog
//
@@ -204,7 +166,7 @@
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
CancelButton = button_Cancel;
ClientSize = new Size(1126, 449);
ClientSize = new Size(1042, 472);
Controls.Add(panel);
FormBorderStyle = FormBorderStyle.FixedDialog;
Icon = (Icon)resources.GetObject("$this.Icon");
@@ -214,7 +176,6 @@
ShowInTaskbar = false;
StartPosition = FormStartPosition.CenterScreen;
Text = "批量打开骨骼";
Load += BatchOpenSpineDialog_Load;
panel.ResumeLayout(false);
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
@@ -225,15 +186,12 @@
#endregion
private Panel panel;
private TableLayoutPanel tableLayoutPanel1;
private Label label_Tip;
private ListBox listBox_FilePath;
private Button button_SelectSkel;
private TableLayoutPanel tableLayoutPanel2;
private Button button_Ok;
private Button button_Cancel;
private Label label3;
private ComboBox comboBox_Version;
private OpenFileDialog openFileDialog_Skel;
private Label label4;
private Controls.SkelFileListBox skelFileListBox;
}
}

View File

@@ -1,4 +1,5 @@
using SpineViewer.Spine;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -13,59 +14,48 @@ namespace SpineViewer.Dialogs
{
public partial class BatchOpenSpineDialog : Form
{
/// <summary>
/// 对话框结果, 取消时为 null
/// </summary>
public BatchOpenSpineDialogResult Result { get; private set; }
public BatchOpenSpineDialog()
{
InitializeComponent();
comboBox_Version.DataSource = VersionHelper.Versions.ToList();
comboBox_Version.DataSource = SpineHelper.Names.ToList();
comboBox_Version.DisplayMember = "Value";
comboBox_Version.ValueMember = "Key";
comboBox_Version.SelectedValue = Spine.Version.Auto;
}
private void BatchOpenSpineDialog_Load(object sender, EventArgs e)
{
button_SelectSkel_Click(sender, e);
}
private void button_SelectSkel_Click(object sender, EventArgs e)
{
if (openFileDialog_Skel.ShowDialog() == DialogResult.OK)
{
listBox_FilePath.Items.Clear();
foreach (var p in openFileDialog_Skel.FileNames)
listBox_FilePath.Items.Add(Path.GetFullPath(p));
label_Tip.Text = $"已选择 {listBox_FilePath.Items.Count} 个文件";
}
comboBox_Version.SelectedValue = SpineVersion.Auto;
}
private void button_Ok_Click(object sender, EventArgs e)
{
var version = (Spine.Version)comboBox_Version.SelectedValue;
var version = (SpineVersion)comboBox_Version.SelectedValue;
if (listBox_FilePath.Items.Count <= 0)
var items = skelFileListBox.Items;
if (items.Count <= 0)
{
MessageBox.Show("未选择任何文件", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info("未选择任何文件");
return;
}
foreach (string p in listBox_FilePath.Items)
foreach (string p in items)
{
if (!File.Exists(p))
{
MessageBox.Show($"{p}", "skel文件不存在", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{p}", "skel文件不存在");
return;
}
}
if (version != Spine.Version.Auto && !Spine.Spine.ImplementedVersions.Contains(version))
if (version != SpineVersion.Auto && !Spine.Spine.HasImplementation(version))
{
MessageBox.Show($"{version.String()} 版本尚未实现(咕咕咕~", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{version.GetName()} 版本尚未实现(咕咕咕~");
return;
}
Result = new(version, listBox_FilePath.Items.Cast<string>().ToArray());
Result = new(version, items.Cast<string>().ToArray());
DialogResult = DialogResult.OK;
}
@@ -75,9 +65,19 @@ namespace SpineViewer.Dialogs
}
}
public class BatchOpenSpineDialogResult(Spine.Version version, string[] skelPaths)
/// <summary>
/// 批量打开对话框结果
/// </summary>
public class BatchOpenSpineDialogResult(SpineVersion version, string[] skelPaths)
{
public Spine.Version Version { get; } = version;
public string[] SkelPaths { get; } = skelPaths;
/// <summary>
/// 版本
/// </summary>
public SpineVersion Version => version;
/// <summary>
/// 路径列表
/// </summary>
public string[] SkelPaths => skelPaths;
}
}

View File

@@ -117,9 +117,6 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="openFileDialog_Skel.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>92, 26</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>

View File

@@ -31,6 +31,7 @@
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ConvertFileFormatDialog));
panel = new Panel();
tableLayoutPanel1 = new TableLayoutPanel();
comboBox_TargetVersion = new ComboBox();
flowLayoutPanel_TargetFormat = new FlowLayoutPanel();
radioButton_BinaryTarget = new RadioButton();
radioButton_JsonTarget = new RadioButton();
@@ -41,19 +42,12 @@
tableLayoutPanel2 = new TableLayoutPanel();
button_Ok = new Button();
button_Cancel = new Button();
listBox_FilePath = new ListBox();
button_SelectSkel = new Button();
label_Tip = new Label();
label2 = new Label();
flowLayoutPanel_SourceFormat = new FlowLayoutPanel();
radioButton_BinarySource = new RadioButton();
radioButton_JsonSource = new RadioButton();
openFileDialog_Skel = new OpenFileDialog();
skelFileListBox = new SpineViewer.Controls.SkelFileListBox();
panel.SuspendLayout();
tableLayoutPanel1.SuspendLayout();
flowLayoutPanel_TargetFormat.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
flowLayoutPanel_SourceFormat.SuspendLayout();
SuspendLayout();
//
// panel
@@ -63,7 +57,7 @@
panel.Location = new Point(0, 0);
panel.Name = "panel";
panel.Padding = new Padding(50, 15, 50, 10);
panel.Size = new Size(1039, 530);
panel.Size = new Size(1051, 538);
panel.TabIndex = 2;
//
// tableLayoutPanel1
@@ -71,40 +65,48 @@
tableLayoutPanel1.ColumnCount = 2;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle());
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(flowLayoutPanel_TargetFormat, 1, 5);
tableLayoutPanel1.Controls.Add(label1, 0, 4);
tableLayoutPanel1.Controls.Add(comboBox_TargetVersion, 1, 3);
tableLayoutPanel1.Controls.Add(flowLayoutPanel_TargetFormat, 1, 4);
tableLayoutPanel1.Controls.Add(label1, 0, 3);
tableLayoutPanel1.Controls.Add(label4, 0, 0);
tableLayoutPanel1.Controls.Add(label3, 0, 3);
tableLayoutPanel1.Controls.Add(comboBox_SourceVersion, 1, 3);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 6);
tableLayoutPanel1.Controls.Add(listBox_FilePath, 0, 2);
tableLayoutPanel1.Controls.Add(button_SelectSkel, 0, 1);
tableLayoutPanel1.Controls.Add(label_Tip, 1, 1);
tableLayoutPanel1.Controls.Add(label2, 0, 5);
tableLayoutPanel1.Controls.Add(flowLayoutPanel_SourceFormat, 1, 4);
tableLayoutPanel1.Controls.Add(label3, 0, 2);
tableLayoutPanel1.Controls.Add(comboBox_SourceVersion, 1, 2);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 5);
tableLayoutPanel1.Controls.Add(label2, 0, 4);
tableLayoutPanel1.Controls.Add(skelFileListBox, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(50, 15);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 7;
tableLayoutPanel1.RowCount = 6;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Size = new Size(939, 505);
tableLayoutPanel1.Size = new Size(951, 513);
tableLayoutPanel1.TabIndex = 1;
//
// comboBox_TargetVersion
//
comboBox_TargetVersion.Anchor = AnchorStyles.Left;
comboBox_TargetVersion.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox_TargetVersion.FormattingEnabled = true;
comboBox_TargetVersion.Location = new Point(95, 365);
comboBox_TargetVersion.Name = "comboBox_TargetVersion";
comboBox_TargetVersion.Size = new Size(182, 32);
comboBox_TargetVersion.Sorted = true;
comboBox_TargetVersion.TabIndex = 21;
//
// flowLayoutPanel_TargetFormat
//
flowLayoutPanel_TargetFormat.AutoSize = true;
flowLayoutPanel_TargetFormat.Controls.Add(radioButton_BinaryTarget);
flowLayoutPanel_TargetFormat.Controls.Add(radioButton_JsonTarget);
flowLayoutPanel_TargetFormat.Dock = DockStyle.Fill;
flowLayoutPanel_TargetFormat.Location = new Point(146, 381);
flowLayoutPanel_TargetFormat.Location = new Point(95, 403);
flowLayoutPanel_TargetFormat.Name = "flowLayoutPanel_TargetFormat";
flowLayoutPanel_TargetFormat.Size = new Size(790, 34);
flowLayoutPanel_TargetFormat.Size = new Size(853, 34);
flowLayoutPanel_TargetFormat.TabIndex = 19;
//
// radioButton_BinaryTarget
@@ -116,7 +118,6 @@
radioButton_BinaryTarget.TabIndex = 17;
radioButton_BinaryTarget.Text = "二进制 (*.skel)";
radioButton_BinaryTarget.UseVisualStyleBackColor = true;
radioButton_BinaryTarget.CheckedChanged += radioButton_Target_CheckedChanged;
//
// radioButton_JsonTarget
//
@@ -129,17 +130,16 @@
radioButton_JsonTarget.TabStop = true;
radioButton_JsonTarget.Text = "文本 (*.json)";
radioButton_JsonTarget.UseVisualStyleBackColor = true;
radioButton_JsonTarget.CheckedChanged += radioButton_Target_CheckedChanged;
//
// label1
//
label1.Anchor = AnchorStyles.Right;
label1.AutoSize = true;
label1.Location = new Point(72, 346);
label1.Location = new Point(3, 369);
label1.Name = "label1";
label1.Size = new Size(68, 24);
label1.Size = new Size(86, 24);
label1.TabIndex = 15;
label1.Text = "源格式:";
label1.Text = "目标版本:";
//
// label4
//
@@ -149,7 +149,7 @@
label4.Location = new Point(15, 15);
label4.Margin = new Padding(15);
label4.Name = "label4";
label4.Size = new Size(909, 24);
label4.Size = new Size(921, 24);
label4.TabIndex = 14;
label4.Text = "说明:将在每个文件同级目录下生成目标格式后缀的文件,会覆盖已存在文件";
label4.TextAlign = ContentAlignment.MiddleCenter;
@@ -158,19 +158,19 @@
//
label3.Anchor = AnchorStyles.Right;
label3.AutoSize = true;
label3.Location = new Point(72, 307);
label3.Location = new Point(21, 331);
label3.Name = "label3";
label3.Size = new Size(68, 24);
label3.TabIndex = 12;
label3.Text = "源版本:";
//
// comboBox_Version
// comboBox_SourceVersion
//
comboBox_SourceVersion.Anchor = AnchorStyles.Left;
comboBox_SourceVersion.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox_SourceVersion.FormattingEnabled = true;
comboBox_SourceVersion.Location = new Point(146, 303);
comboBox_SourceVersion.Name = "comboBox_Version";
comboBox_SourceVersion.Location = new Point(95, 327);
comboBox_SourceVersion.Name = "comboBox_SourceVersion";
comboBox_SourceVersion.Size = new Size(182, 32);
comboBox_SourceVersion.Sorted = true;
comboBox_SourceVersion.TabIndex = 13;
@@ -185,18 +185,19 @@
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(button_Ok, 0, 0);
tableLayoutPanel2.Controls.Add(button_Cancel, 1, 0);
tableLayoutPanel2.Dock = DockStyle.Bottom;
tableLayoutPanel2.Location = new Point(3, 462);
tableLayoutPanel2.Dock = DockStyle.Fill;
tableLayoutPanel2.Location = new Point(3, 470);
tableLayoutPanel2.Margin = new Padding(3, 30, 3, 3);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 1;
tableLayoutPanel2.RowStyles.Add(new RowStyle());
tableLayoutPanel2.Size = new Size(933, 40);
tableLayoutPanel2.Size = new Size(945, 40);
tableLayoutPanel2.TabIndex = 11;
//
// button_Ok
//
button_Ok.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_Ok.Location = new Point(324, 3);
button_Ok.Location = new Point(330, 3);
button_Ok.Margin = new Padding(3, 3, 30, 3);
button_Ok.Name = "button_Ok";
button_Ok.Size = new Size(112, 34);
@@ -208,7 +209,7 @@
// button_Cancel
//
button_Cancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button_Cancel.Location = new Point(496, 3);
button_Cancel.Location = new Point(502, 3);
button_Cancel.Margin = new Padding(30, 3, 3, 3);
button_Cancel.Name = "button_Cancel";
button_Cancel.Size = new Size(112, 34);
@@ -217,92 +218,24 @@
button_Cancel.UseVisualStyleBackColor = true;
button_Cancel.Click += button_Cancel_Click;
//
// listBox_FilePath
//
tableLayoutPanel1.SetColumnSpan(listBox_FilePath, 2);
listBox_FilePath.Dock = DockStyle.Fill;
listBox_FilePath.FormattingEnabled = true;
listBox_FilePath.HorizontalScrollbar = true;
listBox_FilePath.ItemHeight = 24;
listBox_FilePath.Location = new Point(3, 97);
listBox_FilePath.Name = "listBox_FilePath";
listBox_FilePath.Size = new Size(933, 200);
listBox_FilePath.TabIndex = 2;
//
// button_SelectSkel
//
button_SelectSkel.Anchor = AnchorStyles.None;
button_SelectSkel.Location = new Point(3, 57);
button_SelectSkel.Name = "button_SelectSkel";
button_SelectSkel.Size = new Size(137, 34);
button_SelectSkel.TabIndex = 1;
button_SelectSkel.Text = "选择文件...";
button_SelectSkel.UseVisualStyleBackColor = true;
button_SelectSkel.Click += button_SelectSkel_Click;
//
// label_Tip
//
label_Tip.AutoSize = true;
label_Tip.Dock = DockStyle.Fill;
label_Tip.Location = new Point(146, 54);
label_Tip.Name = "label_Tip";
label_Tip.Size = new Size(790, 40);
label_Tip.TabIndex = 0;
label_Tip.Text = "已选择 0 个文件";
label_Tip.TextAlign = ContentAlignment.MiddleLeft;
//
// label2
//
label2.Anchor = AnchorStyles.Right;
label2.AutoSize = true;
label2.Location = new Point(54, 386);
label2.Location = new Point(3, 408);
label2.Name = "label2";
label2.Size = new Size(86, 24);
label2.TabIndex = 16;
label2.Text = "目标格式:";
//
// flowLayoutPanel_SourceFormat
// skelFileListBox
//
flowLayoutPanel_SourceFormat.AutoSize = true;
flowLayoutPanel_SourceFormat.Controls.Add(radioButton_BinarySource);
flowLayoutPanel_SourceFormat.Controls.Add(radioButton_JsonSource);
flowLayoutPanel_SourceFormat.Dock = DockStyle.Fill;
flowLayoutPanel_SourceFormat.Location = new Point(146, 341);
flowLayoutPanel_SourceFormat.Name = "flowLayoutPanel_SourceFormat";
flowLayoutPanel_SourceFormat.Size = new Size(790, 34);
flowLayoutPanel_SourceFormat.TabIndex = 18;
//
// radioButton_BinarySource
//
radioButton_BinarySource.AutoSize = true;
radioButton_BinarySource.Checked = true;
radioButton_BinarySource.Location = new Point(3, 3);
radioButton_BinarySource.Name = "radioButton_BinarySource";
radioButton_BinarySource.Size = new Size(151, 28);
radioButton_BinarySource.TabIndex = 17;
radioButton_BinarySource.TabStop = true;
radioButton_BinarySource.Text = "二进制 (*.skel)";
radioButton_BinarySource.UseVisualStyleBackColor = true;
radioButton_BinarySource.CheckedChanged += radioButton_Source_CheckedChanged;
//
// radioButton_JsonSource
//
radioButton_JsonSource.AutoSize = true;
radioButton_JsonSource.Location = new Point(160, 3);
radioButton_JsonSource.Name = "radioButton_JsonSource";
radioButton_JsonSource.Size = new Size(135, 28);
radioButton_JsonSource.TabIndex = 18;
radioButton_JsonSource.Text = "文本 (*.json)";
radioButton_JsonSource.UseVisualStyleBackColor = true;
radioButton_JsonSource.CheckedChanged += radioButton_Source_CheckedChanged;
//
// openFileDialog_Skel
//
openFileDialog_Skel.AddExtension = false;
openFileDialog_Skel.AddToRecent = false;
openFileDialog_Skel.Filter = "skel 文件 (*.skel; *.json)|*.skel;*.json|二进制文件 (*.skel)|*.skel|文本文件 (*.json)|*.json|所有文件 (*.*)|*.*";
openFileDialog_Skel.Multiselect = true;
openFileDialog_Skel.Title = "批量选择skel文件";
tableLayoutPanel1.SetColumnSpan(skelFileListBox, 2);
skelFileListBox.Dock = DockStyle.Fill;
skelFileListBox.Location = new Point(3, 57);
skelFileListBox.Name = "skelFileListBox";
skelFileListBox.Size = new Size(945, 264);
skelFileListBox.TabIndex = 20;
//
// ConvertFileFormatDialog
//
@@ -310,7 +243,7 @@
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
CancelButton = button_Cancel;
ClientSize = new Size(1039, 530);
ClientSize = new Size(1051, 538);
Controls.Add(panel);
FormBorderStyle = FormBorderStyle.FixedDialog;
Icon = (Icon)resources.GetObject("$this.Icon");
@@ -320,15 +253,12 @@
ShowInTaskbar = false;
StartPosition = FormStartPosition.CenterScreen;
Text = "骨骼文件格式转换";
Load += ConvertFileFormatDialog_Load;
panel.ResumeLayout(false);
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
flowLayoutPanel_TargetFormat.ResumeLayout(false);
flowLayoutPanel_TargetFormat.PerformLayout();
tableLayoutPanel2.ResumeLayout(false);
flowLayoutPanel_SourceFormat.ResumeLayout(false);
flowLayoutPanel_SourceFormat.PerformLayout();
ResumeLayout(false);
}
@@ -342,17 +272,12 @@
private TableLayoutPanel tableLayoutPanel2;
private Button button_Ok;
private Button button_Cancel;
private ListBox listBox_FilePath;
private Button button_SelectSkel;
private Label label_Tip;
private OpenFileDialog openFileDialog_Skel;
private Label label1;
private Label label2;
private RadioButton radioButton_BinarySource;
private FlowLayoutPanel flowLayoutPanel_SourceFormat;
private RadioButton radioButton_JsonSource;
private FlowLayoutPanel flowLayoutPanel_TargetFormat;
private RadioButton radioButton_BinaryTarget;
private RadioButton radioButton_JsonTarget;
private Controls.SkelFileListBox skelFileListBox;
private ComboBox comboBox_TargetVersion;
}
}

View File

@@ -1,4 +1,5 @@
using SpineViewer.Spine;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -13,92 +14,65 @@ namespace SpineViewer.Dialogs
{
public partial class ConvertFileFormatDialog : Form
{
public string[] SkelPaths { get; private set; }
public Spine.Version SourceVersion { get; private set; }
public Spine.Version TargetVersion { get; private set; }
public bool JsonSource { get; private set; }
public bool JsonTarget { get; private set; }
/// <summary>
/// 对话框结果, 取消时为 null
/// </summary>
public ConvertFileFormatDialogResult Result { get; private set; }
public ConvertFileFormatDialog()
{
InitializeComponent();
// XXX: 文件格式转换暂时不支持自动检测版本
var impVersions = VersionHelper.Versions.ToDictionary();
impVersions.Remove(Spine.Version.Auto);
comboBox_SourceVersion.DataSource = impVersions.ToList();
comboBox_SourceVersion.DataSource = SpineHelper.Names.ToList();
comboBox_SourceVersion.DisplayMember = "Value";
comboBox_SourceVersion.ValueMember = "Key";
comboBox_SourceVersion.SelectedValue = Spine.Version.V38;
//comboBox_TargetVersion.DataSource = VersionHelper.Versions.ToList();
//comboBox_TargetVersion.DisplayMember = "Value";
//comboBox_TargetVersion.ValueMember = "Key";
//comboBox_TargetVersion.SelectedValue = Spine.Version.V38;
}
comboBox_SourceVersion.SelectedValue = SpineVersion.Auto;
private void ConvertFileFormatDialog_Load(object sender, EventArgs e)
{
button_SelectSkel_Click(sender, e);
}
private void button_SelectSkel_Click(object sender, EventArgs e)
{
if (openFileDialog_Skel.ShowDialog() == DialogResult.OK)
{
listBox_FilePath.Items.Clear();
foreach (var p in openFileDialog_Skel.FileNames)
listBox_FilePath.Items.Add(Path.GetFullPath(p));
label_Tip.Text = $"已选择 {listBox_FilePath.Items.Count} 个文件";
}
// 目标版本不包含自动
var versionsWithoutAuto = SpineHelper.Names.ToDictionary();
versionsWithoutAuto.Remove(SpineVersion.Auto);
comboBox_TargetVersion.DataSource = versionsWithoutAuto.ToList();
comboBox_TargetVersion.DisplayMember = "Value";
comboBox_TargetVersion.ValueMember = "Key";
comboBox_TargetVersion.SelectedValue = SpineVersion.V38;
}
private void button_Ok_Click(object sender, EventArgs e)
{
var sourceVersion = (Spine.Version)comboBox_SourceVersion.SelectedValue;
var targetVersion = (Spine.Version)comboBox_SourceVersion.SelectedValue; // TODO: 增加目标版本
var jsonSource = radioButton_JsonSource.Checked;
var sourceVersion = (SpineVersion)comboBox_SourceVersion.SelectedValue;
var targetVersion = (SpineVersion)comboBox_TargetVersion.SelectedValue;
var jsonTarget = radioButton_JsonTarget.Checked;
if (listBox_FilePath.Items.Count <= 0)
var items = skelFileListBox.Items;
if (items.Count <= 0)
{
MessageBox.Show("未选择任何文件", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info("未选择任何文件");
return;
}
foreach (string p in listBox_FilePath.Items)
foreach (string p in items)
{
if (!File.Exists(p))
{
MessageBox.Show($"{p}", "skel文件不存在", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{p}", "skel文件不存在");
return;
}
}
if (!SkeletonConverter.ImplementedVersions.Contains(sourceVersion))
if (sourceVersion != SpineVersion.Auto && !SkeletonConverter.HasImplementation(sourceVersion))
{
MessageBox.Show($"{sourceVersion.String()} 版本尚未实现(咕咕咕~", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{sourceVersion.GetName()} 版本尚未实现(咕咕咕~");
return;
}
if (!SkeletonConverter.ImplementedVersions.Contains(targetVersion))
if (!SkeletonConverter.HasImplementation(targetVersion))
{
MessageBox.Show($"{targetVersion.String()} 版本尚未实现(咕咕咕~", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{targetVersion.GetName()} 版本尚未实现(咕咕咕~");
return;
}
if (jsonSource == jsonTarget && sourceVersion == targetVersion)
{
MessageBox.Show($"不需要转换相同的格式和版本", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
SkelPaths = listBox_FilePath.Items.Cast<string>().ToArray();
SourceVersion = sourceVersion;
TargetVersion = targetVersion;
JsonSource = jsonSource;
JsonTarget = jsonTarget;
Result = new(items.Cast<string>().ToArray(), sourceVersion, targetVersion, jsonTarget);
DialogResult = DialogResult.OK;
}
@@ -106,21 +80,31 @@ namespace SpineViewer.Dialogs
{
DialogResult = DialogResult.Cancel;
}
}
private void radioButton_Source_CheckedChanged(object sender, EventArgs e)
{
if (radioButton_BinarySource.Checked)
radioButton_JsonTarget.Checked = true;
else
radioButton_BinaryTarget.Checked = true;
}
/// <summary>
/// 文件格式转换对话框结果包装类
/// </summary>
public class ConvertFileFormatDialogResult(string[] skelPaths, SpineVersion sourceVersion, SpineVersion targetVersion, bool jsonTarget)
{
/// <summary>
/// 骨骼文件路径列表
/// </summary>
public string[] SkelPaths => skelPaths;
private void radioButton_Target_CheckedChanged(object sender, EventArgs e)
{
if (radioButton_BinaryTarget.Checked)
radioButton_JsonSource.Checked = true;
else
radioButton_BinarySource.Checked = true;
}
/// <summary>
/// 源版本
/// </summary>
public SpineVersion SourceVersion => sourceVersion;
/// <summary>
/// 目标版本
/// </summary>
public SpineVersion TargetVersion => targetVersion;
/// <summary>
/// 目标格式是否为 Json
/// </summary>
public bool JsonTarget => jsonTarget;
}
}

View File

@@ -117,9 +117,6 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="openFileDialog_Skel.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>92, 26</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>

View File

@@ -1,4 +1,5 @@
using Microsoft.Win32;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -26,7 +27,29 @@ namespace SpineViewer.Dialogs
private class DiagnosticsInformation
{
[Category("Versions")]
[Category("Hardware")]
public string CPU
{
get => Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString", "Unknown").ToString();
}
[Category("Hardware")]
public string Memory
{
get => $"{new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024f / 1024f / 1024f:F1} GB";
}
[Category("Hardware")]
public string GPU
{
get
{
var searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_VideoController");
return string.Join("; ", searcher.Get().Cast<ManagementObject>().Select(mo => mo["Name"].ToString()));
}
}
[Category("Software")]
public string WindowsVersion
{
get
@@ -39,54 +62,38 @@ namespace SpineViewer.Dialogs
}
}
[Category("Versions")]
[Category("Software")]
public string Version
{
get => Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
}
[Category("Versions")]
[Category("Software")]
public string DotNetVersion
{
get => Environment.Version.ToString();
}
[Category("Versions")]
[Category("Software")]
public string SFMLVersion
{
get => typeof(SFML.ObjectBase).Assembly.GetName().Version.ToString();
}
[Category("Hardwares")]
public string CPU
[Category("Software")]
public string FFMpegCoreVersion
{
get => Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString", "Unknown").ToString();
}
[Category("Hardwares")]
public string Memory
{
get => $"{new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / 1024f / 1024f / 1024f:F1} GB";
}
[Category("Hardwares")]
public string GPU
{
get
{
var searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_VideoController");
return string.Join("; ", searcher.Get().Cast<ManagementObject>().Select(mo => mo["Name"].ToString()));
}
get => typeof(FFMpegCore.FFMpeg).Assembly.GetName().Version.ToString();
}
}
private void button_Copy_Click(object sender, EventArgs e)
{
var selectedObject = propertyGrid.SelectedObject as DiagnosticsInformation;
var selectedObject = (DiagnosticsInformation)propertyGrid.SelectedObject;
var properties = selectedObject.GetType().GetProperties();
var result = string.Join(Environment.NewLine, properties.Select(p => $"{p.Name}\t{p.GetValue(selectedObject)?.ToString()}"));
Clipboard.SetText(result);
MessageBox.Show(this, "已复制", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info("已复制");
}
}
}

View File

@@ -0,0 +1,155 @@
namespace SpineViewer.Dialogs
{
partial class ExportDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExportDialog));
panel1 = new Panel();
tableLayoutPanel1 = new TableLayoutPanel();
propertyGrid_ExportArgs = new PropertyGrid();
tableLayoutPanel2 = new TableLayoutPanel();
button_Ok = new Button();
button_Cancel = new Button();
panel1.SuspendLayout();
tableLayoutPanel1.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(tableLayoutPanel1);
panel1.Dock = DockStyle.Fill;
panel1.Location = new Point(0, 0);
panel1.Name = "panel1";
panel1.Padding = new Padding(50, 15, 50, 10);
panel1.Size = new Size(793, 754);
panel1.TabIndex = 2;
//
// tableLayoutPanel1
//
tableLayoutPanel1.AutoSize = true;
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(propertyGrid_ExportArgs, 0, 0);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(50, 15);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 20F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 20F));
tableLayoutPanel1.Size = new Size(693, 729);
tableLayoutPanel1.TabIndex = 0;
//
// propertyGrid_ExportArgs
//
propertyGrid_ExportArgs.Dock = DockStyle.Fill;
propertyGrid_ExportArgs.Location = new Point(3, 3);
propertyGrid_ExportArgs.Name = "propertyGrid_ExportArgs";
propertyGrid_ExportArgs.PropertySort = PropertySort.Categorized;
propertyGrid_ExportArgs.Size = new Size(687, 650);
propertyGrid_ExportArgs.TabIndex = 1;
propertyGrid_ExportArgs.ToolbarVisible = false;
//
// tableLayoutPanel2
//
tableLayoutPanel2.AutoSize = true;
tableLayoutPanel2.AutoSizeMode = AutoSizeMode.GrowAndShrink;
tableLayoutPanel2.ColumnCount = 2;
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(button_Ok, 0, 0);
tableLayoutPanel2.Controls.Add(button_Cancel, 1, 0);
tableLayoutPanel2.Dock = DockStyle.Bottom;
tableLayoutPanel2.Location = new Point(3, 686);
tableLayoutPanel2.Margin = new Padding(3, 30, 3, 3);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 1;
tableLayoutPanel2.RowStyles.Add(new RowStyle());
tableLayoutPanel2.Size = new Size(687, 40);
tableLayoutPanel2.TabIndex = 10;
//
// button_Ok
//
button_Ok.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_Ok.Location = new Point(201, 3);
button_Ok.Margin = new Padding(3, 3, 30, 3);
button_Ok.Name = "button_Ok";
button_Ok.Size = new Size(112, 34);
button_Ok.TabIndex = 7;
button_Ok.Text = "确认";
button_Ok.UseVisualStyleBackColor = true;
button_Ok.Click += button_Ok_Click;
//
// button_Cancel
//
button_Cancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button_Cancel.Location = new Point(373, 3);
button_Cancel.Margin = new Padding(30, 3, 3, 3);
button_Cancel.Name = "button_Cancel";
button_Cancel.Size = new Size(112, 34);
button_Cancel.TabIndex = 8;
button_Cancel.Text = "取消";
button_Cancel.UseVisualStyleBackColor = true;
button_Cancel.Click += button_Cancel_Click;
//
// ExportDialog
//
AcceptButton = button_Ok;
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
CancelButton = button_Cancel;
ClientSize = new Size(793, 754);
Controls.Add(panel1);
Icon = (Icon)resources.GetObject("$this.Icon");
MaximizeBox = false;
MinimizeBox = false;
Name = "ExportDialog";
ShowInTaskbar = false;
StartPosition = FormStartPosition.CenterScreen;
Text = "导出参数";
panel1.ResumeLayout(false);
panel1.PerformLayout();
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
tableLayoutPanel2.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private Panel panel1;
private TableLayoutPanel tableLayoutPanel1;
private TableLayoutPanel tableLayoutPanel2;
private Button button_Ok;
private Button button_Cancel;
private PropertyGrid propertyGrid_ExportArgs;
}
}

View File

@@ -0,0 +1,79 @@
using SpineViewer.PropertyGridWrappers.Exporter;
using SpineViewer.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace SpineViewer.Dialogs
{
public partial class ExportDialog : Form
{
private readonly ExporterWrapper wrapper;
public ExportDialog(ExporterWrapper wrapper)
{
InitializeComponent();
this.wrapper = wrapper;
propertyGrid_ExportArgs.SelectedObject = wrapper;
#region XXX:
var categories = propertyGrid_ExportArgs.SelectedGridItem?.Parent?.Parent?.GridItems;
if (categories is null) return;
foreach (var category in categories)
{
// 查找 "导出" 分组
if (category == null) continue;
PropertyInfo? labelProp = category.GetType().GetProperty("Label", BindingFlags.Instance | BindingFlags.Public);
if (labelProp == null) continue;
string? label = labelProp.GetValue(category) as string;
if (label != "[0] 导出") continue;
// 获取该分组下的所有属性项
PropertyInfo? gridItemsProp = category.GetType().GetProperty("GridItems", BindingFlags.Instance | BindingFlags.Public);
if (gridItemsProp == null) continue;
var gridItemsObj = gridItemsProp.GetValue(category);
if (gridItemsObj is not IEnumerable gridItems) continue;
foreach (object item in gridItems)
{
if (item == null) continue;
PropertyInfo? propDescProp = item.GetType().GetProperty("PropertyDescriptor", BindingFlags.Instance | BindingFlags.Public);
if (propDescProp == null) continue;
var propDesc = propDescProp.GetValue(item) as PropertyDescriptor;
if (propDesc == null) continue;
if (propDesc.Name == "OutputDir")
{
if (item is GridItem gridItem)
propertyGrid_ExportArgs.SelectedGridItem = gridItem; // 找到后,将此项设为选中项
else
propertyGrid_ExportArgs.SelectedGridItem = (GridItem)item; // 如果转换失败,则尝试直接赋值
}
return; // 设置成功后退出
}
}
#endregion
}
private void button_Ok_Click(object sender, EventArgs e)
{
if (wrapper.Exporter.Validate() is string error)
{
MessagePopup.Info(error, "参数错误");
return;
}
DialogResult = DialogResult.OK;
}
private void button_Cancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}

View File

@@ -117,9 +117,6 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="folderBrowserDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="$this.Icon" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>

View File

@@ -1,270 +0,0 @@
namespace SpineViewer.Dialogs
{
partial class ExportPngDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExportPngDialog));
panel1 = new Panel();
tableLayoutPanel1 = new TableLayoutPanel();
label4 = new Label();
label1 = new Label();
label2 = new Label();
label3 = new Label();
textBox_OutputDir = new TextBox();
button_SelectOutputDir = new Button();
tableLayoutPanel2 = new TableLayoutPanel();
button_Ok = new Button();
button_Cancel = new Button();
numericUpDown_Duration = new NumericUpDown();
numericUpDown_Fps = new NumericUpDown();
folderBrowserDialog = new FolderBrowserDialog();
panel1.SuspendLayout();
tableLayoutPanel1.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDown_Duration).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDown_Fps).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(tableLayoutPanel1);
panel1.Dock = DockStyle.Fill;
panel1.Location = new Point(0, 0);
panel1.Name = "panel1";
panel1.Padding = new Padding(50, 15, 50, 10);
panel1.Size = new Size(919, 276);
panel1.TabIndex = 1;
//
// tableLayoutPanel1
//
tableLayoutPanel1.AutoSize = true;
tableLayoutPanel1.ColumnCount = 4;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle());
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle());
tableLayoutPanel1.Controls.Add(label4, 0, 0);
tableLayoutPanel1.Controls.Add(label1, 0, 1);
tableLayoutPanel1.Controls.Add(label2, 0, 2);
tableLayoutPanel1.Controls.Add(label3, 0, 3);
tableLayoutPanel1.Controls.Add(textBox_OutputDir, 1, 1);
tableLayoutPanel1.Controls.Add(button_SelectOutputDir, 3, 1);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 4);
tableLayoutPanel1.Controls.Add(numericUpDown_Duration, 1, 2);
tableLayoutPanel1.Controls.Add(numericUpDown_Fps, 1, 3);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(50, 15);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 5;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Size = new Size(819, 251);
tableLayoutPanel1.TabIndex = 0;
//
// label4
//
label4.AutoSize = true;
tableLayoutPanel1.SetColumnSpan(label4, 4);
label4.Dock = DockStyle.Fill;
label4.Location = new Point(15, 15);
label4.Margin = new Padding(15);
label4.Name = "label4";
label4.Size = new Size(789, 24);
label4.TabIndex = 11;
label4.Text = "说明:时长不足一帧时仅导出第一帧";
label4.TextAlign = ContentAlignment.MiddleCenter;
//
// label1
//
label1.Anchor = AnchorStyles.Right;
label1.AutoSize = true;
label1.Location = new Point(3, 62);
label1.Name = "label1";
label1.Size = new Size(104, 24);
label1.TabIndex = 0;
label1.Text = "输出文件夹:";
//
// label2
//
label2.Anchor = AnchorStyles.Right;
label2.AutoSize = true;
label2.Location = new Point(57, 100);
label2.Name = "label2";
label2.Size = new Size(50, 24);
label2.TabIndex = 1;
label2.Text = "时长:";
//
// label3
//
label3.Anchor = AnchorStyles.Right;
label3.AutoSize = true;
label3.Location = new Point(57, 136);
label3.Name = "label3";
label3.Size = new Size(50, 24);
label3.TabIndex = 2;
label3.Text = "帧率:";
//
// textBox_OutputDir
//
tableLayoutPanel1.SetColumnSpan(textBox_OutputDir, 2);
textBox_OutputDir.Dock = DockStyle.Fill;
textBox_OutputDir.Location = new Point(113, 57);
textBox_OutputDir.Name = "textBox_OutputDir";
textBox_OutputDir.Size = new Size(664, 30);
textBox_OutputDir.TabIndex = 3;
//
// button_SelectOutputDir
//
button_SelectOutputDir.AutoSize = true;
button_SelectOutputDir.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_SelectOutputDir.Location = new Point(783, 57);
button_SelectOutputDir.Name = "button_SelectOutputDir";
button_SelectOutputDir.Size = new Size(32, 34);
button_SelectOutputDir.TabIndex = 5;
button_SelectOutputDir.Text = "...";
button_SelectOutputDir.UseVisualStyleBackColor = true;
button_SelectOutputDir.Click += button_SelectOutputDir_Click;
//
// tableLayoutPanel2
//
tableLayoutPanel2.AutoSize = true;
tableLayoutPanel2.AutoSizeMode = AutoSizeMode.GrowAndShrink;
tableLayoutPanel2.ColumnCount = 2;
tableLayoutPanel1.SetColumnSpan(tableLayoutPanel2, 4);
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(button_Ok, 0, 0);
tableLayoutPanel2.Controls.Add(button_Cancel, 1, 0);
tableLayoutPanel2.Dock = DockStyle.Bottom;
tableLayoutPanel2.Location = new Point(3, 208);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 1;
tableLayoutPanel2.RowStyles.Add(new RowStyle());
tableLayoutPanel2.Size = new Size(813, 40);
tableLayoutPanel2.TabIndex = 10;
//
// button_Ok
//
button_Ok.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_Ok.Location = new Point(264, 3);
button_Ok.Margin = new Padding(3, 3, 30, 3);
button_Ok.Name = "button_Ok";
button_Ok.Size = new Size(112, 34);
button_Ok.TabIndex = 7;
button_Ok.Text = "确认";
button_Ok.UseVisualStyleBackColor = true;
button_Ok.Click += button_Ok_Click;
//
// button_Cancel
//
button_Cancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button_Cancel.Location = new Point(436, 3);
button_Cancel.Margin = new Padding(30, 3, 3, 3);
button_Cancel.Name = "button_Cancel";
button_Cancel.Size = new Size(112, 34);
button_Cancel.TabIndex = 8;
button_Cancel.Text = "取消";
button_Cancel.UseVisualStyleBackColor = true;
button_Cancel.Click += button_Cancel_Click;
//
// numericUpDown_Duration
//
numericUpDown_Duration.Anchor = AnchorStyles.Left;
numericUpDown_Duration.DecimalPlaces = 3;
numericUpDown_Duration.Location = new Point(113, 97);
numericUpDown_Duration.Maximum = new decimal(new int[] { 300, 0, 0, 0 });
numericUpDown_Duration.Name = "numericUpDown_Duration";
numericUpDown_Duration.Size = new Size(180, 30);
numericUpDown_Duration.TabIndex = 12;
numericUpDown_Duration.TextAlign = HorizontalAlignment.Right;
numericUpDown_Duration.Value = new decimal(new int[] { 1, 0, 0, 0 });
//
// numericUpDown_Fps
//
numericUpDown_Fps.Anchor = AnchorStyles.Left;
numericUpDown_Fps.Location = new Point(113, 133);
numericUpDown_Fps.Maximum = new decimal(new int[] { 300, 0, 0, 0 });
numericUpDown_Fps.Minimum = new decimal(new int[] { 1, 0, 0, 0 });
numericUpDown_Fps.Name = "numericUpDown_Fps";
numericUpDown_Fps.Size = new Size(180, 30);
numericUpDown_Fps.TabIndex = 13;
numericUpDown_Fps.TextAlign = HorizontalAlignment.Right;
numericUpDown_Fps.Value = new decimal(new int[] { 60, 0, 0, 0 });
//
// folderBrowserDialog
//
folderBrowserDialog.AddToRecent = false;
//
// ExportPngDialog
//
AcceptButton = button_Ok;
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
CancelButton = button_Cancel;
ClientSize = new Size(919, 276);
Controls.Add(panel1);
FormBorderStyle = FormBorderStyle.FixedDialog;
Icon = (Icon)resources.GetObject("$this.Icon");
MaximizeBox = false;
MinimizeBox = false;
Name = "ExportPngDialog";
ShowInTaskbar = false;
StartPosition = FormStartPosition.CenterScreen;
Text = "导出PNG序列";
Load += ExportPngDialog_Load;
panel1.ResumeLayout(false);
panel1.PerformLayout();
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
tableLayoutPanel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDown_Duration).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDown_Fps).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private TableLayoutPanel tableLayoutPanel1;
private Label label4;
private Label label1;
private Label label2;
private Label label3;
private TextBox textBox_OutputDir;
private Button button_SelectOutputDir;
private TableLayoutPanel tableLayoutPanel2;
private Button button_Ok;
private Button button_Cancel;
private NumericUpDown numericUpDown_Duration;
private NumericUpDown numericUpDown_Fps;
private FolderBrowserDialog folderBrowserDialog;
}
}

View File

@@ -1,80 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpineViewer.Dialogs
{
public partial class ExportPngDialog : Form
{
public string OutputDir { get; private set; }
public float Duration { get; private set; }
public uint Fps { get; private set; }
public ExportPngDialog()
{
InitializeComponent();
}
private void ExportPngDialog_Load(object sender, EventArgs e)
{
button_SelectOutputDir_Click(sender, e);
}
private void button_SelectOutputDir_Click(object sender, EventArgs e)
{
folderBrowserDialog.InitialDirectory = textBox_OutputDir.Text;
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
textBox_OutputDir.Text = Path.GetFullPath(folderBrowserDialog.SelectedPath);
}
}
private void button_Ok_Click(object sender, EventArgs e)
{
var outputDir = textBox_OutputDir.Text;
if (File.Exists(outputDir))
{
MessageBox.Show("输出文件夹无效", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (!Directory.Exists(outputDir))
{
if (MessageBox.Show($"文件夹 {outputDir} 不存在,是否创建?", "操作确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
try
{
Directory.CreateDirectory(outputDir);
}
catch (Exception ex)
{
Program.Logger.Error(ex.ToString());
MessageBox.Show(ex.ToString(), "文件夹创建失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
return;
}
}
OutputDir = Path.GetFullPath(outputDir);
Duration = (float)numericUpDown_Duration.Value;
Fps = (uint)numericUpDown_Fps.Value;
DialogResult = DialogResult.OK;
}
private void button_Cancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,270 +0,0 @@
namespace SpineViewer.Dialogs
{
partial class ExportPreviewDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExportPreviewDialog));
panel1 = new Panel();
tableLayoutPanel1 = new TableLayoutPanel();
label4 = new Label();
label1 = new Label();
label2 = new Label();
label3 = new Label();
textBox_OutputDir = new TextBox();
button_SelectOutputDir = new Button();
tableLayoutPanel2 = new TableLayoutPanel();
button_Ok = new Button();
button_Cancel = new Button();
numericUpDown_Width = new NumericUpDown();
numericUpDown_Height = new NumericUpDown();
folderBrowserDialog = new FolderBrowserDialog();
panel1.SuspendLayout();
tableLayoutPanel1.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDown_Width).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDown_Height).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(tableLayoutPanel1);
panel1.Dock = DockStyle.Fill;
panel1.Location = new Point(0, 0);
panel1.Name = "panel1";
panel1.Padding = new Padding(50, 15, 50, 10);
panel1.Size = new Size(919, 276);
panel1.TabIndex = 2;
//
// tableLayoutPanel1
//
tableLayoutPanel1.AutoSize = true;
tableLayoutPanel1.ColumnCount = 4;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle());
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle());
tableLayoutPanel1.Controls.Add(label4, 0, 0);
tableLayoutPanel1.Controls.Add(label1, 0, 1);
tableLayoutPanel1.Controls.Add(label2, 0, 2);
tableLayoutPanel1.Controls.Add(label3, 0, 3);
tableLayoutPanel1.Controls.Add(textBox_OutputDir, 1, 1);
tableLayoutPanel1.Controls.Add(button_SelectOutputDir, 3, 1);
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 4);
tableLayoutPanel1.Controls.Add(numericUpDown_Width, 1, 2);
tableLayoutPanel1.Controls.Add(numericUpDown_Height, 1, 3);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(50, 15);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 5;
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Size = new Size(819, 251);
tableLayoutPanel1.TabIndex = 0;
//
// label4
//
label4.AutoSize = true;
tableLayoutPanel1.SetColumnSpan(label4, 4);
label4.Dock = DockStyle.Fill;
label4.Location = new Point(15, 15);
label4.Margin = new Padding(15);
label4.Name = "label4";
label4.Size = new Size(789, 24);
label4.TabIndex = 11;
label4.Text = "说明:导出的文件名与骨骼文件名相同";
label4.TextAlign = ContentAlignment.MiddleCenter;
//
// label1
//
label1.Anchor = AnchorStyles.Right;
label1.AutoSize = true;
label1.Location = new Point(3, 62);
label1.Name = "label1";
label1.Size = new Size(104, 24);
label1.TabIndex = 0;
label1.Text = "输出文件夹:";
//
// label2
//
label2.Anchor = AnchorStyles.Right;
label2.AutoSize = true;
label2.Location = new Point(75, 100);
label2.Name = "label2";
label2.Size = new Size(32, 24);
label2.TabIndex = 1;
label2.Text = "宽:";
//
// label3
//
label3.Anchor = AnchorStyles.Right;
label3.AutoSize = true;
label3.Location = new Point(75, 136);
label3.Name = "label3";
label3.Size = new Size(32, 24);
label3.TabIndex = 2;
label3.Text = "高:";
//
// textBox_OutputDir
//
tableLayoutPanel1.SetColumnSpan(textBox_OutputDir, 2);
textBox_OutputDir.Dock = DockStyle.Fill;
textBox_OutputDir.Location = new Point(113, 57);
textBox_OutputDir.Name = "textBox_OutputDir";
textBox_OutputDir.Size = new Size(664, 30);
textBox_OutputDir.TabIndex = 3;
//
// button_SelectOutputDir
//
button_SelectOutputDir.AutoSize = true;
button_SelectOutputDir.AutoSizeMode = AutoSizeMode.GrowAndShrink;
button_SelectOutputDir.Location = new Point(783, 57);
button_SelectOutputDir.Name = "button_SelectOutputDir";
button_SelectOutputDir.Size = new Size(32, 34);
button_SelectOutputDir.TabIndex = 5;
button_SelectOutputDir.Text = "...";
button_SelectOutputDir.UseVisualStyleBackColor = true;
button_SelectOutputDir.Click += button_SelectOutputDir_Click;
//
// tableLayoutPanel2
//
tableLayoutPanel2.AutoSize = true;
tableLayoutPanel2.AutoSizeMode = AutoSizeMode.GrowAndShrink;
tableLayoutPanel2.ColumnCount = 2;
tableLayoutPanel1.SetColumnSpan(tableLayoutPanel2, 4);
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(button_Ok, 0, 0);
tableLayoutPanel2.Controls.Add(button_Cancel, 1, 0);
tableLayoutPanel2.Dock = DockStyle.Bottom;
tableLayoutPanel2.Location = new Point(3, 208);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 1;
tableLayoutPanel2.RowStyles.Add(new RowStyle());
tableLayoutPanel2.Size = new Size(813, 40);
tableLayoutPanel2.TabIndex = 10;
//
// button_Ok
//
button_Ok.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_Ok.Location = new Point(264, 3);
button_Ok.Margin = new Padding(3, 3, 30, 3);
button_Ok.Name = "button_Ok";
button_Ok.Size = new Size(112, 34);
button_Ok.TabIndex = 7;
button_Ok.Text = "确认";
button_Ok.UseVisualStyleBackColor = true;
button_Ok.Click += button_Ok_Click;
//
// button_Cancel
//
button_Cancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
button_Cancel.Location = new Point(436, 3);
button_Cancel.Margin = new Padding(30, 3, 3, 3);
button_Cancel.Name = "button_Cancel";
button_Cancel.Size = new Size(112, 34);
button_Cancel.TabIndex = 8;
button_Cancel.Text = "取消";
button_Cancel.UseVisualStyleBackColor = true;
button_Cancel.Click += button_Cancel_Click;
//
// numericUpDown_Width
//
numericUpDown_Width.Anchor = AnchorStyles.Left;
numericUpDown_Width.Location = new Point(113, 97);
numericUpDown_Width.Maximum = new decimal(new int[] { 4096, 0, 0, 0 });
numericUpDown_Width.Minimum = new decimal(new int[] { 32, 0, 0, 0 });
numericUpDown_Width.Name = "numericUpDown_Width";
numericUpDown_Width.Size = new Size(180, 30);
numericUpDown_Width.TabIndex = 12;
numericUpDown_Width.TextAlign = HorizontalAlignment.Right;
numericUpDown_Width.Value = new decimal(new int[] { 256, 0, 0, 0 });
//
// numericUpDown_Height
//
numericUpDown_Height.Anchor = AnchorStyles.Left;
numericUpDown_Height.Location = new Point(113, 133);
numericUpDown_Height.Maximum = new decimal(new int[] { 4096, 0, 0, 0 });
numericUpDown_Height.Minimum = new decimal(new int[] { 32, 0, 0, 0 });
numericUpDown_Height.Name = "numericUpDown_Height";
numericUpDown_Height.Size = new Size(180, 30);
numericUpDown_Height.TabIndex = 13;
numericUpDown_Height.TextAlign = HorizontalAlignment.Right;
numericUpDown_Height.Value = new decimal(new int[] { 256, 0, 0, 0 });
//
// folderBrowserDialog
//
folderBrowserDialog.AddToRecent = false;
//
// ExportPreviewDialog
//
AcceptButton = button_Ok;
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
CancelButton = button_Cancel;
ClientSize = new Size(919, 276);
Controls.Add(panel1);
FormBorderStyle = FormBorderStyle.FixedDialog;
Icon = (Icon)resources.GetObject("$this.Icon");
MaximizeBox = false;
MinimizeBox = false;
Name = "ExportPreviewDialog";
ShowInTaskbar = false;
StartPosition = FormStartPosition.CenterScreen;
Text = "导出预览图";
Load += ExportPreviewDialog_Load;
panel1.ResumeLayout(false);
panel1.PerformLayout();
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
tableLayoutPanel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)numericUpDown_Width).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDown_Height).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private TableLayoutPanel tableLayoutPanel1;
private Label label4;
private Label label1;
private Label label2;
private Label label3;
private TextBox textBox_OutputDir;
private Button button_SelectOutputDir;
private TableLayoutPanel tableLayoutPanel2;
private Button button_Ok;
private Button button_Cancel;
private NumericUpDown numericUpDown_Width;
private NumericUpDown numericUpDown_Height;
private FolderBrowserDialog folderBrowserDialog;
}
}

View File

@@ -1,80 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpineViewer.Dialogs
{
public partial class ExportPreviewDialog: Form
{
public string OutputDir { get; private set; }
public uint PreviewWidth { get; private set; }
public uint PreviewHeight { get; private set; }
public ExportPreviewDialog()
{
InitializeComponent();
}
private void ExportPreviewDialog_Load(object sender, EventArgs e)
{
button_SelectOutputDir_Click(sender, e);
}
private void button_SelectOutputDir_Click(object sender, EventArgs e)
{
folderBrowserDialog.InitialDirectory = textBox_OutputDir.Text;
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
textBox_OutputDir.Text = Path.GetFullPath(folderBrowserDialog.SelectedPath);
}
}
private void button_Ok_Click(object sender, EventArgs e)
{
var outputDir = textBox_OutputDir.Text;
if (File.Exists(outputDir))
{
MessageBox.Show("输出文件夹无效", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (!Directory.Exists(outputDir))
{
if (MessageBox.Show($"文件夹 {outputDir} 不存在,是否创建?", "操作确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
try
{
Directory.CreateDirectory(outputDir);
}
catch (Exception ex)
{
Program.Logger.Error(ex.ToString());
MessageBox.Show(ex.ToString(), "文件夹创建失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
return;
}
}
OutputDir = Path.GetFullPath(outputDir);
PreviewWidth = (uint)numericUpDown_Width.Value;
PreviewHeight = (uint)numericUpDown_Height.Value;
DialogResult = DialogResult.OK;
}
private void button_Cancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}

View File

@@ -1,4 +1,5 @@
using SpineViewer.Spine;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -12,15 +13,18 @@ namespace SpineViewer.Dialogs
{
public partial class OpenSpineDialog : Form
{
/// <summary>
/// 对话框结果
/// </summary>
public OpenSpineDialogResult Result { get; private set; }
public OpenSpineDialog()
{
InitializeComponent();
comboBox_Version.DataSource = VersionHelper.Versions.ToList();
comboBox_Version.DataSource = SpineHelper.Names.ToList();
comboBox_Version.DisplayMember = "Value";
comboBox_Version.ValueMember = "Key";
comboBox_Version.SelectedValue = Spine.Version.Auto;
comboBox_Version.SelectedValue = SpineVersion.Auto;
}
private void OpenSpineDialog_Load(object sender, EventArgs e)
@@ -50,11 +54,11 @@ namespace SpineViewer.Dialogs
{
var skelPath = textBox_SkelPath.Text;
var atlasPath = textBox_AtlasPath.Text;
var version = (Spine.Version)comboBox_Version.SelectedValue;
var version = (SpineVersion)comboBox_Version.SelectedValue;
if (!File.Exists(skelPath))
{
MessageBox.Show($"{skelPath}", "skel文件不存在", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{skelPath}", "skel文件不存在");
return;
}
else
@@ -62,13 +66,13 @@ namespace SpineViewer.Dialogs
skelPath = Path.GetFullPath(skelPath);
}
if (string.IsNullOrEmpty(atlasPath))
if (string.IsNullOrWhiteSpace(atlasPath))
{
atlasPath = null;
}
else if (!File.Exists(atlasPath))
{
MessageBox.Show($"{atlasPath}", "atlas文件不存在", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{atlasPath}", "atlas文件不存在");
return;
}
else
@@ -76,9 +80,9 @@ namespace SpineViewer.Dialogs
atlasPath = Path.GetFullPath(atlasPath);
}
if (version != Spine.Version.Auto && !Spine.Spine.ImplementedVersions.Contains(version))
if (version != SpineVersion.Auto && !Spine.Spine.HasImplementation(version))
{
MessageBox.Show($"{version.String()} 版本尚未实现(咕咕咕~", "错误信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessagePopup.Info($"{version.GetName()} 版本尚未实现(咕咕咕~");
return;
}
@@ -92,10 +96,24 @@ namespace SpineViewer.Dialogs
}
}
public class OpenSpineDialogResult(Spine.Version version, string skelPath, string? atlasPath = null)
/// <summary>
/// 打开骨骼对话框结果
/// </summary>
public class OpenSpineDialogResult(SpineVersion version, string skelPath, string? atlasPath = null)
{
public Spine.Version Version { get; } = version;
public string SkelPath { get; } = skelPath;
public string? AtlasPath { get; } = atlasPath;
/// <summary>
/// 版本
/// </summary>
public SpineVersion Version => version;
/// <summary>
/// skel 文件路径
/// </summary>
public string SkelPath => skelPath;
/// <summary>
/// atlas 文件路径
/// </summary>
public string? AtlasPath => atlasPath;
}
}

View File

@@ -1,4 +1,6 @@
using System;
using NLog;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -12,21 +14,33 @@ namespace SpineViewer.Dialogs
{
public partial class ProgressDialog : Form
{
[Category("自定义"), Description("BackgroundWorker 的 DoWork 事件")]
public event DoWorkEventHandler? DoWork
{
add { backgroundWorker.DoWork += value; }
remove { backgroundWorker.DoWork -= value; }
}
public void RunWorkerAsync() { backgroundWorker.RunWorkerAsync(); }
public void RunWorkerAsync(object? argument) { backgroundWorker.RunWorkerAsync(argument); }
private readonly Logger logger = LogManager.GetCurrentClassLogger();
public ProgressDialog()
{
InitializeComponent();
}
/// <summary>
/// BackgroundWorker.DoWork 接口暴露
/// </summary>
[Category("自定义"), Description("BackgroundWorker 的 DoWork 事件")]
public event DoWorkEventHandler? DoWork
{
add => backgroundWorker.DoWork += value;
remove => backgroundWorker.DoWork -= value;
}
/// <summary>
/// 启动后台执行
/// </summary>
public void RunWorkerAsync() => backgroundWorker.RunWorkerAsync();
/// <summary>
/// 使用给定参数启动后台执行
/// </summary>
public void RunWorkerAsync(object? argument) => backgroundWorker.RunWorkerAsync(argument);
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label_Tip.Text = e.UserState as string;
@@ -37,8 +51,8 @@ namespace SpineViewer.Dialogs
{
if (e.Error != null)
{
Program.Logger.Error(e.Error.ToString());
MessageBox.Show(e.Error.ToString(), "执行出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
logger.Error(e.Error.ToString());
MessagePopup.Error(e.Error.ToString(), "执行出错");
DialogResult = DialogResult.Abort;
}
else if (e.Cancelled)

View File

@@ -0,0 +1,55 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// MP4 导出参数
/// </summary>
public class AvifExporter : FFmpegVideoExporter
{
public AvifExporter()
{
FPS = 24;
}
public override string Format => "avif";
public override string Suffix => ".avif";
/// <summary>
/// 编码器
/// </summary>
public string Codec { get; set; } = "av1_nvenc";
/// <summary>
/// CRF
/// </summary>
public int CRF { get => crf; set => crf = Math.Clamp(value, 0, 63); }
private int crf = 23;
/// <summary>
/// 像素格式
/// </summary>
public string PixelFormat { get; set; } = "yuv420p";
/// <summary>
/// 循环次数, 0 无限循环, 取值范围 [0, 65535]
/// </summary>
public int Loop { get => loop; set => loop = Math.Clamp(value, 0, 65535); }
private int loop = 0;
public override string FileNameNoteSuffix => $"{Codec}_{CRF}_{PixelFormat}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
options.WithVideoCodec(Codec).WithConstantRateFactor(CRF).WithCustomArgument($"-loop {Loop}");
}
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// FFmpeg 自定义视频导出参数
/// </summary>
public class CustomExporter : FFmpegVideoExporter
{
public CustomExporter()
{
CustomArgument = "-c:v libx264 -crf 23 -pix_fmt yuv420p"; // 提供一个示例参数
}
public override string Format => CustomFormat;
public override string Suffix => CustomSuffix;
public override string FileNameNoteSuffix => string.Empty;
/// <summary>
/// 文件格式
/// </summary>
public string CustomFormat { get; set; } = "mp4";
/// <summary>
/// 文件名后缀
/// </summary>
public string CustomSuffix { get; set; } = ".mp4";
}
}

View File

@@ -0,0 +1,61 @@
using FFMpegCore.Pipes;
using SpineViewer.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
namespace SpineViewer.Exporter
{
/// <summary>
/// SFML.Graphics.Image 帧对象包装类, 将接管给定的 image 对象生命周期
/// </summary>
public class SFMLImageVideoFrame(SFML.Graphics.Image image) : IVideoFrame, IDisposable
{
public int Width => (int)image.Size.X;
public int Height => (int)image.Size.Y;
public string Format => "rgba";
public void Serialize(Stream pipe) => pipe.Write(image.Pixels);
public async Task SerializeAsync(Stream pipe, CancellationToken token) => await pipe.WriteAsync(image.Pixels, token);
public void Dispose() => image.Dispose();
/// <summary>
/// Save the contents of the image to a file
/// </summary>
/// <param name="filename">Path of the file to save (overwritten if already exist)</param>
/// <returns>True if saving was successful</returns>
public bool SaveToFile(string filename) => image.SaveToFile(filename);
/// <summary>
/// Save the image to a buffer in memory The format of the image must be specified.
/// The supported image formats are bmp, png, tga and jpg. This function fails if
/// the image is empty, or if the format was invalid.
/// </summary>
/// <param name="output">Byte array filled with encoded data</param>
/// <param name="format">Encoding format to use</param>
/// <returns>True if saving was successful</returns>
public bool SaveToMemory(out byte[] output, string format) => image.SaveToMemory(out output, format);
/// <summary>
/// 获取 Winforms Bitmap 对象
/// </summary>
public Bitmap CopyToBitmap() => image.CopyToBitmap();
}
/// <summary>
/// 为帧导出创建的辅助类
/// </summary>
public static class ExportHelper
{
/// <summary>
/// 根据 Bitmap 文件格式获取合适的文件后缀
/// </summary>
public static string GetSuffix(this ImageFormat imageFormat)
{
if (imageFormat == ImageFormat.Icon) return ".ico";
else if (imageFormat == ImageFormat.Exif) return ".jpeg";
else return $".{imageFormat.ToString().ToLower()}";
}
}
}

View File

@@ -0,0 +1,194 @@
using NLog;
using SpineViewer.Extensions;
using SpineViewer.PropertyGridWrappers;
using SpineViewer.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// 导出器基类
/// </summary>
public abstract class Exporter : IDisposable
{
/// <summary>
/// 日志器
/// </summary>
protected readonly Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 可用于文件名的时间戳字符串
/// </summary>
protected readonly string timestamp = DateTime.Now.ToString("yyMMddHHmmss");
~Exporter() { Dispose(false); }
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
protected virtual void Dispose(bool disposing) { View.Dispose(); }
/// <summary>
/// 输出文件夹
/// </summary>
public string? OutputDir { get; set; } = null;
/// <summary>
/// 导出单个
/// </summary>
public bool IsExportSingle { get; set; } = false;
/// <summary>
/// 画面分辨率
/// </summary>
public Size Resolution { get; set; } = new(100, 100);
/// <summary>
/// 渲染视窗, 接管对象生命周期
/// </summary>
public SFML.Graphics.View View { get => view; set { view.Dispose(); view = value; } }
private SFML.Graphics.View view = new();
/// <summary>
/// 是否仅渲染选中
/// </summary>
public bool RenderSelectedOnly { get; set; } = false;
/// <summary>
/// 背景颜色
/// </summary>
public SFML.Graphics.Color BackgroundColor
{
get => backgroundColor;
set
{
backgroundColor = value;
var bcPma = value;
var a = bcPma.A / 255f;
bcPma.R = (byte)(bcPma.R * a);
bcPma.G = (byte)(bcPma.G * a);
bcPma.B = (byte)(bcPma.B * a);
BackgroundColorPma = bcPma;
}
}
private SFML.Graphics.Color backgroundColor = SFML.Graphics.Color.Transparent;
/// <summary>
/// 预乘后的背景颜色
/// </summary>
public SFML.Graphics.Color BackgroundColorPma { get; private set; } = SFML.Graphics.Color.Transparent;
/// <summary>
/// 获取供渲染的 SFML.Graphics.RenderTexture
/// </summary>
private SFML.Graphics.RenderTexture GetRenderTexture()
{
var tex = new SFML.Graphics.RenderTexture((uint)Resolution.Width, (uint)Resolution.Height);
tex.Clear(SFML.Graphics.Color.Transparent);
tex.SetView(View);
return tex;
}
/// <summary>
/// 获取单个模型的单帧画面
/// </summary>
protected SFMLImageVideoFrame GetFrame(Spine.Spine spine) => GetFrame([spine]);
/// <summary>
/// 获取模型列表的单帧画面
/// </summary>
protected SFMLImageVideoFrame GetFrame(Spine.Spine[] spinesToRender)
{
// RenderTexture 必须临时创建, 随用随取, 防止出现跨线程的情况
using var texPma = GetRenderTexture();
// 先将预乘结果准确绘制出来, 注意背景色也应当是预乘的
texPma.Clear(BackgroundColorPma);
foreach (var spine in spinesToRender) texPma.Draw(spine);
texPma.Display();
// 背景色透明度不为 1 时需要处理反预乘, 否则直接就是结果
if (BackgroundColor.A < 255)
{
// 从预乘结果构造渲染对象, 并正确设置变换
using var view = texPma.GetView();
using var img = texPma.Texture.CopyToImage();
using var texSprite = new SFML.Graphics.Texture(img);
using var sp = new SFML.Graphics.Sprite(texSprite)
{
Origin = new(texPma.Size.X / 2f, texPma.Size.Y / 2f),
Position = new(view.Center.X, view.Center.Y),
Scale = new(view.Size.X / texPma.Size.X, view.Size.Y / texPma.Size.Y),
Rotation = view.Rotation
};
// 混合模式用直接覆盖的方式, 保证得到的图像区域是反预乘的颜色和透明度, 同时使用反预乘着色器
var st = SFML.Graphics.RenderStates.Default;
st.BlendMode = SFMLBlendMode.SourceOnly;
st.Shader = SFMLShader.InversePma;
// 在最终结果上二次渲染非预乘画面
using var tex = GetRenderTexture();
// 将非预乘结果覆盖式绘制在目标对象上, 注意背景色应该用非预乘的
tex.Clear(BackgroundColor);
tex.Draw(sp, st);
tex.Display();
return new(tex.Texture.CopyToImage());
}
else
{
return new(texPma.Texture.CopyToImage());
}
}
/// <summary>
/// 每个模型在同一个画面进行导出
/// </summary>
protected abstract void ExportSingle(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null);
/// <summary>
/// 每个模型独立导出
/// </summary>
protected abstract void ExportIndividual(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null);
/// <summary>
/// 检查参数是否合法并规范化参数值, 否则返回用户错误原因
/// </summary>
public virtual string? Validate()
{
if (!string.IsNullOrWhiteSpace(OutputDir) && File.Exists(OutputDir))
return "输出文件夹无效";
if (!string.IsNullOrWhiteSpace(OutputDir) && !Directory.Exists(OutputDir))
return $"文件夹 {OutputDir} 不存在";
if (IsExportSingle && string.IsNullOrWhiteSpace(OutputDir))
return "导出单个时必须提供输出文件夹";
OutputDir = string.IsNullOrWhiteSpace(OutputDir) ? null : Path.GetFullPath(OutputDir);
return null;
}
/// <summary>
/// 执行导出
/// </summary>
/// <param name="spines">要进行导出的 Spine 列表</param>
/// <param name="worker">用来执行该函数的 worker</param>
/// <exception cref="ArgumentException"></exception>
public virtual void Export(Spine.Spine[] spines, BackgroundWorker? worker = null)
{
if (Validate() is string err)
throw new ArgumentException(err);
var spinesToRender = spines.Where(sp => !RenderSelectedOnly || sp.IsSelected).Reverse().ToArray();
if (IsExportSingle) ExportSingle(spinesToRender, worker);
else ExportIndividual(spinesToRender, worker);
logger.LogCurrentProcessMemoryUsage();
}
}
}

View File

@@ -0,0 +1,111 @@
using FFMpegCore.Pipes;
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace SpineViewer.Exporter
{
/// <summary>
/// 使用 FFmpeg 的视频导出器
/// </summary>
public abstract class FFmpegVideoExporter : VideoExporter
{
/// <summary>
/// 文件格式
/// </summary>
public abstract string Format { get; }
/// <summary>
/// 文件名后缀
/// </summary>
public abstract string Suffix { get; }
/// <summary>
/// 文件名后缀
/// </summary>
public string CustomArgument { get; set; }
/// <summary>
/// 要追加在文件名末尾的信息字串, 首尾不需要提供额外分隔符
/// </summary>
public abstract string FileNameNoteSuffix { get; }
/// <summary>
/// 获取输出附加选项
/// </summary>
public virtual void SetOutputOptions(FFMpegArgumentOptions options) => options.ForceFormat(Format).WithCustomArgument(CustomArgument);
public override string? Validate()
{
if (base.Validate() is string error)
return error;
if (string.IsNullOrWhiteSpace(Format))
return "需要提供有效的格式";
if (string.IsNullOrWhiteSpace(Suffix))
return "需要提供有效的文件名后缀";
return null;
}
protected override void ExportSingle(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
var noteSuffix = FileNameNoteSuffix;
if (!string.IsNullOrWhiteSpace(noteSuffix)) noteSuffix = $"_{noteSuffix}";
var filename = $"ffmpeg_{timestamp}_{FPS:f0}{noteSuffix}{Suffix}";
// 导出单个时必定提供输出文件夹
var savePath = Path.Combine(OutputDir, filename);
var videoFramesSource = new RawVideoPipeSource(GetFrames(spinesToRender, worker)) { FrameRate = FPS };
try
{
var ffmpegArgs = FFMpegArguments.FromPipeInput(videoFramesSource).OutputToFile(savePath, true, SetOutputOptions);
logger.Info("FFmpeg arguments: {}", ffmpegArgs.Arguments);
ffmpegArgs.ProcessSynchronously();
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to export {} {}", Format, savePath);
}
}
protected override void ExportIndividual(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
var noteSuffix = FileNameNoteSuffix;
if (!string.IsNullOrWhiteSpace(noteSuffix)) noteSuffix = $"_{noteSuffix}";
foreach (var spine in spinesToRender)
{
if (worker?.CancellationPending == true) break; // 取消的日志在 GetFrames 里输出
var filename = $"{spine.Name}_{timestamp}_{FPS:f0}{noteSuffix}{Suffix}";
// 如果提供了输出文件夹, 则全部导出到输出文件夹, 否则导出到各自的文件夹下
var savePath = Path.Combine(OutputDir ?? spine.AssetsDir, filename);
var videoFramesSource = new RawVideoPipeSource(GetFrames(spine, worker)) { FrameRate = FPS };
try
{
var ffmpegArgs = FFMpegArguments
.FromPipeInput(videoFramesSource)
.OutputToFile(savePath, true, SetOutputOptions);
logger.Info("FFmpeg arguments: {}", ffmpegArgs.Arguments);
ffmpegArgs.ProcessSynchronously();
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to export {} {} {}", Format, savePath, spine.SkelPath);
}
}
}
}
}

View File

@@ -0,0 +1,107 @@
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// 单帧画面导出器
/// </summary>
public class FrameExporter : Exporter
{
/// <summary>
/// 单帧画面格式
/// </summary>
public ImageFormat ImageFormat
{
get => imageFormat;
set
{
if (value == ImageFormat.MemoryBmp) value = ImageFormat.Bmp;
imageFormat = value;
}
}
private ImageFormat imageFormat = ImageFormat.Png;
/// <summary>
/// DPI
/// </summary>
public SizeF DPI
{
get => dpi;
set
{
if (value.Width <= 0) value.Width = 144;
if (value.Height <= 0) value.Height = 144;
dpi = value;
}
}
private SizeF dpi = new(144, 144);
protected override void ExportSingle(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
// 导出单个时必定提供输出文件夹
var filename = $"frame_{timestamp}{ImageFormat.GetSuffix()}";
var savePath = Path.Combine(OutputDir, filename);
worker?.ReportProgress(0, $"已处理 0/1");
try
{
using var frame = GetFrame(spinesToRender);
using var img = frame.CopyToBitmap();
img.SetResolution(DPI.Width, DPI.Height);
img.Save(savePath, ImageFormat);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to save single frame");
}
worker?.ReportProgress(100, $"已处理 1/1");
}
protected override void ExportIndividual(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
int total = spinesToRender.Length;
int success = 0;
int error = 0;
worker?.ReportProgress(0, $"已处理 0/{total}");
for (int i = 0; i < total; i++)
{
var spine = spinesToRender[i];
// 逐个导出时如果提供了输出文件夹, 则全部导出到输出文件夹, 否则输出到各自的文件夹
var filename = $"{spine.Name}_{timestamp}{ImageFormat.GetSuffix()}";
var savePath = Path.Combine(OutputDir ?? spine.AssetsDir, filename);
try
{
using var frame = GetFrame(spine);
using var img = frame.CopyToBitmap();
img.SetResolution(DPI.Width, DPI.Height);
img.Save(savePath, ImageFormat);
success++;
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to save single frame {} {}", savePath, spine.SkelPath);
error++;
}
worker?.ReportProgress((int)((i + 1) * 100.0) / total, $"已处理 {i + 1}/{total}");
}
if (error > 0)
logger.Warn("Frames save {} successfully, {} failed", success, error);
else
logger.Info("{} frames saved successfully", success);
}
}
}

View File

@@ -0,0 +1,85 @@
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// 帧序列导出器
/// </summary>
public class FrameSequenceExporter : VideoExporter
{
/// <summary>
/// 文件名后缀, 同时决定帧图像格式, 支持的格式为 <c>".png", ".jpg", ".tga", ".bmp"</c>
/// </summary>
public string Suffix { get; set; } = ".png";
protected override void ExportSingle(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
// 导出单个时必定提供输出文件夹,
var saveDir = Path.Combine(OutputDir, $"frames_{timestamp}_{FPS:f0}");
Directory.CreateDirectory(saveDir);
int frameIdx = 0;
foreach (var frame in GetFrames(spinesToRender, worker))
{
var filename = $"frames_{timestamp}_{FPS:f0}_{frameIdx:d6}{Suffix}";
var savePath = Path.Combine(saveDir, filename);
try
{
frame.SaveToFile(savePath);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to save frame {}", savePath);
}
finally
{
frame.Dispose();
}
frameIdx++;
}
}
protected override void ExportIndividual(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
foreach (var spine in spinesToRender)
{
if (worker?.CancellationPending == true) break; // 取消的日志在 GetFrames 里输出
// 如果提供了输出文件夹, 则全部导出到输出文件夹, 否则导出到各自的文件夹下
var subDir = $"{spine.Name}_{timestamp}_{FPS:f0}";
var saveDir = Path.Combine(OutputDir ?? spine.AssetsDir, subDir);
Directory.CreateDirectory(saveDir);
int frameIdx = 0;
foreach (var frame in GetFrames(spine, worker))
{
var filename = $"{spine.Name}_{timestamp}_{FPS:f0}_{frameIdx:d6}{Suffix}";
var savePath = Path.Combine(saveDir, filename);
try
{
frame.SaveToFile(savePath);
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to save frame {} {}", savePath, spine.SkelPath);
}
finally
{
frame.Dispose();
}
frameIdx++;
}
}
}
}
}

View File

@@ -0,0 +1,55 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// GIF 导出参数
/// </summary>
public class GifExporter : FFmpegVideoExporter
{
public GifExporter()
{
FPS = 24;
}
public override string Format => "gif";
public override string Suffix => ".gif";
/// <summary>
/// 调色板最大颜色数量
/// </summary>
public uint MaxColors { get => maxColors; set => maxColors = Math.Clamp(value, 2, 256); }
private uint maxColors = 256;
/// <summary>
/// 透明度阈值
/// </summary>
public byte AlphaThreshold { get => alphaThreshold; set => alphaThreshold = value; }
private byte alphaThreshold = 128;
/// <summary>
/// 循环次数, -1 不循环, 0 无限循环, 取值范围 [-1, 65535]
/// </summary>
public int Loop { get => loop; set => loop = Math.Clamp(value, -1, 65535); }
private int loop = 0;
public override string FileNameNoteSuffix => $"{MaxColors}_{AlphaThreshold}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
var v = $"[0:v] split [s0][s1]";
var s0 = $"[s0] palettegen=reserve_transparent=1:max_colors={MaxColors} [p]";
var s1 = $"[s1][p] paletteuse=dither=bayer:alpha_threshold={AlphaThreshold}";
var customArgs = $"-filter_complex \"{v};{s0};{s1}\" -loop {Loop}";
options.WithCustomArgument(customArgs);
}
}
}

View File

@@ -0,0 +1,49 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// MKV 导出参数
/// </summary>
public class MkvExporter : FFmpegVideoExporter
{
public MkvExporter()
{
BackgroundColor = new(0, 255, 0);
}
public override string Format => "matroska";
public override string Suffix => ".mkv";
/// <summary>
/// 编码器
/// </summary>
public string Codec { get; set; } = "libx265";
/// <summary>
/// CRF
/// </summary>
public int CRF { get => crf; set => crf = Math.Clamp(value, 0, 63); }
private int crf = 23;
/// <summary>
/// 像素格式
/// </summary>
public string PixelFormat { get; set; } = "yuv444p";
public override string FileNameNoteSuffix => $"{Codec}_{CRF}_{PixelFormat}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
options.WithVideoCodec(Codec).WithConstantRateFactor(CRF).ForcePixelFormat(PixelFormat);
}
}
}

View File

@@ -0,0 +1,48 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// MOV 导出参数
/// </summary>
public class MovExporter : FFmpegVideoExporter
{
public MovExporter()
{
BackgroundColor = new(0, 255, 0);
}
public override string Format => "mov";
public override string Suffix => ".mov";
/// <summary>
/// 编码器
/// </summary>
public string Codec { get; set; } = "prores_ks";
/// <summary>
/// 预设
/// </summary>
public string Profile { get; set; } = "auto";
/// <summary>
/// 像素格式
/// </summary>
public string PixelFormat { get; set; } = "yuva444p10le";
public override string FileNameNoteSuffix => $"{Codec}_{Profile}_{PixelFormat}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
options.WithFastStart().WithVideoCodec(Codec).WithCustomArgument($"-profile {Profile}").ForcePixelFormat(PixelFormat);
}
}
}

View File

@@ -0,0 +1,49 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// MP4 导出参数
/// </summary>
public class Mp4Exporter : FFmpegVideoExporter
{
public Mp4Exporter()
{
BackgroundColor = new(0, 255, 0);
}
public override string Format => "mp4";
public override string Suffix => ".mp4";
/// <summary>
/// 编码器
/// </summary>
public string Codec { get; set; } = "libx264";
/// <summary>
/// CRF
/// </summary>
public int CRF { get => crf; set => crf = Math.Clamp(value, 0, 63); }
private int crf = 23;
/// <summary>
/// 像素格式
/// </summary>
public string PixelFormat { get; set; } = "yuv444p";
public override string FileNameNoteSuffix => $"{Codec}_{CRF}_{PixelFormat}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
options.WithFastStart().WithVideoCodec(Codec).WithConstantRateFactor(CRF).ForcePixelFormat(PixelFormat);
}
}
}

View File

@@ -0,0 +1,145 @@
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// 视频导出基类
/// </summary>
public abstract class VideoExporter : Exporter
{
/// <summary>
/// 导出时长
/// </summary>
public float Duration { get => duration; set => duration = value < 0 ? -1 : value; }
private float duration = -1;
/// <summary>
/// 帧率
/// </summary>
public float FPS { get; set; } = 60;
/// <summary>
/// 是否保留最后一帧
/// </summary>
public bool KeepLast { get; set; } = true;
public override string? Validate()
{
if (base.Validate() is string error)
return error;
if (IsExportSingle && Duration < 0)
return "导出单个时导出时长不能为负数";
return null;
}
/// <summary>
/// 生成单个模型的帧序列
/// </summary>
protected IEnumerable<SFMLImageVideoFrame> GetFrames(Spine.Spine spine, BackgroundWorker? worker = null)
{
// 独立导出时如果 Duration 小于 0 则使用所有轨道上动画时长最大值
var duration = Duration;
if (duration < 0) duration = spine.GetTrackIndices().Select(i => spine.GetAnimationDuration(spine.GetAnimation(i))).Max();
float delta = 1f / FPS;
int total = (int)(duration * FPS); // 完整帧的数量
float deltaFinal = duration - delta * total; // 最后一帧时长
int final = (KeepLast && (deltaFinal > 1e-3)) ? 1 : 0;
int frameCount = 1 + total + final; // 所有帧的数量 = 起始帧 + 完整帧 + 最后一帧
worker?.ReportProgress(0, $"{spine.Name} 已处理 0/{frameCount} 帧");
// 导出首帧
var firstFrame = GetFrame(spine);
worker?.ReportProgress(1 * 100 / frameCount, $"{spine.Name} 已处理 1/{frameCount} 帧");
yield return firstFrame;
// 导出完整帧
for (int i = 0; i < total; i++)
{
if (worker?.CancellationPending == true)
{
logger.Info("Export cancelled");
break;
}
spine.Update(delta);
var frame = GetFrame(spine);
worker?.ReportProgress((1 + i + 1) * 100 / frameCount, $"{spine.Name} 已处理 {1 + i + 1}/{frameCount} 帧");
yield return frame;
}
// 导出最后一帧
if (final > 0)
{
spine.Update(deltaFinal);
var finalFrame = GetFrame(spine);
worker?.ReportProgress(100, $"{spine.Name} 已处理 {frameCount}/{frameCount} 帧");
yield return finalFrame;
}
}
/// <summary>
/// 生成多个模型的帧序列
/// </summary>
protected IEnumerable<SFMLImageVideoFrame> GetFrames(Spine.Spine[] spinesToRender, BackgroundWorker? worker = null)
{
// 导出单个时必须根据 Duration 决定导出时长
var duration = Duration;
float delta = 1f / FPS;
int total = (int)(duration * FPS); // 完整帧的数量
float deltaFinal = duration - delta * total; // 最后一帧时长
int final = (KeepLast && (deltaFinal > 1e-3)) ? 1 : 0;
int frameCount = 1 + total + final; // 所有帧的数量 = 起始帧 + 完整帧 + 最后一帧
worker?.ReportProgress(0, $"已处理 0/{frameCount} 帧");
// 导出首帧
var firstFrame = GetFrame(spinesToRender);
worker?.ReportProgress(1 * 100 / frameCount, $"已处理 1/{frameCount} 帧");
yield return firstFrame;
// 导出完整帧
for (int i = 0; i < total; i++)
{
if (worker?.CancellationPending == true)
{
logger.Info("Export cancelled");
break;
}
foreach (var spine in spinesToRender) spine.Update(delta);
var frame = GetFrame(spinesToRender);
worker?.ReportProgress((1 + i + 1) * 100 / frameCount, $"已处理 {1 + i + 1}/{frameCount} 帧");
yield return frame;
}
// 导出最后一帧
if (final > 0)
{
foreach (var spine in spinesToRender) spine.Update(delta);
var finalFrame = GetFrame(spinesToRender);
worker?.ReportProgress(100, $"已处理 {frameCount}/{frameCount} 帧");
yield return finalFrame;
}
}
public override void Export(Spine.Spine[] spines, BackgroundWorker? worker = null)
{
// 导出视频格式需要把模型时间都重置到 0
foreach (var spine in spines) spine.ResetAnimationsTime();
base.Export(spines, worker);
}
}
}

View File

@@ -0,0 +1,50 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// WebM 导出参数
/// </summary>
public class WebmExporter : FFmpegVideoExporter
{
public WebmExporter()
{
// 默认用透明黑背景
BackgroundColor = new(0, 0, 0, 0);
}
public override string Format => "webm";
public override string Suffix => ".webm";
/// <summary>
/// 编码器
/// </summary>
public string Codec { get; set; } = "libvpx-vp9";
/// <summary>
/// CRF
/// </summary>
public int CRF { get => crf; set => crf = Math.Clamp(value, 0, 63); }
private int crf = 23;
/// <summary>
/// 像素格式
/// </summary>
public string PixelFormat { get; set; } = "yuva420p";
public override string FileNameNoteSuffix => $"{Codec}_{CRF}_{PixelFormat}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
options.WithVideoCodec(Codec).WithConstantRateFactor(CRF).ForcePixelFormat(PixelFormat);
}
}
}

View File

@@ -0,0 +1,60 @@
using FFMpegCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Exporter
{
/// <summary>
/// MP4 导出参数
/// </summary>
public class WebpExporter : FFmpegVideoExporter
{
public WebpExporter()
{
FPS = 24;
}
public override string Format => "webp";
public override string Suffix => ".webp";
/// <summary>
/// 编码器
/// </summary>
public string Codec { get; set; } = "libwebp_anim";
/// <summary>
/// 是否无损
/// </summary>
public bool Lossless { get; set; } = false;
/// <summary>
/// 质量
/// </summary>
public int Quality { get => quality; set => quality = Math.Clamp(value, 0, 100); }
private int quality = 75;
/// <summary>
/// 像素格式
/// </summary>
public string PixelFormat { get; set; } = "yuva420p";
/// <summary>
/// 循环次数, 0 无限循环, 取值范围 [0, 65535]
/// </summary>
public int Loop { get => loop; set => loop = Math.Clamp(value, 0, 65535); }
private int loop = 0;
public override string FileNameNoteSuffix => $"{Codec}_{Quality}_{PixelFormat}";
public override void SetOutputOptions(FFMpegArgumentOptions options)
{
base.SetOutputOptions(options);
options.WithVideoCodec(Codec).WithCustomArgument($"-lossless {(Lossless ? 1 : 0)} -quality {Quality} -loop {Loop}");
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Extensions
{
public static class NLogExtension
{
/// <summary>
/// 输出当前进程的内存占用
/// </summary>
public static void LogCurrentProcessMemoryUsage(this NLog.Logger logger)
{
var process = Process.GetCurrentProcess();
logger.Info("Current memory usage for {}: {:F2} MB", process.ProcessName, process.WorkingSet64 / 1024.0 / 1024.0);
}
}
}

View File

@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Extensions
{
public static class SFMLExtension
{
/// <summary>
/// 获取 Winforms Bitmap 对象, 需要使用 Dispose 释放对象
/// </summary>
public static Bitmap CopyToBitmap(this SFML.Graphics.Image image)
{
image.SaveToMemory(out var imgBuffer, "bmp");
using var stream = new MemoryStream(imgBuffer);
using var bitmap = new Bitmap(stream);
return new(bitmap); // 必须重复构造一个副本才能摆脱对流的依赖, 否则之后使用会报错
}
/// <summary>
/// 获取 Winforms Bitmap 对象, 需要使用 Dispose 释放对象
/// </summary>
public static Bitmap CopyToBitmap(this SFML.Graphics.Texture texture)
{
using var image = texture.CopyToImage();
return image.CopyToBitmap();
}
/// <summary>
/// 获取某个包围盒下合适的视图
/// </summary>
public static SFML.Graphics.View GetView(this RectangleF bounds, Size resolution, Padding padding)
=> bounds.GetView((uint)resolution.Width, (uint)resolution.Height, (uint)padding.Left, (uint)padding.Right, (uint)padding.Top, (uint)padding.Bottom);
/// <summary>
/// 获取某个包围盒下合适的视图
/// </summary>
public static SFML.Graphics.View GetView(this RectangleF bounds, uint width, uint height, Padding padding)
=> bounds.GetView(width, height, (uint)padding.Left, (uint)padding.Right, (uint)padding.Top, (uint)padding.Bottom);
/// <summary>
/// 获取某个包围盒下合适的视图
/// </summary>
public static SFML.Graphics.View GetView(this RectangleF bounds, Size resolution, uint paddingL = 1, uint paddingR = 1, uint paddingT = 1, uint paddingB = 1)
=> bounds.GetView((uint)resolution.Width, (uint)resolution.Height, paddingL, paddingR, paddingT, paddingB);
/// <summary>
/// 获取某个包围盒下合适的视图
/// </summary>
public static SFML.Graphics.View GetView(this RectangleF bounds, uint width, uint height, uint paddingL = 1, uint paddingR = 1, uint paddingT = 1, uint paddingB = 1)
{
float sizeX = bounds.Width;
float sizeY = bounds.Height;
float innerW = width - paddingL - paddingR;
float innerH = height - paddingT - paddingB;
float scale = 1;
if (sizeY / sizeX < innerH / innerW)
scale = sizeX / innerW; // 相同的 X, 视窗 Y 更大
else
scale = sizeY / innerH; // 相同的 Y, 视窗 X 更大
var x = bounds.X + bounds.Width / 2 + (paddingL - (float)paddingR) * scale;
var y = bounds.Y + bounds.Height / 2 + (paddingT - (float)paddingB) * scale;
var viewX = width * scale;
var viewY = height * scale;
return new(new(x, y), new(viewX, -viewY));
}
}
}

50
SpineViewer/Forms/PetForm.Designer.cs generated Normal file
View File

@@ -0,0 +1,50 @@
namespace SpineViewer
{
partial class PetForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
SuspendLayout();
//
// PetForm
//
AutoScaleMode = AutoScaleMode.None;
ClientSize = new Size(490, 456);
ControlBox = false;
MaximizeBox = false;
MinimizeBox = false;
Name = "PetForm";
ShowIcon = false;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
Text = "PetForm";
ResumeLayout(false);
}
#endregion
}
}

View File

@@ -0,0 +1,49 @@
using SpineViewer.Natives;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SpineViewer
{
public partial class PetForm: Form
{
public PetForm()
{
InitializeComponent();
}
protected override CreateParams CreateParams
{
get
{
//var style = Win32.GetWindowLong(hWnd, Win32.GWL_STYLE) | Win32.WS_POPUP;
//var exStyle = Win32.GetWindowLong(hWnd, Win32.GWL_EXSTYLE) | Win32.WS_EX_LAYERED | Win32.WS_EX_TOOLWINDOW | Win32.WS_EX_TOPMOST;
//Win32.SetWindowLong(hWnd, Win32.GWL_STYLE, style);
//Win32.SetWindowLong(hWnd, Win32.GWL_EXSTYLE, exStyle);
//Win32.SetLayeredWindowAttributes(hWnd, crKey, 255, Win32.LWA_COLORKEY | Win32.LWA_ALPHA);
//Win32.SetWindowPos(hWnd, Win32.HWND_TOPMOST, 0, 0, 0, 0, Win32.SWP_NOMOVE | Win32.SWP_NOSIZE);
var cp = base.CreateParams;
cp.ExStyle = Win32.WS_EX_LAYERED | Win32.WS_EX_TOPMOST;
cp.Style = Win32.WS_POPUP;
//cp.ExStyle |= Win32.WS_EX_LAYERED | Win32.WS_EX_TOOLWINDOW | Win32.WS_EX_TOPMOST;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
;
}
protected override void OnPaintBackground(PaintEventArgs e)
{
;
}
}
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -1,6 +1,6 @@
namespace SpineViewer
{
partial class MainForm
partial class SpineViewerForm
{
/// <summary>
/// Required designer variable.
@@ -29,18 +29,23 @@
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SpineViewerForm));
menuStrip = new MenuStrip();
toolStripMenuItem_File = new ToolStripMenuItem();
toolStripMenuItem_Open = new ToolStripMenuItem();
toolStripMenuItem_BatchOpen = new ToolStripMenuItem();
toolStripSeparator1 = new ToolStripSeparator();
toolStripMenuItem_Export = new ToolStripMenuItem();
toolStripMenuItem_ExportPreview = new ToolStripMenuItem();
toolStripMenuItem_ExportFrame = new ToolStripMenuItem();
toolStripMenuItem_ExportFrameSequence = new ToolStripMenuItem();
toolStripMenuItem_ExportGif = new ToolStripMenuItem();
toolStripMenuItem_ExportMp4 = new ToolStripMenuItem();
toolStripMenuItem_ExportWebm = new ToolStripMenuItem();
toolStripMenuItem_ExportMkv = new ToolStripMenuItem();
toolStripMenuItem_ExportMov = new ToolStripMenuItem();
toolStripMenuItem_ExportCustom = new ToolStripMenuItem();
toolStripSeparator2 = new ToolStripSeparator();
toolStripMenuItem_Exit = new ToolStripMenuItem();
toolStripMenuItem_Function = new ToolStripMenuItem();
toolStripMenuItem_ResetAnimation = new ToolStripMenuItem();
toolStripMenuItem_Tool = new ToolStripMenuItem();
toolStripMenuItem_ConvertFileFormat = new ToolStripMenuItem();
toolStripMenuItem_Download = new ToolStripMenuItem();
@@ -55,15 +60,22 @@
splitContainer_Information = new SplitContainer();
groupBox_SkelList = new GroupBox();
spineListView = new SpineViewer.Controls.SpineListView();
propertyGrid_Spine = new PropertyGrid();
splitContainer_Config = new SplitContainer();
groupBox_SkelConfig = new GroupBox();
spinePropertyGrid = new SpineViewer.Controls.SpinePropertyGrid();
tabControl_Config = new TabControl();
tabPage_Previewer = new TabPage();
groupBox_PreviewConfig = new GroupBox();
propertyGrid_Previewer = new PropertyGrid();
tabPage_SpineProperty = new TabPage();
groupBox_SkelConfig = new GroupBox();
groupBox_Preview = new GroupBox();
spinePreviewer = new SpineViewer.Controls.SpinePreviewer();
panel_MainForm = new Panel();
toolTip = new ToolTip(components);
toolStripSeparator4 = new ToolStripSeparator();
toolStripSeparator5 = new ToolStripSeparator();
toolStripSeparator6 = new ToolStripSeparator();
toolStripMenuItem_ExportWebp = new ToolStripMenuItem();
toolStripMenuItem_ExportAvif = new ToolStripMenuItem();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)splitContainer_MainForm).BeginInit();
splitContainer_MainForm.Panel1.SuspendLayout();
@@ -78,12 +90,11 @@
splitContainer_Information.Panel2.SuspendLayout();
splitContainer_Information.SuspendLayout();
groupBox_SkelList.SuspendLayout();
((System.ComponentModel.ISupportInitialize)splitContainer_Config).BeginInit();
splitContainer_Config.Panel1.SuspendLayout();
splitContainer_Config.Panel2.SuspendLayout();
splitContainer_Config.SuspendLayout();
groupBox_SkelConfig.SuspendLayout();
tabControl_Config.SuspendLayout();
tabPage_Previewer.SuspendLayout();
groupBox_PreviewConfig.SuspendLayout();
tabPage_SpineProperty.SuspendLayout();
groupBox_SkelConfig.SuspendLayout();
groupBox_Preview.SuspendLayout();
panel_MainForm.SuspendLayout();
SuspendLayout();
@@ -92,16 +103,16 @@
//
menuStrip.BackColor = SystemColors.Control;
menuStrip.ImageScalingSize = new Size(24, 24);
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_File, toolStripMenuItem_Function, toolStripMenuItem_Tool, toolStripMenuItem_Download, toolStripMenuItem_Help });
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem_File, toolStripMenuItem_Tool, toolStripMenuItem_Download, toolStripMenuItem_Help });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1748, 32);
menuStrip.Size = new Size(1778, 32);
menuStrip.TabIndex = 0;
menuStrip.Text = "菜单";
//
// toolStripMenuItem_File
//
toolStripMenuItem_File.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem_Open, toolStripMenuItem_BatchOpen, toolStripSeparator1, toolStripMenuItem_Export, toolStripMenuItem_ExportPreview, toolStripSeparator2, toolStripMenuItem_Exit });
toolStripMenuItem_File.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem_Open, toolStripMenuItem_BatchOpen, toolStripSeparator1, toolStripMenuItem_Export, toolStripSeparator2, toolStripMenuItem_Exit });
toolStripMenuItem_File.Name = "toolStripMenuItem_File";
toolStripMenuItem_File.Size = new Size(84, 28);
toolStripMenuItem_File.Text = "文件(&F)";
@@ -110,64 +121,98 @@
//
toolStripMenuItem_Open.Name = "toolStripMenuItem_Open";
toolStripMenuItem_Open.ShortcutKeys = Keys.Control | Keys.O;
toolStripMenuItem_Open.Size = new Size(254, 34);
toolStripMenuItem_Open.Size = new Size(270, 34);
toolStripMenuItem_Open.Text = "打开(&O)...";
toolStripMenuItem_Open.Click += toolStripMenuItem_Open_Click;
//
// toolStripMenuItem_BatchOpen
//
toolStripMenuItem_BatchOpen.Name = "toolStripMenuItem_BatchOpen";
toolStripMenuItem_BatchOpen.Size = new Size(254, 34);
toolStripMenuItem_BatchOpen.Size = new Size(270, 34);
toolStripMenuItem_BatchOpen.Text = "批量打开(&B)...";
toolStripMenuItem_BatchOpen.Click += toolStripMenuItem_BatchOpen_Click;
//
// toolStripSeparator1
//
toolStripSeparator1.Name = "toolStripSeparator1";
toolStripSeparator1.Size = new Size(251, 6);
toolStripSeparator1.Size = new Size(267, 6);
//
// toolStripMenuItem_Export
//
toolStripMenuItem_Export.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem_ExportFrame, toolStripMenuItem_ExportFrameSequence, toolStripSeparator4, toolStripMenuItem_ExportGif, toolStripMenuItem_ExportWebp, toolStripMenuItem_ExportAvif, toolStripSeparator5, toolStripMenuItem_ExportMp4, toolStripMenuItem_ExportWebm, toolStripMenuItem_ExportMkv, toolStripMenuItem_ExportMov, toolStripSeparator6, toolStripMenuItem_ExportCustom });
toolStripMenuItem_Export.Name = "toolStripMenuItem_Export";
toolStripMenuItem_Export.ShortcutKeys = Keys.Control | Keys.S;
toolStripMenuItem_Export.Size = new Size(254, 34);
toolStripMenuItem_Export.Text = "导出(&E)...";
toolStripMenuItem_Export.Click += toolStripMenuItem_Export_Click;
toolStripMenuItem_Export.Size = new Size(270, 34);
toolStripMenuItem_Export.Text = "导出(&E)";
//
// toolStripMenuItem_ExportPreview
// toolStripMenuItem_ExportFrame
//
toolStripMenuItem_ExportPreview.Name = "toolStripMenuItem_ExportPreview";
toolStripMenuItem_ExportPreview.Size = new Size(254, 34);
toolStripMenuItem_ExportPreview.Text = "导出预览图(&P)...";
toolStripMenuItem_ExportPreview.Click += toolStripMenuItem_ExportPreview_Click;
toolStripMenuItem_ExportFrame.Name = "toolStripMenuItem_ExportFrame";
toolStripMenuItem_ExportFrame.Size = new Size(288, 34);
toolStripMenuItem_ExportFrame.Text = "单帧画面...";
toolStripMenuItem_ExportFrame.Click += toolStripMenuItem_ExportFrame_Click;
//
// toolStripMenuItem_ExportFrameSequence
//
toolStripMenuItem_ExportFrameSequence.Name = "toolStripMenuItem_ExportFrameSequence";
toolStripMenuItem_ExportFrameSequence.Size = new Size(288, 34);
toolStripMenuItem_ExportFrameSequence.Text = "帧序列...";
toolStripMenuItem_ExportFrameSequence.Click += toolStripMenuItem_ExportFrameSequence_Click;
//
// toolStripMenuItem_ExportGif
//
toolStripMenuItem_ExportGif.Name = "toolStripMenuItem_ExportGif";
toolStripMenuItem_ExportGif.Size = new Size(288, 34);
toolStripMenuItem_ExportGif.Text = "GIF...";
toolStripMenuItem_ExportGif.Click += toolStripMenuItem_ExportGif_Click;
//
// toolStripMenuItem_ExportMp4
//
toolStripMenuItem_ExportMp4.Name = "toolStripMenuItem_ExportMp4";
toolStripMenuItem_ExportMp4.Size = new Size(288, 34);
toolStripMenuItem_ExportMp4.Text = "MP4...";
toolStripMenuItem_ExportMp4.Click += toolStripMenuItem_ExportMp4_Click;
//
// toolStripMenuItem_ExportWebm
//
toolStripMenuItem_ExportWebm.Name = "toolStripMenuItem_ExportWebm";
toolStripMenuItem_ExportWebm.Size = new Size(288, 34);
toolStripMenuItem_ExportWebm.Text = "WebM...";
toolStripMenuItem_ExportWebm.Click += toolStripMenuItem_ExportWebm_Click;
//
// toolStripMenuItem_ExportMkv
//
toolStripMenuItem_ExportMkv.Name = "toolStripMenuItem_ExportMkv";
toolStripMenuItem_ExportMkv.Size = new Size(288, 34);
toolStripMenuItem_ExportMkv.Text = "MKV...";
toolStripMenuItem_ExportMkv.Click += toolStripMenuItem_ExportMkv_Click;
//
// toolStripMenuItem_ExportMov
//
toolStripMenuItem_ExportMov.Name = "toolStripMenuItem_ExportMov";
toolStripMenuItem_ExportMov.Size = new Size(288, 34);
toolStripMenuItem_ExportMov.Text = "MOV...";
toolStripMenuItem_ExportMov.Click += toolStripMenuItem_ExportMov_Click;
//
// toolStripMenuItem_ExportCustom
//
toolStripMenuItem_ExportCustom.Name = "toolStripMenuItem_ExportCustom";
toolStripMenuItem_ExportCustom.Size = new Size(288, 34);
toolStripMenuItem_ExportCustom.Text = "FFmpeg 自定义导出...";
toolStripMenuItem_ExportCustom.Click += toolStripMenuItem_ExportCustom_Click;
//
// toolStripSeparator2
//
toolStripSeparator2.Name = "toolStripSeparator2";
toolStripSeparator2.Size = new Size(251, 6);
toolStripSeparator2.Size = new Size(267, 6);
//
// toolStripMenuItem_Exit
//
toolStripMenuItem_Exit.Name = "toolStripMenuItem_Exit";
toolStripMenuItem_Exit.ShortcutKeys = Keys.Alt | Keys.F4;
toolStripMenuItem_Exit.Size = new Size(254, 34);
toolStripMenuItem_Exit.Size = new Size(270, 34);
toolStripMenuItem_Exit.Text = "退出(&X)";
toolStripMenuItem_Exit.Click += toolStripMenuItem_Exit_Click;
//
// toolStripMenuItem_Function
//
toolStripMenuItem_Function.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem_ResetAnimation });
toolStripMenuItem_Function.Name = "toolStripMenuItem_Function";
toolStripMenuItem_Function.Size = new Size(87, 28);
toolStripMenuItem_Function.Text = "功能(&G)";
//
// toolStripMenuItem_ResetAnimation
//
toolStripMenuItem_ResetAnimation.Name = "toolStripMenuItem_ResetAnimation";
toolStripMenuItem_ResetAnimation.Size = new Size(242, 34);
toolStripMenuItem_ResetAnimation.Text = "重置动画时间(&R)";
toolStripMenuItem_ResetAnimation.Click += toolStripMenuItem_ResetAnimation_Click;
//
// toolStripMenuItem_Tool
//
toolStripMenuItem_Tool.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem_ConvertFileFormat });
@@ -232,7 +277,7 @@
rtbLog.Margin = new Padding(3, 2, 3, 2);
rtbLog.Name = "rtbLog";
rtbLog.ReadOnly = true;
rtbLog.Size = new Size(1728, 114);
rtbLog.Size = new Size(1758, 172);
rtbLog.TabIndex = 0;
rtbLog.Text = "";
rtbLog.WordWrap = false;
@@ -241,6 +286,7 @@
//
splitContainer_MainForm.Cursor = Cursors.SizeNS;
splitContainer_MainForm.Dock = DockStyle.Fill;
splitContainer_MainForm.FixedPanel = FixedPanel.Panel2;
splitContainer_MainForm.Location = new Point(10, 5);
splitContainer_MainForm.Name = "splitContainer_MainForm";
splitContainer_MainForm.Orientation = Orientation.Horizontal;
@@ -254,8 +300,9 @@
//
splitContainer_MainForm.Panel2.Controls.Add(rtbLog);
splitContainer_MainForm.Panel2.Cursor = Cursors.Default;
splitContainer_MainForm.Size = new Size(1728, 997);
splitContainer_MainForm.SplitterDistance = 879;
splitContainer_MainForm.Size = new Size(1758, 1097);
splitContainer_MainForm.SplitterDistance = 917;
splitContainer_MainForm.SplitterWidth = 8;
splitContainer_MainForm.TabIndex = 3;
splitContainer_MainForm.TabStop = false;
splitContainer_MainForm.SplitterMoved += splitContainer_SplitterMoved;
@@ -265,6 +312,7 @@
//
splitContainer_Functional.Cursor = Cursors.SizeWE;
splitContainer_Functional.Dock = DockStyle.Fill;
splitContainer_Functional.FixedPanel = FixedPanel.Panel1;
splitContainer_Functional.Location = new Point(0, 0);
splitContainer_Functional.Name = "splitContainer_Functional";
//
@@ -277,8 +325,9 @@
//
splitContainer_Functional.Panel2.Controls.Add(groupBox_Preview);
splitContainer_Functional.Panel2.Cursor = Cursors.Default;
splitContainer_Functional.Size = new Size(1728, 879);
splitContainer_Functional.SplitterDistance = 747;
splitContainer_Functional.Size = new Size(1758, 917);
splitContainer_Functional.SplitterDistance = 759;
splitContainer_Functional.SplitterWidth = 8;
splitContainer_Functional.TabIndex = 2;
splitContainer_Functional.TabStop = false;
splitContainer_Functional.SplitterMoved += splitContainer_SplitterMoved;
@@ -298,10 +347,11 @@
//
// splitContainer_Information.Panel2
//
splitContainer_Information.Panel2.Controls.Add(splitContainer_Config);
splitContainer_Information.Panel2.Controls.Add(tabControl_Config);
splitContainer_Information.Panel2.Cursor = Cursors.Default;
splitContainer_Information.Size = new Size(747, 879);
splitContainer_Information.SplitterDistance = 399;
splitContainer_Information.Size = new Size(759, 917);
splitContainer_Information.SplitterDistance = 354;
splitContainer_Information.SplitterWidth = 8;
splitContainer_Information.TabIndex = 1;
splitContainer_Information.TabStop = false;
splitContainer_Information.SplitterMoved += splitContainer_SplitterMoved;
@@ -313,7 +363,7 @@
groupBox_SkelList.Dock = DockStyle.Fill;
groupBox_SkelList.Location = new Point(0, 0);
groupBox_SkelList.Name = "groupBox_SkelList";
groupBox_SkelList.Size = new Size(399, 879);
groupBox_SkelList.Size = new Size(354, 917);
groupBox_SkelList.TabIndex = 0;
groupBox_SkelList.TabStop = false;
groupBox_SkelList.Text = "模型列表";
@@ -323,63 +373,51 @@
spineListView.Dock = DockStyle.Fill;
spineListView.Location = new Point(3, 26);
spineListView.Name = "spineListView";
spineListView.PropertyGrid = propertyGrid_Spine;
spineListView.Size = new Size(393, 850);
spineListView.Size = new Size(348, 888);
spineListView.SpinePropertyGrid = spinePropertyGrid;
spineListView.TabIndex = 0;
//
// propertyGrid_Spine
// spinePropertyGrid
//
propertyGrid_Spine.Dock = DockStyle.Fill;
propertyGrid_Spine.HelpVisible = false;
propertyGrid_Spine.Location = new Point(3, 26);
propertyGrid_Spine.Name = "propertyGrid_Spine";
propertyGrid_Spine.Size = new Size(338, 485);
propertyGrid_Spine.TabIndex = 0;
propertyGrid_Spine.ToolbarVisible = false;
propertyGrid_Spine.PropertyValueChanged += propertyGrid_PropertyValueChanged;
spinePropertyGrid.Dock = DockStyle.Fill;
spinePropertyGrid.Location = new Point(3, 26);
spinePropertyGrid.Name = "spinePropertyGrid";
spinePropertyGrid.Size = new Size(383, 849);
spinePropertyGrid.TabIndex = 0;
//
// splitContainer_Config
// tabControl_Config
//
splitContainer_Config.Cursor = Cursors.SizeNS;
splitContainer_Config.Dock = DockStyle.Fill;
splitContainer_Config.Location = new Point(0, 0);
splitContainer_Config.Name = "splitContainer_Config";
splitContainer_Config.Orientation = Orientation.Horizontal;
tabControl_Config.Alignment = TabAlignment.Bottom;
tabControl_Config.Controls.Add(tabPage_Previewer);
tabControl_Config.Controls.Add(tabPage_SpineProperty);
tabControl_Config.Dock = DockStyle.Fill;
tabControl_Config.ItemSize = new Size(100, 35);
tabControl_Config.Location = new Point(0, 0);
tabControl_Config.Multiline = true;
tabControl_Config.Name = "tabControl_Config";
tabControl_Config.Padding = new Point(0, 0);
tabControl_Config.SelectedIndex = 0;
tabControl_Config.Size = new Size(397, 917);
tabControl_Config.TabIndex = 0;
//
// splitContainer_Config.Panel1
// tabPage_Previewer
//
splitContainer_Config.Panel1.Controls.Add(groupBox_SkelConfig);
splitContainer_Config.Panel1.Cursor = Cursors.Default;
//
// splitContainer_Config.Panel2
//
splitContainer_Config.Panel2.Controls.Add(groupBox_PreviewConfig);
splitContainer_Config.Panel2.Cursor = Cursors.Default;
splitContainer_Config.Size = new Size(344, 879);
splitContainer_Config.SplitterDistance = 514;
splitContainer_Config.TabIndex = 0;
splitContainer_Config.TabStop = false;
splitContainer_Config.SplitterMoved += splitContainer_SplitterMoved;
splitContainer_Config.MouseUp += splitContainer_MouseUp;
//
// groupBox_SkelConfig
//
groupBox_SkelConfig.Controls.Add(propertyGrid_Spine);
groupBox_SkelConfig.Dock = DockStyle.Fill;
groupBox_SkelConfig.Location = new Point(0, 0);
groupBox_SkelConfig.Name = "groupBox_SkelConfig";
groupBox_SkelConfig.Size = new Size(344, 514);
groupBox_SkelConfig.TabIndex = 0;
groupBox_SkelConfig.TabStop = false;
groupBox_SkelConfig.Text = "模型参数";
tabPage_Previewer.Controls.Add(groupBox_PreviewConfig);
tabPage_Previewer.Location = new Point(4, 4);
tabPage_Previewer.Margin = new Padding(0);
tabPage_Previewer.Name = "tabPage_Previewer";
tabPage_Previewer.Size = new Size(389, 874);
tabPage_Previewer.TabIndex = 0;
tabPage_Previewer.Text = "画面参数";
//
// groupBox_PreviewConfig
//
groupBox_PreviewConfig.Controls.Add(propertyGrid_Previewer);
groupBox_PreviewConfig.Dock = DockStyle.Fill;
groupBox_PreviewConfig.Location = new Point(0, 0);
groupBox_PreviewConfig.Margin = new Padding(0);
groupBox_PreviewConfig.Name = "groupBox_PreviewConfig";
groupBox_PreviewConfig.Size = new Size(344, 361);
groupBox_PreviewConfig.Size = new Size(389, 874);
groupBox_PreviewConfig.TabIndex = 1;
groupBox_PreviewConfig.TabStop = false;
groupBox_PreviewConfig.Text = "画面参数";
@@ -390,33 +428,54 @@
propertyGrid_Previewer.HelpVisible = false;
propertyGrid_Previewer.Location = new Point(3, 26);
propertyGrid_Previewer.Name = "propertyGrid_Previewer";
propertyGrid_Previewer.Size = new Size(338, 332);
propertyGrid_Previewer.Size = new Size(383, 845);
propertyGrid_Previewer.TabIndex = 1;
propertyGrid_Previewer.ToolbarVisible = false;
propertyGrid_Previewer.PropertyValueChanged += propertyGrid_PropertyValueChanged;
//
// tabPage_SpineProperty
//
tabPage_SpineProperty.BackColor = SystemColors.Control;
tabPage_SpineProperty.Controls.Add(groupBox_SkelConfig);
tabPage_SpineProperty.Location = new Point(4, 4);
tabPage_SpineProperty.Margin = new Padding(0);
tabPage_SpineProperty.Name = "tabPage_SpineProperty";
tabPage_SpineProperty.Size = new Size(389, 878);
tabPage_SpineProperty.TabIndex = 1;
tabPage_SpineProperty.Text = "模型参数";
//
// groupBox_SkelConfig
//
groupBox_SkelConfig.Controls.Add(spinePropertyGrid);
groupBox_SkelConfig.Dock = DockStyle.Fill;
groupBox_SkelConfig.Location = new Point(0, 0);
groupBox_SkelConfig.Margin = new Padding(0);
groupBox_SkelConfig.Name = "groupBox_SkelConfig";
groupBox_SkelConfig.Size = new Size(389, 878);
groupBox_SkelConfig.TabIndex = 0;
groupBox_SkelConfig.TabStop = false;
groupBox_SkelConfig.Text = "模型参数";
//
// groupBox_Preview
//
groupBox_Preview.Controls.Add(spinePreviewer);
groupBox_Preview.Dock = DockStyle.Fill;
groupBox_Preview.Location = new Point(0, 0);
groupBox_Preview.Name = "groupBox_Preview";
groupBox_Preview.Size = new Size(977, 879);
groupBox_Preview.Size = new Size(991, 917);
groupBox_Preview.TabIndex = 1;
groupBox_Preview.TabStop = false;
groupBox_Preview.Text = "预览画面";
//
// spinePreviewer
//
spinePreviewer.BackColor = SystemColors.ControlDark;
spinePreviewer.Dock = DockStyle.Fill;
spinePreviewer.Location = new Point(3, 26);
spinePreviewer.Name = "spinePreviewer";
spinePreviewer.PropertyGrid = propertyGrid_Previewer;
spinePreviewer.Size = new Size(971, 850);
spinePreviewer.Size = new Size(985, 888);
spinePreviewer.SpineListView = spineListView;
spinePreviewer.TabIndex = 0;
spinePreviewer.MouseUp += spinePreviewer_MouseUp;
//
// panel_MainForm
//
@@ -425,24 +484,53 @@
panel_MainForm.Location = new Point(0, 32);
panel_MainForm.Name = "panel_MainForm";
panel_MainForm.Padding = new Padding(10, 5, 10, 10);
panel_MainForm.Size = new Size(1748, 1012);
panel_MainForm.Size = new Size(1778, 1112);
panel_MainForm.TabIndex = 4;
//
// toolTip
//
toolTip.ShowAlways = true;
//
// MainForm
// toolStripSeparator4
//
toolStripSeparator4.Name = "toolStripSeparator4";
toolStripSeparator4.Size = new Size(285, 6);
//
// toolStripSeparator5
//
toolStripSeparator5.Name = "toolStripSeparator5";
toolStripSeparator5.Size = new Size(285, 6);
//
// toolStripSeparator6
//
toolStripSeparator6.Name = "toolStripSeparator6";
toolStripSeparator6.Size = new Size(285, 6);
//
// toolStripMenuItem_ExportWebp
//
toolStripMenuItem_ExportWebp.Name = "toolStripMenuItem_ExportWebp";
toolStripMenuItem_ExportWebp.Size = new Size(288, 34);
toolStripMenuItem_ExportWebp.Text = "WebP...";
toolStripMenuItem_ExportWebp.Click += toolStripMenuItem_ExportWebp_Click;
//
// toolStripMenuItem_ExportAvif
//
toolStripMenuItem_ExportAvif.Name = "toolStripMenuItem_ExportAvif";
toolStripMenuItem_ExportAvif.Size = new Size(288, 34);
toolStripMenuItem_ExportAvif.Text = "AVIF...";
toolStripMenuItem_ExportAvif.Click += toolStripMenuItem_ExportAvif_Click;
//
// SpineViewerForm
//
AutoScaleDimensions = new SizeF(11F, 24F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1748, 1044);
ClientSize = new Size(1778, 1144);
Controls.Add(panel_MainForm);
Controls.Add(menuStrip);
Icon = (Icon)resources.GetObject("$this.Icon");
MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "MainForm";
Name = "SpineViewerForm";
StartPosition = FormStartPosition.CenterScreen;
Text = "SpineViewer";
FormClosing += MainForm_FormClosing;
@@ -462,12 +550,11 @@
((System.ComponentModel.ISupportInitialize)splitContainer_Information).EndInit();
splitContainer_Information.ResumeLayout(false);
groupBox_SkelList.ResumeLayout(false);
splitContainer_Config.Panel1.ResumeLayout(false);
splitContainer_Config.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)splitContainer_Config).EndInit();
splitContainer_Config.ResumeLayout(false);
groupBox_SkelConfig.ResumeLayout(false);
tabControl_Config.ResumeLayout(false);
tabPage_Previewer.ResumeLayout(false);
groupBox_PreviewConfig.ResumeLayout(false);
tabPage_SpineProperty.ResumeLayout(false);
groupBox_SkelConfig.ResumeLayout(false);
groupBox_Preview.ResumeLayout(false);
panel_MainForm.ResumeLayout(false);
ResumeLayout(false);
@@ -481,7 +568,6 @@
private ToolStripMenuItem toolStripMenuItem_Open;
private ToolStripMenuItem toolStripMenuItem_Exit;
private ToolStripSeparator toolStripSeparator1;
private ToolStripMenuItem toolStripMenuItem_Export;
private ToolStripSeparator toolStripSeparator2;
private RichTextBox rtbLog;
private SplitContainer splitContainer_MainForm;
@@ -489,7 +575,6 @@
private SplitContainer splitContainer_Information;
private GroupBox groupBox_SkelList;
private GroupBox groupBox_SkelConfig;
private SplitContainer splitContainer_Config;
private GroupBox groupBox_PreviewConfig;
private Panel panel_MainForm;
private ToolStripMenuItem toolStripMenuItem_Help;
@@ -497,18 +582,32 @@
private ToolStripMenuItem toolStripMenuItem_BatchOpen;
private GroupBox groupBox_Preview;
private ToolTip toolTip;
private PropertyGrid propertyGrid_Spine;
private Controls.SpineListView spineListView;
private PropertyGrid propertyGrid_Previewer;
private Controls.SpinePreviewer spinePreviewer;
private ToolStripMenuItem toolStripMenuItem_Function;
private ToolStripMenuItem toolStripMenuItem_ResetAnimation;
private ToolStripMenuItem toolStripMenuItem_Diagnostics;
private ToolStripSeparator toolStripSeparator3;
private ToolStripMenuItem toolStripMenuItem_Download;
private ToolStripMenuItem toolStripMenuItem_ManageResource;
private ToolStripMenuItem toolStripMenuItem_Tool;
private ToolStripMenuItem toolStripMenuItem_ConvertFileFormat;
private ToolStripMenuItem toolStripMenuItem_ExportPreview;
private ToolStripMenuItem toolStripMenuItem_Export;
private ToolStripMenuItem toolStripMenuItem_ExportFrame;
private ToolStripMenuItem toolStripMenuItem_ExportFrameSequence;
private ToolStripMenuItem toolStripMenuItem_ExportGif;
private ToolStripMenuItem toolStripMenuItem_ExportMp4;
private ToolStripMenuItem toolStripMenuItem_ExportMov;
private ToolStripMenuItem toolStripMenuItem_ExportMkv;
private ToolStripMenuItem toolStripMenuItem_ExportWebm;
private ToolStripMenuItem toolStripMenuItem_ExportCustom;
private Controls.SpinePropertyGrid spinePropertyGrid;
private TabControl tabControl_Config;
private TabPage tabPage_Previewer;
private TabPage tabPage_SpineProperty;
private ToolStripSeparator toolStripSeparator4;
private ToolStripMenuItem toolStripMenuItem_ExportWebp;
private ToolStripMenuItem toolStripMenuItem_ExportAvif;
private ToolStripSeparator toolStripSeparator5;
private ToolStripSeparator toolStripSeparator6;
}
}

View File

@@ -0,0 +1,482 @@
using NLog;
using SpineViewer.Spine;
using System.ComponentModel;
using System.Diagnostics;
using SpineViewer.Exporter;
using System.Reflection.Metadata;
using SpineViewer.PropertyGridWrappers.Exporter;
using SpineViewer.Utilities;
using SpineViewer.Natives;
namespace SpineViewer
{
internal partial class SpineViewerForm : Form
{
private readonly Logger logger = LogManager.GetCurrentClassLogger();
private readonly Dictionary<string, Exporter.Exporter> exporterCache = [];
public SpineViewerForm()
{
InitializeComponent();
InitializeLogConfiguration();
// 执行一些初始化工作
try
{
SFMLShader.Init();
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to load fragment shader");
MessagePopup.Warn("Fragment shader 加载失败预乘Alpha通道属性失效");
}
}
/// <summary>
/// 初始化窗口日志器
/// </summary>
private void InitializeLogConfiguration()
{
// 窗口日志
var rtbTarget = new NLog.Windows.Forms.RichTextBoxTarget
{
Name = "rtbTarget",
TargetForm = this,
TargetRichTextBox = rtbLog,
AutoScroll = true,
MaxLines = 3000,
SupportLinks = true,
Layout = "[${level:format=OneLetter}]${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${message}"
};
rtbTarget.WordColoringRules.Add(new("[D]", "Gray", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[I]", "DimGray", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[W]", "DarkOrange", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[E]", "Red", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[F]", "DarkRed", "Empty", FontStyle.Bold));
LogManager.Configuration.AddTarget(rtbTarget);
LogManager.Configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, rtbTarget);
LogManager.ReconfigExistingLoggers();
}
private void MainForm_Load(object sender, EventArgs e)
{
spinePreviewer.StartRender();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
spinePreviewer.StopRender();
}
private void toolStripMenuItem_Open_Click(object sender, EventArgs e)
{
spineListView.Add();
}
private void toolStripMenuItem_BatchOpen_Click(object sender, EventArgs e)
{
spineListView.BatchAdd();
}
#region private void toolStripMenuItem_ExportXXX_Click(object sender, EventArgs e)
private void toolStripMenuItem_ExportFrame_Click(object sender, EventArgs e)
{
if (spinePreviewer.IsUpdating && MessagePopup.Quest("画面仍在更新,建议手动暂停画面后导出固定的一帧,是否继续?") != DialogResult.OK)
return;
var k = nameof(toolStripMenuItem_ExportFrame);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new FrameExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new FrameExporterWrapper((FrameExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportFrameSequence_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportFrameSequence);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new FrameSequenceExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new FrameSequenceExporterWrapper((FrameSequenceExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportGif_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportGif);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new GifExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new GifExporterWrapper((GifExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportWebp_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportWebp);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new WebpExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new WebpExporterWrapper((WebpExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportAvif_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportAvif);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new AvifExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new AvifExporterWrapper((AvifExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportMp4_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportMp4);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new Mp4Exporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new Mp4ExporterWrapper((Mp4Exporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportWebm_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportWebm);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new WebmExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new WebmExporterWrapper((WebmExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportMkv_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportMkv);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new MkvExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new MkvExporterWrapper((MkvExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportMov_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportMov);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new MovExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new MovExporterWrapper((MovExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportCustom_Click(object sender, EventArgs e)
{
var k = nameof(toolStripMenuItem_ExportCustom);
if (!exporterCache.ContainsKey(k)) exporterCache[k] = new CustomExporter();
var exporter = exporterCache[k];
exporter.Resolution = spinePreviewer.Resolution;
exporter.View = spinePreviewer.GetView();
exporter.RenderSelectedOnly = spinePreviewer.RenderSelectedOnly;
var exportDialog = new Dialogs.ExportDialog(new CustomExporterWrapper((CustomExporter)exporter));
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += Export_Work;
progressDialog.RunWorkerAsync(exporter);
progressDialog.ShowDialog();
}
#endregion
private void toolStripMenuItem_Exit_Click(object sender, EventArgs e)
{
Close();
}
private void toolStripMenuItem_ConvertFileFormat_Click(object sender, EventArgs e)
{
var openDialog = new Dialogs.ConvertFileFormatDialog();
if (openDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += ConvertFileFormat_Work;
progressDialog.RunWorkerAsync(openDialog.Result);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ManageResource_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem_About_Click(object sender, EventArgs e)
{
using var dialog = new Dialogs.AboutDialog();
dialog.ShowDialog();
}
private void toolStripMenuItem_Diagnostics_Click(object sender, EventArgs e)
{
using var dialog = new Dialogs.DiagnosticsDialog();
dialog.ShowDialog();
}
private void splitContainer_SplitterMoved(object sender, SplitterEventArgs e) => ActiveControl = null;
private void splitContainer_MouseUp(object sender, MouseEventArgs e) => ActiveControl = null;
private void propertyGrid_PropertyValueChanged(object sender, PropertyValueChangedEventArgs e)
{
// 用来解决对面板某些值修改之后, 其他被联动修改的值不会实时刷新的问题
(sender as PropertyGrid)?.Refresh();
}
private void Export_Work(object? sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
var exporter = (Exporter.Exporter)e.Argument;
Invoke(() => TaskbarManager.SetProgressState(Handle, TBPFLAG.TBPF_INDETERMINATE));
spinePreviewer.StopRender();
lock (spineListView.Spines) { exporter.Export(spineListView.Spines.Where(sp => !sp.IsHidden).ToArray(), (BackgroundWorker)sender); }
e.Cancel = worker.CancellationPending;
spinePreviewer.StartRender();
Invoke(() => TaskbarManager.SetProgressState(Handle, TBPFLAG.TBPF_NOPROGRESS));
}
private void ConvertFileFormat_Work(object? sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
var arguments = e.Argument as Dialogs.ConvertFileFormatDialogResult;
var skelPaths = arguments.SkelPaths;
var srcVersion = arguments.SourceVersion;
var tgtVersion = arguments.TargetVersion;
var jsonTarget = arguments.JsonTarget;
var newSuffix = jsonTarget ? ".json" : ".skel";
int totalCount = skelPaths.Length;
int success = 0;
int error = 0;
SkeletonConverter srcCvter = srcVersion != SpineVersion.Auto ? SkeletonConverter.New(srcVersion) : null;
SkeletonConverter tgtCvter = SkeletonConverter.New(tgtVersion);
worker.ReportProgress(0, $"已处理 0/{totalCount}");
for (int i = 0; i < totalCount; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
var skelPath = skelPaths[i];
var newPath = Path.ChangeExtension(skelPath, newSuffix);
try
{
if (srcVersion == SpineVersion.Auto)
{
try
{
srcCvter = SkeletonConverter.New(SpineHelper.GetVersion(skelPath));
}
catch (Exception ex)
{
throw new InvalidDataException($"Auto version detection failed for {skelPath}, try to use a specific version", ex);
}
}
var root = srcCvter.Read(skelPath);
root = srcCvter.ToVersion(root, tgtVersion);
if (jsonTarget) tgtCvter.WriteJson(root, newPath); else tgtCvter.WriteBinary(root, newPath);
success++;
}
catch (Exception ex)
{
logger.Error(ex.ToString());
logger.Error("Failed to convert {}", skelPath);
error++;
}
worker.ReportProgress((int)((i + 1) * 100.0) / totalCount, $"已处理 {i + 1}/{totalCount}");
}
if (error > 0)
{
logger.Warn("Batch convert {} successfully, {} failed", success, error);
}
else
{
logger.Info("{} skel converted successfully", success);
}
}
//private System.Windows.Forms.Timer timer = new();
//private PetForm pet = new PetForm();
//private IntPtr screenDC;
//private IntPtr memDC;
//private void _Test()
//{
// screenDC = Win32.GetDC(IntPtr.Zero);
// memDC = Win32.CreateCompatibleDC(screenDC);
// pet.Show();
// timer.Tick += Timer_Tick;
// timer.Enabled = true;
// timer.Interval = 50;
// timer.Start();
//}
//private void Timer_Tick(object? sender, EventArgs e)
//{
// using var tex = new SFML.Graphics.RenderTexture((uint)pet.Width, (uint)pet.Height);
// var v = spinePreviewer.GetView();
// tex.SetView(v);
// tex.Clear(new SFML.Graphics.Color(0, 0, 0, 0));
// lock (spineListView.Spines)
// {
// foreach (var sp in spineListView.Spines)
// tex.Draw(sp);
// }
// tex.Display();
// using var frame = new SFMLImageVideoFrame(tex.Texture.CopyToImage());
// using var bitmap = frame.CopyToBitmap();
// var newBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
// var oldBitmap = Win32.SelectObject(memDC, newBitmap);
// Win32.SIZE size = new Win32.SIZE { cx = pet.Width, cy = pet.Height };
// Win32.POINT srcPos = new Win32.POINT { x = 0, y = 0 };
// Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION { BlendOp = 0, BlendFlags = 0, SourceConstantAlpha = 255, AlphaFormat = Win32.AC_SRC_ALPHA };
// Win32.UpdateLayeredWindow(pet.Handle, screenDC, IntPtr.Zero, ref size, memDC, ref srcPos, 0, ref blend, Win32.ULW_ALPHA);
// Win32.SelectObject(memDC, oldBitmap);
// Win32.DeleteObject(newBitmap);
//}
//private void spinePreviewer_KeyDown(object sender, KeyEventArgs e)
//{
// switch (e.KeyCode)
// {
// case Keys.Space:
// if ((ModifierKeys & Keys.Alt) != 0)
// spinePreviewer.ClickStopButton();
// else
// spinePreviewer.ClickStartButton();
// break;
// case Keys.Right:
// if ((ModifierKeys & Keys.Alt) != 0)
// spinePreviewer.ClickForwardFastButton();
// else
// spinePreviewer.ClickForwardStepButton();
// break;
// case Keys.Left:
// if ((ModifierKeys & Keys.Alt) != 0)
// spinePreviewer.ClickRestartButton();
// break;
// }
//}
}
}

View File

@@ -1,268 +0,0 @@
using NLog;
using SpineViewer.Spine;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace SpineViewer
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
InitializeLogConfiguration();
}
/// <summary>
/// 初始化窗口日志器
/// </summary>
private void InitializeLogConfiguration()
{
// 窗口日志
var rtbTarget = new NLog.Windows.Forms.RichTextBoxTarget
{
Name = "rtbTarget",
TargetForm = this,
TargetRichTextBox = rtbLog,
AutoScroll = true,
MaxLines = 3000,
SupportLinks = true,
Layout = "[${level:format=OneLetter}]${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${message}"
};
rtbTarget.WordColoringRules.Add(new("[D]", "Gray", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[I]", "DimGray", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[W]", "DarkOrange", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[E]", "Red", "Empty", FontStyle.Bold));
rtbTarget.WordColoringRules.Add(new("[F]", "DarkRed", "Empty", FontStyle.Bold));
LogManager.Configuration.AddTarget(rtbTarget);
LogManager.Configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, rtbTarget);
LogManager.ReconfigExistingLoggers();
}
private void MainForm_Load(object sender, EventArgs e)
{
spinePreviewer.StartPreview();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
spinePreviewer.StopPreview();
}
private void toolStripMenuItem_Open_Click(object sender, EventArgs e)
{
spineListView.Add();
}
private void toolStripMenuItem_BatchOpen_Click(object sender, EventArgs e)
{
spineListView.BatchAdd();
}
private void toolStripMenuItem_Export_Click(object sender, EventArgs e)
{
lock (spineListView.Spines)
{
if (spineListView.Spines.Count <= 0)
{
MessageBox.Show("请至少打开一个骨骼文件", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
}
var exportDialog = new Dialogs.ExportPngDialog();
if (exportDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += ExportPng_Work;
progressDialog.RunWorkerAsync(exportDialog);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ExportPreview_Click(object sender, EventArgs e)
{
spineListView.ExportPreviews();
}
private void toolStripMenuItem_Exit_Click(object sender, EventArgs e)
{
Close();
}
private void toolStripMenuItem_ResetAnimation_Click(object sender, EventArgs e)
{
lock (spineListView.Spines)
{
foreach (var spine in spineListView.Spines)
spine.CurrentAnimation = spine.CurrentAnimation;
}
}
private void toolStripMenuItem_ConvertFileFormat_Click(object sender, EventArgs e)
{
var openDialog = new Dialogs.ConvertFileFormatDialog();
if (openDialog.ShowDialog() != DialogResult.OK)
return;
var progressDialog = new Dialogs.ProgressDialog();
progressDialog.DoWork += ConvertFileFormat_Work;
progressDialog.RunWorkerAsync(openDialog);
progressDialog.ShowDialog();
}
private void toolStripMenuItem_ManageResource_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem_About_Click(object sender, EventArgs e)
{
(new Dialogs.AboutDialog()).ShowDialog();
}
private void toolStripMenuItem_Diagnostics_Click(object sender, EventArgs e)
{
(new Dialogs.DiagnosticsDialog()).ShowDialog();
}
private void splitContainer_SplitterMoved(object sender, SplitterEventArgs e) { ActiveControl = null; }
private void splitContainer_MouseUp(object sender, MouseEventArgs e) { ActiveControl = null; }
private void propertyGrid_PropertyValueChanged(object sender, PropertyValueChangedEventArgs e) { (sender as PropertyGrid)?.Refresh(); }
private void spinePreviewer_MouseUp(object sender, MouseEventArgs e) { propertyGrid_Spine.Refresh(); }
private void ExportPng_Work(object? sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
var arguments = e.Argument as Dialogs.ExportPngDialog;
var outputDir = arguments.OutputDir;
var duration = arguments.Duration;
var fps = arguments.Fps;
var timestamp = DateTime.Now.ToString("yyMMddHHmmss");
var resolution = spinePreviewer.Resolution;
var tex = new SFML.Graphics.RenderTexture((uint)resolution.Width, (uint)resolution.Height);
tex.SetView(spinePreviewer.View);
var delta = 1f / fps;
var frameCount = 1 + (int)(duration / delta); // 零帧开始导出
spinePreviewer.StopPreview();
lock (spineListView.Spines)
{
var spinesReverse = spineListView.Spines.Reverse();
// 重置动画时间
foreach (var spine in spinesReverse)
spine.CurrentAnimation = spine.CurrentAnimation;
Program.Logger.Info(
"Begin exporting png frames to output dir {}, duration: {}, fps: {}, totally {} spines",
[outputDir, duration, fps, spinesReverse.Count()]
);
// 逐帧导出
var success = 0;
worker.ReportProgress(0, $"已处理 0/{frameCount}");
for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
{
if (worker.CancellationPending)
break;
tex.Clear(SFML.Graphics.Color.Transparent);
foreach (var spine in spinesReverse)
{
tex.Draw(spine);
spine.Update(delta);
}
tex.Display();
using (var img = tex.Texture.CopyToImage())
{
img.SaveToFile(Path.Combine(outputDir, $"{timestamp}_{fps}_{frameIndex:d6}.png"));
}
success++;
worker.ReportProgress((int)((frameIndex + 1) * 100.0) / frameCount, $"已处理 {frameIndex + 1}/{frameCount}");
}
Program.Logger.Info("Exporting done: {}/{}", success, frameCount);
}
spinePreviewer.StartPreview();
}
private void ConvertFileFormat_Work(object? sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
var arguments = e.Argument as Dialogs.ConvertFileFormatDialog;
var skelPaths = arguments.SkelPaths;
var srcVersion = arguments.SourceVersion;
var tgtVersion = arguments.TargetVersion;
var jsonSource = arguments.JsonSource;
var jsonTarget = arguments.JsonTarget;
var newSuffix = jsonTarget ? ".json" : ".skel";
if (jsonTarget == jsonSource)
{
if (tgtVersion == srcVersion)
return;
else
newSuffix += $".{tgtVersion.ToString().ToLower()}"; // TODO: 仅转换版本的情况下考虑文件覆盖问题
}
int totalCount = skelPaths.Length;
int success = 0;
int error = 0;
SkeletonConverter srcCvter = SkeletonConverter.New(srcVersion);
SkeletonConverter tgtCvter = tgtVersion == srcVersion ? srcCvter : SkeletonConverter.New(tgtVersion);
worker.ReportProgress(0, $"已处理 0/{totalCount}");
for (int i = 0; i < totalCount; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
var skelPath = skelPaths[i];
var newPath = Path.ChangeExtension(skelPath, newSuffix);
try
{
var root = jsonSource ? srcCvter.ReadJson(skelPath) : srcCvter.ReadBinary(skelPath);
if (tgtVersion != srcVersion) root = srcCvter.ToVersion(root, tgtVersion);
if (jsonTarget) tgtCvter.WriteJson(root, newPath); else tgtCvter.WriteBinary(root, newPath);
success++;
}
catch (Exception ex)
{
Program.Logger.Error(ex.ToString());
Program.Logger.Error("Failed to convert {}", skelPath);
error++;
}
worker.ReportProgress((int)((i + 1) * 100.0) / totalCount, $"已处理 {i + 1}/{totalCount}");
}
if (error > 0)
{
Program.Logger.Warn("Batch convert {} successfully, {} failed", success, error);
}
else
{
Program.Logger.Info("{} skel converted successfully", success);
}
}
}
}

View File

@@ -0,0 +1,65 @@
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SpineViewer.Natives
{
internal enum TBPFLAG
{
TBPF_NOPROGRESS = 0,
TBPF_INDETERMINATE = 0x1,
TBPF_NORMAL = 0x2,
TBPF_ERROR = 0x4,
TBPF_PAUSED = 0x8
}
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport, Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")]
internal interface ITaskbarList3
{
// ITaskbarList
void HrInit();
void AddTab(nint hwnd);
void DeleteTab(nint hwnd);
void ActivateTab(nint hwnd);
void SetActiveAlt(nint hwnd);
// ITaskbarList2
void MarkFullscreenWindow(nint hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen);
// ITaskbarList3
void SetProgressValue(nint hwnd, ulong ullCompleted, ulong ullTotal);
void SetProgressState(nint hwnd, TBPFLAG tbpFlags);
//void RegisterTab(IntPtr hwndTab, IntPtr hwndMDI);
//void UnregisterTab(IntPtr hwndTab);
//void SetTabOrder(IntPtr hwndTab, IntPtr hwndInsertBefore);
//void SetTabActive(IntPtr hwndTab, IntPtr hwndMDI, uint dwReserved);
//void ThumbBarAddButtons(IntPtr hwnd, uint cButtons, THUMBBUTTON[] pButton);
//void ThumbBarUpdateButtons(IntPtr hwnd, uint cButtons, THUMBBUTTON[] pButton);
//void ThumbBarSetImageList(IntPtr hwnd, IntPtr himl);
//void SetOverlayIcon(IntPtr hwnd, IntPtr hIcon, string pszDescription);
//void SetThumbnailTooltip(IntPtr hwnd, string pszTip);
//void SetThumbnailClip(IntPtr hwnd, ref RECT prcClip);
}
[ComImport, Guid("56FDF344-FD6D-11d0-958A-006097C9A090")]
internal class TaskbarList { }
internal static class TaskbarManager
{
private static readonly ITaskbarList3 taskbarList = (ITaskbarList3)new TaskbarList();
static TaskbarManager()
{
taskbarList.HrInit();
}
public static void SetProgressState(nint windowHandle, TBPFLAG state)
{
taskbarList.SetProgressState(windowHandle, state);
}
public static void SetProgressValue(nint windowHandle, ulong completed, ulong total)
{
taskbarList.SetProgressValue(windowHandle, completed, total);
}
}
}

View File

@@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Natives
{
/// <summary>
/// Win32 Sdk 包装类
/// </summary>
public static class Win32
{
public const int GWL_STYLE = -16;
public const int WS_SIZEBOX = 0x40000;
public const int WS_BORDER = 0x800000;
public const int WS_POPUP = unchecked((int)0x80000000);
public const int GWL_EXSTYLE = -20;
public const int WS_EX_TOPMOST = 0x8;
public const int WS_EX_TRANSPARENT = 0x20;
public const int WS_EX_TOOLWINDOW = 0x80;
public const int WS_EX_WINDOWEDGE = 0x100;
public const int WS_EX_CLIENTEDGE = 0x200;
public const int WS_EX_LAYERED = 0x80000;
public const int WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE;
public const uint LWA_COLORKEY = 0x1;
public const uint LWA_ALPHA = 0x2;
public const byte AC_SRC_OVER = 0x00;
public const byte AC_SRC_ALPHA = 0x01;
public const int ULW_COLORKEY = 0x00000001;
public const int ULW_ALPHA = 0x00000002;
public const int ULW_OPAQUE = 0x00000004;
public const nint HWND_TOPMOST = -1;
public const uint SWP_NOSIZE = 0x0001;
public const uint SWP_NOMOVE = 0x0002;
public const uint SWP_NOZORDER = 0x0004;
public const uint SWP_FRAMECHANGED = 0x0020;
public const uint SWP_REFRESHLONG = SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED;
public const int WM_SPAWN_WORKER = 0x052C; // 一个未公开的神秘消息
public const uint SMTO_NORMAL = 0x0000;
public const uint SMTO_BLOCK = 0x0001;
public const uint SMTO_ABORTIFHUNG = 0x0002;
public const uint SMTO_NOTIMEOUTIFNOTHUNG = 0x0008;
public const uint GA_PARENT = 1;
public const uint GW_OWNER = 4;
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public struct SIZE
{
public int cx;
public int cy;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll", SetLastError = true)]
public static extern nint GetDC(nint hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern int ReleaseDC(nint hWnd, nint hDC);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SetWindowLong(nint hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowLong(nint hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetLayeredWindowAttributes(nint hWnd, ref uint crKey, ref byte bAlpha, ref uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetLayeredWindowAttributes(nint hWnd, uint pcrKey, byte pbAlpha, uint pdwFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UpdateLayeredWindow(nint hWnd, nint hdcDst, nint pptDst, ref SIZE psize, nint hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetWindowPos(nint hWnd, nint hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetDoubleClickTime();
[DllImport("user32.dll", SetLastError = true)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint SendMessageTimeout(nint hWnd, uint Msg, nint wParam, nint lParam, uint fuFlags, uint uTimeout, out nint lpdwResult);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint FindWindowEx(nint parentHandle, nint childAfter, string className, string windowTitle);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint SetParent(nint hWndChild, nint hWndNewParent);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint GetParent(nint hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint GetAncestor(nint hWnd, uint gaFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern nint GetWindow(nint hWnd, uint uCmd);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern nint CreateCompatibleDC(nint hdc);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern bool DeleteDC(nint hdc);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern nint SelectObject(nint hdc, nint hgdiobj);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern bool DeleteObject(nint hObject);
public static TimeSpan GetLastInputElapsedTime()
{
LASTINPUTINFO lastInputInfo = new();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
uint idleTimeMillis = 1000;
if (GetLastInputInfo(ref lastInputInfo))
{
uint tickCount = (uint)Environment.TickCount;
uint lastInputTick = lastInputInfo.dwTime;
idleTimeMillis = tickCount - lastInputTick;
}
return TimeSpan.FromMilliseconds(idleTimeMillis);
}
public static nint GetWorkerW()
{
var progman = FindWindow("Progman", null);
if (progman == nint.Zero)
return nint.Zero;
nint hWnd = FindWindowEx(progman, 0, "WorkerW", null);
Debug.WriteLine($"{hWnd:x8}");
return hWnd;
}
}
}

View File

@@ -1,23 +1,48 @@
using NLog;
using SpineViewer.Utilities;
using System.Diagnostics;
using System.Reflection;
namespace SpineViewer
{
internal static class Program
{
public const string Name = "SpineViewer";
public static readonly string TempDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Name)).FullName;
public static readonly Process Process = Process.GetCurrentProcess();
public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
///// <summary>
///// 程序路径
///// </summary>
//public static readonly string FilePath = Environment.ProcessPath;
///// <summary>
///// 程序名
///// </summary>
//public static readonly string Name = Path.GetFileNameWithoutExtension(FilePath);
///// <summary>
///// 程序目录
///// </summary>
//public static readonly string RootDir = Path.GetDirectoryName(FilePath);
///// <summary>
///// 程序临时目录
///// </summary>
//public static readonly string TempDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Name)).FullName;
public static string Version => Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
/// <summary>
/// The main entry point for the application.
/// 程序日志器
/// </summary>
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 应用入口点
/// </summary>
[STAThread]
static void Main()
{
// 此处先初始化全局配置再触发静态字段 Logger 引用构造, 才能将配置应用到新的日志器上
InitializeLogConfiguration();
Logger.Info("Program Started");
logger.Info("Program Started");
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
@@ -25,12 +50,12 @@ namespace SpineViewer
try
{
Application.Run(new MainForm());
Application.Run(new SpineViewerForm() { Text = $"SpineViewer - v{Version}"});
}
catch (Exception ex)
{
Logger.Fatal(ex.ToString());
MessageBox.Show(ex.ToString(), "程序已崩溃", MessageBoxButtons.OK, MessageBoxIcon.Stop);
logger.Fatal(ex.ToString());
MessagePopup.Error(ex.ToString(), "程序已崩溃");
}
}
@@ -57,6 +82,5 @@ namespace SpineViewer
config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);
LogManager.Configuration = config;
}
}
}

View File

@@ -0,0 +1,44 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class AvifExporterWrapper(AvifExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override AvifExporter Exporter => (AvifExporter)base.Exporter;
/// <summary>
/// 编码器
/// </summary>
[StringEnumConverter.StandardValues("av1_nvenc", "av1_amf", "libaom-av1", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-c:v, 使\n建议使用硬件加速, libaom-av1 ")]
public string Codec { get => Exporter.Codec; set => Exporter.Codec = value; }
/// <summary>
/// CRF
/// </summary>
[Category("[3] "), DisplayName("CRF"), Description("-crf, 0-63, 18-28, 23, ")]
public int CRF { get => Exporter.CRF; set => Exporter.CRF = value; }
/// <summary>
/// 像素格式
/// </summary>
[StringEnumConverter.StandardValues("yuv420p", "yuv422p", "yuv444p", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-pix_fmt, 使")]
public string PixelFormat { get => Exporter.PixelFormat; set => Exporter.PixelFormat = value; }
/// <summary>
/// 循环次数
/// </summary>
[Category("[3] "), DisplayName(""), Description("-loop, , 0 , [0, 65535]")]
public int Loop { get => Exporter.Loop; set => Exporter.Loop = value; }
}
}

View File

@@ -0,0 +1,34 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class CustomExporterWrapper(CustomExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override CustomExporter Exporter => (CustomExporter)base.Exporter;
[Browsable(false)]
public override string Format => Exporter.Format;
[Browsable(false)]
public override string Suffix => Exporter.Suffix;
/// <summary>
/// 文件格式
/// </summary>
[Category("[2] FFmpeg "), DisplayName(""), Description("-f, ")]
public string CustomFormat { get => Exporter.CustomFormat; set => Exporter.CustomFormat = value; }
/// <summary>
/// 文件名后缀
/// </summary>
[Category("[2] FFmpeg "), DisplayName(""), Description("")]
public string CustomSuffix { get => Exporter.CustomSuffix; set => Exporter.CustomSuffix = value; }
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class ExporterWrapper(SpineViewer.Exporter.Exporter exporter)
{
[Browsable(false)]
public virtual SpineViewer.Exporter.Exporter Exporter { get; } = exporter;
/// <summary>
/// 输出文件夹
/// </summary>
[Editor(typeof(FolderNameEditor), typeof(UITypeEditor))]
[Category("[0] "), DisplayName(""), Description("")]
public string? OutputDir { get => Exporter.OutputDir; set => Exporter.OutputDir = value; }
/// <summary>
/// 导出单个
/// </summary>
[Category("[0] "), DisplayName(""), Description("")]
public bool IsExportSingle { get => Exporter.IsExportSingle; set => Exporter.IsExportSingle = value; }
/// <summary>
/// 画面分辨率
/// </summary>
[TypeConverter(typeof(SizeConverter))]
[Category("[0] "), DisplayName(""), Description("")]
public Size Resolution { get => Exporter.Resolution; }
/// <summary>
/// 渲染视窗
/// </summary>
[Category("[0] "), DisplayName(""), Description("")]
public SFML.Graphics.View View { get => Exporter.View; }
/// <summary>
/// 是否仅渲染选中
/// </summary>
[Category("[0] "), DisplayName(""), Description("")]
public bool RenderSelectedOnly { get => Exporter.RenderSelectedOnly; }
/// <summary>
/// 背景颜色
/// </summary>
[Editor(typeof(SFMLColorEditor), typeof(UITypeEditor))]
[TypeConverter(typeof(SFMLColorConverter))]
[Category("[0] "), DisplayName(""), Description("使, #RRGGBBAA")]
public SFML.Graphics.Color BackgroundColor { get => Exporter.BackgroundColor; set => Exporter.BackgroundColor = value; }
}
}

View File

@@ -0,0 +1,34 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class FFmpegVideoExporterWrapper(FFmpegVideoExporter exporter) : VideoExporterWrapper(exporter)
{
[Browsable(false)]
public override FFmpegVideoExporter Exporter => (FFmpegVideoExporter)base.Exporter;
/// <summary>
/// 文件格式
/// </summary>
[Category("[2] FFmpeg "), DisplayName(""), Description("-f, ")]
public virtual string Format => Exporter.Format;
/// <summary>
/// 文件名后缀
/// </summary>
[Category("[2] FFmpeg "), DisplayName(""), Description("")]
public virtual string Suffix => Exporter.Suffix;
/// <summary>
/// 文件名后缀
/// </summary>
[Category("[2] FFmpeg "), DisplayName(""), Description("使 \"ffmpeg -h encoder=<编码器>\" 查看编码器支持的参数\n使用 \"ffmpeg -h muxer=<文件格式>\" 查看文件格式支持的参数")]
public string CustomArgument { get => Exporter.CustomArgument; set => Exporter.CustomArgument = value; }
}
}

View File

@@ -0,0 +1,37 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class FrameExporterWrapper(FrameExporter exporter) : ExporterWrapper(exporter)
{
[Browsable(false)]
public override FrameExporter Exporter => (FrameExporter)base.Exporter;
/// <summary>
/// 单帧画面格式
/// </summary>
[TypeConverter(typeof(ImageFormatConverter))]
[Category("[1] "), DisplayName("")]
public ImageFormat ImageFormat { get => Exporter.ImageFormat; set => Exporter.ImageFormat = value; }
/// <summary>
/// 文件名后缀
/// </summary>
[Category("[1] "), DisplayName(""), Description("")]
public string Suffix { get => Exporter.ImageFormat.GetSuffix(); }
/// <summary>
/// DPI
/// </summary>
[TypeConverter(typeof(SizeFConverter))]
[Category("[1] "), DisplayName("DPI"), Description("")]
public SizeF DPI { get => Exporter.DPI; set => Exporter.DPI = value; }
}
}

View File

@@ -0,0 +1,23 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class FrameSequenceExporterWrapper(VideoExporter exporter) : VideoExporterWrapper(exporter)
{
[Browsable(false)]
public override FrameSequenceExporter Exporter => (FrameSequenceExporter)base.Exporter;
/// <summary>
/// 文件名后缀
/// </summary>
[TypeConverter(typeof(StringEnumConverter)), StringEnumConverter.StandardValues(".png", ".jpg", ".tga", ".bmp")]
[Category("[2] "), DisplayName(""), Description("")]
public string Suffix { get => Exporter.Suffix; set => Exporter.Suffix = value; }
}
}

View File

@@ -0,0 +1,34 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
class GifExporterWrapper(FFmpegVideoExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override GifExporter Exporter => (GifExporter)base.Exporter;
/// <summary>
/// 调色板最大颜色数量
/// </summary>
[Category("[3] "), DisplayName(""), Description("使, ")]
public uint MaxColors { get => Exporter.MaxColors; set => Exporter.MaxColors = value; }
/// <summary>
/// 透明度阈值
/// </summary>
[Category("[3] "), DisplayName(""), Description("")]
public byte AlphaThreshold { get => Exporter.AlphaThreshold; set => Exporter.AlphaThreshold = value; }
/// <summary>
/// 透明度阈值
/// </summary>
[Category("[3] "), DisplayName(""), Description("-loop, , -1 , 0 , [-1, 65535]")]
public int Loop { get => Exporter.Loop; set => Exporter.Loop = value; }
}
}

View File

@@ -0,0 +1,38 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class MkvExporterWrapper(FFmpegVideoExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override MkvExporter Exporter => (MkvExporter)base.Exporter;
/// <summary>
/// 编码器
/// </summary>
[StringEnumConverter.StandardValues("libx264", "libx265", "libvpx-vp9", "av1_nvenc", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-c:v, 使")]
public string Codec { get => Exporter.Codec; set => Exporter.Codec = value; }
/// <summary>
/// CRF
/// </summary>
[Category("[3] "), DisplayName("CRF"), Description("-crf, 0-63, 18-28, 23, ")]
public int CRF { get => Exporter.CRF; set => Exporter.CRF = value; }
/// <summary>
/// 像素格式
/// </summary>
[StringEnumConverter.StandardValues("yuv420p", "yuv422p", "yuv444p", "yuva420p", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-pix_fmt, 使")]
public string PixelFormat { get => Exporter.PixelFormat; set => Exporter.PixelFormat = value; }
}
}

View File

@@ -0,0 +1,40 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class MovExporterWrapper(FFmpegVideoExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override MovExporter Exporter => (MovExporter)base.Exporter;
/// <summary>
/// 编码器
/// </summary>
[StringEnumConverter.StandardValues("prores_ks", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-c:v, 使")]
public string Codec { get => Exporter.Codec; set => Exporter.Codec = value; }
/// <summary>
/// 预设
/// </summary>
[StringEnumConverter.StandardValues("auto", "proxy", "lt", "standard", "hq", "4444", "4444xq")]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-profile, ")]
public string Profile { get => Exporter.Profile; set => Exporter.Profile = value; }
/// <summary>
/// 像素格式
/// </summary>
[StringEnumConverter.StandardValues("yuv422p10le", "yuv444p10le", "yuva444p10le", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-pix_fmt, 使")]
public string PixelFormat { get => Exporter.PixelFormat; set => Exporter.PixelFormat = value; }
}
}

View File

@@ -0,0 +1,38 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class Mp4ExporterWrapper(FFmpegVideoExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override Mp4Exporter Exporter => (Mp4Exporter)base.Exporter;
/// <summary>
/// 编码器
/// </summary>
[StringEnumConverter.StandardValues("libx264", "libx265", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-c:v, 使")]
public string Codec { get => Exporter.Codec; set => Exporter.Codec = value; }
/// <summary>
/// CRF
/// </summary>
[Category("[3] "), DisplayName("CRF"), Description("-crf, 0-63, 18-28, 23, ")]
public int CRF { get => Exporter.CRF; set => Exporter.CRF = value; }
/// <summary>
/// 像素格式
/// </summary>
[StringEnumConverter.StandardValues("yuv420p", "yuv422p", "yuv444p", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-pix_fmt, 使")]
public string PixelFormat { get => Exporter.PixelFormat; set => Exporter.PixelFormat = value; }
}
}

View File

@@ -0,0 +1,34 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class VideoExporterWrapper(VideoExporter exporter) : ExporterWrapper(exporter)
{
[Browsable(false)]
public override VideoExporter Exporter => (VideoExporter)base.Exporter;
/// <summary>
/// 导出时长
/// </summary>
[Category("[1] "), DisplayName(""), Description(", 0, 使")]
public float Duration { get => Exporter.Duration; set => Exporter.Duration = value; }
/// <summary>
/// 帧率
/// </summary>
[Category("[1] "), DisplayName(""), Description("")]
public float FPS { get => Exporter.FPS; set => Exporter.FPS = value; }
/// <summary>
/// 保留最后一帧
/// </summary>
[Category("[1] "), DisplayName(""), Description(", , 1")]
public bool KeepLast { get => Exporter.KeepLast; set => Exporter.KeepLast = value; }
}
}

View File

@@ -0,0 +1,38 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class WebmExporterWrapper(WebmExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override WebmExporter Exporter => (WebmExporter)base.Exporter;
/// <summary>
/// 编码器
/// </summary>
[StringEnumConverter.StandardValues("libvpx-vp9", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-c:v, 使")]
public string Codec { get => Exporter.Codec; set => Exporter.Codec = value; }
/// <summary>
/// CRF
/// </summary>
[Category("[3] "), DisplayName("CRF"), Description("-crf, 0-63, 18-28, 23, ")]
public int CRF { get => Exporter.CRF; set => Exporter.CRF = value; }
/// <summary>
/// 像素格式
/// </summary>
[StringEnumConverter.StandardValues("yuv420p", "yuv422p", "yuv444p", "yuva420p", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-pix_fmt, 使")]
public string PixelFormat { get => Exporter.PixelFormat; set => Exporter.PixelFormat = value; }
}
}

View File

@@ -0,0 +1,50 @@
using SpineViewer.Exporter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Exporter
{
public class WebpExporterWrapper(WebpExporter exporter) : FFmpegVideoExporterWrapper(exporter)
{
[Browsable(false)]
public override WebpExporter Exporter => (WebpExporter)base.Exporter;
/// <summary>
/// 编码器
/// </summary>
[StringEnumConverter.StandardValues("libwebp_anim", "libwebp", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-c:v, 使")]
public string Codec { get => Exporter.Codec; set => Exporter.Codec = value; }
/// <summary>
/// 是否无损
/// </summary>
[Category("[3] "), DisplayName(""), Description("-lossless, 0 , 1 ")]
public bool Lossless { get => Exporter.Lossless; set => Exporter.Lossless = value; }
/// <summary>
/// CRF
/// </summary>
[Category("[3] "), DisplayName(""), Description("-quality, 0-100, 75")]
public int Quality { get => Exporter.Quality; set => Exporter.Quality = value; }
/// <summary>
/// 像素格式
/// </summary>
[StringEnumConverter.StandardValues("yuv420p", "yuva420p", Customizable = true)]
[TypeConverter(typeof(StringEnumConverter))]
[Category("[3] "), DisplayName(""), Description("-pix_fmt, 使")]
public string PixelFormat { get => Exporter.PixelFormat; set => Exporter.PixelFormat = value; }
/// <summary>
/// 透明度阈值
/// </summary>
[Category("[3] "), DisplayName(""), Description("-loop, , 0 , [0, 65535]")]
public int Loop { get => Exporter.Loop; set => Exporter.Loop = value; }
}
}

View File

@@ -0,0 +1,170 @@
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
/// <summary>
/// 对轨道索引属性的包装类, 能够在面板上显示例如时长的属性, 但是处理该属性时按字符串去处理, 例如 ToString 和判断对象相等都是用动画名称实现逻辑
/// </summary>
/// <param name="spine"></param>
/// <param name="i"></param>
[TypeConverter(typeof(TrackWrapperConverter))]
public class TrackWrapper(SpineViewer.Spine.Spine spine, int i)
{
private readonly SpineViewer.Spine.Spine spine = spine;
[Browsable(false)]
public int Index { get; } = i;
[DisplayName("时长")]
public float Duration => spine.GetAnimationDuration(spine.GetAnimation(Index));
/// <summary>
/// 实现了默认的转为字符串的方式
/// </summary>
public override string ToString() => spine.GetAnimation(Index);
/// <summary>
/// 影响了属性面板的判断, 当动画名称相同的时候认为两个对象是相同的, 这样属性面板可以在多选的时候正确显示相同取值的内容
/// </summary>
public override bool Equals(object? obj)
{
if (obj is TrackWrapper) return ToString() == obj.ToString();
return base.Equals(obj);
}
/// <summary>
/// 哈希码需要和 Equals 行为类似
/// </summary>
public override int GetHashCode() => HashCode.Combine(typeof(TrackWrapper).FullName.GetHashCode(), ToString().GetHashCode());
}
/// <summary>
/// 用于在 PropertyGrid 上显示 Spine 动画列表的包装类
/// </summary>
public class SpineAnimationWrapper(SpineViewer.Spine.Spine spine) : ICustomTypeDescriptor
{
/// <summary>
/// 轨道属性描述符, 实现对属性的读取和赋值
/// </summary>
/// <param name="i">轨道索引</param>
private class TrackWrapperPropertyDescriptor(int i, Attribute[]? attributes) : PropertyDescriptor($"Track{i}", attributes)
{
private readonly int idx = i;
public override Type ComponentType => typeof(SpineAnimationWrapper);
public override bool IsReadOnly => false;
public override Type PropertyType => typeof(TrackWrapper);
public override bool CanResetValue(object component) => false;
public override void ResetValue(object component) { }
public override bool ShouldSerializeValue(object component) => false;
/// <summary>
/// 得到一个轨道包装类, 允许用户查看或者修改具体的属性值, 这个地方决定了在面板上看到的是一个对象及其属性
/// </summary>
public override object? GetValue(object? component)
{
if (component is SpineAnimationWrapper tracks)
return tracks.GetTrackWrapper(idx);
return null;
}
/// <summary>
/// 允许通过字符串赋值修改该轨道的动画, 这里决定了当其他地方的调用 (比如 Converter) 通过 value 来设置属性值的时候应该怎么处理
/// </summary>
public override void SetValue(object? component, object? value)
{
if (component is SpineAnimationWrapper tracks)
{
if (value is string s)
tracks.SetTrackWrapper(idx, s);
}
}
}
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
/// <summary>
/// 全轨道动画最大时长
/// </summary>
[DisplayName("全轨道最大时长")]
public float AnimationTracksMaxDuration => Spine.GetTrackIndices().Select(i => Spine.GetAnimationDuration(Spine.GetAnimation(i))).Max();
/// <summary>
/// TrackWrapper 属性对象缓存
/// </summary>
private readonly Dictionary<int, TrackWrapper> trackWrapperProperties = [];
/// <summary>
/// 访问 TrackWrapper 属性 <c>AnimationTracks.Track{i}</c>
/// </summary>
public TrackWrapper GetTrackWrapper(int i)
{
if (!trackWrapperProperties.ContainsKey(i))
trackWrapperProperties[i] = new TrackWrapper(Spine, i);
return trackWrapperProperties[i];
}
/// <summary>
/// 设置 TrackWrapper 属性 <c>AnimationTracks.Track{i} = <paramref name="value"/></c>
/// </summary>
public void SetTrackWrapper(int i, string value)
{
Spine.SetAnimation(i, value);
TypeDescriptor.Refresh(this);
}
/// <summary>
/// 在属性面板悬停可以按轨道顺序显示动画名称
/// </summary>
public override string ToString() => $"[{string.Join(", ", Spine.GetTrackIndices().Select(Spine.GetAnimation))}]";
public override bool Equals(object? obj)
{
if (obj is SpineAnimationWrapper wrapper) return ToString() == wrapper.ToString();
return base.Equals(obj);
}
public override int GetHashCode() => HashCode.Combine(typeof(SpineAnimationWrapper).FullName.GetHashCode(), ToString().GetHashCode());
#region ICustomTypeDescriptor
// XXX: 必须实现 ICustomTypeDescriptor 接口, 不能继承 CustomTypeDescriptor, 似乎继承下来的东西会有问题, 导致某些调用不正确
/// <summary>
/// 属性描述符缓存
/// </summary>
private static readonly Dictionary<int, TrackWrapperPropertyDescriptor> pdCache = [];
public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public string? GetClassName() => TypeDescriptor.GetClassName(this, true);
public string? GetComponentName() => TypeDescriptor.GetComponentName(this, true);
public TypeConverter? GetConverter() => TypeDescriptor.GetConverter(this, true);
public EventDescriptor? GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
public PropertyDescriptor? GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public object? GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
public EventDescriptorCollection GetEvents(Attribute[]? attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public object? GetPropertyOwner(PropertyDescriptor? pd) => this;
public PropertyDescriptorCollection GetProperties() => GetProperties(null);
public PropertyDescriptorCollection GetProperties(Attribute[]? attributes)
{
var props = new PropertyDescriptorCollection(TypeDescriptor.GetProperties(this, attributes, true).Cast<PropertyDescriptor>().ToArray());
foreach (var i in Spine.GetTrackIndices())
{
if (!pdCache.ContainsKey(i))
pdCache[i] = new TrackWrapperPropertyDescriptor(i, [new DisplayNameAttribute($"轨道 {i}")]);
props.Add(pdCache[i]);
}
return props;
}
#endregion
}
}

View File

@@ -0,0 +1,56 @@
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
/// <summary>
/// 用于在 PropertyGrid 上显示 Spine 基本信息的包装类
/// </summary>
public class SpineBaseInfoWrapper(SpineViewer.Spine.Spine spine)
{
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
/// <summary>
/// 获取所属版本
/// </summary>
[TypeConverter(typeof(SpineVersionConverter))]
[DisplayName("运行时版本")]
public SpineVersion Version => Spine.Version;
/// <summary>
/// 资源所在完整目录
/// </summary>
[DisplayName("资源目录")]
public string AssetsDir => Spine.AssetsDir;
/// <summary>
/// skel 文件完整路径
/// </summary>
[DisplayName("skel文件路径")]
public string SkelPath => Spine.SkelPath;
/// <summary>
/// atlas 文件完整路径
/// </summary>
[DisplayName("atlas文件路径")]
public string AtlasPath => Spine.AtlasPath;
/// <summary>
/// 名称
/// </summary>
[DisplayName("名称")]
public string Name => Spine.Name;
/// <summary>
/// 获取所属文件版本
/// </summary>
[DisplayName("文件版本")]
public string FileVersion => Spine.FileVersion;
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
/// <summary>
/// 用于在 PropertyGrid 上显示 Spine 调试属性的包装类
/// </summary>
public class SpineDebugWrapper(SpineViewer.Spine.Spine spine)
{
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
/// <summary>
/// 显示纹理
/// </summary>
[DisplayName("纹理")]
public bool DebugTexture { get => Spine.DebugTexture; set => Spine.DebugTexture = value; }
/// <summary>
/// 显示包围盒
/// </summary>
[DisplayName("包围盒")]
public bool DebugBounds { get => Spine.DebugBounds; set => Spine.DebugBounds = value; }
/// <summary>
/// 显示骨骼
/// </summary>
[DisplayName("骨架")]
public bool DebugBones { get => Spine.DebugBones; set => Spine.DebugBones = value; }
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
/// <summary>
/// 用于在 PropertyGrid 上显示 Spine 渲染设置的包装类
/// </summary>
public class SpineRenderWrapper(SpineViewer.Spine.Spine spine)
{
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
/// <summary>
/// 是否被隐藏, 被隐藏的模型将仅仅在列表显示, 不参与其他行为
/// </summary>
[DisplayName("是否隐藏")]
public bool IsHidden { get => Spine.IsHidden; set => Spine.IsHidden = value; }
/// <summary>
/// 是否使用预乘Alpha
/// </summary>
[DisplayName("预乘Alpha通道")]
public bool UsePremultipliedAlpha { get => Spine.UsePma; set => Spine.UsePma = value; }
}
}

View File

@@ -0,0 +1,153 @@
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
/// <summary>
/// 对皮肤属性的包装类
/// </summary>
[TypeConverter(typeof(SkinWrapperConverter))]
public class SkinWrapper(SpineViewer.Spine.Spine spine, int i)
{
private readonly SpineViewer.Spine.Spine spine = spine;
[Browsable(false)]
public int Index { get; } = i;
public override string ToString()
{
var loadedSkins = spine.GetLoadedSkins();
if (Index >= 0 && Index < loadedSkins.Length)
return loadedSkins[Index];
return "!NULL"; // XXX: 预期应该不会发生
}
public override bool Equals(object? obj)
{
if (obj is SkinWrapper) return ToString() == obj.ToString();
return base.Equals(obj);
}
public override int GetHashCode() => HashCode.Combine(typeof(SkinWrapper).FullName.GetHashCode(), ToString().GetHashCode());
}
/// <summary>
/// 皮肤列表动态类型包装类, 用于提供对 Spine 皮肤列表的管理能力
/// </summary>
/// <param name="spine">关联的 Spine 对象</param>
public class SpineSkinWrapper(SpineViewer.Spine.Spine spine) : ICustomTypeDescriptor
{
/// <summary>
/// 皮肤属性描述符, 实现对属性的读取和赋值
/// </summary>
private class SkinWrapperPropertyDescriptor(int i, Attribute[]? attributes) : PropertyDescriptor($"Skin{i}", attributes)
{
private readonly int idx = i;
public override Type ComponentType => typeof(SpineSkinWrapper);
public override bool IsReadOnly => false;
public override Type PropertyType => typeof(SkinWrapper);
public override bool CanResetValue(object component) => false;
public override void ResetValue(object component) { }
public override bool ShouldSerializeValue(object component) => false;
/// <summary>
/// 得到一个 SkinWrapper, 允许用户查看或者修改具体的属性值, 这个地方决定了在面板上看到的是一个对象及其属性
/// </summary>
public override object? GetValue(object? component)
{
if (component is SpineSkinWrapper manager)
return manager.GetSkinWrapper(idx);
return null;
}
/// <summary>
/// 允许通过字符串赋值修改该位置的皮肤
/// </summary>
public override void SetValue(object? component, object? value)
{
if (component is SpineSkinWrapper manager)
{
if (value is string s)
manager.SetSkinWrapper(idx, s);
}
}
}
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
/// <summary>
/// SkinWrapper 属性缓存
/// </summary>
private readonly Dictionary<int, SkinWrapper> skinWrapperProperties = [];
/// <summary>
/// 访问 SkinWrapper 属性 <c>SkinManager.Skin{i}</c>
/// </summary>
public SkinWrapper GetSkinWrapper(int i)
{
if (!skinWrapperProperties.ContainsKey(i))
skinWrapperProperties[i] = new SkinWrapper(Spine, i);
return skinWrapperProperties[i];
}
/// <summary>
/// 设置 SkinWrapper 属性 <c>SkinManager.Skin{i} = <paramref name="value"/></c>
/// </summary>
public void SetSkinWrapper(int i, string value)
{
Spine.ReplaceSkin(i, value);
TypeDescriptor.Refresh(this);
}
/// <summary>
/// 在属性面板悬停可以显示已加载的皮肤列表
/// </summary>
public override string ToString() => $"[{string.Join(", ", Spine.GetLoadedSkins())}]";
public override bool Equals(object? obj)
{
if (obj is SpineSkinWrapper wrapper) return ToString() == wrapper.ToString();
return base.Equals(obj);
}
public override int GetHashCode() => HashCode.Combine(typeof(SpineSkinWrapper).FullName.GetHashCode(), ToString().GetHashCode());
#region ICustomTypeDescriptor
// XXX: 必须实现 ICustomTypeDescriptor 接口, 不能继承 CustomTypeDescriptor, 似乎继承下来的东西会有问题, 导致某些调用不正确
private static readonly Dictionary<int, SkinWrapperPropertyDescriptor> pdCache = [];
public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public string? GetClassName() => TypeDescriptor.GetClassName(this, true);
public string? GetComponentName() => TypeDescriptor.GetComponentName(this, true);
public TypeConverter? GetConverter() => TypeDescriptor.GetConverter(this, true);
public EventDescriptor? GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
public PropertyDescriptor? GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public object? GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
public EventDescriptorCollection GetEvents(Attribute[]? attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public object? GetPropertyOwner(PropertyDescriptor? pd) => this;
public PropertyDescriptorCollection GetProperties() => GetProperties(null);
public PropertyDescriptorCollection GetProperties(Attribute[]? attributes)
{
var props = new PropertyDescriptorCollection(TypeDescriptor.GetProperties(this, attributes, true).Cast<PropertyDescriptor>().ToArray());
for (var i = 0; i < Spine.GetLoadedSkins().Length; i++)
{
if (!pdCache.ContainsKey(i))
pdCache[i] = new SkinWrapperPropertyDescriptor(i, [new DisplayNameAttribute($"皮肤 {i}")]);
props.Add(pdCache[i]);
}
return props;
}
#endregion
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
/// <summary>
/// 用于在 PropertyGrid 上显示 Spine 空间变换的包装类
/// </summary>
public class SpineTransformWrapper(SpineViewer.Spine.Spine spine)
{
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
/// <summary>
/// 缩放比例
/// </summary>
[DisplayName("缩放比例")]
public float Scale { get => Spine.Scale; set => Spine.Scale = value; }
/// <summary>
/// 位置
/// </summary>
[TypeConverter(typeof(PointFConverter))]
[DisplayName("位置")]
public PointF Position { get => Spine.Position; set => Spine.Position = value; }
/// <summary>
/// 水平翻转
/// </summary>
[DisplayName("水平翻转")]
public bool FlipX { get => Spine.FlipX; set => Spine.FlipX = value; }
/// <summary>
/// 垂直翻转
/// </summary>
[DisplayName("垂直翻转")]
public bool FlipY { get => Spine.FlipY; set => Spine.FlipY = value; }
}
}

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers.Spine
{
public class SpineWrapper(SpineViewer.Spine.Spine spine)
{
[Browsable(false)]
public SpineViewer.Spine.Spine Spine { get; } = spine;
[DisplayName("基本信息")]
public SpineBaseInfoWrapper BaseInfo { get; } = new(spine);
[DisplayName("渲染")]
public SpineRenderWrapper Render { get; } = new(spine);
[DisplayName("变换")]
public SpineTransformWrapper Transform { get; } = new(spine);
[TypeConverter(typeof(ExpandableObjectConverter))]
[DisplayName("皮肤")]
public SpineSkinWrapper Skin { get; } = new(spine);
[TypeConverter(typeof(ExpandableObjectConverter))]
[DisplayName("动画")]
public SpineAnimationWrapper Animation { get; } = new(spine);
[DisplayName("调试")]
public SpineDebugWrapper Debug { get; } = new(spine);
}
}

View File

@@ -0,0 +1,48 @@
using SpineViewer.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers
{
/// <summary>
/// 用于在 PropertyGrid 上显示 SpinePreviewe 属性的包装类
/// </summary>
public class SpinePreviewerWrapper(SpinePreviewer previewer)
{
[Browsable(false)]
public SpinePreviewer Previewer { get; } = previewer;
[TypeConverter(typeof(SizeConverter))]
[Category("[0] "), DisplayName("")]
public Size Resolution { get => Previewer.Resolution; set => Previewer.Resolution = value; }
[TypeConverter(typeof(PointFConverter))]
[Category("[0] "), DisplayName("")]
public PointF Center { get => Previewer.Center; set => Previewer.Center = value; }
[Category("[0] "), DisplayName("")]
public float Zoom { get => Previewer.Zoom; set => Previewer.Zoom = value; }
[Category("[0] "), DisplayName("")]
public float Rotation { get => Previewer.Rotation; set => Previewer.Rotation = value; }
[Category("[0] "), DisplayName("")]
public bool FlipX { get => Previewer.FlipX; set => Previewer.FlipX = value; }
[Category("[0] "), DisplayName("")]
public bool FlipY { get => Previewer.FlipY; set => Previewer.FlipY = value; }
[Category("[0] "), DisplayName("")]
public bool RenderSelectedOnly { get => Previewer.RenderSelectedOnly; set => Previewer.RenderSelectedOnly = value; }
[Category("[1] "), DisplayName("")]
public bool ShowAxis { get => Previewer.ShowAxis; set => Previewer.ShowAxis = value; }
[Category("[1] "), DisplayName("")]
public uint MaxFps { get => Previewer.MaxFps; set => Previewer.MaxFps = value; }
}
}

View File

@@ -0,0 +1,307 @@
using SpineViewer.PropertyGridWrappers.Spine;
using SpineViewer.Spine;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.PropertyGridWrappers
{
public class PointFConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType)
{
return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (destinationType == typeof(string) && value is PointF point)
{
return $"{point.X}, {point.Y}";
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (value is string str)
{
var parts = str.Split(',');
if (parts.Length == 2 &&
float.TryParse(parts[0], out var x) &&
float.TryParse(parts[1], out var y))
{
return new PointF(x, y);
}
}
return base.ConvertFrom(context, culture, value);
}
}
public class StringEnumConverter : StringConverter
{
/// <summary>
/// 字符串标准值列表属性
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class StandardValuesAttribute : Attribute
{
/// <summary>
/// 标准值列表
/// </summary>
public ReadOnlyCollection<string> StandardValues { get; private set; }
private readonly List<string> standardValues = [];
/// <summary>
/// 是否允许用户自定义
/// </summary>
public bool Customizable { get; set; } = false;
/// <summary>
/// 字符串标准值列表
/// </summary>
/// <param name="values">允许的字符串标准值</param>
public StandardValuesAttribute(params string[] values)
{
standardValues.AddRange(values);
StandardValues = standardValues.AsReadOnly();
}
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context)
{
var customizable = context?.PropertyDescriptor?.Attributes.OfType<StandardValuesAttribute>().FirstOrDefault()?.Customizable ?? false;
return !customizable;
}
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
{
// 查找属性上的 StandardValuesAttribute
var attribute = context?.PropertyDescriptor?.Attributes.OfType<StandardValuesAttribute>().FirstOrDefault();
StandardValuesCollection result;
if (attribute != null)
result = new StandardValuesCollection(attribute.StandardValues);
else
result = new StandardValuesCollection(Array.Empty<string>());
return result;
}
}
public class SpineVersionConverter : EnumConverter
{
public SpineVersionConverter() : base(typeof(SpineVersion)) { }
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type? destinationType)
{
if (destinationType == typeof(string) && value is SpineVersion version)
return version.GetName();
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class SpineSkinNameConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context) => true;
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
{
if (context?.Instance is SpineViewer.Spine.Spine obj)
{
return new StandardValuesCollection(obj.SkinNames);
}
else if (context?.Instance is SpineViewer.Spine.Spine[] spines)
{
if (spines.Length > 0)
{
IEnumerable<string> common = spines[0].SkinNames;
foreach (var spine in spines.Skip(1))
common = common.Union(spine.SkinNames);
return new StandardValuesCollection(common.ToArray());
}
}
return base.GetStandardValues(context);
}
}
public class SpineAnimationNameConverter : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context) => true;
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
{
if (context?.Instance is SpineViewer.Spine.Spine obj)
{
return new StandardValuesCollection(obj.AnimationNames);
}
else if (context?.Instance is SpineViewer.Spine.Spine[] spines)
{
if (spines.Length > 0)
{
IEnumerable<string> common = spines[0].AnimationNames;
foreach (var spine in spines.Skip(1))
common = common.Union(spine.AnimationNames);
return new StandardValuesCollection(common.ToArray());
}
}
return base.GetStandardValues(context);
}
}
/// <summary>
/// 皮肤位包装类转换器, 实现字符串和包装类的互相转换, 并且提供标准值列表对属性进行设置, 同时还提供在面板上显示包装类属性的能力
/// </summary>
public class SkinWrapperConverter : StringConverter
{
// NOTE: 可以不用实现 ConvertTo/ConvertFrom, 因为属性实现了与字符串之间的互转
// ToString 实现了 ConvertTo
// SetValue 实现了从字符串设置属性
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context) => true;
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
{
if (context?.Instance is SpineSkinWrapper manager)
{
return new StandardValuesCollection(manager.Spine.SkinNames);
}
else if (context?.Instance is object[] instances && instances.All(x => x is SpineSkinWrapper))
{
// XXX: 这里不知道为啥总是会得到 object[] 类型而不是具体的 SpineSkinWrapper[] 类型
var managers = instances.Cast<SpineSkinWrapper>().ToArray();
if (managers.Length > 0)
{
IEnumerable<string> common = managers[0].Spine.SkinNames;
foreach (var t in managers.Skip(1))
common = common.Union(t.Spine.SkinNames);
return new StandardValuesCollection(common.ToArray());
}
}
return base.GetStandardValues(context);
}
}
/// <summary>
/// 轨道索引包装类转换器, 实现字符串和包装类的互相转换, 并且提供标准值列表对属性进行设置, 同时还提供在面板上显示包装类属性的能力
/// </summary>
public class TrackWrapperConverter : ExpandableObjectConverter
{
// NOTE: 可以不用实现 ConvertTo/ConvertFrom, 因为属性实现了与字符串之间的互转
// ToString 实现了 ConvertTo
// SetValue 实现了从字符串设置属性
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext? context) => true;
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
{
if (context?.Instance is SpineAnimationWrapper tracks)
{
return new StandardValuesCollection(tracks.Spine.AnimationNames);
}
else if (context?.Instance is object[] instances && instances.All(x => x is SpineAnimationWrapper))
{
// XXX: 这里不知道为啥总是会得到 object[] 类型而不是具体的类型
var animTracks = instances.Cast<SpineAnimationWrapper>().ToArray();
if (animTracks.Length > 0)
{
IEnumerable<string> common = animTracks[0].Spine.AnimationNames;
foreach (var t in animTracks.Skip(1))
common = common.Union(t.Spine.AnimationNames);
return new StandardValuesCollection(common.ToArray());
}
}
return base.GetStandardValues(context);
}
}
public class SFMLColorConverter : ExpandableObjectConverter
{
private class SFMLColorPropertyDescriptor : SimplePropertyDescriptor
{
public SFMLColorPropertyDescriptor(Type componentType, string name, Type propertyType) : base(componentType, name, propertyType) { }
public override object? GetValue(object? component) => component?.GetType().GetField(Name)?.GetValue(component) ?? default;
public override void SetValue(object? component, object? value) => component?.GetType().GetField(Name)?.SetValue(component, value);
}
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
{
if (value is string s)
{
s = s.Trim();
if (s.StartsWith("#") && s.Length == 9)
{
try
{
// 解析 R, G, B, A 分量注意16进制解析
byte r = byte.Parse(s.Substring(1, 2), NumberStyles.HexNumber);
byte g = byte.Parse(s.Substring(3, 2), NumberStyles.HexNumber);
byte b = byte.Parse(s.Substring(5, 2), NumberStyles.HexNumber);
byte a = byte.Parse(s.Substring(7, 2), NumberStyles.HexNumber);
return new SFML.Graphics.Color(r, g, b, a);
}
catch (Exception ex)
{
throw new FormatException("无法解析颜色,确保格式为 #RRGGBBAA", ex);
}
}
throw new FormatException("格式错误,正确格式为 #RRGGBBAA");
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType)
{
return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}
public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType)
{
if (destinationType == typeof(string) && value is SFML.Graphics.Color color)
return $"#{color.R:X2}{color.G:X2}{color.B:X2}{color.A:X2}";
return base.ConvertTo(context, culture, value, destinationType);
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext? context, object value, Attribute[]? attributes)
{
// 自定义属性集合
var properties = new List<PropertyDescriptor>
{
// 定义 R, G, B, A 四个字段的描述器
new SFMLColorPropertyDescriptor(typeof(SFML.Graphics.Color), "R", typeof(byte)),
new SFMLColorPropertyDescriptor(typeof(SFML.Graphics.Color), "G", typeof(byte)),
new SFMLColorPropertyDescriptor(typeof(SFML.Graphics.Color), "B", typeof(byte)),
new SFMLColorPropertyDescriptor(typeof(SFML.Graphics.Color), "A", typeof(byte))
};
// 返回自定义属性集合
return new PropertyDescriptorCollection(properties.ToArray());
}
}
}

View File

@@ -0,0 +1,124 @@
using SpineViewer.Dialogs;
using SpineViewer.PropertyGridWrappers.Spine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.Design;
namespace SpineViewer.PropertyGridWrappers
{
/// <summary>
/// 使用 FolderBrowserDialog 的文件夹路径编辑器
/// </summary>
public class FolderNameEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext? context)
{
// 指定编辑风格为 Modal 对话框, 提供右边用来点击的按钮
return UITypeEditorEditStyle.Modal;
}
public override object? EditValue(ITypeDescriptorContext? context, IServiceProvider provider, object? value)
{
// 重写 EditValue 方法,提供自定义的文件夹选择对话框逻辑
using var dialog = new FolderBrowserDialog();
// 如果当前值为有效路径,则设置为初始选中路径
if (value is string currentPath && Directory.Exists(currentPath))
dialog.SelectedPath = currentPath;
if (dialog.ShowDialog() == DialogResult.OK)
value = dialog.SelectedPath;
return value;
}
}
/// <summary>
/// skel 文件路径编辑器
/// </summary>
public class SkelFileNameEditor : FileNameEditor
{
protected override void InitializeDialog(OpenFileDialog openFileDialog)
{
base.InitializeDialog(openFileDialog);
openFileDialog.Title = "选择 skel 文件";
openFileDialog.AddExtension = false;
openFileDialog.Filter = "skel 文件 (*.skel; *.json)|*.skel;*.json|二进制文件 (*.skel)|*.skel|文本文件 (*.json)|*.json|所有文件 (*.*)|*.*";
}
}
/// <summary>
/// atlas 文件路径编辑器
/// </summary>
public class AtlasFileNameEditor : FileNameEditor
{
protected override void InitializeDialog(OpenFileDialog openFileDialog)
{
base.InitializeDialog(openFileDialog);
openFileDialog.Title = "选择 atlas 文件";
openFileDialog.AddExtension = false;
openFileDialog.Filter = "atlas 文件 (*.atlas)|*.atlas|所有文件 (*.*)|*.*";
}
}
class SFMLColorEditor : UITypeEditor
{
public override bool GetPaintValueSupported(ITypeDescriptorContext? context) => true;
public override void PaintValue(PaintValueEventArgs e)
{
if (e.Value is SFML.Graphics.Color color)
{
// 定义颜色和透明度的绘制区域
var colorBox = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width / 2, e.Bounds.Height);
var alphaBox = new Rectangle(e.Bounds.X + e.Bounds.Width / 2, e.Bounds.Y, e.Bounds.Width / 2, e.Bounds.Height);
// 转换为 System.Drawing.Color
var drawColor = Color.FromArgb(color.A, color.R, color.G, color.B);
// 绘制纯颜色RGB 部分)
using (var brush = new SolidBrush(Color.FromArgb(color.R, color.G, color.B)))
{
e.Graphics.FillRectangle(brush, colorBox);
e.Graphics.DrawRectangle(Pens.Black, colorBox);
}
// 绘制带透明度效果的颜色
using (var checkerBrush = CreateTransparencyBrush())
{
e.Graphics.FillRectangle(checkerBrush, alphaBox); // 背景棋盘格
}
using (var brush = new SolidBrush(drawColor))
{
e.Graphics.FillRectangle(brush, alphaBox); // 叠加透明颜色
e.Graphics.DrawRectangle(Pens.Black, alphaBox);
}
}
else
{
base.PaintValue(e);
}
}
// 创建一个透明背景的棋盘格图案画刷
private static TextureBrush CreateTransparencyBrush()
{
var bitmap = new Bitmap(8, 8);
using (var g = Graphics.FromImage(bitmap))
{
g.Clear(Color.White);
using (var grayBrush = new SolidBrush(Color.LightGray))
{
g.FillRectangle(grayBrush, 0, 0, 4, 4);
g.FillRectangle(grayBrush, 4, 4, 4, 4);
}
}
return new TextureBrush(bitmap);
}
}
}

View File

@@ -1,64 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpineViewer.Spine
{
/// <summary>
/// SFML 混合模式
/// </summary>
public static class BlendModeSFML
{
/// <summary>
/// Alpha Blend
/// <code>
/// res.c = src.c * src.a + dst.c * (1 - src.a)
/// res.a = src.a * 1 + dst.a * (1 - src.a)
/// </code>
/// </summary>
public static SFML.Graphics.BlendMode Normal = SFML.Graphics.BlendMode.Alpha;
/// <summary>
/// Additive Blend
/// <code>
/// res.c = src.c * src.a + dst.c * 1
/// res.a = src.a * 1 + dst.a * 1
/// </code>
/// </summary>
public static SFML.Graphics.BlendMode Additive = SFML.Graphics.BlendMode.Add;
/// <summary>
/// Multiply Blend (PremultipliedAlpha Only)
/// <code>
/// res.c = src.c * dst.c + dst.c * (1 - src.a)
/// res.a = src.a * 1 + dst.a * (1 - src.a)
/// </code>
/// </summary>
public static SFML.Graphics.BlendMode Multiply = new(
SFML.Graphics.BlendMode.Factor.DstColor,
SFML.Graphics.BlendMode.Factor.OneMinusSrcAlpha,
SFML.Graphics.BlendMode.Equation.Add,
SFML.Graphics.BlendMode.Factor.One,
SFML.Graphics.BlendMode.Factor.OneMinusSrcAlpha,
SFML.Graphics.BlendMode.Equation.Add
);
/// <summary>
/// Screen Blend (PremultipliedAlpha Only)
/// <code>
/// res.c = src.c * 1 + dst.c * (1 - src.c) = 1 - [(1 - src.c)(1 - dst.c)]
/// res.a = src.a * 1 + dst.a * (1 - src.a)
/// </code>
/// </summary>
public static SFML.Graphics.BlendMode Screen = new(
SFML.Graphics.BlendMode.Factor.One,
SFML.Graphics.BlendMode.Factor.OneMinusSrcColor,
SFML.Graphics.BlendMode.Equation.Add,
SFML.Graphics.BlendMode.Factor.One,
SFML.Graphics.BlendMode.Factor.OneMinusSrcAlpha,
SFML.Graphics.BlendMode.Equation.Add
);
}
}

View File

@@ -11,7 +11,7 @@ using System.Globalization;
namespace SpineViewer.Spine.Implementations.SkeletonConverter
{
[SkeletonConverterImplementation(Version.V38)]
[SpineImplementation(SpineVersion.V38)]
class SkeletonConverter38 : SpineViewer.Spine.SkeletonConverter
{
private BinaryReader reader = null;
@@ -225,8 +225,8 @@ namespace SpineViewer.Spine.Implementations.SkeletonConverter
skin["name"] = reader.ReadStringRef();
skin["bones"] = ReadNames(root["bones"].AsArray());
skin["ik"] = ReadNames(root["ik"].AsArray());
skin["transform"] = ReadNames(root["transform"].AsArray()); ;
skin["path"] = ReadNames(root["path"].AsArray()); ;
skin["transform"] = ReadNames(root["transform"].AsArray());
skin["path"] = ReadNames(root["path"].AsArray());
slotCount = reader.ReadVarInt();
}
@@ -1014,31 +1014,163 @@ namespace SpineViewer.Spine.Implementations.SkeletonConverter
private void WriteSkins()
{
//JsonArray skins = [];
//// default skin
//if (ReadSkin(true) is JsonObject data)
// skins.Add(data);
//// other skins
//for (int n = reader.ReadVarInt(); n > 0; n--)
// skins.Add(ReadSkin());
//root["skins"] = skins;
if (!root.ContainsKey("skins"))
{
writer.WriteVarInt(0); // default 的 slotCount
writer.WriteVarInt(0); // 其他皮肤数量
return;
}
JsonArray skins = root["skins"].AsArray();
bool hasDefault = false;
foreach (JsonObject skin in skins)
{
if ((string)skin["name"] == "default")
{
hasDefault = true;
WriteSkin(skin, true);
break;
}
}
if (!hasDefault) writer.WriteVarInt(0);
int skinCount = hasDefault ? skins.Count - 1 : skins.Count;
if (skinCount <= 0)
{
writer.WriteVarInt(0);
return;
}
JsonArray skins = root["skins"].AsArray();
writer.WriteVarInt(skins.Count);
for (int i = 0, n = skins.Count; i < n; i++)
writer.WriteVarInt(skinCount);
foreach (JsonObject skin in skins)
{
throw new NotImplementedException();
if ((string)skin["name"] != "default")
WriteSkin(skin);
}
}
private void WriteSkin(JsonObject skin, bool isDefault = false)
{
JsonObject skinAttachments = null;
if (isDefault)
{
// 这里固定有一个给 default 的 count 值, 算是占位符, 如果是 0 则表示没有 default 的 skin
if (skin.TryGetPropertyValue("attachments", out var attachments)) skinAttachments = attachments.AsObject();
writer.WriteVarInt(skinAttachments?.Count ?? 0);
}
else
{
writer.WriteStringRef((string)skin["name"]);
if (skin.TryGetPropertyValue("bones", out var bones)) WriteNames(bone2idx, bones.AsArray()); else writer.WriteVarInt(0);
if (skin.TryGetPropertyValue("ik", out var ik)) WriteNames(ik2idx, ik.AsArray()); else writer.WriteVarInt(0);
if (skin.TryGetPropertyValue("transform", out var transform)) WriteNames(transform2idx, transform.AsArray()); else writer.WriteVarInt(0);
if (skin.TryGetPropertyValue("path", out var path)) WriteNames(path2idx, path.AsArray()); else writer.WriteVarInt(0);
if (skin.TryGetPropertyValue("attachments", out var attachments)) skinAttachments = attachments.AsObject();
writer.WriteVarInt(skinAttachments?.Count ?? 0);
}
if (skinAttachments is null)
return;
foreach (var (slotName, _slotAttachments) in skinAttachments)
{
JsonObject slotAttachments = _slotAttachments.AsObject();
writer.WriteVarInt(slot2idx[slotName]);
writer.WriteVarInt(slotAttachments.Count);
foreach (var (attachmentKey, attachment) in slotAttachments)
{
writer.WriteStringRef(attachmentKey);
WriteAttachment(attachment.AsObject(), attachmentKey);
}
}
}
private void WriteAttachment(JsonObject attachment, string keyName)
{
int vertexCount;
string name = keyName;
AttachmentType type = AttachmentType.Region;
if (attachment.TryGetPropertyValue("name", out var _name)) name = (string)_name;
if (attachment.TryGetPropertyValue("type", out var _type)) type = Enum.Parse<AttachmentType>((string)_type, true);
writer.WriteStringRef(name);
writer.WriteByte((byte)type);
switch (type)
{
case AttachmentType.Region:
if (attachment.TryGetPropertyValue("path", out var path1)) writer.WriteStringRef((string)path1); else writer.WriteStringRef(null);
if (attachment.TryGetPropertyValue("rotation", out var rotation1)) writer.WriteFloat((float)rotation1); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("x", out var x1)) writer.WriteFloat((float)x1); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("y", out var y1)) writer.WriteFloat((float)y1); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("scaleX", out var scaleX)) writer.WriteFloat((float)scaleX); else writer.WriteFloat(1);
if (attachment.TryGetPropertyValue("scaleY", out var scaleY)) writer.WriteFloat((float)scaleY); else writer.WriteFloat(1);
if (attachment.TryGetPropertyValue("width", out var width)) writer.WriteFloat((float)width); else writer.WriteFloat(32);
if (attachment.TryGetPropertyValue("height", out var height)) writer.WriteFloat((float)height); else writer.WriteFloat(32);
if (attachment.TryGetPropertyValue("color", out var color1)) writer.WriteInt(int.Parse((string)color1, NumberStyles.HexNumber)); else writer.WriteInt(0);
break;
case AttachmentType.Boundingbox:
if (attachment.TryGetPropertyValue("vertexCount", out var _vertexCount1)) vertexCount = (int)_vertexCount1; else vertexCount = 0;
writer.WriteVarInt(vertexCount);
WriteVertices(attachment["vertices"].AsArray(), vertexCount);
if (nonessential) writer.WriteInt(0);
break;
case AttachmentType.Mesh:
if (attachment.TryGetPropertyValue("path", out var path2)) writer.WriteStringRef((string)path2); else writer.WriteStringRef(null);
if (attachment.TryGetPropertyValue("color", out var color2)) writer.WriteInt(int.Parse((string)color2, NumberStyles.HexNumber)); else writer.WriteInt(0);
if (attachment.TryGetPropertyValue("vertexCount", out var _vertexCount2)) vertexCount = (int)_vertexCount2; else vertexCount = 0;
writer.WriteVarInt(vertexCount);
WriteFloatArray(attachment["uvs"].AsArray(), vertexCount << 1); // vertexCount = uvs.Length
WriteShortArray(attachment["triangles"].AsArray());
WriteVertices(attachment["vertices"].AsArray(), vertexCount);
if (attachment.TryGetPropertyValue("hull", out var hull)) writer.WriteVarInt((int)hull); else writer.WriteVarInt(0);
if (nonessential)
{
if (attachment.TryGetPropertyValue("edges", out var edges)) WriteShortArray(edges.AsArray()); else writer.WriteVarInt(0);
if (attachment.TryGetPropertyValue("width", out var _width)) writer.WriteFloat((float)_width); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("height", out var _height)) writer.WriteFloat((float)_height); else writer.WriteFloat(0);
}
break;
case AttachmentType.Linkedmesh:
if (attachment.TryGetPropertyValue("path", out var path3)) writer.WriteStringRef((string)path3); else writer.WriteStringRef(null);
if (attachment.TryGetPropertyValue("color", out var color3)) writer.WriteInt(int.Parse((string)color3, NumberStyles.HexNumber)); else writer.WriteInt(0);
if (attachment.TryGetPropertyValue("skin", out var skin)) writer.WriteStringRef((string)skin); else writer.WriteStringRef(null);
if (attachment.TryGetPropertyValue("parent", out var parent)) writer.WriteStringRef((string)parent); else writer.WriteStringRef(null);
if (attachment.TryGetPropertyValue("deform", out var deform)) writer.WriteBoolean((bool)deform); else writer.WriteBoolean(true);
if (nonessential)
{
if (attachment.TryGetPropertyValue("width", out var _width)) writer.WriteFloat((float)_width); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("height", out var _height)) writer.WriteFloat((float)_height); else writer.WriteFloat(0);
}
break;
case AttachmentType.Path:
if (attachment.TryGetPropertyValue("closed", out var closed)) writer.WriteBoolean((bool)closed); else writer.WriteBoolean(false);
if (attachment.TryGetPropertyValue("constantSpeed", out var constantSpeed)) writer.WriteBoolean((bool)constantSpeed); else writer.WriteBoolean(true);
if (attachment.TryGetPropertyValue("vertexCount", out var _vertexCount3)) vertexCount = (int)_vertexCount3; else vertexCount = 0;
writer.WriteVarInt(vertexCount);
WriteVertices(attachment["vertices"].AsArray(), vertexCount);
WriteFloatArray(attachment["lengths"].AsArray(), vertexCount / 3);
if (nonessential) writer.WriteInt(0);
break;
case AttachmentType.Point:
if (attachment.TryGetPropertyValue("rotation", out var rotation2)) writer.WriteFloat((float)rotation2); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("x", out var x2)) writer.WriteFloat((float)x2); else writer.WriteFloat(0);
if (attachment.TryGetPropertyValue("y", out var y2)) writer.WriteFloat((float)y2); else writer.WriteFloat(0);
if (nonessential) writer.WriteInt(0);
break;
case AttachmentType.Clipping:
writer.WriteVarInt(slot2idx[(string)attachment["end"]]);
if (attachment.TryGetPropertyValue("vertexCount", out var _vertexCount4)) vertexCount = (int)_vertexCount4; else vertexCount = 0;
writer.WriteVarInt(vertexCount);
WriteVertices(attachment["vertices"].AsArray(), vertexCount);
if (nonessential) writer.WriteInt(0);
break;
default:
throw new ArgumentOutOfRangeException($"Invalid attachment type: {type}");
}
}
private void WriteEvents()
{
@@ -1089,33 +1221,80 @@ namespace SpineViewer.Spine.Implementations.SkeletonConverter
private void WriteNames(Dictionary<string, int> name2idx, JsonArray names)
{
writer.WriteVarInt(names.Count);
foreach (var name in names)
writer.WriteVarInt(name2idx[(string)name]);
foreach (string name in names)
writer.WriteVarInt(name2idx[name]);
}
public override JsonObject ToVersion(JsonObject root, Version version)
public void WriteFloatArray(JsonArray array, int n)
{
for (int i = 0; i < n; i++)
writer.WriteFloat((float)array[i]);
}
public void WriteShortArray(JsonArray array)
{
writer.WriteVarInt(array.Count);
foreach (uint i in array)
{
writer.WriteByte((byte)(i >> 8));
writer.WriteByte((byte)i);
}
}
private void WriteVertices(JsonArray vertices, int vertexCount)
{
bool hasWeight = vertices.Count != (vertexCount << 1);
writer.WriteBoolean(hasWeight);
if (!hasWeight)
{
WriteFloatArray(vertices, vertexCount << 1);
}
else
{
int idx = 0;
for (int i = 0; i < vertexCount; i++)
{
var bonesCount = (int)vertices[idx++];
writer.WriteVarInt(bonesCount);
for (int j = 0; j < bonesCount; j++)
{
writer.WriteVarInt((int)vertices[idx++]);
writer.WriteFloat((float)vertices[idx++]);
writer.WriteFloat((float)vertices[idx++]);
writer.WriteFloat((float)vertices[idx++]);
}
}
}
}
public override JsonObject ReadJson(string jsonPath)
{
// replace 3.8.75 to another version to avoid detection in official runtime
var root = base.ReadJson(jsonPath);
var skeleton = root["skeleton"].AsObject();
var version = (string)skeleton["spine"];
if (version == "3.8.75") skeleton["spine"] = "3.8.76";
return root;
}
public override void WriteJson(JsonObject root, string jsonPath)
{
// replace 3.8.75 to another version to avoid detection in official runtime
var skeleton = root["skeleton"].AsObject();
var version = (string)skeleton["spine"];
if (version == "3.8.75") skeleton["spine"] = "3.8.76";
base.WriteJson(root, jsonPath);
}
public override JsonObject ToVersion(JsonObject root, SpineVersion version)
{
root = version switch
{
Version.V38 => root.DeepClone().AsObject(),
SpineVersion.V38 => root.DeepClone().AsObject(),
_ => throw new NotImplementedException(),
};
return root;
}
//public void WriteFloatArray(float[] array)
//{
// foreach (var i in array)
// writer.WriteFloat(i);
//}
//public void WriteShortArray(int[] array)
//{
// foreach (var i in array)
// {
// writer.WriteByte((byte)(i >> 8));
// writer.WriteByte((byte)i);
// }
//}
}
}

View File

@@ -7,10 +7,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpineRuntime21;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V21)]
[SpineImplementation(SpineVersion.V21)]
internal class Spine21 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -26,8 +27,6 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -49,7 +48,7 @@ namespace SpineViewer.Spine.Implementations.Spine
// 2.1.x 不支持剪裁
//private SkeletonClipping clipping = new();
public Spine21(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine21(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -75,13 +74,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData);
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -92,7 +93,7 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
@@ -106,20 +107,19 @@ namespace SpineViewer.Spine.Implementations.Spine
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var pos = position;
var fX = flipX;
var fY = flipY;
var animations = animationState.Tracks.Where(te => te is not null).Select(te => te.Animation.Name).ToArray();
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonBinary.Scale = value;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonJson.Scale = value;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
@@ -129,63 +129,66 @@ namespace SpineViewer.Spine.Implementations.Spine
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.Time = savedTrack0.Time;
// 2.1.x 没有提供 Next 访问器,故放弃还原后续动画,问题不大,因为预览画面目前不需要连续播放不同动画,只需要循环同一个动画
//var savedEntry = savedTrack0.Next;
//while (savedEntry is not null)
//{
// entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
// entry.Time = savedEntry.TrackTime;
// savedEntry = savedEntry.Next;
//}
}
position = pos;
flipX = fX;
flipY = fY;
foreach (var s in loadedSkins) addSkin(s);
for (int i = 0; i < animations.Length; i++) setAnimation(i, animations[i]);
}
}
public override PointF Position
{
get => new(skeleton.X, skeleton.Y);
set
{
skeleton.X = value.X;
skeleton.Y = value.Y;
}
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
{
skeleton.X = value.X;
skeleton.Y = value.Y;
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.FlipX;
set => skeleton.FlipX = value;
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.FlipY;
set => skeleton.FlipY = value;
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
}
if (!skinNames.Contains(name)) return;
skeleton.SetSkin(name); // XXX: 3.7 及以下不支持 AddSkin
skeleton.SetSlotsToSetupPose();
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.SetSkin(skeletonData.DefaultSkin);
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -235,13 +238,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
skeleton.Update(delta);
animationState.Update(delta);
animationState.Apply(skeleton);
skeleton.Update(delta);
skeleton.UpdateWorldTransform();
}
@@ -257,10 +258,11 @@ namespace SpineViewer.Spine.Implementations.Spine
// };
//}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -322,18 +324,17 @@ namespace SpineViewer.Spine.Implementations.Spine
}
// 似乎 2.1.x 也没有 BlendMode
SFML.Graphics.BlendMode blendMode = slot.Data.AdditiveBlending ? BlendModeSFML.Additive : BlendModeSFML.Normal;
SFML.Graphics.BlendMode blendMode = slot.Data.AdditiveBlending ? SFMLBlendMode.AdditivePma : SFMLBlendMode.NormalPma;
states.Texture ??= texture;
if (states.BlendMode != blendMode || states.Texture != texture)
{
if (vertexArray.VertexCount > 0)
{
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -373,13 +374,22 @@ namespace SpineViewer.Spine.Implementations.Spine
//clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
//clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -7,10 +7,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpineRuntime36;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V36)]
[SpineImplementation(SpineVersion.V36)]
internal class Spine36 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -26,8 +27,6 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -48,7 +47,7 @@ namespace SpineViewer.Spine.Implementations.Spine
private SkeletonClipping clipping = new();
public Spine36(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine36(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -74,13 +73,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData);
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -91,7 +92,7 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
@@ -105,20 +106,19 @@ namespace SpineViewer.Spine.Implementations.Spine
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var pos = position;
var fX = flipX;
var fY = flipY;
var animations = animationState.Tracks.Where(te => te is not null).Select(te => te.Animation.Name).ToArray();
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonBinary.Scale = value;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonJson.Scale = value;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
@@ -128,62 +128,66 @@ namespace SpineViewer.Spine.Implementations.Spine
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.TrackTime = savedTrack0.TrackTime;
var savedEntry = savedTrack0.Next;
while (savedEntry is not null)
{
entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
entry.TrackTime = savedEntry.TrackTime;
savedEntry = savedEntry.Next;
}
}
position = pos;
flipX = fX;
flipY = fY;
foreach (var s in loadedSkins) addSkin(s);
for (int i = 0; i < animations.Length; i++) setAnimation(i, animations[i]);
}
}
public override PointF Position
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
{
skeleton.X = value.X;
skeleton.Y = value.Y;
skeleton.Y = value.Y;
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.FlipX;
set => skeleton.FlipX = value;
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.FlipY;
set => skeleton.FlipY = value;
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
}
if (!skinNames.Contains(name)) return;
skeleton.SetSkin(name); // XXX: 3.7 及以下不支持 AddSkin
skeleton.SetSlotsToSetupPose();
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.SetSkin(skeletonData.DefaultSkin);
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks.Items[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -193,13 +197,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
skeleton.Update(delta);
animationState.Update(delta);
animationState.Apply(skeleton);
skeleton.Update(delta);
skeleton.UpdateWorldTransform();
}
@@ -207,18 +209,19 @@ namespace SpineViewer.Spine.Implementations.Spine
{
return spineBlendMode switch
{
BlendMode.Normal => BlendModeSFML.Normal,
BlendMode.Additive => BlendModeSFML.Additive,
BlendMode.Multiply => BlendModeSFML.Multiply,
BlendMode.Screen => BlendModeSFML.Screen,
BlendMode.Normal => SFMLBlendMode.NormalPma,
BlendMode.Additive => SFMLBlendMode.AdditivePma,
BlendMode.Multiply => SFMLBlendMode.MultiplyPma,
BlendMode.Screen => SFMLBlendMode.ScreenPma,
_ => throw new NotImplementedException($"{spineBlendMode}"),
};
}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -285,11 +288,10 @@ namespace SpineViewer.Spine.Implementations.Spine
{
if (vertexArray.VertexCount > 0)
{
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -329,13 +331,22 @@ namespace SpineViewer.Spine.Implementations.Spine
clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -4,10 +4,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpineRuntime37;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V37)]
[SpineImplementation(SpineVersion.V37)]
internal class Spine37 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -23,8 +24,6 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -46,7 +45,7 @@ namespace SpineViewer.Spine.Implementations.Spine
private SkeletonClipping clipping = new();
public Spine37(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine37(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -72,14 +71,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData);
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -90,64 +90,17 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
if (skeletonBinary is not null)
return skeletonBinary.Scale;
else if (skeletonJson is not null)
return skeletonJson.Scale;
else
return 1f;
}
get => Math.Abs(skeleton.ScaleX);
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
// reload skel-dependent data
animationStateData = new AnimationStateData(skeletonData) { DefaultMix = animationStateData.DefaultMix };
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.TrackTime = savedTrack0.TrackTime;
var savedEntry = savedTrack0.Next;
while (savedEntry is not null)
{
entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
entry.TrackTime = savedEntry.TrackTime;
savedEntry = savedEntry.Next;
}
}
skeleton.ScaleX = Math.Sign(skeleton.ScaleX) * value;
skeleton.ScaleY = Math.Sign(skeleton.ScaleY) * value;
}
}
public override PointF Position
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
@@ -157,7 +110,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.ScaleX < 0;
set
@@ -167,7 +120,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.ScaleY < 0;
set
@@ -177,20 +130,36 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
}
if (!skinNames.Contains(name)) return;
skeleton.SetSkin(name); // XXX: 3.7 及以下不支持 AddSkin
skeleton.SetSlotsToSetupPose();
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.SetSkin(skeletonData.DefaultSkin);
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks.Items[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -200,13 +169,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
skeleton.Update(delta);
animationState.Update(delta);
animationState.Apply(skeleton);
skeleton.Update(delta);
skeleton.UpdateWorldTransform();
}
@@ -214,18 +181,19 @@ namespace SpineViewer.Spine.Implementations.Spine
{
return spineBlendMode switch
{
BlendMode.Normal => BlendModeSFML.Normal,
BlendMode.Additive => BlendModeSFML.Additive,
BlendMode.Multiply => BlendModeSFML.Multiply,
BlendMode.Screen => BlendModeSFML.Screen,
BlendMode.Normal => SFMLBlendMode.NormalPma,
BlendMode.Additive => SFMLBlendMode.AdditivePma,
BlendMode.Multiply => SFMLBlendMode.MultiplyPma,
BlendMode.Screen => SFMLBlendMode.ScreenPma,
_ => throw new NotImplementedException($"{spineBlendMode}"),
};
}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -292,12 +260,10 @@ namespace SpineViewer.Spine.Implementations.Spine
{
if (vertexArray.VertexCount > 0)
{
// XXX: 实测不用设置 sampler2D 的值也正确
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -337,13 +303,22 @@ namespace SpineViewer.Spine.Implementations.Spine
clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -7,10 +7,11 @@ using System.Text;
using System.Threading.Tasks;
using SpineRuntime38;
using SpineRuntime38.Attachments;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V38)]
[SpineImplementation(SpineVersion.V38)]
internal class Spine38 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -26,8 +27,9 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
// 似乎是不需要设置的, 因为存在某些 png 和 atlas 大小不同的情况, 一般是有一些缩放, 如果设置了反而渲染异常
// page.width = (int)texture.Size.X;
// page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -49,7 +51,7 @@ namespace SpineViewer.Spine.Implementations.Spine
private SkeletonClipping clipping = new();
public Spine38(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine38(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -75,14 +77,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData) { Skin = new(Guid.NewGuid().ToString()) }; // 挂载一个空皮肤当作容器
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -93,64 +96,17 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
if (skeletonBinary is not null)
return skeletonBinary.Scale;
else if (skeletonJson is not null)
return skeletonJson.Scale;
else
return 1f;
}
get => Math.Abs(skeleton.ScaleX);
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
// reload skel-dependent data
animationStateData = new AnimationStateData(skeletonData) { DefaultMix = animationStateData.DefaultMix };
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.TrackTime = savedTrack0.TrackTime;
var savedEntry = savedTrack0.Next;
while (savedEntry is not null)
{
entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
entry.TrackTime = savedEntry.TrackTime;
savedEntry = savedEntry.Next;
}
}
skeleton.ScaleX = Math.Sign(skeleton.ScaleX) * value;
skeleton.ScaleY = Math.Sign(skeleton.ScaleY) * value;
}
}
public override PointF Position
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
@@ -160,7 +116,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.ScaleX < 0;
set
@@ -170,7 +126,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.ScaleY < 0;
set
@@ -180,20 +136,38 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
if (skeletonData.FindSkin(name) is Skin sk)
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
skeleton.Skin.AddSkin(sk);
skeleton.SetSlotsToSetupPose();
}
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.Skin.Clear();
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks.Items[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -203,13 +177,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
skeleton.Update(delta);
animationState.Update(delta);
animationState.Apply(skeleton);
skeleton.Update(delta);
skeleton.UpdateWorldTransform();
}
@@ -217,18 +189,19 @@ namespace SpineViewer.Spine.Implementations.Spine
{
return spineBlendMode switch
{
BlendMode.Normal => BlendModeSFML.Normal,
BlendMode.Additive => BlendModeSFML.Additive,
BlendMode.Multiply => BlendModeSFML.Multiply,
BlendMode.Screen => BlendModeSFML.Screen,
BlendMode.Normal => SFMLBlendMode.NormalPma,
BlendMode.Additive => SFMLBlendMode.AdditivePma,
BlendMode.Multiply => SFMLBlendMode.MultiplyPma,
BlendMode.Screen => SFMLBlendMode.ScreenPma,
_ => throw new NotImplementedException($"{spineBlendMode}"),
};
}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -295,12 +268,10 @@ namespace SpineViewer.Spine.Implementations.Spine
{
if (vertexArray.VertexCount > 0)
{
// XXX: 实测不用设置 sampler2D 的值也正确
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -340,13 +311,22 @@ namespace SpineViewer.Spine.Implementations.Spine
clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 调试包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -6,10 +6,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpineRuntime40;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V40)]
[SpineImplementation(SpineVersion.V40)]
internal class Spine40 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -25,8 +26,6 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -48,7 +47,7 @@ namespace SpineViewer.Spine.Implementations.Spine
private SkeletonClipping clipping = new();
public Spine40(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine40(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -74,14 +73,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData) { Skin = new(Guid.NewGuid().ToString()) }; // 挂载一个空皮肤当作容器
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -92,64 +92,17 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
if (skeletonBinary is not null)
return skeletonBinary.Scale;
else if (skeletonJson is not null)
return skeletonJson.Scale;
else
return 1f;
}
get => Math.Abs(skeleton.ScaleX);
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
// reload skel-dependent data
animationStateData = new AnimationStateData(skeletonData) { DefaultMix = animationStateData.DefaultMix };
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.TrackTime = savedTrack0.TrackTime;
var savedEntry = savedTrack0.Next;
while (savedEntry is not null)
{
entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
entry.TrackTime = savedEntry.TrackTime;
savedEntry = savedEntry.Next;
}
}
skeleton.ScaleX = Math.Sign(skeleton.ScaleX) * value;
skeleton.ScaleY = Math.Sign(skeleton.ScaleY) * value;
}
}
public override PointF Position
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
@@ -159,7 +112,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.ScaleX < 0;
set
@@ -169,7 +122,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.ScaleY < 0;
set
@@ -179,20 +132,38 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
if (skeletonData.FindSkin(name) is Skin sk)
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
skeleton.Skin.AddSkin(sk);
skeleton.SetSlotsToSetupPose();
}
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.Skin.Clear();
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks.Items[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -202,13 +173,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
skeleton.Update(delta);
animationState.Update(delta);
animationState.Apply(skeleton);
skeleton.Update(delta);
skeleton.UpdateWorldTransform();
}
@@ -216,18 +185,19 @@ namespace SpineViewer.Spine.Implementations.Spine
{
return spineBlendMode switch
{
BlendMode.Normal => BlendModeSFML.Normal,
BlendMode.Additive => BlendModeSFML.Additive,
BlendMode.Multiply => BlendModeSFML.Multiply,
BlendMode.Screen => BlendModeSFML.Screen,
BlendMode.Normal => SFMLBlendMode.NormalPma,
BlendMode.Additive => SFMLBlendMode.AdditivePma,
BlendMode.Multiply => SFMLBlendMode.MultiplyPma,
BlendMode.Screen => SFMLBlendMode.ScreenPma,
_ => throw new NotImplementedException($"{spineBlendMode}"),
};
}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -294,12 +264,10 @@ namespace SpineViewer.Spine.Implementations.Spine
{
if (vertexArray.VertexCount > 0)
{
// XXX: 实测不用设置 sampler2D 的值也正确
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -339,13 +307,22 @@ namespace SpineViewer.Spine.Implementations.Spine
clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -6,10 +6,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpineRuntime41;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V41)]
[SpineImplementation(SpineVersion.V41)]
internal class Spine41 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -25,8 +26,6 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -48,7 +47,7 @@ namespace SpineViewer.Spine.Implementations.Spine
private SkeletonClipping clipping = new();
public Spine41(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine41(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -74,14 +73,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData) { Skin = new(Guid.NewGuid().ToString()) }; // 挂载一个空皮肤当作容器
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -92,64 +92,17 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
if (skeletonBinary is not null)
return skeletonBinary.Scale;
else if (skeletonJson is not null)
return skeletonJson.Scale;
else
return 1f;
}
get => Math.Abs(skeleton.ScaleX);
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
// reload skel-dependent data
animationStateData = new AnimationStateData(skeletonData) { DefaultMix = animationStateData.DefaultMix };
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.TrackTime = savedTrack0.TrackTime;
var savedEntry = savedTrack0.Next;
while (savedEntry is not null)
{
entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
entry.TrackTime = savedEntry.TrackTime;
savedEntry = savedEntry.Next;
}
}
skeleton.ScaleX = Math.Sign(skeleton.ScaleX) * value;
skeleton.ScaleY = Math.Sign(skeleton.ScaleY) * value;
}
}
public override PointF Position
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
@@ -159,7 +112,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.ScaleX < 0;
set
@@ -169,7 +122,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.ScaleY < 0;
set
@@ -179,20 +132,38 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
if (skeletonData.FindSkin(name) is Skin sk)
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
skeleton.Skin.AddSkin(sk);
skeleton.SetSlotsToSetupPose();
}
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.Skin.Clear();
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks.Items[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -202,13 +173,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
//skeleton.Update(delta); // XXX: v4.1.x 没有 Update 方法
animationState.Update(delta);
animationState.Apply(skeleton);
//skeleton.Update(delta); // XXX: v4.1.x 没有 Update 方法
skeleton.UpdateWorldTransform();
}
@@ -216,18 +185,19 @@ namespace SpineViewer.Spine.Implementations.Spine
{
return spineBlendMode switch
{
BlendMode.Normal => BlendModeSFML.Normal,
BlendMode.Additive => BlendModeSFML.Additive,
BlendMode.Multiply => BlendModeSFML.Multiply,
BlendMode.Screen => BlendModeSFML.Screen,
BlendMode.Normal => SFMLBlendMode.NormalPma,
BlendMode.Additive => SFMLBlendMode.AdditivePma,
BlendMode.Multiply => SFMLBlendMode.MultiplyPma,
BlendMode.Screen => SFMLBlendMode.ScreenPma,
_ => throw new NotImplementedException($"{spineBlendMode}"),
};
}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -294,12 +264,10 @@ namespace SpineViewer.Spine.Implementations.Spine
{
if (vertexArray.VertexCount > 0)
{
// XXX: 实测不用设置 sampler2D 的值也正确
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -339,13 +307,22 @@ namespace SpineViewer.Spine.Implementations.Spine
clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -6,10 +6,11 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpineRuntime42;
using SpineViewer.Utilities;
namespace SpineViewer.Spine.Implementations.Spine
{
[SpineImplementation(Version.V42)]
[SpineImplementation(SpineVersion.V42)]
internal class Spine42 : SpineViewer.Spine.Spine
{
private static readonly Animation EmptyAnimation = new(EMPTY_ANIMATION, [], 0);
@@ -25,8 +26,6 @@ namespace SpineViewer.Spine.Implementations.Spine
texture.Repeated = true;
page.rendererObject = texture;
page.width = (int)texture.Size.X;
page.height = (int)texture.Size.Y;
}
public void Unload(object texture)
@@ -48,7 +47,7 @@ namespace SpineViewer.Spine.Implementations.Spine
private SkeletonClipping clipping = new();
public Spine42(string skelPath, string? atlasPath = null) : base(skelPath, atlasPath)
public Spine42(string skelPath, string atlasPath) : base(skelPath, atlasPath)
{
atlas = new Atlas(AtlasPath, textureLoader);
try
@@ -74,14 +73,15 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
animationStateData = new AnimationStateData(skeletonData);
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
foreach (var skin in skeletonData.Skins)
skinNames.Add(skin.Name);
foreach (var anime in skeletonData.Animations)
animationNames.Add(anime.Name);
CurrentAnimation = DefaultAnimationName;
skeleton = new Skeleton(skeletonData) { Skin = new(Guid.NewGuid().ToString()) }; // 挂载一个空皮肤当作容器
animationStateData = new AnimationStateData(skeletonData);
animationState = new AnimationState(animationStateData);
}
protected override void Dispose(bool disposing)
@@ -92,64 +92,17 @@ namespace SpineViewer.Spine.Implementations.Spine
public override string FileVersion { get => skeletonData.Version; }
public override float Scale
protected override float scale
{
get
{
if (skeletonBinary is not null)
return skeletonBinary.Scale;
else if (skeletonJson is not null)
return skeletonJson.Scale;
else
return 1f;
}
get => Math.Abs(skeleton.ScaleX);
set
{
// 保存状态
var position = Position;
var flipX = FlipX;
var flipY = FlipY;
var savedTrack0 = animationState.GetCurrent(0);
var val = Math.Max(value, SCALE_MIN);
if (skeletonBinary is not null)
{
skeletonBinary.Scale = val;
skeletonData = skeletonBinary.ReadSkeletonData(SkelPath);
}
else if (skeletonJson is not null)
{
skeletonJson.Scale = val;
skeletonData = skeletonJson.ReadSkeletonData(SkelPath);
}
// reload skel-dependent data
animationStateData = new AnimationStateData(skeletonData) { DefaultMix = animationStateData.DefaultMix };
skeleton = new Skeleton(skeletonData);
animationState = new AnimationState(animationStateData);
// 恢复状态
Position = position;
FlipX = flipX;
FlipY = flipY;
// 恢复原本 Track0 上所有动画
if (savedTrack0 is not null)
{
var entry = animationState.SetAnimation(0, savedTrack0.Animation.Name, true);
entry.TrackTime = savedTrack0.TrackTime;
var savedEntry = savedTrack0.Next;
while (savedEntry is not null)
{
entry = animationState.AddAnimation(0, savedEntry.Animation.Name, true, 0);
entry.TrackTime = savedEntry.TrackTime;
savedEntry = savedEntry.Next;
}
}
skeleton.ScaleX = Math.Sign(skeleton.ScaleX) * value;
skeleton.ScaleY = Math.Sign(skeleton.ScaleY) * value;
}
}
public override PointF Position
protected override PointF position
{
get => new(skeleton.X, skeleton.Y);
set
@@ -159,7 +112,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipX
protected override bool flipX
{
get => skeleton.ScaleX < 0;
set
@@ -169,7 +122,7 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override bool FlipY
protected override bool flipY
{
get => skeleton.ScaleY < 0;
set
@@ -179,20 +132,38 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override string CurrentAnimation
protected override void addSkin(string name)
{
get => animationState.GetCurrent(0)?.Animation.Name ?? EMPTY_ANIMATION;
set
if (skeletonData.FindSkin(name) is Skin sk)
{
if (value == EMPTY_ANIMATION)
animationState.SetAnimation(0, EmptyAnimation, false);
else if (animationNames.Contains(value))
animationState.SetAnimation(0, value, true);
Update(0);
skeleton.Skin.AddSkin(sk);
skeleton.SetSlotsToSetupPose();
}
}
public override RectangleF Bounds
protected override void clearSkin()
{
skeleton.Skin.Clear();
skeleton.SetSlotsToSetupPose();
}
protected override int[] getTrackIndices() => animationState.Tracks.Select((_, i) => i).Where(i => animationState.Tracks.Items[i] is not null).ToArray();
protected override string getAnimation(int track) => animationState.GetCurrent(track)?.Animation.Name ?? EMPTY_ANIMATION;
protected override void setAnimation(int track, string name)
{
if (name == EMPTY_ANIMATION)
animationState.SetAnimation(track, EmptyAnimation, false);
else if (animationNames.Contains(name))
animationState.SetAnimation(track, name, true);
}
protected override void clearTrack(int i) => animationState.ClearTrack(i);
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
protected override RectangleF bounds
{
get
{
@@ -202,13 +173,11 @@ namespace SpineViewer.Spine.Implementations.Spine
}
}
public override float GetAnimationDuration(string name) { return skeletonData.FindAnimation(name)?.Duration ?? 0f; }
public override void Update(float delta)
protected override void update(float delta)
{
skeleton.Update(delta);
animationState.Update(delta);
animationState.Apply(skeleton);
skeleton.Update(delta);
skeleton.UpdateWorldTransform(Skeleton.Physics.Update);
}
@@ -216,18 +185,19 @@ namespace SpineViewer.Spine.Implementations.Spine
{
return spineBlendMode switch
{
BlendMode.Normal => BlendModeSFML.Normal,
BlendMode.Additive => BlendModeSFML.Additive,
BlendMode.Multiply => BlendModeSFML.Multiply,
BlendMode.Screen => BlendModeSFML.Screen,
BlendMode.Normal => SFMLBlendMode.NormalPma,
BlendMode.Additive => SFMLBlendMode.AdditivePma,
BlendMode.Multiply => SFMLBlendMode.MultiplyPma,
BlendMode.Screen => SFMLBlendMode.ScreenPma,
_ => throw new NotImplementedException($"{spineBlendMode}"),
};
}
public override void Draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
protected override void draw(SFML.Graphics.RenderTarget target, SFML.Graphics.RenderStates states)
{
vertexArray.Clear();
states.Texture = null;
states.Shader = SFMLShader.GetSpineShader(usePma);
// 要用 DrawOrder 而不是 Slots
foreach (var slot in skeleton.DrawOrder)
@@ -294,12 +264,10 @@ namespace SpineViewer.Spine.Implementations.Spine
{
if (vertexArray.VertexCount > 0)
{
// XXX: 实测不用设置 sampler2D 的值也正确
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
vertexArray.Clear();
}
states.BlendMode = blendMode;
@@ -339,13 +307,22 @@ namespace SpineViewer.Spine.Implementations.Spine
clipping.ClipEnd(slot);
}
if (UsePremultipliedAlpha && (states.BlendMode == BlendModeSFML.Normal || states.BlendMode == BlendModeSFML.Additive))
states.Shader = FragmentShader;
else
states.Shader = null;
target.Draw(vertexArray, states);
clipping.ClipEnd();
// 调试纹理
if (!isDebug || debugTexture)
target.Draw(vertexArray, states);
// 包围盒
if (isDebug && isSelected && debugBounds)
{
var b = bounds;
boundsVertices[0] = boundsVertices[4] = new(new(b.Left, b.Top), BoundsColor);
boundsVertices[1] = new(new(b.Right, b.Top), BoundsColor);
boundsVertices[2] = new(new(b.Right, b.Bottom), BoundsColor);
boundsVertices[3] = new(new(b.Left, b.Bottom), BoundsColor);
target.Draw(boundsVertices);
}
}
}
}

View File

@@ -9,66 +9,19 @@ using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Encodings.Web;
using SpineViewer.Utilities;
namespace SpineViewer.Spine
{
/// <summary>
/// SkeletonConverter 实现类标记
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class SkeletonConverterImplementationAttribute : Attribute
{
public Version Version { get; }
public SkeletonConverterImplementationAttribute(Version version)
{
Version = version;
}
}
/// <summary>
/// SkeletonConverter 基类, 使用静态方法 New 来创建具体版本对象
/// </summary>
public abstract class SkeletonConverter
public abstract class SkeletonConverter : ImplementationResolver<SkeletonConverter, SpineImplementationAttribute, SpineVersion>
{
/// <summary>
/// 实现类缓存
/// </summary>
private static readonly Dictionary<Version, Type> ImplementationTypes = [];
public static readonly Dictionary<Version, Type>.KeyCollection ImplementedVersions;
/// <summary>
/// 静态构造函数
/// </summary>
static SkeletonConverter()
{
// 遍历并缓存标记了 SkeletonConverterImplementationAttribute 的类型
var impTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => typeof(SkeletonConverter).IsAssignableFrom(t) && !t.IsAbstract);
foreach (var type in impTypes)
{
var attr = type.GetCustomAttribute<SkeletonConverterImplementationAttribute>();
if (attr is not null)
{
if (ImplementationTypes.ContainsKey(attr.Version))
throw new InvalidOperationException($"Multiple implementations found: {attr.Version}");
ImplementationTypes[attr.Version] = type;
}
}
Program.Logger.Debug("Find SkeletonConverter implementations: [{}]", string.Join(", ", ImplementationTypes.Keys));
ImplementedVersions = ImplementationTypes.Keys;
}
/// <summary>
/// 创建特定版本的 SkeletonConverter
/// </summary>
public static SkeletonConverter New(Version version)
{
if (!ImplementationTypes.TryGetValue(version, out var cvterType))
{
throw new NotImplementedException($"Not implemented version: {version}");
}
return (SkeletonConverter)Activator.CreateInstance(cvterType);
}
public static SkeletonConverter New(SpineVersion version) => New(version, []);
/// <summary>
/// Json 格式控制
@@ -92,7 +45,7 @@ namespace SpineViewer.Spine
/// <summary>
/// 读取 Json 对象
/// </summary>
public JsonObject ReadJson(string jsonPath)
public virtual JsonObject ReadJson(string jsonPath)
{
using var input = File.OpenRead(jsonPath);
if (JsonNode.Parse(input) is JsonObject root)
@@ -104,17 +57,40 @@ namespace SpineViewer.Spine
/// <summary>
/// 写入 Json 对象
/// </summary>
public void WriteJson(JsonObject root, string jsonPath)
public virtual void WriteJson(JsonObject root, string jsonPath)
{
using var output = File.Create(jsonPath);
using var writer = new Utf8JsonWriter(output, jsonWriterOptions);
root.WriteTo(writer);
}
/// <summary>
/// 读取骨骼文件
/// </summary>
public JsonObject Read(string path)
{
try
{
return ReadBinary(path);
}
catch
{
try
{
return ReadJson(path);
}
catch
{
// 都不行就报错
throw new InvalidDataException($"Unknown skeleton file format {path}");
}
}
}
/// <summary>
/// 转换到目标版本
/// </summary>
public abstract JsonObject ToVersion(JsonObject root, Version version);
public abstract JsonObject ToVersion(JsonObject root, SpineVersion version);
/// <summary>
/// 二进制骨骼文件读

Some files were not shown because too many files have changed in this diff Show More