50 Commits

Author SHA1 Message Date
8dd32afb74 Prevents dynamic anchor set twice. Implement special dynamic anchors. 2023-02-05 22:13:44 +08:00
313824b4bb Fix abnormal shaking at dynamic anchor. 2023-02-05 22:12:47 +08:00
b166c0f5ef Fix overflowed integral digits always prepended in string formatter. 2023-02-05 22:03:31 +08:00
300e44bd4b Code cleanup. 2023-02-05 15:59:20 +08:00
ab6f983392 Implement meta table for font. 2023-02-05 15:59:12 +08:00
596c6395e4 Prevent non-Windows system trying to initialize WindowsPointerHandler. 2023-02-05 15:58:31 +08:00
404a36f9b8 Replace text components in the main browser with TMP. 2023-02-05 15:56:56 +08:00
1711fbadf7 Add fallback logic for TMP auto font. 2023-02-05 15:55:53 +08:00
84b7a6d183 Seperate matcher from font manager. 2023-02-05 15:53:30 +08:00
6d0fd0f9ec Support multiple fonts with the same full name. 2023-02-05 15:51:18 +08:00
b407ba88c4 Add system font matcher. 2023-02-02 18:35:18 +08:00
bd256ba1a6 Reimport upgraded TextMesh Pro, modified. 2023-02-01 22:14:43 +08:00
623c53f79a Cleanup. 2023-01-31 22:56:19 +08:00
969fdc8069 Optimize GC for status info. 2023-01-31 22:56:06 +08:00
cbc874dd72 Optimize GC for proxied input variables. 2023-01-31 22:51:17 +08:00
450bd52095 Implement dynamic stack for skin. 2023-01-31 22:50:24 +08:00
5727fcf177 Introduce UnsafeIL for IL2CPP compatibility. 2023-01-31 22:49:04 +08:00
8ab0c2698b Fix TargetString stuck when length was 0. Add TargetString.TrustedAsArray. 2023-01-31 22:47:35 +08:00
6c7b52d93c Import TextMesh Pro. 2023-01-31 22:44:54 +08:00
91f55cd9a3 Add state count debug info. 2023-01-31 15:54:46 +08:00
a1ce459a0e Restructure event/container system. 2023-01-31 15:53:43 +08:00
9700992c3a Add DisposeAll. 2023-01-31 15:39:40 +08:00
f9a1ea72fe Refactor ReleaseEvent. 2023-01-31 15:30:27 +08:00
507b656eab Pull up StampedEvent.Temporary. Fix temporary event discarding. 2023-01-31 15:26:13 +08:00
c16776aee9 Code cleanup. (Amend) 2023-01-31 15:18:24 +08:00
e109e0bd24 Separate dynamic anchors. 2023-01-31 15:15:13 +08:00
776a615464 Code cleanup. 2023-01-31 15:06:31 +08:00
5514b6cf37 Pull up clip from judge definition. Add clip to event container. 2023-01-31 14:55:41 +08:00
8932d1b8d0 Add current_time variable. 2023-01-28 11:58:13 +08:00
10988847b3 Implement anchor related annotations. 2023-01-28 11:57:49 +08:00
c4b139c7a4 Code cleanup. 2023-01-27 17:30:10 +08:00
130896df1f Fix SkinSelectors.ToString. (2) 2023-01-27 16:54:11 +08:00
5d5c519a1d Remove dynamic judge anchors. (Amend) 2023-01-27 16:41:40 +08:00
3d1a11f78b Remove dynamic judge anchors. Add judge time properties. 2023-01-27 16:05:57 +08:00
cc985844cd Optimize GC for identifier and beat time property source. 2023-01-27 16:03:27 +08:00
feffbaa5a6 Refactor SkinPropertyKey. 2023-01-27 15:31:51 +08:00
d0f0c8ce6d Fix SkinSelectors.ToString. 2023-01-27 15:28:22 +08:00
3fdc236b1d Fix EmptyBinder not identifying inheritance. 2023-01-27 15:24:48 +08:00
46870e163a Code cleanup. 2023-01-26 18:12:22 +08:00
601f64cc61 Introduce no GC string formatter to optimize score string formatting. 2023-01-26 16:52:05 +08:00
c015b60dc3 Code cleanup. 2023-01-26 16:47:56 +08:00
5e01b654bd Optimize GC for enumerating TargetString. 2023-01-26 16:46:43 +08:00
2304257201 Add exception description on PDT parsing error. 2023-01-24 23:10:52 +08:00
02794d88b9 Fix config scene stuck on ruleset format error. 2023-01-22 22:29:16 +08:00
9f73c8ffad Code cleanup. 2023-01-21 20:14:41 +08:00
c1c354959d Add MotionCache. 2023-01-21 20:13:40 +08:00
94428d9e18 Append IDE warning suppression. 2023-01-21 20:12:03 +08:00
5198ecec1f Optimize code structure for input module. 2023-01-21 17:04:29 +08:00
6779b88055 Code cleanup. 2023-01-21 16:59:19 +08:00
c5dab3a232 Refactor SelectorNotAvailableException. 2023-01-20 22:50:31 +08:00
387 changed files with 106740 additions and 858 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -91,7 +91,7 @@ namespace Cryville.Common.Pdt {
} }
} }
} }
public partial class PdtInterpreter<T> { public partial class PdtInterpreter {
readonly static Dictionary<char, int> OP_PRIORITY = new Dictionary<char, int> { readonly static Dictionary<char, int> OP_PRIORITY = new Dictionary<char, int> {
{ '@', 7 }, { '@', 7 },
{ '*', 6 }, { '/', 6 }, { '%', 6 }, { '*', 6 }, { '/', 6 }, { '%', 6 },

View File

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

View File

@@ -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

@@ -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,28 +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),
}; };
readonly List<InputHandler> _handlers = new List<InputHandler>(); readonly HashSet<InputHandler> _handlers = new HashSet<InputHandler>();
readonly Dictionary<Type, InputHandler> _typemap = new Dictionary<Type, InputHandler>(); readonly Dictionary<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) {
@@ -36,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

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

View File

@@ -9,19 +9,19 @@ namespace Cryville.Common.Unity.Input {
public UnityKeyHandler() { } 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,7 +44,7 @@ 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;
} }

View File

@@ -12,18 +12,18 @@ 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();
} }
} }

View File

@@ -12,18 +12,18 @@ 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();
} }
} }

View File

@@ -31,6 +31,8 @@ namespace Cryville.Common.Unity.Input {
public WindowsPointerHandler() { public WindowsPointerHandler() {
if (Instance != null) if (Instance != null)
throw new InvalidOperationException("WindowsPointerHandler already created"); throw new InvalidOperationException("WindowsPointerHandler already created");
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
throw new NotSupportedException("Windows pointer is not supported on this device");
Instance = this; Instance = this;
usePointerMessage = true; usePointerMessage = true;
@@ -61,7 +63,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 +79,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,9 +144,11 @@ namespace Cryville.Common.Unity.Input {
} }
public override void Dispose(bool disposing) { public override void Dispose(bool disposing) {
DeactivateImpl(); if (disposing) {
if (usePointerMessage) Deactivate();
NativeMethods.EnableMouseInPointer(false); if (usePointerMessage)
NativeMethods.EnableMouseInPointer(false);
}
Instance = null; Instance = null;
} }

View File

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

View File

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

View File

@@ -7,10 +7,10 @@ namespace Cryville.Crtr {
public Transform Transform { get; private set; } public Transform Transform { get; private set; }
public SkinContext SkinContext { get; private set; } public SkinContext SkinContext { get; private set; }
public Dictionary<int, PropSrc> PropSrcs { get; private set; } public Dictionary<int, PropSrc> PropSrcs { get; private set; }
public Anchor(int name, Transform transform, bool hasProps = false) { public Anchor(int name, Transform transform, int propSrcCount = 0) {
Name = name; Name = name;
Transform = transform; Transform = transform;
if (hasProps) PropSrcs = new Dictionary<int, PropSrc>(); if (propSrcCount > 0) PropSrcs = new Dictionary<int, PropSrc>(propSrcCount);
SkinContext = new SkinContext(transform, PropSrcs); SkinContext = new SkinContext(transform, PropSrcs);
} }
} }

View File

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

View File

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

View File

@@ -130,11 +130,11 @@ namespace Cryville.Crtr {
get { return Duration > 0; } get { return Duration > 0; }
} }
private InstantEvent relev = null; private ReleaseEvent relev = null;
[JsonIgnore] [JsonIgnore]
public InstantEvent ReleaseEvent { public ReleaseEvent ReleaseEvent {
get { get {
if (relev == null) relev = new InstantEvent(this, true); if (relev == null) relev = new ReleaseEvent(this);
return relev; return relev;
} }
} }
@@ -161,18 +161,12 @@ namespace Cryville.Crtr {
} }
} }
public class InstantEvent : ChartEvent { public class ReleaseEvent : ChartEvent {
public readonly ChartEvent Original; public readonly ChartEvent Original;
public bool IsRelease;
public InstantEvent(ChartEvent orig, bool release = false) { public ReleaseEvent(ChartEvent orig) {
IsRelease = release; Original = orig;
if (orig != null) { time = orig.endtime;
Original = orig;
time = orig.time;
if (IsRelease)
BeatOffset = orig.Duration;
}
} }
public override int Priority { public override int Priority {
@@ -184,6 +178,13 @@ namespace Cryville.Crtr {
public abstract class EventContainer : ChartEvent { public abstract class EventContainer : ChartEvent {
public List<Chart.Motion> motions = new List<Chart.Motion>(); public List<Chart.Motion> motions = new List<Chart.Motion>();
[JsonIgnore]
public Clip Clip { get; private set; }
public EventContainer() {
SubmitPropOp("clip", new PropOp.Clip(v => Clip = v));
}
[JsonIgnore] [JsonIgnore]
public virtual IEnumerable<ChartEvent> Events { public virtual IEnumerable<ChartEvent> Events {
get { get {
@@ -194,7 +195,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(string.Format("Unknown event type {0}", type)); default: throw new ArgumentException(string.Format("Unknown event type \"{0}\"", type));
} }
} }
} }

View File

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

View File

@@ -1,6 +1,7 @@
#define BUILD #define BUILD
using Cryville.Common; using Cryville.Common;
using Cryville.Common.Buffers;
using Cryville.Crtr.Config; using Cryville.Crtr.Config;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -8,7 +9,9 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using System.Text.Formatting;
using System.Threading; using System.Threading;
using TMPro;
using UnityEngine; using UnityEngine;
using UnityEngine.Networking; using UnityEngine.Networking;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
@@ -19,6 +22,7 @@ using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class ChartPlayer : MonoBehaviour { public class ChartPlayer : MonoBehaviour {
#region Fields
Chart chart; Chart chart;
Skin skin; Skin skin;
PdtSkin pskin; PdtSkin pskin;
@@ -44,7 +48,9 @@ namespace Cryville.Crtr {
static bool initialized; static bool initialized;
static Text logs; static Text logs;
Text status; TextMeshProUGUI status;
readonly TargetString statusstr = new TargetString();
readonly StringBuffer statusbuf = new StringBuffer();
static Vector2 screenSize; static Vector2 screenSize;
public static Rect hitRect; public static Rect hitRect;
@@ -66,6 +72,7 @@ namespace Cryville.Crtr {
public static PdtEvaluator etor; public static PdtEvaluator etor;
InputProxy inputProxy; InputProxy inputProxy;
#endregion
#region MonoBehaviour #region MonoBehaviour
void Start() { void Start() {
@@ -79,7 +86,7 @@ namespace Cryville.Crtr {
} }
OnSettingsUpdate(); OnSettingsUpdate();
status = GameObject.Find("Status").GetComponent<Text>(); status = GameObject.Find("Status").GetComponent<TextMeshProUGUI>();
texHandler = new DownloadHandlerTexture(); texHandler = new DownloadHandlerTexture();
#if BUILD #if BUILD
@@ -105,7 +112,6 @@ namespace Cryville.Crtr {
if (texLoader != null) texLoader.Dispose(); if (texLoader != null) texLoader.Dispose();
if (inputProxy != null) inputProxy.Dispose(); if (inputProxy != null) inputProxy.Dispose();
if (texs != null) foreach (var t in texs) Texture.Destroy(t.Value); if (texs != null) foreach (var t in texs) Texture.Destroy(t.Value);
Camera.onPostRender -= OnCameraPostRender;
GC.Collect(); GC.Collect();
} }
@@ -146,13 +152,13 @@ namespace Cryville.Crtr {
actualRenderStep = step; actualRenderStep = step;
nbus.ForwardStepByTime(clippingDist, step); nbus.ForwardStepByTime(clippingDist, step);
nbus.BroadcastEndUpdate(); nbus.EndPreGraphicalUpdate();
nbus.Anchor(); nbus.Anchor();
tbus.StripTempEvents(); tbus.StripTempEvents();
tbus.ForwardStepByTime(clippingDist, step); tbus.ForwardStepByTime(clippingDist, step);
tbus.ForwardStepByTime(renderDist, step); tbus.ForwardStepByTime(renderDist, step);
tbus.BroadcastEndUpdate(); tbus.EndGraphicalUpdate();
UnityEngine.Profiling.Profiler.EndSample(); UnityEngine.Profiling.Profiler.EndSample();
} }
catch (Exception ex) { catch (Exception ex) {
@@ -214,7 +220,6 @@ namespace Cryville.Crtr {
} }
} }
} }
string timetext = string.Empty;
void LogUpdate() { void LogUpdate() {
string _logs = logs.text; string _logs = logs.text;
Game.MainLogger.Enumerate((level, module, msg) => { Game.MainLogger.Enumerate((level, module, msg) => {
@@ -234,36 +239,45 @@ namespace Cryville.Crtr {
); );
}); });
logs.text = _logs.Substring(Mathf.Max(0, _logs.IndexOf('\n', Mathf.Max(0, _logs.Length - 4096)))); logs.text = _logs.Substring(Mathf.Max(0, _logs.IndexOf('\n', Mathf.Max(0, _logs.Length - 4096))));
var sttext = string.Format( statusbuf.Clear();
"FPS: i{0:0} / s{1:0}\nSMem: {2:N0} / {3:N0}\nIMem: {4:N0} / {5:N0}", statusbuf.AppendFormat(
1 / Time.deltaTime, "FPS: i{0:0} / s{1:0}\nSMem: {2:N0} / {3:N0}\nIMem: {4:N0} / {5:N0}",
1 / Time.smoothDeltaTime, 1 / Time.deltaTime,
1 / Time.smoothDeltaTime,
#if UNITY_5_6_OR_NEWER #if UNITY_5_6_OR_NEWER
UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong(), UnityEngine.Profiling.Profiler.GetMonoUsedSizeLong(),
UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong(), UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong(),
UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong(), UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong(),
UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong() UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong()
#else #else
UnityEngine.Profiling.Profiler.GetMonoUsedSize(), UnityEngine.Profiling.Profiler.GetMonoUsedSize(),
UnityEngine.Profiling.Profiler.GetMonoHeapSize(), UnityEngine.Profiling.Profiler.GetMonoHeapSize(),
UnityEngine.Profiling.Profiler.GetTotalAllocatedMemory(), UnityEngine.Profiling.Profiler.GetTotalAllocatedMemory(),
UnityEngine.Profiling.Profiler.GetTotalReservedMemory() UnityEngine.Profiling.Profiler.GetTotalReservedMemory()
#endif #endif
);
sttext += timetext;
if (judge != null) sttext += "\n== Scores ==\n" + judge.GetFullFormattedScoreString();
status.text = sttext;
}
void OnCameraPostRender(Camera cam) {
if (!started) return;
if (!logEnabled) return;
timetext = string.Format(
"\nSTime: {0:R}s {3}\ndATime: {1:+0.0ms;-0.0ms;0} {3}\ndITime: {2:+0.0ms;-0.0ms;0} {3}",
cbus.Time,
(Game.AudioClient.Position - atime0 - cbus.Time) * 1e3,
(inputProxy.GetTimestampAverage() - cbus.Time) * 1e3,
forceSyncFrames != 0 ? "(force sync)" : ""
); );
if (started) {
statusbuf.AppendFormat(
"\nStates: c{0} / b{1}",
cbus.ActiveStateCount, bbus.ActiveStateCount
);
statusbuf.AppendFormat(
"\nSTime: {0:G17}s {3}\ndATime: {1:+0.0ms;-0.0ms;0} {3}\ndITime: {2:+0.0ms;-0.0ms;0} {3}",
cbus.Time,
(Game.AudioClient.Position - atime0 - cbus.Time) * 1e3,
(inputProxy.GetTimestampAverage() - cbus.Time) * 1e3,
forceSyncFrames != 0 ? "(force sync)" : ""
);
if (judge != null) {
statusbuf.Append("\n== Scores ==\n");
var fullScoreStr = judge.GetFullFormattedScoreString();
statusbuf.Append(fullScoreStr.TrustedAsArray(), 0, fullScoreStr.Length);
}
}
statusstr.Length = statusbuf.Count;
var arr = statusstr.TrustedAsArray();
statusbuf.CopyTo(0, arr, 0, statusbuf.Count);
status.SetText(arr, 0, statusbuf.Count);
} }
#endregion #endregion
@@ -294,7 +308,7 @@ namespace Cryville.Crtr {
bool logEnabled = true; bool logEnabled = true;
public void ToggleLogs() { public void ToggleLogs() {
logs.text = ""; logs.text = "";
status.text = ""; status.SetText("");
logEnabled = !logEnabled; logEnabled = !logEnabled;
} }
@@ -322,8 +336,6 @@ namespace Cryville.Crtr {
Game.NetworkTaskWorker.SuspendBackgroundTasks(); Game.NetworkTaskWorker.SuspendBackgroundTasks();
Game.AudioSession = Game.AudioSequencer.NewSession(); Game.AudioSession = Game.AudioSequencer.NewSession();
Camera.onPostRender += OnCameraPostRender;
var hitPlane = new Plane(Vector3.forward, Vector3.zero); var hitPlane = new Plane(Vector3.forward, Vector3.zero);
var r0 = Camera.main.ViewportPointToRay(new Vector3(0, 0, 1)); var r0 = Camera.main.ViewportPointToRay(new Vector3(0, 0, 1));
float dist; float dist;
@@ -437,10 +449,10 @@ namespace Cryville.Crtr {
Logger.Log("main", 1, "Game", "Stopping"); Logger.Log("main", 1, "Game", "Stopping");
Game.AudioSession = Game.AudioSequencer.NewSession(); Game.AudioSession = Game.AudioSequencer.NewSession();
inputProxy.Deactivate(); inputProxy.Deactivate();
if (cbus != null) { cbus.Dispose(); cbus = null; }
if (bbus != null) { bbus.Dispose(); bbus = null; }
if (tbus != null) { tbus.Dispose(); tbus = null; }
if (nbus != null) { nbus.Dispose(); nbus = null; } if (nbus != null) { nbus.Dispose(); nbus = null; }
if (tbus != null) { tbus.Dispose(); tbus = null; }
if (bbus != null) { bbus.Dispose(); bbus = null; }
if (cbus != null) { cbus.Dispose(); cbus.DisposeAll(); cbus = null; }
Logger.Log("main", 1, "Game", "Stopped"); Logger.Log("main", 1, "Game", "Stopped");
} }
catch (Exception ex) { catch (Exception ex) {
@@ -485,6 +497,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);

View File

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

View File

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

View File

@@ -4,6 +4,7 @@ using System.IO;
using System.Text; using System.Text;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using Logger = Cryville.Common.Logger;
namespace Cryville.Crtr.Config { namespace Cryville.Crtr.Config {
public class ConfigScene : MonoBehaviour { public class ConfigScene : MonoBehaviour {
@@ -20,44 +21,48 @@ namespace Cryville.Crtr.Config {
RulesetConfig _rscfg; RulesetConfig _rscfg;
void Start() { void Start() {
ChartPlayer.etor = new PdtEvaluator(); try {
FileInfo file = new FileInfo( ChartPlayer.etor = new PdtEvaluator();
Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset FileInfo file = new FileInfo(
); Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
if (!file.Exists) { );
Popup.Create("Ruleset for the chart not found\nMake sure you have imported the ruleset"); if (!file.Exists) {
ReturnToMenu(); throw new FileNotFoundException("Ruleset for the chart not found\nMake sure you have imported the ruleset");
return; }
} DirectoryInfo dir = file.Directory;
DirectoryInfo dir = file.Directory; using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) { ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
MissingMemberHandling = MissingMemberHandling.Error
});
if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
ruleset.LoadPdt(dir);
}
FileInfo cfgfile = new FileInfo(
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
);
if (!cfgfile.Exists) {
if (!cfgfile.Directory.Exists) cfgfile.Directory.Create();
_rscfg = new RulesetConfig();
}
else {
using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) {
_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
MissingMemberHandling = MissingMemberHandling.Error MissingMemberHandling = MissingMemberHandling.Error
}); });
if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
ruleset.LoadPdt(dir);
} }
FileInfo cfgfile = new FileInfo(
Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
);
if (!cfgfile.Exists) {
if (!cfgfile.Directory.Exists) cfgfile.Directory.Create();
_rscfg = new RulesetConfig();
}
else {
using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) {
_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
MissingMemberHandling = MissingMemberHandling.Error
});
}
}
m_genericConfigPanel.Target = _rscfg.generic;
var proxy = new InputProxy(ruleset.Root, null);
proxy.LoadFrom(_rscfg.inputs);
m_inputConfigPanel.proxy = proxy;
}
catch (Exception ex) {
Popup.CreateException(ex);
Logger.Log("main", 4, "Config", "An error occured while loading the config: {0}", ex);
ReturnToMenu();
} }
m_genericConfigPanel.Target = _rscfg.generic;
var proxy = new InputProxy(ruleset.Root, null);
proxy.LoadFrom(_rscfg.inputs);
m_inputConfigPanel.proxy = proxy;
Game.InputManager.Activate();
} }
public void SwitchCategory(GameObject cat) { public void SwitchCategory(GameObject cat) {
@@ -68,7 +73,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,6 +24,7 @@ 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;
readonly Dictionary<string, InputConfigPanelEntry> _entries = new Dictionary<string, InputConfigPanelEntry>(); readonly Dictionary<string, InputConfigPanelEntry> _entries = new Dictionary<string, InputConfigPanelEntry>();
@@ -32,7 +33,7 @@ namespace Cryville.Crtr.Config {
_sel = entry; _sel = entry;
m_inputDialog.SetActive(true); m_inputDialog.SetActive(true);
CallHelper.Purge(m_deviceList); CallHelper.Purge(m_deviceList);
Game.InputManager.EnumerateEvents(ev => { }); _consumer.EnumerateEvents(ev => { });
_recvsrcs.Clear(); _recvsrcs.Clear();
AddSourceItem(null); AddSourceItem(null);
} }
@@ -46,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);
@@ -59,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));
@@ -67,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

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

