145 Commits

Author SHA1 Message Date
8dd32afb74 Prevents dynamic anchor set twice. Implement special dynamic anchors. 2023-02-05 22:13:44 +08:00
313824b4bb Fix abnormal shaking at dynamic anchor. 2023-02-05 22:12:47 +08:00
b166c0f5ef Fix overflowed integral digits always prepended in string formatter. 2023-02-05 22:03:31 +08:00
300e44bd4b Code cleanup. 2023-02-05 15:59:20 +08:00
ab6f983392 Implement meta table for font. 2023-02-05 15:59:12 +08:00
596c6395e4 Prevent non-Windows system trying to initialize WindowsPointerHandler. 2023-02-05 15:58:31 +08:00
404a36f9b8 Replace text components in the main browser with TMP. 2023-02-05 15:56:56 +08:00
1711fbadf7 Add fallback logic for TMP auto font. 2023-02-05 15:55:53 +08:00
84b7a6d183 Seperate matcher from font manager. 2023-02-05 15:53:30 +08:00
6d0fd0f9ec Support multiple fonts with the same full name. 2023-02-05 15:51:18 +08:00
b407ba88c4 Add system font matcher. 2023-02-02 18:35:18 +08:00
bd256ba1a6 Reimport upgraded TextMesh Pro, modified. 2023-02-01 22:14:43 +08:00
623c53f79a Cleanup. 2023-01-31 22:56:19 +08:00
969fdc8069 Optimize GC for status info. 2023-01-31 22:56:06 +08:00
cbc874dd72 Optimize GC for proxied input variables. 2023-01-31 22:51:17 +08:00
450bd52095 Implement dynamic stack for skin. 2023-01-31 22:50:24 +08:00
5727fcf177 Introduce UnsafeIL for IL2CPP compatibility. 2023-01-31 22:49:04 +08:00
8ab0c2698b Fix TargetString stuck when length was 0. Add TargetString.TrustedAsArray. 2023-01-31 22:47:35 +08:00
6c7b52d93c Import TextMesh Pro. 2023-01-31 22:44:54 +08:00
91f55cd9a3 Add state count debug info. 2023-01-31 15:54:46 +08:00
a1ce459a0e Restructure event/container system. 2023-01-31 15:53:43 +08:00
9700992c3a Add DisposeAll. 2023-01-31 15:39:40 +08:00
f9a1ea72fe Refactor ReleaseEvent. 2023-01-31 15:30:27 +08:00
507b656eab Pull up StampedEvent.Temporary. Fix temporary event discarding. 2023-01-31 15:26:13 +08:00
c16776aee9 Code cleanup. (Amend) 2023-01-31 15:18:24 +08:00
e109e0bd24 Separate dynamic anchors. 2023-01-31 15:15:13 +08:00
776a615464 Code cleanup. 2023-01-31 15:06:31 +08:00
5514b6cf37 Pull up clip from judge definition. Add clip to event container. 2023-01-31 14:55:41 +08:00
8932d1b8d0 Add current_time variable. 2023-01-28 11:58:13 +08:00
10988847b3 Implement anchor related annotations. 2023-01-28 11:57:49 +08:00
c4b139c7a4 Code cleanup. 2023-01-27 17:30:10 +08:00
130896df1f Fix SkinSelectors.ToString. (2) 2023-01-27 16:54:11 +08:00
5d5c519a1d Remove dynamic judge anchors. (Amend) 2023-01-27 16:41:40 +08:00
3d1a11f78b Remove dynamic judge anchors. Add judge time properties. 2023-01-27 16:05:57 +08:00
cc985844cd Optimize GC for identifier and beat time property source. 2023-01-27 16:03:27 +08:00
feffbaa5a6 Refactor SkinPropertyKey. 2023-01-27 15:31:51 +08:00
d0f0c8ce6d Fix SkinSelectors.ToString. 2023-01-27 15:28:22 +08:00
3fdc236b1d Fix EmptyBinder not identifying inheritance. 2023-01-27 15:24:48 +08:00
46870e163a Code cleanup. 2023-01-26 18:12:22 +08:00
601f64cc61 Introduce no GC string formatter to optimize score string formatting. 2023-01-26 16:52:05 +08:00
c015b60dc3 Code cleanup. 2023-01-26 16:47:56 +08:00
5e01b654bd Optimize GC for enumerating TargetString. 2023-01-26 16:46:43 +08:00
2304257201 Add exception description on PDT parsing error. 2023-01-24 23:10:52 +08:00
02794d88b9 Fix config scene stuck on ruleset format error. 2023-01-22 22:29:16 +08:00
9f73c8ffad Code cleanup. 2023-01-21 20:14:41 +08:00
c1c354959d Add MotionCache. 2023-01-21 20:13:40 +08:00
94428d9e18 Append IDE warning suppression. 2023-01-21 20:12:03 +08:00
5198ecec1f Optimize code structure for input module. 2023-01-21 17:04:29 +08:00
6779b88055 Code cleanup. 2023-01-21 16:59:19 +08:00
c5dab3a232 Refactor SelectorNotAvailableException. 2023-01-20 22:50:31 +08:00
a7608bcd7e Matches dynamic on anchoring. 2023-01-20 22:50:05 +08:00
be64bc76b5 Revert "Revise update clone type to update depth."
This reverts commit 4185303bd2.
2023-01-20 22:26:56 +08:00
39bc34fd42 Fix dynamic judge anchors not updated if note is not working. 2023-01-17 22:16:40 +08:00
4185303bd2 Revise update clone type to update depth. 2023-01-17 22:16:09 +08:00
3280693e8f Update project version. 2023-01-16 22:11:19 +08:00
29432feabc Fix error on "(at) anchor" selector when no anchor is opened. 2023-01-16 20:57:19 +08:00
86559c681e Fix relative time calculation in judge report. 2023-01-16 20:55:32 +08:00
79f11b9c33 Implement judge_result contextual variable. 2023-01-16 20:54:53 +08:00
5b9149cb34 Make the output type of a property source read-only. 2023-01-16 20:53:45 +08:00
9d6bdd968f Implement write-only context. 2023-01-16 20:50:14 +08:00
bc4fec33ef Add null constant. 2023-01-16 20:47:54 +08:00
09e917dbe8 Add is function. 2023-01-16 20:46:57 +08:00
1003a0e199 Add forced variable syntax in PDT. 2023-01-16 20:45:06 +08:00
e3a805b855 Implement skin context property source injection. 2023-01-16 15:23:57 +08:00
4222176979 Add temporary event discard handling. 2023-01-16 15:09:34 +08:00
43c87fba70 Wrap Transform into SkinContext. Implement r/w context separation for skins. 2023-01-16 15:08:25 +08:00
d0a23aaf30 Add static judge anchor. Change dynamic anchors to single only. 2023-01-16 13:35:51 +08:00
a09a5686d7 Change anchor opening to single only. 2023-01-16 13:33:25 +08:00
609bb317d0 Code cleanup. 2023-01-15 11:54:11 +08:00
898fb7d557 Pull down chart field from StateBase. 2023-01-15 11:52:28 +08:00
c39f258a19 Code cleanup. 2023-01-14 22:03:08 +08:00
4fdd4e1935 Implement multiple static matching. 2023-01-14 22:01:29 +08:00
7662011d60 Pull down some judge preparation logic. 2023-01-14 21:39:10 +08:00
c24372b308 Pull up tail anchoring. 2023-01-14 21:35:15 +08:00
5e4c53113a Revise anchor data structure. 2023-01-14 21:34:13 +08:00
4f93995bbd Pull down EvaluationFailureException. 2023-01-13 22:18:13 +08:00
5b14466059 Add error handling for Discord callback. 2023-01-13 22:16:16 +08:00
1d3aa85446 Fix polysec.part. Enable judge anchor. 2023-01-13 16:46:29 +08:00
6efe70d751 Implement coevent. (2) 2023-01-13 16:37:31 +08:00
555c88855c Adapt Bestdori chart converter to coevents. 2023-01-12 18:05:20 +08:00
105aacc133 Fix config scene not unloaded if the ruleset is not present. 2023-01-10 21:41:48 +08:00
ea9000f2b0 Cleanup. 2023-01-09 22:17:42 +08:00
4e851d9b73 Implement coevent. 2023-01-09 16:28:36 +08:00
0a1e512f41 Code cleanup. 2023-01-08 16:27:02 +08:00
a7baef2c9d Add NoRequireDiscord flag when initializing Discord GameSDK. 2023-01-08 13:00:35 +08:00
723ec937ad Remove callback parameters on states. 2023-01-03 12:09:16 +08:00
7c77ba83f8 Fix polysec not mapping textures correctly if texture set partly. 2023-01-03 11:58:39 +08:00
6da4b96b24 Optimize motion invalidation performance. 2023-01-02 20:05:14 +08:00
e8f8593555 Fix conditional compilation. 2023-01-01 20:07:58 +08:00
2b5bc5dd08 Optimize GC for RMV pool. 2023-01-01 19:03:19 +08:00
cf6186aa16 Add judge anchor stub. 2023-01-01 19:02:49 +08:00
4d7773a2ac Cleanup anchor related code. 2023-01-01 19:01:34 +08:00
e8f74399f2 Implement judge report. 2023-01-01 19:00:19 +08:00
ca72f7adb5 Implement temporary event injection. (Amend) 2023-01-01 18:55:22 +08:00
5e19a8b886 Code cleanup. 2023-01-01 18:54:53 +08:00
a416f772d4 Add force sync frames. 2023-01-01 18:52:28 +08:00
989a6b5554 Fix osu chart ruleset and effect point. 2023-01-01 18:50:03 +08:00
732af15d9b Add Discord GameSDK. 2023-01-01 18:48:14 +08:00
8cdab36cd6 Fix handling for first timing point of osu chart. 2022-12-31 18:17:24 +08:00
44180c7e0f Optimize GC for PropSrc. 2022-12-25 22:20:46 +08:00
e589e37640 Code cleanup. 2022-12-24 19:12:16 +08:00
94107de97d Optimize GC for temporary anchor event injection. 2022-12-23 17:46:29 +08:00
13c55dc23e Optimize GC for PropOp.Enum<T>. 2022-12-23 17:45:07 +08:00
617eddc030 Reimplement cur anchor. 2022-12-23 16:28:48 +08:00
7475b19547 Implement temporary event injection. 2022-12-23 16:27:34 +08:00
0049ace91a Refactor polysec.suppressed to polysec.partial and polysec.part. 2022-12-23 16:25:57 +08:00
356f4df9a9 Exception cleanup. Code cleanup. 2022-12-23 15:20:16 +08:00
ff5928b556 Code cleanup. 2022-12-22 17:15:31 +08:00
1f0ac2a2e9 Add "at anchor" skin selector. 2022-12-22 17:14:48 +08:00
95628f07d1 Remove faulty toggling of anchor "cur". 2022-12-22 17:13:39 +08:00
3bead4f1b3 Add "polysec.suppressed" property. 2022-12-22 17:10:55 +08:00
ec9b23f797 Add "cur" anchor. 2022-12-22 14:43:50 +08:00
8175ca7e82 Optimize anchor identifiers. 2022-12-22 14:06:05 +08:00
451ebbe91a Code cleanup. 2022-12-22 14:02:58 +08:00
da2313ab57 Revert incorrect uct. 2022-12-22 12:30:57 +08:00
c5571e7d17 Make frame properties animatable. 2022-12-21 20:22:41 +08:00
959157255f Code cleanup. 2022-12-20 16:06:01 +08:00
06d8012675 Optimize GC for group frame. 2022-12-20 16:05:52 +08:00
571320630b Optimize performance for skin component properties. 2022-12-20 16:04:35 +08:00
207dee9932 Fix offsets for chart converters. (2) 2022-12-20 16:01:04 +08:00
d7b0ca77e9 Change state timestamp to double precision. 2022-12-19 14:55:15 +08:00
e55642cdeb Update project version. 2022-12-19 14:54:27 +08:00
595fd74662 Remove unused code. 2022-12-16 23:38:00 +08:00
3f7becf580 Temporarily change extension detection for Bestdori chart converter. 2022-12-16 17:51:23 +08:00
5d17555744 Implement preset path in file dialog. 2022-12-16 17:50:26 +08:00
e6d94f248c Logic cleanup for file dialog. 2022-12-16 17:48:43 +08:00
b0c70bc62e Pull up ExtensionInterface. 2022-12-16 17:44:41 +08:00
8eb0b11027 Add LocalResourceFinder. 2022-12-16 17:41:23 +08:00
7f2cfe94c1 Move GlobalSuppressions. 2022-12-16 15:45:51 +08:00
e4524bda0b Fix osu! charts with timing point with negative timestamp not able to be imported. 2022-12-16 15:45:26 +08:00
226fb15eb1 Resource cleanup. 2022-12-16 14:55:21 +08:00
645c4af2f2 Fix offsets for chart converters. 2022-12-16 14:36:10 +08:00
6e0f41c7fd Add osuChartConverter. 2022-12-16 14:17:32 +08:00
b9001ed9b2 Add BeatLength to TimingModel. 2022-12-13 17:53:59 +08:00
04abf59521 Fix QuaverChartConverter not generating endbeat of chart. 2022-12-13 15:10:00 +08:00
251f92532d Add QuaverChartConverter. 2022-12-13 10:51:29 +08:00
f5df56687b Add TimeTimingModel. 2022-12-13 10:51:05 +08:00
b582da90e5 Add optional offset to TimingModel constructor. 2022-12-13 10:50:34 +08:00
815f48fe06 Update Cryville.Common. 2022-12-13 09:21:52 +08:00
1470fa87dd Pull up BeatTimeTimingModel. 2022-12-13 08:59:35 +08:00
4b4356aaab Pull up FractionalBeatTimeTimingModel. 2022-12-12 23:48:15 +08:00
a8658856ca Code cleanup. 2022-12-12 22:28:08 +08:00
1477e907e6 Import YamlDotNet. 2022-12-12 22:23:49 +08:00
f559cea826 Code cleanup. 2022-12-05 12:16:42 +08:00
d363042036 Fix incorrect identifier load in PDT evaluator. 2022-12-05 11:43:31 +08:00
936 changed files with 141700 additions and 2717 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

