38 Commits

533 changed files with 29874 additions and 1615 deletions

View File

@@ -1,8 +0,0 @@
using System.Reflection;
[assembly: AssemblyCompany("Cryville")]
[assembly: AssemblyCopyright("Copyright © Cryville 2020-2022")]
[assembly: AssemblyDefaultAlias("Cosmo Resona")]
[assembly: AssemblyProduct("Cosmo Resona")]
[assembly: AssemblyTitle("Cosmo Resona")]
[assembly: AssemblyVersion("0.5.0")]

View File

@@ -73,7 +73,7 @@ namespace Cryville.Common.Buffers {
if (!_invalidated) return; if (!_invalidated) return;
_invalidated = false; _invalidated = false;
var ev = OnUpdate; var ev = OnUpdate;
if (ev != null) OnUpdate.Invoke(); if (ev != null) ev.Invoke();
} }
IEnumerator IEnumerable.GetEnumerator() { IEnumerator IEnumerable.GetEnumerator() {

View File

@@ -48,5 +48,31 @@ namespace Cryville.Common.Math {
} }
} }
} }
/// <summary>
/// Gets the greatest common divisor (GCD) of two integers.
/// </summary>
/// <param name="n">The first integer.</param>
/// <param name="d">The second integer.</param>
/// <returns>The greatest common divisor (GCD) of the two integers.</returns>
public static int GreatestCommonDivisor(int n, int d) {
while (d != 0) {
int t = d;
d = n % d;
n = t;
}
return n;
}
/// <summary>
/// Simplifies a fraction.
/// </summary>
/// <param name="n">The numerator.</param>
/// <param name="d">The denominator.</param>
public static void Simplify(ref int n, ref int d) {
var gcd = GreatestCommonDivisor(n, d);
n /= gcd;
d /= gcd;
}
} }
} }

View File

@@ -1,9 +1,13 @@
namespace Cryville.Common.Math { using System;
namespace Cryville.Common.Math {
/// <summary> /// <summary>
/// Represents a square matrix. /// Represents a square matrix.
/// </summary> /// </summary>
public class SquareMatrix { public class SquareMatrix {
readonly float[,] content; readonly float[,] content;
readonly float[,] buffer;
readonly int[] refl;
/// <summary> /// <summary>
/// The size of the matrix. /// The size of the matrix.
/// </summary> /// </summary>
@@ -17,6 +21,8 @@
/// <param name="size">The size of the matrix.</param> /// <param name="size">The size of the matrix.</param>
public SquareMatrix(int size) { public SquareMatrix(int size) {
content = new float[size, size]; content = new float[size, size];
buffer = new float[size, size];
refl = new int[size];
Size = size; Size = size;
} }
/// <summary> /// <summary>
@@ -38,38 +44,36 @@
/// <returns>The column vector eliminated.</returns> /// <returns>The column vector eliminated.</returns>
public ColumnVector<T> Eliminate<T>(ColumnVector<T> v, IVectorOperator<T> o) { public ColumnVector<T> Eliminate<T>(ColumnVector<T> v, IVectorOperator<T> o) {
int s = Size; int s = Size;
float[,] d = (float[,])content.Clone(); Array.Copy(content, buffer, Size * Size);
int[] refl = new int[s]; for (int i = 0; i < s; i++) refl[i] = i;
for (int i = 0; i < s; i++)
refl[i] = i;
for (int r = 0; r < s; r++) { for (int r = 0; r < s; r++) {
for (int r0 = r; r0 < s; r0++) for (int r0 = r; r0 < s; r0++)
if (d[refl[r0], r] != 0) { if (buffer[refl[r0], r] != 0) {
refl[r] = r0; refl[r] = r0;
refl[r0] = r; refl[r0] = r;
break; break;
} }
int or = refl[r]; int or = refl[r];
float sf0 = d[or, r]; float sf0 = buffer[or, r];
for (int c0 = r; c0 < s; c0++) for (int c0 = r; c0 < s; c0++)
d[or, c0] /= sf0; buffer[or, c0] /= sf0;
v[or] = o.ScalarMultiply(1 / sf0, v[or]); v[or] = o.ScalarMultiply(1 / sf0, v[or]);
for (int r1 = r + 1; r1 < s; r1++) { for (int r1 = r + 1; r1 < s; r1++) {
int or1 = refl[r1]; int or1 = refl[r1];
float sf1 = d[or1, r]; float sf1 = buffer[or1, r];
for (int c1 = r; c1 < s; c1++) for (int c1 = r; c1 < s; c1++)
d[or1, c1] -= d[or, c1] * sf1; buffer[or1, c1] -= buffer[or, c1] * sf1;
v[or1] = o.Add(v[or1], o.ScalarMultiply(-sf1, v[or])); v[or1] = o.Add(v[or1], o.ScalarMultiply(-sf1, v[or]));
} }
} }
T[] res = new T[s]; ColumnVector<T> res = new ColumnVector<T>(s);
for (int r2 = s - 1; r2 >= 0; r2--) { for (int r2 = s - 1; r2 >= 0; r2--) {
var v2 = v[refl[r2]]; var v2 = v[refl[r2]];
for (int c2 = r2 + 1; c2 < s; c2++) for (int c2 = r2 + 1; c2 < s; c2++)
v2 = o.Add(v2, o.ScalarMultiply(-d[refl[r2], c2], res[refl[c2]])); v2 = o.Add(v2, o.ScalarMultiply(-buffer[refl[r2], c2], res[refl[c2]]));
res[refl[r2]] = v2; res[refl[r2]] = v2;
} }
return new ColumnVector<T>(res); return res;
} }
/// <summary> /// <summary>
/// Creates a square matrix and fills it with polynomial coefficients. /// Creates a square matrix and fills it with polynomial coefficients.

View File

@@ -44,5 +44,21 @@ namespace Cryville.Common {
if (result.Length == 0) return "_"; if (result.Length == 0) return "_";
return result; return result;
} }
/// <summary>
/// Gets the process path from a command.
/// </summary>
/// <param name="command">The command.</param>
/// <returns>The process path.</returns>
public static string GetProcessPathFromCommand(string command) {
command = command.Trim();
if (command[0] == '"') {
return command.Substring(1, command.IndexOf('"', 1) - 1);
}
else {
int e = command.IndexOf(' ');
if (e == -1) return command;
else return command.Substring(0, e);
}
}
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
@@ -11,13 +12,13 @@ namespace Cryville.Common.Unity {
Transform dirs; Transform dirs;
Transform files; Transform files;
public Action Callback { private get; set; } public event Action OnClose;
#if UNITY_ANDROID && !UNITY_EDITOR_WIN #if UNITY_ANDROID && !UNITY_EDITOR_WIN
string androidStorage = ""; string androidStorage = "";
#endif #endif
string fileName = ""; string fileName = null;
public string FileName { public string FileName {
get { return fileName; } get { return fileName; }
} }
@@ -27,8 +28,16 @@ namespace Cryville.Common.Unity {
set { m_filter = value; } set { m_filter = value; }
} }
#pragma warning disable IDE0051 public Dictionary<string, string> m_presetPaths = new Dictionary<string, string>();
public Dictionary<string, string> PresetPaths {
get { return m_presetPaths; }
set { m_presetPaths = value; }
}
GameObject prefabButton;
void Start() { void Start() {
prefabButton = Resources.Load<GameObject>("Common/Button");
panel = gameObject.transform.Find("Panel"); panel = gameObject.transform.Find("Panel");
title = panel.Find("Title/Text"); title = panel.Find("Title/Text");
drives = panel.Find("Drives/DrivesInner"); drives = panel.Find("Drives/DrivesInner");
@@ -38,8 +47,8 @@ namespace Cryville.Common.Unity {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
CurrentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory()); CurrentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
#elif UNITY_ANDROID #elif UNITY_ANDROID
using (AndroidJavaClass ajc=new AndroidJavaClass("android.os.Environment")) using (AndroidJavaClass ajc = new AndroidJavaClass("android.os.Environment"))
using (AndroidJavaObject file=ajc.CallStatic<AndroidJavaObject>("getExternalStorageDirectory")) { using (AndroidJavaObject file = ajc.CallStatic<AndroidJavaObject>("getExternalStorageDirectory")) {
androidStorage = file.Call<string>("getAbsolutePath"); androidStorage = file.Call<string>("getAbsolutePath");
CurrentDirectory = new DirectoryInfo(androidStorage); CurrentDirectory = new DirectoryInfo(androidStorage);
} }
@@ -47,9 +56,8 @@ namespace Cryville.Common.Unity {
#error No default directory #error No default directory
#endif #endif
} }
UpdateGUI(); UpdateGUI(0);
} }
#pragma warning restore IDE0051
public void Show() { public void Show() {
fileName = null; fileName = null;
@@ -57,85 +65,82 @@ namespace Cryville.Common.Unity {
} }
public void Close() { public void Close() {
if (Callback != null) Callback.Invoke(); var ev = OnClose;
if (ev != null) ev.Invoke();
gameObject.SetActive(false); gameObject.SetActive(false);
} }
public DirectoryInfo CurrentDirectory; public DirectoryInfo CurrentDirectory;
void OnDriveChanged(string s) { void ChangeDirectory(DirectoryInfo s) {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN CurrentDirectory = s;
CurrentDirectory = new DirectoryInfo(s); UpdateGUI(1);
#elif UNITY_ANDROID
switch (s) {
case "?storage":
CurrentDirectory = new DirectoryInfo(androidStorage);
break;
}
#else
#error No change drive logic
#endif
UpdateGUI();
} }
void OnDirectoryChanged(string s) { void SelectFile(string s) {
CurrentDirectory = new DirectoryInfo(CurrentDirectory.FullName + "/" + s);
UpdateGUI();
}
void OnFileChanged(string s) {
fileName = s; fileName = s;
Close(); Close();
} }
void UpdateGUI() { void UpdateGUI(int depth) {
title.GetComponent<Text>().text = CurrentDirectory.FullName; title.GetComponent<Text>().text = CurrentDirectory.FullName;
CallHelper.Purge(drives); if (depth <= 0) {
CallHelper.Purge(drives);
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
var dl = Directory.GetLogicalDrives(); var dl = Directory.GetLogicalDrives();
foreach (string d in dl) { foreach (string d in dl) {
GameObject btn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button")); GameObject btn = Instantiate(prefabButton);
btn.GetComponentInChildren<Text>().text = d; btn.GetComponentInChildren<Text>().text = d;
var ts = d; btn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(new DirectoryInfo(d)));
btn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDriveChanged(ts)); btn.transform.SetParent(drives, false);
btn.transform.SetParent(drives, false); }
}
#elif UNITY_ANDROID #elif UNITY_ANDROID
GameObject sbtn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button")); GameObject sbtn = GameObject.Instantiate<GameObject>(prefabButton);
sbtn.GetComponentInChildren<Text>().text = "Storage"; sbtn.GetComponentInChildren<Text>().text = "Storage";
sbtn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDriveChanged("?storage")); sbtn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDriveChanged(new DirectoryInfo(androidStorage)));
sbtn.transform.SetParent(drives, false); sbtn.transform.SetParent(drives, false);
#else #else
#error No update GUI logic #error No update GUI logic
#endif #endif
foreach (var p in m_presetPaths) {
var d = new DirectoryInfo(p.Value);
if (d.Exists) {
GameObject btn = Instantiate(prefabButton);
btn.GetComponentInChildren<Text>().text = p.Key;
btn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(d));
btn.transform.SetParent(drives, false);
}
}
}
CallHelper.Purge(dirs); CallHelper.Purge(dirs);
DirectoryInfo[] subdirs = CurrentDirectory.GetDirectories(); DirectoryInfo[] subdirs = CurrentDirectory.GetDirectories();
GameObject pbtn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button")); GameObject pbtn = Instantiate(prefabButton);
pbtn.GetComponentInChildren<Text>().text = ".."; pbtn.GetComponentInChildren<Text>().text = "..";
pbtn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDirectoryChanged("..")); pbtn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(new DirectoryInfo(Path.Combine(CurrentDirectory.FullName, ".."))));
pbtn.transform.SetParent(dirs, false); pbtn.transform.SetParent(dirs, false);
foreach (DirectoryInfo d in subdirs) { foreach (DirectoryInfo d in subdirs) {
GameObject btn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button")); GameObject btn = Instantiate(prefabButton);
btn.GetComponentInChildren<Text>().text = d.Name; btn.GetComponentInChildren<Text>().text = d.Name;
var ts = d.Name; var ts = d;
btn.GetComponentInChildren<Button>().onClick.AddListener(() => OnDirectoryChanged(ts)); btn.GetComponentInChildren<Button>().onClick.AddListener(() => ChangeDirectory(ts));
btn.transform.SetParent(dirs, false); btn.transform.SetParent(dirs, false);
} }
CallHelper.Purge(files); CallHelper.Purge(files);
FileInfo[] fl = CurrentDirectory.GetFiles(); FileInfo[] fl = CurrentDirectory.GetFiles();
foreach (FileInfo d in fl) { foreach (FileInfo d in fl) {
foreach (string ext in m_filter) foreach (string ext in m_filter) {
if (d.Extension == ext) goto ext_matched; if (d.Extension == ext) {
continue; GameObject btn = Instantiate(prefabButton);
ext_matched: btn.GetComponentInChildren<Text>().text = d.Name + " / " + (d.Length / 1024.0).ToString("0.0 KiB");
GameObject btn = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/Button")); var ts = d.FullName;
btn.GetComponentInChildren<Text>().text = d.Name + " / " + (d.Length / 1024.0).ToString("0.0 KiB"); btn.GetComponentInChildren<Button>().onClick.AddListener(() => SelectFile(ts));
var ts = d.FullName; btn.transform.SetParent(files, false);
btn.GetComponentInChildren<Button>().onClick.AddListener(() => OnFileChanged(ts)); break;
btn.transform.SetParent(files, false); }
}
} }
} }
} }

