130 Commits

Author SHA1 Message Date
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
69e4ecd0a9 Fix BestdoriChartConverter generating track motions incorrectly. Add outro time to BestdoriChartConverter. 2022-12-01 12:34:56 +08:00
35d2e06625 Fix improper use of RMVPool. 2022-12-01 12:33:32 +08:00
358e654f51 Code cleanup. 2022-11-28 14:20:49 +08:00
d16548e570 Fix BinarySearchFirst algorithm. 2022-11-28 11:53:13 +08:00
c7201dd62c Add ingame log related settings. 2022-11-26 21:55:29 +08:00
e43a0e62b7 Fix zindex property not working on polysec component. 2022-11-26 21:55:03 +08:00
4bcf76819c Clears the input event queue on input dialog open. 2022-11-26 17:19:47 +08:00
31155c909c Make the buttons in the play scene not interactable with keyboard. 2022-11-24 22:37:59 +08:00
ab2670358a Add scroll bars to file dialog. 2022-11-24 22:37:03 +08:00
3da70bdccc Remove key count limit in Malody chart converter. 2022-11-23 12:03:24 +08:00
e370e1937c Code cleanup. 2022-11-23 12:02:25 +08:00
d9f6dd33d4 Optimize texture size. 2022-11-22 21:48:41 +08:00
e5d6e549bd Code cleanup. 2022-11-21 18:16:12 +08:00
145c0ce6c8 Optimize GC for value updating in text component. 2022-11-21 14:10:20 +08:00
a0174b94c6 Optimize GC for input proxy. 2022-11-21 14:09:44 +08:00
109b489104 Introduce TargetString to eliminate text GC. 2022-11-21 14:09:01 +08:00
784c3fc338 Disable GUI layout on Unity key receiver to avoid GC. 2022-11-21 14:06:57 +08:00
77d6ac2caf Cleanup unused functions. 2022-11-21 12:14:34 +08:00
321af22775 Code cleanup. 2022-11-20 23:17:08 +08:00
39ef9815e8 Fix verbose log about invalid resource. 2022-11-20 23:08:58 +08:00
bb3afba11f Fix import error on cover file missing. 2022-11-20 22:36:53 +08:00
e4fa160a90 Fix log typo. 2022-11-20 19:13:40 +08:00
34df9e2257 Optimize MatchDynamic performance. 2022-11-20 19:04:33 +08:00
cfdb5f021e Reconstruct skin container. Add update clone type limit to skin property. 2022-11-20 16:12:19 +08:00
d08eea5c1e Postpone skin static matching. 2022-11-20 16:09:34 +08:00
ce30b5427b Improve vector cache performance. 2022-11-20 16:02:39 +08:00
e38fed89e9 Update Cryville.Audio. 2022-11-20 13:29:29 +08:00
d4b12bf3f7 Add extra fallback logic for audio engine initialization. 2022-11-20 13:29:09 +08:00
40d75a91c6 Remove IL2CPP incompatibility workaround. 2022-11-20 09:34:37 +08:00
689 changed files with 36631 additions and 2670 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

@@ -0,0 +1,120 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace Cryville.Common.Buffers {
/// <summary>
/// An auto-resized <see cref="char" /> array as a variable-length string used as a target that is modified frequently.
/// </summary>
public class TargetString : IEnumerable<char> {
public event Action OnUpdate;
char[] _arr;
bool _invalidated;
/// <summary>
/// Creates an instance of the <see cref="TargetString" /> class with a capacity of 16.
/// </summary>
public TargetString() : this(16) { }
/// <summary>
/// Creates an instance of the <see cref="TargetString" /> class.
/// </summary>
/// <param name="capacity">The initial capacity of the string.</param>
public TargetString(int capacity) {
_arr = new char[capacity];
}
/// <summary>
/// Gets or sets one of the characters in the string.
/// </summary>
/// <param name="index">The zero-based index of the character.</param>
/// <returns>The character at the given index.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index" /> is less than 0 or not less than <see cref="Length" />.</exception>
/// <remarks>
/// <para>Set <see cref="Length" /> to a desired value before updating the characters.</para>
/// <para>Call <see cref=" Validate" /> after all the characters are updated.</para>
/// </remarks>
public char this[int index] {
get {
if (index < 0 || index >= m_length)
throw new ArgumentOutOfRangeException("index");
return _arr[index];
}
set {
if (index < 0 || index >= m_length)
throw new ArgumentOutOfRangeException("index");
if (_arr[index] == value) return;
_arr[index] = value;
_invalidated = true;
}
}
int m_length;
/// <summary>
/// The length of the string.
/// </summary>
public int Length {
get {
return m_length;
}
set {
if (m_length == value) return;
if (_arr.Length < value) {
var len = m_length;
while (len < value) len *= 2;
var arr2 = new char[len];
Array.Copy(_arr, arr2, m_length);
_arr = arr2;
}
m_length = value;
_invalidated = true;
}
}
/// <summary>
/// Validates the string.
/// </summary>
public void Validate() {
if (!_invalidated) return;
_invalidated = false;
var ev = OnUpdate;
if (ev != null) ev.Invoke();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public IEnumerator<char> GetEnumerator() {
return new Enumerator(this);
}
class Enumerator : IEnumerator<char> {
readonly TargetString _self;
int _index = -1;
public Enumerator(TargetString self) { _self = self; }
public char 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.Length) {
_index = -2;
return false;
}
return true;
}
public void Reset() {
_index = -1;
}
}
}
}

View File

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

View File