@@ -33,12 +33,12 @@ namespace Cryville.Common {
public override object ChangeType(object value, Type type, CultureInfo culture) {
if (value == null)
return null;
else if (type == value.GetType())
else if (type.IsAssignableFrom(value.GetType()))
return value;
else if (type.IsEnum && value is string) {
return Enum.Parse(type, (string)value);
}
throw new InvalidCastException();
throw new InvalidCastException(string.Format("Cannot cast {0} to {1}", value.GetType(), type));
}
public override void ReorderArgumentArray(ref object[] args, object state) {

View File

@@ -18,7 +18,9 @@ namespace Cryville.Common.Buffers {
/// Creates an instance of the <see cref="TargetString" /> class.
/// </summary>
/// <param name="capacity">The initial capacity of the string.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity" /> is less than or equal to 0.</exception>
public TargetString(int capacity) {
if (capacity <= 0) throw new ArgumentOutOfRangeException("capacity");
_arr = new char[capacity];
}
/// <summary>
@@ -49,14 +51,16 @@ namespace Cryville.Common.Buffers {
/// <summary>
/// The length of the string.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">The value specified for a set operation is less than 0.</exception>
public int Length {
get {
return m_length;
}
set {
if (Length < 0) throw new ArgumentOutOfRangeException("length");
if (m_length == value) return;
if (_arr.Length < value) {
var len = m_length;
var len = _arr.Length;
while (len < value) len *= 2;
var arr2 = new char[len];
Array.Copy(_arr, arr2, m_length);
@@ -73,20 +77,31 @@ namespace Cryville.Common.Buffers {
if (!_invalidated) return;
_invalidated = false;
var ev = OnUpdate;
if (ev != null) OnUpdate.Invoke();
if (ev != null) ev.Invoke();
}
internal char[] TrustedAsArray() { return _arr; }
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
/// <summary>
/// Returns an enumerator that iterates through the <see cref="TargetString" />.
/// </summary>
/// <returns>A <see cref="Enumerator" /> for the <see cref="TargetString" />.</returns>
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
public IEnumerator<char> GetEnumerator() {
IEnumerator<char> IEnumerable<char>.GetEnumerator() {
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
class Enumerator : IEnumerator<char> {
public struct Enumerator : IEnumerator<char> {
readonly TargetString _self;
int _index = -1;
public Enumerator(TargetString self) { _self = self; }
int _index;
internal Enumerator(TargetString self) {
_self = self;
_index = -1;
}
public char Current {
get {

View File

@@ -1,9 +1,8 @@
fileFormatVersion: 2
guid: abad95983f1ca394a92bb061b76ebb2f
guid: 520554ce9a8205b4b91e0ff2b8011673
folderAsset: yes
timeCreated: 1638411493
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace Cryville.Common.Culture {
public static class ScriptUtils {
public static string[] Scripts = new string[] { "adlm", "afak", "aghb", "ahom", "arab", "aran", "armi", "armn", "avst", "bali", "bamu", "bass", "batk", "beng", "bhks", "blis", "bopo", "brah", "brai", "bugi", "buhd", "cakm", "cans", "cari", "cham", "cher", "chrs", "cirt", "copt", "cpmn", "cprt", "cyrl", "cyrs", "deva", "diak", "dogr", "dsrt", "dupl", "egyd", "egyh", "egyp", "elba", "elym", "ethi", "geok", "geor", "glag", "gong", "gonm", "goth", "gran", "grek", "gujr", "guru", "hanb", "hang", "hani", "hano", "hans", "hant", "hatr", "hebr", "hira", "hluw", "hmng", "hmnp", "hrkt", "hung", "inds", "ital", "jamo", "java", "jpan", "jurc", "kali", "kana", "khar", "khmr", "khoj", "kitl", "kits", "knda", "kore", "kpel", "kthi", "lana", "laoo", "latf", "latg", "latn", "leke", "lepc", "limb", "lina", "linb", "lisu", "loma", "lyci", "lydi", "mahj", "maka", "mand", "mani", "marc", "maya", "medf", "mend", "merc", "mero", "mlym", "modi", "mong", "moon", "mroo", "mtei", "mult", "mymr", "nand", "narb", "nbat", "newa", "nkdb", "nkgb", "nkoo", "nshu", "ogam", "olck", "orkh", "orya", "osge", "osma", "ougr", "palm", "pauc", "pcun", "pelm", "perm", "phag", "phli", "phlp", "phlv", "phnx", "piqd", "plrd", "prti", "psin", "qaaa", "qaai", "qabx", "ranj", "rjng", "rohg", "roro", "runr", "samr", "sara", "sarb", "saur", "sgnw", "shaw", "shrd", "shui", "sidd", "sind", "sinh", "sogd", "sogo", "sora", "soyo", "sund", "sylo", "syrc", "syre", "syrj", "syrn", "tagb", "takr", "tale", "talu", "taml", "tang", "tavt", "telu", "teng", "tfng", "tglg", "thaa", "thai", "tibt", "tirh", "toto", "ugar", "vaii", "visp", "wara", "wcho", "wole", "xpeo", "xsux", "yezi", "yiii", "zanb", "zinh", "zmth", "zsye", "zsym", "zxxx", "zyyy", "zzzz", };
public static string UltimateFallbackScript = "zyyy";
public static Dictionary<string, string[]> FallbackScriptMap = new Dictionary<string, string[]> {
{ "aran", new string[] { "arab" } }, { "cyrs", new string[] { "cyrl" } },
{ "hanb", new string[] { "hant", "bopo" } }, { "hans", new string[] { "hani" } }, { "hant", new string[] { "hani" } },
{ "hrkt", new string[] { "hira", "kana" } }, { "jpan", new string[] { "hani", "hira", "kana" } },
{ "jamo", new string[] { "hang" } }, { "kore", new string[] { "hang", "hani" } },
{ "latf", new string[] { "latn" } }, { "latg", new string[] { "latn" } },
{ "syre", new string[] { "syrc" } }, { "syrj", new string[] { "syrc" } }, { "syrn", new string[] { "syrc" } },
{ "zsye", new string[] { "zsym" } },
};
public static void FillKeysWithScripts(IDictionary dict, Func<object> value) {
foreach (var s in Scripts) dict.Add(s, value());
}
public static IEnumerable<string> EnumerateFallbackScripts(string script) {
if (string.IsNullOrEmpty(script)) throw new ArgumentNullException("script");
script = script.ToLower();
if (script == UltimateFallbackScript) {
yield return null;
yield break;
}
string[] fblist;
if (FallbackScriptMap.TryGetValue(script, out fblist)) {
foreach (var fb in fblist) {
yield return fb;
}
}
else yield return UltimateFallbackScript;
}
}
}

View File

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

View File

@@ -0,0 +1,114 @@
using Cryville.Common.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Cryville.Common.Font {
public abstract class FontFile : IEnumerable<Typeface> {
public abstract int Count { get; }
public abstract Typeface this[int index] { get; }
protected FileInfo File { get; private set; }
protected BinaryReader Reader { get; private set; }
public FontFile(FileInfo file) {
File = file;
Reader = new BinaryReaderBE(new FileStream(file.FullName, FileMode.Open, FileAccess.Read));
}
public void Close() { Reader.Close(); }
public static FontFile Create(FileInfo file) {
switch (file.Extension) {
case ".ttf": case ".otf": return new FontFileTTF(file);
case ".ttc": case ".otc": return new FontFileTTC(file);
default: return null;
}
}
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
IEnumerator<Typeface> IEnumerable<Typeface>.GetEnumerator() {
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public struct Enumerator : IEnumerator<Typeface> {
readonly FontFile _self;
int _index;
internal Enumerator(FontFile self) {
_self = self;
_index = -1;
}
public Typeface Current {
get {
if (_index < 0)
throw new InvalidOperationException(_index == -1 ? "Enum not started" : "Enum ended");
return _self[_index];
}
}
object IEnumerator.Current { get { return Current; } }
public void Dispose() {
_index = -2;
}
public bool MoveNext() {
if (_index == -2) return false;
_index++;
if (_index >= _self.Count) {
_index = -2;
return false;
}
return true;
}
public void Reset() {
_index = -1;
}
}
}
public class FontFileTTF : FontFile {
public override int Count { get { return 1; } }
public override Typeface this[int index] {
get {
if (index != 0) throw new ArgumentOutOfRangeException("index");
try {
return new TypefaceTTF(Reader, File, index);
}
catch (Exception) {
throw new InvalidDataException("Invalid font");
}
}
}
public FontFileTTF(FileInfo file) : base(file) { }
}
public class FontFileTTC : FontFile {
readonly IReadOnlyList<uint> _offsets;
public override int Count { get { return _offsets.Count; } }
public override Typeface this[int index] {
get {
if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index");
Reader.BaseStream.Position = _offsets[index];
try {
return new TypefaceTTF(Reader, File, index);
}
catch (Exception) {
throw new InvalidDataException("Invalid font");
}
}
}
public FontFileTTC(FileInfo file) : base(file) {
try {
_offsets = new TTCHeader(Reader, 0).GetItems();
}
catch (Exception) {
throw new InvalidDataException("Invalid font");
}
}
}
}

View File

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

View File

@@ -0,0 +1,63 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Cryville.Common.Font {
public abstract class FontManager {
public IReadOnlyDictionary<string, IReadOnlyCollection<Typeface>> MapFullNameToTypeface { get; private set; }
public IReadOnlyDictionary<string, IReadOnlyCollection<Typeface>> MapNameToTypefaces { get; private set; }
public FontManager() {
var map1 = new Dictionary<string, List<Typeface>>();
var map2 = new Dictionary<string, List<Typeface>>();
foreach (var f in EnumerateAllTypefaces()) {
List<Typeface> set1;
if (!map1.TryGetValue(f.FullName, out set1)) {
map1.Add(f.FullName, set1 = new List<Typeface>());
}
set1.Add(f);
List<Typeface> set2;
if (!map2.TryGetValue(f.FamilyName, out set2)) {
map2.Add(f.FamilyName, set2 = new List<Typeface>());
}
set2.Add(f);
}
MapFullNameToTypeface = map1.ToDictionary(i => i.Key, i => (IReadOnlyCollection<Typeface>)i.Value);
MapNameToTypefaces = map2.ToDictionary(i => i.Key, i => (IReadOnlyCollection<Typeface>)i.Value);
}
protected abstract IEnumerable<Typeface> EnumerateAllTypefaces();
protected static IEnumerable<Typeface> ScanDirectoryForTypefaces(string dir) {
foreach (var f in new DirectoryInfo(dir).EnumerateFiles()) {
FontFile file;
try {
file = FontFile.Create(f);
}
catch (InvalidDataException) {
continue;
}
if (file == null) continue;
var enumerator = file.GetEnumerator();
while (enumerator.MoveNext()) {
Typeface ret;
try {
ret = enumerator.Current;
}
catch (InvalidDataException) {
continue;
}
yield return ret;
}
file.Close();
}
}
}
public class FontManagerAndroid : FontManager {
protected override IEnumerable<Typeface> EnumerateAllTypefaces() {
return ScanDirectoryForTypefaces("/system/fonts");
}
}
public class FontManagerWindows : FontManager {
protected override IEnumerable<Typeface> EnumerateAllTypefaces() {
return ScanDirectoryForTypefaces("C:/Windows/Fonts");
}
}
}

View File

@@ -0,0 +1,329 @@
using Cryville.Common.Culture;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cryville.Common.Font {
public abstract class FontMatcher {
protected FontManager Manager { get; private set; }
public FontMatcher(FontManager manafer) { Manager = manafer; }
public abstract IEnumerable<Typeface> MatchScript(string script = null, bool distinctFamily = false);
}
public class FallbackListFontMatcher : FontMatcher {
public Dictionary<string, List<string>> MapScriptToTypefaces = new Dictionary<string, List<string>>();
public void LoadDefaultWindowsFallbackList() {
if (Environment.OSVersion.Platform != PlatformID.Win32NT) return;
MapScriptToTypefaces.Clear();
ScriptUtils.FillKeysWithScripts(MapScriptToTypefaces, () => new List<string>());
// Reference: https://github.com/chromium/chromium/blob/main/third_party/blink/renderer/platform/fonts/win/font_fallback_win.cc
MapScriptToTypefaces["zyyy"].Insert(0, "SimSun"); // Custom
MapScriptToTypefaces["zyyy"].Insert(0, "SimHei"); // Custom
MapScriptToTypefaces["zyyy"].Insert(0, "Microsoft YaHei"); // Custom
MapScriptToTypefaces["zyyy"].Insert(0, "Arial");
MapScriptToTypefaces["zyyy"].Insert(0, "Times New Roman");
MapScriptToTypefaces["zyyy"].Insert(0, "Segoe UI"); // Custom
MapScriptToTypefaces["arab"].Insert(0, "Tahoma");
MapScriptToTypefaces["cyrl"].Insert(0, "Times New Roman");
MapScriptToTypefaces["grek"].Insert(0, "Times New Roman");
MapScriptToTypefaces["hebr"].Insert(0, "David");
MapScriptToTypefaces["jpan"].Insert(0, "MS PGothic");
MapScriptToTypefaces["latn"].Insert(0, "Times New Roman");
MapScriptToTypefaces["hans"].Insert(0, "SimSun");
MapScriptToTypefaces["hans"].Insert(0, "SimHei"); // Custom
MapScriptToTypefaces["thai"].Insert(0, "Tahoma");
MapScriptToTypefaces["hans"].Insert(0, "PMingLiU");
// Reference: https://learn.microsoft.com/en-us/globalization/input/font-support
var ver = Environment.OSVersion.Version;
if (ver >= new Version(5, 0)) { // Windows 2000
MapScriptToTypefaces["armn"].Insert(0, "Sylfaen");
MapScriptToTypefaces["deva"].Insert(0, "Mangal");
MapScriptToTypefaces["geor"].Insert(0, "Sylfaen");
MapScriptToTypefaces["taml"].Insert(0, "Latha");
}
if (ver >= new Version(5, 1)) { // Windows XP
MapScriptToTypefaces["gujr"].Insert(0, "Shruti");
MapScriptToTypefaces["guru"].Insert(0, "Raavi");
MapScriptToTypefaces["knda"].Insert(0, "Tunga");
MapScriptToTypefaces["syrc"].Insert(0, "Estrangelo Edessa");
MapScriptToTypefaces["telu"].Insert(0, "Gautami");
MapScriptToTypefaces["thaa"].Insert(0, "MV Boli");
// SP2
MapScriptToTypefaces["beng"].Insert(0, "Vrinda");
MapScriptToTypefaces["mlym"].Insert(0, "Kartika");
}
if (ver >= new Version(6, 0)) { // Windows Vista
MapScriptToTypefaces["cans"].Insert(0, "Euphemia");
MapScriptToTypefaces["cher"].Insert(0, "Plantagenet");
MapScriptToTypefaces["ethi"].Insert(0, "Nyala");
MapScriptToTypefaces["khmr"].Insert(0, "DaunPenh MoolBoran");
MapScriptToTypefaces["laoo"].Insert(0, "DokChampa");
MapScriptToTypefaces["mong"].Insert(0, "Mongolian Baiti");
MapScriptToTypefaces["orya"].Insert(0, "Kalinga");
MapScriptToTypefaces["sinh"].Insert(0, "Iskoola Pota");
MapScriptToTypefaces["tibt"].Insert(0, "Microsoft Himalaya");
MapScriptToTypefaces["yiii"].Insert(0, "Microsoft Yi Baiti");
MapScriptToTypefaces["arab"].Insert(0, "Segoe UI");
MapScriptToTypefaces["cyrl"].Insert(0, "Segoe UI");
MapScriptToTypefaces["grek"].Insert(0, "Segoe UI");
MapScriptToTypefaces["latn"].Insert(0, "Segoe UI");
MapScriptToTypefaces["hans"].Add("SimSun-ExtB");
MapScriptToTypefaces["hant"].Add("MingLiU-ExtB");
MapScriptToTypefaces["hant"].Add("MingLiU_HKSCS-ExtB");
MapScriptToTypefaces["arab"].Add("Microsoft Uighur");
MapScriptToTypefaces["zmth"].Insert(0, "Cambria Math");
// Reference: https://en.wikipedia.org/wiki/List_of_CJK_fonts
MapScriptToTypefaces["jpan"].Insert(0, "Meiryo");
MapScriptToTypefaces["hans"].Insert(0, "Microsoft YaHei");
}
if (ver >= new Version(6, 1)) { // Windows 7
MapScriptToTypefaces["brai"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["dsrt"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["talu"].Insert(0, "Microsoft New Tai Lue");
MapScriptToTypefaces["ogam"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["osma"].Insert(0, "Ebrima");
MapScriptToTypefaces["phag"].Insert(0, "Microsoft PhagsPa");
MapScriptToTypefaces["runr"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["zsym"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["tale"].Insert(0, "Microsoft Tai Le");
MapScriptToTypefaces["tfng"].Insert(0, "Ebrima");
MapScriptToTypefaces["vaii"].Insert(0, "Ebrima");
}
if (ver >= new Version(6, 2)) { // Windows 8
MapScriptToTypefaces["glag"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["goth"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["hang"].Add("Malgun Gothic");
MapScriptToTypefaces["ital"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["lisu"].Insert(0, "Segoe UI");
MapScriptToTypefaces["mymr"].Insert(0, "Myanmar Text");
MapScriptToTypefaces["nkoo"].Insert(0, "Ebrima");
MapScriptToTypefaces["orkh"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["ethi"].Insert(0, "Ebrima");
MapScriptToTypefaces["cans"].Insert(0, "Gadugi");
MapScriptToTypefaces["hant"].Insert(0, "Microsoft JhengHei UI");
MapScriptToTypefaces["hans"].Insert(0, "Microsoft YaHei UI");
MapScriptToTypefaces["beng"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["deva"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["gujr"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["guru"].Insert(0, "Nirmala UI"); // NOT DOCUMENTED, UNVERIFIED
MapScriptToTypefaces["knda"].Insert(0, "Nirmala UI"); // NOT DOCUMENTED, UNVERIFIED
MapScriptToTypefaces["mlym"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["orya"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["sinh"].Insert(0, "Nirmala UI"); // NOT DOCUMENTED, UNVERIFIED
MapScriptToTypefaces["taml"].Insert(0, "Nirmala UI"); // NOT DOCUMENTED, UNVERIFIED
MapScriptToTypefaces["telu"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["armn"].Insert(0, "Segoe UI");
MapScriptToTypefaces["geor"].Insert(0, "Segoe UI");
MapScriptToTypefaces["hebr"].Insert(0, "Segoe UI");
}
if (ver >= new Version(6, 3)) { // Windows 8.1
MapScriptToTypefaces["bugi"].Insert(0, "Leelawadee UI");
MapScriptToTypefaces["copt"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["java"].Insert(0, "Javanese Text");
MapScriptToTypefaces["merc"].Insert(0, "Segoe UI Symbol");
MapScriptToTypefaces["olck"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["sora"].Insert(0, "Nirmala UI");
MapScriptToTypefaces["khmr"].Insert(0, "Leelawadee UI");
MapScriptToTypefaces["laoo"].Insert(0, "Leelawadee UI");
MapScriptToTypefaces["thai"].Insert(0, "Leelawadee UI");
MapScriptToTypefaces["zsye"].Insert(0, "Segoe UI Emoji");
}
if (ver >= new Version(10, 0)) { // Windows 10
MapScriptToTypefaces["brah"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["cari"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["cprt"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["egyp"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["armi"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["phli"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["prti"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["khar"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["lyci"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["lydi"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["phnx"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["xpeo"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["sarb"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["shaw"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["xsux"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["ugar"].Insert(0, "Segoe UI Historic");
// Segoe UI Symbol -> Segoe UI Historic
MapScriptToTypefaces["glag"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["goth"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["merc"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["ogam"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["ital"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["orkh"].Insert(0, "Segoe UI Historic");
MapScriptToTypefaces["runr"].Insert(0, "Segoe UI Historic");
//
MapScriptToTypefaces["jpan"].Insert(0, "Yu Gothic UI");
MapScriptToTypefaces["zsym"].Add("Segoe MDL2 Assets");
}
}
public void LoadDefaultAndroidFallbackList() {
if (Environment.OSVersion.Platform != PlatformID.Unix) return;
MapScriptToTypefaces.Clear();
ScriptUtils.FillKeysWithScripts(MapScriptToTypefaces, () => new List<string>());
MapScriptToTypefaces["zyyy"].Insert(0, "Noto Sans CJK TC"); // TODO Modify default fallback
MapScriptToTypefaces["zyyy"].Insert(0, "Noto Sans CJK JP");
MapScriptToTypefaces["zyyy"].Insert(0, "Noto Sans CJK SC");
MapScriptToTypefaces["zyyy"].Insert(0, "Roboto");
MapScriptToTypefaces["zsye"].Insert(0, "Noto Color Emoji");
MapScriptToTypefaces["zsye"].Add("Noto Color Emoji Flags");
MapScriptToTypefaces["arab"].Insert(0, "Noto Naskh Arabic");
MapScriptToTypefaces["adlm"].Insert(0, "Noto Sans Adlam");
MapScriptToTypefaces["ahom"].Insert(0, "Noto Sans Ahom");
MapScriptToTypefaces["hluw"].Insert(0, "Noto Sans Anatolian Hieroglyphs");
MapScriptToTypefaces["armn"].Insert(0, "Noto Sans Armenian");
MapScriptToTypefaces["avst"].Insert(0, "Noto Sans Avestan");
MapScriptToTypefaces["bali"].Insert(0, "Noto Sans Balinese");
MapScriptToTypefaces["bamu"].Insert(0, "Noto Sans Bamum");
MapScriptToTypefaces["bass"].Insert(0, "Noto Sans Bassa Vah");
MapScriptToTypefaces["batk"].Insert(0, "Noto Sans Batak");
MapScriptToTypefaces["beng"].Insert(0, "Noto Sans Bengali");
MapScriptToTypefaces["bhks"].Insert(0, "Noto Sans Bhaiksuki");
MapScriptToTypefaces["brah"].Insert(0, "Noto Sans Brahmi");
MapScriptToTypefaces["bugi"].Insert(0, "Noto Sans Buginese");
MapScriptToTypefaces["buhd"].Insert(0, "Noto Sans Buhid");
MapScriptToTypefaces["jpan"].Insert(0, "Noto Sans CJK JP");
MapScriptToTypefaces["kore"].Insert(0, "Noto Sans CJK KR");
MapScriptToTypefaces["hans"].Insert(0, "Noto Sans CJK SC");
MapScriptToTypefaces["hant"].Insert(0, "Noto Sans CJK TC");
MapScriptToTypefaces["hant"].Add("Noto Sans CJK HK");
MapScriptToTypefaces["cans"].Insert(0, "Noto Sans Canadian Aboriginal");
MapScriptToTypefaces["cari"].Insert(0, "Noto Sans Carian");
MapScriptToTypefaces["cakm"].Insert(0, "Noto Sans Chakma");
MapScriptToTypefaces["cham"].Insert(0, "Noto Sans Cham");
MapScriptToTypefaces["cher"].Insert(0, "Noto Sans Cherokee");
MapScriptToTypefaces["copt"].Insert(0, "Noto Sans Coptic");
MapScriptToTypefaces["xsux"].Insert(0, "Noto Sans Cuneiform");
MapScriptToTypefaces["cprt"].Insert(0, "Noto Sans Cypriot");
MapScriptToTypefaces["dsrt"].Insert(0, "Noto Sans Deseret");
MapScriptToTypefaces["deva"].Insert(0, "Noto Sans Devanagari");
MapScriptToTypefaces["egyp"].Insert(0, "Noto Sans Egyptian Hieroglyphs");
MapScriptToTypefaces["elba"].Insert(0, "Noto Sans Elbasan");
MapScriptToTypefaces["ethi"].Insert(0, "Noto Sans Ethiopic");
MapScriptToTypefaces["geor"].Insert(0, "Noto Sans Georgian");
MapScriptToTypefaces["glag"].Insert(0, "Noto Sans Glagolitic");
MapScriptToTypefaces["goth"].Insert(0, "Noto Sans Gothic");
MapScriptToTypefaces["gran"].Insert(0, "Noto Sans Grantha");
MapScriptToTypefaces["gujr"].Insert(0, "Noto Sans Gujarati");
MapScriptToTypefaces["gong"].Insert(0, "Noto Sans Gunjala Gondi");
MapScriptToTypefaces["guru"].Insert(0, "Noto Sans Gurmukhi");
MapScriptToTypefaces["rohg"].Insert(0, "Noto Sans Hanifi Rohingya");
MapScriptToTypefaces["hano"].Insert(0, "Noto Sans Hanunoo");
MapScriptToTypefaces["hatr"].Insert(0, "Noto Sans Hatran");
MapScriptToTypefaces["hebr"].Insert(0, "Noto Sans Hebrew");
MapScriptToTypefaces["armi"].Insert(0, "Noto Sans Imperial Aramaic");
MapScriptToTypefaces["phli"].Insert(0, "Noto Sans Inscriptional Pahlavi");
MapScriptToTypefaces["prti"].Insert(0, "Noto Sans Inscriptional Parthian");
MapScriptToTypefaces["java"].Insert(0, "Noto Sans Javanese");
MapScriptToTypefaces["kthi"].Insert(0, "Noto Sans Kaithi");
MapScriptToTypefaces["knda"].Insert(0, "Noto Sans Kannada");
MapScriptToTypefaces["kali"].Insert(0, "Noto Sans KayahLi");
MapScriptToTypefaces["khar"].Insert(0, "Noto Sans Kharoshthi");
MapScriptToTypefaces["khmr"].Insert(0, "Noto Sans Khmer");
MapScriptToTypefaces["khoj"].Insert(0, "Noto Sans Khojki");
MapScriptToTypefaces["laoo"].Insert(0, "Noto Sans Lao");
MapScriptToTypefaces["lepc"].Insert(0, "Noto Sans Lepcha");
MapScriptToTypefaces["limb"].Insert(0, "Noto Sans Limbu");
MapScriptToTypefaces["lina"].Insert(0, "Noto Sans Linear A");
MapScriptToTypefaces["linb"].Insert(0, "Noto Sans Linear B");
MapScriptToTypefaces["lisu"].Insert(0, "Noto Sans Lisu");
MapScriptToTypefaces["lyci"].Insert(0, "Noto Sans Lycian");
MapScriptToTypefaces["lydi"].Insert(0, "Noto Sans Lydian");
MapScriptToTypefaces["mlym"].Insert(0, "Noto Sans Malayalam");
MapScriptToTypefaces["mand"].Insert(0, "Noto Sans Mandiac");
MapScriptToTypefaces["mani"].Insert(0, "Noto Sans Manichaean");
MapScriptToTypefaces["marc"].Insert(0, "Noto Sans Marchen");
MapScriptToTypefaces["gonm"].Insert(0, "Noto Sans Masaram Gondi");
MapScriptToTypefaces["medf"].Insert(0, "Noto Sans Medefaidrin");
MapScriptToTypefaces["mtei"].Insert(0, "Noto Sans Meetei Mayek");
MapScriptToTypefaces["merc"].Insert(0, "Noto Sans Meroitic");
MapScriptToTypefaces["mero"].Insert(0, "Noto Sans Meroitic");
MapScriptToTypefaces["plrd"].Insert(0, "Noto Sans Miao");
MapScriptToTypefaces["modi"].Insert(0, "Noto Sans Modi");
MapScriptToTypefaces["mong"].Insert(0, "Noto Sans Mongolian");
MapScriptToTypefaces["mroo"].Insert(0, "Noto Sans Mro");
MapScriptToTypefaces["mult"].Insert(0, "Noto Sans Multani");
MapScriptToTypefaces["mymr"].Insert(0, "Noto Sans Myanmar");
MapScriptToTypefaces["nkoo"].Insert(0, "Noto Sans Nko");
MapScriptToTypefaces["nbat"].Insert(0, "Noto Sans Nabataean");
MapScriptToTypefaces["talu"].Insert(0, "Noto Sans New Tai Lue");
MapScriptToTypefaces["newa"].Insert(0, "Noto Sans Newa");
MapScriptToTypefaces["ogam"].Insert(0, "Noto Sans Ogham");
MapScriptToTypefaces["olck"].Insert(0, "Noto Sans Ol Chiki");
MapScriptToTypefaces["ital"].Insert(0, "Noto Sans Old Italian");
MapScriptToTypefaces["narb"].Insert(0, "Noto Sans Old North Arabian");
MapScriptToTypefaces["perm"].Insert(0, "Noto Sans Old Permic");
MapScriptToTypefaces["xpeo"].Insert(0, "Noto Sans Old Persian");
MapScriptToTypefaces["sarb"].Insert(0, "Noto Sans Old South Arabian");
MapScriptToTypefaces["orkh"].Insert(0, "Noto Sans Old Turkic");
MapScriptToTypefaces["orya"].Insert(0, "Noto Sans Oriya");
MapScriptToTypefaces["osge"].Insert(0, "Noto Sans Osage");
MapScriptToTypefaces["osma"].Insert(0, "Noto Sans Osmanya");
MapScriptToTypefaces["hmng"].Insert(0, "Noto Sans Pahawh Hmong");
MapScriptToTypefaces["palm"].Insert(0, "Noto Sans Palmyrene");
MapScriptToTypefaces["pauc"].Insert(0, "Noto Sans Pau Cin Hau");
MapScriptToTypefaces["phag"].Insert(0, "Noto Sans Phags Pa");
MapScriptToTypefaces["phnx"].Insert(0, "Noto Sans Phoenician");
MapScriptToTypefaces["rjng"].Insert(0, "Noto Sans Rejang");
MapScriptToTypefaces["runr"].Insert(0, "Noto Sans Runic");
MapScriptToTypefaces["samr"].Insert(0, "Noto Sans Samaritan");
MapScriptToTypefaces["saur"].Insert(0, "Noto Sans Saurashtra");
MapScriptToTypefaces["shrd"].Insert(0, "Noto Sans Sharada");
MapScriptToTypefaces["shaw"].Insert(0, "Noto Sans Shavian");
MapScriptToTypefaces["sinh"].Insert(0, "Noto Sans Sinhala");
MapScriptToTypefaces["sora"].Insert(0, "Noto Sans Sora Sompeng");
MapScriptToTypefaces["soyo"].Insert(0, "Noto Sans Soyombo");
MapScriptToTypefaces["sund"].Insert(0, "Noto Sans Sundanese");
MapScriptToTypefaces["sylo"].Insert(0, "Noto Sans Syloti Nagri");
MapScriptToTypefaces["zsym"].Insert(0, "Noto Sans Symbols");
MapScriptToTypefaces["syrn"].Insert(0, "Noto Sans Syriac Eastern");
MapScriptToTypefaces["syre"].Insert(0, "Noto Sans Syriac Estrangela");
MapScriptToTypefaces["syrj"].Insert(0, "Noto Sans Syriac Western");
MapScriptToTypefaces["tglg"].Insert(0, "Noto Sans Tagalog");
MapScriptToTypefaces["tagb"].Insert(0, "Noto Sans Tagbanwa");
MapScriptToTypefaces["tale"].Insert(0, "Noto Sans Tai Le");
MapScriptToTypefaces["lana"].Insert(0, "Noto Sans Tai Tham");
MapScriptToTypefaces["tavt"].Insert(0, "Noto Sans Tai Viet");
MapScriptToTypefaces["takr"].Insert(0, "Noto Sans Takri");
MapScriptToTypefaces["taml"].Insert(0, "Noto Sans Tamil");
MapScriptToTypefaces["telu"].Insert(0, "Noto Sans Telugu");
MapScriptToTypefaces["thaa"].Insert(0, "Noto Sans Thaana");
MapScriptToTypefaces["thai"].Insert(0, "Noto Sans Thai");
MapScriptToTypefaces["tfng"].Insert(0, "Noto Sans Tifinagh");
MapScriptToTypefaces["ugar"].Insert(0, "Noto Sans Ugaritic");
MapScriptToTypefaces["vaii"].Insert(0, "Noto Sans Vai");
MapScriptToTypefaces["wcho"].Insert(0, "Noto Sans Wancho");
MapScriptToTypefaces["wara"].Insert(0, "Noto Sans Warang Citi");
MapScriptToTypefaces["yiii"].Insert(0, "Noto Sans Yi");
}
public FallbackListFontMatcher(FontManager manager) : base(manager) { }
public override IEnumerable<Typeface> MatchScript(string script = null, bool distinctFamily = false) {
if (string.IsNullOrEmpty(script)) script = ScriptUtils.UltimateFallbackScript;
List<string> candidates;
IEnumerable<string> candidateScripts = new string[] { script };
while (candidateScripts != null) {
foreach (var candidateScript in candidateScripts) {
if (MapScriptToTypefaces.TryGetValue(candidateScript, out candidates)) {
foreach (var candidate in candidates) {
IReadOnlyCollection<Typeface> typefaces1;
if (Manager.MapFullNameToTypeface.TryGetValue(candidate, out typefaces1)) {
foreach (var typeface in typefaces1) {
yield return typeface;
}
}
if (distinctFamily) continue;
IReadOnlyCollection<Typeface> typefaces2;
if (Manager.MapNameToTypefaces.TryGetValue(candidate, out typefaces2)) {
foreach (var typeface in typefaces2) {
if (typefaces1.Contains(typeface)) continue;
yield return typeface;
}
}
}
}
}
candidateScripts = ScriptUtils.EnumerateFallbackScripts(script);
}
}
}
}

View File

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

View File

@@ -0,0 +1,222 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Cryville.Common.Font {
public abstract class FontTable<T> {
protected UInt32 Offset { get; private set; }
protected BinaryReader Reader { get; private set; }
protected FontTable(BinaryReader reader, UInt32 offset) {
Reader = reader;
Offset = offset;
reader.BaseStream.Position = offset;
}
public abstract IReadOnlyList<T> GetItems();
}
public abstract class FontTable<T, U> : FontTable<T> {
protected FontTable(BinaryReader reader, UInt32 offset) : base(reader, offset) { }
public abstract U GetSubTable(T item);
}
public sealed class TTCHeader : FontTable<UInt32, TableDirectory> {
readonly String ttcTag;
readonly UInt16 majorVersion;
readonly UInt16 minorVersion;
readonly UInt32 numFonts;
readonly List<UInt32> tableDirectoryOffsets = new List<UInt32>();
readonly String dsigTag;
readonly UInt32 dsigLength;
readonly UInt32 dsigOffset;
public TTCHeader(BinaryReader reader, UInt32 offset) : base(reader, offset) {
ttcTag = reader.ReadTag();
if (ttcTag != "ttcf") throw new NotImplementedException();
majorVersion = reader.ReadUInt16();
minorVersion = reader.ReadUInt16();
numFonts = reader.ReadUInt32();
for (UInt32 i = 0; i < numFonts; i++) tableDirectoryOffsets.Add(reader.ReadUInt32());
if (majorVersion == 2) {
dsigTag = reader.ReadTag();
dsigLength = reader.ReadUInt32();
dsigOffset = reader.ReadUInt32();
}
}
public override IReadOnlyList<UInt32> GetItems() {
return tableDirectoryOffsets;
}
public override TableDirectory GetSubTable(UInt32 item) {
var i = (UInt32)item;
return new TableDirectory(Reader, i);
}
}
public sealed class TableDirectory : FontTable<TableRecord, object> {
readonly UInt32 sfntVersion;
readonly UInt16 numTables;
readonly UInt16 searchRange;
readonly UInt16 entrySelector;
readonly UInt16 rangeShift;
readonly List<TableRecord> tableRecords = new List<TableRecord>();
public TableDirectory(BinaryReader reader, UInt32 offset) : base(reader, offset) {
sfntVersion = reader.ReadUInt32();
numTables = reader.ReadUInt16();
searchRange = reader.ReadUInt16();
entrySelector = reader.ReadUInt16();
rangeShift = reader.ReadUInt16();
for (int i = 0; i < numTables; i++)
tableRecords.Add(new TableRecord {
tableTag = reader.ReadTag(),
checksum = reader.ReadUInt32(),
offset = reader.ReadUInt32(),
length = reader.ReadUInt32(),
});
}
public override IReadOnlyList<TableRecord> GetItems() {
return tableRecords;
}
public override object GetSubTable(TableRecord item) {
switch (item.tableTag) {
case "name": return new NameTable(Reader, item.offset);
case "meta": return new MetaTable(Reader, item.offset);
default: throw new NotImplementedException();
}
}
}
public struct TableRecord {
public string tableTag;
public UInt32 checksum;
public UInt32 offset;
public UInt32 length;
}
public sealed class NameTable : FontTable<NameRecord> {
readonly UInt16 version;
readonly UInt16 count;
readonly UInt16 storageOffset;
readonly List<NameRecord> nameRecord = new List<NameRecord>();
readonly UInt16 langTagCount;
readonly List<LangTagRecord> langTagRecord = new List<LangTagRecord>();
public NameTable(BinaryReader reader, UInt32 offset) : base(reader, offset) {
version = reader.ReadUInt16();
count = reader.ReadUInt16();
storageOffset = reader.ReadUInt16();
for (UInt16 i = 0; i < count; i++)
nameRecord.Add(new NameRecord {
platformID = reader.ReadUInt16(),
encodingID = reader.ReadUInt16(),
languageID = reader.ReadUInt16(),
nameID = (NameID)reader.ReadUInt16(),
length = reader.ReadUInt16(),
stringOffset = reader.ReadUInt16(),
});
if (version == 1) {
langTagCount = reader.ReadUInt16();
for (UInt16 i = 0; i < langTagCount; i++)
langTagRecord.Add(new LangTagRecord {
length = reader.ReadUInt16(),
langTagOffset = reader.ReadUInt16(),
});
}
UInt32 origin = (UInt32)reader.BaseStream.Position;
for (int i = 0; i < nameRecord.Count; i++) nameRecord[i] = nameRecord[i].Load(reader, origin);
for (int i = 0; i < langTagRecord.Count; i++) langTagRecord[i] = langTagRecord[i].Load(reader, origin);
}
public sealed override IReadOnlyList<NameRecord> GetItems() {
return nameRecord;
}
}
public struct NameRecord {
public UInt16 platformID;
public UInt16 encodingID;
public UInt16 languageID;
public NameID nameID;
public UInt16 length;
public UInt16 stringOffset;
public String value { get; private set; }
public NameRecord Load(BinaryReader reader, UInt32 origin) {
reader.BaseStream.Position = origin + stringOffset;
Encoding encoding;
switch (platformID) {
case 0: encoding = Encoding.BigEndianUnicode; break;
case 3: encoding = Encoding.BigEndianUnicode; break;
default: return this;
}
value = encoding.GetString(reader.ReadBytes(length));
return this;
}
}
public enum NameID : UInt16 {
CopyrightNotice = 0,
FontFamilyName = 1,
FontSubfamilyName = 2,
UniqueFontIdentifier = 3,
FullFontName = 4,
VersionString = 5,
PostScriptName = 6,
Trademark = 7,
ManufacturerName = 8,
Designer = 9,
Description = 10,
URLVendor = 11,
URLDesigner = 12,
LicenseDescription = 13,
LicenseInfoURL = 14,
TypographicFamilyName = 16,
TypographicSubfamilyName = 17,
CompatibleFull = 18,
SampleText = 19,
PostScriptCIDFindfontName = 20,
WWSFamilyName = 21,
WWSSubfamilyName = 22,
LightBackgroundPalette = 23,
DarkBackgroundPalette = 24,
VariationsPostScriptNamePrefix = 25,
}
public struct LangTagRecord {
public UInt16 length;
public UInt16 langTagOffset;
public String value { get; private set; }
public LangTagRecord Load(BinaryReader reader, UInt32 origin) {
reader.BaseStream.Position = origin + langTagOffset;
value = Encoding.BigEndianUnicode.GetString(reader.ReadBytes(length));
return this;
}
}
public sealed class MetaTable : FontTable<DataMap> {
readonly UInt32 version;
readonly UInt32 flags;
readonly UInt32 dataMapCount;
readonly List<DataMap> dataMaps = new List<DataMap>();
public MetaTable(BinaryReader reader, UInt32 offset) : base(reader, offset) {
version = reader.ReadUInt32();
flags = reader.ReadUInt32();
reader.ReadUInt32();
dataMapCount = reader.ReadUInt32();
for (UInt32 i = 0; i < dataMapCount; i++)
dataMaps.Add(new DataMap {
tag = reader.ReadTag(),
dataOffset = reader.ReadUInt32(),
dataLength = reader.ReadUInt32(),
});
for (int i = 0; i < dataMaps.Count; i++) dataMaps[i] = dataMaps[i].Load(reader, offset);
}
public sealed override IReadOnlyList<DataMap> GetItems() {
return dataMaps;
}
}
public struct DataMap {
public String tag;
public UInt32 dataOffset;
public UInt32 dataLength;
public String value { get; private set; }
public DataMap Load(BinaryReader reader, UInt32 origin) {
reader.BaseStream.Position = origin + dataOffset;
value = Encoding.ASCII.GetString(reader.ReadBytes((int)dataLength));
return this;
}
}
public static class BinaryReaderExtensions {
public static string ReadTag(this BinaryReader reader) {
return Encoding.ASCII.GetString(reader.ReadBytes(4));
}
}
}

View File

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

View File

@@ -1,9 +0,0 @@
using System.Globalization;
namespace Cryville.Common.Font {
public static class FontUtil {
/*public static string MatchFontNameWithLang(string lang) {
}*/
}
}

View File

@@ -0,0 +1,31 @@
using System.IO;
using System.Linq;
namespace Cryville.Common.Font {
public abstract class Typeface {
public FileInfo File { get; private set; }
public int IndexInFile { get; private set; }
public string FamilyName { get; protected set; }
public string SubfamilyName { get; protected set; }
public string FullName { get; protected set; }
protected abstract void GetName(BinaryReader reader);
public Typeface(BinaryReader reader, FileInfo file, int index) {
File = file;
IndexInFile = index;
GetName(reader);
}
}
public class TypefaceTTF : Typeface {
public TypefaceTTF(BinaryReader reader, FileInfo file, int index)
: base(reader, file, index) { }
protected override void GetName(BinaryReader reader) {
var dir = new TableDirectory(reader, (uint)reader.BaseStream.Position);
var nameTable = (NameTable)dir.GetSubTable((from i in dir.GetItems() where i.tableTag == "name" select i).Single());
FamilyName = (from i in nameTable.GetItems() where i.nameID == NameID.FontFamilyName && i.value != null select i.value).First();
SubfamilyName = (from i in nameTable.GetItems() where i.nameID == NameID.FontSubfamilyName && i.value != null select i.value).First();
FullName = (from i in nameTable.GetItems() where i.nameID == NameID.FullFontName && i.value != null select i.value).First();
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,75 @@
using System;
using System.IO;
using System.Text;
namespace Cryville.Common.IO {
public class BinaryReaderBE : BinaryReader {
readonly byte[] m_buffer = new byte[8];
public BinaryReaderBE(Stream input) : base(input) { }
public BinaryReaderBE(Stream input, Encoding encoding) : base(input, encoding) { }
public BinaryReaderBE(Stream input, Encoding encoding, bool leaveOpen) : base(input, encoding, leaveOpen) { }
public override short ReadInt16() {
FillBuffer(2);
return (short)(m_buffer[1] | (m_buffer[0] << 8));
}
public override ushort ReadUInt16() {
FillBuffer(2);
return (ushort)(m_buffer[1] | (m_buffer[0] << 8));
}
public override int ReadInt32() {
FillBuffer(4);
return m_buffer[3] | (m_buffer[2] << 8) | (m_buffer[1] << 16) | (m_buffer[0] << 24);
}
public override uint ReadUInt32() {
FillBuffer(4);
return (uint)(m_buffer[3] | (m_buffer[2] << 8) | (m_buffer[1] << 16) | (m_buffer[0] << 24));
}
public override long ReadInt64() {
FillBuffer(8);
uint num = (uint)(m_buffer[7] | (m_buffer[6] << 8) | (m_buffer[5] << 16) | (m_buffer[4] << 24));
uint num2 = (uint)(m_buffer[3] | (m_buffer[2] << 8) | (m_buffer[1] << 16) | (m_buffer[0] << 24));
return (long)(((ulong)num2 << 32) | num);
}
public override ulong ReadUInt64() {
FillBuffer(8);
uint num = (uint)(m_buffer[7] | (m_buffer[6] << 8) | (m_buffer[5] << 16) | (m_buffer[4] << 24));
uint num2 = (uint)(m_buffer[3] | (m_buffer[2] << 8) | (m_buffer[1] << 16) | (m_buffer[0] << 24));
return ((ulong)num2 << 32) | num;
}
protected new void FillBuffer(int numBytes) {
if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) {
throw new ArgumentOutOfRangeException("numBytes", "Requested numBytes is larger than the internal buffer size");
}
int num = 0, num2;
if (BaseStream == null) {
throw new IOException("File not open");
}
if (numBytes == 1) {
num2 = BaseStream.ReadByte();
if (num2 == -1) {
throw new EndOfStreamException("The end of the stream is reached before numBytes could be read");
}
m_buffer[0] = (byte)num2;
return;
}
do {
num2 = BaseStream.Read(m_buffer, num, numBytes - num);
if (num2 == 0) {
throw new EndOfStreamException("The end of the stream is reached before numBytes could be read");
}
num += num2;
}
while (num < numBytes);
}
}
}

View File

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

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

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Cryville.Common.Pdt {
/// <summary>
@@ -104,7 +105,7 @@ namespace Cryville.Common.Pdt {
else if (i is PdtInstruction.PushVariable) {
i.Execute(this);
var frame = _stack[_framecount - 1];
if (frame.Type != PdtInternalType.Undefined) {
if (frame.Type != PdtInternalType.Undefined && frame.Type != PdtInternalType.Error) {
_rip = il.AddAfter(_rip, new PdtInstruction.PushConstant(frame.Type, _mem, frame.Offset, frame.Length));
il.Remove(_rip.Previous);
}
@@ -147,10 +148,10 @@ namespace Cryville.Common.Pdt {
_goffset += value.Length;
}
}
internal unsafe void PushVariable(int name) {
internal unsafe void PushVariable(int name, bool forced) {
fixed (StackFrame* frame = &_stack[_framecount++]) {
byte[] value;
GetVariable(name, out frame->Type, out value);
GetVariable(name, forced, out frame->Type, out value);
frame->Offset = _goffset;
frame->Length = value.Length;
Array.Copy(value, 0, _mem, _goffset, value.Length);
@@ -161,16 +162,17 @@ namespace Cryville.Common.Pdt {
/// Gets a variable of the specified name.
/// </summary>
/// <param name="name">The name of the variable.</param>
/// <param name="forced">Whether to produce an error stack instead of an identifier stack if the variable is not found.</param>
/// <param name="type">The type of the variable.</param>
/// <param name="value">The value of the variable.</param>
protected abstract void GetVariable(int name, out int type, out byte[] value);
protected abstract void GetVariable(int name, bool forced, out int type, out byte[] value);
internal void Operate(PdtOperatorSignature sig) {
PdtOperator op;
try { op = GetOperator(sig); }
catch (Exception) {
catch (Exception ex) {
for (int i = 0; i < sig.ParamCount; i++)
DiscardStack();
throw;
throw new EvaluationFailureException(string.Format("Failed to get operator {0}", sig), ex);
}
Operate(op, sig.ParamCount);
}
@@ -222,4 +224,18 @@ namespace Cryville.Common.Pdt {
_goffset -= _stack[--_framecount].Length;
}
}
/// <summary>
/// The exception that is thrown when the evalution of a <see cref="PdtExpression" /> fails.
/// </summary>
public class EvaluationFailureException : Exception {
/// <inheritdoc />
public EvaluationFailureException() : base("Evaluation failed") { }
/// <inheritdoc />
public EvaluationFailureException(string message) : base(message) { }
/// <inheritdoc />
public EvaluationFailureException(string message, Exception innerException) : base(message, innerException) { }
/// <inheritdoc />
protected EvaluationFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@@ -51,13 +51,14 @@ namespace Cryville.Common.Pdt {
}
public class PushVariable : PdtInstruction {
public int Name { get; private set; }
public PushVariable(int name) { Name = name; }
public PushVariable(string name) : this(IdentifierManager.SharedInstance.Request(name)) { }
public bool Forced { get; private set; }
public PushVariable(int name, bool forced = false) { Name = name; Forced = forced; }
public PushVariable(string name, bool forced = false) : this(IdentifierManager.SharedInstance.Request(name)) { Forced = forced; }
internal override void Execute(PdtEvaluatorBase etor) {
etor.PushVariable(Name);
etor.PushVariable(Name, Forced);
}
public override string ToString() {
return string.Format("pushv {0}", IdentifierManager.SharedInstance.Retrieve(Name));
return string.Format(Forced ? "pushv ?{0}" : "pushv {0}", IdentifierManager.SharedInstance.Retrieve(Name));
}
}
public class Operate : PdtInstruction {
@@ -90,7 +91,7 @@ namespace Cryville.Common.Pdt {
}
}
}
public partial class PdtInterpreter<T> {
public partial class PdtInterpreter {
readonly static Dictionary<char, int> OP_PRIORITY = new Dictionary<char, int> {
{ '@', 7 },
{ '*', 6 }, { '/', 6 }, { '%', 6 },
@@ -239,7 +240,11 @@ namespace Cryville.Common.Pdt {
if (defs.TryGetValue(buf.Value.Value, out def)) {
foreach (var i in def.Instructions) ins.AddLast(i);
}
else ins.AddLast(new PdtInstruction.PushVariable(buf.Value.Value));
else {
var name = buf.Value.Value;
if (name[0] == '?') ins.AddLast(new PdtInstruction.PushVariable(name.Substring(1), true));
else ins.AddLast(new PdtInstruction.PushVariable(name));
}
buf = null;
TryPushAdjMul(ins, ref flag);
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
@@ -8,8 +9,7 @@ namespace Cryville.Common.Pdt {
/// <summary>
/// Interpreter for Property Definition Tree (PDT) file format.
/// </summary>
/// <typeparam name="T">The object type represented by the PDT.</typeparam>
public partial class PdtInterpreter<T> {
public partial class PdtInterpreter {
/// <summary>
/// The character category map.
/// </summary>
@@ -32,7 +32,7 @@ namespace Cryville.Common.Pdt {
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0001, 0x0080, 0x0100, 0x0000, 0x0030, 0x0080, 0x0080, 0x0000, 0x0200, 0x0400, 0x0080, 0x0080, 0x0080, 0x0080, 0x0040, 0x0080,
0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x1000, 0x1800, 0x0080, 0x0080, 0x0080, 0x0000,
0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x0050, 0x1000, 0x1800, 0x0080, 0x0080, 0x0080, 0x0030,
0x0080, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,
0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0000, 0x0000, 0x0000, 0x0000, 0x0030,
0x0000, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,
@@ -44,34 +44,35 @@ namespace Cryville.Common.Pdt {
/// </summary>
/// <param name="src">The source string.</param>
/// <returns>The interpreted object.</returns>
public static T Interpret(string src) {
return Interpret(src, BinderAttribute.CreateBinderOfType(typeof(T)));
public static T Interpret<T>(string src) {
return Interpret<T>(src, BinderAttribute.CreateBinderOfType(typeof(T)));
}
/// <summary>
/// Interprets a source string to an object of type <typeparamref name="T" /> with a binder.
/// Interprets a source string to an object of type <typeparamref name="T"/> with a binder.
/// </summary>
/// <param name="src">The source string.</param>
/// <param name="binder">The binder.</param>
/// <returns>The interpreted object.</returns>
public static T Interpret(string src, Binder binder) {
return new PdtInterpreter<T>(src, binder).Interpret();
public static T Interpret<T>(string src, Binder binder) {
return (T)new PdtInterpreter(src, typeof(T), binder).Interpret();
}
readonly string _src;
public string Source { get; private set; }
readonly Type _type;
readonly Binder _binder;
protected int Position { get; private set; }
public int Position { get; private set; }
#pragma warning disable IDE1006
protected char cc { get { return _src[Position]; } }
protected char cc { get { return Source[Position]; } }
protected int ct { get { return cm[cc]; } }
protected string tokenb(int flag) { // Token Whitelist
int sp = Position;
while ((ct & flag) == 0) Position++;
return _src.Substring(sp, Position - sp);
return Source.Substring(sp, Position - sp);
}
protected string tokenw(int flag) { // Token Whitelist
int sp = Position;
while ((ct & flag) != 0) Position++;
return _src.Substring(sp, Position - sp);
return Source.Substring(sp, Position - sp);
}
protected void ws() {
while ((ct & 0x0001) != 0) Position++;
@@ -97,7 +98,7 @@ namespace Cryville.Common.Pdt {
Position++;
} while (ct != 0x0100);
Position++;
return Regex.Replace(_src.Substring(sp + 1, Position - sp - 2), @"\\(.)", "$1");
return Regex.Replace(Source.Substring(sp + 1, Position - sp - 2), @"\\(.)", "$1");
}
protected PdtExpression GetExp() {
var ins = new LinkedList<PdtInstruction>();
@@ -108,23 +109,30 @@ namespace Cryville.Common.Pdt {
readonly Dictionary<string, PdtExpression> defs = new Dictionary<string, PdtExpression>();
/// <summary>
/// Creates an instance of the <see cref="PdtInterpreter{T}" /> class.
/// Creates an instance of the <see cref="PdtInterpreter" /> class.
/// </summary>
/// <param name="src">The source string.</param>
/// <param name="type">The destination type.</param>
/// <param name="binder">The binder. May be <c>null</c>.</param>
public PdtInterpreter(string src, Binder binder) {
_src = src;
public PdtInterpreter(string src, Type type, Binder binder) {
Source = src;
_type = type;
_binder = binder;
if (_binder == null)
_binder = BinderAttribute.CreateBinderOfType(typeof(T));
_binder = BinderAttribute.CreateBinderOfType(_type);
}
/// <summary>
/// Interprets the source to an object of type <typeparamref name="T" />.
/// Interprets the source to an object.
/// </summary>
/// <returns>The interpreted object.</returns>
public T Interpret() {
InterpretDirectives();
return (T)InterpretObject(typeof(T));
public object Interpret() {
try {
InterpretDirectives();
return InterpretObject(_type);
}
catch (Exception ex) {
throw new PdtParsingException(this, ex);
}
}
void InterpretDirectives() {
bool flag = false;
@@ -229,4 +237,36 @@ namespace Cryville.Common.Pdt {
return tokenb(0x1000).Trim();
}
}
/// <summary>
/// The exception that is thrown when the interpretation of a PDT fails.
/// </summary>
public class PdtParsingException : Exception {
public PdtParsingException(PdtInterpreter interpreter) : this(interpreter, null) { }
public PdtParsingException(PdtInterpreter interpreter, Exception innerException)
: base(GenerateMessage(interpreter, innerException), innerException) { }
static string GenerateMessage(PdtInterpreter interpreter, Exception innerException) {
string src = interpreter.Source;
int pos = interpreter.Position;
if (pos >= src.Length) return "Failed to interpret the PDT: There are some missing or redundant tokens";
int lineStartPos = src.LastIndexOf('\n', pos) + 1;
int previewStartPos = src.LastIndexOf('\n', pos, 64);
if (previewStartPos == -1) {
previewStartPos = pos - 64;
if (previewStartPos < 0) previewStartPos = 0;
}
else previewStartPos++;
int previewEndPos = src.IndexOf('\n', pos, 64);
if (previewEndPos == -1) {
previewEndPos = pos + 64;
if (previewEndPos > src.Length) previewEndPos = src.Length;
}
return string.Format(
"Failed to interpret the PDT at line {0}, position {1}: {2}\n{3}",
src.Take(interpreter.Position).Count(c => c == '\n') + 1,
pos - lineStartPos + 1,
innerException == null ? "Unknown error" : innerException.Message,
src.Substring(previewStartPos, previewEndPos - previewStartPos)
);
}
}
}

View File

@@ -19,7 +19,8 @@ namespace Cryville.Common.Pdt {
/// <returns>The operand at the specified index.</returns>
/// <exception cref="IndexOutOfRangeException"><paramref name="index" /> is not less than <see cref="LoadedOperandCount" /> or less than 0.</exception>
protected PdtVariableMemory GetOperand(int index) {
if (index >= LoadedOperandCount || index < 0) throw new IndexOutOfRangeException();
if (index >= LoadedOperandCount || index < 0)
throw new ArgumentOutOfRangeException("index");
int i = index + _loadindex;
return _operands[i];
}
@@ -33,11 +34,9 @@ namespace Cryville.Common.Pdt {
_operands = new PdtVariableMemory[pc];
}
PdtEvaluatorBase _etor;
bool _failure = false;
bool _rfreq = true;
internal void Begin(PdtEvaluatorBase etor) {
_etor = etor;
_failure = false;
_loadindex = ParamCount;
}
internal void LoadOperand(PdtVariableMemory mem) {
@@ -49,13 +48,9 @@ namespace Cryville.Common.Pdt {
_rfreq = false;
try { Execute(); } catch (Exception ex) {
if (_rfreq) _etor.DiscardStack();
throw new InvalidOperationException("Evaluation failed", ex);
throw new EvaluationFailureException("Evaluation failed", ex);
}
if (_failure) {
if (_rfreq) _etor.DiscardStack();
throw new InvalidOperationException("Evaluation failed");
}
if (!_rfreq && !noset) throw new InvalidOperationException("Return frame not set");
if (!_rfreq && !noset) throw new EvaluationFailureException("Return frame not set");
}
/// <summary>
/// Executes the operator.
@@ -69,10 +64,7 @@ namespace Cryville.Common.Pdt {
/// <returns>The return frame.</returns>
/// <exception cref="InvalidOperationException">The return frame has already been requested.</exception>
protected PdtVariableMemory GetReturnFrame(int type, int len) {
if (_rfreq) {
_failure = true;
throw new InvalidOperationException("Return frame already requested");
}
if (_rfreq) throw new InvalidOperationException("Return frame requested twice");
_rfreq = true;
return _etor.StackAlloc(type, _prmem, len);
}

View File

@@ -4,7 +4,7 @@ namespace Cryville.Common.Pdt {
/// <summary>
/// Span on the memory of a <see cref="PdtEvaluatorBase" />.
/// </summary>
public unsafe struct PdtVariableMemory {
public unsafe struct PdtVariableMemory : IEquatable<PdtVariableMemory> {
readonly byte* _ptr;
/// <summary>
/// The length of the span.
@@ -46,6 +46,14 @@ namespace Cryville.Common.Pdt {
for (int i = 0; i < length; i++)
dest[destOffset + i] = _ptr[i];
}
/// <inheritdoc />
public bool Equals(PdtVariableMemory obj) {
if (Type != obj.Type || Length != obj.Length) return false;
for (int i = 0; i < Length; i++) {
if (*(_ptr + i) != *(obj._ptr + i)) return false;
}
return true;
}
/// <summary>
/// Gets the memory of the span as a number.
/// </summary>

View File

@@ -145,7 +145,7 @@ namespace Cryville.Common {
/// <returns>An array containing all the subclasses of the type in the current app domain.</returns>
public static Type[] GetSubclassesOf<T>() where T : class {
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
IEnumerable<Type> r = new List<Type>();
IEnumerable<Type> r = Enumerable.Empty<Type>();
foreach (var a in assemblies)
r = r.Concat(a.GetTypes().Where(
t => t.IsClass

View File

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

View File

@@ -4,7 +4,19 @@ using UnityEngine;
namespace Cryville.Common.Unity.Input {
public delegate void InputEventDelegate(InputIdentifier id, InputVector vec);
public abstract class InputHandler : IDisposable {
public event InputEventDelegate OnInput;
InputEventDelegate m_onInput;
public event InputEventDelegate OnInput {
add {
if (m_onInput == null) Activate();
m_onInput -= value;
m_onInput += value;
}
remove {
if (m_onInput == null) return;
m_onInput -= value;
if (m_onInput == null) Deactivate();
}
}
~InputHandler() {
Dispose(false);
@@ -14,26 +26,15 @@ namespace Cryville.Common.Unity.Input {
GC.SuppressFinalize(this);
}
public bool Activated { get; private set; }
public void Activate() {
if (Activated) return;
Activated = true;
ActivateImpl();
}
protected abstract void ActivateImpl();
public void Deactivate() {
if (!Activated) return;
Activated = false;
DeactivateImpl();
}
protected abstract void DeactivateImpl();
protected abstract void Activate();
protected abstract void Deactivate();
public abstract void Dispose(bool disposing);
public abstract bool IsNullable(int type);
public abstract byte GetDimension(int type);
public abstract string GetTypeName(int type);
public abstract double GetCurrentTimestamp();
protected void Feed(int type, int id, InputVector vec) {
var del = OnInput;
var del = m_onInput;
if (del != null) del(new InputIdentifier { Source = new InputSource { Handler = this, Type = type }, Id = id }, vec);
}
}

View File

@@ -4,28 +4,22 @@ using System.Reflection;
namespace Cryville.Common.Unity.Input {
public class InputManager {
static readonly List<Type> HandlerRegistries = new List<Type> {
static readonly HashSet<Type> HandlerRegistries = new HashSet<Type> {
typeof(WindowsPointerHandler),
typeof(UnityKeyHandler<UnityKeyboardReceiver>),
typeof(UnityKeyHandler<UnityMouseButtonReceiver>),
typeof(UnityMouseHandler),
typeof(UnityTouchHandler),
};
readonly List<InputHandler> _handlers = new List<InputHandler>();
readonly HashSet<InputHandler> _handlers = new HashSet<InputHandler>();
readonly Dictionary<Type, InputHandler> _typemap = new Dictionary<Type, InputHandler>();
readonly Dictionary<InputHandler, double> _timeOrigins = new Dictionary<InputHandler, double>();
readonly object _lock = new object();
readonly Dictionary<InputIdentifier, InputVector> _vectors = new Dictionary<InputIdentifier, InputVector>();
readonly List<InputEvent> _events = new List<InputEvent>();
public InputManager() {
foreach (var t in HandlerRegistries) {
try {
if (!typeof(InputHandler).IsAssignableFrom(t)) continue;
var h = (InputHandler)ReflectionHelper.InvokeEmptyConstructor(t);
_typemap.Add(t, h);
h.OnInput += OnInput;
_handlers.Add(h);
_timeOrigins.Add(h, 0);
Logger.Log("main", 1, "Input", "Initialized {0}", ReflectionHelper.GetSimpleName(t));
}
catch (TargetInvocationException ex) {
@@ -36,49 +30,8 @@ namespace Cryville.Common.Unity.Input {
public InputHandler GetHandler(string name) {
return _typemap[Type.GetType(name)];
}
public void Activate() {
lock (_lock) {
_events.Clear();
}
foreach (var h in _handlers) h.Activate();
}
public void SyncTime(double time) {
foreach (var h in _handlers) {
_timeOrigins[h] = time - h.GetCurrentTimestamp();
}
}
public void Deactivate() {
foreach (var h in _handlers) h.Deactivate();
}
void OnInput(InputIdentifier id, InputVector vec) {
lock (_lock) {
double timeOrigin = _timeOrigins[id.Source.Handler];
vec.Time += timeOrigin;
InputVector vec0;
if (_vectors.TryGetValue(id, out vec0)) {
_events.Add(new InputEvent {
Id = id,
From = vec0,
To = vec,
});
if (vec.IsNull) _vectors.Remove(id);
else _vectors[id] = vec;
}
else {
_events.Add(new InputEvent {
Id = id,
From = new InputVector(vec.Time),
To = vec,
});
_vectors.Add(id, vec);
}
}
}
public void EnumerateEvents(Action<InputEvent> cb) {
lock (_lock) {
foreach (var ev in _events) cb(ev);
_events.Clear();
}
public void EnumerateHandlers(Action<InputHandler> cb) {
foreach (var h in _handlers) cb(h);
}
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
namespace Cryville.Common.Unity.Input {
public class SimpleInputConsumer {
readonly InputManager _manager;
readonly object _lock = new object();
readonly Dictionary<InputIdentifier, InputVector> _vectors = new Dictionary<InputIdentifier, InputVector>();
readonly List<InputEvent> _events = new List<InputEvent>();
public SimpleInputConsumer(InputManager manager) { _manager = manager; }
public void Activate() {
lock (_lock) {
_events.Clear();
}
_manager.EnumerateHandlers(h => h.OnInput += OnInput);
}
public void Deactivate() {
_manager.EnumerateHandlers(h => h.OnInput -= OnInput);
}
protected void OnInput(InputIdentifier id, InputVector vec) {
lock (_lock) {
InputVector vec0;
if (_vectors.TryGetValue(id, out vec0)) {
_events.Add(new InputEvent {
Id = id,
From = vec0,
To = vec,
});
if (vec.IsNull) _vectors.Remove(id);
else _vectors[id] = vec;
}
else {
_events.Add(new InputEvent {
Id = id,
From = new InputVector(vec.Time),
To = vec,
});
_vectors.Add(id, vec);
}
}
}
public void EnumerateEvents(Action<InputEvent> cb) {
lock (_lock) {
foreach (var ev in _events) cb(ev);
_events.Clear();
}
}
}
}

View File

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

View File

@@ -9,19 +9,19 @@ namespace Cryville.Common.Unity.Input {
public UnityKeyHandler() { }
protected override void ActivateImpl() {
protected override void Activate() {
receiver = new GameObject("__keyrecv__");
recvcomp = receiver.AddComponent<T>();
recvcomp.SetCallback(Feed);
}
protected override void DeactivateImpl() {
protected override void Deactivate() {
if (receiver) GameObject.Destroy(receiver);
}
public override void Dispose(bool disposing) {
if (disposing) {
DeactivateImpl();
Deactivate();
}
}
@@ -44,7 +44,7 @@ namespace Cryville.Common.Unity.Input {
public abstract class UnityKeyReceiver<T> : MonoBehaviour where T : UnityKeyReceiver<T> {
protected Action<int, int, InputVector> Callback;
protected readonly List<int> Keys = new List<int>();
protected readonly HashSet<int> Keys = new HashSet<int>();
public void SetCallback(Action<int, int, InputVector> h) {
Callback = h;
}

View File

@@ -12,35 +12,35 @@ namespace Cryville.Common.Unity.Input {
}
}
protected override void ActivateImpl() {
protected override void Activate() {
receiver = new GameObject("__mouserecv__");
receiver.AddComponent<UnityMouseReceiver>().SetHandler(this);
}
protected override void DeactivateImpl() {
protected override void Deactivate() {
if (receiver) GameObject.Destroy(receiver);
}
public override void Dispose(bool disposing) {
if (disposing) {
DeactivateImpl();
Deactivate();
}
}
public override bool IsNullable(int type) {
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
if (type != 0) throw new ArgumentOutOfRangeException("type");
return false;
}
public override byte GetDimension(int type) {
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
if (type != 0) throw new ArgumentOutOfRangeException("type");
return 2;
}
public override string GetTypeName(int type) {
switch (type) {
case 0: return "Mouse Position";
default: throw new ArgumentOutOfRangeException(nameof(type));
default: throw new ArgumentOutOfRangeException("type");
}
}

View File

@@ -12,35 +12,35 @@ namespace Cryville.Common.Unity.Input {
}
}
protected override void ActivateImpl() {
protected override void Activate() {
receiver = new GameObject("__touchrecv__");
receiver.AddComponent<UnityPointerReceiver>().SetHandler(this);
}
protected override void DeactivateImpl() {
protected override void Deactivate() {
if (receiver) GameObject.Destroy(receiver);
}
public override void Dispose(bool disposing) {
if (disposing) {
DeactivateImpl();
Deactivate();
}
}
public override bool IsNullable(int type) {
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
if (type != 0) throw new ArgumentOutOfRangeException("type");
return true;
}
public override byte GetDimension(int type) {
if (type != 0) throw new ArgumentOutOfRangeException(nameof(type));
if (type != 0) throw new ArgumentOutOfRangeException("type");
return 2;
}
public override string GetTypeName(int type) {
switch (type) {
case 0: return "Touch";
default: throw new ArgumentOutOfRangeException(nameof(type));
default: throw new ArgumentOutOfRangeException("type");
}
}

View File

@@ -31,6 +31,8 @@ namespace Cryville.Common.Unity.Input {
public WindowsPointerHandler() {
if (Instance != null)
throw new InvalidOperationException("WindowsPointerHandler already created");
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
throw new NotSupportedException("Windows pointer is not supported on this device");
Instance = this;
usePointerMessage = true;
@@ -61,7 +63,7 @@ namespace Cryville.Common.Unity.Input {
public const int TABLET_DISABLE_PENBARRELFEEDBACK = 0x00000010;
public const int TABLET_DISABLE_FLICKS = 0x00010000;
protected override void ActivateImpl() {
protected override void Activate() {
newWndProc = WndProc;
newWndProcPtr = Marshal.GetFunctionPointerForDelegate(newWndProc);
oldWndProcPtr = SetWindowLongPtr(hMainWindow, -4, newWndProcPtr);
@@ -77,7 +79,7 @@ namespace Cryville.Common.Unity.Input {
);
}
protected override void DeactivateImpl() {
protected override void Deactivate() {
if (pressAndHoldAtomID != 0) {
NativeMethods.RemoveProp(hMainWindow, PRESS_AND_HOLD_ATOM);
NativeMethods.GlobalDeleteAtom(pressAndHoldAtomID);
@@ -142,9 +144,11 @@ namespace Cryville.Common.Unity.Input {
}
public override void Dispose(bool disposing) {
DeactivateImpl();
if (usePointerMessage)
NativeMethods.EnableMouseInPointer(false);
if (disposing) {
Deactivate();
if (usePointerMessage)
NativeMethods.EnableMouseInPointer(false);
}
Instance = null;
}

View File

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

View File

@@ -0,0 +1,66 @@
using Cryville.Common.Font;
using System;
using System.Collections.Generic;
using System.Reflection;
using TMPro;
using UnityEngine;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.TextCore.Text;
namespace Cryville.Common.Unity.UI {
[RequireComponent(typeof(TextMeshProUGUI))]
public class TMPAutoFont : MonoBehaviour {
public static Shader DefaultShader;
public static FontMatcher FontMatcher;
public static int MaxFallbackCount = 4;
static FontAsset _font;
TextMeshProUGUI _text;
[SerializeField]
Shader m_shader;
void Awake() {
if (FontMatcher == null) return;
_text = GetComponent<TextMeshProUGUI>();
if (_font == null) {
foreach (var typeface in FontMatcher.MatchScript(null, true)) {
try {
var ifont = CreateFontAsset(typeface.File.FullName, typeface.IndexInFile);
if (m_shader) ifont.material.shader = m_shader;
else if (DefaultShader) ifont.material.shader = DefaultShader;
if (_font == null) {
_font = ifont;
if (MaxFallbackCount <= 0) break;
}
else {
if (_font.fallbackFontAssetTable == null)
_font.fallbackFontAssetTable = new List<FontAsset>();
_font.fallbackFontAssetTable.Add(ifont);
if (_font.fallbackFontAssetTable.Count >= MaxFallbackCount) break;
}
}
catch (Exception) { }
}
}
_text.font = _font;
}
static MethodInfo _methodCreateFontAsset;
static object[] _paramsCreateFontAsset = new object[] { null, null, 90, 9, GlyphRenderMode.SDFAA, 1024, 1024, Type.Missing, Type.Missing };
static FontAsset CreateFontAsset(string path, int index) {
if (_methodCreateFontAsset == null) {
_methodCreateFontAsset = typeof(FontAsset).GetMethod(
"CreateFontAsset", BindingFlags.Static | BindingFlags.NonPublic, null,
new Type[] {
typeof(string), typeof(int), typeof(int), typeof(int),
typeof(GlyphRenderMode), typeof(int), typeof(int),
typeof(AtlasPopulationMode), typeof(bool)
},
null
);
}
_paramsCreateFontAsset[0] = path;
_paramsCreateFontAsset[1] = index;
return (FontAsset)_methodCreateFontAsset.Invoke(null, _paramsCreateFontAsset);
}
}
}

View File

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

View File

@@ -1,15 +1,17 @@
using UnityEngine;
using System.Collections.Generic;
using UnityEngine;
namespace Cryville.Crtr {
public class Anchor {
bool _opened;
public bool Opened { get { return _opened; } }
public Transform Transform { get; set; }
public void Open() {
_opened = true;
}
public void Close() {
_opened = false;
public int Name { get; private set; }
public Transform Transform { get; private set; }
public SkinContext SkinContext { get; private set; }
public Dictionary<int, PropSrc> PropSrcs { get; private set; }
public Anchor(int name, Transform transform, int propSrcCount = 0) {
Name = name;
Transform = transform;
if (propSrcCount > 0) PropSrcs = new Dictionary<int, PropSrc>(propSrcCount);
SkinContext = new SkinContext(transform, PropSrcs);
}
}
}

View File

@@ -1,4 +1,5 @@
using UnityEngine;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Cryville.Crtr.Browsing {
@@ -10,14 +11,14 @@ namespace Cryville.Crtr.Browsing {
private bool _dir;
private Image _icon;
private Text _title;
private Text _desc;
private TMP_Text _title;
private TMP_Text _desc;
#pragma warning disable IDE0051
void Awake() {
_icon = transform.Find("__content__/Icon").GetComponent<Image>();
_title = transform.Find("__content__/Texts/Title/__text__").GetComponent<Text>();
_desc = transform.Find("__content__/Texts/Description/__text__").GetComponent<Text>();
_title = transform.Find("__content__/Texts/Title/__text__").GetComponent<TMP_Text>();
_desc = transform.Find("__content__/Texts/Description/__text__").GetComponent<TMP_Text>();
}
void OnDestroy() {
if (meta.Icon != null) meta.Icon.Cancel();

View File

@@ -1,6 +1,7 @@
using Cryville.Common;
using Cryville.Common.Unity.UI;
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
@@ -18,8 +19,8 @@ namespace Cryville.Crtr.Browsing {
DockOccupiedRatioLayoutGroup _outerContentGroup;
Transform _content;
Image _cover;
Text _title;
Text _desc;
TMP_Text _title;
TMP_Text _desc;
protected override void Awake() {
base.Awake();
@@ -28,8 +29,8 @@ namespace Cryville.Crtr.Browsing {
_outerContentGroup = _outerContent.GetComponent<DockOccupiedRatioLayoutGroup>();
_content = _outerContent.transform.Find("__content__");
_cover = _content.Find("Cover").GetComponent<Image>();
_title = _content.Find("Texts/Title").GetComponent<Text>();
_desc = _content.Find("Texts/Description").GetComponent<Text>();
_title = _content.Find("Texts/Title").GetComponent<TMP_Text>();
_desc = _content.Find("Texts/Description").GetComponent<TMP_Text>();
}
void OnDestroy() {
if (_data.Cover != null) _data.Cover.Cancel();

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

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

View File

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

View File

@@ -17,6 +17,8 @@ namespace Cryville.Crtr.Browsing {
static readonly Dictionary<string, List<ResourceConverter>> converters
= new Dictionary<string, List<ResourceConverter>>();
static readonly Dictionary<string, string> localRes
= new Dictionary<string, string>();
public LegacyResourceManager(string rootPath) {
_rootPath = rootPath;
@@ -25,13 +27,35 @@ namespace Cryville.Crtr.Browsing {
static LegacyResourceManager() {
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (var type in asm.GetTypes()) {
if (type.IsSubclassOf(typeof(ResourceConverter))) {
var converter = (ResourceConverter)Activator.CreateInstance(type);
foreach (var f in converter.GetSupportedFormats()) {
if (!converters.ContainsKey(f))
converters.Add(f, new List<ResourceConverter> { converter });
else converters[f].Add(converter);
if (!type.IsSubclassOf(typeof(ExtensionInterface))) continue;
var ext = (ExtensionInterface)Activator.CreateInstance(type);
try {
var cs = ext.GetResourceConverters();
if (cs != null) {
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() {
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

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

View File

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

View File

@@ -73,6 +73,9 @@ namespace Cryville.Crtr.Browsing {
Application.LoadLevelAdditive("Play");
#endif
GameObject.Find("/Master").GetComponent<Master>().HideMenu();
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
DiscordController.Instance.SetPlaying(string.Format("{0} - {1}", detail.Meta.song.name, detail.Meta.name), detail.Meta.length);
#endif
}
public void OpenConfig(int id, ChartDetail detail) {

View File

@@ -9,14 +9,19 @@ using System.Text.RegularExpressions;
namespace Cryville.Crtr {
[JsonConverter(typeof(BeatTimeConverter))]
public struct BeatTime {
public struct BeatTime : IComparable<BeatTime>, IEquatable<BeatTime> {
[JsonConstructor()]
public BeatTime(int _b, int _n, int _d) {
b = _b;
n = _n;
d = _d;
}
public BeatTime(int _n, int _d) {
b = _n / _d;
n = _n % _d;
d = _d;
}
[JsonIgnore]
public int b;
@@ -25,6 +30,36 @@ namespace Cryville.Crtr {
[JsonIgnore]
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 {
@@ -56,7 +91,7 @@ namespace Cryville.Crtr {
[JsonIgnore]
public float BeatPosition {
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 {
get {
if (endtime == null) return BeatPosition;
return endtime.Value.b + endtime.Value.n / (float)endtime.Value.d + BeatOffset;
return (float)endtime.Value.Decimal + BeatOffset;
}
}
@@ -95,20 +130,11 @@ namespace Cryville.Crtr {
get { return Duration > 0; }
}
private InstantEvent attev = null;
private ReleaseEvent relev = null;
[JsonIgnore]
public InstantEvent AttackEvent {
public ReleaseEvent ReleaseEvent {
get {
if (attev == null) attev = new InstantEvent(this);
return attev;
}
}
private InstantEvent relev = null;
[JsonIgnore]
public InstantEvent ReleaseEvent {
get {
if (relev == null) relev = new InstantEvent(this, true);
if (relev == null) relev = new ReleaseEvent(this);
return relev;
}
}
@@ -135,18 +161,12 @@ namespace Cryville.Crtr {
}
}
public class InstantEvent : ChartEvent {
public class ReleaseEvent : ChartEvent {
public readonly ChartEvent Original;
public bool IsRelease;
public InstantEvent(ChartEvent orig, bool release = false) {
IsRelease = release;
if (orig != null) {
Original = orig;
time = orig.time;
if (IsRelease)
BeatOffset = orig.Duration;
}
public ReleaseEvent(ChartEvent orig) {
Original = orig;
time = orig.endtime;
}
public override int Priority {
@@ -157,6 +177,13 @@ namespace Cryville.Crtr {
}
public abstract class EventContainer : ChartEvent {
public List<Chart.Motion> motions = new List<Chart.Motion>();
[JsonIgnore]
public Clip Clip { get; private set; }
public EventContainer() {
SubmitPropOp("clip", new PropOp.Clip(v => Clip = v));
}
[JsonIgnore]
public virtual IEnumerable<ChartEvent> Events {
@@ -168,7 +195,7 @@ namespace Cryville.Crtr {
public virtual EventList GetEventsOfType(string type) {
switch (type) {
case "motions": return new EventList<Chart.Motion>(motions);
default: throw new ArgumentException("Unknown type");
default: throw new ArgumentException(string.Format("Unknown event type \"{0}\"", type));
}
}
}
@@ -275,6 +302,8 @@ namespace Cryville.Crtr {
#pragma warning restore IDE1006
private void LoadFromString(string s) {
if (RelativeNode != null || AbsoluteValue != null)
throw new InvalidOperationException("The motion property can only be set at initialization");
Match m = Regex.Match(s, @"^(.+?)(#(\d+))?(@(.+?))?(\^(.+?))?(\*(.+?))?(:(.+))?$");
if (!m.Success) throw new ArgumentException("Invalid motion string format");
name = new Identifier(m.Groups[1].Value);
@@ -296,6 +325,10 @@ namespace Cryville.Crtr {
else {
AbsoluteValue = Vector.Construct(registry.Type, m.Groups[11].Value);
}
SubmitPropSrc("value", VectorSrc.Construct(() => {
if (RelativeNode != null) return RelativeNode.Value;
else return AbsoluteValue;
}));
}
public override string ToString() {
@@ -347,10 +380,6 @@ namespace Cryville.Crtr {
}
public Motion() {
SubmitPropSrc("value", new VectorSrc(() => {
if (RelativeNode != null) return RelativeNode.Value;
else return AbsoluteValue;
}));
SubmitPropOp("motion", new PropOp.String(v => motion = v));
SubmitPropOp("name", new PropOp.Identifier(v => {
var n = new Identifier(v);

View File

@@ -14,22 +14,12 @@ namespace Cryville.Crtr {
chart = _chart;
}
public override string TypeName {
get {
return "chart";
}
}
public override string TypeName { get { return "chart"; } }
public override void PreInit() {
base.PreInit();
}
public override void Dispose() {
if (Disposed) return;
base.Dispose();
foreach (var s in sounds) s.Dispose();
}
public override void Update(ContainerState s, StampedEvent ev) {
base.Update(s, ev);
if (s.CloneType == 16) {
@@ -50,9 +40,14 @@ namespace Cryville.Crtr {
}
}
public override void EndUpdate(ContainerState s) {
base.EndUpdate(s);
public override void EndLogicalUpdate(ContainerState s) {
base.EndLogicalUpdate(s);
// TODO End of chart
}
public override void DisposeAll() {
base.DisposeAll();
foreach (var s in sounds) s.Dispose();
}
}
}

View File

@@ -1,6 +1,7 @@
#define BUILD
using Cryville.Common;
using Cryville.Common.Buffers;
using Cryville.Crtr.Config;
using Cryville.Crtr.Event;
using Newtonsoft.Json;
@@ -8,7 +9,9 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Formatting;
using System.Threading;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
@@ -19,6 +22,7 @@ using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr {
public class ChartPlayer : MonoBehaviour {
#region Fields
Chart chart;
Skin skin;
PdtSkin pskin;
@@ -44,7 +48,9 @@ namespace Cryville.Crtr {
static bool initialized;
static Text logs;
Text status;
TextMeshProUGUI status;
readonly TargetString statusstr = new TargetString();
readonly StringBuffer statusbuf = new StringBuffer();
static Vector2 screenSize;
public static Rect hitRect;
@@ -54,8 +60,8 @@ namespace Cryville.Crtr {
static bool disableGC = true;
static float clippingDist = 1f;
static float renderDist = 6f;
static float renderStep = 0.05f;
public static float actualRenderStep = 0f;
static double renderStep = 0.05;
public static double actualRenderStep = 0;
static bool autoRenderStep = false;
public static float soundOffset = 0;
static float startOffset = 0;
@@ -66,6 +72,7 @@ namespace Cryville.Crtr {
public static PdtEvaluator etor;
InputProxy inputProxy;
#endregion
#region MonoBehaviour
void Start() {
@@ -79,7 +86,7 @@ namespace Cryville.Crtr {
}
OnSettingsUpdate();
status = GameObject.Find("Status").GetComponent<Text>();
status = GameObject.Find("Status").GetComponent<TextMeshProUGUI>();
texHandler = new DownloadHandlerTexture();
#if BUILD
@@ -105,13 +112,12 @@ namespace Cryville.Crtr {
if (texLoader != null) texLoader.Dispose();
if (inputProxy != null) inputProxy.Dispose();
if (texs != null) foreach (var t in texs) Texture.Destroy(t.Value);
Camera.onPostRender -= OnCameraPostRender;
GC.Collect();
}
bool texloaddone;
diag::Stopwatch texloadtimer = new diag::Stopwatch();
bool firstFrame;
int forceSyncFrames;
double atime0;
void Update() {
if (started) GameUpdate();
@@ -123,10 +129,18 @@ namespace Cryville.Crtr {
try {
if (Screen.width != screenSize.x || Screen.height != screenSize.y)
throw new InvalidOperationException("Window resized while playing");
float dt = firstFrame
? 1f / Application.targetFrameRate
: Time.deltaTime;
firstFrame = false;
double dt, step;
if (forceSyncFrames != 0) {
forceSyncFrames--;
double target = Game.AudioClient.Position - atime0;
dt = target - cbus.Time;
step = autoRenderStep ? 1f / Application.targetFrameRate : renderStep;
inputProxy.SyncTime(target);
}
else {
dt = Time.deltaTime;
step = autoRenderStep ? Time.smoothDeltaTime : renderStep;
}
inputProxy.ForceTick();
cbus.ForwardByTime(dt);
bbus.ForwardByTime(dt);
@@ -135,19 +149,16 @@ namespace Cryville.Crtr {
bbus.CopyTo(2, tbus);
bbus.CopyTo(3, nbus);
UnityEngine.Profiling.Profiler.EndSample();
float step = autoRenderStep ? ( firstFrame
? 1f / Application.targetFrameRate
: Time.smoothDeltaTime
) : renderStep;
actualRenderStep = step;
nbus.ForwardStepByTime(clippingDist, step);
nbus.BroadcastEndUpdate();
nbus.EndPreGraphicalUpdate();
nbus.Anchor();
tbus.StripTempEvents();
tbus.ForwardStepByTime(clippingDist, step);
tbus.ForwardStepByTime(renderDist, step);
tbus.BroadcastEndUpdate();
tbus.EndGraphicalUpdate();
UnityEngine.Profiling.Profiler.EndSample();
}
catch (Exception ex) {
@@ -209,7 +220,6 @@ namespace Cryville.Crtr {
}
}
}
string timetext = string.Empty;
void LogUpdate() {
string _logs = logs.text;
Game.MainLogger.Enumerate((level, module, msg) => {
@@ -229,35 +239,45 @@ namespace Cryville.Crtr {
);
});
logs.text = _logs.Substring(Mathf.Max(0, _logs.IndexOf('\n', Mathf.Max(0, _logs.Length - 4096))));
var sttext = string.Format(
"FPS: i{0:0} / s{1:0}\nSMem: {2:N0} / {3:N0}\nIMem: {4:N0} / {5:N0}",
1 / Time.deltaTime,
1 / Time.smoothDeltaTime,
statusbuf.Clear();
statusbuf.AppendFormat(
"FPS: i{0:0} / s{1:0}\nSMem: {2:N0} / {3:N0}\nIMem: {4:N0} / {5:N0}",
1 / Time.deltaTime,
1 / Time.smoothDeltaTime,
#if UNITY_5_6_OR_NEWER
UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong(),
UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong(),
UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong(),
UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong()
UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong(),
UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong(),
UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong(),
UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong()
#else
UnityEngine.Profiling.Profiler.GetMonoUsedSize(),
UnityEngine.Profiling.Profiler.GetMonoHeapSize(),
UnityEngine.Profiling.Profiler.GetTotalAllocatedMemory(),
UnityEngine.Profiling.Profiler.GetTotalReservedMemory()
UnityEngine.Profiling.Profiler.GetMonoUsedSize(),
UnityEngine.Profiling.Profiler.GetMonoHeapSize(),
UnityEngine.Profiling.Profiler.GetTotalAllocatedMemory(),
UnityEngine.Profiling.Profiler.GetTotalReservedMemory()
#endif
);
sttext += timetext;
if (judge != null) sttext += "\n== Scores ==\n" + judge.GetFullFormattedScoreString();
status.text = sttext;
}
void OnCameraPostRender(Camera cam) {
if (!logEnabled) return;
if (started) timetext = string.Format(
"\nSTime: {0:R}\nATime: {1:R}\nITime: {2:R}",
cbus.Time,
Game.AudioClient.Position - atime0,
inputProxy.GetTimestampAverage()
);
else timetext = string.Empty;
if (started) {
statusbuf.AppendFormat(
"\nStates: c{0} / b{1}",
cbus.ActiveStateCount, bbus.ActiveStateCount
);
statusbuf.AppendFormat(
"\nSTime: {0:G17}s {3}\ndATime: {1:+0.0ms;-0.0ms;0} {3}\ndITime: {2:+0.0ms;-0.0ms;0} {3}",
cbus.Time,
(Game.AudioClient.Position - atime0 - cbus.Time) * 1e3,
(inputProxy.GetTimestampAverage() - cbus.Time) * 1e3,
forceSyncFrames != 0 ? "(force sync)" : ""
);
if (judge != null) {
statusbuf.Append("\n== Scores ==\n");
var fullScoreStr = judge.GetFullFormattedScoreString();
statusbuf.Append(fullScoreStr.TrustedAsArray(), 0, fullScoreStr.Length);
}
}
statusstr.Length = statusbuf.Count;
var arr = statusstr.TrustedAsArray();
statusbuf.CopyTo(0, arr, 0, statusbuf.Count);
status.SetText(arr, 0, statusbuf.Count);
}
#endregion
@@ -278,6 +298,9 @@ namespace Cryville.Crtr {
SceneManager.UnloadSceneAsync("Play");
#elif UNITY_5_3_OR_NEWER
SceneManager.UnloadScene("Play");
#endif
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
DiscordController.Instance.SetIdle();
#endif
}
#pragma warning restore IDE1006
@@ -285,7 +308,7 @@ namespace Cryville.Crtr {
bool logEnabled = true;
public void ToggleLogs() {
logs.text = "";
status.text = "";
status.SetText("");
logEnabled = !logEnabled;
}
@@ -308,13 +331,11 @@ namespace Cryville.Crtr {
autoRenderStep = renderStep == 0;
soundOffset = Settings.Default.SoundOffset;
startOffset = Settings.Default.StartOffset;
firstFrame = true;
forceSyncFrames= Settings.Default.ForceSyncFrames;
texloaddone = false;
Game.NetworkTaskWorker.SuspendBackgroundTasks();
Game.AudioSession = Game.AudioSequencer.NewSession();
Camera.onPostRender += OnCameraPostRender;
var hitPlane = new Plane(Vector3.forward, Vector3.zero);
var r0 = Camera.main.ViewportPointToRay(new Vector3(0, 0, 1));
float dist;
@@ -371,8 +392,9 @@ namespace Cryville.Crtr {
texloadtimer.Start();
frames = new Dictionary<string, SpriteFrame>();
texs = new Dictionary<string, Texture2D>();
var skinDir = skinFile.Directory.FullName;
foreach (var f in skin.frames) {
texLoadQueue.Enqueue(Path.Combine(skinFile.Directory.FullName, f));
texLoadQueue.Enqueue(Path.Combine(skinDir, f));
}
}
@@ -427,10 +449,10 @@ namespace Cryville.Crtr {
Logger.Log("main", 1, "Game", "Stopping");
Game.AudioSession = Game.AudioSequencer.NewSession();
inputProxy.Deactivate();
if (cbus != null) { cbus.Dispose(); cbus = null; }
if (bbus != null) { bbus.Dispose(); bbus = null; }
if (tbus != null) { tbus.Dispose(); tbus = null; }
if (nbus != null) { nbus.Dispose(); nbus = null; }
if (tbus != null) { tbus.Dispose(); tbus = null; }
if (bbus != null) { bbus.Dispose(); bbus = null; }
if (cbus != null) { cbus.Dispose(); cbus.DisposeAll(); cbus = null; }
Logger.Log("main", 1, "Game", "Stopped");
}
catch (Exception ex) {
@@ -475,6 +497,7 @@ namespace Cryville.Crtr {
workerTimer = new diag::Stopwatch();
workerTimer.Start();
RMVPool.Prepare();
MotionCachePool.Prepare();
LoadChart(info);
workerTimer.Stop();
Logger.Log("main", 1, "Load/WorkerThread", "Worker thread done ({0}ms)", workerTimer.Elapsed.TotalMilliseconds);
@@ -506,10 +529,10 @@ namespace Cryville.Crtr {
var batcher = new EventBatcher(chart);
batcher.Forward();
cbus = batcher.Batch();
Logger.Log("main", 0, "Load/WorkerThread", "Batched {0} event batches", cbus.events.Count);
LoadSkin(info.skinFile);
Logger.Log("main", 0, "Load/WorkerThread", "Initializing judge and input");
judge = new Judge(pruleset);
etor.ContextJudge = judge;
@@ -528,10 +551,10 @@ namespace Cryville.Crtr {
foreach (var ts in gs.Value.Children) {
ContainerHandler th;
if (ts.Key is Chart.Note) {
th = new NoteHandler(gh, (Chart.Note)ts.Key, pruleset, judge);
th = new NoteHandler((Chart.Note)ts.Key, gh);
}
else {
th = new TrackHandler(gh, (Chart.Track)ts.Key);
th = new TrackHandler((Chart.Track)ts.Key, gh);
}
ts.Value.AttachHandler(th);
}
@@ -541,8 +564,6 @@ namespace Cryville.Crtr {
using (var pbus = cbus.Clone(16)) {
pbus.Forward();
}
Logger.Log("main", 0, "Load/WorkerThread", "Patching events");
cbus.DoPatch();
Logger.Log("main", 0, "Load/WorkerThread", "Cloning states (type 1)");
bbus = cbus.Clone(1, -clippingDist);

View File

@@ -0,0 +1,10 @@
namespace Cryville.Crtr {
public struct Clip {
public float Behind { get; set; }
public float Ahead { get; set; }
public Clip(float behind, float ahead) {
Behind = behind;
Ahead = ahead;
}
}
}

View File

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

View File

@@ -9,6 +9,18 @@ namespace Cryville.Crtr.Components {
protected Vector3? prevpt;
protected Quaternion? prevrot;
protected int vertCount = 0;
Part part = Part.whole;
enum Part {
whole = 0,
idle = 1,
start = 2,
end = 3,
}
public SectionalGameObject() {
SubmitProperty("partial", new PropOp.Boolean(v => part = Part.idle));
SubmitProperty("part", new PropOp.Enum<Part>(v => part = v, v => (Part)v), 2);
}
protected override void OnDestroy() {
mesh.Destroy();
@@ -23,7 +35,7 @@ namespace Cryville.Crtr.Components {
}
public void AppendPoint(Vector3 p, Quaternion r) {
if (prevpt == p && prevrot == r) return;
if (prevpt == p && prevrot == r || ((int)part & 1) == 1) return;
AppendPointInternal(p, r);
// if (!headGenerated) Logger.Log("main", 0, "Skin/Polysec", "{0}", r);
prevpt = p;
@@ -98,25 +110,14 @@ namespace Cryville.Crtr.Components {
public override void Init() {
base.Init();
head.Load();
body.Load();
tail.Load();
mesh.Init(transform);
List<Material> materials = new List<Material>();
if (head.FrameName != null) AddMat(materials, head.FrameName);
if (body.FrameName != null) AddMat(materials, body.FrameName);
if (tail.FrameName != null) AddMat(materials, tail.FrameName);
mesh.Renderer.materials = materials.ToArray();
UpdateZIndex();
}
var mats = mesh.Renderer.materials = new Material[] { mesh.NewMaterial, mesh.NewMaterial, mesh.NewMaterial };
head.Bind(mats[0]);
body.Bind(mats[1]);
tail.Bind(mats[2]);
void AddMat(List<Material> list, string frame) {
var mat = mesh.NewMaterial;
mat.mainTexture = ChartPlayer.frames[frame].Texture;
list.Add(mat);
UpdateZIndex();
}
protected override void OnDestroy() {
@@ -151,15 +152,16 @@ namespace Cryville.Crtr.Components {
List<Vector3> verts;
List<Vector2> uvs;
List<int> trih = null, trib = null, trit = null;
static List<int> _emptyTris = new List<int>();
public override void Seal() {
if (vertCount <= 1 || sumLength == 0) return;
int vcpsec = _shapeLength; // Vertex Count Per Section
float width = GetWidth();
float headLength = 0;
if (head.FrameName != null) headLength = width / head.Ratio;
if (head.Frame != null) headLength = width / head.Ratio;
float tailLength = 0;
if (tail.FrameName != null) tailLength = width / tail.Ratio;
if (tail.Frame != null) tailLength = width / tail.Ratio;
float endLength = headLength + tailLength;
if (sumLength <= endLength) {
// The total length of the two ends is longer than the whole mesh, squeeze the two ends
@@ -187,17 +189,17 @@ namespace Cryville.Crtr.Components {
verts = _vertPool.Rent(vc * vcpsec);
uvs = _uvPool.Rent(vc * vcpsec);
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 (body.FrameName != 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 (head.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); }
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.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 = 3;
m = 0;
mesh.Mesh.SetVertices(verts);
mesh.Mesh.SetUVs(0, uvs);
if (head.FrameName != null) mesh.Mesh.SetTriangles(trih, m++);
if (body.FrameName != null) mesh.Mesh.SetTriangles(trib, m++);
if (tail.FrameName != null) mesh.Mesh.SetTriangles(trit, m++);
mesh.Mesh.SetTriangles(head.Frame == null ? _emptyTris : trih, m++);
mesh.Mesh.SetTriangles(body.Frame == null ? _emptyTris : trib, m++);
mesh.Mesh.SetTriangles(tail.Frame == null ? _emptyTris : trit, m++);
mesh.Mesh.RecalculateNormals();
_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 UnityEngine;
@@ -7,21 +8,21 @@ namespace Cryville.Crtr.Components {
/// <summary>
/// The property operators of the component.
/// </summary>
public Dictionary<string, SkinProperty> Properties { get; private set; }
public Dictionary<int, SkinProperty> Properties { get; private set; }
/// <summary>
/// Submits a property.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="property">The property.</param>
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>
/// Creates a skin component.
/// </summary>
protected SkinComponent() {
Properties = new Dictionary<string, SkinProperty>();
Properties = new Dictionary<int, SkinProperty>();
}
public virtual void Init() { }

View File

@@ -4,13 +4,22 @@ using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr.Components {
public class SpriteInfo {
public string FrameName;
string m_frameName;
public string FrameName {
get {
return m_frameName;
}
set {
m_frameName = value;
Reload();
}
}
public SpriteFrame Frame {
get;
private set;
}
public Rect Rect {
get { return Frame.frame; }
get { return Frame.Frame; }
}
/// <summary>
/// The ratio of width divided by height.
@@ -20,22 +29,39 @@ namespace Cryville.Crtr.Components {
return Rect.width / Rect.height;
}
}
bool _loaded;
Material _mat;
public void Bind(Material mat) {
_loaded = true;
_mat = mat;
Reload();
}
public void Load() {
if (FrameName != null) {
_loaded = true;
Reload();
}
public void Reload() {
if (!_loaded) return;
if (!string.IsNullOrEmpty(FrameName)) {
if (ChartPlayer.frames.ContainsKey(FrameName)) {
Frame = ChartPlayer.frames[FrameName];
}
else {
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;
}
}
}
public class SpritePlane : SpriteBase {
public SpritePlane() {
SubmitProperty("frame", new PropOp.String(v => Frame = v));
SubmitProperty("fit", new PropOp.Enum<FitMode>(v => Fit = v));
SubmitProperty("fit", new PropOp.Enum<FitMode>(v => Fit = v, v => (FitMode)v));
SubmitProperty("opacity", new PropOp.Float(v => Opacity = v));
}
@@ -68,16 +94,11 @@ namespace Cryville.Crtr.Components {
}
protected void OnFrameUpdate() {
if (!mesh.Initialized) return;
if (frameInfo.FrameName == null) {
if (frameInfo.Frame == null) {
mesh.Renderer.enabled = false;
return;
}
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();
UpdateScale();
UpdateZIndex();
@@ -140,8 +161,8 @@ namespace Cryville.Crtr.Components {
}
public override void Init() {
frameInfo.Load();
InternalInit();
frameInfo.Bind(mesh.Renderer.material);
OnFrameUpdate();
UpdateOpacity();
}

View File

@@ -63,13 +63,13 @@ namespace Cryville.Crtr.Components {
case 1: x = _border.x; bx = b.x; break;
case 2: x = _border.y; bx = b.y; break;
case 3: x = 1; bx = 1; break;
default: throw new Exception();
default: throw new NotSupportedException("Built-in resource corrupted");
}
float y;
switch ((int)muv[i].y) {
case 0: y = 0; break;
case 3: y = 1; break;
default: throw new Exception();
default: throw new NotSupportedException("Built-in resource corrupted");
}
uv[i] = frameInfo.Frame.GetUV(x, y);
bx -= 0.5f; y -= 0.5f;

View File

@@ -79,7 +79,7 @@ namespace Cryville.Crtr.Components {
foreach (var f in m_frames) {
f.Value.Load();
if (frameHeight == 0) frameHeight = f.Value.Rect.height;
else if (frameHeight != f.Value.Rect.height) throw new Exception("Inconsistent frame height");
else if (frameHeight != f.Value.Rect.height) throw new Exception("Inconsistent frame height for text component");
var tex = f.Value.Frame.Texture;
if (!meshes.ContainsKey(tex)) {
var m = new MeshWrapper();

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr.Config {
public class ConfigScene : MonoBehaviour {
@@ -19,45 +20,49 @@ namespace Cryville.Crtr.Config {
public Ruleset ruleset;
RulesetConfig _rscfg;
void Awake() {
ChartPlayer.etor = new PdtEvaluator();
FileInfo file = new FileInfo(
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
);
if (!file.Exists) {
Popup.Create("Ruleset for the chart not found\nMake sure you have imported the ruleset");
ReturnToMenu();
return;
}
DirectoryInfo dir = file.Directory;
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
MissingMemberHandling = MissingMemberHandling.Error
});
if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
ruleset.LoadPdt(dir);
}
FileInfo cfgfile = new FileInfo(
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
);
if (!cfgfile.Exists) {
if (!cfgfile.Directory.Exists) cfgfile.Directory.Create();
_rscfg = new RulesetConfig();
}
else {
using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) {
_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
void Start() {
try {
ChartPlayer.etor = new PdtEvaluator();
FileInfo file = new FileInfo(
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
);
if (!file.Exists) {
throw new FileNotFoundException("Ruleset for the chart not found\nMake sure you have imported the ruleset");
}
DirectoryInfo dir = file.Directory;
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
MissingMemberHandling = MissingMemberHandling.Error
});
if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
ruleset.LoadPdt(dir);
}
FileInfo cfgfile = new FileInfo(
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
);
if (!cfgfile.Exists) {
if (!cfgfile.Directory.Exists) cfgfile.Directory.Create();
_rscfg = new RulesetConfig();
}
else {
using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) {
_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
MissingMemberHandling = MissingMemberHandling.Error
});
}
}
m_genericConfigPanel.Target = _rscfg.generic;
var proxy = new InputProxy(ruleset.Root, null);
proxy.LoadFrom(_rscfg.inputs);
m_inputConfigPanel.proxy = proxy;
}
catch (Exception ex) {
Popup.CreateException(ex);
Logger.Log("main", 4, "Config", "An error occured while loading the config: {0}", ex);
ReturnToMenu();
}
m_genericConfigPanel.Target = _rscfg.generic;
var proxy = new InputProxy(ruleset.Root, null);
proxy.LoadFrom(_rscfg.inputs);
m_inputConfigPanel.proxy = proxy;
Game.InputManager.Activate();
}
public void SwitchCategory(GameObject cat) {
@@ -68,7 +73,6 @@ namespace Cryville.Crtr.Config {
}
public void SaveAndReturnToMenu() {
Game.InputManager.Deactivate();
m_inputConfigPanel.proxy.SaveTo(_rscfg.inputs);
m_inputConfigPanel.proxy.Dispose();
FileInfo cfgfile = new FileInfo(

View File

@@ -24,6 +24,7 @@ namespace Cryville.Crtr.Config {
[SerializeField]
GameObject m_prefabInputConfigEntry;
readonly SimpleInputConsumer _consumer = new SimpleInputConsumer(Game.InputManager);
public InputProxy proxy;
readonly Dictionary<string, InputConfigPanelEntry> _entries = new Dictionary<string, InputConfigPanelEntry>();
@@ -32,7 +33,7 @@ namespace Cryville.Crtr.Config {
_sel = entry;
m_inputDialog.SetActive(true);
CallHelper.Purge(m_deviceList);
Game.InputManager.EnumerateEvents(ev => { });
_consumer.EnumerateEvents(ev => { });
_recvsrcs.Clear();
AddSourceItem(null);
}
@@ -46,10 +47,11 @@ namespace Cryville.Crtr.Config {
Target = _sel,
Source = src,
});
m_inputDialog.SetActive(false);
CloseDialog();
}
void Start() {
_consumer.Activate();
foreach (var i in m_configScene.ruleset.Root.inputs) {
var e = GameObject.Instantiate(m_prefabInputConfigEntry, m_entryList.transform).GetComponent<InputConfigPanelEntry>();
_entries.Add(i.Key, e);
@@ -59,6 +61,10 @@ namespace Cryville.Crtr.Config {
proxy.ProxyChanged += OnProxyChanged;
}
void OnDestroy() {
_consumer.Deactivate();
}
void OnProxyChanged(object sender, ProxyChangedEventArgs e) {
_entries[e.Name].SetEnabled(!e.Used);
_entries[e.Name].SetValue(e.Proxy == null ? "None" : e.Proxy.Value.Handler.GetTypeName(e.Proxy.Value.Type));
@@ -67,7 +73,7 @@ namespace Cryville.Crtr.Config {
readonly List<InputSource?> _recvsrcs = new List<InputSource?>();
void Update() {
if (m_inputDialog.activeSelf) {
Game.InputManager.EnumerateEvents(ev => {
_consumer.EnumerateEvents(ev => {
AddSourceItem(ev.Id.Source);
});
}

View File

@@ -0,0 +1,78 @@
using Discord;
using System;
using UnityEngine;
using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr {
internal class DiscordController : MonoBehaviour {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
public static DiscordController Instance;
const long CLIENT_ID = 1059021675578007622L;
Discord.Discord dc;
ActivityManager am;
long launchTime;
void Start() {
Instance = this;
launchTime = (long)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
try {
dc = new Discord.Discord(CLIENT_ID, (UInt64)CreateFlags.NoRequireDiscord);
Logger.Log("main", 1, "Discord", "Connected to Discord");
am = dc.GetActivityManager();
SetIdle();
}
catch (ResultException) {
if (dc != null) {
dc.Dispose();
dc = null;
}
Logger.Log("main", 3, "Discord", "Cannot connect to Discord");
}
}
void Update() {
if (dc == null) return;
try {
dc.RunCallbacks();
}
catch (ResultException ex) {
dc.Dispose();
dc = null;
Logger.Log("main", 4, "Discord", "An error occured while running callbacks: {0}", ex);
}
}
void OnApplicationQuit() {
if (dc == null) return;
dc.Dispose();
}
void Callback(Result result) { }
public void SetIdle() {
if (dc == null) return;
am.UpdateActivity(new Activity {
State = "Idle",
Instance = false,
Timestamps = { Start = launchTime },
}, Callback);
}
public void SetPlaying(string detail, double? duration) {
if (dc == null) return;
long now = (long)(DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds;
am.UpdateActivity(new Activity {
State = "Playing a chart",
Details = detail,
Instance = true,
Timestamps = {
Start = now,
End = duration == null ? 0 : now + (long)duration,
},
}, Callback);
}
#endif
}
}

View File

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

View File

@@ -1,11 +1,18 @@
using Cryville.Common;
using Cryville.Common.Buffers;
using Cryville.Crtr.Components;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using UnityEngine;
namespace Cryville.Crtr.Event {
public abstract class ContainerHandler : IDisposable {
public abstract class ContainerHandler {
#region Struct
public ContainerHandler() { }
public abstract string TypeName { get; }
/// <summary>
/// Prehandling <see cref="ContainerState"/>, prehandling the events.
/// </summary>
@@ -34,61 +41,85 @@ namespace Cryville.Crtr.Event {
/// <summary>
/// <see cref="GameObject"/> group, the <see cref="Transform"/> containing all the generated elements in the <see cref="ContainerHandler"/>.
/// </summary>
public Transform gogroup;
protected Transform gogroup;
public SkinContext SkinContext;
public readonly Dictionary<string, Anchor> Anchors = new Dictionary<string, Anchor>();
public Transform a_head;
public Transform a_tail;
public Vector3 Position {
get;
protected set;
public Vector3 Position { get; protected set; }
public Quaternion Rotation { get; protected set; }
public bool Alive { get; private set; }
bool PreGraphicalActive;
public void SetPreGraphicalActive(bool value, ContainerState s) {
if (PreGraphicalActive == value) return;
PreGraphicalActive = value;
if (PreGraphicalActive) StartPreGraphicalUpdate(s);
else EndPreGraphicalUpdate(s);
}
public Quaternion Rotation {
get;
protected set;
}
public bool Alive {
get;
private set;
}
public bool Awoken {
get;
private set;
}
public bool Disposed {
get;
private set;
bool GraphicalActive;
public void SetGraphicalActive(bool value, ContainerState s) {
if (GraphicalActive == value) return;
GraphicalActive = value;
if (GraphicalActive) StartGraphicalUpdate(s);
else EndGraphicalUpdate(s);
}
public EventContainer Container {
get { return cs.Container; }
}
public SkinContainer skinContainer;
public Judge judge;
SkinContainer skinContainer;
protected Judge judge;
public void AttachSystems(PdtSkin skin, Judge judge) {
skinContainer = new SkinContainer(skin);
this.judge = judge;
}
public ContainerHandler() { }
public abstract string TypeName {
get;
public readonly Dictionary<int, List<Anchor>> Anchors = new Dictionary<int, List<Anchor>>();
public readonly Dictionary<int, Anchor> DynamicAnchors = new Dictionary<int, Anchor>();
public readonly Dictionary<int, bool> DynamicAnchorSet = new Dictionary<int, bool>();
public Anchor OpenedAnchor;
protected Anchor a_cur;
protected Anchor a_head;
protected Anchor a_tail;
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 Anchor RegisterAnchor(int name, bool dyn = false, int propSrcCount = 0) {
var strname = IdentifierManager.SharedInstance.Retrieve(name);
var go = new GameObject("." + strname).transform;
go.SetParent(gogroup, false);
var result = new Anchor(name, go, propSrcCount);
if (dyn) {
if (DynamicAnchors.ContainsKey(name))
throw new ArgumentException(string.Format("The anchor \"{0}\" already exists", strname));
DynamicAnchors.Add(name, result);
DynamicAnchorSet.Add(name, false);
}
List<Anchor> list;
if (!Anchors.TryGetValue(name, out list))
Anchors.Add(name, list = new List<Anchor>());
list.Add(result);
return result;
}
protected void OpenAnchor(Anchor anchor) {
if (OpenedAnchor != null) throw new InvalidOperationException("An anchor has been opened");
OpenedAnchor = anchor;
}
protected void CloseAnchor() {
OpenedAnchor = null;
}
#endregion
#region Logic
#region Init methods: Called on prehandle
public virtual void PreInit() {
gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString(CultureInfo.InvariantCulture)).transform;
SkinContext = new SkinContext(gogroup);
if (cs.Parent != null)
gogroup.SetParent(cs.Parent.Handler.gogroup, false);
a_head = new GameObject("::head").transform;
a_head.SetParent(gogroup, false);
Anchors.Add("head", new Anchor() { Transform = a_head });
a_tail = new GameObject("::tail").transform;
a_tail.SetParent(gogroup, false);
Anchors.Add("tail", new Anchor() { Transform = a_tail });
a_cur = RegisterAnchor(_a_cur);
a_head = RegisterAnchor(_a_head, true);
a_tail = RegisterAnchor(_a_tail, true);
}
/// <summary>
/// Called upon StartUpdate of ps 17.
/// </summary>
public virtual void Init() {
skinContainer.MatchStatic(ps);
foreach (var i in gogroup.GetComponentsInChildren<SkinComponent>())
@@ -97,52 +128,93 @@ namespace Cryville.Crtr.Event {
public virtual void PostInit() {
gogroup.gameObject.SetActive(false);
}
#endregion
#region Start methods
public virtual void StartPhysicalUpdate(ContainerState s) {
if (s.CloneType < 16) Alive = true;
else if (s.CloneType == 17) Init();
}
public virtual void StartLogicalUpdate(ContainerState s) { }
public virtual void StartPreGraphicalUpdate(ContainerState s) { }
public virtual void StartGraphicalUpdate(ContainerState s) {
if (gogroup) gogroup.gameObject.SetActive(true);
}
#endregion
public virtual void Update(ContainerState s, StampedEvent ev) {
if (s.CloneType == 3) SetPreGraphicalActive(true, s);
else if (ev is StampedEvent.Anchor) {
var tev = (StampedEvent.Anchor)ev;
if (tev.Target == a_head) {
SetGraphicalActive(true, s);
}
else if (tev.Target == a_tail) {
SetGraphicalActive(false, s);
}
if (gogroup) {
OpenAnchor(tev.Target);
#if UNITY_5_6_OR_NEWER
tev.Target.Transform.SetPositionAndRotation(Position, Rotation);
#else
tev.Target.Transform.position = GetCurrentWorldPoint();
tev.Target.Transform.rotation = Quaternion.Euler(s.Direction);
#endif
skinContainer.MatchDynamic(s);
CloseAnchor();
}
anchorEvPool.Return(tev);
}
else if (gogroup && s.CloneType == 2) skinContainer.MatchDynamic(s);
}
#region End methods
public virtual void EndGraphicalUpdate(ContainerState s) { }
public virtual void EndPreGraphicalUpdate(ContainerState s) { }
public virtual void EndLogicalUpdate(ContainerState s) { }
public virtual void EndPhysicalUpdate(ContainerState s) { }
public virtual void Dispose() {
if (Disposed) return;
Disposed = true;
if (gogroup)
GameObject.Destroy(gogroup.gameObject);
// gogroup.gameObject.SetActive(false);
Alive = false;
}
protected virtual void PreAwake(ContainerState s) {
if (gogroup) gogroup.gameObject.SetActive(true);
Awoken = true; Alive = true;
OpenAnchor("head");
}
protected virtual void Awake(ContainerState s) {
CloseAnchor("head");
}
protected virtual void GetPosition(ContainerState s) { }
public virtual void StartUpdate(ContainerState s) {
if (s.CloneType >= 2 && s.CloneType < 16) {
PreAwake(s);
Awake(s);
}
else if (s.CloneType == 17) {
Init();
public virtual void DisposeAll() { }
#endregion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static bool CanDoGraphicalUpdate(ContainerState s) { return s.CloneType >= 2 && s.CloneType < 16; }
#region Anchor
public virtual void Anchor() {
foreach (var a in DynamicAnchors.Keys) DynamicAnchorSet[a] = false;
skinContainer.MatchDynamic(cs);
if (cs.Active) PushAnchorEvent(cs.Time, a_cur);
if (Alive) {
if (!DynamicAnchorSet[_a_head]) PushAnchorEvent(cs.StampedContainer.Time, a_head, -1, true);
if (!DynamicAnchorSet[_a_tail]) PushAnchorEvent(cs.StampedContainer.Time + cs.StampedContainer.Duration, a_tail, 1, true);
}
}
public virtual void Update(ContainerState s, StampedEvent ev) {
bool flag = !Awoken && s.CloneType >= 2 && s.CloneType < 16;
if (flag) PreAwake(s);
if (s.CloneType <= 2) if (gogroup) skinContainer.MatchDynamic(s);
if (flag) Awake(s);
static readonly SimpleObjectPool<StampedEvent.Anchor> anchorEvPool
= new SimpleObjectPool<StampedEvent.Anchor>(1024);
public void PushAnchorEvent(double time, int name) {
Anchor anchor;
if (!DynamicAnchors.TryGetValue(name, out anchor))
throw new ArgumentException(string.Format("Specified anchor \"{0}\" not found", IdentifierManager.SharedInstance.Retrieve(name)));
if (DynamicAnchorSet[name])
throw new InvalidOperationException(string.Format("Specified anchor \"{0}\" has been set", IdentifierManager.SharedInstance.Retrieve(name)));
PushAnchorEvent(time, anchor);
DynamicAnchorSet[name] = true;
}
public virtual void ExUpdate(ContainerState s, StampedEvent ev) { }
public virtual void MotionUpdate(byte ct, Chart.Motion ev) { }
public virtual void EndUpdate(ContainerState s) {
if (s.CloneType < 16) {
Awoken = false;
if (gogroup && s.CloneType <= 2) skinContainer.MatchDynamic(s);
void PushAnchorEvent(double time, Anchor anchor, int priority = 0, bool forced = false) {
var tev = anchorEvPool.Rent();
tev.Time = time;
tev.Container = Container;
tev.Target = anchor;
tev.CanDiscard = !forced;
tev.SetPriority(priority);
ts.Bus.PushTempEvent(tev);
}
public virtual void Discard(ContainerState s, StampedEvent ev) {
if (ev is StampedEvent.Anchor) {
anchorEvPool.Return((StampedEvent.Anchor)ev);
}
}
public virtual void Anchor() { }
protected void OpenAnchor(string name) {
if (Anchors.ContainsKey(name)) Anchors[name].Open();
}
protected void CloseAnchor(string name) {
if (Anchors.ContainsKey(name)) Anchors[name].Close();
}
#endregion
#endregion
}
}

View File

@@ -3,20 +3,21 @@
using Cryville.Common;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
namespace Cryville.Crtr.Event {
public class ContainerState {
#region Struct
public EventBus Bus;
public EventContainer Container;
public StampedEvent StampedContainer;
public ContainerState Parent = null;
public ushort Depth;
public Dictionary<EventContainer, ContainerState> Children
= new Dictionary<EventContainer, ContainerState>();
readonly HashSet<EventContainer> WorkingChildren
= new HashSet<EventContainer>();
readonly HashSet<EventContainer> InvalidatedChildren
HashSet<EventContainer> ActiveChildren
= new HashSet<EventContainer>();
public Dictionary<Type, List<ContainerState>> TypedChildren
= new Dictionary<Type, List<ContainerState>>();
@@ -28,27 +29,47 @@ namespace Cryville.Crtr.Event {
return Children[ev];
}
void NotifyWorkingChanged(EventContainer key) {
InvalidatedChildren.Add(key);
}
void ValidateChildren() {
foreach (var cev in InvalidatedChildren)
if (Children[cev].Working && !WorkingChildren.Contains(cev)) WorkingChildren.Add(cev);
else if (!Children[cev].Working && WorkingChildren.Contains(cev)) WorkingChildren.Remove(cev);
InvalidatedChildren.Clear();
}
private bool m_Working;
public bool Working {
get { return m_Working; }
set {
m_Working = value;
if (Parent != null) Parent.NotifyWorkingChanged(Container);
Bus.NotifyWorkingChanged(this);
private bool m_active;
public bool Active {
get { return m_active; }
private set {
if (m_active == value) return;
m_active = value;
if (!m_active && CloneType == 1) Dispose();
if (Parent != null) {
if (m_active) Parent.ActiveChildren.Add(Container);
else Parent.ActiveChildren.Remove(Container);
}
Bus.NotifyActiveChanged(this);
}
}
private bool m_lActive;
public bool LogicalActive {
get { return m_lActive; }
set {
if (m_lActive == value) return;
m_lActive = value;
UpdateActive();
if (m_lActive) Handler.StartLogicalUpdate(this);
else Handler.EndLogicalUpdate(this);
}
}
private bool m_pActive;
public bool PhysicalActive {
get { return m_pActive; }
set {
if (m_pActive == value) return;
m_pActive = value;
UpdateActive();
if (m_pActive) Handler.StartPhysicalUpdate(this);
else Handler.EndPhysicalUpdate(this);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void UpdateActive() { Active = m_lActive || m_pActive; }
public byte CloneType;
private ContainerState rootPrototype = null;
public ContainerState rootPrototype = null;
private ContainerState prototype = null;
public ContainerHandler Handler {
@@ -56,53 +77,13 @@ namespace Cryville.Crtr.Event {
private set;
}
public float Time {
public double Time {
get {
return Bus.Time;
}
}
readonly RMVPool RMVPool = new RMVPool();
protected Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>();
protected Dictionary<Identifier, RealtimeMotionValue> Values;
protected Dictionary<Identifier, CacheEntry> CachedValues;
protected class CacheEntry {
public bool Valid { get; set; }
public Vector Value { get; set; }
public CacheEntry Clone() {
return new CacheEntry { Valid = Valid, Value = Value == null ? null : Value.Clone() };
}
}
/// <summary>
/// Gets a motion value.
/// </summary>
/// <param name="name">The motion name.</param>
/// <param name="clone">Returns a cloned motion value instead.</param>
/// <returns>A motion value.</returns>
RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) {
RealtimeMotionValue value;
if (!Values.TryGetValue(name, out value)) {
value = new RealtimeMotionValue().Init(Parent == null
? ChartPlayer.motionRegistry[name].GlobalInitValue
: ChartPlayer.motionRegistry[name].InitValue
);
Values.Add(name, value);
}
if (clone) return value.Clone();
return value;
}
void InvalidateMotion(Identifier name) {
CacheEntry cache;
if (!CachedValues.TryGetValue(name, out cache))
CachedValues.Add(name, cache = new CacheEntry());
cache.Valid = false;
foreach (var c in Children)
c.Value.InvalidateMotion(name);
}
public ContainerState(Chart c, EventContainer _ev, ContainerState parent = null) {
public ContainerState(EventContainer _ev, ContainerState parent = null) {
Container = _ev;
if (parent != null) {
@@ -111,9 +92,11 @@ namespace Cryville.Crtr.Event {
}
Values = new Dictionary<Identifier, RealtimeMotionValue>(ChartPlayer.motionRegistry.Count);
CachedValues = new Dictionary<Identifier, CacheEntry>(ChartPlayer.motionRegistry.Count);
CachedValues = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
foreach (var m in ChartPlayer.motionRegistry)
Values.Add(m.Key, new RealtimeMotionValue().Init(Parent == null ? m.Value.GlobalInitValue : m.Value.InitValue));
rootPrototype = this;
}
static void AddChild(EventContainer c, ContainerState s, ContainerState target) {
@@ -132,9 +115,11 @@ namespace Cryville.Crtr.Event {
}
r.Values = mvs;
var cvs = new Dictionary<Identifier, CacheEntry>(ChartPlayer.motionRegistry.Count);
var cvs = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
foreach (var cv in CachedValues) {
cvs.Add(cv.Key, cv.Value.Clone());
var dv = r.MCPool.Rent(cv.Key);
cv.Value.CopyTo(dv);
cvs.Add(cv.Key, dv);
}
r.CachedValues = cvs;
@@ -145,7 +130,9 @@ namespace Cryville.Crtr.Event {
AddChild(child.Key, cc, r);
}
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(PlayingMotions.Count);
r.ActiveChildren = new HashSet<EventContainer>();
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(Math.Max(4, PlayingMotions.Count));
foreach (var m in PlayingMotions)
pms.Add(m.Key, m.Value);
r.PlayingMotions = pms;
@@ -156,14 +143,15 @@ namespace Cryville.Crtr.Event {
else if (ct >= 16) Handler.ps = r;
else throw new InvalidOperationException("Invalid clone type");
r.prototype = this;
if (prototype == null) r.rootPrototype = this;
else r.rootPrototype = rootPrototype;
r.CloneType = ct;
return r;
}
public void CopyTo(byte ct, ContainerState dest) {
dest.Working = Working;
dest.m_lActive = m_lActive;
dest.m_pActive = m_pActive;
dest.m_active = m_active;
if (dest.m_active) dest.Bus.NotifyActiveChanged(dest);
foreach (var mv in Values) {
RealtimeMotionValue dv;
@@ -171,20 +159,24 @@ namespace Cryville.Crtr.Event {
else dest.Values.Add(mv.Key, mv.Value.Clone());
}
foreach (var cv in dest.CachedValues) cv.Value.Valid = false;
foreach (var cv in CachedValues) {
CacheEntry dv;
if (dest.CachedValues.TryGetValue(cv.Key, out dv)) {
dv.Valid = cv.Value.Valid;
if (cv.Value.Value != null) cv.Value.Value.CopyTo(dv.Value);
MotionCache dv;
if (!dest.CachedValues.TryGetValue(cv.Key, out dv)) {
dest.CachedValues.Add(cv.Key, dv = dest.MCPool.Rent(cv.Key));
}
else dest.CachedValues.Add(cv.Key, cv.Value.Clone());
cv.Value.CopyTo(dv);
}
if (ct != 1) foreach (var cev in WorkingChildren)
foreach (var cev in dest.ActiveChildren) {
if (!ActiveChildren.Contains(cev))
Children[cev].CopyTo(ct, dest.Children[cev]);
}
dest.ActiveChildren.Clear();
foreach (var cev in ActiveChildren) {
dest.ActiveChildren.Add(cev);
Children[cev].CopyTo(ct, dest.Children[cev]);
else foreach (var child in Children)
child.Value.CopyTo(ct, dest.Children[child.Key]);
ValidateChildren();
}
dest.PlayingMotions.Clear();
foreach (var m in PlayingMotions) dest.PlayingMotions.Add(m.Key, m.Value);
@@ -197,15 +189,21 @@ namespace Cryville.Crtr.Event {
public void Dispose() {
if (Disposed) return;
Disposed = true;
if (CloneType < 16 && Handler != null) Handler.Dispose();
if (CloneType == 1) Handler.Dispose();
foreach (var s in Children)
s.Value.Dispose();
RMVPool.ReturnAll();
MCPool.ReturnAll();
}
public void DisposeAll() {
foreach (var s in Children)
s.Value.DisposeAll();
Handler.DisposeAll();
}
public void AttachHandler(ContainerHandler h) {
if (Handler != null)
throw new InvalidOperationException();
throw new InvalidOperationException("Handler attached twice");
Handler = h;
h.cs = this;
}
@@ -213,19 +211,46 @@ namespace Cryville.Crtr.Event {
public void AttachSystems(PdtSkin skin, Judge judge) {
Handler.AttachSystems(skin, judge);
}
#endregion
#region Motion
readonly RMVPool RMVPool = new RMVPool();
readonly MotionCachePool MCPool = new MotionCachePool();
Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>(4);
Dictionary<Identifier, RealtimeMotionValue> Values;
Dictionary<Identifier, MotionCache> CachedValues;
/// <summary>
/// Gets a motion value.
/// </summary>
/// <param name="name">The motion name.</param>
/// <param name="clone">Returns a cloned motion value instead.</param>
/// <returns>A motion value.</returns>
RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) {
RealtimeMotionValue value = Values[name];
if (clone) return value.Clone();
return value;
}
void InvalidateMotion(Identifier name) {
MotionCache cache;
if (!CachedValues.TryGetValue(name, out cache))
CachedValues.Add(name, cache = MCPool.Rent(name));
cache.Valid = false;
foreach (var c in ActiveChildren)
Children[c].InvalidateMotion(name);
}
public Vector GetRawValue(Identifier key) {
CacheEntry tr;
MotionCache tr;
if (!CachedValues.TryGetValue(key, out tr))
CachedValues.Add(key, tr = new CacheEntry { Valid = false });
if (tr.Value == null)
tr.Value = (Vector)ReflectionHelper.InvokeEmptyConstructor(ChartPlayer.motionRegistry[key].Type);
CachedValues.Add(key, tr = MCPool.Rent(key));
Vector r = tr.Value;
#if !DISABLE_CACHE
if (tr.Valid) return r;
#endif
float reltime = 0;
if (rootPrototype != null) reltime = Time - rootPrototype.Time;
if (rootPrototype != null) reltime = (float)(Time - rootPrototype.Time);
GetMotionValue(key).GetValue(reltime, ref r);
if (Parent != null) r.ApplyFrom(Parent.GetRawValue(key));
#if !DISABLE_CACHE
@@ -308,16 +333,22 @@ namespace Cryville.Crtr.Event {
return GetRawValue<Vec1>(n_track).Value;
}
}
#endregion
#region Update
bool breakflag = false;
public void Break() {
Handler.EndUpdate(this);
// Handler.EndLogicalUpdate(this);
breakflag = true;
Working = false;
// LogicalActive = false;
}
public void Handle(StampedEvent ev, Action<StampedEvent> callback = null) {
public void Discard(StampedEvent ev) {
Handler.Discard(this, ev);
}
public void Handle(StampedEvent ev) {
if (breakflag) return;
if (ev != null) {
if (ev.Unstamped is Chart.Motion) {
@@ -326,7 +357,7 @@ namespace Cryville.Crtr.Event {
mv.CloneTypeFlag = CloneType;
GetMotionValue(tev.Name).CopyTo(mv);
PlayingMotions.Add(ev, mv);
Callback(ev, callback);
Update(ev);
if (!ev.Unstamped.IsLong) {
PlayingMotions.Remove(ev);
RMVPool.Return(mv);
@@ -335,48 +366,37 @@ namespace Cryville.Crtr.Event {
else if (ev.Unstamped is EventContainer) {
var cev = (EventContainer)ev.Unstamped;
var ccs = GetChild(cev);
ccs.Working = true;
ccs.StartUpdate();
ccs.LogicalActive = true;
UpdateMotions();
if (!ev.Unstamped.IsLong) {
ccs.Working = false;
ccs.BroadcastEndUpdate();
if (CloneType == 1) ccs.Dispose();
if (!cev.IsLong) {
ccs.LogicalActive = false;
}
}
else if (ev.Unstamped is InstantEvent) {
var tev = (InstantEvent)ev.Unstamped;
if (tev.IsRelease) {
var nev = tev.Original;
if (nev is Chart.Motion) {
Callback(ev, callback);
var mv = PlayingMotions[ev.Origin];
if (mv.CloneTypeFlag == CloneType) RMVPool.Return(mv);
PlayingMotions.Remove(ev.Origin);
}
else if (nev is EventContainer) {
var cev = (EventContainer)ev.Origin.Unstamped;
var ccs = GetChild(cev);
UpdateMotions();
ccs.Working = false;
ccs.BroadcastEndUpdate();
if (CloneType == 1) ccs.Dispose();
}
else if (ev.Unstamped is ReleaseEvent) {
var tev = (ReleaseEvent)ev.Unstamped;
var nev = tev.Original;
if (nev is Chart.Motion) {
Update(ev);
var mv = PlayingMotions[ev.Origin];
if (mv.CloneTypeFlag == CloneType) RMVPool.Return(mv);
PlayingMotions.Remove(ev.Origin);
}
else if (nev is EventContainer) {
var cev = (EventContainer)ev.Origin.Unstamped;
var ccs = GetChild(cev);
UpdateMotions();
ccs.LogicalActive = false;
}
}
Callback(ev.Unstamped == null || ev.Unstamped.Priority >= 0 ? ev : null, callback);
Update(ev.Unstamped == null || ev.Unstamped.Priority >= 0 ? ev : null);
}
else Callback(null, callback);
else Update(null);
}
void Callback(StampedEvent ev, Action<StampedEvent> callback) {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Update(StampedEvent ev) {
UpdateMotions();
if (callback != null)
callback(ev);
if (ev == null || ev.Unstamped != null) Handler.Update(this, ev);
else Handler.ExUpdate(this, ev);
foreach (var m in PlayingMotions)
Handler.MotionUpdate(CloneType, (Chart.Motion)m.Key.Unstamped);
Handler.Update(this, ev);
}
private void UpdateMotions() {
@@ -394,7 +414,7 @@ namespace Cryville.Crtr.Event {
}
}
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);
if (tev.RelativeNode != null) {
var target = value.QueryRelativeNode(tev.RelativeNode.Id);
@@ -421,14 +441,17 @@ namespace Cryville.Crtr.Event {
}
}
public void StartUpdate() {
Handler.StartUpdate(this);
public void EndPreGraphicalUpdate() {
Handler.SetPreGraphicalActive(false, this);
foreach (var ls in ActiveChildren) {
Children[ls].EndPreGraphicalUpdate();
}
}
public void BroadcastEndUpdate() {
Handler.EndUpdate(this);
foreach (var ls in Children.Values) {
if (ls.Working) ls.BroadcastEndUpdate();
public void EndGraphicalUpdate() {
Handler.SetGraphicalActive(false, this);
foreach (var ls in ActiveChildren) {
Children[ls].EndGraphicalUpdate();
}
}
@@ -438,5 +461,6 @@ namespace Cryville.Crtr.Event {
if (ls.Handler.Alive) ls.Anchor();
}
}
#endregion
}
}

View File

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

View File

@@ -9,124 +9,148 @@ namespace Cryville.Crtr.Event {
get;
private set;
}
ContainerState RootState;
/// <summary>
/// event => the container state that handles the event
/// </summary>
readonly Dictionary<ChartEvent, ContainerState> table
readonly Chart chart;
ContainerState rootState;
readonly Dictionary<ChartEvent, ContainerState> containerMap
= new Dictionary<ChartEvent, ContainerState>();
public List<StampedEvent> stampedEvents = new List<StampedEvent>();
readonly Dictionary<EventContainer, ContainerState> stateMap
= new Dictionary<EventContainer, ContainerState>();
readonly Dictionary<ChartEvent, StampedEvent> map
= new Dictionary<ChartEvent, StampedEvent>();
readonly Dictionary<EventContainer, List<StampedEvent>> coeventMap
= new Dictionary<EventContainer, List<StampedEvent>>();
readonly HashSet<ChartEvent> coevents = new HashSet<ChartEvent>();
readonly List<StampedEvent> stampedEvents = new List<StampedEvent>();
readonly List<EventBatch> batches = new List<EventBatch>();
float beat;
double beat;
float tempo;
public EventBatcher(Chart c) : base(c, new List<ChartEvent>()) {
public EventBatcher(Chart c) : base(new List<ChartEvent>()) {
chart = c;
beat = chart.BeatPosition;
tempo = (float)c.sigs[0].tempo;
events.Add(c);
events.Add(c.ReleaseEvent);
Events.Add(c);
Events.Add(c.ReleaseEvent);
AddEventContainer(c);
events.Sort((a, b) => a.BeatPosition.CompareTo(b.BeatPosition));
Events.Sort((a, b) => a.BeatPosition.CompareTo(b.BeatPosition));
}
void AddEventContainer(EventContainer c, ContainerState parent = null) {
var cs = new ContainerState(chart, c, parent);
var cs = new ContainerState(c, parent);
stateMap.Add(c, cs);
if (parent == null) {
cs.Depth = 0;
RootState = cs;
rootState = cs;
}
else {
cs.Depth = (ushort)(parent.Depth + 1);
}
foreach (var ev in c.Events) {
if (ev.time == null) {
coevents.Add(ev);
ev.time = c.time;
if (ev is EventContainer)
ev.endtime = c.endtime;
}
if (ev.IsLong) {
events.Add(ev.ReleaseEvent);
table.Add(ev.ReleaseEvent, cs);
Events.Add(ev.ReleaseEvent);
containerMap.Add(ev.ReleaseEvent, cs);
}
events.Add(ev);
table.Add(ev, cs);
Events.Add(ev);
containerMap.Add(ev, cs);
if (ev is EventContainer)
AddEventContainer((EventContainer)ev, cs);
}
}
public override void ForwardOnceToTime(float toTime, Action<ChartEvent> callback) {
float toBeat = (float)Math.Round(beat + (toTime - Time) * tempo / 60f, 6);
if (EventId >= events.Count)
public override void ForwardOnceToTime(double toTime) {
double toBeat = Math.Round(beat + (toTime - Time) * tempo / 60f, 6);
if (EventId >= Events.Count)
goto return_ahead;
float ebeat = events[EventId].BeatPosition;
float etime = (float)Math.Round((ebeat - beat) / tempo * 60f + Time, 6);
double ebeat = Events[EventId].BeatPosition;
double etime = Math.Round((ebeat - beat) / tempo * 60f + Time, 6);
if (etime > toTime)
goto return_ahead;
var batch = GetEventBatch();
Time = etime;
beat = ebeat;
bool flag = false;
foreach (var ev in batch) {
EventContainer con = null;
if (table.ContainsKey(ev)) con = table[ev].Container;
if (containerMap.ContainsKey(ev)) con = containerMap[ev].Container;
var sev = new StampedEvent() {
Time = etime,
Unstamped = ev,
Container = con
};
if (ev is InstantEvent) {
var tev = (InstantEvent)ev;
var pev = stampedEvents.First(tpev => tpev.Unstamped == tev.Original);
pev.Subevents.Add(sev);
if (ev is EventContainer) {
var tev = (EventContainer)ev;
stateMap[tev].StampedContainer = sev;
stampedEvents.Add(new StampedEvent.ClipBehind {
Container = con,
Origin = sev,
Time = etime + tev.Clip.Behind,
});
if (!ev.IsLong) {
stampedEvents.Add(new StampedEvent.ClipAhead {
Container = con,
Origin = sev,
Time = etime + tev.Clip.Ahead,
});
}
}
if (ev is ReleaseEvent) {
var tev = (ReleaseEvent)ev;
var oev = tev.Original;
var pev = map[oev];
pev.ReleaseEvent = sev;
sev.Origin = pev;
if (oev is EventContainer) {
stampedEvents.Add(new StampedEvent.ClipAhead {
Container = con,
Origin = pev,
Time = etime + ((EventContainer)oev).Clip.Ahead,
});
}
}
stampedEvents.Add(sev);
if (ev.Priority >= 0) {
if (callback != null) callback(ev);
flag = true;
if (con != null && coevents.Contains(ev)) {
List<StampedEvent> cevs;
if (!coeventMap.TryGetValue(con, out cevs)) {
coeventMap.Add(con, cevs = new List<StampedEvent>());
}
cevs.Add(sev);
}
else stampedEvents.Add(sev);
map.Add(ev, sev);
if (ev is Chart.Signature) {
var tev = (Chart.Signature)ev;
if (tev.tempo != null) tempo = (float)tev.tempo;
}
EventId++;
}
if (callback != null && !flag) callback(batch.First());
return;
return_ahead:
Time = toTime;
beat = toBeat;
if (callback != null) callback(null);
}
IOrderedEnumerable<ChartEvent> GetEventBatch() {
float cbeat = events[EventId].BeatPosition;
float cbeat = Events[EventId].BeatPosition;
int b = EventId;
while (Mathf.Approximately(events[b].BeatPosition, cbeat)) {
while (Mathf.Approximately(Events[b].BeatPosition, cbeat)) {
b--;
if (b == -1) break;
}
int a = EventId;
while (Mathf.Approximately(events[a].BeatPosition, cbeat)) {
while (Mathf.Approximately(Events[a].BeatPosition, cbeat)) {
a++;
if (a == events.Count) break;
if (a == Events.Count) break;
}
return from ev in events.GetRange(b + 1, a - b - 1) orderby ev.Priority select ev;
return from ev in Events.GetRange(b + 1, a - b - 1) orderby ev.Priority select ev;
}
public EventBus Batch() {
stampedEvents.Sort((a, b) => {
int u = a.CompareTo(b);
if (u != 0) return u;
if (a.Unstamped != null && b.Unstamped != null)
if (table.ContainsKey(a.Unstamped) && table.ContainsKey(b.Unstamped)) {
u = table[a.Unstamped].Depth.CompareTo(table[b.Unstamped].Depth);
if (u != 0) return u;
}
return a.GetHashCode().CompareTo(b.GetHashCode());
});
stampedEvents.Sort(CompareStampedEvents);
var cb = new EventBatch(stampedEvents[0].Time);
foreach (var ev in stampedEvents) {
if (ev.Time != cb.Time) {
@@ -134,10 +158,36 @@ namespace Cryville.Crtr.Event {
cb = new EventBatch(ev.Time);
}
cb.Enqueue(ev);
BatchCoevents(ev);
}
batches.Add(cb);
Bus = new EventBus(chart, RootState, batches);
Bus = new EventBus(rootState, batches);
return Bus;
}
void BatchCoevents(StampedEvent ev, List<StampedEvent> ocevs = null) {
if (!(ev.Unstamped is EventContainer)) return;
List<StampedEvent> cevs;
if (coeventMap.TryGetValue((EventContainer)ev.Unstamped, out cevs)) {
var rootFlag = ocevs == null;
if (rootFlag) ev.Coevents = ocevs = new List<StampedEvent>();
foreach (var cev in cevs) {
ocevs.Add(cev);
BatchCoevents(cev, ocevs);
}
if (rootFlag) ocevs.Sort(CompareStampedEvents);
else ocevs.Add(ev);
}
}
int CompareStampedEvents(StampedEvent a, StampedEvent b) {
int u = a.CompareTo(b);
if (u != 0) return u;
if (a.Unstamped != null && b.Unstamped != null && containerMap.ContainsKey(a.Unstamped) && containerMap.ContainsKey(b.Unstamped)) {
u = containerMap[a.Unstamped].Depth.CompareTo(containerMap[b.Unstamped].Depth);
if (u != 0) return u;
}
return 0;
}
}
}

View File

@@ -11,31 +11,27 @@ namespace Cryville.Crtr.Event {
Dictionary<EventContainer, ContainerState> states
= new Dictionary<EventContainer, ContainerState>();
List<EventContainer> activeContainers
= new List<EventContainer>();
HashSet<ContainerState> workingStates
HashSet<ContainerState> activeStates
= new HashSet<ContainerState>();
HashSet<ContainerState> invalidatedStates
= new HashSet<ContainerState>();
public int ActiveStateCount { get { return activeStates.Count; } }
public EventBus(Chart c, ContainerState root, List<EventBatch> b)
: base(c, b) {
public EventBus(ContainerState root, List<EventBatch> b) : base(b) {
RootState = root;
Expand();
AttachBus();
RootState.Working = true;
}
public EventBus Clone(byte ct, float offsetTime = 0) {
var r = (EventBus)MemberwiseClone();
r.prototype = this;
r.states = new Dictionary<EventContainer, ContainerState>();
r.activeContainers = new List<EventContainer>();
r.workingStates = new HashSet<ContainerState>();
r.activeStates = new HashSet<ContainerState>();
r.invalidatedStates = new HashSet<ContainerState>();
r.tempEvents = new List<StampedEvent.Temporary>();
r.Time += offsetTime;
r.RootState = RootState.Clone(ct);
r.RootState.StartUpdate();
r.Expand();
r.AttachBus();
foreach (var s in r.states) r.invalidatedStates.Add(s.Value);
@@ -45,26 +41,20 @@ namespace Cryville.Crtr.Event {
public void CopyTo(byte ct, EventBus dest) {
base.CopyTo(dest);
dest.workingStates.Clear();
dest.activeStates.Clear();
dest.invalidatedStates.Clear();
RootState.CopyTo(ct, dest.RootState);
if (ct >= 2) {
dest.activeContainers.Clear();
foreach (var c in activeContainers) {
if (states[c].Working) {
states[c].CopyTo(ct, dest.states[c]);
dest.activeContainers.Add(c);
}
}
}
dest.ValidateStates();
}
public void Dispose() {
RootState.Dispose();
}
public void DisposeAll() {
RootState.DisposeAll();
}
public void NotifyWorkingChanged(ContainerState state) {
public void NotifyActiveChanged(ContainerState state) {
if (!invalidatedStates.Contains(state)) invalidatedStates.Add(state);
}
@@ -83,12 +73,6 @@ namespace Cryville.Crtr.Event {
s.Bus = this;
}
void EnsureActivity(EventContainer c) {
if (activeContainers.Contains(c)) return;
if (RootState.CloneType >= 2) prototype.states[c].CopyTo(RootState.CloneType, states[c]);
activeContainers.Add(c);
}
void AttachBus() {
foreach (var s in states.Values)
s.Bus = this;
@@ -99,51 +83,84 @@ namespace Cryville.Crtr.Event {
s.AttachSystems(skin, judge);
}
readonly List<StampedEvent> patch = new List<StampedEvent>();
public void IssuePatch(IEnumerable<StampedEvent> l) {
patch.AddRange(l);
}
public void DoPatch() {
foreach (var ev in patch) {
var batch = new EventBatch(ev.Time);
var batchIndex = events.BinarySearch(batch);
if (batchIndex >= 0) batch = events[batchIndex];
else events.Insert(~batchIndex, batch);
batch.Add(ev);
}
patch.Clear();
List<StampedEvent.Temporary> tempEvents = new List<StampedEvent.Temporary>();
public void PushTempEvent(StampedEvent.Temporary ev) {
var index = tempEvents.BinarySearch(ev);
if (index < 0) index = ~index;
tempEvents.Insert(index, ev);
}
public override void ForwardOnceToTime(float toTime, Action<EventBatch> callback = null) {
if (EventId < events.Count && events[EventId].Time <= toTime) {
Time = events[EventId].Time;
var batch = events[EventId];
foreach (var s in workingStates) s.Handle(null);
ValidateStates();
for (var i = 0; i < batch.Count; i++) {
var ev = batch[i];
readonly StampedEvent.Temporary _dummyEvent = new StampedEvent.Temporary();
public void StripTempEvents() {
_dummyEvent.Time = Time;
var index = tempEvents.BinarySearch(_dummyEvent);
if (index < 0) index = ~index;
for (var i = index - 1; i >= 0; i--) {
var ev = tempEvents[i];
tempEvents.RemoveAt(i);
if (ev.CanDiscard) {
if (ev.Container != null) {
EnsureActivity(ev.Container);
states[ev.Container].Handle(ev);
}
if (ev.Unstamped is EventContainer) {
if (ev.Container != null) EnsureActivity((EventContainer)ev.Unstamped);
states[ev.Container].Discard(ev);
}
}
else {
ev.Time = Time;
PushTempEvent(ev);
}
}
}
public override void ForwardOnceToTime(double toTime) {
double time1 = EventId < Events.Count ? Events[EventId].Time : double.PositiveInfinity;
double time2 = tempEvents.Count > 0 ? tempEvents[0].Time : double.PositiveInfinity;
double time0 = Math.Min(time1, time2);
if (time0 <= toTime && time0 != double.PositiveInfinity) {
Time = time0;
foreach (var s in activeStates) s.Handle(null);
ValidateStates();
EventId++;
if (time1 == time0) {
var batch = Events[EventId];
for (var i = 0; i < batch.Count; i++) {
var ev = batch[i];
if (ev is StampedEvent.ClipBehind) {
var cevs = ev.Origin.Coevents;
if (cevs != null) foreach (var cev in cevs) {
if (cev.Container == null) continue;
states[cev.Container].Handle(cev);
}
states[(EventContainer)ev.Origin.Unstamped].PhysicalActive = true;
}
else if (ev is StampedEvent.ClipAhead) {
states[(EventContainer)ev.Origin.Unstamped].PhysicalActive = false;
}
else if (ev.Container != null) {
states[ev.Container].Handle(ev);
}
}
EventId++;
}
if (time2 == time0) {
while (tempEvents.Count > 0) {
var ev = tempEvents[0];
if (ev.Time != time0) break;
if (ev.Container != null) {
states[ev.Container].Handle(ev);
}
tempEvents.RemoveAt(0);
}
}
}
else {
Time = toTime;
foreach (var s in workingStates) s.Handle(null);
ValidateStates();
foreach (var s in activeStates) s.Handle(null);
}
ValidateStates();
}
private void ValidateStates() {
foreach (var s in invalidatedStates)
if (s.Working && !workingStates.Contains(s)) workingStates.Add(s);
else if (!s.Working && workingStates.Contains(s)) workingStates.Remove(s);
if (s.Active && !activeStates.Contains(s)) activeStates.Add(s);
else if (!s.Active && activeStates.Contains(s)) activeStates.Remove(s);
invalidatedStates.Clear();
}
@@ -154,12 +171,21 @@ namespace Cryville.Crtr.Event {
RootState.BroadcastPostInit();
}
public void BroadcastEndUpdate() {
RootState.BroadcastEndUpdate();
public void EndPreGraphicalUpdate() {
RootState.EndPreGraphicalUpdate();
}
public void EndGraphicalUpdate() {
RootState.EndGraphicalUpdate();
foreach (var ev in tempEvents) {
if (ev.Container != null) {
states[ev.Container].Discard(ev);
}
}
tempEvents.Clear();
}
public void Anchor() {
RootState.Anchor();
if (RootState.Handler.Alive) RootState.Anchor();
}
}
}

View File

@@ -0,0 +1,55 @@
using Cryville.Common;
using Cryville.Common.Buffers;
using System.Collections.Generic;
namespace Cryville.Crtr.Event {
internal class MotionCache {
public bool Valid { get; set; }
public Vector Value { get; set; }
public void CopyTo(MotionCache dest) {
dest.Valid = Valid;
Value.CopyTo(dest.Value);
}
}
internal class MotionCachePool {
private class Bucket : ObjectPool<MotionCache> {
readonly MotionRegistry _reg;
public Bucket(string name, int capacity) : base(capacity) {
_reg = ChartPlayer.motionRegistry[name];
}
protected override MotionCache Construct() {
var result = new MotionCache();
result.Value = (Vector)ReflectionHelper.InvokeEmptyConstructor(_reg.Type);
return result;
}
}
static Dictionary<Identifier, Bucket> _buckets;
public static void Prepare() {
_buckets = new Dictionary<Identifier, Bucket>(ChartPlayer.motionRegistry.Count);
foreach (var reg in ChartPlayer.motionRegistry)
_buckets.Add(reg.Key, new Bucket(reg.Key, 4096));
}
static readonly SimpleObjectPool<Dictionary<MotionCache, Identifier>> _dictPool
= new SimpleObjectPool<Dictionary<MotionCache, Identifier>>(1024);
Dictionary<MotionCache, Identifier> _rented;
public MotionCache Rent(Identifier name) {
var obj = _buckets[name].Rent();
obj.Valid = false;
if (_rented == null) _rented = _dictPool.Rent();
_rented.Add(obj, name);
return obj;
}
public void Return(MotionCache obj) {
_buckets[_rented[obj]].Return(obj);
_rented.Remove(obj);
}
public void ReturnAll() {
if (_rented == null) return;
foreach (var obj in _rented)
_buckets[obj.Value].Return(obj.Key);
_rented.Clear();
_dictPool.Return(_rented);
}
}
}

View File

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

View File

@@ -20,11 +20,13 @@ namespace Cryville.Crtr.Event {
_buckets.Add(reg.Key, new Bucket(reg.Key, 4096));
}
readonly Dictionary<RealtimeMotionValue, Identifier> _rented = new Dictionary<RealtimeMotionValue, Identifier>();
static readonly SimpleObjectPool<Dictionary<RealtimeMotionValue, Identifier>> _dictPool
= new SimpleObjectPool<Dictionary<RealtimeMotionValue, Identifier>>(1024);
Dictionary<RealtimeMotionValue, Identifier> _rented;
public RealtimeMotionValue Rent(Identifier name) {
var n = name;
var obj = _buckets[n].Rent();
_rented.Add(obj, n);
var obj = _buckets[name].Rent();
if (_rented == null) _rented = _dictPool.Rent();
_rented.Add(obj, name);
return obj;
}
public void Return(RealtimeMotionValue obj) {
@@ -32,9 +34,11 @@ namespace Cryville.Crtr.Event {
_rented.Remove(obj);
}
public void ReturnAll() {
if (_rented == null) return;
foreach (var obj in _rented)
_buckets[obj.Value].Return(obj.Key);
_rented.Clear();
_dictPool.Return(_rented);
}
}
}

View File

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

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

View File

@@ -18,11 +18,11 @@ namespace Cryville.Crtr.Extensions.Malody {
public override IEnumerable<Resource> ConvertFrom(FileInfo file) {
List<Resource> result = new List<Resource>();
MalodyChart src;
if (file.Extension != ".mc") throw new NotImplementedException("mcz file is not supported");
if (file.Extension != ".mc") throw new NotImplementedException("mcz file is not supported yet");
using (var reader = new StreamReader(file.FullName)) {
src = JsonConvert.DeserializeObject<MalodyChart>(reader.ReadToEnd());
}
if (src.meta.mode != 0) throw new NotImplementedException("The chart mode is not supported");
if (src.meta.mode != 0) throw new NotImplementedException(string.Format("{0} mode is not supported yet", MODES[src.meta.mode]));
var ruleset = "malody!" + MODES[src.meta.mode];
if (src.meta.mode == 0) {
@@ -73,30 +73,28 @@ namespace Cryville.Crtr.Extensions.Malody {
Dictionary<MalodyChart.IEvent, StartEventState> longEvents
= new Dictionary<MalodyChart.IEvent, StartEventState>();
float? baseBpm = null, cbpm = null;
float pbeat = 0f, ctime = 0f;
int[] endbeat = new int[] { 0, 0, 1 };
float? baseBpm = null;
var tm = new FractionalBeatTimeTimingModel();
foreach (var ev in events) {
float cbeat = ConvertBeat(ev.beat);
ctime += cbpm == null ? 0 : (cbeat - pbeat) / cbpm.Value * 60f;
pbeat = cbeat;
var beat = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]);
tm.ForwardTo(beat);
if (ev is MalodyChart.Time) {
var tev = (MalodyChart.Time)ev;
if (baseBpm == null) baseBpm = tev.bpm;
cbpm = tev.bpm;
tm.BPM = tev.bpm;
chart.sigs.Add(new Chart.Signature {
time = new BeatTime(ev.beat[0], ev.beat[1], ev.beat[2]),
time = beat,
tempo = tev.bpm,
});
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)
});
}
else if (ev is MalodyChart.Effect) {
var tev = (MalodyChart.Effect)ev;
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)
});
}
@@ -112,22 +110,20 @@ namespace Cryville.Crtr.Extensions.Malody {
offset = -tev.offset / 1000f,
});
}
else throw new NotImplementedException();
else throw new NotImplementedException("Key sounds are not supported yet");
}
else {
if (ConvertBeat(tev.beat) > ConvertBeat(endbeat)) endbeat = tev.beat;
var rn = new Chart.Note() {
time = new BeatTime(tev.beat[0], tev.beat[1], tev.beat[2]),
time = beat,
motions = new List<Chart.Motion> {
new Chart.Motion() { motion = "track:" + tev.column.ToString(CultureInfo.InvariantCulture) }
},
};
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]);
longEvents.Add(ev, new StartEventState {
Destination = rn,
Time = ctime,
Time = tm.Time,
});
}
group.notes.Add(rn);
@@ -139,12 +135,14 @@ namespace Cryville.Crtr.Extensions.Malody {
var sev = tev.StartEvent;
longEvents.Remove(sev);
}
else throw new NotSupportedException();
else throw new NotSupportedException("Unrecognized long event");
}
else throw new NotSupportedException();
else throw new NotSupportedException("Unrecognized event");
}
chart.endtime = new BeatTime(endbeat[0] + 4, endbeat[1], endbeat[2]);
meta.length = ctime;
var endbeat = tm.FractionalBeatTime;
endbeat.b += 4;
chart.endtime = endbeat;
meta.length = (float)tm.Time;
meta.note_count = group.notes.Count;
string chartName = string.Format("{0} - {1}", meta.song.name, meta.name);
if (src.meta.background != null) {
@@ -155,77 +153,73 @@ namespace Cryville.Crtr.Extensions.Malody {
}
struct StartEventState {
public float Time { get; set; }
public double Time { get; set; }
public ChartEvent Destination { get; set; }
}
float ConvertBeat(int[] beat) {
return beat[0] + (float)beat[1] / beat[2];
}
}
#pragma warning disable IDE1006
struct MalodyChart {
public interface IEvent {
int[] beat { get; set; }
int[] endbeat { get; set; }
int Priority { get; }
}
public struct EndEvent : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public IEvent StartEvent { get; set; }
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;
struct MalodyChart {
public interface IEvent {
int[] beat { get; set; }
int[] endbeat { get; set; }
int Priority { get; }
}
public struct EndEvent : IEvent {
public int[] beat { get; set; }
public int[] endbeat { get; set; }
public IEvent StartEvent { get; set; }
public int Priority { get { return StartEvent.Priority - 1; } }
}
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 version;
public string background;
public int mode;
public ModeExt mode_ext;
public struct ModeExt {
public string creator;
public string version;
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 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
}
}

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

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

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6823ead66b33bc048bbad48719feb25d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
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

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dbc046e7cabacbb4fbf74520399a7340
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,383 @@
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>();
bool ftc = false;
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 NotImplementedException("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, ref ftc, section, line);
}
}
if (meta.ruleset == "osu!mania") {
chart.ruleset = meta.ruleset += "." + diff.CircleSize.ToString(CultureInfo.InvariantCulture) + "k";
}
if (!ftc) throw new InvalidOperationException("Unconvertible chart: no timing point is present in this beatmap");
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 { time = tm.FractionalBeatTime, 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, ref bool ftc, 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, ref ftc, 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 NotImplementedException("osu!standard mode is not supported yet");
case 1: /*ruleset += "taiko";*/ throw new NotImplementedException("osu!taiko mode is not supported yet");
case 2: /*ruleset += "catch";*/ throw new NotImplementedException("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, ref bool ftc, 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");
var ev = new osuEvent.TimingChange { StartTime = time, BeatLength = beatLength, TimeSignature = timeSignature };
if (!ftc) {
ftc = true;
ev.StartTime = time % beatLength - beatLength;
}
evs.Add(ev);
}
// 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,8 +1,10 @@
using Cryville.Audio;
using Cryville.Audio.Source;
using Cryville.Common;
using Cryville.Common.Font;
using Cryville.Common.Unity;
using Cryville.Common.Unity.Input;
using Cryville.Common.Unity.UI;
using FFmpeg.AutoGen;
using Ionic.Zip;
using Newtonsoft.Json;
@@ -127,6 +129,21 @@ namespace Cryville.Crtr {
Settings.Default.LastRunVersion = Application.version;
Settings.Default.Save();
Logger.Log("main", 1, "UI", "Initializing font manager");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
var fontMatcher = new FallbackListFontMatcher(new FontManagerWindows());
fontMatcher.LoadDefaultWindowsFallbackList();
TMPAutoFont.FontMatcher = fontMatcher;
TMPAutoFont.DefaultShader = Resources.Load<Shader>("TextMesh Pro/Shaders/TMP_SDF SSD");
#elif UNITY_ANDROID
var fontMatcher = new FallbackListFontMatcher(new FontManagerAndroid());
fontMatcher.LoadDefaultAndroidFallbackList();
TMPAutoFont.FontMatcher = fontMatcher;
TMPAutoFont.DefaultShader = Resources.Load<Shader>("TextMesh Pro/Shaders/TMP_SDF-Mobile SSD");
#else
#error No font manager initialization logic.
#endif
Logger.Log("main", 1, "Game", "Initialized");
}

View File

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

View File

@@ -65,10 +65,6 @@ namespace Cryville.Crtr {
if (_use[target] > 0)
throw new InvalidOperationException("Input already assigned");
if (proxy.Source != null) {
if (_judge != null) {
proxy.Source.Value.Handler.OnInput -= OnInput; // Prevent duplicated hooks, no exception will be thrown
proxy.Source.Value.Handler.OnInput += OnInput;
}
_tproxies.Add(target, proxy);
_sproxies.Add(proxy.Source.Value, proxy);
IncrementUseRecursive(target);
@@ -77,7 +73,6 @@ namespace Cryville.Crtr {
}
void Remove(InputProxyEntry proxy) {
var target = proxy.Target;
if (_judge != null) _tproxies[target].Source.Value.Handler.OnInput -= OnInput;
_sproxies.Remove(_tproxies[target].Source.Value);
_tproxies.Remove(target);
DecrementUseRecursive(target);
@@ -142,12 +137,22 @@ namespace Cryville.Crtr {
public void Activate() {
_activeCounts.Clear();
_vect.Clear(); _vecs.Clear();
foreach (var src in _sproxies.Keys) {
_activeCounts.Add(src, 0);
src.Handler.Activate();
foreach (var src in _sproxies) {
_activeCounts.Add(src.Key, 0);
var isrc = src.Value.Source;
if (isrc != null) {
isrc.Value.Handler.OnInput += OnInput;
}
}
}
public void Deactivate() {
foreach (var src in _sproxies) {
var isrc = src.Value.Source;
if (isrc != null) {
isrc.Value.Handler.OnInput -= OnInput;
}
}
}
public void Deactivate() { foreach (var src in _sproxies.Keys) src.Handler.Deactivate(); }
~InputProxy() {
Dispose(false);
@@ -173,7 +178,7 @@ namespace Cryville.Crtr {
readonly Dictionary<InputHandler, double> _timeOrigins = new Dictionary<InputHandler, double>();
readonly Dictionary<InputSource, int> _activeCounts = new Dictionary<InputSource, int>();
readonly Dictionary<InputIdentifier, float> _vect = new Dictionary<InputIdentifier, float>();
readonly Dictionary<ProxiedInputIdentifier, PropSrc.Arbitrary> _vecs = new Dictionary<ProxiedInputIdentifier, PropSrc.Arbitrary>();
readonly Dictionary<ProxiedInputIdentifier, PropSrc> _vecs = new Dictionary<ProxiedInputIdentifier, PropSrc>();
static readonly PropSrc.Arbitrary _nullsrc = new PropSrc.Arbitrary(PdtInternalType.Null, new byte[0]);
unsafe void OnInput(InputIdentifier id, InputVector vec) {
lock (_lock) {
@@ -214,7 +219,7 @@ namespace Cryville.Crtr {
}
else {
var pid = new ProxiedInputIdentifier { Source = id, Target = target };
PropSrc.Arbitrary fv, tv = _etor.ContextCascadeLookup(_var_value);
PropSrc fv, tv = _etor.ContextCascadeLookup(_var_value);
if (!_vecs.TryGetValue(pid, out fv)) fv = _nullsrc;
if (fv.Type != PdtInternalType.Null || tv.Type != PdtInternalType.Null) {
if (fv.Type == PdtInternalType.Null) _activeCounts[id.Source]++;
@@ -232,8 +237,7 @@ namespace Cryville.Crtr {
public void SyncTime(double time) {
foreach (var s in _sproxies.Keys) {
var h = s.Handler;
if (!_timeOrigins.ContainsKey(h))
_timeOrigins.Add(h, h.GetCurrentTimestamp() - time);
_timeOrigins[h] = h.GetCurrentTimestamp() - time;
}
}
public void ForceTick() {

View File

@@ -1,13 +1,14 @@
using Cryville.Common;
using Cryville.Common.Buffers;
using Cryville.Common.Pdt;
using Cryville.Crtr.Event;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Formatting;
namespace Cryville.Crtr {
public class Judge {
#region Data
readonly PdtEvaluator _etor;
readonly PdtRuleset _rs;
readonly Dictionary<Identifier, float> ct
@@ -16,13 +17,14 @@ namespace Cryville.Crtr {
= new Dictionary<Identifier, List<JudgeEvent>>();
readonly Dictionary<Identifier, List<JudgeEvent>> activeEvs
= new Dictionary<Identifier, List<JudgeEvent>>();
struct JudgeEvent {
public float StartTime { get; set; }
public float EndTime { get; set; }
public float StartClip { get; set; }
public float EndClip { get; set; }
public struct JudgeEvent {
public double StartTime { get; set; }
public double EndTime { get; set; }
public double StartClip { get; set; }
public double EndClip { get; set; }
public Chart.Judge BaseEvent { get; set; }
public JudgeDefinition Definition { get; set; }
public ContainerState State { get; set; }
public NoteHandler Handler { get; set; }
}
static readonly IComparer<JudgeEvent> _stcmp = new JudgeEventStartTimeComparer();
class JudgeEventStartTimeComparer : IComparer<JudgeEvent> {
@@ -33,37 +35,54 @@ namespace Cryville.Crtr {
public Judge(PdtRuleset rs) {
_etor = ChartPlayer.etor;
_rs = rs;
_numsrc1 = new PropSrc.Float(() => _numbuf1);
_numsrc2 = new PropSrc.Float(() => _numbuf2);
_numsrc3 = new PropSrc.Float(() => _numbuf3);
_numsrc4 = new PropSrc.Float(() => _numbuf4);
InitJudges();
InitScores();
}
public void Prepare(float st, float et, Identifier input, JudgeDefinition def, ContainerState container) {
public void Prepare(StampedEvent sev, NoteHandler handler) {
var tev = (Chart.Judge)sev.Unstamped;
Identifier input = default(Identifier);
ChartPlayer.etor.Evaluate(new PropOp.Identifier(v => input = new Identifier(v)), _rs.judges[tev.Id].input);
double st = sev.Time, et = st + sev.Duration;
List<JudgeEvent> list;
if (!evs.TryGetValue(input, out list)) {
ct.Add(input, 0);
evs.Add(input, list = new List<JudgeEvent>());
activeEvs.Add(input, new List<JudgeEvent>());
}
var def = _rs.judges[tev.Id];
var ev = new JudgeEvent {
StartTime = st,
EndTime = et,
StartClip = st + def.clip[0],
EndClip = et + def.clip[1],
StartClip = st + def.clip.Behind,
EndClip = et + def.clip.Ahead,
BaseEvent = tev,
Definition = def,
State = container,
Handler = handler,
};
var index = list.BinarySearch(ev, _stcmp);
if (index < 0) index = ~index;
list.Insert(index, ev);
}
#endregion
#region Judge
internal readonly Dictionary<int, int> judgeMap = new Dictionary<int, int>();
void InitJudges() {
foreach (var i in _rs.judges.Keys) {
judgeMap.Add(i.Key, IdentifierManager.SharedInstance.Request("judge_" + i.Name));
}
}
static bool _flag;
static readonly PropOp.Boolean _flagop = new PropOp.Boolean(v => _flag = v);
static readonly int _var_fn = IdentifierManager.SharedInstance.Request("fn");
static readonly int _var_tn = IdentifierManager.SharedInstance.Request("tn");
static readonly int _var_ft = IdentifierManager.SharedInstance.Request("ft");
static readonly int _var_tt = IdentifierManager.SharedInstance.Request("tt");
readonly byte[] _numbuf1 = new byte[sizeof(float)];
readonly byte[] _numbuf2 = new byte[sizeof(float)];
readonly byte[] _numbuf3 = new byte[sizeof(float)];
readonly byte[] _numbuf4 = new byte[sizeof(float)];
float _numbuf1, _numbuf2, _numbuf3, _numbuf4;
readonly PropSrc _numsrc1, _numsrc2, _numsrc3, _numsrc4;
unsafe void LoadNum(byte[] buffer, float value) {
fixed (byte* ptr = buffer) *(float*)ptr = value;
}
@@ -100,22 +119,22 @@ namespace Cryville.Crtr {
Forward(target, tt);
var actlist = activeEvs[target];
if (actlist.Count > 0) {
LoadNum(_numbuf3, ft); _etor.ContextCascadeUpdate(_var_ft, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf3));
LoadNum(_numbuf4, tt); _etor.ContextCascadeUpdate(_var_tt, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf4));
_numbuf3 = ft; _numsrc3.Invalidate(); _etor.ContextCascadeUpdate(_var_ft, _numsrc3);
_numbuf4 = tt; _numsrc4.Invalidate(); _etor.ContextCascadeUpdate(_var_tt, _numsrc4);
var index = 0;
while (index >= 0 && index < actlist.Count) {
var ev = actlist[index];
LoadNum(_numbuf1, 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));
_numbuf1 = (float)ev.StartTime; _numsrc1.Invalidate(); _etor.ContextCascadeUpdate(_var_fn, _numsrc1);
_numbuf2 = (float)ev.EndTime; _numsrc2.Invalidate(); _etor.ContextCascadeUpdate(_var_tn, _numsrc2);
var def = ev.Definition;
if (def.hit != null) _etor.Evaluate(_flagop, def.hit);
else _flag = true;
if (_flag) {
if (def.scores != null) UpdateScore(def.scores);
if (def.pass != null) Pass(def.pass);
if (def.pass != null) Pass(ev, (ft + tt) / 2, def.pass);
actlist.RemoveAt(index);
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;
}
else index++;
@@ -124,14 +143,15 @@ namespace Cryville.Crtr {
}
}
}
bool Pass(Identifier[] ids) {
bool Pass(JudgeEvent ev, float time, Identifier[] ids) {
foreach (var i in ids) {
var def = _rs.judges[i];
if (def.hit != null) _etor.Evaluate(_flagop, def.hit);
else _flag = true;
if (_flag) {
if (def.scores != null) UpdateScore(def.scores);
if (def.pass != null) Pass(def.pass);
if (def.pass != null) Pass(ev, time, def.pass);
ev.Handler.ReportJudge(ev, time, i);
return true;
}
}
@@ -144,7 +164,7 @@ namespace Cryville.Crtr {
JudgeEvent ev = actlist[i];
if (tt > ev.EndClip) {
actlist.RemoveAt(i);
if (ev.Definition.miss != null) Pass(ev.Definition.miss);
if (ev.Definition.miss != null) Pass(ev, tt, ev.Definition.miss);
}
}
}
@@ -154,7 +174,7 @@ namespace Cryville.Crtr {
JudgeEvent ev;
while (list.Count > 0 && (ev = list[0]).StartClip <= tt) {
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;
actlist.Insert(index, ev);
}
@@ -174,6 +194,8 @@ namespace Cryville.Crtr {
}
}
}
#endregion
#region Score
readonly Dictionary<int, int> scoreStringKeys = new Dictionary<int, int>();
readonly Dictionary<int, int> scoreStringKeysRev = new Dictionary<int, int>();
readonly Dictionary<int, PropSrc> scoreSrcs = new Dictionary<int, PropSrc>();
@@ -183,6 +205,9 @@ namespace Cryville.Crtr {
readonly Dictionary<int, string> scoreStringCache = new Dictionary<int, string>();
readonly Dictionary<int, PropSrc> scoreStringSrcs = new Dictionary<int, PropSrc>();
readonly ArrayPool<byte> scoreStringPool = new ArrayPool<byte>();
readonly Dictionary<int, string> scoreFormatCache = new Dictionary<int, string>();
readonly TargetString scoreFullStr = new TargetString();
readonly StringBuffer scoreFullBuf = new StringBuffer();
void InitScores() {
foreach (var s in _rs.scores) {
var key = s.Key.Key;
@@ -194,7 +219,8 @@ namespace Cryville.Crtr {
scoreDefs.Add(key, s.Value);
scores.Add(key, s.Value.init);
scoreStringCache.Add(scoreStringKeys[key], null);
scoreStringSrcs.Add(scoreStringKeys[key], new ScoreStringSrc(scoreStringPool, () => GetScoreString(strkey)));
scoreStringSrcs.Add(scoreStringKeys[key], new ScoreStringSrc(scoreStringPool, () => scores[key], scoreDefs[key].format));
scoreFormatCache[key] = string.Format("{{0:{0}}}", s.Value.format);
}
}
void InvalidateScore(int key) {
@@ -202,65 +228,65 @@ namespace Cryville.Crtr {
scoreStringCache[scoreStringKeys[key]] = null;
scoreStringSrcs[scoreStringKeys[key]].Invalidate();
}
string GetScoreString(int key) {
var result = scoreStringCache[key];
if (result == null) {
var rkey = scoreStringKeysRev[key];
return scoreStringCache[key] = scores[rkey].ToString(scoreDefs[rkey].format, CultureInfo.InvariantCulture);
}
else return result;
}
public bool TryGetScoreSrc(int key, out PropSrc value) {
return scoreSrcs.TryGetValue(key, out value);
}
public bool TryGetScoreStringSrc(int key, out PropSrc value) {
return scoreStringSrcs.TryGetValue(key, out value);
}
public string GetFullFormattedScoreString() {
public TargetString GetFullFormattedScoreString() {
bool flag = false;
string result = "";
scoreFullBuf.Clear();
foreach (var s in scores.Keys) {
result += string.Format(flag ? "\n{0}: {1}" : "{0}: {1}", IdentifierManager.SharedInstance.Retrieve(s), GetScoreString(scoreStringKeys[s]));
scoreFullBuf.AppendFormat(flag ? "\n{0}: " : "{0}: ", (string)IdentifierManager.SharedInstance.Retrieve(s));
scoreFullBuf.AppendFormat(scoreFormatCache[s], scores[s]);
flag = true;
}
return result;
scoreFullStr.Length = scoreFullBuf.Count;
var arr = scoreFullStr.TrustedAsArray();
scoreFullBuf.CopyTo(0, arr, 0, scoreFullBuf.Count);
return scoreFullStr;
}
class ScoreStringSrc : PropSrc {
readonly Func<string> _cb;
readonly Func<float> _cb;
readonly string _format;
readonly ArrayPool<byte> _pool;
byte[] _buf;
public ScoreStringSrc(ArrayPool<byte> pool, Func<string> cb) {
readonly StringBuffer _buf = new StringBuffer() { Culture = CultureInfo.InvariantCulture };
public ScoreStringSrc(ArrayPool<byte> pool, Func<float> cb, string format)
: base(PdtInternalType.String) {
_pool = pool;
_cb = cb;
_format = string.Format("{{0:{0}}}", format);
}
public override void Invalidate() {
base.Invalidate();
if (_buf != null) {
_pool.Return(_buf);
_buf = null;
if (buf != null) {
_pool.Return(buf);
base.Invalidate();
}
}
protected override unsafe void InternalGet(out int type, out byte[] value) {
protected override unsafe void InternalGet() {
var src = _cb();
int strlen = src.Length;
type = PdtInternalType.String;
value = _pool.Rent(sizeof(int) + strlen * sizeof(char));
fixed (byte* _ptr = value) {
char* ptr = (char*)(_ptr + sizeof(int));
_buf.Clear();
_buf.AppendFormat(_format, src);
int strlen = _buf.Count;
buf = _pool.Rent(sizeof(int) + strlen * sizeof(char));
fixed (byte* _ptr = buf) {
*(int*)_ptr = strlen;
int i = 0;
foreach (var c in src) ptr[i++] = c;
char* ptr = (char*)(_ptr + sizeof(int));
_buf.CopyTo(ptr, 0, strlen);
}
}
}
#endregion
}
#region Definitions
public class InputDefinition {
public int dim;
public bool notnull;
public Dictionary<Identifier, PdtExpression> pass;
}
public class JudgeDefinition {
public float[] clip;
public Clip clip;
public PdtExpression input;
public PdtExpression hit;
public Identifier[] pass;
@@ -282,4 +308,5 @@ namespace Cryville.Crtr {
public float init = 0;
public string format = "";
}
#endregion
}

View File

@@ -1,11 +1,10 @@
fileFormatVersion: 2
guid: ceefede648e4d6d40839f2dda9019066
timeCreated: 1637222453
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
executionOrder: -500
icon: {instanceID: 0}
userData:
assetBundleName:

View File

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

View File

@@ -23,9 +23,9 @@ namespace Cryville.Crtr {
}
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());
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 {
@@ -35,7 +35,7 @@ namespace Cryville.Crtr {
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());
var t = Delerp(value, fv, tv, type, rate);
return ft * (1 - t) + tt * t;
@@ -351,6 +351,8 @@ namespace Cryville.Crtr {
public abstract class Vector : IComparable<Vector> {
public Vector() { }
public abstract byte Dimension { get; }
public abstract int CompareTo(Vector other);
public abstract void ApplyFrom(Vector parent);
@@ -392,6 +394,8 @@ namespace Cryville.Crtr {
Value = i;
}
public override byte Dimension { get { return 1; } }
public override int CompareTo(Vector other) {
return CompareTo((Vec1)other);
}
@@ -457,6 +461,8 @@ namespace Cryville.Crtr {
Value = i;
}
public override byte Dimension { get { return 1; } }
public override int CompareTo(Vector other) {
throw new NotImplementedException();
}
@@ -517,6 +523,8 @@ namespace Cryville.Crtr {
Value = i;
}
public override byte Dimension { get { return 1; } }
public override int CompareTo(Vector other) {
throw new NotImplementedException();
}
@@ -578,6 +586,8 @@ namespace Cryville.Crtr {
this.h = h;
}
public override byte Dimension { get { return 2; } }
public static void Parse(string s, out float? w, out float? h) {
string[] c = s.Split('+');
float rw = 0, rh = 0;
@@ -697,6 +707,8 @@ namespace Cryville.Crtr {
this.x = x; this.y = y; this.z = z;
}
public override byte Dimension { get { return 3; } }
public override int CompareTo(Vector other) {
throw new NotImplementedException();
}
@@ -773,6 +785,8 @@ namespace Cryville.Crtr {
this.xw = xw; this.xh = xh; this.yw = yw; this.yh = yh;
}
public override byte Dimension { get { return 4; } }
public override int CompareTo(Vector other) {
throw new NotImplementedException();
}
@@ -852,6 +866,8 @@ namespace Cryville.Crtr {
this.xw = xw; this.xh = xh; this.yw = yw; this.yh = yh; this.z = z;
}
public override byte Dimension { get { return 5; } }
public override int CompareTo(Vector other) {
throw new NotImplementedException();
}
@@ -925,22 +941,29 @@ namespace Cryville.Crtr {
}
}
public class VectorSrc : PropSrc {
readonly Func<Vector> _cb;
public VectorSrc(Func<Vector> cb) { _cb = cb; }
protected override unsafe void InternalGet(out int type, out byte[] value) {
var arr = _cb().ToArray();
if (arr.Length == 1) {
type = PdtInternalType.Number;
value = new byte[sizeof(float)];
fixed (byte* ptr = value) {
public abstract class VectorSrc : PropSrc {
protected readonly Func<Vector> _cb;
public VectorSrc(Func<Vector> cb, int type) : base(type) { _cb = cb; }
public static VectorSrc Construct(Func<Vector> cb) {
if (cb().Dimension == 1) return new INumber(cb);
else return new IVector(cb);
}
class INumber : VectorSrc {
public INumber(Func<Vector> cb) : base(cb, PdtInternalType.Number) { }
protected override unsafe void InternalGet() {
var arr = _cb().ToArray();
buf = new byte[sizeof(float)];
fixed (byte* ptr = buf) {
*(float*)ptr = arr[0];
}
}
else {
type = PdtInternalType.Vector;
value = new byte[sizeof(float) * arr.Length + sizeof(int)];
fixed (byte* rptr = value) {
}
class IVector : VectorSrc {
public IVector(Func<Vector> cb) : base(cb, PdtInternalType.Vector) { }
protected override unsafe void InternalGet() {
var arr = _cb().ToArray();
buf = new byte[sizeof(float) * arr.Length + sizeof(int)];
fixed (byte* rptr = buf) {
var ptr = (float*)rptr;
for (int i = 0; i < arr.Length; i++, ptr++) {
*ptr = arr[i];

View File

@@ -7,44 +7,70 @@ using System.Collections.Generic;
using UnityEngine;
namespace Cryville.Crtr {
class NoteHandler : ContainerHandler {
public class NoteHandler : ContainerHandler {
readonly GroupHandler gh;
public readonly Chart.Note Event;
readonly PdtRuleset ruleset;
public NoteHandler(GroupHandler gh, Chart.Note ev, PdtRuleset rs, Judge j) : base() {
this.gh = gh;
public NoteHandler(Chart.Note ev, GroupHandler gh) : base() {
Event = ev;
ruleset = rs;
judge = j;
this.gh = gh;
}
public override string TypeName {
get {
return "note";
public override string TypeName { get { return "note"; } }
SectionalGameObject[] sgos;
readonly Dictionary<Chart.Judge, JudgeState> judges = new Dictionary<Chart.Judge, JudgeState>();
class JudgeState {
static readonly int _var_judge_result = IdentifierManager.SharedInstance.Request("judge_result");
static readonly int _var_judge_time_absolute = IdentifierManager.SharedInstance.Request("judge_time_absolute");
static readonly int _var_judge_time_relative = IdentifierManager.SharedInstance.Request("judge_time_relative");
public Anchor StaticAnchor { get; private set; }
public float AbsoluteTime { get; private set; }
PropSrc _jtabsPropSrc;
public float RelativeTime { get; private set; }
PropSrc _jtrelPropSrc;
public int Result { get; private set; }
PropSrc _resultPropSrc;
public JudgeState(NoteHandler handler, int name) {
StaticAnchor = handler.RegisterAnchor(handler.judge.judgeMap[name], false, 3);
}
public void MarkJudged(float abs, float rel, int result) {
AbsoluteTime = abs;
RelativeTime = rel;
Result = result;
_jtabsPropSrc.Invalidate();
_jtrelPropSrc.Invalidate();
_resultPropSrc.Invalidate();
}
public void InitPropSrcs() {
StaticAnchor.PropSrcs.Add(_var_judge_result, _resultPropSrc = new PropSrc.Identifier(() => Result));
StaticAnchor.PropSrcs.Add(_var_judge_time_absolute, _jtabsPropSrc = new PropSrc.Float(() => AbsoluteTime));
StaticAnchor.PropSrcs.Add(_var_judge_time_relative, _jtrelPropSrc = new PropSrc.Float(() => RelativeTime));
}
}
SectionalGameObject[] sgos;
public override void PreInit() {
base.PreInit();
foreach (var j in Event.judges) {
judges.Add(j, new JudgeState(this, j.Id.Key));
}
}
public override void Init() {
base.Init();
sgos = gogroup.GetComponentsInChildren<SectionalGameObject>();
foreach (var judge in judges.Values) judge.InitPropSrcs();
}
protected override void PreAwake(ContainerState s) {
base.PreAwake(s);
#if UNITY_5_6_OR_NEWER
a_head.SetPositionAndRotation(Position = GetFramePoint(s.Parent, s.Track), Rotation = GetFrameRotation(s.Parent, s.Track));
#else
a_head.position = Position = GetFramePoint(s.Parent, s.Track);
a_head.rotation = Rotation = GetFrameRotation(s.Parent, s.Track);
#endif
}
protected override void Awake(ContainerState s) {
base.Awake(s);
public override void StartPhysicalUpdate(ContainerState s) {
base.StartPhysicalUpdate(s);
if (s.CloneType == 2) {
if (!gogroup) return;
Chart.Note tev = Event;
if (tev.IsLong) {
TransformAwake(s);
}
}
public override void StartGraphicalUpdate(ContainerState s) {
base.StartGraphicalUpdate(s);
TransformAwake(s);
if (gogroup) {
if (Event.IsLong) {
foreach (var i in sgos) {
i.Reset();
i.AppendPoint(Position, Rotation);
@@ -54,25 +80,24 @@ namespace Cryville.Crtr {
#if UNITY_5_6_OR_NEWER
gogroup.SetPositionAndRotation(Position, Rotation);
#else
gogroup.position = Position;
gogroup.rotation = Rotation;
gogroup.position = Position;
gogroup.rotation = Rotation;
#endif
}
}
}
void TransformAwake(ContainerState s) {
Position = GetFramePoint(s.Parent, s.Track);
Rotation = GetFrameRotation(s.Parent, s.Track);
}
public override void Update(ContainerState s, StampedEvent ev) {
base.Update(s, ev);
if (s.CloneType == 1) {
Position = GetFramePoint(bs.Parent, bs.Track);
Rotation = GetFrameRotation(bs.Parent, bs.Track);
}
else if (s.CloneType == 2) {
Position = GetFramePoint(ts.Parent, ts.Track);
Rotation = GetFrameRotation(ts.Parent, ts.Track);
if (!gogroup) return;
Chart.Note tev = Event;
if (tev.IsLong) {
if (s.CloneType <= 2) {
Position = GetFramePoint(s.Parent, s.Track);
Rotation = GetFrameRotation(s.Parent, s.Track);
if (s.CloneType == 2) {
if (!gogroup || !Event.IsLong) return;
foreach (var i in sgos)
i.AppendPoint(Position, Rotation);
}
@@ -81,31 +106,20 @@ namespace Cryville.Crtr {
if (ev == null) { }
else if (ev.Unstamped == null) { }
else if (ev.Unstamped is Chart.Judge) {
var tev = (Chart.Judge)ev.Unstamped;
Identifier name = default(Identifier);
ChartPlayer.etor.ContextEvent = tev;
ChartPlayer.etor.ContextEvent = ev.Unstamped;
ChartPlayer.etor.ContextState = s;
ChartPlayer.etor.Evaluate(new PropOp.Identifier(v => name = new Identifier(v)), ruleset.judges[tev.Id].input);
judge.Prepare(ev.Time, ev.Time + ev.Duration, name, ruleset.judges[tev.Id], cs);
judge.Prepare(ev, this);
ChartPlayer.etor.ContextState = null;
ChartPlayer.etor.ContextEvent = null;
}
}
}
public override void EndUpdate(ContainerState s) {
if (s.CloneType == 2 && gogroup) {
public override void EndGraphicalUpdate(ContainerState s) {
if (gogroup) {
foreach (var i in sgos) i.Seal();
#if UNITY_5_6_OR_NEWER
a_tail.SetPositionAndRotation(GetFramePoint(ts.Parent, ts.Track), Quaternion.Euler(ts.Direction));
#else
a_tail.position = GetFramePoint(ts.Parent, ts.Track);
a_tail.rotation = Quaternion.Euler(ts.Direction);
#endif
}
OpenAnchor("tail");
base.EndUpdate(s);
CloseAnchor("tail");
base.EndGraphicalUpdate(s);
}
Vector3 GetFramePoint(ContainerState state, float track) {
@@ -117,6 +131,7 @@ namespace Cryville.Crtr {
return Quaternion.LookRotation(r, state.Normal);
}
readonly List<Vector3> ctrl = new List<Vector3>(2);
Vector3 GetFrame(ContainerState state, float track, Func<ContainerState, Vector3> func) {
// TODO
int id = Mathf.FloorToInt(track);
@@ -134,7 +149,7 @@ namespace Cryville.Crtr {
if (c0 && c1)
return (1 - t) * p1 + t * p2;
else {
var ctrl = new List<Vector3>(2);
ctrl.Clear();
if (!c0) {
var tp = ts0.GetControlPoint(true, deltaz);
if (tp != Vector3.zero) ctrl.Add(tp);
@@ -149,7 +164,7 @@ namespace Cryville.Crtr {
ColumnVector<float>.WithPolynomialCoefficients(
frame.Size, track
),
new Vector3Operator()
Vector3Operator.Instance
);
}
else if (ctrl.Count == 1) {
@@ -161,5 +176,11 @@ namespace Cryville.Crtr {
}
}
}
public void ReportJudge(Judge.JudgeEvent ev, float time, Identifier result) {
JudgeState state;
if (!judges.TryGetValue(ev.BaseEvent, out state)) return;
state.MarkJudged(time, (float)(ev.StartTime - time), result.Key);
}
}
}

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