View File

@@ -118,7 +118,7 @@ namespace Cryville.Common.Unity {
fdialog = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>(); fdialog = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>();
fdialog.Filter = filter; fdialog.Filter = filter;
fdialog.CurrentDirectory = ContextPath; fdialog.CurrentDirectory = ContextPath;
fdialog.Callback = () => OnFileDialogClosed(); fdialog.OnClose += OnFileDialogClosed;
} }
editor.SetDescription(PropertyName, desc); editor.SetDescription(PropertyName, desc);
UpdateValue(); UpdateValue();

View File

@@ -0,0 +1,9 @@
using System;
using System.Collections.Generic;
namespace Cryville.Crtr.Browsing {
public abstract class ExtensionInterface {
public abstract IEnumerable<ResourceConverter> GetResourceConverters();
public abstract IEnumerable<LocalResourceFinder> GetResourceFinders();
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: a69a6c726b01961419c4835bba37a218 guid: 4ffe72fef6ebb9e4da3571b4117f0d6d
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@@ -1,4 +1,6 @@
namespace Cryville.Crtr.Browsing { using System.Collections.Generic;
namespace Cryville.Crtr.Browsing {
public interface IResourceManager<T> { public interface IResourceManager<T> {
string[] CurrentDirectory { get; } string[] CurrentDirectory { get; }
int ChangeDirectory(string[] dir); int ChangeDirectory(string[] dir);
@@ -10,5 +12,6 @@
bool ImportItemFrom(string path); bool ImportItemFrom(string path);
string[] GetSupportedFormats(); string[] GetSupportedFormats();
Dictionary<string, string> GetPresetPaths();
} }
} }

View File

@@ -17,6 +17,8 @@ namespace Cryville.Crtr.Browsing {
static readonly Dictionary<string, List<ResourceConverter>> converters static readonly Dictionary<string, List<ResourceConverter>> converters
= new Dictionary<string, List<ResourceConverter>>(); = new Dictionary<string, List<ResourceConverter>>();
static readonly Dictionary<string, string> localRes
= new Dictionary<string, string>();
public LegacyResourceManager(string rootPath) { public LegacyResourceManager(string rootPath) {
_rootPath = rootPath; _rootPath = rootPath;
@@ -25,13 +27,35 @@ namespace Cryville.Crtr.Browsing {
static LegacyResourceManager() { static LegacyResourceManager() {
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (var type in asm.GetTypes()) { foreach (var type in asm.GetTypes()) {
if (type.IsSubclassOf(typeof(ResourceConverter))) { if (!type.IsSubclassOf(typeof(ExtensionInterface))) continue;
var converter = (ResourceConverter)Activator.CreateInstance(type); var ext = (ExtensionInterface)Activator.CreateInstance(type);
foreach (var f in converter.GetSupportedFormats()) { try {
if (!converters.ContainsKey(f)) var cs = ext.GetResourceConverters();
converters.Add(f, new List<ResourceConverter> { converter }); if (cs != null) {
else converters[f].Add(converter); foreach (var c in cs) {
var fs = c.GetSupportedFormats();
if (fs == null) continue;
foreach (var f in fs) {
if (f == null) continue;
if (!converters.ContainsKey(f))
converters.Add(f, new List<ResourceConverter> { c });
else converters[f].Add(c);
}
}
} }
var fs2 = ext.GetResourceFinders();
if (fs2 != null) {
foreach (var f in fs2) {
var name = f.Name;
var path = f.GetRootPath();
if (name != null && path != null)
localRes.Add(name, path);
}
}
Logger.Log("main", 1, "Resource", "Loaded extension {0}", ReflectionHelper.GetNamespaceQualifiedName(type));
}
catch (Exception ex) {
Logger.Log("main", 4, "Resource", "Failed to initialize extension {0}: {1}", ReflectionHelper.GetNamespaceQualifiedName(type), ex);
} }
} }
} }
@@ -198,5 +222,9 @@ namespace Cryville.Crtr.Browsing {
public string[] GetSupportedFormats() { public string[] GetSupportedFormats() {
return converters.Keys.ToArray(); return converters.Keys.ToArray();
} }
public Dictionary<string, string> GetPresetPaths() {
return localRes;
}
} }
} }

View File

@@ -0,0 +1,6 @@
namespace Cryville.Crtr.Browsing {
public abstract class LocalResourceFinder {
public abstract string Name { get; }
public abstract string GetRootPath();
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: d6a3a023271b82a4985d1bbcc86e6fa8 guid: f5b3f3294f679f14f8ec1195b0def630
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

View File

@@ -20,6 +20,9 @@ namespace Cryville.Crtr.Browsing {
_dialog = GameObject.Instantiate(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>(); _dialog = GameObject.Instantiate(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>();
_dialog.gameObject.SetActive(false); _dialog.gameObject.SetActive(false);
_dialog.Filter = ResourceManager.GetSupportedFormats();
_dialog.PresetPaths = ResourceManager.GetPresetPaths();
_dialog.OnClose += OnAddDialogClosed;
} }
private bool LoadPathPart(int id, GameObject obj) { private bool LoadPathPart(int id, GameObject obj) {
@@ -57,8 +60,6 @@ namespace Cryville.Crtr.Browsing {
} }
public void OnAddButtonClicked() { public void OnAddButtonClicked() {
_dialog.Callback = OnAddDialogClosed;
_dialog.Filter = ResourceManager.GetSupportedFormats();
_dialog.Show(); _dialog.Show();
} }

View File

@@ -9,14 +9,19 @@ using System.Text.RegularExpressions;
namespace Cryville.Crtr { namespace Cryville.Crtr {
[JsonConverter(typeof(BeatTimeConverter))] [JsonConverter(typeof(BeatTimeConverter))]
public struct BeatTime { public struct BeatTime : IComparable<BeatTime>, IEquatable<BeatTime> {
[JsonConstructor()] [JsonConstructor()]
public BeatTime(int _b, int _n, int _d) { public BeatTime(int _b, int _n, int _d) {
b = _b; b = _b;
n = _n; n = _n;
d = _d; d = _d;
} }
public BeatTime(int _n, int _d) {
b = _n / _d;
n = _n % _d;
d = _d;
}
[JsonIgnore] [JsonIgnore]
public int b; public int b;
@@ -25,6 +30,36 @@ namespace Cryville.Crtr {
[JsonIgnore] [JsonIgnore]
public int d; public int d;
[JsonIgnore]
public double Decimal { get { return b + (double)n / d; } }
public int CompareTo(BeatTime other) {
var c = b.CompareTo(other.b);
if (c != 0) return c;
return ((double)n / d).CompareTo((double)other.n / other.d);
}
public override bool Equals(object obj) {
if (!(obj is BeatTime)) return false;
return Equals((BeatTime)obj);
}
public bool Equals(BeatTime other) {
return b.Equals(other.b) && ((double)n / d).Equals((double)other.n / other.d);
}
public override int GetHashCode() {
return Decimal.GetHashCode();
}
public static bool operator ==(BeatTime left, BeatTime right) {
return left.Equals(right);
}
public static bool operator !=(BeatTime left, BeatTime right) {
return !left.Equals(right);
}
} }
public class BeatTimeConverter : JsonConverter { public class BeatTimeConverter : JsonConverter {
@@ -56,7 +91,7 @@ namespace Cryville.Crtr {
[JsonIgnore] [JsonIgnore]
public float BeatPosition { public float BeatPosition {
get { get {
return time.Value.b + time.Value.n / (float)time.Value.d + BeatOffset; return (float)time.Value.Decimal + BeatOffset;
} }
} }
@@ -66,7 +101,7 @@ namespace Cryville.Crtr {
public float EndBeatPosition { public float EndBeatPosition {
get { get {
if (endtime == null) return BeatPosition; if (endtime == null) return BeatPosition;
return endtime.Value.b + endtime.Value.n / (float)endtime.Value.d + BeatOffset; return (float)endtime.Value.Decimal + BeatOffset;
} }
} }

View File

@@ -371,8 +371,9 @@ namespace Cryville.Crtr {
texloadtimer.Start(); texloadtimer.Start();
frames = new Dictionary<string, SpriteFrame>(); frames = new Dictionary<string, SpriteFrame>();
texs = new Dictionary<string, Texture2D>(); texs = new Dictionary<string, Texture2D>();
var skinDir = skinFile.Directory.FullName;
foreach (var f in skin.frames) { foreach (var f in skin.frames) {
texLoadQueue.Enqueue(Path.Combine(skinFile.Directory.FullName, f)); texLoadQueue.Enqueue(Path.Combine(skinDir, f));
} }
} }
@@ -528,7 +529,7 @@ namespace Cryville.Crtr {
foreach (var ts in gs.Value.Children) { foreach (var ts in gs.Value.Children) {
ContainerHandler th; ContainerHandler th;
if (ts.Key is Chart.Note) { if (ts.Key is Chart.Note) {
th = new NoteHandler(gh, (Chart.Note)ts.Key, pruleset, judge); th = new NoteHandler(gh, (Chart.Note)ts.Key, pruleset);
} }
else { else {
th = new TrackHandler(gh, (Chart.Track)ts.Key); th = new TrackHandler(gh, (Chart.Track)ts.Key);

View File

@@ -9,6 +9,11 @@ namespace Cryville.Crtr.Components {
protected Vector3? prevpt; protected Vector3? prevpt;
protected Quaternion? prevrot; protected Quaternion? prevrot;
protected int vertCount = 0; protected int vertCount = 0;
bool suppressed;
public SectionalGameObject() {
SubmitProperty("suppressed", new PropOp.Boolean(v => suppressed = v), 2);
}
protected override void OnDestroy() { protected override void OnDestroy() {
mesh.Destroy(); mesh.Destroy();
@@ -23,7 +28,7 @@ namespace Cryville.Crtr.Components {
} }
public void AppendPoint(Vector3 p, Quaternion r) { public void AppendPoint(Vector3 p, Quaternion r) {
if (prevpt == p && prevrot == r) return; if (prevpt == p && prevrot == r || suppressed) return;
AppendPointInternal(p, r); AppendPointInternal(p, r);
// if (!headGenerated) Logger.Log("main", 0, "Skin/Polysec", "{0}", r); // if (!headGenerated) Logger.Log("main", 0, "Skin/Polysec", "{0}", r);
prevpt = p; prevpt = p;
@@ -98,25 +103,14 @@ namespace Cryville.Crtr.Components {
public override void Init() { public override void Init() {
base.Init(); base.Init();
head.Load();
body.Load();
tail.Load();
mesh.Init(transform); mesh.Init(transform);
List<Material> materials = new List<Material>(); var mats = mesh.Renderer.materials = new Material[] { mesh.NewMaterial, mesh.NewMaterial, mesh.NewMaterial };
if (head.FrameName != null) AddMat(materials, head.FrameName); head.Bind(mats[0]);
if (body.FrameName != null) AddMat(materials, body.FrameName); body.Bind(mats[1]);
if (tail.FrameName != null) AddMat(materials, tail.FrameName); tail.Bind(mats[2]);
mesh.Renderer.materials = materials.ToArray();
UpdateZIndex();
}
void AddMat(List<Material> list, string frame) { UpdateZIndex();
var mat = mesh.NewMaterial;
mat.mainTexture = ChartPlayer.frames[frame].Texture;
list.Add(mat);
} }
protected override void OnDestroy() { protected override void OnDestroy() {
@@ -157,9 +151,9 @@ namespace Cryville.Crtr.Components {
int vcpsec = _shapeLength; // Vertex Count Per Section int vcpsec = _shapeLength; // Vertex Count Per Section
float width = GetWidth(); float width = GetWidth();
float headLength = 0; float headLength = 0;
if (head.FrameName != null) headLength = width / head.Ratio; if (head.Frame != null) headLength = width / head.Ratio;
float tailLength = 0; float tailLength = 0;
if (tail.FrameName != null) tailLength = width / tail.Ratio; if (tail.Frame != null) tailLength = width / tail.Ratio;
float endLength = headLength + tailLength; float endLength = headLength + tailLength;
if (sumLength <= endLength) { if (sumLength <= endLength) {
// The total length of the two ends is longer than the whole mesh, squeeze the two ends // The total length of the two ends is longer than the whole mesh, squeeze the two ends
@@ -187,17 +181,17 @@ namespace Cryville.Crtr.Components {
verts = _vertPool.Rent(vc * vcpsec); verts = _vertPool.Rent(vc * vcpsec);
uvs = _uvPool.Rent(vc * vcpsec); uvs = _uvPool.Rent(vc * vcpsec);
int i = 0; int t = 0; float l = 0; int m = 0; int i = 0; int t = 0; float l = 0; int m = 0;
if (head.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); } if (head.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); }
if (body.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trib, body, ref i, ref t, ref l, headLength, sumLength - tailLength, vcpsec, hvc + bvc); } if (body.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trib, body, ref i, ref t, ref l, headLength, sumLength - tailLength, vcpsec, hvc + bvc); }
if (tail.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trit, tail, ref i, ref t, ref l, sumLength - tailLength, sumLength, vcpsec, vc); } if (tail.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trit, tail, ref i, ref t, ref l, sumLength - tailLength, sumLength, vcpsec, vc); }
mesh.Mesh.subMeshCount = m; mesh.Mesh.subMeshCount = m;
m = 0; m = 0;
mesh.Mesh.SetVertices(verts); mesh.Mesh.SetVertices(verts);
mesh.Mesh.SetUVs(0, uvs); mesh.Mesh.SetUVs(0, uvs);
if (head.FrameName != null) mesh.Mesh.SetTriangles(trih, m++); if (head.Frame != null) mesh.Mesh.SetTriangles(trih, m++);
if (body.FrameName != null) mesh.Mesh.SetTriangles(trib, m++); if (body.Frame != null) mesh.Mesh.SetTriangles(trib, m++);
if (tail.FrameName != null) mesh.Mesh.SetTriangles(trit, m++); if (tail.Frame != null) mesh.Mesh.SetTriangles(trit, m++);
mesh.Mesh.RecalculateNormals(); mesh.Mesh.RecalculateNormals();
_vertPool.Return(verts); verts = null; _vertPool.Return(verts); verts = null;

View File

@@ -1,4 +1,5 @@
using Cryville.Common.Pdt; using Cryville.Common;
using Cryville.Common.Pdt;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
@@ -7,21 +8,21 @@ namespace Cryville.Crtr.Components {
/// <summary> /// <summary>
/// The property operators of the component. /// The property operators of the component.
/// </summary> /// </summary>
public Dictionary<string, SkinProperty> Properties { get; private set; } public Dictionary<int, SkinProperty> Properties { get; private set; }
/// <summary> /// <summary>
/// Submits a property. /// Submits a property.
/// </summary> /// </summary>
/// <param name="name">The name of the property.</param> /// <param name="name">The name of the property.</param>
/// <param name="property">The property.</param> /// <param name="property">The property.</param>
protected void SubmitProperty(string name, PdtOperator property, int uct = 1) { protected void SubmitProperty(string name, PdtOperator property, int uct = 1) {
Properties.Add(name, new SkinProperty(property, uct)); Properties.Add(IdentifierManager.SharedInstance.Request(name), new SkinProperty(property, uct));
} }
/// <summary> /// <summary>
/// Creates a skin component. /// Creates a skin component.
/// </summary> /// </summary>
protected SkinComponent() { protected SkinComponent() {
Properties = new Dictionary<string, SkinProperty>(); Properties = new Dictionary<int, SkinProperty>();
} }
public virtual void Init() { } public virtual void Init() { }

View File

@@ -4,7 +4,16 @@ using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr.Components { namespace Cryville.Crtr.Components {
public class SpriteInfo { public class SpriteInfo {
public string FrameName; string m_frameName;
public string FrameName {
get {
return m_frameName;
}
set {
m_frameName = value;
Reload();
}
}
public SpriteFrame Frame { public SpriteFrame Frame {
get; get;
private set; private set;
@@ -20,15 +29,32 @@ namespace Cryville.Crtr.Components {
return Rect.width / Rect.height; return Rect.width / Rect.height;
} }
} }
bool _loaded;
Material _mat;
public void Bind(Material mat) {
_loaded = true;
_mat = mat;
Reload();
}
public void Load() { public void Load() {
if (FrameName != null) { _loaded = true;
Reload();
}
public void Reload() {
if (!_loaded) return;
if (!string.IsNullOrEmpty(FrameName)) {
if (ChartPlayer.frames.ContainsKey(FrameName)) { if (ChartPlayer.frames.ContainsKey(FrameName)) {
Frame = ChartPlayer.frames[FrameName]; Frame = ChartPlayer.frames[FrameName];
} }
else { else {
Logger.Log("main", 4, "Skin", "Texture {0} not found", FrameName); Logger.Log("main", 4, "Skin", "Texture {0} not found", FrameName);
Frame = null;
} }
} }
else Frame = null;
if (_mat != null) {
_mat.mainTexture = Frame == null ? null : Frame.Texture;
}
} }
} }
@@ -68,16 +94,11 @@ namespace Cryville.Crtr.Components {
} }
protected void OnFrameUpdate() { protected void OnFrameUpdate() {
if (!mesh.Initialized) return; if (!mesh.Initialized) return;
if (frameInfo.FrameName == null) { if (frameInfo.Frame == null) {
mesh.Renderer.enabled = false; mesh.Renderer.enabled = false;
return; return;
} }
mesh.Renderer.enabled = true; mesh.Renderer.enabled = true;
frameInfo.Load();
if (frameInfo.Frame != null)
mesh.Renderer.material.mainTexture = frameInfo.Frame.Texture;
else
Logger.Log("main", 4, "Skin", "Unable to load texture {0}", frameInfo.FrameName);
UpdateUV(); UpdateUV();
UpdateScale(); UpdateScale();
UpdateZIndex(); UpdateZIndex();
@@ -140,8 +161,8 @@ namespace Cryville.Crtr.Components {
} }
public override void Init() { public override void Init() {
frameInfo.Load();
InternalInit(); InternalInit();
frameInfo.Bind(mesh.Renderer.material);
OnFrameUpdate(); OnFrameUpdate();
UpdateOpacity(); UpdateOpacity();
} }

View File

@@ -1,3 +1,4 @@
using Cryville.Common;
using Cryville.Crtr.Components; using Cryville.Crtr.Components;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@@ -36,9 +37,10 @@ namespace Cryville.Crtr.Event {
/// </summary> /// </summary>
public Transform gogroup; public Transform gogroup;
public readonly Dictionary<string, Anchor> Anchors = new Dictionary<string, Anchor>(); public readonly Dictionary<int, Anchor> Anchors = new Dictionary<int, Anchor>();
public Transform a_head; protected Transform a_cur;
public Transform a_tail; protected Transform a_head;
protected Transform a_tail;
public Vector3 Position { public Vector3 Position {
get; get;
protected set; protected set;
@@ -64,8 +66,8 @@ namespace Cryville.Crtr.Event {
get { return cs.Container; } get { return cs.Container; }
} }
public SkinContainer skinContainer; SkinContainer skinContainer;
public Judge judge; protected Judge judge;
public void AttachSystems(PdtSkin skin, Judge judge) { public void AttachSystems(PdtSkin skin, Judge judge) {
skinContainer = new SkinContainer(skin); skinContainer = new SkinContainer(skin);
this.judge = judge; this.judge = judge;
@@ -75,17 +77,24 @@ namespace Cryville.Crtr.Event {
public abstract string TypeName { public abstract string TypeName {
get; get;
} }
protected readonly static int _a_cur = IdentifierManager.SharedInstance.Request("cur");
protected readonly static int _a_head = IdentifierManager.SharedInstance.Request("head");
protected readonly static int _a_tail = IdentifierManager.SharedInstance.Request("tail");
public virtual void PreInit() { public virtual void PreInit() {
gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString(CultureInfo.InvariantCulture)).transform; gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString(CultureInfo.InvariantCulture)).transform;
if (cs.Parent != null) if (cs.Parent != null)
gogroup.SetParent(cs.Parent.Handler.gogroup, false); gogroup.SetParent(cs.Parent.Handler.gogroup, false);
a_head = new GameObject("::head").transform; a_cur = RegisterAnchor(_a_cur);
a_head.SetParent(gogroup, false); a_head = RegisterAnchor(_a_head);
Anchors.Add("head", new Anchor() { Transform = a_head }); a_tail = RegisterAnchor(_a_tail);
a_tail = new GameObject("::tail").transform;
a_tail.SetParent(gogroup, false);
Anchors.Add("tail", new Anchor() { Transform = a_tail });
} }
protected Transform RegisterAnchor(int name) {
var go = new GameObject("." + IdentifierManager.SharedInstance.Retrieve(name)).transform;
go.SetParent(gogroup, false);
Anchors.Add(name, new Anchor() { Transform = go });
return go;
}
/// <summary> /// <summary>
/// Called upon StartUpdate of ps 17. /// Called upon StartUpdate of ps 17.
/// </summary> /// </summary>
@@ -108,10 +117,10 @@ namespace Cryville.Crtr.Event {
protected virtual void PreAwake(ContainerState s) { protected virtual void PreAwake(ContainerState s) {
if (gogroup) gogroup.gameObject.SetActive(true); if (gogroup) gogroup.gameObject.SetActive(true);
Awoken = true; Alive = true; Awoken = true; Alive = true;
OpenAnchor("head"); OpenAnchor(_a_head);
} }
protected virtual void Awake(ContainerState s) { protected virtual void Awake(ContainerState s) {
CloseAnchor("head"); CloseAnchor(_a_head);
} }
protected virtual void GetPosition(ContainerState s) { } protected virtual void GetPosition(ContainerState s) { }
public virtual void StartUpdate(ContainerState s) { public virtual void StartUpdate(ContainerState s) {
@@ -138,10 +147,10 @@ namespace Cryville.Crtr.Event {
} }
} }
public virtual void Anchor() { } public virtual void Anchor() { }
protected void OpenAnchor(string name) { protected void OpenAnchor(int name) {
if (Anchors.ContainsKey(name)) Anchors[name].Open(); if (Anchors.ContainsKey(name)) Anchors[name].Open();
} }
protected void CloseAnchor(string name) { protected void CloseAnchor(int name) {
if (Anchors.ContainsKey(name)) Anchors[name].Close(); if (Anchors.ContainsKey(name)) Anchors[name].Close();
} }
} }

View File

@@ -56,7 +56,7 @@ namespace Cryville.Crtr.Event {
private set; private set;
} }
public float Time { public double Time {
get { get {
return Bus.Time; return Bus.Time;
} }
@@ -225,7 +225,7 @@ namespace Cryville.Crtr.Event {
if (tr.Valid) return r; if (tr.Valid) return r;
#endif #endif
float reltime = 0; float reltime = 0;
if (rootPrototype != null) reltime = Time - rootPrototype.Time; if (rootPrototype != null) reltime = (float)(Time - rootPrototype.Time);
GetMotionValue(key).GetValue(reltime, ref r); GetMotionValue(key).GetValue(reltime, ref r);
if (Parent != null) r.ApplyFrom(Parent.GetRawValue(key)); if (Parent != null) r.ApplyFrom(Parent.GetRawValue(key));
#if !DISABLE_CACHE #if !DISABLE_CACHE
@@ -394,7 +394,7 @@ namespace Cryville.Crtr.Event {
} }
} }
else { else {
var scaledTime = (Time - m.Key.Time - ChartPlayer.actualRenderStep * tev.sumfix) / m.Key.Duration; var scaledTime = (float)((Time - m.Key.Time - ChartPlayer.actualRenderStep * tev.sumfix) / m.Key.Duration);
var lerpedTime = MotionLerper.GetEaseTime(scaledTime, tev.transition, tev.rate); var lerpedTime = MotionLerper.GetEaseTime(scaledTime, tev.transition, tev.rate);
if (tev.RelativeNode != null) { if (tev.RelativeNode != null) {
var target = value.QueryRelativeNode(tev.RelativeNode.Id); var target = value.QueryRelativeNode(tev.RelativeNode.Id);

View File

@@ -4,7 +4,7 @@ using System.Collections.Generic;
namespace Cryville.Crtr.Event { namespace Cryville.Crtr.Event {
public class EventBatch : IComparable<EventBatch>, IEnumerable<StampedEvent> { public class EventBatch : IComparable<EventBatch>, IEnumerable<StampedEvent> {
public float Time { public double Time {
get; get;
private set; private set;
} }
@@ -14,7 +14,7 @@ namespace Cryville.Crtr.Event {
get { return queue.Count; } get { return queue.Count; }
} }
public EventBatch(float time) { public EventBatch(double time) {
Time = time; Time = time;
} }
@@ -32,7 +32,7 @@ namespace Cryville.Crtr.Event {
} }
public int CompareTo(EventBatch other) { public int CompareTo(EventBatch other) {
return this.Time.CompareTo(other.Time); return Time.CompareTo(other.Time);
} }
public IEnumerator<StampedEvent> GetEnumerator() { public IEnumerator<StampedEvent> GetEnumerator() {

View File

@@ -17,8 +17,8 @@ namespace Cryville.Crtr.Event {
= new Dictionary<ChartEvent, ContainerState>(); = new Dictionary<ChartEvent, ContainerState>();
public List<StampedEvent> stampedEvents = new List<StampedEvent>(); public List<StampedEvent> stampedEvents = new List<StampedEvent>();
readonly List<EventBatch> batches = new List<EventBatch>(); readonly List<EventBatch> batches = new List<EventBatch>();
float beat; double beat;
float tempo; float tempo;
public EventBatcher(Chart c) : base(c, new List<ChartEvent>()) { public EventBatcher(Chart c) : base(c, new List<ChartEvent>()) {
@@ -56,12 +56,12 @@ namespace Cryville.Crtr.Event {
} }
} }
public override void ForwardOnceToTime(float toTime, Action<ChartEvent> callback) { public override void ForwardOnceToTime(double toTime, Action<ChartEvent> callback) {
float toBeat = (float)Math.Round(beat + (toTime - Time) * tempo / 60f, 6); double toBeat = Math.Round(beat + (toTime - Time) * tempo / 60f, 6);
if (EventId >= events.Count) if (EventId >= events.Count)
goto return_ahead; goto return_ahead;
float ebeat = events[EventId].BeatPosition; double ebeat = events[EventId].BeatPosition;
float etime = (float)Math.Round((ebeat - beat) / tempo * 60f + Time, 6); double etime = Math.Round((ebeat - beat) / tempo * 60f + Time, 6);
if (etime > toTime) if (etime > toTime)
goto return_ahead; goto return_ahead;
var batch = GetEventBatch(); var batch = GetEventBatch();

View File

@@ -114,7 +114,7 @@ namespace Cryville.Crtr.Event {
patch.Clear(); patch.Clear();
} }
public override void ForwardOnceToTime(float toTime, Action<EventBatch> callback = null) { public override void ForwardOnceToTime(double toTime, Action<EventBatch> callback = null) {
if (EventId < events.Count && events[EventId].Time <= toTime) { if (EventId < events.Count && events[EventId].Time <= toTime) {
Time = events[EventId].Time; Time = events[EventId].Time;
var batch = events[EventId]; var batch = events[EventId];

View File

@@ -11,7 +11,7 @@ using System.IO;
namespace Cryville.Crtr.Extensions.Bestdori { namespace Cryville.Crtr.Extensions.Bestdori {
public class BestdoriChartConverter : ResourceConverter { public class BestdoriChartConverter : ResourceConverter {
static readonly string[] SUPPORTED_FORMATS = { ".json" }; static readonly string[] SUPPORTED_FORMATS = { ".bestdori" };
public override string[] GetSupportedFormats() { public override string[] GetSupportedFormats() {
return SUPPORTED_FORMATS; return SUPPORTED_FORMATS;
} }
@@ -36,15 +36,12 @@ namespace Cryville.Crtr.Extensions.Bestdori {
motions = new List<Chart.Motion>(), motions = new List<Chart.Motion>(),
groups = new List<Chart.Group> { group }, groups = new List<Chart.Group> { group },
}; };
var tm = new BeatTimeTimingModel();
string bgm = null; string bgm = null;
double? cbpm = null;
double pbeat = 0, ctime = 0;
double endbeat = 0; double endbeat = 0;
foreach (var ev in src) { foreach (var ev in src) {
double cbeat = ev.StartBeat; tm.ForwardTo(ev.StartBeat);
ctime += cbpm == null ? 0 : (cbeat - pbeat) / cbpm.Value * 60; if (ev.StartBeat > endbeat) endbeat = ev.StartBeat;
pbeat = cbeat;
if (cbeat > endbeat) endbeat = cbeat;
if (ev is BestdoriChartEvent.System) { if (ev is BestdoriChartEvent.System) {
if (bgm != null) continue; if (bgm != null) continue;
var tev = (BestdoriChartEvent.System)ev; var tev = (BestdoriChartEvent.System)ev;
@@ -55,7 +52,7 @@ namespace Cryville.Crtr.Extensions.Bestdori {
} }
else if (ev is BestdoriChartEvent.BPM) { else if (ev is BestdoriChartEvent.BPM) {
var tev = (BestdoriChartEvent.BPM)ev; var tev = (BestdoriChartEvent.BPM)ev;
cbpm = tev.bpm; tm.BPM = tev.bpm;
chart.sigs.Add(new Chart.Signature { time = ToBeatTime(tev.beat), tempo = (float)tev.bpm }); chart.sigs.Add(new Chart.Signature { time = ToBeatTime(tev.beat), tempo = (float)tev.bpm });
} }
else if (ev is BestdoriChartEvent.Single) { else if (ev is BestdoriChartEvent.Single) {
@@ -95,12 +92,13 @@ namespace Cryville.Crtr.Extensions.Bestdori {
} }
if (bgm == null) throw new FormatException("Chart contains no song"); if (bgm == null) throw new FormatException("Chart contains no song");
chart.endtime = ToBeatTime(endbeat + 4); chart.endtime = ToBeatTime(endbeat + 4);
if (endbeat > tm.BeatTime) tm.ForwardTo(endbeat);
result.Add(new RawChartResource(string.Format("bang_dream_girls_band_party__{0}__{1}", bgm, StringUtils.TrimExt(file.Name)), chart, new ChartMeta { result.Add(new RawChartResource(string.Format("bang_dream_girls_band_party__{0}__{1}", bgm, StringUtils.TrimExt(file.Name)), chart, new ChartMeta {
name = string.Format("Bandori {0} {1}", bgm, StringUtils.TrimExt(file.Name)), name = string.Format("Bandori {0} {1}", bgm, StringUtils.TrimExt(file.Name)),
author = "©BanG Dream! Project ©Craft Egg Inc. ©bushiroad", author = "©BanG Dream! Project ©Craft Egg Inc. ©bushiroad",
ruleset = "bang_dream_girls_band_party", ruleset = "bang_dream_girls_band_party",
note_count = group.notes.Count, note_count = group.notes.Count,
length = (float)ctime, length = (float)tm.Time,
song = new SongMetaInfo { song = new SongMetaInfo {
name = bgm, name = bgm,
author = "©BanG Dream! Project ©Craft Egg Inc. ©bushiroad", author = "©BanG Dream! Project ©Craft Egg Inc. ©bushiroad",
@@ -115,73 +113,73 @@ namespace Cryville.Crtr.Extensions.Bestdori {
i = n / d; n %= d; i = n / d; n %= d;
return new BeatTime(i, n, d); return new BeatTime(i, n, d);
} }
}
#pragma warning disable IDE1006 #pragma warning disable IDE1006
[JsonConverter(typeof(BestdoriChartEventCreator))] [JsonConverter(typeof(BestdoriChartEventCreator))]
abstract class BestdoriChartEvent { abstract class BestdoriChartEvent {
public abstract string type { get; } public abstract string type { get; }
public abstract double StartBeat { get; } public abstract double StartBeat { get; }
public abstract class InstantEvent : BestdoriChartEvent { public abstract class InstantEvent : BestdoriChartEvent {
public double beat; public double beat;
public override double StartBeat { get { return beat; } } public override double StartBeat { get { return beat; } }
}
public class BPM : InstantEvent {
public override string type { get { return "BPM"; } }
public double bpm;
}
public class System : InstantEvent {
public override string type { get { return "System"; } }
public string data;
}
public abstract class SingleBase : InstantEvent {
public double lane;
public bool skill;
public bool flick;
}
public class Single : SingleBase {
public override string type { get { return "Single"; } }
}
public class Directional : SingleBase {
public override string type { get { return "Directional"; } }
public string direction;
public int width;
}
public class Connection : SingleBase {
public override string type { get { return null; } }
public bool hidden;
}
public class Long : BestdoriChartEvent {
public override string type { get { return "Long"; } }
public List<Connection> connections;
public override double StartBeat { get { return connections[0].beat; } }
}
public class Slide : Long {
public override string type { get { return "Slide"; } }
}
} }
public class BPM : InstantEvent {
public override string type { get { return "BPM"; } }
public double bpm;
}
public class System : InstantEvent {
public override string type { get { return "System"; } }
public string data;
}
public abstract class SingleBase : InstantEvent {
public double lane;
public bool skill;
public bool flick;
}
public class Single : SingleBase {
public override string type { get { return "Single"; } }
}
public class Directional : SingleBase {
public override string type { get { return "Directional"; } }
public string direction;
public int width;
}
public class Connection : SingleBase {
public override string type { get { return null; } }
public bool hidden;
}
public class Long : BestdoriChartEvent {
public override string type { get { return "Long"; } }
public List<Connection> connections;
public override double StartBeat { get { return connections[0].beat; } }
}
public class Slide : Long {
public override string type { get { return "Slide"; } }
}
}
#pragma warning restore IDE1006 #pragma warning restore IDE1006
class BestdoriChartEventCreator : CustomCreationConverter<BestdoriChartEvent> { class BestdoriChartEventCreator : CustomCreationConverter<BestdoriChartEvent> {
string _currentType; string _currentType;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var obj = JObject.ReadFrom(reader); var obj = JObject.ReadFrom(reader);
var type = obj["type"]; var type = obj["type"];
if (type == null) _currentType = null; if (type == null) _currentType = null;
else _currentType = obj["type"].ToObject<string>(); else _currentType = obj["type"].ToObject<string>();
return base.ReadJson(obj.CreateReader(), objectType, existingValue, serializer); return base.ReadJson(obj.CreateReader(), objectType, existingValue, serializer);
} }
public override BestdoriChartEvent Create(Type objectType) { public override BestdoriChartEvent Create(Type objectType) {
switch (_currentType) { switch (_currentType) {
case "BPM": return new BestdoriChartEvent.BPM(); case "BPM": return new BestdoriChartEvent.BPM();
case "System": return new BestdoriChartEvent.System(); case "System": return new BestdoriChartEvent.System();
case "Single": return new BestdoriChartEvent.Single(); case "Single": return new BestdoriChartEvent.Single();
case "Directional": return new BestdoriChartEvent.Directional(); case "Directional": return new BestdoriChartEvent.Directional();
case null: return new BestdoriChartEvent.Connection(); case null: return new BestdoriChartEvent.Connection();
case "Long": return new BestdoriChartEvent.Long(); case "Long": return new BestdoriChartEvent.Long();
case "Slide": return new BestdoriChartEvent.Slide(); case "Slide": return new BestdoriChartEvent.Slide();
default: throw new ArgumentException("Unknown event type: " + _currentType); default: throw new ArgumentException("Unknown event type: " + _currentType);
}
} }
} }
} }

View File

@@ -0,0 +1,27 @@
using Cryville.Crtr.Browsing;
using Cryville.Crtr.Extensions.Bestdori;
using Cryville.Crtr.Extensions.Malody;
using Cryville.Crtr.Extensions.osu;
using Cryville.Crtr.Extensions.Quaver;
using System.Collections.Generic;
namespace Cryville.Crtr.Extensions {
public class Extensions : ExtensionInterface {
public override IEnumerable<ResourceConverter> GetResourceConverters() {
return new ResourceConverter[] {
new BestdoriChartConverter(),
new MalodyChartConverter(),
new osuChartConverter(),
new QuaverChartConverter(),
};
}
public override IEnumerable<LocalResourceFinder> GetResourceFinders() {
return new LocalResourceFinder[] {
new MalodyChartFinder(),
new osuChartFinder(),
new QuaverChartFinder(),
};
}
}
}

View File

@@ -1,8 +1,7 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 62489f8e495a805478e5b45c0f53ca4e guid: 23377bf2926d93a4b8e3f3ab6040c7f2
timeCreated: 1623583546
licenseType: Pro
MonoImporter: MonoImporter:
externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0

View File

@@ -73,30 +73,28 @@ namespace Cryville.Crtr.Extensions.Malody {
Dictionary<MalodyChart.IEvent, StartEventState> longEvents Dictionary<MalodyChart.IEvent, StartEventState> longEvents
= new Dictionary<MalodyChart.IEvent, StartEventState>(); = new Dictionary<MalodyChart.IEvent, StartEventState>();
float? baseBpm = null, cbpm = null; float? baseBpm = null;
float pbeat = 0f, ctime = 0f; var tm = new FractionalBeatTimeTimingModel();
int[] endbeat = new int[] { 0, 0, 1 };
foreach (var ev in events) { foreach (var ev in events) {
float cbeat = ConvertBeat(ev.beat); var beat = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]);
ctime += cbpm == null ? 0 : (cbeat - pbeat) / cbpm.Value * 60f; tm.ForwardTo(beat);
pbeat = cbeat;
if (ev is MalodyChart.Time) { if (ev is MalodyChart.Time) {
var tev = (MalodyChart.Time)ev; var tev = (MalodyChart.Time)ev;
if (baseBpm == null) baseBpm = tev.bpm; if (baseBpm == null) baseBpm = tev.bpm;
cbpm = tev.bpm; tm.BPM = tev.bpm;
chart.sigs.Add(new Chart.Signature { chart.sigs.Add(new Chart.Signature {
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]), time = beat,
tempo = tev.bpm, tempo = tev.bpm,
}); });
chart.motions.Add(new Chart.Motion { chart.motions.Add(new Chart.Motion {
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]), time = beat,
motion = "svm:" + (tev.bpm / baseBpm.Value).ToString(CultureInfo.InvariantCulture) motion = "svm:" + (tev.bpm / baseBpm.Value).ToString(CultureInfo.InvariantCulture)
}); });
} }
else if (ev is MalodyChart.Effect) { else if (ev is MalodyChart.Effect) {
var tev = (MalodyChart.Effect)ev; var tev = (MalodyChart.Effect)ev;
if (tev.scroll != null) group.motions.Add(new Chart.Motion { if (tev.scroll != null) group.motions.Add(new Chart.Motion {
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]), time = beat,
motion = "svm:" + tev.scroll.Value.ToString(CultureInfo.InvariantCulture) motion = "svm:" + tev.scroll.Value.ToString(CultureInfo.InvariantCulture)
}); });
} }
@@ -115,19 +113,17 @@ namespace Cryville.Crtr.Extensions.Malody {
else throw new NotImplementedException(); else throw new NotImplementedException();
} }
else { else {
if (ConvertBeat(tev.beat) > ConvertBeat(endbeat)) endbeat = tev.beat;
var rn = new Chart.Note() { var rn = new Chart.Note() {
time = new BeatTime(tev.beat[0], tev.beat[1], tev.beat[2]), time = beat,
motions = new List<Chart.Motion> { motions = new List<Chart.Motion> {
new Chart.Motion() { motion = "track:" + tev.column.ToString(CultureInfo.InvariantCulture) } new Chart.Motion() { motion = "track:" + tev.column.ToString(CultureInfo.InvariantCulture) }
}, },
}; };
if (tev.endbeat != null) { if (tev.endbeat != null) {
if (ConvertBeat(tev.endbeat) > ConvertBeat(endbeat)) endbeat = tev.endbeat;
rn.endtime = new BeatTime(tev.endbeat[0], tev.endbeat[1], tev.endbeat[2]); rn.endtime = new BeatTime(tev.endbeat[0], tev.endbeat[1], tev.endbeat[2]);
longEvents.Add(ev, new StartEventState { longEvents.Add(ev, new StartEventState {
Destination = rn, Destination = rn,
Time = ctime, Time = tm.Time,
}); });
} }
group.notes.Add(rn); group.notes.Add(rn);
@@ -143,8 +139,10 @@ namespace Cryville.Crtr.Extensions.Malody {
} }
else throw new NotSupportedException(); else throw new NotSupportedException();
} }
chart.endtime = new BeatTime(endbeat[0] + 4, endbeat[1], endbeat[2]); var endbeat = tm.FractionalBeatTime;
meta.length = ctime; endbeat.b += 4;
chart.endtime = endbeat;
meta.length = (float)tm.Time;
meta.note_count = group.notes.Count; meta.note_count = group.notes.Count;
string chartName = string.Format("{0} - {1}", meta.song.name, meta.name); string chartName = string.Format("{0} - {1}", meta.song.name, meta.name);
if (src.meta.background != null) { if (src.meta.background != null) {
@@ -155,77 +153,73 @@ namespace Cryville.Crtr.Extensions.Malody {
} }
struct StartEventState { struct StartEventState {
public float Time { get; set; } public double Time { get; set; }
public ChartEvent Destination { get; set; } public ChartEvent Destination { get; set; }
} }
float ConvertBeat(int[] beat) {
return beat[0] + (float)beat[1] / beat[2];
}
}
#pragma warning disable IDE1006 #pragma warning disable IDE1006
struct MalodyChart { struct MalodyChart {
public interface IEvent { public interface IEvent {
int[] beat { get; set; } int[] beat { get; set; }
int[] endbeat { get; set; } int[] endbeat { get; set; }
int Priority { get; } int Priority { get; }
} }
public struct EndEvent : IEvent { public struct EndEvent : IEvent {
public int[] beat { get; set; } public int[] beat { get; set; }
public int[] endbeat { get; set; } public int[] endbeat { get; set; }
public IEvent StartEvent { get; set; } public IEvent StartEvent { get; set; }
public int Priority { get { return StartEvent.Priority - 1; } } public int Priority { get { return StartEvent.Priority - 1; } }
}
public Meta meta;
public struct Meta {
public SongInfo song;
public struct SongInfo {
public string title;
public string artist;
public string titleorg;
public string artistorg;
} }
public string background; public Meta meta;
public struct Meta {
public SongInfo song;
public struct SongInfo {
public string title;
public string artist;
public string titleorg;
public string artistorg;
}
public string creator; public string background;
public string version;
public int mode; public string creator;
public ModeExt mode_ext; public string version;
public struct ModeExt {
public int mode;
public ModeExt mode_ext;
public struct ModeExt {
public int column;
}
}
public List<Time> time;
public struct Time : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public float bpm;
public int Priority { get { return -2; } }
}
public List<Effect> effect;
public struct Effect : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public float? scroll;
public int Priority { get { return 0; } }
}
public List<Note> note;
public struct Note : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public int column; public int column;
public string sound;
public int offset;
public int type;
public int Priority { get { return 0; } }
} }
} }
public List<Time> time;
public struct Time : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public float bpm;
public int Priority { get { return -2; } }
}
public List<Effect> effect;
public struct Effect : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public float? scroll;
public int Priority { get { return 0; } }
}
public List<Note> note;
public struct Note : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public int column;
public string sound;
public int offset;
public int type;
public int Priority { get { return 0; } }
}
}
#pragma warning restore IDE1006 #pragma warning restore IDE1006
}
} }

View File

@@ -0,0 +1,26 @@
using Cryville.Common;
using Cryville.Crtr.Browsing;
using Microsoft.Win32;
using System;
using System.IO;
namespace Cryville.Crtr.Extensions.Malody {
public class MalodyChartFinder : LocalResourceFinder {
public override string Name { get { return "Malody beatmaps"; } }
public override string GetRootPath() {
switch (Environment.OSVersion.Platform) {
case PlatformID.Unix:
return "/storage/emulated/0/data/malody/beatmap";
case PlatformID.Win32NT:
var reg = Registry.ClassesRoot.OpenSubKey(@"malody\Shell\Open\Command");
if (reg == null) return null;
var pathObj = reg.GetValue(null);
if (pathObj == null) return null;
var path = (string)pathObj;
return Path.Combine(new FileInfo(StringUtils.GetProcessPathFromCommand(path)).Directory.FullName, "beatmap");
default: return null;
}
}
}
}

View File

@@ -1,8 +1,7 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 58e01e1e11af164408a19c1086709bd7 guid: 3c9beaff62143a2468e18ad4642232c0
timeCreated: 1638411495
licenseType: Free
MonoImporter: MonoImporter:
externalObjects: {}
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
executionOrder: 0 executionOrder: 0

View File

@@ -1,9 +1,8 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: ef3100799cf39eb4d8585dcfba2529a5 guid: 6823ead66b33bc048bbad48719feb25d
folderAsset: yes folderAsset: yes
timeCreated: 1623583530
licenseType: Pro
DefaultImporter: DefaultImporter:
externalObjects: {}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:

View File

@@ -0,0 +1,153 @@
using Cryville.Crtr.Browsing;
using Quaver.API.Maps;
using Quaver.API.Maps.Structures;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace Cryville.Crtr.Extensions.Quaver {
public class QuaverChartConverter : ResourceConverter {
static readonly string[] SUPPORTED_FORMATS = { ".qua" };
const double OFFSET = 0.05;
public override string[] GetSupportedFormats() {
return SUPPORTED_FORMATS;
}
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
List<Resource> result = new List<Resource>();
var src = Qua.Parse(file.FullName);
var ruleset = "quaver!" + src.Mode.ToString().ToLower();
var meta = new ChartMeta {
name = src.DifficultyName,
author = src.Creator,
song = new SongMetaInfo {
name = src.Title,
author = src.Artist,
},
ruleset = ruleset,
cover = src.BackgroundFile,
note_count = src.HitObjects.Count,
};
var chart = new Chart {
format = 2,
time = new BeatTime(-4, 0, 1),
ruleset = ruleset,
sigs = new List<Chart.Signature>(),
sounds = new List<Chart.Sound> {
new Chart.Sound { time = new BeatTime(0, 0, 1), id = src.Title, offset = (float)(src.TimingPoints[0].StartTime / 1e3 + OFFSET) }
},
motions = new List<Chart.Motion>(),
groups = new List<Chart.Group>(),
};
var group = new Chart.Group() {
tracks = new List<Chart.Track>(),
notes = new List<Chart.Note>(),
motions = new List<Chart.Motion>(),
};
chart.groups.Add(group);
result.Add(new RawChartResource(string.Format("{0} - {1}", meta.song.name, meta.name), chart, meta));
result.Add(new SongResource(meta.song.name, new FileInfo(Path.Combine(file.DirectoryName, src.AudioFile))));
var evs = new List<EventWrapper>();
foreach (var e in src.HitObjects) evs.Add(new EventWrapper.HitObject(e));
foreach (var e in src.SliderVelocities) evs.Add(new EventWrapper.SliderVelocity(e));
foreach (var e in src.SoundEffects) evs.Add(new EventWrapper.SoundEffect(e));
foreach (var e in src.TimingPoints) evs.Add(new EventWrapper.TimingPoint(e));
var evc = evs.Count;
for (int i = 0; i < evc; i++) if (evs[i].IsLong) evs.Add(new EventWrapper.EndEvent(evs[i]));
evs.Sort();
var longevs = new Dictionary<EventWrapper, ChartEvent>();
var tm = new TimeTimingModel(src.TimingPoints[0].StartTime / 1e3);
foreach (var ev in evs) {
tm.ForwardTo(ev.StartTime / 1e3);
if (ev is EventWrapper.HitObject) {
var tev = (EventWrapper.HitObject)ev;
var rn = new Chart.Note {
time = tm.FractionalBeatTime,
motions = new List<Chart.Motion> {
new Chart.Motion { motion = string.Format(CultureInfo.InvariantCulture, "track:{0}", tev.Event.Lane - 1) }
},
};
if (ev.IsLong) longevs.Add(ev, rn);
group.notes.Add(rn);
}
else if (ev is EventWrapper.SliderVelocity) {
var tev = (EventWrapper.SliderVelocity)ev;
group.motions.Add(new Chart.Motion {
time = tm.FractionalBeatTime,
motion = string.Format(CultureInfo.InvariantCulture, "svm:{0}", tev.Event.Multiplier),
});
}
else if (ev is EventWrapper.TimingPoint) {
var tev = (EventWrapper.TimingPoint)ev;
tm.BPM = tev.Event.Bpm;
chart.sigs.Add(new Chart.Signature {
time = tm.FractionalBeatTime,
tempo = tev.Event.Bpm,
});
}
else if (ev is EventWrapper.EndEvent) {
var tev = (EventWrapper.EndEvent)ev;
var oev = tev.Original;
longevs[oev].endtime = tm.FractionalBeatTime;
}
else throw new NotSupportedException("Sound effects are not supported yet");
}
var endbeat = tm.FractionalBeatTime;
endbeat.b += 4;
chart.endtime = endbeat;
meta.length = (float)tm.Time;
return result;
}
abstract class EventWrapper : IComparable<EventWrapper> {
public abstract int StartTime { get; }
public abstract int EndTime { get; }
public bool IsLong { get { return EndTime > 0; } }
public abstract int Priority { get; }
public int CompareTo(EventWrapper other) {
var c = StartTime.CompareTo(other.StartTime);
if (c != 0) return c;
return Priority.CompareTo(other.Priority);
}
public class HitObject : EventWrapper {
public HitObjectInfo Event;
public HitObject(HitObjectInfo ev) { Event = ev; }
public override int StartTime { get { return Event.StartTime; } }
public override int EndTime { get { return Event.EndTime; } }
public override int Priority { get { return 0; } }
}
public class SliderVelocity : EventWrapper {
public SliderVelocityInfo Event;
public SliderVelocity(SliderVelocityInfo ev) { Event = ev; }
public override int StartTime { get { return (int)Event.StartTime; } }
public override int EndTime { get { return 0; } }
public override int Priority { get { return 0; } }
}
public class SoundEffect : EventWrapper {
public SoundEffectInfo Event;
public SoundEffect(SoundEffectInfo ev) { Event = ev; }
public override int StartTime { get { return (int)Event.StartTime; } }
public override int EndTime { get { return 0; } }
public override int Priority { get { return 0; } }
}
public class TimingPoint : EventWrapper {
public TimingPointInfo Event;
public TimingPoint(TimingPointInfo ev) { Event = ev; }
public override int StartTime { get { return (int)Event.StartTime; } }
public override int EndTime { get { return 0; } }
public override int Priority { get { return -2; } }
}
public class EndEvent : EventWrapper {
public EventWrapper Original;
public EndEvent(EventWrapper ev) { if (!ev.IsLong) throw new ArgumentException("Event is not long"); Original = ev; }
public override int StartTime { get { return Original.EndTime; } }
public override int EndTime { get { return 0; } }
public override int Priority { get { return Original.Priority - 1; } }
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b073cac7ce0d41a4f8ca589845678aa2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
using Cryville.Common;
using Cryville.Crtr.Browsing;
using Microsoft.Win32;
using System;
using System.IO;
namespace Cryville.Crtr.Extensions.Quaver {
public class QuaverChartFinder : LocalResourceFinder {
public override string Name { get { return "Quaver beatmaps"; } }
public override string GetRootPath() {
switch (Environment.OSVersion.Platform) {
case PlatformID.Win32NT:
var reg = Registry.ClassesRoot.OpenSubKey(@"quaver\Shell\Open\Command");
if (reg == null) return null;
var pathObj = reg.GetValue(null);
if (pathObj == null) return null;
var path = (string)pathObj;
return Path.Combine(new FileInfo(StringUtils.GetProcessPathFromCommand(path)).Directory.FullName, "Songs");
default: return null;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 68bacf7746cbeea42a78a7d55cfdbea0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,56 @@
using Cryville.Common.Math;
using System;
namespace Cryville.Crtr.Extensions {
public abstract class TimingModel {
public double Time { get; protected set; }
public double BeatTime { get; protected set; }
public BeatTime FractionalBeatTime { get; protected set; }
double m_bpm;
public double BPM { get { return m_bpm; } set { m_bpm = value; } }
public double BeatLength { get { return 60 / m_bpm; } set { m_bpm = 60 / value; } }
public TimingModel(double offset) {
Time = offset;
FractionalBeatTime = new BeatTime(0, 0, 1);
}
}
public class FractionalBeatTimeTimingModel : TimingModel {
public FractionalBeatTimeTimingModel(double offset = 0) : base(offset) { }
public void ForwardTo(BeatTime t) {
if (t == FractionalBeatTime) return;
if (BPM == 0) throw new InvalidOperationException("BPM not determined");
FractionalBeatTime = t;
var nt = t.Decimal;
Time += (nt - BeatTime) / BPM * 60;
BeatTime = nt;
}
}
public class BeatTimeTimingModel : TimingModel {
public BeatTimeTimingModel(double offset = 0) : base(offset) { }
public void ForwardTo(double t) {
if (t == BeatTime) return;
if (BPM == 0) throw new InvalidOperationException("BPM not determined");
Time += (t - BeatTime) / BPM * 60;
BeatTime = t;
FractionalBeatTime = ToBeatTime(t);
}
static BeatTime ToBeatTime(double beat, double error = 1e-4) {
int i, n, d;
FractionUtils.ToFraction(beat, error, out n, out d);
i = n / d; n %= d;
return new BeatTime(i, n, d);
}
}
public class TimeTimingModel : TimingModel {
public TimeTimingModel(double offset = 0) : base(offset) { }
public void ForwardTo(double t) {
if (t == Time) return;
if (BPM == 0) throw new InvalidOperationException("BPM not determined");
BeatTime += (t - Time) * BPM / 60;
int n, d;
FractionUtils.ToFraction(BeatTime, 1f / 48 / BPM * 60, out n, out d);
FractionalBeatTime = new BeatTime(n, d);
Time = t;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5c4a1fab8f53dd742ba6501d682eb7f6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,9 +1,8 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: dc2947c139e087f43b375d2510a449df guid: dbc046e7cabacbb4fbf74520399a7340
folderAsset: yes folderAsset: yes
timeCreated: 1621384032
licenseType: Free
DefaultImporter: DefaultImporter:
externalObjects: {}
userData: userData:
assetBundleName: assetBundleName:
assetBundleVariant: assetBundleVariant:

View File

@@ -0,0 +1,373 @@
using Cryville.Crtr.Browsing;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace Cryville.Crtr.Extensions.osu {
#pragma warning disable IDE1006
public class osuChartConverter : ResourceConverter {
#pragma warning restore IDE1006
static readonly string[] SUPPORTED_FORMATS = { ".osu" };
const double OFFSET = 0.07;
public override string[] GetSupportedFormats() {
return SUPPORTED_FORMATS;
}
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
List<Resource> result = new List<Resource>();
var meta = new ChartMeta { song = new SongMetaInfo() };
var group = new Chart.Group() {
tracks = new List<Chart.Track>(),
notes = new List<Chart.Note>(),
motions = new List<Chart.Motion>(),
};
var chart = new Chart {
format = 2,
time = new BeatTime(-4, 0, 1),
sigs = new List<Chart.Signature>(),
sounds = new List<Chart.Sound>(),
motions = new List<Chart.Motion>(),
groups = new List<Chart.Group> { group },
};
var diff = new DifficultyInfo();
var evs = new List<osuEvent>();
using (var reader = new StreamReader(file.FullName, Encoding.UTF8)) {
Section section = Section.General;
int version;
bool flag = false;
string line;
while ((line = reader.ReadLine()) != null) {
if (!flag) {
if (line.StartsWith("osu file format v")) {
version = int.Parse(line.Substring(17), CultureInfo.InvariantCulture);
if (version > 14) throw new NotSupportedException("osu! chart format version too high");
else if (version < 5) throw new NotSupportedException("osu! chart format version too low"); // TODO apply offset
}
else throw new NotSupportedException("Unrecognized osu! chart format");
flag = true;
}
if (ShouldSkipLine(line)) continue;
if (section != Section.Metadata) line = StripComments(line);
line = line.TrimEnd();
if (line.StartsWith('[') && line.EndsWith(']')) {
Enum.TryParse(line.Substring(1, line.Length - 2), out section);
continue;
}
ParseLine(meta, chart, diff, evs, section, line);
}
}
result.Add(new RawChartResource(string.Format("{0} - {1}", meta.song.name, meta.name), chart, meta));
var evc = evs.Count;
for (int i = 0; i < evc; i++) if (evs[i].IsLong) evs.Add(new osuEvent.EndEvent(evs[i]));
evs.Sort();
var longevs = new Dictionary<osuEvent, ChartEvent>();
Chart.Sound bgmEv = null;
TimeTimingModel tm = null;
foreach (var ev in evs) {
if (tm != null) tm.ForwardTo(ev.StartTime / 1e3);
if (ev is osuEvent.Audio) {
var tev = (osuEvent.Audio)ev;
chart.sounds.Add(bgmEv = new Chart.Sound { time = new BeatTime(0, 0, 1), id = meta.song.name });
result.Add(new SongResource(meta.song.name, new FileInfo(Path.Combine(file.DirectoryName, tev.AudioFile))));
}
else if (ev is osuEvent.Background) {
meta.cover = ((osuEvent.Background)ev).FileName;
}
else if (ev is osuEvent.EffectPoint) {
var tev = (osuEvent.EffectPoint)ev;
group.motions.Add(new Chart.Motion { motion = string.Format(CultureInfo.InvariantCulture, "svm:{0}", tev.ScrollSpeed) });
}
else if (ev is osuEvent.EndEvent) {
if (tm == null) throw new InvalidOperationException("Unconvertible chart: timed event before first timing point");
var tev = (osuEvent.EndEvent)ev;
longevs[tev.Original].endtime = tm.FractionalBeatTime;
}
else if (ev is osuEvent.HOMania) {
if (tm == null) throw new InvalidOperationException("Unconvertible chart: timed event before first timing point");
var tev = (osuEvent.HOMania)ev;
var rn = new Chart.Note {
time = tm.FractionalBeatTime,
motions = new List<Chart.Motion> {
new Chart.Motion{ motion = string.Format(CultureInfo.InvariantCulture, "track:{0}", (int)(tev.X * diff.CircleSize / 512)) }
},
};
group.notes.Add(rn);
if (tev.IsLong) longevs.Add(tev, rn);
}
else if (ev is osuEvent.TimingChange) {
var tev = (osuEvent.TimingChange)ev;
if (tm == null) {
tm = new TimeTimingModel(tev.StartTime / 1e3);
bgmEv.offset = (float)(tev.StartTime / 1e3 + OFFSET);
}
tm.BeatLength = tev.BeatLength / 1e3;
chart.sigs.Add(new Chart.Signature {
time = tm.FractionalBeatTime,
tempo = (float)tm.BPM,
});
}
else throw new NotSupportedException("Unsupported event detected");
}
var endbeat = tm.FractionalBeatTime;
endbeat.b += 4;
chart.endtime = endbeat;
meta.length = (float)tm.Time;
meta.note_count = group.notes.Count;
return result;
}
void ParseLine(ChartMeta meta, Chart chart, DifficultyInfo diff, List<osuEvent> evs, Section section, string line) {
switch (section) {
case Section.General: HandleGeneral(meta, chart, evs, line); return;
case Section.Metadata: HandleMetadata(meta, line); return;
case Section.Difficulty: HandleDifficulty(diff, line); return;
case Section.Events: HandleEvent(evs, line); return;
case Section.TimingPoints: HandleTimingPoint(chart, evs, line); return;
case Section.HitObjects: HandleHitObject(evs, line); return;
}
}
void HandleGeneral(ChartMeta meta, Chart chart, List<osuEvent> evs, string line) {
var pair = SplitKeyVal(line);
switch (pair.Key) {
case @"AudioFilename":
evs.Add(new osuEvent.Audio { StartTime = double.NegativeInfinity, AudioFile = pair.Value });
break;
case @"Mode":
int rulesetID = int.Parse(pair.Value, CultureInfo.InvariantCulture);
var ruleset = "osu!";
switch (rulesetID) {
case 0: /*ruleset += "standard";*/ throw new NotSupportedException("osu!standard mode is not supported yet");
case 1: /*ruleset += "taiko";*/ throw new NotSupportedException("osu!taiko mode is not supported yet");
case 2: /*ruleset += "catch";*/ throw new NotSupportedException("osu!catch mode is not supported yet");
case 3: ruleset += "mania"; break;
}
meta.ruleset = chart.ruleset = ruleset;
break;
}
}
void HandleMetadata(ChartMeta meta, string line) {
var pair = SplitKeyVal(line);
switch (pair.Key) {
case @"Title": if (meta.song.name == null) meta.song.name = pair.Value; break;
case @"TitleUnicode": meta.song.name = pair.Value; break;
case @"Artist": if (meta.song.author == null) meta.song.author = pair.Value; break;
case @"ArtistUnicode": meta.song.author = pair.Value; break;
case @"Creator": meta.author = pair.Value; break;
case @"Version": meta.name = pair.Value; break;
}
}
void HandleDifficulty(DifficultyInfo diff, string line) {
var pair = SplitKeyVal(line);
switch (pair.Key) {
case @"CircleSize":
diff.CircleSize = float.Parse(pair.Value, CultureInfo.InvariantCulture);
break;
case @"SliderMultiplier":
diff.SliderMultiplier = double.Parse(pair.Value, CultureInfo.InvariantCulture);
break;
}
}
void HandleEvent(List<osuEvent> evs, string line) {
string[] split = line.Split(',');
if (!Enum.TryParse(split[0], out LegacyEventType type))
throw new InvalidDataException($@"Unknown event type: {split[0]}");
switch (type) {
case LegacyEventType.Sprite:
if (evs.Count == 0 || !(evs[evs.Count - 1] is osuEvent.Background))
evs.Add(new osuEvent.Background { StartTime = double.NegativeInfinity, FileName = CleanFilename(split[3]) });
break;
case LegacyEventType.Background:
evs.Add(new osuEvent.Background { StartTime = double.NegativeInfinity, FileName = CleanFilename(split[2]) });
break;
}
}
enum LegacyEventType {
Background = 0,
Video = 1,
Break = 2,
Colour = 3,
Sprite = 4,
Sample = 5,
Animation = 6
}
void HandleTimingPoint(Chart chart, List<osuEvent> evs, string line) {
string[] split = line.Split(',');
double time = double.Parse(split[0].Trim(), CultureInfo.InvariantCulture)/* + offset*/;
// beatLength is allowed to be NaN to handle an edge case in which some beatmaps use NaN slider velocity to disable slider tick generation (see LegacyDifficultyControlPoint).
double beatLength = double.Parse(split[1].Trim(), CultureInfo.InvariantCulture);
// If beatLength is NaN, speedMultiplier should still be 1 because all comparisons against NaN are false.
double speedMultiplier = beatLength < 0 ? 100.0 / -beatLength : 1;
int timeSignature = 4;
if (split.Length >= 3)
timeSignature = split[2][0] == '0' ? 4 : int.Parse(split[2], CultureInfo.InvariantCulture);
bool timingChange = true;
if (split.Length >= 7)
timingChange = split[6][0] == '1';
//bool omitFirstBarSignature = false;
//if (split.Length >= 8) {
// int effectFlags = int.Parse(split[7], CultureInfo.InvariantCulture);
// omitFirstBarSignature = (effectFlags & 0x8) != 0;
//}
if (timingChange) {
if (double.IsNaN(beatLength))
throw new InvalidDataException("Beat length cannot be NaN in a timing control point");
evs.Add(new osuEvent.TimingChange { StartTime = time, BeatLength = beatLength, TimeSignature = timeSignature });
}
// osu!taiko and osu!mania use effect points rather than difficulty points for scroll speed adjustments.
if (chart.ruleset == "osu!taiko" || chart.ruleset == "osu!mania")
evs.Add(new osuEvent.EffectPoint { StartTime = time, ScrollSpeed = speedMultiplier });
}
void HandleHitObject(List<osuEvent> evs, string line) {
string[] split = line.Split(',');
int posx = (int)float.Parse(split[0], CultureInfo.InvariantCulture);
// int posy = (int)float.Parse(split[1], CultureInfo.InvariantCulture);
double startTime = double.Parse(split[2], CultureInfo.InvariantCulture)/* + Offset*/;
LegacyHitObjectType type = (LegacyHitObjectType)int.Parse(split[3], CultureInfo.InvariantCulture);
// int comboOffset = (int)(type & LegacyHitObjectType.ComboOffset) >> 4;
type &= ~LegacyHitObjectType.ComboOffset;
// bool combo = type.HasFlag(LegacyHitObjectType.NewCombo);
type &= ~LegacyHitObjectType.NewCombo;
osuEvent.HitObject result;
if (type.HasFlag(LegacyHitObjectType.Circle)) {
result = new osuEvent.HOManiaHit { X = posx };
}
else if (type.HasFlag(LegacyHitObjectType.Hold)) {
double endTime = Math.Max(startTime, double.Parse(split[2], CultureInfo.InvariantCulture));
if (split.Length > 5 && !string.IsNullOrEmpty(split[5])) {
string[] ss = split[5].Split(':');
endTime = Math.Max(startTime, double.Parse(ss[0], CultureInfo.InvariantCulture));
}
result = new osuEvent.HOManiaHold { X = posx, EndTime = endTime };
}
else throw new NotSupportedException(string.Format("Hit objects of type {0} is not supported yet", type));
if (result == null) throw new InvalidDataException($"Unknown hit object type: {split[3]}");
result.StartTime = startTime;
if (result != null) evs.Add(result);
}
[Flags]
enum LegacyHitObjectType {
Circle = 1,
Slider = 1 << 1,
NewCombo = 1 << 2,
Spinner = 1 << 3,
ComboOffset = (1 << 4) | (1 << 5) | (1 << 6),
Hold = 1 << 7
}
static bool ShouldSkipLine(string line) => string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith("//", StringComparison.Ordinal)
|| line.StartsWith(' ') || line.StartsWith('_');
protected string StripComments(string line) {
int index = line.IndexOf("//");
if (index > 0) return line.Substring(0, index);
return line;
}
KeyValuePair<string, string> SplitKeyVal(string line, char separator = ':', bool shouldTrim = true) {
string[] split = line.Split(separator, 2);
if (shouldTrim) {
for (int i = 0; i < split.Length; i++)
split[i] = split[i].Trim();
}
return new KeyValuePair<string, string> (
split[0],
split.Length > 1 ? split[1] : string.Empty
);
}
static string CleanFilename(string path) => path.Replace(@"\\", @"\").Trim('"');
enum Section {
General,
Editor,
Metadata,
Difficulty,
Events,
TimingPoints,
Colours,
HitObjects,
Variables,
Fonts,
CatchTheBeat,
Mania,
}
class DifficultyInfo {
public float CircleSize { get; internal set; }
public double SliderMultiplier { get; set; }
}
#pragma warning disable IDE1006 // Naming Styles
abstract class osuEvent : IComparable<osuEvent> {
public virtual double StartTime { get; set; }
public virtual double EndTime { get; set; }
public bool IsLong { get { return EndTime - StartTime > 0 && EndTime > 0; } }
public abstract int Priority { get; }
public int CompareTo(osuEvent other) {
var c = StartTime.CompareTo(other.StartTime);
if (c != 0) return c;
return Priority.CompareTo(other.Priority);
}
public class EndEvent : osuEvent {
public osuEvent Original;
public EndEvent(osuEvent ev) { if (!ev.IsLong) throw new ArgumentException("Event is not long"); Original = ev; }
public override double StartTime { get { return Original.EndTime; } }
public override double EndTime { get { return 0; } }
public override int Priority { get { return Original.Priority - 1; } }
}
public class Audio : osuEvent {
public string AudioFile { get; set; }
public override int Priority { get { return 0; } }
}
public class TimingChange : osuEvent {
public double BeatLength { get; set; }
public int TimeSignature { get; set; }
public override int Priority { get { return -4; } }
}
public class EffectPoint : osuEvent {
public double ScrollSpeed { get; set; }
public override int Priority { get { return -2; } }
}
public class Background : osuEvent {
public string FileName { get; set; }
public override int Priority { get { return 0; } }
}
public class HitObject : osuEvent {
public sealed override int Priority { get { return 0; } }
}
public class HOMania : HitObject {
public float X { get; set; }
}
public class HOManiaHit : HOMania { }
public class HOManiaHold : HOMania { }
}
#pragma warning restore IDE1006 // Naming Styles
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 82838dd8639c2244caf3c830edfbc59c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
using Cryville.Common;
using Cryville.Crtr.Browsing;
using Microsoft.Win32;
using System;
using System.IO;
namespace Cryville.Crtr.Extensions.osu {
public class osuChartFinder : LocalResourceFinder {
public override string Name { get { return "osu! beatmaps"; } }
public override string GetRootPath() {
switch (Environment.OSVersion.Platform) {
case PlatformID.Win32NT:
var reg = Registry.ClassesRoot.OpenSubKey(@"osu!\Shell\Open\Command");
if (reg == null) return null;
var pathObj = reg.GetValue(null);
if (pathObj == null) return null;
var path = (string)pathObj;
return Path.Combine(new FileInfo(StringUtils.GetProcessPathFromCommand(path)).Directory.FullName, "Songs");
default: return null;
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 365d879536c05284fa2335a7676c6cf4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,7 +1,6 @@
using Cryville.Common.Math; using Cryville.Common.Math;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using UnityEngine; using UnityEngine;
@@ -10,7 +9,7 @@ namespace Cryville.Crtr {
public ChartHandler ch; public ChartHandler ch;
SquareMatrix matFrame; SquareMatrix matFrame;
List<ContainerState> tracks; ContainerState[] tracks;
public GroupHandler(Chart.Group tg, ChartHandler ch) : base() { public GroupHandler(Chart.Group tg, ChartHandler ch) : base() {
this.ch = ch; this.ch = ch;
@@ -28,20 +27,22 @@ namespace Cryville.Crtr {
from c in cs.Children from c in cs.Children
where c.Value.Container is Chart.Track where c.Value.Container is Chart.Track
select c.Value select c.Value
).ToList(); ).ToArray();
matFrame = SquareMatrix.WithPolynomialCoefficients(tracks.Count); matFrame = SquareMatrix.WithPolynomialCoefficients(tracks.Length);
frame = new ColumnVector<Vector3>(tracks.Length);
} }
ColumnVector<Vector3> frame;
public ColumnVector<Vector3> GetCurrentFrame(Func<ContainerState, Vector3> func) { public ColumnVector<Vector3> GetCurrentFrame(Func<ContainerState, Vector3> func) {
var vl = from t in tracks select func(t); for (int i = 0; i < tracks.Length; i++)
return matFrame.Eliminate( frame[i] = func(tracks[i]);
new ColumnVector<Vector3>(vl.ToArray()), return matFrame.Eliminate(frame, Vector3Operator.Instance);
new Vector3Operator()
);
} }
} }
class Vector3Operator : IVectorOperator<Vector3> { class Vector3Operator : IVectorOperator<Vector3> {
public static Vector3Operator Instance = new Vector3Operator();
public Vector3 Add(Vector3 lhs, Vector3 rhs) { public Vector3 Add(Vector3 lhs, Vector3 rhs) {
return lhs + rhs; return lhs + rhs;
} }

View File

@@ -17,10 +17,10 @@ namespace Cryville.Crtr {
readonly Dictionary<Identifier, List<JudgeEvent>> activeEvs readonly Dictionary<Identifier, List<JudgeEvent>> activeEvs
= new Dictionary<Identifier, List<JudgeEvent>>(); = new Dictionary<Identifier, List<JudgeEvent>>();
struct JudgeEvent { struct JudgeEvent {
public float StartTime { get; set; } public double StartTime { get; set; }
public float EndTime { get; set; } public double EndTime { get; set; }
public float StartClip { get; set; } public double StartClip { get; set; }
public float EndClip { get; set; } public double EndClip { get; set; }
public JudgeDefinition Definition { get; set; } public JudgeDefinition Definition { get; set; }
public ContainerState State { get; set; } public ContainerState State { get; set; }
} }
@@ -35,7 +35,7 @@ namespace Cryville.Crtr {
_rs = rs; _rs = rs;
InitScores(); InitScores();
} }
public void Prepare(float st, float et, Identifier input, JudgeDefinition def, ContainerState container) { public void Prepare(double st, double et, Identifier input, JudgeDefinition def, ContainerState container) {
List<JudgeEvent> list; List<JudgeEvent> list;
if (!evs.TryGetValue(input, out list)) { if (!evs.TryGetValue(input, out list)) {
ct.Add(input, 0); ct.Add(input, 0);
@@ -105,8 +105,8 @@ namespace Cryville.Crtr {
var index = 0; var index = 0;
while (index >= 0 && index < actlist.Count) { while (index >= 0 && index < actlist.Count) {
var ev = actlist[index]; var ev = actlist[index];
LoadNum(_numbuf1, ev.StartTime); _etor.ContextCascadeUpdate(_var_fn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf1)); LoadNum(_numbuf1, (float)ev.StartTime); _etor.ContextCascadeUpdate(_var_fn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf1));
LoadNum(_numbuf2, ev.EndTime); _etor.ContextCascadeUpdate(_var_tn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf2)); LoadNum(_numbuf2, (float)ev.EndTime); _etor.ContextCascadeUpdate(_var_tn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf2));
var def = ev.Definition; var def = ev.Definition;
if (def.hit != null) _etor.Evaluate(_flagop, def.hit); if (def.hit != null) _etor.Evaluate(_flagop, def.hit);
else _flag = true; else _flag = true;
@@ -115,7 +115,7 @@ namespace Cryville.Crtr {
if (def.pass != null) Pass(def.pass); if (def.pass != null) Pass(def.pass);
actlist.RemoveAt(index); actlist.RemoveAt(index);
if (def.prop != 0 && actlist.Count > 0) { if (def.prop != 0 && actlist.Count > 0) {
index = BinarySearchFirst(actlist, ev.StartClip, def.stack - def.prop); index = BinarySearchFirst(actlist, (float)ev.StartClip, def.stack - def.prop);
if (index < 0) index = ~index; if (index < 0) index = ~index;
} }
else index++; else index++;
@@ -154,7 +154,7 @@ namespace Cryville.Crtr {
JudgeEvent ev; JudgeEvent ev;
while (list.Count > 0 && (ev = list[0]).StartClip <= tt) { while (list.Count > 0 && (ev = list[0]).StartClip <= tt) {
list.RemoveAt(0); list.RemoveAt(0);
var index = BinarySearch(actlist, ev.StartClip, ev.Definition.stack); var index = BinarySearch(actlist, (float)ev.StartClip, ev.Definition.stack);
if (index < 0) index = ~index; if (index < 0) index = ~index;
actlist.Insert(index, ev); actlist.Insert(index, ev);
} }

View File

@@ -41,7 +41,7 @@ namespace Cryville.Crtr {
MeshObject.AddComponent<MeshRenderer>(); MeshObject.AddComponent<MeshRenderer>();
MeshFilter = MeshObject.GetComponent<MeshFilter>(); MeshFilter = MeshObject.GetComponent<MeshFilter>();
Renderer = MeshObject.GetComponent<Renderer>(); Renderer = MeshObject.GetComponent<Renderer>();
Renderer.material = GenericResources.Materials["-SpriteMat"]; Renderer.material = NewMaterial;
Initialized = true; Initialized = true;
} }
public void Destroy() { public void Destroy() {

View File

@@ -23,9 +23,9 @@ namespace Cryville.Crtr {
} }
public static class MotionLerper { public static class MotionLerper {
public static void Lerp<T>(float time, float tt, T tv, float ft, T fv, TransitionType type, float rate, ref T result) where T : Vector { public static void Lerp<T>(double time, double tt, T tv, double ft, T fv, TransitionType type, float rate, ref T result) where T : Vector {
if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType()); if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType());
Lerp((time - ft) / (tt - ft), fv, tv, type, rate, ref result); Lerp((float)((time - ft) / (tt - ft)), fv, tv, type, rate, ref result);
} }
public static void Lerp<T>(float scaledTime, T from, T to, TransitionType type, float rate, ref T result) where T : Vector { public static void Lerp<T>(float scaledTime, T from, T to, TransitionType type, float rate, ref T result) where T : Vector {
@@ -35,7 +35,7 @@ namespace Cryville.Crtr {
to.LerpWith(from, GetEaseTime(scaledTime, type, rate), ref r); to.LerpWith(from, GetEaseTime(scaledTime, type, rate), ref r);
} }
public static float Delerp<T>(T value, float tt, T tv, float ft, T fv, TransitionType type, float rate) where T : Vector { public static double Delerp<T>(T value, double tt, T tv, double ft, T fv, TransitionType type, float rate) where T : Vector {
if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType()); if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType());
var t = Delerp(value, fv, tv, type, rate); var t = Delerp(value, fv, tv, type, rate);
return ft * (1 - t) + tt * t; return ft * (1 - t) + tt * t;

View File

@@ -11,11 +11,10 @@ namespace Cryville.Crtr {
readonly GroupHandler gh; readonly GroupHandler gh;
public readonly Chart.Note Event; public readonly Chart.Note Event;
readonly PdtRuleset ruleset; readonly PdtRuleset ruleset;
public NoteHandler(GroupHandler gh, Chart.Note ev, PdtRuleset rs, Judge j) : base() { public NoteHandler(GroupHandler gh, Chart.Note ev, PdtRuleset rs) : base() {
this.gh = gh; this.gh = gh;
Event = ev; Event = ev;
ruleset = rs; ruleset = rs;
judge = j;
} }
public override string TypeName { public override string TypeName {
@@ -43,8 +42,7 @@ namespace Cryville.Crtr {
base.Awake(s); base.Awake(s);
if (s.CloneType == 2) { if (s.CloneType == 2) {
if (!gogroup) return; if (!gogroup) return;
Chart.Note tev = Event; if (Event.IsLong) {
if (tev.IsLong) {
foreach (var i in sgos) { foreach (var i in sgos) {
i.Reset(); i.Reset();
i.AppendPoint(Position, Rotation); i.AppendPoint(Position, Rotation);
@@ -54,8 +52,8 @@ namespace Cryville.Crtr {
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
gogroup.SetPositionAndRotation(Position, Rotation); gogroup.SetPositionAndRotation(Position, Rotation);
#else #else
gogroup.position = Position; gogroup.position = Position;
gogroup.rotation = Rotation; gogroup.rotation = Rotation;
#endif #endif
} }
} }
@@ -63,13 +61,19 @@ namespace Cryville.Crtr {
public override void Update(ContainerState s, StampedEvent ev) { public override void Update(ContainerState s, StampedEvent ev) {
base.Update(s, ev); base.Update(s, ev);
if (s.CloneType == 1) { if (s.CloneType <= 2) {
Position = GetFramePoint(bs.Parent, bs.Track); Position = GetFramePoint(s.Parent, s.Track);
Rotation = GetFrameRotation(bs.Parent, bs.Track); Rotation = GetFrameRotation(s.Parent, s.Track);
}
if (s.CloneType == 0) {
#if UNITY_5_6_OR_NEWER
a_cur.SetPositionAndRotation(Position, Rotation);
#else
a_cur.position = Position;
a_cur.rotation = Rotation;
#endif
} }
else if (s.CloneType == 2) { else if (s.CloneType == 2) {
Position = GetFramePoint(ts.Parent, ts.Track);
Rotation = GetFrameRotation(ts.Parent, ts.Track);
if (!gogroup) return; if (!gogroup) return;
Chart.Note tev = Event; Chart.Note tev = Event;
if (tev.IsLong) { if (tev.IsLong) {
@@ -103,9 +107,9 @@ namespace Cryville.Crtr {
a_tail.rotation = Quaternion.Euler(ts.Direction); a_tail.rotation = Quaternion.Euler(ts.Direction);
#endif #endif
} }
OpenAnchor("tail"); OpenAnchor(_a_tail);
base.EndUpdate(s); base.EndUpdate(s);
CloseAnchor("tail"); CloseAnchor(_a_tail);
} }
Vector3 GetFramePoint(ContainerState state, float track) { Vector3 GetFramePoint(ContainerState state, float track) {
@@ -117,6 +121,7 @@ namespace Cryville.Crtr {
return Quaternion.LookRotation(r, state.Normal); return Quaternion.LookRotation(r, state.Normal);
} }
readonly List<Vector3> ctrl = new List<Vector3>(2);
Vector3 GetFrame(ContainerState state, float track, Func<ContainerState, Vector3> func) { Vector3 GetFrame(ContainerState state, float track, Func<ContainerState, Vector3> func) {
// TODO // TODO
int id = Mathf.FloorToInt(track); int id = Mathf.FloorToInt(track);
@@ -134,7 +139,7 @@ namespace Cryville.Crtr {
if (c0 && c1) if (c0 && c1)
return (1 - t) * p1 + t * p2; return (1 - t) * p1 + t * p2;
else { else {
var ctrl = new List<Vector3>(2); ctrl.Clear();
if (!c0) { if (!c0) {
var tp = ts0.GetControlPoint(true, deltaz); var tp = ts0.GetControlPoint(true, deltaz);
if (tp != Vector3.zero) ctrl.Add(tp); if (tp != Vector3.zero) ctrl.Add(tp);
@@ -149,7 +154,7 @@ namespace Cryville.Crtr {
ColumnVector<float>.WithPolynomialCoefficients( ColumnVector<float>.WithPolynomialCoefficients(
frame.Size, track frame.Size, track
), ),
new Vector3Operator() Vector3Operator.Instance
); );
} }
else if (ctrl.Count == 1) { else if (ctrl.Count == 1) {

View File

@@ -46,13 +46,13 @@ namespace Cryville.Crtr {
} }
else { else {
type = PdtInternalType.Undefined; type = PdtInternalType.Undefined;
LoadNum(name); LoadIdent(name);
value = _numbuf; value = _numbuf;
} }
} }
} }
} }
unsafe void LoadNum(int value) { unsafe void LoadIdent(int value) {
fixed (byte* ptr = _numbuf) *(int*)ptr = value; fixed (byte* ptr = _numbuf) *(int*)ptr = value;
} }
unsafe void LoadNum(float value) { unsafe void LoadNum(float value) {
@@ -251,7 +251,7 @@ namespace Cryville.Crtr {
if (blit) GetReturnFrame(PdtInternalType.Array, len + 2 * sizeof(int)).SetArraySuffix(type, LoadedOperandCount); if (blit) GetReturnFrame(PdtInternalType.Array, len + 2 * sizeof(int)).SetArraySuffix(type, LoadedOperandCount);
else GetReturnFrame(PdtInternalType.Vector, len + sizeof(int)).SetArraySuffix(type); else GetReturnFrame(PdtInternalType.Vector, len + sizeof(int)).SetArraySuffix(type);
} }
bool IsBlittable(int type) { static bool IsBlittable(int type) {
return type == PdtInternalType.Number; return type == PdtInternalType.Number;
} }
} }

View File

@@ -69,7 +69,7 @@ namespace Cryville.Crtr {
} }
public struct SkinPropertyKey { public struct SkinPropertyKey {
public Type Component; public Type Component;
public string Name; public int Name;
} }
public class SkinElementBinder : EmptyBinder { public class SkinElementBinder : EmptyBinder {
public override object ChangeType(object value, Type type, CultureInfo culture) { public override object ChangeType(object value, Type type, CultureInfo culture) {
@@ -81,9 +81,9 @@ namespace Cryville.Crtr {
if (key[0] == '*') if (key[0] == '*')
return new SkinPropertyKey { Component = GetComponentByName(key.Substring(1)) }; return new SkinPropertyKey { Component = GetComponentByName(key.Substring(1)) };
else else
return new SkinPropertyKey { Component = typeof(TransformInterface), Name = key }; return new SkinPropertyKey { Component = typeof(TransformInterface), Name = IdentifierManager.SharedInstance.Request(key) };
case 2: case 2:
return new SkinPropertyKey { Component = GetComponentByName(cp[0]), Name = cp[1] }; return new SkinPropertyKey { Component = GetComponentByName(cp[0]), Name = IdentifierManager.SharedInstance.Request(cp[1]) };
} }
} }
return base.ChangeType(value, type, culture); return base.ChangeType(value, type, culture);

View File

@@ -1,4 +1,4 @@
using Cryville.Common.Pdt; using Cryville.Common.Pdt;
using Cryville.Crtr.Components; using Cryville.Crtr.Components;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using System; using System;
@@ -35,7 +35,7 @@ namespace Cryville.Crtr {
void MatchStatic(SkinElement rel, ContainerState context, Transform anchor = null) { void MatchStatic(SkinElement rel, ContainerState context, Transform anchor = null) {
ChartPlayer.etor.ContextTransform = anchor; ChartPlayer.etor.ContextTransform = anchor;
foreach (var p in rel.properties) { foreach (var p in rel.properties) {
if (p.Key.Name == null) if (p.Key.Name == 0)
anchor.gameObject.AddComponent(p.Key.Component); anchor.gameObject.AddComponent(p.Key.Component);
else { else {
ChartPlayer.etor.Evaluate(GetPropOp(anchor, p.Key).Operator, p.Value); ChartPlayer.etor.Evaluate(GetPropOp(anchor, p.Key).Operator, p.Value);
@@ -82,7 +82,7 @@ namespace Cryville.Crtr {
void MatchDynamic(SkinElement rel, ContainerState context, Transform anchor = null) { void MatchDynamic(SkinElement rel, ContainerState context, Transform anchor = null) {
ChartPlayer.etor.ContextTransform = anchor; ChartPlayer.etor.ContextTransform = anchor;
foreach (var p in rel.properties) { foreach (var p in rel.properties) {
if (p.Key.Name == null) if (p.Key.Name == 0)
throw new InvalidOperationException("Component creation in dynamic context is not allowed"); throw new InvalidOperationException("Component creation in dynamic context is not allowed");
var prop = GetPropOp(anchor, p.Key); var prop = GetPropOp(anchor, p.Key);
if (context.CloneType > prop.UpdateCloneType) continue; if (context.CloneType > prop.UpdateCloneType) continue;

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