diff --git a/.gitignore b/.gitignore index 2a9b4c6e..60d0cd39 100644 --- a/.gitignore +++ b/.gitignore @@ -73,3 +73,9 @@ Assets/Plugins.meta .DS_Store +Packages/essential/Tests +Packages/essential/Tests.meta +Packages/variant.expression/Tests/ +Packages/codegen/Tests +Packages/codegen/Tests.meta +Packages/variant.expression/Tests.meta diff --git a/Assets/_ b/Assets/_ deleted file mode 100644 index e69de29b..00000000 diff --git a/Assets/___.cs b/Assets/___.cs new file mode 100644 index 00000000..f4f3f8e8 --- /dev/null +++ b/Assets/___.cs @@ -0,0 +1,2 @@ +// for generating Assembly-CSharp.dll +public class ___ { } diff --git a/Packages/builder.component/Runtime/Variant/SingleVariantReaderAndWriter.cs.meta b/Assets/___.cs.meta similarity index 83% rename from Packages/builder.component/Runtime/Variant/SingleVariantReaderAndWriter.cs.meta rename to Assets/___.cs.meta index 66c37af3..4821e5b1 100644 --- a/Packages/builder.component/Runtime/Variant/SingleVariantReaderAndWriter.cs.meta +++ b/Assets/___.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5a8de5c5120b01244bcdd98c4c9ce50e +guid: 800e31150363343439916790c230e370 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Packages/builder.component/Editor/ComponentFieldCodeGenerator.cs b/Packages/builder.component/Editor/ComponentFieldCodeGenerator.cs index 48e5bf89..4ee58e45 100644 --- a/Packages/builder.component/Editor/ComponentFieldCodeGenerator.cs +++ b/Packages/builder.component/Editor/ComponentFieldCodeGenerator.cs @@ -50,22 +50,7 @@ public string GenerateBuild(FieldInfo fi) public class BlobVariantFieldCodeGenerator : INodeDataFieldCodeGenerator { - protected const string HEAD_LINE = "// Automatically generated by `BlobVariantFieldCodeGenerator`"; - - public bool ShouldGenerateVariantInterface = true; - public string VariantInterfaceDirectory = "Variant"; public string VariantInterfaceNamespace = "EntitiesBT.Variant"; - public string VariantPropertyNameSuffix = "Variant"; - public NodeCodeGenerator Generator; - public AssemblyDefinitionAsset Assembly; - - private ISet _referenceAssemblies; - - private bool IsReferenceType(Type type) - { - _referenceAssemblies ??= Assembly.ToAssembly().FindReferenceAssemblies(); - return _referenceAssemblies.Contains(type.Assembly); - } public bool ShouldGenerate(FieldInfo fi) { @@ -81,63 +66,16 @@ public string GenerateField(FieldInfo fi) { var valueType = fi.FieldType.GetGenericArguments()[0]; var variantType = fi.FieldType.GetGenericTypeDefinition(); - var readerSuffix = $"{VariantPropertyNameSuffix}Reader"; - var writerSuffix = $"{VariantPropertyNameSuffix}Writer"; - var readerAndWriterSuffix = $"{VariantPropertyNameSuffix}ReaderAndWriter"; - if (ShouldGenerateVariantInterface) - { - if (variantType == typeof(BlobVariantReaderAndWriter<>)) - { - GenerateVariantInterface(valueType, readerSuffix, VariantGenerator.CreateReaderVariants); - GenerateVariantInterface(valueType, writerSuffix, VariantGenerator.CreateWriterVariants); - GenerateVariantInterface(valueType, readerAndWriterSuffix, (writer, valueType, isReferenceType, suffix) => - { - writer.CreateReaderAndWriterVariants(valueType, isReferenceType, suffix); - writer.CreateSerializedReaderAndWriterVariant(valueType, suffix, $"{VariantPropertyNameSuffix}Reader", $"{VariantPropertyNameSuffix}Writer"); - }); - } - else if (variantType == typeof(BlobVariantReader<>)) - { - GenerateVariantInterface(valueType, readerSuffix, VariantGenerator.CreateReaderVariants); - } - else if (variantType == typeof(BlobVariantWriter<>)) - { - GenerateVariantInterface(valueType, writerSuffix, VariantGenerator.CreateWriterVariants); - } - } - if (variantType == typeof(BlobVariantReaderAndWriter<>)) - return $"public {VariantInterfaceNamespace}.{valueType.Name}SerializedReaderAndWriterVariant {fi.Name};"; - - var suffix = variantType == typeof(BlobVariantReader<>) ? readerSuffix : writerSuffix; - var stringBuilder = new StringBuilder(); - stringBuilder.Append("[UnityEngine.SerializeReference, SerializeReferenceButton]"); - stringBuilder.Append(" "); - stringBuilder.AppendLine($"public {VariantInterfaceNamespace}.{valueType.Name}{suffix} {fi.Name};"); - return stringBuilder.ToString(); + return $"public {VariantInterfaceNamespace}.SerializedVariantRW<{valueType.FullName}> {fi.Name};"; + if (variantType == typeof(BlobVariantReader<>)) + return $"public {VariantInterfaceNamespace}.SerializedVariantRO<{valueType.FullName}> {fi.Name};"; + return $"public {VariantInterfaceNamespace}.SerializedVariantWO<{valueType.FullName}> {fi.Name};"; } public string GenerateBuild(FieldInfo fi) { return $"{fi.Name}.Allocate(ref builder, ref data.{fi.Name}, Self, tree);"; } - - private void GenerateVariantInterface(Type valueType, string suffix, CreateVariants createVariants) - { - var directory = Path.GetDirectoryName(AssetDatabase.GetAssetPath(Generator)) + "/" + VariantInterfaceDirectory; - if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); - - var filepath = $"{directory}/{valueType.Name}{suffix}.cs"; - if (!File.Exists(filepath) || File.ReadLines(filepath).FirstOrDefault() == HEAD_LINE) - { - using var writer = new StreamWriter(filepath); - writer.WriteLine(HEAD_LINE); - writer.WriteLine(VariantGenerator.NamespaceBegin(VariantInterfaceNamespace)); - createVariants(writer, valueType, IsReferenceType, suffix); - writer.WriteLine(VariantGenerator.NamespaceEnd()); - } - } - - private delegate void CreateVariants(StreamWriter writer, Type valueType, Predicate isReferenceType, string suffix); } } diff --git a/Packages/builder.component/Runtime/Components/BTDelayTimer.cs b/Packages/builder.component/Runtime/Components/BTDelayTimer.cs index 4fc591c7..b8867aa9 100644 --- a/Packages/builder.component/Runtime/Components/BTDelayTimer.cs +++ b/Packages/builder.component/Runtime/Components/BTDelayTimer.cs @@ -8,7 +8,7 @@ namespace EntitiesBT.Components { public class BTDelayTimer : BTNode { - public EntitiesBT.Variant.SingleSerializedReaderAndWriterVariant TimerSeconds; + public EntitiesBT.Variant.SerializedVariantRW TimerSeconds; protected override void Build(ref EntitiesBT.Nodes.DelayTimerNode data, BlobBuilder builder, ITreeNode[] tree) { TimerSeconds.Allocate(ref builder, ref data.TimerSeconds, Self, tree); diff --git a/Packages/builder.component/Runtime/Components/BTTimer.cs b/Packages/builder.component/Runtime/Components/BTTimer.cs index a9868edf..d069f801 100644 --- a/Packages/builder.component/Runtime/Components/BTTimer.cs +++ b/Packages/builder.component/Runtime/Components/BTTimer.cs @@ -8,7 +8,7 @@ namespace EntitiesBT.Components { public class BTTimer : BTNode { - public EntitiesBT.Variant.SingleSerializedReaderAndWriterVariant CountdownSeconds; + public EntitiesBT.Variant.SerializedVariantRW CountdownSeconds; public EntitiesBT.Core.NodeState BreakReturnState; protected override void Build(ref EntitiesBT.Nodes.TimerNode data, BlobBuilder builder, ITreeNode[] tree) { diff --git a/Packages/builder.component/Runtime/NodeCodeGenerator.asset b/Packages/builder.component/Runtime/NodeCodeGenerator.asset index 9f1709b7..d37526fc 100644 --- a/Packages/builder.component/Runtime/NodeCodeGenerator.asset +++ b/Packages/builder.component/Runtime/NodeCodeGenerator.asset @@ -46,12 +46,6 @@ MonoBehaviour: 00000005: type: {class: BlobVariantFieldCodeGenerator, ns: EntitiesBT.Editor, asm: EntitiesBT.Components.Editor} data: - ShouldGenerateVariantInterface: 1 - VariantInterfaceDirectory: Variant VariantInterfaceNamespace: EntitiesBT.Variant - VariantPropertyNameSuffix: Variant - Generator: {fileID: 11400000} - Assembly: {fileID: 5897886265953266890, guid: c7babe7561eb244059259745ef27b866, - type: 3} 00000006: type: {class: DefaultNodeDataFieldCodeGenerator, ns: EntitiesBT.Editor, asm: EntitiesBT.Editor} diff --git a/Packages/builder.component/Runtime/Variant/NodeVariant.cs b/Packages/builder.component/Runtime/Variant/NodeVariant.cs index 1d4b8ebd..d0432b6e 100644 --- a/Packages/builder.component/Runtime/Variant/NodeVariant.cs +++ b/Packages/builder.component/Runtime/Variant/NodeVariant.cs @@ -6,7 +6,6 @@ using Unity.Collections.LowLevel.Unsafe; using Unity.Entities; using UnityEngine; -using UnityEngine.Scripting; using static EntitiesBT.Core.Utilities; namespace EntitiesBT.Variant @@ -21,8 +20,12 @@ public VariantNodeObjectAttribute(string nodeObjectFieldName) } } + [VariantClass(ID_RUNTIME_NODE_VARIANT)] public class NodeVariant { + public const string ID_RUNTIME_NODE = "220681AA-D884-4E87-90A8-5A8657A734BD"; + public const string ID_RUNTIME_NODE_VARIANT = "7DE6DCA5-71DF-4145-91A6-17EB813B9DEB"; + // TODO: check loop ref? [Serializable] public class Any : IVariant where T : unmanaged @@ -40,23 +43,20 @@ public unsafe IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVaria [Serializable] public class Writer : Any, IVariantWriter where T : unmanaged {} [Serializable] public class ReaderAndWriter : Any, IVariantReaderAndWriter where T : unmanaged {} - public const string ID_RUNTIME_NODE = "220681AA-D884-4E87-90A8-5A8657A734BD"; - public const string ID_RUNTIME_NODE_VARIANT = "7DE6DCA5-71DF-4145-91A6-17EB813B9DEB"; - - [Preserve, WriterMethod(ID_RUNTIME_NODE_VARIANT)] + [WriterMethod] private static unsafe void WriteVariableFunc(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb, T value) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - ref var data = ref blobVariant.Value(); + ref var data = ref blobVariant.As(); var ptr = blob.GetRuntimeDataPtr(data.Index); ref var variable = ref UnsafeUtility.AsRef>(IntPtr.Add(ptr, data.Offset).ToPointer()); // TODO: check writable on editor? variable.Value.WriteWithRefFallback(index, ref blob, ref bb, value); } - [Preserve, RefReaderMethod(ID_RUNTIME_NODE)] + [RefReaderMethod(OverrideGuid = ID_RUNTIME_NODE)] private static ref T GetRuntimeNodeData(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob @@ -65,13 +65,13 @@ private static ref T GetRuntimeNodeData(ref BlobVaria return ref GetValue(ref blobVariant, blob.GetRuntimeDataPtr); } - [Preserve, ReaderMethod(ID_RUNTIME_NODE_VARIANT)] + [ReaderMethod] private static unsafe T GetRuntimeNodeVariable(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - ref var data = ref blobVariant.Value(); + ref var data = ref blobVariant.As(); var ptr = blob.GetRuntimeDataPtr(data.Index); ref var variable = ref UnsafeUtility.AsRef>(IntPtr.Add(ptr, data.Offset).ToPointer()); return variable.Read(index, ref blob, ref bb); @@ -79,7 +79,7 @@ private static unsafe T GetRuntimeNodeVariable(ref Bl private static unsafe ref T GetValue(ref BlobVariant blobVariant, Func ptrFunc) where T : unmanaged { - ref var data = ref blobVariant.Value(); + ref var data = ref blobVariant.As(); var ptr = ptrFunc(data.Index); return ref UnsafeUtility.AsRef(IntPtr.Add(ptr, data.Offset).ToPointer()); } diff --git a/Packages/builder.component/Runtime/Variant/SingleVariantReader.cs b/Packages/builder.component/Runtime/Variant/SingleVariantReader.cs deleted file mode 100644 index abc228ff..00000000 --- a/Packages/builder.component/Runtime/Variant/SingleVariantReader.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Automatically generated by `BlobVariantFieldCodeGenerator` -namespace EntitiesBT.Variant -{ - -public interface SingleVariantReader : EntitiesBT.Variant.IVariantReader { } -public class SingleNodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, SingleVariantReader { } -public class SingleComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, SingleVariantReader { } -public class SingleLocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, SingleVariantReader { } -public class SingleScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, SingleVariantReader { } - - -} - diff --git a/Packages/builder.component/Runtime/Variant/SingleVariantReader.cs.meta b/Packages/builder.component/Runtime/Variant/SingleVariantReader.cs.meta deleted file mode 100644 index 67dd6d9a..00000000 --- a/Packages/builder.component/Runtime/Variant/SingleVariantReader.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 50ac4a5047df7494ca76349586d85730 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/builder.component/Runtime/Variant/SingleVariantReaderAndWriter.cs b/Packages/builder.component/Runtime/Variant/SingleVariantReaderAndWriter.cs deleted file mode 100644 index dc9b67de..00000000 --- a/Packages/builder.component/Runtime/Variant/SingleVariantReaderAndWriter.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Automatically generated by `BlobVariantFieldCodeGenerator` -namespace EntitiesBT.Variant -{ - -public interface SingleVariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class SingleNodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, SingleVariantReaderAndWriter { } -public class SingleComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, SingleVariantReaderAndWriter { } -public class SingleLocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, SingleVariantReaderAndWriter { } - - -[System.Serializable] -public class SingleSerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private SingleVariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private SingleVariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private SingleVariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} - -} - diff --git a/Packages/builder.component/Runtime/Variant/SingleVariantWriter.cs b/Packages/builder.component/Runtime/Variant/SingleVariantWriter.cs deleted file mode 100644 index fb2a84a2..00000000 --- a/Packages/builder.component/Runtime/Variant/SingleVariantWriter.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Automatically generated by `BlobVariantFieldCodeGenerator` -namespace EntitiesBT.Variant -{ - -public interface SingleVariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class SingleNodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, SingleVariantWriter { } -public class SingleComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, SingleVariantWriter { } - - -} - diff --git a/Packages/builder.component/package.json b/Packages/builder.component/package.json index d56a5f76..84e29245 100644 --- a/Packages/builder.component/package.json +++ b/Packages/builder.component/package.json @@ -1,11 +1,10 @@ { "name": "com.quabug.entities-bt.builder.component", "description": "Behavior Tree for Unity Entities - Component Builder", - "version": "1.0.2", + "version": "1.2.0", "unity": "2020.2", "displayName": "EntitiesBT - Component Builder", "dependencies": { - "com.quabug.entities-bt.essential": "1.0.1", - "com.quabug.entities-bt.variable.scriptable-object": "1.0.1" + "com.quabug.entities-bt.essential": "1.2.0" } } \ No newline at end of file diff --git a/Packages/builder.odin/Editor/EntitiesBT.Builder.Odin.Editor.asmdef b/Packages/builder.odin/Editor/EntitiesBT.Builder.Odin.Editor.asmdef index d347382c..d7221597 100644 --- a/Packages/builder.odin/Editor/EntitiesBT.Builder.Odin.Editor.asmdef +++ b/Packages/builder.odin/Editor/EntitiesBT.Builder.Odin.Editor.asmdef @@ -6,7 +6,9 @@ "EntitiesBT.Runtime", "EntitiesBT.Builder.Odin" ], - "includePlatforms": [], + "includePlatforms": [ + "Editor" + ], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": true, diff --git a/Packages/builder.odin/Runtime/OdinEditorUtilities.cs.meta b/Packages/builder.odin/Runtime/OdinEditorUtilities.cs.meta index 4646fee9..f871e334 100644 --- a/Packages/builder.odin/Runtime/OdinEditorUtilities.cs.meta +++ b/Packages/builder.odin/Runtime/OdinEditorUtilities.cs.meta @@ -1,3 +1,11 @@ -fileFormatVersion: 2 +fileFormatVersion: 2 guid: 2a3fa9f15b014abd8642bfa60467124c -timeCreated: 1615010740 \ No newline at end of file +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/builder.odin/Runtime/OdinNode.cs.meta b/Packages/builder.odin/Runtime/OdinNode.cs.meta index a3cb4719..89305acb 100644 --- a/Packages/builder.odin/Runtime/OdinNode.cs.meta +++ b/Packages/builder.odin/Runtime/OdinNode.cs.meta @@ -1,3 +1,11 @@ -fileFormatVersion: 2 +fileFormatVersion: 2 guid: 965dafbd4a8641c9a0102f44412fb206 -timeCreated: 1614954450 \ No newline at end of file +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/builder.odin/Runtime/OdinNodeVariant.cs.meta b/Packages/builder.odin/Runtime/OdinNodeVariant.cs.meta index a045f5d1..c4b651fc 100644 --- a/Packages/builder.odin/Runtime/OdinNodeVariant.cs.meta +++ b/Packages/builder.odin/Runtime/OdinNodeVariant.cs.meta @@ -1,3 +1,11 @@ -fileFormatVersion: 2 +fileFormatVersion: 2 guid: d05280ccd7a448fda0d0103c8d62d4a6 -timeCreated: 1614965419 \ No newline at end of file +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/builder.odin/Runtime/OdinSerializedVariant.cs.meta b/Packages/builder.odin/Runtime/OdinSerializedVariant.cs.meta index 25535faa..989276a2 100644 --- a/Packages/builder.odin/Runtime/OdinSerializedVariant.cs.meta +++ b/Packages/builder.odin/Runtime/OdinSerializedVariant.cs.meta @@ -1,3 +1,11 @@ -fileFormatVersion: 2 +fileFormatVersion: 2 guid: 7fe2dd8f03be4819889da871555e91c4 -timeCreated: 1614964921 \ No newline at end of file +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/builder.odin/Runtime/SaveToLocalVariant.cs b/Packages/builder.odin/Runtime/SaveToLocalVariant.cs index 8c1c9f55..c1a271e7 100644 --- a/Packages/builder.odin/Runtime/SaveToLocalVariant.cs +++ b/Packages/builder.odin/Runtime/SaveToLocalVariant.cs @@ -7,6 +7,7 @@ namespace EntitiesBT.Components.Odin { + [VariantClass(GUID)] public class SaveToLocalVariant { [Serializable] @@ -27,7 +28,7 @@ public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INo public const string GUID = "F315684E-2AA1-4780-B31B-2791A93359F1"; - [Preserve, RefReaderMethod(GUID)] + [RefReaderMethod] private static ref T Read(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob diff --git a/Packages/builder.odin/Runtime/SaveToLocalVariant.cs.meta b/Packages/builder.odin/Runtime/SaveToLocalVariant.cs.meta index 9407c73f..ea017277 100644 --- a/Packages/builder.odin/Runtime/SaveToLocalVariant.cs.meta +++ b/Packages/builder.odin/Runtime/SaveToLocalVariant.cs.meta @@ -1,3 +1,11 @@ -fileFormatVersion: 2 +fileFormatVersion: 2 guid: 800828d0438e4cabb27681ea8f85ab2b -timeCreated: 1614967676 \ No newline at end of file +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/builder.odin/package.json b/Packages/builder.odin/package.json index 231024de..252bf582 100644 --- a/Packages/builder.odin/package.json +++ b/Packages/builder.odin/package.json @@ -1,17 +1,10 @@ { "name": "com.quabug.entities-bt.builder.odin", "description": "Behavior Tree for Unity Entities - Odin Builder", - "version": "1.0.1", + "version": "1.2.0", "unity": "2020.2", "displayName": "EntitiesBT - Odin Builder", "dependencies": { - "com.quabug.entities-bt.builder.component": "1.0.2" - }, - "samples": [ - { - "displayName": "Sample", - "description": "Sample", - "path": "Sample~" - } - ] + "com.quabug.entities-bt.builder.component": "1.2.0" + } } \ No newline at end of file diff --git a/Packages/builder.visual/Runtime/BehaviorTreeEntity.cs b/Packages/builder.visual/Runtime/BehaviorTreeEntity.cs index 65ae1f15..ba950609 100644 --- a/Packages/builder.visual/Runtime/BehaviorTreeEntity.cs +++ b/Packages/builder.visual/Runtime/BehaviorTreeEntity.cs @@ -10,7 +10,7 @@ namespace EntitiesBT.Builder.Visual { public class BehaviorTreeEntity : MonoBehaviour, IConvertGameObjectToEntity { - [SerializeReference, SerializeReferenceButton] private IBehaviorTreeSource _source = default; + [SerializeReference, SerializeReferenceDrawer] private IBehaviorTreeSource _source = default; [SerializeField] private BehaviorTreeThread _thread = BehaviorTreeThread.ForceRunOnMainThread; [Tooltip("add queried components of behavior tree into entity automatically")] diff --git a/Packages/builder.visual/Runtime/Extensions.cs b/Packages/builder.visual/Runtime/Extensions.cs index 87a46bc2..f24908c3 100644 --- a/Packages/builder.visual/Runtime/Extensions.cs +++ b/Packages/builder.visual/Runtime/Extensions.cs @@ -26,7 +26,7 @@ public DataPortReaderAndWriter(bool isLinked, InputDataPort input, OutputDataPor } } - public readonly struct SerializedVisualReaderAndWriter : ISerializedVariantReaderAndWriter where T : unmanaged + public readonly struct SerializedVisualReaderAndWriter : ISerializedVariantRW where T : unmanaged { public bool IsLinked { get; } public IVariantReaderAndWriter ReaderAndWriter { get; } @@ -94,7 +94,7 @@ public static IVariantWriter ToVariantWriter(this OutputDataPort port, [No } [Pure] - public static ISerializedVariantReaderAndWriter ToVariantReaderAndWriter(this in DataPortReaderAndWriter port, [NotNull] GraphInstance instance, [NotNull] GraphDefinition definition) where T : unmanaged + public static ISerializedVariantRW ToVariantReaderAndWriter(this in DataPortReaderAndWriter port, [NotNull] GraphInstance instance, [NotNull] GraphDefinition definition) where T : unmanaged { if (!port.IsLinked) throw new NotImplementedException(); return new SerializedVisualReaderAndWriter(true, ToLocalReaderAndWriter(instance, port.Input), null, null); diff --git a/Packages/builder.visual/Runtime/Variant/GraphVariant.cs b/Packages/builder.visual/Runtime/Variant/GraphVariant.cs index 1a2b9adf..82e676f2 100644 --- a/Packages/builder.visual/Runtime/Variant/GraphVariant.cs +++ b/Packages/builder.visual/Runtime/Variant/GraphVariant.cs @@ -5,11 +5,11 @@ using EntitiesBT.Variant; using Runtime; using Unity.Entities; -using UnityEngine.Scripting; using static EntitiesBT.Core.Utilities; namespace EntitiesBT.Builder.Visual { + [VariantClass(GUID)] public static class GraphVariant { public const string GUID = "7BCAE9F4-BE78-424D-84DD-5DA101A3F07F"; @@ -26,13 +26,13 @@ public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INo } } - [Preserve, ReaderMethod(GUID)] + [ReaderMethod] private static T GetData(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - ref var port = ref blobVariant.Value(); + ref var port = ref blobVariant.As(); var behaviorTree = bb.GetData().RefValue.BehaviorTree; // HACK: how to support multiple worlds? var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; @@ -40,7 +40,7 @@ private static T GetData(ref BlobVariant blobVariant, return graphInstance.ReadValue(port); } - [Preserve, AccessorMethod(GUID)] + [AccessorMethod] private static IEnumerable GetComponentAccess(ref BlobVariant variant) { return ComponentType.ReadOnly().Yield(); diff --git a/Packages/codegen/Editor/AccessorAttributeILPostProcessor.cs b/Packages/codegen/Editor/AccessorAttributeILPostProcessor.cs index 9ae2a29e..8b47f72f 100644 --- a/Packages/codegen/Editor/AccessorAttributeILPostProcessor.cs +++ b/Packages/codegen/Editor/AccessorAttributeILPostProcessor.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using EntitiesBT.Core; using Mono.Cecil; @@ -13,29 +14,37 @@ public class AccessorAttributeILPostProcessor : IILCodeGenerator public bool Generate(AssemblyDefinition assemblyDefinition) { - Logger.Debug($"generate accessor attributes for {assemblyDefinition.Name}"); - var methods = assemblyDefinition.MainModule.GetAllTypes() - .Where(type => type.IsClass && !type.IsAbstract && type.TypeImplements(typeof(INodeData))) - .SelectMany(FetchNodeDataMethods) - .Where(method => !method.CustomAttributes.FindAccessorAttributes().Any()) - ; - var modified = false; - foreach (var method in methods) + var sw = Stopwatch.StartNew(); + try { - var attributes = method.GenerateAccessorAttributes(); - if (!attributes.Any()) continue; + var methods = assemblyDefinition.MainModule.GetAllTypes() + .Where(type => type.IsClass && !type.IsAbstract && type.TypeImplements(typeof(INodeData))) + .SelectMany(FetchNodeDataMethods) + .Where(method => method != null && !method.CustomAttributes.FindAccessorAttributes().Any()) + ; + var modified = false; + foreach (var method in methods) + { + var attributes = method.GenerateAccessorAttributes(); + if (!attributes.Any()) continue; - Logger.Debug($"generate accessor attributes for {method.FullName}"); - modified = true; - method.CustomAttributes.AddRange(attributes); + Logger.Debug($"generate accessor attributes for {method.FullName}"); + modified = true; + method.CustomAttributes.AddRange(attributes); + } + + return modified; + } + finally + { + Logger.Debug($"generate accessor attributes for {assemblyDefinition.Name} ({sw.ElapsedMilliseconds}ms)"); } - return modified; } IEnumerable FetchNodeDataMethods(TypeDefinition type) { yield return type.GetMethod(nameof(INodeData.Tick)); - yield return type.GetMethod(nameof(INodeData.Reset)); + yield return type.GetMethodNullable(nameof(ICustomResetAction.Reset)); } } } \ No newline at end of file diff --git a/Packages/codegen/Editor/AssemblyInfo.cs b/Packages/codegen/Editor/AssemblyInfo.cs index 822d1c47..3f9a3ffa 100644 --- a/Packages/codegen/Editor/AssemblyInfo.cs +++ b/Packages/codegen/Editor/AssemblyInfo.cs @@ -1,3 +1,4 @@ using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("EntitiesBT.CodeGen.Tests")] \ No newline at end of file +[assembly: InternalsVisibleTo("EntitiesBT.Tests.Editor")] +[assembly: InternalsVisibleTo("EntitiesBT.Tests.Runtime")] diff --git a/Packages/codegen/Editor/CecilExtension.cs b/Packages/codegen/Editor/CecilExtension.cs index e5c58280..4dbc1431 100644 --- a/Packages/codegen/Editor/CecilExtension.cs +++ b/Packages/codegen/Editor/CecilExtension.cs @@ -5,7 +5,11 @@ using EntitiesBT.Core; using JetBrains.Annotations; using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Cecil.Rocks; using Mono.Collections.Generic; +using ICustomAttributeProvider = Mono.Cecil.ICustomAttributeProvider; +using MethodAttributes = Mono.Cecil.MethodAttributes; using TypeAttributes = Mono.Cecil.TypeAttributes; namespace EntitiesBT.CodeGen.Editor @@ -121,6 +125,12 @@ public static MethodDefinition GetMethod([NotNull] this TypeDefinition self, [No return self.Methods.First(m => m.Name == name); } + [Pure, CanBeNull] + public static MethodDefinition GetMethodNullable([NotNull] this TypeDefinition self, [NotNull] string name) + { + return self.Methods.FirstOrDefault(m => m.Name == name); + } + [Pure] public static void AddRange([NotNull] this Collection self, [NotNull, ItemNotNull] IEnumerable items) { @@ -178,7 +188,199 @@ public static string GetCodeName(this FieldDefinition fieldDefinition) } return name; } + public static bool IsINodeDataStruct(this TypeDefinition typeDefinition) => typeDefinition.TypeImplements(typeof(INodeData)) && typeDefinition.IsValueType(); + + public static string ToReadableName(this TypeReference type) + { + if (!type.IsGenericInstance) return type.Name; + return $"{type.Name.Split('`')[0]}<{string.Join(",", ((GenericInstanceType)type).GenericArguments.Select(a => a.Name))}>"; + } + + public static IReadOnlyList ResolveGenericArguments(this TypeDefinition self, TypeReference @base) + { + if (!@base.IsGenericInstance) + return self.IsGenericInstance ? self.GenericParameters.ToArray() : Array.Empty(); + + var genericBase = (GenericInstanceType) @base; + var selfBase = ParentTypes(self).Where(p => IsTypeEqual(p, @base)) + // let it throw + .Select(p => (GenericInstanceType)p) + .First(p => IsPartialGenericMatch(p, genericBase)) + ; + var genericArguments = new TypeReference[self.GenericParameters.Count]; + var selfBaseGenericArguments = selfBase.GenericArguments.ToList(); + for (var i = 0; i < self.GenericParameters.Count; i++) + { + var genericParameter = self.GenericParameters[i]; + var index = selfBaseGenericArguments.FindIndex(type => type.Name == genericParameter.Name); + if (index >= 0) genericArguments[i] = genericBase.GenericArguments[index]; + else genericArguments[i] = self.GenericParameters[i]; + } + return genericArguments; + } + + public static IEnumerable ParentTypes(this TypeDefinition type) + { + var parents = Enumerable.Empty(); + if (type.HasInterfaces) parents = type.Interfaces.Select(i => i.InterfaceType); + if (type.BaseType != null) parents = parents.Append(type.BaseType); + return parents; + } + + public static bool IsPartialGenericMatch(this GenericInstanceType partial, GenericInstanceType concrete) + { + if (!IsTypeEqual(partial, concrete)) + throw new ArgumentException($"{partial} and {concrete} have different type"); + if (partial.GenericArguments.Count != concrete.GenericArguments.Count) + throw new ArgumentException($"{partial} and {concrete} have different count of generic arguments"); ; + if (concrete.GenericArguments.Any(arg => arg.IsGenericParameter)) + throw new ArgumentException($"{concrete} is not a concrete generic type"); ; + + return partial.GenericArguments + .Zip(concrete.GenericArguments, (partialArgument, concreteArgument) => (partialArgument, concreteArgument)) + .All(t => t.partialArgument.IsGenericParameter || IsTypeEqual(t.partialArgument, t.concreteArgument)) + ; + } + + public static bool IsTypeEqual(this TypeReference lhs, TypeReference rhs) + { + return IsTypeEqual(lhs.Resolve(), rhs.Resolve()); + } + + public static bool IsTypeEqual(this TypeDefinition lhs, TypeDefinition rhs) + { + return lhs != null && rhs != null && + lhs.MetadataToken == rhs.MetadataToken && + lhs.Module.Name == rhs.Module.Name + ; + } + + + //.method public hidebysig specialname rtspecialname instance void + // .ctor() cil managed + //{ + // .maxstack 8 + + // IL_0000: ldarg.0 // this + // IL_0001: call instance void class [GenericSerializeReference.Tests]GenericSerializeReference.Tests.MultipleGeneric/Object`2::.ctor() + // IL_0006: nop + // IL_0007: ret + + //} // end of method Object::.ctor + public static void AddEmptyCtor(this TypeDefinition type, MethodReference baseCtor) + { + var attributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; + var ctor = new MethodDefinition(".ctor", attributes, baseCtor.ReturnType); + ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Call, baseCtor)); + ctor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + type.Methods.Add(ctor); + } + + public static TypeReference CreateTypeReference(this TypeDefinition type, IReadOnlyList genericArguments) + { + return type.HasGenericParameters + ? (TypeReference) type.MakeGenericInstanceType(genericArguments.ToArray()) + : type + ; + } + + public static bool IsPublicOrNestedPublic(this TypeDefinition type) + { + foreach (var t in type.GetSelfAndAllDeclaringTypes()) + { + if ((t.IsNested && !t.IsNestedPublic) || (!t.IsNested && !t.IsPublic)) return false; + } + return true; + } + + public static string NameWithOuterClasses(this TypeDefinition type) + { + return type.GetSelfAndAllDeclaringTypes().Aggregate("", (name, t) => $"{t.Name}.{name}"); + } + + public static IEnumerable GetSelfAndAllDeclaringTypes(this TypeDefinition type) + { + yield return type; + while (type.DeclaringType != null) + { + yield return type.DeclaringType; + type = type.DeclaringType; + } + } + + public static CustomAttribute AddCustomAttribute( + this ICustomAttributeProvider attributeProvider + , ModuleDefinition module + , params Type[] constructorTypes + ) where T : Attribute + { + var attribute = new CustomAttribute(module.ImportReference(typeof(T).GetConstructor(constructorTypes))); + attributeProvider.CustomAttributes.Add(attribute); + return attribute; + } + + public static TypeDefinition GenerateDerivedClass(this TypeReference baseType, IEnumerable genericArguments, string className, ModuleDefinition module = null) + { + // .class nested public auto ansi beforefieldinit + // Object + // extends class [GenericSerializeReference.Tests]GenericSerializeReference.Tests.MultipleGeneric/Object`2 + // implements GenericSerializeReference.Tests.TestMonoBehavior/IBase + // { + + // .method public hidebysig specialname rtspecialname instance void + // .ctor() cil managed + // { + // .maxstack 8 + + // IL_0000: ldarg.0 // this + // IL_0001: call instance void class [GenericSerializeReference.Tests]GenericSerializeReference.Tests.MultipleGeneric/Object`2::.ctor() + // IL_0006: nop + // IL_0007: ret + + // } // end of method Object::.ctor + // } // end of class Object + module ??= baseType.Module; + var classAttributes = TypeAttributes.Class | TypeAttributes.NestedPublic | TypeAttributes.BeforeFieldInit; + var type = new TypeDefinition("", className, classAttributes); + type.BaseType = baseType.HasGenericParameters ? baseType.MakeGenericInstanceType(genericArguments.ToArray()) : baseType; + var ctor = module.ImportReference(baseType.Resolve().GetConstructors().First(c => !c.HasParameters)).Resolve(); + var ctorCall = new MethodReference(ctor.Name, module.ImportReference(ctor.ReturnType)) + { + DeclaringType = type.BaseType, + HasThis = ctor.HasThis, + ExplicitThis = ctor.ExplicitThis, + CallingConvention = ctor.CallingConvention, + }; + type.AddEmptyCtor(ctorCall); + return type; + } + + public static TypeDefinition CreateNestedStaticPrivateClass(this TypeDefinition type, string name) + { + // .class nested private abstract sealed auto ansi beforefieldinit + // <$PropertyName>__generic_serialize_reference + // extends [mscorlib]System.Object + var typeAttributes = TypeAttributes.Class | + TypeAttributes.Sealed | + TypeAttributes.Abstract | + TypeAttributes.NestedPrivate | + TypeAttributes.BeforeFieldInit; + var nestedType = new TypeDefinition("", name, typeAttributes); + nestedType.BaseType = type.Module.ImportReference(typeof(object)); + type.NestedTypes.Add(nestedType); + return nestedType; + } + + public static IEnumerable GetAttributesOf([NotNull] this ICustomAttributeProvider provider) where T : Attribute + { + return provider.HasCustomAttributes ? + provider.CustomAttributes.Where(IsAttributeOf) : + Enumerable.Empty(); + + static bool IsAttributeOf(CustomAttribute attribute) => attribute.AttributeType.FullName == typeof(T).FullName; + } } } \ No newline at end of file diff --git a/Packages/codegen/Editor/Extensions.cs b/Packages/codegen/Editor/Extensions.cs new file mode 100644 index 00000000..d1e5c4c7 --- /dev/null +++ b/Packages/codegen/Editor/Extensions.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using JetBrains.Annotations; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Cecil.Rocks; +using Unity.CompilationPipeline.Common.Diagnostics; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace EntitiesBT.CodeGen.Editor +{ + internal static class EnumerableExtension + { + public static IEnumerable Yield(this T value) + { + yield return value; + } + + public static int FindLastIndexOf(this IList list, Predicate predicate) + { + for (var i = list.Count - 1; i >= 0; i--) + { + if (predicate(list[i])) + return i; + } + return -1; + } + } + + internal static class PostProcessorExtension + { + public static AssemblyDefinition LoadAssembly(this ICompiledAssembly compiledAssembly, IAssemblyResolver resolver) + { + var symbolStream = new MemoryStream(compiledAssembly.InMemoryAssembly.PdbData.ToArray()); + var readerParameters = new ReaderParameters + { + SymbolStream = symbolStream, + SymbolReaderProvider = new PortablePdbReaderProvider(), + AssemblyResolver = resolver, + ReflectionImporterProvider = new PostProcessorReflectionImporterProvider(), + ReadingMode = ReadingMode.Immediate, + }; + var peStream = new MemoryStream(compiledAssembly.InMemoryAssembly.PeData.ToArray()); + return AssemblyDefinition.ReadAssembly(peStream, readerParameters); + } + + public static IEnumerable LoadLibraryAssemblies(this ICompiledAssembly compiledAssembly, PostProcessorAssemblyResolver resolver) + { + return compiledAssembly.References.Where(name => name.StartsWith("Library")).Select(resolver.Resolve); + } + + public static ILPostProcessorLogger CreateLogger(this AssemblyDefinition assembly) + { + var logger = new ILPostProcessorLogger(new List()); + // var loggerAttributes = assembly.GetAttributesOf(); + // if (loggerAttributes.Any()) logger.LogLevel = (LogLevel)loggerAttributes.First().ConstructorArguments[0].Value; + return logger; + } + } +} \ No newline at end of file diff --git a/Packages/codegen/Tests~/TestCecilExtension.cs.meta b/Packages/codegen/Editor/Extensions.cs.meta similarity index 83% rename from Packages/codegen/Tests~/TestCecilExtension.cs.meta rename to Packages/codegen/Editor/Extensions.cs.meta index 617b5628..cf64e9c1 100644 --- a/Packages/codegen/Tests~/TestCecilExtension.cs.meta +++ b/Packages/codegen/Editor/Extensions.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a3dfcdb452164f540909213fe3e7078c +guid: 4feb796af3c54b84faccb00f50e8fe88 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs b/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs index cb37bb79..c9302700 100644 --- a/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs +++ b/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs @@ -14,9 +14,9 @@ internal class PostProcessorAssemblyResolver : IAssemblyResolver private readonly IDictionary _cache = new Dictionary(); private readonly IReadOnlyList _references; - public PostProcessorAssemblyResolver([NotNull] IReadOnlyList references) + public PostProcessorAssemblyResolver([NotNull] IEnumerable references) { - _references = references; + _references = references.ToArray(); } public void Dispose() @@ -30,6 +30,11 @@ public AssemblyDefinition Resolve(AssemblyNameReference name) return Resolve(name, new ReaderParameters(ReadingMode.Deferred)); } + public AssemblyDefinition Resolve(string name) + { + return Resolve(new AssemblyNameReference(name, new Version()), new ReaderParameters(ReadingMode.Deferred)); + } + public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) { lock (_cache) @@ -59,11 +64,8 @@ public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters p private string FindFile(AssemblyNameReference name) { - var fileName = _references.FirstOrDefault(r => Path.GetFileName(r) == name.Name + ".dll"); - if (fileName != null) return fileName; - - // perhaps the type comes from an exe instead - fileName = _references.FirstOrDefault(r => Path.GetFileName(r) == name.Name + ".exe"); + var fileName = _references.FirstOrDefault(r => + r == name.Name || Path.GetFileName(r) == name.Name + ".dll" || Path.GetFileName(r) == name.Name + ".exe"); if (fileName != null) return fileName; //Unfortunately the current ICompiledAssembly API only provides direct references. diff --git a/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs.meta b/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs.meta index c3265a57..80ff727c 100644 --- a/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs.meta +++ b/Packages/codegen/Editor/PostProcessorAssemblyResolver.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c1adc5d4c9af46cb8f08b06f46487929 +guid: 4dc1ddb05b2bb4faf9b43527dd18f883 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Packages/codegen/Editor/PostProcessorReflectionImporterProvider.cs.meta b/Packages/codegen/Editor/PostProcessorReflectionImporterProvider.cs.meta index 3a65d965..4fb0820c 100644 --- a/Packages/codegen/Editor/PostProcessorReflectionImporterProvider.cs.meta +++ b/Packages/codegen/Editor/PostProcessorReflectionImporterProvider.cs.meta @@ -1,3 +1,11 @@ -fileFormatVersion: 2 -guid: e7b00fcb1d5440e585b2a39fcef2f0ea -timeCreated: 1613631884 \ No newline at end of file +fileFormatVersion: 2 +guid: 7b8274ea305c44056b45362f73b155b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/codegen/Editor/ReflectionExtension.cs b/Packages/codegen/Editor/ReflectionExtension.cs index 7c3dfb46..2ef9ab9d 100644 --- a/Packages/codegen/Editor/ReflectionExtension.cs +++ b/Packages/codegen/Editor/ReflectionExtension.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Text.RegularExpressions; using JetBrains.Annotations; namespace EntitiesBT.CodeGen.Editor @@ -36,5 +37,11 @@ public static IEnumerable CreateInstances([NotNull] this AppDomain appDoma .Select(type => (T) Activator.CreateInstance(type)) ; } + + [Pure] + public static string ToReadableName(this Type type) + { + return type.IsGenericType ? Regex.Replace(type.ToString(), @"(\w+)`\d+\[(.*)\]", "$1<$2>") : type.ToString(); + } } } \ No newline at end of file diff --git a/Packages/codegen/Editor/TypeTree.cs b/Packages/codegen/Editor/TypeTree.cs new file mode 100644 index 00000000..f01f92fd --- /dev/null +++ b/Packages/codegen/Editor/TypeTree.cs @@ -0,0 +1,273 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using JetBrains.Annotations; +using Mono.Cecil; +using Mono.Cecil.Rocks; + +namespace EntitiesBT.CodeGen.Editor +{ + + /// + /// + /// create tree structure for types + /// + /// "X": class + /// "<-": inherit from + /// "X(I)": X implement interface I + /// + /// A <-+-- B(I) <---- C + /// | + /// +-- D(I) <-+-- E(I) + /// | + /// +-- F + /// + /// type tree structure: A ( B ( C ) + D ( E + F ) ) + /// interface chain: I(B, D, E) + /// + public class TypeTree + { + class TypeDefinitionTokenComparer : IEqualityComparer + { + public bool Equals(TypeDefinition x, TypeDefinition y) + { + if (ReferenceEquals(x, y)) return true; + if (x == null || y == null) return false; + return new TypeKey(x).Equals(new TypeKey(y)); + } + + public int GetHashCode(TypeDefinition obj) + { + return new TypeKey(obj).GetHashCode(); + } + } + + readonly struct TypeKey : IEquatable + { + public readonly string ModuleName; + public readonly MetadataToken Token; + + public TypeKey(TypeDefinition typeDefinition) + { + ModuleName = typeDefinition.Module.Name; + Token = typeDefinition.MetadataToken; + } + + public bool Equals(TypeKey other) + { + return ModuleName == other.ModuleName && Token.Equals(other.Token); + } + + public override bool Equals(object obj) + { + return obj is TypeKey other && Equals(other); + } + + public override int GetHashCode() + { + unchecked + { + return (ModuleName.GetHashCode() * 397) ^ Token.GetHashCode(); + } + } + } + + private class TypeTreeNode + { + public ISet Interfaces { get; } = new HashSet(new TypeDefinitionTokenComparer()); + public TypeDefinition Type { get; } + public TypeTreeNode Base { get; set; } + public List Subs { get; } = new List(); + + public TypeTreeNode(TypeDefinition type) => Type = type; + + public override string ToString() + { + return $"{Type.Name}({Type.Module.Name})"; + } + } + + private readonly Dictionary _typeTreeNodeMap; + + private readonly ILogger _logger; + + /// + /// Create a type-tree from a collection of + /// + /// The source types of tree. + public TypeTree([NotNull] IEnumerable sourceTypes, ILogger logger = null) + { + _logger = logger; + _typeTreeNodeMap = new Dictionary(); + foreach (var type in sourceTypes.Where(t => t.IsClass || t.IsInterface)) CreateTypeTree(type); + } + + // TODO: + // /// + // /// Create a type-tree from a collection of + // /// + // /// The source types of tree. + // /// Excluded any types from which is not derived from base type. + // public TypeTree([NotNull] ICollection sourceTypes, [NotNull] ICollection baseTypes) + // { + // } + + /// + /// Get all derived class type of . + /// Ignore generic type argument if is a generic class with certain type of arguments. + /// + /// + /// Any type of classes derived from directly or indirectly. + /// + public IEnumerable GetAllDerivedDefinition(TypeDefinition baseType) + { + _typeTreeNodeMap.TryGetValue(new TypeKey(baseType), out var node); + if (node == null) throw new ArgumentException($"{baseType} is not part of this tree"); + return GetDescendantsAndSelf(node).Skip(1).Select(n => n.Type); + + IEnumerable GetDescendantsAndSelf(TypeTreeNode self) + { + yield return self; + foreach (var childNode in + from sub in self.Subs + from type in GetDescendantsAndSelf(sub) + select type + ) yield return childNode; + } + } + + /// + /// Get directly derived class type of . + /// Ignore generic type argument if is a generic class with certain type argument. + /// + /// + /// Any type of classes derived from directly. + /// + public IEnumerable GetDirectDerivedDefinition(TypeDefinition baseType) + { + _typeTreeNodeMap.TryGetValue(new TypeKey(baseType), out var node); + if (node == null) throw new ArgumentException($"{baseType} is not part of this tree"); + return node.Subs.Select(sub => sub.Type); + } + + public bool HasBaseType(TypeDefinition baseType) + { + return _typeTreeNodeMap.ContainsKey(new TypeKey(baseType)); + } + + /// + /// Get all derived class type of . + /// Will make new TypeReference if derived type is generic. + /// + /// + /// including public only classes or also including private ones. + /// Any type of classes derived from directly or indirectly. + public IEnumerable GetOrCreateAllDerivedReference(TypeReference rootType, bool publicOnly = true) + { + return GetDirectDerivedDefinition(rootType.Resolve()).SelectMany(t => RecursiveProcess(t, rootType)); + + IEnumerable RecursiveProcess(TypeDefinition type, TypeReference baseType) + { + if (publicOnly && !type.IsPublicOrNestedPublic()) return Enumerable.Empty(); + var baseCtor = type.GetConstructors().FirstOrDefault(ctor => !ctor.HasParameters); + if (baseCtor == null) return Enumerable.Empty(); + + IReadOnlyList genericArguments = Array.Empty(); + try + { + genericArguments = type.ResolveGenericArguments(baseType); + } + catch (Exception ex) + { + _logger?.Debug($"cannot resolve {type.ToReadableName()} : {baseType.ToReadableName()}: {ex}"); + return Enumerable.Empty(); + } + + baseType = type.HasGenericParameters + ? (TypeReference) type.MakeGenericInstanceType(genericArguments.ToArray()) + : type + ; + + return baseType.Yield().Concat( + GetDirectDerivedDefinition(type).SelectMany(t => RecursiveProcess(t, baseType)) + ); + } + } + + public override string ToString() + { + var builder = new StringBuilder(); + foreach (var pair in _typeTreeNodeMap) + { + if (pair.Value.Base == null) + { + var root = pair.Value; + ToString(root); + } + } + return builder.ToString(); + + void ToString(TypeTreeNode node, int indent = 0) + { + for (var i = 0; i < indent; i++) builder.Append(" "); + builder.AppendLine(node.ToString()); + foreach (var child in node.Subs) ToString(child, indent + 1); + } + } + + TypeTreeNode CreateTypeTree(TypeDefinition type) + { + if (type == null) return null; + if (_typeTreeNodeMap.TryGetValue(new TypeKey(type), out var node)) return node; + + var self = new TypeTreeNode(type); + foreach (var @interface in type.Interfaces) + { + // HACK: some interface cannot be resolved? has been stripped by Unity? + // e.g. the interface `IEditModeTestYieldInstruction` of `ExitPlayMode` + // will resolve to null + var interfaceDefinition = @interface.InterfaceType.Resolve(); + if (interfaceDefinition == null) + _logger?.Warning($"Invalid interface definition {@interface.InterfaceType}({@interface.InterfaceType.Module}) on {type}"); + else + self.Interfaces.Add(interfaceDefinition); + } + + var baseTypeDef = type.BaseType?.Resolve(); + if (baseTypeDef == null && type.BaseType != null) + _logger?.Warning($"Invalid base type definition {type.BaseType}({type.BaseType.Module}) on {type.Name}"); + var parent = CreateTypeTree(baseTypeDef); + var uniqueInterfaces = new HashSet(self.Interfaces, new TypeDefinitionTokenComparer()); + if (parent != null) + { + self.Base = parent; + parent.Subs.Add(self); + self.Interfaces.UnionWith(parent.Interfaces); + uniqueInterfaces.ExceptWith(parent.Interfaces); + } + + foreach (var @interface in uniqueInterfaces) + { + var typeKey = new TypeKey(@interface); + if (!_typeTreeNodeMap.TryGetValue(typeKey, out var implementations)) + { + implementations = new TypeTreeNode(@interface); + _typeTreeNodeMap.Add(typeKey, implementations); + } + implementations.Subs.Add(self); + } + + try + { + _typeTreeNodeMap.Add(new TypeKey(type), self); + } + catch + { + var duplicate = _typeTreeNodeMap[new TypeKey(type)]; + _logger?.Error($"Duplicate type? {type} {duplicate.Type}"); + } + return self; + } + } +} \ No newline at end of file diff --git a/Packages/codegen/Editor/TypeTree.cs.meta b/Packages/codegen/Editor/TypeTree.cs.meta new file mode 100644 index 00000000..f3f9347f --- /dev/null +++ b/Packages/codegen/Editor/TypeTree.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bec8feed579e4f3ca51b70b16c9bb84f +timeCreated: 1615194743 \ No newline at end of file diff --git a/Packages/codegen/Editor/Unity.EntitiesBT.CodeGen.asmdef b/Packages/codegen/Editor/Unity.EntitiesBT.CodeGen.asmdef index d4dcd42a..3d0f22c8 100644 --- a/Packages/codegen/Editor/Unity.EntitiesBT.CodeGen.asmdef +++ b/Packages/codegen/Editor/Unity.EntitiesBT.CodeGen.asmdef @@ -5,7 +5,9 @@ "GUID:c7babe7561eb244059259745ef27b866", "GUID:3d9288551f5f1b14b9fcbd11fd97a391" ], - "includePlatforms": [], + "includePlatforms": [ + "Editor" + ], "excludePlatforms": [], "allowUnsafeCode": false, "overrideReferences": true, diff --git a/Packages/codegen/Editor/VariantsPostProcessor.cs b/Packages/codegen/Editor/VariantsPostProcessor.cs new file mode 100644 index 00000000..a4ab4e19 --- /dev/null +++ b/Packages/codegen/Editor/VariantsPostProcessor.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using EntitiesBT.Variant; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Cecil.Rocks; +using Unity.CompilationPipeline.Common.ILPostProcessing; + +namespace EntitiesBT.CodeGen.Editor +{ + public class VariantsPostProcessor : ILPostProcessor + { + private const string _overrideAssemblyCSharp = "Variants.CodeGen"; + + public override ILPostProcessor GetInstance() + { + return this; + } + + public override bool WillProcess(ICompiledAssembly compiledAssembly) + { + if (compiledAssembly.Name == _overrideAssemblyCSharp) return true; + var overrideDll = $"{_overrideAssemblyCSharp}.dll"; + var hasOverride = compiledAssembly.References.Any(@ref => @ref.EndsWith(overrideDll)); + return compiledAssembly.Name == "Assembly-CSharp" && !hasOverride; + } + + public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) + { + var sw = Stopwatch.StartNew(); + using var resolver = new PostProcessorAssemblyResolver(compiledAssembly.References); + using var assembly = compiledAssembly.LoadAssembly(resolver); + var referenceAssemblies = compiledAssembly.LoadLibraryAssemblies(resolver).ToArray(); + var logger = assembly.CreateLogger(); + var module = assembly.MainModule; + + try + { + + var allTypes = referenceAssemblies.Append(assembly) + .Where(asm => !asm.Name.Name.StartsWith("Unity.") && + !asm.Name.Name.StartsWith("UnityEditor.") && + !asm.Name.Name.StartsWith("UnityEngine.") + ) + .SelectMany(asm => asm.MainModule.GetAllTypes()) + .Where(type => type.GetAttributesOf().Any()) + .SelectMany(type => type.NestedTypes) + .ToArray() + ; + var typeTree = new TypeTree(allTypes, logger); + var valueTypes = referenceAssemblies.Append(assembly) + .SelectMany(asm => asm.GetAttributesOf()) + .Select(attribute => (TypeReference) attribute.ConstructorArguments[0].Value) + .Select(valueType => module.ImportReference(valueType.Resolve())) + .ToArray() + ; + + var ro = GenerateVariants(typeof(IVariantReader<>), valueTypes, typeTree); + var wo = GenerateVariants(typeof(IVariantWriter<>), valueTypes, typeTree); + var rw = GenerateVariants(typeof(IVariantReaderAndWriter<>), valueTypes, typeTree); + + if (!ro && !wo && !rw) return new ILPostProcessResult(null, logger.Messages); + + var pe = new MemoryStream(); + var pdb = new MemoryStream(); + var writerParameters = new WriterParameters + { + SymbolWriterProvider = new PortablePdbWriterProvider(), SymbolStream = pdb, WriteSymbols = true + }; + assembly.Write(pe, writerParameters); + return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), logger.Messages); + } + finally + { + foreach (var reference in referenceAssemblies) reference.Dispose(); + logger.Info($"process Variants.AssemblyCSharp ({sw.ElapsedMilliseconds}ms) on {assembly.Name.Name}({string.Join(",", compiledAssembly.References.Where(r => r.StartsWith("Library")))})"); + } + + bool GenerateVariants(Type interfaceType, IReadOnlyList valueTypes, TypeTree typeTree) + { + var @interface = module.ImportReference(interfaceType); + if (!typeTree.HasBaseType(@interface.Resolve())) return false; + + logger.Info($"process interface {@interface.Name}"); + + var wrapper = new TypeDefinition( + "EntitiesBT.Variant.CodeGen", + $"<{@interface.Name.Split('`')[0]}>", + TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Abstract | TypeAttributes.Public | TypeAttributes.BeforeFieldInit + ); + wrapper.BaseType = module.ImportReference(typeof(object)); + module.Types.Add(wrapper); + + var modified = false; + + foreach (var (valueType, variantType) in + from valueType in valueTypes + from variantType in typeTree.GetOrCreateAllDerivedReference(@interface.MakeGenericInstanceType(valueType)) + select (valueType, module.ImportReference(variantType)) + ) + { + var className = $"{valueType.Name}{variantType.DeclaringType.Name}"; + var variantDefinition = CreateVariantDefinition(variantType, className); + wrapper.NestedTypes.Add(variantDefinition); + modified = true; + } + + return modified; + } + + TypeDefinition CreateVariantDefinition(TypeReference variantType, string className) + { + var genericArguments = variantType.IsGenericInstance + ? ((GenericInstanceType) variantType).GenericArguments + : (IEnumerable)Array.Empty() + ; + if (genericArguments.All(arg => !arg.IsGenericParameter)) + { + var classAttributes = TypeAttributes.Class | TypeAttributes.NestedPublic | TypeAttributes.BeforeFieldInit; + var generated = new TypeDefinition("", className, classAttributes); + generated.BaseType = variantType.HasGenericParameters ? variantType.MakeGenericInstanceType(genericArguments.ToArray()) : variantType; + var ctor = module.ImportReference(variantType.Resolve().GetConstructors().First(c => !c.HasParameters)).Resolve(); + var ctorCall = new MethodReference(ctor.Name, module.ImportReference(ctor.ReturnType)) + { + DeclaringType = generated.BaseType, + HasThis = ctor.HasThis, + ExplicitThis = ctor.ExplicitThis, + CallingConvention = ctor.CallingConvention, + }; + generated.AddEmptyCtor(ctorCall); + return generated; + } + return null; + } + } + } +} \ No newline at end of file diff --git a/Packages/codegen/Editor/VariantsPostProcessor.cs.meta b/Packages/codegen/Editor/VariantsPostProcessor.cs.meta new file mode 100644 index 00000000..b3f4eb6f --- /dev/null +++ b/Packages/codegen/Editor/VariantsPostProcessor.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 96eeecf641524af79225003122a4fddd +timeCreated: 1625371957 \ No newline at end of file diff --git a/Packages/codegen/Tests~/EntitiesBT.CodeGen.Tests.asmdef b/Packages/codegen/Tests~/EntitiesBT.CodeGen.Tests.asmdef deleted file mode 100644 index dc932389..00000000 --- a/Packages/codegen/Tests~/EntitiesBT.CodeGen.Tests.asmdef +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "EntitiesBT.CodeGen.Tests", - "rootNamespace": "EntitiesBT.CodeGen.Tests", - "references": [ - "GUID:c7babe7561eb244059259745ef27b866", - "GUID:ce5f967ea6c735344b367065891c4afb", - "GUID:734d92eba21c94caba915361bd5ac177" - ], - "includePlatforms": [ - "Editor" - ], - "excludePlatforms": [], - "allowUnsafeCode": false, - "overrideReferences": true, - "precompiledReferences": [ - "nunit.framework.dll", - "Mono.Cecil.dll", - "Mono.Cecil.Rocks.dll", - "Mono.Cecil.Pdb.dll", - "Mono.Cecil.Mdb.dll" - ], - "autoReferenced": false, - "defineConstraints": [], - "versionDefines": [], - "noEngineReferences": false -} \ No newline at end of file diff --git a/Packages/codegen/Tests~/TestCodeGenForNode.cs.meta b/Packages/codegen/Tests~/TestCodeGenForNode.cs.meta deleted file mode 100644 index 014f3a23..00000000 --- a/Packages/codegen/Tests~/TestCodeGenForNode.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: abc7c55947474b1db5702c4f20960407 -timeCreated: 1613850671 \ No newline at end of file diff --git a/Packages/codegen/Tests~/TestGenerateAccessorAttributesFromMethod.cs.meta b/Packages/codegen/Tests~/TestGenerateAccessorAttributesFromMethod.cs.meta deleted file mode 100644 index adc1bd0a..00000000 --- a/Packages/codegen/Tests~/TestGenerateAccessorAttributesFromMethod.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: f04c9b9571064746ac347117dbdcd0c7 -timeCreated: 1613798384 \ No newline at end of file diff --git a/Packages/codegen/package.json b/Packages/codegen/package.json index 2386a504..2ea9ae34 100644 --- a/Packages/codegen/package.json +++ b/Packages/codegen/package.json @@ -1,14 +1,7 @@ { "name": "com.quabug.entities-bt.codegen", "description": "Behavior Tree for Unity Entities - ILCodeGen", - "version": "1.0.2", + "version": "1.2.0", "unity": "2020.2", - "displayName": "EntitiesBT - IL CodeGen", - "samples": [ - { - "displayName": "[Test] tests", - "description": "test cases of il codegen", - "path": "Test~" - } - ] + "displayName": "EntitiesBT - IL CodeGen" } diff --git a/Packages/debug.component-viewer/Runtime/BehaviorTreeDebugViewerSystem.cs b/Packages/debug.component-viewer/Runtime/BehaviorTreeDebugViewerSystem.cs index 54cdb39f..02e45293 100644 --- a/Packages/debug.component-viewer/Runtime/BehaviorTreeDebugViewerSystem.cs +++ b/Packages/debug.component-viewer/Runtime/BehaviorTreeDebugViewerSystem.cs @@ -1,3 +1,5 @@ +#if UNITY_EDITOR + using System.Linq; using EntitiesBT.Entities; using Unity.Entities; @@ -67,3 +69,5 @@ protected override void OnUpdate() } } } + +#endif \ No newline at end of file diff --git a/Packages/debug.component-viewer/package.json b/Packages/debug.component-viewer/package.json index 610e890b..e2279e49 100644 --- a/Packages/debug.component-viewer/package.json +++ b/Packages/debug.component-viewer/package.json @@ -1,10 +1,10 @@ { "name": "com.quabug.entities-bt.debug.component-viewer", "description": "Behavior Tree for Unity Entities - Component Debug Viewer", - "version": "1.0.0", + "version": "1.2.0", "unity": "2020.2", "displayName": "EntitiesBT - Component Debug Viewer", "dependencies": { - "com.quabug.entities-bt.essential": "1.0.0" + "com.quabug.entities-bt.essential": "1.2.0" } } diff --git a/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceButtonAttributeDrawer.cs b/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceButtonAttributeDrawer.cs deleted file mode 100644 index df444fcd..00000000 --- a/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceButtonAttributeDrawer.cs +++ /dev/null @@ -1,233 +0,0 @@ -/*** - * MIT License - * - * Copyright (c) 2020 TextusGames - * - * 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. - */ - -// https://github.com/TextusGames/UnitySerializedReferenceUI/ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using UnityEditor; -using UnityEngine; - -namespace EntitiesBT.Attributes.Editor -{ - [CustomMultiPropertyDrawer(typeof(SerializeReferenceButtonAttribute))] - public class SerializeReferenceButtonAttributeDrawer : BaseMultiPropertyDrawer - { - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) - { - EditorGUI.BeginProperty(position, label, property); - - var labelPosition = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight); - EditorGUI.LabelField(labelPosition, label); - - // var typeRestrictions = SerializedReferenceUIDefaultTypeRestrictions.GetAllBuiltInTypeRestrictions(fieldInfo); - DrawSelectionButtonForManagedReference(property, position); - - EditorGUI.PropertyField(position, property, GUIContent.none, true); - - EditorGUI.EndProperty(); - } - - private void DrawSelectionButtonForManagedReference(SerializedProperty property, Rect position, IEnumerable> filters = null) - { - var backgroundColor = new Color(0.1f, 0.55f, 0.9f, 1f); - - var buttonPosition = position; - buttonPosition.x += EditorGUIUtility.labelWidth + 1 * EditorGUIUtility.standardVerticalSpacing; - buttonPosition.width = position.width - EditorGUIUtility.labelWidth - 1 * EditorGUIUtility.standardVerticalSpacing; - buttonPosition.height = EditorGUIUtility.singleLineHeight; - - var storedIndent = EditorGUI.indentLevel; - EditorGUI.indentLevel = 0; - var storedColor = GUI.backgroundColor; - GUI.backgroundColor = backgroundColor; - - - var names = GetSplitNamesFromTypename(property.managedReferenceFullTypename); - var className = string.IsNullOrEmpty(names.ClassName) ? "Null (Assign)" : names.ClassName; - var assemblyName = names.AssemblyName; - if (GUI.Button(buttonPosition, new GUIContent(className, className + " ( "+ assemblyName +" )" ))) - ShowContextMenuForManagedReference(property, filters); - - GUI.backgroundColor = storedColor; - EditorGUI.indentLevel = storedIndent; - } - - private (string AssemblyName, string ClassName) GetSplitNamesFromTypename(string typename) - { - if (string.IsNullOrEmpty(typename)) - return ("",""); - - var typeSplitString = typename.Split(char.Parse(" ")); - var typeClassName = typeSplitString[1]; - var typeAssemblyName = typeSplitString[0]; - return (typeAssemblyName, typeClassName); - } - - private void ShowContextMenuForManagedReference(SerializedProperty property, IEnumerable> filters = null) - { - var context = new GenericMenu(); - FillContextMenu(filters, context, property); - context.ShowAsContext(); - } - - private void FillContextMenu(IEnumerable> enumerableFilters, GenericMenu contextMenu, SerializedProperty property) - { - var filters = new List>(); - if (enumerableFilters != null) filters.AddRange(enumerableFilters); - - // Adds "Make Null" menu command - contextMenu.AddItem(new GUIContent("Null"), false, SetManagedReferenceToNull(property)); - - // Collects appropriate types - var appropriateTypes = GetAppropriateTypesForAssigningToManagedReference(property, filters); - - // Adds appropriate types to menu - foreach (var appropriateType in appropriateTypes) - AddItemToContextMenu(appropriateType, contextMenu, property); - } - - private GenericMenu.MenuFunction SetManagedReferenceToNull(SerializedProperty serializedProperty) - { - return () => - { - serializedProperty.serializedObject.Update(); - serializedProperty.managedReferenceValue = null; - serializedProperty.serializedObject.ApplyModifiedProperties(); - }; - } - - private void AddItemToContextMenu(Type type, GenericMenu genericMenuContext, SerializedProperty property) - { - var assemblyName = type.Assembly.ToString().Split('(', ',')[0]; - var entryName = type + " ( " + assemblyName + " )"; - genericMenuContext.AddItem(new GUIContent(entryName), false, AssignNewInstanceCommand, new GenericMenuParameterForAssignInstanceCommand(type, property)); - } - - private void AssignNewInstanceCommand(object objectGenericMenuParameter ) - { - var parameter = (GenericMenuParameterForAssignInstanceCommand) objectGenericMenuParameter; - var type = parameter.Type; - var property = parameter.Property; - AssignNewInstanceOfTypeToManagedReference(property, type); - } - - private object AssignNewInstanceOfTypeToManagedReference(SerializedProperty serializedProperty, Type type) - { - var instance = Activator.CreateInstance(type); - - serializedProperty.serializedObject.Update(); - serializedProperty.managedReferenceValue = instance; - serializedProperty.serializedObject.ApplyModifiedProperties(); - - return instance; - } - - private readonly struct GenericMenuParameterForAssignInstanceCommand - { - public GenericMenuParameterForAssignInstanceCommand(Type type, SerializedProperty property) - { - Type = type; - Property = property; - } - - public readonly SerializedProperty Property; - public readonly Type Type; - } - - private IEnumerable GetAppropriateTypesForAssigningToManagedReference(SerializedProperty property, List> filters = null) - { - var fieldType = GetManagedReferenceFieldType(property); - return GetAppropriateTypesForAssigningToManagedReference(fieldType, filters); - } - - /// Gets real type of managed reference - private Type GetManagedReferenceFieldType(SerializedProperty property) - { - var realPropertyType = GetRealTypeFromTypename(property.managedReferenceFieldTypename); - if (realPropertyType != null) - return realPropertyType; - - Debug.LogError($"Can not get field type of managed reference : {property.managedReferenceFieldTypename}"); - return null; - } - - /// Gets real type of managed reference's field typeName - private Type GetRealTypeFromTypename(string stringType) - { - var names = GetSplitNamesFromTypename(stringType); - var realType = Type.GetType($"{names.ClassName}, {names.AssemblyName}"); - return realType; - } - - private IEnumerable GetAppropriateTypesForAssigningToManagedReference(Type fieldType, List> filters = null) - { - var appropriateTypes = new List(); - - // Get and filter all appropriate types - var derivedTypes = TypeCache.GetTypesDerivedFrom(fieldType); - foreach (var type in derivedTypes) - { - // Skips unity engine Objects (because they are not serialized by SerializeReference) - if (type.IsSubclassOf(typeof(UnityEngine.Object))) - continue; - // Skip abstract classes because they should not be instantiated - if (type.IsAbstract) - continue; - // Skip types that has no public empty constructors (activator can not create them) - if (type.IsClass && type.GetConstructor(Type.EmptyTypes) == null) // Structs still can be created (strangely) - continue; - // Filter types by provided filters if there is ones - if (filters != null && filters.All(f => f == null || f.Invoke(type)) == false) - continue; - - appropriateTypes.Add(type); - } - - return appropriateTypes; - } - // - // private IEnumerable> GetAllBuiltInTypeRestrictions(FieldInfo fieldInfo) - // { - // var result = new List>(); - // - // var attributeObjects = fieldInfo.GetCustomAttributes(false); - // foreach (var attributeObject in attributeObjects) - // { - // switch (attributeObject) - // { - // case SerializeReferenceUIRestrictionIncludeTypes includeTypes: - // result.Add(SerializeReferenceTypeRestrictionFilters.TypeIsSubclassOrEqualOrHasInterface(includeTypes.Types)); - // continue; - // case SerializeReferenceUIRestrictionExcludeTypes excludeTypes: - // result.Add(SerializeReferenceTypeRestrictionFilters.TypeIsNotSubclassOrEqualOrHasInterface(excludeTypes.Types)); - // continue; - // } - // } - // return result; - // } - } -} \ No newline at end of file diff --git a/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceDrawerAttributeDrawer.cs b/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceDrawerAttributeDrawer.cs new file mode 100644 index 00000000..0db380af --- /dev/null +++ b/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceDrawerAttributeDrawer.cs @@ -0,0 +1,226 @@ +/*** + * MIT License + * + * Copyright (c) 2020 TextusGames + * + * 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. + */ + +// https://github.com/TextusGames/UnitySerializedReferenceUI/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using Shtif; +using UnityEditor; +using UnityEngine; + +namespace EntitiesBT.Attributes.Editor +{ + [CustomMultiPropertyDrawer(typeof(SerializeReferenceDrawerAttribute))] + public class SerializeReferenceDrawerAttributeDrawer : BaseMultiPropertyDrawer + { + protected override void OnGUISelf(Rect position, SerializedProperty property, GUIContent label) + { + EditorGUI.BeginProperty(position, label, property); + + var labelPosition = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight); + EditorGUI.LabelField(labelPosition, label); + + var attribute = (SerializeReferenceDrawerAttribute) Decorator; + var filters = GetAllBuiltInTypeRestrictions(); + DrawSelectionButtonForManagedReference(); + + EditorGUI.PropertyField(position, property, GUIContent.none, true); + + EditorGUI.EndProperty(); + + IEnumerable> GetAllBuiltInTypeRestrictions() + { + var result = new List>(); + if (!string.IsNullOrEmpty(attribute.TypeRestrictionBySiblingProperty)) + { + var baseType = property.GetSiblingPropertyInfo(attribute.TypeRestrictionBySiblingProperty).PropertyType; + var derivedTypes = TypeCache.GetTypesDerivedFrom(baseType); + result.Add(derivedTypes.Contains); + } + return result; + } + + void DrawSelectionButtonForManagedReference() + { + var backgroundColor = new Color(0.1f, 0.55f, 0.9f, 1f); + + var buttonPosition = position; + buttonPosition.x += EditorGUIUtility.labelWidth + 1 * EditorGUIUtility.standardVerticalSpacing; + buttonPosition.width = position.width - EditorGUIUtility.labelWidth - 1 * EditorGUIUtility.standardVerticalSpacing; + buttonPosition.height = EditorGUIUtility.singleLineHeight; + + var storedIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + var storedColor = GUI.backgroundColor; + GUI.backgroundColor = backgroundColor; + + + var names = GetSplitNamesFromTypename(property.managedReferenceFullTypename); + var className = string.IsNullOrEmpty(names.ClassName) ? "Null (Assign)" : names.ClassName; + var assemblyName = names.AssemblyName; + if (GUI.Button(buttonPosition, new GUIContent(className, className + " ( "+ assemblyName +" )" ))) + ShowContextMenuForManagedReference(); + + GUI.backgroundColor = storedColor; + EditorGUI.indentLevel = storedIndent; + + void ShowContextMenuForManagedReference() + { + var context = new GenericMenu(); + FillContextMenu(context); + var popup = GenericMenuPopup.Get(context, ""); + popup.width = 400; + popup.showSearch = true; + popup.showTooltip = false; + popup.resizeToContent = true; + popup.Show(new Vector2(buttonPosition.x, buttonPosition.y)); + // context.ShowAsContext(); + } + } + + void FillContextMenu(GenericMenu contextMenu) + { + // Adds "Make Null" menu command + contextMenu.AddItem(new GUIContent("Null"), false, SetManagedReferenceToNull()); + + // Collects appropriate types + var appropriateTypes = GetAppropriateTypesForAssigningToManagedReference(); + + // Adds appropriate types to menu + foreach (var appropriateType in appropriateTypes) + AddItemToContextMenu(appropriateType, contextMenu); + } + + GenericMenu.MenuFunction SetManagedReferenceToNull() + { + return () => + { + property.serializedObject.Update(); + property.managedReferenceValue = null; + property.serializedObject.ApplyModifiedProperties(); + }; + } + + void AddItemToContextMenu(Type type, GenericMenu genericMenuContext) + { + var assemblyName = type.Assembly.ToString().Split('(', ',')[0]; + var entryName = type + " ( " + assemblyName + " )"; + // HACK: display subclass name after "+" + entryName = entryName.Substring(entryName.IndexOf('+') + 1); + genericMenuContext.AddItem(new GUIContent(entryName), false, AssignNewInstanceCommand, new GenericMenuParameterForAssignInstanceCommand(type, property)); + + void AssignNewInstanceCommand(object objectGenericMenuParameter) + { + var parameter = (GenericMenuParameterForAssignInstanceCommand) objectGenericMenuParameter; + AssignNewInstanceOfTypeToManagedReference(parameter.Property, parameter.Type); + } + + object AssignNewInstanceOfTypeToManagedReference(SerializedProperty serializedProperty, Type type) + { + var instance = Activator.CreateInstance(type); + serializedProperty.serializedObject.Update(); + serializedProperty.managedReferenceValue = instance; + serializedProperty.serializedObject.ApplyModifiedProperties(); + return instance; + } + } + + IEnumerable GetAppropriateTypesForAssigningToManagedReference() + { + var fieldType = GetManagedReferenceFieldType(); + var appropriateTypes = new List(); + + // Get and filter all appropriate types + var derivedTypes = TypeCache.GetTypesDerivedFrom(fieldType); + foreach (var type in derivedTypes) + { + // Skips unity engine Objects (because they are not serialized by SerializeReference) + if (type.IsSubclassOf(typeof(UnityEngine.Object))) + continue; + // Skip abstract classes because they should not be instantiated + if (type.IsAbstract) + continue; + if (type.IsGenericType) + continue; + // Skip types that has no public empty constructors (activator can not create them) + if (type.IsClass && type.GetConstructor(Type.EmptyTypes) == null) // Structs still can be created (strangely) + continue; + // Filter types by provided filters if there is ones + if (filters != null && filters.All(f => f == null || f.Invoke(type)) == false) + continue; + + appropriateTypes.Add(type); + } + + return appropriateTypes; + } + + // Gets real type of managed reference + Type GetManagedReferenceFieldType() + { + var realPropertyType = GetRealTypeFromTypename(property.managedReferenceFieldTypename); + if (realPropertyType != null) + return realPropertyType; + + Debug.LogError($"Can not get field type of managed reference : {property.managedReferenceFieldTypename}"); + return null; + + // Gets real type of managed reference's field typeName + Type GetRealTypeFromTypename(string stringType) + { + var names = GetSplitNamesFromTypename(stringType); + var realType = Type.GetType($"{names.ClassName}, {names.AssemblyName}"); + return realType; + } + } + } + + private (string AssemblyName, string ClassName) GetSplitNamesFromTypename(string typename) + { + if (string.IsNullOrEmpty(typename)) + return ("",""); + + var typeSplitString = typename.Split(char.Parse(" ")); + var typeClassName = typeSplitString[1]; + var typeAssemblyName = typeSplitString[0]; + return (typeAssemblyName, typeClassName); + } + + private readonly struct GenericMenuParameterForAssignInstanceCommand + { + public GenericMenuParameterForAssignInstanceCommand(Type type, SerializedProperty property) + { + Type = type; + Property = property; + } + + public readonly SerializedProperty Property; + public readonly Type Type; + } + } +} \ No newline at end of file diff --git a/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceButtonAttributeDrawer.cs.meta b/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceDrawerAttributeDrawer.cs.meta similarity index 54% rename from Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceButtonAttributeDrawer.cs.meta rename to Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceDrawerAttributeDrawer.cs.meta index d1f536f9..a37a6f62 100644 --- a/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceButtonAttributeDrawer.cs.meta +++ b/Packages/essential/Dependencies/Attributes/Editor/Drawers/SerializeReferenceDrawerAttributeDrawer.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 7109165dc85343189dcfc5d8cf821ec1 +guid: e927744c85e1cbf4c80f2e767bc61779 timeCreated: 1612017002 \ No newline at end of file diff --git a/Packages/essential/Dependencies/Attributes/Editor/Extensions.cs b/Packages/essential/Dependencies/Attributes/Editor/Extensions.cs index f3634362..457f5901 100644 --- a/Packages/essential/Dependencies/Attributes/Editor/Extensions.cs +++ b/Packages/essential/Dependencies/Attributes/Editor/Extensions.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -9,21 +10,43 @@ public static class Extensions { public static object GetSiblingFieldValue(this SerializedProperty property, string fieldName) { - var pathCount = property.propertyPath.Split('.').Length; - var obj = property.GetFieldsByPath().ElementAt(pathCount - 1).field; + var obj = GetDeclaringObject(property); var fieldInfo = obj.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return fieldInfo.GetValue(obj); } + public static PropertyInfo GetSiblingPropertyInfo(this SerializedProperty property, string propertyName) + { + var obj = GetDeclaringObject(property); + return obj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + } + + public static object GetDeclaringObject(this SerializedProperty property) + { + return property.GetFieldsByPath().Reverse().Skip(1).First().field; + } + public static IEnumerable<(object field, FieldInfo fi)> GetFieldsByPath(this SerializedProperty property) { var obj = (object)property.serializedObject.targetObject; - yield return (obj, null); + FieldInfo fi = null; + yield return (obj, fi); foreach (var fieldName in property.propertyPath.Split('.')) { - var t = Field(obj, fieldName); - obj = t.field; - yield return t; + if (obj.GetType().IsArray) + { + if (fieldName == "Array") continue; + var itemIndex = int.Parse(fieldName.Substring(5 /*"data["*/, fieldName.Length - 6 /*"data[]"*/)); + obj = ((Array) obj).GetValue(itemIndex); + yield return (obj, fi); + } + else + { + var t = Field(obj, fieldName); + obj = t.field; + fi = t.fi; + yield return t; + } } (object field, FieldInfo fi) Field(object @object, string fieldName) diff --git a/Packages/essential/Dependencies/Attributes/Editor/GenericMenuPopup.cs b/Packages/essential/Dependencies/Attributes/Editor/GenericMenuPopup.cs new file mode 100644 index 00000000..7688f368 --- /dev/null +++ b/Packages/essential/Dependencies/Attributes/Editor/GenericMenuPopup.cs @@ -0,0 +1,527 @@ +/* + * Created by: Peter @sHTiF Stefcek + */ + +// +// MIT License +// +// Copyright (c) 2021 Peter @sHTiF Stefcek +// +// 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. + +// https://github.com/pshtif/GenericMenuPopup + +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace Shtif +{ + public class MenuItemNode + { + public GUIContent content; + public GenericMenu.MenuFunction func; + public GenericMenu.MenuFunction2 func2; + public object userData; + public bool separator; + public bool on; + + public string name { get; } + public MenuItemNode parent { get; } + + public List Nodes { get; private set; } + + public MenuItemNode(string p_name = "", MenuItemNode p_parent = null) + { + name = p_name; + parent = p_parent; + Nodes = new List(); + } + + public MenuItemNode CreateNode(string p_name) + { + var node = new MenuItemNode(p_name, this); + Nodes.Add(node); + return node; + } + + // TODO Optimize + public MenuItemNode GetOrCreateNode(string p_name) + { + var node = Nodes.Find(n => n.name == p_name); + if (node == null) + { + node = CreateNode(p_name); + } + + return node; + } + + public List Search(string p_search) + { + p_search = p_search.ToLower(); + List result = new List(); + + foreach (var node in Nodes) + { + if (node.Nodes.Count == 0 && node.name.ToLower().Contains(p_search)) + { + result.Add(node); + } + + result.AddRange(node.Search(p_search)); + } + + return result; + } + + public string GetPath() + { + return parent == null ? "" : parent.GetPath() + "/" + name; + } + + public void Execute() + { + if (func != null) + { + func?.Invoke(); + } + else + { + func2?.Invoke(userData); + } + } + } + + public class GenericMenuPopup : PopupWindowContent + { + public static GenericMenuPopup Get(GenericMenu p_menu, string p_title) + { + var popup = new GenericMenuPopup(p_menu, p_title); + return popup; + } + + public static GenericMenuPopup Show(GenericMenu p_menu, string p_title, Vector2 p_position) { + var popup = new GenericMenuPopup(p_menu, p_title); + PopupWindow.Show(new Rect(p_position.x, p_position.y, 0, 0), popup); + return popup; + } + + private GUIStyle _backStyle; + public GUIStyle BackStyle + { + get + { + if (_backStyle == null) + { + _backStyle = new GUIStyle(GUI.skin.button); + _backStyle.alignment = TextAnchor.MiddleLeft; + _backStyle.hover.background = Texture2D.grayTexture; + _backStyle.normal.textColor = Color.black; + } + + return _backStyle; + } + } + + private GUIStyle _plusStyle; + public GUIStyle PlusStyle + { + get { + if (_plusStyle == null) + { + _plusStyle = new GUIStyle(); + _plusStyle.fontStyle = FontStyle.Bold; + _plusStyle.normal.textColor = Color.white; + _plusStyle.fontSize = 16; + } + + return _plusStyle; + } + } + + private string _title; + private Vector2 _scrollPosition; + private MenuItemNode _rootNode; + private MenuItemNode _currentNode; + private MenuItemNode _hoverNode; + private string _search; + private bool _repaint = false; + private int _contentHeight; + private bool _useScroll; + + public int width = 200; + public int height = 200; + public int maxHeight = 300; + public bool resizeToContent = false; + public bool showOnStatus = true; + public bool showSearch = true; + public bool showTooltip = false; + public bool showTitle = false; + + + public GenericMenuPopup(GenericMenu p_menu, string p_title) + { + _title = p_title; + showTitle = !string.IsNullOrWhiteSpace(_title); + _currentNode = _rootNode = GenerateMenuItemNodeTree(p_menu); + } + + public override Vector2 GetWindowSize() + { + return new Vector2(width, height); + } + + public void Show(float p_x, float p_y) + { + PopupWindow.Show(new Rect(p_x, p_y, 0, 0), this); + } + + public void Show(Vector2 p_position) + { + PopupWindow.Show(new Rect(p_position.x, p_position.y, 0, 0), this); + } + + public override void OnGUI(Rect p_rect) + { + if (Event.current.type == EventType.Layout) + _useScroll = _contentHeight > maxHeight || (!resizeToContent && _contentHeight > height); + + _contentHeight = 0; + GUIStyle style = new GUIStyle(); + style.normal.background = Texture2D.whiteTexture; + GUI.color = new Color(0.1f, 0.1f, 0.1f, 1); + GUI.Box(p_rect, string.Empty, style); + GUI.color = Color.white; + + if (showTitle) + { + DrawTitle(new Rect(p_rect.x, p_rect.y, p_rect.width, 24)); + } + + if (showSearch) + { + DrawSearch(new Rect(p_rect.x, p_rect.y + (showTitle ? 24 : 0), p_rect.width, 20)); + } + + DrawMenuItems(new Rect(p_rect.x, p_rect.y + (showTitle ? 24 : 0) + (showSearch ? 22 : 0), p_rect.width, p_rect.height - (showTooltip ? 60 : 0) - (showTitle ? 24 : 0) - (showSearch ? 22 : 0))); + + if (showTooltip) + { + DrawTooltip(new Rect(p_rect.x + 5, p_rect.y + p_rect.height - 58, p_rect.width - 10, 56)); + } + + if (resizeToContent) + { + height = Mathf.Min(_contentHeight, maxHeight); + } + EditorGUI.FocusTextInControl("Search"); + } + + private void DrawTitle(Rect p_rect) + { + _contentHeight += 24; + GUIStyle style = new GUIStyle(); + style.normal.textColor = Color.white; + style.fontStyle = FontStyle.Bold; + style.fontSize = 16; + style.alignment = TextAnchor.LowerCenter; + GUI.Label(p_rect, _title, style); + } + + private void DrawSearch(Rect p_rect) + { + _contentHeight += 22; + GUI.SetNextControlName("Search"); + _search = GUI.TextArea(p_rect, _search); + } + + private void DrawTooltip(Rect p_rect) + { + _contentHeight += 60; + if (_hoverNode == null || _hoverNode.content == null || string.IsNullOrWhiteSpace(_hoverNode.content.tooltip)) + return; + + GUIStyle style = new GUIStyle(); + style.fontSize = 9; + style.wordWrap = true; + style.normal.textColor = Color.white; + GUI.Label(p_rect, _hoverNode.content.tooltip, style); + } + + private void DrawMenuItems(Rect p_rect) + { + GUILayout.BeginArea(p_rect); + if (_useScroll) + { + _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition, GUIStyle.none, GUI.skin.verticalScrollbar); + } + + GUILayout.BeginVertical(); + + if (string.IsNullOrWhiteSpace(_search) || _search.Length<2) + { + DrawNodeTree(p_rect); + } + else + { + DrawNodeSearch(p_rect); + } + + GUILayout.EndVertical(); + if (_useScroll) + { + EditorGUILayout.EndScrollView(); + } + + GUILayout.EndArea(); + } + + private void DrawNodeSearch(Rect p_rect) + { + List search = _rootNode.Search(_search); + search.Sort((n1, n2) => + { + string p1 = n1.parent.GetPath(); + string p2 = n2.parent.GetPath(); + if (p1 == p2) + return n1.name.CompareTo(n2.name); + + return p1.CompareTo(p2); + }); + + string lastPath = ""; + foreach (var node in search) + { + string nodePath = node.parent.GetPath(); + if (nodePath != lastPath) + { + _contentHeight += 21; + GUILayout.Label(nodePath); + lastPath = nodePath; + } + + _contentHeight += 21; + GUI.color = _hoverNode == node ? Color.white : Color.gray; + GUIStyle style = new GUIStyle(); + style.normal.background = Texture2D.grayTexture; + GUILayout.BeginHorizontal(style); + + if (showOnStatus) + { + style = new GUIStyle("box"); + style.normal.background = Texture2D.whiteTexture; + GUI.color = node.on ? new Color(0, .6f, .8f) : new Color(.2f, .2f, .2f); + GUILayout.Box("", style, GUILayout.Width(14), GUILayout.Height(14)); + } + + GUI.color = _hoverNode == node ? Color.white : Color.white; + GUILayout.Label(node.name); + + GUILayout.EndHorizontal(); + + var nodeRect = GUILayoutUtility.GetLastRect(); + if (Event.current.isMouse) + { + if (nodeRect.Contains(Event.current.mousePosition)) + { + if (Event.current.type == EventType.MouseDown && Event.current.button == 0) + { + if (node.Nodes.Count > 0) + { + _currentNode = node; + _repaint = true; + } + else + { + node.Execute(); + base.editorWindow.Close(); + } + + break; + } + + if (_hoverNode != node) + { + _hoverNode = node; + _repaint = true; + } + } + else if (_hoverNode == node) + { + _hoverNode = null; + _repaint = true; + } + } + } + + if (search.Count == 0) + { + GUILayout.Label("No result found for specified search."); + } + } + + private void DrawNodeTree(Rect p_rect) + { + if (_currentNode != _rootNode) + { + _contentHeight += 21; + if (GUILayout.Button(_currentNode.GetPath(), BackStyle)) + { + _currentNode = _currentNode.parent; + } + } + + foreach (var node in _currentNode.Nodes) + { + if (node.separator) + { + GUILayout.Space(4); + _contentHeight += 4; + continue; + } + + _contentHeight += 21; + GUI.color = _hoverNode == node ? Color.white : Color.gray; + GUIStyle style = new GUIStyle(); + style.normal.background = Texture2D.grayTexture; + GUILayout.BeginHorizontal(style); + + if (showOnStatus) + { + style = new GUIStyle("box"); + style.normal.background = Texture2D.whiteTexture; + GUI.color = node.on ? new Color(0, .6f, .8f, .5f) : new Color(.2f, .2f, .2f, .2f); + GUILayout.Box("", style, GUILayout.Width(14), GUILayout.Height(14)); + } + + GUI.color = _hoverNode == node ? Color.white : Color.white; + style = new GUIStyle("label"); + style.fontStyle = node.Nodes.Count > 0 ? FontStyle.Bold : FontStyle.Normal; + GUILayout.Label(node.name, style); + + GUILayout.EndHorizontal(); + + var nodeRect = GUILayoutUtility.GetLastRect(); + if (Event.current.isMouse) + { + if (nodeRect.Contains(Event.current.mousePosition)) + { + if (Event.current.type == EventType.MouseDown && Event.current.button == 0) + { + if (node.Nodes.Count > 0) + { + _currentNode = node; + _repaint = true; + } + else + { + node.Execute(); + base.editorWindow.Close(); + } + + break; + } + + if (_hoverNode != node) + { + _hoverNode = node; + _repaint = true; + } + } + else if (_hoverNode == node) + { + _hoverNode = null; + _repaint = true; + } + } + + if (node.Nodes.Count > 0) + { + Rect lastRect = GUILayoutUtility.GetLastRect(); + GUI.Label(new Rect(lastRect.x+lastRect.width-16, lastRect.y-2, 20, 20), "+", PlusStyle); + } + } + } + + void OnEditorUpdate() { + if (_repaint) + { + _repaint = false; + base.editorWindow.Repaint(); + } + } + + // TODO Possible type caching? + public static MenuItemNode GenerateMenuItemNodeTree(GenericMenu p_menu) + { + MenuItemNode rootNode = new MenuItemNode(); + if (p_menu == null) + return rootNode; + + var menuItemsField = p_menu.GetType().GetField("menuItems", BindingFlags.Instance | BindingFlags.NonPublic); + var menuItems = menuItemsField.GetValue(p_menu) as ArrayList; + + foreach (var menuItem in menuItems) + { + var menuItemType = menuItem.GetType(); + GUIContent content = (GUIContent)menuItemType.GetField("content").GetValue(menuItem); + + bool separator = (bool)menuItemType.GetField("separator").GetValue(menuItem); + string path = content.text; + string[] splitPath = path.Split('/'); + MenuItemNode currentNode = rootNode; + for (int i = 0; i < splitPath.Length; i++) + { + currentNode = (i < splitPath.Length - 1) + ? currentNode.GetOrCreateNode(splitPath[i]) + : currentNode.CreateNode(splitPath[i]); + } + + if (separator) + { + currentNode.separator = true; + } + else + { + currentNode.content = content; + currentNode.func = (GenericMenu.MenuFunction) menuItemType.GetField("func").GetValue(menuItem); + currentNode.func2 = (GenericMenu.MenuFunction2) menuItemType.GetField("func2").GetValue(menuItem); + currentNode.userData = menuItemType.GetField("userData").GetValue(menuItem); + currentNode.on = (bool) menuItemType.GetField("on").GetValue(menuItem); + } + } + + return rootNode; + } + + public override void OnOpen() + { + EditorApplication.update -= OnEditorUpdate; + EditorApplication.update += OnEditorUpdate; + } + + public override void OnClose() + { + EditorApplication.update -= OnEditorUpdate; + } + } +} \ No newline at end of file diff --git a/Packages/essential/Dependencies/Attributes/Editor/GenericMenuPopup.cs.meta b/Packages/essential/Dependencies/Attributes/Editor/GenericMenuPopup.cs.meta new file mode 100644 index 00000000..afc5c6b7 --- /dev/null +++ b/Packages/essential/Dependencies/Attributes/Editor/GenericMenuPopup.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b28c75c1637445c196896fba741068f7 +timeCreated: 1627315179 \ No newline at end of file diff --git a/Packages/essential/Dependencies/Attributes/SerializeReferenceButtonAttribute.cs b/Packages/essential/Dependencies/Attributes/SerializeReferenceButtonAttribute.cs deleted file mode 100644 index 67923458..00000000 --- a/Packages/essential/Dependencies/Attributes/SerializeReferenceButtonAttribute.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace EntitiesBT.Attributes -{ - [AttributeUsage(AttributeTargets.Field)] - public class SerializeReferenceButtonAttribute : MultiPropertyAttribute - { - public SerializeReferenceButtonAttribute() => order = int.MaxValue; - } -} diff --git a/Packages/essential/Dependencies/Attributes/SerializeReferenceDrawerAttribute.cs b/Packages/essential/Dependencies/Attributes/SerializeReferenceDrawerAttribute.cs new file mode 100644 index 00000000..2e34f3f2 --- /dev/null +++ b/Packages/essential/Dependencies/Attributes/SerializeReferenceDrawerAttribute.cs @@ -0,0 +1,11 @@ +using System; + +namespace EntitiesBT.Attributes +{ + [AttributeUsage(AttributeTargets.Field)] + public class SerializeReferenceDrawerAttribute : MultiPropertyAttribute + { + public string TypeRestrictionBySiblingProperty; + public SerializeReferenceDrawerAttribute() => order = int.MaxValue; + } +} diff --git a/Packages/essential/Dependencies/Attributes/SerializeReferenceButtonAttribute.cs.meta b/Packages/essential/Dependencies/Attributes/SerializeReferenceDrawerAttribute.cs.meta similarity index 54% rename from Packages/essential/Dependencies/Attributes/SerializeReferenceButtonAttribute.cs.meta rename to Packages/essential/Dependencies/Attributes/SerializeReferenceDrawerAttribute.cs.meta index a654ed16..169e4a77 100644 --- a/Packages/essential/Dependencies/Attributes/SerializeReferenceButtonAttribute.cs.meta +++ b/Packages/essential/Dependencies/Attributes/SerializeReferenceDrawerAttribute.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: c64e0f68b41b48939c9b98cc29a19b20 +guid: 87356a7e833eaf4439649e552ad2cfb7 timeCreated: 1579584059 \ No newline at end of file diff --git a/Packages/essential/Editor/CodeGen/NodeCodeGenerator.cs b/Packages/essential/Editor/CodeGen/NodeCodeGenerator.cs index 2d7ffa93..93488ac4 100644 --- a/Packages/essential/Editor/CodeGen/NodeCodeGenerator.cs +++ b/Packages/essential/Editor/CodeGen/NodeCodeGenerator.cs @@ -18,7 +18,7 @@ namespace EntitiesBT.Editor [CreateAssetMenu(fileName = "NodeCodeGenerator", menuName = "EntitiesBT/NodeCodeGenerator")] public class NodeCodeGenerator : ScriptableObject { - [SerializeReference, SerializeReferenceButton, DrawWithUnity] + [SerializeReference, SerializeReferenceDrawer, DrawWithUnity] private INodeCodeTemplate _codeTemplate; [SerializeField] @@ -27,13 +27,13 @@ public class NodeCodeGenerator : ScriptableObject [SerializeField] private string _classRenameRegex = @"(\w+)(?:Node)/$1"; - [SerializeReference, SerializeReferenceButton, DrawWithUnity] + [SerializeReference, SerializeReferenceDrawer, DrawWithUnity] private ITypeGroup[] _includedNodes = { new TypeGroupAssemblies() }; - [SerializeReference, SerializeReferenceButton, DrawWithUnity] + [SerializeReference, SerializeReferenceDrawer, DrawWithUnity] private ITypeValidator[] _excludedNodes = { new TypeValidatorWithFullName() }; - [SerializeReference, SerializeReferenceButton, DrawWithUnity] + [SerializeReference, SerializeReferenceDrawer, DrawWithUnity] private INodeDataFieldCodeGenerator[] _fieldCodeGenerators = { new DefaultNodeDataFieldCodeGenerator() }; [ContextMenu("Generate")] diff --git a/Packages/essential/Editor/VariantGeneratorSetting.cs b/Packages/essential/Editor/VariantGeneratorSetting.cs deleted file mode 100644 index 5f78eb7d..00000000 --- a/Packages/essential/Editor/VariantGeneratorSetting.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using EntitiesBT.Core; -using EntitiesBT.Variant; -using UnityEditor; -using UnityEditorInternal; -using UnityEngine; -using static UnityEditor.EditorUtility; -using static EntitiesBT.Variant.Utilities; - -namespace EntitiesBT.Editor -{ - [CreateAssetMenu(fileName = "VariantGeneratorSetting", menuName = "EntitiesBT/VariantGeneratorSetting")] - public class VariantGeneratorSetting : ScriptableObject - { - public string[] Types; - public string Filename = "VariantProperties"; - public string Namespace = $"{nameof(EntitiesBT)}.{nameof(Variant)}"; - public AssemblyDefinitionAsset Assembly; - private ISet _referenceAssemblies; - - [ContextMenu("CreateScript")] - public void CreateScript() - { - RecursiveFindReferences(); - var filePath = SaveFilePanel("Save Script", Directory, Filename, "cs"); - VariantGenerator.CreateScript(filePath, Namespace, Types, IsReferenceType); - } - - [ContextMenu("CreateScript-InterfaceOnly")] - public void CreateInterfaceScript() - { - RecursiveFindReferences(); - var filePath = SaveFilePanel("Save Script", Directory, $"{Filename}-Interface", "cs"); - VariantGenerator.CreateScriptInterfaceOnly(filePath, Namespace, Types); - } - - [ContextMenu("CreateScript-ClassesOnly")] - public void CreateClassesScript() - { - RecursiveFindReferences(); - var filePath = SaveFilePanel("Save Script", Directory, $"{Filename}-Classes", "cs"); - VariantGenerator.CreateScriptClassOnly(filePath, Namespace, Types, IsReferenceType); - } - - private string Directory => Path.GetDirectoryName(AssetDatabase.GetAssetPath(this)); - - private void RecursiveFindReferences() - { - _referenceAssemblies = Assembly.ToAssembly().FindReferenceAssemblies(); - } - - private bool IsReferenceType(Type type) => _referenceAssemblies.Contains(type.Assembly); - } - - public static class VariantGenerator - { - public static void CreateScript(string filepath, string @namespace, string[] types, Predicate isReferenceType) - { - using (var writer = new StreamWriter(filepath)) - { - writer.WriteLine(NamespaceBegin(@namespace)); - foreach (var type in _VALUE_TYPES.Value) - { - if (types.Contains(type.FullName)) - { - writer.CreateReaderVariants(type, isReferenceType); - writer.CreateWriterVariants(type, isReferenceType); - writer.CreateReaderAndWriterVariants(type, isReferenceType); - writer.CreateSerializedReaderAndWriterVariant(type); - } - } - writer.WriteLine(NamespaceEnd()); - } - AssetDatabase.Refresh(); - } - - public static void CreateReaderVariants(this StreamWriter writer, Type valueType, Predicate isReferenceType = null, string suffix = "VariantReader") - { - writer.WriteLine(CreateInterface(valueType, typeof(IVariantReader<>), suffix)); - foreach (var propertyType in VARIANT_READER_TYPES.Value.Where(type => isReferenceType == null || isReferenceType(type))) - writer.WriteLine(CreateClass(valueType, propertyType, suffix)); - writer.WriteLine(); - } - - public static void CreateWriterVariants(this StreamWriter writer, Type valueType, Predicate isReferenceType = null, string suffix = "VariantWriter") - { - writer.WriteLine(CreateInterface(valueType, typeof(IVariantWriter<>), suffix)); - foreach (var propertyType in VARIANT_WRITER_TYPES.Value.Where(type => isReferenceType == null || isReferenceType(type))) - writer.WriteLine(CreateClass(valueType, propertyType, suffix)); - writer.WriteLine(); - } - - public static void CreateReaderAndWriterVariants(this StreamWriter writer, Type valueType, Predicate isReferenceType = null, string suffix = "VariantReaderAndWriter") - { - writer.WriteLine(CreateInterface(valueType, typeof(IVariantReaderAndWriter<>), suffix)); - foreach (var propertyType in VARIANT_READER_AND_WRITER_TYPES.Value.Where(type => isReferenceType == null || isReferenceType(type))) - writer.WriteLine(CreateClass(valueType, propertyType, suffix)); - writer.WriteLine(); - } - - public static void CreateSerializedReaderAndWriterVariant(this StreamWriter writer - , Type valueType - , string readerAndWriterSuffix = "VariantReaderAndWriter" - , string readerSuffix = "VariantReader" - , string writerSuffix = "VariantWriter" - ) - { - writer.Write($@" -[System.Serializable] -public class {valueType.Name}SerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter<{valueType.FullName}> -{{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private {valueType.Name}{readerAndWriterSuffix} _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter<{valueType.FullName}> ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private {valueType.Name}{readerSuffix} _reader; - public EntitiesBT.Variant.IVariantReader<{valueType.FullName}> Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private {valueType.Name}{writerSuffix} _writer; - public EntitiesBT.Variant.IVariantWriter<{valueType.FullName}> Writer => _writer; -}} -"); - } - - public static void CreateScriptInterfaceOnly(string filepath, string @namespace, params string[] types) - { - using (var writer = new StreamWriter(filepath)) - { - writer.WriteLine(NamespaceBegin(@namespace)); - foreach (var type in _VALUE_TYPES.Value) - if (types.Contains(type.FullName)) - { - writer.WriteLine(CreateInterface(type, typeof(IVariantReader<>))); - writer.WriteLine(CreateInterface(type, typeof(IVariantWriter<>))); - } - writer.WriteLine(NamespaceEnd()); - } - AssetDatabase.Refresh(); - } - - public static void CreateScriptClassOnly(string filepath, string @namespace, string[] types, Predicate isReferenceType = null) - { - using (var writer = new StreamWriter(filepath)) - { - writer.WriteLine(NamespaceBegin(@namespace)); - foreach (var type in _VALUE_TYPES.Value) - { - if (types.Contains(type.FullName)) - { - foreach (var propertyType in VARIANT_READER_TYPES.Value.Where(t => isReferenceType == null || isReferenceType(t))) - writer.WriteLine(CreateClass(type, propertyType)); - foreach (var propertyType in VARIANT_WRITER_TYPES.Value.Where(t => isReferenceType == null || isReferenceType(t))) - writer.WriteLine(CreateClass(type, propertyType)); - } - } - writer.WriteLine(NamespaceEnd()); - } - AssetDatabase.Refresh(); - } - - private static string CreateInterface(Type type, Type variantType, string suffix = "Variant") - { - return $"public interface {type.Name}{suffix} : {variantType.FullName.ToCodeName()}<{type.FullName}> {{ }}"; - } - - private static string CreateClass(Type valueType, Type variantType, string suffix = "Variant", string classNameSuffix = null) - { - classNameSuffix ??= variantType.FullName.ToShortNameWithInnerClass(); - var className = $"{valueType.Name}{classNameSuffix}"; - var baseClassName = $"{variantType.FullName.ToCodeName()}<{valueType.FullName}>"; - var interfaceName = $"{valueType.Name}{suffix}"; - return $"public class {className} : {baseClassName}, {interfaceName} {{ }}"; - } - - public static string NamespaceBegin(string @namespace) - { - return $"namespace {@namespace}" + Environment.NewLine + "{" + Environment.NewLine; - } - - public static string NamespaceEnd() - { - return Environment.NewLine + "}" + Environment.NewLine; - } - - private static readonly Lazy> _VALUE_TYPES = new Lazy>(() => - Core.Utilities.ALL_TYPES.Value - .Where(type => type != typeof(void)) - .Where(type => type.IsPrimitive || type.IsValueType && type.HasSerializableAttribute()) - ); - - private static bool HasSerializableAttribute(this Type type) - { - return Attribute.GetCustomAttribute(type, typeof(SerializableAttribute)) != null; - } - } -} diff --git a/Packages/essential/Editor/VariantGeneratorSetting.cs.meta b/Packages/essential/Editor/VariantGeneratorSetting.cs.meta deleted file mode 100644 index bcac12b1..00000000 --- a/Packages/essential/Editor/VariantGeneratorSetting.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: f90e02d7d6784323bd6696496977dabc -timeCreated: 1583061570 \ No newline at end of file diff --git a/Packages/essential/Runtime/Components/BehaviorTreeRoot.cs b/Packages/essential/Runtime/Components/BehaviorTreeRoot.cs index accfa308..fcf74a0b 100644 --- a/Packages/essential/Runtime/Components/BehaviorTreeRoot.cs +++ b/Packages/essential/Runtime/Components/BehaviorTreeRoot.cs @@ -9,7 +9,7 @@ namespace EntitiesBT.Components { public class BehaviorTreeRoot : MonoBehaviour, IConvertGameObjectToEntity { - [SerializeReference, SerializeReferenceButton] private IBehaviorTreeSource _source = default; + [SerializeReference, SerializeReferenceDrawer] private IBehaviorTreeSource _source = default; [SerializeField] private BehaviorTreeThread _thread = BehaviorTreeThread.ForceRunOnMainThread; [Tooltip("add queried components of behavior tree into entity automatically")] diff --git a/Packages/essential/Runtime/Core/BehaviorNodeAttribute.cs b/Packages/essential/Runtime/Core/BehaviorNodeAttribute.cs index 6a4018a3..48fafd09 100644 --- a/Packages/essential/Runtime/Core/BehaviorNodeAttribute.cs +++ b/Packages/essential/Runtime/Core/BehaviorNodeAttribute.cs @@ -1,6 +1,7 @@ using System; using System.Reflection; using JetBrains.Annotations; +using UnityEngine.Scripting; namespace EntitiesBT.Core { @@ -13,7 +14,7 @@ public enum BehaviorNodeType [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] [BaseTypeRequired(typeof(INodeData))] - public class BehaviorNodeAttribute : Attribute + public class BehaviorNodeAttribute : PreserveAttribute { public Guid Guid { get; } public int Id { get; } diff --git a/Packages/essential/Runtime/Core/IBlackboard.cs b/Packages/essential/Runtime/Core/IBlackboard.cs index 1f364f12..6894c171 100644 --- a/Packages/essential/Runtime/Core/IBlackboard.cs +++ b/Packages/essential/Runtime/Core/IBlackboard.cs @@ -6,7 +6,7 @@ namespace EntitiesBT.Core public interface IBlackboard { bool HasData() where T : struct; - T GetData<[ReadOnly(typeof(int))] T>() where T : struct; + T GetData<[ReadOnly] T>() where T : struct; ref T GetDataRef<[ReadWrite] T>() where T : struct; bool HasData(Type type); diff --git a/Packages/essential/Runtime/Core/INodeBlob.cs b/Packages/essential/Runtime/Core/INodeBlob.cs index 4dc9d94f..661b7bd0 100644 --- a/Packages/essential/Runtime/Core/INodeBlob.cs +++ b/Packages/essential/Runtime/Core/INodeBlob.cs @@ -6,6 +6,7 @@ namespace EntitiesBT.Core { public interface INodeBlob { + int RuntimeId { [Pure] get; } int Count { [Pure] get; } [Pure] int GetTypeId(int nodeIndex); diff --git a/Packages/essential/Runtime/Core/INodeData.cs b/Packages/essential/Runtime/Core/INodeData.cs index 5dcf4e79..17104779 100644 --- a/Packages/essential/Runtime/Core/INodeData.cs +++ b/Packages/essential/Runtime/Core/INodeData.cs @@ -6,7 +6,10 @@ NodeState Tick(int index, ref TNodeBlob blob, ref TBlack where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard ; - + } + + public interface ICustomResetAction + { void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard diff --git a/Packages/essential/Runtime/Core/MetaNodeRegister.cs b/Packages/essential/Runtime/Core/MetaNodeRegister.cs index b711be21..f35aa8a5 100644 --- a/Packages/essential/Runtime/Core/MetaNodeRegister.cs +++ b/Packages/essential/Runtime/Core/MetaNodeRegister.cs @@ -7,6 +7,7 @@ using System.Runtime.InteropServices; using Unity.Collections.LowLevel.Unsafe; using Unity.Entities; +using UnityEngine; using UnityEngine.Scripting; using static EntitiesBT.Core.Utilities; @@ -104,7 +105,7 @@ internal static class MetaNodeRegister [Preserve] private static unsafe NodeState Tick(IntPtr ptr, int index, TNodeBlob blob, TBlackboard bb) - where TNodeData : struct, INodeData + where TNodeData : unmanaged, INodeData { return UnsafeUtility.AsRef((void*)ptr).Tick(index, ref blob, ref bb); } @@ -113,11 +114,13 @@ private static unsafe NodeState Tick(IntPtr ptr, int index, TNodeBlob [Preserve] private static unsafe void Reset(IntPtr ptr, int index, TNodeBlob blob, TBlackboard bb) - where TNodeData : struct, INodeData + where TNodeData : unmanaged, ICustomResetAction { UnsafeUtility.AsRef((void*)ptr).Reset(index, ref blob, ref bb); } - + + private static void DefaultReset(IntPtr ptr, int index, TNodeBlob blob, TBlackboard bb) {} + internal class Node { public ResetFunc Reset; @@ -126,27 +129,45 @@ internal class Node internal static readonly IReadOnlyDictionary NODES; + [Preserve] static MetaNodeRegister() { + var resetMethod = GetMethod(nameof(Reset)); + var tickMethod = GetMethod(nameof(Tick)); + var nodes = new Dictionary(); foreach (var type in MetaNodeRegister.NODES.Values.Select(node => node.Type)) { var attribute = type.GetCustomAttribute(); - nodes[attribute.Id] = new Node { - Reset = CreateDelegate(nameof(Reset), type) - , Tick = CreateDelegate(nameof(Tick), type) - }; + try + { + var node = new Node + { + Reset = typeof(ICustomResetAction).IsAssignableFrom(type) ? + CreateDelegate(resetMethod, type) : DefaultReset, + Tick = CreateDelegate(tickMethod, type) + }; + nodes[attribute.Id] = node; + } + catch (Exception ex) + { + Debug.LogException(ex); + } } + NODES = new ReadOnlyDictionary(nodes); - - T CreateDelegate(string methodName, Type type) where T : Delegate + + MethodInfo GetMethod(string methodName) { - return (T) typeof(MetaNodeRegister) - .GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static) - .MakeGenericMethod(type) - .CreateDelegate(typeof(T)) + return typeof(MetaNodeRegister) + .GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) ; } + + T CreateDelegate(MethodInfo methodInfo, Type type) where T : Delegate + { + return (T) methodInfo.MakeGenericMethod(type).CreateDelegate(typeof(T)); + } } } } diff --git a/Packages/essential/Runtime/Core/Utilities.cs b/Packages/essential/Runtime/Core/Utilities.cs index fe0a7606..8f6be03e 100644 --- a/Packages/essential/Runtime/Core/Utilities.cs +++ b/Packages/essential/Runtime/Core/Utilities.cs @@ -120,7 +120,7 @@ public static Type[] GetTypesWithoutException(this Assembly assembly) ); public static readonly Lazy> ALL_TYPES = new Lazy>( - () => new ReadOnlyCollection(ALL_ASSEMBLIES.Value.SelectMany(assembly => assembly.GetTypes()).ToArray()) + () => new ReadOnlyCollection(ALL_ASSEMBLIES.Value.SelectMany(assembly => assembly.GetTypesWithoutException()).ToArray()) ); public static readonly Lazy> BEHAVIOR_TREE_ASSEMBLY_TYPES = new Lazy>( diff --git a/Packages/essential/Runtime/Entities/BehaviorTreeLifeCycleSystem.cs b/Packages/essential/Runtime/Entities/BehaviorTreeLifeCycleSystem.cs index 49d81396..23ab43df 100644 --- a/Packages/essential/Runtime/Entities/BehaviorTreeLifeCycleSystem.cs +++ b/Packages/essential/Runtime/Entities/BehaviorTreeLifeCycleSystem.cs @@ -6,6 +6,8 @@ namespace EntitiesBT.Entities [UpdateBefore(typeof(VirtualMachineSystem))] public class BehaviorTreeLifeCycleSystem : SystemBase { + private int _runtimeId = 0; + struct LastTargetComponent : ISystemStateComponentData { public Entity Target; @@ -23,6 +25,8 @@ protected override void OnUpdate() .ForEach((Entity entity, in BlackboardDataQuery query, in BehaviorTreeComponent bt, in BehaviorTreeTargetComponent target, in BehaviorTreeOrderComponent order) => { var blob = new NodeBlobRef(bt.Blob.BlobRef.Clone()); + blob.RuntimeId = _runtimeId; + _runtimeId++; EntityManager.AddComponentData(entity, new LastTargetComponent {Target = target.Value, Blob = blob}); BindBehaviorTree(entity, bt, query, target.Value, order.Value, blob); }).Run(); diff --git a/Packages/essential/Runtime/Entities/ComponentVariant.cs b/Packages/essential/Runtime/Entities/ComponentVariant.cs index 706027fb..c94388e7 100644 --- a/Packages/essential/Runtime/Entities/ComponentVariant.cs +++ b/Packages/essential/Runtime/Entities/ComponentVariant.cs @@ -4,7 +4,6 @@ using Unity.Collections.LowLevel.Unsafe; using Unity.Entities; using UnityEngine; -using UnityEngine.Scripting; using static EntitiesBT.Core.Utilities; using static EntitiesBT.Variant.Utilities; @@ -13,8 +12,11 @@ namespace EntitiesBT.Variant [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class VariantComponentDataAttribute : PropertyAttribute {} + [VariantClass(GUID)] public static class ComponentVariant { + public const string GUID = "8E5CDB60-17DB-498A-B925-2094062769AB"; + [Serializable] public class Any : IVariant where T : unmanaged { @@ -37,18 +39,16 @@ public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INo [Serializable] public class Writer : Any, IVariantWriter where T : unmanaged {} [Serializable] public class ReaderAndWriter : Any, IVariantReaderAndWriter where T : unmanaged {} - public const string GUID = "8E5CDB60-17DB-498A-B925-2094062769AB"; - public struct DynamicComponentData { public ulong StableHash; public int Offset; } - [Preserve, AccessorMethod(GUID)] + [AccessorMethod] private static IEnumerable GetDynamicAccess(ref BlobVariant blobVariant) { - var hash = blobVariant.Value().StableHash; + var hash = blobVariant.As().StableHash; var typeIndex = TypeManager.GetTypeIndexFromStableTypeHash(hash); return ComponentType.FromTypeIndex(typeIndex).Yield(); } @@ -63,23 +63,23 @@ private static unsafe ref T GetComponentValue(ulong stableHash, int offset, F return ref UnsafeUtility.AsRef(dataPtr.ToPointer()); } - [Preserve, ReaderMethod(GUID)] + [ReaderMethod] private static T GetData(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - ref var data = ref blobVariant.Value(); + ref var data = ref blobVariant.As(); return GetComponentValue(data.StableHash, data.Offset, bb.GetDataPtrRO); } - [Preserve, RefReaderMethod(GUID)] + [RefReaderMethod] private static ref T GetDataRef(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - ref var data = ref blobVariant.Value(); + ref var data = ref blobVariant.As(); return ref GetComponentValue(data.StableHash, data.Offset, bb.GetDataPtrRW); } diff --git a/Packages/essential/Runtime/Entities/NodeBlob.cs b/Packages/essential/Runtime/Entities/NodeBlob.cs index 5631fd65..f38d7f16 100644 --- a/Packages/essential/Runtime/Entities/NodeBlob.cs +++ b/Packages/essential/Runtime/Entities/NodeBlob.cs @@ -9,7 +9,7 @@ namespace EntitiesBT.Entities { public struct NodeBlob { - public const int VERSION = 2; + public const int VERSION = 3; #region Serialized Data public BlobArray Types; @@ -19,6 +19,7 @@ public struct NodeBlob #endregion #region NonSerialized Data (runtime only) + public int RuntimeId; public BlobArray States; // states of each nodes public BlobArray RuntimeDataBlob; // initialize from `DefaultDataBlob` #endregion @@ -44,7 +45,13 @@ public static int CalculateSize(int count, int dataSize) => public readonly BlobAssetReference BlobRef; public NodeBlobRef(BlobAssetReference blobRef) => BlobRef = blobRef; - + + public int RuntimeId + { + get => _blob.RuntimeId; + set => _blob.RuntimeId = value; + } + public int Count => _blob.Count; public int GetTypeId(int nodeIndex) => _blob.Types[nodeIndex]; public int GetEndIndex(int nodeIndex) => _blob.EndIndices[nodeIndex]; diff --git a/Packages/essential/Runtime/Nodes/Actions/DelayTimeNode.cs b/Packages/essential/Runtime/Nodes/Actions/DelayTimeNode.cs index d5724765..7da4aaec 100644 --- a/Packages/essential/Runtime/Nodes/Actions/DelayTimeNode.cs +++ b/Packages/essential/Runtime/Nodes/Actions/DelayTimeNode.cs @@ -20,11 +20,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref TimerSeconds.Write(index, ref blob, ref bb, timer); return timer <= 0 ? NodeState.Success : NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Actions/FailedNode.cs b/Packages/essential/Runtime/Nodes/Actions/FailedNode.cs index b6ca4ada..00610b77 100644 --- a/Packages/essential/Runtime/Nodes/Actions/FailedNode.cs +++ b/Packages/essential/Runtime/Nodes/Actions/FailedNode.cs @@ -11,11 +11,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref { return NodeState.Failure; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Actions/HasComponentNode.cs b/Packages/essential/Runtime/Nodes/Actions/HasComponentNode.cs index 91bcd2c2..510a88b0 100644 --- a/Packages/essential/Runtime/Nodes/Actions/HasComponentNode.cs +++ b/Packages/essential/Runtime/Nodes/Actions/HasComponentNode.cs @@ -16,11 +16,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref var type = TypeManager.GetType(typeIndex); return bb.HasData(type).ToNodeState(); } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Actions/ModifyPriorityNode.cs b/Packages/essential/Runtime/Nodes/Actions/ModifyPriorityNode.cs index 785f704b..6e625e25 100644 --- a/Packages/essential/Runtime/Nodes/Actions/ModifyPriorityNode.cs +++ b/Packages/essential/Runtime/Nodes/Actions/ModifyPriorityNode.cs @@ -21,11 +21,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref prioritySelectorData.Weights[WeightIndex] += AddWeight; return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Actions/RunningNode.cs b/Packages/essential/Runtime/Nodes/Actions/RunningNode.cs index a7b5202d..9f475088 100644 --- a/Packages/essential/Runtime/Nodes/Actions/RunningNode.cs +++ b/Packages/essential/Runtime/Nodes/Actions/RunningNode.cs @@ -11,11 +11,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref { return NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Actions/SuccessNode.cs b/Packages/essential/Runtime/Nodes/Actions/SuccessNode.cs index fc0d166c..02e9a548 100644 --- a/Packages/essential/Runtime/Nodes/Actions/SuccessNode.cs +++ b/Packages/essential/Runtime/Nodes/Actions/SuccessNode.cs @@ -11,11 +11,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref { return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Composites/ParallelNode.cs b/Packages/essential/Runtime/Nodes/Composites/ParallelNode.cs index d3daec1d..0d6bc462 100644 --- a/Packages/essential/Runtime/Nodes/Composites/ParallelNode.cs +++ b/Packages/essential/Runtime/Nodes/Composites/ParallelNode.cs @@ -30,11 +30,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref if (flags.HasFlagFast(NodeState.Success)) return NodeState.Success; return 0; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Composites/PrioritySelectorNode.cs b/Packages/essential/Runtime/Nodes/Composites/PrioritySelectorNode.cs index 59134c26..f14cbc31 100644 --- a/Packages/essential/Runtime/Nodes/Composites/PrioritySelectorNode.cs +++ b/Packages/essential/Runtime/Nodes/Composites/PrioritySelectorNode.cs @@ -40,11 +40,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref return VirtualMachine.Tick(maxChildIndex, ref blob, ref blackboard); } } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Composites/RandomSelectorNode.cs b/Packages/essential/Runtime/Nodes/Composites/RandomSelectorNode.cs index a5b371d6..d1891810 100644 --- a/Packages/essential/Runtime/Nodes/Composites/RandomSelectorNode.cs +++ b/Packages/essential/Runtime/Nodes/Composites/RandomSelectorNode.cs @@ -36,10 +36,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref return VirtualMachine.Tick(chosenIndex, ref blob, ref blackboard); } } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - {} } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Composites/SelectorNode.cs b/Packages/essential/Runtime/Nodes/Composites/SelectorNode.cs index 63d849d0..d6dcdd19 100644 --- a/Packages/essential/Runtime/Nodes/Composites/SelectorNode.cs +++ b/Packages/essential/Runtime/Nodes/Composites/SelectorNode.cs @@ -11,11 +11,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref { return index.TickChildrenReturnLastOrDefault(ref blob, ref bb, breakCheck: state => state.IsRunningOrSuccess()); } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Composites/SequenceNode.cs b/Packages/essential/Runtime/Nodes/Composites/SequenceNode.cs index 3695f1cb..c502f441 100644 --- a/Packages/essential/Runtime/Nodes/Composites/SequenceNode.cs +++ b/Packages/essential/Runtime/Nodes/Composites/SequenceNode.cs @@ -11,11 +11,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref { return index.TickChildrenReturnLastOrDefault(ref blob, ref bb, breakCheck: state => state.IsRunningOrFailure()); } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Composites/WeightRandomSelectorNode.cs b/Packages/essential/Runtime/Nodes/Composites/WeightRandomSelectorNode.cs index 1e75c05f..48eea999 100644 --- a/Packages/essential/Runtime/Nodes/Composites/WeightRandomSelectorNode.cs +++ b/Packages/essential/Runtime/Nodes/Composites/WeightRandomSelectorNode.cs @@ -37,11 +37,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref return 0; } } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Decorators/ErrorRerunOnceNode.cs b/Packages/essential/Runtime/Nodes/Decorators/ErrorRerunOnceNode.cs index c3f742e5..8e81d77b 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/ErrorRerunOnceNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/ErrorRerunOnceNode.cs @@ -15,9 +15,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref } return childState; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/RecursiveResetStateNode.cs b/Packages/essential/Runtime/Nodes/Decorators/RecursiveResetStateNode.cs index 028df981..5625e6ab 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/RecursiveResetStateNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/RecursiveResetStateNode.cs @@ -24,11 +24,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref blob.ResetStates(childIndex, count); return index.TickChild(ref blob, ref bb); } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/RepeatDurationNode.cs b/Packages/essential/Runtime/Nodes/Decorators/RepeatDurationNode.cs index 3489574a..bad856a5 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/RepeatDurationNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/RepeatDurationNode.cs @@ -26,11 +26,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref CountdownSeconds -= bb.GetData().Value; return CountdownSeconds <= 0 ? NodeState.Success : NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/RepeatForeverNode.cs b/Packages/essential/Runtime/Nodes/Decorators/RepeatForeverNode.cs index caa42def..c622b3c0 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/RepeatForeverNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/RepeatForeverNode.cs @@ -21,11 +21,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref } return BreakStates.HasFlagFast(childState) ? childState : NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/RepeatTimesNode.cs b/Packages/essential/Runtime/Nodes/Decorators/RepeatTimesNode.cs index 2f01b239..4b8efb32 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/RepeatTimesNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/RepeatTimesNode.cs @@ -25,11 +25,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref TickTimes--; return TickTimes <= 0 ? NodeState.Success : NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/ResetBranchNode.cs b/Packages/essential/Runtime/Nodes/Decorators/ResetBranchNode.cs index 4fe9f32e..54177607 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/ResetBranchNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/ResetBranchNode.cs @@ -12,11 +12,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref VirtualMachine.Reset(index, ref blob, ref blackboard, blob.GetEndIndex(index) - index); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/essential/Runtime/Nodes/Decorators/RunOnMainThreadNode.cs b/Packages/essential/Runtime/Nodes/Decorators/RunOnMainThreadNode.cs index 795f1b8f..0fe521d3 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/RunOnMainThreadNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/RunOnMainThreadNode.cs @@ -24,11 +24,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref if (state != NodeState.Running) behaviorTreeElement.RuntimeThread = BehaviorTreeRuntimeThread.JobThread; return state; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/StateMapNode.cs b/Packages/essential/Runtime/Nodes/Decorators/StateMapNode.cs index c58c41a2..33ab955c 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/StateMapNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/StateMapNode.cs @@ -21,9 +21,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref default: return MapError; } } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/StateReverseNode.cs b/Packages/essential/Runtime/Nodes/Decorators/StateReverseNode.cs index edf97801..a2df0be2 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/StateReverseNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/StateReverseNode.cs @@ -17,11 +17,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref default: return childState; } } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/Decorators/TimerNode.cs b/Packages/essential/Runtime/Nodes/Decorators/TimerNode.cs index b1fce66e..49ca221b 100644 --- a/Packages/essential/Runtime/Nodes/Decorators/TimerNode.cs +++ b/Packages/essential/Runtime/Nodes/Decorators/TimerNode.cs @@ -26,11 +26,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref CountdownSeconds.Write(index, ref blob, ref bb, countdown); return countdown <= 0f ? NodeState.Success : NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/essential/Runtime/Nodes/ZeroNode.cs b/Packages/essential/Runtime/Nodes/ZeroNode.cs index b875188c..efb746b8 100644 --- a/Packages/essential/Runtime/Nodes/ZeroNode.cs +++ b/Packages/essential/Runtime/Nodes/ZeroNode.cs @@ -5,7 +5,7 @@ namespace EntitiesBT.Nodes { [BehaviorNode("08A91977-0B32-455D-874E-E29B4F1A0FD1"), StructLayout(LayoutKind.Explicit)] - public struct ZeroNode : INodeData + public struct ZeroNode : INodeData, ICustomResetAction { public NodeState Tick(int index, ref TNodeBlob blob, ref TBlackboard bb) where TNodeBlob : struct, INodeBlob diff --git a/Packages/essential/Runtime/Variant/BlobVariant.cs b/Packages/essential/Runtime/Variant/BlobVariant.cs index afd82868..1f54f4e6 100644 --- a/Packages/essential/Runtime/Variant/BlobVariant.cs +++ b/Packages/essential/Runtime/Variant/BlobVariant.cs @@ -1,9 +1,4 @@ -using System.Collections.Generic; using System.Runtime.InteropServices; -using EntitiesBT.Core; -using JetBrains.Annotations; -using Unity.Collections.LowLevel.Unsafe; -using Unity.Entities; namespace EntitiesBT.Variant { @@ -12,64 +7,5 @@ public struct BlobVariant { public int VariantId; public int MetaDataOffsetPtr; - - public static BlobVariant INVALID = new BlobVariant {VariantId = 0, MetaDataOffsetPtr = 0}; - - [Pure] - public ref TValue Value() where TValue : struct => - ref UnsafeUtility.As>(ref MetaDataOffsetPtr).Value; - - [Pure] - public IEnumerable GetComponentAccessList() => - VariantRegisters.GetComponentAccess(VariantId)(ref this); - } - - internal static class BlobVariantExtension - { - public static T Read(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) - where T : unmanaged - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - return VariantRegisters.GetReader(blobVariant.VariantId)(ref blobVariant, index, ref blob, ref bb); - } - - public static ref T ReadRef(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) - where T : unmanaged - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - return ref VariantRegisters.GetRefReader(blobVariant.VariantId)(ref blobVariant, index, ref blob, ref bb); - } - - public static T ReadWithRefFallback(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) - where T : unmanaged - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - return VariantRegisters.TryGetReader(blobVariant.VariantId, out var reader) - ? reader(ref blobVariant, index, ref blob, ref bb) - : VariantRegisters.GetRefReader(blobVariant.VariantId)(ref blobVariant, index, ref blob, ref bb) - ; - } - - public static void Write(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb, T value) - where T : unmanaged - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - VariantRegisters.GetWriter(blobVariant.VariantId)(ref blobVariant, index, ref blob, ref bb, value); - } - - public static void WriteWithRefFallback(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb, T value) - where T : unmanaged - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - if (VariantRegisters.TryGetWriter(blobVariant.VariantId, out var writer)) - writer(ref blobVariant, index, ref blob, ref bb, value); - else - VariantRegisters.GetRefReader(blobVariant.VariantId)(ref blobVariant, index, ref blob, ref bb) = value; - } } } diff --git a/Packages/essential/Runtime/Variant/BlobVariantReadOnlyPtr.cs b/Packages/essential/Runtime/Variant/BlobVariantReadOnlyPtr.cs new file mode 100644 index 00000000..f6590c5e --- /dev/null +++ b/Packages/essential/Runtime/Variant/BlobVariantReadOnlyPtr.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using EntitiesBT.Core; +using Unity.Entities; + +namespace EntitiesBT.Variant +{ + [StructLayout(LayoutKind.Sequential)] + public struct BlobVariantReadOnlyPtr : IRuntimeComponentAccessor + { + internal BlobVariant Value; + + public IntPtr GetPointer(int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + return Value.ReadOnlyPtrWithReadWriteFallback(index, ref blob, ref bb); + } + + public IEnumerable AccessTypes => + Value.GetComponentAccessList().Select(t => ComponentType.ReadOnly(t.TypeIndex)) + ; + } +} diff --git a/Packages/essential/Runtime/Variant/BlobVariantReadOnlyPtr.cs.meta b/Packages/essential/Runtime/Variant/BlobVariantReadOnlyPtr.cs.meta new file mode 100644 index 00000000..aaa338c8 --- /dev/null +++ b/Packages/essential/Runtime/Variant/BlobVariantReadOnlyPtr.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1f75d77fbb764e378d9357d52da79b59 +timeCreated: 1626933286 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/BlobVariantReadWritePtr.cs b/Packages/essential/Runtime/Variant/BlobVariantReadWritePtr.cs new file mode 100644 index 00000000..0dc21c26 --- /dev/null +++ b/Packages/essential/Runtime/Variant/BlobVariantReadWritePtr.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using EntitiesBT.Core; +using Unity.Entities; + +namespace EntitiesBT.Variant +{ + [StructLayout(LayoutKind.Sequential)] + public struct BlobVariantReadWritePtr : IRuntimeComponentAccessor + { + internal BlobVariant Value; + + public IntPtr GetPointer(int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + return Value.ReadWritePtr(index, ref blob, ref bb); + } + + public IEnumerable AccessTypes => + Value.GetComponentAccessList().Select(t => ComponentType.ReadWrite(t.TypeIndex)) + ; + } +} diff --git a/Packages/essential/Runtime/Variant/BlobVariantReadWritePtr.cs.meta b/Packages/essential/Runtime/Variant/BlobVariantReadWritePtr.cs.meta new file mode 100644 index 00000000..a1505692 --- /dev/null +++ b/Packages/essential/Runtime/Variant/BlobVariantReadWritePtr.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1683585571194125b92391187fc1582d +timeCreated: 1626934058 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/DelegateRegistry.cs b/Packages/essential/Runtime/Variant/DelegateRegistry.cs new file mode 100644 index 00000000..e77d8da6 --- /dev/null +++ b/Packages/essential/Runtime/Variant/DelegateRegistry.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using EntitiesBT.Core; +using JetBrains.Annotations; +using UnityEngine; +using UnityEngine.Scripting; +using static EntitiesBT.Core.Utilities; + +namespace EntitiesBT.Variant +{ + [AttributeUsage(AttributeTargets.Class)] + public class RegisterDelegateClassAttribute : PreserveAttribute + { + public string Guid { get; } + public RegisterDelegateClassAttribute([NotNull] string guid) => Guid = guid; + } + + [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] + public class RegisterDelegateMethodAttribute : PreserveAttribute + { + public Type DelegateType { get; } + public string OverrideGuid = null; + public RegisterDelegateMethodAttribute([NotNull] Type delegateType) => DelegateType = delegateType; + public RegisterDelegateMethodAttribute([NotNull] Type delegateType, string guid) => + (DelegateType, OverrideGuid) = (delegateType, guid); + } + + internal static class DelegateRegistry + { + internal static readonly IReadOnlyDictionary> DELEGATE_METHOD_MAP; + + static DelegateRegistry() + { + var methodFlags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public; + if (Application.isEditor || Debug.isDebugBuild) methodFlags |= BindingFlags.Instance; + + var map = new Dictionary>(); + foreach (var (guid, methodInfo, delegateType) in + from type in typeof(RegisterDelegateMethodAttribute).Assembly.GetTypesIncludeReference() + from classAttribute in type.GetCustomAttributes() + from method in type.GetMethods(methodFlags) + from methodAttribute in method.GetCustomAttributes() + select (methodAttribute.OverrideGuid ?? classAttribute.Guid, method, methodAttribute.DelegateType) + ) + { + if (Validate(guid, methodInfo, delegateType, out var key, out var delegateIdMethodMap)) + { + if (delegateIdMethodMap == null) + { + delegateIdMethodMap = new Dictionary(); + map[delegateType] = delegateIdMethodMap; + } + delegateIdMethodMap[key] = methodInfo; + } + } + + DELEGATE_METHOD_MAP = new ReadOnlyDictionary>( + map.Select(t => (t.Key, Value: new ReadOnlyDictionary(t.Value))) + .ToDictionary(t => t.Key, t => (IReadOnlyDictionary)t.Value) + ); + + bool Validate(string guid, MethodInfo methodInfo, Type delegateType, out int key, out Dictionary delegateIdMethodMap) + { + key = 0; + delegateIdMethodMap = null; + + if (!methodInfo.IsStatic) + { + Debug.LogError($"Non-static method {methodInfo.Name} {guid} is not support"); + return false; + } + + if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) + { + Debug.LogError($"{delegateType.FullName} on {methodInfo.Name} is not a delegate."); + return false; + } + + if (!Guid.TryParse(guid, out var id)) + { + Debug.LogError($"Invalid guid {guid} of delegate method {methodInfo.Name}"); + return false; + } + + key = GuidHashCode(id); + if (map.TryGetValue(delegateType, out delegateIdMethodMap) && delegateIdMethodMap.TryGetValue(key, out var duplicateMethod)) + { + Debug.LogError($"Duplicate guid {guid} of delegate method {methodInfo.Name} and {duplicateMethod.Name}"); + return false; + } + + // TODO: check the compability of `methodInfo` and `delegateType` + // if (!methodInfo.IsDelegate(delegateType)) + // { + // Debug.LogError($"{methodInfo.Name} cannot match delegate {delegateType.FullName}"); + // return false; + // } + + return true; + } + } + } + + public static class DelegateRegistry where TDelegate : Delegate + { + internal static readonly IReadOnlyDictionary DELEGATES; + + static DelegateRegistry() + { + IReadOnlyDictionary delegateMap = null; + IReadOnlyDictionary genericDelegateMap = null; + var delegateType = typeof(TDelegate); + DelegateRegistry.DELEGATE_METHOD_MAP.TryGetValue(delegateType, out delegateMap); + if (delegateType.IsGenericType) + DelegateRegistry.DELEGATE_METHOD_MAP.TryGetValue(delegateType.GetGenericTypeDefinition(), out genericDelegateMap); + + var count = (delegateMap?.Count ?? 0) + (genericDelegateMap?.Count ?? 0); + var map = new Dictionary(count); + + var genericArguments = delegateType.GetGenericArguments(); + FillMap(delegateMap, methodInfo => methodInfo); + FillMap(genericDelegateMap, methodInfo => methodInfo.MakeGenericMethod(genericArguments)); + DELEGATES = new ReadOnlyDictionary(map); + + void FillMap(IReadOnlyDictionary idMethodMap, Func createConcreteMethodInfo) + { + if (idMethodMap == null) return; + + foreach (var t in idMethodMap) + { + if (map.TryGetValue(t.Key, out var oldDelegate)) + { + Debug.Log($"Skip {t.Value} @ {delegateType.Name}[{t.Key}], already have {oldDelegate}"); + continue; + } + + try + { + var methodInfo = createConcreteMethodInfo(t.Value); + var @delegate = (TDelegate) methodInfo.CreateDelegate(typeof(TDelegate)); + map[t.Key] = @delegate; + } + catch + { + Debug.LogError($"Cannot create delegate {delegateType.GetFriendlyName()} from {t.Value.Name}"); + } + } + } + } + + [CanBeNull] public static TDelegate TryGetValue(int id) + { + DELEGATES.TryGetValue(id, out var value); + return value; + } + } +} \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/DelegateRegistry.cs.meta b/Packages/essential/Runtime/Variant/DelegateRegistry.cs.meta new file mode 100644 index 00000000..2a3fbbaf --- /dev/null +++ b/Packages/essential/Runtime/Variant/DelegateRegistry.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7da3e769816c4b2183c25bb43e86d293 +timeCreated: 1614863356 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/Extensions.cs b/Packages/essential/Runtime/Variant/Extensions.cs new file mode 100644 index 00000000..f81b131a --- /dev/null +++ b/Packages/essential/Runtime/Variant/Extensions.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using EntitiesBT.Core; +using JetBrains.Annotations; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Entities; +using Debug = UnityEngine.Debug; + +namespace EntitiesBT.Variant +{ + public static class BlobVariantExtension + { + [Pure] + public static unsafe ref TValue As(this ref BlobVariant blobVariant) where TValue : unmanaged => + ref UnsafeUtility.AsRef(blobVariant.AsPointer()); + + [Pure] + public static unsafe void* AsPointer(this ref BlobVariant blobVariant) + { + fixed (int* thisPtr = &blobVariant.MetaDataOffsetPtr) + { + return (byte*)thisPtr + blobVariant.MetaDataOffsetPtr; + } + } + + [Pure] + public static unsafe object AsObject(this ref BlobVariant blobVariant, Type valueType) => + Marshal.PtrToStructure(new IntPtr(blobVariant.AsPointer()), valueType); + + [Pure] + public static IEnumerable GetComponentAccessList(this ref BlobVariant blobVariant) + { + var @delegate = DelegateRegistry.TryGetValue(blobVariant.VariantId); + return @delegate == null ? Enumerable.Empty() : @delegate(ref blobVariant); + } + + public static T Read(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where T : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var @delegate = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + Debug.Assert(@delegate != null, nameof(@delegate) + " != null"); + return @delegate.Invoke(ref blobVariant, index, ref blob, ref bb); + } + + public static IntPtr ReadOnlyPtr(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var @delegate = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + Debug.Assert(@delegate != null, nameof(@delegate) + " != null"); + return @delegate.Invoke(ref blobVariant, index, ref blob, ref bb); + } + + public static IntPtr ReadWritePtr(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var @delegate = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + Debug.Assert(@delegate != null, nameof(@delegate) + " != null"); + return @delegate.Invoke(ref blobVariant, index, ref blob, ref bb); + } + + public static IntPtr ReadOnlyPtrWithReadWriteFallback(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var @delegate = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + if (@delegate != null) return @delegate.Invoke(ref blobVariant, index, ref blob, ref bb); + return ReadWritePtr(ref blobVariant, index, ref blob, ref bb); + } + + public static ref T ReadRef(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where T : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var @delegate = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + Debug.Assert(@delegate != null, nameof(@delegate) + " != null"); + return ref @delegate(ref blobVariant, index, ref blob, ref bb); + } + + public static T ReadWithRefFallback(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where T : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var reader = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + if (reader != null) return reader(ref blobVariant, index, ref blob, ref bb); + return ReadRef(ref blobVariant, index, ref blob, ref bb); + } + + public static void Write(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb, T value) + where T : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var @delegate = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + Debug.Assert(@delegate != null, nameof(@delegate) + " != null"); + @delegate(ref blobVariant, index, ref blob, ref bb, value); + } + + public static void WriteWithRefFallback(this ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb, T value) + where T : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + var writer = DelegateRegistry> + .TryGetValue(blobVariant.VariantId) + ; + if (writer != null) writer(ref blobVariant, index, ref blob, ref bb, value); + else ReadRef(ref blobVariant, index, ref blob, ref bb) = value; + } + } +} \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/Extensions.cs.meta b/Packages/essential/Runtime/Variant/Extensions.cs.meta new file mode 100644 index 00000000..16f95df4 --- /dev/null +++ b/Packages/essential/Runtime/Variant/Extensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 975a07d113154344b496b0c9e36a40bf +timeCreated: 1614937821 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/ISerializedVariantReaderAndWriter.cs b/Packages/essential/Runtime/Variant/ISerializedVariantRW.cs similarity index 73% rename from Packages/essential/Runtime/Variant/ISerializedVariantReaderAndWriter.cs rename to Packages/essential/Runtime/Variant/ISerializedVariantRW.cs index b5b534d3..78f50ba5 100644 --- a/Packages/essential/Runtime/Variant/ISerializedVariantReaderAndWriter.cs +++ b/Packages/essential/Runtime/Variant/ISerializedVariantRW.cs @@ -1,6 +1,6 @@ namespace EntitiesBT.Variant { - public interface ISerializedVariantReaderAndWriter where T : unmanaged + public interface ISerializedVariantRW where T : unmanaged { bool IsLinked { get; } IVariantReaderAndWriter ReaderAndWriter { get; } diff --git a/Packages/essential/Runtime/Variant/ISerializedVariantReaderAndWriter.cs.meta b/Packages/essential/Runtime/Variant/ISerializedVariantRW.cs.meta similarity index 100% rename from Packages/essential/Runtime/Variant/ISerializedVariantReaderAndWriter.cs.meta rename to Packages/essential/Runtime/Variant/ISerializedVariantRW.cs.meta diff --git a/Packages/essential/Runtime/Variant/IVariant.cs b/Packages/essential/Runtime/Variant/IVariant.cs index 1e80cc15..5b5b1f88 100644 --- a/Packages/essential/Runtime/Variant/IVariant.cs +++ b/Packages/essential/Runtime/Variant/IVariant.cs @@ -1,5 +1,6 @@ using System; using EntitiesBT.Core; +using JetBrains.Annotations; using Unity.Entities; namespace EntitiesBT.Variant @@ -15,8 +16,20 @@ ref BlobBuilder builder ); } - public interface IVariant : IVariant where T : unmanaged {} - public interface IVariantReader : IVariant where T : unmanaged {} - public interface IVariantWriter : IVariant where T : unmanaged {} - public interface IVariantReaderAndWriter : IVariant where T : unmanaged {} + public interface IVariantReader : IVariant {} + public interface IVariantWriter : IVariant {} + public interface IVariantReaderAndWriter : IVariant {} + public interface IVariant : IVariant where T : unmanaged {} + public interface IVariantReader : IVariantReader, IVariant where T : unmanaged {} + public interface IVariantWriter : IVariantWriter, IVariant where T : unmanaged {} + public interface IVariantReaderAndWriter : IVariantReaderAndWriter, IVariant where T : unmanaged {} + + public static partial class VariantExtension + { + [CanBeNull] public static Type FindValueType([NotNull] this IVariant variant) + { + var type = variant.GetType(); + return type.GetInterface(typeof(IVariant).Name)?.GenericTypeArguments[0]; + } + } } diff --git a/Packages/essential/Runtime/Variant/LocalVariant.cs b/Packages/essential/Runtime/Variant/LocalVariant.cs index 2594b82a..d3b5b16d 100644 --- a/Packages/essential/Runtime/Variant/LocalVariant.cs +++ b/Packages/essential/Runtime/Variant/LocalVariant.cs @@ -2,7 +2,6 @@ using EntitiesBT.Core; using Unity.Entities; using UnityEngine; -using UnityEngine.Scripting; using static EntitiesBT.Core.Utilities; namespace EntitiesBT.Variant @@ -10,8 +9,11 @@ namespace EntitiesBT.Variant [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class LocalVariantAttribute : PropertyAttribute {} + [VariantClass(GUID)] public static class LocalVariant { + public const string GUID = "BF510555-7E38-49BB-BDC1-E4A85A174EEC"; + [Serializable] public class Any : IVariant where T : unmanaged { @@ -27,15 +29,21 @@ public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INo [Serializable] public class Reader : Any, IVariantReader where T : unmanaged {} [Serializable] public class ReaderAndWriter : Any, IVariantReaderAndWriter where T : unmanaged {} - public const string GUID = "BF510555-7E38-49BB-BDC1-E4A85A174EEC"; - - [Preserve, RefReaderMethod(GUID)] + [RefReaderMethod] private static ref T Read(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - return ref blobVariant.Value(); + return ref blobVariant.As(); + } + + [ReadWritePointerMethod] + private static unsafe IntPtr GetPointer(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + return new IntPtr(blobVariant.AsPointer()); } } } diff --git a/Packages/essential/Runtime/Variant/Registry.meta b/Packages/essential/Runtime/Variant/Registry.meta new file mode 100644 index 00000000..ab2aba1c --- /dev/null +++ b/Packages/essential/Runtime/Variant/Registry.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a731fc44256c4968a224f077b6941bb8 +timeCreated: 1627208029 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/Registry/CommonValueTypes.cs b/Packages/essential/Runtime/Variant/Registry/CommonValueTypes.cs new file mode 100644 index 00000000..6f8bc937 --- /dev/null +++ b/Packages/essential/Runtime/Variant/Registry/CommonValueTypes.cs @@ -0,0 +1,79 @@ +using EntitiesBT.Variant; +using Unity.Mathematics; + +[assembly: VariantValueType(typeof(byte), 0)] +[assembly: VariantValueType(typeof(short), 1)] +[assembly: VariantValueType(typeof(int), 2)] +[assembly: VariantValueType(typeof(long), 3)] +[assembly: VariantValueType(typeof(sbyte), 4)] +[assembly: VariantValueType(typeof(ushort), 5)] +[assembly: VariantValueType(typeof(uint), 6)] +[assembly: VariantValueType(typeof(ulong), 7)] +[assembly: VariantValueType(typeof(float), 8)] +[assembly: VariantValueType(typeof(double), 9)] +[assembly: VariantValueType(typeof(bool), 10)] +[assembly: VariantValueType(typeof(bool2), 20)] +[assembly: VariantValueType(typeof(bool2x2), 21)] +[assembly: VariantValueType(typeof(bool2x3), 22)] +[assembly: VariantValueType(typeof(bool2x4), 23)] +[assembly: VariantValueType(typeof(bool3), 24)] +[assembly: VariantValueType(typeof(bool3x2), 25)] +[assembly: VariantValueType(typeof(bool3x3), 26)] +[assembly: VariantValueType(typeof(bool3x4), 27)] +[assembly: VariantValueType(typeof(bool4), 28)] +[assembly: VariantValueType(typeof(bool4x2), 29)] +[assembly: VariantValueType(typeof(bool4x3), 30)] +[assembly: VariantValueType(typeof(bool4x4), 31)] +[assembly: VariantValueType(typeof(int2), 32)] +[assembly: VariantValueType(typeof(int2x2), 33)] +[assembly: VariantValueType(typeof(int2x3), 34)] +[assembly: VariantValueType(typeof(int2x4), 35)] +[assembly: VariantValueType(typeof(int3), 36)] +[assembly: VariantValueType(typeof(int3x2), 37)] +[assembly: VariantValueType(typeof(int3x3), 38)] +[assembly: VariantValueType(typeof(int3x4), 39)] +[assembly: VariantValueType(typeof(int4), 40)] +[assembly: VariantValueType(typeof(int4x2), 41)] +[assembly: VariantValueType(typeof(int4x3), 42)] +[assembly: VariantValueType(typeof(int4x4), 43)] +[assembly: VariantValueType(typeof(uint2), 44)] +[assembly: VariantValueType(typeof(uint2x2), 45)] +[assembly: VariantValueType(typeof(uint2x3), 46)] +[assembly: VariantValueType(typeof(uint2x4), 47)] +[assembly: VariantValueType(typeof(uint3), 48)] +[assembly: VariantValueType(typeof(uint3x2), 49)] +[assembly: VariantValueType(typeof(uint3x3), 50)] +[assembly: VariantValueType(typeof(uint3x4), 51)] +[assembly: VariantValueType(typeof(uint4), 52)] +[assembly: VariantValueType(typeof(uint4x2), 53)] +[assembly: VariantValueType(typeof(uint4x3), 54)] +[assembly: VariantValueType(typeof(uint4x4), 55)] +[assembly: VariantValueType(typeof(float2), 56)] +[assembly: VariantValueType(typeof(float2x2), 57)] +[assembly: VariantValueType(typeof(float2x3), 58)] +[assembly: VariantValueType(typeof(float2x4), 59)] +[assembly: VariantValueType(typeof(float3), 60)] +[assembly: VariantValueType(typeof(float3x2), 61)] +[assembly: VariantValueType(typeof(float3x3), 62)] +[assembly: VariantValueType(typeof(float3x4), 63)] +[assembly: VariantValueType(typeof(float4), 64)] +[assembly: VariantValueType(typeof(float4x2), 65)] +[assembly: VariantValueType(typeof(float4x3), 66)] +[assembly: VariantValueType(typeof(float4x4), 67)] +[assembly: VariantValueType(typeof(double2), 68)] +[assembly: VariantValueType(typeof(double2x2), 69)] +[assembly: VariantValueType(typeof(double2x3), 70)] +[assembly: VariantValueType(typeof(double2x4), 71)] +[assembly: VariantValueType(typeof(double3), 72)] +[assembly: VariantValueType(typeof(double3x2), 73)] +[assembly: VariantValueType(typeof(double3x3), 74)] +[assembly: VariantValueType(typeof(double3x4), 75)] +[assembly: VariantValueType(typeof(double4), 76)] +[assembly: VariantValueType(typeof(double4x2), 77)] +[assembly: VariantValueType(typeof(double4x3), 78)] +[assembly: VariantValueType(typeof(double4x4), 79)] +[assembly: VariantValueType(typeof(half), 80)] +[assembly: VariantValueType(typeof(half2), 81)] +[assembly: VariantValueType(typeof(half3), 82)] +[assembly: VariantValueType(typeof(half4), 83)] +[assembly: VariantValueType(typeof(quaternion), 84)] diff --git a/Packages/essential/Runtime/Variant/Registry/CommonValueTypes.cs.meta b/Packages/essential/Runtime/Variant/Registry/CommonValueTypes.cs.meta new file mode 100644 index 00000000..21f3d656 --- /dev/null +++ b/Packages/essential/Runtime/Variant/Registry/CommonValueTypes.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0e5484d864014bff8bd72853652661a2 +timeCreated: 1627208103 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/Registry/VariantValueTypeRegistry.cs b/Packages/essential/Runtime/Variant/Registry/VariantValueTypeRegistry.cs new file mode 100644 index 00000000..25dd2592 --- /dev/null +++ b/Packages/essential/Runtime/Variant/Registry/VariantValueTypeRegistry.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using static EntitiesBT.Core.Utilities; + +namespace EntitiesBT.Variant +{ + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public class VariantValueTypeAttribute : Attribute + { + public Type Type { get; } + public int Id { get; } + + public VariantValueTypeAttribute(Type type, string guid) + { + Type = type; + Id = GuidHashCode(guid); + } + + public VariantValueTypeAttribute(Type type, int id) + { + Type = type; + Id = id; + } + } + + public static class VariantValueTypeRegistry + { + private static readonly IReadOnlyDictionary _idTypeMap; + private static readonly IReadOnlyDictionary _typeIdMap; + + static VariantValueTypeRegistry() + { + var types = AppDomain.CurrentDomain.GetAssemblies() + .SelectMany(assembly => assembly.GetCustomAttributes()) + ; + + var idTypeMap = new Dictionary(); + var typeIdMap = new Dictionary(); + + foreach (var attribute in types) + { + idTypeMap.Add(attribute.Id, attribute.Type); + typeIdMap.Add(attribute.Type, attribute.Id); + } + + _idTypeMap = idTypeMap; + _typeIdMap = typeIdMap; + } + + public static IEnumerable GetAllTypes() => _typeIdMap.Keys; + + public static Type GetTypeById(int id) + { + _idTypeMap.TryGetValue(id, out var type); + return type; + } + + public static int GetIdByType(Type type) + { + return _typeIdMap.TryGetValue(type, out var id) ? id : throw new VariantValueTypeNotRegisteredException(type); + } + } + + [Serializable] + public class VariantValueTypeNotRegisteredException : Exception + { + public Type Type { get; } + + public VariantValueTypeNotRegisteredException(Type type) + : base($"{type.FullName} must be register into {nameof(VariantValueTypeRegistry)} by {nameof(VariantValueTypeAttribute)}") + { + Type = type; + } + } +} \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/Registry/VariantValueTypeRegistry.cs.meta b/Packages/essential/Runtime/Variant/Registry/VariantValueTypeRegistry.cs.meta new file mode 100644 index 00000000..bfabf582 --- /dev/null +++ b/Packages/essential/Runtime/Variant/Registry/VariantValueTypeRegistry.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 750438b6825a48e8bf7fc8622a05fa52 +timeCreated: 1627208075 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/SerializedVariant.cs b/Packages/essential/Runtime/Variant/SerializedVariant.cs new file mode 100644 index 00000000..0c7e7b72 --- /dev/null +++ b/Packages/essential/Runtime/Variant/SerializedVariant.cs @@ -0,0 +1,61 @@ +using System; +using EntitiesBT.Attributes; +using EntitiesBT.Core; +using Unity.Entities; + +namespace EntitiesBT.Variant +{ + [Serializable] + public class SerializedVariantRW : ISerializedVariantRW where T : unmanaged + { + [UnityEngine.SerializeField] + private bool _isLinked = true; + public bool IsLinked => _isLinked; + + [UnityEngine.SerializeReference] + [HideIf(nameof(_isLinked), false)] + [SerializeReferenceDrawer(TypeRestrictionBySiblingProperty = nameof(ReaderAndWriter))] + private object _readerAndWriter; + public IVariantReaderAndWriter ReaderAndWriter => (IVariantReaderAndWriter)_readerAndWriter; + + [UnityEngine.SerializeReference] + [HideIf(nameof(_isLinked))] + [SerializeReferenceDrawer(TypeRestrictionBySiblingProperty = nameof(Reader))] + private object _reader; + public IVariantReader Reader => (IVariantReader)_reader; + + [UnityEngine.SerializeReference] + [HideIf(nameof(_isLinked))] + [SerializeReferenceDrawer(TypeRestrictionBySiblingProperty = nameof(Writer))] + private object _writer; + public IVariantWriter Writer => (IVariantWriter)_writer; + } + + [Serializable] + public class SerializedVariantRO : IVariantReader where T : unmanaged + { + [UnityEngine.SerializeReference] + [SerializeReferenceDrawer(TypeRestrictionBySiblingProperty = nameof(Reader))] + private object _reader; + public IVariantReader Reader => (IVariantReader)_reader; + + public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INodeDataBuilder self, ITreeNode[] tree) + { + return Reader.Allocate(ref builder, ref blobVariant, self, tree); + } + } + + [Serializable] + public class SerializedVariantWO : IVariantWriter where T : unmanaged + { + [UnityEngine.SerializeReference] + [SerializeReferenceDrawer(TypeRestrictionBySiblingProperty = nameof(Writer))] + private object _writer; + public IVariantWriter Writer => (IVariantWriter)_writer; + + public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INodeDataBuilder self, ITreeNode[] tree) + { + return Writer.Allocate(ref builder, ref blobVariant, self, tree); + } + } +} \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/SerializedVariant.cs.meta b/Packages/essential/Runtime/Variant/SerializedVariant.cs.meta new file mode 100644 index 00000000..fc718713 --- /dev/null +++ b/Packages/essential/Runtime/Variant/SerializedVariant.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: aa82e71f91db43bd8cf00e42cd399ea6 +timeCreated: 1627202014 \ No newline at end of file diff --git a/Packages/essential/Runtime/Variant/Utilities.cs b/Packages/essential/Runtime/Variant/Utilities.cs index 862b8b93..0effd914 100644 --- a/Packages/essential/Runtime/Variant/Utilities.cs +++ b/Packages/essential/Runtime/Variant/Utilities.cs @@ -84,6 +84,11 @@ public static unsafe IntPtr Allocate(this BlobBuilder builder, ref BlobV return new IntPtr(ptr); } + public static IntPtr Allocate(this BlobBuilder builder, ref BlobVariantReadOnlyPtr blob, TValue value) where TValue : unmanaged + { + return builder.Allocate(ref blob.Value, value); + } + public static IntPtr Allocate( this IVariantReader property , ref BlobBuilder builder @@ -92,6 +97,14 @@ this IVariantReader property , [NotNull] ITreeNode[] tree ) where T : unmanaged => property.Allocate(ref builder, ref blobVariant.Value, self, tree); + public static IntPtr Allocate( + this IVariantReader property + , ref BlobBuilder builder + , ref BlobVariantReadOnlyPtr blobVariant + , [NotNull] INodeDataBuilder self + , [NotNull] ITreeNode[] tree + ) => property.Allocate(ref builder, ref blobVariant.Value, self, tree); + public static IntPtr Allocate( this IVariantWriter property , ref BlobBuilder builder @@ -117,7 +130,7 @@ this IVariantReaderAndWriter property } public static IntPtr Allocate( - this ISerializedVariantReaderAndWriter property + this ISerializedVariantRW property , ref BlobBuilder builder , ref BlobVariantReaderAndWriter blobVariant , [NotNull] INodeDataBuilder self diff --git a/Packages/essential/Runtime/Variant/VariantAttributes.cs b/Packages/essential/Runtime/Variant/VariantAttributes.cs new file mode 100644 index 00000000..f963da81 --- /dev/null +++ b/Packages/essential/Runtime/Variant/VariantAttributes.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using EntitiesBT.Core; +using JetBrains.Annotations; +using Unity.Entities; + +namespace EntitiesBT.Variant +{ + public class ReaderMethodAttribute : RegisterDelegateMethodAttribute + { + public delegate TResult Delegate(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TResult : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + ; + public ReaderMethodAttribute() : base(typeof(Delegate<,,>)) {} + } + + public class RefReaderMethodAttribute : RegisterDelegateMethodAttribute + { + public delegate ref TResult Delegate(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TResult : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + ; + public RefReaderMethodAttribute() : base(typeof(Delegate<,,>)) {} + } + + public class WriterMethodAttribute : RegisterDelegateMethodAttribute + { + public delegate void Delegate(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb, T value) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + ; + public WriterMethodAttribute() : base(typeof(Delegate<,,>)) {} + } + + public class ReadOnlyPointerMethodAttribute : RegisterDelegateMethodAttribute + { + public delegate IntPtr Delegate(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + ; + public ReadOnlyPointerMethodAttribute() : base(typeof(Delegate<,>)) {} + } + + public class ReadWritePointerMethodAttribute : RegisterDelegateMethodAttribute + { + public delegate IntPtr Delegate(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + ; + public ReadWritePointerMethodAttribute() : base(typeof(Delegate<,>)) {} + } + + public class AccessorMethodAttribute : RegisterDelegateMethodAttribute + { + public delegate IEnumerable Delegate(ref BlobVariant variant); + public AccessorMethodAttribute() : base(typeof(Delegate)) {} + } + + public class VariantClassAttribute : RegisterDelegateClassAttribute + { + public VariantClassAttribute([NotNull] string guid) : base(guid) {} + } +} diff --git a/Packages/essential/Runtime/Variant/VariantRegisters.cs.meta b/Packages/essential/Runtime/Variant/VariantAttributes.cs.meta similarity index 100% rename from Packages/essential/Runtime/Variant/VariantRegisters.cs.meta rename to Packages/essential/Runtime/Variant/VariantAttributes.cs.meta diff --git a/Packages/essential/Runtime/Variant/VariantRegisters.cs b/Packages/essential/Runtime/Variant/VariantRegisters.cs deleted file mode 100644 index 6be08930..00000000 --- a/Packages/essential/Runtime/Variant/VariantRegisters.cs +++ /dev/null @@ -1,254 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using EntitiesBT.Core; -using Unity.Entities; -using UnityEngine.Assertions; -using static EntitiesBT.Core.Utilities; - -namespace EntitiesBT.Variant -{ - public class MethodIdAttribute : Attribute - { - internal readonly int ID; - public MethodIdAttribute(string guid) => ID = GuidHashCode(guid); - } - - [AttributeUsage(AttributeTargets.Method)] - public class ReaderMethodAttribute : MethodIdAttribute - { - public ReaderMethodAttribute(string guid) : base(guid) {} - } - - [AttributeUsage(AttributeTargets.Method)] - public class RefReaderMethodAttribute : MethodIdAttribute - { - public RefReaderMethodAttribute(string guid) : base(guid) {} - } - - [AttributeUsage(AttributeTargets.Method)] - public class WriterMethodAttribute : MethodIdAttribute - { - public WriterMethodAttribute(string guid) : base(guid) {} - } - - [AttributeUsage(AttributeTargets.Method)] - public class AccessorMethodAttribute : MethodIdAttribute - { - public AccessorMethodAttribute(string guid) : base(guid) {} - } - - internal static class VariantRegisters - { - internal delegate IEnumerable GetComponentAccessFunc(ref BlobVariant variant); - internal static readonly IReadOnlyDictionary READERS; - internal static readonly IReadOnlyDictionary REF_READERS; - internal static readonly IReadOnlyDictionary WRITERS; - internal static readonly IReadOnlyDictionary ACCESSORS; - public static GetComponentAccessFunc GetComponentAccess(int entryId) - { - return ACCESSORS.TryGetValue(entryId, out var func) ? func : GetComponentAccessDefault; - } - - private static IEnumerable GetComponentAccessDefault(ref BlobVariant _) => Enumerable.Empty(); - - static VariantRegisters() - { - var readers = new Dictionary(); - var refReaders = new Dictionary(); - var writers = new Dictionary(); - var accessors = new Dictionary(); - foreach (var (methodInfo, attribute) in - from type in BEHAVIOR_TREE_ASSEMBLY_TYPES.Value - from methodInfo in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) - from attribute in methodInfo.GetCustomAttributes() - select (methodInfo, attribute) - ) - { - switch (attribute) - { - case ReaderMethodAttribute _: - ValidateReaderMethod(methodInfo, isRef: false); - readers.Add(attribute.ID, methodInfo); - break; - case RefReaderMethodAttribute _: - ValidateReaderMethod(methodInfo, isRef: true); - refReaders.Add(attribute.ID, methodInfo); - break; - case WriterMethodAttribute _: - ValidateWriterMethod(methodInfo); - writers.Add(attribute.ID, methodInfo); - break; - case AccessorMethodAttribute _: - ValidateAccessorMethod(methodInfo); - accessors.Add(attribute.ID, (GetComponentAccessFunc)methodInfo.CreateDelegate(typeof(GetComponentAccessFunc))); - break; - default: - throw new NotImplementedException(); - } - } - READERS = new ReadOnlyDictionary(readers); - REF_READERS = new ReadOnlyDictionary(refReaders); - WRITERS = new ReadOnlyDictionary(writers); - ACCESSORS = new ReadOnlyDictionary(accessors); - } - - static void ValidateAccessorMethod(MethodInfo methodInfo) - { - // static IEnumerable GetDynamicAccess(ref BlobVariant blobVariant) - var methodMessage = $"{methodInfo.DeclaringType.FullName}.{methodInfo.Name}"; - Assert.IsFalse(methodInfo.IsGenericMethod, methodMessage); - - Assert.AreEqual(typeof(IEnumerable), methodInfo.ReturnType, methodMessage); - - var parameters = methodInfo.GetParameters(); - Assert.AreEqual(1, parameters.Length, methodMessage); - Assert.AreEqual(typeof(BlobVariant), parameters[0].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[0].ParameterType.IsByRef, methodMessage); - } - - static void ValidateWriterMethod(MethodInfo methodInfo) - { - // static void WriteFunc(ref BlobVariant variant, int nodeIndex, ref TNodeBlob blob, ref TBlackboard bb, T value) - - var methodMessage = $"{methodInfo.DeclaringType.FullName}.{methodInfo.Name}"; - Assert.IsTrue(methodInfo.IsGenericMethod, methodMessage); - - var genericArguments = methodInfo.GetGenericArguments(); - Assert.AreEqual(3, genericArguments.Length, methodMessage); - - Assert.AreEqual(typeof(void), methodInfo.ReturnType, methodMessage); - - var parameters = methodInfo.GetParameters(); - Assert.AreEqual(5, parameters.Length, methodMessage); - Assert.AreEqual(typeof(BlobVariant), parameters[0].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[0].ParameterType.IsByRef, methodMessage); - Assert.AreEqual(typeof(int), parameters[1].ParameterType, methodMessage); - Assert.AreEqual(genericArguments[1], parameters[2].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[2].ParameterType.IsByRef, methodMessage); - Assert.AreEqual(genericArguments[2], parameters[3].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[3].ParameterType.IsByRef, methodMessage); - Assert.AreEqual(genericArguments[0], parameters[4].ParameterType, methodMessage); - Assert.IsFalse(parameters[4].ParameterType.IsByRef, methodMessage); - } - - static void ValidateReaderMethod(MethodInfo methodInfo, bool isRef) - { - // static ref T Read(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) - - var methodMessage = $"{methodInfo.DeclaringType.FullName}.{methodInfo.Name}"; - Assert.IsTrue(methodInfo.IsGenericMethod, methodMessage); - - var genericArguments = methodInfo.GetGenericArguments(); - Assert.AreEqual(3, genericArguments.Length, methodMessage); - - var returnType = methodInfo.ReturnType; - Assert.AreEqual(isRef, returnType.IsByRef, methodMessage); - if (returnType.IsByRef) returnType = returnType.GetElementType(); - Assert.AreEqual(genericArguments[0], returnType, methodMessage); - - var parameters = methodInfo.GetParameters(); - Assert.AreEqual(4, parameters.Length, methodMessage); - Assert.AreEqual(typeof(BlobVariant), parameters[0].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[0].ParameterType.IsByRef, methodMessage); - Assert.AreEqual(typeof(int), parameters[1].ParameterType, methodMessage); - Assert.AreEqual(genericArguments[1], parameters[2].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[2].ParameterType.IsByRef, methodMessage); - Assert.AreEqual(genericArguments[2], parameters[3].ParameterType.GetElementType(), methodMessage); - Assert.IsTrue(parameters[3].ParameterType.IsByRef, methodMessage); - } - } - - public static class VariantRegisters where T : struct - { - private static IReadOnlyDictionary MakeRegisterDictionary( - IReadOnlyDictionary methodInfoMap - ) - where TDelegate : System.Delegate - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - var map = new Dictionary(methodInfoMap.Count * 3); - var types = new [] {typeof(T), typeof(TNodeBlob), typeof(TBlackboard)}; - foreach (var keyValue in methodInfoMap) - { - var func = (TDelegate)keyValue.Value - .MakeGenericMethod(types) - .CreateDelegate(typeof(TDelegate)) - ; - map[keyValue.Key] = func; - - } - return new ReadOnlyDictionary(map); - } - - public delegate T ReadFunc(ref BlobVariant variant, int nodeIndex, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - ; - - public delegate ref T ReadRefFunc(ref BlobVariant variant, int nodeIndex, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - ; - - public static ReadFunc GetReader(int entryId) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - => ReaderRegisters.READERS[entryId]; - - public static bool TryGetReader(int entryId, out ReadFunc value) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - => ReaderRegisters.READERS.TryGetValue(entryId, out value); - - public static ReadRefFunc GetRefReader(int entryId) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - => RefReaderRegisters.READERS[entryId]; - - // optimize: convert method info into delegate to increase performance on calling. - private static class ReaderRegisters - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - public static readonly IReadOnlyDictionary> READERS = - MakeRegisterDictionary, TNodeBlob, TBlackboard>(VariantRegisters.READERS); - } - - // optimize: convert method info into delegate to increase performance on calling. - private static class RefReaderRegisters - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - public static readonly IReadOnlyDictionary> READERS = - MakeRegisterDictionary, TNodeBlob, TBlackboard>(VariantRegisters.REF_READERS); - } - - public delegate void WriteFunc(ref BlobVariant variant, int nodeIndex, ref TNodeBlob blob, ref TBlackboard bb, T value) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - ; - - public static WriteFunc GetWriter(int entryId) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - => WriterRegisters.WRITERS[entryId]; - - public static bool TryGetWriter(int entryId, out WriteFunc writer) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - => WriterRegisters.WRITERS.TryGetValue(entryId, out writer); - - // optimize: convert writer method info into delegate to increase performance on calling. - private static class WriterRegisters - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - public static readonly IReadOnlyDictionary> WRITERS = - MakeRegisterDictionary, TNodeBlob, TBlackboard>(VariantRegisters.WRITERS); - } - } -} diff --git a/Packages/essential/package.json b/Packages/essential/package.json index 29fa197d..e044ae3f 100644 --- a/Packages/essential/package.json +++ b/Packages/essential/package.json @@ -1,11 +1,11 @@ { "name": "com.quabug.entities-bt.essential", "description": "Behavior Tree for Unity Entities - Essential", - "version": "1.1.3", + "version": "1.2.0", "unity": "2020.2", "displayName": "EntitiesBT - Essential", "dependencies": { "com.unity.entities": "0.14.0-preview.19", - "com.quabug.entities-bt.codegen": "1.0.2" + "com.quabug.entities-bt.codegen": "1.2.0" } } diff --git a/Packages/manifest.json b/Packages/manifest.json index e3e06085..9bcedc5f 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -4,7 +4,7 @@ "com.unity.dots.editor": "0.11.0-preview.3", "com.unity.graphtools.foundation": "0.4.0-preview.1", "com.unity.ide.rider": "3.0.3", - "com.unity.ide.visualstudio": "2.0.7", + "com.unity.ide.visualstudio": "2.0.9", "com.unity.ide.vscode": "1.2.3", "com.unity.nuget.newtonsoft-json": "2.0.0", "com.unity.rendering.hybrid": "0.10.0-preview.21", diff --git a/Packages/packages-lock.json b/Packages/packages-lock.json index 42209eaf..94a21e04 100644 --- a/Packages/packages-lock.json +++ b/Packages/packages-lock.json @@ -5,8 +5,7 @@ "depth": 0, "source": "embedded", "dependencies": { - "com.quabug.entities-bt.essential": "1.0.1", - "com.quabug.entities-bt.variable.scriptable-object": "1.0.1" + "com.quabug.entities-bt.essential": "1.2.0" } }, "com.quabug.entities-bt.builder.odin": { @@ -14,7 +13,7 @@ "depth": 0, "source": "embedded", "dependencies": { - "com.quabug.entities-bt.builder.component": "1.0.2" + "com.quabug.entities-bt.builder.component": "1.2.0" } }, "com.quabug.entities-bt.builder.visual": { @@ -38,7 +37,7 @@ "depth": 0, "source": "embedded", "dependencies": { - "com.quabug.entities-bt.essential": "1.0.0" + "com.quabug.entities-bt.essential": "1.2.0" } }, "com.quabug.entities-bt.essential": { @@ -47,7 +46,7 @@ "source": "embedded", "dependencies": { "com.unity.entities": "0.14.0-preview.19", - "com.quabug.entities-bt.codegen": "1.0.2" + "com.quabug.entities-bt.codegen": "1.2.0" } }, "com.quabug.entities-bt.samples": { @@ -57,9 +56,10 @@ "dependencies": { "com.unity.inputsystem": "1.0.0", "com.unity.rendering.hybrid": "0.8.0-preview.19", - "com.quabug.entities-bt.builder.component": "1.0.0", - "com.quabug.entities-bt.debug.component-viewer": "1.0.0", - "com.quabug.entities-bt.essential": "1.1.0" + "com.quabug.entities-bt.builder.component": "1.2.0", + "com.quabug.entities-bt.debug.component-viewer": "1.2.0", + "com.quabug.entities-bt.essential": "1.2.0", + "com.quabug.entities-bt.variant-expression": "0.2.0" } }, "com.quabug.entities-bt.variable.scriptable-object": { @@ -67,7 +67,15 @@ "depth": 0, "source": "embedded", "dependencies": { - "com.quabug.entities-bt.essential": "1.0.1" + "com.quabug.entities-bt.essential": "1.2.0" + } + }, + "com.quabug.entities-bt.variant-expression": { + "version": "file:variant.expression", + "depth": 0, + "source": "embedded", + "dependencies": { + "com.quabug.entities-bt.essential": "1.2.0" } }, "com.unity.burst": { @@ -154,7 +162,7 @@ "url": "https://packages.unity.com" }, "com.unity.ide.visualstudio": { - "version": "2.0.7", + "version": "2.0.9", "depth": 0, "source": "registry", "dependencies": { @@ -279,7 +287,7 @@ "url": "https://packages.unity.com" }, "com.unity.test-framework": { - "version": "1.1.22", + "version": "1.1.27", "depth": 1, "source": "registry", "dependencies": { diff --git a/Packages/samples/Runtime/Entity/EntityMove.cs b/Packages/samples/Runtime/Entity/EntityMove.cs index 6644b0d4..2a51cde8 100644 --- a/Packages/samples/Runtime/Entity/EntityMove.cs +++ b/Packages/samples/Runtime/Entity/EntityMove.cs @@ -35,12 +35,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref translation.Value += Velocity * deltaTime.Value; return NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } public class EntityMoveDebugView : BTDebugView {} diff --git a/Packages/samples/Runtime/Entity/EntityRotate.cs b/Packages/samples/Runtime/Entity/EntityRotate.cs index 63cb7d49..e95798f3 100644 --- a/Packages/samples/Runtime/Entity/EntityRotate.cs +++ b/Packages/samples/Runtime/Entity/EntityRotate.cs @@ -41,12 +41,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref ); return NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } public class EntityRotateDebugView : BTDebugView {} diff --git a/Packages/samples/Runtime/Entity/EntityTranslate.cs b/Packages/samples/Runtime/Entity/EntityTranslate.cs index f2e3ed9a..a0794cd4 100644 --- a/Packages/samples/Runtime/Entity/EntityTranslate.cs +++ b/Packages/samples/Runtime/Entity/EntityTranslate.cs @@ -33,12 +33,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref translation.Value = Position; return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } public class EntityTranslateDebugView : BTDebugView {} diff --git a/Packages/samples/Runtime/Entity/IsEntityPositionInBox.cs b/Packages/samples/Runtime/Entity/IsEntityPositionInBox.cs index fd65c7bc..506cef77 100644 --- a/Packages/samples/Runtime/Entity/IsEntityPositionInBox.cs +++ b/Packages/samples/Runtime/Entity/IsEntityPositionInBox.cs @@ -32,12 +32,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref var translation = bb.GetData(); return Bounds.Contains(translation.Value) ? NodeState.Success : NodeState.Failure; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } public class IsEntityPositionInBoxNodeDebugView : BTDebugView {} diff --git a/Packages/samples/Runtime/InputSystem/BTCheckInputPhase.cs b/Packages/samples/Runtime/InputSystem/BTCheckInputPhase.cs index 468bcda3..2dbac7c6 100644 --- a/Packages/samples/Runtime/InputSystem/BTCheckInputPhase.cs +++ b/Packages/samples/Runtime/InputSystem/BTCheckInputPhase.cs @@ -29,11 +29,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref var phase = GetInputActionPhase(index, ref blob, ref bb); return phase == Phase ? NodeState.Success : NodeState.Failure; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } \ No newline at end of file diff --git a/Packages/samples/Runtime/InputSystem/BTInputAimPosition.cs b/Packages/samples/Runtime/InputSystem/BTInputAimPosition.cs index 1af8625f..b480c7dc 100644 --- a/Packages/samples/Runtime/InputSystem/BTInputAimPosition.cs +++ b/Packages/samples/Runtime/InputSystem/BTInputAimPosition.cs @@ -31,12 +31,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref bb.GetDataRef().Value = inputValue.Value; return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } public class InputAimPositionDebugView : BTDebugView diff --git a/Packages/samples/Runtime/InputSystem/BTInputEnableDisable.cs b/Packages/samples/Runtime/InputSystem/BTInputEnableDisable.cs index a48f108f..314e5d19 100644 --- a/Packages/samples/Runtime/InputSystem/BTInputEnableDisable.cs +++ b/Packages/samples/Runtime/InputSystem/BTInputEnableDisable.cs @@ -28,12 +28,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref bb.GetObject().Value.Enable(); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } [BehaviorNode("03D959C3-D9F6-478D-A5E5-DCA4ADBD6C3D"), StructLayout(LayoutKind.Explicit)] @@ -46,11 +40,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref bb.GetObject().Value.Enable(); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Runtime/InputSystem/BTInputLook.cs b/Packages/samples/Runtime/InputSystem/BTInputLook.cs index a307e06f..49efa9cc 100644 --- a/Packages/samples/Runtime/InputSystem/BTInputLook.cs +++ b/Packages/samples/Runtime/InputSystem/BTInputLook.cs @@ -34,11 +34,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref Output.Write(index, ref blob, ref bb, inputValue.Value); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Runtime/InputSystem/BTInputMove.cs b/Packages/samples/Runtime/InputSystem/BTInputMove.cs index a1d600b1..3d4b00ed 100644 --- a/Packages/samples/Runtime/InputSystem/BTInputMove.cs +++ b/Packages/samples/Runtime/InputSystem/BTInputMove.cs @@ -1,7 +1,5 @@ using System; -using EntitiesBT.Attributes; using EntitiesBT.Core; -using EntitiesBT.Sample; using EntitiesBT.Variant; using Unity.Entities; using Unity.Mathematics; @@ -12,7 +10,7 @@ namespace EntitiesBT.Extensions.InputSystem { public class BTInputMove : BTInputActionBase { - public float2SerializedReaderAndWriterVariant Output; + public SerializedVariantRW Output; protected override unsafe void Build(ref InputMoveNode data, BlobBuilder builder, ITreeNode[] tree) { @@ -36,11 +34,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref Output.Write(index, ref blob, ref bb, inputValue.Value); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Runtime/InputSystem/BTIsInputActionTriggered.cs b/Packages/samples/Runtime/InputSystem/BTIsInputActionTriggered.cs index c568095b..62a5c393 100644 --- a/Packages/samples/Runtime/InputSystem/BTIsInputActionTriggered.cs +++ b/Packages/samples/Runtime/InputSystem/BTIsInputActionTriggered.cs @@ -18,11 +18,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref var isTriggered = IsInputActionTriggered(index, ref blob, ref bb); return isTriggered ? NodeState.Success : NodeState.Failure; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Runtime/InputSystem/BTReadInputVector2.cs b/Packages/samples/Runtime/InputSystem/BTReadInputVector2.cs index b3d9bcb6..76ac4404 100644 --- a/Packages/samples/Runtime/InputSystem/BTReadInputVector2.cs +++ b/Packages/samples/Runtime/InputSystem/BTReadInputVector2.cs @@ -19,10 +19,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard => ReadInputValueNode.Tick(index, ref blob, ref bb); - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - {} } } diff --git a/Packages/samples/Runtime/UnityMovement/BTCharacterSimpleMove.cs b/Packages/samples/Runtime/UnityMovement/BTCharacterSimpleMove.cs index 822c2f80..68772c4a 100644 --- a/Packages/samples/Runtime/UnityMovement/BTCharacterSimpleMove.cs +++ b/Packages/samples/Runtime/UnityMovement/BTCharacterSimpleMove.cs @@ -1,7 +1,5 @@ -using EntitiesBT.Attributes; using EntitiesBT.Components; using EntitiesBT.Core; -using EntitiesBT.Sample; using EntitiesBT.Variant; using Unity.Entities; using Unity.Mathematics; @@ -13,8 +11,7 @@ public class BTCharacterSimpleMove : BTNode { public bool IsLocal; - [SerializeReference, SerializeReferenceButton] - public float3VariantReader VelocityPropertyReader; + public SerializedVariantRO VelocityPropertyReader; protected override unsafe void Build(ref CharacterSimpleMoveNode data, BlobBuilder builder, ITreeNode[] tree) { @@ -39,11 +36,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref controller.SimpleMove(IsLocal ? controller.transform.localToWorldMatrix.MultiplyVector(velocity) : velocity); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Runtime/UnityMovement/BTSetTransformRotation.cs b/Packages/samples/Runtime/UnityMovement/BTSetTransformRotation.cs index 4844c8ad..a894ac62 100644 --- a/Packages/samples/Runtime/UnityMovement/BTSetTransformRotation.cs +++ b/Packages/samples/Runtime/UnityMovement/BTSetTransformRotation.cs @@ -1,7 +1,6 @@ using EntitiesBT.Attributes; using EntitiesBT.Components; using EntitiesBT.Core; -using EntitiesBT.Sample; using EntitiesBT.Variant; using Unity.Entities; using Unity.Mathematics; @@ -11,8 +10,7 @@ namespace EntitiesBT.Extensions.UnityMovement { public class BTSetTransformRotation : BTNode { - [SerializeReference, SerializeReferenceButton] - public quaternionVariantReader RotationReader; + public SerializedVariantRO RotationReader; protected override unsafe void Build(ref SetTransformRotationNode data, BlobBuilder builder, ITreeNode[] tree) { @@ -35,11 +33,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref transform.rotation = rotation; return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Runtime/Variable/VariableProperties.cs b/Packages/samples/Runtime/Variable/VariableProperties.cs deleted file mode 100644 index 89dc9659..00000000 --- a/Packages/samples/Runtime/Variable/VariableProperties.cs +++ /dev/null @@ -1,252 +0,0 @@ -namespace EntitiesBT.Sample -{ - -public interface Int32VariantReader : EntitiesBT.Variant.IVariantReader { } -public class Int32NodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, Int32VariantReader { } -public class Int32ComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, Int32VariantReader { } -public class Int32LocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, Int32VariantReader { } -public class Int32ScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, Int32VariantReader { } - -public interface Int32VariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class Int32NodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, Int32VariantWriter { } -public class Int32ComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, Int32VariantWriter { } - -public interface Int32VariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class Int32NodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, Int32VariantReaderAndWriter { } -public class Int32ComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, Int32VariantReaderAndWriter { } -public class Int32LocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, Int32VariantReaderAndWriter { } - - -[System.Serializable] -public class Int32SerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private Int32VariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private Int32VariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private Int32VariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} -public interface Int64VariantReader : EntitiesBT.Variant.IVariantReader { } -public class Int64NodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, Int64VariantReader { } -public class Int64ComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, Int64VariantReader { } -public class Int64LocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, Int64VariantReader { } -public class Int64ScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, Int64VariantReader { } - -public interface Int64VariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class Int64NodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, Int64VariantWriter { } -public class Int64ComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, Int64VariantWriter { } - -public interface Int64VariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class Int64NodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, Int64VariantReaderAndWriter { } -public class Int64ComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, Int64VariantReaderAndWriter { } -public class Int64LocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, Int64VariantReaderAndWriter { } - - -[System.Serializable] -public class Int64SerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private Int64VariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private Int64VariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private Int64VariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} -public interface SingleVariantReader : EntitiesBT.Variant.IVariantReader { } -public class SingleNodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, SingleVariantReader { } -public class SingleComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, SingleVariantReader { } -public class SingleLocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, SingleVariantReader { } -public class SingleScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, SingleVariantReader { } - -public interface SingleVariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class SingleNodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, SingleVariantWriter { } -public class SingleComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, SingleVariantWriter { } - -public interface SingleVariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class SingleNodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, SingleVariantReaderAndWriter { } -public class SingleComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, SingleVariantReaderAndWriter { } -public class SingleLocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, SingleVariantReaderAndWriter { } - - -[System.Serializable] -public class SingleSerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private SingleVariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private SingleVariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private SingleVariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} -public interface float2VariantReader : EntitiesBT.Variant.IVariantReader { } -public class float2NodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, float2VariantReader { } -public class float2ComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, float2VariantReader { } -public class float2LocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, float2VariantReader { } -public class float2ScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, float2VariantReader { } - -public interface float2VariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class float2NodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, float2VariantWriter { } -public class float2ComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, float2VariantWriter { } - -public interface float2VariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class float2NodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, float2VariantReaderAndWriter { } -public class float2ComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, float2VariantReaderAndWriter { } -public class float2LocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, float2VariantReaderAndWriter { } - - -[System.Serializable] -public class float2SerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private float2VariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private float2VariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private float2VariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} -public interface float3VariantReader : EntitiesBT.Variant.IVariantReader { } -public class float3NodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, float3VariantReader { } -public class float3ComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, float3VariantReader { } -public class float3LocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, float3VariantReader { } -public class float3ScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, float3VariantReader { } - -public interface float3VariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class float3NodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, float3VariantWriter { } -public class float3ComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, float3VariantWriter { } - -public interface float3VariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class float3NodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, float3VariantReaderAndWriter { } -public class float3ComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, float3VariantReaderAndWriter { } -public class float3LocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, float3VariantReaderAndWriter { } - - -[System.Serializable] -public class float3SerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private float3VariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private float3VariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private float3VariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} -public interface quaternionVariantReader : EntitiesBT.Variant.IVariantReader { } -public class quaternionNodeVariantReader : EntitiesBT.Variant.NodeVariant.Reader, quaternionVariantReader { } -public class quaternionComponentVariantReader : EntitiesBT.Variant.ComponentVariant.Reader, quaternionVariantReader { } -public class quaternionLocalVariantReader : EntitiesBT.Variant.LocalVariant.Reader, quaternionVariantReader { } -public class quaternionScriptableObjectVariantReader : EntitiesBT.Variant.ScriptableObjectVariant.Reader, quaternionVariantReader { } - -public interface quaternionVariantWriter : EntitiesBT.Variant.IVariantWriter { } -public class quaternionNodeVariantWriter : EntitiesBT.Variant.NodeVariant.Writer, quaternionVariantWriter { } -public class quaternionComponentVariantWriter : EntitiesBT.Variant.ComponentVariant.Writer, quaternionVariantWriter { } - -public interface quaternionVariantReaderAndWriter : EntitiesBT.Variant.IVariantReaderAndWriter { } -public class quaternionNodeVariantReaderAndWriter : EntitiesBT.Variant.NodeVariant.ReaderAndWriter, quaternionVariantReaderAndWriter { } -public class quaternionComponentVariantReaderAndWriter : EntitiesBT.Variant.ComponentVariant.ReaderAndWriter, quaternionVariantReaderAndWriter { } -public class quaternionLocalVariantReaderAndWriter : EntitiesBT.Variant.LocalVariant.ReaderAndWriter, quaternionVariantReaderAndWriter { } - - -[System.Serializable] -public class quaternionSerializedReaderAndWriterVariant : EntitiesBT.Variant.ISerializedVariantReaderAndWriter -{ - [UnityEngine.SerializeField] - private bool _isLinked = true; - public bool IsLinked => _isLinked; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked), false)] - [EntitiesBT.Attributes.SerializeReferenceButton] - private quaternionVariantReaderAndWriter _readerAndWriter; - public EntitiesBT.Variant.IVariantReaderAndWriter ReaderAndWriter => _readerAndWriter; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private quaternionVariantReader _reader; - public EntitiesBT.Variant.IVariantReader Reader => _reader; - - [UnityEngine.SerializeReference] - [EntitiesBT.Attributes.HideIf(nameof(_isLinked))] - [EntitiesBT.Attributes.SerializeReferenceButton] - private quaternionVariantWriter _writer; - public EntitiesBT.Variant.IVariantWriter Writer => _writer; -} - -} - diff --git a/Packages/samples/Runtime/Variable/VariableProperties.cs.meta b/Packages/samples/Runtime/Variable/VariableProperties.cs.meta deleted file mode 100644 index 6e1d66c5..00000000 --- a/Packages/samples/Runtime/Variable/VariableProperties.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 50faea9d890b34ff7a08eb6f939025df -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/samples/Runtime/Variable/VariablesGeneratorSetting.asset b/Packages/samples/Runtime/Variable/VariablesGeneratorSetting.asset deleted file mode 100644 index 77787d9b..00000000 --- a/Packages/samples/Runtime/Variable/VariablesGeneratorSetting.asset +++ /dev/null @@ -1,26 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!114 &11400000 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 0} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: f90e02d7d6784323bd6696496977dabc, type: 3} - m_Name: VariablesGeneratorSetting - m_EditorClassIdentifier: - Types: - - Unity.Mathematics.float2 - - Unity.Mathematics.float3 - - System.Single - - System.Int32 - - System.Int64 - - Unity.Mathematics.quaternion - - UnityEngine.Quaternion - Filename: VariableProperties - Namespace: EntitiesBT.Sample - Assembly: {fileID: 5897886265953266890, guid: 4285913d8daed4d6fb1061c793376ad4, - type: 3} diff --git a/Packages/samples/Runtime/Variable/VariablesGeneratorSetting.asset.meta b/Packages/samples/Runtime/Variable/VariablesGeneratorSetting.asset.meta deleted file mode 100644 index a6e1493f..00000000 --- a/Packages/samples/Runtime/Variable/VariablesGeneratorSetting.asset.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: d9ca5d4928634e2e9168d993c8610ded -timeCreated: 1583256114 \ No newline at end of file diff --git a/Packages/samples/Samples~/Animator/AnimatorSample.unity b/Packages/samples/Samples~/Animator/AnimatorSample.unity index d5b74d58..cc7216fe 100644 --- a/Packages/samples/Samples~/Animator/AnimatorSample.unity +++ b/Packages/samples/Samples~/Animator/AnimatorSample.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 705507994} - m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_IndirectSpecularColor: {r: 0.44657874, g: 0.49641258, b: 0.5748171, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -668,7 +668,8 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: 2 00000001: @@ -810,9 +811,10 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - Value: 2 + Value: 3 00000001: type: {class: , ns: , asm: } --- !u!1 &1365720264 @@ -1131,7 +1133,8 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: 1 00000001: diff --git a/Packages/samples/Samples~/Animator/SetAnimatorTrigger.cs b/Packages/samples/Samples~/Animator/SetAnimatorTrigger.cs index 5188d5ea..6c96a05e 100644 --- a/Packages/samples/Samples~/Animator/SetAnimatorTrigger.cs +++ b/Packages/samples/Samples~/Animator/SetAnimatorTrigger.cs @@ -30,11 +30,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref animator.SetTrigger(Value); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Samples~/Entity/EntitySample.unity b/Packages/samples/Samples~/Entity/EntitySample.unity index b0eed709..1f567953 100644 --- a/Packages/samples/Samples~/Entity/EntitySample.unity +++ b/Packages/samples/Samples~/Entity/EntitySample.unity @@ -178,7 +178,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 0.5 00000001: @@ -239,7 +239,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -572,7 +572,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -633,7 +633,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -755,7 +755,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -1144,7 +1144,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -1344,7 +1344,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -1579,7 +1579,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -1742,7 +1742,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -1803,7 +1803,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 2 00000001: @@ -2095,7 +2095,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -2156,7 +2156,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -2399,7 +2399,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -2578,7 +2578,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 2 00000001: @@ -3062,7 +3062,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -3283,7 +3283,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -3344,7 +3344,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -3944,7 +3944,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -4439,7 +4439,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -4757,7 +4757,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -5246,7 +5246,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -5429,7 +5429,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 2 00000001: @@ -5490,7 +5490,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -6237,7 +6237,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -6569,7 +6569,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -6718,7 +6718,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 2 00000001: @@ -7093,7 +7093,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -7202,7 +7202,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -7454,7 +7454,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -7731,7 +7731,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: @@ -7896,7 +7896,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 1 00000001: diff --git a/Packages/samples/Samples~/Entity/bt-entity-move.bytes b/Packages/samples/Samples~/Entity/bt-entity-move.bytes index 176b176e..04319645 100644 Binary files a/Packages/samples/Samples~/Entity/bt-entity-move.bytes and b/Packages/samples/Samples~/Entity/bt-entity-move.bytes differ diff --git a/Packages/samples/Samples~/Entity/bt-entity-move.prefab b/Packages/samples/Samples~/Entity/bt-entity-move.prefab index edc92215..bd156a42 100644 --- a/Packages/samples/Samples~/Entity/bt-entity-move.prefab +++ b/Packages/samples/Samples~/Entity/bt-entity-move.prefab @@ -56,9 +56,10 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - Value: 1 + Value: 2 00000001: type: {class: , ns: , asm: } --- !u!1 &7154796705611245648 @@ -117,9 +118,10 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - Value: 1 + Value: 2 00000001: type: {class: , ns: , asm: } --- !u!1 &7154796705739208521 @@ -222,9 +224,10 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - Value: 1 + Value: 2 00000001: type: {class: , ns: , asm: } --- !u!1 &7154796705978280124 @@ -375,7 +378,8 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: 1 00000001: @@ -584,9 +588,10 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - Value: 1 + Value: 2 00000001: type: {class: , ns: , asm: } --- !u!1 &7154796706839227953 @@ -781,8 +786,9 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - Value: 1 + Value: 2 00000001: type: {class: , ns: , asm: } diff --git a/Packages/samples/Samples~/Entity/bt-entity-rotate.bytes b/Packages/samples/Samples~/Entity/bt-entity-rotate.bytes index e0f806db..52d2e5db 100644 Binary files a/Packages/samples/Samples~/Entity/bt-entity-rotate.bytes and b/Packages/samples/Samples~/Entity/bt-entity-rotate.bytes differ diff --git a/Packages/samples/Samples~/Visual.meta b/Packages/samples/Samples~/Expression.meta similarity index 77% rename from Packages/samples/Samples~/Visual.meta rename to Packages/samples/Samples~/Expression.meta index a0ecf83c..c8181a60 100644 --- a/Packages/samples/Samples~/Visual.meta +++ b/Packages/samples/Samples~/Expression.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ad2febf9543f65049ade4b057752e7f8 +guid: 62a12b17aecf0a54d8b2ca22fb01f636 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Packages/samples/Samples~/Expression/BTPrint.cs b/Packages/samples/Samples~/Expression/BTPrint.cs new file mode 100644 index 00000000..5cb61b9d --- /dev/null +++ b/Packages/samples/Samples~/Expression/BTPrint.cs @@ -0,0 +1,34 @@ +using EntitiesBT.Core; +using Unity.Entities; +using System; +using EntitiesBT.Variant; +using Unity.Mathematics; +using UnityEngine; + +namespace EntitiesBT.Components.Odin +{ + public class BTPrint : BTNode + { + public SerializedVariantRO Value; + + protected override void Build(ref PrintNode data, BlobBuilder builder, ITreeNode[] tree) + { + Value.Allocate(ref builder, ref data.Value, this, tree); + } + } + + [Serializable] + [BehaviorNode("30E1D8D2-356D-422A-AF98-1CB734C3C63D")] + public struct PrintNode : INodeData + { + public BlobVariantReader Value; + + public NodeState Tick(int index, ref TNodeBlob blob, ref TBlackboard bb) + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + Debug.Log(Value.Read(index, ref blob, ref bb)); + return NodeState.Success; + } + } +} \ No newline at end of file diff --git a/Packages/builder.component/Runtime/Variant/SingleVariantWriter.cs.meta b/Packages/samples/Samples~/Expression/BTPrint.cs.meta similarity index 83% rename from Packages/builder.component/Runtime/Variant/SingleVariantWriter.cs.meta rename to Packages/samples/Samples~/Expression/BTPrint.cs.meta index 82ecf85b..3e4bd64e 100644 --- a/Packages/builder.component/Runtime/Variant/SingleVariantWriter.cs.meta +++ b/Packages/samples/Samples~/Expression/BTPrint.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9f0f9363db13c4045aeddb282a78c4e7 +guid: bbbe6bf307a5abe4e9b9f9a925279349 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Packages/samples/Samples~/Expression/EntitiesBT.Samples.Expression.asmdef b/Packages/samples/Samples~/Expression/EntitiesBT.Samples.Expression.asmdef new file mode 100644 index 00000000..6fcbd476 --- /dev/null +++ b/Packages/samples/Samples~/Expression/EntitiesBT.Samples.Expression.asmdef @@ -0,0 +1,20 @@ +{ + "name": "EntitiesBT.Samples.Expression", + "rootNamespace": "", + "references": [ + "GUID:c7babe7561eb244059259745ef27b866", + "GUID:531c7a9266080bf4ba6b3998d6aa0137", + "GUID:734d92eba21c94caba915361bd5ac177", + "GUID:d8b63aba1907145bea998dd612889d6b", + "GUID:6679f77e90ec1d540ab279146d203dbb" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Packages/codegen/Tests~/EntitiesBT.CodeGen.Tests.asmdef.meta b/Packages/samples/Samples~/Expression/EntitiesBT.Samples.Expression.asmdef.meta similarity index 76% rename from Packages/codegen/Tests~/EntitiesBT.CodeGen.Tests.asmdef.meta rename to Packages/samples/Samples~/Expression/EntitiesBT.Samples.Expression.asmdef.meta index ca664041..295770da 100644 --- a/Packages/codegen/Tests~/EntitiesBT.CodeGen.Tests.asmdef.meta +++ b/Packages/samples/Samples~/Expression/EntitiesBT.Samples.Expression.asmdef.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e3fee1400c7c8ac49a1d2ddffda4f640 +guid: 17e81534352c6d64393711649f703e04 AssemblyDefinitionImporter: externalObjects: {} userData: diff --git a/Packages/samples/Samples~/Expression/SampleExpression.unity b/Packages/samples/Samples~/Expression/SampleExpression.unity new file mode 100644 index 00000000..6222b7b9 --- /dev/null +++ b/Packages/samples/Samples~/Expression/SampleExpression.unity @@ -0,0 +1,733 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0.3731193, g: 0.38073996, b: 0.35872698, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 12 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 + m_LightingDataAsset: {fileID: 0} + m_LightingSettings: {fileID: 0} +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + maxJobWorkers: 0 + preserveTilesOutsideBounds: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &51284400 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 51284401} + - component: {fileID: 51284403} + - component: {fileID: 51284402} + m_Layer: 0 + m_Name: BTPrint + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &51284401 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 51284400} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 883457543} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &51284402 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 51284400} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: bbbe6bf307a5abe4e9b9f9a925279349, type: 3} + m_Name: + m_EditorClassIdentifier: + Value: + _reader: + id: 0 + references: + version: 1 + 00000000: + type: {class: /float2ExpressionVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + _expression: x * y + _sources: + - Value: + id: 1 + Name: x + - Value: + id: 2 + Name: y + 00000001: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 3.4 + y: 2.1 + 00000002: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 2.1 + y: 5.2 +--- !u!114 &51284403 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 51284400} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2ac9e180769c4e749aa9d96d2f996aee, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &220197280 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 220197281} + - component: {fileID: 220197283} + - component: {fileID: 220197282} + m_Layer: 0 + m_Name: BTPrint + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &220197281 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220197280} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1122494587} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &220197282 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220197280} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: bbbe6bf307a5abe4e9b9f9a925279349, type: 3} + m_Name: + m_EditorClassIdentifier: + Value: + _reader: + id: 0 + references: + version: 1 + 00000000: + type: {class: /float2ExpressionVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + _expression: (x+y)*2+1 + _sources: + - Value: + id: 1 + Name: x + - Value: + id: 2 + Name: y + 00000001: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 3.4 + y: 2.1 + 00000002: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 2.1 + y: 5.2 +--- !u!114 &220197283 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 220197280} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2ac9e180769c4e749aa9d96d2f996aee, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &883457541 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 883457543} + - component: {fileID: 883457542} + - component: {fileID: 883457544} + m_Layer: 0 + m_Name: BTSequence + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &883457542 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 883457541} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: ce483d001ae6449ea17ef9d3fbfdb5d8, type: 3} + m_Name: + m_EditorClassIdentifier: + _recursiveResetStatesBeforeTick: 0 +--- !u!4 &883457543 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 883457541} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 51284401} + - {fileID: 2076864907} + m_Father: {fileID: 1766680688} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &883457544 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 883457541} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2ac9e180769c4e749aa9d96d2f996aee, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1122494585 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1122494587} + - component: {fileID: 1122494586} + - component: {fileID: 1122494588} + m_Layer: 0 + m_Name: BTSequence + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1122494586 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1122494585} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: ce483d001ae6449ea17ef9d3fbfdb5d8, type: 3} + m_Name: + m_EditorClassIdentifier: + _recursiveResetStatesBeforeTick: 0 +--- !u!4 &1122494587 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1122494585} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 220197281} + - {fileID: 1541864080} + m_Father: {fileID: 1706943926} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1122494588 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1122494585} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2ac9e180769c4e749aa9d96d2f996aee, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1541864079 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1541864080} + - component: {fileID: 1541864082} + - component: {fileID: 1541864081} + m_Layer: 0 + m_Name: BTPrint.1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &1541864080 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1541864079} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1122494587} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1541864081 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1541864079} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: bbbe6bf307a5abe4e9b9f9a925279349, type: 3} + m_Name: + m_EditorClassIdentifier: + Value: + _reader: + id: 0 + references: + version: 1 + 00000000: + type: {class: /float2ExpressionVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + _expression: x - y * 4 - 3 + _sources: + - Value: + id: 1 + Name: x + - Value: + id: 2 + Name: y + 00000001: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 3.4 + y: 2.1 + 00000002: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 2.1 + y: 5.2 +--- !u!114 &1541864082 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1541864079} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2ac9e180769c4e749aa9d96d2f996aee, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!1 &1706943923 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1706943926} + - component: {fileID: 1706943925} + - component: {fileID: 1706943924} + m_Layer: 0 + m_Name: GameObject + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1706943924 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1706943923} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 535cc0336ffb441b9aa72e1fe9000207, type: 3} + m_Name: + m_EditorClassIdentifier: + _source: + id: 0 + _thread: 0 + _autoCreateTypes: 2147483647 + _order: 0 + _debugName: + references: + version: 1 + 00000000: + type: {class: BehaviorTreeSourceGameObject, ns: EntitiesBT.Components, asm: EntitiesBT.Runtime} + data: + Root: {fileID: 1122494586} + AutoDestroy: 1 +--- !u!114 &1706943925 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1706943923} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: ea7d7495833204790ba1d3a8755397f8, type: 3} + m_Name: + m_EditorClassIdentifier: + ConversionMode: 0 +--- !u!4 &1706943926 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1706943923} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1122494587} + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1766680684 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1766680688} + - component: {fileID: 1766680687} + - component: {fileID: 1766680685} + m_Layer: 0 + m_Name: GameObject.1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1766680685 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1766680684} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 535cc0336ffb441b9aa72e1fe9000207, type: 3} + m_Name: + m_EditorClassIdentifier: + _source: + id: 0 + _thread: 0 + _autoCreateTypes: 2147483647 + _order: 0 + _debugName: + references: + version: 1 + 00000000: + type: {class: BehaviorTreeSourceGameObject, ns: EntitiesBT.Components, asm: EntitiesBT.Runtime} + data: + Root: {fileID: 883457542} + AutoDestroy: 1 +--- !u!114 &1766680687 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1766680684} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: ea7d7495833204790ba1d3a8755397f8, type: 3} + m_Name: + m_EditorClassIdentifier: + ConversionMode: 0 +--- !u!4 &1766680688 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1766680684} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 883457543} + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &2076864906 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 2076864907} + - component: {fileID: 2076864909} + - component: {fileID: 2076864908} + m_Layer: 0 + m_Name: BTPrint.1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!4 &2076864907 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2076864906} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 883457543} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &2076864908 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2076864906} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: bbbe6bf307a5abe4e9b9f9a925279349, type: 3} + m_Name: + m_EditorClassIdentifier: + Value: + _reader: + id: 0 + references: + version: 1 + 00000000: + type: {class: /float2ExpressionVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + _expression: (x +1) * (y - 3) + _sources: + - Value: + id: 1 + Name: x + - Value: + id: 2 + Name: y + 00000001: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 3.4 + y: 2.1 + 00000002: + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} + data: + Value: + x: 2.1 + y: 5.2 +--- !u!114 &2076864909 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 2076864906} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 2ac9e180769c4e749aa9d96d2f996aee, type: 3} + m_Name: + m_EditorClassIdentifier: diff --git a/Assets/_.meta b/Packages/samples/Samples~/Expression/SampleExpression.unity.meta similarity index 74% rename from Assets/_.meta rename to Packages/samples/Samples~/Expression/SampleExpression.unity.meta index 84132336..1a7ac9bd 100644 --- a/Assets/_.meta +++ b/Packages/samples/Samples~/Expression/SampleExpression.unity.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ef915f20bc2034c1cb7df53d4ac76392 +guid: b6a242e0521a16045abe2502e2b9dbc5 DefaultImporter: externalObjects: {} userData: diff --git a/Packages/samples/Samples~/GameObjectWithoutEntity/GameObjectSample.unity b/Packages/samples/Samples~/GameObjectWithoutEntity/GameObjectSample.unity index f286a707..96e71067 100644 --- a/Packages/samples/Samples~/GameObjectWithoutEntity/GameObjectSample.unity +++ b/Packages/samples/Samples~/GameObjectWithoutEntity/GameObjectSample.unity @@ -317,7 +317,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 2 00000001: @@ -692,7 +692,7 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Variant, asm: EntitiesBT.Runtime} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen,asm: Assembly-CSharp} data: Value: 2 00000001: diff --git a/Packages/samples/Samples~/GameObjectWithoutEntity/TransformMove.cs b/Packages/samples/Samples~/GameObjectWithoutEntity/TransformMove.cs index 73b39790..756cebfb 100644 --- a/Packages/samples/Samples~/GameObjectWithoutEntity/TransformMove.cs +++ b/Packages/samples/Samples~/GameObjectWithoutEntity/TransformMove.cs @@ -33,11 +33,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref transform.position += deltaMove; return NodeState.Running; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToCharacterVelocity.cs b/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToCharacterVelocity.cs index 9dfa93da..962eaaef 100644 --- a/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToCharacterVelocity.cs +++ b/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToCharacterVelocity.cs @@ -1,24 +1,18 @@ using EntitiesBT.Attributes; using EntitiesBT.Components; using EntitiesBT.Core; -using EntitiesBT.Sample; using EntitiesBT.Variant; using Unity.Entities; using Unity.Mathematics; using UnityEngine; -using SingleVariantReader = EntitiesBT.Sample.SingleVariantReader; namespace EntitiesBT.Samples { public class BTInputMoveToCharacterVelocity : BTNode { - [SerializeReference, SerializeReferenceButton] - public SingleVariantReader SpeedPropertyReader; - - [SerializeReference, SerializeReferenceButton] - public float2VariantReader InputMovePropertyReader; - - public float3SerializedReaderAndWriterVariant OutputVelocityPropertyWriter; + public SerializedVariantRO SpeedPropertyReader; + public SerializedVariantRO InputMovePropertyReader; + public SerializedVariantRW OutputVelocityPropertyWriter; protected override unsafe void Build(ref InputMoveToCharacterVelocityNode data, BlobBuilder builder, ITreeNode[] tree) { @@ -45,11 +39,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref OutputVelocity.Write(index, ref blob, ref bb, direction * speed); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToRotation.cs b/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToRotation.cs index 8145ea4f..b9bee88e 100644 --- a/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToRotation.cs +++ b/Packages/samples/Samples~/InputAndCharacterController/BTInputMoveToRotation.cs @@ -1,7 +1,6 @@ using EntitiesBT.Attributes; using EntitiesBT.Components; using EntitiesBT.Core; -using EntitiesBT.Sample; using EntitiesBT.Variant; using Unity.Entities; using Unity.Mathematics; @@ -11,10 +10,8 @@ namespace EntitiesBT.Samples { public class BTInputMoveToRotation : BTNode { - [SerializeReference, SerializeReferenceButton] - public float2VariantReader InputMovePropertyReader; - - public quaternionSerializedReaderAndWriterVariant OutputDirectionPropertyWriter; + public SerializedVariantRO InputMovePropertyReader; + public SerializedVariantRW OutputDirectionPropertyWriter; protected override unsafe void Build(ref InputMoveToRotationNode data, BlobBuilder builder, ITreeNode[] tree) { @@ -40,11 +37,5 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref OutputDirection.Write(index, ref blob, ref bb, direction); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } } } diff --git a/Packages/samples/Samples~/InputAndCharacterController/InputAndCharacterControllerSample.unity b/Packages/samples/Samples~/InputAndCharacterController/InputAndCharacterControllerSample.unity index 6d5e200e..848b577f 100644 --- a/Packages/samples/Samples~/InputAndCharacterController/InputAndCharacterControllerSample.unity +++ b/Packages/samples/Samples~/InputAndCharacterController/InputAndCharacterControllerSample.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_IndirectSpecularColor: {r: 0.44657874, g: 0.49641258, b: 0.5748171, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -167,9 +167,11 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: SpeedPropertyReader: - id: 0 + _reader: + id: 0 InputMovePropertyReader: - id: 1 + _reader: + id: 1 OutputVelocityPropertyWriter: _isLinked: 1 _readerAndWriter: @@ -181,16 +183,19 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: 2 00000001: - type: {class: float2NodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float2NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 1332110029} ValueFieldName: Output 00000002: - type: {class: float3LocalVariantReaderAndWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float3LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: x: 0 @@ -623,11 +628,13 @@ MonoBehaviour: m_EditorClassIdentifier: IsLocal: 0 VelocityPropertyReader: - id: 0 + _reader: + id: 0 references: version: 1 00000000: - type: {class: float3NodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float3NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 775125229} ValueFieldName: OutputVelocity @@ -758,9 +765,11 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: SpeedPropertyReader: - id: 0 + _reader: + id: 0 InputMovePropertyReader: - id: 1 + _reader: + id: 1 OutputVelocityPropertyWriter: _isLinked: 1 _readerAndWriter: @@ -772,16 +781,19 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: SingleLocalVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: 4 00000001: - type: {class: float2NodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float2NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 1332110029} ValueFieldName: Output 00000002: - type: {class: float3LocalVariantReaderAndWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float3LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: x: 0 @@ -879,11 +891,13 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: RotationReader: - id: 0 + _reader: + id: 0 references: version: 1 00000000: - type: {class: quaternionNodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /quaternionNodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 1160618947} ValueFieldName: OutputDirection @@ -1106,7 +1120,8 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: InputMovePropertyReader: - id: 0 + _reader: + id: 0 OutputDirectionPropertyWriter: _isLinked: 1 _readerAndWriter: @@ -1118,13 +1133,14 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: float2NodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float2NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 1332110029} ValueFieldName: Output 00000001: - type: {class: quaternionLocalVariantReaderAndWriter, ns: EntitiesBT.Sample, - asm: EntitiesBT.Sample.Variable} + type: {class: /quaternionLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: value: @@ -1367,7 +1383,8 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: float2LocalVariantReaderAndWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float2LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: x: 0 @@ -1466,16 +1483,18 @@ MonoBehaviour: m_EditorClassIdentifier: IsLocal: 1 VelocityPropertyReader: - id: 0 + _reader: + id: 0 references: version: 1 00000000: - type: {class: float3LocalVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float3LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: x: 0 y: 0 - z: 8 + z: 10 --- !u!1 &1454846012 GameObject: m_ObjectHideFlags: 0 @@ -1843,11 +1862,13 @@ MonoBehaviour: m_EditorClassIdentifier: IsLocal: 0 VelocityPropertyReader: - id: 0 + _reader: + id: 0 references: version: 1 00000000: - type: {class: float3NodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /float3NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 2282878} ValueFieldName: OutputVelocity diff --git a/Packages/samples/Runtime/Variable.meta b/Packages/samples/Samples~/Odin.meta similarity index 77% rename from Packages/samples/Runtime/Variable.meta rename to Packages/samples/Samples~/Odin.meta index 66a3b106..e951015a 100644 --- a/Packages/samples/Runtime/Variable.meta +++ b/Packages/samples/Samples~/Odin.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 163550939ad6a4aff89431745e705373 +guid: fc578504ebc00bf4d9eb1e3fe36d0f56 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Packages/builder.odin/Sample~/EntitiesBT.Odin.Sample.asmdef b/Packages/samples/Samples~/Odin/EntitiesBT.Odin.Sample.asmdef similarity index 100% rename from Packages/builder.odin/Sample~/EntitiesBT.Odin.Sample.asmdef rename to Packages/samples/Samples~/Odin/EntitiesBT.Odin.Sample.asmdef diff --git a/Packages/builder.odin/Sample~/EntitiesBT.Odin.Sample.asmdef.meta b/Packages/samples/Samples~/Odin/EntitiesBT.Odin.Sample.asmdef.meta similarity index 100% rename from Packages/builder.odin/Sample~/EntitiesBT.Odin.Sample.asmdef.meta rename to Packages/samples/Samples~/Odin/EntitiesBT.Odin.Sample.asmdef.meta diff --git a/Packages/builder.odin/Sample~/EntityMove.cs b/Packages/samples/Samples~/Odin/EntityMove.cs similarity index 100% rename from Packages/builder.odin/Sample~/EntityMove.cs rename to Packages/samples/Samples~/Odin/EntityMove.cs diff --git a/Packages/builder.odin/Sample~/EntityMove.cs.meta b/Packages/samples/Samples~/Odin/EntityMove.cs.meta similarity index 100% rename from Packages/builder.odin/Sample~/EntityMove.cs.meta rename to Packages/samples/Samples~/Odin/EntityMove.cs.meta diff --git a/Packages/builder.odin/Sample~/OdinSample.unity b/Packages/samples/Samples~/Odin/OdinSample.unity similarity index 100% rename from Packages/builder.odin/Sample~/OdinSample.unity rename to Packages/samples/Samples~/Odin/OdinSample.unity diff --git a/Packages/builder.odin/Sample~/OdinSample.unity.meta b/Packages/samples/Samples~/Odin/OdinSample.unity.meta similarity index 100% rename from Packages/builder.odin/Sample~/OdinSample.unity.meta rename to Packages/samples/Samples~/Odin/OdinSample.unity.meta diff --git a/Packages/samples/Samples~/Variable/BTVariantTest.cs b/Packages/samples/Samples~/Variable/BTVariantTest.cs index e2f80dd9..82c17778 100644 --- a/Packages/samples/Samples~/Variable/BTVariantTest.cs +++ b/Packages/samples/Samples~/Variable/BTVariantTest.cs @@ -1,3 +1,4 @@ +using System; using EntitiesBT.Attributes; using EntitiesBT.Components; using EntitiesBT.Core; @@ -5,19 +6,18 @@ using EntitiesBT.Entities; using EntitiesBT.Variant; using Unity.Entities; -using UnityEngine; namespace EntitiesBT.Sample { public class BTVariantTest : BTNode { - [SerializeReference, SerializeReferenceButton] public Int64VariantReader LongReader; + public SerializedVariantRO LongReader; public string String; public int[] IntArray; - [SerializeReference, SerializeReferenceButton] public Int64VariantWriter LongWriter; - [SerializeReference, SerializeReferenceButton] public SingleVariantReader SingleReader; + public SerializedVariantWO LongWriter; + public SerializedVariantRO SingleReader; public long LongValue; - public SingleSerializedReaderAndWriterVariant SingleReaderAndWriter; + public SerializedVariantRW SingleReaderAndWriter; protected override unsafe void Build(ref VariablesTestNode data, BlobBuilder builder, ITreeNode[] tree) { @@ -49,11 +49,6 @@ public NodeState Tick(int index, ref TNodeBlob blob, ref LongWriter.Write(index, ref blob, ref bb, (int)SingleReader.Read(index, ref blob, ref bb)); return NodeState.Success; } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - {} } [BehaviorTreeDebugView(typeof(VariablesTestNode))] diff --git a/Packages/samples/Samples~/Variable/ConfigVariable.cs b/Packages/samples/Samples~/Variable/ConfigVariable.cs index e363612f..2e915705 100644 --- a/Packages/samples/Samples~/Variable/ConfigVariable.cs +++ b/Packages/samples/Samples~/Variable/ConfigVariable.cs @@ -9,7 +9,7 @@ public class ConfigVariable : ScriptableObject public int IntValue; public float FloatValue; public float AnotherFloatValue; - + [field: SerializeField] public float FloatProperty { get; set; } } diff --git a/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variable.Ref.asmref b/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variable.Ref.asmref deleted file mode 100644 index 7a931148..00000000 --- a/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variable.Ref.asmref +++ /dev/null @@ -1,3 +0,0 @@ -{ - "reference": "GUID:4285913d8daed4d6fb1061c793376ad4" -} \ No newline at end of file diff --git a/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variable.Ref.asmref.meta b/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variable.Ref.asmref.meta deleted file mode 100644 index ed3f0995..00000000 --- a/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variable.Ref.asmref.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: a9d1749e19d01460d95f2534f6820569 -AssemblyDefinitionReferenceImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variant.asmdef b/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variant.asmdef new file mode 100644 index 00000000..860f9dcc --- /dev/null +++ b/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variant.asmdef @@ -0,0 +1,19 @@ +{ + "name": "EntitiesBT.Sample.Variant", + "rootNamespace": "", + "references": [ + "GUID:abe4851e67df59644865a60dae54a845", + "GUID:c7babe7561eb244059259745ef27b866", + "GUID:734d92eba21c94caba915361bd5ac177", + "GUID:d8b63aba1907145bea998dd612889d6b" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Packages/samples/Runtime/Variable/EntitiesBT.Sample.Variable.asmdef.meta b/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variant.asmdef.meta similarity index 76% rename from Packages/samples/Runtime/Variable/EntitiesBT.Sample.Variable.asmdef.meta rename to Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variant.asmdef.meta index c71450f1..bcf0656f 100644 --- a/Packages/samples/Runtime/Variable/EntitiesBT.Sample.Variable.asmdef.meta +++ b/Packages/samples/Samples~/Variable/EntitiesBT.Sample.Variant.asmdef.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4285913d8daed4d6fb1061c793376ad4 +guid: 72b8a38d1f175904fb366feca059252d AssemblyDefinitionImporter: externalObjects: {} userData: diff --git a/Packages/samples/Samples~/Variable/VariableSample.unity b/Packages/samples/Samples~/Variable/VariableSample.unity index 7b7e0b51..cca8eb14 100644 --- a/Packages/samples/Samples~/Variable/VariableSample.unity +++ b/Packages/samples/Samples~/Variable/VariableSample.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_IndirectSpecularColor: {r: 0.3731193, g: 0.38073996, b: 0.35872698, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -153,13 +153,16 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: LongReader: - id: 0 + _reader: + id: 0 String: aabbbcccc IntArray: a00c0000020000002000000004000000b3150000 LongWriter: - id: 1 + _writer: + id: 1 SingleReader: - id: 2 + _reader: + id: 2 LongValue: 23333 SingleReaderAndWriter: _isLinked: 1 @@ -172,21 +175,24 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: Int64ComponentVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /Int64LocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - ComponentValueName: EntitiesBT.Sample.ComponentVariableData.LongValue + Value: 111 00000001: - type: {class: Int64ComponentVariantWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /Int64NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - ComponentValueName: EntitiesBT.Sample.ComponentVariableData.LongValue + NodeObject: {fileID: 327906297} + ValueFieldName: LongReader 00000002: - type: {class: SingleScriptableObjectVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - ScriptableObject: {fileID: 11400000, guid: cee16ca8c8b594efb867f66c8d699937, - type: 2} - ScriptableObjectValueName: FloatValue + Value: 43243 00000003: - type: {class: SingleLocalVariantReaderAndWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleLocalVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: Value: 123 00000004: @@ -432,13 +438,16 @@ MonoBehaviour: m_Name: m_EditorClassIdentifier: LongReader: - id: 0 + _reader: + id: 0 String: 43242131 IntArray: LongWriter: - id: 1 + _writer: + id: 1 SingleReader: - id: 2 + _reader: + id: 2 LongValue: 44332 SingleReaderAndWriter: _isLinked: 0 @@ -451,28 +460,33 @@ MonoBehaviour: references: version: 1 00000000: - type: {class: Int64NodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /Int64NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - NodeObject: {fileID: 327906297} + NodeObject: {fileID: 1667038669} ValueFieldName: Long 00000001: - type: {class: Int64NodeVariantWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /Int64NodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - NodeObject: {fileID: 327906297} + NodeObject: {fileID: 1667038669} ValueFieldName: Long 00000002: - type: {class: SingleComponentVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleComponentVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: - ComponentValueName: EntitiesBT.Sample.ComponentVariableData.InputValue + ComponentValueName: EntitiesBT.Sample.SampleTimeDelayData.TwoSeconds 00000003: type: {class: , ns: , asm: } 00000004: - type: {class: SingleNodeVariantReader, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleNodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 327906297} ValueFieldName: SingleReader 00000005: - type: {class: SingleNodeVariantWriter, ns: EntitiesBT.Sample, asm: EntitiesBT.Sample.Variable} + type: {class: /SingleNodeVariant, ns: EntitiesBT.Variant.CodeGen, + asm: Assembly-CSharp} data: NodeObject: {fileID: 327906297} ValueFieldName: SingleReader diff --git a/Packages/samples/Samples~/Visual/VisualEntityRotate.cs b/Packages/samples/Samples~/Visual/VisualEntityRotate.cs deleted file mode 100644 index 7b7ddbe0..00000000 --- a/Packages/samples/Samples~/Visual/VisualEntityRotate.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using EntitiesBT.Core; -using EntitiesBT.Entities; -using EntitiesBT.Variant; -using Runtime; -using Unity.Entities; -using Unity.Mathematics; -using Unity.Transforms; -using ValueType = Runtime.ValueType; - -namespace EntitiesBT.Builder.Visual -{ - [NodeSearcherItem("EntitiesBT/Node/EntityRotate")] - [Serializable] - public struct VisualEntityRotate : IVisualBuilderNode - { - [PortDescription("")] public InputTriggerPort Parent; - [PortDescription(ValueType.Float3)] public InputDataPort Axis; - [PortDescription(ValueType.Float)] public InputDataPort RadianPerSecond; - - public INodeDataBuilder GetBuilder(GraphInstance instance, GraphDefinition definition) - { - var @this = this; - return new VisualBuilder(BuildImpl); - - unsafe void BuildImpl(BlobBuilder blobBuilder, ref VisualEntityRotateNode data, INodeDataBuilder self, ITreeNode[] builders) - { - @this.Axis.ToVariantReader(instance, definition) - .Allocate(ref blobBuilder, ref data.Axis, self, builders) - ; - @this.RadianPerSecond.ToVariantReader(instance, definition) - .Allocate(ref blobBuilder, ref data.RadianPerSecond, self, builders) - ; - } - } - - public Execution Execute(TCtx ctx, InputTriggerPort port) where TCtx : IGraphInstance => Execution.Done; - } - - [Serializable] - [BehaviorNode("6A4E0F98-7305-439B-A68C-CA42AAC51C34")] - public struct VisualEntityRotateNode : INodeData - { - public BlobVariantReader Axis; - public BlobVariantReader RadianPerSecond; - - public NodeState Tick(int index, ref TNodeBlob blob, ref TBlackboard bb) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - ref var rotation = ref bb.GetDataRef(); - var deltaTime = bb.GetData(); - var axis = Axis.Read(index, ref blob, ref bb); - var radianPerSecond = RadianPerSecond.Read(index, ref blob, ref bb); - rotation.Value = math.mul( - math.normalize(rotation.Value) - , quaternion.AxisAngle(axis, radianPerSecond * deltaTime.Value) - ); - return NodeState.Running; - } - - public void Reset(int index, ref TNodeBlob blob, ref TBlackboard blackboard) - where TNodeBlob : struct, INodeBlob - where TBlackboard : struct, IBlackboard - { - } - } -} \ No newline at end of file diff --git a/Packages/samples/Samples~/Visual/VisualEntityRotate.cs.meta b/Packages/samples/Samples~/Visual/VisualEntityRotate.cs.meta deleted file mode 100644 index 19e93f00..00000000 --- a/Packages/samples/Samples~/Visual/VisualEntityRotate.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2b5442195ce36474d8438b3a43c7819f -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Packages/samples/Tests~/Editor/EntitiesBT.Tests.Editor.asmdef b/Packages/samples/Tests~/Editor/EntitiesBT.Tests.Editor.asmdef index cee60195..fc53bd99 100644 --- a/Packages/samples/Tests~/Editor/EntitiesBT.Tests.Editor.asmdef +++ b/Packages/samples/Tests~/Editor/EntitiesBT.Tests.Editor.asmdef @@ -1,5 +1,6 @@ { "name": "EntitiesBT.Tests.Editor", + "rootNamespace": "", "references": [ "GUID:0acc523941302664db1f4e527237feb3", "GUID:27619889b8ba8c24980f49ee34dbb44a", @@ -7,16 +8,23 @@ "GUID:734d92eba21c94caba915361bd5ac177", "GUID:0db6da4b0e13948bab4bf99649766bad", "GUID:c7babe7561eb244059259745ef27b866", - "GUID:d3630359ae08047918d5cd6cddd51767" + "GUID:6679f77e90ec1d540ab279146d203dbb", + "GUID:f49b79f7e0a9b4b63a97d15e26787406", + "GUID:ce5f967ea6c735344b367065891c4afb" ], "includePlatforms": [ "Editor" ], "excludePlatforms": [], "allowUnsafeCode": true, - "overrideReferences": false, + "overrideReferences": true, "precompiledReferences": [ - "nunit.framework.dll" + "nunit.framework.dll", + "Moq.dll", + "Mono.Cecil.dll", + "Mono.Cecil.Mdb.dll", + "Mono.Cecil.Pdb.dll", + "Mono.Cecil.Rocks.dll" ], "autoReferenced": false, "defineConstraints": [], diff --git a/Packages/samples/Tests~/Editor/TestBlobBuilder.cs b/Packages/samples/Tests~/Editor/TestBlobBuilder.cs new file mode 100644 index 00000000..da88425e --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestBlobBuilder.cs @@ -0,0 +1,58 @@ +using EntitiesBT.Components; +using EntitiesBT.Variant; +using NUnit.Framework; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Entities; + +namespace EntitiesBT.Test +{ + public class TestBlobBuilder + { + struct Data + { + public BlobString StringValue; + public BlobArray IntArrayValue; + public BlobArray StringArrayValue; + public int IntValue; + } + + [Test] + public void should_build_complex_data_into_blob() + { + var builder = new BlobBuilder(Allocator.Temp); + try + { + ref var variant = ref builder.ConstructRoot(); + variant.VariantId = 1; + ref var blobPtr = ref UnsafeUtility.As>(ref variant.MetaDataOffsetPtr); + ref var data = ref builder.Allocate(ref blobPtr); + builder.AllocateString(ref data.StringValue, "abc"); + data.IntValue = 2; + builder.AllocateArray(ref data.IntArrayValue, new[] { 7, 8, 9}); + var stringArray = builder.Allocate(ref data.StringArrayValue, 2); + builder.AllocateString(ref stringArray[0], "123"); + builder.AllocateString(ref stringArray[1], "456"); + + using var persistent = builder.CreateBlobAssetReference(Allocator.Persistent); + var value = persistent.Value; + ref var valueData = ref persistent.Value.As(); + + Assert.That(value.VariantId, Is.EqualTo(1)); + Assert.That(valueData.IntValue, Is.EqualTo(2)); + Assert.That(valueData.StringValue.ToString(), Is.EqualTo("abc")); + + Assert.That(valueData.IntArrayValue.Length, Is.EqualTo(3)); + Assert.That(valueData.IntArrayValue.ToArray(), Is.EquivalentTo(new [] { 7, 8, 9 })); + + Assert.That(valueData.StringArrayValue.Length, Is.EqualTo(2)); + Assert.That(valueData.StringArrayValue[0].ToString(), Is.EqualTo("123")); + Assert.That(valueData.StringArrayValue[1].ToString(), Is.EqualTo("456")); + } + finally + { + builder.Dispose(); + } + } + } +} \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestBlobBuilder.cs.meta b/Packages/samples/Tests~/Editor/TestBlobBuilder.cs.meta new file mode 100644 index 00000000..fe8514ea --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestBlobBuilder.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2b53c80f02444bacae15ee84c6d3d581 +timeCreated: 1626943696 \ No newline at end of file diff --git a/Packages/codegen/Tests~/TestCecilExtension.cs b/Packages/samples/Tests~/Editor/TestCecilExtension.cs similarity index 99% rename from Packages/codegen/Tests~/TestCecilExtension.cs rename to Packages/samples/Tests~/Editor/TestCecilExtension.cs index 3bd93754..b134b738 100644 --- a/Packages/codegen/Tests~/TestCecilExtension.cs +++ b/Packages/samples/Tests~/Editor/TestCecilExtension.cs @@ -5,7 +5,7 @@ using Mono.Cecil; using NUnit.Framework; -namespace EntitiesBT.CodeGen.Tests +namespace EntitiesBT.Test { public class TestCecilExtension { diff --git a/Packages/samples/Tests~/Editor/TestCecilExtension.cs.meta b/Packages/samples/Tests~/Editor/TestCecilExtension.cs.meta new file mode 100644 index 00000000..657bb223 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestCecilExtension.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e99755c04b514d20bc542f67c8f2bdb8 +timeCreated: 1627287913 \ No newline at end of file diff --git a/Packages/codegen/Tests~/TestCodeGenForNode.cs b/Packages/samples/Tests~/Editor/TestCodeGenForNode.cs similarity index 97% rename from Packages/codegen/Tests~/TestCodeGenForNode.cs rename to Packages/samples/Tests~/Editor/TestCodeGenForNode.cs index 1294ce94..450c2897 100644 --- a/Packages/codegen/Tests~/TestCodeGenForNode.cs +++ b/Packages/samples/Tests~/Editor/TestCodeGenForNode.cs @@ -7,7 +7,7 @@ using NUnit.Framework; using Unity.Entities; -namespace EntitiesBT.CodeGen.Tests +namespace EntitiesBT.Test { public class TestCodeGenForNode { @@ -30,7 +30,7 @@ public void should_avoid_generate_attributes_on_method_already_has_attributes() } [BehaviorNode("E683A98D-96D3-4EFE-B5E4-250F92441B3B", Ignore = true)] - class TestManualNode : INodeData + class TestManualNode : INodeData, ICustomResetAction { [ReadWrite(typeof(double))] public NodeState Tick(int index, ref TNodeBlob blob, ref TBlackboard bb) where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard @@ -73,9 +73,8 @@ struct FooComponent : IComponentData {} struct BarComponent : IComponentData {} [BehaviorNode("D4C33711-96CB-448B-BD6E-182271E2D69F", Ignore = true)] - class TestNode : INodeData + class TestNode : INodeData, ICustomResetAction { - public NodeState Tick(int index, ref TNodeBlob blob, ref TBlackboard bb) where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { bb.GetData(); diff --git a/Packages/samples/Tests~/Editor/TestCodeGenForNode.cs.meta b/Packages/samples/Tests~/Editor/TestCodeGenForNode.cs.meta new file mode 100644 index 00000000..46d1ced5 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestCodeGenForNode.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bb27b8321925431f8b0db34157f827c4 +timeCreated: 1627287913 \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestDelegateRegistry.cs b/Packages/samples/Tests~/Editor/TestDelegateRegistry.cs new file mode 100644 index 00000000..2e0a49ec --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestDelegateRegistry.cs @@ -0,0 +1,78 @@ +using System; +using System.Text.RegularExpressions; +using EntitiesBT.Variant; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.TestTools; +using static EntitiesBT.Core.Utilities; + +namespace EntitiesBT.Test +{ + public class TestDelegateRegistry + { + [RegisterDelegateClass(GUID)] + static class TestClass + { + public const string GUID = "BBE08DBD-ADD1-463A-B9C8-92CC8CCAF789"; + + [RegisterDelegateMethod(typeof(Func))] + public static int A(int l, int r) => l + r; + + // should log error + [RegisterDelegateMethod(typeof(Func))] + public static float B(int l, float r) => l + r; + + [RegisterDelegateMethod(typeof(Func<,,>))] + public static R C(T l, U r) => throw new NotImplementedException(); + + [RegisterDelegateMethod(typeof(Func))] + public static float D(int l, int r) => 4; + } + + [Test] + public void should_get_delegate_method_A_by_id_from_registry() + { + var @delegate = DelegateRegistry>.TryGetValue(GuidHashCode(TestClass.GUID)); + Assert.IsNotNull(@delegate); + Assert.AreEqual(3, @delegate(1, 2)); + } + + static bool _isFirstRun = true; + static class FirstRun + { + public static void Init() { } + static FirstRun() => _isFirstRun = false; + } + + [Test] + public void should_log_error_while_fetching_delegate_method_B_by_id_from_registry() + { + DelegateRegistry>.TryGetValue(GuidHashCode(TestClass.GUID)); + if (_isFirstRun) LogAssert.Expect(LogType.Error, new Regex("Cannot create delegate .*")); + FirstRun.Init(); + } + + [Test] + public void should_get_delegate_method_C_by_id_from_registry() + { + var @delegate = DelegateRegistry>.TryGetValue(GuidHashCode(TestClass.GUID)); + Assert.IsNotNull(@delegate); + Assert.Throws(() => @delegate(0, 0)); + } + + static class TestGeneric + { + public static R Call() where R : unmanaged + { + var id = GuidHashCode(TestClass.GUID); + var @delegate = DelegateRegistry>.TryGetValue(id); + return @delegate?.Invoke(default, default) ?? default; + } + } + [Test] + public void should_call_delegate_by_types_and_id() + { + Assert.AreEqual(4, TestGeneric.Call()); + } + } +} \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestDelegateRegistry.cs.meta b/Packages/samples/Tests~/Editor/TestDelegateRegistry.cs.meta new file mode 100644 index 00000000..d2b7f9b6 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestDelegateRegistry.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 78f176c1ac524285bdc4710a4358128a +timeCreated: 1614790322 \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestExpression.cs b/Packages/samples/Tests~/Editor/TestExpression.cs new file mode 100644 index 00000000..0b4217db --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestExpression.cs @@ -0,0 +1,78 @@ +using System; +using EntitiesBT.Core; +using EntitiesBT.Entities; +using EntitiesBT.Variant; +using EntitiesBT.Variant.Expression; +using Moq; +using NUnit.Framework; +using Unity.Collections; +using Unity.Entities; + +namespace EntitiesBT.Test +{ + using TreeNodeBuilder = ITreeNode; + + public class TestExpression + { + private BlobBuilder _builder; + private MockNodeBlob _nodeBlob; + private MockBlackboard _bb; + + private struct MockNodeBlob : INodeBlob + { + public int RuntimeId { get; } + public int Count { get; } + public int GetTypeId(int nodeIndex) => throw new NotImplementedException(); + public int GetEndIndex(int nodeIndex) => throw new NotImplementedException(); + public int GetNodeDataSize(int startNodeIndex, int count = 1) => throw new NotImplementedException(); + public NodeState GetState(int nodeIndex) => throw new NotImplementedException(); + public void SetState(int nodeIndex, NodeState state) => throw new NotImplementedException(); + public void ResetStates(int index, int count = 1) => throw new NotImplementedException(); + public IntPtr GetDefaultDataPtr(int nodeIndex) => throw new NotImplementedException(); + public IntPtr GetRuntimeDataPtr(int nodeIndex) => throw new NotImplementedException(); + } + + private struct MockBlackboard : IBlackboard + { + public bool HasData() where T : struct => throw new NotImplementedException(); + public T GetData() where T : struct => throw new NotImplementedException(); + public ref T GetDataRef() where T : struct => throw new NotImplementedException(); + public bool HasData(Type type) => throw new NotImplementedException(); + public IntPtr GetDataPtrRO(Type type) => throw new NotImplementedException(); + public IntPtr GetDataPtrRW(Type type) => throw new NotImplementedException(); + public T GetObject() where T : class => throw new NotImplementedException(); + } + + [SetUp] + public void SetUp() + { + _builder = new BlobBuilder(Allocator.Temp); + _nodeBlob = new MockNodeBlob(); + _bb = new MockBlackboard(); + } + + [TearDown] + public void TearDown() + { + _builder.Dispose(); + } + + [Test] + public void should_eval_expression() + { + var expression = new ExpressionVariant.Reader(); + expression._expression = "(x+y)*2+10"; + expression._sources = new[] + { + new ExpressionVariant.Reader.Variant {Value = new LocalVariant.Reader {Value = 4.1f}, Name = "x"}, + new ExpressionVariant.Reader.Variant {Value = new LocalVariant.Reader {Value = 5}, Name = "y"}, + }; + + ref var buildVariant = ref _builder.ConstructRoot(); + expression.Allocate(ref _builder, ref buildVariant, null, null); + using var variant = _builder.CreateBlobAssetReference(Allocator.Temp); + var result = BlobVariantExtension.Read(ref variant.Value, 0, ref _nodeBlob, ref _bb); + Assert.That(result, Is.EqualTo((4.1f + 5) * 2 + 10)); + } + } +} \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestExpression.cs.meta b/Packages/samples/Tests~/Editor/TestExpression.cs.meta new file mode 100644 index 00000000..7e3bd749 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestExpression.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c85908ffc42644b2be5f66e30c73c267 +timeCreated: 1627280625 \ No newline at end of file diff --git a/Packages/codegen/Tests~/TestGenerateAccessorAttributesFromMethod.cs b/Packages/samples/Tests~/Editor/TestGenerateAccessorAttributesFromMethod.cs similarity index 99% rename from Packages/codegen/Tests~/TestGenerateAccessorAttributesFromMethod.cs rename to Packages/samples/Tests~/Editor/TestGenerateAccessorAttributesFromMethod.cs index 5ff2a4a1..6b71abe5 100644 --- a/Packages/codegen/Tests~/TestGenerateAccessorAttributesFromMethod.cs +++ b/Packages/samples/Tests~/Editor/TestGenerateAccessorAttributesFromMethod.cs @@ -6,7 +6,7 @@ using Mono.Cecil; using NUnit.Framework; -namespace EntitiesBT.CodeGen.Tests +namespace EntitiesBT.Test { public class TestGenerateAccessorAttributesFromMethod { diff --git a/Packages/samples/Tests~/Editor/TestGenerateAccessorAttributesFromMethod.cs.meta b/Packages/samples/Tests~/Editor/TestGenerateAccessorAttributesFromMethod.cs.meta new file mode 100644 index 00000000..e5aa3cb7 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestGenerateAccessorAttributesFromMethod.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1a7d11f8b92e48d39bce3a016768a3ca +timeCreated: 1627287913 \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestVariant.cs b/Packages/samples/Tests~/Editor/TestVariant.cs new file mode 100644 index 00000000..e88a5fe9 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestVariant.cs @@ -0,0 +1,33 @@ +using System; +using EntitiesBT.Core; +using EntitiesBT.Variant; +using NUnit.Framework; +using Unity.Entities; + +namespace EntitiesBT.Test +{ + public class TestVariant + { + [Test] + public void should_find_value_type_of_variant() + { + var variant = new LocalVariant.Reader(); + Assert.That(variant.FindValueType(), Is.EqualTo(typeof(int))); + } + + class InvalidVariant : IVariant + { + public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INodeDataBuilder self, ITreeNode[] tree) + { + throw new NotImplementedException(); + } + } + + [Test] + public void should_get_null_as_value_type_from_invalid_variant() + { + var variant = new InvalidVariant(); + Assert.That(variant.FindValueType(), Is.EqualTo(null)); + } + } +} \ No newline at end of file diff --git a/Packages/samples/Tests~/Editor/TestVariant.cs.meta b/Packages/samples/Tests~/Editor/TestVariant.cs.meta new file mode 100644 index 00000000..9ca3af80 --- /dev/null +++ b/Packages/samples/Tests~/Editor/TestVariant.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a5df43d008284ee2aa20b7df8c02b8a1 +timeCreated: 1626675699 \ No newline at end of file diff --git a/Packages/samples/Tests~/Runtime/BTTestNodeA.cs b/Packages/samples/Tests~/Runtime/BTTestNodeA.cs index ac119f01..a56c4138 100644 --- a/Packages/samples/Tests~/Runtime/BTTestNodeA.cs +++ b/Packages/samples/Tests~/Runtime/BTTestNodeA.cs @@ -8,7 +8,7 @@ namespace EntitiesBT.Test { [BehaviorNode("29E6B4D9-4388-4EA8-8F36-162ACBE5C166")] - public struct NodeA : INodeData + public struct NodeA : INodeData, ICustomResetAction { public int A; diff --git a/Packages/samples/Tests~/Runtime/BTTestNodeB.cs b/Packages/samples/Tests~/Runtime/BTTestNodeB.cs index 5f1f2638..032615cc 100644 --- a/Packages/samples/Tests~/Runtime/BTTestNodeB.cs +++ b/Packages/samples/Tests~/Runtime/BTTestNodeB.cs @@ -8,7 +8,7 @@ namespace EntitiesBT.Test { [BehaviorNode("793F38C5-B0BD-410A-87BD-D122B10E636F")] - public struct NodeB : INodeData + public struct NodeB : INodeData, ICustomResetAction { public int B; public int BB; diff --git a/Packages/samples/Tests~/Runtime/BTTestNodeState.cs b/Packages/samples/Tests~/Runtime/BTTestNodeState.cs index 82918437..9ec42d76 100644 --- a/Packages/samples/Tests~/Runtime/BTTestNodeState.cs +++ b/Packages/samples/Tests~/Runtime/BTTestNodeState.cs @@ -8,7 +8,7 @@ namespace EntitiesBT.Test { [BehaviorNode("59E8EB08-1652-45F3-81DB-775D9D76508D")] - public struct TestNode : INodeData + public struct TestNode : INodeData, ICustomResetAction { public NodeState State; public int Index; diff --git a/Packages/samples/package.json b/Packages/samples/package.json index 3af1ae6c..d9f0101d 100644 --- a/Packages/samples/package.json +++ b/Packages/samples/package.json @@ -1,18 +1,24 @@ { "name": "com.quabug.entities-bt.samples", "description": "Behavior Tree for Unity Entities - Samples", - "version": "1.1.1", + "version": "1.2.0", "unity": "2020.2", "displayName": "EntitiesBT - Samples", "type": "sample", "dependencies": { "com.unity.inputsystem": "1.0.0", "com.unity.rendering.hybrid": "0.8.0-preview.19", - "com.quabug.entities-bt.builder.component": "1.0.0", - "com.quabug.entities-bt.debug.component-viewer": "1.0.0", - "com.quabug.entities-bt.essential": "1.1.0" + "com.quabug.entities-bt.builder.component": "1.2.0", + "com.quabug.entities-bt.debug.component-viewer": "1.2.0", + "com.quabug.entities-bt.essential": "1.2.0", + "com.quabug.entities-bt.variant-expression": "0.2.0" }, "samples": [ + { + "displayName": "[Test] tests", + "description": "test cases of behavior tree", + "path": "Tests~" + }, { "displayName": "[Sample] hybrid-animator", "description": "animator controlled by behavior tree", @@ -44,9 +50,14 @@ "path": "Samples~/RuntimeEntityCreation" }, { - "displayName": "[Test] tests", - "description": "test cases of behavior tree", - "path": "Test~" + "displayName": "[Sample] Expression", + "description": "expression", + "path": "Samples~/Expression" + }, + { + "displayName": "[Sample] Odin Builder", + "description": "odin", + "path": "Samples~/Odin" } ] } \ No newline at end of file diff --git a/Packages/variable.scriptable-object/Runtime/ScriptableObjectVariant.cs b/Packages/variable.scriptable-object/Runtime/ScriptableObjectVariant.cs index ae68313f..2fa736e9 100644 --- a/Packages/variable.scriptable-object/Runtime/ScriptableObjectVariant.cs +++ b/Packages/variable.scriptable-object/Runtime/ScriptableObjectVariant.cs @@ -3,7 +3,6 @@ using EntitiesBT.Core; using Unity.Entities; using UnityEngine; -using UnityEngine.Scripting; using static EntitiesBT.Core.Utilities; namespace EntitiesBT.Variant @@ -19,9 +18,11 @@ public VariantScriptableObjectValueAttribute(string scriptableObjectFieldName) } } - + [VariantClass(GUID)] public static class ScriptableObjectVariant { + public const string GUID = "B14A224A-7ADF-4E03-8240-60DE620FF946"; + [Serializable] public class Reader : IVariantReader where T : unmanaged { @@ -53,15 +54,13 @@ public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INo } } - public const string GUID = "B14A224A-7ADF-4E03-8240-60DE620FF946"; - - [Preserve, RefReaderMethod(GUID)] + [RefReaderMethod] private static ref T GetDataRef(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) where T : unmanaged where TNodeBlob : struct, INodeBlob where TBlackboard : struct, IBlackboard { - return ref blobVariant.Value(); + return ref blobVariant.As(); } } diff --git a/Packages/variable.scriptable-object/package.json b/Packages/variable.scriptable-object/package.json index 22bb82ca..4045f032 100644 --- a/Packages/variable.scriptable-object/package.json +++ b/Packages/variable.scriptable-object/package.json @@ -1,10 +1,10 @@ { "name": "com.quabug.entities-bt.variable.scriptable-object", "description": "Behavior Tree for Unity Entities - Scriptable Object Variable", - "version": "1.0.1", + "version": "1.2.0", "unity": "2020.2", "displayName": "EntitiesBT - Scriptable Object Variable", "dependencies": { - "com.quabug.entities-bt.essential": "1.0.1" + "com.quabug.entities-bt.essential": "1.2.0" } } \ No newline at end of file diff --git a/Packages/variant.expression.meta b/Packages/variant.expression.meta new file mode 100644 index 00000000..06eb5b1d --- /dev/null +++ b/Packages/variant.expression.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ba470376b0cf48518d1b16474876f22d +timeCreated: 1614771327 \ No newline at end of file diff --git a/Packages/variant.expression/Runtime.meta b/Packages/variant.expression/Runtime.meta new file mode 100644 index 00000000..0cb33cfa --- /dev/null +++ b/Packages/variant.expression/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0315101cccc72b8428702408d9e244a6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/AssemblyInfo.cs b/Packages/variant.expression/Runtime/AssemblyInfo.cs new file mode 100644 index 00000000..3f9a3ffa --- /dev/null +++ b/Packages/variant.expression/Runtime/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("EntitiesBT.Tests.Editor")] +[assembly: InternalsVisibleTo("EntitiesBT.Tests.Runtime")] diff --git a/Packages/variant.expression/Runtime/AssemblyInfo.cs.meta b/Packages/variant.expression/Runtime/AssemblyInfo.cs.meta new file mode 100644 index 00000000..3c68550d --- /dev/null +++ b/Packages/variant.expression/Runtime/AssemblyInfo.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2daf6b59b02a44c58066ca64801b76f6 +timeCreated: 1627281190 \ No newline at end of file diff --git a/Packages/samples/Runtime/Variable/EntitiesBT.Sample.Variable.asmdef b/Packages/variant.expression/Runtime/EntitiesBT.Variant.Expression.asmdef similarity index 78% rename from Packages/samples/Runtime/Variable/EntitiesBT.Sample.Variable.asmdef rename to Packages/variant.expression/Runtime/EntitiesBT.Variant.Expression.asmdef index 2b252929..5f182036 100644 --- a/Packages/samples/Runtime/Variable/EntitiesBT.Sample.Variable.asmdef +++ b/Packages/variant.expression/Runtime/EntitiesBT.Variant.Expression.asmdef @@ -1,18 +1,18 @@ { - "name": "EntitiesBT.Sample.Variable", + "name": "EntitiesBT.Variant.Expression", "rootNamespace": "", "references": [ "GUID:c7babe7561eb244059259745ef27b866", - "GUID:734d92eba21c94caba915361bd5ac177", "GUID:d8b63aba1907145bea998dd612889d6b", + "GUID:734d92eba21c94caba915361bd5ac177", "GUID:abe4851e67df59644865a60dae54a845" ], "includePlatforms": [], "excludePlatforms": [], "allowUnsafeCode": true, - "overrideReferences": false, + "overrideReferences": true, "precompiledReferences": [ - "EntitiesBT.Variable.Sample.VariableProperties.dll" + "DynamicExpresso.Core.dll" ], "autoReferenced": true, "defineConstraints": [], diff --git a/Packages/variant.expression/Runtime/EntitiesBT.Variant.Expression.asmdef.meta b/Packages/variant.expression/Runtime/EntitiesBT.Variant.Expression.asmdef.meta new file mode 100644 index 00000000..1450696c --- /dev/null +++ b/Packages/variant.expression/Runtime/EntitiesBT.Variant.Expression.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6679f77e90ec1d540ab279146d203dbb +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/Expression.cs b/Packages/variant.expression/Runtime/Expression.cs new file mode 100644 index 00000000..d708a997 --- /dev/null +++ b/Packages/variant.expression/Runtime/Expression.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using DynamicExpresso; + +namespace EntitiesBT.Variant.Expression +{ + public static class Expression + { + private static readonly Interpreter _interpreter; + private static readonly ConcurrentDictionary _lambdas = new ConcurrentDictionary(); + + static Expression() + { + _interpreter = new Interpreter(); + _interpreter.EnableAssignment(AssignmentOperators.None); + foreach (var type in VariantValueTypeRegistry.GetAllTypes()) _interpreter.Reference(type); + foreach (var type in AppDomain.CurrentDomain.GetAssemblies() + .SelectMany(assembly => assembly.GetCustomAttributes()) + .Select(attribute => attribute.Type) + ) _interpreter.Reference(type); + } + + public static Lambda Parse(this ref ExpressionVariant.Data data, in LambdaId lambdaId) + { + if (_lambdas.TryGetValue(lambdaId, out var lambda)) return lambda; + + var expressionType = VariantValueTypeRegistry.GetTypeById(data.ExpressionType); + var parameters = new Parameter[data.VariantTypes.Length]; + for (var i = 0; i < parameters.Length; i++) + { + var type = VariantValueTypeRegistry.GetTypeById(data.VariantTypes[i]); + var name = data.VariantNames[i].ToString(); + parameters[i] = new Parameter(name, type); + } + + lambda = _interpreter.Parse( + data.Expression.ToString(), + expressionType, + parameters + ); + _lambdas[lambdaId] = lambda; + return lambda; + } + } +} \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/Expression.cs.meta b/Packages/variant.expression/Runtime/Expression.cs.meta new file mode 100644 index 00000000..7ded9cb9 --- /dev/null +++ b/Packages/variant.expression/Runtime/Expression.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3c691664819543aa9119f47417961dc1 +timeCreated: 1626681095 \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/ExpressionReferenceAttribute.cs b/Packages/variant.expression/Runtime/ExpressionReferenceAttribute.cs new file mode 100644 index 00000000..343e4325 --- /dev/null +++ b/Packages/variant.expression/Runtime/ExpressionReferenceAttribute.cs @@ -0,0 +1,11 @@ +using System; + +namespace EntitiesBT.Variant.Expression +{ + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + public class ExpressionReferenceAttribute : Attribute + { + public Type Type { get; } + public ExpressionReferenceAttribute(Type type) => Type = type; + } +} \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/ExpressionReferenceAttribute.cs.meta b/Packages/variant.expression/Runtime/ExpressionReferenceAttribute.cs.meta new file mode 100644 index 00000000..9c5c8336 --- /dev/null +++ b/Packages/variant.expression/Runtime/ExpressionReferenceAttribute.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e2b2c9d2da984299a25cf8dc6307479d +timeCreated: 1626849521 \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/ExpressionVariant.cs b/Packages/variant.expression/Runtime/ExpressionVariant.cs new file mode 100644 index 00000000..f3227df7 --- /dev/null +++ b/Packages/variant.expression/Runtime/ExpressionVariant.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using EntitiesBT.Attributes; +using EntitiesBT.Core; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Entities; +using UnityEngine; +using static EntitiesBT.Core.Utilities; + +namespace EntitiesBT.Variant.Expression +{ + [VariantClass(GUID)] + public static class ExpressionVariant + { + public const string GUID = "D7492D8C-CCE3-4071-85C6-92E7EE1E9C48"; + + public struct Data + { + public BlobString Expression; + public int ExpressionType; + public BlobArray Variants; + public BlobArray VariantNames; + public BlobArray VariantTypes; + } + + private static readonly ConcurrentDictionary _expressionParameters = new ConcurrentDictionary(); + + [Serializable] + public class Reader : IVariantReader where T : unmanaged + { + [Serializable] + internal class Variant + { + [SerializeReference, SerializeReferenceDrawer] public IVariantReader Value; + public string Name; + } + + [SerializeField] internal string _expression; + [SerializeField] internal Variant[] _sources; + + public unsafe IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant, INodeDataBuilder self, ITreeNode[] tree) + { + blobVariant.VariantId = GuidHashCode(GUID); + ref var blobPtr = ref UnsafeUtility.As>(ref blobVariant.MetaDataOffsetPtr); + ref var data = ref builder.Allocate(ref blobPtr); + data.ExpressionType = VariantValueTypeRegistry.GetIdByType(typeof(T)); + builder.AllocateString(ref data.Expression, _expression); + var variants = builder.Allocate(ref data.Variants, _sources.Length); + var names = builder.Allocate(ref data.VariantNames, _sources.Length); + var types = builder.Allocate(ref data.VariantTypes, _sources.Length); + for (var i = 0; i < _sources.Length; i++) + { + _sources[i].Value.Allocate(ref builder, ref variants[i], self, tree); + builder.AllocateString(ref names[i], _sources[i].Name); + types[i] = VariantValueTypeRegistry.GetIdByType(_sources[i].Value.FindValueType()); + } + return new IntPtr(UnsafeUtility.AddressOf(ref data)); + } + } + + [ReaderMethod] + private static T Read(ref BlobVariant blobVariant, int index, ref TNodeBlob blob, ref TBlackboard bb) + where T : unmanaged + where TNodeBlob : struct, INodeBlob + where TBlackboard : struct, IBlackboard + { + ref var data = ref blobVariant.As(); + var lambdaId = new LambdaId(blob.RuntimeId, index); + var lambda = data.Parse(lambdaId); + + if (!_expressionParameters.TryGetValue(lambdaId, out var arguments)) + { + arguments = new object[data.Variants.Length]; + _expressionParameters[lambdaId] = arguments; + } + + for (var i = 0; i < arguments.Length; i++) + { + var type = VariantValueTypeRegistry.GetTypeById(data.VariantTypes[i]); + var pointer = data.Variants[i].GetPointer(index, ref blob, ref bb); + arguments[i] = Marshal.PtrToStructure(pointer, type); + } + return (T) lambda.Invoke(arguments); + } + } +} \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/ExpressionVariant.cs.meta b/Packages/variant.expression/Runtime/ExpressionVariant.cs.meta new file mode 100644 index 00000000..c283febb --- /dev/null +++ b/Packages/variant.expression/Runtime/ExpressionVariant.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a4e3ee048ea54913bf430d50a91f7f24 +timeCreated: 1614938769 \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/LambdaId.cs b/Packages/variant.expression/Runtime/LambdaId.cs new file mode 100644 index 00000000..450e7fea --- /dev/null +++ b/Packages/variant.expression/Runtime/LambdaId.cs @@ -0,0 +1,35 @@ +using System; + +namespace EntitiesBT.Variant.Expression +{ + public readonly struct LambdaId : IEquatable + { + public readonly int BehaviorTreeId; + public readonly int NodeId; + + public LambdaId(int behaviorTreeId, int nodeId) + { + BehaviorTreeId = behaviorTreeId; + NodeId = nodeId; + } + + public bool Equals(LambdaId other) + { + return BehaviorTreeId == other.BehaviorTreeId && NodeId == other.NodeId; + } + + public override bool Equals(object obj) + { + return obj is LambdaId other && Equals(other); + } + + public override int GetHashCode() + { + unchecked + { + return (BehaviorTreeId * 397) ^ NodeId; + } + } + } + +} \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/LambdaId.cs.meta b/Packages/variant.expression/Runtime/LambdaId.cs.meta new file mode 100644 index 00000000..2fb76efe --- /dev/null +++ b/Packages/variant.expression/Runtime/LambdaId.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b9915eb3dd1f4967a9a12dc6b2968e3c +timeCreated: 1627317111 \ No newline at end of file diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1.meta b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1.meta new file mode 100644 index 00000000..3df06c64 --- /dev/null +++ b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b7c7a95e4c3d4a546b255871b072adab +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/LICENSE b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/LICENSE new file mode 100644 index 00000000..c969623f Binary files /dev/null and b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/LICENSE differ diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/LICENSE.meta b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/LICENSE.meta new file mode 100644 index 00000000..6dbe9d9a --- /dev/null +++ b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 51b495ac660bdbe4a8d84bf18b79127b +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461.meta b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461.meta new file mode 100644 index 00000000..61dffb20 --- /dev/null +++ b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 97fd52878bd72e54fb58d3e25070129d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461/DynamicExpresso.Core.dll b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461/DynamicExpresso.Core.dll new file mode 100644 index 00000000..a39788d0 Binary files /dev/null and b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461/DynamicExpresso.Core.dll differ diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461/DynamicExpresso.Core.dll.meta b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461/DynamicExpresso.Core.dll.meta new file mode 100644 index 00000000..96b524ec --- /dev/null +++ b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/net461/DynamicExpresso.Core.dll.meta @@ -0,0 +1,77 @@ +fileFormatVersion: 2 +guid: e8f7708192727d344b036915f6a42a77 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: + - NET_4_6 + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0.meta b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0.meta new file mode 100644 index 00000000..f0f8f7bf --- /dev/null +++ b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3ea4e3d01c15ce843860f85c5a36bb41 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0/DynamicExpresso.Core.dll b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0/DynamicExpresso.Core.dll new file mode 100644 index 00000000..d3e103f4 Binary files /dev/null and b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0/DynamicExpresso.Core.dll differ diff --git a/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0/DynamicExpresso.Core.dll.meta b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0/DynamicExpresso.Core.dll.meta new file mode 100644 index 00000000..3a07f68b --- /dev/null +++ b/Packages/variant.expression/Runtime/dynamicexpresso.core.2.8.1/netstandard2.0/DynamicExpresso.Core.dll.meta @@ -0,0 +1,77 @@ +fileFormatVersion: 2 +guid: 3b71c4be50d15aa45a695effabaad4e3 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: + - NET_STANDARD_2_0 + isPreloaded: 0 + isOverridable: 1 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/variant.expression/package.json b/Packages/variant.expression/package.json new file mode 100644 index 00000000..348dfbef --- /dev/null +++ b/Packages/variant.expression/package.json @@ -0,0 +1,9 @@ +{ + "name": "com.quabug.entities-bt.variant-expression", + "version": "0.2.0", + "unity": "2020.2", + "displayName": "EntitiesBT - Expression Variant", + "dependencies": { + "com.quabug.entities-bt.essential": "1.2.0" + } +} \ No newline at end of file diff --git a/Packages/variant.expression/package.json.meta b/Packages/variant.expression/package.json.meta new file mode 100644 index 00000000..78793fb4 --- /dev/null +++ b/Packages/variant.expression/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: dc4e269afe72fc846b96f4a683f71460 +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/ProjectSettings/EditorBuildSettings.asset b/ProjectSettings/EditorBuildSettings.asset index 0147887e..66749c5d 100644 --- a/ProjectSettings/EditorBuildSettings.asset +++ b/ProjectSettings/EditorBuildSettings.asset @@ -4,5 +4,8 @@ EditorBuildSettings: m_ObjectHideFlags: 0 serializedVersion: 2 - m_Scenes: [] + m_Scenes: + - enabled: 1 + path: Packages/com.quabug.entities-bt.samples/Samples/Expression/SampleExpression.unity + guid: b6a242e0521a16045abe2502e2b9dbc5 m_configObjects: {} diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 25b1e1e1..6bed516a 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -128,7 +128,12 @@ PlayerSettings: 16:9: 1 Others: 1 bundleVersion: 0.1 - preloadedAssets: [] + preloadedAssets: + - {fileID: 0} + - {fileID: 0} + - {fileID: 0} + - {fileID: 0} + - {fileID: 0} metroInputSource: 0 wsaTransparentSwapchain: 0 m_HolographicPauseOnTrackingLoss: 1 @@ -146,6 +151,7 @@ PlayerSettings: androidSupportedAspectRatio: 1 androidMaxAspectRatio: 2.1 applicationIdentifier: + Android: com.DefaultCompany.BehaviorTreeExample Standalone: com.DefaultCompany.BehaviorTreeExample buildNumber: Standalone: 0 @@ -258,7 +264,99 @@ PlayerSettings: AndroidValidateAppBundleSize: 1 AndroidAppBundleSizeToValidate: 150 m_BuildTargetIcons: [] - m_BuildTargetPlatformIcons: [] + m_BuildTargetPlatformIcons: + - m_BuildTarget: Android + m_Icons: + - m_Textures: [] + m_Width: 432 + m_Height: 432 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 324 + m_Height: 324 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 216 + m_Height: 216 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 162 + m_Height: 162 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 108 + m_Height: 108 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 81 + m_Height: 81 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 192 + m_Height: 192 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 144 + m_Height: 144 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 96 + m_Height: 96 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 72 + m_Height: 72 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 48 + m_Height: 48 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 36 + m_Height: 36 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 192 + m_Height: 192 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 144 + m_Height: 144 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 96 + m_Height: 96 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 72 + m_Height: 72 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 48 + m_Height: 48 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 36 + m_Height: 36 + m_Kind: 1 + m_SubKind: m_BuildTargetBatching: - m_BuildTarget: Standalone m_StaticBatching: 1 @@ -371,6 +469,7 @@ PlayerSettings: switchTitleNames_12: switchTitleNames_13: switchTitleNames_14: + switchTitleNames_15: switchPublisherNames_0: switchPublisherNames_1: switchPublisherNames_2: @@ -386,6 +485,7 @@ PlayerSettings: switchPublisherNames_12: switchPublisherNames_13: switchPublisherNames_14: + switchPublisherNames_15: switchIcons_0: {fileID: 0} switchIcons_1: {fileID: 0} switchIcons_2: {fileID: 0} @@ -401,6 +501,7 @@ PlayerSettings: switchIcons_12: {fileID: 0} switchIcons_13: {fileID: 0} switchIcons_14: {fileID: 0} + switchIcons_15: {fileID: 0} switchSmallIcons_0: {fileID: 0} switchSmallIcons_1: {fileID: 0} switchSmallIcons_2: {fileID: 0} @@ -416,6 +517,7 @@ PlayerSettings: switchSmallIcons_12: {fileID: 0} switchSmallIcons_13: {fileID: 0} switchSmallIcons_14: {fileID: 0} + switchSmallIcons_15: {fileID: 0} switchManualHTML: switchAccessibleURLs: switchLegalInformation: @@ -479,6 +581,8 @@ PlayerSettings: switchNetworkInterfaceManagerInitializeEnabled: 1 switchPlayerConnectionEnabled: 1 switchUseNewStyleFilepaths: 0 + switchUseMicroSleepForYield: 1 + switchMicroSleepForYieldTime: 25 ps4NPAgeRating: 12 ps4NPTitleSecret: ps4NPTrophyPackPath: @@ -549,6 +653,7 @@ PlayerSettings: ps4videoRecordingFeaturesUsed: 0 ps4contentSearchFeaturesUsed: 0 ps4CompatibilityPS5: 0 + ps4AllowPS5Detection: 0 ps4GPU800MHz: 1 ps4attribEyeToEyeDistanceSettingVR: 0 ps4IncludedModules: [] @@ -573,10 +678,14 @@ PlayerSettings: webGLLinkerTarget: 1 webGLThreadsSupport: 0 webGLDecompressionFallback: 0 - scriptingDefineSymbols: {} + scriptingDefineSymbols: + 1: + 7: ODIN_INSPECTOR;ODIN_INSPECTOR_3 additionalCompilerArguments: {} platformArchitecture: {} - scriptingBackend: {} + scriptingBackend: + Android: 1 + Standalone: 1 il2cppCompilerConfiguration: {} managedStrippingLevel: {} incrementalIl2cppBuild: {} diff --git a/ProjectSettings/ProjectVersion.txt b/ProjectSettings/ProjectVersion.txt index 4db0bd06..98c9697e 100644 --- a/ProjectSettings/ProjectVersion.txt +++ b/ProjectSettings/ProjectVersion.txt @@ -1,2 +1,2 @@ -m_EditorVersion: 2020.3.0f1 -m_EditorVersionWithRevision: 2020.3.0f1 (c7b5465681fb) +m_EditorVersion: 2020.3.14f1 +m_EditorVersionWithRevision: 2020.3.14f1 (d0d1bb862f9d) diff --git a/ProjectSettings/SceneTemplateSettings.json b/ProjectSettings/SceneTemplateSettings.json new file mode 100644 index 00000000..6f3e60fd --- /dev/null +++ b/ProjectSettings/SceneTemplateSettings.json @@ -0,0 +1,167 @@ +{ + "templatePinStates": [], + "dependencyTypeInfos": [ + { + "userAdded": false, + "type": "UnityEngine.AnimationClip", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEditor.Animations.AnimatorController", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.AnimatorOverrideController", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEditor.Audio.AudioMixerController", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.ComputeShader", + "ignore": true, + "defaultInstantiationMode": 1, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Cubemap", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.GameObject", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEditor.LightingDataAsset", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": false + }, + { + "userAdded": false, + "type": "UnityEngine.LightingSettings", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Material", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEditor.MonoScript", + "ignore": true, + "defaultInstantiationMode": 1, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.PhysicMaterial", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.PhysicsMaterial2D", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Rendering.PostProcessing.PostProcessProfile", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Rendering.PostProcessing.PostProcessResources", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Rendering.VolumeProfile", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEditor.SceneAsset", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": false + }, + { + "userAdded": false, + "type": "UnityEngine.Shader", + "ignore": true, + "defaultInstantiationMode": 1, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.ShaderVariantCollection", + "ignore": true, + "defaultInstantiationMode": 1, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Texture", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Texture2D", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + }, + { + "userAdded": false, + "type": "UnityEngine.Timeline.TimelineAsset", + "ignore": false, + "defaultInstantiationMode": 0, + "supportsModification": true + } + ], + "defaultDependencyTypeInfo": { + "userAdded": false, + "type": "", + "ignore": false, + "defaultInstantiationMode": 1, + "supportsModification": true + }, + "newSceneOverride": 0 +} \ No newline at end of file diff --git a/ProjectSettings/UnityConnectSettings.asset b/ProjectSettings/UnityConnectSettings.asset index fa0b1465..6125b308 100644 --- a/ProjectSettings/UnityConnectSettings.asset +++ b/ProjectSettings/UnityConnectSettings.asset @@ -9,6 +9,7 @@ UnityConnectSettings: m_EventOldUrl: https://api.uca.cloud.unity3d.com/v1/events m_EventUrl: https://cdp.cloud.unity3d.com/v1/events m_ConfigUrl: https://config.uca.cloud.unity3d.com + m_DashboardUrl: https://dashboard.unity3d.com m_TestInitMode: 0 CrashReportingSettings: m_EventUrl: https://perf-events.cloud.unity3d.com