Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
64bc12db06 | ||
|
|
7a29fee641 | ||
|
|
49f95ddbb7 | ||
|
|
317ee71882 | ||
|
|
7780fbda28 | ||
|
|
b54c6a1777 | ||
|
|
617157044c | ||
|
|
29d7e8d9d8 | ||
|
|
701d1fcf90 | ||
|
|
df36d46528 | ||
|
|
3459f3af03 | ||
|
|
5498508700 | ||
|
|
a61bb43250 | ||
|
|
aace461ae0 | ||
|
|
c02cec9a18 | ||
|
|
31daed9e81 | ||
|
|
997d55350d | ||
|
|
cc6d1b6c00 | ||
|
|
e14c54c3a4 | ||
|
|
5eba515eac | ||
|
|
f878530184 | ||
|
|
81d9224658 | ||
|
|
9d9edb8bc4 | ||
|
|
d3b5814c6f | ||
|
|
aade44cffb | ||
|
|
c4956b9c16 | ||
|
|
7ca431b214 | ||
|
|
74538ddf74 | ||
|
|
779500ee8e | ||
|
|
ee7c9e9e54 | ||
|
|
d335645dc1 | ||
|
|
6a17ec0397 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -396,3 +396,5 @@ FodyWeavers.xsd
|
||||
|
||||
# JetBrains Rider
|
||||
*.sln.iml
|
||||
|
||||
launchSettings.json
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# CHANGELOG
|
||||
|
||||
## v0.16.9
|
||||
|
||||
- 重构 CLI 工具
|
||||
|
||||
## v0.16.8
|
||||
|
||||
- 去除首次的最小化提示弹框
|
||||
|
||||
@@ -143,6 +143,7 @@ For detailed usage and documentation, see the [Wiki](https://github.com/ww-rm/Sp
|
||||
- [HandyControl](https://github.com/HandyOrg/HandyControl)
|
||||
- [NLog](https://github.com/NLog/NLog)
|
||||
- [SkiaSharp](https://github.com/mono/SkiaSharp)
|
||||
- [Spectre.Console](https://github.com/spectreconsole/spectre.console)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -142,6 +142,7 @@ https://github.com/user-attachments/assets/37b6b730-088a-4352-827a-c338127a16f0
|
||||
- [HandyControl](https://github.com/HandyOrg/HandyControl)
|
||||
- [NLog](https://github.com/NLog/NLog)
|
||||
- [SkiaSharp](https://github.com/mono/SkiaSharp)
|
||||
- [Spectre.Console](https://github.com/spectreconsole/spectre.console)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
using SFML.Graphics;
|
||||
using SFML.System;
|
||||
using SkiaSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace SpineViewer.Extensions
|
||||
namespace Spine.Exporters
|
||||
{
|
||||
public static class SFMLExtension
|
||||
public static class Extension
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取适合指定画布参数下能够覆盖包围盒的画布视区包围盒
|
||||
@@ -53,31 +49,11 @@ namespace SpineViewer.Extensions
|
||||
public static FloatRect GetBounds(this View self)
|
||||
{
|
||||
return new(
|
||||
self.Center.X - self.Size.X / 2,
|
||||
self.Center.Y - self.Size.Y / 2,
|
||||
self.Size.X,
|
||||
self.Center.X - self.Size.X / 2,
|
||||
self.Center.Y - self.Size.Y / 2,
|
||||
self.Size.X,
|
||||
self.Size.Y
|
||||
);
|
||||
}
|
||||
|
||||
public static FloatRect ToFloatRect(this Rect self)
|
||||
{
|
||||
return new((float)self.X, (float)self.Y, (float)self.Width, (float)self.Height);
|
||||
}
|
||||
|
||||
public static Vector2f ToVector2f(this Size self)
|
||||
{
|
||||
return new((float)self.Width, (float)self.Height);
|
||||
}
|
||||
|
||||
public static Vector2u ToVector2u(this Size self)
|
||||
{
|
||||
return new((uint)self.Width, (uint)self.Height);
|
||||
}
|
||||
|
||||
public static Vector2i ToVector2i(this Size self)
|
||||
{
|
||||
return new((int)self.Width, (int)self.Height);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,33 @@ namespace Spine.Exporters
|
||||
Mov,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Apng 格式预测器算法
|
||||
/// </summary>
|
||||
public enum ApngPredMethod
|
||||
{
|
||||
None = 0,
|
||||
Sub = 1,
|
||||
Up = 2,
|
||||
Avg = 3,
|
||||
Paeth = 4,
|
||||
Mixed = 5,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mov prores_ks 编码器 profile 参数
|
||||
/// </summary>
|
||||
public enum MovProfile
|
||||
{
|
||||
Auto = -1,
|
||||
Proxy = 0,
|
||||
Light = 1,
|
||||
Standard = 2,
|
||||
High = 3,
|
||||
Yuv4444 = 4,
|
||||
Yuv4444Extreme = 5,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 视频格式
|
||||
/// </summary>
|
||||
@@ -60,10 +87,10 @@ namespace Spine.Exporters
|
||||
private bool _lossless = false;
|
||||
|
||||
/// <summary>
|
||||
/// [Apng] 预测器算法, 取值范围 0-5, 分别对应 none, sub, up, avg, paeth, mixed
|
||||
/// [Apng] 预测器算法
|
||||
/// </summary>
|
||||
public int ApngPred { get => _apngPred; set => _apngPred = Math.Clamp(value, 0, 5); }
|
||||
private int _apngPred = 5;
|
||||
public ApngPredMethod PredMethod { get => _predMethod; set => _predMethod = value; }
|
||||
private ApngPredMethod _predMethod = ApngPredMethod.Mixed;
|
||||
|
||||
/// <summary>
|
||||
/// [Mp4/Webm/Mkv] CRF
|
||||
@@ -72,10 +99,10 @@ namespace Spine.Exporters
|
||||
private int _crf = 23;
|
||||
|
||||
/// <summary>
|
||||
/// [Mov] prores_ks 编码器的配置等级, -1 是自动, 越高质量越好, 只有 4 及以上才有透明通道
|
||||
/// [Mov] prores_ks 编码器的配置等级, 越高质量越好, 只有 <see cref="MovProfile.Yuv4444"> 及以上才有透明通道
|
||||
/// </summary>
|
||||
public int Profile { get => _profile; set => _profile = Math.Clamp(value, -1, 5); }
|
||||
private int _profile = 5;
|
||||
public MovProfile Profile { get => _profile; set => _profile = value; }
|
||||
private MovProfile _profile = MovProfile.Yuv4444Extreme;
|
||||
|
||||
/// <summary>
|
||||
/// 获取的一帧, 结果是预乘的
|
||||
@@ -142,7 +169,7 @@ namespace Spine.Exporters
|
||||
|
||||
private void SetApngOptions(FFMpegArgumentOptions options)
|
||||
{
|
||||
var customArgs = $"-vf unpremultiply=inplace=1 -plays {(_loop ? 0 : 1)} -pred {_apngPred}";
|
||||
var customArgs = $"-vf unpremultiply=inplace=1 -plays {(_loop ? 0 : 1)} -pred {(int)_predMethod}";
|
||||
options.ForceFormat("apng").WithVideoCodec("apng").ForcePixelFormat("rgba")
|
||||
.WithCustomArgument(customArgs);
|
||||
}
|
||||
@@ -179,7 +206,7 @@ namespace Spine.Exporters
|
||||
var customArgs = "-vf unpremultiply=inplace=1";
|
||||
options.ForceFormat("mov").WithVideoCodec("prores_ks").ForcePixelFormat("yuva444p10le")
|
||||
.WithFastStart()
|
||||
.WithCustomArgument($"-profile {_profile}")
|
||||
.WithCustomArgument($"-profile {(int)_profile}")
|
||||
.WithCustomArgument(customArgs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,27 @@ namespace Spine.Exporters
|
||||
public FrameExporter(uint width = 100, uint height = 100) : base(width, height) { }
|
||||
public FrameExporter(Vector2u resolution) : base(resolution) { }
|
||||
|
||||
public SKEncodedImageFormat Format { get => _format; set => _format = value; }
|
||||
public SKEncodedImageFormat Format
|
||||
{
|
||||
get => _format;
|
||||
set {
|
||||
switch (value)
|
||||
{
|
||||
case SKEncodedImageFormat.Jpeg:
|
||||
case SKEncodedImageFormat.Png:
|
||||
case SKEncodedImageFormat.Webp:
|
||||
_format = value;
|
||||
break;
|
||||
default:
|
||||
_logger.Warn("Omit unsupported exporter format: {0}", value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
protected SKEncodedImageFormat _format = SKEncodedImageFormat.Png;
|
||||
|
||||
public int Quality { get => _quality; set => _quality = Math.Clamp(value, 0, 100); }
|
||||
protected int _quality = 80;
|
||||
protected int _quality = 100;
|
||||
|
||||
public override void Export(string output, params SpineObject[] spines)
|
||||
{
|
||||
@@ -33,5 +49,15 @@ namespace Spine.Exporters
|
||||
using var stream = File.OpenWrite(output);
|
||||
data.SaveTo(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取帧图像, 结果是预乘的
|
||||
/// </summary>
|
||||
public SKImage ExportMemoryImage(params SpineObject[] spines)
|
||||
{
|
||||
using var frame = GetFrame(spines);
|
||||
var info = new SKImageInfo(frame.Width, frame.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
|
||||
return SKImage.FromPixelCopy(info, frame.Image.Pixels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ namespace Spine.Exporters
|
||||
int frameCount = GetFrameCount();
|
||||
int frameIdx = 0;
|
||||
|
||||
_progressReporter?.Invoke(frameCount, 0, $"[{frameIdx}/{frameCount}] {output}");
|
||||
_progressReporter?.Invoke(frameCount, 0, $"[0/{frameCount}] {output}"); // 导出帧序列单独在此处调用进度报告
|
||||
foreach (var frame in GetFrames(spines))
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
@@ -37,7 +37,7 @@ namespace Spine.Exporters
|
||||
var savePath = Path.Combine(output, $"frame_{_fps}_{frameIdx:d6}.png");
|
||||
var info = new SKImageInfo(frame.Width, frame.Height, SKColorType.Rgba8888, SKAlphaType.Premul);
|
||||
|
||||
_progressReporter?.Invoke(frameCount, frameIdx, $"[{frameIdx + 1}/{frameCount}] {savePath}");
|
||||
_progressReporter?.Invoke(frameCount, frameIdx + 1, $"[{frameIdx + 1}/{frameCount}] {savePath}");
|
||||
try
|
||||
{
|
||||
using var skImage = SKImage.FromPixelCopy(info, frame.Image.Pixels);
|
||||
|
||||
@@ -92,7 +92,7 @@ namespace Spine.Exporters
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成帧序列
|
||||
/// 生成帧序列, 用于导出帧序列
|
||||
/// </summary>
|
||||
protected IEnumerable<SFMLImageVideoFrame> GetFrames(SpineObject[] spines)
|
||||
{
|
||||
@@ -121,14 +121,14 @@ namespace Spine.Exporters
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成帧序列, 支持中途取消和进度输出
|
||||
/// 生成帧序列, 支持中途取消和进度输出, 用于动图视频等单个文件输出
|
||||
/// </summary>
|
||||
protected IEnumerable<SFMLImageVideoFrame> GetFrames(SpineObject[] spines, string output, CancellationToken ct)
|
||||
{
|
||||
int frameCount = GetFrameCount();
|
||||
int frameIdx = 0;
|
||||
|
||||
_progressReporter?.Invoke(frameCount, 0, $"[{frameIdx}/{frameCount}] {output}");
|
||||
_progressReporter?.Invoke(frameCount, 0, $"[0/{frameCount}] {output}");
|
||||
foreach (var frame in GetFrames(spines))
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
@@ -138,7 +138,7 @@ namespace Spine.Exporters
|
||||
break;
|
||||
}
|
||||
|
||||
_progressReporter?.Invoke(frameCount, frameIdx, $"[{frameIdx + 1}/{frameCount}] {output}");
|
||||
_progressReporter?.Invoke(frameCount, frameIdx + 1, $"[{frameIdx + 1}/{frameCount}] {output}");
|
||||
yield return frame;
|
||||
frameIdx++;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<Version>0.16.8</Version>
|
||||
<Version>0.16.9</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
|
||||
@@ -84,12 +84,13 @@ namespace SpineViewer
|
||||
var fileTarget = new NLog.Targets.FileTarget("fileTarget")
|
||||
{
|
||||
Encoding = System.Text.Encoding.UTF8,
|
||||
Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${level:uppercase=true} - ${processid} - ${callsite-filename:includeSourcePath=false}:${callsite-linenumber} - ${message}",
|
||||
AutoFlush = true,
|
||||
FileName = "${basedir}/logs/app.log",
|
||||
ArchiveFileName = "${basedir}/logs/app.{#}.log",
|
||||
ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Rolling,
|
||||
ArchiveAboveSize = 1048576,
|
||||
MaxArchiveFiles = 5,
|
||||
Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${level:uppercase=true} - ${processid} - ${callsite-filename:includeSourcePath=false}:${callsite-linenumber} - ${message}",
|
||||
ConcurrentWrites = true,
|
||||
KeepFileOpen = false,
|
||||
};
|
||||
|
||||
@@ -1,19 +1,41 @@
|
||||
using SkiaSharp;
|
||||
using SFML.Graphics;
|
||||
using SFML.System;
|
||||
using SkiaSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Media;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SpineViewer.Extensions
|
||||
{
|
||||
public static class WpfExtension
|
||||
{
|
||||
public static FloatRect ToFloatRect(this Rect self)
|
||||
{
|
||||
return new((float)self.X, (float)self.Y, (float)self.Width, (float)self.Height);
|
||||
}
|
||||
|
||||
public static Vector2f ToVector2f(this Size self)
|
||||
{
|
||||
return new((float)self.Width, (float)self.Height);
|
||||
}
|
||||
|
||||
public static Vector2u ToVector2u(this Size self)
|
||||
{
|
||||
return new((uint)self.Width, (uint)self.Height);
|
||||
}
|
||||
|
||||
public static Vector2i ToVector2i(this Size self)
|
||||
{
|
||||
return new((int)self.Width, (int)self.Height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从本地 WebP 文件读取,并保留透明度,返回一个可以直接用于 WPF Image.Source 的 BitmapSource。
|
||||
/// </summary>
|
||||
|
||||
@@ -206,12 +206,12 @@
|
||||
<s:String x:Key="Str_QualityParameterTooltip" xml:space="preserve">[Webp]
Quality parameter, range 0-100, higher value means better quality</s:String>
|
||||
<s:String x:Key="Str_LosslessParam">Lossless Compression</s:String>
|
||||
<s:String x:Key="Str_LosslessParamTooltip" xml:space="preserve">[Webp]
Lossless compression, quality parameter will be ignored</s:String>
|
||||
<s:String x:Key="Str_ApngPred">Predictor Method</s:String>
|
||||
<s:String x:Key="Str_ApngPredTooltip" xml:space="preserve">[Apng]
Pred parameter, value range 0-5, corresponding to different encoding strategies: none, sub, up, avg, paeth, and mixed.
It affects encoding time and file size.</s:String>
|
||||
<s:String x:Key="Str_PredMethod">Predictor Method</s:String>
|
||||
<s:String x:Key="Str_PredMethodTooltip" xml:space="preserve">[Apng]
Pred parameter, value range 0-5, corresponding to different encoding strategies: none, sub, up, avg, paeth, and mixed.
It affects encoding time and file size.</s:String>
|
||||
<s:String x:Key="Str_CrfParameter">CRF Parameter</s:String>
|
||||
<s:String x:Key="Str_CrfParameterTooltip" xml:space="preserve">[Mp4/Webm/Mkv]
CRF parameter, range 0-63, lower value means higher quality</s:String>
|
||||
<s:String x:Key="Str_ProfileParameter">Profile Parameter</s:String>
|
||||
<s:String x:Key="Str_ProfileParameterTooltip" xml:space="preserve">[Mov]
Profile parameter, integer between -1 and 5,
-1 means automatic, higher values indicate higher quality,
Alpha channel encoding is only available when value is 4 or higher</s:String>
|
||||
<s:String x:Key="Str_ProfileParameterTooltip" xml:space="preserve">[Mov]
Profile parameter, an integer between -1 and 5,
corresponding to: auto, proxy, lt, standard, hq, 4444, and 4444xq.
Alpha channel encoding is available only when the value is 4 or higher.</s:String>
|
||||
|
||||
<s:String x:Key="Str_FFmpegFormat">Export Format</s:String>
|
||||
<s:String x:Key="Str_FFmpegFormatTooltip">FFmpeg export format (equivalent to "-f"), e.g. "mp4", "webm"</s:String>
|
||||
|
||||
@@ -206,12 +206,12 @@
|
||||
<s:String x:Key="Str_QualityParameterTooltip" xml:space="preserve">[Webp]
品質パラメータ、範囲は0-100。値が高いほど品質が良い</s:String>
|
||||
<s:String x:Key="Str_LosslessParam">無損失圧縮</s:String>
|
||||
<s:String x:Key="Str_LosslessParamTooltip" xml:space="preserve">[Webp]
無損失圧縮、品質パラメータは無視されます</s:String>
|
||||
<s:String x:Key="Str_ApngPred">予測器方式</s:String>
|
||||
<s:String x:Key="Str_ApngPredTooltip" xml:space="preserve">[Apng]
Pred パラメータ。値の範囲は 0~5 で、それぞれ none、sub、up、avg、paeth、mixed の異なるエンコード方式に対応します。
エンコード時間とファイルサイズに影響します。</s:String>
|
||||
<s:String x:Key="Str_PredMethod">予測器方式</s:String>
|
||||
<s:String x:Key="Str_PredMethodTooltip" xml:space="preserve">[Apng]
Pred パラメータ。値の範囲は 0~5 で、それぞれ none、sub、up、avg、paeth、mixed の異なるエンコード方式に対応します。
エンコード時間とファイルサイズに影響します。</s:String>
|
||||
<s:String x:Key="Str_CrfParameter">CRF パラメータ</s:String>
|
||||
<s:String x:Key="Str_CrfParameterTooltip" xml:space="preserve">[Mp4/Webm/Mkv]
CRF パラメータ、範囲0-63。値が小さいほど品質が高い</s:String>
|
||||
<s:String x:Key="Str_ProfileParameter">プロファイルパラメータ</s:String>
|
||||
<s:String x:Key="Str_ProfileParameterTooltip" xml:space="preserve">[Mov]
プロファイルパラメータ、-1から5の整数、
-1は自動、値が大きいほど品質が高い、
値が4以上の場合のみアルファチャンネルをエンコード可能</s:String>
|
||||
<s:String x:Key="Str_ProfileParameterTooltip" xml:space="preserve">[Mov]
Profile パラメータ。値は -1 ~ 5 の整数で、
それぞれ auto、proxy、lt、standard、hq、4444、4444xq に対応します。
値が 4 以上の場合のみアルファチャンネルのエンコードが可能です。</s:String>
|
||||
|
||||
<s:String x:Key="Str_FFmpegFormat">エクスポートフォーマット</s:String>
|
||||
<s:String x:Key="Str_FFmpegFormatTooltip">FFmpegエクスポートフォーマット。パラメーター“-f”に相当します。例: “mp4”、“webm”</s:String>
|
||||
|
||||
@@ -206,12 +206,12 @@
|
||||
<s:String x:Key="Str_QualityParameterTooltip" xml:space="preserve">[Webp]
质量参数,取值范围 0-100,越高质量越好</s:String>
|
||||
<s:String x:Key="Str_LosslessParam">无损压缩</s:String>
|
||||
<s:String x:Key="Str_LosslessParamTooltip" xml:space="preserve">[Webp]
无损压缩,会忽略质量参数</s:String>
|
||||
<s:String x:Key="Str_ApngPred">预测器方法</s:String>
|
||||
<s:String x:Key="Str_ApngPredTooltip" xml:space="preserve">[Apng]
Pred 参数,取值范围 0-5,分别对应 none、sub、up、avg、paeth、mixed 几种不同的编码策略,
影响编码时间和文件大小</s:String>
|
||||
<s:String x:Key="Str_PredMethod">预测器方法</s:String>
|
||||
<s:String x:Key="Str_PredMethodTooltip" xml:space="preserve">[Apng]
Pred 参数,取值范围 0-5,分别对应 none、sub、up、avg、paeth、mixed 几种不同的编码策略,
影响编码时间和文件大小</s:String>
|
||||
<s:String x:Key="Str_CrfParameter">CRF 参数</s:String>
|
||||
<s:String x:Key="Str_CrfParameterTooltip" xml:space="preserve">[Mp4/Webm/Mkv]
CRF 参数,取值范围 0-63,越小质量越高</s:String>
|
||||
<s:String x:Key="Str_ProfileParameter">Profile 参数</s:String>
|
||||
<s:String x:Key="Str_ProfileParameterTooltip" xml:space="preserve">[Mov]
Profile 参数,取值集合为 -1 到 5 之间的整数,
-1 表示自动,0-5 取值越高质量越高,
仅在取值大于等于 4 时可以编码透明度通道</s:String>
|
||||
<s:String x:Key="Str_ProfileParameterTooltip" xml:space="preserve">[Mov]
Profile 参数,取值范围为 -1 到 5 之间的整数,
分别对应 auto、proxy、lt、standard、hq、4444、4444xq 几种配置,
仅在取值大于等于 4 时可以编码透明度通道</s:String>
|
||||
|
||||
<s:String x:Key="Str_FFmpegFormat">导出格式</s:String>
|
||||
<s:String x:Key="Str_FFmpegFormatTooltip">FFmpeg 导出格式,等价于参数 “-f”,例如 “mp4”、“webm”</s:String>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<Version>0.16.8</Version>
|
||||
<Version>0.16.9</Version>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<UseWPF>true</UseWPF>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -19,6 +19,8 @@ namespace SpineViewer.ViewModels.Exporters
|
||||
public class FFmpegVideoExporterViewModel(MainWindowViewModel vmMain) : VideoExporterViewModel(vmMain)
|
||||
{
|
||||
public static ImmutableArray<FFmpegVideoExporter.VideoFormat> VideoFormatOptions { get; } = Enum.GetValues<FFmpegVideoExporter.VideoFormat>().ToImmutableArray();
|
||||
public static ImmutableArray<FFmpegVideoExporter.ApngPredMethod> ApngPredMethodOptions { get; } = Enum.GetValues<FFmpegVideoExporter.ApngPredMethod>().ToImmutableArray();
|
||||
public static ImmutableArray<FFmpegVideoExporter.MovProfile> MovProfileOptions { get; } = Enum.GetValues<FFmpegVideoExporter.MovProfile>().ToImmutableArray();
|
||||
|
||||
public FFmpegVideoExporter.VideoFormat Format
|
||||
{
|
||||
@@ -57,8 +59,8 @@ namespace SpineViewer.ViewModels.Exporters
|
||||
public bool EnableParamLossless =>
|
||||
_format == FFmpegVideoExporter.VideoFormat.Webp;
|
||||
|
||||
public int ApngPred { get => _apngPred; set => SetProperty(ref _apngPred, Math.Clamp(value, 0, 5)); }
|
||||
protected int _apngPred = 5;
|
||||
public FFmpegVideoExporter.ApngPredMethod PredMethod { get => _predMethod; set => SetProperty(ref _predMethod, value); }
|
||||
protected FFmpegVideoExporter.ApngPredMethod _predMethod = FFmpegVideoExporter.ApngPredMethod.Mixed;
|
||||
|
||||
public bool EnableParamApngPred =>
|
||||
_format == FFmpegVideoExporter.VideoFormat.Apng;
|
||||
@@ -71,8 +73,8 @@ namespace SpineViewer.ViewModels.Exporters
|
||||
_format == FFmpegVideoExporter.VideoFormat.Webm ||
|
||||
_format == FFmpegVideoExporter.VideoFormat.Mkv;
|
||||
|
||||
public int Profile { get => _profile; set => SetProperty(ref _profile, Math.Clamp(value, -1, 5)); }
|
||||
protected int _profile = 5;
|
||||
public FFmpegVideoExporter.MovProfile Profile { get => _profile; set => SetProperty(ref _profile, value); }
|
||||
protected FFmpegVideoExporter.MovProfile _profile = FFmpegVideoExporter.MovProfile.Yuv4444Extreme;
|
||||
|
||||
public bool EnableParamProfile =>
|
||||
_format == FFmpegVideoExporter.VideoFormat.Mov;
|
||||
@@ -102,7 +104,7 @@ namespace SpineViewer.ViewModels.Exporters
|
||||
Loop = _loop,
|
||||
Quality = _quality,
|
||||
Lossless = _lossless,
|
||||
ApngPred = _apngPred,
|
||||
PredMethod = _predMethod,
|
||||
Crf = _crf,
|
||||
Profile = _profile,
|
||||
};
|
||||
|
||||
@@ -20,13 +20,17 @@ namespace SpineViewer.ViewModels.Exporters
|
||||
{
|
||||
public class FrameExporterViewModel(MainWindowViewModel vmMain) : BaseExporterViewModel(vmMain)
|
||||
{
|
||||
public static ImmutableArray<SKEncodedImageFormat> FrameFormatOptions { get; } = Enum.GetValues<SKEncodedImageFormat>().ToImmutableArray();
|
||||
public static ImmutableArray<SKEncodedImageFormat> FrameFormatOptions { get; } = [
|
||||
SKEncodedImageFormat.Png,
|
||||
SKEncodedImageFormat.Webp,
|
||||
SKEncodedImageFormat.Jpeg,
|
||||
];
|
||||
|
||||
public SKEncodedImageFormat Format { get => _format; set => SetProperty(ref _format, value); }
|
||||
protected SKEncodedImageFormat _format = SKEncodedImageFormat.Png;
|
||||
|
||||
public int Quality { get => _quality; set => SetProperty(ref _quality, Math.Clamp(value, 0, 100)); }
|
||||
protected int _quality = 80;
|
||||
protected int _quality = 100;
|
||||
|
||||
private string FormatSuffix
|
||||
{
|
||||
|
||||
@@ -247,8 +247,11 @@
|
||||
<ColumnDefinition Width="Auto" SharedSizeGroup="LabelCol"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Label Content="{DynamicResource Str_ApngPred}" ToolTip="{DynamicResource Str_ApngPredTooltip}"/>
|
||||
<TextBox Grid.Column="1" Text="{Binding ApngPred}" ToolTip="{DynamicResource Str_ApngPredTooltip}"/>
|
||||
<Label Content="{DynamicResource Str_PredMethod}" ToolTip="{DynamicResource Str_PredMethodTooltip}"/>
|
||||
<ComboBox Grid.Column="1"
|
||||
SelectedItem="{Binding PredMethod}"
|
||||
ItemsSource="{x:Static vmexp:FFmpegVideoExporterViewModel.ApngPredMethodOptions}"
|
||||
ToolTip="{DynamicResource Str_PredMethodTooltip}"/>
|
||||
</Grid>
|
||||
|
||||
<!-- CRF 参数 -->
|
||||
@@ -268,7 +271,10 @@
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Label Content="{DynamicResource Str_ProfileParameter}" ToolTip="{DynamicResource Str_ProfileParameterTooltip}"/>
|
||||
<TextBox Grid.Column="1" Text="{Binding Profile}" ToolTip="{DynamicResource Str_ProfileParameterTooltip}"/>
|
||||
<ComboBox Grid.Column="1"
|
||||
SelectedItem="{Binding Profile}"
|
||||
ItemsSource="{x:Static vmexp:FFmpegVideoExporterViewModel.MovProfileOptions}"
|
||||
ToolTip="{DynamicResource Str_ProfileParameterTooltip}"/>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</GroupBox>
|
||||
|
||||
@@ -120,11 +120,11 @@ public partial class MainWindow : Window
|
||||
var rtbTarget = new NLog.Windows.Wpf.RichTextBoxTarget
|
||||
{
|
||||
Name = "rtbTarget",
|
||||
Layout = "[${level:format=OneLetter}]${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${message}",
|
||||
WindowName = _mainWindow.Name,
|
||||
ControlName = _loggerRichTextBox.Name,
|
||||
AutoScroll = true,
|
||||
MaxLines = 3000,
|
||||
Layout = "[${level:format=OneLetter}]${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${message}",
|
||||
};
|
||||
|
||||
rtbTarget.WordColoringRules.Add(new("[D]", "Gray", "Empty"));
|
||||
|
||||
217
SpineViewerCLI/CanvasAscii.cs
Normal file
217
SpineViewerCLI/CanvasAscii.cs
Normal file
@@ -0,0 +1,217 @@
|
||||
using SkiaSharp;
|
||||
using Spectre.Console;
|
||||
using Spectre.Console.Rendering;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public class CanvasAscii : Renderable
|
||||
{
|
||||
private readonly SKColor?[,] _pixels;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the width of the canvas.
|
||||
/// </summary>
|
||||
public int Width { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the height of the canvas.
|
||||
/// </summary>
|
||||
public int Height { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the render width of the canvas.
|
||||
/// </summary>
|
||||
public int? MaxWidth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether or not
|
||||
/// to scale the canvas when rendering.
|
||||
/// </summary>
|
||||
public bool Scale { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the pixel width.
|
||||
/// </summary>
|
||||
public int PixelWidth { get; set; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the pixel characters, ordered by transparency.
|
||||
/// </summary>
|
||||
public string PixelCharacters { get; set; } = ".,:;-=+*?oSXBGWM$&%#@";
|
||||
|
||||
/// <summary>
|
||||
/// Whether to use pixel characters instead of spaces.
|
||||
/// </summary>
|
||||
public bool UsePixelCharacters { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CanvasAscii"/> class.
|
||||
/// </summary>
|
||||
/// <param name="width">The canvas width.</param>
|
||||
/// <param name="height">The canvas height.</param>
|
||||
public CanvasAscii(int width, int height)
|
||||
{
|
||||
if (width < 1)
|
||||
{
|
||||
throw new ArgumentException("Must be > 1", nameof(width));
|
||||
}
|
||||
|
||||
if (height < 1)
|
||||
{
|
||||
throw new ArgumentException("Must be > 1", nameof(height));
|
||||
}
|
||||
|
||||
Width = width;
|
||||
Height = height;
|
||||
|
||||
_pixels = new SKColor?[Width, Height];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a pixel with the specified color in the canvas at the specified location.
|
||||
/// </summary>
|
||||
/// <param name="x">The X coordinate for the pixel.</param>
|
||||
/// <param name="y">The Y coordinate for the pixel.</param>
|
||||
/// <param name="color">The pixel color.</param>
|
||||
/// <returns>The same <see cref="CanvasAscii"/> instance so that multiple calls can be chained.</returns>
|
||||
public CanvasAscii SetPixel(int x, int y, SKColor color)
|
||||
{
|
||||
_pixels[x, y] = color;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override Measurement Measure(RenderOptions options, int maxWidth)
|
||||
{
|
||||
if (PixelWidth < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Pixel width must be greater than zero.");
|
||||
}
|
||||
|
||||
var width = MaxWidth ?? Width;
|
||||
|
||||
if (maxWidth < width * PixelWidth)
|
||||
{
|
||||
return new Measurement(maxWidth, maxWidth);
|
||||
}
|
||||
|
||||
return new Measurement(width * PixelWidth, width * PixelWidth);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override IEnumerable<Segment> Render(RenderOptions options, int maxWidth)
|
||||
{
|
||||
if (PixelWidth < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Pixel width must be greater than zero.");
|
||||
}
|
||||
|
||||
if (UsePixelCharacters && PixelCharacters.Length <= 0)
|
||||
{
|
||||
throw new InvalidOperationException("Pixel letters can't be empty.");
|
||||
}
|
||||
|
||||
var pixels = _pixels;
|
||||
var emptyPixel = new string(' ', PixelWidth);
|
||||
var width = Width;
|
||||
var height = Height;
|
||||
|
||||
// Got a max width?
|
||||
if (MaxWidth != null)
|
||||
{
|
||||
height = (int)(height * ((float)MaxWidth.Value) / Width);
|
||||
width = MaxWidth.Value;
|
||||
}
|
||||
|
||||
// Exceed the max width when we take pixel width into account?
|
||||
if (width * PixelWidth > maxWidth)
|
||||
{
|
||||
height = (int)(height * (maxWidth / (float)(width * PixelWidth)));
|
||||
width = maxWidth / PixelWidth;
|
||||
|
||||
// If it's not possible to scale the canvas sufficiently, it's too small to render.
|
||||
if (height == 0)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
|
||||
// Need to rescale the pixel buffer?
|
||||
if (Scale && (width != Width || height != Height))
|
||||
{
|
||||
pixels = ScaleDown(width, height);
|
||||
}
|
||||
|
||||
if (UsePixelCharacters)
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var color = pixels[x, y];
|
||||
if (color.HasValue)
|
||||
{
|
||||
var c = color.Value;
|
||||
yield return new Segment(GetPixelChar(c), new Style(foreground: new(c.Red, c.Green, c.Blue)));
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return new Segment(emptyPixel);
|
||||
}
|
||||
}
|
||||
|
||||
yield return Segment.LineBreak;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var color = pixels[x, y];
|
||||
if (color.HasValue)
|
||||
{
|
||||
var c = color.Value;
|
||||
yield return new Segment(emptyPixel, new Style(background: new(c.Red, c.Green, c.Blue)));
|
||||
}
|
||||
else
|
||||
{
|
||||
yield return new Segment(emptyPixel);
|
||||
}
|
||||
}
|
||||
|
||||
yield return Segment.LineBreak;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SKColor?[,] ScaleDown(int newWidth, int newHeight)
|
||||
{
|
||||
var buffer = new SKColor?[newWidth, newHeight];
|
||||
var xRatio = ((Width << 16) / newWidth) + 1;
|
||||
var yRatio = ((Height << 16) / newHeight) + 1;
|
||||
|
||||
for (var i = 0; i < newHeight; i++)
|
||||
{
|
||||
for (var j = 0; j < newWidth; j++)
|
||||
{
|
||||
buffer[j, i] = _pixels[(j * xRatio) >> 16, (i * yRatio) >> 16];
|
||||
}
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
private string GetPixelChar(SKColor c)
|
||||
{
|
||||
var index = Math.Min((int)(c.Alpha / 255f * PixelCharacters.Length), PixelCharacters.Length - 1);
|
||||
return new(PixelCharacters[index], PixelWidth);
|
||||
}
|
||||
}
|
||||
}
|
||||
163
SpineViewerCLI/CanvasImageAscii.cs
Normal file
163
SpineViewerCLI/CanvasImageAscii.cs
Normal file
@@ -0,0 +1,163 @@
|
||||
using SkiaSharp;
|
||||
using Spectre.Console;
|
||||
using Spectre.Console.Rendering;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
internal class CanvasImageAscii : Renderable
|
||||
{
|
||||
private static readonly SKSamplingOptions _defaultSamplingOptions = new(new SKCubicResampler());
|
||||
|
||||
/// <summary>
|
||||
/// Gets the image width.
|
||||
/// </summary>
|
||||
public int Width => Image.Width;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the image height.
|
||||
/// </summary>
|
||||
public int Height => Image.Height;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the render width of the canvas.
|
||||
/// </summary>
|
||||
public int? MaxWidth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the render width of the canvas.
|
||||
/// </summary>
|
||||
public int PixelWidth { get; set; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the pixel characters, ordered by transparency.
|
||||
/// </summary>
|
||||
public string PixelCharacters { get; set; } = ".,:;-=+*?oSXBGWM$&%#@";
|
||||
|
||||
/// <summary>
|
||||
/// Whether to use pixel characters instead of spaces.
|
||||
/// </summary>
|
||||
public bool UsePixelCharacters { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the <see cref="SKSamplingOptions"/> that should
|
||||
/// be used when scaling the image. Defaults to bicubic sampling.
|
||||
/// </summary>
|
||||
public SKSamplingOptions? SamplingOptions { get; set; }
|
||||
|
||||
internal SKBitmap Image { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CanvasImageAscii"/> class.
|
||||
/// </summary>
|
||||
/// <param name="filename">The image filename.</param>
|
||||
public CanvasImageAscii(string filename)
|
||||
{
|
||||
Image = SKBitmap.Decode(filename);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CanvasImageAscii"/> class.
|
||||
/// </summary>
|
||||
/// <param name="data">Buffer containing an image.</param>
|
||||
public CanvasImageAscii(ReadOnlySpan<byte> data)
|
||||
{
|
||||
Image = SKBitmap.Decode(data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CanvasImageAscii"/> class.
|
||||
/// </summary>
|
||||
/// <param name="data">Stream containing an image.</param>
|
||||
public CanvasImageAscii(Stream data)
|
||||
{
|
||||
Image = SKBitmap.Decode(data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CanvasImageAscii"/> class.
|
||||
/// </summary>
|
||||
/// <param name="image">The <see cref="SKImage"/> object.</param>
|
||||
public CanvasImageAscii(SKImage image)
|
||||
{
|
||||
Image = SKBitmap.FromImage(image);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override Measurement Measure(RenderOptions options, int maxWidth)
|
||||
{
|
||||
if (PixelWidth < 0)
|
||||
{
|
||||
throw new InvalidOperationException("Pixel width must be greater than zero.");
|
||||
}
|
||||
|
||||
var width = MaxWidth ?? Width;
|
||||
if (maxWidth < width * PixelWidth)
|
||||
{
|
||||
return new Measurement(maxWidth, maxWidth);
|
||||
}
|
||||
|
||||
return new Measurement(width * PixelWidth, width * PixelWidth);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override IEnumerable<Segment> Render(RenderOptions options, int maxWidth)
|
||||
{
|
||||
var image = Image;
|
||||
|
||||
var width = Width;
|
||||
var height = Height;
|
||||
|
||||
// Got a max width?
|
||||
if (MaxWidth != null)
|
||||
{
|
||||
height = (int)(height * ((float)MaxWidth.Value) / Width);
|
||||
width = MaxWidth.Value;
|
||||
}
|
||||
|
||||
// Exceed the max width when we take pixel width into account?
|
||||
if (width * PixelWidth > maxWidth)
|
||||
{
|
||||
height = (int)(height * (maxWidth / (float)(width * PixelWidth)));
|
||||
width = maxWidth / PixelWidth;
|
||||
}
|
||||
|
||||
// Need to rescale the pixel buffer?
|
||||
if (width != Width || height != Height)
|
||||
{
|
||||
var samplingOptions = SamplingOptions ?? _defaultSamplingOptions;
|
||||
image = image.Resize(new SKSizeI(width, height), samplingOptions);
|
||||
}
|
||||
|
||||
var canvas = new CanvasAscii(width, height)
|
||||
{
|
||||
MaxWidth = MaxWidth,
|
||||
PixelWidth = PixelWidth,
|
||||
PixelCharacters = PixelCharacters,
|
||||
UsePixelCharacters = UsePixelCharacters,
|
||||
Scale = false,
|
||||
};
|
||||
|
||||
// XXX: 也许是 SkiaSharp@3.119.0 的 bug, 此处像素值一定是非预乘的格式
|
||||
for (var y = 0; y < image.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < image.Width; x++)
|
||||
{
|
||||
var p = image.GetPixel(x, y);
|
||||
if (p.Alpha == 0) continue;
|
||||
float a = p.Alpha / 255f;
|
||||
byte r = (byte)(p.Red * a);
|
||||
byte g = (byte)(p.Green * a);
|
||||
byte b = (byte)(p.Blue * a);
|
||||
canvas.SetPixel(x, y, new(r, g, b, p.Alpha));
|
||||
}
|
||||
}
|
||||
|
||||
return ((IRenderable)canvas).Render(options, maxWidth);
|
||||
}
|
||||
}
|
||||
}
|
||||
471
SpineViewerCLI/ExportCommand.cs
Normal file
471
SpineViewerCLI/ExportCommand.cs
Normal file
@@ -0,0 +1,471 @@
|
||||
using NLog;
|
||||
using Spectre.Console;
|
||||
using Spine;
|
||||
using Spine.Exporters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public enum ExportFormat
|
||||
{
|
||||
Png = 0x0100,
|
||||
Jpg = 0x0101,
|
||||
Webp = 0x0102,
|
||||
Frames = 0x0200,
|
||||
Gif = 0x0300,
|
||||
Webpa = 0x0301,
|
||||
Apng = 0x0302,
|
||||
Mp4 = 0x0303,
|
||||
Webm = 0x0304,
|
||||
Mkv = 0x0305,
|
||||
Mov = 0x0306,
|
||||
Custom = 0x0400,
|
||||
}
|
||||
|
||||
public class ExportCommand : Command
|
||||
{
|
||||
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private static readonly string _name = "export";
|
||||
private static readonly string _desc = "Export single model";
|
||||
|
||||
#region >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 基本参数 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
||||
|
||||
public Argument<FileInfo> ArgSkel { get; } = new("skel")
|
||||
{
|
||||
Description = "Path of skel file.",
|
||||
};
|
||||
|
||||
public Option<ExportFormat> OptFormat { get; } = new("--format", "-f")
|
||||
{
|
||||
Description = "Export format.",
|
||||
Required = true,
|
||||
};
|
||||
|
||||
public Option<string> OptOutput { get; } = new("--output", "-o")
|
||||
{
|
||||
Description = "Output file or directory. Use a directory for frame sequence export.",
|
||||
Required = true,
|
||||
};
|
||||
|
||||
public Option<string[]> OptAnimations { get; } = new("--animations", "-a")
|
||||
{
|
||||
Description = "Animations to export. Supports multiple entries, placed in order on tracks starting from 0.",
|
||||
Required = true,
|
||||
Arity = ArgumentArity.OneOrMore,
|
||||
AllowMultipleArgumentsPerToken = true,
|
||||
};
|
||||
|
||||
public Option<FileInfo> OptAtlas { get; } = new("--atlas")
|
||||
{
|
||||
Description = "Path to the atlas file that matches the skel file.",
|
||||
};
|
||||
|
||||
public Option<float> OptScale { get; } = new("--scale")
|
||||
{
|
||||
Description = "Scale factor of the model.",
|
||||
DefaultValueFactory = _ => 1f,
|
||||
};
|
||||
|
||||
public Option<bool> OptPma { get; } = new("--pma")
|
||||
{
|
||||
Description = "Specifies whether the texture uses PMA (premultiplied alpha) format.",
|
||||
};
|
||||
|
||||
public Option<string[]> OptSkins { get; } = new("--skins")
|
||||
{
|
||||
Description = "Skins to export. Multiple skins can be specified.",
|
||||
Arity = ArgumentArity.OneOrMore,
|
||||
AllowMultipleArgumentsPerToken = true,
|
||||
};
|
||||
|
||||
public Option<string[]> OptDisableSlots { get; } = new("--disable-slots")
|
||||
{
|
||||
Description = "Slots to disable during export. Multiple slots can be specified.",
|
||||
Arity = ArgumentArity.OneOrMore,
|
||||
AllowMultipleArgumentsPerToken = true,
|
||||
};
|
||||
|
||||
public Option<float> OptWarmUp { get; } = new("--warm-up")
|
||||
{
|
||||
Description = "Warm-up duration of the animation, used to stabilize physics effects. A negative value will automatically warm up for the maximum duration among all animations.",
|
||||
DefaultValueFactory = _ => 0f,
|
||||
};
|
||||
|
||||
public Option<bool> OptNoProgress { get; } = new("--no-progress")
|
||||
{
|
||||
Description = "Do not display real-time progress.",
|
||||
};
|
||||
|
||||
#endregion
|
||||
|
||||
#region >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 基本导出参数 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
||||
|
||||
public Option<SFML.Graphics.Color> OptColor { get; } = new("--color")
|
||||
{
|
||||
Description = "Background color of content.",
|
||||
//DefaultValueFactory = ...
|
||||
CustomParser = Utils.ParseColor
|
||||
};
|
||||
|
||||
public Option<uint> OptMargin { get; } = new("--margin")
|
||||
{
|
||||
Description = "Size of the margin (in pixels) around the content.",
|
||||
DefaultValueFactory = _ => 0u,
|
||||
};
|
||||
|
||||
public Option<uint> OptMaxResolution { get; } = new("--max-resolution")
|
||||
{
|
||||
Description = "Maximum width or height (in pixels) for exported images.",
|
||||
DefaultValueFactory = _ => 2048u,
|
||||
};
|
||||
|
||||
public Option<float> OptTime { get; } = new("--time")
|
||||
{
|
||||
Description = "Start time offset of the animation.",
|
||||
DefaultValueFactory = _ => 0f,
|
||||
};
|
||||
|
||||
public Option<float> OptDuration { get; } = new("--duration")
|
||||
{
|
||||
Description = "Export duration. Negative values indicate automatic duration calculation.",
|
||||
DefaultValueFactory = _ => -1f,
|
||||
};
|
||||
|
||||
public Option<uint> OptFps { get; } = new("--fps")
|
||||
{
|
||||
Description = "Frame rate for export.",
|
||||
DefaultValueFactory = _ => 30u,
|
||||
};
|
||||
|
||||
public Option<float> OptSpeed { get; } = new("--speed")
|
||||
{
|
||||
Description = "Speed factor for the exported animation.",
|
||||
DefaultValueFactory = _ => 1f,
|
||||
};
|
||||
|
||||
public Option<bool> OptDropLastFrame { get; } = new("--drop-last-frame")
|
||||
{
|
||||
Description = "Whether to drop the incomplete last frame.",
|
||||
};
|
||||
|
||||
#endregion
|
||||
|
||||
#region >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 格式参数 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
||||
|
||||
public Option<uint> OptQuality { get; } = new("--quality")
|
||||
{
|
||||
Description = "Image quality.",
|
||||
DefaultValueFactory = _ => 80u,
|
||||
};
|
||||
|
||||
public Option<bool> OptLoop { get; } = new("--loop")
|
||||
{
|
||||
Description = "Whether the animation should loop.",
|
||||
};
|
||||
|
||||
public Option<bool> OptLossless { get; } = new("--lossless")
|
||||
{
|
||||
Description = "Whether to encode the WebP animation losslessly.",
|
||||
};
|
||||
|
||||
public Option<FFmpegVideoExporter.ApngPredMethod> OptApngPredMethod { get; } = new("--apng-pred")
|
||||
{
|
||||
Description = "Prediction method used for APNG animations.",
|
||||
DefaultValueFactory = _ => FFmpegVideoExporter.ApngPredMethod.Mixed,
|
||||
};
|
||||
|
||||
public Option<uint> OptCrf { get; } = new("--crf")
|
||||
{
|
||||
Description = "CRF (Constant Rate Factor) value for encoding.",
|
||||
DefaultValueFactory = _ => 23u,
|
||||
};
|
||||
|
||||
public Option<FFmpegVideoExporter.MovProfile> OptMovProfile { get; } = new("--mov-profile")
|
||||
{
|
||||
Description = "Profile setting for MOV format export.",
|
||||
DefaultValueFactory = _ => FFmpegVideoExporter.MovProfile.Yuv4444Extreme,
|
||||
};
|
||||
|
||||
#endregion
|
||||
|
||||
#region >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 自定义导出格式参数 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
||||
|
||||
public Option<string> OptFFFormat { get; } = new("--ff-format")
|
||||
{
|
||||
Description = "format option of ffmpeg",
|
||||
};
|
||||
|
||||
public Option<string> OptFFCodec { get; } = new("--ff-codec")
|
||||
{
|
||||
Description = "codec option of ffmpeg",
|
||||
};
|
||||
|
||||
public Option<string> OptFFPixelFormat { get; } = new("--ff-pixfmt")
|
||||
{
|
||||
Description = "pixel format option of ffmpeg",
|
||||
};
|
||||
|
||||
public Option<string> OptFFBitrate { get; } = new("--ff-bitrate")
|
||||
{
|
||||
Description = "bitrate option of ffmpeg",
|
||||
};
|
||||
|
||||
public Option<string> OptFFFilter { get; } = new("--ff-filter")
|
||||
{
|
||||
Description = "filter option of ffmpeg",
|
||||
};
|
||||
|
||||
public Option<string> OptFFArgs { get; } = new("--ff-args")
|
||||
{
|
||||
Description = "other arguments of ffmpeg",
|
||||
};
|
||||
|
||||
#endregion
|
||||
|
||||
public ExportCommand() : base(_name, _desc)
|
||||
{
|
||||
OptColor.DefaultValueFactory = r =>
|
||||
{
|
||||
var defVal = SFML.Graphics.Color.Black;
|
||||
try
|
||||
{
|
||||
switch (r.GetValue(OptFormat))
|
||||
{
|
||||
case ExportFormat.Png:
|
||||
case ExportFormat.Webp:
|
||||
case ExportFormat.Frames:
|
||||
case ExportFormat.Gif:
|
||||
case ExportFormat.Webpa:
|
||||
case ExportFormat.Apng:
|
||||
case ExportFormat.Webm:
|
||||
defVal = SFML.Graphics.Color.Transparent;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException) { } // 未提供 OptFormat 的时候 GetValue 会报错
|
||||
return defVal;
|
||||
};
|
||||
OptScale.Validators.Add(r =>
|
||||
{
|
||||
if (r.Tokens.Count > 0 && float.TryParse(r.Tokens[0].Value, out var v) && v < 0)
|
||||
r.AddError($"{OptScale.Name} must be non-negative.");
|
||||
});
|
||||
OptTime.Validators.Add(r =>
|
||||
{
|
||||
if (r.Tokens.Count > 0 && float.TryParse(r.Tokens[0].Value, out var v) && v < 0)
|
||||
r.AddError($"{OptTime.Name} must be non-negative.");
|
||||
});
|
||||
OptSpeed.Validators.Add(r =>
|
||||
{
|
||||
if (r.Tokens.Count > 0 && float.TryParse(r.Tokens[0].Value, out var v) && v < 0)
|
||||
r.AddError($"{OptSpeed.Name} must be non-negative.");
|
||||
});
|
||||
|
||||
this.AddArgsAndOpts();
|
||||
SetAction(ExportAction);
|
||||
}
|
||||
|
||||
private void ExportAction(ParseResult result)
|
||||
{
|
||||
// 读取模型
|
||||
using var spine = new SpineObject(result.GetValue(ArgSkel)!.FullName, result.GetValue(OptAtlas)?.FullName);
|
||||
|
||||
// 设置模型参数
|
||||
spine.Skeleton.ScaleX = spine.Skeleton.ScaleY = result.GetValue(OptScale);
|
||||
spine.UsePma = result.GetValue(OptPma);
|
||||
|
||||
// 设置要导出的动画
|
||||
int trackIdx = 0;
|
||||
foreach (var name in result.GetValue(OptAnimations))
|
||||
{
|
||||
if (!spine.Data.AnimationsByName.ContainsKey(name))
|
||||
{
|
||||
_logger.Warn("No animation named '{0}', skip it", name);
|
||||
continue;
|
||||
}
|
||||
spine.AnimationState.SetAnimation(trackIdx, name, true);
|
||||
trackIdx++;
|
||||
}
|
||||
|
||||
// 设置需要启用的皮肤
|
||||
foreach (var name in result.GetValue(OptSkins))
|
||||
{
|
||||
if (!spine.SetSkinStatus(name, true))
|
||||
{
|
||||
_logger.Warn("Failed to enable skin '{0}'", name);
|
||||
}
|
||||
}
|
||||
|
||||
// 设置需要屏蔽的插槽
|
||||
foreach (var name in result.GetValue(OptDisableSlots))
|
||||
{
|
||||
if (!spine.SetSlotVisible(name, false))
|
||||
{
|
||||
_logger.Warn("Failed to disable slot '{0}'", name);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: 设置要启用的插槽
|
||||
|
||||
// 时间轴处理
|
||||
var warmup = result.GetValue(OptWarmUp);
|
||||
spine.Update(warmup < 0 ? spine.GetAnimationMaxDuration() : warmup);
|
||||
spine.Update(result.GetValue(OptTime));
|
||||
|
||||
using var exporter = GetExporterFilledWithArgs(result, spine);
|
||||
|
||||
// 创建输出目录
|
||||
string output = result.GetValue(OptOutput);
|
||||
Directory.CreateDirectory(exporter is FrameSequenceExporter ? output : Path.GetDirectoryName(output));
|
||||
|
||||
// 挂载进度报告函数
|
||||
if (exporter is VideoExporter ve && !result.GetValue(OptNoProgress))
|
||||
{
|
||||
AnsiConsole.Progress().Columns(
|
||||
[
|
||||
new TaskDescriptionColumn(),
|
||||
new ProgressBarColumn(),
|
||||
new PercentageColumn(),
|
||||
new RemainingTimeColumn(),
|
||||
new SpinnerColumn(),
|
||||
]).Start(ctx =>
|
||||
{
|
||||
var task = ctx.AddTask($"Exporting '{spine.Name}'");
|
||||
task.MaxValue = ve.GetFrameCount();
|
||||
ve.ProgressReporter = (total, done, text) => task.Value = done;
|
||||
ve.Export(output, spine);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
exporter.Export(output, spine);
|
||||
}
|
||||
|
||||
_logger.Info($"{spine.SkelPath} export completed");
|
||||
}
|
||||
|
||||
private BaseExporter GetExporterFilledWithArgs(ParseResult result, SpineObject spine)
|
||||
{
|
||||
var formatType = (int)result.GetValue(OptFormat) >> 8;
|
||||
|
||||
// 根据模型获取自动分辨率和视区参数
|
||||
var maxResolution = result.GetValue(OptMaxResolution);
|
||||
var margin = result.GetValue(OptMargin);
|
||||
var bounds = formatType == 0x01 ? spine.GetCurrentBounds() : spine.GetAnimationBounds(result.GetValue(OptFps));
|
||||
var resolution = new SFML.System.Vector2u((uint)bounds.Size.X, (uint)bounds.Size.Y);
|
||||
if (resolution.X >= maxResolution || resolution.Y >= maxResolution)
|
||||
{
|
||||
// 缩小到最大像素限制
|
||||
var scale = Math.Min(maxResolution / bounds.Width, maxResolution / bounds.Height);
|
||||
resolution.X = (uint)(bounds.Width * scale);
|
||||
resolution.Y = (uint)(bounds.Height * scale);
|
||||
}
|
||||
var viewBounds = bounds.GetCanvasBounds(resolution, margin);
|
||||
|
||||
var duration = result.GetValue(OptDuration);
|
||||
if (duration < 0) duration = spine.GetAnimationMaxDuration();
|
||||
|
||||
if (formatType == 0x01)
|
||||
{
|
||||
return new FrameExporter(resolution.X + margin * 2, resolution.Y + margin * 2)
|
||||
{
|
||||
Size = new(viewBounds.Width, -viewBounds.Height),
|
||||
Center = viewBounds.Position + viewBounds.Size / 2,
|
||||
Rotation = 0,
|
||||
BackgroundColor = result.GetValue(OptColor),
|
||||
|
||||
Format = result.GetValue(OptFormat) switch
|
||||
{
|
||||
ExportFormat.Png => SkiaSharp.SKEncodedImageFormat.Png,
|
||||
ExportFormat.Jpg => SkiaSharp.SKEncodedImageFormat.Jpeg,
|
||||
ExportFormat.Webp => SkiaSharp.SKEncodedImageFormat.Webp,
|
||||
var v => throw new InvalidOperationException($"{v}"),
|
||||
},
|
||||
Quality = (int)result.GetValue(OptQuality),
|
||||
};
|
||||
}
|
||||
else if (formatType == 0x02)
|
||||
{
|
||||
return new FrameSequenceExporter(resolution.X + margin * 2, resolution.Y + margin * 2)
|
||||
{
|
||||
Size = new(viewBounds.Width, -viewBounds.Height),
|
||||
Center = viewBounds.Position + viewBounds.Size / 2,
|
||||
Rotation = 0,
|
||||
BackgroundColor = result.GetValue(OptColor),
|
||||
|
||||
Fps = result.GetValue(OptFps),
|
||||
Speed = result.GetValue(OptSpeed),
|
||||
KeepLast = !result.GetValue(OptDropLastFrame),
|
||||
Duration = duration,
|
||||
};
|
||||
}
|
||||
else if (formatType == 0x03)
|
||||
{
|
||||
return new FFmpegVideoExporter(resolution.X + margin * 2, resolution.Y + margin * 2)
|
||||
{
|
||||
Size = new(viewBounds.Width, -viewBounds.Height),
|
||||
Center = viewBounds.Position + viewBounds.Size / 2,
|
||||
Rotation = 0,
|
||||
BackgroundColor = result.GetValue(OptColor),
|
||||
|
||||
Fps = result.GetValue(OptFps),
|
||||
Speed = result.GetValue(OptSpeed),
|
||||
KeepLast = !result.GetValue(OptDropLastFrame),
|
||||
Duration = duration,
|
||||
|
||||
Format = result.GetValue(OptFormat) switch
|
||||
{
|
||||
ExportFormat.Gif => FFmpegVideoExporter.VideoFormat.Gif,
|
||||
ExportFormat.Webpa => FFmpegVideoExporter.VideoFormat.Webp,
|
||||
ExportFormat.Apng => FFmpegVideoExporter.VideoFormat.Apng,
|
||||
ExportFormat.Mp4 => FFmpegVideoExporter.VideoFormat.Mp4,
|
||||
ExportFormat.Webm => FFmpegVideoExporter.VideoFormat.Webm,
|
||||
ExportFormat.Mkv => FFmpegVideoExporter.VideoFormat.Mkv,
|
||||
ExportFormat.Mov => FFmpegVideoExporter.VideoFormat.Mov,
|
||||
var v => throw new InvalidOperationException($"{v}"),
|
||||
},
|
||||
Quality = (int)result.GetValue(OptQuality),
|
||||
Loop = result.GetValue(OptLoop),
|
||||
Lossless = result.GetValue(OptLossless),
|
||||
PredMethod = result.GetValue(OptApngPredMethod),
|
||||
Crf = (int)result.GetValue(OptCrf),
|
||||
Profile = result.GetValue(OptMovProfile),
|
||||
}
|
||||
;
|
||||
}
|
||||
else if (formatType == 0x04)
|
||||
{
|
||||
return new CustomFFmpegExporter(resolution.X + margin * 2, resolution.Y + margin * 2)
|
||||
{
|
||||
Size = new(viewBounds.Width, -viewBounds.Height),
|
||||
Center = viewBounds.Position + viewBounds.Size / 2,
|
||||
Rotation = 0,
|
||||
BackgroundColor = result.GetValue(OptColor),
|
||||
|
||||
Fps = result.GetValue(OptFps),
|
||||
Speed = result.GetValue(OptSpeed),
|
||||
KeepLast = !result.GetValue(OptDropLastFrame),
|
||||
Duration = duration,
|
||||
|
||||
Format = result.GetValue(OptFFFormat),
|
||||
Codec = result.GetValue(OptFFCodec),
|
||||
PixelFormat = result.GetValue(OptFFPixelFormat),
|
||||
Bitrate = result.GetValue(OptFFBitrate),
|
||||
Filter = result.GetValue(OptFFFilter),
|
||||
CustomArgs = result.GetValue(OptFFArgs),
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentOutOfRangeException($"Unknown format type {formatType}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
105
SpineViewerCLI/Extension.cs
Normal file
105
SpineViewerCLI/Extension.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
using SFML.Graphics;
|
||||
using SFML.System;
|
||||
using Spine;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public static class Extension
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取一个对象副本, 继承所有状态
|
||||
/// </summary>
|
||||
public static SpineObject Copy(this SpineObject self, bool keepTrackTime = false)
|
||||
{
|
||||
var spineObject = new SpineObject(self, true);
|
||||
|
||||
// 拷贝轨道动画, 但是仅拷贝第一个条目
|
||||
foreach (var tr in self.AnimationState.IterTracks().Where(t => t is not null))
|
||||
{
|
||||
var t = spineObject.AnimationState.SetAnimation(tr!.TrackIndex, tr.Animation, tr.Loop);
|
||||
t.TimeScale = tr.TimeScale;
|
||||
t.Alpha = tr.Alpha;
|
||||
if (keepTrackTime)
|
||||
t.TrackTime = tr.TrackTime;
|
||||
}
|
||||
|
||||
// XXX(#105): 部分 3.4.02 版本模型在设置动画后出现附件残留, 因此强制进行一次 Setup
|
||||
if (spineObject.Version == SpineVersion.V34)
|
||||
{
|
||||
spineObject.Skeleton.SetSlotsToSetupPose();
|
||||
}
|
||||
|
||||
spineObject.Update(0);
|
||||
return spineObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前状态包围盒
|
||||
/// </summary>
|
||||
public static FloatRect GetCurrentBounds(this SpineObject self)
|
||||
{
|
||||
self.Skeleton.GetBounds(out var x, out var y, out var w, out var h);
|
||||
return new(x, y, Math.Max(w, 1e-6f), Math.Max(h, 1e-6f));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算所有轨道第一个条目的动画时长最大值
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
/// <returns></returns>
|
||||
public static float GetAnimationMaxDuration(this SpineObject self)
|
||||
{
|
||||
return self.AnimationState.IterTracks().Select(t => t?.Animation.Duration ?? 0).DefaultIfEmpty(0).Max();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并另一个矩形
|
||||
/// </summary>
|
||||
public static FloatRect Union(this FloatRect self, FloatRect rect)
|
||||
{
|
||||
float left = Math.Min(self.Left, rect.Left);
|
||||
float top = Math.Min(self.Top, rect.Top);
|
||||
float right = Math.Max(self.Left + self.Width, rect.Left + rect.Width);
|
||||
float bottom = Math.Max(self.Top + self.Height, rect.Top + rect.Height);
|
||||
return new(left, top, right - left, bottom - top);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按给定的帧率获取所有轨道第一个条目动画全时长包围盒大小, 是一个耗时操作, 如果可能的话最好缓存结果
|
||||
/// </summary>
|
||||
public static FloatRect GetAnimationBounds(this SpineObject self, float fps = 30)
|
||||
{
|
||||
using var copy = self.Copy();
|
||||
var bounds = copy.GetCurrentBounds();
|
||||
var maxDuration = copy.GetAnimationMaxDuration();
|
||||
for (float tick = 0, delta = 1 / fps; tick < maxDuration; tick += delta)
|
||||
{
|
||||
bounds = bounds.Union(copy.GetCurrentBounds());
|
||||
copy.Update(delta);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动添加所有能找到的类型是 <see cref="Argument"/> 或者 <see cref="Option"/> 的公开属性
|
||||
/// </summary>
|
||||
/// <param name="self"></param>
|
||||
public static void AddArgsAndOpts(this Command self)
|
||||
{
|
||||
// 用反射查找自己所有的公开属性是 Argument 或者 Option 的
|
||||
foreach (var prop in self.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
var value = prop.GetValue(self);
|
||||
if (value is Argument arg) self.Add(arg);
|
||||
else if (value is Option opt) self.Add(opt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
137
SpineViewerCLI/PreviewCommand.cs
Normal file
137
SpineViewerCLI/PreviewCommand.cs
Normal file
@@ -0,0 +1,137 @@
|
||||
using NLog;
|
||||
using Spectre.Console;
|
||||
using Spine;
|
||||
using Spine.Exporters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public class PreviewCommand : Command
|
||||
{
|
||||
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private static readonly string _name = "preview";
|
||||
private static readonly string _desc = "Preview a model";
|
||||
private static readonly int MaxResolution = 1024;
|
||||
|
||||
public Argument<FileInfo> ArgSkel { get; } = new("skel")
|
||||
{
|
||||
Description = "Path of skel file.",
|
||||
};
|
||||
|
||||
public Option<FileInfo> OptAtlas { get; } = new("--atlas")
|
||||
{
|
||||
Description = "Path to the atlas file that matches the skel file.",
|
||||
};
|
||||
|
||||
public Option<bool> OptPma { get; } = new("--pma")
|
||||
{
|
||||
Description = "Specifies whether the texture uses PMA (premultiplied alpha) format.",
|
||||
};
|
||||
|
||||
public Option<string[]> OptSkins { get; } = new("--skins")
|
||||
{
|
||||
Description = "Skins to enable. Multiple skins can be specified.",
|
||||
Arity = ArgumentArity.OneOrMore,
|
||||
AllowMultipleArgumentsPerToken = true,
|
||||
};
|
||||
|
||||
public Option<string[]> OptAnimations { get; } = new("--animations")
|
||||
{
|
||||
Description = "Animations to export. Supports multiple entries, placed in order on tracks starting from 0.",
|
||||
Arity = ArgumentArity.OneOrMore,
|
||||
AllowMultipleArgumentsPerToken = true,
|
||||
};
|
||||
|
||||
public Option<float> OptTime { get; } = new("--time")
|
||||
{
|
||||
Description = "Start time offset of the animation.",
|
||||
DefaultValueFactory = _ => 0f,
|
||||
};
|
||||
|
||||
public Option<bool> OptUseChars { get; } = new("--use-chars")
|
||||
{
|
||||
Description = "Whether to use characters instead of colored spaces for pixels",
|
||||
};
|
||||
|
||||
public PreviewCommand() : base(_name, _desc)
|
||||
{
|
||||
OptTime.Validators.Add(r =>
|
||||
{
|
||||
if (r.Tokens.Count > 0 && float.TryParse(r.Tokens[0].Value, out var v) && v < 0)
|
||||
r.AddError($"{OptTime.Name} must be non-negative.");
|
||||
});
|
||||
|
||||
this.AddArgsAndOpts();
|
||||
SetAction(PreviewAction);
|
||||
}
|
||||
|
||||
private void PreviewAction(ParseResult result)
|
||||
{
|
||||
// 读取模型
|
||||
using var spine = new SpineObject(result.GetValue(ArgSkel)!.FullName, result.GetValue(OptAtlas)?.FullName);
|
||||
|
||||
spine.UsePma = result.GetValue(OptPma);
|
||||
|
||||
// 设置要导出的动画
|
||||
int trackIdx = 0;
|
||||
foreach (var name in result.GetValue(OptAnimations))
|
||||
{
|
||||
if (!spine.Data.AnimationsByName.ContainsKey(name))
|
||||
{
|
||||
_logger.Warn("No animation named '{0}', skip it", name);
|
||||
continue;
|
||||
}
|
||||
spine.AnimationState.SetAnimation(trackIdx, name, true);
|
||||
trackIdx++;
|
||||
}
|
||||
|
||||
// 设置需要启用的皮肤
|
||||
foreach (var name in result.GetValue(OptSkins))
|
||||
{
|
||||
if (!spine.SetSkinStatus(name, true))
|
||||
{
|
||||
_logger.Warn("Failed to enable skin '{0}'", name);
|
||||
}
|
||||
}
|
||||
|
||||
// 设置时间偏移量
|
||||
spine.Update(result.GetValue(OptTime));
|
||||
|
||||
using var exporter = GetExporterFilledWithArgs(result, spine);
|
||||
using var skImage = exporter.ExportMemoryImage(spine);
|
||||
var img = new CanvasImageAscii(skImage) { UsePixelCharacters = result.GetValue(OptUseChars) };
|
||||
AnsiConsole.Write(img);
|
||||
}
|
||||
|
||||
private FrameExporter GetExporterFilledWithArgs(ParseResult result, SpineObject spine)
|
||||
{
|
||||
// 根据模型获取自动分辨率和视区参数
|
||||
var bounds = spine.GetCurrentBounds();
|
||||
var resolution = new SFML.System.Vector2u((uint)bounds.Size.X, (uint)bounds.Size.Y);
|
||||
if (resolution.X >= MaxResolution || resolution.Y >= MaxResolution)
|
||||
{
|
||||
// 缩小到最大像素限制
|
||||
var scale = Math.Min(MaxResolution / bounds.Width, MaxResolution / bounds.Height);
|
||||
resolution.X = (uint)(bounds.Width * scale);
|
||||
resolution.Y = (uint)(bounds.Height * scale);
|
||||
}
|
||||
var viewBounds = bounds.GetCanvasBounds(resolution);
|
||||
|
||||
return new FrameExporter(resolution)
|
||||
{
|
||||
Size = new(viewBounds.Width, -viewBounds.Height),
|
||||
Center = viewBounds.Position + viewBounds.Size / 2,
|
||||
Rotation = 0,
|
||||
BackgroundColor = SFML.Graphics.Color.Transparent,
|
||||
|
||||
Format = SkiaSharp.SKEncodedImageFormat.Png,
|
||||
Quality = 100,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
121
SpineViewerCLI/QueryCommand.cs
Normal file
121
SpineViewerCLI/QueryCommand.cs
Normal file
@@ -0,0 +1,121 @@
|
||||
using NLog;
|
||||
using Spine;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public class QueryCommand : Command
|
||||
{
|
||||
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
|
||||
private static readonly string _name = "query";
|
||||
private static readonly string _desc = "Query information of single model";
|
||||
|
||||
private static readonly string HalfHeader = new('>', 15);
|
||||
private static readonly char Separator = '\t';
|
||||
|
||||
public Argument<FileInfo> ArgSkel { get; } = new("skel")
|
||||
{
|
||||
Description = "Path of skel file.",
|
||||
};
|
||||
|
||||
public Option<FileInfo> OptAtlas { get; } = new("--atlas")
|
||||
{
|
||||
Description = "Path to the atlas file that matches the skel file.",
|
||||
};
|
||||
|
||||
public Option<bool> OptAll { get; } = new("--all")
|
||||
{
|
||||
Description = "Print all information",
|
||||
};
|
||||
|
||||
public Option<bool> OptSkin { get; } = new("--skin")
|
||||
{
|
||||
Description = "Print skins",
|
||||
};
|
||||
|
||||
public Option<bool> OptAnimation { get; } = new("--animation")
|
||||
{
|
||||
Description = "Print animations",
|
||||
};
|
||||
|
||||
public Option<bool> OptSlot { get; } = new("--slot")
|
||||
{
|
||||
Description = "Print slots",
|
||||
};
|
||||
|
||||
public QueryCommand() : base(_name, _desc)
|
||||
{
|
||||
this.AddArgsAndOpts();
|
||||
SetAction(QueryAction);
|
||||
}
|
||||
|
||||
private void QueryAction(ParseResult result)
|
||||
{
|
||||
// 读取模型
|
||||
using var spine = new SpineObject(result.GetValue(ArgSkel)!.FullName, result.GetValue(OptAtlas)?.FullName);
|
||||
|
||||
var all = result.GetValue(OptAll);
|
||||
|
||||
if (all || result.GetValue(OptSkin))
|
||||
{
|
||||
SkinRecord[] data = spine.Data.SkinsByName.Keys.Select(v => new SkinRecord(v)).ToArray();
|
||||
PrintData("Skins", SkinRecord.Headers, data);
|
||||
}
|
||||
if (all || result.GetValue(OptAnimation))
|
||||
{
|
||||
AnimationRecord[] data = spine.Data.Animations.Select(v => new AnimationRecord(v.Name, v.Duration)).ToArray();
|
||||
PrintData("Animations", AnimationRecord.Headers, data);
|
||||
}
|
||||
if (all || result.GetValue(OptSlot))
|
||||
{
|
||||
SlotRecord[] data = spine.Data.SlotAttachments.Select(v => new SlotRecord(v.Key, v.Value.Keys.ToArray())).ToArray();
|
||||
PrintData("Slots", SlotRecord.Headers, data);
|
||||
}
|
||||
}
|
||||
|
||||
private void PrintData(string dataName, string[] headers, RowRecord[] rows)
|
||||
{
|
||||
var header = $"{HalfHeader} {dataName} {HalfHeader}";
|
||||
var footer = new string('<', header.Length);
|
||||
|
||||
Console.WriteLine(header);
|
||||
Console.WriteLine(string.Join(Separator, headers));
|
||||
foreach (var row in rows)
|
||||
Console.WriteLine(string.Join(Separator, row.Values));
|
||||
Console.WriteLine(footer);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public abstract record RowRecord
|
||||
{
|
||||
public abstract object[] Values { get; }
|
||||
}
|
||||
|
||||
public record SkinRecord(string Name) : RowRecord
|
||||
{
|
||||
public static string[] Headers { get; } = [nameof(Name)];
|
||||
|
||||
public override object[] Values => [Name];
|
||||
}
|
||||
|
||||
public record AnimationRecord(string Name, float Duration) : RowRecord
|
||||
{
|
||||
public static string[] Headers { get; } = [nameof(Name), nameof(Duration)];
|
||||
|
||||
public override object[] Values => [Name, Duration];
|
||||
}
|
||||
|
||||
public record SlotRecord(string Name, string[] Attachments) : RowRecord
|
||||
{
|
||||
public static string[] Headers { get; } = [nameof(Name), nameof(Attachments)];
|
||||
|
||||
public override object[] Values => [Name, string.Join(';', Attachments)];
|
||||
}
|
||||
}
|
||||
3
SpineViewerCLI/README.md
Normal file
3
SpineViewerCLI/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# SpineViewerCLI
|
||||
|
||||
基于 [System.Command](https://www.nuget.org/packages/System.CommandLine) 的命令行工具.
|
||||
@@ -1,352 +1,84 @@
|
||||
using System.Globalization;
|
||||
using SFML.Graphics;
|
||||
using SFML.System;
|
||||
using NLog;
|
||||
using SkiaSharp;
|
||||
using Spectre.Console;
|
||||
using Spine;
|
||||
using Spine.Exporters;
|
||||
using SkiaSharp;
|
||||
using System.CommandLine;
|
||||
using System.Globalization;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public class CLI
|
||||
public static class SpineViewerCLI
|
||||
{
|
||||
const string USAGE = @"
|
||||
usage: SpineViewerCLI.exe [--skel PATH] [--atlas PATH] [--output PATH] [--animation STR] [--skin STR] [--hide-slot STR] [--pma] [--fps INT] [--loop] [--crf INT] [--time FLOAT] [--quality INT] [--width INT] [--height INT] [--centerx INT] [--centery INT] [--zoom FLOAT] [--speed FLOAT] [--color HEX] [--quiet]
|
||||
|
||||
options:
|
||||
--skel PATH Path to the .skel file
|
||||
--atlas PATH Path to the .atlas file, default searches in the skel file directory
|
||||
--output PATH Output file path. Extension determines export type (.mp4, .webm for video; .png, .jpg for frame)
|
||||
--animation STR Animation name
|
||||
--skin STR Skin name to apply. Can be used multiple times to stack skins.
|
||||
--hide-slot STR Slot name to hide. Can be used multiple times.
|
||||
--pma Use premultiplied alpha, default false
|
||||
--fps INT Frames per second (for video), default 24
|
||||
--loop Whether to loop the animation (for video), default false
|
||||
--crf INT Constant Rate Factor (for video), from 0 (lossless) to 51 (worst), default 23
|
||||
--time FLOAT Time in seconds to export a single frame. Providing this argument forces frame export mode.
|
||||
--quality INT Quality for lossy image formats (jpg, webp), from 0 to 100, default 80
|
||||
--width INT Output width, default 512
|
||||
--height INT Output height, default 512
|
||||
--centerx INT Center X offset, default automatically finds bounds
|
||||
--centery INT Center Y offset, default automatically finds bounds
|
||||
--zoom FLOAT Zoom level, default 1.0
|
||||
--speed FLOAT Speed of animation (for video), default 1.0
|
||||
--color HEX Background color as a hex RGBA color, default 000000ff (opaque black)
|
||||
--quiet Removes console progress log, default false
|
||||
";
|
||||
|
||||
public static void Main(string[] args)
|
||||
public static Option<bool> OptQuiet { get; } = new("--quiet", "-q")
|
||||
{
|
||||
string? skelPath = null;
|
||||
string? atlasPath = null;
|
||||
string? output = null;
|
||||
string? animation = null;
|
||||
var skins = new List<string>();
|
||||
var hideSlots = new List<string>();
|
||||
bool pma = false;
|
||||
uint fps = 24;
|
||||
bool loop = false;
|
||||
int crf = 23;
|
||||
float? time = null;
|
||||
int quality = 80;
|
||||
uint? width = null;
|
||||
uint? height = null;
|
||||
int? centerx = null;
|
||||
int? centery = null;
|
||||
float zoom = 1;
|
||||
float speed = 1;
|
||||
Color backgroundColor = Color.Black;
|
||||
bool quiet = false;
|
||||
Description = "Suppress console logging (quiet mode).",
|
||||
Recursive = true,
|
||||
};
|
||||
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
InitializeFileLog();
|
||||
|
||||
var cmdRoot = new RootCommand("Root Command")
|
||||
{
|
||||
switch (args[i])
|
||||
{
|
||||
case "--help":
|
||||
Console.Write(USAGE);
|
||||
Environment.Exit(0);
|
||||
break;
|
||||
case "--skel":
|
||||
skelPath = args[++i];
|
||||
break;
|
||||
case "--atlas":
|
||||
atlasPath = args[++i];
|
||||
break;
|
||||
case "--output":
|
||||
output = args[++i];
|
||||
break;
|
||||
case "--animation":
|
||||
animation = args[++i];
|
||||
break;
|
||||
case "--skin":
|
||||
skins.Add(args[++i]);
|
||||
break;
|
||||
case "--hide-slot":
|
||||
hideSlots.Add(args[++i]);
|
||||
break;
|
||||
case "--pma":
|
||||
pma = true;
|
||||
break;
|
||||
case "--fps":
|
||||
fps = uint.Parse(args[++i]);
|
||||
break;
|
||||
case "--loop":
|
||||
loop = true;
|
||||
break;
|
||||
case "--crf":
|
||||
crf = int.Parse(args[++i]);
|
||||
break;
|
||||
case "--time":
|
||||
time = float.Parse(args[++i]);
|
||||
break;
|
||||
case "--quality":
|
||||
quality = int.Parse(args[++i]);
|
||||
break;
|
||||
case "--width":
|
||||
width = uint.Parse(args[++i]);
|
||||
break;
|
||||
case "--height":
|
||||
height = uint.Parse(args[++i]);
|
||||
break;
|
||||
case "--centerx":
|
||||
centerx = int.Parse(args[++i]);
|
||||
break;
|
||||
case "--centery":
|
||||
centery = int.Parse(args[++i]);
|
||||
break;
|
||||
case "--zoom":
|
||||
zoom = float.Parse(args[++i]);
|
||||
break;
|
||||
case "--speed":
|
||||
speed = float.Parse(args[++i]);
|
||||
break;
|
||||
case "--color":
|
||||
backgroundColor = new Color(uint.Parse(args[++i], NumberStyles.HexNumber));
|
||||
break;
|
||||
case "--quiet":
|
||||
quiet = true;
|
||||
break;
|
||||
default:
|
||||
Console.Error.WriteLine($"Unknown argument: {args[i]}");
|
||||
Environment.Exit(2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
OptQuiet,
|
||||
new QueryCommand(),
|
||||
new PreviewCommand(),
|
||||
new ExportCommand(),
|
||||
};
|
||||
|
||||
if (string.IsNullOrEmpty(skelPath))
|
||||
{
|
||||
Console.Error.WriteLine("Missing --skel");
|
||||
Environment.Exit(2);
|
||||
}
|
||||
if (string.IsNullOrEmpty(output))
|
||||
{
|
||||
Console.Error.WriteLine("Missing --output");
|
||||
Environment.Exit(2);
|
||||
}
|
||||
var outputExtension = Path.GetExtension(output).TrimStart('.').ToLowerInvariant();
|
||||
var result = cmdRoot.Parse(args);
|
||||
|
||||
var sp = new SpineObject(skelPath, atlasPath);
|
||||
sp.UsePma = pma;
|
||||
if (!result.GetValue(OptQuiet))
|
||||
InitializeConsoleLog();
|
||||
|
||||
foreach (var skinName in skins)
|
||||
{
|
||||
if (!sp.SetSkinStatus(skinName, true))
|
||||
{
|
||||
var availableSkins = string.Join(", ", sp.Data.Skins.Select(s => s.Name));
|
||||
Console.Error.WriteLine($"Error: Skin '{skinName}' not found. Available skins: {availableSkins}");
|
||||
Environment.Exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(animation))
|
||||
{
|
||||
var availableAnimations = string.Join(", ", sp.Data.Animations.Select(a => a.Name));
|
||||
Console.Error.WriteLine($"Missing --animation. Available animations for {sp.Name}: {availableAnimations}");
|
||||
Environment.Exit(2);
|
||||
}
|
||||
|
||||
var trackEntry = sp.AnimationState.SetAnimation(0, animation, loop);
|
||||
if (time.HasValue)
|
||||
{
|
||||
trackEntry.TrackTime = time.Value;
|
||||
}
|
||||
sp.Update(0);
|
||||
|
||||
foreach (var slotName in hideSlots)
|
||||
{
|
||||
if (!sp.SetSlotVisible(slotName, false))
|
||||
{
|
||||
if (!quiet) Console.WriteLine($"Warning: Slot '{slotName}' not found, cannot hide.");
|
||||
}
|
||||
}
|
||||
|
||||
if (time.HasValue)
|
||||
{
|
||||
if (TryGetImageFormat(outputExtension, out var imageFormat))
|
||||
{
|
||||
if (!quiet) Console.WriteLine($"Exporting single frame at {time.Value:F2}s to {output}...");
|
||||
|
||||
FrameExporter exporter;
|
||||
if (width is uint w && height is uint h && centerx is int cx && centery is int cy)
|
||||
{
|
||||
exporter = new FrameExporter(w, h)
|
||||
{
|
||||
Center = (cx, cy),
|
||||
Size = (w / zoom, -h / zoom),
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
var frameBounds = GetSpineObjectBounds(sp);
|
||||
var bounds = GetFloatRectCanvasBounds(frameBounds, new(width ?? 512, height ?? 512));
|
||||
exporter = new FrameExporter(width ?? (uint)Math.Ceiling(bounds.Width), height ?? (uint)Math.Ceiling(bounds.Height))
|
||||
{
|
||||
Center = bounds.Position + bounds.Size / 2,
|
||||
Size = (bounds.Width, -bounds.Height),
|
||||
};
|
||||
}
|
||||
exporter.Format = imageFormat;
|
||||
exporter.Quality = quality;
|
||||
exporter.BackgroundColor = backgroundColor;
|
||||
|
||||
exporter.Export(output, sp);
|
||||
|
||||
if (!quiet)
|
||||
Console.WriteLine("Frame export complete.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var validImageExtensions = "png, jpg, jpeg, webp, bmp";
|
||||
Console.Error.WriteLine($"Error: --time argument requires a valid image format extension. Supported formats are: {validImageExtensions}.");
|
||||
Environment.Exit(2);
|
||||
}
|
||||
}
|
||||
else if (Enum.TryParse<FFmpegVideoExporter.VideoFormat>(outputExtension, true, out var videoFormat))
|
||||
{
|
||||
FFmpegVideoExporter exporter;
|
||||
if (width is uint w && height is uint h && centerx is int cx && centery is int cy)
|
||||
{
|
||||
exporter = new FFmpegVideoExporter(w, h)
|
||||
{
|
||||
Center = (cx, cy),
|
||||
Size = (w / zoom, -h / zoom),
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
var bounds = GetFloatRectCanvasBounds(GetSpineObjectAnimationBounds(sp, fps), new(width ?? 512, height ?? 512));
|
||||
exporter = new FFmpegVideoExporter(width ?? (uint)Math.Ceiling(bounds.Width), height ?? (uint)Math.Ceiling(bounds.Height))
|
||||
{
|
||||
Center = bounds.Position + bounds.Size / 2,
|
||||
Size = (bounds.Width, -bounds.Height),
|
||||
};
|
||||
}
|
||||
exporter.Duration = trackEntry.Animation.Duration;
|
||||
exporter.Fps = fps;
|
||||
exporter.Format = videoFormat;
|
||||
exporter.Loop = loop;
|
||||
exporter.Crf = crf;
|
||||
exporter.Speed = speed;
|
||||
exporter.BackgroundColor = backgroundColor;
|
||||
|
||||
if (!quiet)
|
||||
exporter.ProgressReporter = (total, done, text) => Console.Write($"\r{text}");
|
||||
|
||||
using var cts = new CancellationTokenSource();
|
||||
exporter.Export(output, cts.Token, sp);
|
||||
|
||||
if (!quiet)
|
||||
Console.WriteLine("\nVideo export complete.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var validVideoExtensions = string.Join(", ", Enum.GetNames(typeof(FFmpegVideoExporter.VideoFormat)));
|
||||
var validImageExtensions = "png, jpg, jpeg, webp, bmp";
|
||||
Console.Error.WriteLine($"Invalid output extension or missing --time for image export. Supported video formats are: {validVideoExtensions}. Supported image formats (with --time) are: {validImageExtensions}.");
|
||||
Environment.Exit(2);
|
||||
}
|
||||
|
||||
Environment.Exit(0);
|
||||
return result.Invoke();
|
||||
}
|
||||
|
||||
private static bool TryGetImageFormat(string extension, out SKEncodedImageFormat format)
|
||||
private static void InitializeFileLog()
|
||||
{
|
||||
switch (extension)
|
||||
var config = new NLog.Config.LoggingConfiguration();
|
||||
var fileTarget = new NLog.Targets.FileTarget("fileTarget")
|
||||
{
|
||||
case "png":
|
||||
format = SKEncodedImageFormat.Png;
|
||||
return true;
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
format = SKEncodedImageFormat.Jpeg;
|
||||
return true;
|
||||
case "webp":
|
||||
format = SKEncodedImageFormat.Webp;
|
||||
return true;
|
||||
case "bmp":
|
||||
format = SKEncodedImageFormat.Bmp;
|
||||
return true;
|
||||
default:
|
||||
format = default;
|
||||
return false;
|
||||
}
|
||||
Encoding = System.Text.Encoding.UTF8,
|
||||
Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${level:uppercase=true} - ${processid} - ${callsite-filename:includeSourcePath=false}:${callsite-linenumber} - ${message}",
|
||||
AutoFlush = true,
|
||||
FileName = "${basedir}/logs/cli.log",
|
||||
ArchiveFileName = "${basedir}/logs/cli.{#}.log",
|
||||
ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Rolling,
|
||||
ArchiveAboveSize = 1048576,
|
||||
MaxArchiveFiles = 5,
|
||||
ConcurrentWrites = true,
|
||||
KeepFileOpen = false,
|
||||
};
|
||||
|
||||
config.AddTarget(fileTarget);
|
||||
config.AddRule(LogLevel.Trace, LogLevel.Fatal, fileTarget);
|
||||
LogManager.Configuration = config;
|
||||
}
|
||||
|
||||
public static SpineObject CopySpineObject(SpineObject sp)
|
||||
private static void InitializeConsoleLog()
|
||||
{
|
||||
var spineObject = new SpineObject(sp, true);
|
||||
foreach (var tr in sp.AnimationState.IterTracks().Where(t => t is not null))
|
||||
var config = new NLog.Config.LoggingConfiguration();
|
||||
var consoleTarget = new NLog.Targets.ColoredConsoleTarget("consoleTarget")
|
||||
{
|
||||
var t = spineObject.AnimationState.SetAnimation(tr!.TrackIndex, tr.Animation, tr.Loop);
|
||||
}
|
||||
spineObject.Update(0);
|
||||
return spineObject;
|
||||
}
|
||||
Encoding = System.Text.Encoding.UTF8,
|
||||
Layout = "[${level:format=OneLetter}]${date:format=yyyy-MM-dd HH\\:mm\\:ss} - ${message}",
|
||||
AutoFlush = true,
|
||||
DetectConsoleAvailable = true,
|
||||
StdErr = true,
|
||||
DetectOutputRedirected = true,
|
||||
};
|
||||
|
||||
static FloatRect GetSpineObjectBounds(SpineObject sp)
|
||||
{
|
||||
sp.Skeleton.GetBounds(out var x, out var y, out var w, out var h);
|
||||
return new(x, y, Math.Max(w, 1e-6f), Math.Max(h, 1e-6f));
|
||||
}
|
||||
static FloatRect FloatRectUnion(FloatRect a, FloatRect b)
|
||||
{
|
||||
float left = Math.Min(a.Left, b.Left);
|
||||
float top = Math.Min(a.Top, b.Top);
|
||||
float right = Math.Max(a.Left + a.Width, b.Left + b.Width);
|
||||
float bottom = Math.Max(a.Top + a.Height, b.Top + b.Height);
|
||||
return new FloatRect(left, top, right - left, bottom - top);
|
||||
}
|
||||
static FloatRect GetSpineObjectAnimationBounds(SpineObject sp, float fps = 10)
|
||||
{
|
||||
sp = CopySpineObject(sp);
|
||||
var bounds = GetSpineObjectBounds(sp);
|
||||
var maxDuration = sp.AnimationState.IterTracks().Select(t => t?.Animation.Duration ?? 0).DefaultIfEmpty(0).Max();
|
||||
sp.Update(0);
|
||||
for (float tick = 0, delta = 1 / fps; tick < maxDuration; tick += delta)
|
||||
{
|
||||
bounds = FloatRectUnion(bounds, GetSpineObjectBounds(sp));
|
||||
sp.Update(delta);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
static FloatRect GetFloatRectCanvasBounds(FloatRect rect, Vector2u resolution)
|
||||
{
|
||||
float sizeW = rect.Width;
|
||||
float sizeH = rect.Height;
|
||||
float innerW = resolution.X;
|
||||
float innerH = resolution.Y;
|
||||
var scale = Math.Max(Math.Abs(sizeW / innerW), Math.Abs(sizeH / innerH));
|
||||
var scaleW = scale * Math.Sign(sizeW);
|
||||
var scaleH = scale * Math.Sign(sizeH);
|
||||
consoleTarget.RowHighlightingRules.Add(new("level == LogLevel.Info", NLog.Targets.ConsoleOutputColor.DarkGray, NLog.Targets.ConsoleOutputColor.NoChange));
|
||||
consoleTarget.RowHighlightingRules.Add(new("level == LogLevel.Warn", NLog.Targets.ConsoleOutputColor.DarkYellow, NLog.Targets.ConsoleOutputColor.NoChange));
|
||||
consoleTarget.RowHighlightingRules.Add(new("level == LogLevel.Error", NLog.Targets.ConsoleOutputColor.Red, NLog.Targets.ConsoleOutputColor.NoChange));
|
||||
consoleTarget.RowHighlightingRules.Add(new("level == LogLevel.Fatal", NLog.Targets.ConsoleOutputColor.White, NLog.Targets.ConsoleOutputColor.DarkRed));
|
||||
|
||||
innerW *= scaleW;
|
||||
innerH *= scaleH;
|
||||
|
||||
var x = rect.Left - (innerW - sizeW) / 2;
|
||||
var y = rect.Top - (innerH - sizeH) / 2;
|
||||
var w = resolution.X * scaleW;
|
||||
var h = resolution.Y * scaleH;
|
||||
return new(x, y, w, h);
|
||||
config.AddTarget(consoleTarget);
|
||||
config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget);
|
||||
LogManager.Configuration = config;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
@@ -7,7 +7,7 @@
|
||||
<TargetFramework>net8.0-windows</TargetFramework>
|
||||
<BaseOutputPath>$(SolutionDir)out</BaseOutputPath>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<Version>0.0.1</Version>
|
||||
<Version>0.16.9</Version>
|
||||
<OutputType>Exe</OutputType>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -15,6 +15,12 @@
|
||||
<NoWarn>$(NoWarn);NETSDK1206</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="NLog" Version="5.4.0" />
|
||||
<PackageReference Include="Spectre.Console" Version="0.52.0" />
|
||||
<PackageReference Include="System.CommandLine" Version="2.0.0-rc.2.25502.107" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SFMLRenderer\SFMLRenderer.csproj" />
|
||||
<ProjectReference Include="..\Spine\Spine.csproj" />
|
||||
|
||||
67
SpineViewerCLI/Utils.cs
Normal file
67
SpineViewerCLI/Utils.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using SFML.Graphics;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.CommandLine.Parsing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SpineViewerCLI
|
||||
{
|
||||
public static class Utils
|
||||
{
|
||||
public static Color ParseColor(ArgumentResult result)
|
||||
{
|
||||
var token = result.Tokens.Count > 0 ? result.Tokens[0].Value : null;
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
return Color.Black;
|
||||
|
||||
try
|
||||
{
|
||||
// 去掉开头的 #
|
||||
var hex = token.Trim().TrimStart('#');
|
||||
|
||||
// 支持格式: RGB / ARGB / RRGGBB / AARRGGBB
|
||||
if (hex.Length == 3)
|
||||
{
|
||||
// #RGB → #RRGGBB
|
||||
var r = hex[0];
|
||||
var g = hex[1];
|
||||
var b = hex[2];
|
||||
hex = $"{r}{r}{g}{g}{b}{b}";
|
||||
hex = "FF" + hex; // 加上不透明 alpha
|
||||
}
|
||||
else if (hex.Length == 4)
|
||||
{
|
||||
// #ARGB → #AARRGGBB
|
||||
var a = hex[0];
|
||||
var r = hex[1];
|
||||
var g = hex[2];
|
||||
var b = hex[3];
|
||||
hex = $"{a}{a}{r}{r}{g}{g}{b}{b}";
|
||||
}
|
||||
else if (hex.Length == 6)
|
||||
{
|
||||
// #RRGGBB → #AARRGGBB
|
||||
hex = "FF" + hex;
|
||||
}
|
||||
else if (hex.Length != 8)
|
||||
{
|
||||
result.AddError("Invalid color format. Use #RGB, #ARGB, #RRGGBB, or #AARRGGBB.");
|
||||
return Color.Black;
|
||||
}
|
||||
|
||||
var aVal = Convert.ToByte(hex[..2], 16);
|
||||
var rVal = Convert.ToByte(hex.Substring(2, 2), 16);
|
||||
var gVal = Convert.ToByte(hex.Substring(4, 2), 16);
|
||||
var bVal = Convert.ToByte(hex.Substring(6, 2), 16);
|
||||
return new(rVal, gVal, bVal, aVal);
|
||||
}
|
||||
catch
|
||||
{
|
||||
result.AddError("Invalid color format.");
|
||||
return Color.Black;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user