View File

@@ -3,10 +3,12 @@
using Cryville.Common; using Cryville.Common;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine; using UnityEngine;
namespace Cryville.Crtr.Event { namespace Cryville.Crtr.Event {
public class ContainerState { public class ContainerState {
#region Struct
public EventBus Bus; public EventBus Bus;
public EventContainer Container; public EventContainer Container;
public StampedEvent StampedContainer; public StampedEvent StampedContainer;
@@ -15,9 +17,7 @@ namespace Cryville.Crtr.Event {
public Dictionary<EventContainer, ContainerState> Children public Dictionary<EventContainer, ContainerState> Children
= new Dictionary<EventContainer, ContainerState>(); = new Dictionary<EventContainer, ContainerState>();
readonly HashSet<EventContainer> WorkingChildren HashSet<EventContainer> ActiveChildren
= new HashSet<EventContainer>();
readonly HashSet<EventContainer> InvalidatedChildren
= new HashSet<EventContainer>(); = new HashSet<EventContainer>();
public Dictionary<Type, List<ContainerState>> TypedChildren public Dictionary<Type, List<ContainerState>> TypedChildren
= new Dictionary<Type, List<ContainerState>>(); = new Dictionary<Type, List<ContainerState>>();
@@ -29,28 +29,47 @@ namespace Cryville.Crtr.Event {
return Children[ev]; return Children[ev];
} }
void NotifyWorkingChanged(EventContainer key) { private bool m_active;
InvalidatedChildren.Add(key); public bool Active {
} get { return m_active; }
void ValidateChildren() { private set {
foreach (var cev in InvalidatedChildren) if (m_active == value) return;
if (Children[cev].Working && !WorkingChildren.Contains(cev)) WorkingChildren.Add(cev); m_active = value;
else if (!Children[cev].Working && WorkingChildren.Contains(cev)) WorkingChildren.Remove(cev); if (!m_active && CloneType == 1) Dispose();
InvalidatedChildren.Clear(); if (Parent != null) {
} if (m_active) Parent.ActiveChildren.Add(Container);
else Parent.ActiveChildren.Remove(Container);
public bool Active { get; set; } }
private bool m_Working; Bus.NotifyActiveChanged(this);
public bool Working {
get { return m_Working; }
set {
m_Working = value;
if (Parent != null) Parent.NotifyWorkingChanged(Container);
Bus.NotifyWorkingChanged(this);
} }
} }
private bool m_lActive;
public bool LogicalActive {
get { return m_lActive; }
set {
if (m_lActive == value) return;
m_lActive = value;
UpdateActive();
if (m_lActive) Handler.StartLogicalUpdate(this);
else Handler.EndLogicalUpdate(this);
}
}
private bool m_pActive;
public bool PhysicalActive {
get { return m_pActive; }
set {
if (m_pActive == value) return;
m_pActive = value;
UpdateActive();
if (m_pActive) Handler.StartPhysicalUpdate(this);
else Handler.EndPhysicalUpdate(this);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void UpdateActive() { Active = m_lActive || m_pActive; }
public byte CloneType; public byte CloneType;
private ContainerState rootPrototype = null; public ContainerState rootPrototype = null;
private ContainerState prototype = null; private ContainerState prototype = null;
public ContainerHandler Handler { public ContainerHandler Handler {
@@ -64,41 +83,7 @@ namespace Cryville.Crtr.Event {
} }
} }
readonly RMVPool RMVPool = new RMVPool(); public ContainerState(EventContainer _ev, ContainerState parent = null) {
protected Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>();
protected Dictionary<Identifier, RealtimeMotionValue> Values;
protected Dictionary<Identifier, CacheEntry> CachedValues;
protected class CacheEntry {
public bool Valid { get; set; }
public Vector Value { get; set; }
public CacheEntry Clone() {
return new CacheEntry { Valid = Valid, Value = Value == null ? null : Value.Clone() };
}
}
/// <summary>
/// Gets a motion value.
/// </summary>
/// <param name="name">The motion name.</param>
/// <param name="clone">Returns a cloned motion value instead.</param>
/// <returns>A motion value.</returns>
RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) {
RealtimeMotionValue value = Values[name];
if (clone) return value.Clone();
return value;
}
void InvalidateMotion(Identifier name) {
CacheEntry cache;
if (!CachedValues.TryGetValue(name, out cache))
CachedValues.Add(name, cache = new CacheEntry());
cache.Valid = false;
ValidateChildren();
foreach (var c in WorkingChildren)
Children[c].InvalidateMotion(name);
}
public ContainerState(Chart c, EventContainer _ev, ContainerState parent = null) {
Container = _ev; Container = _ev;
if (parent != null) { if (parent != null) {
@@ -107,9 +92,11 @@ namespace Cryville.Crtr.Event {
} }
Values = new Dictionary<Identifier, RealtimeMotionValue>(ChartPlayer.motionRegistry.Count); Values = new Dictionary<Identifier, RealtimeMotionValue>(ChartPlayer.motionRegistry.Count);
CachedValues = new Dictionary<Identifier, CacheEntry>(ChartPlayer.motionRegistry.Count); CachedValues = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
foreach (var m in ChartPlayer.motionRegistry) 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));
rootPrototype = this;
} }
static void AddChild(EventContainer c, ContainerState s, ContainerState target) { static void AddChild(EventContainer c, ContainerState s, ContainerState target) {
@@ -128,9 +115,11 @@ namespace Cryville.Crtr.Event {
} }
r.Values = mvs; r.Values = mvs;
var cvs = new Dictionary<Identifier, CacheEntry>(ChartPlayer.motionRegistry.Count); var cvs = new Dictionary<Identifier, MotionCache>(ChartPlayer.motionRegistry.Count);
foreach (var cv in CachedValues) { 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;
@@ -141,7 +130,9 @@ namespace Cryville.Crtr.Event {
AddChild(child.Key, cc, r); AddChild(child.Key, cc, r);
} }
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(PlayingMotions.Count); r.ActiveChildren = new HashSet<EventContainer>();
var pms = new Dictionary<StampedEvent, RealtimeMotionValue>(Math.Max(4, PlayingMotions.Count));
foreach (var m in PlayingMotions) foreach (var m in PlayingMotions)
pms.Add(m.Key, m.Value); pms.Add(m.Key, m.Value);
r.PlayingMotions = pms; r.PlayingMotions = pms;
@@ -152,14 +143,15 @@ namespace Cryville.Crtr.Event {
else if (ct >= 16) Handler.ps = r; else if (ct >= 16) Handler.ps = r;
else throw new InvalidOperationException("Invalid clone type"); else throw new InvalidOperationException("Invalid clone type");
r.prototype = this; r.prototype = this;
if (prototype == null) r.rootPrototype = this;
else r.rootPrototype = rootPrototype;
r.CloneType = ct; r.CloneType = ct;
return r; return r;
} }
public void CopyTo(byte ct, ContainerState dest) { public void CopyTo(byte ct, ContainerState dest) {
dest.Working = Working; dest.m_lActive = m_lActive;
dest.m_pActive = m_pActive;
dest.m_active = m_active;
if (dest.m_active) dest.Bus.NotifyActiveChanged(dest);
foreach (var mv in Values) { foreach (var mv in Values) {
RealtimeMotionValue dv; RealtimeMotionValue dv;
@@ -169,19 +161,22 @@ namespace Cryville.Crtr.Event {
foreach (var cv in dest.CachedValues) cv.Value.Valid = false; foreach (var cv in dest.CachedValues) cv.Value.Valid = false;
foreach (var cv in CachedValues) { foreach (var cv in CachedValues) {
CacheEntry dv; MotionCache dv;
if (dest.CachedValues.TryGetValue(cv.Key, out dv)) { if (!dest.CachedValues.TryGetValue(cv.Key, out dv)) {
dv.Valid = cv.Value.Valid; dest.CachedValues.Add(cv.Key, dv = dest.MCPool.Rent(cv.Key));
if (cv.Value.Value != null) cv.Value.Value.CopyTo(dv.Value);
} }
else dest.CachedValues.Add(cv.Key, cv.Value.Clone()); cv.Value.CopyTo(dv);
} }
if (ct != 1) foreach (var cev in WorkingChildren) foreach (var cev in dest.ActiveChildren) {
if (!ActiveChildren.Contains(cev))
Children[cev].CopyTo(ct, dest.Children[cev]);
}
dest.ActiveChildren.Clear();
foreach (var cev in ActiveChildren) {
dest.ActiveChildren.Add(cev);
Children[cev].CopyTo(ct, dest.Children[cev]); Children[cev].CopyTo(ct, dest.Children[cev]);
else foreach (var child in Children) }
child.Value.CopyTo(ct, dest.Children[child.Key]);
dest.ValidateChildren();
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);
@@ -194,10 +189,16 @@ namespace Cryville.Crtr.Event {
public void Dispose() { public void Dispose() {
if (Disposed) return; if (Disposed) return;
Disposed = true; Disposed = true;
if (CloneType < 16 && Handler != null) Handler.Dispose(); if (CloneType == 1) Handler.Dispose();
foreach (var s in Children) foreach (var s in Children)
s.Value.Dispose(); s.Value.Dispose();
RMVPool.ReturnAll(); RMVPool.ReturnAll();
MCPool.ReturnAll();
}
public void DisposeAll() {
foreach (var s in Children)
s.Value.DisposeAll();
Handler.DisposeAll();
} }
public void AttachHandler(ContainerHandler h) { public void AttachHandler(ContainerHandler h) {
@@ -210,13 +211,40 @@ namespace Cryville.Crtr.Event {
public void AttachSystems(PdtSkin skin, Judge judge) { public void AttachSystems(PdtSkin skin, Judge judge) {
Handler.AttachSystems(skin, judge); Handler.AttachSystems(skin, judge);
} }
#endregion
#region Motion
readonly RMVPool RMVPool = new RMVPool();
readonly MotionCachePool MCPool = new MotionCachePool();
Dictionary<StampedEvent, RealtimeMotionValue> PlayingMotions = new Dictionary<StampedEvent, RealtimeMotionValue>(4);
Dictionary<Identifier, RealtimeMotionValue> Values;
Dictionary<Identifier, MotionCache> CachedValues;
/// <summary>
/// Gets a motion value.
/// </summary>
/// <param name="name">The motion name.</param>
/// <param name="clone">Returns a cloned motion value instead.</param>
/// <returns>A motion value.</returns>
RealtimeMotionValue GetMotionValue(Identifier name, bool clone = false) {
RealtimeMotionValue value = Values[name];
if (clone) return value.Clone();
return value;
}
void InvalidateMotion(Identifier name) {
MotionCache cache;
if (!CachedValues.TryGetValue(name, out cache))
CachedValues.Add(name, cache = MCPool.Rent(name));
cache.Valid = false;
foreach (var c in ActiveChildren)
Children[c].InvalidateMotion(name);
}
public Vector GetRawValue(Identifier key) { public Vector GetRawValue(Identifier key) {
CacheEntry tr; MotionCache tr;
if (!CachedValues.TryGetValue(key, out tr)) if (!CachedValues.TryGetValue(key, out tr))
CachedValues.Add(key, tr = new CacheEntry { }); CachedValues.Add(key, tr = MCPool.Rent(key));
if (tr.Value == null)
tr.Value = RMVPool.Rent(key).AbsoluteValue;
Vector r = tr.Value; Vector r = tr.Value;
#if !DISABLE_CACHE #if !DISABLE_CACHE
if (tr.Valid) return r; if (tr.Valid) return r;
@@ -305,13 +333,15 @@ namespace Cryville.Crtr.Event {
return GetRawValue<Vec1>(n_track).Value; return GetRawValue<Vec1>(n_track).Value;
} }
} }
#endregion
#region Update
bool breakflag = false; bool breakflag = false;
public void Break() { public void Break() {
Handler.EndUpdate(this); // Handler.EndLogicalUpdate(this);
breakflag = true; breakflag = true;
Working = false; // LogicalActive = false;
} }
public void Discard(StampedEvent ev) { public void Discard(StampedEvent ev) {
@@ -336,33 +366,26 @@ namespace Cryville.Crtr.Event {
else if (ev.Unstamped is EventContainer) { else if (ev.Unstamped is EventContainer) {
var cev = (EventContainer)ev.Unstamped; var cev = (EventContainer)ev.Unstamped;
var ccs = GetChild(cev); var ccs = GetChild(cev);
ccs.Working = true; ccs.LogicalActive = true;
ccs.StartUpdate();
UpdateMotions(); UpdateMotions();
if (!cev.IsLong) { if (!cev.IsLong) {
ccs.Working = false; ccs.LogicalActive = false;
ccs.BroadcastEndUpdate();
if (CloneType == 1) ccs.Dispose();
} }
} }
else if (ev.Unstamped is InstantEvent) { else if (ev.Unstamped is ReleaseEvent) {
var tev = (InstantEvent)ev.Unstamped; var tev = (ReleaseEvent)ev.Unstamped;
if (tev.IsRelease) { var nev = tev.Original;
var nev = tev.Original; if (nev is Chart.Motion) {
if (nev is Chart.Motion) { Update(ev);
Update(ev); var mv = PlayingMotions[ev.Origin];
var mv = PlayingMotions[ev.Origin]; if (mv.CloneTypeFlag == CloneType) RMVPool.Return(mv);
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) { var cev = (EventContainer)ev.Origin.Unstamped;
var cev = (EventContainer)ev.Origin.Unstamped; var ccs = GetChild(cev);
var ccs = GetChild(cev); UpdateMotions();
UpdateMotions(); ccs.LogicalActive = false;
ccs.Working = false;
ccs.BroadcastEndUpdate();
if (CloneType == 1) ccs.Dispose();
}
} }
} }
Update(ev.Unstamped == null || ev.Unstamped.Priority >= 0 ? ev : null); Update(ev.Unstamped == null || ev.Unstamped.Priority >= 0 ? ev : null);
@@ -370,12 +393,10 @@ namespace Cryville.Crtr.Event {
else Update(null); else Update(null);
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void Update(StampedEvent ev) { void Update(StampedEvent ev) {
UpdateMotions(); UpdateMotions();
if (ev == null || ev.Unstamped != null) Handler.Update(this, ev); Handler.Update(this, ev);
else Handler.ExUpdate(this, ev);
foreach (var m in PlayingMotions)
Handler.MotionUpdate(CloneType, (Chart.Motion)m.Key.Unstamped);
} }
private void UpdateMotions() { private void UpdateMotions() {
@@ -420,14 +441,17 @@ namespace Cryville.Crtr.Event {
} }
} }
public void StartUpdate() { public void EndPreGraphicalUpdate() {
Handler.StartUpdate(this); Handler.SetPreGraphicalActive(false, this);
foreach (var ls in ActiveChildren) {
Children[ls].EndPreGraphicalUpdate();
}
} }
public void BroadcastEndUpdate() { public void EndGraphicalUpdate() {
Handler.EndUpdate(this); Handler.SetGraphicalActive(false, this);
foreach (var ls in Children.Values) { foreach (var ls in ActiveChildren) {
if (ls.Working) ls.BroadcastEndUpdate(); Children[ls].EndGraphicalUpdate();
} }
} }
@@ -437,5 +461,6 @@ namespace Cryville.Crtr.Event {
if (ls.Handler.Alive) ls.Anchor(); if (ls.Handler.Alive) ls.Anchor();
} }
} }
#endregion
} }
} }

View File

@@ -37,7 +37,7 @@ namespace Cryville.Crtr.Event {
} }
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(c, parent);
stateMap.Add(c, cs); stateMap.Add(c, cs);
if (parent == null) { if (parent == null) {
cs.Depth = 0; cs.Depth = 0;
@@ -84,13 +84,34 @@ namespace Cryville.Crtr.Event {
Container = con Container = con
}; };
if (ev is EventContainer) { if (ev is EventContainer) {
stateMap[(EventContainer)ev].StampedContainer = sev; var tev = (EventContainer)ev;
stateMap[tev].StampedContainer = sev;
stampedEvents.Add(new StampedEvent.ClipBehind {
Container = con,
Origin = sev,
Time = etime + tev.Clip.Behind,
});
if (!ev.IsLong) {
stampedEvents.Add(new StampedEvent.ClipAhead {
Container = con,
Origin = sev,
Time = etime + tev.Clip.Ahead,
});
}
} }
if (ev is InstantEvent) { if (ev is ReleaseEvent) {
var tev = (InstantEvent)ev; var tev = (ReleaseEvent)ev;
var pev = map[tev.Original]; var oev = tev.Original;
pev.Subevents.Add(sev); var pev = map[oev];
pev.ReleaseEvent = sev;
sev.Origin = pev; sev.Origin = pev;
if (oev is EventContainer) {
stampedEvents.Add(new StampedEvent.ClipAhead {
Container = con,
Origin = pev,
Time = etime + ((EventContainer)oev).Clip.Ahead,
});
}
} }
if (con != null && coevents.Contains(ev)) { if (con != null && coevents.Contains(ev)) {
List<StampedEvent> cevs; List<StampedEvent> cevs;

View File

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

View File

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

View File

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

View File

@@ -24,10 +24,9 @@ namespace Cryville.Crtr.Event {
= new SimpleObjectPool<Dictionary<RealtimeMotionValue, Identifier>>(1024); = new SimpleObjectPool<Dictionary<RealtimeMotionValue, Identifier>>(1024);
Dictionary<RealtimeMotionValue, Identifier> _rented; 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(); 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) {
@@ -35,6 +34,7 @@ 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();

View File

@@ -1,8 +1,10 @@
using Cryville.Audio; using Cryville.Audio;
using Cryville.Audio.Source; using Cryville.Audio.Source;
using Cryville.Common; using Cryville.Common;
using Cryville.Common.Font;
using Cryville.Common.Unity; using Cryville.Common.Unity;
using Cryville.Common.Unity.Input; using Cryville.Common.Unity.Input;
using Cryville.Common.Unity.UI;
using FFmpeg.AutoGen; using FFmpeg.AutoGen;
using Ionic.Zip; using Ionic.Zip;
using Newtonsoft.Json; using Newtonsoft.Json;
@@ -127,6 +129,21 @@ namespace Cryville.Crtr {
Settings.Default.LastRunVersion = Application.version; Settings.Default.LastRunVersion = Application.version;
Settings.Default.Save(); Settings.Default.Save();
Logger.Log("main", 1, "UI", "Initializing font manager");
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
var fontMatcher = new FallbackListFontMatcher(new FontManagerWindows());
fontMatcher.LoadDefaultWindowsFallbackList();
TMPAutoFont.FontMatcher = fontMatcher;
TMPAutoFont.DefaultShader = Resources.Load<Shader>("TextMesh Pro/Shaders/TMP_SDF SSD");
#elif UNITY_ANDROID
var fontMatcher = new FallbackListFontMatcher(new FontManagerAndroid());
fontMatcher.LoadDefaultAndroidFallbackList();
TMPAutoFont.FontMatcher = fontMatcher;
TMPAutoFont.DefaultShader = Resources.Load<Shader>("TextMesh Pro/Shaders/TMP_SDF-Mobile SSD");
#else
#error No font manager initialization logic.
#endif
Logger.Log("main", 1, "Game", "Initialized"); Logger.Log("main", 1, "Game", "Initialized");
} }

View File

@@ -15,11 +15,7 @@ namespace Cryville.Crtr {
this.ch = ch; this.ch = ch;
} }
public override string TypeName { public override string TypeName { get { return "group"; } }
get {
return "group";
}
}
public override void PreInit() { public override void PreInit() {
base.PreInit(); base.PreInit();

View File

@@ -65,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);
@@ -77,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);
@@ -142,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);

View File

@@ -4,6 +4,7 @@ using Cryville.Common.Pdt;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Text.Formatting;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class Judge { public class Judge {
@@ -34,6 +35,10 @@ namespace Cryville.Crtr {
public Judge(PdtRuleset rs) { public Judge(PdtRuleset rs) {
_etor = ChartPlayer.etor; _etor = ChartPlayer.etor;
_rs = rs; _rs = rs;
_numsrc1 = new PropSrc.Float(() => _numbuf1);
_numsrc2 = new PropSrc.Float(() => _numbuf2);
_numsrc3 = new PropSrc.Float(() => _numbuf3);
_numsrc4 = new PropSrc.Float(() => _numbuf4);
InitJudges(); InitJudges();
InitScores(); InitScores();
} }
@@ -52,8 +57,8 @@ namespace Cryville.Crtr {
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.Behind,
EndClip = et + def.clip[1], EndClip = et + def.clip.Ahead,
BaseEvent = tev, BaseEvent = tev,
Definition = def, Definition = def,
Handler = handler, Handler = handler,
@@ -65,13 +70,9 @@ namespace Cryville.Crtr {
#endregion #endregion
#region Judge #region Judge
internal readonly Dictionary<int, int> judgeMap = new Dictionary<int, int>(); 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() { void InitJudges() {
foreach (var i in _rs.judges.Keys) { foreach (var i in _rs.judges.Keys) {
judgeMap.Add(i.Key, IdentifierManager.SharedInstance.Request("judge_" + i.Name)); 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;
@@ -80,10 +81,8 @@ namespace Cryville.Crtr {
static readonly int _var_tn = IdentifierManager.SharedInstance.Request("tn"); static readonly int _var_tn = IdentifierManager.SharedInstance.Request("tn");
static readonly int _var_ft = IdentifierManager.SharedInstance.Request("ft"); static readonly int _var_ft = IdentifierManager.SharedInstance.Request("ft");
static readonly int _var_tt = IdentifierManager.SharedInstance.Request("tt"); static readonly int _var_tt = IdentifierManager.SharedInstance.Request("tt");
readonly byte[] _numbuf1 = new byte[sizeof(float)]; float _numbuf1, _numbuf2, _numbuf3, _numbuf4;
readonly byte[] _numbuf2 = new byte[sizeof(float)]; readonly PropSrc _numsrc1, _numsrc2, _numsrc3, _numsrc4;
readonly byte[] _numbuf3 = new byte[sizeof(float)];
readonly byte[] _numbuf4 = new byte[sizeof(float)];
unsafe void LoadNum(byte[] buffer, float value) { unsafe void LoadNum(byte[] buffer, float value) {
fixed (byte* ptr = buffer) *(float*)ptr = value; fixed (byte* ptr = buffer) *(float*)ptr = value;
} }
@@ -120,13 +119,13 @@ namespace Cryville.Crtr {
Forward(target, tt); Forward(target, tt);
var actlist = activeEvs[target]; var actlist = activeEvs[target];
if (actlist.Count > 0) { if (actlist.Count > 0) {
LoadNum(_numbuf3, ft); _etor.ContextCascadeUpdate(_var_ft, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf3)); _numbuf3 = ft; _numsrc3.Invalidate(); _etor.ContextCascadeUpdate(_var_ft, _numsrc3);
LoadNum(_numbuf4, tt); _etor.ContextCascadeUpdate(_var_tt, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf4)); _numbuf4 = tt; _numsrc4.Invalidate(); _etor.ContextCascadeUpdate(_var_tt, _numsrc4);
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, (float)ev.StartTime); _etor.ContextCascadeUpdate(_var_fn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf1)); _numbuf1 = (float)ev.StartTime; _numsrc1.Invalidate(); _etor.ContextCascadeUpdate(_var_fn, _numsrc1);
LoadNum(_numbuf2, (float)ev.EndTime); _etor.ContextCascadeUpdate(_var_tn, new PropSrc.Arbitrary(PdtInternalType.Number, _numbuf2)); _numbuf2 = (float)ev.EndTime; _numsrc2.Invalidate(); _etor.ContextCascadeUpdate(_var_tn, _numsrc2);
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;
@@ -206,6 +205,9 @@ namespace Cryville.Crtr {
readonly Dictionary<int, string> scoreStringCache = new Dictionary<int, string>(); readonly Dictionary<int, string> scoreStringCache = new Dictionary<int, string>();
readonly Dictionary<int, PropSrc> scoreStringSrcs = new Dictionary<int, PropSrc>(); readonly Dictionary<int, PropSrc> scoreStringSrcs = new Dictionary<int, PropSrc>();
readonly ArrayPool<byte> scoreStringPool = new ArrayPool<byte>(); readonly ArrayPool<byte> scoreStringPool = new ArrayPool<byte>();
readonly Dictionary<int, string> scoreFormatCache = new Dictionary<int, string>();
readonly TargetString scoreFullStr = new TargetString();
readonly StringBuffer scoreFullBuf = new StringBuffer();
void InitScores() { void InitScores() {
foreach (var s in _rs.scores) { foreach (var s in _rs.scores) {
var key = s.Key.Key; var key = s.Key.Key;
@@ -217,7 +219,8 @@ namespace Cryville.Crtr {
scoreDefs.Add(key, s.Value); scoreDefs.Add(key, s.Value);
scores.Add(key, s.Value.init); scores.Add(key, s.Value.init);
scoreStringCache.Add(scoreStringKeys[key], null); scoreStringCache.Add(scoreStringKeys[key], null);
scoreStringSrcs.Add(scoreStringKeys[key], new ScoreStringSrc(scoreStringPool, () => GetScoreString(strkey))); scoreStringSrcs.Add(scoreStringKeys[key], new ScoreStringSrc(scoreStringPool, () => scores[key], scoreDefs[key].format));
scoreFormatCache[key] = string.Format("{{0:{0}}}", s.Value.format);
} }
} }
void InvalidateScore(int key) { void InvalidateScore(int key) {
@@ -225,54 +228,52 @@ namespace Cryville.Crtr {
scoreStringCache[scoreStringKeys[key]] = null; scoreStringCache[scoreStringKeys[key]] = null;
scoreStringSrcs[scoreStringKeys[key]].Invalidate(); scoreStringSrcs[scoreStringKeys[key]].Invalidate();
} }
string GetScoreString(int key) {
var result = scoreStringCache[key];
if (result == null) {
var rkey = scoreStringKeysRev[key];
return scoreStringCache[key] = scores[rkey].ToString(scoreDefs[rkey].format, CultureInfo.InvariantCulture);
}
else return result;
}
public bool TryGetScoreSrc(int key, out PropSrc value) { public bool TryGetScoreSrc(int key, out PropSrc value) {
return scoreSrcs.TryGetValue(key, out value); return scoreSrcs.TryGetValue(key, out value);
} }
public bool TryGetScoreStringSrc(int key, out PropSrc value) { public bool TryGetScoreStringSrc(int key, out PropSrc value) {
return scoreStringSrcs.TryGetValue(key, out value); return scoreStringSrcs.TryGetValue(key, out value);
} }
public string GetFullFormattedScoreString() { public TargetString GetFullFormattedScoreString() {
bool flag = false; bool flag = false;
string result = ""; scoreFullBuf.Clear();
foreach (var s in scores.Keys) { foreach (var s in scores.Keys) {
result += string.Format(flag ? "\n{0}: {1}" : "{0}: {1}", IdentifierManager.SharedInstance.Retrieve(s), GetScoreString(scoreStringKeys[s])); scoreFullBuf.AppendFormat(flag ? "\n{0}: " : "{0}: ", (string)IdentifierManager.SharedInstance.Retrieve(s));
scoreFullBuf.AppendFormat(scoreFormatCache[s], scores[s]);
flag = true; flag = true;
} }
return result; scoreFullStr.Length = scoreFullBuf.Count;
var arr = scoreFullStr.TrustedAsArray();
scoreFullBuf.CopyTo(0, arr, 0, scoreFullBuf.Count);
return scoreFullStr;
} }
class ScoreStringSrc : PropSrc { class ScoreStringSrc : PropSrc {
readonly Func<string> _cb; readonly Func<float> _cb;
readonly string _format;
readonly ArrayPool<byte> _pool; readonly ArrayPool<byte> _pool;
byte[] _buf; readonly StringBuffer _buf = new StringBuffer() { Culture = CultureInfo.InvariantCulture };
public ScoreStringSrc(ArrayPool<byte> pool, Func<string> cb) public ScoreStringSrc(ArrayPool<byte> pool, Func<float> cb, string format)
: base(PdtInternalType.String) { : base(PdtInternalType.String) {
_pool = pool; _pool = pool;
_cb = cb; _cb = cb;
_format = string.Format("{{0:{0}}}", format);
} }
public override void Invalidate() { public override void Invalidate() {
base.Invalidate(); if (buf != null) {
if (_buf != null) { _pool.Return(buf);
_pool.Return(_buf); base.Invalidate();
_buf = null;
} }
} }
protected override unsafe void InternalGet() { protected override unsafe void InternalGet() {
var src = _cb(); var src = _cb();
int strlen = src.Length; _buf.Clear();
_buf.AppendFormat(_format, src);
int strlen = _buf.Count;
buf = _pool.Rent(sizeof(int) + strlen * sizeof(char)); buf = _pool.Rent(sizeof(int) + strlen * sizeof(char));
fixed (byte* _ptr = buf) { fixed (byte* _ptr = buf) {
char* ptr = (char*)(_ptr + sizeof(int));
*(int*)_ptr = strlen; *(int*)_ptr = strlen;
int i = 0; char* ptr = (char*)(_ptr + sizeof(int));
foreach (var c in src) ptr[i++] = c; _buf.CopyTo(ptr, 0, strlen);
} }
} }
} }
@@ -285,7 +286,7 @@ namespace Cryville.Crtr {
public Dictionary<Identifier, PdtExpression> pass; public Dictionary<Identifier, PdtExpression> pass;
} }
public class JudgeDefinition { public class JudgeDefinition {
public float[] clip; public Clip clip;
public PdtExpression input; public PdtExpression input;
public PdtExpression hit; public PdtExpression hit;
public Identifier[] pass; public Identifier[] pass;

View File

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

View File

@@ -15,57 +15,38 @@ namespace Cryville.Crtr {
this.gh = gh; this.gh = gh;
} }
public override string TypeName { public override string TypeName { get { return "note"; } }
get {
return "note";
}
}
SectionalGameObject[] sgos; SectionalGameObject[] sgos;
readonly Dictionary<Chart.Judge, JudgeState> judges = new Dictionary<Chart.Judge, JudgeState>(); readonly Dictionary<Chart.Judge, JudgeState> judges = new Dictionary<Chart.Judge, JudgeState>();
readonly Dictionary<int, DynamicJudgeAnchorPair> dynJudgeAnchors = new Dictionary<int, DynamicJudgeAnchorPair>();
class JudgeState { class JudgeState {
static readonly int _var_judge_result = IdentifierManager.SharedInstance.Request("judge_result"); static readonly int _var_judge_result = IdentifierManager.SharedInstance.Request("judge_result");
static readonly int _var_judge_time_absolute = IdentifierManager.SharedInstance.Request("judge_time_absolute");
static readonly int _var_judge_time_relative = IdentifierManager.SharedInstance.Request("judge_time_relative");
public Anchor StaticAnchor { get; private set; } public 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 AbsoluteTime { get; private set; }
PropSrc _jtabsPropSrc;
public float RelativeTime { get; private set; } public float RelativeTime { get; private set; }
int _result = 0; PropSrc _jtrelPropSrc;
public int Result { get; private set; }
PropSrc _resultPropSrc; PropSrc _resultPropSrc;
public JudgeState(NoteHandler handler, int name) { public JudgeState(NoteHandler handler, int name) {
StaticAnchor = handler.RegisterAnchor(handler.judge.judgeMap[name], true); StaticAnchor = handler.RegisterAnchor(handler.judge.judgeMap[name], false, 3);
DynamicAnchors = handler.GetDynamicJudgeAnchorPair(name);
} }
public void MarkJudged(float abs, float rel, int result) { public void MarkJudged(float abs, float rel, int result) {
Judged = true;
AbsoluteTime = abs; AbsoluteTime = abs;
RelativeTime = rel; RelativeTime = rel;
_result = result; Result = result;
_jtabsPropSrc.Invalidate();
_jtrelPropSrc.Invalidate();
_resultPropSrc.Invalidate(); _resultPropSrc.Invalidate();
} }
public void InitPropSrcs() { public void InitPropSrcs() {
StaticAnchor.PropSrcs.Add(_var_judge_result, _resultPropSrc = new PropSrc.Identifier(() => _result)); StaticAnchor.PropSrcs.Add(_var_judge_result, _resultPropSrc = new PropSrc.Identifier(() => Result));
StaticAnchor.PropSrcs.Add(_var_judge_time_absolute, _jtabsPropSrc = new PropSrc.Float(() => AbsoluteTime));
StaticAnchor.PropSrcs.Add(_var_judge_time_relative, _jtrelPropSrc = new PropSrc.Float(() => RelativeTime));
} }
} }
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() { public override void PreInit() {
base.PreInit(); base.PreInit();
@@ -78,19 +59,17 @@ namespace Cryville.Crtr {
sgos = gogroup.GetComponentsInChildren<SectionalGameObject>(); sgos = gogroup.GetComponentsInChildren<SectionalGameObject>();
foreach (var judge in judges.Values) judge.InitPropSrcs(); foreach (var judge in judges.Values) judge.InitPropSrcs();
} }
protected override void PreAwake(ContainerState s) {
base.PreAwake(s); public override void StartPhysicalUpdate(ContainerState s) {
#if UNITY_5_6_OR_NEWER base.StartPhysicalUpdate(s);
a_head.Transform.SetPositionAndRotation(Position = GetFramePoint(s.Parent, s.Track), Rotation = GetFrameRotation(s.Parent, s.Track));
#else
a_head.Transform.position = Position = GetFramePoint(s.Parent, s.Track);
a_head.Transform.rotation = Rotation = GetFrameRotation(s.Parent, s.Track);
#endif
}
protected override void Awake(ContainerState s) {
base.Awake(s);
if (s.CloneType == 2) { if (s.CloneType == 2) {
if (!gogroup) return; TransformAwake(s);
}
}
public override void StartGraphicalUpdate(ContainerState s) {
base.StartGraphicalUpdate(s);
TransformAwake(s);
if (gogroup) {
if (Event.IsLong) { if (Event.IsLong) {
foreach (var i in sgos) { foreach (var i in sgos) {
i.Reset(); i.Reset();
@@ -107,17 +86,18 @@ namespace Cryville.Crtr {
} }
} }
} }
void TransformAwake(ContainerState s) {
Position = GetFramePoint(s.Parent, s.Track);
Rotation = GetFrameRotation(s.Parent, s.Track);
}
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 <= 2) { if (s.CloneType <= 2) {
Position = GetFramePoint(s.Parent, s.Track); Position = GetFramePoint(s.Parent, s.Track);
Rotation = GetFrameRotation(s.Parent, s.Track); Rotation = GetFrameRotation(s.Parent, s.Track);
} if (s.CloneType == 2) {
if (s.CloneType == 2) { if (!gogroup || !Event.IsLong) return;
if (!gogroup) return;
Chart.Note tev = Event;
if (tev.IsLong) {
foreach (var i in sgos) foreach (var i in sgos)
i.AppendPoint(Position, Rotation); i.AppendPoint(Position, Rotation);
} }
@@ -135,26 +115,11 @@ namespace Cryville.Crtr {
} }
} }
public override void Anchor() { public override void EndGraphicalUpdate(ContainerState s) {
base.Anchor(); if (gogroup) {
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) {
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
a_tail.Transform.SetPositionAndRotation(GetFramePoint(ts.Parent, ts.Track), Quaternion.Euler(ts.Direction));
#else
a_tail.Transform.position = GetFramePoint(ts.Parent, ts.Track);
a_tail.Transform.rotation = Quaternion.Euler(ts.Direction);
#endif
} }
base.EndUpdate(s); base.EndGraphicalUpdate(s);
} }
Vector3 GetFramePoint(ContainerState state, float track) { Vector3 GetFramePoint(ContainerState state, float track) {

View File

@@ -15,6 +15,7 @@ namespace Cryville.Crtr {
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_current_time = IdentifierManager.SharedInstance.Request("current_time");
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");
static readonly int _var_null = IdentifierManager.SharedInstance.Request("null"); static readonly int _var_null = IdentifierManager.SharedInstance.Request("null");
@@ -34,6 +35,11 @@ namespace Cryville.Crtr {
var vec = ContextState.GetRawValue(id); var vec = ContextState.GetRawValue(id);
VectorSrc.Construct(() => vec).Get(out type, out value); VectorSrc.Construct(() => vec).Get(out type, out value);
} }
else if (ContextState != null && name == _var_current_time) {
LoadNum((float)ContextState.rootPrototype.Time);
type = PdtInternalType.Number;
value = _numbuf;
}
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);
RevokePotentialConstant(); RevokePotentialConstant();

View File

@@ -4,11 +4,13 @@ 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 RClip = Cryville.Crtr.Clip;
using RTargetString = Cryville.Common.Buffers.TargetString; using RTargetString = Cryville.Common.Buffers.TargetString;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public abstract class PropOp : PdtOperator { public abstract class PropOp : PdtOperator {
internal PropOp() : base(1) { } protected PropOp() : base(1) { }
protected PropOp(int pc) : base(pc) { }
public class Arbitrary : PropOp { public class Arbitrary : PropOp {
public int Name { get; set; } public int Name { get; set; }
protected override void Execute() { protected override void Execute() {
@@ -25,6 +27,15 @@ namespace Cryville.Crtr {
_cb(GetOperand(0).AsNumber() > 0); _cb(GetOperand(0).AsNumber() > 0);
} }
} }
public class Clip : PropOp {
readonly Action<RClip> _cb;
public Clip(Action<RClip> cb) : base(2) { _cb = cb; }
protected override void Execute() {
if (LoadedOperandCount < 2)
throw new ArgumentException("Invalid clip syntax");
_cb(new RClip(GetOperand(0).AsNumber(), GetOperand(1).AsNumber()));
}
}
public class Integer : PropOp { public class Integer : PropOp {
readonly Action<int> _cb; readonly Action<int> _cb;
public Integer(Action<int> cb) { _cb = cb; } public Integer(Action<int> cb) { _cb = cb; }

View File

@@ -17,6 +17,15 @@ namespace Cryville.Crtr {
value = buf; value = buf;
} }
protected abstract void InternalGet(); protected abstract void InternalGet();
public abstract class FixedBuffer : PropSrc {
bool m_invalidated = true;
protected override bool Invalidated { get { return m_invalidated; } }
public override void Invalidate() { m_invalidated = true; }
public FixedBuffer(int type, int size) : base(type) { buf = new byte[size]; }
protected override void InternalGet() {
m_invalidated = false;
}
}
public class Arbitrary : PropSrc { public class Arbitrary : PropSrc {
readonly byte[] _value; readonly byte[] _value;
public Arbitrary(int type, byte[] value) : base(type) { public Arbitrary(int type, byte[] value) : base(type) {
@@ -26,25 +35,19 @@ namespace Cryville.Crtr {
buf = _value; buf = _value;
} }
} }
public class Boolean : PropSrc { public class Boolean : FixedBuffer {
readonly Func<bool> _cb; readonly Func<bool> _cb;
bool m_invalidated = true; public Boolean(Func<bool> cb) : base(PdtInternalType.Number, 4) { _cb = cb; }
protected override bool Invalidated { get { return m_invalidated; } }
public override void Invalidate() { m_invalidated = true; }
public Boolean(Func<bool> cb) : base(PdtInternalType.Number) { _cb = cb; buf = new byte[4]; }
protected override void InternalGet() { protected override void InternalGet() {
m_invalidated = false; base.InternalGet();
buf[0] = _cb() ? (byte)1 : (byte)0; buf[0] = _cb() ? (byte)1 : (byte)0;
} }
} }
public class Float : PropSrc { public class Float : FixedBuffer {
readonly Func<float> _cb; readonly Func<float> _cb;
bool m_invalidated = true; public Float(Func<float> cb) : base(PdtInternalType.Number, 4) { _cb = cb; }
protected override bool Invalidated { get { return m_invalidated; } }
public override void Invalidate() { m_invalidated = true; }
public Float(Func<float> cb) : base(PdtInternalType.Number) { _cb = cb; buf = new byte[4]; }
protected override unsafe void InternalGet() { protected override unsafe void InternalGet() {
m_invalidated = false; base.InternalGet();
fixed (byte* _ptr = buf) { fixed (byte* _ptr = buf) {
*(float*)_ptr = _cb(); *(float*)_ptr = _cb();
} }
@@ -65,19 +68,22 @@ namespace Cryville.Crtr {
} }
} }
} }
public class Identifier : PropSrc { public class Identifier : FixedBuffer {
readonly Func<int> _cb; readonly Func<int> _cb;
public Identifier(Func<int> cb) : base(PdtInternalType.Undefined) { _cb = cb; } public Identifier(Func<int> cb) : base(PdtInternalType.Undefined, 4) { _cb = cb; }
protected override void InternalGet() { protected override unsafe void InternalGet() {
buf = BitConverter.GetBytes(_cb()); base.InternalGet();
fixed (byte* _ptr = buf) {
*(int*)_ptr = _cb();
}
} }
} }
public class BeatTime : PropSrc { public class BeatTime : FixedBuffer {
readonly Func<RBeatTime> _cb; readonly Func<RBeatTime> _cb;
public BeatTime(Func<RBeatTime> cb) : base(PdtInternalType.Vector) { _cb = cb; } public BeatTime(Func<RBeatTime> cb) : base(PdtInternalType.Vector, 4 * sizeof(int)) { _cb = cb; }
protected override unsafe void InternalGet() { protected override unsafe void InternalGet() {
base.InternalGet();
var bt = _cb(); var bt = _cb();
buf = new byte[4 * sizeof(int)];
fixed (byte* _ptr = buf) { fixed (byte* _ptr = buf) {
int* ptr = (int*)_ptr; int* ptr = (int*)_ptr;
*ptr++ = bt.b; *ptr++ = bt.b;

View File

@@ -25,7 +25,7 @@ namespace Cryville.Crtr {
public void LoadPdt(DirectoryInfo dir) { public void LoadPdt(DirectoryInfo dir) {
using (StreamReader pdtreader = new StreamReader(dir.FullName + "/" + data + ".pdt", Encoding.UTF8)) { using (StreamReader pdtreader = new StreamReader(dir.FullName + "/" + data + ".pdt", Encoding.UTF8)) {
var src = pdtreader.ReadToEnd(); var src = pdtreader.ReadToEnd();
Root = new RulesetInterpreter(src, null).Interpret(); Root = (PdtRuleset)new RulesetInterpreter(src, null).Interpret();
} }
} }
} }
@@ -150,9 +150,9 @@ namespace Cryville.Crtr {
ChartPlayer.etor.Evaluate(new PropOp.String(r => result = r), exp); ChartPlayer.etor.Evaluate(new PropOp.String(r => result = r), exp);
return result; return result;
} }
else if (type.Equals(typeof(float[]))) { else if (type.Equals(typeof(Clip))) {
float[] result = null; Clip result = default(Clip);
ChartPlayer.etor.Evaluate(new pop_numarr(r => result = r), exp); ChartPlayer.etor.Evaluate(new PropOp.Clip(r => result = r), exp);
return result; return result;
} }
else if (type.Equals(typeof(Identifier))) { else if (type.Equals(typeof(Identifier))) {
@@ -182,17 +182,6 @@ namespace Cryville.Crtr {
return base.ChangeType(value, type, culture); return base.ChangeType(value, type, culture);
} }
#pragma warning disable IDE1006 #pragma warning disable IDE1006
class pop_numarr : PdtOperator {
readonly Action<float[]> _cb;
public pop_numarr(Action<float[]> cb) : base(16) { _cb = cb; }
protected override void Execute() {
var result = new float[LoadedOperandCount];
for (int i = 0; i < LoadedOperandCount; i++) {
result[i] = GetOperand(i).AsNumber();
}
_cb(result);
}
}
class pop_identstr : PropOp { class pop_identstr : PropOp {
readonly Action<SIdentifier> _cb; readonly Action<SIdentifier> _cb;
public pop_identstr(Action<SIdentifier> cb) { _cb = cb; } public pop_identstr(Action<SIdentifier> cb) { _cb = cb; }

View File

@@ -4,8 +4,8 @@ using System.Collections.Generic;
using System.Reflection; using System.Reflection;
namespace Cryville.Crtr { namespace Cryville.Crtr {
internal class RulesetInterpreter : PdtInterpreter<PdtRuleset> { internal class RulesetInterpreter : PdtInterpreter {
public RulesetInterpreter(string src, Binder binder) : base(src, binder) { } public RulesetInterpreter(string src, Binder binder) : base(src, typeof(PdtRuleset), binder) { }
readonly List<RulesetSelector> s = new List<RulesetSelector>(); readonly List<RulesetSelector> s = new List<RulesetSelector>();
readonly List<string> a = new List<string>(); readonly List<string> a = new List<string>();

View File

@@ -1,13 +1,8 @@
using Cryville.Common;
using Cryville.Common.Pdt; using Cryville.Common.Pdt;
using Cryville.Crtr.Browsing; using Cryville.Crtr.Browsing;
using Cryville.Crtr.Components;
using Newtonsoft.Json; using Newtonsoft.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.Reflection;
using System.Text; using System.Text;
namespace Cryville.Crtr { namespace Cryville.Crtr {
@@ -30,14 +25,13 @@ namespace Cryville.Crtr {
public void LoadPdt(DirectoryInfo dir) { public void LoadPdt(DirectoryInfo dir) {
using (StreamReader pdtreader = new StreamReader(dir.FullName + "/" + data + ".pdt", Encoding.UTF8)) { using (StreamReader pdtreader = new StreamReader(dir.FullName + "/" + data + ".pdt", Encoding.UTF8)) {
var src = pdtreader.ReadToEnd(); var src = pdtreader.ReadToEnd();
Root = new SkinInterpreter(src, null).Interpret(); Root = (PdtSkin)new SkinInterpreter(src, null).Interpret();
} }
} }
} }
public class PdtSkin : SkinElement { } public class PdtSkin : SkinElement { }
[Binder(typeof(SkinElementBinder))]
public class SkinElement { public class SkinElement {
[ElementList] [ElementList]
public Dictionary<SkinSelectors, SkinElement> elements public Dictionary<SkinSelectors, SkinElement> elements
@@ -67,36 +61,4 @@ namespace Cryville.Crtr {
} }
} }
} }
public struct SkinPropertyKey {
public Type Component;
public int Name;
}
public class SkinElementBinder : EmptyBinder {
public override object ChangeType(object value, Type type, CultureInfo culture) {
if (value is string && type == typeof(SkinPropertyKey)) {
var cp = ((string)value).Split('.');
switch (cp.Length) {
case 1:
var key = cp[0];
if (key[0] == '*')
return new SkinPropertyKey { Component = GetComponentByName(key.Substring(1)) };
else
return new SkinPropertyKey { Component = typeof(TransformInterface), Name = IdentifierManager.SharedInstance.Request(key) };
case 2:
return new SkinPropertyKey { Component = GetComponentByName(cp[0]), Name = IdentifierManager.SharedInstance.Request(cp[1]) };
}
}
return base.ChangeType(value, type, culture);
}
static readonly char[] nssep = new char[]{':'};
Type GetComponentByName(string name) {
var nstuple = name.Split(nssep, 2);
var ns = nssep.Length == 2 ? nstuple[0] : "generic";
name = nssep.Length == 2 ? nstuple[1] : nstuple[0];
if (ns == "generic")
return GenericResources.Components[name];
throw new ArgumentException(string.Format("Component type {0} not found", name));
}
}
} }

View File

@@ -1,8 +1,5 @@
using Cryville.Common;
using Cryville.Common.Pdt; using Cryville.Common.Pdt;
using Cryville.Crtr.Components;
using Cryville.Crtr.Event; using Cryville.Crtr.Event;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.Profiling; using UnityEngine.Profiling;
@@ -10,13 +7,20 @@ using UnityEngine.Profiling;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class SkinContainer { public class SkinContainer {
readonly PdtSkin skin; readonly PdtSkin skin;
readonly List<DynamicProperty> dynprops = new List<DynamicProperty>(); readonly DynamicStack[] _stacks = new DynamicStack[2];
class DynamicStack {
public readonly List<DynamicProperty> Properties = new List<DynamicProperty>();
public readonly List<DynamicElement> Elements = new List<DynamicElement>();
public void Clear() {
Properties.Clear();
Elements.Clear();
}
}
struct DynamicProperty { struct DynamicProperty {
public RuntimeSkinContext Context { get; set; } public RuntimeSkinContext Context { get; set; }
public SkinPropertyKey Key { get; set; } public SkinPropertyKey Key { get; set; }
public PdtExpression Value { get; set; } public PdtExpression Value { get; set; }
} }
readonly List<DynamicElement> dynelems = new List<DynamicElement>();
struct DynamicElement { struct DynamicElement {
public RuntimeSkinContext Context { get; set; } public RuntimeSkinContext Context { get; set; }
public SkinSelectors Selectors { get; set; } public SkinSelectors Selectors { get; set; }
@@ -24,68 +28,73 @@ namespace Cryville.Crtr {
} }
public SkinContainer(PdtSkin _skin) { public SkinContainer(PdtSkin _skin) {
skin = _skin; skin = _skin;
for (int i = 0; i < _stacks.Length; i++) _stacks[i] = new DynamicStack();
} }
public void MatchStatic(ContainerState state) { public void MatchStatic(ContainerState state) {
dynprops.Clear(); dynelems.Clear(); var stack = _stacks[0];
stack.Clear();
ChartPlayer.etor.ContextState = state; ChartPlayer.etor.ContextState = state;
ChartPlayer.etor.ContextEvent = state.Container; ChartPlayer.etor.ContextEvent = state.Container;
MatchStatic(skin, state, new RuntimeSkinContext(state.Handler.SkinContext)); MatchStatic(skin, state, stack, new RuntimeSkinContext(state.Handler.SkinContext));
ChartPlayer.etor.ContextEvent = null; ChartPlayer.etor.ContextEvent = null;
ChartPlayer.etor.ContextState = null; ChartPlayer.etor.ContextState = null;
} }
void MatchStatic(SkinElement rel, ContainerState state, RuntimeSkinContext ctx) { void MatchStatic(SkinElement rel, ContainerState state, DynamicStack stack, RuntimeSkinContext ctx) {
var rc = ctx.ReadContext; var rc = ctx.ReadContext;
ChartPlayer.etor.ContextTransform = rc.Transform; ChartPlayer.etor.ContextTransform = rc.Transform;
if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeInsert(rc.PropSrcs); if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeInsert(rc.PropSrcs);
foreach (var p in rel.properties) { foreach (var p in rel.properties) {
if (p.Key.Name == 0) p.Key.ExecuteStatic(state, ctx, p.Value);
rc.Transform.gameObject.AddComponent(p.Key.Component); if (p.Key.IsValueRequired && !p.Value.IsConstant) stack.Properties.Add(
else { new DynamicProperty { Context = ctx, Key = p.Key, Value = p.Value }
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; ChartPlayer.etor.ContextTransform = null;
foreach (var r in rel.elements) { foreach (var e in rel.elements) {
try { try {
var nctxs = r.Key.MatchStatic(state, rc); var nctxs = e.Key.MatchStatic(state, rc);
var roflag = r.Key.annotations.Contains("if"); if (nctxs != null) {
var woflag = r.Key.annotations.Contains("then"); var roflag = e.Key.annotations.Contains("if");
foreach (var nctx in nctxs) { var woflag = e.Key.annotations.Contains("then");
var nrctx = new RuntimeSkinContext(nctx, ctx, roflag, woflag); foreach (var nctx in nctxs) {
MatchStatic(r.Value, state, nrctx); var nrctx = new RuntimeSkinContext(nctx, ctx, roflag, woflag);
MatchStatic(e.Value, state, stack, nrctx);
}
} }
} }
catch (SelectorNotStaticException) { catch (SelectorNotAvailableException) {
dynelems.Add( stack.Elements.Add(
new DynamicElement { Context = ctx, Selectors = r.Key, Element = r.Value } new DynamicElement { Context = ctx, Selectors = e.Key, Element = e.Value }
); );
} }
} }
if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeDiscard(); if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
} }
public void MatchDynamic(ContainerState state) { public void MatchDynamic(ContainerState state) {
if (dynprops.Count == 0 && dynelems.Count == 0) return; var stack = _stacks[state.CloneType >> 1];
var nstack = (state.CloneType >> 1) + 1 < _stacks.Length ? _stacks[(state.CloneType >> 1) + 1] : null;
if (nstack != null) nstack.Clear();
if (stack.Properties.Count == 0 && stack.Elements.Count == 0) return;
Profiler.BeginSample("SkinContainer.MatchDynamic"); Profiler.BeginSample("SkinContainer.MatchDynamic");
ChartPlayer.etor.ContextState = state; ChartPlayer.etor.ContextState = state;
ChartPlayer.etor.ContextEvent = state.Container; ChartPlayer.etor.ContextEvent = state.Container;
for (int i = 0; i < dynprops.Count; i++) { for (int i = 0; i < stack.Properties.Count; i++) {
DynamicProperty p = dynprops[i]; DynamicProperty p = stack.Properties[i];
var psrcs = p.Context.ReadContext.PropSrcs; p.Key.ExecuteDynamic(state, p.Context, p.Value);
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++) { for (int i = 0; i < stack.Elements.Count; i++) {
DynamicElement e = dynelems[i]; DynamicElement e = stack.Elements[i];
var psrcs = e.Context.ReadContext.PropSrcs; var psrcs = e.Context.ReadContext.PropSrcs;
if (psrcs != null) ChartPlayer.etor.ContextCascadeInsert(psrcs); if (psrcs != null) ChartPlayer.etor.ContextCascadeInsert(psrcs);
var nctx = e.Selectors.MatchDynamic(state, e.Context.ReadContext); SkinContext nctx = null;
if (nctx != null) MatchDynamic(e.Element, state, new RuntimeSkinContext( try {
nctx = e.Selectors.MatchDynamic(state, e.Context.ReadContext);
}
catch (SelectorNotAvailableException) {
if (nstack == null) throw;
nstack.Elements.Add(e);
}
if (nctx != null) MatchDynamic(e.Element, state, nstack, new RuntimeSkinContext(
nctx, e.Context, e.Selectors.annotations.Contains("if"), e.Selectors.annotations.Contains("then") nctx, e.Context, e.Selectors.annotations.Contains("if"), e.Selectors.annotations.Contains("then")
)); ));
if (psrcs != null) ChartPlayer.etor.ContextCascadeDiscard(); if (psrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
@@ -94,42 +103,30 @@ namespace Cryville.Crtr {
ChartPlayer.etor.ContextState = null; ChartPlayer.etor.ContextState = null;
Profiler.EndSample(); Profiler.EndSample();
} }
void MatchDynamic(SkinElement rel, ContainerState state, RuntimeSkinContext ctx) { void MatchDynamic(SkinElement rel, ContainerState state, DynamicStack stack, RuntimeSkinContext ctx) {
var rc = ctx.ReadContext; var rc = ctx.ReadContext;
ChartPlayer.etor.ContextTransform = rc.Transform; ChartPlayer.etor.ContextTransform = rc.Transform;
if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeInsert(rc.PropSrcs); if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeInsert(rc.PropSrcs);
foreach (var p in rel.properties) { foreach (var p in rel.properties) {
if (p.Key.Name == 0) p.Key.ExecuteDynamic(state, ctx, p.Value);
throw new InvalidOperationException("Component creation in dynamic context is not allowed");
var prop = GetPropOp(ctx.WriteTransform, p.Key);
if (state.CloneType > prop.UpdateCloneType) continue;
ChartPlayer.etor.Evaluate(prop.Operator, p.Value);
} }
ChartPlayer.etor.ContextTransform = null; ChartPlayer.etor.ContextTransform = null;
foreach (var r in rel.elements) { foreach (var e in rel.elements) {
if (!r.Key.IsUpdatable(state)) continue; if (e.Key.IsUpdatable(state)) {
var nctx = r.Key.MatchDynamic(state, rc); SkinContext nctx = e.Key.MatchDynamic(state, rc);
if (nctx != null) MatchDynamic(r.Value, state, new RuntimeSkinContext( if (nctx != null) MatchDynamic(e.Value, state, stack, new RuntimeSkinContext(
nctx, ctx, r.Key.annotations.Contains("if"), r.Key.annotations.Contains("then") nctx, ctx, e.Key.annotations.Contains("if"), e.Key.annotations.Contains("then")
)); ));
}
else {
if (stack == null) throw new SelectorNotAvailableException();
stack.Elements.Add(
new DynamicElement { Context = ctx, Selectors = e.Key, Element = e.Value }
);
}
} }
if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeDiscard(); if (rc.PropSrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
} }
SkinProperty GetPropOp(Transform obj, SkinPropertyKey key) {
var ctype = key.Component;
var comp = (SkinComponent)obj.GetComponent(ctype);
if (comp == null) throw new InvalidOperationException(string.Format(
"Trying to set property {0} but the component is not found",
IdentifierManager.SharedInstance.Retrieve(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;
}
} }
public class SkinContext { public class SkinContext {
public Transform Transform { get; private set; } public Transform Transform { get; private set; }

View File

@@ -1,17 +1,20 @@
using Cryville.Common.Pdt; using Cryville.Common;
using Cryville.Common.Pdt;
using Cryville.Crtr.Components;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
namespace Cryville.Crtr { namespace Cryville.Crtr {
public class SkinInterpreter : PdtInterpreter<PdtSkin> { public class SkinInterpreter : PdtInterpreter {
public SkinInterpreter(string src, Binder binder) : base(src, binder) { } public SkinInterpreter(string src, Binder binder) : base(src, typeof(PdtSkin), binder) { }
readonly List<SkinSelector> s = new List<SkinSelector>(); readonly List<SkinSelector> s = new List<SkinSelector>();
readonly List<string> a = new List<string>(); readonly HashSet<string> a = new HashSet<string>();
readonly List<string> k = new List<string>(2);
protected override object InterpretKey(Type type) { protected override object InterpretKey(Type type) {
s.Clear(); a.Clear(); s.Clear(); a.Clear(); k.Clear();
string key = ""; bool invalidKeyFlag = false, compKeyFlag = false;
while (true) { while (true) {
int pp = Position; int pp = Position;
switch (cc) { switch (cc) {
@@ -22,19 +25,22 @@ namespace Cryville.Crtr {
case '$': case '$':
GetChar(); GetChar();
s.Add(new SkinSelector.CreateObject()); s.Add(new SkinSelector.CreateObject());
key = null; invalidKeyFlag = true;
break; break;
case '.': case '.':
GetChar(); GetChar();
if (cc == '.') { if (cc == '.') {
GetChar(); GetChar();
s.Add(new SkinSelector.AtAnchor(GetIdentifier())); s.Add(new SkinSelector.AtAnchor(GetIdentifier()));
key = null; invalidKeyFlag = true;
} }
else { else {
var p3 = GetIdentifier(); var p3 = GetIdentifier();
s.Add(new SkinSelector.Anchor(p3)); s.Add(new SkinSelector.Anchor(p3));
if (key != null) key += "." + p3; if (!invalidKeyFlag) {
if (k.Count != 1) invalidKeyFlag = true;
else k.Add(p3);
}
} }
break; break;
case '>': case '>':
@@ -43,24 +49,61 @@ namespace Cryville.Crtr {
break; break;
case ';': case ';':
case ':': case ':':
return key; if (invalidKeyFlag) throw new FormatException("Invalid key format");
if (a.Contains("has")) {
if (k.Count != 1) throw new FormatException("Invalid anchor name");
return new SkinPropertyKey.CreateAnchor {
Name = IdentifierManager.SharedInstance.Request(k[0])
};
}
else if (a.Contains("at")) {
if (k.Count != 1) throw new FormatException("Invalid anchor name");
return new SkinPropertyKey.SetAnchor {
Name = IdentifierManager.SharedInstance.Request(k[0])
};
}
switch (k.Count) {
case 1:
if (compKeyFlag) return new SkinPropertyKey.CreateComponent {
Component = GetComponentByName(k[0])
};
else return new SkinPropertyKey.SetProperty {
Component = typeof(TransformInterface),
Name = IdentifierManager.SharedInstance.Request(k[0])
};
case 2:
return new SkinPropertyKey.SetProperty {
Component = GetComponentByName(k[0]),
Name = IdentifierManager.SharedInstance.Request(k[1])
};
default:
throw new FormatException("Unknown error"); // Unreachable
}
case '{': case '{':
return new SkinSelectors(s, a); return new SkinSelectors(s, a);
case '}': case '}':
return null; return null;
case '*': case '*':
GetChar(); GetChar();
key += "*"; compKeyFlag = true;
break; break;
default: default:
var p4 = GetIdentifier(); var p4 = GetIdentifier();
s.Add(new SkinSelector.ElementType(p4)); s.Add(new SkinSelector.ElementType(p4));
if (key != null) key += p4; if (!invalidKeyFlag) {
if (k.Count != 0) invalidKeyFlag = true;
else k.Add(p4);
}
break; break;
} }
ws(); ws();
if (Position == pp) throw new FormatException("Invalid selector or key format"); if (Position == pp) throw new FormatException("Invalid selector or key format");
} }
} }
static Type GetComponentByName(string name) {
Type result;
if (GenericResources.Components.TryGetValue(name, out result)) return result;
throw new ArgumentException(string.Format("Component type \"{0}\" not found", name));
}
} }
} }

View File

@@ -0,0 +1,101 @@
using Cryville.Common;
using Cryville.Common.Pdt;
using Cryville.Crtr.Components;
using Cryville.Crtr.Event;
using System;
using UnityEngine;
namespace Cryville.Crtr {
public abstract class SkinPropertyKey {
public abstract override string ToString();
public abstract bool IsValueRequired { get; }
public abstract void ExecuteStatic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp);
public abstract void ExecuteDynamic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp);
public class CreateComponent : SkinPropertyKey {
public Type Component { get; set; }
public override string ToString() {
return string.Format("*{0}", Component.Name);
}
public override bool IsValueRequired { get { return false; } }
public override void ExecuteStatic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
ctx.ReadContext.Transform.gameObject.AddComponent(Component);
}
public override void ExecuteDynamic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
throw new InvalidOperationException("Component creation in dynamic context is not allowed");
}
}
public class SetProperty : SkinPropertyKey {
public Type Component { get; set; }
public int Name { get; set; }
public override string ToString() {
return string.Format("{0}.{1}", Component.Name, IdentifierManager.SharedInstance.Retrieve(Name));
}
public override bool IsValueRequired { get { return true; } }
public override void ExecuteStatic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
Execute(ctx, GetPropOp(ctx.WriteTransform).Operator, exp);
}
public override void ExecuteDynamic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
var prop = GetPropOp(ctx.WriteTransform);
if (state.CloneType > prop.UpdateCloneType) return;
Execute(ctx, prop.Operator, exp);
}
void Execute(RuntimeSkinContext ctx, PdtOperator op, PdtExpression exp) {
var psrcs = ctx.ReadContext.PropSrcs;
if (psrcs != null) ChartPlayer.etor.ContextCascadeInsert(psrcs);
ChartPlayer.etor.Evaluate(op, exp);
if (psrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
}
SkinProperty GetPropOp(Transform obj) {
var ctype = Component;
var comp = (SkinComponent)obj.GetComponent(ctype);
if (comp == null) throw new InvalidOperationException(string.Format(
"Trying to set property \"{0}\" but the component is not found",
IdentifierManager.SharedInstance.Retrieve(Name)
));
SkinProperty result;
if (!comp.Properties.TryGetValue(Name, out result))
throw new InvalidOperationException(string.Format(
"Property \"{0}\" not found on component",
IdentifierManager.SharedInstance.Retrieve(Name)
));
return result;
}
}
public class CreateAnchor : SkinPropertyKey {
public int Name { get; set; }
public override string ToString() {
return string.Format("@has {0}", IdentifierManager.SharedInstance.Retrieve(Name));
}
public override bool IsValueRequired { get { return false; } }
public override void ExecuteStatic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
state.Handler.RegisterAnchor(Name, true);
}
public override void ExecuteDynamic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
throw new InvalidOperationException("Anchor creation in dynamic context is not allowed");
}
}
public class SetAnchor : SkinPropertyKey {
public int Name { get; set; }
public SetAnchor() {
_timeOp = new PropOp.Float(v => _time = v);
}
public override string ToString() {
return string.Format("@at {0}", IdentifierManager.SharedInstance.Retrieve(Name));
}
public override bool IsValueRequired { get { return true; } }
public override void ExecuteStatic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
throw new InvalidOperationException("Setting anchor in static context is not allowed");
}
float _time;
readonly PropOp _timeOp;
public override void ExecuteDynamic(ContainerState state, RuntimeSkinContext ctx, PdtExpression exp) {
if (state.CloneType > 1) return;
var psrcs = ctx.ReadContext.PropSrcs;
if (psrcs != null) ChartPlayer.etor.ContextCascadeInsert(psrcs);
ChartPlayer.etor.Evaluate(_timeOp, exp);
if (psrcs != null) ChartPlayer.etor.ContextCascadeDiscard();
state.Handler.PushAnchorEvent(_time, Name);
}
}
}
}

View File

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

View File

@@ -23,8 +23,8 @@ namespace Cryville.Crtr {
bool flag = false; bool flag = false;
string r = ""; string r = "";
foreach (var a in annotations) { foreach (var a in annotations) {
if (flag) r += " " + a; if (flag) r += " @" + a;
else { r += a; flag = true; } else { r += "@" + a; flag = true; }
} }
foreach (var s in selectors) { foreach (var s in selectors) {
if (flag) r += " " + s.ToString(); if (flag) r += " " + s.ToString();
@@ -60,14 +60,18 @@ namespace Cryville.Crtr {
public abstract class SkinSelector { public abstract class SkinSelector {
protected SkinSelector() { } protected SkinSelector() { }
public abstract override string ToString();
public virtual void Optimize(PdtEvaluatorBase etor) { } public virtual void Optimize(PdtEvaluatorBase etor) { }
public virtual IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) { throw new SelectorNotStaticException(); } public virtual IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) { throw new SelectorNotAvailableException(); }
public virtual SkinContext MatchDynamic(ContainerState h, SkinContext c) { throw new NotSupportedException(); } 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 string ToString() { return "$"; }
public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
var obj = new GameObject("__obj__"); var obj = new GameObject("__obj__");
obj.transform.SetParent(c.Transform, false); obj.transform.SetParent(c.Transform, false);
@@ -80,6 +84,7 @@ namespace Cryville.Crtr {
public Anchor(string name) { public Anchor(string name) {
Name = IdentifierManager.SharedInstance.Request(name); Name = IdentifierManager.SharedInstance.Request(name);
} }
public override string ToString() { return string.Format(".{0}", IdentifierManager.SharedInstance.Retrieve(Name)); }
public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
List<CAnchor> anchors; List<CAnchor> anchors;
@@ -88,20 +93,19 @@ namespace Cryville.Crtr {
} }
else return Enumerable.Empty<SkinContext>(); else return Enumerable.Empty<SkinContext>();
} }
public override bool IsUpdatable(ContainerState h) {
return h.Handler.OpenedAnchor != null && h.Handler.OpenedAnchor.Name == Name;
}
} }
public class AtAnchor : SkinSelector { public class AtAnchor : SkinSelector {
public int Name { get; private set; } public int Name { get; private set; }
public AtAnchor(string name) { public AtAnchor(string name) {
Name = IdentifierManager.SharedInstance.Request(name); Name = IdentifierManager.SharedInstance.Request(name);
} }
public override string ToString() { return string.Format("..{0}", IdentifierManager.SharedInstance.Retrieve(Name)); }
public override SkinContext MatchDynamic(ContainerState h, SkinContext c) { public override SkinContext MatchDynamic(ContainerState h, SkinContext c) {
return IsUpdatable(h) ? c : null; return h.Handler.OpenedAnchor != null && h.Handler.OpenedAnchor.Name == Name ? c : null;
} }
public override bool IsUpdatable(ContainerState h) { public override bool IsUpdatable(ContainerState h) {
return h.Handler.OpenedAnchor != null && h.Handler.OpenedAnchor.Name == Name; return h.CloneType >= 2;
} }
} }
public class Property : SkinSelector { public class Property : SkinSelector {
@@ -112,6 +116,8 @@ namespace Cryville.Crtr {
_exp = exp; _exp = exp;
_op = new PropOp.Boolean(v => _flag = v); _op = new PropOp.Boolean(v => _flag = v);
} }
public override string ToString() { return string.Format("> {{{0}}}", _exp); }
public override void Optimize(PdtEvaluatorBase etor) { public override void Optimize(PdtEvaluatorBase etor) {
etor.Optimize(_exp); etor.Optimize(_exp);
} }
@@ -121,41 +127,36 @@ namespace Cryville.Crtr {
else return Enumerable.Empty<SkinContext>(); else return Enumerable.Empty<SkinContext>();
} }
public override SkinContext MatchDynamic(ContainerState h, SkinContext c) { public override SkinContext MatchDynamic(ContainerState h, SkinContext c) {
return Match(c, true); return Match(c);
} }
public SkinContext Match(SkinContext a, bool dyn = false) { public SkinContext Match(SkinContext a) {
ChartPlayer.etor.ContextTransform = a.Transform; ChartPlayer.etor.ContextTransform = a.Transform;
try { try {
ChartPlayer.etor.Evaluate(_op, _exp); ChartPlayer.etor.Evaluate(_op, _exp);
return _flag ? a : null; return _flag ? a : null;
} }
catch (Exception) { catch (Exception ex) {
if (dyn) throw; throw new SelectorNotAvailableException("The expression is not evaluatable under the current context", ex);
else throw new SelectorNotStaticException();
} }
finally { finally {
ChartPlayer.etor.ContextTransform = null; ChartPlayer.etor.ContextTransform = null;
} }
} }
} }
public class State : SkinSelector {
public State(string state) { }
public override SkinContext MatchDynamic(ContainerState h, SkinContext c) {
return null;
}
}
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 string ToString() { return _type; }
public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) { public override IEnumerable<SkinContext> MatchStatic(ContainerState h, SkinContext c) {
return h.Handler.TypeName == _type ? new SkinContext[] { c } : Enumerable.Empty<SkinContext>(); return h.Handler.TypeName == _type ? new SkinContext[] { c } : Enumerable.Empty<SkinContext>();
} }
} }
} }
public class SelectorNotStaticException : Exception { public class SelectorNotAvailableException : Exception {
public SelectorNotStaticException() : base("The selector is not static") { } public SelectorNotAvailableException() : base("The selector is not available under the current context") { }
public SelectorNotStaticException(string message) : base(message) { } public SelectorNotAvailableException(string message) : base(message) { }
public SelectorNotStaticException(string message, Exception innerException) : base(message, innerException) { } public SelectorNotAvailableException(string message, Exception innerException) : base(message, innerException) { }
protected SelectorNotStaticException(SerializationInfo info, StreamingContext context) : base(info, context) { } protected SelectorNotAvailableException(SerializationInfo info, StreamingContext context) : base(info, context) { }
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using CAnchor = Cryville.Crtr.Anchor; using CAnchor = Cryville.Crtr.Anchor;
namespace Cryville.Crtr { namespace Cryville.Crtr {
@@ -9,9 +8,7 @@ namespace Cryville.Crtr {
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> Coevents; public List<StampedEvent> Coevents;
private StampedEvent relev = null;
public double Duration { public double Duration {
get { get {
@@ -29,17 +26,38 @@ namespace Cryville.Crtr {
} }
} }
public class Anchor : StampedEvent { public class Temporary : StampedEvent, IComparable<Temporary> {
public CAnchor Target; public bool CanDiscard;
public override int Priority { public int CompareTo(Temporary other) {
get { return 0; } return base.CompareTo(other);
} }
} }
public class Anchor : Temporary {
public CAnchor Target;
int m_priority;
public override int Priority { get { return m_priority; } }
public void SetPriority(int value) { m_priority = value; }
}
public class ClipBehind : StampedEvent {
public override int Priority {
get { return Origin.Priority - 0x8000; }
}
}
public class ClipAhead : StampedEvent {
public override int Priority {
get { return 0x7fff - Origin.Priority; }
}
}
StampedEvent relev = null;
public StampedEvent ReleaseEvent { public StampedEvent ReleaseEvent {
get { get { return relev; }
if (relev == null) relev = Subevents.FirstOrDefault(ev => ((InstantEvent)ev.Unstamped).IsRelease); set {
return relev; if (relev != null) throw new InvalidOperationException("Release event already set");
relev = value;
} }
} }

View File

@@ -12,11 +12,7 @@ namespace Cryville.Crtr {
this.gh = gh; this.gh = gh;
} }
public override string TypeName { public override string TypeName { get { return "track"; } }
get {
return "track";
}
}
public override void Init() { public override void Init() {
base.Init(); base.Init();
@@ -25,34 +21,37 @@ namespace Cryville.Crtr {
SectionalGameObject[] sgos; SectionalGameObject[] sgos;
Vector3 bpos; Quaternion brot; Vector3 bpos; Quaternion brot;
Vector3 spos; Vector3 spos;
protected override void PreAwake(ContainerState s) { public override void StartPhysicalUpdate(ContainerState s) {
base.PreAwake(s); base.StartPhysicalUpdate(s);
if (CanDoGraphicalUpdate(s)) {
TransformAwake(s);
}
}
public override void StartPreGraphicalUpdate(ContainerState s) {
base.StartPreGraphicalUpdate(s);
TransformAwake(s);
}
public override void StartGraphicalUpdate(ContainerState s) {
base.StartGraphicalUpdate(s);
if (gogroup) {
TransformAwake(s);
var p = GetCurrentWorldPoint();
foreach (var i in sgos) {
i.Reset();
i.AppendPoint(p, s.QuatDir);
}
}
}
void TransformAwake(ContainerState s) {
pwp = Vector3.zero; pwp = Vector3.zero;
cpt = s.ScreenPoint; cpt = s.ScreenPoint;
ptime = s.Time; ptime = s.Time;
if (s.CloneType == 2) { if (s.CloneType == 3) {
#if UNITY_5_6_OR_NEWER
a_head.Transform.SetPositionAndRotation(GetCurrentWorldPoint(), Quaternion.Euler(s.Direction));
#else
a_head.Transform.position = GetCurrentWorldPoint();
a_head.Transform.rotation = Quaternion.Euler(s.Direction);
#endif
}
else if (s.CloneType == 3) {
spos = Vector3.zero; spos = Vector3.zero;
bpos = cpt; bpos = cpt;
brot = Quaternion.Euler(s.Direction); brot = Quaternion.Euler(s.Direction);
} }
} }
protected override void Awake(ContainerState s) {
base.Awake(s);
if (!gogroup) return;
var p = GetCurrentWorldPoint();
foreach (var i in sgos) {
i.Reset();
i.AppendPoint(p, s.QuatDir);
}
}
Vector3 cpt; // Current point Vector3 cpt; // Current point
Vector3 ppt = Vector3.zero; // Previous point Vector3 ppt = Vector3.zero; // Previous point
@@ -62,7 +61,7 @@ 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 == 2 || s.CloneType == 3) { if (CanDoGraphicalUpdate(s)) {
var tpt = s.ScreenPoint; var tpt = s.ScreenPoint;
var tsv = s.ScrollVelocity; var tsv = s.ScrollVelocity;
@@ -106,24 +105,14 @@ namespace Cryville.Crtr {
spos = bpos - GetCurrentWorldPoint(); spos = bpos - GetCurrentWorldPoint();
} }
public override void EndUpdate(ContainerState s) { public override void EndGraphicalUpdate(ContainerState s) {
base.EndUpdate(s); base.EndGraphicalUpdate(s);
if (s.CloneType == 0 || s.CloneType == 2) { EndUpdatePosition(s);
EndUpdatePosition(ts); var p = GetCurrentWorldPoint();
var p = GetCurrentWorldPoint(); foreach (var i in sgos) {
foreach (var i in sgos) { i.AppendPoint(p, s.QuatDir);
i.AppendPoint(p, s.QuatDir); i.Seal();
i.Seal();
}
#if UNITY_5_6_OR_NEWER
a_tail.Transform.SetPositionAndRotation(GetCurrentWorldPoint(), Quaternion.Euler(ts.Direction));
#else
a_tail.Transform.position = GetCurrentWorldPoint();
a_tail.Transform.rotation = Quaternion.Euler(ts.Direction);
#endif
} }
else if (s.CloneType == 3) EndUpdatePosition(ns);
else if (s.CloneType >= 16) EndUpdatePosition(ps);
} }
void EndUpdatePosition(ContainerState s) { void EndUpdatePosition(ContainerState s) {

View File

@@ -3,7 +3,9 @@
"rootNamespace": "", "rootNamespace": "",
"references": [ "references": [
"GUID:d8ea0e0da3ad53a45b65c912ffcacab0", "GUID:d8ea0e0da3ad53a45b65c912ffcacab0",
"GUID:5686e5ee69d0e084c843d61c240d7fdb" "GUID:5686e5ee69d0e084c843d61c240d7fdb",
"GUID:2922aa74af3b2854e81b8a8b286d8206",
"GUID:da293eebbcb9a4947a212534c52d1a32"
], ],
"includePlatforms": [], "includePlatforms": [],
"excludePlatforms": [], "excludePlatforms": [],

View File

@@ -27,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

Binary file not shown.

Binary file not shown.

View File

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

View File

@@ -0,0 +1,337 @@
// Copyright (c) 2023 Cryville
//
// This file contains an implementation of the stub for custom format string
// originally written by Michael Popoloski. Below is the original license.
//
// Copyright (c) 2015-2017 Michael Popoloski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace System.Text.Formatting {
// this file contains the custom numeric formatting routines split out from the Numeric.cs file
unsafe partial class Numeric {
static void NumberToCustomFormatString(StringBuffer formatter, ref Number number, StringView specifier, CachedCulture culture) {
// Special: Handle special values
switch (number.Scale) {
case ScaleInf: formatter.Append(number.Sign == 0 ? culture.PositiveInfinity : culture.NegativeInfinity); return;
case ScaleNaN: formatter.Append(culture.NaN); return;
}
// Iteration 1: Split by semicolon
int specifierPositiveEnd = IndexOfSectionSeparator(specifier);
int specifierNegativeStart = 0, specifierNegativeEnd, specifierZeroStart = 0;
if (specifierPositiveEnd == -1) {
specifierPositiveEnd = specifierNegativeEnd = specifier.Length;
}
else {
specifierNegativeStart = specifierPositiveEnd + 1;
specifierNegativeEnd = IndexOfSectionSeparator(specifier, specifierNegativeStart);
if (specifierNegativeEnd == -1) {
specifierNegativeEnd = specifier.Length;
}
else {
specifierZeroStart = specifierNegativeEnd + 1;
}
}
// Special: Handle zero
if (IsZero(ref number)) {
FormatCustomFormatString(formatter, ref number, null, specifier, specifierZeroStart, specifier.Length, culture);
return;
}
// Iteration 2: Divide and round number
int originalScale = number.Scale;
if (number.Sign == 0) ApplyDivisionAndPrecision(ref number, specifier, 0, specifierPositiveEnd);
else ApplyDivisionAndPrecision(ref number, specifier, specifierNegativeStart, specifierNegativeEnd);
// Iteration 3: Count; Iteration 4: Format
if (IsZero(ref number)) FormatCustomFormatString(formatter, ref number, null, specifier, specifierZeroStart, specifier.Length, culture);
else if (number.Sign == 0) FormatCustomFormatString(formatter, ref number, originalScale, specifier, 0, specifierPositiveEnd, culture);
else {
if (specifierNegativeStart == 0) formatter.Append(culture.NegativeSign);
FormatCustomFormatString(formatter, ref number, originalScale, specifier, specifierNegativeStart, specifierNegativeEnd, culture);
}
}
static int IndexOfSectionSeparator(StringView specifier) {
return IndexOfSectionSeparator(specifier, 0);
}
static int IndexOfSectionSeparator(StringView specifier, int index) {
if (index < 0 || index > specifier.Length) throw new ArgumentOutOfRangeException("index");
char* ptr = specifier.Data;
for (; index < specifier.Length; index++) {
switch (ptr[index]) {
case ';': return index;
case '\\':
index++;
if (index >= specifier.Length) throw new FormatException();
break;
case '\'':
SkipLiteral(specifier, ref index, '\'');
break;
case '"':
SkipLiteral(specifier, ref index, '"');
break;
}
}
return -1;
}
static bool IsZero(ref Number number) {
char* ptr = number.Digits;
while (*ptr != '\0') if (*ptr++ != '0') return false;
return true;
}
static void ApplyDivisionAndPrecision(ref Number number, StringView specifier, int index, int end) {
int deltaScale = 0, scalingSpecifiers = 0;
int integralDigits = 0, decimalDigits = 0;
bool decimalFlag = false, exponentialFlag = false;
char* ptr = specifier.Data;
for (; index < end; index++) {
switch (ptr[index]) {
case '\\':
if (++index >= end) throw new FormatException();
break;
case '\'':
SkipLiteral(specifier, ref index, '\'');
break;
case '"':
SkipLiteral(specifier, ref index, '"');
break;
case '0':
case '#':
if (decimalFlag) decimalDigits++;
else integralDigits++;
scalingSpecifiers = 0;
break;
case '.': decimalFlag = true; deltaScale -= scalingSpecifiers * 3; break;
case ',': scalingSpecifiers++; break;
case '%': deltaScale += 2; break;
case '‰': deltaScale += 3; break;
case 'E':
case 'e':
if (++index >= end) goto exit;
char tc0 = ptr[index];
if (tc0 == '+' || tc0 == '-') {
if (++index >= end) goto exit;
}
if (ptr[index] != '0') break;
exponentialFlag = true;
for (index++; index < end && ptr[index] == '0'; index++) ;
index--;
break;
}
}
exit:
if (exponentialFlag) {
number.Scale = integralDigits;
RoundNumber(ref number, integralDigits + decimalDigits);
}
else {
number.Scale += deltaScale;
RoundNumber(ref number, number.Scale + decimalDigits);
}
}
static void FormatCustomFormatString(StringBuffer formatter, ref Number number, int? originalScale, StringView specifier, int index, int end, CachedCulture culture) {
int start = index;
int integralDigits = 0, integralZeros = 0,
decimalDigits = 0, decimalZeros = 0;
bool integralHasZeroFlag = false;
int exponentialZeros = 0;
bool decimalFlag = false;
bool commaFlag = false, groupFlag = false;
char* ptr = specifier.Data;
for (; index < end; index++) {
switch (ptr[index]) {
case '\\':
if (++index >= end) throw new FormatException();
break;
case '\'':
SkipLiteral(specifier, ref index, '\'');
break;
case '"':
SkipLiteral(specifier, ref index, '"');
break;
case '0':
if (decimalFlag) {
if (decimalZeros < decimalDigits)
decimalZeros = decimalDigits;
decimalDigits++;
decimalZeros++;
}
else {
integralDigits++;
integralZeros++;
integralHasZeroFlag = true;
if (commaFlag) groupFlag = true;
}
break;
case '#':
if (decimalFlag) {
decimalDigits++;
}
else {
integralDigits++;
if (integralHasZeroFlag) integralZeros++;
if (commaFlag) groupFlag = true;
}
break;
case '.': decimalFlag = true; commaFlag = false; break;
case ',': commaFlag = true; break;
case 'E':
case 'e':
if (++index >= end) goto exit;
char tc0 = ptr[index];
if (tc0 == '+' || tc0 == '-') {
if (++index >= end) goto exit;
}
if (ptr[index] != '0') break;
for (; index < end && ptr[index] == '0'; index++) exponentialZeros++;
index--;
break;
}
}
exit:
int currentDigitIndex = 0;
int groupIndex = 0, remainingDigitsInGroup = Math.Max(number.Scale, decimalZeros);
if (groupFlag) while (true) {
int groupSize = culture.NumberData.GroupSizes.ElementAtOrLast(groupIndex);
if (remainingDigitsInGroup <= groupSize) break;
remainingDigitsInGroup -= groupSize;
groupIndex++;
}
bool appendingDigitFlag = false;
decimalFlag = false;
for (index = start; index < end; index++) {
switch (ptr[index]) {
case '\\':
if (++index >= end) throw new FormatException();
formatter.Append(ptr[index]);
break;
case '\'':
formatter.AppendLiteral(specifier, ref index, '\'');
break;
case '"':
formatter.AppendLiteral(specifier, ref index, '"');
break;
case '0':
case '#':
if (!appendingDigitFlag) {
if (number.Scale > integralDigits) while (currentDigitIndex < number.Scale - integralDigits)
formatter.AppendIntegralDigit(ref number, ref currentDigitIndex, culture, groupFlag, ref groupIndex, ref remainingDigitsInGroup);
appendingDigitFlag = true;
}
if (decimalFlag) {
if (currentDigitIndex < number.Precision) {
char digit = number.Digits[currentDigitIndex++];
if (digit == '\0') digit = '0';
formatter.Append(digit);
}
else if (decimalZeros > 0)
formatter.Append('0');
--decimalDigits;
--decimalZeros;
}
else {
if (integralDigits <= number.Scale)
formatter.AppendIntegralDigit(ref number, ref currentDigitIndex, culture, groupFlag, ref groupIndex, ref remainingDigitsInGroup);
else if (integralDigits <= integralZeros)
formatter.AppendIntegralDigit('0', culture, groupFlag, ref groupIndex, ref remainingDigitsInGroup);
--integralDigits;
}
break;
case '.': formatter.Append(culture.NumberData.DecimalSeparator); decimalFlag = true; break;
case ',': break;
case '%': formatter.Append(culture.PercentSymbol); break;
case '‰': formatter.Append(culture.PerMilleSymbol); break;
case 'E':
case 'e':
char exponentialSymbol = ptr[index];
if (++index >= end) {
index--;
goto default;
}
char tc0 = ptr[index];
bool hasPlusFlag = false;
if (tc0 == '+' || tc0 == '-') {
if (++index >= end) {
index -= 2;
goto default;
}
if (tc0 == '+') hasPlusFlag = true;
}
if (ptr[index] != '0') {
index -= 2;
goto default;
}
for (index++; index < end && ptr[index] == '0'; index++) ;
index--;
int exp = originalScale == null ? 0 : originalScale.Value - number.Scale;
formatter.Append(exponentialSymbol);
if (exp < 0) {
formatter.Append(culture.NegativeSign);
exp = -exp;
}
else if (hasPlusFlag) {
formatter.Append(culture.PositiveSign);
}
Int32ToDecStr(formatter, exp, exponentialZeros, "");
break;
default:
formatter.Append(ptr[index]);
break;
}
}
}
static void AppendIntegralDigit(this StringBuffer self, ref Number number, ref int index, CachedCulture culture, bool groupFlag, ref int groupIndex, ref int remainingDigitsInGroup) {
char digit;
if (index >= number.Precision) digit = '0';
else digit = number.Digits[index];
if (digit == '\0') digit = '0';
self.AppendIntegralDigit(digit, culture, groupFlag, ref groupIndex, ref remainingDigitsInGroup);
index++;
}
static void AppendIntegralDigit(this StringBuffer self, char digit, CachedCulture culture, bool groupFlag, ref int groupIndex, ref int remainingDigitsInGroup) {
self.Append(digit);
if (!groupFlag) return;
if (--remainingDigitsInGroup == 0) {
if (--groupIndex >= 0) {
remainingDigitsInGroup = culture.NumberData.GroupSizes.ElementAtOrLast(groupIndex);
self.Append(culture.NumberData.GroupSeparator);
}
}
}
static T ElementAtOrLast<T>(this T[] arr, int index) {
if (index >= arr.Length) index = arr.Length - 1;
return arr[index];
}
static void SkipLiteral(StringView specifier, ref int index, char delimiter) {
while (++index < specifier.Length) {
if (specifier.Data[index] == delimiter) return;
}
throw new FormatException();
}
static void AppendLiteral(this StringBuffer self, StringView specifier, ref int index, char delimiter) {
int start = index + 1;
while (++index < specifier.Length) {
if (specifier.Data[index] == delimiter) {
self.Append(specifier.Data + start, index - start);
return;
}
}
throw new FormatException();
}
}
}

View File

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

View File

@@ -0,0 +1,14 @@
{
"name": "StringFormatter",
"rootNamespace": "",
"references": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": true
}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

BIN
Assets/Plugins/UnsafeIL.dll Normal file

Binary file not shown.

View File

@@ -0,0 +1,33 @@
fileFormatVersion: 2
guid: d927992f95b82f740a0a95bb6d617d73
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
Windows Store Apps: WindowsStoreApps
second:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1 @@
)]}〕〉》」』】〙〗〟’”⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、%,.:;。!?]):;=}¢°"†‡℃〆%,.

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fade42e8bc714b018fac513c043d323b
timeCreated: 1425440388
licenseType: Store
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1 @@
([{〔〈《「『【〘〖〝‘“⦅«$—…‥〳〴〵\{£¥"々〇$¥₩ #

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d82c1b31c7e74239bff1220585707d2b
timeCreated: 1425440388
licenseType: Store
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3f5b5dff67a942289a9defa416b206f3
timeCreated: 1436653997
licenseType: Pro
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

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

View File

@@ -0,0 +1,178 @@
float2 UnpackUV(float uv)
{
float2 output;
output.x = floor(uv / 4096.0);
output.y = uv - 4096.0 * output.x;
return output * 0.001953125;
}
float4 BlendARGB(float4 overlying, float4 underlying)
{
overlying.rgb *= overlying.a;
underlying.rgb *= underlying.a;
float3 blended = overlying.rgb + ((1 - overlying.a) * underlying.rgb);
float alpha = underlying.a + (1 - underlying.a) * overlying.a;
return float4(blended / alpha, alpha);
}
float3 GetSpecular(float3 n, float3 l)
{
float spec = pow(max(0.0, dot(n, l)), _Reflectivity);
return _SpecularColor.rgb * spec * _SpecularPower;
}
void GetSurfaceNormal_float(texture2D atlas, float textureWidth, float textureHeight, float2 uv, bool isFront, out float3 nornmal)
{
float3 delta = float3(1.0 / textureWidth, 1.0 / textureHeight, 0.0);
// Read "height field"
float4 h = float4(
SAMPLE_TEXTURE2D(atlas, SamplerState_Linear_Clamp, uv - delta.xz).a,
SAMPLE_TEXTURE2D(atlas, SamplerState_Linear_Clamp, uv + delta.xz).a,
SAMPLE_TEXTURE2D(atlas, SamplerState_Linear_Clamp, uv - delta.zy).a,
SAMPLE_TEXTURE2D(atlas, SamplerState_Linear_Clamp, uv + delta.zy).a);
bool raisedBevel = _BevelType;
h += _BevelOffset;
float bevelWidth = max(.01, _BevelWidth);
// Track outline
h -= .5;
h /= bevelWidth;
h = saturate(h + .5);
if (raisedBevel) h = 1 - abs(h * 2.0 - 1.0);
h = lerp(h, sin(h * 3.141592 / 2.0), float4(_BevelRoundness, _BevelRoundness, _BevelRoundness, _BevelRoundness));
h = min(h, 1.0 - float4(_BevelClamp, _BevelClamp, _BevelClamp, _BevelClamp));
h *= _BevelAmount * bevelWidth * _GradientScale * -2.0;
float3 va = normalize(float3(-1.0, 0.0, h.y - h.x));
float3 vb = normalize(float3(0.0, 1.0, h.w - h.z));
float3 f = float3(1, 1, 1);
if (isFront) f = float3(1, 1, -1);
nornmal = cross(va, vb) * f;
}
void EvaluateLight_float(float4 faceColor, float3 n, out float4 color)
{
n.z = abs(n.z);
float3 light = normalize(float3(sin(_LightAngle), cos(_LightAngle), 1.0));
float3 col = max(faceColor.rgb, 0) + GetSpecular(n, light)* faceColor.a;
//faceColor.rgb += col * faceColor.a;
col *= 1 - (dot(n, light) * _Diffuse);
col *= lerp(_Ambient, 1, n.z * n.z);
//fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDir, -n));
//faceColor.rgb += reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a;
color = float4(col, faceColor.a);
}
// Add custom function to handle time in HDRP
//
void GenerateUV_float(float2 inUV, float4 transform, float2 animSpeed, out float2 outUV)
{
outUV = inUV * transform.xy + transform.zw + (animSpeed * _Time.y);
}
void ComputeUVOffset_float(float texWidth, float texHeight, float2 offset, float SDR, out float2 uvOffset)
{
uvOffset = float2(-offset.x * SDR / texWidth, -offset.y * SDR / texHeight);
}
void ScreenSpaceRatio2_float(float4x4 projection, float4 position, float2 objectScale, float screenWidth, float screenHeight, float fontScale, out float SSR)
{
float2 pixelSize = position.w;
pixelSize /= (objectScale * mul((float2x2)projection, float2(screenWidth, screenHeight)));
SSR = rsqrt(dot(pixelSize, pixelSize)*2) * fontScale;
}
// UV : Texture coordinate of the source distance field texture
// TextureSize : Size of the source distance field texture
// Filter : Enable perspective filter (soften)
void ScreenSpaceRatio_float(float2 UV, float TextureSize, bool Filter, out float SSR)
{
if(Filter)
{
float2 a = float2(ddx(UV.x), ddy(UV.x));
float2 b = float2(ddx(UV.y), ddy(UV.y));
float s = lerp(dot(a,a), dot(b,b), 0.5);
SSR = rsqrt(s) / TextureSize;
}
else
{
float s = rsqrt(abs(ddx(UV.x) * ddy(UV.y) - ddy(UV.x) * ddx(UV.y)));
SSR = s / TextureSize;
}
}
// SSR : Screen Space Ratio
// SD : Signed Distance (encoded : Distance / SDR + .5)
// SDR : Signed Distance Ratio
//
// IsoPerimeter : Dilate / Contract the shape
void ComputeSDF_float(float SSR, float SD, float SDR, float isoPerimeter, float softness, out float outAlpha)
{
softness *= SSR * SDR;
float d = (SD - 0.5) * SDR; // Signed distance to edge, in Texture space
outAlpha = saturate((d * 2.0 * SSR + 0.5 + isoPerimeter * SDR * SSR + softness * 0.5) / (1.0 + softness)); // Screen pixel coverage (alpha)
}
void ComputeSDF2_float(float SSR, float SD, float SDR, float2 isoPerimeter, float2 softness, out float2 outAlpha)
{
softness *= SSR * SDR;
float d = (SD - 0.5f) * SDR;
outAlpha = saturate((d * 2.0f * SSR + 0.5f + isoPerimeter * SDR * SSR + softness * 0.5) / (1.0 + softness));
}
void ComputeSDF4_float(float SSR, float SD, float SDR, float4 isoPerimeter, float4 softness, out float4 outAlpha)
{
softness *= SSR * SDR;
float d = (SD - 0.5f) * SDR;
outAlpha = saturate((d * 2.0f * SSR + 0.5f + isoPerimeter * SDR * SSR + softness * 0.5) / (1.0 + softness));
}
void ComputeSDF44_float(float SSR, float4 SD, float SDR, float4 isoPerimeter, float4 softness, bool outline, out float4 outAlpha)
{
softness *= SSR * SDR;
float4 d = (SD - 0.5f) * SDR;
if(outline) d.w = max(max(d.x, d.y), d.z);
outAlpha = saturate((d * 2.0f * SSR + 0.5f + isoPerimeter * SDR * SSR + softness * 0.5) / (1.0 + softness));
}
void Composite_float(float4 overlying, float4 underlying, out float4 outColor)
{
outColor = BlendARGB(overlying, underlying);
}
// Face only
void Layer1_float(float alpha, float4 color0, out float4 outColor)
{
color0.a *= alpha;
outColor = color0;
}
// Face + 1 Outline
void Layer2_float(float2 alpha, float4 color0, float4 color1, out float4 outColor)
{
color1.a *= alpha.y;
color0.rgb *= color0.a; color1.rgb *= color1.a;
outColor = lerp(color1, color0, alpha.x);
outColor.rgb /= outColor.a;
}
// Face + 3 Outline
void Layer4_float(float4 alpha, float4 color0, float4 color1, float4 color2, float4 color3, out float4 outColor)
{
color3.a *= alpha.w;
color0.rgb *= color0.a; color1.rgb *= color1.a; color2.rgb *= color2.a; color3.rgb *= color3.a;
outColor = lerp(lerp(lerp(color3, color2, alpha.z), color1, alpha.y), color0, alpha.x);
outColor.rgb /= outColor.a;
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 96de908384869cd409c75efa351d5edf
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,139 @@
Shader "TextMeshPro/Bitmap Custom Atlas" {
Properties {
_MainTex ("Font Atlas", 2D) = "white" {}
_FaceTex ("Font Texture", 2D) = "white" {}
_FaceColor ("Text Color", Color) = (1,1,1,1)
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_Padding ("Padding", float) = 0
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_CullMode ("Cull Mode", Float) = 0
_ColorMask ("Color Mask", Float) = 15
}
SubShader{
Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
Stencil
{
Ref[_Stencil]
Comp[_StencilComp]
Pass[_StencilOp]
ReadMask[_StencilReadMask]
WriteMask[_StencilWriteMask]
}
Lighting Off
Cull [_CullMode]
ZTest [unity_GUIZTestMode]
ZWrite Off
Fog { Mode Off }
Blend SrcAlpha OneMinusSrcAlpha
ColorMask[_ColorMask]
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
float4 mask : TEXCOORD2;
};
uniform sampler2D _MainTex;
uniform sampler2D _FaceTex;
uniform float4 _FaceTex_ST;
uniform fixed4 _FaceColor;
uniform float _VertexOffsetX;
uniform float _VertexOffsetY;
uniform float4 _ClipRect;
uniform float _MaskSoftnessX;
uniform float _MaskSoftnessY;
uniform float _UIMaskSoftnessX;
uniform float _UIMaskSoftnessY;
v2f vert (appdata_t v)
{
float4 vert = v.vertex;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
vert.xy += (vert.w * 0.5) / _ScreenParams.xy;
float4 vPosition = UnityPixelSnap(UnityObjectToClipPos(vert));
fixed4 faceColor = v.color;
faceColor *= _FaceColor;
v2f OUT;
OUT.vertex = vPosition;
OUT.color = faceColor;
OUT.texcoord0 = v.texcoord0;
OUT.texcoord1 = TRANSFORM_TEX(v.texcoord1, _FaceTex);
float2 pixelSize = vPosition.w;
pixelSize /= abs(float2(_ScreenParams.x * UNITY_MATRIX_P[0][0], _ScreenParams.y * UNITY_MATRIX_P[1][1]));
// Clamp _ClipRect to 16bit.
const float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
const half2 maskSoftness = half2(max(_UIMaskSoftnessX, _MaskSoftnessX), max(_UIMaskSoftnessY, _MaskSoftnessY));
OUT.mask = float4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * maskSoftness + pixelSize.xy));
return OUT;
}
fixed4 frag (v2f IN) : SV_Target
{
fixed4 color = tex2D(_MainTex, IN.texcoord0) * tex2D(_FaceTex, IN.texcoord1) * IN.color;
// Alternative implementation to UnityGet2DClipping with support for softness.
#if UNITY_UI_CLIP_RECT
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(IN.mask.xy)) * IN.mask.zw);
color *= m.x * m.y;
#endif
#if UNITY_UI_ALPHACLIP
clip(color.a - 0.001);
#endif
return color;
}
ENDCG
}
}
CustomEditor "TMPro.EditorUtilities.TMP_BitmapShaderGUI"
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 48bb5f55d8670e349b6e614913f9d910
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,150 @@
Shader "TextMeshPro/Mobile/Bitmap" {
Properties {
_MainTex ("Font Atlas", 2D) = "white" {}
_Color ("Text Color", Color) = (1,1,1,1)
_DiffusePower ("Diffuse Power", Range(1.0,4.0)) = 1.0
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_CullMode ("Cull Mode", Float) = 0
_ColorMask ("Color Mask", Float) = 15
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
Stencil
{
Ref[_Stencil]
Comp[_StencilComp]
Pass[_StencilOp]
ReadMask[_StencilReadMask]
WriteMask[_StencilWriteMask]
}
Lighting Off
Cull [_CullMode]
ZTest [unity_GUIZTestMode]
ZWrite Off
Fog { Mode Off }
Blend SrcAlpha OneMinusSrcAlpha
ColorMask[_ColorMask]
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct v2f
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float4 mask : TEXCOORD2;
};
sampler2D _MainTex;
fixed4 _Color;
float _DiffusePower;
uniform float _VertexOffsetX;
uniform float _VertexOffsetY;
uniform float4 _ClipRect;
uniform float _MaskSoftnessX;
uniform float _MaskSoftnessY;
uniform float _UIMaskSoftnessX;
uniform float _UIMaskSoftnessY;
v2f vert (appdata_t v)
{
v2f OUT;
float4 vert = v.vertex;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
vert.xy += (vert.w * 0.5) / _ScreenParams.xy;
OUT.vertex = UnityPixelSnap(UnityObjectToClipPos(vert));
OUT.color = v.color;
OUT.color *= _Color;
OUT.color.rgb *= _DiffusePower;
OUT.texcoord0 = v.texcoord0;
float2 pixelSize = OUT.vertex.w;
//pixelSize /= abs(float2(_ScreenParams.x * UNITY_MATRIX_P[0][0], _ScreenParams.y * UNITY_MATRIX_P[1][1]));
// Clamp _ClipRect to 16bit.
const float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
const half2 maskSoftness = half2(max(_UIMaskSoftnessX, _MaskSoftnessX), max(_UIMaskSoftnessY, _MaskSoftnessY));
OUT.mask = float4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * maskSoftness + pixelSize.xy));
return OUT;
}
fixed4 frag (v2f IN) : COLOR
{
fixed4 color = fixed4(IN.color.rgb, IN.color.a * tex2D(_MainTex, IN.texcoord0).a);
// Alternative implementation to UnityGet2DClipping with support for softness.
#if UNITY_UI_CLIP_RECT
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(IN.mask.xy)) * IN.mask.zw);
color *= m.x * m.y;
#endif
#if UNITY_UI_ALPHACLIP
clip(color.a - 0.001);
#endif
return color;
}
ENDCG
}
}
SubShader {
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" }
Lighting Off Cull Off ZTest Always ZWrite Off Fog { Mode Off }
Blend SrcAlpha OneMinusSrcAlpha
BindChannels {
Bind "Color", color
Bind "Vertex", vertex
Bind "TexCoord", texcoord0
}
Pass {
SetTexture [_MainTex] {
constantColor [_Color] combine constant * primary, constant * texture
}
}
}
CustomEditor "TMPro.EditorUtilities.TMP_BitmapShaderGUI"
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 1e3b057af24249748ff873be7fafee47
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,139 @@
Shader "TextMeshPro/Bitmap" {
Properties {
_MainTex ("Font Atlas", 2D) = "white" {}
_FaceTex ("Font Texture", 2D) = "white" {}
_FaceColor ("Text Color", Color) = (1,1,1,1)
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_CullMode ("Cull Mode", Float) = 0
_ColorMask ("Color Mask", Float) = 15
}
SubShader{
Tags { "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" }
Stencil
{
Ref[_Stencil]
Comp[_StencilComp]
Pass[_StencilOp]
ReadMask[_StencilReadMask]
WriteMask[_StencilWriteMask]
}
Lighting Off
Cull [_CullMode]
ZTest [unity_GUIZTestMode]
ZWrite Off
Fog { Mode Off }
Blend SrcAlpha OneMinusSrcAlpha
ColorMask[_ColorMask]
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
fixed4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
float4 mask : TEXCOORD2;
};
uniform sampler2D _MainTex;
uniform sampler2D _FaceTex;
uniform float4 _FaceTex_ST;
uniform fixed4 _FaceColor;
uniform float _VertexOffsetX;
uniform float _VertexOffsetY;
uniform float4 _ClipRect;
uniform float _MaskSoftnessX;
uniform float _MaskSoftnessY;
uniform float _UIMaskSoftnessX;
uniform float _UIMaskSoftnessY;
v2f vert (appdata_t v)
{
float4 vert = v.vertex;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
vert.xy += (vert.w * 0.5) / _ScreenParams.xy;
float4 vPosition = UnityPixelSnap(UnityObjectToClipPos(vert));
fixed4 faceColor = v.color;
faceColor *= _FaceColor;
v2f OUT;
OUT.vertex = vPosition;
OUT.color = faceColor;
OUT.texcoord0 = v.texcoord0;
OUT.texcoord1 = TRANSFORM_TEX(v.texcoord1, _FaceTex);
float2 pixelSize = vPosition.w;
pixelSize /= abs(float2(_ScreenParams.x * UNITY_MATRIX_P[0][0], _ScreenParams.y * UNITY_MATRIX_P[1][1]));
// Clamp _ClipRect to 16bit.
const float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
const half2 maskSoftness = half2(max(_UIMaskSoftnessX, _MaskSoftnessX), max(_UIMaskSoftnessY, _MaskSoftnessY));
OUT.mask = float4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * maskSoftness + pixelSize.xy));
return OUT;
}
fixed4 frag (v2f IN) : SV_Target
{
fixed4 color = tex2D(_MainTex, IN.texcoord0);
color = fixed4 (tex2D(_FaceTex, IN.texcoord1).rgb * IN.color.rgb, IN.color.a * color.a);
// Alternative implementation to UnityGet2DClipping with support for softness.
#if UNITY_UI_CLIP_RECT
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(IN.mask.xy)) * IN.mask.zw);
color *= m.x * m.y;
#endif
#if UNITY_UI_ALPHACLIP
clip(color.a - 0.001);
#endif
return color;
}
ENDCG
}
}
CustomEditor "TMPro.EditorUtilities.TMP_BitmapShaderGUI"
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 128e987d567d4e2c824d754223b3f3b0
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,321 @@
Shader "TextMeshPro/Distance Field Overlay" {
Properties {
_FaceTex ("Face Texture", 2D) = "white" {}
_FaceUVSpeedX ("Face UV Speed X", Range(-5, 5)) = 0.0
_FaceUVSpeedY ("Face UV Speed Y", Range(-5, 5)) = 0.0
_FaceColor ("Face Color", Color) = (1,1,1,1)
_FaceDilate ("Face Dilate", Range(-1,1)) = 0
_OutlineColor ("Outline Color", Color) = (0,0,0,1)
_OutlineTex ("Outline Texture", 2D) = "white" {}
_OutlineUVSpeedX ("Outline UV Speed X", Range(-5, 5)) = 0.0
_OutlineUVSpeedY ("Outline UV Speed Y", Range(-5, 5)) = 0.0
_OutlineWidth ("Outline Thickness", Range(0, 1)) = 0
_OutlineSoftness ("Outline Softness", Range(0,1)) = 0
_Bevel ("Bevel", Range(0,1)) = 0.5
_BevelOffset ("Bevel Offset", Range(-0.5,0.5)) = 0
_BevelWidth ("Bevel Width", Range(-.5,0.5)) = 0
_BevelClamp ("Bevel Clamp", Range(0,1)) = 0
_BevelRoundness ("Bevel Roundness", Range(0,1)) = 0
_LightAngle ("Light Angle", Range(0.0, 6.2831853)) = 3.1416
_SpecularColor ("Specular", Color) = (1,1,1,1)
_SpecularPower ("Specular", Range(0,4)) = 2.0
_Reflectivity ("Reflectivity", Range(5.0,15.0)) = 10
_Diffuse ("Diffuse", Range(0,1)) = 0.5
_Ambient ("Ambient", Range(1,0)) = 0.5
_BumpMap ("Normal map", 2D) = "bump" {}
_BumpOutline ("Bump Outline", Range(0,1)) = 0
_BumpFace ("Bump Face", Range(0,1)) = 0
_ReflectFaceColor ("Reflection Color", Color) = (0,0,0,1)
_ReflectOutlineColor("Reflection Color", Color) = (0,0,0,1)
_Cube ("Reflection Cubemap", Cube) = "black" { /* TexGen CubeReflect */ }
_EnvMatrixRotation ("Texture Rotation", vector) = (0, 0, 0, 0)
_UnderlayColor ("Border Color", Color) = (0,0,0, 0.5)
_UnderlayOffsetX ("Border OffsetX", Range(-1,1)) = 0
_UnderlayOffsetY ("Border OffsetY", Range(-1,1)) = 0
_UnderlayDilate ("Border Dilate", Range(-1,1)) = 0
_UnderlaySoftness ("Border Softness", Range(0,1)) = 0
_GlowColor ("Color", Color) = (0, 1, 0, 0.5)
_GlowOffset ("Offset", Range(-1,1)) = 0
_GlowInner ("Inner", Range(0,1)) = 0.05
_GlowOuter ("Outer", Range(0,1)) = 0.05
_GlowPower ("Falloff", Range(1, 0)) = 0.75
_WeightNormal ("Weight Normal", float) = 0
_WeightBold ("Weight Bold", float) = 0.5
_ShaderFlags ("Flags", float) = 0
_ScaleRatioA ("Scale RatioA", float) = 1
_ScaleRatioB ("Scale RatioB", float) = 1
_ScaleRatioC ("Scale RatioC", float) = 1
_MainTex ("Font Atlas", 2D) = "white" {}
_TextureWidth ("Texture Width", float) = 512
_TextureHeight ("Texture Height", float) = 512
_GradientScale ("Gradient Scale", float) = 5.0
_ScaleX ("Scale X", float) = 1.0
_ScaleY ("Scale Y", float) = 1.0
_PerspectiveFilter ("Perspective Correction", Range(0, 1)) = 0.875
_Sharpness ("Sharpness", Range(-1,1)) = 0
_VertexOffsetX ("Vertex OffsetX", float) = 0
_VertexOffsetY ("Vertex OffsetY", float) = 0
_MaskCoord ("Mask Coordinates", vector) = (0, 0, 32767, 32767)
_ClipRect ("Clip Rect", vector) = (-32767, -32767, 32767, 32767)
_MaskSoftnessX ("Mask SoftnessX", float) = 0
_MaskSoftnessY ("Mask SoftnessY", float) = 0
_StencilComp ("Stencil Comparison", Float) = 8
_Stencil ("Stencil ID", Float) = 0
_StencilOp ("Stencil Operation", Float) = 0
_StencilWriteMask ("Stencil Write Mask", Float) = 255
_StencilReadMask ("Stencil Read Mask", Float) = 255
_CullMode ("Cull Mode", Float) = 0
_ColorMask ("Color Mask", Float) = 15
}
SubShader {
Tags
{
"Queue"="Overlay"
"IgnoreProjector"="True"
"RenderType"="Transparent"
}
Stencil
{
Ref [_Stencil]
Comp [_StencilComp]
Pass [_StencilOp]
ReadMask [_StencilReadMask]
WriteMask [_StencilWriteMask]
}
Cull [_CullMode]
ZWrite Off
Lighting Off
Fog { Mode Off }
ZTest Always
Blend One OneMinusSrcAlpha
ColorMask [_ColorMask]
Pass {
CGPROGRAM
#pragma target 3.0
#pragma vertex VertShader
#pragma fragment PixShader
#pragma shader_feature __ BEVEL_ON
#pragma shader_feature __ UNDERLAY_ON UNDERLAY_INNER
#pragma shader_feature __ GLOW_ON
#pragma multi_compile __ UNITY_UI_CLIP_RECT
#pragma multi_compile __ UNITY_UI_ALPHACLIP
#include "UnityCG.cginc"
#include "UnityUI.cginc"
#include "TMPro_Properties.cginc"
#include "TMPro.cginc"
struct vertex_t
{
UNITY_VERTEX_INPUT_INSTANCE_ID
float4 position : POSITION;
float3 normal : NORMAL;
fixed4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float2 texcoord1 : TEXCOORD1;
};
struct pixel_t
{
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
float4 position : SV_POSITION;
fixed4 color : COLOR;
float2 atlas : TEXCOORD0; // Atlas
float4 param : TEXCOORD1; // alphaClip, scale, bias, weight
float4 mask : TEXCOORD2; // Position in object space(xy), pixel Size(zw)
float3 viewDir : TEXCOORD3;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 texcoord2 : TEXCOORD4; // u,v, scale, bias
fixed4 underlayColor : COLOR1;
#endif
float4 textures : TEXCOORD5;
};
// Used by Unity internally to handle Texture Tiling and Offset.
uniform float4 _FaceTex_ST;
uniform float4 _OutlineTex_ST;
uniform float _UIMaskSoftnessX;
uniform float _UIMaskSoftnessY;
pixel_t VertShader(vertex_t input)
{
pixel_t output;
UNITY_INITIALIZE_OUTPUT(pixel_t, output);
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input,output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
float bold = step(input.texcoord0.w, 0);
float4 vert = input.position;
vert.x += _VertexOffsetX;
vert.y += _VertexOffsetY;
float4 vPosition = UnityObjectToClipPos(vert);
float2 pixelSize = vPosition.w;
pixelSize /= float2(_ScaleX, _ScaleY) * abs(mul((float2x2)UNITY_MATRIX_P, _ScreenParams.xy));
float scale = rsqrt(dot(pixelSize, pixelSize));
scale *= abs(input.texcoord0.w) * _GradientScale * (_Sharpness + 1);
if (UNITY_MATRIX_P[3][3] == 0) scale = lerp(abs(scale) * (1 - _PerspectiveFilter), scale, abs(dot(UnityObjectToWorldNormal(input.normal.xyz), normalize(WorldSpaceViewDir(vert)))));
float weight = lerp(_WeightNormal, _WeightBold, bold) / 4.0;
weight = (weight + _FaceDilate) * _ScaleRatioA * 0.5;
float bias =(.5 - weight) + (.5 / scale);
float alphaClip = (1.0 - _OutlineWidth*_ScaleRatioA - _OutlineSoftness*_ScaleRatioA);
#if GLOW_ON
alphaClip = min(alphaClip, 1.0 - _GlowOffset * _ScaleRatioB - _GlowOuter * _ScaleRatioB);
#endif
alphaClip = alphaClip / 2.0 - ( .5 / scale) - weight;
#if (UNDERLAY_ON || UNDERLAY_INNER)
float4 underlayColor = _UnderlayColor;
underlayColor.rgb *= underlayColor.a;
float bScale = scale;
bScale /= 1 + ((_UnderlaySoftness*_ScaleRatioC) * bScale);
float bBias = (0.5 - weight) * bScale - 0.5 - ((_UnderlayDilate * _ScaleRatioC) * 0.5 * bScale);
float x = -(_UnderlayOffsetX * _ScaleRatioC) * _GradientScale / _TextureWidth;
float y = -(_UnderlayOffsetY * _ScaleRatioC) * _GradientScale / _TextureHeight;
float2 bOffset = float2(x, y);
#endif
// Generate UV for the Masking Texture
float4 clampedRect = clamp(_ClipRect, -2e10, 2e10);
float2 maskUV = (vert.xy - clampedRect.xy) / (clampedRect.zw - clampedRect.xy);
// Support for texture tiling and offset
float2 textureUV = input.texcoord1;
float2 faceUV = TRANSFORM_TEX(textureUV, _FaceTex);
float2 outlineUV = TRANSFORM_TEX(textureUV, _OutlineTex);
output.position = vPosition;
output.color = input.color;
output.atlas = input.texcoord0;
output.param = float4(alphaClip, scale, bias, weight);
const half2 maskSoftness = half2(max(_UIMaskSoftnessX, _MaskSoftnessX), max(_UIMaskSoftnessY, _MaskSoftnessY));
output.mask = half4(vert.xy * 2 - clampedRect.xy - clampedRect.zw, 0.25 / (0.25 * maskSoftness + pixelSize.xy));
output.viewDir = mul((float3x3)_EnvMatrix, _WorldSpaceCameraPos.xyz - mul(unity_ObjectToWorld, vert).xyz);
#if (UNDERLAY_ON || UNDERLAY_INNER)
output.texcoord2 = float4(input.texcoord0 + bOffset, bScale, bBias);
output.underlayColor = underlayColor;
#endif
output.textures = float4(faceUV, outlineUV);
return output;
}
fixed4 PixShader(pixel_t input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
float c = tex2D(_MainTex, input.atlas).a;
#ifndef UNDERLAY_ON
clip(c - input.param.x);
#endif
float scale = input.param.y;
float bias = input.param.z;
float weight = input.param.w;
float sd = (bias - c) * scale;
float outline = (_OutlineWidth * _ScaleRatioA) * scale;
float softness = (_OutlineSoftness * _ScaleRatioA) * scale;
half4 faceColor = _FaceColor;
half4 outlineColor = _OutlineColor;
faceColor.rgb *= input.color.rgb;
faceColor *= tex2D(_FaceTex, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y);
outlineColor *= tex2D(_OutlineTex, input.textures.zw + float2(_OutlineUVSpeedX, _OutlineUVSpeedY) * _Time.y);
faceColor = GetColor(sd, faceColor, outlineColor, outline, softness);
#if BEVEL_ON
float3 dxy = float3(0.5 / _TextureWidth, 0.5 / _TextureHeight, 0);
float3 n = GetSurfaceNormal(input.atlas, weight, dxy);
float3 bump = UnpackNormal(tex2D(_BumpMap, input.textures.xy + float2(_FaceUVSpeedX, _FaceUVSpeedY) * _Time.y)).xyz;
bump *= lerp(_BumpFace, _BumpOutline, saturate(sd + outline * 0.5));
n = normalize(n- bump);
float3 light = normalize(float3(sin(_LightAngle), cos(_LightAngle), -1.0));
float3 col = GetSpecular(n, light);
faceColor.rgb += col*faceColor.a;
faceColor.rgb *= 1-(dot(n, light)*_Diffuse);
faceColor.rgb *= lerp(_Ambient, 1, n.z*n.z);
fixed4 reflcol = texCUBE(_Cube, reflect(input.viewDir, -n));
faceColor.rgb += reflcol.rgb * lerp(_ReflectFaceColor.rgb, _ReflectOutlineColor.rgb, saturate(sd + outline * 0.5)) * faceColor.a;
#endif
#if UNDERLAY_ON
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * saturate(d - input.texcoord2.w) * (1 - faceColor.a);
#endif
#if UNDERLAY_INNER
float d = tex2D(_MainTex, input.texcoord2.xy).a * input.texcoord2.z;
faceColor += input.underlayColor * (1 - saturate(d - input.texcoord2.w)) * saturate(1 - sd) * (1 - faceColor.a);
#endif
#if GLOW_ON
float4 glowColor = GetGlowColor(sd, scale);
faceColor.rgb += glowColor.rgb * glowColor.a;
#endif
// Alternative implementation to UnityGet2DClipping with support for softness.
#if UNITY_UI_CLIP_RECT
half2 m = saturate((_ClipRect.zw - _ClipRect.xy - abs(input.mask.xy)) * input.mask.zw);
faceColor *= m.x * m.y;
#endif
#if UNITY_UI_ALPHACLIP
clip(faceColor.a - 0.001);
#endif
return faceColor * input.color.a;
}
ENDCG
}
}
Fallback "TextMeshPro/Mobile/Distance Field"
CustomEditor "TMPro.EditorUtilities.TMP_SDFShaderGUI"
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: dd89cf5b9246416f84610a006f916af7
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

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