@@ -10,10 +10,10 @@ namespace Cryville.Common {
/// </summary> /// </summary>
public static IdentifierManager SharedInstance = new IdentifierManager(); public static IdentifierManager SharedInstance = new IdentifierManager();
Dictionary<object, int> _idents = new Dictionary<object, int>(); readonly Dictionary<object, int> _idents = new Dictionary<object, int>();
List<object> _ids = new List<object>(); readonly List<object> _ids = new List<object>();
object _syncRoot = new object(); readonly object _syncRoot = new object();
/// <summary> /// <summary>
/// Creates an instance of the <see cref="IdentifierManager" /> class. /// Creates an instance of the <see cref="IdentifierManager" /> class.

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
namespace Cryville.Common { namespace Cryville.Common {
@@ -40,7 +41,7 @@ namespace Cryville.Common {
public static void Create(string key, Logger logger) { public static void Create(string key, Logger logger) {
Instances[key] = logger; Instances[key] = logger;
if (logPath != null) { if (logPath != null) {
Files[key] = new StreamWriter(logPath + "/" + ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString() + "-" + key + ".log") { Files[key] = new StreamWriter(logPath + "/" + ((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString(CultureInfo.InvariantCulture) + "-" + key + ".log") {
AutoFlush = true AutoFlush = true
}; };
} }

View File

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

View File

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

View File

@@ -77,7 +77,7 @@ namespace Cryville.Common.Network {
encoding = Encoding.UTF8; encoding = Encoding.UTF8;
payload = encoding.GetBytes(body); payload = encoding.GetBytes(body);
headers.Add("Content-Encoding", encoding.EncodingName); headers.Add("Content-Encoding", encoding.EncodingName);
headers.Add("Content-Length", payload.Length.ToString()); headers.Add("Content-Length", payload.Length.ToString(CultureInfo.InvariantCulture));
} }
string request_line = string.Format( string request_line = string.Format(
"{0} {1} {2}\r\n", method, uri, Version "{0} {1} {2}\r\n", method, uri, Version

View File

@@ -19,9 +19,7 @@ namespace Cryville.Common.Network {
set { throw new NotSupportedException(); } set { throw new NotSupportedException(); }
} }
public override void Flush() { public override void Flush() { }
// Do nothing
}
public abstract byte[] ReadToEnd(); public abstract byte[] ReadToEnd();

View File

@@ -28,7 +28,7 @@ namespace Cryville.Common.Network {
} }
private class InternalTlsClient : DefaultTlsClient { private class InternalTlsClient : DefaultTlsClient {
string _host; readonly string _host;
public InternalTlsClient(string host, TlsCrypto crypto) : base(crypto) { public InternalTlsClient(string host, TlsCrypto crypto) : base(crypto) {
_host = host; _host = host;
@@ -92,9 +92,7 @@ namespace Cryville.Common.Network {
return null; return null;
} }
public void NotifyServerCertificate(TlsServerCertificate serverCertificate) { public void NotifyServerCertificate(TlsServerCertificate serverCertificate) { }
// Do nothing
}
} }
} }
} }

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Cryville.Common.Pdt { namespace Cryville.Common.Pdt {
/// <summary> /// <summary>
@@ -104,7 +105,7 @@ namespace Cryville.Common.Pdt {
else if (i is PdtInstruction.PushVariable) { else if (i is PdtInstruction.PushVariable) {
i.Execute(this); i.Execute(this);
var frame = _stack[_framecount - 1]; 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)); _rip = il.AddAfter(_rip, new PdtInstruction.PushConstant(frame.Type, _mem, frame.Offset, frame.Length));
il.Remove(_rip.Previous); il.Remove(_rip.Previous);
} }
@@ -147,10 +148,10 @@ namespace Cryville.Common.Pdt {
_goffset += value.Length; _goffset += value.Length;
} }
} }
internal unsafe void PushVariable(int name) { internal unsafe void PushVariable(int name, bool forced) {
fixed (StackFrame* frame = &_stack[_framecount++]) { fixed (StackFrame* frame = &_stack[_framecount++]) {
byte[] value; byte[] value;
GetVariable(name, out frame->Type, out value); GetVariable(name, forced, out frame->Type, out value);
frame->Offset = _goffset; frame->Offset = _goffset;
frame->Length = value.Length; frame->Length = value.Length;
Array.Copy(value, 0, _mem, _goffset, 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. /// Gets a variable of the specified name.
/// </summary> /// </summary>
/// <param name="name">The name of the variable.</param> /// <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="type">The type of the variable.</param>
/// <param name="value">The value 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) { internal void Operate(PdtOperatorSignature sig) {
PdtOperator op; PdtOperator op;
try { op = GetOperator(sig); } try { op = GetOperator(sig); }
catch (Exception) { catch (Exception ex) {
for (int i = 0; i < sig.ParamCount; i++) for (int i = 0; i < sig.ParamCount; i++)
DiscardStack(); DiscardStack();
throw; throw new EvaluationFailureException(string.Format("Failed to get operator {0}", sig), ex);
} }
Operate(op, sig.ParamCount); Operate(op, sig.ParamCount);
} }
@@ -222,4 +224,18 @@ namespace Cryville.Common.Pdt {
_goffset -= _stack[--_framecount].Length; _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 class PushVariable : PdtInstruction {
public int Name { get; private set; } public int Name { get; private set; }
public PushVariable(int name) { Name = name; } public bool Forced { get; private set; }
public PushVariable(string name) : this(IdentifierManager.SharedInstance.Request(name)) { } 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) { internal override void Execute(PdtEvaluatorBase etor) {
etor.PushVariable(Name); etor.PushVariable(Name, Forced);
} }
public override string ToString() { 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 { public class Operate : PdtInstruction {
@@ -239,7 +240,11 @@ namespace Cryville.Common.Pdt {
if (defs.TryGetValue(buf.Value.Value, out def)) { if (defs.TryGetValue(buf.Value.Value, out def)) {
foreach (var i in def.Instructions) ins.AddLast(i); 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; buf = null;
TryPushAdjMul(ins, ref flag); TryPushAdjMul(ins, ref flag);
} }

View File

@@ -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, 0x0001, 0x0001, 0x0000, 0x0000, 0x0001, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 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, 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, 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, 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, 0x0000, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030, 0x0030,

View File

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

View File

@@ -4,7 +4,7 @@ namespace Cryville.Common.Pdt {
/// <summary> /// <summary>
/// Span on the memory of a <see cref="PdtEvaluatorBase" />. /// Span on the memory of a <see cref="PdtEvaluatorBase" />.
/// </summary> /// </summary>
public unsafe struct PdtVariableMemory { public unsafe struct PdtVariableMemory : IEquatable<PdtVariableMemory> {
readonly byte* _ptr; readonly byte* _ptr;
/// <summary> /// <summary>
/// The length of the span. /// The length of the span.
@@ -46,6 +46,14 @@ namespace Cryville.Common.Pdt {
for (int i = 0; i < length; i++) for (int i = 0; i < length; i++)
dest[destOffset + i] = _ptr[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> /// <summary>
/// Gets the memory of the span as a number. /// Gets the memory of the span as a number.
/// </summary> /// </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> /// <returns>An array containing all the subclasses of the type in the current app domain.</returns>
public static Type[] GetSubclassesOf<T>() where T : class { public static Type[] GetSubclassesOf<T>() where T : class {
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var assemblies = AppDomain.CurrentDomain.GetAssemblies();
IEnumerable<Type> r = new List<Type>(); IEnumerable<Type> r = Enumerable.Empty<Type>();
foreach (var a in assemblies) foreach (var a in assemblies)
r = r.Concat(a.GetTypes().Where( r = r.Concat(a.GetTypes().Where(
t => t.IsClass t => t.IsClass

View File

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

View File

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

View File

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

View File

@@ -4,29 +4,22 @@ using System.Reflection;
namespace Cryville.Common.Unity.Input { namespace Cryville.Common.Unity.Input {
public class InputManager { public class InputManager {
static readonly List<Type> HandlerRegistries = new List<Type> { static readonly HashSet<Type> HandlerRegistries = new HashSet<Type> {
typeof(WindowsPointerHandler), typeof(WindowsPointerHandler),
typeof(UnityKeyHandler<UnityKeyboardReceiver>), typeof(UnityKeyHandler<UnityKeyboardReceiver>),
typeof(UnityKeyHandler<UnityMouseButtonReceiver>), typeof(UnityKeyHandler<UnityMouseButtonReceiver>),
typeof(UnityMouseHandler), typeof(UnityMouseHandler),
typeof(UnityTouchHandler), typeof(UnityTouchHandler),
}; };
// TODO set private readonly HashSet<InputHandler> _handlers = new HashSet<InputHandler>();
public readonly List<InputHandler> _handlers = new List<InputHandler>();
readonly Dictionary<Type, InputHandler> _typemap = new Dictionary<Type, 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() { public InputManager() {
foreach (var t in HandlerRegistries) { foreach (var t in HandlerRegistries) {
try { try {
if (!typeof(InputHandler).IsAssignableFrom(t)) continue; if (!typeof(InputHandler).IsAssignableFrom(t)) continue;
var h = (InputHandler)ReflectionHelper.InvokeEmptyConstructor(t); var h = (InputHandler)ReflectionHelper.InvokeEmptyConstructor(t);
_typemap.Add(t, h); _typemap.Add(t, h);
h.OnInput += OnInput;
_handlers.Add(h); _handlers.Add(h);
_timeOrigins.Add(h, 0);
Logger.Log("main", 1, "Input", "Initialized {0}", ReflectionHelper.GetSimpleName(t)); Logger.Log("main", 1, "Input", "Initialized {0}", ReflectionHelper.GetSimpleName(t));
} }
catch (TargetInvocationException ex) { catch (TargetInvocationException ex) {
@@ -37,49 +30,8 @@ namespace Cryville.Common.Unity.Input {
public InputHandler GetHandler(string name) { public InputHandler GetHandler(string name) {
return _typemap[Type.GetType(name)]; return _typemap[Type.GetType(name)];
} }
public void Activate() { public void EnumerateHandlers(Action<InputHandler> cb) {
lock (_lock) { foreach (var h in _handlers) cb(h);
_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();
}
} }
} }

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

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

View File

@@ -9,19 +9,19 @@ namespace Cryville.Common.Unity.Input {
public UnityKeyHandler() { } public UnityKeyHandler() { }
protected override void ActivateImpl() { protected override void Activate() {
receiver = new GameObject("__keyrecv__"); receiver = new GameObject("__keyrecv__");
recvcomp = receiver.AddComponent<T>(); recvcomp = receiver.AddComponent<T>();
recvcomp.SetCallback(Feed); recvcomp.SetCallback(Feed);
} }
protected override void DeactivateImpl() { protected override void Deactivate() {
if (receiver) GameObject.Destroy(receiver); if (receiver) GameObject.Destroy(receiver);
} }
public override void Dispose(bool disposing) { public override void Dispose(bool disposing) {
if (disposing) { if (disposing) {
DeactivateImpl(); Deactivate();
} }
} }
@@ -44,11 +44,14 @@ namespace Cryville.Common.Unity.Input {
public abstract class UnityKeyReceiver<T> : MonoBehaviour where T : UnityKeyReceiver<T> { public abstract class UnityKeyReceiver<T> : MonoBehaviour where T : UnityKeyReceiver<T> {
protected Action<int, int, InputVector> Callback; 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) { public void SetCallback(Action<int, int, InputVector> h) {
Callback = h; Callback = h;
} }
public abstract string GetKeyName(int type); public abstract string GetKeyName(int type);
void Awake() {
useGUILayout = false;
}
void Update() { void Update() {
double time = Time.realtimeSinceStartupAsDouble; double time = Time.realtimeSinceStartupAsDouble;
foreach (var k in Keys) { foreach (var k in Keys) {

View File

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

View File

@@ -61,7 +61,7 @@ namespace Cryville.Common.Unity.Input {
public const int TABLET_DISABLE_PENBARRELFEEDBACK = 0x00000010; public const int TABLET_DISABLE_PENBARRELFEEDBACK = 0x00000010;
public const int TABLET_DISABLE_FLICKS = 0x00010000; public const int TABLET_DISABLE_FLICKS = 0x00010000;
protected override void ActivateImpl() { protected override void Activate() {
newWndProc = WndProc; newWndProc = WndProc;
newWndProcPtr = Marshal.GetFunctionPointerForDelegate(newWndProc); newWndProcPtr = Marshal.GetFunctionPointerForDelegate(newWndProc);
oldWndProcPtr = SetWindowLongPtr(hMainWindow, -4, newWndProcPtr); oldWndProcPtr = SetWindowLongPtr(hMainWindow, -4, newWndProcPtr);
@@ -77,7 +77,7 @@ namespace Cryville.Common.Unity.Input {
); );
} }
protected override void DeactivateImpl() { protected override void Deactivate() {
if (pressAndHoldAtomID != 0) { if (pressAndHoldAtomID != 0) {
NativeMethods.RemoveProp(hMainWindow, PRESS_AND_HOLD_ATOM); NativeMethods.RemoveProp(hMainWindow, PRESS_AND_HOLD_ATOM);
NativeMethods.GlobalDeleteAtom(pressAndHoldAtomID); NativeMethods.GlobalDeleteAtom(pressAndHoldAtomID);
@@ -142,7 +142,7 @@ namespace Cryville.Common.Unity.Input {
} }
public override void Dispose(bool disposing) { public override void Dispose(bool disposing) {
DeactivateImpl(); Deactivate();
if (usePointerMessage) if (usePointerMessage)
NativeMethods.EnableMouseInPointer(false); NativeMethods.EnableMouseInPointer(false);
Instance = null; Instance = null;

View File

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

View File

@@ -126,8 +126,8 @@ namespace Cryville.Common.Unity.UI {
void Update() { void Update() {
Vector2 cprectsize = ((RectTransform)transform.parent).rect.size; Vector2 cprectsize = ((RectTransform)transform.parent).rect.size;
if (cprectsize != pprectsize) { if (cprectsize != pprectsize) {
OnFrameUpdate();
pprectsize = cprectsize; pprectsize = cprectsize;
OnFrameUpdate();
} }
} }
#pragma warning restore IDE0051 #pragma warning restore IDE0051

View File

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

View File

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

View File

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

View File

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

View File

@@ -17,6 +17,8 @@ namespace Cryville.Crtr.Browsing {
static readonly Dictionary<string, List<ResourceConverter>> converters static readonly Dictionary<string, List<ResourceConverter>> converters
= new Dictionary<string, List<ResourceConverter>>(); = new Dictionary<string, List<ResourceConverter>>();
static readonly Dictionary<string, string> localRes
= new Dictionary<string, string>();
public LegacyResourceManager(string rootPath) { public LegacyResourceManager(string rootPath) {
_rootPath = rootPath; _rootPath = rootPath;
@@ -25,13 +27,35 @@ namespace Cryville.Crtr.Browsing {
static LegacyResourceManager() { static LegacyResourceManager() {
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var asm in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (var type in asm.GetTypes()) { foreach (var type in asm.GetTypes()) {
if (type.IsSubclassOf(typeof(ResourceConverter))) { if (!type.IsSubclassOf(typeof(ExtensionInterface))) continue;
var converter = (ResourceConverter)Activator.CreateInstance(type); var ext = (ExtensionInterface)Activator.CreateInstance(type);
foreach (var f in converter.GetSupportedFormats()) { try {
if (!converters.ContainsKey(f)) var cs = ext.GetResourceConverters();
converters.Add(f, new List<ResourceConverter> { converter }); if (cs != null) {
else converters[f].Add(converter); foreach (var c in cs) {
var fs = c.GetSupportedFormats();
if (fs == null) continue;
foreach (var f in fs) {
if (f == null) continue;
if (!converters.ContainsKey(f))
converters.Add(f, new List<ResourceConverter> { c });
else converters[f].Add(c);
}
}
} }
var fs2 = ext.GetResourceFinders();
if (fs2 != null) {
foreach (var f in fs2) {
var name = f.Name;
var path = f.GetRootPath();
if (name != null && path != null)
localRes.Add(name, path);
}
}
Logger.Log("main", 1, "Resource", "Loaded extension {0}", ReflectionHelper.GetNamespaceQualifiedName(type));
}
catch (Exception ex) {
Logger.Log("main", 4, "Resource", "Failed to initialize extension {0}: {1}", ReflectionHelper.GetNamespaceQualifiedName(type), ex);
} }
} }
} }
@@ -150,9 +174,11 @@ namespace Cryville.Crtr.Browsing {
tres.Meta.data = ""; tres.Meta.data = "";
writer.Write(JsonConvert.SerializeObject(tres.Meta, Game.GlobalJsonSerializerSettings)); writer.Write(JsonConvert.SerializeObject(tres.Meta, Game.GlobalJsonSerializerSettings));
} }
if (tres.Meta.cover != null) if (tres.Meta.cover != null) {
new FileInfo(Path.Combine(file.Directory.FullName, tres.Meta.cover)) var coverFile = new FileInfo(Path.Combine(file.Directory.FullName, tres.Meta.cover));
.CopyTo(Path.Combine(dir.FullName, tres.Meta.cover), true); if (coverFile.Exists)
coverFile.CopyTo(Path.Combine(dir.FullName, tres.Meta.cover), true);
}
} }
else if (res is FileResource) { else if (res is FileResource) {
var tres = (FileResource)res; var tres = (FileResource)res;
@@ -196,5 +222,9 @@ namespace Cryville.Crtr.Browsing {
public string[] GetSupportedFormats() { public string[] GetSupportedFormats() {
return converters.Keys.ToArray(); return converters.Keys.ToArray();
} }
public Dictionary<string, string> GetPresetPaths() {
return localRes;
}
} }
} }

View File

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

View File

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

View File

@@ -1,5 +1,6 @@
using Cryville.Common.Unity; using Cryville.Common.Unity;
using Cryville.Common.Unity.UI; using Cryville.Common.Unity.UI;
using System;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
@@ -19,6 +20,9 @@ namespace Cryville.Crtr.Browsing {
_dialog = GameObject.Instantiate(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>(); _dialog = GameObject.Instantiate(Resources.Load<GameObject>("Common/FileDialog")).GetComponent<FileDialog>();
_dialog.gameObject.SetActive(false); _dialog.gameObject.SetActive(false);
_dialog.Filter = ResourceManager.GetSupportedFormats();
_dialog.PresetPaths = ResourceManager.GetPresetPaths();
_dialog.OnClose += OnAddDialogClosed;
} }
private bool LoadPathPart(int id, GameObject obj) { private bool LoadPathPart(int id, GameObject obj) {
@@ -29,8 +33,13 @@ namespace Cryville.Crtr.Browsing {
private bool LoadItem(int id, GameObject obj) { private bool LoadItem(int id, GameObject obj) {
var bi = obj.GetComponent<BrowserItem>(); var bi = obj.GetComponent<BrowserItem>();
var item = ResourceManager.GetItemMeta(id); try {
bi.Load(id, item); var item = ResourceManager.GetItemMeta(id);
bi.Load(id, item);
}
catch (Exception) {
bi.Load(id, new ResourceItemMeta { Name = "<color=#ff0000>Invalid resource</color>" });
}
return true; return true;
} }
@@ -51,8 +60,6 @@ namespace Cryville.Crtr.Browsing {
} }
public void OnAddButtonClicked() { public void OnAddButtonClicked() {
_dialog.Callback = OnAddDialogClosed;
_dialog.Filter = ResourceManager.GetSupportedFormats();
_dialog.Show(); _dialog.Show();
} }

View File

@@ -73,6 +73,9 @@ namespace Cryville.Crtr.Browsing {
Application.LoadLevelAdditive("Play"); Application.LoadLevelAdditive("Play");
#endif #endif
GameObject.Find("/Master").GetComponent<Master>().HideMenu(); 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) { public void OpenConfig(int id, ChartDetail detail) {

View File

@@ -1,7 +1,6 @@
using Cryville.Common; using Cryville.Common;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO; using System.IO;
namespace Cryville.Crtr.Browsing { namespace Cryville.Crtr.Browsing {

View File

@@ -3,18 +3,24 @@ using Newtonsoft.Json;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Globalization;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Cryville.Crtr { namespace Cryville.Crtr {
[JsonConverter(typeof(BeatTimeConverter))] [JsonConverter(typeof(BeatTimeConverter))]
public struct BeatTime { public struct BeatTime : IComparable<BeatTime>, IEquatable<BeatTime> {
[JsonConstructor()] [JsonConstructor()]
public BeatTime(int _b, int _n, int _d) { public BeatTime(int _b, int _n, int _d) {
b = _b; b = _b;
n = _n; n = _n;
d = _d; d = _d;
} }
public BeatTime(int _n, int _d) {
b = _n / _d;
n = _n % _d;
d = _d;
}
[JsonIgnore] [JsonIgnore]
public int b; public int b;
@@ -24,6 +30,36 @@ namespace Cryville.Crtr {
[JsonIgnore] [JsonIgnore]
public int d; public int d;
[JsonIgnore]
public double Decimal { get { return b + (double)n / d; } }
public int CompareTo(BeatTime other) {
var c = b.CompareTo(other.b);
if (c != 0) return c;
return ((double)n / d).CompareTo((double)other.n / other.d);
}
public override bool Equals(object obj) {
if (!(obj is BeatTime)) return false;
return Equals((BeatTime)obj);
}
public bool Equals(BeatTime other) {
return b.Equals(other.b) && ((double)n / d).Equals((double)other.n / other.d);
}
public override int GetHashCode() {
return Decimal.GetHashCode();
}
public static bool operator ==(BeatTime left, BeatTime right) {
return left.Equals(right);
}
public static bool operator !=(BeatTime left, BeatTime right) {
return !left.Equals(right);
}
} }
public class BeatTimeConverter : JsonConverter { public class BeatTimeConverter : JsonConverter {
@@ -55,7 +91,7 @@ namespace Cryville.Crtr {
[JsonIgnore] [JsonIgnore]
public float BeatPosition { public float BeatPosition {
get { get {
return time.Value.b + time.Value.n / (float)time.Value.d + BeatOffset; return (float)time.Value.Decimal + BeatOffset;
} }
} }
@@ -65,7 +101,7 @@ namespace Cryville.Crtr {
public float EndBeatPosition { public float EndBeatPosition {
get { get {
if (endtime == null) return BeatPosition; if (endtime == null) return BeatPosition;
return endtime.Value.b + endtime.Value.n / (float)endtime.Value.d + BeatOffset; return (float)endtime.Value.Decimal + BeatOffset;
} }
} }
@@ -94,15 +130,6 @@ namespace Cryville.Crtr {
get { return Duration > 0; } get { return Duration > 0; }
} }
private InstantEvent attev = null;
[JsonIgnore]
public InstantEvent AttackEvent {
get {
if (attev == null) attev = new InstantEvent(this);
return attev;
}
}
private InstantEvent relev = null; private InstantEvent relev = null;
[JsonIgnore] [JsonIgnore]
public InstantEvent ReleaseEvent { public InstantEvent ReleaseEvent {
@@ -167,7 +194,7 @@ namespace Cryville.Crtr {
public virtual EventList GetEventsOfType(string type) { public virtual EventList GetEventsOfType(string type) {
switch (type) { switch (type) {
case "motions": return new EventList<Chart.Motion>(motions); 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));
} }
} }
} }
@@ -274,8 +301,10 @@ namespace Cryville.Crtr {
#pragma warning restore IDE1006 #pragma warning restore IDE1006
private void LoadFromString(string s) { 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+))?(@(.+?))?(\^(.+?))?(\*(.+?))?(:(.+))?$"); Match m = Regex.Match(s, @"^(.+?)(#(\d+))?(@(.+?))?(\^(.+?))?(\*(.+?))?(:(.+))?$");
if (!m.Success) throw new ArgumentException(); // TODO if (!m.Success) throw new ArgumentException("Invalid motion string format");
name = new Identifier(m.Groups[1].Value); name = new Identifier(m.Groups[1].Value);
var registry = ChartPlayer.motionRegistry[name]; var registry = ChartPlayer.motionRegistry[name];
if (m.Groups[3].Success) { if (m.Groups[3].Success) {
@@ -295,6 +324,10 @@ namespace Cryville.Crtr {
else { else {
AbsoluteValue = Vector.Construct(registry.Type, m.Groups[11].Value); 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() { public override string ToString() {
@@ -303,7 +336,7 @@ namespace Cryville.Crtr {
var node = RelativeNode; var node = RelativeNode;
result += "#" + node.Id; result += "#" + node.Id;
if (node.Time != null) result += "@" + node.Time.ToString(); if (node.Time != null) result += "@" + node.Time.ToString();
if (node.Transition != null) result = "^" + node.Transition.ToString(); if (node.Transition != null) result = "^" + ((byte)node.Transition).ToString(CultureInfo.InvariantCulture);
if (node.Rate != null) result += "*" + node.Rate.ToString(); if (node.Rate != null) result += "*" + node.Rate.ToString();
if (node.Value != null) result += ":" + node.Value.ToString(); if (node.Value != null) result += ":" + node.Value.ToString();
} }
@@ -346,10 +379,6 @@ namespace Cryville.Crtr {
} }
public Motion() { public Motion() {
SubmitPropSrc("value", new VectorSrc(() => {
if (RelativeNode != null) return RelativeNode.Value;
else return AbsoluteValue;
}));
SubmitPropOp("motion", new PropOp.String(v => motion = v)); SubmitPropOp("motion", new PropOp.String(v => motion = v));
SubmitPropOp("name", new PropOp.Identifier(v => { SubmitPropOp("name", new PropOp.Identifier(v => {
var n = new Identifier(v); var n = new Identifier(v);
@@ -391,10 +420,12 @@ namespace Cryville.Crtr {
public class Judge : ChartEvent { public class Judge : ChartEvent {
[JsonIgnore] [JsonIgnore]
public Identifier Id; public Identifier Id;
#pragma warning disable IDE1006
public string name { public string name {
get { return Id.ToString(); } get { return Id.ToString(); }
set { Id = new Identifier(value); } set { Id = new Identifier(value); }
} }
#pragma warning restore IDE1006
public override int Priority { public override int Priority {
get { return 0; } get { return 0; }

View File

@@ -54,8 +54,8 @@ namespace Cryville.Crtr {
static bool disableGC = true; static bool disableGC = true;
static float clippingDist = 1f; static float clippingDist = 1f;
static float renderDist = 6f; static float renderDist = 6f;
static float renderStep = 0.05f; static double renderStep = 0.05;
public static float actualRenderStep = 0f; public static double actualRenderStep = 0;
static bool autoRenderStep = false; static bool autoRenderStep = false;
public static float soundOffset = 0; public static float soundOffset = 0;
static float startOffset = 0; static float startOffset = 0;
@@ -111,7 +111,7 @@ namespace Cryville.Crtr {
bool texloaddone; bool texloaddone;
diag::Stopwatch texloadtimer = new diag::Stopwatch(); diag::Stopwatch texloadtimer = new diag::Stopwatch();
bool firstFrame; int forceSyncFrames;
double atime0; double atime0;
void Update() { void Update() {
if (started) GameUpdate(); if (started) GameUpdate();
@@ -123,10 +123,18 @@ namespace Cryville.Crtr {
try { try {
if (Screen.width != screenSize.x || Screen.height != screenSize.y) if (Screen.width != screenSize.x || Screen.height != screenSize.y)
throw new InvalidOperationException("Window resized while playing"); throw new InvalidOperationException("Window resized while playing");
float dt = firstFrame double dt, step;
? 1f / Application.targetFrameRate if (forceSyncFrames != 0) {
: Time.deltaTime; forceSyncFrames--;
firstFrame = false; 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(); inputProxy.ForceTick();
cbus.ForwardByTime(dt); cbus.ForwardByTime(dt);
bbus.ForwardByTime(dt); bbus.ForwardByTime(dt);
@@ -135,16 +143,13 @@ namespace Cryville.Crtr {
bbus.CopyTo(2, tbus); bbus.CopyTo(2, tbus);
bbus.CopyTo(3, nbus); bbus.CopyTo(3, nbus);
UnityEngine.Profiling.Profiler.EndSample(); UnityEngine.Profiling.Profiler.EndSample();
float step = autoRenderStep ? ( firstFrame
? 1f / Application.targetFrameRate
: Time.smoothDeltaTime
) : renderStep;
actualRenderStep = step; actualRenderStep = step;
nbus.ForwardStepByTime(clippingDist, step); nbus.ForwardStepByTime(clippingDist, step);
nbus.BroadcastEndUpdate(); nbus.BroadcastEndUpdate();
nbus.Anchor(); nbus.Anchor();
tbus.StripTempEvents();
tbus.ForwardStepByTime(clippingDist, step); tbus.ForwardStepByTime(clippingDist, step);
tbus.ForwardStepByTime(renderDist, step); tbus.ForwardStepByTime(renderDist, step);
tbus.BroadcastEndUpdate(); tbus.BroadcastEndUpdate();
@@ -250,14 +255,15 @@ namespace Cryville.Crtr {
status.text = sttext; status.text = sttext;
} }
void OnCameraPostRender(Camera cam) { void OnCameraPostRender(Camera cam) {
if (!started) return;
if (!logEnabled) return; if (!logEnabled) return;
if (started) timetext = string.Format( timetext = string.Format(
"\nSTime: {0:R}\nATime: {1:R}\nITime: {2:R}", "\nSTime: {0:R}s {3}\ndATime: {1:+0.0ms;-0.0ms;0} {3}\ndITime: {2:+0.0ms;-0.0ms;0} {3}",
cbus.Time, cbus.Time,
Game.AudioClient.Position - atime0, (Game.AudioClient.Position - atime0 - cbus.Time) * 1e3,
inputProxy.GetTimestampAverage() (inputProxy.GetTimestampAverage() - cbus.Time) * 1e3,
forceSyncFrames != 0 ? "(force sync)" : ""
); );
else timetext = string.Empty;
} }
#endregion #endregion
@@ -278,6 +284,9 @@ namespace Cryville.Crtr {
SceneManager.UnloadSceneAsync("Play"); SceneManager.UnloadSceneAsync("Play");
#elif UNITY_5_3_OR_NEWER #elif UNITY_5_3_OR_NEWER
SceneManager.UnloadScene("Play"); SceneManager.UnloadScene("Play");
#endif
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
DiscordController.Instance.SetIdle();
#endif #endif
} }
#pragma warning restore IDE1006 #pragma warning restore IDE1006
@@ -308,7 +317,7 @@ namespace Cryville.Crtr {
autoRenderStep = renderStep == 0; autoRenderStep = renderStep == 0;
soundOffset = Settings.Default.SoundOffset; soundOffset = Settings.Default.SoundOffset;
startOffset = Settings.Default.StartOffset; startOffset = Settings.Default.StartOffset;
firstFrame = true; forceSyncFrames= Settings.Default.ForceSyncFrames;
texloaddone = false; texloaddone = false;
Game.NetworkTaskWorker.SuspendBackgroundTasks(); Game.NetworkTaskWorker.SuspendBackgroundTasks();
Game.AudioSession = Game.AudioSequencer.NewSession(); Game.AudioSession = Game.AudioSequencer.NewSession();
@@ -371,8 +380,9 @@ namespace Cryville.Crtr {
texloadtimer.Start(); texloadtimer.Start();
frames = new Dictionary<string, SpriteFrame>(); frames = new Dictionary<string, SpriteFrame>();
texs = new Dictionary<string, Texture2D>(); texs = new Dictionary<string, Texture2D>();
var skinDir = skinFile.Directory.FullName;
foreach (var f in skin.frames) { foreach (var f in skin.frames) {
texLoadQueue.Enqueue(Path.Combine(skinFile.Directory.FullName, f)); texLoadQueue.Enqueue(Path.Combine(skinDir, f));
} }
} }
@@ -380,7 +390,7 @@ namespace Cryville.Crtr {
try { try {
diag::Stopwatch timer = new diag::Stopwatch(); diag::Stopwatch timer = new diag::Stopwatch();
timer.Reset(); timer.Start(); timer.Reset(); timer.Start();
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 3)"); Logger.Log("main", 0, "Load/Prehandle", "Initializing textures");
foreach (var t in texs) { foreach (var t in texs) {
if (frames.ContainsKey(t.Key)) { if (frames.ContainsKey(t.Key)) {
Logger.Log("main", 3, "Load/Prehandle", "Duplicated texture name: {0}", t.Key); Logger.Log("main", 3, "Load/Prehandle", "Duplicated texture name: {0}", t.Key);
@@ -390,15 +400,25 @@ namespace Cryville.Crtr {
f.Init(); f.Init();
frames.Add(t.Key, f); frames.Add(t.Key, f);
} }
Logger.Log("main", 0, "Load/Prehandle", "Initializing states"); Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 2)");
cbus.BroadcastInit(); cbus.BroadcastPreInit();
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 3)");
using (var pbus = cbus.Clone(17)) {
pbus.Forward();
}
Logger.Log("main", 0, "Load/Prehandle", "Prehandling (iteration 4)");
cbus.BroadcastPostInit();
inputProxy.Activate(); inputProxy.Activate();
if (logEnabled) ToggleLogs(); if (logEnabled && Settings.Default.HideLogOnPlay) ToggleLogs();
Logger.Log("main", 0, "Load/Prehandle", "Cleaning up"); Logger.Log("main", 0, "Load/Prehandle", "Cleaning up");
GC.Collect(); GC.Collect();
if (disableGC) GarbageCollector.GCMode = GarbageCollector.Mode.Disabled; if (disableGC) GarbageCollector.GCMode = GarbageCollector.Mode.Disabled;
timer.Stop(); timer.Stop();
Logger.Log("main", 1, "Load/Prehandle", "Prehandling done ({0}ms)", timer.Elapsed.TotalMilliseconds); Logger.Log("main", 1, "Load/Prehandle", "Prehandling done ({0}ms)", timer.Elapsed.TotalMilliseconds);
if (Settings.Default.ClearLogOnPlay) {
logs.text = "";
Game.MainLogger.Enumerate((level, module, msg) => { });
}
Game.AudioSequencer.Playing = true; Game.AudioSequencer.Playing = true;
atime0 = Game.AudioClient.BufferPosition; atime0 = Game.AudioClient.BufferPosition;
Thread.Sleep((int)((atime0 - Game.AudioClient.Position) * 1000)); Thread.Sleep((int)((atime0 - Game.AudioClient.Position) * 1000));
@@ -465,6 +485,7 @@ namespace Cryville.Crtr {
workerTimer = new diag::Stopwatch(); workerTimer = new diag::Stopwatch();
workerTimer.Start(); workerTimer.Start();
RMVPool.Prepare(); RMVPool.Prepare();
MotionCachePool.Prepare();
LoadChart(info); LoadChart(info);
workerTimer.Stop(); workerTimer.Stop();
Logger.Log("main", 1, "Load/WorkerThread", "Worker thread done ({0}ms)", workerTimer.Elapsed.TotalMilliseconds); Logger.Log("main", 1, "Load/WorkerThread", "Worker thread done ({0}ms)", workerTimer.Elapsed.TotalMilliseconds);
@@ -496,10 +517,10 @@ namespace Cryville.Crtr {
var batcher = new EventBatcher(chart); var batcher = new EventBatcher(chart);
batcher.Forward(); batcher.Forward();
cbus = batcher.Batch(); cbus = batcher.Batch();
Logger.Log("main", 0, "Load/WorkerThread", "Batched {0} event batches", cbus.events.Count);
LoadSkin(info.skinFile); LoadSkin(info.skinFile);
Logger.Log("main", 0, "Load/WorkerThread", "Initializing judge and input");
judge = new Judge(pruleset); judge = new Judge(pruleset);
etor.ContextJudge = judge; etor.ContextJudge = judge;
@@ -518,10 +539,10 @@ namespace Cryville.Crtr {
foreach (var ts in gs.Value.Children) { foreach (var ts in gs.Value.Children) {
ContainerHandler th; ContainerHandler th;
if (ts.Key is Chart.Note) { if (ts.Key is Chart.Note) {
th = new NoteHandler(gh, (Chart.Note)ts.Key, pruleset, judge); th = new NoteHandler((Chart.Note)ts.Key, gh);
} }
else { else {
th = new TrackHandler(gh, (Chart.Track)ts.Key); th = new TrackHandler((Chart.Track)ts.Key, gh);
} }
ts.Value.AttachHandler(th); ts.Value.AttachHandler(th);
} }
@@ -531,12 +552,6 @@ namespace Cryville.Crtr {
using (var pbus = cbus.Clone(16)) { using (var pbus = cbus.Clone(16)) {
pbus.Forward(); pbus.Forward();
} }
Logger.Log("main", 0, "Load/WorkerThread", "Patching events");
cbus.DoPatch();
Logger.Log("main", 0, "Load/WorkerThread", "Prehandling (iteration 2)");
using (var pbus = cbus.Clone(17)) {
pbus.Forward();
}
Logger.Log("main", 0, "Load/WorkerThread", "Cloning states (type 1)"); Logger.Log("main", 0, "Load/WorkerThread", "Cloning states (type 1)");
bbus = cbus.Clone(1, -clippingDist); bbus = cbus.Clone(1, -clippingDist);

View File

@@ -22,7 +22,9 @@ namespace Cryville.Crtr.Components {
} }
protected void UpdateZIndex() { protected void UpdateZIndex() {
if (!mesh.Initialized) return; if (!mesh.Initialized) return;
mesh.Renderer.material.renderQueue = _zindex; foreach (var mat in mesh.Renderer.materials) {
mat.renderQueue = _zindex;
}
} }
} }
} }

View File

@@ -9,6 +9,18 @@ namespace Cryville.Crtr.Components {
protected Vector3? prevpt; protected Vector3? prevpt;
protected Quaternion? prevrot; protected Quaternion? prevrot;
protected int vertCount = 0; 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() { protected override void OnDestroy() {
mesh.Destroy(); mesh.Destroy();
@@ -23,7 +35,7 @@ namespace Cryville.Crtr.Components {
} }
public void AppendPoint(Vector3 p, Quaternion r) { public void AppendPoint(Vector3 p, Quaternion r) {
if (prevpt == p && prevrot == r) return; if (prevpt == p && prevrot == r || ((int)part & 1) == 1) return;
AppendPointInternal(p, r); AppendPointInternal(p, r);
// if (!headGenerated) Logger.Log("main", 0, "Skin/Polysec", "{0}", r); // if (!headGenerated) Logger.Log("main", 0, "Skin/Polysec", "{0}", r);
prevpt = p; prevpt = p;
@@ -55,7 +67,7 @@ namespace Cryville.Crtr.Components {
SubmitProperty("head", new PropOp.String(v => head.FrameName = v)); SubmitProperty("head", new PropOp.String(v => head.FrameName = v));
SubmitProperty("body", new PropOp.String(v => body.FrameName = v)); SubmitProperty("body", new PropOp.String(v => body.FrameName = v));
SubmitProperty("tail", new PropOp.String(v => tail.FrameName = v)); SubmitProperty("tail", new PropOp.String(v => tail.FrameName = v));
SubmitProperty("shape", new op_set_shape(this)); SubmitProperty("shape", new op_set_shape(this), 2);
} }
#pragma warning disable IDE1006 #pragma warning disable IDE1006
@@ -98,24 +110,14 @@ namespace Cryville.Crtr.Components {
public override void Init() { public override void Init() {
base.Init(); base.Init();
head.Load();
body.Load();
tail.Load();
mesh.Init(transform); mesh.Init(transform);
List<Material> materials = new List<Material>(); var mats = mesh.Renderer.materials = new Material[] { mesh.NewMaterial, mesh.NewMaterial, mesh.NewMaterial };
if (head.FrameName != null) AddMat(materials, head.FrameName); head.Bind(mats[0]);
if (body.FrameName != null) AddMat(materials, body.FrameName); body.Bind(mats[1]);
if (tail.FrameName != null) AddMat(materials, tail.FrameName); tail.Bind(mats[2]);
mesh.Renderer.materials = materials.ToArray();
}
void AddMat(List<Material> list, string frame) { UpdateZIndex();
var mat = mesh.NewMaterial;
mat.mainTexture = ChartPlayer.frames[frame].Texture;
list.Add(mat);
} }
protected override void OnDestroy() { protected override void OnDestroy() {
@@ -129,7 +131,6 @@ namespace Cryville.Crtr.Components {
} }
} }
// Vector3 prevp = Vector3.zero;
protected override void AppendPointInternal(Vector3 p, Quaternion r) { protected override void AppendPointInternal(Vector3 p, Quaternion r) {
if (vertices == null) { if (vertices == null) {
vertices = _ptPool.Rent(); vertices = _ptPool.Rent();
@@ -151,15 +152,16 @@ namespace Cryville.Crtr.Components {
List<Vector3> verts; List<Vector3> verts;
List<Vector2> uvs; List<Vector2> uvs;
List<int> trih = null, trib = null, trit = null; List<int> trih = null, trib = null, trit = null;
static List<int> _emptyTris = new List<int>();
public override void Seal() { public override void Seal() {
if (vertCount <= 1 || sumLength == 0) return; if (vertCount <= 1 || sumLength == 0) return;
int vcpsec = _shapeLength; // Vertex Count Per Section int vcpsec = _shapeLength; // Vertex Count Per Section
float width = GetWidth(); float width = GetWidth();
float headLength = 0; float headLength = 0;
if (head.FrameName != null) headLength = width / head.Ratio; if (head.Frame != null) headLength = width / head.Ratio;
float tailLength = 0; float tailLength = 0;
if (tail.FrameName != null) tailLength = width / tail.Ratio; if (tail.Frame != null) tailLength = width / tail.Ratio;
float endLength = headLength + tailLength; float endLength = headLength + tailLength;
if (sumLength <= endLength) { if (sumLength <= endLength) {
// The total length of the two ends is longer than the whole mesh, squeeze the two ends // The total length of the two ends is longer than the whole mesh, squeeze the two ends
@@ -187,17 +189,17 @@ namespace Cryville.Crtr.Components {
verts = _vertPool.Rent(vc * vcpsec); verts = _vertPool.Rent(vc * vcpsec);
uvs = _uvPool.Rent(vc * vcpsec); uvs = _uvPool.Rent(vc * vcpsec);
int i = 0; int t = 0; float l = 0; int m = 0; int i = 0; int t = 0; float l = 0; int m = 0;
if (head.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); } if (head.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trih, head, ref i, ref t, ref l, 0, headLength, vcpsec, hvc); }
if (body.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trib, body, ref i, ref t, ref l, headLength, sumLength - tailLength, vcpsec, hvc + bvc); } if (body.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trib, body, ref i, ref t, ref l, headLength, sumLength - tailLength, vcpsec, hvc + bvc); }
if (tail.FrameName != null) { m++; GenerateMeshTo(verts, uvs, out trit, tail, ref i, ref t, ref l, sumLength - tailLength, sumLength, vcpsec, vc); } if (tail.Frame != null) { m++; GenerateMeshTo(verts, uvs, out trit, tail, ref i, ref t, ref l, sumLength - tailLength, sumLength, vcpsec, vc); }
mesh.Mesh.subMeshCount = m; mesh.Mesh.subMeshCount = 3;
m = 0; m = 0;
mesh.Mesh.SetVertices(verts); mesh.Mesh.SetVertices(verts);
mesh.Mesh.SetUVs(0, uvs); mesh.Mesh.SetUVs(0, uvs);
if (head.FrameName != null) mesh.Mesh.SetTriangles(trih, m++); mesh.Mesh.SetTriangles(head.Frame == null ? _emptyTris : trih, m++);
if (body.FrameName != null) mesh.Mesh.SetTriangles(trib, m++); mesh.Mesh.SetTriangles(body.Frame == null ? _emptyTris : trib, m++);
if (tail.FrameName != null) mesh.Mesh.SetTriangles(trit, m++); mesh.Mesh.SetTriangles(tail.Frame == null ? _emptyTris : trit, m++);
mesh.Mesh.RecalculateNormals(); mesh.Mesh.RecalculateNormals();
_vertPool.Return(verts); verts = null; _vertPool.Return(verts); verts = null;

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
using Cryville.Common.Pdt; using Cryville.Common.Buffers;
using Cryville.Common.Pdt;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
@@ -7,7 +8,7 @@ namespace Cryville.Crtr.Components {
public class SpriteText : SpriteBase { public class SpriteText : SpriteBase {
public SpriteText() { public SpriteText() {
SubmitProperty("frames", new op_set_frames(this)); SubmitProperty("frames", new op_set_frames(this));
SubmitProperty("value", new PropOp.String(v => Value = v)); SubmitProperty("value", new PropOp.TargetString(() => Value));
SubmitProperty("size", new PropOp.Float(v => Size = v)); SubmitProperty("size", new PropOp.Float(v => Size = v));
SubmitProperty("spacing", new PropOp.Float(v => Spacing = v)); SubmitProperty("spacing", new PropOp.Float(v => Spacing = v));
SubmitProperty("opacity", new PropOp.Float(v => Opacity = v)); SubmitProperty("opacity", new PropOp.Float(v => Opacity = v));
@@ -41,21 +42,14 @@ namespace Cryville.Crtr.Components {
foreach (var m in meshes) m.Value.Destroy(); foreach (var m in meshes) m.Value.Destroy();
} }
readonly Dictionary<Texture2D, MeshWrapper> meshes = new Dictionary<Texture2D, MeshWrapper>();
Dictionary<char, SpriteInfo> m_frames; Dictionary<char, SpriteInfo> m_frames;
public Dictionary<char, SpriteInfo> Frames { public Dictionary<char, SpriteInfo> Frames {
get { return m_frames; } get { return m_frames; }
set { m_frames = value; UpdateFrames(); UpdateScale(); } set { m_frames = value; UpdateFrames(); UpdateScale(); }
} }
public string m_value; readonly TargetString m_value = new TargetString();
public string Value { public TargetString Value { get { return m_value; } }
get { return m_value; }
set {
if (m_value == value) return;
m_value = value; UpdateScale();
}
}
public float m_size; public float m_size;
public float Size { public float Size {
@@ -80,31 +74,38 @@ namespace Cryville.Crtr.Components {
float frameHeight = 0; float frameHeight = 0;
foreach (var m in meshes) m.Value.Destroy(); foreach (var m in meshes) m.Value.Destroy();
meshes.Clear(); meshes.Clear();
verts.Clear();
uvs.Clear();
foreach (var f in m_frames) { foreach (var f in m_frames) {
f.Value.Load(); f.Value.Load();
if (frameHeight == 0) frameHeight = f.Value.Rect.height; 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");
if (!meshes.ContainsKey(f.Value.Frame.Texture)) { var tex = f.Value.Frame.Texture;
if (!meshes.ContainsKey(tex)) {
var m = new MeshWrapper(); var m = new MeshWrapper();
m.Init(mesh.MeshTransform); m.Init(mesh.MeshTransform);
m.Mesh = new Mesh(); m.Mesh = new Mesh();
m.Renderer.material.mainTexture = f.Value.Frame.Texture; m.Renderer.material.mainTexture = tex;
meshes.Add(f.Value.Frame.Texture, m); meshes.Add(tex, m);
verts.Add(tex, new List<Vector3>());
uvs.Add(tex, new List<Vector2>());
tris.Add(tex, new List<int>());
} }
} }
} }
float sum_x; float sum_x;
readonly Dictionary<Texture2D, MeshWrapper> meshes = new Dictionary<Texture2D, MeshWrapper>();
readonly Dictionary<Texture2D, List<Vector3>> verts = new Dictionary<Texture2D, List<Vector3>>();
readonly Dictionary<Texture2D, List<Vector2>> uvs = new Dictionary<Texture2D, List<Vector2>>();
readonly Dictionary<Texture2D, List<int>> tris = new Dictionary<Texture2D, List<int>>();
void UpdateMeshes() { void UpdateMeshes() {
// TODO optimize GC
if (meshes.Count == 0) return; if (meshes.Count == 0) return;
sum_x = 0; sum_x = 0;
int vc = m_value.Length * 4;
Dictionary<Texture2D, List<Vector3>> verts = new Dictionary<Texture2D, List<Vector3>>();
Dictionary<Texture2D, List<Vector2>> uvs = new Dictionary<Texture2D, List<Vector2>>();
foreach (var t in meshes.Keys) { foreach (var t in meshes.Keys) {
verts.Add(t, new List<Vector3>(vc)); verts[t].Clear();
uvs.Add(t, new List<Vector2>(vc)); uvs[t].Clear();
tris[t].Clear();
} }
foreach (var c in m_value) { foreach (var c in m_value) {
var f = m_frames[c]; var f = m_frames[c];
@@ -124,18 +125,18 @@ namespace Cryville.Crtr.Components {
var m = meshes[t].Mesh; var m = meshes[t].Mesh;
m.Clear(); m.Clear();
int cc = verts[t].Count / 4; int cc = verts[t].Count / 4;
int[] tris = new int[cc * 6]; var _tris = tris[t];
for (int i = 0; i < cc; i++) { for (int i = 0; i < cc; i++) {
tris[i * 6 ] = i * 4 ; _tris.Add(i * 4);
tris[i * 6 + 1] = i * 4 + 3; _tris.Add(i * 4 + 3);
tris[i * 6 + 2] = i * 4 + 1; _tris.Add(i * 4 + 1);
tris[i * 6 + 3] = i * 4 + 1; _tris.Add(i * 4 + 1);
tris[i * 6 + 4] = i * 4 + 3; _tris.Add(i * 4 + 3);
tris[i * 6 + 5] = i * 4 + 2; _tris.Add(i * 4 + 2);
} }
m.vertices = verts[t].ToArray(); m.SetVertices(verts[t]);
m.uv = uvs[t].ToArray(); m.SetUVs(0, uvs[t]);
m.triangles = tris; m.SetTriangles(tris[t], 0);
m.RecalculateNormals(); m.RecalculateNormals();
} }
sum_x -= m_spacing; sum_x -= m_spacing;
@@ -175,6 +176,7 @@ namespace Cryville.Crtr.Components {
UpdateFrames(); UpdateFrames();
mesh.Mesh.Clear(); mesh.Mesh.Clear();
UpdateScale(); UpdateScale();
Value.OnUpdate += UpdateScale;
} }
} }
} }

View File

@@ -1,5 +1,4 @@
using JetBrains.Annotations; using Newtonsoft.Json;
using Newtonsoft.Json;
using System; using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
@@ -20,7 +19,7 @@ namespace Cryville.Crtr.Config {
public Ruleset ruleset; public Ruleset ruleset;
RulesetConfig _rscfg; RulesetConfig _rscfg;
void Awake() { void Start() {
ChartPlayer.etor = new PdtEvaluator(); ChartPlayer.etor = new PdtEvaluator();
FileInfo file = new FileInfo( FileInfo file = new FileInfo(
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
@@ -58,7 +57,6 @@ namespace Cryville.Crtr.Config {
var proxy = new InputProxy(ruleset.Root, null); var proxy = new InputProxy(ruleset.Root, null);
proxy.LoadFrom(_rscfg.inputs); proxy.LoadFrom(_rscfg.inputs);
m_inputConfigPanel.proxy = proxy; m_inputConfigPanel.proxy = proxy;
Game.InputManager.Activate();
} }
public void SwitchCategory(GameObject cat) { public void SwitchCategory(GameObject cat) {
@@ -69,7 +67,6 @@ namespace Cryville.Crtr.Config {
} }
public void SaveAndReturnToMenu() { public void SaveAndReturnToMenu() {
Game.InputManager.Deactivate();
m_inputConfigPanel.proxy.SaveTo(_rscfg.inputs); m_inputConfigPanel.proxy.SaveTo(_rscfg.inputs);
m_inputConfigPanel.proxy.Dispose(); m_inputConfigPanel.proxy.Dispose();
FileInfo cfgfile = new FileInfo( FileInfo cfgfile = new FileInfo(

View File

@@ -24,14 +24,16 @@ namespace Cryville.Crtr.Config {
[SerializeField] [SerializeField]
GameObject m_prefabInputConfigEntry; GameObject m_prefabInputConfigEntry;
readonly SimpleInputConsumer _consumer = new SimpleInputConsumer(Game.InputManager);
public InputProxy proxy; public InputProxy proxy;
Dictionary<string, InputConfigPanelEntry> _entries = new Dictionary<string, InputConfigPanelEntry>(); readonly Dictionary<string, InputConfigPanelEntry> _entries = new Dictionary<string, InputConfigPanelEntry>();
string _sel; string _sel;
public void OpenDialog(string entry) { public void OpenDialog(string entry) {
_sel = entry; _sel = entry;
m_inputDialog.SetActive(true); m_inputDialog.SetActive(true);
CallHelper.Purge(m_deviceList); CallHelper.Purge(m_deviceList);
_consumer.EnumerateEvents(ev => { });
_recvsrcs.Clear(); _recvsrcs.Clear();
AddSourceItem(null); AddSourceItem(null);
} }
@@ -45,10 +47,11 @@ namespace Cryville.Crtr.Config {
Target = _sel, Target = _sel,
Source = src, Source = src,
}); });
m_inputDialog.SetActive(false); CloseDialog();
} }
void Start() { void Start() {
_consumer.Activate();
foreach (var i in m_configScene.ruleset.Root.inputs) { foreach (var i in m_configScene.ruleset.Root.inputs) {
var e = GameObject.Instantiate(m_prefabInputConfigEntry, m_entryList.transform).GetComponent<InputConfigPanelEntry>(); var e = GameObject.Instantiate(m_prefabInputConfigEntry, m_entryList.transform).GetComponent<InputConfigPanelEntry>();
_entries.Add(i.Key, e); _entries.Add(i.Key, e);
@@ -58,6 +61,10 @@ namespace Cryville.Crtr.Config {
proxy.ProxyChanged += OnProxyChanged; proxy.ProxyChanged += OnProxyChanged;
} }
void OnDestroy() {
_consumer.Deactivate();
}
void OnProxyChanged(object sender, ProxyChangedEventArgs e) { void OnProxyChanged(object sender, ProxyChangedEventArgs e) {
_entries[e.Name].SetEnabled(!e.Used); _entries[e.Name].SetEnabled(!e.Used);
_entries[e.Name].SetValue(e.Proxy == null ? "None" : e.Proxy.Value.Handler.GetTypeName(e.Proxy.Value.Type)); _entries[e.Name].SetValue(e.Proxy == null ? "None" : e.Proxy.Value.Handler.GetTypeName(e.Proxy.Value.Type));
@@ -66,7 +73,7 @@ namespace Cryville.Crtr.Config {
readonly List<InputSource?> _recvsrcs = new List<InputSource?>(); readonly List<InputSource?> _recvsrcs = new List<InputSource?>();
void Update() { void Update() {
if (m_inputDialog.activeSelf) { if (m_inputDialog.activeSelf) {
Game.InputManager.EnumerateEvents(ev => { _consumer.EnumerateEvents(ev => {
AddSourceItem(ev.Id.Source); 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,6 +1,9 @@
using Cryville.Common;
using Cryville.Common.Buffers;
using Cryville.Crtr.Components; using Cryville.Crtr.Components;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using UnityEngine; using UnityEngine;
namespace Cryville.Crtr.Event { namespace Cryville.Crtr.Event {
@@ -33,38 +36,21 @@ namespace Cryville.Crtr.Event {
/// <summary> /// <summary>
/// <see cref="GameObject"/> group, the <see cref="Transform"/> containing all the generated elements in the <see cref="ContainerHandler"/>. /// <see cref="GameObject"/> group, the <see cref="Transform"/> containing all the generated elements in the <see cref="ContainerHandler"/>.
/// </summary> /// </summary>
public Transform gogroup; protected Transform gogroup;
public SkinContext SkinContext;
public readonly Dictionary<string, Anchor> Anchors = new Dictionary<string, Anchor>(); public Vector3 Position { get; protected set; }
public Transform a_head; public Quaternion Rotation { get; protected set; }
public Transform a_tail; public bool Alive { get; private set; }
public Vector3 Position { public bool Awoken { get; private set; }
get; public bool Disposed { get; private set; }
protected set;
}
public Quaternion Rotation {
get;
protected set;
}
public bool Alive {
get;
private set;
}
public bool Awoken {
get;
private set;
}
public bool Disposed {
get;
private set;
}
public EventContainer Container { public EventContainer Container {
get { return cs.Container; } get { return cs.Container; }
} }
public SkinContainer skinContainer; SkinContainer skinContainer;
public Judge judge; protected Judge judge;
public void AttachSystems(PdtSkin skin, Judge judge) { public void AttachSystems(PdtSkin skin, Judge judge) {
skinContainer = new SkinContainer(skin); skinContainer = new SkinContainer(skin);
this.judge = judge; this.judge = judge;
@@ -74,22 +60,39 @@ namespace Cryville.Crtr.Event {
public abstract string TypeName { public abstract string TypeName {
get; get;
} }
public readonly Dictionary<int, List<Anchor>> Anchors = new Dictionary<int, List<Anchor>>();
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 virtual void PreInit() { public virtual void PreInit() {
gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString()).transform; gogroup = new GameObject(TypeName + ":" + Container.GetHashCode().ToString(CultureInfo.InvariantCulture)).transform;
SkinContext = new SkinContext(gogroup);
if (cs.Parent != null) if (cs.Parent != null)
gogroup.SetParent(cs.Parent.Handler.gogroup, false); gogroup.SetParent(cs.Parent.Handler.gogroup, false);
a_head = new GameObject("::head").transform; a_cur = RegisterAnchor(_a_cur);
a_head.SetParent(gogroup, false); a_head = RegisterAnchor(_a_head);
Anchors.Add("head", new Anchor() { Transform = a_head }); a_tail = RegisterAnchor(_a_tail);
a_tail = new GameObject("::tail").transform;
a_tail.SetParent(gogroup, false);
Anchors.Add("tail", new Anchor() { Transform = a_tail });
} }
protected Anchor RegisterAnchor(int name, bool hasPropSrcs = false) {
var go = new GameObject("." + IdentifierManager.SharedInstance.Retrieve(name)).transform;
go.SetParent(gogroup, false);
var result = new Anchor(name, go, hasPropSrcs);
List<Anchor> list;
if (!Anchors.TryGetValue(name, out list))
Anchors.Add(name, list = new List<Anchor>());
list.Add(result);
return result;
}
/// <summary> /// <summary>
/// Called upon initialization of <see cref="cs" />. /// Called upon StartUpdate of ps 17.
/// </summary> /// </summary>
public virtual void Init() { public virtual void Init() {
skinContainer.MatchStatic(cs); skinContainer.MatchStatic(ps);
foreach (var i in gogroup.GetComponentsInChildren<SkinComponent>()) foreach (var i in gogroup.GetComponentsInChildren<SkinComponent>())
i.Init(); i.Init();
} }
@@ -105,12 +108,14 @@ namespace Cryville.Crtr.Event {
Alive = false; Alive = false;
} }
protected virtual void PreAwake(ContainerState s) { protected virtual void PreAwake(ContainerState s) {
if (gogroup) gogroup.gameObject.SetActive(true); if (gogroup) {
gogroup.gameObject.SetActive(true);
OpenAnchor(a_head);
}
Awoken = true; Alive = true; Awoken = true; Alive = true;
OpenAnchor("head");
} }
protected virtual void Awake(ContainerState s) { protected virtual void Awake(ContainerState s) {
CloseAnchor("head"); if (gogroup) CloseAnchor();
} }
protected virtual void GetPosition(ContainerState s) { } protected virtual void GetPosition(ContainerState s) { }
public virtual void StartUpdate(ContainerState s) { public virtual void StartUpdate(ContainerState s) {
@@ -118,27 +123,68 @@ namespace Cryville.Crtr.Event {
PreAwake(s); PreAwake(s);
Awake(s); Awake(s);
} }
else if (s.CloneType == 17) {
Init();
}
}
static readonly SimpleObjectPool<StampedEvent.Anchor> anchorEvPool
= new SimpleObjectPool<StampedEvent.Anchor>(1024);
protected void PushAnchorEvent(double time, Anchor anchor) {
var tev = anchorEvPool.Rent();
tev.Time = time;
tev.Container = Container;
tev.Target = anchor;
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 Update(ContainerState s, StampedEvent ev) { public virtual void Update(ContainerState s, StampedEvent ev) {
bool flag = !Awoken && s.CloneType >= 2 && s.CloneType < 16; bool flag = !Awoken && s.CloneType >= 2 && s.CloneType < 16;
if (flag) PreAwake(s); if (flag) PreAwake(s);
if (Awoken && s.CloneType <= 2) if (gogroup) skinContainer.MatchDynamic(s); if (gogroup && s.CloneType <= 2) skinContainer.MatchDynamic(s);
if (flag) Awake(s); if (flag) Awake(s);
} }
public virtual void ExUpdate(ContainerState s, StampedEvent ev) { } public virtual void ExUpdate(ContainerState s, StampedEvent ev) {
if (ev is StampedEvent.Anchor) {
var tev = (StampedEvent.Anchor)ev;
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);
}
}
public virtual void MotionUpdate(byte ct, Chart.Motion ev) { } public virtual void MotionUpdate(byte ct, Chart.Motion ev) { }
public virtual void EndUpdate(ContainerState s) { public virtual void EndUpdate(ContainerState s) {
if (s.CloneType < 16) { if (s.CloneType < 16) {
Awoken = false; Awoken = false;
if (gogroup && s.CloneType <= 2) skinContainer.MatchDynamic(s); if (gogroup && s.CloneType <= 2) {
OpenAnchor(a_tail);
skinContainer.MatchDynamic(s);
CloseAnchor();
}
} }
} }
public virtual void Anchor() { } public virtual void Anchor() {
protected void OpenAnchor(string name) { skinContainer.MatchDynamic(cs);
if (Anchors.ContainsKey(name)) Anchors[name].Open(); if (cs.Working) PushAnchorEvent(cs.Time, a_cur);
} }
protected void CloseAnchor(string name) { protected void OpenAnchor(Anchor anchor) {
if (Anchors.ContainsKey(name)) Anchors[name].Close(); if (OpenedAnchor != null) throw new InvalidOperationException("An anchor has been opened");
OpenedAnchor = anchor;
}
protected void CloseAnchor() {
OpenedAnchor = null;
} }
} }
} }

View File

@@ -9,6 +9,7 @@ namespace Cryville.Crtr.Event {
public class ContainerState { public class ContainerState {
public EventBus Bus; public EventBus Bus;
public EventContainer Container; public EventContainer Container;
public StampedEvent StampedContainer;
public ContainerState Parent = null; public ContainerState Parent = null;
public ushort Depth; public ushort Depth;
@@ -38,6 +39,7 @@ namespace Cryville.Crtr.Event {
InvalidatedChildren.Clear(); InvalidatedChildren.Clear();
} }
public bool Active { get; set; }
private bool m_Working; private bool m_Working;
public bool Working { public bool Working {
get { return m_Working; } get { return m_Working; }
@@ -56,17 +58,17 @@ namespace Cryville.Crtr.Event {
private set; private set;
} }
public float Time { public double Time {
get { get {
return Bus.Time; return Bus.Time;
} }
} }
readonly RMVPool RMVPool = new RMVPool(); readonly RMVPool RMVPool = new RMVPool();
protected Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>(); readonly MotionCachePool MCPool = new MotionCachePool();
protected Dictionary<Identifier, RealtimeMotionValue> Values; Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>(4);
protected Dictionary<Identifier, Vector> CachedValues; Dictionary<Identifier, RealtimeMotionValue> Values;
protected Dictionary<Identifier, bool> CachedValueStates; Dictionary<Identifier, MotionCache> CachedValues;
/// <summary> /// <summary>
/// Gets a motion value. /// Gets a motion value.
@@ -75,22 +77,19 @@ namespace Cryville.Crtr.Event {
/// <param name="clone">Returns a cloned motion value instead.</param> /// <param name="clone">Returns a cloned motion value instead.</param>
/// <returns>A motion value.</returns> /// <returns>A motion value.</returns>
RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) { RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) {
RealtimeMotionValue value; RealtimeMotionValue value = Values[name];
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(); if (clone) return value.Clone();
return value; return value;
} }
void InvalidateMotion(Identifier name) { void InvalidateMotion(Identifier name) {
CachedValueStates[name] = false; MotionCache cache;
foreach (var c in Children) if (!CachedValues.TryGetValue(name, out cache))
c.Value.InvalidateMotion(name); CachedValues.Add(name, cache = MCPool.Rent(name));
cache.Valid = false;
ValidateChildren();
foreach (var c in WorkingChildren)
Children[c].InvalidateMotion(name);
} }
public ContainerState(Chart c, EventContainer _ev, ContainerState parent = null) { public ContainerState(Chart c, EventContainer _ev, ContainerState parent = null) {
@@ -102,8 +101,7 @@ namespace Cryville.Crtr.Event {
} }
Values = new Dictionary<Identifier, RealtimeMotionValue>(ChartPlayer.motionRegistry.Count); Values = new Dictionary<Identifier, RealtimeMotionValue>(ChartPlayer.motionRegistry.Count);
CachedValues = new Dictionary<Identifier, Vector>(ChartPlayer.motionRegistry.Count); CachedValues = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
CachedValueStates = new Dictionary<Identifier, bool>(ChartPlayer.motionRegistry.Count);
foreach (var m in ChartPlayer.motionRegistry) foreach (var m in ChartPlayer.motionRegistry)
Values.Add(m.Key, new RealtimeMotionValue().Init(Parent == null ? m.Value.GlobalInitValue : m.Value.InitValue)); Values.Add(m.Key, new RealtimeMotionValue().Init(Parent == null ? m.Value.GlobalInitValue : m.Value.InitValue));
} }
@@ -124,18 +122,14 @@ namespace Cryville.Crtr.Event {
} }
r.Values = mvs; r.Values = mvs;
var cvs = new Dictionary<Identifier, Vector>(ChartPlayer.motionRegistry.Count); var cvs = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
foreach (var cv in CachedValues) { 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; r.CachedValues = cvs;
var cvss = new Dictionary<Identifier, bool>(ChartPlayer.motionRegistry.Count);
foreach (var cv in CachedValueStates) {
cvss.Add(cv.Key, cv.Value);
}
r.CachedValueStates = cvss;
r.Children = new Dictionary<EventContainer, ContainerState>(); r.Children = new Dictionary<EventContainer, ContainerState>();
foreach (var child in Children) { foreach (var child in Children) {
var cc = child.Value.Clone(ct); var cc = child.Value.Clone(ct);
@@ -143,7 +137,7 @@ namespace Cryville.Crtr.Event {
AddChild(child.Key, cc, r); AddChild(child.Key, cc, r);
} }
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(PlayingMotions.Count); var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(Math.Max(4, PlayingMotions.Count));
foreach (var m in PlayingMotions) foreach (var m in PlayingMotions)
pms.Add(m.Key, m.Value); pms.Add(m.Key, m.Value);
r.PlayingMotions = pms; r.PlayingMotions = pms;
@@ -169,20 +163,21 @@ namespace Cryville.Crtr.Event {
else dest.Values.Add(mv.Key, mv.Value.Clone()); else dest.Values.Add(mv.Key, mv.Value.Clone());
} }
foreach (var cv in dest.CachedValues) cv.Value.Valid = false;
foreach (var cv in CachedValues) { foreach (var cv in CachedValues) {
Vector dv; MotionCache dv;
if(dest.CachedValues.TryGetValue(cv.Key, out dv)) cv.Value.CopyTo(dv); if (!dest.CachedValues.TryGetValue(cv.Key, out dv)) {
else dest.CachedValues.Add(cv.Key, cv.Value.Clone()); dest.CachedValues.Add(cv.Key, dv = dest.MCPool.Rent(cv.Key));
}
cv.Value.CopyTo(dv);
} }
foreach (var cvs in CachedValueStates) dest.CachedValueStates[cvs.Key] = cvs.Value;
if (ct != 1) foreach (var cev in WorkingChildren) if (ct != 1) foreach (var cev in WorkingChildren)
Children[cev].CopyTo(ct, dest.Children[cev]); Children[cev].CopyTo(ct, dest.Children[cev]);
else foreach (var child in Children) else foreach (var child in Children)
child.Value.CopyTo(ct, dest.Children[child.Key]); child.Value.CopyTo(ct, dest.Children[child.Key]);
ValidateChildren(); dest.ValidateChildren();
RMVPool.ReturnAll();
dest.PlayingMotions.Clear(); dest.PlayingMotions.Clear();
foreach (var m in PlayingMotions) dest.PlayingMotions.Add(m.Key, m.Value); foreach (var m in PlayingMotions) dest.PlayingMotions.Add(m.Key, m.Value);
} }
@@ -198,11 +193,12 @@ namespace Cryville.Crtr.Event {
foreach (var s in Children) foreach (var s in Children)
s.Value.Dispose(); s.Value.Dispose();
RMVPool.ReturnAll(); RMVPool.ReturnAll();
MCPool.ReturnAll();
} }
public void AttachHandler(ContainerHandler h) { public void AttachHandler(ContainerHandler h) {
if (Handler != null) if (Handler != null)
throw new InvalidOperationException(); throw new InvalidOperationException("Handler attached twice");
Handler = h; Handler = h;
h.cs = this; h.cs = this;
} }
@@ -212,22 +208,19 @@ namespace Cryville.Crtr.Event {
} }
public Vector GetRawValue(Identifier key) { public Vector GetRawValue(Identifier key) {
Vector tr; MotionCache tr;
if (!CachedValues.TryGetValue(key, out tr)) { if (!CachedValues.TryGetValue(key, out tr))
tr = (Vector)ReflectionHelper.InvokeEmptyConstructor(ChartPlayer.motionRegistry[key].Type); CachedValues.Add(key, tr = MCPool.Rent(key));
CachedValues.Add(key, tr); Vector r = tr.Value;
CachedValueStates[key] = false;
}
Vector r = tr;
#if !DISABLE_CACHE #if !DISABLE_CACHE
if (CachedValueStates[key]) return r; if (tr.Valid) return r;
#endif #endif
float reltime = 0; float reltime = 0;
if (rootPrototype != null) reltime = Time - rootPrototype.Time; if (rootPrototype != null) reltime = (float)(Time - rootPrototype.Time);
GetMotionValue(key).GetValue(reltime, ref r); GetMotionValue(key).GetValue(reltime, ref r);
if (Parent != null) r.ApplyFrom(Parent.GetRawValue(key)); if (Parent != null) r.ApplyFrom(Parent.GetRawValue(key));
#if !DISABLE_CACHE #if !DISABLE_CACHE
CachedValueStates[key] = true; tr.Valid = true;
#endif #endif
return r; return r;
} }
@@ -315,17 +308,24 @@ namespace Cryville.Crtr.Event {
Working = false; Working = 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 (breakflag) return;
if (ev != null) { if (ev != null) {
if (ev.Unstamped is Chart.Motion) { if (ev.Unstamped is Chart.Motion) {
var tev = (Chart.Motion)ev.Unstamped; var tev = (Chart.Motion)ev.Unstamped;
var mv = RMVPool.Rent(tev.Name); var mv = RMVPool.Rent(tev.Name);
mv.CloneTypeFlag = CloneType;
GetMotionValue(tev.Name).CopyTo(mv); GetMotionValue(tev.Name).CopyTo(mv);
PlayingMotions.Add(ev, mv); PlayingMotions.Add(ev, mv);
Callback(ev, callback); Update(ev);
if (!ev.Unstamped.IsLong) if (!ev.Unstamped.IsLong) {
PlayingMotions.Remove(ev); PlayingMotions.Remove(ev);
RMVPool.Return(mv);
}
} }
else if (ev.Unstamped is EventContainer) { else if (ev.Unstamped is EventContainer) {
var cev = (EventContainer)ev.Unstamped; var cev = (EventContainer)ev.Unstamped;
@@ -333,7 +333,7 @@ namespace Cryville.Crtr.Event {
ccs.Working = true; ccs.Working = true;
ccs.StartUpdate(); ccs.StartUpdate();
UpdateMotions(); UpdateMotions();
if (!ev.Unstamped.IsLong) { if (!cev.IsLong) {
ccs.Working = false; ccs.Working = false;
ccs.BroadcastEndUpdate(); ccs.BroadcastEndUpdate();
if (CloneType == 1) ccs.Dispose(); if (CloneType == 1) ccs.Dispose();
@@ -344,7 +344,9 @@ namespace Cryville.Crtr.Event {
if (tev.IsRelease) { if (tev.IsRelease) {
var nev = tev.Original; var nev = tev.Original;
if (nev is Chart.Motion) { if (nev is Chart.Motion) {
Callback(ev, callback); Update(ev);
var mv = PlayingMotions[ev.Origin];
if (mv.CloneTypeFlag == CloneType) RMVPool.Return(mv);
PlayingMotions.Remove(ev.Origin); PlayingMotions.Remove(ev.Origin);
} }
else if (nev is EventContainer) { else if (nev is EventContainer) {
@@ -357,15 +359,13 @@ namespace Cryville.Crtr.Event {
} }
} }
} }
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) { void Update(StampedEvent ev) {
UpdateMotions(); UpdateMotions();
if (callback != null)
callback(ev);
if (ev == null || ev.Unstamped != null) Handler.Update(this, ev); if (ev == null || ev.Unstamped != null) Handler.Update(this, ev);
else Handler.ExUpdate(this, ev); else Handler.ExUpdate(this, ev);
foreach (var m in PlayingMotions) foreach (var m in PlayingMotions)
@@ -387,7 +387,7 @@ namespace Cryville.Crtr.Event {
} }
} }
else { else {
var scaledTime = (Time - m.Key.Time - ChartPlayer.actualRenderStep * tev.sumfix) / m.Key.Duration; var scaledTime = (float)((Time - m.Key.Time - ChartPlayer.actualRenderStep * tev.sumfix) / m.Key.Duration);
var lerpedTime = MotionLerper.GetEaseTime(scaledTime, tev.transition, tev.rate); var lerpedTime = MotionLerper.GetEaseTime(scaledTime, tev.transition, tev.rate);
if (tev.RelativeNode != null) { if (tev.RelativeNode != null) {
var target = value.QueryRelativeNode(tev.RelativeNode.Id); var target = value.QueryRelativeNode(tev.RelativeNode.Id);
@@ -401,13 +401,17 @@ namespace Cryville.Crtr.Event {
} }
} }
public void BroadcastInit() { public void BroadcastPreInit() {
Handler.PreInit(); Handler.PreInit();
Handler.Init(); foreach (var c in Children.Values) {
foreach (var s in Children) { c.BroadcastPreInit();
s.Value.BroadcastInit();
} }
}
public void BroadcastPostInit() {
Handler.PostInit(); Handler.PostInit();
foreach (var c in Children.Values) {
c.BroadcastPostInit();
}
} }
public void StartUpdate() { public void StartUpdate() {

View File

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

View File

@@ -9,124 +9,127 @@ namespace Cryville.Crtr.Event {
get; get;
private set; private set;
} }
ContainerState RootState; readonly Chart chart;
/// <summary> ContainerState rootState;
/// event => the container state that handles the event readonly Dictionary<ChartEvent, ContainerState> containerMap
/// </summary>
readonly Dictionary<ChartEvent, ContainerState> table
= new Dictionary<ChartEvent, ContainerState>(); = 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>(); readonly List<EventBatch> batches = new List<EventBatch>();
float beat; double beat;
float tempo; float tempo;
public EventBatcher(Chart c) : base(c, new List<ChartEvent>()) { public EventBatcher(Chart c) : base(new List<ChartEvent>()) {
chart = c;
beat = chart.BeatPosition; beat = chart.BeatPosition;
tempo = (float)c.sigs[0].tempo; tempo = (float)c.sigs[0].tempo;
events.Add(c); Events.Add(c);
events.Add(c.ReleaseEvent); Events.Add(c.ReleaseEvent);
AddEventContainer(c); 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) { void AddEventContainer(EventContainer c, ContainerState parent = null) {
var cs = new ContainerState(chart, c, parent); var cs = new ContainerState(chart, c, parent);
stateMap.Add(c, cs);
if (parent == null) { if (parent == null) {
cs.Depth = 0; cs.Depth = 0;
RootState = cs; rootState = cs;
} }
else { else {
cs.Depth = (ushort)(parent.Depth + 1); cs.Depth = (ushort)(parent.Depth + 1);
} }
foreach (var ev in c.Events) { foreach (var ev in c.Events) {
if (ev.time == null) { if (ev.time == null) {
coevents.Add(ev);
ev.time = c.time; ev.time = c.time;
if (ev is EventContainer) if (ev is EventContainer)
ev.endtime = c.endtime; ev.endtime = c.endtime;
} }
if (ev.IsLong) { if (ev.IsLong) {
events.Add(ev.ReleaseEvent); Events.Add(ev.ReleaseEvent);
table.Add(ev.ReleaseEvent, cs); containerMap.Add(ev.ReleaseEvent, cs);
} }
events.Add(ev); Events.Add(ev);
table.Add(ev, cs); containerMap.Add(ev, cs);
if (ev is EventContainer) if (ev is EventContainer)
AddEventContainer((EventContainer)ev, cs); AddEventContainer((EventContainer)ev, cs);
} }
} }
public override void ForwardOnceToTime(float toTime, Action<ChartEvent> callback) { public override void ForwardOnceToTime(double toTime) {
float toBeat = (float)Math.Round(beat + (toTime - Time) * tempo / 60f, 6); double toBeat = Math.Round(beat + (toTime - Time) * tempo / 60f, 6);
if (EventId >= events.Count) if (EventId >= Events.Count)
goto return_ahead; goto return_ahead;
float ebeat = events[EventId].BeatPosition; double ebeat = Events[EventId].BeatPosition;
float etime = (float)Math.Round((ebeat - beat) / tempo * 60f + Time, 6); double etime = Math.Round((ebeat - beat) / tempo * 60f + Time, 6);
if (etime > toTime) if (etime > toTime)
goto return_ahead; goto return_ahead;
var batch = GetEventBatch(); var batch = GetEventBatch();
Time = etime; Time = etime;
beat = ebeat; beat = ebeat;
bool flag = false;
foreach (var ev in batch) { foreach (var ev in batch) {
EventContainer con = null; EventContainer con = null;
if (table.ContainsKey(ev)) con = table[ev].Container; if (containerMap.ContainsKey(ev)) con = containerMap[ev].Container;
var sev = new StampedEvent() { var sev = new StampedEvent() {
Time = etime, Time = etime,
Unstamped = ev, Unstamped = ev,
Container = con Container = con
}; };
if (ev is EventContainer) {
stateMap[(EventContainer)ev].StampedContainer = sev;
}
if (ev is InstantEvent) { if (ev is InstantEvent) {
var tev = (InstantEvent)ev; var tev = (InstantEvent)ev;
var pev = stampedEvents.First(tpev => tpev.Unstamped == tev.Original); var pev = map[tev.Original];
pev.Subevents.Add(sev); pev.Subevents.Add(sev);
sev.Origin = pev; sev.Origin = pev;
} }
stampedEvents.Add(sev); if (con != null && coevents.Contains(ev)) {
if (ev.Priority >= 0) { List<StampedEvent> cevs;
if (callback != null) callback(ev); if (!coeventMap.TryGetValue(con, out cevs)) {
flag = true; coeventMap.Add(con, cevs = new List<StampedEvent>());
}
cevs.Add(sev);
} }
else stampedEvents.Add(sev);
map.Add(ev, sev);
if (ev is Chart.Signature) { if (ev is Chart.Signature) {
var tev = (Chart.Signature)ev; var tev = (Chart.Signature)ev;
if (tev.tempo != null) tempo = (float)tev.tempo; if (tev.tempo != null) tempo = (float)tev.tempo;
} }
EventId++; EventId++;
} }
if (callback != null && !flag) callback(batch.First());
return; return;
return_ahead: return_ahead:
Time = toTime; Time = toTime;
beat = toBeat; beat = toBeat;
if (callback != null) callback(null);
} }
IOrderedEnumerable<ChartEvent> GetEventBatch() { IOrderedEnumerable<ChartEvent> GetEventBatch() {
float cbeat = events[EventId].BeatPosition; float cbeat = Events[EventId].BeatPosition;
int b = EventId; int b = EventId;
while (Mathf.Approximately(events[b].BeatPosition, cbeat)) { while (Mathf.Approximately(Events[b].BeatPosition, cbeat)) {
b--; b--;
if (b == -1) break; if (b == -1) break;
} }
int a = EventId; int a = EventId;
while (Mathf.Approximately(events[a].BeatPosition, cbeat)) { while (Mathf.Approximately(Events[a].BeatPosition, cbeat)) {
a++; 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() { public EventBus Batch() {
stampedEvents.Sort((a, b) => { stampedEvents.Sort(CompareStampedEvents);
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());
});
var cb = new EventBatch(stampedEvents[0].Time); var cb = new EventBatch(stampedEvents[0].Time);
foreach (var ev in stampedEvents) { foreach (var ev in stampedEvents) {
if (ev.Time != cb.Time) { if (ev.Time != cb.Time) {
@@ -134,10 +137,36 @@ namespace Cryville.Crtr.Event {
cb = new EventBatch(ev.Time); cb = new EventBatch(ev.Time);
} }
cb.Enqueue(ev); cb.Enqueue(ev);
BatchCoevents(ev);
} }
batches.Add(cb); batches.Add(cb);
Bus = new EventBus(chart, RootState, batches); Bus = new EventBus(rootState, batches);
return Bus; 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,15 +11,14 @@ namespace Cryville.Crtr.Event {
Dictionary<EventContainer, ContainerState> states Dictionary<EventContainer, ContainerState> states
= new Dictionary<EventContainer, ContainerState>(); = new Dictionary<EventContainer, ContainerState>();
List<EventContainer> activeContainers HashSet<EventContainer> activeContainers
= new List<EventContainer>(); = new HashSet<EventContainer>();
HashSet<ContainerState> workingStates HashSet<ContainerState> workingStates
= new HashSet<ContainerState>(); = new HashSet<ContainerState>();
HashSet<ContainerState> invalidatedStates HashSet<ContainerState> invalidatedStates
= new HashSet<ContainerState>(); = new HashSet<ContainerState>();
public EventBus(Chart c, ContainerState root, List<EventBatch> b) public EventBus(ContainerState root, List<EventBatch> b) : base(b) {
: base(c, b) {
RootState = root; RootState = root;
Expand(); Expand();
AttachBus(); AttachBus();
@@ -30,9 +29,10 @@ namespace Cryville.Crtr.Event {
var r = (EventBus)MemberwiseClone(); var r = (EventBus)MemberwiseClone();
r.prototype = this; r.prototype = this;
r.states = new Dictionary<EventContainer, ContainerState>(); r.states = new Dictionary<EventContainer, ContainerState>();
r.activeContainers = new List<EventContainer>(); r.activeContainers = new HashSet<EventContainer>();
r.workingStates = new HashSet<ContainerState>(); r.workingStates = new HashSet<ContainerState>();
r.invalidatedStates = new HashSet<ContainerState>(); r.invalidatedStates = new HashSet<ContainerState>();
r.tempEvents = new List<StampedEvent>();
r.Time += offsetTime; r.Time += offsetTime;
r.RootState = RootState.Clone(ct); r.RootState = RootState.Clone(ct);
r.RootState.StartUpdate(); r.RootState.StartUpdate();
@@ -85,8 +85,18 @@ namespace Cryville.Crtr.Event {
void EnsureActivity(EventContainer c) { void EnsureActivity(EventContainer c) {
if (activeContainers.Contains(c)) return; if (activeContainers.Contains(c)) return;
if (RootState.CloneType >= 2) prototype.states[c].CopyTo(RootState.CloneType, states[c]); var state = states[c];
if (state.Parent != null) EnsureActivity(state.Parent.Container);
if (RootState.CloneType >= 2) prototype.states[c].CopyTo(RootState.CloneType, state);
state.Active = true;
activeContainers.Add(c); activeContainers.Add(c);
if (state.StampedContainer.Coevents == null) return;
foreach (var cev in state.StampedContainer.Coevents) {
if (cev.Container == null) continue;
EnsureActivity(cev.Container);
states[cev.Container].Handle(cev);
}
} }
void AttachBus() { void AttachBus() {
@@ -99,39 +109,60 @@ namespace Cryville.Crtr.Event {
s.AttachSystems(skin, judge); s.AttachSystems(skin, judge);
} }
readonly List<StampedEvent> patch = new List<StampedEvent>(); List<StampedEvent> tempEvents = new List<StampedEvent>();
public void IssuePatch(IEnumerable<StampedEvent> l) { public void PushTempEvent(StampedEvent ev) {
patch.AddRange(l); var index = tempEvents.BinarySearch(ev);
} if (index < 0) index = ~index;
public void DoPatch() { tempEvents.Insert(index, ev);
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();
} }
public override void ForwardOnceToTime(float toTime, Action<EventBatch> callback = null) { readonly StampedEvent _dummyEvent = new StampedEvent();
if (EventId < events.Count && events[EventId].Time <= toTime) { public void StripTempEvents() {
Time = events[EventId].Time; _dummyEvent.Time = Time;
var batch = events[EventId]; var index = tempEvents.BinarySearch(_dummyEvent);
if (index < 0) index = ~index;
for (var i = 0; i < index; i++) {
var ev = tempEvents[i];
if (ev.Container != null) {
states[ev.Container].Discard(ev);
}
}
tempEvents.RemoveRange(0, index);
}
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 workingStates) s.Handle(null); foreach (var s in workingStates) s.Handle(null);
ValidateStates(); ValidateStates();
for (var i = 0; i < batch.Count; i++) { if (time1 == time0) {
var ev = batch[i]; var batch = Events[EventId];
if (ev.Container != null) { for (var i = 0; i < batch.Count; i++) {
EnsureActivity(ev.Container); var ev = batch[i];
states[ev.Container].Handle(ev); if (ev.Container != null) {
if (ev.Unstamped is EventContainer) EnsureActivity((EventContainer)ev.Unstamped);
else EnsureActivity(ev.Container);
states[ev.Container].Handle(ev);
}
else if (ev.Coevents != null) EnsureActivity((EventContainer)ev.Unstamped);
} }
if (ev.Unstamped is EventContainer) { EventId++;
if (ev.Container != null) EnsureActivity((EventContainer)ev.Unstamped); }
if (time2 == time0) {
while (tempEvents.Count > 0) {
var ev = tempEvents[0];
if (ev.Time != time0) break;
if (ev.Container != null) {
EnsureActivity(ev.Container);
states[ev.Container].Handle(ev);
}
tempEvents.RemoveAt(0);
} }
} }
ValidateStates(); ValidateStates();
EventId++;
} }
else { else {
Time = toTime; Time = toTime;
@@ -147,12 +178,16 @@ namespace Cryville.Crtr.Event {
invalidatedStates.Clear(); invalidatedStates.Clear();
} }
public void BroadcastInit() { public void BroadcastPreInit() {
RootState.BroadcastInit(); RootState.BroadcastPreInit();
}
public void BroadcastPostInit() {
RootState.BroadcastPostInit();
} }
public void BroadcastEndUpdate() { public void BroadcastEndUpdate() {
RootState.BroadcastEndUpdate(); RootState.BroadcastEndUpdate();
tempEvents.Clear();
} }
public void Anchor() { public void 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)); _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) { public RealtimeMotionValue Rent(Identifier name) {
var n = name; var obj = _buckets[name].Rent();
var obj = _buckets[n].Rent(); if (_rented == null) _rented = _dictPool.Rent();
_rented.Add(obj, n); _rented.Add(obj, name);
return obj; return obj;
} }
public void Return(RealtimeMotionValue obj) { public void Return(RealtimeMotionValue obj) {
@@ -32,9 +34,11 @@ namespace Cryville.Crtr.Event {
_rented.Remove(obj); _rented.Remove(obj);
} }
public void ReturnAll() { public void ReturnAll() {
if (_rented == null) return;
foreach (var obj in _rented) foreach (var obj in _rented)
_buckets[obj.Value].Return(obj.Key); _buckets[obj.Value].Return(obj.Key);
_rented.Clear(); _rented.Clear();
_dictPool.Return(_rented);
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,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

@@ -76,14 +76,30 @@ namespace Cryville.Crtr {
#if UNITY_ANDROID #if UNITY_ANDROID
Cryville.Audio.OpenSL.OutputClient.CallbackFunction = audioCallback; Cryville.Audio.OpenSL.OutputClient.CallbackFunction = audioCallback;
#endif #endif
AudioManager = EngineBuilder.Create(); while (true) {
Logger.Log("main", 1, "Audio", "Using audio API: {0}", AudioManager.GetType().Namespace); try {
AudioClient = AudioManager.GetDefaultDevice(DataFlow.Out).Connect(); AudioManager = EngineBuilder.Create();
AudioClient.Init(AudioClient.DefaultFormat); if (AudioManager == null) {
AudioClient.Source = AudioSequencer = new SimpleSequencerSource(); Popup.Create("Cannot initialize audio engine");
AudioSession = AudioSequencer.NewSession(); Logger.Log("main", 5, "Audio", "Cannot initialize audio engine");
AudioSequencer.Playing = true; }
AudioClient.Start(); else {
Logger.Log("main", 1, "Audio", "Using audio API: {0}", AudioManager.GetType().Namespace);
AudioClient = AudioManager.GetDefaultDevice(DataFlow.Out).Connect();
AudioClient.Init(AudioClient.DefaultFormat);
AudioClient.Source = AudioSequencer = new SimpleSequencerSource();
AudioSession = AudioSequencer.NewSession();
AudioSequencer.Playing = true;
AudioClient.Start();
}
break;
}
catch (Exception ex) {
Logger.Log("main", 4, "Audio", "An error occured when initializing the audio engine: {0}", ex);
Logger.Log("main", 3, "Audio", "Trying to use fallback audio engines");
EngineBuilder.Engines.Remove(AudioManager.GetType());
}
}
ChartPlayer.motionRegistry = new Dictionary<Identifier, MotionRegistry> { ChartPlayer.motionRegistry = new Dictionary<Identifier, MotionRegistry> {
{ "pt" , new MotionRegistry(typeof(VecPt)) }, { "pt" , new MotionRegistry(typeof(VecPt)) },

View File

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

View File

@@ -17,6 +17,7 @@ namespace Cryville.Crtr {
*(int*)(ptr + 3 * sizeof(float)) = PdtInternalType.Number; *(int*)(ptr + 3 * sizeof(float)) = PdtInternalType.Number;
} }
} }
_vecsrc = new PropSrc.Arbitrary(PdtInternalType.Vector, _vecbuf);
_etor = ChartPlayer.etor; _etor = ChartPlayer.etor;
_ruleset = ruleset; _ruleset = ruleset;
_judge = judge; _judge = judge;
@@ -64,10 +65,6 @@ namespace Cryville.Crtr {
if (_use[target] > 0) if (_use[target] > 0)
throw new InvalidOperationException("Input already assigned"); throw new InvalidOperationException("Input already assigned");
if (proxy.Source != null) { 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); _tproxies.Add(target, proxy);
_sproxies.Add(proxy.Source.Value, proxy); _sproxies.Add(proxy.Source.Value, proxy);
IncrementUseRecursive(target); IncrementUseRecursive(target);
@@ -76,7 +73,6 @@ namespace Cryville.Crtr {
} }
void Remove(InputProxyEntry proxy) { void Remove(InputProxyEntry proxy) {
var target = proxy.Target; var target = proxy.Target;
if (_judge != null) _tproxies[target].Source.Value.Handler.OnInput -= OnInput;
_sproxies.Remove(_tproxies[target].Source.Value); _sproxies.Remove(_tproxies[target].Source.Value);
_tproxies.Remove(target); _tproxies.Remove(target);
DecrementUseRecursive(target); DecrementUseRecursive(target);
@@ -141,12 +137,22 @@ namespace Cryville.Crtr {
public void Activate() { public void Activate() {
_activeCounts.Clear(); _activeCounts.Clear();
_vect.Clear(); _vecs.Clear(); _vect.Clear(); _vecs.Clear();
foreach (var src in _sproxies.Keys) { foreach (var src in _sproxies) {
_activeCounts.Add(src, 0); _activeCounts.Add(src.Key, 0);
src.Handler.Activate(); 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() { ~InputProxy() {
Dispose(false); Dispose(false);
@@ -168,11 +174,12 @@ namespace Cryville.Crtr {
static readonly int _var_value = IdentifierManager.SharedInstance.Request("value"); static readonly int _var_value = IdentifierManager.SharedInstance.Request("value");
static readonly PropOp.Arbitrary _arbop = new PropOp.Arbitrary(); static readonly PropOp.Arbitrary _arbop = new PropOp.Arbitrary();
readonly byte[] _vecbuf = new byte[3 * sizeof(float) + sizeof(int)]; readonly byte[] _vecbuf = new byte[3 * sizeof(float) + sizeof(int)];
readonly PropSrc.Arbitrary _vecsrc;
readonly Dictionary<InputHandler, double> _timeOrigins = new Dictionary<InputHandler, double>(); readonly Dictionary<InputHandler, double> _timeOrigins = new Dictionary<InputHandler, double>();
readonly Dictionary<InputSource, int> _activeCounts = new Dictionary<InputSource, int>(); readonly Dictionary<InputSource, int> _activeCounts = new Dictionary<InputSource, int>();
readonly Dictionary<InputIdentifier, float> _vect = new Dictionary<InputIdentifier, float>(); 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 byte[] _nullvalue = new byte[0]; static readonly PropSrc.Arbitrary _nullsrc = new PropSrc.Arbitrary(PdtInternalType.Null, new byte[0]);
unsafe void OnInput(InputIdentifier id, InputVector vec) { unsafe void OnInput(InputIdentifier id, InputVector vec) {
lock (_lock) { lock (_lock) {
InputProxyEntry proxy; InputProxyEntry proxy;
@@ -181,14 +188,15 @@ namespace Cryville.Crtr {
float ft, tt = (float)(vec.Time - _timeOrigins[id.Source.Handler]); float ft, tt = (float)(vec.Time - _timeOrigins[id.Source.Handler]);
if (!_vect.TryGetValue(id, out ft)) ft = tt; if (!_vect.TryGetValue(id, out ft)) ft = tt;
if (vec.IsNull) { if (vec.IsNull) {
_etor.ContextCascadeUpdate(_var_value, new PropSrc.Arbitrary(PdtInternalType.Null, _nullvalue)); _etor.ContextCascadeUpdate(_var_value, _nullsrc);
OnInput(id, proxy.Target, ft, tt, true); OnInput(id, proxy.Target, ft, tt, true);
} }
else { else {
fixed (byte* ptr = _vecbuf) { fixed (byte* ptr = _vecbuf) {
*(Vector3*)ptr = vec.Vector; *(Vector3*)ptr = vec.Vector;
} }
_etor.ContextCascadeUpdate(_var_value, new PropSrc.Arbitrary(PdtInternalType.Vector, _vecbuf)); _vecsrc.Invalidate();
_etor.ContextCascadeUpdate(_var_value, _vecsrc);
OnInput(id, proxy.Target, ft, tt, false); OnInput(id, proxy.Target, ft, tt, false);
} }
_vect[id] = tt; _vect[id] = tt;
@@ -211,8 +219,8 @@ namespace Cryville.Crtr {
} }
else { else {
var pid = new ProxiedInputIdentifier { Source = id, Target = target }; 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 = new PropSrc.Arbitrary(PdtInternalType.Null, _nullvalue); if (!_vecs.TryGetValue(pid, out fv)) fv = _nullsrc;
if (fv.Type != PdtInternalType.Null || tv.Type != PdtInternalType.Null) { if (fv.Type != PdtInternalType.Null || tv.Type != PdtInternalType.Null) {
if (fv.Type == PdtInternalType.Null) _activeCounts[id.Source]++; if (fv.Type == PdtInternalType.Null) _activeCounts[id.Source]++;
_etor.ContextCascadeInsert(); _etor.ContextCascadeInsert();
@@ -222,15 +230,14 @@ namespace Cryville.Crtr {
_etor.ContextCascadeDiscard(); _etor.ContextCascadeDiscard();
if (tv.Type == PdtInternalType.Null) _activeCounts[id.Source]--; if (tv.Type == PdtInternalType.Null) _activeCounts[id.Source]--;
} }
_judge.Cleanup(target, ft, tt); _judge.Cleanup(target, tt);
_vecs[pid] = tv; _vecs[pid] = tv;
} }
} }
public void SyncTime(double time) { public void SyncTime(double time) {
foreach (var s in _sproxies.Keys) { foreach (var s in _sproxies.Keys) {
var h = s.Handler; var h = s.Handler;
if (!_timeOrigins.ContainsKey(h)) _timeOrigins[h] = h.GetCurrentTimestamp() - time;
_timeOrigins.Add(h, h.GetCurrentTimestamp() - time);
} }
} }
public void ForceTick() { public void ForceTick() {

View File

@@ -1,13 +1,13 @@
using Cryville.Common; using Cryville.Common;
using Cryville.Common.Buffers; using Cryville.Common.Buffers;
using Cryville.Common.Pdt; using Cryville.Common.Pdt;
using Cryville.Crtr.Event;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class Judge { public class Judge {
#region Data
readonly PdtEvaluator _etor; readonly PdtEvaluator _etor;
readonly PdtRuleset _rs; readonly PdtRuleset _rs;
readonly Dictionary<Identifier, float> ct readonly Dictionary<Identifier, float> ct
@@ -16,13 +16,14 @@ namespace Cryville.Crtr {
= new Dictionary<Identifier, List<JudgeEvent>>(); = new Dictionary<Identifier, List<JudgeEvent>>();
readonly Dictionary<Identifier, List<JudgeEvent>> activeEvs readonly Dictionary<Identifier, List<JudgeEvent>> activeEvs
= new Dictionary<Identifier, List<JudgeEvent>>(); = new Dictionary<Identifier, List<JudgeEvent>>();
struct JudgeEvent { public struct JudgeEvent {
public float StartTime { get; set; } public double StartTime { get; set; }
public float EndTime { get; set; } public double EndTime { get; set; }
public float StartClip { get; set; } public double StartClip { get; set; }
public float EndClip { get; set; } public double EndClip { get; set; }
public Chart.Judge BaseEvent { get; set; }
public JudgeDefinition Definition { get; set; } public JudgeDefinition Definition { get; set; }
public ContainerState State { get; set; } public NoteHandler Handler { get; set; }
} }
static readonly IComparer<JudgeEvent> _stcmp = new JudgeEventStartTimeComparer(); static readonly IComparer<JudgeEvent> _stcmp = new JudgeEventStartTimeComparer();
class JudgeEventStartTimeComparer : IComparer<JudgeEvent> { class JudgeEventStartTimeComparer : IComparer<JudgeEvent> {
@@ -33,27 +34,46 @@ namespace Cryville.Crtr {
public Judge(PdtRuleset rs) { public Judge(PdtRuleset rs) {
_etor = ChartPlayer.etor; _etor = ChartPlayer.etor;
_rs = rs; _rs = rs;
InitJudges();
InitScores(); 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; List<JudgeEvent> list;
if (!evs.TryGetValue(input, out list)) { if (!evs.TryGetValue(input, out list)) {
ct.Add(input, 0); ct.Add(input, 0);
evs.Add(input, list = new List<JudgeEvent>()); evs.Add(input, list = new List<JudgeEvent>());
activeEvs.Add(input, new List<JudgeEvent>()); activeEvs.Add(input, new List<JudgeEvent>());
} }
var def = _rs.judges[tev.Id];
var ev = new JudgeEvent { var ev = new JudgeEvent {
StartTime = st, StartTime = st,
EndTime = et, EndTime = et,
StartClip = st + def.clip[0], StartClip = st + def.clip[0],
EndClip = et + def.clip[1], EndClip = et + def.clip[1],
BaseEvent = tev,
Definition = def, Definition = def,
State = container, Handler = handler,
}; };
var index = list.BinarySearch(ev, _stcmp); var index = list.BinarySearch(ev, _stcmp);
if (index < 0) index = ~index; if (index < 0) index = ~index;
list.Insert(index, ev); list.Insert(index, ev);
} }
#endregion
#region Judge
internal readonly Dictionary<int, int> judgeMap = new Dictionary<int, int>();
internal readonly Dictionary<int, int> jtabsMap = new Dictionary<int, int>();
internal readonly Dictionary<int, int> jtrelMap = new Dictionary<int, int>();
void InitJudges() {
foreach (var i in _rs.judges.Keys) {
judgeMap.Add(i.Key, IdentifierManager.SharedInstance.Request("judge_" + i.Name));
jtabsMap.Add(i.Key, IdentifierManager.SharedInstance.Request("jtabs_" + i.Name));
jtrelMap.Add(i.Key, IdentifierManager.SharedInstance.Request("jtrel_" + i.Name));
}
}
static bool _flag; static bool _flag;
static readonly PropOp.Boolean _flagop = new PropOp.Boolean(v => _flag = v); static readonly PropOp.Boolean _flagop = new PropOp.Boolean(v => _flag = v);
static readonly int _var_fn = IdentifierManager.SharedInstance.Request("fn"); static readonly int _var_fn = IdentifierManager.SharedInstance.Request("fn");
@@ -89,10 +109,12 @@ namespace Cryville.Crtr {
int num3 = num + (num2 - num >> 1); int num3 = num + (num2 - num >> 1);
int num4 = -list[num3].Definition.stack.CompareTo(stack); int num4 = -list[num3].Definition.stack.CompareTo(stack);
if (num4 == 0) num4 = list[num3].StartClip.CompareTo(time); if (num4 == 0) num4 = list[num3].StartClip.CompareTo(time);
if (num4 >= 0) num2 = num3 - 1; if (num4 > 0) num2 = num3 - 1;
else num = num3 + 1; else if (num4 < 0) num = num3 + 1;
else if (num != num3) num2 = num3;
else return num;
} }
return num + 1; return ~num;
} }
public void Feed(Identifier target, float ft, float tt) { public void Feed(Identifier target, float ft, float tt) {
Forward(target, tt); Forward(target, tt);
@@ -103,17 +125,17 @@ namespace Cryville.Crtr {
var index = 0; var index = 0;
while (index >= 0 && index < actlist.Count) { while (index >= 0 && index < actlist.Count) {
var ev = actlist[index]; var ev = actlist[index];
LoadNum(_numbuf1, ev.StartTime); _etor.ContextCascadeUpdate(_var_fn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf1)); LoadNum(_numbuf1, (float)ev.StartTime); _etor.ContextCascadeUpdate(_var_fn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf1));
LoadNum(_numbuf2, ev.EndTime); _etor.ContextCascadeUpdate(_var_tn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf2)); LoadNum(_numbuf2, (float)ev.EndTime); _etor.ContextCascadeUpdate(_var_tn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf2));
var def = ev.Definition; var def = ev.Definition;
if (def.hit != null) _etor.Evaluate(_flagop, def.hit); if (def.hit != null) _etor.Evaluate(_flagop, def.hit);
else _flag = true; else _flag = true;
if (_flag) { if (_flag) {
if (def.scores != null) UpdateScore(def.scores); 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); actlist.RemoveAt(index);
if (def.prop != 0 && actlist.Count > 0) { if (def.prop != 0 && actlist.Count > 0) {
index = BinarySearchFirst(actlist, ev.StartClip, def.stack - def.prop); index = BinarySearchFirst(actlist, (float)ev.StartClip, def.stack - def.prop);
if (index < 0) index = ~index; if (index < 0) index = ~index;
} }
else index++; else index++;
@@ -122,27 +144,28 @@ namespace Cryville.Crtr {
} }
} }
} }
bool Pass(Identifier[] ids) { bool Pass(JudgeEvent ev, float time, Identifier[] ids) {
foreach (var i in ids) { foreach (var i in ids) {
var def = _rs.judges[i]; var def = _rs.judges[i];
if (def.hit != null) _etor.Evaluate(_flagop, def.hit); if (def.hit != null) _etor.Evaluate(_flagop, def.hit);
else _flag = true; else _flag = true;
if (_flag) { if (_flag) {
if (def.scores != null) UpdateScore(def.scores); 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; return true;
} }
} }
return false; return false;
} }
public void Cleanup(Identifier target, float ft, float tt) { public void Cleanup(Identifier target, float tt) {
Forward(target, tt); Forward(target, tt);
var actlist = activeEvs[target]; var actlist = activeEvs[target];
for (int i = actlist.Count - 1; i >= 0; i--) { for (int i = actlist.Count - 1; i >= 0; i--) {
JudgeEvent ev = actlist[i]; JudgeEvent ev = actlist[i];
if (tt > ev.EndClip) { if (tt > ev.EndClip) {
actlist.RemoveAt(i); actlist.RemoveAt(i);
if (ev.Definition.miss != null) Pass(ev.Definition.miss); if (ev.Definition.miss != null) Pass(ev, tt, ev.Definition.miss);
} }
} }
} }
@@ -152,7 +175,7 @@ namespace Cryville.Crtr {
JudgeEvent ev; JudgeEvent ev;
while (list.Count > 0 && (ev = list[0]).StartClip <= tt) { while (list.Count > 0 && (ev = list[0]).StartClip <= tt) {
list.RemoveAt(0); list.RemoveAt(0);
var index = BinarySearch(actlist, ev.StartClip, ev.Definition.stack); var index = BinarySearch(actlist, (float)ev.StartClip, ev.Definition.stack);
if (index < 0) index = ~index; if (index < 0) index = ~index;
actlist.Insert(index, ev); actlist.Insert(index, ev);
} }
@@ -172,6 +195,8 @@ namespace Cryville.Crtr {
} }
} }
} }
#endregion
#region Score
readonly Dictionary<int, int> scoreStringKeys = new Dictionary<int, int>(); readonly Dictionary<int, int> scoreStringKeys = new Dictionary<int, int>();
readonly Dictionary<int, int> scoreStringKeysRev = new Dictionary<int, int>(); readonly Dictionary<int, int> scoreStringKeysRev = new Dictionary<int, int>();
readonly Dictionary<int, PropSrc> scoreSrcs = new Dictionary<int, PropSrc>(); readonly Dictionary<int, PropSrc> scoreSrcs = new Dictionary<int, PropSrc>();
@@ -227,7 +252,8 @@ namespace Cryville.Crtr {
readonly Func<string> _cb; readonly Func<string> _cb;
readonly ArrayPool<byte> _pool; readonly ArrayPool<byte> _pool;
byte[] _buf; byte[] _buf;
public ScoreStringSrc(ArrayPool<byte> pool, Func<string> cb) { public ScoreStringSrc(ArrayPool<byte> pool, Func<string> cb)
: base(PdtInternalType.String) {
_pool = pool; _pool = pool;
_cb = cb; _cb = cb;
} }
@@ -238,12 +264,11 @@ namespace Cryville.Crtr {
_buf = null; _buf = null;
} }
} }
protected override unsafe void InternalGet(out int type, out byte[] value) { protected override unsafe void InternalGet() {
var src = _cb(); var src = _cb();
int strlen = src.Length; int strlen = src.Length;
type = PdtInternalType.String; buf = _pool.Rent(sizeof(int) + strlen * sizeof(char));
value = _pool.Rent(sizeof(int) + strlen * sizeof(char)); fixed (byte* _ptr = buf) {
fixed (byte* _ptr = value) {
char* ptr = (char*)(_ptr + sizeof(int)); char* ptr = (char*)(_ptr + sizeof(int));
*(int*)_ptr = strlen; *(int*)_ptr = strlen;
int i = 0; int i = 0;
@@ -251,7 +276,9 @@ namespace Cryville.Crtr {
} }
} }
} }
#endregion
} }
#region Definitions
public class InputDefinition { public class InputDefinition {
public int dim; public int dim;
public bool notnull; public bool notnull;
@@ -280,4 +307,5 @@ namespace Cryville.Crtr {
public float init = 0; public float init = 0;
public string format = ""; public string format = "";
} }
#endregion
} }

View File

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

View File

@@ -2,6 +2,7 @@ using Cryville.Common;
using Cryville.Common.Pdt; using Cryville.Common.Pdt;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using UnityEngine; using UnityEngine;
@@ -22,9 +23,9 @@ namespace Cryville.Crtr {
} }
public static class MotionLerper { public static class MotionLerper {
public static void Lerp<T>(float time, float tt, T tv, float ft, T fv, TransitionType type, float rate, ref T result) where T : Vector { public static void Lerp<T>(double time, double tt, T tv, double ft, T fv, TransitionType type, float rate, ref T result) where T : Vector {
if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType()); if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType());
Lerp((time - ft) / (tt - ft), fv, tv, type, rate, ref result); Lerp((float)((time - ft) / (tt - ft)), fv, tv, type, rate, ref result);
} }
public static void Lerp<T>(float scaledTime, T from, T to, TransitionType type, float rate, ref T result) where T : Vector { public static void Lerp<T>(float scaledTime, T from, T to, TransitionType type, float rate, ref T result) where T : Vector {
@@ -34,7 +35,7 @@ namespace Cryville.Crtr {
to.LerpWith(from, GetEaseTime(scaledTime, type, rate), ref r); to.LerpWith(from, GetEaseTime(scaledTime, type, rate), ref r);
} }
public static float Delerp<T>(T value, float tt, T tv, float ft, T fv, TransitionType type, float rate) where T : Vector { public static double Delerp<T>(T value, double tt, T tv, double ft, T fv, TransitionType type, float rate) where T : Vector {
if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType()); if (fv == null) fv = (T)ReflectionHelper.InvokeEmptyConstructor(tv.GetType());
var t = Delerp(value, fv, tv, type, rate); var t = Delerp(value, fv, tv, type, rate);
return ft * (1 - t) + tt * t; return ft * (1 - t) + tt * t;
@@ -170,6 +171,7 @@ namespace Cryville.Crtr {
public class RealtimeMotionValue { public class RealtimeMotionValue {
public Vector AbsoluteValue; public Vector AbsoluteValue;
List<MotionNode> RelativeNodes; List<MotionNode> RelativeNodes;
internal byte CloneTypeFlag;
public RealtimeMotionValue Init(Vector init) { public RealtimeMotionValue Init(Vector init) {
RelativeNodes = new List<MotionNode> { RelativeNodes = new List<MotionNode> {
@@ -349,6 +351,8 @@ namespace Cryville.Crtr {
public abstract class Vector : IComparable<Vector> { public abstract class Vector : IComparable<Vector> {
public Vector() { } public Vector() { }
public abstract byte Dimension { get; }
public abstract int CompareTo(Vector other); public abstract int CompareTo(Vector other);
public abstract void ApplyFrom(Vector parent); public abstract void ApplyFrom(Vector parent);
@@ -367,11 +371,11 @@ namespace Cryville.Crtr {
static readonly Type[] stringTypeArray = new Type[] { typeof(string) }; static readonly Type[] stringTypeArray = new Type[] { typeof(string) };
static readonly Type[] floatArrayTypeArray = new Type[] { typeof(float[]) }; static readonly Type[] floatArrayTypeArray = new Type[] { typeof(float[]) };
public static Vector Construct(Type type, string s) { public static Vector Construct(Type type, string s) {
if (!typeof(Vector).IsAssignableFrom(type)) throw new ArgumentException(); // TODO if (!typeof(Vector).IsAssignableFrom(type)) throw new ArgumentException("Type is not vector");
return (Vector)type.GetConstructor(stringTypeArray).Invoke(new object[] { s }); return (Vector)type.GetConstructor(stringTypeArray).Invoke(new object[] { s });
} }
public static Vector Construct(Type type, float[] values) { public static Vector Construct(Type type, float[] values) {
if (!typeof(Vector).IsAssignableFrom(type)) throw new ArgumentException(); // TODO if (!typeof(Vector).IsAssignableFrom(type)) throw new ArgumentException("Type is not vector");
return (Vector)type.GetConstructor(floatArrayTypeArray).Invoke(new object[] { values }); return (Vector)type.GetConstructor(floatArrayTypeArray).Invoke(new object[] { values });
} }
} }
@@ -390,6 +394,8 @@ namespace Cryville.Crtr {
Value = i; Value = i;
} }
public override byte Dimension { get { return 1; } }
public override int CompareTo(Vector other) { public override int CompareTo(Vector other) {
return CompareTo((Vec1)other); return CompareTo((Vec1)other);
} }
@@ -433,7 +439,7 @@ namespace Cryville.Crtr {
} }
public override string ToString() { public override string ToString() {
return Value.ToString(); return Value.ToString(CultureInfo.InvariantCulture);
} }
public override float[] ToArray() { public override float[] ToArray() {
@@ -455,6 +461,8 @@ namespace Cryville.Crtr {
Value = i; Value = i;
} }
public override byte Dimension { get { return 1; } }
public override int CompareTo(Vector other) { public override int CompareTo(Vector other) {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -493,7 +501,7 @@ namespace Cryville.Crtr {
} }
public override string ToString() { public override string ToString() {
return Value.ToString(); return Value.ToString(CultureInfo.InvariantCulture);
} }
public override float[] ToArray() { public override float[] ToArray() {
@@ -515,6 +523,8 @@ namespace Cryville.Crtr {
Value = i; Value = i;
} }
public override byte Dimension { get { return 1; } }
public override int CompareTo(Vector other) { public override int CompareTo(Vector other) {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -553,7 +563,7 @@ namespace Cryville.Crtr {
} }
public override string ToString() { public override string ToString() {
return Value.ToString(); return Value.ToString(CultureInfo.InvariantCulture);
} }
public override float[] ToArray() { public override float[] ToArray() {
@@ -576,6 +586,8 @@ namespace Cryville.Crtr {
this.h = h; this.h = h;
} }
public override byte Dimension { get { return 2; } }
public static void Parse(string s, out float? w, out float? h) { public static void Parse(string s, out float? w, out float? h) {
string[] c = s.Split('+'); string[] c = s.Split('+');
float rw = 0, rh = 0; float rw = 0, rh = 0;
@@ -648,8 +660,8 @@ namespace Cryville.Crtr {
public static string ToString(float? w, float? h) { public static string ToString(float? w, float? h) {
List<string> list = new List<string>(); List<string> list = new List<string>();
if (w != null) list.Add(w.ToString() + "w"); if (w != null) list.Add(w.Value.ToString(CultureInfo.InvariantCulture) + "w");
if (h != null) list.Add(h.ToString() + "h"); if (h != null) list.Add(h.Value.ToString(CultureInfo.InvariantCulture) + "h");
return string.Join("+", list.ToArray()); return string.Join("+", list.ToArray());
} }
@@ -695,6 +707,8 @@ namespace Cryville.Crtr {
this.x = x; this.y = y; this.z = z; this.x = x; this.y = y; this.z = z;
} }
public override byte Dimension { get { return 3; } }
public override int CompareTo(Vector other) { public override int CompareTo(Vector other) {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -744,9 +758,9 @@ namespace Cryville.Crtr {
public override string ToString() { public override string ToString() {
return string.Format("{0},{1},{2}", return string.Format("{0},{1},{2}",
x != null ? x.ToString() : "", x != null ? x.Value.ToString(CultureInfo.InvariantCulture) : "",
y != null ? y.ToString() : "", y != null ? y.Value.ToString(CultureInfo.InvariantCulture) : "",
z != null ? z.ToString() : "" z != null ? z.Value.ToString(CultureInfo.InvariantCulture) : ""
); );
} }
@@ -771,6 +785,8 @@ namespace Cryville.Crtr {
this.xw = xw; this.xh = xh; this.yw = yw; this.yh = yh; 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) { public override int CompareTo(Vector other) {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -850,6 +866,8 @@ namespace Cryville.Crtr {
this.xw = xw; this.xh = xh; this.yw = yw; this.yh = yh; this.z = z; 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) { public override int CompareTo(Vector other) {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@@ -915,7 +933,7 @@ namespace Cryville.Crtr {
} }
public override string ToString() { public override string ToString() {
return VecPtComp.ToString(xw, xh) + "," + VecPtComp.ToString(yw, yh) + "," + (z != null ? z.ToString() : ""); return VecPtComp.ToString(xw, xh) + "," + VecPtComp.ToString(yw, yh) + "," + (z != null ? z.Value.ToString(CultureInfo.InvariantCulture) : "");
} }
public override float[] ToArray() { public override float[] ToArray() {
@@ -923,22 +941,29 @@ namespace Cryville.Crtr {
} }
} }
public class VectorSrc : PropSrc { public abstract class VectorSrc : PropSrc {
readonly Func<Vector> _cb; protected readonly Func<Vector> _cb;
public VectorSrc(Func<Vector> cb) { _cb = cb; } public VectorSrc(Func<Vector> cb, int type) : base(type) { _cb = cb; }
protected override unsafe void InternalGet(out int type, out byte[] value) { public static VectorSrc Construct(Func<Vector> cb) {
var arr = _cb().ToArray(); if (cb().Dimension == 1) return new INumber(cb);
if (arr.Length == 1) { else return new IVector(cb);
type = PdtInternalType.Number; }
value = new byte[sizeof(float)]; class INumber : VectorSrc {
fixed (byte* ptr = value) { 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]; *(float*)ptr = arr[0];
} }
} }
else { }
type = PdtInternalType.Vector; class IVector : VectorSrc {
value = new byte[sizeof(float) * arr.Length + sizeof(int)]; public IVector(Func<Vector> cb) : base(cb, PdtInternalType.Vector) { }
fixed (byte* rptr = value) { 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; var ptr = (float*)rptr;
for (int i = 0; i < arr.Length; i++, ptr++) { for (int i = 0; i < arr.Length; i++, ptr++) {
*ptr = arr[i]; *ptr = arr[i];

View File

@@ -7,15 +7,12 @@ using System.Collections.Generic;
using UnityEngine; using UnityEngine;
namespace Cryville.Crtr { namespace Cryville.Crtr {
class NoteHandler : ContainerHandler { public class NoteHandler : ContainerHandler {
readonly GroupHandler gh; readonly GroupHandler gh;
public readonly Chart.Note Event; public readonly Chart.Note Event;
readonly PdtRuleset ruleset; public NoteHandler(Chart.Note ev, GroupHandler gh) : base() {
public NoteHandler(GroupHandler gh, Chart.Note ev, PdtRuleset rs, Judge j) : base() {
this.gh = gh;
Event = ev; Event = ev;
ruleset = rs; this.gh = gh;
judge = j;
} }
public override string TypeName { public override string TypeName {
@@ -25,26 +22,76 @@ namespace Cryville.Crtr {
} }
SectionalGameObject[] sgos; SectionalGameObject[] sgos;
readonly Dictionary<Chart.Judge, JudgeState> judges = new Dictionary<Chart.Judge, JudgeState>();
readonly Dictionary<int, DynamicJudgeAnchorPair> dynJudgeAnchors = new Dictionary<int, DynamicJudgeAnchorPair>();
class JudgeState {
static readonly int _var_judge_result = IdentifierManager.SharedInstance.Request("judge_result");
public Anchor StaticAnchor { get; private set; }
public DynamicJudgeAnchorPair DynamicAnchors { get; private set; }
public bool Judged { get; private set; }
public float AbsoluteTime { get; private set; }
public float RelativeTime { get; private set; }
int _result = 0;
PropSrc _resultPropSrc;
public JudgeState(NoteHandler handler, int name) {
StaticAnchor = handler.RegisterAnchor(handler.judge.judgeMap[name], true);
DynamicAnchors = handler.GetDynamicJudgeAnchorPair(name);
}
public void MarkJudged(float abs, float rel, int result) {
Judged = true;
AbsoluteTime = abs;
RelativeTime = rel;
_result = result;
_resultPropSrc.Invalidate();
}
public void InitPropSrcs() {
StaticAnchor.PropSrcs.Add(_var_judge_result, _resultPropSrc = new PropSrc.Identifier(() => _result));
}
}
class DynamicJudgeAnchorPair {
public Anchor Absolute { get; private set; }
public Anchor Relative { get; private set; }
public DynamicJudgeAnchorPair(Anchor absolute, Anchor relative) {
Absolute = absolute;
Relative = relative;
}
}
DynamicJudgeAnchorPair GetDynamicJudgeAnchorPair(int name) {
DynamicJudgeAnchorPair result;
if (!dynJudgeAnchors.TryGetValue(name, out result)) {
dynJudgeAnchors.Add(name, result = new DynamicJudgeAnchorPair(
RegisterAnchor(judge.jtabsMap[name]),
RegisterAnchor(judge.jtrelMap[name])
));
}
return result;
}
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() { public override void Init() {
base.Init(); base.Init();
sgos = gogroup.GetComponentsInChildren<SectionalGameObject>(); sgos = gogroup.GetComponentsInChildren<SectionalGameObject>();
foreach (var judge in judges.Values) judge.InitPropSrcs();
} }
protected override void PreAwake(ContainerState s) { protected override void PreAwake(ContainerState s) {
base.PreAwake(s); base.PreAwake(s);
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
a_head.SetPositionAndRotation(Position = GetFramePoint(s.Parent, s.Track), Rotation = GetFrameRotation(s.Parent, s.Track)); a_head.Transform.SetPositionAndRotation(Position = GetFramePoint(s.Parent, s.Track), Rotation = GetFrameRotation(s.Parent, s.Track));
#else #else
a_head.position = Position = GetFramePoint(s.Parent, s.Track); a_head.Transform.position = Position = GetFramePoint(s.Parent, s.Track);
a_head.rotation = Rotation = GetFrameRotation(s.Parent, s.Track); a_head.Transform.rotation = Rotation = GetFrameRotation(s.Parent, s.Track);
#endif #endif
} }
protected override void Awake(ContainerState s) { protected override void Awake(ContainerState s) {
base.Awake(s); base.Awake(s);
if (s.CloneType == 2) { if (s.CloneType == 2) {
if (!gogroup) return; if (!gogroup) return;
Chart.Note tev = Event; if (Event.IsLong) {
if (tev.IsLong) {
foreach (var i in sgos) { foreach (var i in sgos) {
i.Reset(); i.Reset();
i.AppendPoint(Position, Rotation); i.AppendPoint(Position, Rotation);
@@ -54,8 +101,8 @@ namespace Cryville.Crtr {
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
gogroup.SetPositionAndRotation(Position, Rotation); gogroup.SetPositionAndRotation(Position, Rotation);
#else #else
gogroup.position = Position; gogroup.position = Position;
gogroup.rotation = Rotation; gogroup.rotation = Rotation;
#endif #endif
} }
} }
@@ -63,13 +110,11 @@ namespace Cryville.Crtr {
public override void Update(ContainerState s, StampedEvent ev) { public override void Update(ContainerState s, StampedEvent ev) {
base.Update(s, ev); base.Update(s, ev);
if (s.CloneType == 1) { if (s.CloneType <= 2) {
Position = GetFramePoint(bs.Parent, bs.Track); Position = GetFramePoint(s.Parent, s.Track);
Rotation = GetFrameRotation(bs.Parent, bs.Track); Rotation = GetFrameRotation(s.Parent, s.Track);
} }
else if (s.CloneType == 2) { if (s.CloneType == 2) {
Position = GetFramePoint(ts.Parent, ts.Track);
Rotation = GetFrameRotation(ts.Parent, ts.Track);
if (!gogroup) return; if (!gogroup) return;
Chart.Note tev = Event; Chart.Note tev = Event;
if (tev.IsLong) { if (tev.IsLong) {
@@ -81,31 +126,35 @@ namespace Cryville.Crtr {
if (ev == null) { } if (ev == null) { }
else if (ev.Unstamped == null) { } else if (ev.Unstamped == null) { }
else if (ev.Unstamped is Chart.Judge) { else if (ev.Unstamped is Chart.Judge) {
var tev = (Chart.Judge)ev.Unstamped; ChartPlayer.etor.ContextEvent = ev.Unstamped;
Identifier name = default(Identifier);
ChartPlayer.etor.ContextEvent = tev;
ChartPlayer.etor.ContextState = s; ChartPlayer.etor.ContextState = s;
ChartPlayer.etor.Evaluate(new PropOp.Identifier(v => name = new Identifier(v)), ruleset.judges[tev.Id].input); judge.Prepare(ev, this);
judge.Prepare(ev.Time, ev.Time + ev.Duration, name, ruleset.judges[tev.Id], cs);
ChartPlayer.etor.ContextState = null; ChartPlayer.etor.ContextState = null;
ChartPlayer.etor.ContextEvent = null; ChartPlayer.etor.ContextEvent = null;
} }
} }
} }
public override void Anchor() {
base.Anchor();
foreach (var j in judges.Values) {
if (!j.Judged) continue;
PushAnchorEvent(j.AbsoluteTime, j.DynamicAnchors.Absolute);
PushAnchorEvent(j.RelativeTime + cs.Time, j.DynamicAnchors.Relative);
}
}
public override void EndUpdate(ContainerState s) { public override void EndUpdate(ContainerState s) {
if (s.CloneType == 2 && gogroup) { if (s.CloneType == 2 && gogroup) {
foreach (var i in sgos) i.Seal(); foreach (var i in sgos) i.Seal();
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
a_tail.SetPositionAndRotation(GetFramePoint(ts.Parent, ts.Track), Quaternion.Euler(ts.Direction)); a_tail.Transform.SetPositionAndRotation(GetFramePoint(ts.Parent, ts.Track), Quaternion.Euler(ts.Direction));
#else #else
a_tail.position = GetFramePoint(ts.Parent, ts.Track); a_tail.Transform.position = GetFramePoint(ts.Parent, ts.Track);
a_tail.rotation = Quaternion.Euler(ts.Direction); a_tail.Transform.rotation = Quaternion.Euler(ts.Direction);
#endif #endif
} }
OpenAnchor("tail");
base.EndUpdate(s); base.EndUpdate(s);
CloseAnchor("tail");
} }
Vector3 GetFramePoint(ContainerState state, float track) { Vector3 GetFramePoint(ContainerState state, float track) {
@@ -117,6 +166,7 @@ namespace Cryville.Crtr {
return Quaternion.LookRotation(r, state.Normal); return Quaternion.LookRotation(r, state.Normal);
} }
readonly List<Vector3> ctrl = new List<Vector3>(2);
Vector3 GetFrame(ContainerState state, float track, Func<ContainerState, Vector3> func) { Vector3 GetFrame(ContainerState state, float track, Func<ContainerState, Vector3> func) {
// TODO // TODO
int id = Mathf.FloorToInt(track); int id = Mathf.FloorToInt(track);
@@ -134,7 +184,7 @@ namespace Cryville.Crtr {
if (c0 && c1) if (c0 && c1)
return (1 - t) * p1 + t * p2; return (1 - t) * p1 + t * p2;
else { else {
var ctrl = new List<Vector3>(2); ctrl.Clear();
if (!c0) { if (!c0) {
var tp = ts0.GetControlPoint(true, deltaz); var tp = ts0.GetControlPoint(true, deltaz);
if (tp != Vector3.zero) ctrl.Add(tp); if (tp != Vector3.zero) ctrl.Add(tp);
@@ -149,7 +199,7 @@ namespace Cryville.Crtr {
ColumnVector<float>.WithPolynomialCoefficients( ColumnVector<float>.WithPolynomialCoefficients(
frame.Size, track frame.Size, track
), ),
new Vector3Operator() Vector3Operator.Instance
); );
} }
else if (ctrl.Count == 1) { else if (ctrl.Count == 1) {
@@ -161,5 +211,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);
}
} }
} }

View File

@@ -3,6 +3,7 @@ using Cryville.Common.Pdt;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using UnityEngine; using UnityEngine;
namespace Cryville.Crtr { namespace Cryville.Crtr {
@@ -10,16 +11,19 @@ namespace Cryville.Crtr {
static readonly Dictionary<PdtOperatorSignature, PdtOperator> _shortops = new Dictionary<PdtOperatorSignature, PdtOperator>(); static readonly Dictionary<PdtOperatorSignature, PdtOperator> _shortops = new Dictionary<PdtOperatorSignature, PdtOperator>();
readonly Dictionary<int, PdtOperator> _ctxops = new Dictionary<int, PdtOperator>(); readonly Dictionary<int, PdtOperator> _ctxops = new Dictionary<int, PdtOperator>();
static readonly byte[] _nullbuf = new byte[0];
readonly byte[] _numbuf = new byte[4]; readonly byte[] _numbuf = new byte[4];
static readonly int _var_w = IdentifierManager.SharedInstance.Request("w"); static readonly int _var_w = IdentifierManager.SharedInstance.Request("w");
static readonly int _var_h = IdentifierManager.SharedInstance.Request("h"); static readonly int _var_h = IdentifierManager.SharedInstance.Request("h");
static readonly int _var_true = IdentifierManager.SharedInstance.Request("true"); static readonly int _var_true = IdentifierManager.SharedInstance.Request("true");
static readonly int _var_false = IdentifierManager.SharedInstance.Request("false"); static readonly int _var_false = IdentifierManager.SharedInstance.Request("false");
protected override void GetVariable(int name, out int type, out byte[] value) { static readonly int _var_null = IdentifierManager.SharedInstance.Request("null");
protected override void GetVariable(int name, bool forced, out int type, out byte[] value) {
if (name == _var_w) { LoadNum(ChartPlayer.hitRect.width); type = PdtInternalType.Number; value = _numbuf; } if (name == _var_w) { LoadNum(ChartPlayer.hitRect.width); type = PdtInternalType.Number; value = _numbuf; }
else if (name == _var_h) { LoadNum(ChartPlayer.hitRect.height); type = PdtInternalType.Number; value = _numbuf; } else if (name == _var_h) { LoadNum(ChartPlayer.hitRect.height); type = PdtInternalType.Number; value = _numbuf; }
else if (name == _var_true) { LoadNum(1); type = PdtInternalType.Number; value = _numbuf; } else if (name == _var_true) { LoadNum(1); type = PdtInternalType.Number; value = _numbuf; }
else if (name == _var_false) { LoadNum(0); type = PdtInternalType.Number; value = _numbuf; } else if (name == _var_false) { LoadNum(0); type = PdtInternalType.Number; value = _numbuf; }
else if (name == _var_null) { LoadIdent(0); type = PdtInternalType.Undefined; value = _numbuf; }
else { else {
var id = new Identifier(name); var id = new Identifier(name);
PropSrc prop; PropSrc prop;
@@ -28,7 +32,7 @@ namespace Cryville.Crtr {
} }
else if (ContextState != null && ChartPlayer.motionRegistry.ContainsKey(id)) { else if (ContextState != null && ChartPlayer.motionRegistry.ContainsKey(id)) {
var vec = ContextState.GetRawValue(id); var vec = ContextState.GetRawValue(id);
new VectorSrc(() => vec).Get(out type, out value); VectorSrc.Construct(() => vec).Get(out type, out value);
} }
else if (ContextJudge != null && ContextJudge.TryGetScoreSrc(name, out prop)) { else if (ContextJudge != null && ContextJudge.TryGetScoreSrc(name, out prop)) {
prop.Get(out type, out value); prop.Get(out type, out value);
@@ -39,35 +43,28 @@ namespace Cryville.Crtr {
RevokePotentialConstant(); RevokePotentialConstant();
} }
else { else {
PropSrc.Arbitrary result = ContextCascadeLookup(name); PropSrc result = ContextCascadeLookup(name);
if (result != null) { if (result != null) {
result.Get(out type, out value); result.Get(out type, out value);
} }
else if (forced) {
type = PdtInternalType.Error;
value = _nullbuf;
}
else { else {
type = PdtInternalType.Undefined; type = PdtInternalType.Undefined;
LoadNum(name); LoadIdent(name);
value = _numbuf; value = _numbuf;
} }
} }
} }
} }
unsafe void LoadNum(int value) { unsafe void LoadIdent(int value) {
fixed (byte* ptr = _numbuf) *(int*)ptr = value; fixed (byte* ptr = _numbuf) *(int*)ptr = value;
} }
unsafe void LoadNum(float value) { unsafe void LoadNum(float value) {
fixed (byte* ptr = _numbuf) *(float*)ptr = value; fixed (byte* ptr = _numbuf) *(float*)ptr = value;
} }
unsafe byte[] GetBytes(string value) {
int strlen = value.Length;
byte[] result = new byte[strlen * sizeof(char) + sizeof(int)];
fixed (byte* _ptr = result) {
char* ptr = (char*)(_ptr + sizeof(int));
*(int*)_ptr = strlen;
int i = 0;
foreach (var c in value) ptr[i++] = c;
}
return result;
}
static readonly int _op_sep = IdentifierManager.SharedInstance.Request(","); static readonly int _op_sep = IdentifierManager.SharedInstance.Request(",");
static readonly int _func_int_map = IdentifierManager.SharedInstance.Request("int_map"); static readonly int _func_int_map = IdentifierManager.SharedInstance.Request("int_map");
protected override PdtOperator GetOperator(PdtOperatorSignature sig) { protected override PdtOperator GetOperator(PdtOperatorSignature sig) {
@@ -94,9 +91,10 @@ namespace Cryville.Crtr {
static readonly int _colop_and = IdentifierManager.SharedInstance.Request("&"); static readonly int _colop_and = IdentifierManager.SharedInstance.Request("&");
static readonly int _colop_or = IdentifierManager.SharedInstance.Request("|"); static readonly int _colop_or = IdentifierManager.SharedInstance.Request("|");
protected override bool Collapse(int name, PdtVariableMemory param) { protected override bool Collapse(int name, PdtVariableMemory param) {
if (param.Type == PdtInternalType.Error) throw new ArgumentException("Error");
if (name == _colop_and) return param.Type == PdtInternalType.Number && param.AsNumber() <= 0; if (name == _colop_and) return param.Type == PdtInternalType.Number && param.AsNumber() <= 0;
else if (name == _colop_or) return param.Type != PdtInternalType.Number || param.AsNumber() > 0; else if (name == _colop_or) return param.Type != PdtInternalType.Number || param.AsNumber() > 0;
else throw new KeyNotFoundException(string.Format("Undefined collapse operator {0}", name)); else throw new KeyNotFoundException(string.Format("Undefined collapse operator {0}", IdentifierManager.SharedInstance.Retrieve(name)));
} }
public ChartEvent ContextEvent { private get; set; } public ChartEvent ContextEvent { private get; set; }
@@ -105,18 +103,22 @@ namespace Cryville.Crtr {
public Judge ContextJudge { private get; set; } public Judge ContextJudge { private get; set; }
public PropSrc ContextSelfValue { private get; set; } public PropSrc ContextSelfValue { private get; set; }
readonly Dictionary<int, PropSrc.Arbitrary>[] ContextCascade = new Dictionary<int, PropSrc.Arbitrary>[256]; readonly Dictionary<int, PropSrc>[] ContextCascade = new Dictionary<int, PropSrc>[256];
int _cascadeHeight; int _cascadeHeight;
public void ContextCascadeInsert() { public void ContextCascadeInsert() {
ContextCascade[_cascadeHeight++].Clear(); ContextCascade[_cascadeHeight++].Clear();
} }
public void ContextCascadeUpdate(int key, PropSrc.Arbitrary value) { public void ContextCascadeInsert(Dictionary<int, PropSrc> srcs) {
ContextCascadeInsert();
foreach (var src in srcs) ContextCascadeUpdate(src.Key, src.Value);
}
public void ContextCascadeUpdate(int key, PropSrc value) {
ContextCascade[_cascadeHeight - 1][key] = value; ContextCascade[_cascadeHeight - 1][key] = value;
} }
public PropSrc.Arbitrary ContextCascadeLookup(int name) { public PropSrc ContextCascadeLookup(int name) {
PropSrc.Arbitrary result; PropSrc result;
for (int i = _cascadeHeight - 1; i >= 0; i--) { for (int i = _cascadeHeight - 1; i >= 0; i--) {
Dictionary<int, PropSrc.Arbitrary> cas = ContextCascade[i]; Dictionary<int, PropSrc> cas = ContextCascade[i];
if (cas.TryGetValue(name, out result)) { if (cas.TryGetValue(name, out result)) {
return result; return result;
} }
@@ -128,7 +130,7 @@ namespace Cryville.Crtr {
} }
public PdtEvaluator() { public PdtEvaluator() {
for (int i = 0; i < ContextCascade.Length; i++) ContextCascade[i] = new Dictionary<int, PropSrc.Arbitrary>(); for (int i = 0; i < ContextCascade.Length; i++) ContextCascade[i] = new Dictionary<int, PropSrc>();
_ctxops.Add(IdentifierManager.SharedInstance.Request("screen_edge"), new func_screen_edge(() => ContextTransform)); _ctxops.Add(IdentifierManager.SharedInstance.Request("screen_edge"), new func_screen_edge(() => ContextTransform));
_ctxops.Add(IdentifierManager.SharedInstance.Request("int"), new func_int(() => ContextSelfValue)); _ctxops.Add(IdentifierManager.SharedInstance.Request("int"), new func_int(() => ContextSelfValue));
@@ -164,6 +166,7 @@ namespace Cryville.Crtr {
_shortops.Add(new PdtOperatorSignature("frame_seq", 3), new func_frame_seq()); _shortops.Add(new PdtOperatorSignature("frame_seq", 3), new func_frame_seq());
_shortops.Add(new PdtOperatorSignature("in_area", 1), new func_in_area()); _shortops.Add(new PdtOperatorSignature("in_area", 1), new func_in_area());
_shortops.Add(new PdtOperatorSignature("is", 2), new func_is());
} }
#region Operators #region Operators
#pragma warning disable IDE1006 #pragma warning disable IDE1006
@@ -261,7 +264,7 @@ namespace Cryville.Crtr {
if (blit) GetReturnFrame(PdtInternalType.Array, len + 2 * sizeof(int)).SetArraySuffix(type, LoadedOperandCount); if (blit) GetReturnFrame(PdtInternalType.Array, len + 2 * sizeof(int)).SetArraySuffix(type, LoadedOperandCount);
else GetReturnFrame(PdtInternalType.Vector, len + sizeof(int)).SetArraySuffix(type); else GetReturnFrame(PdtInternalType.Vector, len + sizeof(int)).SetArraySuffix(type);
} }
bool IsBlittable(int type) { static bool IsBlittable(int type) {
return type == PdtInternalType.Number; return type == PdtInternalType.Number;
} }
} }
@@ -309,7 +312,7 @@ namespace Cryville.Crtr {
ret.SetArraySuffix(PdtInternalType.String, fc); ret.SetArraySuffix(PdtInternalType.String, fc);
int o = 0; int o = 0;
for (int i = f; i <= t; i++) { for (int i = f; i <= t; i++) {
var s = pf + i.ToString(); var s = pf + i.ToString(CultureInfo.InvariantCulture);
ret.SetString(s, o); ret.SetString(s, o);
o += sizeof(int) + s.Length * sizeof(char); o += sizeof(int) + s.Length * sizeof(char);
} }
@@ -346,6 +349,17 @@ namespace Cryville.Crtr {
hit.CopyTo(ret); hit.CopyTo(ret);
} }
} }
class func_is : PdtOperator {
public func_is() : base(2) { }
protected override unsafe void Execute() {
var op0 = GetOperand(0);
if (op0.Type == PdtInternalType.Error) throw new ArgumentException("Error");
var op1 = GetOperand(1);
if (op1.Type == PdtInternalType.Error) throw new ArgumentException("Error");
var ret = GetReturnFrame(PdtInternalType.Number, sizeof(float));
ret.SetNumber(op0.Equals(op1) ? 1 : 0);
}
}
#endregion #endregion
#region Contextual Functions #region Contextual Functions
class func_screen_edge : PdtOperator { class func_screen_edge : PdtOperator {

View File

@@ -4,6 +4,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using RBeatTime = Cryville.Crtr.BeatTime; using RBeatTime = Cryville.Crtr.BeatTime;
using RTargetString = Cryville.Common.Buffers.TargetString;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public abstract class PropOp : PdtOperator { public abstract class PropOp : PdtOperator {
@@ -45,6 +46,22 @@ namespace Cryville.Crtr {
_cb(GetOperand(0).AsString()); _cb(GetOperand(0).AsString());
} }
} }
public class TargetString : PropOp {
readonly Func<RTargetString> _cb;
public TargetString(Func<RTargetString> cb) { _cb = cb; }
protected override unsafe void Execute() {
var target = _cb();
var op = GetOperand(0);
if (op.Type != PdtInternalType.String) throw new ArgumentException("Not a string");
var ptr = (byte*)op.TrustedAsOfLength(op.Length);
var len = *(int*)ptr;
target.Length = len;
var cptr = (char*)(ptr + sizeof(int));
for (int i = 0; i < len; i++)
target[i] = cptr[i];
target.Validate();
}
}
public class Identifier : PropOp { public class Identifier : PropOp {
readonly Action<int> _cb; readonly Action<int> _cb;
public Identifier(Action<int> cb) { _cb = cb; } public Identifier(Action<int> cb) { _cb = cb; }
@@ -55,19 +72,21 @@ namespace Cryville.Crtr {
public class Enum<T> : PropOp { public class Enum<T> : PropOp {
readonly static Dictionary<int, int> _cache = new Dictionary<int, int>(); readonly static Dictionary<int, int> _cache = new Dictionary<int, int>();
readonly Action<T> _cb; readonly Action<T> _cb;
public Enum(Action<T> cb) { readonly Func<int, T> _caster;
public Enum(Action<T> cb, Func<int, T> caster) {
if (!typeof(T).IsEnum) if (!typeof(T).IsEnum)
throw new ArgumentException("Type is not enum"); throw new ArgumentException("Type is not enum");
var names = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static); var names = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static);
for (int i = 0; i < names.Length; i++) for (int i = 0; i < names.Length; i++)
_cache[IdentifierManager.SharedInstance.Request(names[i].Name)] = Convert.ToInt32(names[i].GetValue(null)); _cache[IdentifierManager.SharedInstance.Request(names[i].Name)] = Convert.ToInt32(names[i].GetValue(null));
_cb = cb; _cb = cb;
_caster = caster;
} }
protected override void Execute() { protected override void Execute() {
int result = 0; int result = 0;
for (int i = 0; i < LoadedOperandCount; i++) for (int i = 0; i < LoadedOperandCount; i++)
result |= _cache[GetOperand(0).AsIdentifier()]; result |= _cache[GetOperand(0).AsIdentifier()];
_cb((T)(object)result); _cb(_caster(result));
} }
} }
public class BeatTime : PropOp { public class BeatTime : PropOp {

View File

@@ -4,52 +4,60 @@ using RBeatTime = Cryville.Crtr.BeatTime;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public abstract class PropSrc { public abstract class PropSrc {
int _type; public int Type { get; private set; }
byte[] _buf = null; public PropSrc(int type) {
public virtual void Invalidate() { _buf = null; } Type = type;
public void Get(out int type, out byte[] value) {
if (_buf == null) InternalGet(out _type, out _buf);
type = _type;
value = _buf;
} }
protected abstract void InternalGet(out int type, out byte[] value); protected byte[] buf = null;
protected virtual bool Invalidated { get { return buf == null; } }
public virtual void Invalidate() { buf = null; }
public void Get(out int type, out byte[] value) {
if (Invalidated) InternalGet();
type = Type;
value = buf;
}
protected abstract void InternalGet();
public class Arbitrary : PropSrc { public class Arbitrary : PropSrc {
public int Type { get; private set; }
readonly byte[] _value; readonly byte[] _value;
public Arbitrary(int type, byte[] value) { public Arbitrary(int type, byte[] value) : base(type) {
Type = type;
_value = value; _value = value;
} }
protected override void InternalGet(out int type, out byte[] value) { protected override void InternalGet() {
type = Type; buf = _value;
value = _value;
} }
} }
public class Boolean : PropSrc { public class Boolean : PropSrc {
readonly Func<bool> _cb; readonly Func<bool> _cb;
public Boolean(Func<bool> cb) { _cb = cb; } bool m_invalidated = true;
protected override void InternalGet(out int type, out byte[] value) { protected override bool Invalidated { get { return m_invalidated; } }
type = PdtInternalType.Number; public override void Invalidate() { m_invalidated = true; }
value = new byte[] { _cb() ? (byte)1 : (byte)0, 0, 0, 0 }; public Boolean(Func<bool> cb) : base(PdtInternalType.Number) { _cb = cb; buf = new byte[4]; }
protected override void InternalGet() {
m_invalidated = false;
buf[0] = _cb() ? (byte)1 : (byte)0;
} }
} }
public class Float : PropSrc { public class Float : PropSrc {
readonly Func<float> _cb; readonly Func<float> _cb;
public Float(Func<float> cb) { _cb = cb; } bool m_invalidated = true;
protected override void InternalGet(out int type, out byte[] value) { protected override bool Invalidated { get { return m_invalidated; } }
type = PdtInternalType.Number; public override void Invalidate() { m_invalidated = true; }
value = BitConverter.GetBytes(_cb()); public Float(Func<float> cb) : base(PdtInternalType.Number) { _cb = cb; buf = new byte[4]; }
protected override unsafe void InternalGet() {
m_invalidated = false;
fixed (byte* _ptr = buf) {
*(float*)_ptr = _cb();
}
} }
} }
public class String : PropSrc { public class String : PropSrc {
readonly Func<string> _cb; readonly Func<string> _cb;
public String(Func<string> cb) { _cb = cb; } public String(Func<string> cb) : base(PdtInternalType.String) { _cb = cb; }
protected override unsafe void InternalGet(out int type, out byte[] value) { protected override unsafe void InternalGet() {
type = PdtInternalType.String;
var v = _cb(); var v = _cb();
int strlen = v.Length; int strlen = v.Length;
value = new byte[strlen * sizeof(char) + sizeof(int)]; buf = new byte[strlen * sizeof(char) + sizeof(int)];
fixed (byte* _ptr = value) { fixed (byte* _ptr = buf) {
char* ptr = (char*)(_ptr + sizeof(int)); char* ptr = (char*)(_ptr + sizeof(int));
*(int*)_ptr = strlen; *(int*)_ptr = strlen;
int i = 0; int i = 0;
@@ -59,20 +67,18 @@ namespace Cryville.Crtr {
} }
public class Identifier : PropSrc { public class Identifier : PropSrc {
readonly Func<int> _cb; readonly Func<int> _cb;
public Identifier(Func<int> cb) { _cb = cb; } public Identifier(Func<int> cb) : base(PdtInternalType.Undefined) { _cb = cb; }
protected override void InternalGet(out int type, out byte[] value) { protected override void InternalGet() {
type = PdtInternalType.Undefined; buf = BitConverter.GetBytes(_cb());
value = BitConverter.GetBytes(_cb());
} }
} }
public class BeatTime : PropSrc { public class BeatTime : PropSrc {
readonly Func<RBeatTime> _cb; readonly Func<RBeatTime> _cb;
public BeatTime(Func<RBeatTime> cb) { _cb = cb; } public BeatTime(Func<RBeatTime> cb) : base(PdtInternalType.Vector) { _cb = cb; }
protected override unsafe void InternalGet(out int type, out byte[] value) { protected override unsafe void InternalGet() {
var bt = _cb(); var bt = _cb();
type = PdtInternalType.Vector; buf = new byte[4 * sizeof(int)];
value = new byte[4 * sizeof(int)]; fixed (byte* _ptr = buf) {
fixed (byte* _ptr = value) {
int* ptr = (int*)_ptr; int* ptr = (int*)_ptr;
*ptr++ = bt.b; *ptr++ = bt.b;
*ptr++ = bt.n; *ptr++ = bt.n;

View File

@@ -34,6 +34,17 @@ namespace Cryville.Crtr {
} }
} }
[Category("gameplay")]
[Range(-1, 5)]
public int ForceSyncFrames {
get {
return PlayerPrefs.GetInt("ForceSyncFrames", 5);
}
set {
PlayerPrefs.SetInt("ForceSyncFrames", value);
}
}
[Browsable(false)] [Browsable(false)]
[Category("data")] [Category("data")]
[Description("The directory where the game files are stored.")] [Description("The directory where the game files are stored.")]
@@ -175,6 +186,26 @@ namespace Cryville.Crtr {
} }
} }
[Category("debug")]
public bool ClearLogOnPlay {
get {
return PlayerPrefs.GetInt("ClearLogOnPlay", 1) == 1;
}
set {
PlayerPrefs.SetInt("ClearLogOnPlay", value ? 1 : 0);
}
}
[Category("debug")]
public bool HideLogOnPlay {
get {
return PlayerPrefs.GetInt("HideLogOnPlay", 1) == 1;
}
set {
PlayerPrefs.SetInt("HideLogOnPlay", value ? 1 : 0);
}
}
public void Save() { PlayerPrefs.Save(); } public void Save() { PlayerPrefs.Save(); }
public void Reset() { PlayerPrefs.DeleteAll(); } public void Reset() { PlayerPrefs.DeleteAll(); }
} }

View File

@@ -36,7 +36,7 @@ namespace Cryville.Crtr {
} }
} }
Dictionary<string, List<PropertyInfo>> _categories = new Dictionary<string, List<PropertyInfo>>(); readonly Dictionary<string, List<PropertyInfo>> _categories = new Dictionary<string, List<PropertyInfo>>();
public void LoadProperties() { public void LoadProperties() {
_categories.Clear(); _categories.Clear();
_invalidated = false; _invalidated = false;

View File

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

View File

@@ -1,4 +1,5 @@
using Cryville.Common.Pdt; using Cryville.Common;
using Cryville.Common.Pdt;
using Cryville.Crtr.Components; using Cryville.Crtr.Components;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using System; using System;
@@ -9,88 +10,159 @@ using UnityEngine.Profiling;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class SkinContainer { public class SkinContainer {
readonly PdtSkin skin; readonly PdtSkin skin;
readonly Dictionary<SkinElement, Transform> matchedStatic readonly List<DynamicProperty> dynprops = new List<DynamicProperty>();
= new Dictionary<SkinElement, Transform>(); struct DynamicProperty {
readonly Dictionary<SkinElement, Transform> matchedDynamic public RuntimeSkinContext Context { get; set; }
= new Dictionary<SkinElement, Transform>(); public SkinPropertyKey Key { get; set; }
public PdtExpression Value { get; set; }
}
readonly List<DynamicElement> dynelems = new List<DynamicElement>();
struct DynamicElement {
public RuntimeSkinContext Context { get; set; }
public SkinSelectors Selectors { get; set; }
public SkinElement Element { get; set; }
}
public SkinContainer(PdtSkin _skin) { public SkinContainer(PdtSkin _skin) {
skin = _skin; skin = _skin;
} }
public void MatchStatic(ContainerState context) { public void MatchStatic(ContainerState state) {
ChartPlayer.etor.ContextState = context; dynprops.Clear(); dynelems.Clear();
ChartPlayer.etor.ContextEvent = context.Container; ChartPlayer.etor.ContextState = state;
matchedStatic.Clear(); ChartPlayer.etor.ContextEvent = state.Container;
MatchStatic(skin, context, context.Handler.gogroup); MatchStatic(skin, state, new RuntimeSkinContext(state.Handler.SkinContext));
foreach (var m in matchedStatic) {
var el = m.Key;
var obj = m.Value;
ChartPlayer.etor.ContextTransform = obj;
foreach (var p in el.properties) {
if (p.Key.Name == null)
obj.gameObject.AddComponent(p.Key.Component);
else {
ChartPlayer.etor.Evaluate(GetPropOp(obj, p.Key), p.Value);
}
}
ChartPlayer.etor.ContextTransform = null;
}
ChartPlayer.etor.ContextEvent = null; ChartPlayer.etor.ContextEvent = null;
ChartPlayer.etor.ContextState = null; ChartPlayer.etor.ContextState = null;
} }
void MatchStatic(SkinElement rel, ContainerState context, Transform anchor = null) { void MatchStatic(SkinElement rel, ContainerState state, RuntimeSkinContext ctx) {
matchedStatic.Add(rel, anchor); var rc = ctx.ReadContext;
foreach (var r in rel.elements) { ChartPlayer.etor.ContextTransform = rc.Transform;
var new_anchor = r.Key.MatchStatic(context, anchor); if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeInsert(rc.PropSrcs);
if (new_anchor != null) { foreach (var p in rel.properties) {
MatchStatic(r.Value, context, new_anchor); if (p.Key.Name == 0)
rc.Transform.gameObject.AddComponent(p.Key.Component);
else {
ChartPlayer.etor.Evaluate(GetPropOp(ctx.WriteTransform, p.Key).Operator, p.Value);
if (!p.Value.IsConstant) dynprops.Add(
new DynamicProperty { Context = ctx, Key = p.Key, Value = p.Value }
);
} }
} }
} ChartPlayer.etor.ContextTransform = null;
public void MatchDynamic(ContainerState context) { foreach (var r in rel.elements) {
Profiler.BeginSample("SkinContainer.MatchDynamic"); try {
ChartPlayer.etor.ContextState = context; var nctxs = r.Key.MatchStatic(state, rc);
ChartPlayer.etor.ContextEvent = context.Container; var roflag = r.Key.annotations.Contains("if");
matchedDynamic.Clear(); var woflag = r.Key.annotations.Contains("then");
MatchDynamic(skin, context, context.Handler.gogroup); foreach (var nctx in nctxs) {
var nrctx = new RuntimeSkinContext(nctx, ctx, roflag, woflag);
foreach (var m in matchedDynamic) { MatchStatic(r.Value, state, nrctx);
var el = m.Key; }
var obj = m.Value;
ChartPlayer.etor.ContextTransform = obj;
foreach (var p in el.properties) {
if (p.Key.Name == null) continue;
if (p.Value.IsConstant) continue;
ChartPlayer.etor.Evaluate(GetPropOp(obj, p.Key), p.Value);
} }
ChartPlayer.etor.ContextTransform = null; catch (SelectorNotAvailableException) {
dynelems.Add(
new DynamicElement { Context = ctx, Selectors = r.Key, Element = r.Value }
);
}
}
if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
}
public void MatchDynamic(ContainerState state) {
if (dynprops.Count == 0 && dynelems.Count == 0) return;
Profiler.BeginSample("SkinContainer.MatchDynamic");
ChartPlayer.etor.ContextState = state;
ChartPlayer.etor.ContextEvent = state.Container;
for (int i = 0; i < dynprops.Count; i++) {
DynamicProperty p = dynprops[i];
var psrcs = p.Context.ReadContext.PropSrcs;
if (psrcs != null) ChartPlayer.etor.ContextCascadeInsert(psrcs);
var prop = GetPropOp(p.Context.WriteTransform, p.Key);
if (state.CloneType > prop.UpdateCloneType) continue;
ChartPlayer.etor.Evaluate(prop.Operator, p.Value);
if (psrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
}
for (int i = 0; i < dynelems.Count; i++) {
DynamicElement e = dynelems[i];
var psrcs = e.Context.ReadContext.PropSrcs;
if (psrcs != null) ChartPlayer.etor.ContextCascadeInsert(psrcs);
var nctx = e.Selectors.MatchDynamic(state, e.Context.ReadContext);
if (nctx != null) MatchDynamic(e.Element, state, new RuntimeSkinContext(
nctx, e.Context, e.Selectors.annotations.Contains("if"), e.Selectors.annotations.Contains("then")
));
if (psrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
} }
ChartPlayer.etor.ContextEvent = null; ChartPlayer.etor.ContextEvent = null;
ChartPlayer.etor.ContextState = null; ChartPlayer.etor.ContextState = null;
Profiler.EndSample(); Profiler.EndSample();
} }
void MatchDynamic(SkinElement rel, ContainerState context, Transform anchor = null) { void MatchDynamic(SkinElement rel, ContainerState state, RuntimeSkinContext ctx) {
matchedDynamic.Add(rel, anchor); var rc = ctx.ReadContext;
foreach (var r in rel.elements) { ChartPlayer.etor.ContextTransform = rc.Transform;
Transform new_anchor; if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeInsert(rc.PropSrcs);
if (!matchedStatic.ContainsKey(r.Value)) continue; foreach (var p in rel.properties) {
if (!r.Key.IsUpdatable(context)) continue; if (p.Key.Name == 0)
new_anchor = r.Key.MatchDynamic( throw new InvalidOperationException("Component creation in dynamic context is not allowed");
context, r.Value, matchedStatic[r.Value], anchor var prop = GetPropOp(ctx.WriteTransform, p.Key);
); if (state.CloneType > prop.UpdateCloneType) continue;
if (new_anchor != null) { ChartPlayer.etor.Evaluate(prop.Operator, p.Value);
MatchDynamic(r.Value, context, new_anchor);
}
} }
ChartPlayer.etor.ContextTransform = null;
foreach (var r in rel.elements) {
if (!r.Key.IsUpdatable(state)) continue;
var nctx = r.Key.MatchDynamic(state, rc);
if (nctx != null) MatchDynamic(r.Value, state, new RuntimeSkinContext(
nctx, ctx, r.Key.annotations.Contains("if"), r.Key.annotations.Contains("then")
));
}
if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
} }
PdtOperator GetPropOp(Transform obj, SkinPropertyKey key) { SkinProperty GetPropOp(Transform obj, SkinPropertyKey key) {
var ctype = key.Component; var ctype = key.Component;
var comp = (SkinComponent)obj.GetComponent(ctype); var comp = (SkinComponent)obj.GetComponent(ctype);
if (comp == null) throw new InvalidOperationException("Component instance not found"); if (comp == null) throw new InvalidOperationException(string.Format(
PdtOperator result; "Trying to set property {0} but the component is not found",
if (!comp.PropOps.TryGetValue(key.Name, out result)) IdentifierManager.SharedInstance.Retrieve(key.Name)
throw new ArgumentException(string.Format("Property {0} not found on component", key.Name)); ));
SkinProperty result;
if (!comp.Properties.TryGetValue(key.Name, out result))
throw new ArgumentException(string.Format(
"Property {0} not found on component",
IdentifierManager.SharedInstance.Retrieve(key.Name)
));
return result; return result;
} }
} }
public class SkinContext {
public Transform Transform { get; private set; }
public Dictionary<int, PropSrc> PropSrcs { get; private set; }
public SkinContext(Transform transform, Dictionary<int, PropSrc> propSrcs = null) {
Transform = transform;
PropSrcs = propSrcs;
}
}
public struct RuntimeSkinContext {
public SkinContext ReadContext { get; private set; }
public Transform WriteTransform { get; private set; }
public RuntimeSkinContext(SkinContext rw) {
ReadContext = rw;
WriteTransform = rw.Transform;
}
public RuntimeSkinContext(SkinContext r, Transform w) {
ReadContext = r;
WriteTransform = w;
}
public RuntimeSkinContext(SkinContext newctx, RuntimeSkinContext oldctx, bool roflag, bool woflag) {
if (roflag) {
ReadContext = newctx;
WriteTransform = oldctx.WriteTransform;
}
else if (woflag) {
ReadContext = oldctx.ReadContext;
WriteTransform = newctx.Transform;
}
else {
ReadContext = newctx;
WriteTransform = newctx.Transform;
}
}
}
} }

View File

@@ -28,7 +28,7 @@ namespace Cryville.Crtr {
GetChar(); GetChar();
if (cc == '.') { if (cc == '.') {
GetChar(); GetChar();
s.Add(new SkinSelector.State(GetIdentifier())); s.Add(new SkinSelector.AtAnchor(GetIdentifier()));
key = null; key = null;
} }
else { else {

View File

@@ -1,19 +1,22 @@
using Cryville.Common;
using Cryville.Common.Pdt; using Cryville.Common.Pdt;
using Cryville.Crtr.Components; using Cryville.Crtr.Components;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using UnityEngine; using UnityEngine;
using CAnchor = Cryville.Crtr.Anchor;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class SkinSelectors { public class SkinSelectors {
readonly SkinSelector[] selectors; readonly SkinSelector[] selectors;
readonly string[] annotations; public readonly HashSet<string> annotations;
public SkinSelectors(IEnumerable<SkinSelector> s, IEnumerable<string> a) { public SkinSelectors(IEnumerable<SkinSelector> s, IEnumerable<string> a) {
selectors = s.ToArray(); selectors = s.ToArray();
annotations = a.ToArray(); annotations = a.ToHashSet();
} }
public override string ToString() { public override string ToString() {
if (selectors.Length == 0) return ""; if (selectors.Length == 0) return "";
@@ -34,68 +37,71 @@ namespace Cryville.Crtr {
selectors[i].Optimize(etor); selectors[i].Optimize(etor);
} }
} }
public Transform MatchStatic(ContainerState h, Transform anchor = null) { public IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext ctx) {
IEnumerable<SkinContext> result = new SkinContext[] { ctx };
foreach (var s in selectors) { foreach (var s in selectors) {
anchor = s.Match(h, anchor); result = result.SelectMany(l => s.MatchStatic(h, l));
if (anchor == null) return null;
} }
return anchor; return result;
} }
public bool IsUpdatable(ContainerState h) { public bool IsUpdatable(ContainerState h) {
foreach (var s in selectors) foreach (var s in selectors)
if (!s.IsUpdatable(h)) return false; if (!s.IsUpdatable(h)) return false;
return true; return true;
} }
public Transform MatchDynamic(ContainerState h, SkinElement e, Transform old_target, Transform anchor = null) { public SkinContext MatchDynamic(ContainerState h, SkinContext ctx) {
if (!e.IsDynamic) return null;
foreach (var s in selectors) { foreach (var s in selectors) {
anchor = s.Match(h, anchor, old_target); ctx = s.MatchDynamic(h, ctx);
if (anchor == null) return null; if (ctx == null) return null;
} }
return anchor; return ctx;
} }
} }
public abstract class SkinSelector { public abstract class SkinSelector {
protected SkinSelector() { } protected SkinSelector() { }
public abstract bool IsStatic {
get;
}
public virtual void Optimize(PdtEvaluatorBase etor) { } public virtual void Optimize(PdtEvaluatorBase etor) { }
public abstract Transform Match(ContainerState h, Transform a, Transform ot = null); public virtual IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) { throw new SelectorNotAvailableException(); }
public virtual SkinContext MatchDynamic(ContainerState h, SkinContext c) { throw new SelectorNotAvailableException(); }
public virtual bool IsUpdatable(ContainerState h) { public virtual bool IsUpdatable(ContainerState h) {
return true; return true;
} }
public class CreateObject : SkinSelector { public class CreateObject : SkinSelector {
public CreateObject() { } public CreateObject() { }
public override bool IsStatic { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
get { return true; } var obj = new GameObject("__obj__");
} obj.transform.SetParent(c.Transform, false);
public override Transform Match(ContainerState h, Transform a, Transform ot = null) {
if (ot != null)
return ot;
var obj = new GameObject {
name = "__obj__"
};
obj.transform.SetParent(a, false);
obj.AddComponent<TransformInterface>(); obj.AddComponent<TransformInterface>();
return obj.transform; return new SkinContext[] { new SkinContext(obj.transform) };
} }
} }
public class Anchor : SkinSelector { public class Anchor : SkinSelector {
public string Name { get; private set; } public int Name { get; private set; }
public Anchor(string name) { public Anchor(string name) {
Name = name; Name = IdentifierManager.SharedInstance.Request(name);
}
public override bool IsStatic {
get { return true; }
} }
public override Transform Match(ContainerState h, Transform a, Transform ot = null) { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
return h.Handler.Anchors[Name].Transform; List<CAnchor> anchors;
if (h.Handler.Anchors.TryGetValue(Name, out anchors)) {
return anchors.Select(a => a.SkinContext);
}
else return Enumerable.Empty<SkinContext>();
} }
public override bool IsUpdatable(ContainerState h) { public override bool IsUpdatable(ContainerState h) {
return h.Handler.Anchors[Name].Opened; return h.Handler.OpenedAnchor != null && h.Handler.OpenedAnchor.Name == Name;
}
}
public class AtAnchor : SkinSelector {
public int Name { get; private set; }
public AtAnchor(string name) {
Name = IdentifierManager.SharedInstance.Request(name);
}
public override SkinContext MatchDynamic(ContainerState h, SkinContext c) {
return IsUpdatable(h) ? c : null;
}
public override bool IsUpdatable(ContainerState h) {
return h.Handler.OpenedAnchor != null && h.Handler.OpenedAnchor.Name == Name;
} }
} }
public class Property : SkinSelector { public class Property : SkinSelector {
@@ -109,34 +115,46 @@ namespace Cryville.Crtr {
public override void Optimize(PdtEvaluatorBase etor) { public override void Optimize(PdtEvaluatorBase etor) {
etor.Optimize(_exp); etor.Optimize(_exp);
} }
public override bool IsStatic { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
get { throw new NotImplementedException(); } var result = Match(c);
if (result != null) return new SkinContext[] { result };
else return Enumerable.Empty<SkinContext>();
} }
public override Transform Match(ContainerState h, Transform a, Transform ot = null) { public override SkinContext MatchDynamic(ContainerState h, SkinContext c) {
ChartPlayer.etor.ContextTransform = a; return Match(c);
ChartPlayer.etor.Evaluate(_op, _exp); }
ChartPlayer.etor.ContextTransform = null; public SkinContext Match(SkinContext a) {
return _flag ? a : null; ChartPlayer.etor.ContextTransform = a.Transform;
try {
ChartPlayer.etor.Evaluate(_op, _exp);
return _flag ? a : null;
}
catch (Exception ex) {
throw new SelectorNotAvailableException("The expression is not evaluatable under the current context", ex);
}
finally {
ChartPlayer.etor.ContextTransform = null;
}
} }
} }
public class State : SkinSelector { public class State : SkinSelector {
public State(string state) { } public State(string state) { }
public override bool IsStatic { public override SkinContext MatchDynamic(ContainerState h, SkinContext c) {
get { return false; } return null;
}
public override Transform Match(ContainerState h, Transform a, Transform ot = null) {
return null; // TODO
} }
} }
public class ElementType : SkinSelector { public class ElementType : SkinSelector {
readonly string _type; readonly string _type;
public ElementType(string type) { _type = type; } public ElementType(string type) { _type = type; }
public override bool IsStatic { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
get { return true; } return h.Handler.TypeName == _type ? new SkinContext[] { c } : Enumerable.Empty<SkinContext>();
}
public override Transform Match(ContainerState h, Transform a, Transform ot = null) {
return h.Handler.TypeName == _type ? a : null;
} }
} }
} }
public class SelectorNotAvailableException : Exception {
public SelectorNotAvailableException() : base("The selector is not available under the current context") { }
public SelectorNotAvailableException(string message) : base(message) { }
public SelectorNotAvailableException(string message, Exception innerException) : base(message, innerException) { }
protected SelectorNotAvailableException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
} }

View File

@@ -3,32 +3,18 @@ using UnityEngine;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class SpriteFrame { public class SpriteFrame {
#pragma warning disable IDE1006 Rect m_frame;
Rect _frame; public Rect Frame {
public Rect frame { get { return m_frame; }
get { return _frame; } set { m_frame = value; }
set { _frame = value; }
}
public Rect textureRect {
get { return _frame; }
set { _frame = value; }
} }
bool _rotated = false; bool m_rotated = false;
public bool rotated { public bool Rotated {
get { return _rotated; } get { return m_rotated; }
set { _rotated = value; } set { m_rotated = value; }
} }
public bool textureRotated {
get { return _rotated; }
set { _rotated = value; }
}
#pragma warning restore IDE1006
public Vector2 offset;
public Rect sourceColorRect;
public Vector2 sourceSize;
private Rect _uv; private Rect _uv;
private Vector2[] cuv; private Vector2[] cuv;
public Rect UV { public Rect UV {
@@ -41,7 +27,7 @@ namespace Cryville.Crtr {
float x1 = Mathf.Max(_uv.xMin, _uv.xMax); float x1 = Mathf.Max(_uv.xMin, _uv.xMax);
float y0 = Mathf.Min(_uv.yMin, _uv.yMax); float y0 = Mathf.Min(_uv.yMin, _uv.yMax);
float y1 = Mathf.Max(_uv.yMin, _uv.yMax); float y1 = Mathf.Max(_uv.yMin, _uv.yMax);
if (_rotated) cuv = new Vector2[]{ if (m_rotated) cuv = new Vector2[]{
new Vector2(x0, y1), new Vector2(x0, y1),
new Vector2(x1, y0), new Vector2(x1, y0),
new Vector2(x0, y0), new Vector2(x0, y0),
@@ -78,29 +64,18 @@ namespace Cryville.Crtr {
public void Init() { public void Init() {
if (Texture == null) if (Texture == null)
throw new InvalidOperationException(); // TODO throw new InvalidOperationException("Missing texture");
_frame = new Rect(Vector2.zero, Size); m_frame = new Rect(Vector2.zero, Size);
var w = _frame.width; var w = m_frame.width;
var h = _frame.height; var h = m_frame.height;
float x = _frame.x / w; float x = m_frame.x / w;
float y = 1 - _frame.y / h; float y = 1 - m_frame.y / h;
float tw = (_rotated ? _frame.height : _frame.width) / w; float tw = (m_rotated ? m_frame.height : m_frame.width) / w;
float th = (_rotated ? _frame.width : _frame.height) / h; float th = (m_rotated ? m_frame.width : m_frame.height) / h;
if (_rotated) UV = new Rect(x, y, tw, -th); if (m_rotated) UV = new Rect(x, y, tw, -th);
else UV = new Rect(x, y, tw, -th); else UV = new Rect(x, y, tw, -th);
} }
public void Init(int w, int h, Texture2D _base) {
if (Texture != null)
throw new InvalidOperationException(); // TODO
Texture = _base;
float x = _frame.x / w;
float y = 1 - _frame.y / h;
float tw = (_rotated ? _frame.height : _frame.width) / w;
float th = (_rotated ? _frame.width : _frame.height) / h;
if (_rotated) UV = new Rect(x, y, tw, -th);
else UV = new Rect(x, y, tw, -th);
}
public SpriteFrame() { } public SpriteFrame() { }
public SpriteFrame(Texture2D tex) { public SpriteFrame(Texture2D tex) {
Texture = tex; Texture = tex;

View File

@@ -1,18 +1,19 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using CAnchor = Cryville.Crtr.Anchor;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class StampedEvent : IComparable<StampedEvent> { public class StampedEvent : IComparable<StampedEvent> {
public float Time; public double Time;
public ChartEvent Unstamped; public ChartEvent Unstamped;
public EventContainer Container; public EventContainer Container;
public StampedEvent Origin; public StampedEvent Origin;
public List<StampedEvent> Subevents = new List<StampedEvent>(); public List<StampedEvent> Subevents = new List<StampedEvent>();
private StampedEvent attev = null; public List<StampedEvent> Coevents;
private StampedEvent relev = null; private StampedEvent relev = null;
public float Duration { public double Duration {
get { get {
if (Unstamped == null) return 0; if (Unstamped == null) return 0;
if (Unstamped.IsLong) if (Unstamped.IsLong)
@@ -28,33 +29,13 @@ namespace Cryville.Crtr {
} }
} }
public class PlaySound : StampedEvent { public class Anchor : StampedEvent {
public new Chart.Sound Unstamped; public CAnchor Target;
public override int Priority { public override int Priority {
get { return 0; } get { return 0; }
} }
} }
public class Judge : StampedEvent {
public float NoteTime;
public JudgeDefinition TargetJudge;
public Judge StartEvent;
public bool IsEndJudge;
public override int Priority {
get { return StartEvent == null ? 4 : 6; }
}
protected override int cmpExtra(StampedEvent other) {
return Equals(StartEvent, other) ? 1 : 0;
}
}
public StampedEvent AttackEvent {
get {
if (attev == null) attev = Subevents.FirstOrDefault(ev => ev.Time == this.Time);
return attev;
}
}
public StampedEvent ReleaseEvent { public StampedEvent ReleaseEvent {
get { get {
if (relev == null) relev = Subevents.FirstOrDefault(ev => ((InstantEvent)ev.Unstamped).IsRelease); if (relev == null) relev = Subevents.FirstOrDefault(ev => ((InstantEvent)ev.Unstamped).IsRelease);
@@ -75,12 +56,12 @@ namespace Cryville.Crtr {
if (u != 0) return u; if (u != 0) return u;
u = this.Duration.CompareTo(other.Duration); u = this.Duration.CompareTo(other.Duration);
if (u != 0) return u; if (u != 0) return u;
u = cmpExtra(other); u = CompareExtra(other);
if (u != 0) return u; if (u != 0) return u;
return GetHashCode().CompareTo(other.GetHashCode()); return GetHashCode().CompareTo(other.GetHashCode());
} }
protected virtual int cmpExtra(StampedEvent other) { protected virtual int CompareExtra(StampedEvent other) {
return 0; return 0;
} }
} }

View File

@@ -1,71 +1,128 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Cryville.Crtr { namespace Cryville.Crtr {
/// <summary>
/// A time-forward handler of a sequence of events.
/// </summary>
/// <typeparam name="T">The event type.</typeparam>
public abstract class StateBase<T> { public abstract class StateBase<T> {
public int EventId; /// <summary>
public float Time; /// The current time of the state in seconds.
public Chart chart; /// </summary>
public List<T> events; public double Time { get; protected set; }
/// <summary>
/// The index of the event to be handled next.
/// </summary>
protected int EventId;
/// <summary>
/// The event list.
/// </summary>
protected readonly List<T> Events;
bool breakflag = false; bool breakflag = false;
public StateBase(Chart c, List<T> evs) { /// <summary>
chart = c; /// Creates an instance of the <see cref="StateBase{T}" /> class.
events = evs; /// </summary>
/// <param name="evs">The event list.</param>
public StateBase(List<T> evs) {
Events = evs;
EventId = 0; EventId = 0;
Time = 0; Time = 0;
} }
/// <summary>
/// Creates a copy of the current state.
/// </summary>
/// <returns>A copy of the current state.</returns>
/// <remarks>
/// <para><see cref="Events" /> is shared across copies.</para>
/// </remarks>
public virtual StateBase<T> Clone() { public virtual StateBase<T> Clone() {
return (StateBase<T>)base.MemberwiseClone(); return (StateBase<T>)MemberwiseClone();
} }
/// <summary>
/// Copies the state to another existing state.
/// </summary>
/// <param name="dest">The state to be overridden.</param>
public virtual void CopyTo(StateBase<T> dest) { public virtual void CopyTo(StateBase<T> dest) {
dest.EventId = EventId;
dest.Time = Time; dest.Time = Time;
dest.EventId = EventId;
dest.breakflag = breakflag; dest.breakflag = breakflag;
} }
/// <summary>
/// Interrupts the forward process.
/// </summary>
public virtual void Break() { public virtual void Break() {
breakflag = true; breakflag = true;
} }
public void Forward(Action<T> callback = null) { /// <summary>
ForwardToTime(float.PositiveInfinity, callback); /// Walks through all the remaining events.
/// </summary>
public void Forward() {
ForwardToTime(double.PositiveInfinity);
} }
public void ForwardByTime(float time, Action<T> callback = null) { /// <summary>
ForwardToTime(Time + time, callback); /// Forwards the time by the specified span and walks through all the encountered events.
/// </summary>
/// <param name="time">The span in seconds.</param>
public void ForwardByTime(double time) {
ForwardToTime(Time + time);
} }
public void ForwardOnceByTime(float time, Action<T> callback = null) { /// <summary>
ForwardOnceToTime(Time + time, callback); /// Forwards the time by the specified span but walks through at most one event.
/// </summary>
/// <param name="time">The span in seconds.</param>
public void ForwardOnceByTime(double time) {
ForwardOnceToTime(Time + time);
} }
public void ForwardToTime(float toTime, Action<T> callback = null) { /// <summary>
/// Forwards the time to the specified time and walks through all the encountered events.
/// </summary>
/// <param name="toTime">The time in seconds.</param>
public void ForwardToTime(double toTime) {
breakflag = false; breakflag = false;
ForwardOnceToTime(Time, callback); ForwardOnceToTime(Time);
while (Time < toTime) { while (Time < toTime) {
ForwardOnceToTime(toTime, callback); ForwardOnceToTime(toTime);
if (breakflag) break; if (breakflag) break;
} }
} }
public void ForwardStepByTime(float time, float step, Action<T> callback = null) { /// <summary>
ForwardStepToTime(Time + time, step, callback); /// Forwards the time by the specified span and walks through all the encountered events, with a specified step.
/// </summary>
/// <param name="time">The span in seconds.</param>
/// <param name="step">The step in seconds.</param>
public void ForwardStepByTime(double time, double step) {
ForwardStepToTime(Time + time, step);
} }
public void ForwardStepToTime(float toTime, float step, Action<T> callback = null) { /// <summary>
/// Forwards the time to the specified time and walks through all the encountered events, with a specified step.
/// </summary>
/// <param name="toTime">The time in seconds.</param>
/// <param name="step">The step in seconds.</param>
public void ForwardStepToTime(double toTime, double step) {
breakflag = false; breakflag = false;
ForwardOnceToTime(Time, callback); ForwardOnceToTime(Time);
while (Time < toTime) { while (Time < toTime) {
float next = Time + step; double next = Time + step;
ForwardOnceToTime(next < toTime ? next : toTime, callback); ForwardOnceToTime(next < toTime ? next : toTime);
if (breakflag) break; if (breakflag) break;
} }
} }
public abstract void ForwardOnceToTime(float toTime, Action<T> callback = null); /// <summary>
/// Forwards the time to the specified time but walks through at most one event.
/// </summary>
/// <param name="toTime">The time in seconds.</param>
public abstract void ForwardOnceToTime(double toTime);
} }
} }

View File

@@ -7,8 +7,8 @@ namespace Cryville.Crtr {
readonly GroupHandler gh; readonly GroupHandler gh;
readonly Chart.Track track; readonly Chart.Track track;
public TrackHandler(GroupHandler gh, Chart.Track _track) : base() { public TrackHandler(Chart.Track ev, GroupHandler gh) : base() {
track = _track; track = ev;
this.gh = gh; this.gh = gh;
} }
@@ -32,10 +32,10 @@ namespace Cryville.Crtr {
ptime = s.Time; ptime = s.Time;
if (s.CloneType == 2) { if (s.CloneType == 2) {
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
a_head.SetPositionAndRotation(GetCurrentWorldPoint(), Quaternion.Euler(s.Direction)); a_head.Transform.SetPositionAndRotation(GetCurrentWorldPoint(), Quaternion.Euler(s.Direction));
#else #else
a_head.position = GetCurrentWorldPoint(); a_head.Transform.position = GetCurrentWorldPoint();
a_head.rotation = Quaternion.Euler(s.Direction); a_head.Transform.rotation = Quaternion.Euler(s.Direction);
#endif #endif
} }
else if (s.CloneType == 3) { else if (s.CloneType == 3) {
@@ -57,7 +57,7 @@ namespace Cryville.Crtr {
Vector3 cpt; // Current point Vector3 cpt; // Current point
Vector3 ppt = Vector3.zero; // Previous point Vector3 ppt = Vector3.zero; // Previous point
Vector3 pwp = Vector3.zero; // Previous world point Vector3 pwp = Vector3.zero; // Previous world point
float ptime; // Previous time double ptime; // Previous time
float length; float length;
public override void Update(ContainerState s, StampedEvent ev) { public override void Update(ContainerState s, StampedEvent ev) {
@@ -67,7 +67,7 @@ namespace Cryville.Crtr {
var tsv = s.ScrollVelocity; var tsv = s.ScrollVelocity;
Vector3 dpt = (Vector3)tpt - ppt; // Delta 2D point Vector3 dpt = (Vector3)tpt - ppt; // Delta 2D point
dpt.z = (s.Time - ptime) * ChartPlayer.sv * tsv; // Delta Z dpt.z = (float)((s.Time - ptime) * ChartPlayer.sv * tsv); // Delta Z
Quaternion rotq = Quaternion.Euler(s.Direction); // Rotation Quaternion rotq = Quaternion.Euler(s.Direction); // Rotation
var dwp = rotq * dpt; // Delta world point var dwp = rotq * dpt; // Delta world point
var nl = length + dwp.magnitude; // New length var nl = length + dwp.magnitude; // New length
@@ -97,7 +97,7 @@ namespace Cryville.Crtr {
pwp = Vector3.zero; pwp = Vector3.zero;
ptime = s.Time; ptime = s.Time;
length = 0; length = 0;
//Logger.LogFormat("main", 0, "Debug", "SV: {0}", cs.GetRawValue<Vec1m>("svm").Value); // Logger.LogFormat("main", 0, "Debug", "SV: {0}", cs.GetRawValue<Vec1m>("svm").Value);
} }
// TODO Fix anchor rotation // TODO Fix anchor rotation
@@ -107,9 +107,7 @@ namespace Cryville.Crtr {
} }
public override void EndUpdate(ContainerState s) { public override void EndUpdate(ContainerState s) {
OpenAnchor("tail");
base.EndUpdate(s); base.EndUpdate(s);
CloseAnchor("tail");
if (s.CloneType == 0 || s.CloneType == 2) { if (s.CloneType == 0 || s.CloneType == 2) {
EndUpdatePosition(ts); EndUpdatePosition(ts);
var p = GetCurrentWorldPoint(); var p = GetCurrentWorldPoint();
@@ -118,10 +116,10 @@ namespace Cryville.Crtr {
i.Seal(); i.Seal();
} }
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
a_tail.SetPositionAndRotation(GetCurrentWorldPoint(), Quaternion.Euler(ts.Direction)); a_tail.Transform.SetPositionAndRotation(GetCurrentWorldPoint(), Quaternion.Euler(ts.Direction));
#else #else
a_tail.position = GetCurrentWorldPoint(); a_tail.Transform.position = GetCurrentWorldPoint();
a_tail.rotation = Quaternion.Euler(ts.Direction); a_tail.Transform.rotation = Quaternion.Euler(ts.Direction);
#endif #endif
} }
else if (s.CloneType == 3) EndUpdatePosition(ns); else if (s.CloneType == 3) EndUpdatePosition(ns);
@@ -133,7 +131,7 @@ namespace Cryville.Crtr {
var tsv = s.ScrollVelocity; var tsv = s.ScrollVelocity;
Vector3 dpt = (Vector3)tpt - ppt; Vector3 dpt = (Vector3)tpt - ppt;
dpt.z = (s.Time - ptime) * ChartPlayer.sv * tsv; dpt.z = (float)((s.Time - ptime) * ChartPlayer.sv * tsv);
Quaternion rotq = Quaternion.Euler(s.Direction); Quaternion rotq = Quaternion.Euler(s.Direction);
var dwp = rotq * dpt; // Delta world point var dwp = rotq * dpt; // Delta world point
var nl = length + dwp.magnitude; // New length var nl = length + dwp.magnitude; // New length

View File

@@ -0,0 +1,17 @@
{
"name": "Cryville.Crtr",
"rootNamespace": "",
"references": [
"GUID:d8ea0e0da3ad53a45b65c912ffcacab0",
"GUID:5686e5ee69d0e084c843d61c240d7fdb"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6eb95bd93da7fd54c8c2da321efabb1f
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -9,6 +9,7 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0020")] [assembly: SuppressMessage("Style", "IDE0020")]
[assembly: SuppressMessage("Style", "IDE0038")] [assembly: SuppressMessage("Style", "IDE0038")]
[assembly: SuppressMessage("Style", "IDE0018")] [assembly: SuppressMessage("Style", "IDE0018")]
[assembly: SuppressMessage("Style", "IDE0019")]
// Null operators not supported // Null operators not supported
[assembly: SuppressMessage("Style", "IDE0016")] [assembly: SuppressMessage("Style", "IDE0016")]
@@ -26,6 +27,7 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0034")] [assembly: SuppressMessage("Style", "IDE0034")]
// Simplified new not supported // Simplified new not supported
[assembly: SuppressMessage("Style", "IDE0017")]
[assembly: SuppressMessage("Style", "IDE0090")] [assembly: SuppressMessage("Style", "IDE0090")]
// Pattern matching not supported // Pattern matching not supported
@@ -40,3 +42,6 @@ using System.Diagnostics.CodeAnalysis;
// Local function not supported // Local function not supported
[assembly: SuppressMessage("Style", "IDE0039")] [assembly: SuppressMessage("Style", "IDE0039")]
// Readonly struct not supported
[assembly: SuppressMessage("Style", "IDE0250")]

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 50c5924700029154f807fa804934cd76 guid: c800326c576090042bed36b262ea3514
MonoImporter: MonoImporter:
externalObjects: {} externalObjects: {}
serializedVersion: 2 serializedVersion: 2

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