diff --git a/com.wug.behaviortreevisualizer/Editor/Scripts/Graph/BehaviorTreeGraphView.cs b/com.wug.behaviortreevisualizer/Editor/Scripts/Graph/BehaviorTreeGraphView.cs index c8483b9..d2a5d4d 100644 --- a/com.wug.behaviortreevisualizer/Editor/Scripts/Graph/BehaviorTreeGraphView.cs +++ b/com.wug.behaviortreevisualizer/Editor/Scripts/Graph/BehaviorTreeGraphView.cs @@ -170,13 +170,13 @@ public void DrawNodes(bool entryPoint, NodeBase currentNode, int columnIndex, Po decoratorData.Add(fullDetails); - if (currentNode.ChildNodes.Count == 0) + if (currentNode.children.Count == 0) { $"Decorator ({currentNode.GetType().Name}) does not have any children. Nothing will be drawn.".BTDebugLog(); } else { - DrawNodes(false, currentNode.ChildNodes[0], colIndex, parentPort, stackNode, null, decoratorData); + DrawNodes(false, currentNode.children[0], colIndex, parentPort, stackNode, null, decoratorData); } } else @@ -224,7 +224,7 @@ public void DrawNodes(bool entryPoint, NodeBase currentNode, int columnIndex, Po AddElement(node); } - if (currentNode.ChildNodes.Count > 0) + if (currentNode.children.Count > 0) { colIndex++; @@ -248,7 +248,7 @@ public void DrawNodes(bool entryPoint, NodeBase currentNode, int columnIndex, Po AddElement(stack); } - for (int i = 0; i < currentNode.ChildNodes.Count; i++) + for (int i = 0; i < currentNode.children.Count; i++) { node.AddPort(GeneratePort(node, Direction.Output, Port.Capacity.Multi), (i + 1).ToString(), false); @@ -258,12 +258,12 @@ public void DrawNodes(bool entryPoint, NodeBase currentNode, int columnIndex, Po { newStyles.Add("FirstNodeSpacing"); } - else if (i == currentNode.ChildNodes.Count - 1) + else if (i == currentNode.children.Count - 1) { newStyles.Add("LastNodeSpacing"); } - DrawNodes(false, currentNode.ChildNodes[i], colIndex, node.OutputPorts[i], stack, newStyles.ToArray()); + DrawNodes(false, currentNode.children[i], colIndex, node.OutputPorts[i], stack, newStyles.ToArray()); } } diff --git a/com.wug.behaviortreevisualizer/Runtime/NodeBase.cs b/com.wug.behaviortreevisualizer/Runtime/NodeBase.cs index d29d0e6..3ebb6f0 100644 --- a/com.wug.behaviortreevisualizer/Runtime/NodeBase.cs +++ b/com.wug.behaviortreevisualizer/Runtime/NodeBase.cs @@ -16,11 +16,26 @@ public class NodeBase { public string Name { get; set; } public string StatusReason { get; set; } = ""; - public List ChildNodes = new List(); + public List children = new List(); + public NodeBase Parent { get => parent; set { + if (value != null) + { + value.children.Add(this); + }else if (parent != null) + { + parent.children.Remove(this); + } + parent = value; + } } + + public NodeStatus LastNodeStatus = NodeStatus.NotRun; public event NodeStatusChangedEventHandler NodeStatusChanged; + + protected NodeBase parent = null; + /// /// Handles invoking the NodeStatusChangedEventHandler delegate. /// diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/.gitignore b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/.gitignore new file mode 100644 index 0000000..d9c4e71 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/.gitignore @@ -0,0 +1,13 @@ +/.vsconfig +/Assembly-CSharp.csproj +/Assembly-CSharp-Editor.csproj +/Assembly-CSharp-Editor-firstpass.csproj +/Assembly-CSharp-firstpass.csproj +/behaviortreevisualizer.sln +/WhatUpGames.BehaviorTreeDebugger.csproj +/WhatUpGames.BehaviorTreeVisualizer.Editor.csproj +/Library +/Logs +/obj +/Packages +/Temp diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta).meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta).meta new file mode 100644 index 0000000..7ad509a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta).meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bab3839b3715a2743b2244991b145fe1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources.meta new file mode 100644 index 0000000..99998e1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4d003ed7226996e4e9aeee2db7138110 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources/settings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources/settings.asset new file mode 100644 index 0000000..1d88dfb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources/settings.asset @@ -0,0 +1,34 @@ +%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: 97748ca66d1b7b3448e205f8a48a42e1, type: 3} + m_Name: settings + m_EditorClassIdentifier: + DimLevel: 127 + BorderHighlightColor: {r: 0, g: 1, b: 0, a: 1} + EnableMiniMap: 0 + LastRunTimeStamp: 1 + RunningIcon: {fileID: 21300000, guid: e5b1b229d2a13eb48a686864c4c7c993, type: 3} + SuccessIcon: {fileID: 21300000, guid: cdc83b1ed0823ff41805968d8a49da64, type: 3} + FailureIcon: {fileID: 21300000, guid: a12f0f96f8cacf0408b24a9bb943d66b, type: 3} + DefaultStyleProperties: + Script: {fileID: 0} + TitleBarColor: {r: 0.09411765, g: 0.70980394, b: 0.9137255, a: 1} + Icon: {fileID: 21300000, guid: b672344d83977ea4b92d823b96fa1425, type: 3} + IsDecorator: 0 + InvertResult: 0 + MainStyleProperties: + - Script: {fileID: 11500000, guid: 2a35061ee83fc3e4fb9df09683590ce1, type: 3} + TitleBarColor: {r: 0.09411765, g: 0.70980394, b: 0.9137255, a: 1} + Icon: {fileID: 0} + IsDecorator: 0 + InvertResult: 0 + OverrideStyleProperties: [] diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources/settings.asset.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources/settings.asset.meta new file mode 100644 index 0000000..606e7e7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Behavior Tree Visualizer (Beta)/Resources/settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f9aa204a956c04040be40fc76e647d08 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes.meta new file mode 100644 index 0000000..38e856f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9d377af3ec827d3418c88d09cf9e199e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation.meta new file mode 100644 index 0000000..09dafae --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: be4ae8f88c546a94b8f15560df0d1f59 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation/NavigateToDestination.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation/NavigateToDestination.cs new file mode 100644 index 0000000..a5d547d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation/NavigateToDestination.cs @@ -0,0 +1,106 @@ +using System; +using UnityEngine; +using UnityEngine.AI; + +namespace WUG.BehaviorTreeVisualizer.CommunityNodes +{ + [Serializable] + public class NavigateToDestination : Node + { + private Func m_DestinationCalculation; + private Vector3 m_TargetDestination = Vector3.zero; + private NavMeshAgent m_NavMeshAgent; + private float m_MaxDistanceToSample = 1f; + + /// + /// Navigate a game object to a specific location using Unity's Navigation. + /// Behavior will get a SamplePosition within 1 meter of the destination to ensure that the location + /// provided can be navigated. + /// + /// NavMesh on the game object that will be moved + /// Function that can be used to calculate the target destination. Must return a Vector3. + /// Max distance that NavMesh.SamplePosition should check for + public NavigateToDestination(NavMeshAgent navMeshAgent, Func destination, float maxDistance = 1f) + { + Name = "Navigate"; + m_NavMeshAgent = navMeshAgent; + m_DestinationCalculation = destination; + m_MaxDistanceToSample = maxDistance; + } + + /// + /// Navigate a game object to a specific location using Unity's Navigation. + /// Behavior will get a SamplePosition within 1f of the destination to ensure that the location + /// provided can be navigated. + /// + /// Game object that will be moved. Must have a NavMeshAgent on it + /// Function that can be used to calculate the target destination. Must return a Vector3. + /// Max distance that NavMesh.SamplePosition should check for + public NavigateToDestination(GameObject gameObject, Func destination, float maxDistance = 1f) + { + Name = "Navigate"; + m_NavMeshAgent = gameObject.GetComponent(); + m_DestinationCalculation = destination; + m_MaxDistanceToSample = maxDistance; + } + + + protected override void OnReset() { } + + protected override NodeStatus OnRun() + { + //Make sure that a reference to NavMeshAgent and a valid destination exists + if (m_NavMeshAgent == null) + { + StatusReason = "NavMeshAgent is null"; + return NodeStatus.Failure; + } + + //First Evaluation will get the official target destination and set it on the NavMeshAgent + if (IsFirstEvaluation) + { + if (m_DestinationCalculation() == null) + { + StatusReason = "Unable to calculate a destination position. Did you pass a function in?"; + return NodeStatus.Failure; + } + + m_TargetDestination = m_DestinationCalculation(); + + if (m_TargetDestination == Vector3.zero) + { + StatusReason = "Unable to calculate a destination position. Does the function return a position?"; + return NodeStatus.Failure; + } + + NavMesh.SamplePosition(m_TargetDestination, out NavMeshHit hit, m_MaxDistanceToSample, 1); + m_TargetDestination = hit.position; + + m_NavMeshAgent.SetDestination(m_TargetDestination); + StatusReason = $"Starting to navigate to {m_TargetDestination}"; + + return NodeStatus.Running; + } + + //Evaluate the remaining distance + float distanceToTarget = Vector3.Distance(m_TargetDestination, m_NavMeshAgent.transform.position); + + //Reached the destination + if (distanceToTarget < .25f) + { + StatusReason = $"Navigation ended. " + + $"\n - Evaluation Count: {EvaluationCount}. " + + $"\n - Target Destination: {m_TargetDestination}" + + $"\n - Distance to target: {Math.Round(distanceToTarget, 1)}"; + + return NodeStatus.Success; + } + + //Still moving + StatusReason = $"Distance to target: {distanceToTarget}"; + return NodeStatus.Running; + + } + } +} + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation/NavigateToDestination.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation/NavigateToDestination.cs.meta new file mode 100644 index 0000000..3d2c74e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/Navigation/NavigateToDestination.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 885d7b0f78c0c5840b74460a4524e0c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/README.md b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/README.md new file mode 100644 index 0000000..4b676c2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/README.md @@ -0,0 +1,13 @@ + +# Community Nodes +The goal of the Behavior Tree Visualizer tool is to make writing and debugging AI easier for all! To help with this, our hope is to facilitate a repository of Nodes that interact with various elements of Unity. A full list of the nodes can be found [here](https://github.com/Yecats/UnityBehaviorTreeVisualizer/wiki/Community-Nodes). + +## Contribute +Want to contribute a new community node or fix a bug? You can submit a pull request on the GitHub repository at https://github.com/Yecats/UnityBehaviorTreeVisualizer/. A few things to note: + +1. Nodes should be in the **com.wug.behaviortreevisualizer\Samples~\Community Nodes** folder with a sub category folder (i.e. "Navigation"). +2. All community nodes must build off the **Standard Nodes** sample project. In other words, if you are creating a new **Decorator**, make sure it inherits from the `Decorator` node. +3. Documentation, documentation, documentation! Make sure to add comments to explain what your node is doing, parameters that need to be passed, etc. + +## Get Help +If you encounter an issue with a community node, please reach out on GitHub and log an issue at https://github.com/Yecats/UnityBehaviorTreeVisualizer/issues or submit a pull request with the fix. \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/README.md.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/README.md.meta new file mode 100644 index 0000000..aa3feec --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Community Nodes/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5c835b9af8d8137479e3ee25ee2b9064 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame.meta new file mode 100644 index 0000000..e78deb9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 124ba2310ad50aa4bbe1ccc2ad7600b3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua.meta new file mode 100644 index 0000000..cfcca1d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3d484561689578348984556cbd06bb32 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/.vscode/settings.json b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/.vscode/settings.json new file mode 100644 index 0000000..4a576b9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "Lua.diagnostics.globals": [ + "CS" + ] +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs.meta new file mode 100644 index 0000000..8a1bdc5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9e6903836d1143747a7b4adaec5fff49 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/NonPlayerCharacter.lua b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/NonPlayerCharacter.lua new file mode 100644 index 0000000..a55773f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/NonPlayerCharacter.lua @@ -0,0 +1,26 @@ +require'NodeUtil' + +return SelectorNode('Control NPC',{ + SequenceNode('Pickup Item',{ + LeafNode('IsNavigationActivityTypeOf',CS.WUG.BehaviorTreeVisualizer.NavigationActivity.PickupItem), + SelectorNode('Look for or move to items',{ + SequenceNode("Look for items",{ + InverterNode('Inverter',{ + LeafNode('AreItemsNearBy',5) + }), + LeafNode('SetNavigationActivityTo',CS.WUG.BehaviorTreeVisualizer.NavigationActivity.Waypoint), + }), + SequenceNode('Navigate to Item',{ + LeafNode('NavigateToDestination') + }), + }), + }), + SequenceNode('Move to Waypoint',{ + LeafNode('IsNavigationActivityTypeOf',CS.WUG.BehaviorTreeVisualizer.NavigationActivity.Waypoint), + LeafNode('NavigateToDestination'), + Node('Timer',nil,{ + LeafNode('Idle') + },2.0), + LeafNode('SetNavigationActivityTo',CS.WUG.BehaviorTreeVisualizer.NavigationActivity.PickupItem), + }), +}) diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/NonPlayerCharacter.lua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/NonPlayerCharacter.lua.meta new file mode 100644 index 0000000..d4a7698 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/NonPlayerCharacter.lua.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 575ae1de1c79cec49bcdf8f53666d4b0 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 11500000, guid: 505b3ad82f257a34eba53061df16fe7f, type: 3} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/Test.lua b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/Test.lua new file mode 100644 index 0000000..1ca5de8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/Test.lua @@ -0,0 +1,10 @@ +require'NodeUtil' + +return SelectorNode('test1',{ + SequenceNode('test3',{ + LeafNode('NavigateToDestination') + }), + SequenceNode('test2',{ + LeafNode('NavigateToDestination') + }), +}) \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/Test.lua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/Test.lua.meta new file mode 100644 index 0000000..30eaddb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeConfigs/Test.lua.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9c4b63253a5d99848996468e505daf63 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 11500000, guid: 505b3ad82f257a34eba53061df16fe7f, type: 3} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeUtil.lua b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeUtil.lua new file mode 100644 index 0000000..3b3f868 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeUtil.lua @@ -0,0 +1,29 @@ +Selector = 'Selector' +Sequence = 'Sequence' +Inverter = 'Inverter' + + +function Node(type,name,children,...) + return { + type = type, + name = name or type, + children = children, + params = {...} + } +end + +function LeafNode(type,...) + return Node(type,nil,nil,...) +end + +function SelectorNode(...) + return Node(Selector,...) +end + +function SequenceNode(...) + return Node(Sequence,...) +end + +function InverterNode(...) + return Node(Inverter,...) +end \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeUtil.lua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeUtil.lua.meta new file mode 100644 index 0000000..2eb856d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/NodeUtil.lua.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: b9d2ea2d562a4584f99e6550e273bf02 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 11500000, guid: 505b3ad82f257a34eba53061df16fe7f, type: 3} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/TreeCreator.lua b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/TreeCreator.lua new file mode 100644 index 0000000..a358485 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/TreeCreator.lua @@ -0,0 +1,42 @@ + +local table=table +local CS=CS +local require = require +local assert = assert +local print=print +_ENV = {} + +RegisteredNodes={ + Selector = CS.WUG.BehaviorTreeVisualizer.Selector, + Sequence = CS.WUG.BehaviorTreeVisualizer.Sequence, + Inverter = CS.WUG.BehaviorTreeVisualizer.Inverter, + IsNavigationActivityTypeOf = CS.WUG.BehaviorTreeVisualizer.IsNavigationActivityTypeOf, + SetNavigationActivityTo = CS.WUG.BehaviorTreeVisualizer.SetNavigationActivityTo, + NavigateToDestination = CS.WUG.BehaviorTreeVisualizer.NavigateToDestination, + Timer = CS.WUG.BehaviorTreeVisualizer.Timer, + Idle = CS.WUG.BehaviorTreeVisualizer.Idle, + AreItemsNearBy = CS.WUG.BehaviorTreeVisualizer.AreItemsNearBy, +} + +function CreateTree(nodedata,debugShowStep) + if debugShowStep==nil then + debugShowStep = false + end + -- print('type:',nodedata.type) + local type = RegisteredNodes[nodedata.type] or nodedata.type + local node = type(table.unpack(nodedata.params)) + if node.Name == nil or node.Name == '' then + node.Name = nodedata.name + end + -- node.DebugShowStep=debugShowStep + node.DebugShowStep = true + if nodedata.children then + for i = 1, #nodedata.children do + local n = CreateTree(nodedata.children[i]) + n.Parent = node + end + end + return node +end + +return _ENV \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/TreeCreator.lua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/TreeCreator.lua.meta new file mode 100644 index 0000000..a7596f9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/Lua/TreeCreator.lua.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 07322c4ea20d6ce4e88d07105b295162 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 11500000, guid: 505b3ad82f257a34eba53061df16fe7f, type: 3} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/LuaUtil.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/LuaUtil.cs new file mode 100644 index 0000000..bb20c40 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/LuaUtil.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using WUG.BehaviorTreeVisualizer; +using XLua; + +namespace FGGame +{ + static class LuaUtil + { + static LuaEnv lua = new LuaEnv(); + static LuaUtil() + { + var s = @"function ReloadModule(name) + local status, err = xpcall(function() + package.loaded[name] = nil + return require(name) + end, debug.traceback) + if status then + return err + else + print(err) + end + end"; + lua.DoString(s); + lua.AddLoader((ref string filePath) => { + var path = Application.dataPath + "/FGGame/Lua/"; + return File.ReadAllBytes(path + filePath.Replace('.', '/') + ".lua"); + }); + } + + //public static void Reload() + //{ + + + //} + + public static NodeBase CreateTree(T _=null) where T :class + { + var name = typeof(T).Name; + return CreateTree(name); + } + + public static NodeBase CreateTree(string name) + { + var configtable = LoadConfig(name); + var obj = lua.DoString($"return ReloadModule 'TreeCreator'")[0] as LuaTable; + return obj.Get("CreateTree").Call(configtable)[0] as NodeBase; + } + + public static LuaTable LoadConfig(string config) + { + var objs = lua.DoString($"return ReloadModule 'NodeConfigs.{config}'"); + return objs[0] as LuaTable; + } + public static LuaTable LoadConfig(T _ = null) where T : class + { + return LoadConfig(typeof(T).Name); + } + + class LuaDrawData : INodeDrawData + { + public string name { get; set; } + public NodeBase BehaviorTree { get; set; } + } + + [TreeDatasGetter] + public static IList GetTreeDatas() + { + var datas = new List(); + var path = Application.dataPath + "/FGGame/Lua/NodeConfigs"; + var dirinfo = new DirectoryInfo(path); + var files = dirinfo.GetFiles(); + foreach (var item in files) + { + if (item.Name.EndsWith(".lua")) + { + var name = item.Name.Replace(".lua", ""); + datas.Add(new LuaDrawData() { name = name , BehaviorTree = CreateTree(name) }); + } + } + return datas; + } + [TreeDatasSaver] + public static void TreeDatasSaver(NodeBase tree, string name) + { + + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/LuaUtil.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/LuaUtil.cs.meta new file mode 100644 index 0000000..4f5aa6e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/LuaUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: abce1dd80b9aa864983ce0aa90eea961 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/NewBehaviourScript.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/NewBehaviourScript.cs new file mode 100644 index 0000000..0549f64 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/NewBehaviourScript.cs @@ -0,0 +1,18 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class NewBehaviourScript : MonoBehaviour +{ + // Start is called before the first frame update + void Start() + { + + } + + // Update is called once per frame + void Update() + { + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/NewBehaviourScript.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/NewBehaviourScript.cs.meta new file mode 100644 index 0000000..e53a85a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/FGGame/NewBehaviourScript.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 04ca321de102559418ba9318bb3854a4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4.meta new file mode 100644 index 0000000..457333b --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8d14dea27a07bf94f99388988a3b0fa7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Ground.mat b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Ground.mat similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Ground.mat rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Ground.mat diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Ground.mat.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Ground.mat.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Ground.mat.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Ground.mat.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Item.mat b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Item.mat similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Item.mat rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Item.mat diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Item.mat.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Item.mat.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Materials/Item.mat.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Materials/Item.mat.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Prefabs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Prefabs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Prefabs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Prefabs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Prefabs/Item.prefab b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Prefabs/Item.prefab similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Prefabs/Item.prefab rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Prefabs/Item.prefab diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Prefabs/Item.prefab.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Prefabs/Item.prefab.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Prefabs/Item.prefab.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Prefabs/Item.prefab.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.unity b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.unity similarity index 88% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.unity rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.unity index 23cfb3f..8182ed7 100644 --- a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.unity +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.unity @@ -38,12 +38,12 @@ 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.44657898, g: 0.4964133, b: 0.5748178, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: m_ObjectHideFlags: 0 - serializedVersion: 12 + serializedVersion: 11 m_GIWorkflowMode: 1 m_GISettings: serializedVersion: 2 @@ -98,7 +98,7 @@ LightmapSettings: m_TrainingDataDestination: TrainingData m_LightProbeSampleCountMultiplier: 4 m_LightingDataAsset: {fileID: 0} - m_LightingSettings: {fileID: 4890085278179872738, guid: 7bea544ecb60f0c4f824034143ff09a2, type: 2} + m_UseShadowmask: 1 --- !u!196 &4 NavMeshSettings: serializedVersion: 2 @@ -118,8 +118,6 @@ NavMeshSettings: manualTileSize: 0 tileSize: 256 accuratePlacement: 0 - maxJobWorkers: 0 - preserveTilesOutsideBounds: 0 debug: m_Flags: 0 m_NavMeshData: {fileID: 23800000, guid: a501b7fa70d662f40b946878f627c5e3, type: 2} @@ -269,6 +267,8 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 2a35061ee83fc3e4fb9df09683590ce1, type: 3} m_Name: m_EditorClassIdentifier: + useLua: 1 + step: 1 --- !u!54 &361313833 Rigidbody: m_ObjectHideFlags: 0 @@ -292,51 +292,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (7) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 7 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 31.34 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 35.03 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 7 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -344,7 +356,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &406613018 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 406613017} m_PrefabAsset: {fileID: 0} --- !u!1001 &430636814 @@ -354,51 +367,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (11) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 11 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 33.48 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: -26.78 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 11 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -406,7 +431,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &430636815 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 430636814} m_PrefabAsset: {fileID: 0} --- !u!1001 &448889856 @@ -416,51 +442,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (1) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: -33.29 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 27.13 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -468,7 +506,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &448889857 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 448889856} m_PrefabAsset: {fileID: 0} --- !u!1001 &503245624 @@ -478,51 +517,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (14) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 14 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 4.54 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 24.11 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 14 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -530,7 +581,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &503245625 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 503245624} m_PrefabAsset: {fileID: 0} --- !u!1001 &531927202 @@ -540,51 +592,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (10) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 10 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 30.3 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: -27.84 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 10 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -592,7 +656,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &531927203 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 531927202} m_PrefabAsset: {fileID: 0} --- !u!1 &705507993 @@ -735,7 +800,6 @@ MeshRenderer: m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 - m_RayTraceProcedural: 0 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: @@ -760,7 +824,6 @@ MeshRenderer: m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 - m_AdditionalVertexStreams: {fileID: 0} --- !u!33 &740801618 MeshFilter: m_ObjectHideFlags: 0 @@ -790,51 +853,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (3) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 3 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: -21.59 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: -26.73 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 3 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -842,7 +917,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &769017679 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 769017678} m_PrefabAsset: {fileID: 0} --- !u!1001 &806795431 @@ -852,51 +928,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (8) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 8 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 33.55 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 31.67 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 8 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -904,7 +992,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &806795432 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 806795431} m_PrefabAsset: {fileID: 0} --- !u!1 &948465808 @@ -944,51 +1033,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (2) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 2 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: -29.73 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 26.38 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 2 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -996,7 +1097,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &952631115 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 952631114} m_PrefabAsset: {fileID: 0} --- !u!1 &963194225 @@ -1119,51 +1221,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (13) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 13 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 1.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 24.51 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 13 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -1171,7 +1285,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &994960623 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 994960622} m_PrefabAsset: {fileID: 0} --- !u!1001 &1016576634 @@ -1181,51 +1296,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (9) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 9 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 32.67 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: -23.6 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 9 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -1233,7 +1360,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &1016576635 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 1016576634} m_PrefabAsset: {fileID: 0} --- !u!1 &1365056661 @@ -1318,51 +1446,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (5) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 5 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: -19.39 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: -29.48 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 5 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -1370,7 +1510,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &1591648905 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 1591648904} m_PrefabAsset: {fileID: 0} --- !u!1001 &1606341225 @@ -1380,51 +1521,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (12) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 12 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 3.7399998 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 26.31 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 12 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -1432,7 +1585,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &1606341226 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 1606341225} m_PrefabAsset: {fileID: 0} --- !u!1001 &1767207388 @@ -1442,51 +1596,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (4) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 4 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: -23.78 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: -28.960001 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 4 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -1494,7 +1660,8 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &1767207389 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 1767207388} m_PrefabAsset: {fileID: 0} --- !u!1 &1782066002 @@ -1589,7 +1756,6 @@ MeshRenderer: m_LightProbeUsage: 1 m_ReflectionProbeUsage: 1 m_RayTracingMode: 2 - m_RayTraceProcedural: 0 m_RenderingLayerMask: 1 m_RendererPriority: 0 m_Materials: @@ -1614,7 +1780,6 @@ MeshRenderer: m_SortingLayerID: 0 m_SortingLayer: 0 m_SortingOrder: 0 - m_AdditionalVertexStreams: {fileID: 0} --- !u!33 &1880121239 MeshFilter: m_ObjectHideFlags: 0 @@ -1630,51 +1795,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item (6) objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 6 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: 34.39 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 36.35 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 6 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} @@ -1682,12 +1859,14 @@ PrefabInstance: m_SourcePrefab: {fileID: 100100000, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} --- !u!4 &1985659271 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 1985659270} m_PrefabAsset: {fileID: 0} --- !u!4 &2112183903 stripped Transform: - m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + m_CorrespondingSourceObject: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} m_PrefabInstance: {fileID: 5510808762948616666} m_PrefabAsset: {fileID: 0} --- !u!1 &2141783676 @@ -1727,51 +1906,63 @@ PrefabInstance: m_Modification: m_TransformParent: {fileID: 1516184660} m_Modifications: - - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125508, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_Name value: Item objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_RootOrder + value: 0 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.x value: -30.56 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.y value: 0.25 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalPosition.z value: 29.6 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} + propertyPath: m_LocalRotation.w + value: 1 + objectReference: {fileID: 0} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.x value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.y value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalRotation.z value: -0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_LocalRotation.w - value: 1 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} - propertyPath: m_RootOrder - value: 0 - objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.x value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.y value: 0 objectReference: {fileID: 0} - - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, type: 3} + - target: {fileID: 5510808762221125509, guid: de3a7cabf962ec64a942f80d3a0f44c2, + type: 3} propertyPath: m_LocalEulerAnglesHint.z value: 0 objectReference: {fileID: 0} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.unity.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.unity.meta similarity index 74% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.unity.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.unity.meta index 952bd1e..fcf6773 100644 --- a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene.unity.meta +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene.unity.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9fc0d4010bbf28b4594072e72b8655ab +guid: d4d27b0aeb7bb9b4b87655675e993b62 DefaultImporter: externalObjects: {} userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleScene/NavMesh.asset.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scenes/SampleSceneSettings.lighting.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/Idle.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/NavigateToDestination.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs similarity index 57% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs index 8b0778c..cbf6981 100644 --- a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs @@ -1,8 +1,10 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using UnityEngine; namespace WUG.BehaviorTreeVisualizer { @@ -11,24 +13,41 @@ public class SetNavigationActivityTo : Node private NavigationActivity m_NewActivity; + IEnumerator crun; + public SetNavigationActivityTo(NavigationActivity newActivity) { m_NewActivity = newActivity; Name = $"Set NavigationActivity to {m_NewActivity}"; + crun = cRun(); } - protected override void OnReset() { } + protected override void OnReset() { crun = cRun(); } protected override NodeStatus OnRun() { + crun.MoveNext(); + if (crun.Current is NodeStatus) + { + return (NodeStatus)crun.Current; + } + return NodeStatus.Running; + } + + IEnumerator cRun() + { + if(DebugShowStep) + yield return new WaitForSeconds(1); + if (GameManager.Instance == null || GameManager.Instance.NPC == null) { StatusReason = "GameManager or NPC is null"; - return NodeStatus.Failure; + yield return NodeStatus.Failure; } GameManager.Instance.NPC.MyActivity = m_NewActivity; - return NodeStatus.Success; + yield return NodeStatus.Success; + } } } diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Actions/SetNavigationActivityTo.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/AreItemsNearBy.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/BehaviorTree/Custom/Conditions/IsNavigationActivityTypeOf.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor.meta new file mode 100644 index 0000000..05005a4 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 300b21a4e2cb5c54785512efc4a24fd3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs.meta new file mode 100644 index 0000000..fc35b57 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Editor/NonplayerCharacterEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d4d2dddc531691f4eac1416d26ce0692 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/GameManager.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/GameManager.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/GameManager.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/GameManager.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/GameManager.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/GameManager.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/GameManager.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/GameManager.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/Item.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Item.cs similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/Item.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Item.cs diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/Item.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Item.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/Item.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/Item.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs similarity index 82% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs index c48c9e9..acb27c0 100644 --- a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs @@ -15,14 +15,26 @@ public enum NavigationActivity PickupItem } - public class NonPlayerCharacter : MonoBehaviour, IBehaviorTree + public class NonPlayerCharacter : MonoBehaviour, IBehaviorTree, INodeDrawData { + public bool useLua = false; public NavMeshAgent MyNavMesh { get; private set; } - public NodeBase BehaviorTree { get; set; } + public NodeBase BehaviorTree { get { + if (behaviorTree == null) + { + GenerateBehaviorTree(); + } + return behaviorTree; + } set { + behaviorTree = value; + } } public NavigationActivity MyActivity { get; set; } + public float step = 0.5f; + private Coroutine m_BehaviorTreeRoutine; - private YieldInstruction m_WaitTime = new WaitForSeconds(.1f); + + private NodeBase behaviorTree; private void Start() @@ -56,13 +68,19 @@ private IEnumerator RunBehaviorTree() } (BehaviorTree as Node).Run(); + - yield return m_WaitTime; + yield return new WaitForSeconds(step); } } private void GenerateBehaviorTree() { + if (useLua) + { + BehaviorTree = FGGame.LuaUtil.CreateTree(this); + return; + } BehaviorTree = new Selector("Control NPC", new Sequence("Pickup Item", new IsNavigationActivityTypeOf(NavigationActivity.PickupItem), @@ -79,6 +97,7 @@ private void GenerateBehaviorTree() new Timer(2f, new Idle()), new SetNavigationActivityTo(NavigationActivity.PickupItem))); + } public void ForceDrawingOfTree() diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs.meta similarity index 100% rename from com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs.meta rename to com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/NPC Sample 2019.4/Scripts/NonPlayerCharacter.cs.meta diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins.meta new file mode 100644 index 0000000..61dd5a9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: a16bb6756d0496e42a92390340cb94f5 +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android.meta new file mode 100644 index 0000000..7b0709b --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 0004c0a5ad641d4468ebb65779ee48b2 +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs.meta new file mode 100644 index 0000000..b884009 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9cd62bafd75e7604daf2b561b80d136d +folderAsset: yes +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a.meta new file mode 100644 index 0000000..d04cb53 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 084116138e3349d48bdf50214aebefc5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a/libxlua.so b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a/libxlua.so new file mode 100644 index 0000000..2a75f51 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a/libxlua.so differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a/libxlua.so.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a/libxlua.so.meta new file mode 100644 index 0000000..b8c3350 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/arm64-v8a/libxlua.so.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 6c76d1cfa11c6b741ba30b24d36cbcf2 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARM64 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a.meta new file mode 100644 index 0000000..ba53f0f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b8d0cd0f5702f0144af2498bce3ee3e9 +folderAsset: yes +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so new file mode 100644 index 0000000..5743f4e Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so.meta new file mode 100644 index 0000000..2e4b59d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so.meta @@ -0,0 +1,24 @@ +fileFormatVersion: 2 +guid: 6e1b2e17cce240d4c8ff5457ac996e0d +timeCreated: 1451443249 +licenseType: Pro +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 1 + settings: + CPU: ARMv7 + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86.meta new file mode 100644 index 0000000..0861447 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 079ea0ed741ff194a80cce029630b5ac +folderAsset: yes +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86/libxlua.so b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86/libxlua.so new file mode 100644 index 0000000..75959f9 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86/libxlua.so differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86/libxlua.so.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86/libxlua.so.meta new file mode 100644 index 0000000..680638d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/Android/libs/x86/libxlua.so.meta @@ -0,0 +1,24 @@ +fileFormatVersion: 2 +guid: 038a89637b659e346a7a712ce0c9271b +timeCreated: 1451443249 +licenseType: Pro +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 1 + settings: + CPU: x86 + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA.meta new file mode 100644 index 0000000..1c9120c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b8c5688e381fddc4eb22e6f96f69541c +folderAsset: yes +timeCreated: 1489995541 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM.meta new file mode 100644 index 0000000..b830e37 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e6375603a0a1e2647b0c426b27646eb7 +folderAsset: yes +timeCreated: 1490146877 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM/xlua.dll b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM/xlua.dll new file mode 100644 index 0000000..4a30eb4 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM/xlua.dll differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM/xlua.dll.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM/xlua.dll.meta new file mode 100644 index 0000000..36b5c7d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM/xlua.dll.meta @@ -0,0 +1,25 @@ +fileFormatVersion: 2 +guid: cb3d94d8757d66b40b20f0386b52d01d +timeCreated: 1490146878 +licenseType: Free +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + WindowsStoreApps: + enabled: 1 + settings: + CPU: ARM + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64.meta new file mode 100644 index 0000000..6a8714f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 830e69f8ce948ae429150ee86c12ddc0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64/xlua.dll b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64/xlua.dll new file mode 100644 index 0000000..ef3e5a8 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64/xlua.dll differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64/xlua.dll.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64/xlua.dll.meta new file mode 100644 index 0000000..79e2af2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/ARM64/xlua.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: fac391e0450743a48b0946219ab22e43 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64.meta new file mode 100644 index 0000000..bb3efae --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4d5a7116d7e9a33409205303635b8635 +folderAsset: yes +timeCreated: 1490146877 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64/xlua.dll b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64/xlua.dll new file mode 100644 index 0000000..ccb6ba1 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64/xlua.dll differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64/xlua.dll.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64/xlua.dll.meta new file mode 100644 index 0000000..a3bbccf --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x64/xlua.dll.meta @@ -0,0 +1,25 @@ +fileFormatVersion: 2 +guid: a73864467778862409da51f9feb60004 +timeCreated: 1490146878 +licenseType: Free +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + WindowsStoreApps: + enabled: 1 + settings: + CPU: x64 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86.meta new file mode 100644 index 0000000..7a70fd5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 6e0f35de38a8ed24fa8b20d444c9ee5e +folderAsset: yes +timeCreated: 1490146877 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86/xlua.dll b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86/xlua.dll new file mode 100644 index 0000000..3aa1890 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86/xlua.dll differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86/xlua.dll.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86/xlua.dll.meta new file mode 100644 index 0000000..0e61ac0 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WSA/x86/xlua.dll.meta @@ -0,0 +1,25 @@ +fileFormatVersion: 2 +guid: 3fd23a6414095674493657a67a8043a1 +timeCreated: 1489995544 +licenseType: Free +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + WindowsStoreApps: + enabled: 1 + settings: + CPU: x86 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL.meta new file mode 100644 index 0000000..98b3347 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: e7f3a5adb034d684cb13cb257c29a1c3 +folderAsset: yes +timeCreated: 1504062948 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL/xlua_webgl.cpp b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL/xlua_webgl.cpp new file mode 100644 index 0000000..2e373bd --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL/xlua_webgl.cpp @@ -0,0 +1,41 @@ +extern "C" { +#include "../../../WebGLPlugins/lapi.c" +#include "../../../WebGLPlugins/lauxlib.c" +#include "../../../WebGLPlugins/lbaselib.c" +#include "../../../WebGLPlugins/lbitlib.c" +#include "../../../WebGLPlugins/lcode.c" +#include "../../../WebGLPlugins/lcorolib.c" +#include "../../../WebGLPlugins/lctype.c" +#include "../../../WebGLPlugins/ldblib.c" +#include "../../../WebGLPlugins/ldebug.c" +#include "../../../WebGLPlugins/ldo.c" +#include "../../../WebGLPlugins/ldump.c" +#include "../../../WebGLPlugins/lfunc.c" +#include "../../../WebGLPlugins/lgc.c" +#include "../../../WebGLPlugins/linit.c" +#include "../../../WebGLPlugins/liolib.c" +#include "../../../WebGLPlugins/llex.c" +#include "../../../WebGLPlugins/lmathlib.c" +#include "../../../WebGLPlugins/lmem.c" +#include "../../../WebGLPlugins/loadlib.c" +#include "../../../WebGLPlugins/lobject.c" +#include "../../../WebGLPlugins/lopcodes.c" +#include "../../../WebGLPlugins/loslib.c" +#include "../../../WebGLPlugins/lparser.c" +#include "../../../WebGLPlugins/lstate.c" +#include "../../../WebGLPlugins/lstring.c" +#include "../../../WebGLPlugins/lstrlib.c" +#include "../../../WebGLPlugins/ltable.c" +#include "../../../WebGLPlugins/ltablib.c" +#include "../../../WebGLPlugins/ltm.c" +#include "../../../WebGLPlugins/lundump.c" +#include "../../../WebGLPlugins/lutf8lib.c" +#include "../../../WebGLPlugins/lvm.c" +#include "../../../WebGLPlugins/lzio.c" +#include "../../../WebGLPlugins/i64lib.c" +#include "../../../WebGLPlugins/perflib.c" +#include "../../../WebGLPlugins/xlua.c" +} + + + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL/xlua_webgl.cpp.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL/xlua_webgl.cpp.meta new file mode 100644 index 0000000..4f61da8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/WebGL/xlua_webgl.cpp.meta @@ -0,0 +1,39 @@ +fileFormatVersion: 2 +guid: 92f9773841d5ffd44b794b9b584a5c05 +timeCreated: 1504062948 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + data: + first: + Facebook: WebGL + second: + enabled: 1 + settings: {} + data: + first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS.meta new file mode 100644 index 0000000..3237528 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 5a4ab2e5e00054b03a7bf96d03e5b4e1 +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/HotfixFlags.cpp b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/HotfixFlags.cpp new file mode 100644 index 0000000..6451497 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/HotfixFlags.cpp @@ -0,0 +1,37 @@ +#include +#include + +int* xlua_hotfix_flags = NULL; +int xlua_hotfix_flags_len = 0; + +extern "C" { + +int xlua_get_hotfix_flag(int idx) { + if (idx >= xlua_hotfix_flags_len) { + return 0; + } else { + return xlua_hotfix_flags[idx]; + } +} + +void xlua_set_hotfix_flag(int idx, int flag) { + int i = 0; + int* new_hotfix_flags = NULL; + if (idx >= xlua_hotfix_flags_len) { + if (xlua_hotfix_flags == NULL) { + xlua_hotfix_flags = (int*)malloc((idx + 1) * sizeof(int)); + } else { + new_hotfix_flags = (int*)realloc(xlua_hotfix_flags, (idx + 1) * sizeof(int)); + if (NULL == new_hotfix_flags) { // just skip operation + return; + } + xlua_hotfix_flags = new_hotfix_flags; + } + for(i = xlua_hotfix_flags_len; i < (idx + 1); i++) { + xlua_hotfix_flags[i] = 0; + } + xlua_hotfix_flags_len = idx + 1; + } + xlua_hotfix_flags[idx] = flag; +} +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/HotfixFlags.cpp.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/HotfixFlags.cpp.meta new file mode 100644 index 0000000..de5fc71 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/HotfixFlags.cpp.meta @@ -0,0 +1,24 @@ +fileFormatVersion: 2 +guid: ef0ed550afe43d449b58d883fad0585c +timeCreated: 1498103331 +licenseType: Pro +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + iOS: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/libxlua.a b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/libxlua.a new file mode 100644 index 0000000..ba0987b Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/libxlua.a differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/libxlua.a.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/libxlua.a.meta new file mode 100644 index 0000000..3988bc9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/iOS/libxlua.a.meta @@ -0,0 +1,23 @@ +fileFormatVersion: 2 +guid: 2d65468f3356ca741b3fbebea91dfb6c +timeCreated: 1451443249 +licenseType: Pro +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Any: + enabled: 0 + settings: {} + Editor: + enabled: 0 + settings: + DefaultValueInitialized: true + iOS: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86.meta new file mode 100644 index 0000000..de2cb10 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 8b0b0c4ffe67d2f4292c5211de91e55f +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/libxlua.so b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/libxlua.so new file mode 100644 index 0000000..335b0bf Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/libxlua.so differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/libxlua.so.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/libxlua.so.meta new file mode 100644 index 0000000..54824b1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/libxlua.so.meta @@ -0,0 +1,76 @@ +fileFormatVersion: 2 +guid: 9f19d785ae44ddc478a08a87ccd9dbb2 +timeCreated: 1488352111 +licenseType: Pro +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 0 + settings: + CPU: AnyCPU + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + CPU: x86 + DefaultValueInitialized: true + OS: AnyOS + Linux: + enabled: 1 + settings: + CPU: x86 + Linux64: + enabled: 0 + settings: + CPU: None + LinuxUniversal: + enabled: 1 + settings: + CPU: x86 + OSXIntel: + enabled: 0 + settings: + CPU: None + OSXIntel64: + enabled: 0 + settings: + CPU: None + OSXUniversal: + enabled: 0 + settings: + CPU: None + WP8: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + Win: + enabled: 1 + settings: + CPU: AnyCPU + Win64: + enabled: 0 + settings: + CPU: None + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + iOS: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/xlua.dll b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/xlua.dll new file mode 100644 index 0000000..33b34ac Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/xlua.dll differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/xlua.dll.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/xlua.dll.meta new file mode 100644 index 0000000..5295052 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86/xlua.dll.meta @@ -0,0 +1,74 @@ +fileFormatVersion: 2 +guid: 79f5c811b2e4e444ab2d97cad5cfd934 +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 0 + settings: + CPU: AnyCPU + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + CPU: x86 + DefaultValueInitialized: true + OS: Windows + Linux: + enabled: 1 + settings: + CPU: x86 + Linux64: + enabled: 0 + settings: + CPU: None + LinuxUniversal: + enabled: 0 + settings: + CPU: x86 + OSXIntel: + enabled: 1 + settings: + CPU: AnyCPU + OSXIntel64: + enabled: 0 + settings: + CPU: None + OSXUniversal: + enabled: 0 + settings: + CPU: x86 + WP8: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + Win: + enabled: 1 + settings: + CPU: AnyCPU + Win64: + enabled: 0 + settings: + CPU: None + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + iOS: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64.meta new file mode 100644 index 0000000..f0c2343 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 8dba1dfb80e5b7d40bd214fc4ed2ed6b +folderAsset: yes +timeCreated: 1451020766 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/libxlua.so b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/libxlua.so new file mode 100644 index 0000000..dec3ab0 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/libxlua.so differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/libxlua.so.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/libxlua.so.meta new file mode 100644 index 0000000..08a7487 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/libxlua.so.meta @@ -0,0 +1,76 @@ +fileFormatVersion: 2 +guid: 1055830ddb882704fa71275ed9b2a78d +timeCreated: 1488352111 +licenseType: Pro +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 0 + settings: + CPU: AnyCPU + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: AnyOS + Linux: + enabled: 0 + settings: + CPU: None + Linux64: + enabled: 1 + settings: + CPU: x86_64 + LinuxUniversal: + enabled: 1 + settings: + CPU: x86_64 + OSXIntel: + enabled: 0 + settings: + CPU: None + OSXIntel64: + enabled: 0 + settings: + CPU: None + OSXUniversal: + enabled: 0 + settings: + CPU: None + WP8: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + Win: + enabled: 0 + settings: + CPU: None + Win64: + enabled: 1 + settings: + CPU: AnyCPU + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + iOS: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/xlua.dll b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/xlua.dll new file mode 100644 index 0000000..1b2e9a1 Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/xlua.dll differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/xlua.dll.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/xlua.dll.meta new file mode 100644 index 0000000..1800589 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/x86_64/xlua.dll.meta @@ -0,0 +1,74 @@ +fileFormatVersion: 2 +guid: abe4c5ca91772ea4fae0ae15603c10e4 +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 0 + settings: + CPU: AnyCPU + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + Linux: + enabled: 0 + settings: + CPU: None + Linux64: + enabled: 1 + settings: + CPU: x86_64 + LinuxUniversal: + enabled: 0 + settings: + CPU: x86_64 + OSXIntel: + enabled: 0 + settings: + CPU: None + OSXIntel64: + enabled: 1 + settings: + CPU: AnyCPU + OSXUniversal: + enabled: 0 + settings: + CPU: x86_64 + WP8: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + Win: + enabled: 0 + settings: + CPU: None + Win64: + enabled: 1 + settings: + CPU: AnyCPU + WindowsStoreApps: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + iOS: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle.meta new file mode 100644 index 0000000..d365404 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle.meta @@ -0,0 +1,58 @@ +fileFormatVersion: 2 +guid: e6a34038df77e48438826b6ff94aa69e +folderAsset: yes +PluginImporter: + serializedVersion: 1 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + platformData: + Android: + enabled: 0 + settings: + CPU: AnyCPU + Any: + enabled: 0 + settings: {} + Editor: + enabled: 1 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: OSX + Linux: + enabled: 0 + settings: + CPU: x86 + Linux64: + enabled: 0 + settings: + CPU: x86_64 + OSXIntel: + enabled: 1 + settings: + CPU: AnyCPU + OSXIntel64: + enabled: 1 + settings: + CPU: AnyCPU + OSXUniversal: + enabled: 1 + settings: + CPU: AnyCPU + Win: + enabled: 0 + settings: + CPU: AnyCPU + Win64: + enabled: 0 + settings: + CPU: AnyCPU + iOS: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents.meta new file mode 100644 index 0000000..e91d546 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 7e4b7549f5e4a4e71806e3ec8e428b15 +folderAsset: yes +timeCreated: 1457422691 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/Info.plist b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/Info.plist new file mode 100644 index 0000000..58e116f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/Info.plist @@ -0,0 +1,46 @@ + + + + + BuildMachineOSBuild + 15G31 + CFBundleDevelopmentRegion + en + CFBundleExecutable + xlua + CFBundleIdentifier + com.xlua + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + xlua + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 1 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 7D1014 + DTPlatformVersion + GM + DTSDKBuild + 15E60 + DTSDKName + macosx10.11 + DTXcode + 0731 + DTXcodeBuild + 7D1014 + NSHumanReadableCopyright + Copyright @2017 THL A29 Limited, a Tencent company. All rights reserved. + + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/Info.plist.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/Info.plist.meta new file mode 100644 index 0000000..30460d4 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/Info.plist.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ac30af4fb2add4d41a9f50fe4f8292a3 +timeCreated: 1457422749 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS.meta new file mode 100644 index 0000000..75f7610 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c9d8e68fa0fd1465294f1255f6ed8563 +folderAsset: yes +timeCreated: 1457422691 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS/xlua b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS/xlua new file mode 100644 index 0000000..044722b Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS/xlua differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS/xlua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS/xlua.meta new file mode 100644 index 0000000..57a253b --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Plugins/xlua.bundle/Contents/MacOS/xlua.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6f3b1cda03ac84924b1ee0595fc019f5 +timeCreated: 1457422749 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes.meta new file mode 100644 index 0000000..aa32a31 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f60dd9a666ae03a40ad2affbbada3ff8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composite.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composite.cs new file mode 100644 index 0000000..a96038c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composite.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WUG.BehaviorTreeVisualizer +{ + public abstract class Composite : Node + { + //constructor + protected Composite() { } + protected Composite(string name, params Node[] nodes) + { + Name = name; + + children.AddRange(nodes.ToList()); + } + + protected void ShuffleNodes() => children = children.OrderBy(g => Guid.NewGuid()).ToList(); + + protected void WeightedShuffleNodes(List<(int, Node)> nodeWeights) + { + //get node list copy + List<(int, Node)> availableNodes = new List<(int, Node)>(nodeWeights.OrderBy(g => Guid.NewGuid())); + + //new child list + List newChildList = new List(); + + //build new list + while (availableNodes.Count > 0) + { + foreach ((int, Node) node in availableNodes) + { + //check if selection + if (UnityEngine.Random.Range(0, availableNodes.Sum(w => w.Item1)) < node.Item1) + { + //add child and remove from pool + newChildList.Add(node.Item2); + availableNodes.Remove(node); + break; + } + } + } + + //update list + children = newChildList.ToList(); + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composite.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composite.cs.meta new file mode 100644 index 0000000..965d3ea --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composite.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0b8c206b739a8d4fad35fc04a8bd35d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites.meta new file mode 100644 index 0000000..69171f7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 064f0c8e28df8804dbeb80025e639c3f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSelector.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSelector.cs new file mode 100644 index 0000000..20a8264 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSelector.cs @@ -0,0 +1,24 @@ +namespace WUG.BehaviorTreeVisualizer +{ + public class AlwaysRandomSelector : Selector + { + /// + /// Shuffles the child nodes every time it runs for the first time + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Children nodes to run + public AlwaysRandomSelector(string name, params Node[] nodes) : base(name, nodes) + { + ShuffleNodes(); + } + + /// + /// Shuffle nodes after reset + /// + protected override void OnReset() + { + base.OnReset(); + ShuffleNodes(); + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSelector.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSelector.cs.meta new file mode 100644 index 0000000..82971c8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22ef0b50ddd82b4408608e5aa78b6c3e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSequence.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSequence.cs new file mode 100644 index 0000000..5ca3cf0 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSequence.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WUG.BehaviorTreeVisualizer +{ + public class AlwaysRandomSequence : Sequence + { + + /// + /// Shuffles the child nodes every time it runs for the first time + /// + /// + /// + public AlwaysRandomSequence(string name, params Node[] nodes) : base(name, nodes) + { + ShuffleNodes(); + } + + /// + /// Shuffle nodes after reset + /// + protected override void OnReset() + { + base.OnReset(); + ShuffleNodes(); + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSequence.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSequence.cs.meta new file mode 100644 index 0000000..0fdeaa1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/AlwaysRandomSequence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 743825f6944091b4b80956fb67d7fa3c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSelector.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSelector.cs new file mode 100644 index 0000000..28332b5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSelector.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WUG.BehaviorTreeVisualizer +{ + public class RandomSelector : Selector + { + /// + /// This selector will shuffle child nodes (once) upon creation + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Children nodes to run + public RandomSelector(string name, params Node[] nodes) : base(name, nodes.OrderBy(g => Guid.NewGuid()).ToArray()) { } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSelector.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSelector.cs.meta new file mode 100644 index 0000000..8566484 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f11d911efde49804191d662d6b4561fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSequence.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSequence.cs new file mode 100644 index 0000000..70a984f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSequence.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WUG.BehaviorTreeVisualizer +{ + public class RandomSequence : Sequence + { + /// + /// This sequence will shuffle child nodes (once) upon creation + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Children nodes to run + public RandomSequence(string name, params Node[] nodes) : base(name, nodes.OrderBy(g => Guid.NewGuid()).ToArray()) { } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSequence.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSequence.cs.meta new file mode 100644 index 0000000..62a8aa5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/RandomSequence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 299e536a768f5774c9ebc98a83271b4e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Selector.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Selector.cs new file mode 100644 index 0000000..69b9262 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Selector.cs @@ -0,0 +1,47 @@ +namespace WUG.BehaviorTreeVisualizer +{ + public class Selector : Composite + { + int currentChild = 0; + + /// + /// Runs each child until one of them returns status Success. Will return failure if no child runs successfully. + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Children node(s) to run + public Selector(string name, params Node[] childNodes) : base(name, childNodes) { } + public Selector() { } + protected override void OnReset() + { + currentChild = 0; + + for (int i = 0; i < children.Count; i++) + { + (children[i] as Node).Reset(); + } + } + + protected override NodeStatus OnRun() + { + if (currentChild >= children.Count) + { + return NodeStatus.Failure; + } + + NodeStatus nodeStatus = (children[currentChild]as Node).Run(); + + switch (nodeStatus) + { + case NodeStatus.Failure: + currentChild++; + break; + case NodeStatus.Success: + return NodeStatus.Success; + } + + //in progress + return NodeStatus.Running; + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Selector.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Selector.cs.meta new file mode 100644 index 0000000..29430b7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Selector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 819653c6ba2cd164b911bdb6de54f32a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Sequence.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Sequence.cs new file mode 100644 index 0000000..ab5acaa --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Sequence.cs @@ -0,0 +1,54 @@ +namespace WUG.BehaviorTreeVisualizer +{ + public class Sequence : Composite + { + private int _currentChildIndex = 0; + + /// + /// A sequence will continue to run as long as all children return the status of Running or Success. + /// It will return a status code of Failure if any children return status Failure. + /// It will only return status of Success once all children have returned a status of Success. + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Children node(s) to run + public Sequence(string name, params Node[] nodes) : base(name, nodes) { } + public Sequence() { } + protected override void OnReset() + { + _currentChildIndex = 0; + + for (int i = 0; i < children.Count; i++) + { + (children[i] as Node).Reset(); + } + } + + protected override NodeStatus OnRun() + { + //Check the status of the last child + NodeStatus childNodeStatus = (children[_currentChildIndex] as Node).Run(); + + //Evaluate the current child node. If it's failed - sequence should fail. + switch (childNodeStatus) + { + //Child failed - return failure + case NodeStatus.Failure: + return childNodeStatus; + //It succeeded - move to the next child + case NodeStatus.Success: + _currentChildIndex++; + break; + } + + //All children have run successfully - return success + if (_currentChildIndex >= children.Count) + { + return NodeStatus.Success; + } + + //The child was a success but we still have more to do - so call this method again. + return childNodeStatus == NodeStatus.Success ? OnRun() : NodeStatus.Running; + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Sequence.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Sequence.cs.meta new file mode 100644 index 0000000..969abc8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Composites/Sequence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09ae5e16e9e3578478c25c1bfca30e85 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Condition.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Condition.cs new file mode 100644 index 0000000..b8075c5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Condition.cs @@ -0,0 +1,12 @@ +namespace WUG.BehaviorTreeVisualizer +{ + public abstract class Condition : Node + { + + public Condition(string name) + { + Name = name; + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Condition.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Condition.cs.meta new file mode 100644 index 0000000..767f4c9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Condition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 505e0bc15115ad545ab012b98b7e4e0a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorator.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorator.cs new file mode 100644 index 0000000..2a37074 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorator.cs @@ -0,0 +1,14 @@ +namespace WUG.BehaviorTreeVisualizer +{ + public abstract class Decorator : Node + { + public Decorator() { } + public Decorator(string name, Node node=null) + { + Name = name; + if(node !=null) + children.Add(node); + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorator.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorator.cs.meta new file mode 100644 index 0000000..85caeab --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eaf0ef9f348ce6449b1ff56851657f57 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators.meta new file mode 100644 index 0000000..6d5167a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 74cc74d355e590742b2a8a84b68ba455 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Delay.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Delay.cs new file mode 100644 index 0000000..da933b0 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Delay.cs @@ -0,0 +1,58 @@ +using Disguise.Behaviors; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using WUG.BehaviorTreeVisualizer; + + +namespace Disguise.Behaviors.Decorators +{ + public class Delay : Decorator + { + private float m_StartTime; + private bool m_UseFixedTime; + private float m_TimeToWait; + + /// + /// Executes a timer and then runs the child node once + /// + /// Node to run + /// Amount of time to wait in seconds + /// Whether to use Time.fixedTime (true) or Time.time (false) + public Delay(float timeToWait, Node node, bool useFixedTime = false) : base($"Runs after {timeToWait}", node) + { + m_UseFixedTime = useFixedTime; + m_TimeToWait = timeToWait; + } + + protected override void OnReset() { } + protected override NodeStatus OnRun() + { + if (children.Count == 0 || children[0] == null) + { + return NodeStatus.Failure; + } + + float elapsedTime = Time.fixedTime - m_StartTime; + + if (IsFirstEvaluation) + { + StatusReason = $"Starting timer for {m_TimeToWait}"; + m_StartTime = m_UseFixedTime ? Time.fixedTime : Time.time; + } + else if (elapsedTime > m_TimeToWait) + { + NodeStatus originalStatus = (children[0] as Node).Run(); + StatusReason = $"Timer complete - Child node status is: { originalStatus}"; + + return originalStatus; + } + + StatusReason = $"Timer is {elapsedTime} out of {m_TimeToWait}."; + return NodeStatus.Running; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Delay.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Delay.cs.meta new file mode 100644 index 0000000..35bdc9c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Delay.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 789de3b2ef1b99145b991d1dbf75e908 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Inverter.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Inverter.cs new file mode 100644 index 0000000..0fb041f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Inverter.cs @@ -0,0 +1,39 @@ +using UnityEngine; + +namespace WUG.BehaviorTreeVisualizer +{ + public class Inverter : Decorator + { + /// + /// Inverts the final result of the node - Success will return failure and failure will return success. + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Node to alter + public Inverter(string name, Node childNode) : base(name, childNode) { } + public Inverter() { } + protected override void OnReset() { } + + protected override NodeStatus OnRun() + { + + if (children.Count == 0 || children[0] == null) + { + return NodeStatus.Failure; + } + + NodeStatus originalStatus = (children[0] as Node).Run(); + + switch (originalStatus) + { + case NodeStatus.Failure: + return NodeStatus.Success; + case NodeStatus.Success: + return NodeStatus.Failure; + } + + "Inverter decorator has failed".BTDebugLog(); + return originalStatus; + + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Inverter.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Inverter.cs.meta new file mode 100644 index 0000000..c87b4da --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Inverter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5fbef5b1de35c3f46aa3db2ec9c048fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Repeater.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Repeater.cs new file mode 100644 index 0000000..4256872 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Repeater.cs @@ -0,0 +1,50 @@ +namespace WUG.BehaviorTreeVisualizer +{ + + public class Repeater : Decorator + { + private readonly int _repeatCount; + + /// + /// Run the child node a specified amount of times before exiting + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Node to run + /// Amount of times to run + public Repeater(string name, Node childNode, int repeatCount = 0) : base(name, childNode) + { + _repeatCount = repeatCount; + } + + protected override void OnReset() { } + + protected override NodeStatus OnRun() + { + if (children.Count == 0 || children[0] == null) + { + return NodeStatus.Failure; + } + + //update child + NodeStatus returnStatus = (children[0] as Node).Run(); + + //stop if this is a count-limited repeat + if (_repeatCount > 0 && _repeatCount == EvaluationCount) + { + return NodeStatus.Failure; + } + + //otherwise return child state + if (returnStatus == NodeStatus.Running) + { + return NodeStatus.Success; + } + + //finally reset + Reset(); + (children[0] as Node).Reset(); + + return NodeStatus.Success; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Repeater.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Repeater.cs.meta new file mode 100644 index 0000000..9da4c62 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Repeater.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 466b3bf3985b6b241b8777ef1d4fe0ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Succeeder.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Succeeder.cs new file mode 100644 index 0000000..711eac3 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Succeeder.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace WUG.BehaviorTreeVisualizer +{ + public class Succeeder : Decorator + { + /// + /// Returns Running status if running otherwise Success - Never failure. + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Child to run + public Succeeder(string nodeName, Node childNode) : base(nodeName, childNode) { } + + protected override void OnReset() { } + + protected override NodeStatus OnRun() + { + return (children[0] as Node).Run() == NodeStatus.Running ? NodeStatus.Running : NodeStatus.Success; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Succeeder.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Succeeder.cs.meta new file mode 100644 index 0000000..163edad --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Succeeder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86d2cee542884cf4ba1d1c29897ba6ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Timer.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Timer.cs new file mode 100644 index 0000000..821ffae --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Timer.cs @@ -0,0 +1,57 @@ +using UnityEngine; + +namespace WUG.BehaviorTreeVisualizer +{ + + public class Timer : Decorator + { + private float m_StartTime; + private bool m_UseFixedTime; + private float m_TimeToWait; + + /// + /// Run the child node a specified amount of time in seconds before exiting + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Node to run + /// Amount of time to wait in seconds + /// Whether to use Time.fixedTime (true) or Time.time (false) + public Timer(float timeToWait, Node node, bool useFixedTime = false) : base($"Timer for {timeToWait}", node) + { + m_UseFixedTime = useFixedTime; + m_TimeToWait = timeToWait; + } + public Timer(float timeToWait, bool useFixedTime = false) : base($"Timer for {timeToWait}") + { + m_UseFixedTime = useFixedTime; + m_TimeToWait = timeToWait; + } + + protected override void OnReset() { } + protected override NodeStatus OnRun() + { + if (children.Count == 0 || children[0] == null) + { + return NodeStatus.Failure; + } + + NodeStatus originalStatus = (children[0] as Node).Run(); + float elapsedTime = Time.fixedTime - m_StartTime; + + if (IsFirstEvaluation) + { + StatusReason = $"Starting timer for {m_TimeToWait}. Child node status is: {originalStatus}"; + m_StartTime = m_UseFixedTime ? Time.fixedTime : Time.time; + } + else if (elapsedTime > m_TimeToWait) + { + StatusReason = $"Timer complete - Child node status is: { originalStatus}"; + return NodeStatus.Success; + } + + StatusReason = $"Timer is {elapsedTime} out of {m_TimeToWait}. Child node status is: {originalStatus}"; + return NodeStatus.Running; + + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Timer.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Timer.cs.meta new file mode 100644 index 0000000..3f2ce3d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/Timer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0ec2635993bf180449361c55ac04afeb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/UntilFail.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/UntilFail.cs new file mode 100644 index 0000000..ba4a41c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/UntilFail.cs @@ -0,0 +1,21 @@ + + +namespace WUG.BehaviorTreeVisualizer +{ + public class UntilFail : Decorator + { + /// + /// Continues to run the child node unless the child returns a status of Failure. + /// + /// Friendly name - displayed on the Behavior Tool Debugger UI if set + /// Child to run + public UntilFail(string nodeName, Node childNode) : base(nodeName, childNode) { } + protected override void OnReset() { } + + protected override NodeStatus OnRun() + { + return (children[0] as Node).Run() == NodeStatus.Failure ? NodeStatus.Failure : NodeStatus.Running; + + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/UntilFail.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/UntilFail.cs.meta new file mode 100644 index 0000000..4561392 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Decorators/UntilFail.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3391bc93df7aed547962596cb51564a7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Node.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Node.cs new file mode 100644 index 0000000..281d9b7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Node.cs @@ -0,0 +1,55 @@ +using System; + +namespace WUG.BehaviorTreeVisualizer +{ + [Serializable] + public abstract class Node : NodeBase + { + public int EvaluationCount; + public bool DebugNodeStatus = false; + public bool IsFirstEvaluation => EvaluationCount == 0; + private string m_LastStatusReason { get; set; } = ""; + + /// + /// Call on the base part of the Behavior tree to trigger the evaluation of all nodes + /// + public virtual NodeStatus Run() + { + NodeStatus nodeStatus = OnRun(); + + if (LastNodeStatus != nodeStatus || !m_LastStatusReason.Equals(StatusReason)) + { + LastNodeStatus = nodeStatus; + m_LastStatusReason = StatusReason; + OnNodeStatusChanged(this); + } + + EvaluationCount++; + + if (nodeStatus != NodeStatus.Running) + { + Reset(); + } + + return nodeStatus; + } + + /// + /// Execute the reset logic for the node + /// + public void Reset() + { + EvaluationCount = 0; + OnReset(); + } + + /// + /// Contains the custom logic for the node + /// + /// + protected abstract NodeStatus OnRun(); + protected abstract void OnReset(); + + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Node.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Node.cs.meta new file mode 100644 index 0000000..4a848ec --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/Node.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5168ecbedaf6a344da99f34694914294 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/README.md b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/README.md new file mode 100644 index 0000000..6ae9d80 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/README.md @@ -0,0 +1,41 @@ + +# Standard Behavior Tree Nodes +This sample project contains a set of standard behavior tree nodes that can be used for your game. Here's what you need to know: + +1. There are 11 specialized composite and decorator nodes +2. When creating new nodes, make sure to inherit from `Composite`, `Condition` and `Decorator` when creating new nodes of those types. +3. Action/Leaf nodes can be inherited from `Node` directly. +4. A settings file has been included but needs to be moved to **Behavior Tree Visuallizer (Beta)\Resources** for the tool to pick it up. + +## General +There are two general node types: + +| Name | Description | +|----------- |--------------------------------------------------------------------------------------------------------------------------------------------------- | +| Node | Base class for all node types - Everything should ultimately derive from this. | +| Condition | Base class for all condition node types. Does not do anything special. Exists so that you can stylize all conditions in the tool easily. | + +## Composites +Composites are essentially instructions for your behavior tree on how it should run a group of child nodes. + +| Name | Description | +|---------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Composite | Base class for all composite node types. | +| Selector | Runs each child until one of them returns status Success. Will return failure if no child runs successfully. | +| RandomSelector | Shuffles the child nodes the first time the behavior tree is constructed (only once). Executes the same as `Selector` | +| AlwaysRandomSelector | Shuffles the child nodes every time it runs for the first time. Executes the same as `Selector`. | +| Sequence | Will continue to run if all children return the status of Running or Success. Return a status code of Failure if any children return status Failure. Returns status code of Success if all children return Success. | +| RandomSequence | Shuffles the child nodes the first time the behavior tree is constructed (only once). Executes the same as `Sequence`. | +| AlwaysRandomSequence | Shuffles the child nodes every time it runs for the first time. Executes the same as `Sequence`. | + +## Decorators +Decorators are a way to alter how an individual node is run. These can range from changing the return status code (`Inverter`) to defining how many times to excute (`Repeater`). + +| Name | Description | +|----------- |------------------------------------------------------------------------------------------------------------- | +| Decorator | Base class for all decorator node types. Supports a single child. | +| Inverter | Inverts the result of the node - `Success` will return `Failure` and `Failure` will return `Success`. | +| Repeater | Run the child node a specified amount of times before exiting. | +| Succeeder | Returns `Running` status if running otherwise returns the `Success` status. Never the `failure` status. | +| Timer | Run the child node a specified amount of time in seconds. | +| UntilFail | Continues to run the child node until the child returns a status of `Failure`. | \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/README.md.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/README.md.meta new file mode 100644 index 0000000..472d827 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 33f510ffbc4eecf4ca4e7e0ebc8b8b6a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/settings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/settings.asset new file mode 100644 index 0000000..f337527 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/settings.asset @@ -0,0 +1,63 @@ +%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: 97748ca66d1b7b3448e205f8a48a42e1, type: 3} + m_Name: settings + m_EditorClassIdentifier: + DimLevel: 121.73077 + BorderHighlightColor: {r: 0.40864503, g: 1, b: 0, a: 1} + EnableMiniMap: 0 + RunningIcon: {fileID: 21300000, guid: e5b1b229d2a13eb48a686864c4c7c993, type: 3} + SuccessIcon: {fileID: 21300000, guid: cdc83b1ed0823ff41805968d8a49da64, type: 3} + FailureIcon: {fileID: 21300000, guid: a12f0f96f8cacf0408b24a9bb943d66b, type: 3} + DefaultStyleProperties: + Script: {fileID: 0} + TitleBarColor: {r: 0.09411765, g: 0.70980394, b: 0.9137255, a: 1} + Icon: {fileID: 21300000, guid: b672344d83977ea4b92d823b96fa1425, type: 3} + IsDecorator: 0 + InvertResult: 0 + MainStyleProperties: + - Script: {fileID: 11500000, guid: eaf0ef9f348ce6449b1ff56851657f57, type: 3} + TitleBarColor: {r: 0, g: 0, b: 0, a: 1} + Icon: {fileID: 21300000, guid: 56c998e2f5df7684f8ecb19785c5b678, type: 3} + IsDecorator: 1 + InvertResult: 0 + - Script: {fileID: 11500000, guid: 505e0bc15115ad545ab012b98b7e4e0a, type: 3} + TitleBarColor: {r: 1, g: 0.8286116, b: 0, a: 1} + Icon: {fileID: 21300000, guid: 4b0d0df25c6b3e74b84791a68af268a5, type: 3} + IsDecorator: 0 + InvertResult: 0 + OverrideStyleProperties: + - Script: {fileID: 11500000, guid: 819653c6ba2cd164b911bdb6de54f32a, type: 3} + TitleBarColor: {r: 1, g: 0, b: 0.6379585, a: 1} + Icon: {fileID: 21300000, guid: 28fe4a2dbaf436c43afef5207096676c, type: 3} + IsDecorator: 0 + InvertResult: 0 + - Script: {fileID: 11500000, guid: 09ae5e16e9e3578478c25c1bfca30e85, type: 3} + TitleBarColor: {r: 1, g: 0, b: 0.6392157, a: 1} + Icon: {fileID: 21300000, guid: 8988c62742731474c966510270e6c45c, type: 3} + IsDecorator: 0 + InvertResult: 0 + - Script: {fileID: 11500000, guid: 5fbef5b1de35c3f46aa3db2ec9c048fc, type: 3} + TitleBarColor: {r: 0, g: 0, b: 0, a: 1} + Icon: {fileID: 21300000, guid: 314cb246bc81bf04cb7e73b250e47a68, type: 3} + IsDecorator: 1 + InvertResult: 1 + - Script: {fileID: 11500000, guid: 0ec2635993bf180449361c55ac04afeb, type: 3} + TitleBarColor: {r: 0, g: 0, b: 0, a: 1} + Icon: {fileID: 21300000, guid: caca494ba8dd66e4b9778df5ecae5910, type: 3} + IsDecorator: 1 + InvertResult: 0 + - Script: {fileID: 11500000, guid: d9ae14b7ddb461a46928129cfdaab857, type: 3} + TitleBarColor: {r: 0.9056604, g: 0.021359911, b: 0.895257, a: 1} + Icon: {fileID: 21300000, guid: b672344d83977ea4b92d823b96fa1425, type: 3} + IsDecorator: 0 + InvertResult: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/settings.asset.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/settings.asset.meta new file mode 100644 index 0000000..b26f7c4 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/Standard Nodes/settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ed02e1726cb4d384ebf55df5e52f96cd +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua.meta new file mode 100644 index 0000000..5f19941 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5cc99c2bdeceaba4ca7061d5279df704 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/CHANGELOG.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/CHANGELOG.txt new file mode 100644 index 0000000..5956f87 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/CHANGELOG.txt @@ -0,0 +1,487 @@ +v2.1.15 2020年6月24日 +新增特性 +1、生成代码过滤器 +2、优化反射查找delegate匹配bridge的性能 +3、unity 2019.2以上版本手机版本注入不了的问题 + +变更 + +bug修复 +1、反射查找同名delegate桥接在不生成代码的时候表现不一致 +2、嵌套struct标注为PackAsTable时生成代码报错 +3、反射wrap代码加入栈空间检查 +4、如果枚举定义了很多个值(几千个),会触发unity在android下的一个bug:函数体很大而且有很多分支,执行该函数会crash +5、chunkname和脚本文件名不一致的问题 +6、最小生成模式枚举生成代码报错 +7、当采用反射方式注册枚举值时,如果一个枚举有多个相同的值,比如A,B都是1,那么在lua里头访问B将会为空 +8、sbyte[]在.net 4下push到lua变成字符串的问题 +9、泛型导致生成代码失败的问题 +10、非Assembly-CSharp程序集注入时,out参数处理有误 +11、内嵌类通过xlua.private_accessible设置私有访问可能失败的问题 +12、cecil插入指令后,并未自动更新offset,某种情况下会导致计算偏移量错误 + + +v2.1.14 2019年2月27日 +新增特性 +1、新增nintento switch的支持 +2、unity 2018兼容 +3、android arm64支持 +4、原生库的visual studio 2017编译支持 +5、增加“XLua/Generate Minimize Code”菜单 +6、防止有的工程有非法的dll导致生成代码中断 +7、更高效的lua_pushstring(需要通过NATIVE_LUA_PUSHSTRING开启) + +变更 +1、window库默认编译器改为visual studio 2017 + +bug修复 +1、修正枚举类型如果只加GCOptimize不加LuaCallCSharp会crash的问题 +2、示例配置加入对Edtitor类的过滤 +3、UWP兼容修复 +4、接口继承引入的同签名方法实现 +5、未生成代码,extension方法行为不一致 +6、修复Nullable类型参数,如果最后一个参数是nil,会导致其他参数全是nil的问题 + + +v2.1.13 2018年12月5日 +新增特性 +1、新增AdaptByDelegate注入模式; +2、新增xlua.get_generic_method,用于调用泛型函数; +3、支持类似CS.System.Collections.Generic.List(CS.System.Int32)的泛型写法; +4、注入新选项:忽略编译器自动生成代码,以及不生成base代理; +5、针对lua编程以及热补丁,均添加直接可用的自动化配置样例; +6、新增luajit的gc64支持; +7、加入兼容字节码(一份字节码支持32位和64位系统)的支持; +8、内置新lua内存泄漏检测工具; +9、delegate桥接动态实例化:delegate是4个参数以内,参数均引用类型,无返回值或者返回引用类型,不用配置CSharpCallLua也能调用lua函数; +10、提供util.print_func_ref_by_csharp函数,用于查看当前被C#引用的lua函数; +11、支持无CS全局变量的工作方式; + + +变更 +1、虚拟机升级:lua5.3.4 -> lua5.3.5,luajit2.1b2 -> luajit2.1b3; +2、delegate bridge代码段占用优化; +3、改为PostProcessBuild事件检查是否生成代码; +4、适配xcode 10:osx平台不再支持32bit版本构建; +5、名字空间、类名拼写错误时,对静态成员的设置会报错; +6、防止CS全局table被删除导致xlua工作异常; +7、Windows下构建lib,若使用vs 2015参数执行cmake失败,则继续尝试使用vs 2017; +8、编辑器下不生成代码时,也检查Blacklist,维持和运行时一致; + +bug修复 +1、泛型的数组生成代码报错; +2、防止对TypeExtensions配置了LuaCallCSharp后,lua里头IsValueType之类的判断永真; +3、生成代码过滤掉含指针的函数和字段; +4、适应索引器属性名不是Item的情况; +5、解决attribute初始化异常会导致生成代码,注入终止的问题; +6、精简模式下空Enum生成代码错误; +7、通过把初始化函数分割成小函数,规避unity在android下执行大函数crash的bug; +8、Assignable处理obj为null情况; +9、内嵌类不Obsolete,但外层类Obsolete的生成代码报错 +10、解决inline注入方式下,如果lua逻辑跑异常,看不到异常信息的问题; +11、修复xlua.private_accessible访问后,同名public的方法无法访问的Bug; +12、[Out]修饰的参数不应该生成out关键字; +13、通过反射查找合适的适配器时,有可能访问到非适配器函数; +14、精简模式导出代码无get_Item、set_Item; +15、IntKey方式下不自动xlua.private_accessible的问题; + + +v2.1.12 2018年7月9日 +新增特性 +1、Nullable的支持 +2、支持Assembly-CSharp之外的dll注入(beta) +3、执行xlua.hotfix,会自动让该类private能访问 +4、xlua.private_accessible优化:1、会把基类的也设置能私有访问;2、延迟到第一次访问类才私有化 +5、新增xlua.util.state,可为一个c#对象新增状态 +6、this[string field]或者this[object field]操作符重载新增get_Item和set_Item调用 +7、正在编译时注入打印error信息 +8、interface配置到CSharpCallLua时的事件跟索引映射的自动实现 +9、unity5.5以上去掉WARNING: The runtime version supported by this application is unavailable打印 + +变更 +1、去除Stateful方式(因为xlua.util.state已经可以达成类似的效果) +2、废弃掉内嵌模式模式 + +bug修复 +1、生成代码局部变量加下划线,防止符号冲突 +2、如果类没放到Hotfix列表,不生成base调用代理 +3、代码重构,可读性优化 +4、解决带params byte[]可能会导致生成代码编译错误的问题 +5、解决类含有private event的时候,无法xlua.private_accessible的问题 +6、构造函数注入,如果branch外紧跟Ret指令,注入逻辑应该在branch以及Ret之间 +7、构造函数注入,如果注入指令后导致跳转范围大于一个字节,应修改为长跳转 +8、解决一个delegate如果不是某个类的内嵌类型时,CS.namespace.classname为空的问题 +9、防止Editor下的Util类名字冲突 +10、泛型override有异常,先过滤掉 +11、解决空enum导致生成代码编译错误 +12、解决uwp平台下il2cpp方式打包无法访问任何类的问题 +13、hotfix一个私有类型的params参数的函数,导致生成代码编译错误、注入失败的问题 +14、如果两个LuaBase指向的是同一个Lua对象,GetHashCode应该返回的是同一个值 +15、[Out]标记参数生成代码编译失败 +16、交错数组+多维数组的复合,生成代码报错的问题 + +v2.1.11 2018年3月20日 +新增特性 +1、xlua.private_accessible支持私有内嵌类型 +2、添加xlua.release,用于主动解除lua对c#某对象的引用 +3、支持内嵌委托的显示构造 +4、需要传class的地方(比如xlua.private_accessible),支持传C#的Type对象 +5、支持用pairs遍历IEnumerable对象 +6、热补丁场景下,支持override函数调用被override函数(对应c# base关键字) + +变更 +1、简化property的反射访问,简化后有更好的兼容性; + +bug修复 +1、ios 11兼容(去除system调用) +2、实现了interface的struct不走gc优化代码的问题 +3、emit特性的.net兼容性 +4、emit对于ulong的const值处理不当 +5、interface桥接代码,interface继承时,父interface和子interface有同名不同类型属性时的生成代码报错 +6、多虚拟机下,不断创建和销毁协程时,可能出现协程指针重复 +7、当参数为泛型类型时,如ICollectio时,不应该生成代码 + +v2.1.10 2017年9月18日 +新增特性 +1、新增DoNotGen配置,支持一个类型部分函数用反射,部分用生成; +2、新增wrapper的emit; +3、webgl支持; +4、lua实现interface支持interface继承; +5、window下支持android编译(由xdestiny110提供); +6、打包时,如果没执行过“Generate Code”将报错; + +变更 +1、 async_to_sync的改为resume错误时报错; +2、il2cpp下,暂时去掉泛型的反射调用; +3、升级到lua5.3.4并合入2017-9-1为止所有官方patch; + +bug修复 +1、C#仅声明delegate和MulticastDelegate,通过反射创建lua function映射时crash; +2、解决一些古老版本window(比如xp)的dll兼容问题; + +v2.1.9 2017年8月10日 +新增特性 +1、新增最小生成模式(通过GEN_CODE_MINIMIZE切换),可以节省50%的text段空间; +2、新增xlua.util.createdelegate,支持在lua直接用C#函数创建delegate而不需要通过lua适配; +3、xlua.private_accessible支持public int Prop { get; private set; } +4、新增 xlua.getmetatable、xlua.setmetatable、xlua.setclass、xlua.genaccessor,用以支持lua使用C#类型直接在lua侧完成; +5、反射下扩展方法的支持; +6、lua53版本支持位操作符重载:C#侧的位操作符重载对应到lua的位操作符重载;enum全部加上&和|位操作符; + +工程优化 +1、加入travis持续集成; + +变更 +1、LuaCallCSharp自动去除匿名类型; +2、THREAD_SAFT改为THREAD_SAFE; +3、GenFlag.GCOptimize标记为过时; +4、删除过时的GenConfig配置方式; + +bug修复 +1、window phone下一些系统api是禁用的,源码中去掉; +2、泛型约束是struct的时候,生成代码失败; +3、unity2017 .net 4.6,枚举生成代码报错; + +v2.1.8 2017年6月27日 +新增特性 +1、Hotfix标签添加几个订制参数:ValueTypeBoxing、IgnoreProperty、IgnoreNotPublic、Inline、IntKey +2、Hotfix代码注入优化,减少text段占用; +3、Hotfix配置支持放Editor目录,可以减少text段占用; +4、支持以指定类型传递object参数; +5、反射调用Obsolete方法在Editor下打印warning; + +变更 + +bug修复 +1、pinvoke独立设置的In,Out属性可能导致生成代码失败; +2、如果业务在全局名字空间有和xLua名字空间的同名类,生成代码编译失败; + +v2.1.7 2017年5月17日 +新增特性 +1、支持发布UWP(含HoloLens,Xbox one,Win10 Mobile、Win10 PC)应用; +2、支持对lua源代码ras+sha1签名; +3、如果没安装Tools提示“please install the Tools”; +4、linxu版本的支持; +5、支持bitcode打包; +6、对所有struct新增无参数构造函数; +7、delegate的参数名改为p0到pn,防止hotfix时业务代码变量和生成代码冲突; +8、支持对成员名为C#关键字的情况; +9、新增util.loadpackage,和require类似,通过searcher加载文件,不同的是,它不执行,而且也不会cache到package.loaded; +10、优化模版引擎大文件的生成性能; +11、新增不需要生成代码的注入方式; +12、支持构造函数参数带ref和out修饰符; +13、构造函数也支持黑名单排除; + +变更 +1、this[object field]操作符重载; +2、反射的数据转换规则改成和生成代码一致; +3、忽略掉匿名类及匿名函数的注入; + +bug修复 +1、规避Unity的bug:List,CustomType是当前执行程序集的类型,这在.Net是不需要指明程序集就可以通过Type.GetType得到,但Unity下不行。 +2、解决反射下,可变参数不提供时,传null的问题; +3、继承了另外一个程序集的类型,使用了protected类型会导致注入失败; +4、luajit去掉dlopen和dlsym的调用; +5、解决通用版本的生成代码工具找不到模版的问题; +6、修复通用版本反射导入泛化类型的问题; +7、反射调用含delegate参数的的api,会因为缓存而导致调用LuaEnv.Dispose失败; +8、兼容老版本的C编译器,声明要放开头; +9、生成代码对hotfix的检测算法和注入工具不一致导致的注入失败; +10、注入的nested类型是public,但其的外层类型非public,生成代码报错; +11、析构函数只判断名字可能出现误判; +12、构造函数是非public的,可能会导致找不到适配delegate而注入失败; +13、修正Extension method会在所有子类都生成代码的bug(2.1.6泛化特性引入); +14、构造函数重载,只有一个能hotfix成功; +15、规避一个可能是il2cpp的bug(unity5.4):字符串参数默认值是"",ios下在反射的default value也是Reflection.Missing; +16、将一个table传到List<>,取了最后一个参数,而不是那个table的长度; +17、ldarg指令在这种场景下il2cpp转换时会出现异常:1、采用模版注入;2、从4到255间有一个输出参数;改为兼容性更好的ldarg.s; +18、解决配置了System.Delegate到CSCallLua,执行生成代码会编辑器会crash的问题; +19、扩展函数可能和原来的函数同名,反射实现并未考虑到这种情况; +20、通用版本的可变参数delegate调用异常; +21、unity4规避lua53冲突的方式改为返回null更合适,异常方式会导致IsNull无法正常工作; +22、lua_tostring解码失败改为UTF8解码; + +v2.1.6 2017年3月1日 +新增特性 +1、带约束的泛型支持(by forsakenyang); +2、非Unity的.net环境支持; +3、代码注入支持小工具方式,该方式不用拷贝cecil库,可以解决拷错cecil库版本或者和Unity,VS插件冲突的问题; +4、Hotfix配置支持字段和属性 +5、更方便的Unity协程hotfix +6、在hotfix触发事件; +7、LuaTable添加ForEach方法以及Length属性; +8、cmake生成项目优化:保留源文件目录结构; +9、对已经Dispose的LuaEnv的访问做保护;Dispose时检查callback是否已经都释放,没释放的话报错; +10、支持释放Hotfix回调; + +变更 +1、构造函数改为执行原有逻辑后调用lua; +2、this[string field]操作符重载会影响到继承调用,去掉该特性的支持; +3、编辑器下的代码注入改为手动方式; + +bug修复 +1、防止定义了同时定义get_xx方法以及xx属性的生成代码的重名。 +2、struct注入代码无效; +3、Utils加名字空间,防止和业务冲突; +4、返回定长多维数组的delegate,生成代码可能会冲突; +5、interface,以及编辑器下不生成代码情况下,对可变参数的展开; +6、il2cpp下,如果不生成代码,会报ManifestModule不支持; +7、规避Unity4的bug:访问一个已经被Distroy的UnityEngine.Object,编辑器下会崩溃,这个问题在Unity5,或者luajit版本都不会出现; +8、修改上个版本引入的问题:xlua_setglobal会漏一个值在栈上,这会导致一些32位应用不稳定; +9、当delegate参数只有ref和out的区别的话,报重载冲突; + +v2.1.5 2017年1月13日 + +新增特性 +1、全平台热补丁; +2、新增线程安全模式,可通过THREAD_SAFT宏打开; +3、新增更简便的配置方式,具体参见XLua\Doc下《XLua的配置.doc》; +4、多虚拟机实例时的自动Dispose; +5、内存优化:减少匿名闭包到delegate映射的内存占用;减少LuaFunction以及LuaTable内存占用;减少lua table映射C#interface的gc; +6、生成代码速度优化; +7、支持直接在lua侧clone C#结构体; +8、LuaFunction新增无gc调用api; + +变更 +1、delegate必须都加[CSharpCallLua]才支持C#到lua的回调(以前参数和返回值都相同的delegate只要其中一个加了就可以); +2、加回string/number到枚举的自动转换; + +bug修复 +1、枚举不生成代码时,第一次使用会产生两个不同的userdata; +2、数组和System.Type的相互引用导致System.Type生成代码无法加载; +3、更安全的异常处理,封装lua_setglobal,lua_getglobal的异常,C#回调保证所有C#异常都catch并转换到成lua error。 + + +v2.1.4 2016年11月29日 +新增特性 +1、加了ReflectionUse会自动生成到link.xml,可以防止il2cpp下因stripping导致的反射不可用; +2、开放生成引擎,可二次开发自己生成插件,生成所需的代码或配置; +3、GetInPath和SetInPath无C# gc优化; +4、一个lua table自动转换为带GCOptimize标签的复杂类型以及该复杂类型的一维数组不使用反射,如果这复杂类型是纯值类型,无c# gc; + +变更 +1、基于一致性以及性能的考虑,不支持数字和字符串到枚举的静默转换,须主动调用起类下的__CastFrom; +2、名字空间从LuaInterface改为XLua; +3、LuaTable的几个可能导致gc的api标注为Obsolete; +4、在不指明返回类型的情况下,如果一个number是整数会优先转换成整数; + +bug修复 +1、含能隐式转换int,long,decimal的类型传到lua变成decimal; +2、反射的重载判断,如果可变参数的位置上是一个不匹配的参数,也会判断为匹配成功; +3、可变参数+重载的话,可变部分不传会报无效参数; +4、加了LuaCallCSharp的Extension method,在Editor下不生成代码不可用; + +v2.1.3 2016年11月09日 +新增特性 +1、LuaTable新增Get和Set接口,table操作支持值类型无gc; +2、支持decimal,不丢失精度而且传递到lua无gc; +3、增加LuaEnv.LoadString接口,用于指定返回的delegate类型; +4、例子刷新:新增Helloworld,无GC调用,Lua面向对象,协程例子; +5、enum优化:传递到lua无gc,从int或者string到枚举转换无gc; +6、event的+/-优化:性能提升一倍,而且无gc; +7、生成代码简化; + +变更 +1、uint在lua53映射到lua_Integer; +2、StreamingAssets加载改为优先级最低; + +bug修复 +1、生成代码下,如果LuaTable或者LuaFunction参数为null会抛异常; +2、lua5.3下,浮点到枚举的静默转换失败; +3、反射下struct类型参数带默认值抛异常; +4、lua53下Length返回浮点; + +v2.1.2 2016年10月08日 +新增特性 +1、支持lua5.3,进而支持苹果bitcode,原生64位整数,位运算,utf8等特性; +2、CMake编译,更方便加入第三方插件 +3、数组性能优化,包括访问性能以及gc +4、C#调用lua函数减少一次lua gc; +5、优化启动时间; +6、减少类型加载的gc; +7、优化ObjectPool的内存占用; +8、优化小字符串传入lua的gc; +9、LuaTable添加Cast接口,用于LuaTable到其它类型的转换,比如interface; +10、LuaFunction添加Cast接口,用于LuaFunction到delegate的转换; + +变更 +1、lua内部只有带符号的64整数类型,并增加无符号数库 +2、如果不想对Extension Method生成代码,又希望在反射下用,需要添加ReflectionUse; + +bug修复 +1、对ObjectPool已经Destroy的UnityEngine.Object的引用自动解除功能的内存泄漏问题; +2、规避某些版本(已知是5.3.3)的Unity的bug导致的内存泄漏问题; +3、LuaTable或者LuaFunction做返回值的delegate生成代码可能报错; + +v2.1.1 2016年08月29日 +新增特性 +1、支持编辑器下不用生成代码能运行; +2、新增IntPtr的支持 +3、增加对ObjectPool已经Destroy的UnityEngine.Object的引用自动解除; +4、在LuaEnv添加对lua_gc一些封装; + +bug修复 +1、生成代码传送一个LuaFunction、LuaTable到lua和反射版本不一致,生成代码传送过去是一个C#对象,而反射是Lua函数、table对象,反射的处理更合适; +2、修复同名的静态以及成员方法冲突的问题; +3、修复对interface生成CSharpCallLua代码时,interface含indexer时的报错; +4、修复Editor在运行后会new一个xlua实例的bug; +5、修复通过生成代码调用同时含可变参数和默认值的函数,如果不传参数,将会出错的bug; +6、修复调试时,找不到socket库的bug; + + +变更 +1、反射不做重载方法顺序调整,顺序改为固定且生成代码保持一致; +2、i64加上fade_id,参数传递时更安全; +3、重新加入tdr的from_file的支持; + +v2.1.0 2016年08月08日 +新增特性 +1、满足条件struct传递到lua无gc,struct需要满足什么条件才能被优化呢? +a. struct允许嵌套其它struct,但它以及它嵌套的struct只能包含这几种基本类型:byte、sbyte、short、ushort、int、uint、long、ulong、float、double; +b. struct本身以及使用到该struct的地方需要加LuaCallCSharp,并且加了GCOptimize设置; +2、全新实现的反射机制,更容易和生成代码配合使用 +a. 支持extension methods,Enum.__CastFrom; +b. ios下支持反射使用event; +c. 对类型映射、可变参数调用调整为和生成代码一致; +d. 性能更好,gc更少; +3、生成代码菜单简化,并增加“Generate Minimum”选项; +4、支持生成代码配置文件放Editor目录; + +变更 +1、luajit统一升级成2.1.0b2; +2、luasocket库改为按需加载; +3、重载的string,byte[]参数检查允许为nil; +4、子类访问不触发父类加载; +5、struct的ref参数的修改会修改lua测该参数的值; +6、生成代码加载改为静态(原来是反射); +7、菜单改为更简洁; +8、tdr改为默认不加载; +9、StreamingAssets加载lua改为废弃特性; + +bug修复 +1、参数或者返回值是泛型类的数组,或者是二维数组,生成代码报编译错误; +2、抽象类生成代码报编译错误; +3、消除Clear生成代码的warning; +4、profiler、i64库不支持多实例; + +v2.0.5 2016年05月18日 +新增特性 +1、util.async_to_sync,可以更好的利用lua的协程实现同步编程、异步执行;或者异步等待www等; +2、生成代码的规范度调整,消除一些工具的告警; +bug修复 +1、解决在lua gc移除weak table和调用__gc的时间窗内push同一对象,会生成指向同一C#对象的不同userdata的问题; +2、上版本的的lua内存工具并未打包; +3、修正嵌套类型不能生成代码的问题; + +v2.0.4 2016年05月04日 +新增特性 +1、新增函数调用时长报告功能; +2、新增lua内存泄漏定位工具; +3、lua测加入对64位无符号数的支持; +变更 +1、支持多种delegate绑定到一个clousre。调整之前一个clousre只能对应一种delegate; +bug修复 +1、tdr处理长度为1的数组的错误(本来解包应该是{[1] = {a = 1}}的,却是{{a=1}}); +2、tdr数值处理错误(int的-1会解成一个很大的正数) + +v2.0.3 2016年04月13日 +新功能 +1、添加“Advanced Gen”功能,用户可以自定义生成代码的范围; +2、支持对库生成Static pusher; +变更 +1、LuaTable以及InterfaceBirdage改为触发metatable; +2、Extension Methods不自动加到被扩展类,需要加入生成列表; +3、移除特殊ValueType优化; +bug修复 +1、Extension Methods为私有时,生成代码语法错误; +2、重载函数含ulong时,生成代码语法错误; +3、反射调用时的默认值处理错误; +4、C#向lua传中文字符的长度处理错误; + +v2.0.2 2016年04月06日 +变更 +1、库的生成代码配置支持多份,方便项目的模块化; +2、enum的生成代码合并到一个文件里头; +3、优化异常处理; +4、发布包把库和教程、例子分离,更干净; +5、小bug修改; + +升级指引 +由于文件有点变动,直接覆盖原有lib会报错,需要: +1、删除原来的XLua目录; +2、解压xlua_v2.0.2.zip到Assets下; +3、重新执行代码生成; + +v2.0.1 2016年03月24日 +1、支持C# 的extension methods; +2、lua调试方面的支持; +3、android下require一个不存在的lua文件可能成功的bug; +4、TDR 4 Lua库的更新; +5、多机型的兼容性测试; + +v2.0.0 2016年03月08日 +1、性能优化,性能对比报告请看主页; +2、加入官方lua版本的tdr; +3、支持64位整数; +4、修正lua中对C#异常pcall引发的不稳定; +5、易用性的优化; +6、其它一些bug的修改。 + +1.0.2 2015年12月09日 +1、解决新版本(已知5.2版本)下,streamAssetsPath不允许在构造函数访问导致的bug; +2、新增windows x64版本的支持; +3、对web版本才用到的代码加入条件编译,减少对手机版发布包的影响; +4、生成代码文件名去掉“+”号; +5、删除4.6的生成代码,以免在新版本报引用过时api的错; + +v1.0.1 2015年11月30日 +1、支持pcall捕捉C#异常; +2、新增cast方法,支持这种场景:实现类是internal声明,只提供interface; +3、解决interface下如果有event,生成代码编译报错的bug; +4、解决interface下有Obsolete的方法,字段,生成代码编译报错的bug; +5、解决含private的默认geter/setter生成代码编译报错的bug; +6、修正类在全局空间下生成代码不可用的bug; +7、修正bridge代码返回值处理错误。 + +v1.0.0 2015年03月30日 +第一个版本 \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/CHANGELOG.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/CHANGELOG.txt.meta new file mode 100644 index 0000000..e0d4795 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/CHANGELOG.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d8cb92ef607cec548b2afdc6c1359faf +timeCreated: 1470364015 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor.meta new file mode 100644 index 0000000..2a5da38 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 9a5776ff95549f74abe5f594eec7c8e7 +folderAsset: yes +timeCreated: 1534492498 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor/lua.png b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor/lua.png new file mode 100644 index 0000000..8bae58e Binary files /dev/null and b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor/lua.png differ diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor/lua.png.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor/lua.png.meta new file mode 100644 index 0000000..e3df6bb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Editor/lua.png.meta @@ -0,0 +1,96 @@ +fileFormatVersion: 2 +guid: 27748025a773c054892ea0e4f7dd44b2 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 11 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + vTOnly: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + flipbookRows: 1 + flipbookColumns: 1 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + ignorePngGamma: 0 + applyGammaDecoding: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources.meta new file mode 100644 index 0000000..b22e503 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: a939c908d652da849aa86950b3452dc8 +folderAsset: yes +timeCreated: 1458812833 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf.meta new file mode 100644 index 0000000..6c9312e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: f8cd21d315e09d5409393bb24706f33a +folderAsset: yes +timeCreated: 1461553627 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/memory.lua.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/memory.lua.txt new file mode 100644 index 0000000..2a2584a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/memory.lua.txt @@ -0,0 +1,20 @@ +-- Tencent is pleased to support the open source community by making xLua available. +-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. +-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +-- http://opensource.org/licenses/MIT +-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +local function snapshot() + error('use memory leak checker instead!') +end + +--returns the total memory in use by Lua (in Kbytes). +local function total() + error('use memory leak checker instead!') +end + + +return { + snapshot = snapshot, + total = total +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/memory.lua.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/memory.lua.txt.meta new file mode 100644 index 0000000..29ceae3 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/memory.lua.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6f7abd9aabc5bed4299031a003c63c4c +timeCreated: 1461833890 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/profiler.lua.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/profiler.lua.txt new file mode 100644 index 0000000..b1089f5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/profiler.lua.txt @@ -0,0 +1,125 @@ +-- Tencent is pleased to support the open source community by making xLua available. +-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. +-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +-- http://opensource.org/licenses/MIT +-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +local get_time = os.clock +local sethook = xlua.sethook or debug.sethook +local func_info_map = nil + +local start_time + +local function create_func_info(db_info) + return { + db_info = db_info, + count = 0, + total_time = 0 + } +end + +local function on_hook(event, func_info_id, source) + local func_info = func_info_map[func_info_id] + if not func_info then + func_info = create_func_info(debug.getinfo( 2, 'nS' )) + func_info_map[func_info_id] = func_info + end + if event == "call" then + func_info.call_time = get_time() + func_info.count = func_info.count + 1 + func_info.return_time = nil + elseif event == "return" or event == 'tail return' then + local now = get_time() + if func_info.call_time then + func_info.total_time = func_info.total_time + (now - func_info.call_time) + func_info.call_time = nil + else + func_info.total_time = func_info.total_time + (now - (func_info.return_time or now)) + func_info.count = func_info.count + 1 + end + func_info.return_time = now + if source and func_info.count == 1 then + func_info.db_info.short_src = source + end + end +end + +local function start() + func_info_map = {} + start_time = get_time() + sethook(on_hook, 'cr') +end + +local function pause() + sethook() +end + +local function resume() + sethook(on_hook, 'cr') +end + +local function stop() + sethook() + func_info_map = nil + start_time = nil +end + +local function report_output_line(rp, stat_interval) + local source = rp.db_info.short_src or '[NA]' + local linedefined = (rp.db_info.linedefined and rp.db_info.linedefined >= 0) and string.format(":%i", rp.db_info.linedefined) or '' + source = source .. linedefined + local name = rp.db_info.name or '[anonymous]' + local total_time = string.format("%04.3f", rp.total_time * 1000) + local average_time = string.format("%04.3f", rp.total_time / rp.count * 1000) + local relative_time = string.format("%03.2f%%", (rp.total_time / stat_interval) * 100 ) + local count = string.format("%7i", rp.count) + + return string.format("|%-40.40s: %-50.50s: %-12s: %-12s: %-12s: %-12s|\n", name, source, total_time, average_time, relative_time, count) +end + +local sort_funcs = { + TOTAL = function(a, b) return a.total_time > b.total_time end, + AVERAGE = function(a, b) return a.average > b.average end, + CALLED = function(a, b) return a.count > b.count end +} + +local function report(sort_by) + sethook() + local sort_func = type(sort_by) == 'function' and sort_by or sort_funcs[sort_by] + + local FORMAT_HEADER_LINE = "|%-40s: %-50s: %-12s: %-12s: %-12s: %-12s|\n" + local header = string.format( FORMAT_HEADER_LINE, "FUNCTION", "SOURCE", "TOTAL(MS)", "AVERAGE(MS)", "RELATIVE", "CALLED" ) + local stat_interval = get_time() - (start_time or get_time()) + + local report_list = {} + for _, rp in pairs(func_info_map) do + table.insert(report_list, { + total_time = rp.total_time, + count = rp.count, + average = rp.total_time / rp.count, + output = report_output_line(rp, stat_interval) + }) + end + + table.sort(report_list, sort_func or sort_funcs.TOTAL) + + local output = header + + for i, rp in ipairs(report_list) do + output = output .. rp.output + end + + sethook(on_hook, 'cr') + + return output +end + +return { + --开始统计 + start = start, + --获取报告,start和stop之间可以多次调用,参数sort_by类型是string,可以是'TOTAL','AVERAGE', 'CALLED' + report = report, + --停止统计 + stop = stop +} + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/profiler.lua.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/profiler.lua.txt.meta new file mode 100644 index 0000000..74aeab2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/perf/profiler.lua.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4ecd7249a981b104ea3de4d3d70aa6ef +timeCreated: 1461553714 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr.meta new file mode 100644 index 0000000..870edd2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 205e02e3bc8ec9640804088a902f9960 +folderAsset: yes +timeCreated: 1454039150 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr/tdr.lua.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr/tdr.lua.txt new file mode 100644 index 0000000..67ff369 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr/tdr.lua.txt @@ -0,0 +1,80 @@ +-- Tencent is pleased to support the open source community by making xLua available. +-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. +-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +-- http://opensource.org/licenses/MIT +-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +require "libtdrlua" +local m = {} +for k, v in pairs(libtdrlua) do m[k] = v end +local load_metalib, load_metalib_buf, free_metalib, get_meta, table2buf, buf2table, str2table, metamaxbufsize, bufalloc, buffree, buf2str +load_metalib, m.load_metalib = m.load_metalib, nil +load_metalib_buf, m.load_metalib_buf = m.load_metalib_buf, nil +free_metalib, m.free_metalib = m.free_metalib, nil +get_meta, m.get_meta = m.get_meta, nil +table2buf, m.table2buf = m.table2buf, nil +buf2table, m.buf2table = m.buf2table, nil +str2table, m.str2table = m.str2table, nil +buf2str, m.buf2str = m.buf2str, nil + +metamaxbufsize, m.metamaxbufsize = m.metamaxbufsize, nil +bufalloc, m.bufalloc = m.bufalloc, nil +buffree, m.buffree = m.buffree, nil + +local function create_msg_pk(meta, buf, buf_size) + return { + buff = buf, + pack = function(obj) + local ret_code, used_size = table2buf(meta, obj, buf, buf_size, 0) + if ret_code ~= 0 then + return ret_code, used_size + end + return buf2str(buf, used_size) + end, + unpack = function(str) + return libtdrlua.str2table(meta, str, 0) + end + } +end + +local function create_lib(metalib) + return setmetatable({}, { + __index = function(obj, k) + local ret_code, meta = libtdrlua.get_meta(metalib, k) + if ret_code ~= 0 then + error("libtdrlua.get_meta() failed: errno=".. ret_code .. ",msg=" .. meta) + end + local ret_code, buf_size = libtdrlua.metamaxbufsize(metalib, k) + if ret_code ~= 0 then + error("libtdrlua.metamaxbufsize() failed: errno=".. ret_code .. ",msg=" .. buf_size) + end + + local ret_code, buf = libtdrlua.bufalloc(buf_size) + if ret_code ~= 0 then + error("libtdrlua.bufalloc() failed: errno=".. ret_code .. ",msg=" .. buf) + end + + local pk = create_msg_pk(meta, buf, buf_size) + rawset(obj, k, pk) + return pk + end + }) +end + +function m.from_file(file) + local ret_code, metalib = libtdrlua.load_metalib(file) + if ret_code ~= 0 then + error("libtdrlua.load_metalib() failed: " .. metalib) + end + return create_lib(metalib) +end + +function m.from_memory(str) + local ret_code, metalib = libtdrlua.load_metalib_buf(str) + if ret_code ~= 0 then + error("libtdrlua.load_metalib_buf() failed: errno=".. ret_code .. ",msg=" .. metalib) + end + return create_lib(metalib) +end + +return m \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr/tdr.lua.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr/tdr.lua.txt.meta new file mode 100644 index 0000000..da70929 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/tdr/tdr.lua.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5d6a1f9fe4378704ba10aea024606323 +timeCreated: 1458812943 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua.meta new file mode 100644 index 0000000..c0c8b92 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4deb7b295deb6be40875c3e4f33316de +folderAsset: yes +timeCreated: 1463477791 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua/util.lua.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua/util.lua.txt new file mode 100644 index 0000000..cc6bc15 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua/util.lua.txt @@ -0,0 +1,178 @@ +-- Tencent is pleased to support the open source community by making xLua available. +-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. +-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +-- http://opensource.org/licenses/MIT +-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +local unpack = unpack or table.unpack + +local function async_to_sync(async_func, callback_pos) + return function(...) + local _co = coroutine.running() or error ('this function must be run in coroutine') + local rets + local waiting = false + local function cb_func(...) + if waiting then + assert(coroutine.resume(_co, ...)) + else + rets = {...} + end + end + local params = {...} + table.insert(params, callback_pos or (#params + 1), cb_func) + async_func(unpack(params)) + if rets == nil then + waiting = true + rets = {coroutine.yield()} + end + + return unpack(rets) + end +end + +local function coroutine_call(func) + return function(...) + local co = coroutine.create(func) + assert(coroutine.resume(co, ...)) + end +end + +local move_end = {} + +local generator_mt = { + __index = { + MoveNext = function(self) + self.Current = self.co() + if self.Current == move_end then + self.Current = nil + return false + else + return true + end + end; + Reset = function(self) + self.co = coroutine.wrap(self.w_func) + end + } +} + +local function cs_generator(func, ...) + local params = {...} + local generator = setmetatable({ + w_func = function() + func(unpack(params)) + return move_end + end + }, generator_mt) + generator:Reset() + return generator +end + +local function loadpackage(...) + for _, loader in ipairs(package.searchers) do + local func = loader(...) + if type(func) == 'function' then + return func + end + end +end + +local function auto_id_map() + local hotfix_id_map = require 'hotfix_id_map' + local org_hotfix = xlua.hotfix + xlua.hotfix = function(cs, field, func) + local map_info_of_type = hotfix_id_map[typeof(cs):ToString()] + if map_info_of_type then + if func == nil then func = false end + local tbl = (type(field) == 'table') and field or {[field] = func} + for k, v in pairs(tbl) do + local map_info_of_methods = map_info_of_type[k] + local f = type(v) == 'function' and v or nil + for _, id in ipairs(map_info_of_methods or {}) do + CS.XLua.HotfixDelegateBridge.Set(id, f) + end + --CS.XLua.HotfixDelegateBridge.Set( + end + xlua.private_accessible(cs) + else + return org_hotfix(cs, field, func) + end + end +end + +--和xlua.hotfix的区别是:这个可以调用原来的函数 +local function hotfix_ex(cs, field, func) + assert(type(field) == 'string' and type(func) == 'function', 'invalid argument: #2 string needed, #3 function needed!') + local function func_after(...) + xlua.hotfix(cs, field, nil) + local ret = {func(...)} + xlua.hotfix(cs, field, func_after) + return unpack(ret) + end + xlua.hotfix(cs, field, func_after) +end + +local function bind(func, obj) + return function(...) + return func(obj, ...) + end +end + +--为了兼容luajit,lua53版本直接用|操作符即可 +local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor +local enum_or_op_ex = function(first, ...) + for _, e in ipairs({...}) do + first = enum_or_op(first, e) + end + return first +end + +-- description: 直接用C#函数创建delegate +local function createdelegate(delegate_cls, obj, impl_cls, method_name, parameter_type_list) + local flag = enum_or_op_ex(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.NonPublic, + CS.System.Reflection.BindingFlags.Instance, CS.System.Reflection.BindingFlags.Static) + local m = parameter_type_list and typeof(impl_cls):GetMethod(method_name, flag, nil, parameter_type_list, nil) + or typeof(impl_cls):GetMethod(method_name, flag) + return CS.System.Delegate.CreateDelegate(typeof(delegate_cls), obj, m) +end + +local function state(csobj, state) + local csobj_mt = getmetatable(csobj) + for k, v in pairs(csobj_mt) do rawset(state, k, v) end + local csobj_index, csobj_newindex = state.__index, state.__newindex + state.__index = function(obj, k) + return rawget(state, k) or csobj_index(obj, k) + end + state.__newindex = function(obj, k, v) + if rawget(state, k) ~= nil then + rawset(state, k, v) + else + csobj_newindex(obj, k, v) + end + end + debug.setmetatable(csobj, state) + return state +end + +local function print_func_ref_by_csharp() + local registry = debug.getregistry() + for k, v in pairs(registry) do + if type(k) == 'number' and type(v) == 'function' and registry[v] == k then + local info = debug.getinfo(v) + print(string.format('%s:%d', info.short_src, info.linedefined)) + end + end +end + +return { + async_to_sync = async_to_sync, + coroutine_call = coroutine_call, + cs_generator = cs_generator, + loadpackage = loadpackage, + auto_id_map = auto_id_map, + hotfix_ex = hotfix_ex, + bind = bind, + createdelegate = createdelegate, + state = state, + print_func_ref_by_csharp = print_func_ref_by_csharp, +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua/util.lua.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua/util.lua.txt.meta new file mode 100644 index 0000000..c7d8b03 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Resources/xlua/util.lua.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a940c5f537845c040bb7a137a5291370 +timeCreated: 1463477791 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src.meta new file mode 100644 index 0000000..277bfe1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 34c498233b4ebe447a96bc37e08d8b6f +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CodeEmit.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CodeEmit.cs new file mode 100644 index 0000000..fd56abf --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CodeEmit.cs @@ -0,0 +1,1918 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 +using System.Collections.Generic; +using System.Reflection.Emit; +using System.Reflection; +using System; +using System.Linq; + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +namespace XLua +{ + public class CodeEmit + { + private ModuleBuilder codeEmitModule = null; + private ulong genID = 0; + + private MethodInfo LuaEnv_ThrowExceptionFromError = typeof(LuaEnv).GetMethod("ThrowExceptionFromError"); + private FieldInfo LuaBase_luaEnv = typeof(LuaBase).GetField("luaEnv", BindingFlags.NonPublic | BindingFlags.Instance); + private MethodInfo DelegateBridgeBase_errorFuncRef_getter = typeof(LuaBase).GetProperty("_errorFuncRef", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true); + private MethodInfo LuaAPI_load_error_func = typeof(LuaAPI).GetMethod("load_error_func"); + private MethodInfo LuaBase_translator_getter = typeof(LuaBase).GetProperty("_translator", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true); + private FieldInfo LuaBase_luaReference = typeof(LuaBase).GetField("luaReference", BindingFlags.NonPublic | BindingFlags.Instance); + private MethodInfo LuaAPI_lua_getref = typeof(LuaAPI).GetMethod("lua_getref"); + private MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); + private MethodInfo ObjectTranslator_PushAny = typeof(ObjectTranslator).GetMethod("PushAny"); + private MethodInfo ObjectTranslator_PushParams = typeof(ObjectTranslator).GetMethod("PushParams"); + private MethodInfo LuaBase_L_getter = typeof(LuaBase).GetProperty("_L", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true); + private MethodInfo LuaAPI_lua_pcall = typeof(LuaAPI).GetMethod("lua_pcall"); + private MethodInfo LuaAPI_lua_type = typeof(LuaAPI).GetMethod("lua_type"); + private MethodInfo ObjectTranslator_GetObject = typeof(ObjectTranslator).GetMethod("GetObject", new Type[] { typeof(RealStatePtr), + typeof(int), typeof(Type)}); + private MethodInfo ObjectTranslator_GetParams = typeof(ObjectTranslator).GetMethod("GetParams", new Type[] { typeof(RealStatePtr), typeof(int) }); + private MethodInfo ObjectTranslator_Update = typeof(ObjectTranslator).GetMethod("Update"); + private MethodInfo LuaAPI_lua_pushvalue = typeof(LuaAPI).GetMethod("lua_pushvalue"); + private MethodInfo LuaAPI_lua_remove = typeof(LuaAPI).GetMethod("lua_remove"); + private MethodInfo LuaAPI_lua_pushstring = typeof(LuaAPI).GetMethod("lua_pushstring", new Type[] { typeof(RealStatePtr), typeof(string)}); + private MethodInfo LuaAPI_lua_gettop = typeof(LuaAPI).GetMethod("lua_gettop"); + private MethodInfo LuaAPI_xlua_pgettable = typeof(LuaAPI).GetMethod("xlua_pgettable"); + private MethodInfo LuaAPI_xlua_psettable = typeof(LuaAPI).GetMethod("xlua_psettable"); + private MethodInfo LuaAPI_lua_pop = typeof(LuaAPI).GetMethod("lua_pop"); + private MethodInfo LuaAPI_lua_settop = typeof(LuaAPI).GetMethod("lua_settop"); + private MethodInfo LuaAPI_luaL_error = typeof(LuaAPI).GetMethod("luaL_error"); + private MethodInfo LuaAPI_xlua_is_eq_str = typeof(LuaAPI).GetMethod("xlua_is_eq_str", new Type[] { + typeof(RealStatePtr), typeof(int), typeof(string)}); + + private MethodInfo LuaAPI_xlua_pushinteger = typeof(LuaAPI).GetMethod("xlua_pushinteger"); + private MethodInfo LuaAPI_lua_pushint64 = typeof(LuaAPI).GetMethod("lua_pushint64"); + private MethodInfo LuaAPI_lua_pushnumber = typeof(LuaAPI).GetMethod("lua_pushnumber"); + private MethodInfo LuaAPI_xlua_pushuint = typeof(LuaAPI).GetMethod("xlua_pushuint"); + private MethodInfo LuaAPI_lua_pushuint64 = typeof(LuaAPI).GetMethod("lua_pushuint64"); + private MethodInfo LuaAPI_lua_pushboolean = typeof(LuaAPI).GetMethod("lua_pushboolean"); + private MethodInfo LuaAPI_lua_pushbytes = typeof(LuaAPI).GetMethod("lua_pushstring", new Type[] { typeof(RealStatePtr), typeof(byte[]) }); + private MethodInfo LuaAPI_lua_pushlightuserdata = typeof(LuaAPI).GetMethod("lua_pushlightuserdata"); + private MethodInfo ObjectTranslator_PushDecimal = typeof(ObjectTranslator).GetMethod("PushDecimal"); + private MethodInfo ObjectTranslator_GetDecimal = typeof(ObjectTranslator).GetMethod("GetDecimal"); + + private Dictionary fixPush; + + private MethodInfo LuaAPI_xlua_tointeger = typeof(LuaAPI).GetMethod("xlua_tointeger"); + private MethodInfo LuaAPI_lua_tonumber = typeof(LuaAPI).GetMethod("lua_tonumber"); + private MethodInfo LuaAPI_lua_tostring = typeof(LuaAPI).GetMethod("lua_tostring"); + private MethodInfo LuaAPI_lua_toboolean = typeof(LuaAPI).GetMethod("lua_toboolean"); + private MethodInfo LuaAPI_lua_tobytes = typeof(LuaAPI).GetMethod("lua_tobytes"); + private MethodInfo LuaAPI_lua_touserdata = typeof(LuaAPI).GetMethod("lua_touserdata"); + private MethodInfo LuaAPI_xlua_touint = typeof(LuaAPI).GetMethod("xlua_touint"); + private MethodInfo LuaAPI_lua_touint64 = typeof(LuaAPI).GetMethod("lua_touint64"); + private MethodInfo LuaAPI_lua_toint64 = typeof(LuaAPI).GetMethod("lua_toint64"); + + private Dictionary typedCaster; + private Dictionary fixCaster; + + public CodeEmit() + { + fixPush = new Dictionary() + { + {typeof(byte), LuaAPI_xlua_pushinteger}, + {typeof(char), LuaAPI_xlua_pushinteger}, + {typeof(short), LuaAPI_xlua_pushinteger}, + {typeof(int), LuaAPI_xlua_pushinteger}, + {typeof(long), LuaAPI_lua_pushint64}, + {typeof(sbyte), LuaAPI_xlua_pushinteger}, + {typeof(float), LuaAPI_lua_pushnumber}, + {typeof(ushort), LuaAPI_xlua_pushinteger}, + {typeof(uint), LuaAPI_xlua_pushuint}, + {typeof(ulong), LuaAPI_lua_pushuint64}, + {typeof(double), LuaAPI_lua_pushnumber}, + {typeof(string), LuaAPI_lua_pushstring}, + {typeof(byte[]), LuaAPI_lua_pushbytes}, + {typeof(bool), LuaAPI_lua_pushboolean}, + {typeof(IntPtr), LuaAPI_lua_pushlightuserdata}, + }; + + fixCaster = new Dictionary() + { + {typeof(double), LuaAPI_lua_tonumber}, + {typeof(string), LuaAPI_lua_tostring}, + {typeof(bool), LuaAPI_lua_toboolean}, + {typeof(byte[]), LuaAPI_lua_tobytes}, + {typeof(IntPtr), LuaAPI_lua_touserdata}, + {typeof(uint), LuaAPI_xlua_touint}, + {typeof(ulong), LuaAPI_lua_touint64}, + {typeof(int), LuaAPI_xlua_tointeger}, + {typeof(long), LuaAPI_lua_toint64}, + }; + + typedCaster = new Dictionary() + { + {typeof(byte), LuaAPI_xlua_tointeger}, + {typeof(char), LuaAPI_xlua_tointeger}, + {typeof(short), LuaAPI_xlua_tointeger}, + {typeof(sbyte), LuaAPI_xlua_tointeger}, + {typeof(float), LuaAPI_lua_tonumber}, + {typeof(ushort), LuaAPI_xlua_tointeger}, + }; + + initBlackList(); + } + + private void emitPush(ILGenerator il, Type type, short dataPos, bool isParam, LocalBuilder L, LocalBuilder translator, bool isArg) + { + var paramElemType = type.IsByRef ? type.GetElementType() : type; + var ldd = isArg ? OpCodes.Ldarg : OpCodes.Ldloc; + MethodInfo pusher; + if (fixPush.TryGetValue(paramElemType, out pusher)) + { + il.Emit(OpCodes.Ldloc, L); + il.Emit(ldd, dataPos); + + if (type.IsByRef) + { + if (paramElemType.IsValueType) + { + il.Emit(OpCodes.Ldobj, paramElemType); + } + else + { + il.Emit(OpCodes.Ldind_Ref); + } + } + + il.Emit(OpCodes.Call, pusher); + } + else if (paramElemType == typeof(decimal)) + { + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldloc, L); + il.Emit(ldd, dataPos); + if (type.IsByRef) + { + il.Emit(OpCodes.Ldobj, paramElemType); + } + il.Emit(OpCodes.Callvirt, ObjectTranslator_PushDecimal); + } + else + { + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldloc, L); + il.Emit(ldd, dataPos); + if (type.IsByRef) + { + if (paramElemType.IsValueType) + { + il.Emit(OpCodes.Ldobj, paramElemType); + il.Emit(OpCodes.Box, paramElemType); + } + else + { + il.Emit(OpCodes.Ldind_Ref); + } + } + else if (type.IsValueType) + { + il.Emit(OpCodes.Box, type); + } + if (isParam) + { + il.Emit(OpCodes.Callvirt, ObjectTranslator_PushParams); + } + else + { + il.Emit(OpCodes.Callvirt, ObjectTranslator_PushAny); + } + } + } + + private ModuleBuilder CodeEmitModule + { + get + { + if (codeEmitModule == null) + { + var assemblyName = new AssemblyName(); + assemblyName.Name = "XLuaCodeEmit"; + codeEmitModule = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run) + .DefineDynamicModule("XLuaCodeEmit"); + } + return codeEmitModule; + } + } + + public Type EmitDelegateImpl(IEnumerable> groups) + { + TypeBuilder impl_type_builder = CodeEmitModule.DefineType("XLuaGenDelegateImpl" + (genID++), TypeAttributes.Public, typeof(DelegateBridge)); + + MethodBuilder get_deleate_by_type = impl_type_builder.DefineMethod("GetDelegateByType", MethodAttributes.Public + | MethodAttributes.HideBySig + | MethodAttributes.NewSlot + | MethodAttributes.Virtual + | MethodAttributes.Final, + typeof(System.Delegate), new Type[] { typeof(System.Type) }); + + ILGenerator get_deleate_by_type_il = get_deleate_by_type.GetILGenerator(); + + foreach (var group in groups) + { + var to_be_impl = group.Key; + + var method_builder = defineImplementMethod(impl_type_builder, to_be_impl, to_be_impl.Attributes, "__Gen_Delegate_Imp" + (genID++)); + + emitMethodImpl(to_be_impl, method_builder.GetILGenerator(), false); + + foreach(var dt in group) + { + Label end_of_if = get_deleate_by_type_il.DefineLabel(); + get_deleate_by_type_il.Emit(OpCodes.Ldarg_1); + get_deleate_by_type_il.Emit(OpCodes.Ldtoken, dt); + get_deleate_by_type_il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(type) + get_deleate_by_type_il.Emit(OpCodes.Bne_Un, end_of_if); + + get_deleate_by_type_il.Emit(OpCodes.Ldarg_0); + get_deleate_by_type_il.Emit(OpCodes.Ldftn, method_builder); + get_deleate_by_type_il.Emit(OpCodes.Newobj, dt.GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })); + get_deleate_by_type_il.Emit(OpCodes.Ret); + get_deleate_by_type_il.MarkLabel(end_of_if); + } + } + + // Constructor + var ctor_param_types = new Type[] { typeof(int), typeof(LuaEnv) }; + ConstructorInfo parent_ctor = typeof(DelegateBridge).GetConstructor(ctor_param_types); + var ctor_builder = impl_type_builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctor_param_types); + var ctor_il = ctor_builder.GetILGenerator(); + ctor_il.Emit(OpCodes.Ldarg_0); + ctor_il.Emit(OpCodes.Ldarg_1); + ctor_il.Emit(OpCodes.Ldarg_2); + ctor_il.Emit(OpCodes.Call, parent_ctor); + ctor_il.Emit(OpCodes.Ret); + + // end of GetDelegateByType + get_deleate_by_type_il.Emit(OpCodes.Ldnull); + get_deleate_by_type_il.Emit(OpCodes.Ret); + + impl_type_builder.DefineMethodOverride(get_deleate_by_type, typeof(DelegateBridgeBase).GetMethod("GetDelegateByType")); + + + return impl_type_builder.CreateType(); + } + + private void EmitGetObject(ILGenerator il, int offset, Type type, LocalBuilder L, LocalBuilder translator, LocalBuilder offsetBase, bool isParam = false) + { + if (!fixCaster.ContainsKey(type) && !typedCaster.ContainsKey(type)) + { + il.Emit(OpCodes.Ldloc, translator); // translator + } + il.Emit(OpCodes.Ldloc, L); // L + if (offsetBase != null) + { + il.Emit(OpCodes.Ldloc, offsetBase); // err_func + il.Emit(OpCodes.Ldc_I4, offset); + il.Emit(OpCodes.Add); + } + else + { + il.Emit(OpCodes.Ldc_I4, offset); + } + + MethodInfo caster; + + if (fixCaster.TryGetValue(type, out caster)) + { + il.Emit(OpCodes.Call, caster); + } + else if (typedCaster.TryGetValue(type, out caster)) + { + il.Emit(OpCodes.Call, caster); + if (type == typeof(byte)) + { + il.Emit(OpCodes.Conv_U1); + } + else if(type == typeof(char)) + { + il.Emit(OpCodes.Conv_U2); + } + else if (type == typeof(short)) + { + il.Emit(OpCodes.Conv_I2); + } + else if (type == typeof(sbyte)) + { + il.Emit(OpCodes.Conv_I1); + } + else if (type == typeof(ushort)) + { + il.Emit(OpCodes.Conv_U2); + } + else if (type == typeof(float)) + { + il.Emit(OpCodes.Conv_R4); + } + else + { + throw new InvalidProgramException(type + " is not a type need cast"); + } + } + else if (type == typeof(decimal)) + { + il.Emit(OpCodes.Callvirt, ObjectTranslator_GetDecimal); + } + else + { + if (isParam) + { + il.Emit(OpCodes.Callvirt, ObjectTranslator_GetParams.MakeGenericMethod(new Type[] { type.GetElementType() })); + } + else + { + il.Emit(OpCodes.Ldtoken, type); + il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(type) + il.Emit(OpCodes.Callvirt, ObjectTranslator_GetObject); + } + if (type.IsValueType) + { + Label not_null = il.DefineLabel(); + Label null_done = il.DefineLabel(); + LocalBuilder local_new = il.DeclareLocal(type); + + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Brtrue_S, not_null); + + il.Emit(OpCodes.Pop); + il.Emit(OpCodes.Ldloca, local_new); + il.Emit(OpCodes.Initobj, type); + il.Emit(OpCodes.Ldloc, local_new); + il.Emit(OpCodes.Br_S, null_done); + + il.MarkLabel(not_null); + il.Emit(OpCodes.Unbox_Any, type); + il.MarkLabel(null_done); + } + else if (type != typeof(object)) + { + il.Emit(OpCodes.Castclass, type); + } + } + } + + HashSet gen_interfaces = new HashSet(); + + public void SetGenInterfaces(List gen_interfaces) + { + gen_interfaces.ForEach((item) => + { + if (!this.gen_interfaces.Contains(item)) + { + this.gen_interfaces.Add(item); + } + }); + } + + public Type EmitInterfaceImpl(Type to_be_impl) + { + if (!to_be_impl.IsInterface) + { + throw new InvalidOperationException("interface expected, but got " + to_be_impl); + } + + if (!gen_interfaces.Contains(to_be_impl)) + { + throw new InvalidCastException("This type must add to CSharpCallLua: " + to_be_impl.GetFriendlyName()); + } + + TypeBuilder impl_type_builder = CodeEmitModule.DefineType("XLuaGenInterfaceImpl" + (genID++), TypeAttributes.Public | TypeAttributes.Class, typeof(LuaBase), new Type[] { to_be_impl}); + + foreach(var member in (new Type[] { to_be_impl }.Concat(to_be_impl.GetInterfaces()).SelectMany(i=> i.GetMembers()))) + { + if (member.MemberType == MemberTypes.Method) + { + MethodInfo method = member as MethodInfo; + if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_") || + method.Name.StartsWith("add_") || method.Name.StartsWith("remove_")) + { + continue; + } + + var method_builder = defineImplementMethod(impl_type_builder, method, + MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual); + + emitMethodImpl(method, method_builder.GetILGenerator(), true); + } + else if (member.MemberType == MemberTypes.Property) + { + PropertyInfo property = member as PropertyInfo; + PropertyBuilder prop_builder = impl_type_builder.DefineProperty(property.Name, property.Attributes, property.PropertyType, Type.EmptyTypes); + if (property.Name == "Item") + { + if (property.CanRead) + { + var getter_buildler = defineImplementMethod(impl_type_builder, property.GetGetMethod(), + MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig); + emitMethodImpl(property.GetGetMethod(), getter_buildler.GetILGenerator(), true); + prop_builder.SetGetMethod(getter_buildler); + } + if (property.CanWrite) + { + var setter_buildler = defineImplementMethod(impl_type_builder, property.GetSetMethod(), + MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig); + emitMethodImpl(property.GetSetMethod(), setter_buildler.GetILGenerator(), true); + prop_builder.SetSetMethod(setter_buildler); + } + continue; + } + if (property.CanRead) + { + MethodBuilder getter_buildler = impl_type_builder.DefineMethod("get_" + property.Name, + MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, + property.PropertyType, Type.EmptyTypes); + + ILGenerator il = getter_buildler.GetILGenerator(); + + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr)); + LocalBuilder oldTop = il.DeclareLocal(typeof(int)); + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + LocalBuilder ret = il.DeclareLocal(property.PropertyType); + + // L = LuaBase.L; + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, LuaBase_L_getter); + il.Emit(OpCodes.Stloc, L); + + //oldTop = LuaAPI.lua_gettop(L); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Call, LuaAPI_lua_gettop); + il.Emit(OpCodes.Stloc, oldTop); + + //translator = LuaBase.translator; + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, LuaBase_translator_getter); + il.Emit(OpCodes.Stloc, translator); + + //LuaAPI.lua_getref(L, luaReference); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaReference); + il.Emit(OpCodes.Call, LuaAPI_lua_getref); + + //LuaAPI.lua_pushstring(L, "xxx"); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldstr, property.Name); + il.Emit(OpCodes.Call, LuaAPI_lua_pushstring); + + //LuaAPI.xlua_pgettable(L, -2) + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)-2); + il.Emit(OpCodes.Call, LuaAPI_xlua_pgettable); + Label gettable_no_exception = il.DefineLabel(); + il.Emit(OpCodes.Brfalse, gettable_no_exception); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaEnv); + il.Emit(OpCodes.Ldloc, oldTop); + il.Emit(OpCodes.Callvirt, LuaEnv_ThrowExceptionFromError); + il.MarkLabel(gettable_no_exception); + + EmitGetObject(il, -1, property.PropertyType, L, translator, null); + il.Emit(OpCodes.Stloc, ret); + + //LuaAPI.lua_pop(L, 2); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)2); + il.Emit(OpCodes.Call, LuaAPI_lua_pop); + + il.Emit(OpCodes.Ldloc, ret); + il.Emit(OpCodes.Ret); + + prop_builder.SetGetMethod(getter_buildler); + } + if (property.CanWrite) + { + MethodBuilder setter_builder = impl_type_builder.DefineMethod("set_" + property.Name, + MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, + null, new Type[] { property.PropertyType }); + + ILGenerator il = setter_builder.GetILGenerator(); + + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr)); + LocalBuilder oldTop = il.DeclareLocal(typeof(int)); + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + + // L = LuaBase.L; + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, LuaBase_L_getter); + il.Emit(OpCodes.Stloc, L); + + //oldTop = LuaAPI.lua_gettop(L); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Call, LuaAPI_lua_gettop); + il.Emit(OpCodes.Stloc, oldTop); + + //translator = LuaBase.translator; + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, LuaBase_translator_getter); + il.Emit(OpCodes.Stloc, translator); + + //LuaAPI.lua_getref(L, luaReference); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaReference); + il.Emit(OpCodes.Call, LuaAPI_lua_getref); + + //LuaAPI.lua_pushstring(L, "xxx"); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldstr, property.Name); + il.Emit(OpCodes.Call, LuaAPI_lua_pushstring); + + //translator.Push(L, value); + emitPush(il, property.PropertyType, 1, false, L, translator, true); + + //LuaAPI.xlua_psettable(L, -2) + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)-3); + il.Emit(OpCodes.Call, LuaAPI_xlua_psettable); + Label settable_no_exception = il.DefineLabel(); + il.Emit(OpCodes.Brfalse, settable_no_exception); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaEnv); + il.Emit(OpCodes.Ldloc, oldTop); + il.Emit(OpCodes.Callvirt, LuaEnv_ThrowExceptionFromError); + il.MarkLabel(settable_no_exception); + + //LuaAPI.lua_pop(L, 1); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)1); + il.Emit(OpCodes.Call, LuaAPI_lua_pop); + + il.Emit(OpCodes.Ret); + + prop_builder.SetSetMethod(setter_builder); + + } + } + else if(member.MemberType == MemberTypes.Event) + { + + EventInfo event_info = member as EventInfo; + EventBuilder event_builder = impl_type_builder.DefineEvent(event_info.Name, event_info.Attributes, event_info.EventHandlerType); + if (event_info.GetAddMethod() != null) + { + var add_buildler = defineImplementMethod(impl_type_builder, event_info.GetAddMethod(), + MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig); + emitMethodImpl(event_info.GetAddMethod(), add_buildler.GetILGenerator(), true); + event_builder.SetAddOnMethod(add_buildler); + } + if (event_info.GetRemoveMethod() != null) + { + var remove_buildler = defineImplementMethod(impl_type_builder, event_info.GetRemoveMethod(), + MethodAttributes.Virtual | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig); + emitMethodImpl(event_info.GetRemoveMethod(), remove_buildler.GetILGenerator(), true); + event_builder.SetRemoveOnMethod(remove_buildler); + } + } + } + + + // Constructor + var ctor_param_types = new Type[] { typeof(int), typeof(LuaEnv) }; + ConstructorInfo parent_ctor = typeof(LuaBase).GetConstructor(ctor_param_types); + var ctor_builder = impl_type_builder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctor_param_types); + var ctor_il = ctor_builder.GetILGenerator(); + ctor_il.Emit(OpCodes.Ldarg_0); + ctor_il.Emit(OpCodes.Ldarg_1); + ctor_il.Emit(OpCodes.Ldarg_2); + ctor_il.Emit(OpCodes.Call, parent_ctor); + ctor_il.Emit(OpCodes.Ret); + + return impl_type_builder.CreateType(); + } + + private void emitEmptyMethod(ILGenerator il, Type returnType) + { + if(returnType != typeof(void)) + { + if (returnType.IsValueType) + { + LocalBuilder local_new = il.DeclareLocal(returnType); + il.Emit(OpCodes.Ldloca, local_new); + il.Emit(OpCodes.Initobj, returnType); + il.Emit(OpCodes.Ldloc, local_new); + } + else + { + il.Emit(OpCodes.Ldnull); + } + } + il.Emit(OpCodes.Ret); + } + + private MethodBuilder defineImplementMethod(TypeBuilder type_builder, MethodInfo to_be_impl, MethodAttributes attributes, string methodName = null) + { + var parameters = to_be_impl.GetParameters(); + + Type[] param_types = new Type[parameters.Length]; + for (int i = 0; i < parameters.Length; ++i) + { + param_types[i] = parameters[i].ParameterType; + } + + var method_builder = type_builder.DefineMethod(methodName == null ? to_be_impl.Name : methodName, attributes, to_be_impl.ReturnType, param_types); + for (int i = 0; i < parameters.Length; ++i) + { + method_builder.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name); + } + return method_builder; + } + + ConstructorInfo decimalConstructor = typeof(decimal).GetConstructor(new Type[] { + typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) + }); + + private void emitLiteralLoad(ILGenerator il, Type type, object obj, int localIndex) + { + if (!type.IsValueType && ReferenceEquals(obj, null)) + { + il.Emit(OpCodes.Ldnull); + } + else if(type.IsPrimitive || type.IsEnum()) + { + if (type.IsEnum()) + { + type = Enum.GetUnderlyingType(type); + } + if (typeof(bool) == type) + { + if ((bool)obj == true) + { + il.Emit(OpCodes.Ldc_I4_1); + } + else + { + il.Emit(OpCodes.Ldc_I4_0); + } + } + else if (typeof(uint) == type) + { + il.Emit(OpCodes.Ldc_I4, (int)Convert.ToUInt32(obj)); + } + else if(typeof(byte) == type || typeof(sbyte) == type || typeof(short) == type || + typeof(ushort) == type || typeof(int) == type || typeof(char) == type) + { + il.Emit(OpCodes.Ldc_I4, Convert.ToInt32(obj)); + } + else if (typeof(long) == type) + { + il.Emit(OpCodes.Ldc_I8, Convert.ToInt64(obj)); + } + else if (typeof(ulong) == type) + { + il.Emit(OpCodes.Ldc_I8, (long)Convert.ToUInt64(obj)); + } + else if (typeof(IntPtr) == type || typeof(UIntPtr) == type) + { + il.Emit(OpCodes.Ldloca, localIndex); + il.Emit(OpCodes.Initobj, type); + il.Emit(OpCodes.Ldloc, localIndex); + } + else if (typeof(float) == type) + { + il.Emit(OpCodes.Ldc_R4, Convert.ToSingle(obj)); + } + else if (typeof(double) == type) + { + il.Emit(OpCodes.Ldc_R8, Convert.ToDouble(obj)); + } + else + { + throw new Exception(type + " is not primitive or enum!"); + } + } + else if (type == typeof(string)) + { + il.Emit(OpCodes.Ldstr, obj as string); + } + else if (type == typeof(decimal)) + { + var buffer = decimal.GetBits(Convert.ToDecimal(obj)); + il.Emit(OpCodes.Ldc_I4, buffer[0]); + il.Emit(OpCodes.Ldc_I4, buffer[1]); + il.Emit(OpCodes.Ldc_I4, buffer[2]); + //UnityEngine.Debug.Log(string.Format("{0}.{1}.{2}.{3}--{4}", buffer[0], buffer[1], buffer[2], buffer[3], obj)); + il.Emit(OpCodes.Ldc_I4, (buffer[3] & 0x80000000) == 0 ? 0 : 1); + il.Emit(OpCodes.Ldc_I4, (buffer[3] >> 16) & 0xFF); + il.Emit(OpCodes.Newobj, decimalConstructor); + } + else if (type.IsValueType) + { + il.Emit(OpCodes.Ldloca, localIndex); + il.Emit(OpCodes.Initobj, type); + il.Emit(OpCodes.Ldloc, localIndex); + } + else + { + il.Emit(OpCodes.Ldnull); + } + } + + private void emitMethodImpl(MethodInfo to_be_impl, ILGenerator il, bool isObj) + { + var parameters = to_be_impl.GetParameters(); + + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr));//RealStatePtr L; 0 + LocalBuilder err_func = il.DeclareLocal(typeof(int));//int err_func; 1 + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator));//ObjectTranslator translator; 2 + LocalBuilder ret = null; + bool has_return = to_be_impl.ReturnType != typeof(void); + if (has_return) + { + ret = il.DeclareLocal(to_be_impl.ReturnType); //ReturnType ret; 3 + } + + // L = LuaBase.L; + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, LuaBase_L_getter); + il.Emit(OpCodes.Stloc, L); + + //err_func =LuaAPI.load_error_func(L, errorFuncRef); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, DelegateBridgeBase_errorFuncRef_getter); + il.Emit(OpCodes.Call, LuaAPI_load_error_func); + il.Emit(OpCodes.Stloc, err_func); + + //translator = LuaBase.translator; + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Callvirt, LuaBase_translator_getter); + il.Emit(OpCodes.Stloc, translator); + + //LuaAPI.lua_getref(L, luaReference); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaReference); + il.Emit(OpCodes.Call, LuaAPI_lua_getref); + + if (isObj) + { + //LuaAPI.lua_pushstring(L, "xxx"); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldstr, to_be_impl.Name); + il.Emit(OpCodes.Call, LuaAPI_lua_pushstring); + + //LuaAPI.xlua_pgettable(L, -2) + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)-2); + il.Emit(OpCodes.Call, LuaAPI_xlua_pgettable); + Label gettable_no_exception = il.DefineLabel(); + il.Emit(OpCodes.Brfalse, gettable_no_exception); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaEnv); + il.Emit(OpCodes.Ldloc, err_func); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Sub); + il.Emit(OpCodes.Callvirt, LuaEnv_ThrowExceptionFromError); + il.MarkLabel(gettable_no_exception); + + //LuaAPI.lua_pushvalue(L, -2); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)-2); + il.Emit(OpCodes.Call, LuaAPI_lua_pushvalue); + + //LuaAPI.lua_remove(L, -3); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4_S, (sbyte)-3); + il.Emit(OpCodes.Call, LuaAPI_lua_remove); + } + + int in_param_count = 0; + int out_param_count = 0; + bool has_params = false; + //translator.PushAny(L, param_in) + for (int i = 0; i < parameters.Length; ++i) + { + var pinfo = parameters[i]; + if (!pinfo.IsOut) + { + var ptype = pinfo.ParameterType; + bool isParam = pinfo.IsDefined(typeof(ParamArrayAttribute), false); + emitPush(il, ptype, (short)(i + 1), isParam, L, translator, true); + if (isParam) + { + has_params = true; + } + else + { + ++in_param_count; + } + } + + if (pinfo.ParameterType.IsByRef) + { + ++out_param_count; + } + } + + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4, in_param_count + (isObj ? 1 : 0)); + if (has_params) + { + Label l1 = il.DefineLabel(); + + il.Emit(OpCodes.Ldarg, (short)parameters.Length); + il.Emit(OpCodes.Brfalse, l1); + + il.Emit(OpCodes.Ldarg, (short)parameters.Length); + il.Emit(OpCodes.Ldlen); + il.Emit(OpCodes.Add); + il.MarkLabel(l1); + } + il.Emit(OpCodes.Ldc_I4, out_param_count + (has_return ? 1 : 0)); + il.Emit(OpCodes.Ldloc, err_func); + il.Emit(OpCodes.Call, LuaAPI_lua_pcall); + Label no_exception = il.DefineLabel(); + il.Emit(OpCodes.Brfalse, no_exception); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, LuaBase_luaEnv); + il.Emit(OpCodes.Ldloc, err_func); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Sub); + il.Emit(OpCodes.Callvirt, LuaEnv_ThrowExceptionFromError); + il.MarkLabel(no_exception); + + int offset = 1; + if (has_return) + { + EmitGetObject(il, offset++, to_be_impl.ReturnType, L, translator, err_func); + il.Emit(OpCodes.Stloc, ret); + } + + for (int i = 0; i < parameters.Length; ++i) + { + var pinfo = parameters[i]; + var ptype = pinfo.ParameterType; + if (ptype.IsByRef) + { + il.Emit(OpCodes.Ldarg, (short)(i + 1)); + var pelemtype = ptype.GetElementType(); + EmitGetObject(il, offset++, pelemtype, L, translator, err_func); + if (pelemtype.IsValueType) + { + il.Emit(OpCodes.Stobj, pelemtype); + } + else + { + il.Emit(OpCodes.Stind_Ref); + } + + } + } + + if (has_return) + { + il.Emit(OpCodes.Ldloc, ret); + } + + //LuaAPI.lua_settop(L, err_func - 1); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldloc, err_func); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Sub); + il.Emit(OpCodes.Call, LuaAPI_lua_settop); + + il.Emit(OpCodes.Ret); + } + + private MethodInfo ObjectTranslatorPool_FindTranslator = typeof(ObjectTranslatorPool).GetMethod("FindTranslator"); + private Type[] parameterTypeOfWrap = new Type[] { typeof(RealStatePtr) }; + private MethodInfo ObjectTranslator_Assignable = typeof(ObjectTranslator).GetMethod("Assignable", new Type[] { typeof(RealStatePtr), + typeof(int), typeof(Type)}); + + private MethodInfo Utils_BeginObjectRegister = typeof(Utils).GetMethod("BeginObjectRegister"); + private MethodInfo Utils_EndObjectRegister = typeof(Utils).GetMethod("EndObjectRegister"); + private MethodInfo Utils_BeginClassRegister = typeof(Utils).GetMethod("BeginClassRegister"); + private MethodInfo Utils_EndClassRegister = typeof(Utils).GetMethod("EndClassRegister"); + private MethodInfo Utils_RegisterFunc = typeof(Utils).GetMethod("RegisterFunc"); + private MethodInfo Utils_RegisterObject = typeof(Utils).GetMethod("RegisterObject"); + + private ConstructorInfo LuaCSFunction_Constructor = typeof(LuaCSFunction).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) }); + + private MethodInfo String_Concat = typeof(string).GetMethod("Concat", new Type[] { typeof(object), typeof(object) }); + + void checkType(ILGenerator il, Type type, LocalBuilder translator, int argPos, Label endOfBlock, bool isVParam, bool isDefault) + { + Label endOfCheckType = il.DefineLabel(); + + if (isVParam || isDefault) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, argPos); + il.Emit(OpCodes.Call, LuaAPI_lua_type); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Beq, endOfCheckType); + } + + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, argPos); + il.Emit(OpCodes.Ldtoken, isVParam ? type.GetElementType() : type); + il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(DeclaringType) + il.Emit(OpCodes.Callvirt, ObjectTranslator_Assignable); + il.Emit(OpCodes.Brfalse, endOfBlock); + + il.MarkLabel(endOfCheckType); + } + + void emitRegisterFunc(ILGenerator il, MethodBuilder method, int index, string name) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, index); + il.Emit(OpCodes.Ldstr, name); + il.Emit(OpCodes.Ldnull); + il.Emit(OpCodes.Ldftn, method); + il.Emit(OpCodes.Newobj, LuaCSFunction_Constructor); + il.Emit(OpCodes.Call, Utils_RegisterFunc); + } + + void emitCatchBlock(ILGenerator il, LocalBuilder ex, LocalBuilder wrapRet, Label retPoint, Label exceptionBlock) + { + il.BeginCatchBlock(typeof(Exception)); + il.Emit(OpCodes.Stloc, ex); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldstr, "c# exception:"); + il.Emit(OpCodes.Ldloc, ex); + il.Emit(OpCodes.Call, String_Concat); + il.Emit(OpCodes.Call, LuaAPI_luaL_error); + il.Emit(OpCodes.Stloc, wrapRet); + il.Emit(OpCodes.Leave, retPoint); + il.Emit(OpCodes.Leave, exceptionBlock); + + il.EndExceptionBlock(); + } + + public MethodBuilder emitFieldWrap(TypeBuilder typeBuilder, FieldInfo field, bool genGetter) + { + MethodBuilder methodBuilder = typeBuilder.DefineMethod(field.Name + (genID++), MethodAttributes.Static, typeof(int), parameterTypeOfWrap); + methodBuilder.DefineParameter(1, ParameterAttributes.None, "L"); + + ILGenerator il = methodBuilder.GetILGenerator(); + + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr)); + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + LocalBuilder fieldStore = il.DeclareLocal(field.FieldType); + LocalBuilder wrapRet = il.DeclareLocal(typeof(int)); + LocalBuilder ex = il.DeclareLocal(typeof(Exception)); + + Label exceptionBlock = il.BeginExceptionBlock(); + Label retPoint = il.DefineLabel(); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Stloc, L); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, ObjectTranslatorPool_FindTranslator); + il.Emit(OpCodes.Stloc, translator); + + if (genGetter) + { + if (!field.IsStatic) + { + EmitGetObject(il, 1, field.DeclaringType, L, translator, null); + il.Emit(OpCodes.Ldfld, field); + } + else + { + il.Emit(OpCodes.Ldsfld, field); + } + il.Emit(OpCodes.Stloc, fieldStore); + emitPush(il, field.FieldType, 2, false, L, translator, false); + } + else + { + if (!field.IsStatic) + { + EmitGetObject(il, 1, field.DeclaringType, L, translator, null); + LocalBuilder self = null; + if (field.DeclaringType.IsValueType) + { + self = il.DeclareLocal(field.DeclaringType); + il.Emit(OpCodes.Stloc, self); + il.Emit(OpCodes.Ldloca, self); + } + EmitGetObject(il, 2, field.FieldType, L, translator, null); + il.Emit(OpCodes.Stfld, field); + if (self != null) + { + emitUpdateIfNeeded(il, L, translator, field.DeclaringType, 1, self.LocalIndex); + } + } + else + { + EmitGetObject(il, 1, field.FieldType, L, translator, null); + il.Emit(OpCodes.Stsfld, field); + } + } + + il.Emit(OpCodes.Leave, exceptionBlock); + + emitCatchBlock(il, ex, wrapRet, retPoint, exceptionBlock); + + il.Emit(genGetter ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Ret); + + il.MarkLabel(retPoint); + il.Emit(OpCodes.Ldloc, wrapRet); + il.Emit(OpCodes.Ret); + + return methodBuilder; + } + + public MethodBuilder emitPropertyWrap(TypeBuilder typeBuilder, PropertyInfo prop, MethodInfo op, bool genGetter) + { + MethodBuilder methodBuilder = typeBuilder.DefineMethod(prop.Name + (genID++), MethodAttributes.Static, typeof(int), parameterTypeOfWrap); + methodBuilder.DefineParameter(1, ParameterAttributes.None, "L"); + + ILGenerator il = methodBuilder.GetILGenerator(); + + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr)); + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + LocalBuilder propStore = il.DeclareLocal(prop.PropertyType); + LocalBuilder wrapRet = il.DeclareLocal(typeof(int)); + LocalBuilder ex = il.DeclareLocal(typeof(Exception)); + + Label exceptionBlock = il.BeginExceptionBlock(); + Label retPoint = il.DefineLabel(); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Stloc, L); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, ObjectTranslatorPool_FindTranslator); + il.Emit(OpCodes.Stloc, translator); + + if (genGetter) + { + if (!op.IsStatic) + { + EmitGetObject(il, 1, prop.DeclaringType, L, translator, null); + if (prop.DeclaringType.IsValueType) + { + var self = il.DeclareLocal(prop.DeclaringType); + il.Emit(OpCodes.Stloc, self); + il.Emit(OpCodes.Ldloca, self); + il.Emit(OpCodes.Call, op); + emitUpdateIfNeeded(il, L, translator, prop.DeclaringType, 1, self.LocalIndex); + } + else + { + il.Emit(OpCodes.Callvirt, op); + } + } + else + { + il.Emit(OpCodes.Call, op); + } + il.Emit(OpCodes.Stloc, propStore); + emitPush(il, prop.PropertyType, (short)propStore.LocalIndex, false, L, translator, false); + } + else + { + if (!op.IsStatic) + { + EmitGetObject(il, 1, prop.DeclaringType, L, translator, null); + LocalBuilder self = null; + if (prop.DeclaringType.IsValueType) + { + self = il.DeclareLocal(prop.DeclaringType); + il.Emit(OpCodes.Stloc, self); + il.Emit(OpCodes.Ldloca, self); + } + EmitGetObject(il, 2, prop.PropertyType, L, translator, null); + il.Emit(prop.DeclaringType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, op); + if (self != null) + { + emitUpdateIfNeeded(il, L, translator, prop.DeclaringType, 1, self.LocalIndex); + } + } + else + { + EmitGetObject(il, 1, prop.PropertyType, L, translator, null); + il.Emit(OpCodes.Call, op); + } + } + + il.Emit(OpCodes.Leave, exceptionBlock); + + emitCatchBlock(il, ex, wrapRet, retPoint, exceptionBlock); + + il.Emit(genGetter ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Ret); + + il.MarkLabel(retPoint); + il.Emit(OpCodes.Ldloc, wrapRet); + il.Emit(OpCodes.Ret); + + return methodBuilder; + } + + static HashSet BlackList = new HashSet(); + + static void addToBlackList(List info) + { + try + { + var type = Type.GetType(info[0], true); + var members = type.GetMember(info[1], BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); + foreach(var member in members) + { + if (member.MemberType == MemberTypes.Method) + { + var mb = member as MethodBase; + var parameters = mb.GetParameters(); + if (parameters.Length != info.Count - 2) + { + continue; + } + + bool paramsMatch = true; + + for (int i = 0; i < parameters.Length; i++) + { + if (parameters[i].ParameterType.FullName != info[i + 2]) + { + paramsMatch = false; + break; + } + } + if (paramsMatch) + { + BlackList.Add(member); + } + } + else if (info.Count == 2) + { + BlackList.Add(member); + } + } + } catch { } + } + + static void initBlackList() + { + foreach (var t in Utils.GetAllTypes(true)) + { + if (!t.IsAbstract || !t.IsSealed) continue; + + var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < fields.Length; i++) + { + var field = fields[i]; + if (field.IsDefined(typeof(BlackListAttribute), false) + && (typeof(List>)).IsAssignableFrom(field.FieldType)) + { + foreach (var info in (field.GetValue(null) as List>)) + { + addToBlackList(info); + } + } + } + + var props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < props.Length; i++) + { + var prop = props[i]; + if (prop.IsDefined(typeof(BlackListAttribute), false) + && (typeof(List>)).IsAssignableFrom(prop.PropertyType)) + { + foreach (var info in (prop.GetValue(null, null) as List>)) + { + addToBlackList(info); + } + } + } + } + } + + static bool isMemberInBlackList(MemberInfo mb) + { + if (mb is FieldInfo && (mb as FieldInfo).FieldType.IsPointer) return true; + if (mb is PropertyInfo && (mb as PropertyInfo).PropertyType.IsPointer) return true; + + if (mb.IsDefined(typeof(BlackListAttribute), false) || mb.IsDefined(typeof(ObsoleteAttribute), false)) return true; + + return BlackList.Contains(mb); + } + + static bool isMethodInBlackList(MethodBase mb) + { + if (mb.GetParameters().Any(pInfo => pInfo.ParameterType.IsPointer)) return true; + if (mb is MethodInfo && (mb as MethodInfo).ReturnType.IsPointer) return false; + + if (mb.IsDefined(typeof(BlackListAttribute), false) || mb.IsDefined(typeof(ObsoleteAttribute), false)) return true; + + return BlackList.Contains(mb); + } + + public Type EmitTypeWrap(Type toBeWrap) + { + TypeBuilder wrapTypeBuilder = CodeEmitModule.DefineType(toBeWrap.Name + "Wrap" + (genID++), TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed); + + var methodBuilder = wrapTypeBuilder.DefineMethod("__Register", MethodAttributes.Static | MethodAttributes.Public, null, parameterTypeOfWrap); + methodBuilder.DefineParameter(1, ParameterAttributes.None, "L"); + + ILGenerator il = methodBuilder.GetILGenerator(); + + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, ObjectTranslatorPool_FindTranslator); + il.Emit(OpCodes.Stloc, translator); + + var instanceFlag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; + var staticFlag = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly; + + var instanceFields = toBeWrap.GetFields(instanceFlag).Where(m => !isMemberInBlackList(m)); + var instanceProperties = toBeWrap.GetProperties(instanceFlag).Where(m => !isMemberInBlackList(m)); + var extensionMethods = Utils.GetExtensionMethodsOf(toBeWrap); + extensionMethods = (extensionMethods == null) ? Enumerable.Empty() : extensionMethods.Where(m => !isMemberInBlackList(m)); + var instanceMethods = toBeWrap.GetMethods(instanceFlag) + .Where(m => !isMethodInBlackList(m)) + .Concat(extensionMethods) + .Where(m => Utils.IsSupportedMethod(m)) + .Where(m => !m.IsSpecialName + || ( + ((m.Name == "get_Item" && m.GetParameters().Length == 1) || (m.Name == "set_Item" && m.GetParameters().Length == 2)) + && m.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string)) + ) + ).GroupBy(m => m.Name).ToList(); + var supportOperators = toBeWrap.GetMethods(staticFlag) + .Where(m => !isMethodInBlackList(m)) + .Where(m => m.IsSpecialName && InternalGlobals.supportOp.ContainsKey(m.Name)) + .GroupBy(m => m.Name); + + //begin obj + il.Emit(OpCodes.Ldtoken, toBeWrap); + il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(type) + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Call, Utils_BeginObjectRegister); + + foreach(var field in instanceFields) + { + emitRegisterFunc(il, emitFieldWrap(wrapTypeBuilder, field, true), Utils.GETTER_IDX, field.Name); + emitRegisterFunc(il, emitFieldWrap(wrapTypeBuilder, field, false), Utils.SETTER_IDX, field.Name); + } + + List itemGetter = new List(); + List itemSetter = new List(); + + foreach(var prop in instanceProperties) + { + var getter = prop.GetGetMethod(); + if (getter != null && getter.IsPublic) + { + if (prop.GetIndexParameters().Length > 0) + { + if (!prop.GetIndexParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) + { + itemGetter.Add(getter); + } + } + else + { + emitRegisterFunc(il, emitPropertyWrap(wrapTypeBuilder, prop, getter, true), Utils.GETTER_IDX, prop.Name); + } + } + + var setter = prop.GetSetMethod(); + if (setter != null && setter.IsPublic) + { + if (prop.GetIndexParameters().Length > 0) + { + if (!prop.GetIndexParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) + { + itemSetter.Add(setter); + } + } + else + { + emitRegisterFunc(il, emitPropertyWrap(wrapTypeBuilder, prop, setter, false), Utils.SETTER_IDX, prop.Name); + } + } + } + + foreach (var group in instanceMethods) + { + emitRegisterFunc(il, emitMethodWrap(wrapTypeBuilder, group.Cast().ToList(), false, toBeWrap), Utils.METHOD_IDX, group.Key); + } + + foreach (var group in supportOperators) + { + emitRegisterFunc(il, emitMethodWrap(wrapTypeBuilder, group.Cast().ToList(), false, toBeWrap), Utils.OBJ_META_IDX, InternalGlobals.supportOp[group.Key]); + } + + foreach (var ev in toBeWrap.GetEvents(instanceFlag).Where(m => !isMemberInBlackList(m))) + { + emitRegisterFunc(il, emitEventWrap(wrapTypeBuilder, ev), Utils.METHOD_IDX, ev.Name); + } + + //end obj + il.Emit(OpCodes.Ldtoken, toBeWrap); + il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(type) + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldnull); + if (itemGetter.Count > 0) + { + il.Emit(OpCodes.Ldftn, emitMethodWrap(wrapTypeBuilder, itemGetter, true, toBeWrap)); + il.Emit(OpCodes.Newobj, LuaCSFunction_Constructor); + } + il.Emit(OpCodes.Ldnull); + if (itemSetter.Count > 0) + { + il.Emit(OpCodes.Ldftn, emitMethodWrap(wrapTypeBuilder, itemSetter, true, toBeWrap)); + il.Emit(OpCodes.Newobj, LuaCSFunction_Constructor); + } + il.Emit(OpCodes.Ldnull); + il.Emit(OpCodes.Ldnull); + il.Emit(OpCodes.Ldnull); + il.Emit(OpCodes.Call, Utils_EndObjectRegister); + + // begin class + il.Emit(OpCodes.Ldtoken, toBeWrap); + il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(type) + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldnull); + il.Emit(OpCodes.Ldftn, emitMethodWrap(wrapTypeBuilder, + toBeWrap.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase) + .Where(m => !isMethodInBlackList(m)) + .Cast().ToList(), false, toBeWrap, toBeWrap.ToString() + " constructor")); + il.Emit(OpCodes.Newobj, LuaCSFunction_Constructor); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Call, Utils_BeginClassRegister); + + var staticMethods = toBeWrap.GetMethods(staticFlag) + .Where(m => !isMethodInBlackList(m)) + .Where(m => Utils.IsSupportedMethod(m)) + .Where(m => !m.IsSpecialName).GroupBy(m => m.Name); + + var staticFields = toBeWrap.GetFields(staticFlag).Where(m => !isMemberInBlackList(m)); + + var staticProperties = toBeWrap.GetProperties(staticFlag).Where(m => !isMemberInBlackList(m)); + + foreach (var group in staticMethods) + { + emitRegisterFunc(il, emitMethodWrap(wrapTypeBuilder, group.Cast().ToList(), false, toBeWrap), Utils.CLS_IDX, group.Key); + } + + foreach (var ev in toBeWrap.GetEvents(staticFlag).Where(m => !isMemberInBlackList(m))) + { + emitRegisterFunc(il, emitEventWrap(wrapTypeBuilder, ev), Utils.CLS_IDX, ev.Name); + } + + foreach (var prop in staticProperties) + { + var getter = prop.GetGetMethod(); + if (getter != null && getter.IsPublic) + { + emitRegisterFunc(il, emitPropertyWrap(wrapTypeBuilder, prop, getter, true), Utils.GETTER_IDX, prop.Name); + } + + var setter = prop.GetSetMethod(); + if (setter != null && setter.IsPublic) + { + emitRegisterFunc(il, emitPropertyWrap(wrapTypeBuilder, prop, setter, false), Utils.SETTER_IDX, prop.Name); + } + } + + foreach (var field in staticFields) + { + if (field.IsInitOnly || field.IsLiteral) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldc_I4, Utils.CLS_IDX); + il.Emit(OpCodes.Ldstr, field.Name); + if (field.IsLiteral) + { + LocalBuilder literalStore = il.DeclareLocal(field.FieldType); + emitLiteralLoad(il, field.FieldType, field.GetValue(null), literalStore.LocalIndex); + il.Emit(OpCodes.Stloc, literalStore); + il.Emit(OpCodes.Ldloc, literalStore); + } + else + { + il.Emit(OpCodes.Ldsfld, field); + } + if (field.FieldType.IsValueType) + { + il.Emit(OpCodes.Box, field.FieldType); + } + il.Emit(OpCodes.Call, Utils_RegisterObject); + } + else + { + emitRegisterFunc(il, emitFieldWrap(wrapTypeBuilder, field, true), Utils.CLS_GETTER_IDX, field.Name); + emitRegisterFunc(il, emitFieldWrap(wrapTypeBuilder, field, false), Utils.CLS_SETTER_IDX, field.Name); + } + } + + //end class + il.Emit(OpCodes.Ldtoken, toBeWrap); + il.Emit(OpCodes.Call, Type_GetTypeFromHandle); // typeof(type) + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Call, Utils_EndClassRegister); + + il.Emit(OpCodes.Ret); + + return wrapTypeBuilder.CreateType(); + } + + MethodBuilder emitEventWrap(TypeBuilder typeBuilder, EventInfo ev) + { + var addEvent = ev.GetAddMethod(); + var removeEvent = ev.GetRemoveMethod(); + + if (addEvent == null && removeEvent == null) + { + return null; + } + + bool isStatic = addEvent != null ? addEvent.IsStatic : removeEvent.IsStatic; + + var methodBuilder = typeBuilder.DefineMethod(ev.Name + (genID++), MethodAttributes.Static, typeof(int), parameterTypeOfWrap); + methodBuilder.DefineParameter(1, ParameterAttributes.None, "L"); + + ILGenerator il = methodBuilder.GetILGenerator(); + + LocalBuilder wrapRet = il.DeclareLocal(typeof(int)); + LocalBuilder ex = il.DeclareLocal(typeof(Exception)); + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr)); + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + LocalBuilder callback = il.DeclareLocal(ev.EventHandlerType); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Stloc, L); + + Label exceptionBlock = il.BeginExceptionBlock(); + Label retPoint = il.DefineLabel(); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, ObjectTranslatorPool_FindTranslator); + il.Emit(OpCodes.Stloc, translator); + + EmitGetObject(il, isStatic ? 2 : 3, ev.EventHandlerType, L, translator, null); + il.Emit(OpCodes.Stloc, callback); + il.Emit(OpCodes.Ldloc, callback); + Label ifBlock = il.DefineLabel(); + il.Emit(OpCodes.Brtrue, ifBlock); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldstr, string.Format("#{0}, need {1}", isStatic ? 2 : 3, ev.EventHandlerType)); + il.Emit(OpCodes.Call, LuaAPI_luaL_error); + il.Emit(OpCodes.Stloc, wrapRet); + il.Emit(OpCodes.Leave, retPoint); + il.MarkLabel(ifBlock); + + if (addEvent != null) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(isStatic ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_2); + il.Emit(OpCodes.Ldstr, "+"); + il.Emit(OpCodes.Call, LuaAPI_xlua_is_eq_str); + ifBlock = il.DefineLabel(); + il.Emit(OpCodes.Brfalse, ifBlock); + + if (!isStatic) + { + EmitGetObject(il, 1, ev.DeclaringType, L, translator, null); + if (ev.DeclaringType.IsValueType) + { + var self = il.DeclareLocal(ev.DeclaringType); + il.Emit(OpCodes.Stloc, self); + il.Emit(OpCodes.Ldloca, self); + } + } + il.Emit(OpCodes.Ldloc, callback); + il.Emit(OpCodes.Call, addEvent); + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Leave, retPoint); + il.MarkLabel(ifBlock); + } + + if (removeEvent != null) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(isStatic ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_2); + il.Emit(OpCodes.Ldstr, "-"); + il.Emit(OpCodes.Call, LuaAPI_xlua_is_eq_str); + ifBlock = il.DefineLabel(); + il.Emit(OpCodes.Brfalse, ifBlock); + + if (!isStatic) + { + EmitGetObject(il, 1, ev.DeclaringType, L, translator, null); + if (ev.DeclaringType.IsValueType) + { + var self = il.DeclareLocal(ev.DeclaringType); + il.Emit(OpCodes.Stloc, self); + il.Emit(OpCodes.Ldloca, self); + } + } + il.Emit(OpCodes.Ldloc, callback); + il.Emit(OpCodes.Call, removeEvent); + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Leave, retPoint); + il.MarkLabel(ifBlock); + } + + il.Emit(OpCodes.Leave, exceptionBlock); + + emitCatchBlock(il, ex, wrapRet, retPoint, exceptionBlock); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldstr, "invalid arguments to " + ev.DeclaringType + "." + ev.Name + "!"); + il.Emit(OpCodes.Call, LuaAPI_luaL_error); + il.Emit(OpCodes.Ret); + + il.MarkLabel(retPoint); + il.Emit(OpCodes.Ldloc, wrapRet); + il.Emit(OpCodes.Ret); + + return methodBuilder; + } + + void emitUpdateIfNeeded(ILGenerator il, LocalBuilder L, LocalBuilder translator, Type type, int luaIndex, int localIndex) + { + if (type.IsValueType && !type.IsPrimitive && !type.IsEnum() && type != typeof(decimal)) + { + //UnityEngine.Debug.LogWarning("-----------------emit update:" + type); + il.Emit(OpCodes.Ldloc, translator); + il.Emit(OpCodes.Ldloc, L); + il.Emit(OpCodes.Ldc_I4, luaIndex); + il.Emit(OpCodes.Ldloc, localIndex); + il.Emit(OpCodes.Box, type); + il.Emit(OpCodes.Callvirt, ObjectTranslator_Update); + } + } + + //private MethodInfo UnityEngine_Debug_Log = typeof(UnityEngine.Debug).GetMethod("Log", new Type[] { typeof(object)}); + int firstDefaultValue(MethodBase method) + { + var parameters = method.GetParameters(); + for(int i = 0; i < parameters.Length; i++) + { + if (parameters[i].IsOptional) return i; + } + return -1; + } + + MethodBuilder emitMethodWrap(TypeBuilder typeBuilder, List methodsToCall, bool isIndexer, Type declaringType, string methodDesciption = null) + { + string wrapName = (methodsToCall.Count > 0 ? methodsToCall[0].Name : "Constructor"); + var methodBuilder = typeBuilder.DefineMethod(wrapName + (genID++), MethodAttributes.Static, typeof(int), parameterTypeOfWrap); + methodBuilder.DefineParameter(1, ParameterAttributes.None, "L"); + + bool needCheckParameterType = (methodsToCall.Count > 1) || isIndexer; + + if (methodsToCall.Count == 0 || methodsToCall[0].IsConstructor) + { + needCheckParameterType = true; + } + + if (methodsToCall.Count == 1 && firstDefaultValue(methodsToCall[0]) != -1) + { + needCheckParameterType = true; + } + + ILGenerator il = methodBuilder.GetILGenerator(); + + LocalBuilder wrapRet = il.DeclareLocal(typeof(int)); + LocalBuilder ex = il.DeclareLocal(typeof(Exception)); + LocalBuilder L = il.DeclareLocal(typeof(RealStatePtr)); + LocalBuilder translator = il.DeclareLocal(typeof(ObjectTranslator)); + LocalBuilder top = il.DeclareLocal(typeof(int)); + + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Stloc, L); + + Label exceptionBlock = il.BeginExceptionBlock(); + Label retPoint = il.DefineLabel(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, ObjectTranslatorPool_FindTranslator); + il.Emit(OpCodes.Stloc, translator); + + if (needCheckParameterType) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, LuaAPI_lua_gettop); + il.Emit(OpCodes.Stloc, top); + } + + for (int i = 0; i < methodsToCall.Count; i++) + { + var method = methodsToCall[i]; + if ((method is MethodInfo) && method.ContainsGenericParameters) + { + method = Utils.MakeGenericMethodWithConstraints(method as MethodInfo); + } + bool isStatic = method.IsStatic; + var paramInfos = method.GetParameters(); + int minInParamCount = 0; + int maxInParamCount = 0; + int outParamCount = 0; + bool hasParams = paramInfos.Length > 0 && paramInfos[paramInfos.Length - 1].IsDefined(typeof(ParamArrayAttribute), false); + bool hasOptional = false; + + LocalBuilder methodReturn = null; + + for (int j = 0; j < paramInfos.Length; j++) + { + if (!paramInfos[j].IsOut) + { + if (!paramInfos[j].IsOptional && (!hasParams || j != paramInfos.Length - 1)) + { + minInParamCount++; + } + maxInParamCount++; + } + if (paramInfos[j].IsOptional) + { + hasOptional = true; + } + if (paramInfos[j].ParameterType.IsByRef) + { + outParamCount++; + } + } + + Label endOfBlock = il.DefineLabel(); + + if (needCheckParameterType) + { + il.Emit(OpCodes.Ldloc, top); + il.Emit(OpCodes.Ldc_I4, minInParamCount + (isStatic ? 0 : 1)); + il.Emit((hasParams || hasOptional) ? OpCodes.Blt : OpCodes.Bne_Un, endOfBlock); + + if (hasOptional && !hasParams) + { + il.Emit(OpCodes.Ldloc, top); + il.Emit(OpCodes.Ldc_I4, maxInParamCount + (isStatic ? 0 : 1)); + il.Emit(OpCodes.Bgt, endOfBlock); + } + + if (!isStatic && !method.IsConstructor) + { + checkType(il, method.DeclaringType, translator, 1, endOfBlock, false, false); + } + + int argPos = isStatic ? 1 : 2; + + for (int j = 0; j < paramInfos.Length; j++) + { + var paramInfo = paramInfos[j]; + if (!paramInfo.IsOut) + { + var rawParamType = paramInfo.ParameterType; + if (rawParamType.IsByRef) + { + rawParamType = rawParamType.GetElementType(); + } + checkType(il, rawParamType, translator, argPos++, endOfBlock, + hasParams && (j == paramInfos.Length - 1), paramInfo.IsOptional); + } + } + } + + int luaPos = isStatic ? 1 : 2; + + int argStoreStart = -1; + + for (int j = 0; j < paramInfos.Length; j++) + { + var paramInfo = paramInfos[j]; + var paramRawType = paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : + paramInfo.ParameterType; + var argStore = il.DeclareLocal(paramRawType); + if (paramInfo.IsOptional) + { + //UnityEngine.Debug.Log(paramInfo.Name + "," + paramRawType + "," + paramInfo.DefaultValue); + emitLiteralLoad(il, paramRawType, paramInfo.DefaultValue, argStore.LocalIndex); + il.Emit(OpCodes.Stloc, argStore); + } + //UnityEngine.Debug.LogWarning(declaringType.Name + "." + method.Name + "." + paramInfos[j].Name + " pos(d):" + argStore.LocalIndex + ", pt:" + paramRawType + ", j:" + j); + if (argStoreStart == -1) + { + argStoreStart = argStore.LocalIndex; + } + + } + for (int j = 0; j < paramInfos.Length; j++) + { + var paramInfo = paramInfos[j]; + var paramRawType = paramInfo.ParameterType.IsByRef ? paramInfo.ParameterType.GetElementType() : + paramInfo.ParameterType; + if (!paramInfo.IsOut) + { + Label endOfGetValue = il.DefineLabel(); + if (paramInfo.IsOptional) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, luaPos); + il.Emit(OpCodes.Call, LuaAPI_lua_type); + il.Emit(OpCodes.Ldc_I4_M1); + il.Emit(OpCodes.Beq, endOfGetValue); + } + EmitGetObject(il, luaPos++, paramRawType, L, translator, null, hasParams && (j == paramInfos.Length - 1)); + il.Emit(OpCodes.Stloc, argStoreStart + j); + il.MarkLabel(endOfGetValue); + } + } + + LocalBuilder valueTypeTmp = null; + + if (!isStatic && (!method.IsConstructor || method.DeclaringType.IsValueType)) + { + if (!method.IsConstructor) + { + EmitGetObject(il, 1, method.DeclaringType, L, translator, null); + } + if (method.DeclaringType.IsValueType) + { + if (method.IsConstructor) + { + methodReturn = il.DeclareLocal(method.DeclaringType); + il.Emit(OpCodes.Ldloca, methodReturn); + } + else + { + valueTypeTmp = il.DeclareLocal(method.DeclaringType); + il.Emit(OpCodes.Stloc, valueTypeTmp); + il.Emit(OpCodes.Ldloca, valueTypeTmp); + } + } + } + + for (int j = 0; j < paramInfos.Length; j++) + { + //UnityEngine.Debug.LogWarning(declaringType.Name + "." + method.Name + "." + paramInfos[j].Name +" pos:" + (argStoreStart + j) + ", op:" + (paramInfos[j].ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc) + ", j:" + j ); + il.Emit(paramInfos[j].ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc, argStoreStart + j); + } + + if (method.IsConstructor) + { + if (method.DeclaringType.IsValueType) + { + il.Emit(OpCodes.Call, method as ConstructorInfo); + } + else + { + il.Emit(OpCodes.Newobj, method as ConstructorInfo); + } + } + else + { + il.Emit(isStatic ? OpCodes.Call : OpCodes.Callvirt, method as MethodInfo); + } + + if (valueTypeTmp != null) + { + emitUpdateIfNeeded(il, L, translator, method.DeclaringType, 1, valueTypeTmp.LocalIndex); + } + + if (isIndexer) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Call, LuaAPI_lua_pushboolean); + } + + bool hasReturn = false; + + MethodInfo methodInfo = method as MethodInfo; + if (methodInfo == null || methodInfo.ReturnType != typeof(void)) + { + hasReturn = true; + Type returnType = methodInfo == null ? method.DeclaringType : methodInfo.ReturnType; + if (methodReturn == null) + { + methodReturn = il.DeclareLocal(returnType); + il.Emit(OpCodes.Stloc, methodReturn); + } + emitPush(il, returnType, (short)methodReturn.LocalIndex, false, L, translator, false); + } + + int luaIndex = isStatic ? 1 : 2; + for (int j = 0; j < paramInfos.Length; j++) + { + if (paramInfos[j].ParameterType.IsByRef) + { + var rawParamType = paramInfos[j].ParameterType.GetElementType(); + emitPush(il, rawParamType, + (short)(argStoreStart + j), false, L, translator, false); + if (!paramInfos[j].IsOut) + { + emitUpdateIfNeeded(il, L, translator, rawParamType, luaIndex, argStoreStart + j); + } + } + if (!paramInfos[j].IsOut) + { + luaIndex++; + } + } + + il.Emit(OpCodes.Ldc_I4, outParamCount + (hasReturn ? 1 : 0) + (isIndexer ? 1 : 0)); + il.Emit(OpCodes.Stloc, wrapRet); + il.Emit(OpCodes.Leave, retPoint); + //il.Emit(OpCodes.Ret); + + if (needCheckParameterType) + { + il.MarkLabel(endOfBlock); + } + } + + if (declaringType.IsValueType && (methodsToCall.Count == 0 || methodsToCall[0].IsConstructor)) + { + Label endOfBlock = il.DefineLabel(); + il.Emit(OpCodes.Ldloc, top); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Bne_Un, endOfBlock); + + var methodReturn = il.DeclareLocal(declaringType); + + il.Emit(OpCodes.Ldloca, methodReturn); + il.Emit(OpCodes.Initobj, declaringType); + emitPush(il, declaringType, (short)methodReturn.LocalIndex, false, L, translator, false); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Stloc, wrapRet); + il.Emit(OpCodes.Leave_S, retPoint); + il.MarkLabel(endOfBlock); + } + + il.Emit(OpCodes.Leave, exceptionBlock); + emitCatchBlock(il, ex, wrapRet, retPoint, exceptionBlock); + + if (needCheckParameterType) + { + if (isIndexer) + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4_0); + il.Emit(OpCodes.Call, LuaAPI_lua_pushboolean); + il.Emit(OpCodes.Ldc_I4_1); + il.Emit(OpCodes.Ret); + } + else + { + il.Emit(OpCodes.Ldarg_0); + if (methodDesciption == null) + { + if (methodsToCall.Count > 0) + { + methodDesciption = declaringType + "." + methodsToCall[0].Name; + } + else + { + methodDesciption = "unknow method in " + declaringType; + } + } + il.Emit(OpCodes.Ldstr, "invalid arguments to " + methodDesciption + "!"); + il.Emit(OpCodes.Call, LuaAPI_luaL_error); + il.Emit(OpCodes.Ret); + } + } + + il.MarkLabel(retPoint); + il.Emit(OpCodes.Ldloc, wrapRet); + il.Emit(OpCodes.Ret); + + return methodBuilder; + } + } +} + +#endif diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CodeEmit.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CodeEmit.cs.meta new file mode 100644 index 0000000..c3d28ff --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CodeEmit.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f8dcc04206f3524478d86191b3d7e636 +timeCreated: 1470883945 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CopyByValue.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CopyByValue.cs new file mode 100644 index 0000000..d82e1bf --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CopyByValue.cs @@ -0,0 +1,150 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; + +namespace XLua +{ + public static partial class CopyByValue + { + // for int 8 + public static bool Pack(IntPtr buff, int offset, byte field) + { + return LuaAPI.xlua_pack_int8_t(buff, offset, field); + } + public static bool UnPack(IntPtr buff, int offset, out byte field) + { + return LuaAPI.xlua_unpack_int8_t(buff, offset, out field); + } + public static bool Pack(IntPtr buff, int offset, sbyte field) + { + return LuaAPI.xlua_pack_int8_t(buff, offset, (byte)field); + } + public static bool UnPack(IntPtr buff, int offset, out sbyte field) + { + byte tfield; + bool ret = LuaAPI.xlua_unpack_int8_t(buff, offset, out tfield); + field = (sbyte)tfield; + return ret; + } + // for int16 + public static bool Pack(IntPtr buff, int offset, short field) + { + return LuaAPI.xlua_pack_int16_t(buff, offset, field); + } + public static bool UnPack(IntPtr buff, int offset, out short field) + { + return LuaAPI.xlua_unpack_int16_t(buff, offset, out field); + } + public static bool Pack(IntPtr buff, int offset, ushort field) + { + return LuaAPI.xlua_pack_int16_t(buff, offset, (short)field); + } + public static bool UnPack(IntPtr buff, int offset, out ushort field) + { + short tfield; + bool ret = LuaAPI.xlua_unpack_int16_t(buff, offset, out tfield); + field = (ushort)tfield; + return ret; + } + // for int32 + public static bool Pack(IntPtr buff, int offset, int field) + { + return LuaAPI.xlua_pack_int32_t(buff, offset, field); + } + public static bool UnPack(IntPtr buff, int offset, out int field) + { + return LuaAPI.xlua_unpack_int32_t(buff, offset, out field); + } + public static bool Pack(IntPtr buff, int offset, uint field) + { + return LuaAPI.xlua_pack_int32_t(buff, offset, (int)field); + } + public static bool UnPack(IntPtr buff, int offset, out uint field) + { + int tfield; + bool ret = LuaAPI.xlua_unpack_int32_t(buff, offset, out tfield); + field = (uint)tfield; + return ret; + } + // for int64 + public static bool Pack(IntPtr buff, int offset, long field) + { + return LuaAPI.xlua_pack_int64_t(buff, offset, field); + } + public static bool UnPack(IntPtr buff, int offset, out long field) + { + return LuaAPI.xlua_unpack_int64_t(buff, offset, out field); + } + public static bool Pack(IntPtr buff, int offset, ulong field) + { + return LuaAPI.xlua_pack_int64_t(buff, offset, (long)field); + } + public static bool UnPack(IntPtr buff, int offset, out ulong field) + { + long tfield; + bool ret = LuaAPI.xlua_unpack_int64_t(buff, offset, out tfield); + field = (ulong)tfield; + return ret; + } + // for float + public static bool Pack(IntPtr buff, int offset, float field) + { + return LuaAPI.xlua_pack_float(buff, offset, field); + } + public static bool UnPack(IntPtr buff, int offset, out float field) + { + return LuaAPI.xlua_unpack_float(buff, offset, out field); + } + // for double + public static bool Pack(IntPtr buff, int offset, double field) + { + return LuaAPI.xlua_pack_double(buff, offset, field); + } + public static bool UnPack(IntPtr buff, int offset, out double field) + { + return LuaAPI.xlua_unpack_double(buff, offset, out field); + } + // for decimal + public static bool Pack(IntPtr buff, int offset, decimal field) + { + return LuaAPI.xlua_pack_decimal(buff, offset, ref field); + } + public static bool UnPack(IntPtr buff, int offset, out decimal field) + { + byte scale; + byte sign; + int hi32; + ulong lo64; + if (!LuaAPI.xlua_unpack_decimal(buff, offset, out scale, out sign, out hi32, out lo64)) + { + field = default(decimal); + return false; + } + + field = new Decimal((int)(lo64 & 0xFFFFFFFF), (int)(lo64 >> 32), hi32, (sign & 0x80) != 0, scale); + return true; + } + + public static bool IsStruct(Type type) + { + return type.IsValueType() && !type.IsEnum() && !type.IsPrimitive(); + } + + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CopyByValue.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CopyByValue.cs.meta new file mode 100644 index 0000000..7fafbfb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/CopyByValue.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 72828be0a8440c642a2426f9375f82a9 +timeCreated: 1467189953 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/DelegateBridge.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/DelegateBridge.cs new file mode 100644 index 0000000..1bf5d0a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/DelegateBridge.cs @@ -0,0 +1,246 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace XLua +{ + public abstract class DelegateBridgeBase : LuaBase + { + private Type firstKey = null; + + private Delegate firstValue = null; + + private Dictionary bindTo = null; + + protected int errorFuncRef; + + public DelegateBridgeBase(int reference, LuaEnv luaenv) : base(reference, luaenv) + { + errorFuncRef = luaenv.errorFuncRef; + } + + public bool TryGetDelegate(Type key, out Delegate value) + { + if(key == firstKey) + { + value = firstValue; + return true; + } + if (bindTo != null) + { + return bindTo.TryGetValue(key, out value); + } + value = null; + return false; + } + + public void AddDelegate(Type key, Delegate value) + { + if (key == firstKey) + { + throw new ArgumentException("An element with the same key already exists in the dictionary."); + } + + if (firstKey == null && bindTo == null) // nothing + { + firstKey = key; + firstValue = value; + } + else if (firstKey != null && bindTo == null) // one key existed + { + bindTo = new Dictionary(); + bindTo.Add(firstKey, firstValue); + firstKey = null; + firstValue = null; + bindTo.Add(key, value); + } + else + { + bindTo.Add(key, value); + } + } + + public virtual Delegate GetDelegateByType(Type type) + { + return null; + } + } + + public static class HotfixDelegateBridge + { +#if (UNITY_IPHONE || UNITY_TVOS) && !UNITY_EDITOR + [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_get_hotfix_flag(int idx); + + + [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_set_hotfix_flag(int idx, bool flag); +#else + public static bool xlua_get_hotfix_flag(int idx) + { + return (idx < DelegateBridge.DelegateBridgeList.Length) && (DelegateBridge.DelegateBridgeList[idx] != null); + } +#endif + + public static DelegateBridge Get(int idx) + { + return DelegateBridge.DelegateBridgeList[idx]; + } + + public static void Set(int idx, DelegateBridge val) + { + if (idx >= DelegateBridge.DelegateBridgeList.Length) + { + DelegateBridge[] newList = new DelegateBridge[idx + 1]; + for (int i = 0; i < DelegateBridge.DelegateBridgeList.Length; i++) + { + newList[i] = DelegateBridge.DelegateBridgeList[i]; + } + DelegateBridge.DelegateBridgeList = newList; + } + DelegateBridge.DelegateBridgeList[idx] = val; +#if (UNITY_IPHONE || UNITY_TVOS) && !UNITY_EDITOR + xlua_set_hotfix_flag(idx, val != null); +#endif + } + } + + public partial class DelegateBridge : DelegateBridgeBase + { + internal static DelegateBridge[] DelegateBridgeList = new DelegateBridge[0]; + + public static bool Gen_Flag = false; + + public DelegateBridge(int reference, LuaEnv luaenv) : base(reference, luaenv) + { + } + + public void PCall(IntPtr L, int nArgs, int nResults, int errFunc) + { + if (LuaAPI.lua_pcall(L, nArgs, nResults, errFunc) != 0) + luaEnv.ThrowExceptionFromError(errFunc - 1); + } + +#if HOTFIX_ENABLE + + private int _oldTop = 0; + private Stack _stack = new Stack(); + + public void InvokeSessionStart() + { + System.Threading.Monitor.Enter(luaEnv.luaEnvLock); + var L = luaEnv.L; + _stack.Push(_oldTop); + _oldTop = LuaAPI.lua_gettop(L); + LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + } + + public void Invoke(int nRet) + { + int error = LuaAPI.lua_pcall(luaEnv.L, LuaAPI.lua_gettop(luaEnv.L) - _oldTop - 2, nRet, _oldTop + 1); + if (error != 0) + { + var lastOldTop = _oldTop; + _oldTop = _stack.Pop(); + System.Threading.Monitor.Exit(luaEnv.luaEnvLock); + luaEnv.ThrowExceptionFromError(lastOldTop); + } + } + + public void InvokeSessionEnd() + { + LuaAPI.lua_settop(luaEnv.L, _oldTop); + _oldTop = _stack.Pop(); + System.Threading.Monitor.Exit(luaEnv.luaEnvLock); + } + + public TResult InvokeSessionEndWithResult() + { + if (LuaAPI.lua_gettop(luaEnv.L) < _oldTop + 2) + { + InvokeSessionEnd(); + throw new InvalidOperationException("no result!"); + } + + try + { + TResult ret; + luaEnv.translator.Get(luaEnv.L, _oldTop + 2, out ret); + return ret; + } + finally + { + InvokeSessionEnd(); + } + } + + public void InParam(T p) + { + try + { + luaEnv.translator.PushByType(luaEnv.L, p); + } + catch (Exception e) + { + InvokeSessionEnd(); + throw e; + } + } + + public void InParams(T[] ps) + { + try + { + for (int i = 0; i < ps.Length; i++) + { + luaEnv.translator.PushByType(luaEnv.L, ps[i]); + } + } + catch (Exception e) + { + InvokeSessionEnd(); + throw e; + } + } + + //pos start from 0 + public void OutParam(int pos, out TResult ret) + { + if (LuaAPI.lua_gettop(luaEnv.L) < _oldTop + 2 + pos) + { + InvokeSessionEnd(); + throw new InvalidOperationException("no result in " + pos); + } + + try + { + luaEnv.translator.Get(luaEnv.L, _oldTop + 2 + pos, out ret); + } + catch (Exception e) + { + InvokeSessionEnd(); + throw e; + } + } +#endif + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/DelegateBridge.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/DelegateBridge.cs.meta new file mode 100644 index 0000000..509bf22 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/DelegateBridge.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6966e8b5bd3c7ea44b456a251d4d0327 +timeCreated: 1452574309 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor.meta new file mode 100644 index 0000000..027b4d8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: f9610f83376c97748a5db8a68b57d522 +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Generator.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Generator.cs new file mode 100644 index 0000000..1348b12 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Generator.cs @@ -0,0 +1,1834 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if !XLUA_GENERAL +using UnityEngine; +using UnityEditor; +#endif +using System.Collections.Generic; +using System.IO; +using XLua; +using System; +using System.Reflection; +using System.Text; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace CSObjectWrapEditor +{ + public static class GeneratorConfig + { +#if XLUA_GENERAL + public static string common_path = "./Gen/"; +#else + public static string common_path = Application.dataPath + "/XLua/Gen/"; +#endif + + static GeneratorConfig() + { + foreach(var type in (from type in XLua.Utils.GetAllTypes() + where type.IsAbstract && type.IsSealed + select type)) + { + foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) + { + if (field.FieldType == typeof(string) && field.IsDefined(typeof(GenPathAttribute), false)) + { + common_path = field.GetValue(null) as string; + if (!common_path.EndsWith("/")) + { + common_path = common_path + "/"; + } + } + } + + foreach (var prop in type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) + { + if (prop.PropertyType == typeof(string) && prop.IsDefined(typeof(GenPathAttribute), false)) + { + common_path = prop.GetValue(null, null) as string; + if (!common_path.EndsWith("/")) + { + common_path = common_path + "/"; + } + } + } + } + } + } + + public struct CustomGenTask + { + public LuaTable Data; + public TextWriter Output; + } + + public struct UserConfig + { + public IEnumerable LuaCallCSharp; + public IEnumerable CSharpCallLua; + public IEnumerable ReflectionUse; + } + + public class GenCodeMenuAttribute : Attribute + { + + } + + public class GenPathAttribute : Attribute + { + + } + + public struct XLuaTemplate + { + public string name; + public string text; + } + + public struct XLuaTemplates + { + public XLuaTemplate LuaClassWrap; + public XLuaTemplate LuaDelegateBridge; + public XLuaTemplate LuaDelegateWrap; + public XLuaTemplate LuaEnumWrap; + public XLuaTemplate LuaInterfaceBridge; + public XLuaTemplate LuaRegister; + public XLuaTemplate LuaWrapPusher; + public XLuaTemplate PackUnpack; + public XLuaTemplate TemplateCommon; + } + + public static class Generator + { + static LuaEnv luaenv = new LuaEnv(); + static List OpMethodNames = new List() { "op_Addition", "op_Subtraction", "op_Multiply", "op_Division", "op_Equality", "op_UnaryNegation", "op_LessThan", "op_LessThanOrEqual", "op_Modulus", + "op_BitwiseAnd", "op_BitwiseOr", "op_ExclusiveOr", "op_OnesComplement", "op_LeftShift", "op_RightShift"}; + private static XLuaTemplates templateRef; + + static Generator() + { +#if !XLUA_GENERAL + TemplateRef template_ref = ScriptableObject.CreateInstance(); + + templateRef = new XLuaTemplates() + { +#if GEN_CODE_MINIMIZE + LuaClassWrap = { name = template_ref.LuaClassWrapGCM.name, text = template_ref.LuaClassWrapGCM.text }, +#else + LuaClassWrap = { name = template_ref.LuaClassWrap.name, text = template_ref.LuaClassWrap.text }, +#endif + LuaDelegateBridge = { name = template_ref.LuaDelegateBridge.name, text = template_ref.LuaDelegateBridge.text }, + LuaDelegateWrap = { name = template_ref.LuaDelegateWrap.name, text = template_ref.LuaDelegateWrap.text }, +#if GEN_CODE_MINIMIZE + LuaEnumWrap = { name = template_ref.LuaEnumWrapGCM.name, text = template_ref.LuaEnumWrapGCM.text }, +#else + LuaEnumWrap = { name = template_ref.LuaEnumWrap.name, text = template_ref.LuaEnumWrap.text }, +#endif + LuaInterfaceBridge = { name = template_ref.LuaInterfaceBridge.name, text = template_ref.LuaInterfaceBridge.text }, +#if GEN_CODE_MINIMIZE + LuaRegister = { name = template_ref.LuaRegisterGCM.name, text = template_ref.LuaRegisterGCM.text }, +#else + LuaRegister = { name = template_ref.LuaRegister.name, text = template_ref.LuaRegister.text }, +#endif + LuaWrapPusher = { name = template_ref.LuaWrapPusher.name, text = template_ref.LuaWrapPusher.text }, + PackUnpack = { name = template_ref.PackUnpack.name, text = template_ref.PackUnpack.text }, + TemplateCommon = { name = template_ref.TemplateCommon.name, text = template_ref.TemplateCommon.text }, + }; +#endif + luaenv.AddLoader((ref string filepath) => + { + if (filepath == "TemplateCommon") + { + return Encoding.UTF8.GetBytes(templateRef.TemplateCommon.text); + } + else + { + return null; + } + }); + } + + static bool IsOverride(MethodBase method) + { + var m = method as MethodInfo; + return m != null && !m.IsConstructor && m.IsVirtual && (m.GetBaseDefinition().DeclaringType != m.DeclaringType); + } + + static int OverloadCosting(MethodBase mi) + { + int costing = 0; + + if (!mi.IsStatic) + { + costing++; + } + + foreach (var paraminfo in mi.GetParameters()) + { + if ((!paraminfo.ParameterType.IsPrimitive ) && (paraminfo.IsIn || !paraminfo.IsOut)) + { + costing++; + } + } + costing = costing * 10000 + (mi.GetParameters().Length + (mi.IsStatic ? 0 : 1)); + return costing; + } + + static IEnumerable type_has_extension_methods = null; + + static IEnumerable GetExtensionMethods(Type extendedType) + { + if (type_has_extension_methods == null) + { + var gen_types = LuaCallCSharp; + + type_has_extension_methods = from type in gen_types + where type.GetMethods(BindingFlags.Static | BindingFlags.Public) + .Any(method => isDefined(method, typeof(ExtensionAttribute))) + select type; + } + return from type in type_has_extension_methods + where type.IsSealed && !type.IsGenericType && !type.IsNested + from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) + where isSupportedExtensionMethod(method, extendedType) + select method; + } + + static bool isSupportedExtensionMethod(MethodBase method, Type extendedType) + { + if (!isDefined(method, typeof(ExtensionAttribute))) + return false; + var methodParameters = method.GetParameters(); + if (methodParameters.Length < 1) + return false; + + var hasValidGenericParameter = false; + for (var i = 0; i < methodParameters.Length; i++) + { + var parameterType = methodParameters[i].ParameterType; + if (i == 0) + { + if (parameterType.IsGenericParameter) + { + var parameterConstraints = parameterType.GetGenericParameterConstraints(); + if (parameterConstraints.Length == 0) return false; + bool firstParamMatch = false; + foreach (var parameterConstraint in parameterConstraints) + { + if (parameterConstraint != typeof(ValueType) && parameterConstraint.IsAssignableFrom(extendedType)) + { + firstParamMatch = true; + } + } + if (!firstParamMatch) return false; + + hasValidGenericParameter = true; + } + else if (parameterType != extendedType) + return false; + } + else if (parameterType.IsGenericParameter) + { + var parameterConstraints = parameterType.GetGenericParameterConstraints(); + if (parameterConstraints.Length == 0) return false; + foreach (var parameterConstraint in parameterConstraints) + { + if (!parameterConstraint.IsClass || (parameterConstraint == typeof(ValueType)) || Generator.hasGenericParameter(parameterConstraint)) + return false; + } + hasValidGenericParameter = true; + } + } + return hasValidGenericParameter || !method.ContainsGenericParameters; + } + + static bool IsDoNotGen(Type type, string name) + { + return DoNotGen.ContainsKey(type) && DoNotGen[type].Contains(name); + } + + static void getClassInfo(Type type, LuaTable parameters) + { + parameters.Set("type", type); + + var constructors = new List(); + var constructor_def_vals = new List(); + if (!type.IsAbstract) + { + foreach (var con in type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase).Cast() + .Where(constructor => !isMethodInBlackList(constructor) && !isObsolete(constructor))) + { + int def_count = 0; + constructors.Add(con); + constructor_def_vals.Add(def_count); + + var ps = con.GetParameters(); + for (int i = ps.Length - 1; i >= 0; i--) + { + if (ps[i].IsOptional || + (ps[i].IsDefined(typeof(ParamArrayAttribute), false) && i > 0 && ps[i - 1].IsOptional)) + { + def_count++; + constructors.Add(con); + constructor_def_vals.Add(def_count); + } + else + { + break; + } + } + } + } + parameters.Set("constructors", constructors); + parameters.Set("constructor_def_vals", constructor_def_vals); + + List extension_methods_namespace = new List(); + var extension_methods = type.IsInterface ? new MethodInfo[0]:GetExtensionMethods(type).ToArray(); + foreach(var extension_method in extension_methods) + { + if (extension_method.DeclaringType.Namespace != null + && extension_method.DeclaringType.Namespace != "System.Collections.Generic" + && extension_method.DeclaringType.Namespace != "XLua") + { + extension_methods_namespace.Add(extension_method.DeclaringType.Namespace); + } + } + parameters.Set("namespaces", extension_methods_namespace.Distinct().ToList()); + + List lazyMemberInfos = new List(); + + //warnning: filter all method start with "op_" "add_" "remove_" may filter some ordinary method + parameters.Set("methods", type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + .Where(method => !isDefined(method, typeof (ExtensionAttribute)) || method.GetParameters()[0].ParameterType.IsInterface || method.DeclaringType != type) + .Where(method => !method.IsSpecialName + || ( + ((method.Name == "get_Item" && method.GetParameters().Length == 1) || (method.Name == "set_Item" && method.GetParameters().Length == 2)) + && method.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string)) + ) + ) + .Concat(extension_methods) + .Where(method => !IsDoNotGen(type, method.Name)) + .Where(method => !isMethodInBlackList(method) && (!method.IsGenericMethod || extension_methods.Contains(method) || isSupportedGenericMethod(method)) && !isObsolete(method)) + .GroupBy(method => (method.Name + ((method.IsStatic && (!isDefined(method, typeof (ExtensionAttribute)) || method.GetParameters()[0].ParameterType.IsInterface)) ? "_xlua_st_" : "")), (k, v) => + { + var overloads = new List(); + List def_vals = new List(); + bool isOverride = false; + foreach (var overload in v.Cast().OrderBy(mb => OverloadCosting(mb))) + { + int def_count = 0; + overloads.Add(overload); + def_vals.Add(def_count); + + if (!isOverride) + { + isOverride = IsOverride(overload); + } + + var ps = overload.GetParameters(); + for (int i = ps.Length - 1; i >=0; i--) + { + if(ps[i].IsOptional || + (ps[i].IsDefined(typeof(ParamArrayAttribute), false) && i > 0 && ps[i - 1].IsOptional)) + { + def_count++; + overloads.Add(overload); + def_vals.Add(def_count); + } + else + { + break; + } + } + } + + return new { + Name = k, + IsStatic = overloads[0].IsStatic && (!isDefined(overloads[0], typeof(ExtensionAttribute)) || overloads[0].GetParameters()[0].ParameterType.IsInterface), + Overloads = overloads, + DefaultValues = def_vals + }; + }).ToList()); + + parameters.Set("getters", type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + + .Where(prop => prop.GetIndexParameters().Length == 0 && prop.CanRead && (prop.GetGetMethod() != null) && prop.Name != "Item" && !isObsolete(prop) && !isObsolete(prop.GetGetMethod()) && !isMemberInBlackList(prop) && !isMemberInBlackList(prop.GetGetMethod())).Select(prop => new { prop.Name, IsStatic = prop.GetGetMethod().IsStatic, ReadOnly = false, Type = prop.PropertyType }) + .Concat( + type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + .Where(field => !isObsolete(field) && !isMemberInBlackList(field)) + .Select(field => new { field.Name, field.IsStatic, ReadOnly = field.IsInitOnly || field.IsLiteral, Type = field.FieldType }) + ).Where(info => !IsDoNotGen(type, info.Name))/*.Where(getter => !typeof(Delegate).IsAssignableFrom(getter.Type))*/.ToList()); + + parameters.Set("setters", type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + .Where(prop => prop.GetIndexParameters().Length == 0 && prop.CanWrite && (prop.GetSetMethod() != null) && prop.Name != "Item" && !isObsolete(prop) && !isObsolete(prop.GetSetMethod()) && !isMemberInBlackList(prop) && !isMemberInBlackList(prop.GetSetMethod())).Select(prop => new { prop.Name, IsStatic = prop.GetSetMethod().IsStatic, Type = prop.PropertyType, IsProperty = true }) + .Concat( + type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + .Where(field => !isObsolete(field) && !isMemberInBlackList(field) && !field.IsInitOnly && !field.IsLiteral) + .Select(field => new { field.Name, field.IsStatic, Type = field.FieldType, IsProperty = false }) + ).Where(info => !IsDoNotGen(type, info.Name))/*.Where(setter => !typeof(Delegate).IsAssignableFrom(setter.Type))*/.ToList()); + + parameters.Set("operators", type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + .Where(method => OpMethodNames.Contains(method.Name)) + .GroupBy(method => method.Name, (k, v) => new { Name = k, Overloads = v.Cast().OrderBy(mb => mb.GetParameters().Length).ToList() }).ToList()); + + var indexers = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(prop => prop.GetIndexParameters().Length > 0); + + parameters.Set("indexers", indexers.Where(prop => prop.CanRead && (prop.GetGetMethod() != null)).Select(prop => prop.GetGetMethod()) + .Where(method => method.GetParameters().Length == 1 && !method.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) + .ToList()); + + parameters.Set("newindexers", indexers.Where(prop => prop.CanWrite && (prop.GetSetMethod() != null)).Select(prop => prop.GetSetMethod()) + .Where(method => method.GetParameters().Length == 2 && !method.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) + .ToList()); + + parameters.Set("events", type.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly).Where(e => !isObsolete(e) && !isMemberInBlackList(e)) + .Where(ev=> ev.GetAddMethod() != null || ev.GetRemoveMethod() != null) + .Where(ev => !IsDoNotGen(type, ev.Name)) + .Select(ev => new { IsStatic = ev.GetAddMethod() != null? ev.GetAddMethod().IsStatic: ev.GetRemoveMethod().IsStatic, ev.Name, + CanSet = false, CanAdd = ev.GetRemoveMethod() != null, CanRemove = ev.GetRemoveMethod() != null, Type = ev.EventHandlerType}) + .ToList()); + + parameters.Set("lazymembers", lazyMemberInfos); + foreach (var member in type.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly) + .Where(m => IsDoNotGen(type, m.Name)) + .GroupBy(m=>m.Name).Select(g => g.First()) + ) + { + switch(member.MemberType) + { + case MemberTypes.Method: + MethodBase mb = member as MethodBase; + lazyMemberInfos.Add(new LazyMemberInfo + { + Index = mb.IsStatic ? "CLS_IDX" : "METHOD_IDX", + Name = member.Name, + MemberType = "LazyMemberTypes.Method", + IsStatic = mb.IsStatic ? "true" : "false" + }); + break; + case MemberTypes.Event: + EventInfo ev = member as EventInfo; + if (ev.GetAddMethod() == null && ev.GetRemoveMethod() == null) break; + bool eventIsStatic = ev.GetAddMethod() != null ? ev.GetAddMethod().IsStatic : ev.GetRemoveMethod().IsStatic; + lazyMemberInfos.Add(new LazyMemberInfo { + Index = eventIsStatic ? "CLS_IDX" : "METHOD_IDX", + Name = member.Name, + MemberType = "LazyMemberTypes.Event", + IsStatic = eventIsStatic ? "true" : "false" + }); + break; + case MemberTypes.Field: + FieldInfo field = member as FieldInfo; + lazyMemberInfos.Add(new LazyMemberInfo + { + Index = field.IsStatic ? "CLS_GETTER_IDX" : "GETTER_IDX", + Name = member.Name, + MemberType = "LazyMemberTypes.FieldGet", + IsStatic = field.IsStatic ? "true" : "false" + }); + lazyMemberInfos.Add(new LazyMemberInfo + { + Index = field.IsStatic ? "CLS_SETTER_IDX" : "SETTER_IDX", + Name = member.Name, + MemberType = "LazyMemberTypes.FieldSet", + IsStatic = field.IsStatic ? "true" : "false" + }); + break; + case MemberTypes.Property: + PropertyInfo prop = member as PropertyInfo; + if (prop.Name != "Item" || prop.GetIndexParameters().Length == 0) + { + if (prop.CanRead && prop.GetGetMethod() != null) + { + var isStatic = prop.GetGetMethod().IsStatic; + lazyMemberInfos.Add(new LazyMemberInfo + { + Index = isStatic ? "CLS_GETTER_IDX" : "GETTER_IDX", + Name = member.Name, + MemberType = "LazyMemberTypes.PropertyGet", + IsStatic = isStatic ? "true" : "false" + }); + } + if (prop.CanWrite && prop.GetSetMethod() != null) + { + var isStatic = prop.GetSetMethod().IsStatic; + lazyMemberInfos.Add(new LazyMemberInfo + { + Index = isStatic ? "CLS_SETTER_IDX" : "SETTER_IDX", + Name = member.Name, + MemberType = "LazyMemberTypes.PropertySet", + IsStatic = isStatic ? "true" : "false" + }); + } + } + break; + } + } + } + + class LazyMemberInfo + { + public string Index; + public string Name; + public string MemberType; + public string IsStatic; + } + + static void getInterfaceInfo(Type type, LuaTable parameters) + { + parameters.Set("type", type); + + var itfs = new Type[] { type }.Concat(type.GetInterfaces()); + parameters.Set("methods", itfs.SelectMany(i => i.GetMethods()) + .Where(method => !method.IsSpecialName && !method.IsGenericMethod && !method.Name.StartsWith("op_") && !method.Name.StartsWith("add_") && !method.Name.StartsWith("remove_")) //GenericMethod can not be invoke becuase not static info available! + .ToList()); + + parameters.Set("propertys", itfs.SelectMany(i => i.GetProperties()) + .Where(prop => (prop.CanRead || prop.CanWrite) && prop.Name != "Item") + .ToList()); + + parameters.Set("events", itfs.SelectMany(i => i.GetEvents()).ToList()); + + parameters.Set("indexers", itfs.SelectMany(i => i.GetProperties()) + .Where(prop => (prop.CanRead || prop.CanWrite) && prop.Name == "Item") + .ToList()); + } + + static bool isObsolete(MemberInfo mb) + { + if (mb == null) return false; + ObsoleteAttribute oa = GetCustomAttribute(mb, typeof(ObsoleteAttribute)) as ObsoleteAttribute; +#if XLUA_GENERAL && !XLUA_ALL_OBSOLETE || XLUA_JUST_EXCLUDE_ERROR + return oa != null && oa.IsError; +#else + return oa != null; +#endif + } + + static bool isObsolete(Type type) + { + if (type == null) return false; + if (isObsolete(type as MemberInfo)) + { + return true; + } + return (type.DeclaringType != null) ? isObsolete(type.DeclaringType) : false; + } + + static bool isMemberInBlackList(MemberInfo mb) + { + if (isDefined(mb, typeof(BlackListAttribute))) return true; + if (mb is FieldInfo && (mb as FieldInfo).FieldType.IsPointer) return true; + if (mb is PropertyInfo && (mb as PropertyInfo).PropertyType.IsPointer) return true; + + foreach(var filter in memberFilters) + { + if (filter(mb)) + { + return true; + } + } + + foreach (var exclude in BlackList) + { + if (mb.DeclaringType.ToString() == exclude[0] && mb.Name == exclude[1]) + { + return true; + } + } + + return false; + } + + static bool isMethodInBlackList(MethodBase mb) + { + if (isDefined(mb, typeof(BlackListAttribute))) return true; + + //指针目前不支持,先过滤 + if (mb.GetParameters().Any(pInfo => pInfo.ParameterType.IsPointer)) return true; + if (mb is MethodInfo && (mb as MethodInfo).ReturnType.IsPointer) return true; + + foreach (var filter in memberFilters) + { + if (filter(mb)) + { + return true; + } + } + + foreach (var exclude in BlackList) + { + if (mb.DeclaringType.ToString() == exclude[0] && mb.Name == exclude[1]) + { + var parameters = mb.GetParameters(); + if (parameters.Length != exclude.Count - 2) + { + continue; + } + bool paramsMatch = true; + + for (int i = 0; i < parameters.Length; i++) + { + if (parameters[i].ParameterType.ToString() != exclude[i + 2]) + { + paramsMatch = false; + break; + } + } + if (paramsMatch) return true; + } + } + return false; + } + + static Dictionary templateCache = new Dictionary(); + static void GenOne(Type type, Action type_info_getter, XLuaTemplate templateAsset, StreamWriter textWriter) + { + if (isObsolete(type)) return; + LuaFunction template; + if (!templateCache.TryGetValue(templateAsset.name, out template)) + { + template = XLua.TemplateEngine.LuaTemplate.Compile(luaenv, templateAsset.text); + templateCache[templateAsset.name] = template; + } + + LuaTable type_info = luaenv.NewTable(); + LuaTable meta = luaenv.NewTable(); + meta.Set("__index", luaenv.Global); + type_info.SetMetaTable(meta); + meta.Dispose(); + + type_info_getter(type, type_info); + + try + { + string genCode = XLua.TemplateEngine.LuaTemplate.Execute(template, type_info); + //string filePath = save_path + type.ToString().Replace("+", "").Replace(".", "").Replace("`", "").Replace("&", "").Replace("[", "").Replace("]", "").Replace(",", "") + file_suffix + ".cs"; + textWriter.Write(genCode); + textWriter.Flush(); + } + catch (Exception e) + { +#if XLUA_GENERAL + System.Console.WriteLine("Error: gen wrap file fail! err=" + e.Message + ", stack=" + e.StackTrace); +#else + Debug.LogError("gen wrap file fail! err=" + e.Message + ", stack=" + e.StackTrace); +#endif + } + finally + { + type_info.Dispose(); + } + } + + static void GenEnumWrap(IEnumerable types, string save_path) + { + string filePath = save_path + "EnumWrap.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + + GenOne(null, (type, type_info) => + { + var type2fields = luaenv.NewTable(); + foreach(var _type in types) + type2fields.Set(_type, _type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(x => !isMemberInBlackList(x)).ToArray()); + type_info.Set("type2fields", type2fields); + type_info.Set("types", types.ToList()); + }, templateRef.LuaEnumWrap, textWriter); + + textWriter.Close(); + } + + static string NonmalizeName(string name) + { + return name.Replace("+", "_").Replace(".", "_").Replace("`", "_").Replace("&", "_").Replace("[", "_").Replace("]", "_").Replace(",", "_"); + } + + static void GenInterfaceBridge(IEnumerable types, string save_path) + { + foreach (var wrap_type in types) + { + if (!wrap_type.IsInterface) continue; + + string filePath = save_path + NonmalizeName(wrap_type.ToString()) + "Bridge.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + GenOne(wrap_type, (type, type_info) => + { + getInterfaceInfo(type, type_info); + }, templateRef.LuaInterfaceBridge, textWriter); + textWriter.Close(); + } + } + + class ParameterInfoSimulation + { + public string Name; + public bool IsOut; + public bool IsIn; + public Type ParameterType; + public bool IsParamArray; + } + + class MethodInfoSimulation + { + public Type ReturnType; + public ParameterInfoSimulation[] ParameterInfos; + + public int HashCode; + + public ParameterInfoSimulation[] GetParameters() + { + return ParameterInfos; + } + + public Type DeclaringType = null; + public string DeclaringTypeName = null; + } + + static MethodInfoSimulation makeMethodInfoSimulation(MethodInfo method) + { + int hashCode = method.ReturnType.GetHashCode(); + + List paramsExpect = new List(); + + foreach (var param in method.GetParameters()) + { + if (param.IsOut) + { + hashCode++; + } + hashCode += param.ParameterType.GetHashCode(); + paramsExpect.Add(new ParameterInfoSimulation() + { + Name = param.Name, + IsOut = param.IsOut, + IsIn = param.IsIn, + ParameterType = param.ParameterType, + IsParamArray = param.IsDefined(typeof(System.ParamArrayAttribute), false) + }); + } + + return new MethodInfoSimulation() + { + ReturnType = method.ReturnType, + HashCode = hashCode, + ParameterInfos = paramsExpect.ToArray(), + DeclaringType = method.DeclaringType + }; + } + + static bool isNotPublic(Type type) + { + if (type.IsByRef || type.IsArray) + { + return isNotPublic(type.GetElementType()); + } + else + { + if ((!type.IsNested && !type.IsPublic) || (type.IsNested && !type.IsNestedPublic)) + { + return true; + } + if (type.IsGenericType) + { + foreach (var ga in type.GetGenericArguments()) + { + if (isNotPublic(ga)) + { + return true; + } + } + } + if (type.IsNested) + { + var parent = type.DeclaringType; + while (parent != null) + { + if ((!parent.IsNested && !parent.IsPublic) || (parent.IsNested && !parent.IsNestedPublic)) + { + return true; + } + if (parent.IsNested) + { + parent = parent.DeclaringType; + } + else + { + break; + } + } + } + return false; + } + } + + static bool hasGenericParameter(Type type) + { + if (type.IsByRef || type.IsArray) + { + return hasGenericParameter(type.GetElementType()); + } + if (type.IsGenericType) + { + foreach (var typeArg in type.GetGenericArguments()) + { + if (hasGenericParameter(typeArg)) + { + return true; + } + } + return false; + } + return type.IsGenericParameter; + } + + static MethodInfoSimulation makeHotfixMethodInfoSimulation(MethodBase hotfixMethod, HotfixFlag hotfixType) + { + bool ignoreValueType = hotfixType.HasFlag(HotfixFlag.ValueTypeBoxing); + //ignoreValueType = true; + + Type retTypeExpect = (hotfixMethod.IsConstructor ? typeof(void) : (hotfixMethod as MethodInfo).ReturnType); + int hashCode = retTypeExpect.GetHashCode(); + List paramsExpect = new List(); + if (!hotfixMethod.IsStatic) // add self + { + paramsExpect.Add(new ParameterInfoSimulation() + { + Name = "self", + IsOut = false, + IsIn = true, + ParameterType = (hotfixMethod.DeclaringType.IsValueType && !ignoreValueType) ? hotfixMethod.DeclaringType : typeof(object), + IsParamArray = false + }); + hashCode += paramsExpect[0].ParameterType.GetHashCode(); + } + + foreach (var param in hotfixMethod.GetParameters()) + { + var paramExpect = new ParameterInfoSimulation() + { + Name = param.Name, + IsOut = param.IsOut, + IsIn = param.IsIn, + ParameterType = (param.ParameterType.IsByRef || (param.ParameterType.IsValueType && !ignoreValueType) + || param.IsDefined(typeof(System.ParamArrayAttribute), false)) ? param.ParameterType : typeof(object), + IsParamArray = param.IsDefined(typeof(System.ParamArrayAttribute), false) + }; + if (param.IsOut) + { + hashCode++; + } + hashCode += paramExpect.ParameterType.GetHashCode(); + paramsExpect.Add(paramExpect); + } + + return new MethodInfoSimulation() + { + HashCode = hashCode, + ReturnType = retTypeExpect, + ParameterInfos = paramsExpect.ToArray() + }; + } + + class MethodInfoSimulationComparer : IEqualityComparer + { + public bool Equals(MethodInfoSimulation x, MethodInfoSimulation y) + { + if (object.ReferenceEquals(x, y)) return true; + if (x == null || y == null) + { + return false; + } + if (x.ReturnType != y.ReturnType) + { + return false; + } + var xParams = x.GetParameters(); + var yParams = y.GetParameters(); + if (xParams.Length != yParams.Length) + { + return false; + } + + for (int i = 0; i < xParams.Length; i++) + { + if (xParams[i].ParameterType != yParams[i].ParameterType || xParams[i].IsOut != yParams[i].IsOut) + { + return false; + } + } + + var lastPos = xParams.Length - 1; + return lastPos < 0 || xParams[lastPos].IsParamArray == yParams[lastPos].IsParamArray; + } + public int GetHashCode(MethodInfoSimulation obj) + { + return obj.HashCode; + } + } + + static bool injectByGeneric(MethodBase method, HotfixFlag hotfixType) + { + bool ignoreValueType = hotfixType.HasFlag(HotfixFlag.ValueTypeBoxing); + //ignoreValueType = true; + + if (!method.IsConstructor && (isNotPublic((method as MethodInfo).ReturnType) || hasGenericParameter((method as MethodInfo).ReturnType))) return true; + + if (!method.IsStatic + &&(((method.DeclaringType.IsValueType && !ignoreValueType) && isNotPublic(method.DeclaringType)) || hasGenericParameter(method.DeclaringType))) + { + return true; + } + + foreach (var param in method.GetParameters()) + { + if ((((param.ParameterType.IsValueType && !ignoreValueType) + || param.ParameterType.IsByRef || param.IsDefined(typeof(System.ParamArrayAttribute), false)) && isNotPublic(param.ParameterType)) + || hasGenericParameter(param.ParameterType)) + return true; + } + return false; + } + + static bool HasFlag(this HotfixFlag toCheck, HotfixFlag flag) + { + return (toCheck != HotfixFlag.Stateless) && ((toCheck & flag) == flag); + } + + static void GenDelegateBridge(IEnumerable types, string save_path, IEnumerable hotfix_check_types) + { + string filePath = save_path + "DelegatesGensBridge.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + types = types.Where(type => !type.GetMethod("Invoke").GetParameters().Any(paramInfo => paramInfo.ParameterType.IsGenericParameter)); + var hotfxDelegates = new List(); + var comparer = new MethodInfoSimulationComparer(); + + var bindingAttrOfMethod = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.NonPublic; + var bindingAttrOfConstructor = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic; + foreach (var type in (from type in hotfix_check_types where isDefined(type, typeof(HotfixAttribute)) select type)) + { + var ca = GetCustomAttribute(type, typeof(HotfixAttribute)); +#if XLUA_GENERAL + var hotfixType = (HotfixFlag)Convert.ToInt32(ca.GetType().GetProperty("Flag").GetValue(ca, null)); +#else + var hotfixType = (ca as HotfixAttribute).Flag; +#endif + HotfixCfg[type] = hotfixType; + } + foreach (var kv in HotfixCfg) + { + if (kv.Key.Name.Contains("<") || kv.Value.HasFlag(HotfixFlag.Inline)) + { + continue; + } + bool ignoreProperty = kv.Value.HasFlag(HotfixFlag.IgnoreProperty); + bool ignoreNotPublic = kv.Value.HasFlag(HotfixFlag.IgnoreNotPublic); + bool ignoreCompilerGenerated = kv.Value.HasFlag(HotfixFlag.IgnoreCompilerGenerated); + if (ignoreCompilerGenerated && isDefined(kv.Key, typeof(CompilerGeneratedAttribute))) + { + continue; + } + //ignoreProperty = true; + hotfxDelegates.AddRange(kv.Key.GetMethods(bindingAttrOfMethod) + .Where(method => method.GetMethodBody() != null) + .Where(method => !method.Name.Contains("<")) + .Where(method => !ignoreCompilerGenerated || !isDefined(method, typeof(CompilerGeneratedAttribute))) + .Where(method => !ignoreNotPublic || method.IsPublic) + .Where(method => !ignoreProperty || !method.IsSpecialName || (!method.Name.StartsWith("get_") && !method.Name.StartsWith("set_"))) + .Where(method => !method.GetParameters().Any(pInfo => pInfo.ParameterType.IsPointer)) + .Where(method => !method.ReturnType.IsPointer) + .Cast() + .Concat(kv.Key.GetConstructors(bindingAttrOfConstructor).Cast()) + .Where(method => !injectByGeneric(method, kv.Value)) + .Select(method => makeHotfixMethodInfoSimulation(method, kv.Value))); + } + hotfxDelegates = hotfxDelegates.Distinct(comparer).ToList(); + for(int i = 0; i < hotfxDelegates.Count; i++) + { + hotfxDelegates[i].DeclaringTypeName = "__Gen_Hotfix_Delegate" + i; + } + + var delegates_groups = types.Select(delegate_type => makeMethodInfoSimulation(delegate_type.GetMethod("Invoke"))) + .Where(d => d.DeclaringType.FullName != null) + .Concat(hotfxDelegates) + .GroupBy(d => d, comparer).Select((group) => new { Key = group.Key, Value = group.ToList()}); + GenOne(typeof(DelegateBridge), (type, type_info) => + { + type_info.Set("delegates_groups", delegates_groups.ToList()); + }, templateRef.LuaDelegateBridge, textWriter); + textWriter.Close(); + } + + static void GenWrapPusher(IEnumerable types, string save_path) + { + string filePath = save_path + "WrapPusher.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + var emptyMap = new Dictionary(); + GenOne(typeof(ObjectTranslator), (type, type_info) => + { + type_info.Set("purevaluetypes", types + .Where(t => t.IsEnum || (!t.IsPrimitive && SizeOf(t) != -1)) + .Select(t => new { + Type = t, + Size = SizeOf(t), + Flag = t.IsEnum ? OptimizeFlag.Default : OptimizeCfg[t], + FieldInfos = (t.IsEnum || OptimizeCfg[t] == OptimizeFlag.Default) ? null : getXluaTypeInfo(t, emptyMap).FieldInfos + }).ToList()); + type_info.Set("tableoptimzetypes", types.Where(t => !t.IsEnum && SizeOf(t) == -1) + .Select(t => new { Type = t, Fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) }) + .ToList()); + }, templateRef.LuaWrapPusher, textWriter); + textWriter.Close(); + } + + static void GenWrap(IEnumerable types, string save_path) + { + types = types.Where(type=>!type.IsEnum); + +#if GENERIC_SHARING + types = types.GroupBy(t => t.IsGenericType ? t.GetGenericTypeDefinition() : t).Select(g => g.Key); +#endif + + var typeMap = types.ToDictionary(type => { + //Debug.Log("type:" + type); + return type.ToString(); + }); + + foreach (var wrap_type in types) + { + string filePath = save_path + NonmalizeName(wrap_type.ToString()) + "Wrap.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + if (wrap_type.IsEnum) + { + GenOne(wrap_type, (type, type_info) => + { + type_info.Set("type", type); + type_info.Set("fields", type.GetFields(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static) + .Where(field => !isObsolete(field)) + .ToList()); + }, templateRef.LuaEnumWrap, textWriter); + } + else if (typeof(Delegate).IsAssignableFrom(wrap_type)) + { + + + GenOne(wrap_type, (type, type_info) => + { + type_info.Set("type", type); + type_info.Set("delegate", type.GetMethod("Invoke")); + }, templateRef.LuaDelegateWrap, textWriter); + + } + else + { + GenOne(wrap_type, (type, type_info) => + { + if (type.BaseType != null && typeMap.ContainsKey(type.BaseType.ToString())) + { + type_info.Set("base", type.BaseType); + } + getClassInfo(type, type_info); + }, templateRef.LuaClassWrap, textWriter); + } + textWriter.Close(); + } + } + +#if !XLUA_GENERAL + static void clear(string path) + { + if (Directory.Exists(path)) + { + Directory.Delete(path, true); + AssetDatabase.DeleteAsset(path.Substring(path.IndexOf("Assets") + "Assets".Length)); + + AssetDatabase.Refresh(); + } + } +#endif + + class DelegateByMethodDecComparer : IEqualityComparer + { + public bool Equals(Type x, Type y) + { + return XLua.Utils.IsParamsMatch(x.GetMethod("Invoke"), y.GetMethod("Invoke")); + } + public int GetHashCode(Type obj) + { + int hc = 0; + var method = obj.GetMethod("Invoke"); + hc += method.ReturnType.GetHashCode(); + foreach (var pi in method.GetParameters()) + { + hc += pi.ParameterType.GetHashCode(); + } + return hc; + } + } + + public static void GenDelegateBridges(IEnumerable hotfix_check_types) + { + var delegate_types = CSharpCallLua.Where(type => typeof(Delegate).IsAssignableFrom(type)); + + GenDelegateBridge(delegate_types, GeneratorConfig.common_path, hotfix_check_types); + } + + public static void GenEnumWraps() + { + var enum_types = LuaCallCSharp.Where(type => type.IsEnum).Distinct(); + + GenEnumWrap(enum_types, GeneratorConfig.common_path); + } + + static MethodInfo makeGenericMethodIfNeeded(MethodInfo method) + { + if (!method.ContainsGenericParameters) return method; + + var genericArguments = method.GetGenericArguments(); + var constraintedArgumentTypes = new Type[genericArguments.Length]; + for (var i = 0; i < genericArguments.Length; i++) + { + var argumentType = genericArguments[i]; + var parameterConstraints = argumentType.GetGenericParameterConstraints(); + Type parameterConstraint = parameterConstraints[0]; + foreach(var type in argumentType.GetGenericParameterConstraints()) + { + if (parameterConstraint.IsAssignableFrom(type)) + { + parameterConstraint = type; + } + } + + constraintedArgumentTypes[i] = parameterConstraint; + } + return method.MakeGenericMethod(constraintedArgumentTypes); + } + + public static void GenLuaRegister(bool minimum = false) + { + var wraps = minimum ? new List() : LuaCallCSharp; + + var itf_bridges = CSharpCallLua.Where(t => t.IsInterface); + + string filePath = GeneratorConfig.common_path + "XLuaGenAutoRegister.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + + var lookup = LuaCallCSharp.Distinct().ToDictionary(t => t); + + var extension_methods_from_lcs = (from t in LuaCallCSharp + where isDefined(t, typeof(ExtensionAttribute)) + from method in t.GetMethods(BindingFlags.Static | BindingFlags.Public) + where isDefined(method, typeof(ExtensionAttribute)) && !isObsolete(method) + where !method.ContainsGenericParameters || isSupportedGenericMethod(method) + select makeGenericMethodIfNeeded(method)) + .Where(method => !lookup.ContainsKey(method.GetParameters()[0].ParameterType)); + + var extension_methods = (from t in ReflectionUse + where isDefined(t, typeof(ExtensionAttribute)) + from method in t.GetMethods(BindingFlags.Static | BindingFlags.Public) + where isDefined(method, typeof(ExtensionAttribute)) && !isObsolete(method) + where !method.ContainsGenericParameters || isSupportedGenericMethod(method) + select makeGenericMethodIfNeeded(method)).Concat(extension_methods_from_lcs); + GenOne(typeof(DelegateBridgeBase), (type, type_info) => + { +#if GENERIC_SHARING + type_info.Set("wraps", wraps.Where(t=>!t.IsGenericType).ToList()); + var genericTypeGroups = wraps.Where(t => t.IsGenericType).GroupBy(t => t.GetGenericTypeDefinition()); + + var typeToArgsList = luaenv.NewTable(); + foreach (var genericTypeGroup in genericTypeGroups) + { + var argsList = luaenv.NewTable(); + int i = 1; + foreach(var genericType in genericTypeGroup) + { + argsList.Set(i++, genericType.GetGenericArguments()); + } + typeToArgsList.Set(genericTypeGroup.Key, argsList); + argsList.Dispose(); + } + + type_info.Set("generic_wraps", typeToArgsList); + typeToArgsList.Dispose(); +#else + type_info.Set("wraps", wraps.ToList()); +#endif + + type_info.Set("itf_bridges", itf_bridges.ToList()); + type_info.Set("extension_methods", extension_methods.ToList()); + }, templateRef.LuaRegister, textWriter); + textWriter.Close(); + } + + public static void AllSubStruct(Type type, Action cb) + { + if (!type.IsPrimitive && type != typeof(decimal)) + { + cb(type); + foreach(var fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + AllSubStruct(fieldInfo.FieldType, cb); + } + + foreach(var propInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + if ((AdditionalProperties.ContainsKey(type) && AdditionalProperties[type].Contains(propInfo.Name)) + || isDefined(propInfo, typeof(AdditionalPropertiesAttribute))) + { + AllSubStruct(propInfo.PropertyType, cb); + } + } + } + } + + class XluaFieldInfo + { + public string Name; + public Type Type; + public bool IsField; + public int Size; + } + + class XluaTypeInfo + { + public Type Type; + public List FieldInfos; + public List> FieldGroup; + public bool IsRoot; + } + + static XluaTypeInfo getXluaTypeInfo(Type t, Dictionary set) + { + var fs = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(fi => new XluaFieldInfo { Name = fi.Name, Type = fi.FieldType, IsField = true, Size = SizeOf(fi.FieldType) }) + .Concat(t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(prop => { + return (AdditionalProperties.ContainsKey(t) && AdditionalProperties[t].Contains(prop.Name)) + || isDefined(prop, typeof(AdditionalPropertiesAttribute)); + }) + .Select(prop => new XluaFieldInfo { Name = prop.Name, Type = prop.PropertyType, IsField = false, Size = SizeOf(prop.PropertyType) })); + int float_field_count = 0; + bool only_float = true; + foreach (var f in fs) + { + if (f.Type == typeof(float)) + { + float_field_count++; + } + else + { + only_float = false; + break; + } + } + List> grouped_field = null; + if (only_float && float_field_count > 1) + { + grouped_field = new List>(); + List group = null; + foreach (var f in fs) + { + if (group == null) group = new List(); + group.Add(f); + if (group.Count >= 6) + { + grouped_field.Add(group); + group = null; + } + } + if (group != null) grouped_field.Add(group); + } + return new XluaTypeInfo { Type = t, FieldInfos = fs.ToList(), FieldGroup = grouped_field, IsRoot = set.ContainsKey(t) }; + } + + public static void GenPackUnpack(IEnumerable types, string save_path) + { + var set = types.ToDictionary(type => type); + List all_types = new List(); + + foreach(var type in types) + { + AllSubStruct(type, (t) => + { + all_types.Add(t); + }); + } + + string filePath = save_path + "PackUnpack.cs"; + StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8); + GenOne(typeof(CopyByValue), (type, type_info) => + { + type_info.Set("type_infos", all_types.Distinct().Select(t => getXluaTypeInfo(t, set)).ToList()); + }, templateRef.PackUnpack, textWriter); + textWriter.Close(); + } + + //lua中要使用到C#库的配置,比如C#标准库,或者Unity API,第三方库等。 + public static List LuaCallCSharp = null; + + //C#静态调用Lua的配置(包括事件的原型),仅可以配delegate,interface + public static List CSharpCallLua = null; + + //黑名单 + public static List> BlackList = null; + + public static List GCOptimizeList = null; + + public static Dictionary> AdditionalProperties = null; + + public static List ReflectionUse = null; + + public static Dictionary HotfixCfg = null; + + public static Dictionary OptimizeCfg = null; + + public static Dictionary> DoNotGen = null; + + public static List assemblyList = null; + + public static List> memberFilters = null; + + static void AddToList(List list, Func get, object attr) + { + object obj = get(); + if (obj is Type) + { + list.Add(obj as Type); + } + else if (obj is IEnumerable) + { + list.AddRange(obj as IEnumerable); + } + else + { + throw new InvalidOperationException("Only field/property with the type IEnumerable can be marked " + attr.GetType().Name); + } +#if XLUA_GENERAL + if (attr != null && attr.GetType().ToString() == typeof(GCOptimizeAttribute).ToString()) + { + var flag = (OptimizeFlag)Convert.ToInt32(attr.GetType().GetProperty("Flag").GetValue(attr, null)); +#else + if (attr is GCOptimizeAttribute) + { + var flag = (attr as GCOptimizeAttribute).Flag; +#endif + if (obj is Type) + { + OptimizeCfg.Add(obj as Type, flag); + } + else if (obj is IEnumerable) + { + foreach(var type in (obj as IEnumerable)) + { + OptimizeCfg.Add(type, flag); + } + } + } + } + + static bool isDefined(MemberInfo test, Type type) + { +#if XLUA_GENERAL + return test.GetCustomAttributes(false).Any(ca => ca.GetType().ToString() == type.ToString()); +#else + return test.IsDefined(type, false); +#endif + } + + static object GetCustomAttribute(MemberInfo test, Type type) + { +#if XLUA_GENERAL + return test.GetCustomAttributes(false).FirstOrDefault(ca => ca.GetType().ToString() == type.ToString()); +#else + return test.GetCustomAttributes(type, false).FirstOrDefault(); +#endif + } + + static void MergeCfg(MemberInfo test, Type cfg_type, Func get_cfg) + { + if (isDefined(test, typeof(LuaCallCSharpAttribute))) + { + object ccla = GetCustomAttribute(test, typeof(LuaCallCSharpAttribute)); + AddToList(LuaCallCSharp, get_cfg, ccla); +#if !XLUA_GENERAL +#pragma warning disable 618 + if (ccla != null && (((ccla as LuaCallCSharpAttribute).Flag & GenFlag.GCOptimize) != 0)) +#pragma warning restore 618 + { + AddToList(GCOptimizeList, get_cfg, ccla); + } +#endif + } + if (isDefined(test, typeof(CSharpCallLuaAttribute))) + { + AddToList(CSharpCallLua, get_cfg, GetCustomAttribute(test, typeof(CSharpCallLuaAttribute))); + } + if (isDefined(test, typeof(GCOptimizeAttribute))) + { + AddToList(GCOptimizeList, get_cfg, GetCustomAttribute(test, typeof(GCOptimizeAttribute))); + } + if (isDefined(test, typeof(ReflectionUseAttribute))) + { + AddToList(ReflectionUse, get_cfg, GetCustomAttribute(test, typeof(ReflectionUseAttribute))); + } + if (isDefined(test, typeof(HotfixAttribute))) + { + object cfg = get_cfg(); + if (cfg is IEnumerable) + { + var ca = GetCustomAttribute(test, typeof(HotfixAttribute)); +#if XLUA_GENERAL + var hotfixType = (HotfixFlag)Convert.ToInt32(ca.GetType().GetProperty("Flag").GetValue(ca, null)); +#else + var hotfixType = (ca as HotfixAttribute).Flag; +#endif + foreach (var type in cfg as IEnumerable) + { + if (!HotfixCfg.ContainsKey(type) && !isObsolete(type) + && !type.IsEnum && !typeof(Delegate).IsAssignableFrom(type) + && (!type.IsGenericType || type.IsGenericTypeDefinition) + && (type.Namespace == null || (type.Namespace != "XLua" && !type.Namespace.StartsWith("XLua."))) + && (assemblyList.Contains(type.Module.Assembly.GetName().Name))) + { + HotfixCfg.Add(type, hotfixType); + } + } + } + } + if (isDefined(test, typeof(BlackListAttribute)) + && (typeof(List>)).IsAssignableFrom(cfg_type)) + { + BlackList.AddRange(get_cfg() as List>); + } + if (isDefined(test, typeof(BlackListAttribute)) && typeof(Func).IsAssignableFrom(cfg_type)) + { + memberFilters.Add(get_cfg() as Func); + } + + if (isDefined(test, typeof(AdditionalPropertiesAttribute)) + && (typeof(Dictionary>)).IsAssignableFrom(cfg_type)) + { + var cfg = get_cfg() as Dictionary>; + foreach (var kv in cfg) + { + if (!AdditionalProperties.ContainsKey(kv.Key)) + { + AdditionalProperties.Add(kv.Key, kv.Value); + } + } + } + + if (isDefined(test, typeof(DoNotGenAttribute)) + && (typeof(Dictionary>)).IsAssignableFrom(cfg_type)) + { + var cfg = get_cfg() as Dictionary>; + foreach (var kv in cfg) + { + HashSet set; + if (!DoNotGen.TryGetValue(kv.Key, out set)) + { + set = new HashSet(); + DoNotGen.Add(kv.Key, set); + } + set.UnionWith(kv.Value); + } + } + } + + static bool IsPublic(Type type) + { + if (type.IsPublic || type.IsNestedPublic) + { + if (type.DeclaringType != null) + { + return IsPublic(type.DeclaringType); + } + else + { + return true; + } + } + return false; + } + + public static void GetGenConfig(IEnumerable check_types) + { + LuaCallCSharp = new List(); + + CSharpCallLua = new List(); + + GCOptimizeList = new List(); + + AdditionalProperties = new Dictionary>(); + + ReflectionUse = new List(); + + BlackList = new List>() + { + }; + + HotfixCfg = new Dictionary(); + + OptimizeCfg = new Dictionary(); + + DoNotGen = new Dictionary>(); + +#if UNITY_EDITOR && HOTFIX_ENABLE + assemblyList = HotfixConfig.GetHotfixAssembly().Select(a => a.GetName().Name).ToList(); +#else + assemblyList = new List(); +#endif + memberFilters = new List>(); + + foreach (var t in check_types) + { + MergeCfg(t, null, () => t); + + if (!t.IsAbstract || !t.IsSealed) continue; + + var fields = t.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < fields.Length; i++) + { + var field = fields[i]; + MergeCfg(field, field.FieldType, () => field.GetValue(null)); + } + + var props = t.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < props.Length; i++) + { + var prop = props[i]; + MergeCfg(prop, prop.PropertyType, () => prop.GetValue(null, null)); + } + } + LuaCallCSharp = LuaCallCSharp.Distinct() + .Where(type=> IsPublic(type) && !isObsolete(type) && !type.IsGenericTypeDefinition) + .Where(type => !typeof(Delegate).IsAssignableFrom(type)) + .Where(type => !type.Name.Contains("<")) + .ToList(); + CSharpCallLua = CSharpCallLua.Distinct() + .Where(type => IsPublic(type) && !isObsolete(type) && !type.IsGenericTypeDefinition) + .Where(type => type != typeof(Delegate) && type != typeof(MulticastDelegate)) + .ToList(); + GCOptimizeList = GCOptimizeList.Distinct() + .Where(type => IsPublic(type) && !isObsolete(type) && !type.IsGenericTypeDefinition) + .ToList(); + ReflectionUse = ReflectionUse.Distinct() + .Where(type => !isObsolete(type) && !type.IsGenericTypeDefinition) + .ToList(); + } + + static Dictionary type_size = new Dictionary() + { + { typeof(byte), 1 }, + { typeof(sbyte), 1 }, + { typeof(short), 2 }, + { typeof(ushort), 2 }, + { typeof(int), 4 }, + { typeof(uint), 4 }, + { typeof(long), 8 }, + { typeof(ulong), 8 }, + { typeof(float), 4 }, + { typeof(double), 8 }, + { typeof(decimal), 16 } + }; + + static int SizeOf(Type type) + { + if (type_size.ContainsKey(type)) + { + return type_size[type]; + } + + if (!CopyByValue.IsStruct(type)) + { + return -1; + } + + int size = 0; + foreach(var fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + int t_size = SizeOf(fieldInfo.FieldType); + if (t_size == -1) + { + size = -1; + break; + } + size += t_size; + } + if (size != -1) + { + foreach (var propInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + { + if ((AdditionalProperties.ContainsKey(type) && AdditionalProperties[type].Contains(propInfo.Name)) || isDefined(propInfo, typeof(AdditionalPropertiesAttribute))) + { + int t_size = SizeOf(propInfo.PropertyType); + if (t_size == -1) + { + size = -1; + break; + } + size += t_size; + } + } + } + + if (!type_size.ContainsKey(type)) + { + type_size.Add(type, size); + } + + return size; + } + + public static void Gen(IEnumerable wraps, IEnumerable gc_optimze_list, IEnumerable itf_bridges, string save_path) + { + templateCache.Clear(); + Directory.CreateDirectory(save_path); + GenWrap(wraps, save_path); + GenWrapPusher(gc_optimze_list.Concat(wraps.Where(type=>type.IsEnum)).Distinct(), save_path); + GenPackUnpack(gc_optimze_list.Where(type => !type.IsPrimitive && SizeOf(type) != -1), save_path); + GenInterfaceBridge(itf_bridges, save_path); + } + + public static void GenCodeForClass(bool minimum = false) + { + var warp_types = minimum ? new List() : LuaCallCSharp; + var itf_bridges_types = CSharpCallLua.Where(type => type.IsInterface).Distinct(); + + Gen(warp_types, GCOptimizeList, itf_bridges_types, GeneratorConfig.common_path); + } + +#if XLUA_GENERAL + static bool IsExtensionMethod(MethodInfo method) + { + return isDefined(method, typeof(ExtensionAttribute)); + } + + static bool IsDelegate(Type type) + { + return type.BaseType != null && type.BaseType.ToString() == "System.MulticastDelegate"; + } + + public static void GenAll(XLuaTemplates templates, IEnumerable all_types) + { + var start = DateTime.Now; + Directory.CreateDirectory(GeneratorConfig.common_path); + templateRef = templates; + GetGenConfig(all_types.Where(type => !type.IsGenericTypeDefinition)); + luaenv.DoString("require 'TemplateCommon'"); + luaenv.Global.Set("IsExtensionMethod", new Func(IsExtensionMethod)); + luaenv.Global.Set("IsDelegate", new Func(IsDelegate)); + var gen_push_types_setter = luaenv.Global.Get("SetGenPushAndUpdateTypes"); + gen_push_types_setter.Call(GCOptimizeList.Where(t => !t.IsPrimitive && SizeOf(t) != -1).Concat(LuaCallCSharp.Where(t => t.IsEnum)).Distinct().ToList()); + var xlua_classes_setter = luaenv.Global.Get("SetXLuaClasses"); + xlua_classes_setter.Call(XLua.Utils.GetAllTypes().Where(t => t.Namespace == "XLua").ToList()); + GenDelegateBridges(all_types); + GenEnumWraps(); + GenCodeForClass(); + GenLuaRegister(); + Console.WriteLine("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); + luaenv.Dispose(); + } +#endif + +#if !XLUA_GENERAL + static void callCustomGen() + { + foreach (var method in (from type in XLua.Utils.GetAllTypes() + from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) + where method.IsDefined(typeof(GenCodeMenuAttribute), false) select method)) + { + method.Invoke(null, new object[] { }); + } + } + + [MenuItem("XLua/Generate Code", false, 1)] + public static void GenAll() + { +#if UNITY_2018 && (UNITY_EDITOR_WIN || UNITY_EDITOR_OSX) + if (File.Exists("./Tools/MonoBleedingEdge/bin/mono.exe")) + { + GenUsingCLI(); + return; + } +#endif + var start = DateTime.Now; + Directory.CreateDirectory(GeneratorConfig.common_path); + GetGenConfig(XLua.Utils.GetAllTypes()); + luaenv.DoString("require 'TemplateCommon'"); + var gen_push_types_setter = luaenv.Global.Get("SetGenPushAndUpdateTypes"); + gen_push_types_setter.Call(GCOptimizeList.Where(t => !t.IsPrimitive && SizeOf(t) != -1).Concat(LuaCallCSharp.Where(t => t.IsEnum)).Distinct().ToList()); + var xlua_classes_setter = luaenv.Global.Get("SetXLuaClasses"); + xlua_classes_setter.Call(XLua.Utils.GetAllTypes().Where(t => t.Namespace == "XLua").ToList()); + GenDelegateBridges(XLua.Utils.GetAllTypes(false)); + GenEnumWraps(); + GenCodeForClass(); + GenLuaRegister(); + callCustomGen(); + Debug.Log("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); + AssetDatabase.Refresh(); + } + +#if UNITY_EDITOR_OSX || UNITY_EDITOR_WIN + public static void GenUsingCLI() + { +#if UNITY_EDITOR_OSX + var monoPath = "./Tools/MonoBleedingEdge/bin/mono"; +#else + var monoPath = "./Tools/MonoBleedingEdge/bin/mono.exe"; +#endif + + var args = new List() + { + "./Tools/XLuaGenerate.exe", + "./Library/ScriptAssemblies/Assembly-CSharp.dll", + "./Library/ScriptAssemblies/Assembly-CSharp-Editor.dll", + GeneratorConfig.common_path + }; + + var searchPaths = new List(); + foreach (var path in + (from asm in AppDomain.CurrentDomain.GetAssemblies() select asm.ManifestModule.FullyQualifiedName) + .Distinct()) + { + try + { + searchPaths.Add(Path.GetDirectoryName(path)); + } + catch { } + } + args.AddRange(searchPaths.Distinct()); + + System.Diagnostics.Process process = new System.Diagnostics.Process(); + process.StartInfo.FileName = monoPath; + process.StartInfo.Arguments = "\"" + string.Join("\" \"", args.ToArray()) + "\""; + process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + process.Start(); + + while (!process.StandardError.EndOfStream) + { + Debug.LogError(process.StandardError.ReadLine()); + } + + while (!process.StandardOutput.EndOfStream) + { + Debug.Log(process.StandardOutput.ReadLine()); + } + + process.WaitForExit(); + GetGenConfig(XLua.Utils.GetAllTypes()); + callCustomGen(); + AssetDatabase.Refresh(); + } +#endif + + [MenuItem("XLua/Clear Generated Code", false, 2)] + public static void ClearAll() + { + clear(GeneratorConfig.common_path); + } + + public delegate IEnumerable GetTasks(LuaEnv lua_env, UserConfig user_cfg); + + public static void CustomGen(string template_src, GetTasks get_tasks) + { + GetGenConfig(XLua.Utils.GetAllTypes()); + + LuaFunction template = XLua.TemplateEngine.LuaTemplate.Compile(luaenv, + template_src); + foreach (var gen_task in get_tasks(luaenv, new UserConfig() { + LuaCallCSharp = LuaCallCSharp, + CSharpCallLua = CSharpCallLua, + ReflectionUse = ReflectionUse + })) + { + LuaTable meta = luaenv.NewTable(); + meta.Set("__index", luaenv.Global); + gen_task.Data.SetMetaTable(meta); + meta.Dispose(); + + try + { + string genCode = XLua.TemplateEngine.LuaTemplate.Execute(template, gen_task.Data); + gen_task.Output.Write(genCode); + gen_task.Output.Flush(); + } + catch (Exception e) + { + Debug.LogError("gen file fail! template=" + template_src + ", err=" + e.Message + ", stack=" + e.StackTrace); + } + finally + { + gen_task.Output.Close(); + } + } + } + +#endif + + private static bool isSupportedGenericMethod(MethodInfo method) + { + + if (!method.ContainsGenericParameters) + return true; + var methodParameters = method.GetParameters(); + var _hasGenericParameter = false; + for (var i = 0; i < methodParameters.Length; i++) + { + var parameterType = methodParameters[i].ParameterType; + if (!isSupportGenericParameter(parameterType, true, ref _hasGenericParameter)) + return false; + } + return _hasGenericParameter; + } + private static bool isSupportGenericParameter(Type parameterType,bool checkConstraint, ref bool _hasGenericParameter) + { + + if (parameterType.IsGenericParameter) + { + if (!checkConstraint) + return false; + var parameterConstraints = parameterType.GetGenericParameterConstraints(); + if (parameterConstraints.Length == 0) return false; + foreach (var parameterConstraint in parameterConstraints) + { + if (!parameterConstraint.IsClass || (parameterConstraint == typeof(ValueType)) || Generator.hasGenericParameter(parameterConstraint)) + return false; + } + _hasGenericParameter = true; + } + else if(parameterType.IsGenericType) + { + foreach (var argument in parameterType.GetGenericArguments()) + { + if (!isSupportGenericParameter(argument,false, ref _hasGenericParameter)) + return false; + } + } + return true; + } +#if !XLUA_GENERAL + [UnityEditor.Callbacks.PostProcessBuild(1)] + public static void CheckGenrate(BuildTarget target, string pathToBuiltProject) + { + if (EditorApplication.isCompiling || Application.isPlaying) + { + return; + } + if (!DelegateBridge.Gen_Flag) + { + throw new InvalidOperationException("Code has not been genrated, may be not work in phone!"); + } + } +#endif + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Generator.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Generator.cs.meta new file mode 100644 index 0000000..314cd66 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Generator.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 06e8d22c9f9a48c40b8db0c14d7f4e04 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Hotfix.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Hotfix.cs new file mode 100644 index 0000000..5c51ba7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Hotfix.cs @@ -0,0 +1,1747 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if HOTFIX_ENABLE +using System.Collections.Generic; +using System; +using System.Reflection; +using System.Linq; +using System.IO; +using System.Text.RegularExpressions; + +#if XLUA_GENERAL +using Mono.Cecil; +using Mono.Cecil.Cil; +#endif + +#if !XLUA_GENERAL +using UnityEngine; +using UnityEditor; +using UnityEditor.Callbacks; +using System.Diagnostics; +#if UNITY_2019_1_OR_NEWER +using UnityEditor.Build; +using UnityEditor.Build.Reporting; +#endif +#endif + +namespace XLua +{ + public static class HotfixConfig + { + //返回-1表示没有标签 + static int getHotfixType(MemberInfo memberInfo) + { + try + { + foreach (var ca in memberInfo.GetCustomAttributes(false)) + { + var ca_type = ca.GetType(); + if (ca_type.ToString() == "XLua.HotfixAttribute") + { + return (int)(ca_type.GetProperty("Flag").GetValue(ca, null)); + } + } + } + catch { } + return -1; + } + + static void mergeConfig(MemberInfo test, Type cfg_type, Func> get_cfg, Action on_cfg) + { + int hotfixType = getHotfixType(test); + if (-1 == hotfixType || !typeof(IEnumerable).IsAssignableFrom(cfg_type)) + { + return; + } + + foreach (var type in get_cfg()) + { + if (!type.IsDefined(typeof(ObsoleteAttribute), false) + && !type.IsEnum && !typeof(Delegate).IsAssignableFrom(type) + && (!type.IsGenericType || type.IsGenericTypeDefinition)) + { + if ((type.Namespace == null || (type.Namespace != "XLua" && !type.Namespace.StartsWith("XLua.")))) + { + on_cfg(type, hotfixType); + } + } + } + } + + public static void GetConfig(Dictionary hotfixCfg, IEnumerable cfg_check_types) + { + if (cfg_check_types != null) + { + Action on_cfg = (type, hotfixType) => + { + string key = type.FullName.Replace('+', '/'); + if (!hotfixCfg.ContainsKey(key)) + { + hotfixCfg.Add(key, hotfixType); + } + }; + foreach (var type in cfg_check_types.Where(t => !t.IsGenericTypeDefinition && t.IsAbstract && t.IsSealed)) + { + var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + foreach (var field in type.GetFields(flags)) + { + mergeConfig(field, field.FieldType, () => field.GetValue(null) as IEnumerable, on_cfg); + } + foreach (var prop in type.GetProperties(flags)) + { + mergeConfig(prop, prop.PropertyType, () => prop.GetValue(null, null) as IEnumerable, on_cfg); + } + } + } + } + + public static List GetHotfixAssembly() + { + var projectPath = Assembly.Load("Assembly-CSharp").ManifestModule.FullyQualifiedName; + Regex rgx = new Regex(@"^(.*)[\\/]Library[\\/]ScriptAssemblies[\\/]Assembly-CSharp.dll$"); + MatchCollection matches = rgx.Matches(projectPath); + projectPath = matches[0].Groups[1].Value; + + List types = new List(); + Action on_cfg = (type, hotfixType) => + { + types.Add(type); + }; + + foreach (var assmbly in AppDomain.CurrentDomain.GetAssemblies()) + { + try + { + foreach (var type in (from type in assmbly.GetTypes() + where !type.IsGenericTypeDefinition + select type)) + { + if (getHotfixType(type) != -1) + { + types.Add(type); + } + else + { + var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + foreach (var field in type.GetFields(flags)) + { + mergeConfig(field, field.FieldType, () => field.GetValue(null) as IEnumerable, on_cfg); + } + foreach (var prop in type.GetProperties(flags)) + { + mergeConfig(prop, prop.PropertyType, () => prop.GetValue(null, null) as IEnumerable, on_cfg); + } + } + } + } + catch { } // 防止有的工程有非法的dll导致中断 + } + return types.Select(t => t.Assembly).Distinct() + .Where(a => a.ManifestModule.FullyQualifiedName.IndexOf(projectPath) == 0) + .ToList(); + } + + public static List GetHotfixAssemblyPaths() + { + return GetHotfixAssembly().Select(a => a.ManifestModule.FullyQualifiedName).Distinct().ToList(); + } + } +} +#if XLUA_GENERAL + +namespace XLua +{ + [Flags] + enum HotfixFlagInTool + { + Stateless = 0, + Stateful = 1, + ValueTypeBoxing = 2, + IgnoreProperty = 4, + IgnoreNotPublic = 8, + Inline = 16, + IntKey = 32, + AdaptByDelegate = 64, + IgnoreCompilerGenerated = 128, + NoBaseProxy = 256, + } + + static class ExtentionMethods + { + public static bool HasFlag(this HotfixFlagInTool toCheck, HotfixFlagInTool flag) + { + return (toCheck != HotfixFlagInTool.Stateless) && ((toCheck & flag) == flag); + } + + public static MethodReference MakeGenericMethod(this MethodReference self, params TypeReference[] arguments) + { + if (self.GenericParameters.Count != arguments.Length) + throw new ArgumentException(); + + var instance = new GenericInstanceMethod(self); + foreach (var argument in arguments) + instance.GenericArguments.Add(argument); + + return instance; + } + + public static FieldReference GetGeneric(this FieldDefinition definition) + { + if (definition.DeclaringType.HasGenericParameters) + { + var declaringType = new GenericInstanceType(definition.DeclaringType); + foreach (var parameter in definition.DeclaringType.GenericParameters) + { + declaringType.GenericArguments.Add(parameter); + } + return new FieldReference(definition.Name, definition.FieldType, declaringType); + } + + return definition; + } + + public static TypeReference GetGeneric(this TypeDefinition definition) + { + if (definition.HasGenericParameters) + { + var genericInstanceType = new GenericInstanceType(definition); + foreach (var parameter in definition.GenericParameters) + { + genericInstanceType.GenericArguments.Add(parameter); + } + return genericInstanceType; + } + + return definition; + } + + public static TypeReference TryImport(this ModuleDefinition module, TypeReference type) + { + if (module.Assembly.FullName == type.Module.Assembly.FullName + && module.FullyQualifiedName == type.Module.FullyQualifiedName) + { + return type; + } + else + { +#if XLUA_GENERAL + return module.ImportReference(type); +#else + return module.Import(type); +#endif + } + } + + public static MethodReference TryImport(this ModuleDefinition module, MethodReference method) + { + if (module.Assembly.FullName == method.Module.Assembly.FullName + && module.FullyQualifiedName == method.Module.FullyQualifiedName) + { + return method; + } + else + { +#if XLUA_GENERAL + return module.ImportReference(method); +#else + return module.Import(method); +#endif + } + } + } + + public class Hotfix + { + private TypeReference objType = null; + private TypeReference delegateBridgeType = null; + private AssemblyDefinition injectAssembly = null; + + private MethodReference delegateBridgeGetter = null; + private MethodReference hotfixFlagGetter = null; + private MethodReference invokeSessionStart = null; + private MethodReference functionInvoke = null; + private MethodReference invokeSessionEnd = null; + private MethodReference invokeSessionEndWithResult = null; + private MethodReference inParam = null; + private MethodReference inParams = null; + private MethodReference outParam = null; + + private Dictionary hotfixCfg = null; + private List hotfixBridgesDef = null; + private Dictionary hotfixBridgeToDelegate = null; + + private List bridgeIndexByKey = null; + + private bool isTheSameAssembly = false; + + private int delegateId = 0; + + public void Init(AssemblyDefinition injectAssembly, AssemblyDefinition xluaAssembly, IEnumerable searchDirectorys, Dictionary hotfixCfg) + { + isTheSameAssembly = injectAssembly == xluaAssembly; + this.injectAssembly = injectAssembly; + this.hotfixCfg = hotfixCfg; + var injectModule = injectAssembly.MainModule; + objType = injectModule.TypeSystem.Object; + + var delegateBridgeTypeDef = xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.DelegateBridge"); + delegateBridgeType = injectModule.TryImport(delegateBridgeTypeDef); + delegateBridgeGetter = injectModule.TryImport(xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateBridge") + .Methods.Single(m => m.Name == "Get")); + hotfixFlagGetter = injectModule.TryImport(xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateBridge") + .Methods.Single(m => m.Name == "xlua_get_hotfix_flag")); + + //luaFunctionType = assembly.MainModule.Types.Single(t => t.FullName == "XLua.LuaFunction"); + invokeSessionStart = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InvokeSessionStart")); + functionInvoke = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "Invoke")); + invokeSessionEnd = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InvokeSessionEnd")); + invokeSessionEndWithResult = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InvokeSessionEndWithResult")); + inParam = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InParam")); + inParams = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "InParams")); + outParam = injectModule.TryImport(delegateBridgeTypeDef.Methods.Single(m => m.Name == "OutParam")); + + hotfixBridgesDef = (from method in delegateBridgeTypeDef.Methods + where method.Name.StartsWith("__Gen_Delegate_Imp") + select method).ToList(); + hotfixBridgeToDelegate = new Dictionary(); + delegateId = 0; + + //hotfixBridges = hotfixBridgesDef.Select(m => injectModule.TryImport(m)).ToList(); + + bridgeIndexByKey = new List(); + + var resolverOfInjectAssembly = injectAssembly.MainModule.AssemblyResolver as BaseAssemblyResolver; + var resolverOfXluaAssembly = xluaAssembly.MainModule.AssemblyResolver as BaseAssemblyResolver; + if (!isTheSameAssembly) + { + resolverOfXluaAssembly.AddSearchDirectory(Path.GetDirectoryName(injectAssembly.MainModule.FullyQualifiedName)); + } + Action addSearchDirectory = (string dir) => + { + resolverOfInjectAssembly.AddSearchDirectory(dir); + if (!isTheSameAssembly) + { + resolverOfXluaAssembly.AddSearchDirectory(dir); + } + }; + addSearchDirectory("./Library/ScriptAssemblies/"); + foreach (var path in + (from asm in AppDomain.CurrentDomain.GetAssemblies() select asm.ManifestModule.FullyQualifiedName) + .Distinct()) + { + try + { + addSearchDirectory(Path.GetDirectoryName(path)); + } + catch(Exception) + { + + } + } + + if (searchDirectorys != null) + { + foreach(var directory in searchDirectorys.Distinct()) + { + addSearchDirectory(directory); + } + } + + var nameToOpcodes = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .ToDictionary(f => f.Name, f => ((OpCode)f.GetValue(null))); + foreach(var kv in nameToOpcodes) + { + if (kv.Key.EndsWith("_S")) + { + shortToLong[kv.Value] = nameToOpcodes[kv.Key.Substring(0, kv.Key.Length - 2)]; + } + } + } + + static string getAssemblyFullName(IMetadataScope scope) + { + if (scope == null) return null; + switch(scope.MetadataScopeType) + { + case MetadataScopeType.ModuleDefinition: + { + ModuleDefinition md = scope as ModuleDefinition; + return md.Assembly.FullName; + } + case MetadataScopeType.AssemblyNameReference: + { + AssemblyNameReference anr = scope as AssemblyNameReference; + return anr.FullName; + } + } + return null; + } + + static bool isSameType(TypeReference left, TypeReference right) + { + if (left.FullName != right.FullName) + { + return false; + } + + //TypeReference.Module.FullyQualifiedName不验证 + if (left.Module.Assembly.FullName == right.Module.Assembly.FullName) + { + return true; + } + else + { + var lafn = getAssemblyFullName(left.Scope); + var rafn = getAssemblyFullName(right.Scope); + if (lafn != null && lafn == rafn) + { + return true; + } + var lr = left.Resolve(); + var rr = right.Resolve(); + if (lr == null || rr == null) return false; + return lr.Module.Assembly.FullName == rr.Module.Assembly.FullName; + } + } + + MethodDefinition createDelegateFor(MethodDefinition method, AssemblyDefinition assembly, string delegateName, bool ignoreValueType) + { + var voidType = assembly.MainModule.TypeSystem.Void; + var objectType = assembly.MainModule.TypeSystem.Object; + var nativeIntType = assembly.MainModule.TypeSystem.IntPtr; + var asyncResultType = assembly.MainModule.Import(typeof(IAsyncResult)); + var asyncCallbackType = assembly.MainModule.Import(typeof(AsyncCallback)); + + Mono.Cecil.MethodAttributes delegateMethodAttributes = Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.Virtual | Mono.Cecil.MethodAttributes.VtableLayoutMask; + + var delegateDef = new TypeDefinition("XLua", delegateName, Mono.Cecil.TypeAttributes.Sealed | Mono.Cecil.TypeAttributes.Public, + assembly.MainModule.Import(typeof(MulticastDelegate))); + List argTypes = new List(); + TypeReference self = null; + if (!method.IsStatic) + { + self = (!ignoreValueType && method.DeclaringType.IsValueType) ? method.DeclaringType : objType; + } + foreach(var parameter in method.Parameters) + { + bool isparam = parameter.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Name == "ParamArrayAttribute") != null; + argTypes.Add((isparam || parameter.ParameterType.IsByReference || (!ignoreValueType && parameter.ParameterType.IsValueType)) ? parameter.ParameterType : objType); + } + + var constructor = new MethodDefinition(".ctor", Mono.Cecil.MethodAttributes.Public | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName | Mono.Cecil.MethodAttributes.RTSpecialName, voidType); + constructor.Parameters.Add(new ParameterDefinition("objectInstance", Mono.Cecil.ParameterAttributes.None, objectType)); + constructor.Parameters.Add(new ParameterDefinition("functionPtr", Mono.Cecil.ParameterAttributes.None, nativeIntType)); + constructor.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime; + delegateDef.Methods.Add(constructor); + + var beginInvoke = new MethodDefinition("BeginInvoke", delegateMethodAttributes, asyncResultType); + if (self != null) + { + beginInvoke.Parameters.Add(new ParameterDefinition(self)); + } + for (int i = 0; i < argTypes.Count; i++) + { + beginInvoke.Parameters.Add(new ParameterDefinition(method.Parameters[i].Name, (method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None), argTypes[i])); + } + beginInvoke.Parameters.Add(new ParameterDefinition("callback", Mono.Cecil.ParameterAttributes.None, asyncCallbackType)); + beginInvoke.Parameters.Add(new ParameterDefinition("object", Mono.Cecil.ParameterAttributes.None, objectType)); + beginInvoke.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime; + delegateDef.Methods.Add(beginInvoke); + + var endInvoke = new MethodDefinition("EndInvoke", delegateMethodAttributes, method.ReturnType); + for (int i = 0; i < argTypes.Count; i++) + { + if (argTypes[i].IsByReference) + { + endInvoke.Parameters.Add(new ParameterDefinition(method.Parameters[i].Name, (method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None), argTypes[i])); + } + } + endInvoke.Parameters.Add(new ParameterDefinition("result", Mono.Cecil.ParameterAttributes.None, asyncResultType)); + endInvoke.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime; + delegateDef.Methods.Add(endInvoke); + + var invoke = new MethodDefinition("Invoke", delegateMethodAttributes, method.ReturnType); + if (self != null) + { + invoke.Parameters.Add(new ParameterDefinition(self)); + } + for(int i = 0; i < argTypes.Count; i++) + { + invoke.Parameters.Add(new ParameterDefinition(method.Parameters[i].Name, (method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None), argTypes[i])); + } + invoke.ImplAttributes = Mono.Cecil.MethodImplAttributes.Runtime; + delegateDef.Methods.Add(invoke); + + assembly.MainModule.Types.Add(delegateDef); + + return invoke; + } + + MethodDefinition getDelegateInvokeFor(MethodDefinition method, MethodDefinition bridgeDef, bool ignoreValueType) + { + MethodDefinition ret; + if (!hotfixBridgeToDelegate.TryGetValue(bridgeDef, out ret)) + { + ret = createDelegateFor(method, injectAssembly, ("__XLua_Gen_Delegate" + (delegateId++)), ignoreValueType); + hotfixBridgeToDelegate.Add(bridgeDef, ret); + } + + return ret; + } + + bool findHotfixDelegate(MethodDefinition method, out MethodReference invoke, HotfixFlagInTool hotfixType) + { + bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing); + + bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !method.DeclaringType.HasGenericParameters && isTheSameAssembly; + + bool isAdaptByDelegate = !isIntKey && hotfixType.HasFlag(HotfixFlagInTool.AdaptByDelegate); + + for (int i = 0; i < hotfixBridgesDef.Count; i++) + { + MethodDefinition hotfixBridgeDef = hotfixBridgesDef[i]; + var returnType = method.ReturnType; + if (isSameType(returnType, hotfixBridgeDef.ReturnType)) + { + var parametersOfDelegate = hotfixBridgeDef.Parameters; + int compareOffset = 0; + if (!method.IsStatic) + { + var typeOfSelf = (!ignoreValueType && method.DeclaringType.IsValueType) ? method.DeclaringType : objType; + if ((parametersOfDelegate.Count == 0) || parametersOfDelegate[0].ParameterType.IsByReference || !isSameType(typeOfSelf, parametersOfDelegate[0].ParameterType)) + { + continue; + } + compareOffset++; + } + if (method.Parameters.Count != (parametersOfDelegate.Count - compareOffset)) + { + continue; + } + bool paramMatch = true; + for (int j = 0; j < method.Parameters.Count; j++) + { + var param_left = method.Parameters[j]; + var param_right = parametersOfDelegate[compareOffset++]; + if (param_left.IsOut != param_right.IsOut + || param_left.ParameterType.IsByReference != param_right.ParameterType.IsByReference) + { + paramMatch = false; + break; + } + if (!ignoreValueType && param_left.ParameterType.IsValueType != param_right.ParameterType.IsValueType) + { + paramMatch = false; + break; + } + bool isparam = param_left.CustomAttributes.FirstOrDefault(ca => ca.AttributeType.Name == "ParamArrayAttribute") != null; + var type_left = (isparam || param_left.ParameterType.IsByReference || (!ignoreValueType && param_left.ParameterType.IsValueType)) ? param_left.ParameterType : objType; + if (!isSameType(type_left, param_right.ParameterType)) + { + paramMatch = false; + break; + } + } + + if (!paramMatch) + { + continue; + } + invoke = (isTheSameAssembly && !isAdaptByDelegate) ? hotfixBridgeDef : getDelegateInvokeFor(method, hotfixBridgeDef, ignoreValueType); + return true; + } + } + invoke = null; + return false; + } + + static bool hasGenericParameter(TypeReference type) + { + if (type.HasGenericParameters) + { + return true; + } + if (type.IsByReference) + { + return hasGenericParameter(((ByReferenceType)type).ElementType); + } + if (type.IsArray) + { + return hasGenericParameter(((ArrayType)type).ElementType); + } + if (type.IsGenericInstance) + { + foreach (var typeArg in ((GenericInstanceType)type).GenericArguments) + { + if (hasGenericParameter(typeArg)) + { + return true; + } + } + return false; + } + return type.IsGenericParameter; + } + + static bool hasGenericParameter(MethodDefinition method) + { + if (method.HasGenericParameters) return true; + if (!method.IsStatic && hasGenericParameter(method.DeclaringType)) return true; + if (hasGenericParameter(method.ReturnType)) return true; + foreach(var paramInfo in method.Parameters) + { + if (hasGenericParameter(paramInfo.ParameterType)) return true; + } + return false; + } + + static bool isNoPublic(TypeReference type) + { + if (type.IsByReference) + { + return isNoPublic(((ByReferenceType)type).ElementType); + } + if (type.IsArray) + { + return isNoPublic(((ArrayType)type).ElementType); + } + else + { + if (type.IsGenericInstance) + { + foreach (var typeArg in ((GenericInstanceType)type).GenericArguments) + { + if (isNoPublic(typeArg)) + { + return true; + } + } + } + + var resolveType = type.Resolve(); + if ((!type.IsNested && !resolveType.IsPublic) || (type.IsNested && !resolveType.IsNestedPublic)) + { + return true; + } + if (type.IsNested) + { + var parent = type.DeclaringType; + while (parent != null) + { + var resolveParent = parent.Resolve(); + if ((!parent.IsNested && !resolveParent.IsPublic) || (parent.IsNested && !resolveParent.IsNestedPublic)) + { + return true; + } + if (parent.IsNested) + { + parent = parent.DeclaringType; + } + else + { + break; + } + } + } + return false; + } + + } + + static bool genericInOut(MethodDefinition method, HotfixFlagInTool hotfixType) + { + bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing); + + if (hasGenericParameter(method.ReturnType) || isNoPublic(method.ReturnType)) + { + return true; + } + var parameters = method.Parameters; + + if (!method.IsStatic + && (hasGenericParameter(method.DeclaringType) || ((!ignoreValueType && method.DeclaringType.IsValueType) && isNoPublic(method.DeclaringType)))) + { + return true; + } + for (int i = 0; i < parameters.Count; i++) + { + if ( hasGenericParameter(parameters[i].ParameterType) || (((!ignoreValueType && parameters[i].ParameterType.IsValueType) || parameters[i].ParameterType.IsByReference || parameters[i].CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.ParamArrayAttribute")) && isNoPublic(parameters[i].ParameterType))) + { + return true; + } + } + return false; + } + + public bool InjectType(TypeReference hotfixAttributeType, TypeDefinition type) + { + foreach(var nestedTypes in type.NestedTypes) + { + if (!InjectType(hotfixAttributeType, nestedTypes)) + { + return false; + } + } + if (type.Name.Contains("<") || type.IsInterface || type.Methods.Count == 0) // skip anonymous type and interface + { + return true; + } + CustomAttribute hotfixAttr = type.CustomAttributes.FirstOrDefault(ca => ca.AttributeType == hotfixAttributeType); + HotfixFlagInTool hotfixType; + if (hotfixAttr != null) + { + hotfixType = (HotfixFlagInTool)(int)hotfixAttr.ConstructorArguments[0].Value; + } + else + { + if (!hotfixCfg.ContainsKey(type.FullName)) + { + return true; + } + hotfixType = (HotfixFlagInTool)hotfixCfg[type.FullName]; + } + + bool ignoreProperty = hotfixType.HasFlag(HotfixFlagInTool.IgnoreProperty); + bool ignoreCompilerGenerated = hotfixType.HasFlag(HotfixFlagInTool.IgnoreCompilerGenerated); + bool ignoreNotPublic = hotfixType.HasFlag(HotfixFlagInTool.IgnoreNotPublic); + bool isInline = hotfixType.HasFlag(HotfixFlagInTool.Inline); + bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey); + bool noBaseProxy = hotfixType.HasFlag(HotfixFlagInTool.NoBaseProxy); + if (ignoreCompilerGenerated && type.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) + { + return true; + } + if (isIntKey && type.HasGenericParameters) + { + throw new InvalidOperationException(type.FullName + " is generic definition, can not be mark as IntKey!"); + } + //isIntKey = !type.HasGenericParameters; + + foreach (var method in type.Methods) + { + if (ignoreNotPublic && !method.IsPublic) + { + continue; + } + if (ignoreProperty && method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))) + { + continue; + } + if (ignoreCompilerGenerated && method.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) + { + continue; + } + if (method.Parameters.Any(pd => pd.ParameterType.IsPointer) || method.ReturnType.IsPointer) + { + continue; + } + if (method.Name != ".cctor" && !method.IsAbstract && !method.IsPInvokeImpl && method.Body != null && !method.Name.Contains("<")) + { + //Debug.Log(method); + if ((isInline || method.HasGenericParameters || genericInOut(method, hotfixType)) + ? !injectGenericMethod(method, hotfixType) : + !injectMethod(method, hotfixType)) + { + return false; + } + } + } + + if (!noBaseProxy) + { + List toAdd = new List(); + foreach (var method in type.Methods) + { + if (ignoreNotPublic && !method.IsPublic) + { + continue; + } + if (ignoreProperty && method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))) + { + continue; + } + if (ignoreCompilerGenerated && method.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")) + { + continue; + } + if (method.Parameters.Any(pd => pd.ParameterType.IsPointer) || method.ReturnType.IsPointer) + { + continue; + } + if (method.Name != ".cctor" && !method.IsAbstract && !method.IsPInvokeImpl && method.Body != null && !method.Name.Contains("<")) + { + var proxyMethod = tryAddBaseProxy(type, method); + if (proxyMethod != null) toAdd.Add(proxyMethod); + } + } + + foreach (var md in toAdd) + { + type.Methods.Add(md); + } + } + + return true; + } + +#if !XLUA_GENERAL + [PostProcessScene] + [MenuItem("XLua/Hotfix Inject In Editor", false, 3)] + public static void HotfixInject() + { + if (EditorApplication.isCompiling || Application.isPlaying) + { + return; + } + var hotfixCfg = new Dictionary(); + HotfixConfig.GetConfig(hotfixCfg, Utils.GetAllTypes()); + var xluaAssemblyPath = typeof(LuaEnv).Module.FullyQualifiedName; + var idMapFileName = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map.lua.txt"; + var injectAssemblyPaths = HotfixConfig.GetHotfixAssemblyPaths(); + + foreach (var injectAssemblyPath in injectAssemblyPaths) + { + Info("injecting " + injectAssemblyPath); + if (injectAssemblyPaths.Count > 1) + { + var injectAssemblyFileName = Path.GetFileName(injectAssemblyPath); + idMapFileName = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map_" + injectAssemblyFileName.Substring(0, injectAssemblyFileName.Length - 4) + ".lua.txt"; + } + HotfixInject(injectAssemblyPath, xluaAssemblyPath, null, idMapFileName, hotfixCfg); + } + AssetDatabase.Refresh(); + } +#endif + + static AssemblyDefinition readAssembly(string assemblyPath) + { +#if HOTFIX_SYMBOLS_DISABLE + return AssemblyDefinition.ReadAssembly(assemblyPath); +#else + if (File.Exists(assemblyPath + ".mdb")) + { + var readerParameters = new ReaderParameters { ReadSymbols = true }; + return AssemblyDefinition.ReadAssembly(assemblyPath, readerParameters); + } + else + { + return AssemblyDefinition.ReadAssembly(assemblyPath); + } +#endif + } + + static void writeAssembly(AssemblyDefinition assembly, string assemblyPath) + { +#if HOTFIX_SYMBOLS_DISABLE + assembly.Write(assemblyPath); +#else + if (File.Exists(assemblyPath + ".mdb")) + { + var writerParameters = new WriterParameters { WriteSymbols = true }; + assembly.Write(assemblyPath, writerParameters); + } + else + { + assembly.Write(assemblyPath); + } +#endif + } + + public static void HotfixInject(string injectAssemblyPath, string xluaAssemblyPath, IEnumerable searchDirectorys, string idMapFilePath, Dictionary hotfixConfig) + { + AssemblyDefinition injectAssembly = null; + AssemblyDefinition xluaAssembly = null; + try + { + injectAssembly = readAssembly(injectAssemblyPath); + + // injected flag check + if (injectAssembly.MainModule.Types.Any(t => t.Name == "__XLUA_GEN_FLAG")) + { + Info(injectAssemblyPath + " had injected!"); + return; + } + injectAssembly.MainModule.Types.Add(new TypeDefinition("__XLUA_GEN", "__XLUA_GEN_FLAG", Mono.Cecil.TypeAttributes.Class, + injectAssembly.MainModule.TypeSystem.Object)); + + xluaAssembly = (injectAssemblyPath == xluaAssemblyPath || injectAssembly.MainModule.FullyQualifiedName == xluaAssemblyPath) ? + injectAssembly : readAssembly(xluaAssemblyPath); + + Hotfix hotfix = new Hotfix(); + hotfix.Init(injectAssembly, xluaAssembly, searchDirectorys, hotfixConfig); + + //var hotfixDelegateAttributeType = assembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixDelegateAttribute"); + var hotfixAttributeType = xluaAssembly.MainModule.Types.Single(t => t.FullName == "XLua.HotfixAttribute"); + var toInject = (from module in injectAssembly.Modules from type in module.Types select type).ToList(); + foreach (var type in toInject) + { + if (!hotfix.InjectType(hotfixAttributeType, type)) + { + return; + } + } + Directory.CreateDirectory(Path.GetDirectoryName(idMapFilePath)); + hotfix.OutputIntKeyMapper(new FileStream(idMapFilePath, FileMode.Create, FileAccess.Write)); + File.Copy(idMapFilePath, idMapFilePath + "." + DateTime.Now.ToString("yyyyMMddHHmmssfff")); + + writeAssembly(injectAssembly, injectAssemblyPath); + Info(injectAssemblyPath + " inject finish!"); + } + catch(Exception e) + { + Error(injectAssemblyPath + " inject Exception! " + e); + } + finally + { + if (injectAssembly != null) + { + Clean(injectAssembly); + } + if (xluaAssembly != null) + { + Clean(xluaAssembly); + } + } + } + + static void Info(string info) + { +#if XLUA_GENERAL + System.Console.WriteLine(info); +#else + UnityEngine.Debug.Log(info); +#endif + } + + static void Error(string info) + { +#if XLUA_GENERAL + System.Console.WriteLine("Error:" + info); +#else + UnityEngine.Debug.LogError(info); +#endif + } + + static void Clean(AssemblyDefinition assembly) + { + if (assembly.MainModule.SymbolReader != null) + { + assembly.MainModule.SymbolReader.Dispose(); + } + } + + static OpCode[] ldargs = new OpCode[] { OpCodes.Ldarg_0, OpCodes.Ldarg_1, OpCodes.Ldarg_2, OpCodes.Ldarg_3 }; + + static readonly int MAX_OVERLOAD = 100; + + static string getDelegateName(MethodDefinition method) + { + string fieldName = method.Name; + if (fieldName.StartsWith(".")) + { + fieldName = fieldName.Substring(1); + } + string ccFlag = method.IsConstructor ? "_c" : ""; + string luaDelegateName = null; + var type = method.DeclaringType; + for (int i = 0; i < MAX_OVERLOAD; i++) + { + string tmp = ccFlag + "__Hotfix" + i + "_" + fieldName; + if (!type.Fields.Any(f => f.Name == tmp)) // injected + { + luaDelegateName = tmp; + break; + } + } + return luaDelegateName; + } + + static Instruction findNextRet(Mono.Collections.Generic.Collection instructions, Instruction pos) + { + bool posFound = false; + for(int i = 0; i < instructions.Count; i++) + { + if (posFound && instructions[i].OpCode == OpCodes.Ret) + { + return instructions[i]; + } + else if (instructions[i] == pos) + { + posFound = true; + } + } + return null; + } + + Dictionary shortToLong = new Dictionary(); + + void fixBranch(ILProcessor processor, Mono.Collections.Generic.Collection instructions, Dictionary originToNewTarget, HashSet noCheck) + { + foreach(var instruction in instructions) + { + Instruction target = instruction.Operand as Instruction; + if (target != null && !noCheck.Contains(instruction)) + { + if (originToNewTarget.ContainsKey(target)) + { + instruction.Operand = originToNewTarget[target]; + } + } + } + + int offset = 0; + for (int i = 0; i < instructions.Count; i++) + { + var instruction = instructions[i]; + instruction.Offset = offset; + offset += instruction.GetSize(); + } + + for (int i = 0; i < instructions.Count; i++) + { + var instruction = instructions[i]; + Instruction target = instruction.Operand as Instruction; + + if (target != null) + { + int diff = target.Offset - instruction.Offset; + if ((diff > sbyte.MaxValue || diff < sbyte.MinValue) && shortToLong.ContainsKey(instruction.OpCode)) + { + instructions[i] = processor.Create(shortToLong[instruction.OpCode], target); + } + } + } + } + + static MethodDefinition findOverride(TypeDefinition type, MethodReference vmethod) + { + foreach (var method in type.Methods) + { + if (method.Name == vmethod.Name && method.IsVirtual && !method.IsAbstract && (method.ReturnType.FullName == vmethod.ReturnType.FullName) && method.Parameters.Count == vmethod.Parameters.Count) + { + bool isParamsMatch = true; + for (int i = 0; i < method.Parameters.Count; i++) + { + if (method.Parameters[i].Attributes != vmethod.Parameters[i].Attributes + || (method.Parameters[i].ParameterType.FullName != vmethod.Parameters[i].ParameterType.FullName)) + { + isParamsMatch = false; + break; + } + } + if (isParamsMatch) return method; + } + } + return null; + } + + static MethodReference _findBase(TypeReference type, MethodDefinition method) + { + TypeDefinition td = type.Resolve(); + if (td == null) + { + return null; + } + //if (type.IsGenericInstance && + // (method.Module.Assembly.FullName != type.Module.Assembly.FullName || method.Module.Assembly.FullName != td.Module.Assembly.FullName + // || method.Module.FullyQualifiedName != type.Module.FullyQualifiedName || method.Module.FullyQualifiedName != td.Module.FullyQualifiedName)) + //{ + // return _findBase(td.BaseType, method); + //} + var m = findOverride(td, method); + if (m != null) + { + if (type.IsGenericInstance) + { + var reference = new MethodReference(m.Name, tryImport(method.DeclaringType, m.ReturnType), tryImport(method.DeclaringType, type)) + { + HasThis = m.HasThis, + ExplicitThis = m.ExplicitThis, + CallingConvention = m.CallingConvention + }; + foreach (var parameter in m.Parameters) + reference.Parameters.Add(new ParameterDefinition(tryImport(method.DeclaringType, parameter.ParameterType))); + foreach (var generic_parameter in m.GenericParameters) + reference.GenericParameters.Add(new GenericParameter(generic_parameter.Name, reference)); + return reference; + } + else + { + return m; + } + } + return _findBase(td.BaseType, method); + } + + static MethodReference findBase(TypeDefinition type, MethodDefinition method) + { + if (method.IsVirtual && !method.IsNewSlot) //表明override + { + try + { + if (hasGenericParameter(method)) return null; + var b = _findBase(type.BaseType, method); + try + { + if (hasGenericParameter(b.Resolve())) return null; + }catch { } + return b; + } + catch { } + } + return null; + } + + const string BASE_RPOXY_PERFIX = "<>xLuaBaseProxy_"; + + static TypeReference tryImport(TypeReference type, TypeReference toImport) + { + if (type.Module.Assembly.FullName == toImport.Module.Assembly.FullName + && type.Module.FullyQualifiedName == toImport.Module.FullyQualifiedName) + { + return toImport; + } + else + { +#if XLUA_GENERAL + return type.Module.ImportReference(toImport); +#else + return type.Module.Import(toImport); +#endif + } + } + + static MethodReference tryImport(TypeReference type, MethodReference toImport) + { + if (type.Module.Assembly.FullName == toImport.Module.Assembly.FullName + && type.Module.FullyQualifiedName == toImport.Module.FullyQualifiedName) + { + return toImport; + } + else + { +#if XLUA_GENERAL + return type.Module.ImportReference(toImport); +#else + return type.Module.Import(toImport); +#endif + } + } + + static MethodDefinition tryAddBaseProxy(TypeDefinition type, MethodDefinition method) + { + var mbase = findBase(type, method); + if (mbase != null) + { + var proxyMethod = new MethodDefinition(BASE_RPOXY_PERFIX + method.Name, Mono.Cecil.MethodAttributes.Private, tryImport(type, method.ReturnType)); + for (int i = 0; i < method.Parameters.Count; i++) + { + proxyMethod.Parameters.Add(new ParameterDefinition("P" + i, method.Parameters[i].IsOut ? Mono.Cecil.ParameterAttributes.Out : Mono.Cecil.ParameterAttributes.None, tryImport(type, method.Parameters[i].ParameterType))); + } + var instructions = proxyMethod.Body.Instructions; + var processor = proxyMethod.Body.GetILProcessor(); + int paramCount = method.Parameters.Count + 1; + for (int i = 0; i < paramCount; i++) + { + if (i < ldargs.Length) + { + instructions.Add(processor.Create(ldargs[i])); + } + else if (i < 256) + { + instructions.Add(processor.Create(OpCodes.Ldarg_S, (byte)i)); + } + else + { + instructions.Add(processor.Create(OpCodes.Ldarg, (short)i)); + } + if (i == 0 && type.IsValueType) + { + instructions.Add(Instruction.Create(OpCodes.Ldobj, type)); + instructions.Add(Instruction.Create(OpCodes.Box, type)); + } + } + instructions.Add(Instruction.Create(OpCodes.Call, tryImport(type, mbase))); + instructions.Add(Instruction.Create(OpCodes.Ret)); + return proxyMethod; + } + return null; + } + + bool injectMethod(MethodDefinition method, HotfixFlagInTool hotfixType) + { + var type = method.DeclaringType; + + bool isFinalize = (method.Name == "Finalize" && method.IsSpecialName); + + MethodReference invoke = null; + + int param_count = method.Parameters.Count + (method.IsStatic ? 0 : 1); + + if (!findHotfixDelegate(method, out invoke, hotfixType)) + { + Error("can not find delegate for " + method.DeclaringType + "." + method.Name + "! try re-genertate code."); + return false; + } + + if (invoke == null) + { + throw new Exception("unknow exception!"); + } + +#if XLUA_GENERAL + invoke = injectAssembly.MainModule.ImportReference(invoke); +#else + invoke = injectAssembly.MainModule.Import(invoke); +#endif + + FieldReference fieldReference = null; + VariableDefinition injection = null; + bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !type.HasGenericParameters && isTheSameAssembly; + //isIntKey = !type.HasGenericParameters; + + if (!isIntKey) + { + injection = new VariableDefinition(invoke.DeclaringType); + method.Body.Variables.Add(injection); + + var luaDelegateName = getDelegateName(method); + if (luaDelegateName == null) + { + Error("too many overload!"); + return false; + } + + FieldDefinition fieldDefinition = new FieldDefinition(luaDelegateName, Mono.Cecil.FieldAttributes.Static | Mono.Cecil.FieldAttributes.Private, + invoke.DeclaringType); + type.Fields.Add(fieldDefinition); + fieldReference = fieldDefinition.GetGeneric(); + } + + bool ignoreValueType = hotfixType.HasFlag(HotfixFlagInTool.ValueTypeBoxing); + + var insertPoint = method.Body.Instructions[0]; + var processor = method.Body.GetILProcessor(); + + if (method.IsConstructor) + { + insertPoint = findNextRet(method.Body.Instructions, insertPoint); + } + + Dictionary originToNewTarget = new Dictionary(); + HashSet noCheck = new HashSet(); + + while (insertPoint != null) + { + Instruction firstInstruction; + if (isIntKey) + { + firstInstruction = processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count); + processor.InsertBefore(insertPoint, firstInstruction); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, hotfixFlagGetter)); + } + else + { + firstInstruction = processor.Create(OpCodes.Ldsfld, fieldReference); + processor.InsertBefore(insertPoint, firstInstruction); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + } + + var jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint); + processor.InsertBefore(insertPoint, jmpInstruction); + + if (isIntKey) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, delegateBridgeGetter)); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + } + + for (int i = 0; i < param_count; i++) + { + if (i < ldargs.Length) + { + processor.InsertBefore(insertPoint, processor.Create(ldargs[i])); + } + else if (i < 256) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)i)); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)i)); + } + if (i == 0 && !method.IsStatic && type.IsValueType) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, type)); + + } + if (ignoreValueType) + { + TypeReference paramType; + if (method.IsStatic) + { + paramType = method.Parameters[i].ParameterType; + } + else + { + paramType = (i == 0) ? type : method.Parameters[i - 1].ParameterType; + } + if (paramType.IsValueType) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Box, paramType)); + } + } + } + + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, invoke)); + + if (!method.IsConstructor && !isFinalize) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ret)); + } + + if (!method.IsConstructor) + { + break; + } + else + { + originToNewTarget[insertPoint] = firstInstruction; + noCheck.Add(jmpInstruction); + } + insertPoint = findNextRet(method.Body.Instructions, insertPoint); + } + + if (method.IsConstructor) + { + fixBranch(processor, method.Body.Instructions, originToNewTarget, noCheck); + } + + if (isFinalize) + { + if (method.Body.ExceptionHandlers.Count == 0) + { + throw new InvalidProgramException("Finalize has not try-catch? Type :" + method.DeclaringType); + } + method.Body.ExceptionHandlers[0].TryStart = method.Body.Instructions[0]; + } + if (isIntKey) + { + bridgeIndexByKey.Add(method); + } + return true; + } + + bool injectGenericMethod(MethodDefinition method, HotfixFlagInTool hotfixType) + { + //如果注入的是xlua所在之外的Assembly的话,不支持该方式 + if (!isTheSameAssembly) + { + return true; + } + var type = method.DeclaringType; + + bool isFinalize = (method.Name == "Finalize" && method.IsSpecialName); + bool isIntKey = hotfixType.HasFlag(HotfixFlagInTool.IntKey) && !type.HasGenericParameters; + //isIntKey = !type.HasGenericParameters; + + FieldReference fieldReference = null; + VariableDefinition injection = null; + if (!isIntKey) + { + var luaDelegateName = getDelegateName(method); + if (luaDelegateName == null) + { + Error("too many overload!"); + return false; + } + + FieldDefinition fieldDefinition = new FieldDefinition(luaDelegateName, Mono.Cecil.FieldAttributes.Static | Mono.Cecil.FieldAttributes.Private, + delegateBridgeType); + type.Fields.Add(fieldDefinition); + + fieldReference = fieldDefinition.GetGeneric(); + } + + injection = new VariableDefinition(delegateBridgeType); + method.Body.Variables.Add(injection); + + int param_start = method.IsStatic ? 0 : 1; + int param_count = method.Parameters.Count + param_start; + var insertPoint = method.Body.Instructions[0]; + var processor = method.Body.GetILProcessor(); + + if (method.IsConstructor) + { + insertPoint = findNextRet(method.Body.Instructions, insertPoint); + } + + Dictionary originToNewTarget = new Dictionary(); + HashSet noCheck = new HashSet(); + + while (insertPoint != null) + { + Instruction firstInstruction; + Instruction jmpInstruction; + if (isIntKey) + { + firstInstruction = processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count); + processor.InsertBefore(insertPoint, firstInstruction); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, hotfixFlagGetter)); + jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint); + processor.InsertBefore(insertPoint, jmpInstruction); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, bridgeIndexByKey.Count)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Call, delegateBridgeGetter)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection)); + } + else + { + firstInstruction = processor.Create(OpCodes.Ldsfld, fieldReference); + processor.InsertBefore(insertPoint, firstInstruction); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Stloc, injection)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + jmpInstruction = processor.Create(OpCodes.Brfalse, insertPoint); + processor.InsertBefore(insertPoint, jmpInstruction); + } + + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, invokeSessionStart)); + + TypeReference returnType = method.ReturnType; + + bool isVoid = returnType.FullName == "System.Void"; + + int outCout = 0; + + for (int i = 0; i < param_count; i++) + { + if (i == 0 && !method.IsStatic) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_0)); + if (type.IsValueType) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, method.DeclaringType.GetGeneric())); + } + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, inParam.MakeGenericMethod(method.DeclaringType.GetGeneric()))); + } + else + { + var param = method.Parameters[i - param_start]; + if (param.ParameterType.IsByReference) + { + outCout++; + } + if (!param.IsOut) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + + if (i < ldargs.Length) + { + processor.InsertBefore(insertPoint, processor.Create(ldargs[i])); + } + else if (i < 256) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)i)); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)i)); + } + + var paramType = param.ParameterType; + + if (param.ParameterType.IsByReference) + { + paramType = ((ByReferenceType)paramType).ElementType; + if (paramType.IsValueType || paramType.IsGenericParameter) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldobj, paramType)); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldind_Ref)); + } + } + if (i == param_count - 1 && param.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.ParamArrayAttribute")) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, inParams.MakeGenericMethod(((ArrayType)paramType).ElementType))); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, inParam.MakeGenericMethod(paramType))); + } + } + } + } + + int outStart = (isVoid ? 0 : 1); + + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, outCout + outStart)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, functionInvoke)); + + int outPos = outStart; + for (int i = 0; i < method.Parameters.Count; i++) + { + if (method.Parameters[i].ParameterType.IsByReference) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldc_I4, outPos)); + int arg_pos = param_start + i; + if (arg_pos < ldargs.Length) + { + processor.InsertBefore(insertPoint, processor.Create(ldargs[arg_pos])); + } + else if (arg_pos < 256) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg_S, (byte)arg_pos)); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldarg, (short)arg_pos)); + } + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, outParam.MakeGenericMethod( + ((ByReferenceType)method.Parameters[i].ParameterType).ElementType))); + outPos++; + } + } + + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ldloc, injection)); + if (isVoid) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, invokeSessionEnd)); + } + else + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Callvirt, invokeSessionEndWithResult.MakeGenericMethod(returnType))); + } + + if (!method.IsConstructor && !isFinalize) + { + processor.InsertBefore(insertPoint, processor.Create(OpCodes.Ret)); + } + + if (!method.IsConstructor) + { + break; + } + else + { + originToNewTarget[insertPoint] = firstInstruction; + noCheck.Add(jmpInstruction); + } + + insertPoint = findNextRet(method.Body.Instructions, insertPoint); + } + + if (method.IsConstructor) + { + fixBranch(processor, method.Body.Instructions, originToNewTarget, noCheck); + } + + if (isFinalize) + { + method.Body.ExceptionHandlers[0].TryStart = method.Body.Instructions[0]; + } + + if (isIntKey) + { + bridgeIndexByKey.Add(method); + } + + return true; + } + + public void OutputIntKeyMapper(Stream output) + { + using (StreamWriter writer = new StreamWriter(output)) + { + writer.WriteLine("return {"); + var data = bridgeIndexByKey + .Select((md, idx) => new { Method = md, Index = idx}) + .GroupBy(info => info.Method.DeclaringType) + .ToDictionary(group => group.Key, group => + { + return group.GroupBy(info => info.Method.Name).ToDictionary(group_by_name => group_by_name.Key, group_by_name => group_by_name.Select(info => info.Index.ToString()).ToArray()); + }); + foreach(var kv in data) + { + writer.WriteLine(" [\"" + kv.Key.FullName.Replace('/', '+') + "\"] = {"); + foreach(var kv2 in kv.Value) + { + writer.WriteLine(" [\"" + kv2.Key + "\"] = {"); + writer.WriteLine(" " + string.Join(",", kv2.Value)); + writer.WriteLine(" },"); + } + writer.WriteLine(" },"); + } + writer.WriteLine("}"); + } + } + } +} +#else + +namespace XLua +{ +#if UNITY_2019_1_OR_NEWER + class MyCustomBuildProcessor : IPostBuildPlayerScriptDLLs + { + public int callbackOrder { get { return 0; } } + public void OnPostBuildPlayerScriptDLLs(BuildReport report) + { + var dir = Path.GetDirectoryName(report.files.Single(file => file.path.EndsWith("Assembly-CSharp.dll")).path); + Hotfix.HotfixInject(dir); + } + } +#endif + + public static class Hotfix + { + static bool ContainNotAsciiChar(string s) + { + for (int i = 0; i < s.Length; ++i) + { + if (s[i] > 127) + { + return true; + } + } + return false; + } + +#if !UNITY_2019_1_OR_NEWER + [PostProcessScene] +#endif + [MenuItem("XLua/Hotfix Inject In Editor", false, 3)] + public static void HotfixInject() + { + HotfixInject("./Library/ScriptAssemblies"); + } + + public static void HotfixInject(string assemblyDir) + { + if (Application.isPlaying) + { + return; + } + + if (EditorApplication.isCompiling) + { + UnityEngine.Debug.LogError("You can't inject before the compilation is done"); + return; + } + +#if UNITY_EDITOR_OSX + var mono_path = Path.Combine(Path.GetDirectoryName(typeof(UnityEngine.Debug).Module.FullyQualifiedName), + "../MonoBleedingEdge/bin/mono"); + if(!File.Exists(mono_path)) + { + mono_path = Path.Combine(Path.GetDirectoryName(typeof(UnityEngine.Debug).Module.FullyQualifiedName), + "../../MonoBleedingEdge/bin/mono"); + } + if(!File.Exists(mono_path)) + { + UnityEngine.Debug.LogError("can not find mono!"); + } +#elif UNITY_EDITOR_WIN + var mono_path = Path.Combine(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), + "Data/MonoBleedingEdge/bin/mono.exe"); +#endif + var inject_tool_path = "./Tools/XLuaHotfixInject.exe"; + if (!File.Exists(inject_tool_path)) + { + UnityEngine.Debug.LogError("please install the Tools"); + return; + } + + var assembly_csharp_path = Path.Combine(assemblyDir, "Assembly-CSharp.dll"); + var id_map_file_path = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map.lua.txt"; + var hotfix_cfg_in_editor = CSObjectWrapEditor.GeneratorConfig.common_path + "hotfix_cfg_in_editor.data"; + + Dictionary editor_cfg = new Dictionary(); + Assembly editor_assembly = typeof(Hotfix).Assembly; + HotfixConfig.GetConfig(editor_cfg, Utils.GetAllTypes().Where(t => t.Assembly == editor_assembly)); + + if (!Directory.Exists(CSObjectWrapEditor.GeneratorConfig.common_path)) + { + Directory.CreateDirectory(CSObjectWrapEditor.GeneratorConfig.common_path); + } + + using (BinaryWriter writer = new BinaryWriter(new FileStream(hotfix_cfg_in_editor, FileMode.Create, FileAccess.Write))) + { + writer.Write(editor_cfg.Count); + foreach (var kv in editor_cfg) + { + writer.Write(kv.Key); + writer.Write(kv.Value); + } + } + + List args = new List() { assembly_csharp_path, typeof(LuaEnv).Module.FullyQualifiedName, id_map_file_path, hotfix_cfg_in_editor }; + + foreach (var path in + (from asm in AppDomain.CurrentDomain.GetAssemblies() select asm.ManifestModule.FullyQualifiedName) + .Distinct()) + { + try + { + args.Add(System.IO.Path.GetDirectoryName(path)); + } + catch (Exception) + { + + } + } + var injectAssemblyPaths = HotfixConfig.GetHotfixAssemblyPaths(); + var idMapFileNames = new List(); + foreach (var injectAssemblyPath in injectAssemblyPaths) + { + args[0] = Path.Combine(assemblyDir, Path.GetFileName(injectAssemblyPath)); + if (ContainNotAsciiChar(args[0])) + { + throw new Exception("project path must contain only ascii characters"); + } + + if (injectAssemblyPaths.Count > 1) + { + var injectAssemblyFileName = Path.GetFileName(injectAssemblyPath); + args[2] = CSObjectWrapEditor.GeneratorConfig.common_path + "Resources/hotfix_id_map_" + injectAssemblyFileName.Substring(0, injectAssemblyFileName.Length - 4) + ".lua.txt"; + idMapFileNames.Add(args[2]); + } + Process hotfix_injection = new Process(); + hotfix_injection.StartInfo.FileName = mono_path; +#if UNITY_5_6_OR_NEWER + hotfix_injection.StartInfo.Arguments = "--runtime=v4.0.30319 " + inject_tool_path + " \"" + String.Join("\" \"", args.ToArray()) + "\""; +#else + hotfix_injection.StartInfo.Arguments = inject_tool_path + " \"" + String.Join("\" \"", args.ToArray()) + "\""; +#endif + hotfix_injection.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + hotfix_injection.StartInfo.RedirectStandardOutput = true; + hotfix_injection.StartInfo.UseShellExecute = false; + hotfix_injection.StartInfo.CreateNoWindow = true; + hotfix_injection.Start(); + UnityEngine.Debug.Log(hotfix_injection.StandardOutput.ReadToEnd()); + hotfix_injection.WaitForExit(); + } + + File.Delete(hotfix_cfg_in_editor); + AssetDatabase.Refresh(); + } + } +} +#endif +#endif diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Hotfix.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Hotfix.cs.meta new file mode 100644 index 0000000..03cf74d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Hotfix.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e9c0ec9b36733894b8026b9593247368 +timeCreated: 1482299911 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen.meta new file mode 100644 index 0000000..a5505a2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 2adb77766078ea34b8c50aba719384e1 +folderAsset: yes +timeCreated: 1479105499 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs new file mode 100644 index 0000000..519f211 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs @@ -0,0 +1,34 @@ +using UnityEngine; +using System.Collections.Generic; +using XLua; +using System.IO; +using System.Text; +using System.Linq; +using CSObjectWrapEditor; + +public class LinkXmlGen : ScriptableObject +{ + public TextAsset Template; + + public static IEnumerable GetTasks(LuaEnv lua_env, UserConfig user_cfg) + { + LuaTable data = lua_env.NewTable(); + var assembly_infos = (from type in (user_cfg.ReflectionUse.Concat(user_cfg.LuaCallCSharp)) + group type by type.Assembly.GetName().Name into assembly_info + select new { FullName = assembly_info.Key, Types = assembly_info.ToList()}).ToList(); + data.Set("assembly_infos", assembly_infos); + + yield return new CustomGenTask + { + Data = data, + Output = new StreamWriter(GeneratorConfig.common_path + "/link.xml", + false, Encoding.UTF8) + }; + } + + [GenCodeMenu]//加到Generate Code菜单里头 + public static void GenLinkXml() + { + Generator.CustomGen(ScriptableObject.CreateInstance().Template.text, GetTasks); + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs.meta new file mode 100644 index 0000000..fa5b4db --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 613237163ad3fb144b4ee9785dc32656 +timeCreated: 1482482561 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: + - Template: {fileID: 4900000, guid: 384feb229d259f549bbbac9e910b782b, type: 3} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.tpl.txt new file mode 100644 index 0000000..5adb08a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.tpl.txt @@ -0,0 +1,13 @@ +<% +require "TemplateCommon" +%> + + +<%ForEachCsList(assembly_infos, function(assembly_info)%> + + <%ForEachCsList(assembly_info.Types, function(type) + %> + <%end)%> + +<%end)%> + \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.tpl.txt.meta new file mode 100644 index 0000000..1d7084c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5c42a395cd94e544e8250436a6096f6b +timeCreated: 1481621844 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LuaImporter.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LuaImporter.cs new file mode 100644 index 0000000..d10eef3 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LuaImporter.cs @@ -0,0 +1,188 @@ +#if UNITY_2018_1_OR_NEWER + +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +using System.IO; +using System.Security.Cryptography; +using System.Text; + +#if UNITY_2020_2_OR_NEWER +using UnityEditor.AssetImporters; +#else +using UnityEditor.Experimental.AssetImporters; +#endif + +[ScriptedImporter(2, new[] {"lua"})] +public class LuaImporter : ScriptedImporter +{ + const string Tag = "LuaImporter"; + public static bool compile = false; // compile to lua byte code + public static bool strip = false; // strip lua debug info + public static bool encode = true; + + public static void Compile(string exe, string prmt) + { + //bool finished = false; + var process = new System.Diagnostics.Process(); + //var processing = 0f; + try + { + var pi = new System.Diagnostics.ProcessStartInfo(exe, prmt); + pi.WorkingDirectory = "."; + pi.RedirectStandardInput = false; + pi.RedirectStandardOutput = true; + pi.RedirectStandardError = true; + pi.UseShellExecute = false; + pi.CreateNoWindow = true; + + process.OutputDataReceived += (sender, e) => + { + if (string.IsNullOrEmpty(e.Data)) + return; + UnityEngine.Debug.Log(e.Data); + }; + process.ErrorDataReceived += (sender, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + UnityEngine.Debug.LogError(e.GetType() + ": " + e.Data); + }; + process.Exited += (sender, e) => + { + UnityEngine.Debug.Log($"{exe} {prmt} Exit"); + }; + + process.StartInfo = pi; + process.EnableRaisingEvents = true; + process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + process.WaitForExit(); + } + catch (System.Exception e) + { + UnityEngine.Debug.LogError("catch: " + e); + } + + // UnityEngine.Debug.Log("finished: " + process.ExitCode); + EditorUtility.ClearProgressBar(); + } + + public override void OnImportAsset(AssetImportContext ctx) + { + var prefax = Path.GetExtension(ctx.assetPath).Substring(1); + + var asset = LuaAsset.CreateInstance(); + byte[] data; + if (compile) + { + // compile to lua byte code + var outDir = $"obj/{Path.GetDirectoryName(ctx.assetPath)}"; + if (!Directory.Exists(outDir)) + Directory.CreateDirectory(outDir); + var outPath = $"obj/{ctx.assetPath}c"; + #if UNITY_EDITOR_OSX + var luac = "build/luac/build_unix/luac"; + #elif UNITY_EDITOR_WIN + var luac = "build/luac/build32/luac.exe"; + #elif UNITY_EDITOR_WIN64 + var luac = "build/luac/build64/luac.exe"; + #endif + var prmt = $"{(strip ? "-s" : "")} -o {outPath} -- {ctx.assetPath}"; + Compile(luac, prmt); + data = File.ReadAllBytes(outPath); + } + else + { + data = File.ReadAllBytes(ctx.assetPath); + } + + // TODO: your encode function, like xxtea + if(encode) + { + data = Security.XXTEA.Encrypt(data, LuaAsset.LuaDecodeKey); + } + + asset.data = data; + asset.encode = encode; + ctx.AddObjectToAsset("main obj", asset, LoadIconTexture(prefax)); + ctx.SetMainObject(asset); + } + + private Texture2D LoadIconTexture(string prefax) + { + return AssetDatabase.LoadAssetAtPath("Assets/XLua/Editor/lua.png", typeof(Texture2D)) as + Texture2D; + } +} + + +[CustomEditor(typeof(LuaAsset))] +public class LuaAssetEditor : UnityEditor.Editor +{ + private static bool decode = true; + private LuaAsset mTarget; + private void OnEnable() + { + mTarget = target as LuaAsset; + } + + public override void OnInspectorGUI() + { + GUI.enabled = true; + EditorGUILayout.LabelField("Import Config(重新导入时生效)"); + { + ++EditorGUI.indentLevel; + LuaImporter.compile = EditorGUILayout.Toggle("compile(编译为字节码)", LuaImporter.compile); + if (LuaImporter.compile) + { + ++EditorGUI.indentLevel; + LuaImporter.strip = EditorGUILayout.Toggle("strip", LuaImporter.strip); + --EditorGUI.indentLevel; + } + + LuaImporter.encode = EditorGUILayout.Toggle("encode(加密)", LuaImporter.encode); + --EditorGUI.indentLevel; + } + EditorGUILayout.Space(); + + EditorGUILayout.LabelField("Display Config"); + { + ++EditorGUI.indentLevel; + GUI.enabled = false; + EditorGUILayout.Toggle("encoded(加密)", mTarget.encode); + GUI.enabled = true; + + if(mTarget.encode) + decode = EditorGUILayout.Toggle("decode", decode); + --EditorGUI.indentLevel; + } + + var text = string.Empty; + if (mTarget.encode && decode) + { + // TODO: your decode function + text = Encoding.UTF8.GetString(Security.XXTEA.Decrypt(mTarget.data, LuaAsset.LuaDecodeKey)); + }else + { + text = Encoding.UTF8.GetString(mTarget.data); + } + var MaxTextPreviewLength = 4096; + if (text.Length > MaxTextPreviewLength + 3) + { + text = text.Substring(0, MaxTextPreviewLength) + "..."; + } + + GUIStyle style = "ScriptText"; + Rect rect = GUILayoutUtility.GetRect(new GUIContent(text), style); + rect.x = 0f; + rect.y -= 3f; + rect.width = EditorGUIUtility.currentViewWidth + 1f; + GUI.Box(rect, text, style); + } +} + +#endif diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LuaImporter.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LuaImporter.cs.meta new file mode 100644 index 0000000..b9b5df5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/LuaImporter.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 505b3ad82f257a34eba53061df16fe7f +timeCreated: 1614334463 \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template.meta new file mode 100644 index 0000000..24d7ea3 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: bd93bf928ae4d7b488f37272895b12c3 +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrap.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrap.tpl.txt new file mode 100644 index 0000000..0ee1e9f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrap.tpl.txt @@ -0,0 +1,589 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using XLua; +using System.Collections.Generic; +<%ForEachCsList(namespaces, function(namespace)%>using <%=namespace%>;<%end)%> +<% +require "TemplateCommon" + +local OpNameMap = { + op_Addition = "__AddMeta", + op_Subtraction = "__SubMeta", + op_Multiply = "__MulMeta", + op_Division = "__DivMeta", + op_Equality = "__EqMeta", + op_UnaryNegation = "__UnmMeta", + op_LessThan = "__LTMeta", + op_LessThanOrEqual = "__LEMeta", + op_Modulus = "__ModMeta", + op_BitwiseAnd = "__BandMeta", + op_BitwiseOr = "__BorMeta", + op_ExclusiveOr = "__BxorMeta", + op_OnesComplement = "__BnotMeta", + op_LeftShift = "__ShlMeta", + op_RightShift = "__ShrMeta", +} + +local OpCallNameMap = { + op_Addition = "+", + op_Subtraction = "-", + op_Multiply = "*", + op_Division = "/", + op_Equality = "==", + op_UnaryNegation = "-", + op_LessThan = "<", + op_LessThanOrEqual = "<=", + op_Modulus = "%", + op_BitwiseAnd = "&", + op_BitwiseOr = "|", + op_ExclusiveOr = "^", + op_OnesComplement = "~", + op_LeftShift = "<<", + op_RightShift = ">>", +} + +local obj_method_count = 0 +local obj_getter_count = 0 +local obj_setter_count = 0 +local meta_func_count = operators.Count +local cls_field_count = 1 +local cls_getter_count = 0 +local cls_setter_count = 0 + +ForEachCsList(methods, function(method) + if method.IsStatic then + cls_field_count = cls_field_count + 1 + else + obj_method_count = obj_method_count + 1 + end +end) + +ForEachCsList(events, function(event) + if event.IsStatic then + cls_field_count = cls_field_count + 1 + else + obj_method_count = obj_method_count + 1 + end +end) + +ForEachCsList(getters, function(getter) + if getter.IsStatic then + if getter.ReadOnly then + cls_field_count = cls_field_count + 1 + else + cls_getter_count = cls_getter_count + 1 + end + else + obj_getter_count = obj_getter_count + 1 + end +end) + +ForEachCsList(setters, function(setter) + if setter.IsStatic then + cls_setter_count = cls_setter_count + 1 + else + obj_setter_count = obj_setter_count + 1 + end +end) + +ForEachCsList(lazymembers, function(lazymember) + if lazymember.IsStatic == 'true' then + if 'CLS_IDX' == lazymember.Index then + cls_field_count = cls_field_count + 1 + elseif 'CLS_GETTER_IDX' == lazymember.Index then + cls_getter_count = cls_getter_count + 1 + elseif 'CLS_SETTER_IDX' == lazymember.Index then + cls_setter_count = cls_setter_count + 1 + end + else + if 'METHOD_IDX' == lazymember.Index then + obj_method_count = obj_method_count + 1 + elseif 'GETTER_IDX' == lazymember.Index then + obj_getter_count = obj_getter_count + 1 + elseif 'SETTER_IDX' == lazymember.Index then + obj_setter_count = obj_setter_count + 1 + end + end +end) + +local generic_arg_list, type_constraints = GenericArgumentList(type) + +%> +namespace XLua.CSObjectWrap +{ + using Utils = XLua.Utils; + public class <%=CSVariableName(type)%>Wrap<%=generic_arg_list%> <%=type_constraints%> + { + public static void __Register(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + System.Type type = typeof(<%=CsFullTypeName(type)%>); + Utils.BeginObjectRegister(type, L, translator, <%=meta_func_count%>, <%=obj_method_count%>, <%=obj_getter_count%>, <%=obj_setter_count%>); + <%ForEachCsList(operators, function(operator)%>Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "<%=(OpNameMap[operator.Name]):gsub('Meta', ''):lower()%>", <%=OpNameMap[operator.Name]%>); + <%end)%> + <%ForEachCsList(methods, function(method) if not method.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=method.Name%>", _m_<%=method.Name%>); + <% end end)%> + <%ForEachCsList(events, function(event) if not event.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=event.Name%>", _e_<%=event.Name%>); + <% end end)%> + <%ForEachCsList(getters, function(getter) if not getter.IsStatic then %>Utils.RegisterFunc(L, Utils.GETTER_IDX, "<%=getter.Name%>", _g_get_<%=getter.Name%>); + <%end end)%> + <%ForEachCsList(setters, function(setter) if not setter.IsStatic then %>Utils.RegisterFunc(L, Utils.SETTER_IDX, "<%=setter.Name%>", _s_set_<%=setter.Name%>); + <%end end)%> + <%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'false' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>); + <%end end)%> + Utils.EndObjectRegister(type, L, translator, <% if type.IsArray or ((indexers.Count or 0) > 0) then %>__CSIndexer<%else%>null<%end%>, <%if type.IsArray or ((newindexers.Count or 0) > 0) then%>__NewIndexer<%else%>null<%end%>, + null, null, null); + + Utils.BeginClassRegister(type, L, __CreateInstance, <%=cls_field_count%>, <%=cls_getter_count%>, <%=cls_setter_count%>); + <%ForEachCsList(methods, function(method) if method.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=method.Overloads[0].Name%>", _m_<%=method.Name%>); + <% end end)%> + <%ForEachCsList(events, function(event) if event.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=event.Name%>", _e_<%=event.Name%>); + <% end end)%> + <%ForEachCsList(getters, function(getter) if getter.IsStatic and getter.ReadOnly then %>Utils.RegisterObject(L, translator, Utils.CLS_IDX, "<%=getter.Name%>", <%=CsFullTypeName(type).."."..getter.Name%>); + <%end end)%> + <%ForEachCsList(getters, function(getter) if getter.IsStatic and (not getter.ReadOnly) then %>Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "<%=getter.Name%>", _g_get_<%=getter.Name%>); + <%end end)%> + <%ForEachCsList(setters, function(setter) if setter.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "<%=setter.Name%>", _s_set_<%=setter.Name%>); + <%end end)%> + <%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'true' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>); + <%end end)%> + Utils.EndClassRegister(type, L, translator); + } + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int __CreateInstance(RealStatePtr L) + { + <% + if constructors.Count == 0 and (not type.IsValueType) then + %>return LuaAPI.luaL_error(L, "<%=CsFullTypeName(type)%> does not have a constructor!");<% + else %> + try { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + <% + local hasZeroParamsCtor = false + ForEachCsList(constructors, function(constructor, ci) + local parameters = constructor:GetParameters() + if parameters.Length == 0 then + hasZeroParamsCtor = true + end + local def_count = constructor_def_vals[ci] + local param_count = parameters.Length + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local real_param_count = param_count - def_count + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + local in_pos = 0 + %>if(LuaAPI.lua_gettop(L) <%=has_v_params and ">=" or "=="%> <%=in_num + 1 - def_count - (has_v_params and 1 or 0)%><%ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + local parameterType = parameter.ParameterType + if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1 + %> && <%=GetCheckStatement(parameterType, in_pos+1, has_v_params and pi == param_count - 1)%><% + end + end)%>) + { + <%ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + %><%=GetCasterStatement(parameter.ParameterType, pi+2, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%>; + <%end)%> + var gen_ret = new <%=CsFullTypeName(type)%>(<%ForEachCsList(parameters, function(parameter, pi) if pi >= real_param_count then return end; if pi ~=0 then %><%=', '%><% end ;if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end)%>); + <%=GetPushStatement(type, "gen_ret")%>; + <%local in_pos = 0 + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + end + if parameter.ParameterType.IsByRef then + %><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>; + <%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then + %><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+1, LocalName(parameter.Name))%>; + <%end%> + <% + end + end) + %> + return <%=out_num + 1%>; + } + <%end) + if (not hasZeroParamsCtor) and type.IsValueType then + %> + if (LuaAPI.lua_gettop(L) == 1) + { + <%=GetPushStatement(type, "default(" .. CsFullTypeName(type).. ")")%>; + return 1; + } + <%end%> + } + catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%> constructor!"); + <% end %> + } + + <% if type.IsArray or ((indexers.Count or 0) > 0) then %> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + public static int __CSIndexer(RealStatePtr L) + { + <%if type.IsArray then %> + try { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + + if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2)) + { + int index = (int)LuaAPI.lua_tonumber(L, 2); + <%=GetSelfStatement(type)%>; + LuaAPI.lua_pushboolean(L, true); + <%=GetPushStatement(type:GetElementType(), "gen_to_be_invoked[index]")%>; + return 2; + } + } + catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + <%elseif indexers.Count > 0 then + %>try { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + <% + ForEachCsList(indexers, function(indexer) + local paramter = indexer:GetParameters()[0] + %> + if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(paramter.ParameterType, 2)%>) + { + + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(paramter.ParameterType, 2, "index", true)%>; + LuaAPI.lua_pushboolean(L, true); + <%=GetPushStatement(indexer.ReturnType, "gen_to_be_invoked[index]")%>; + return 2; + } + <%end)%> + } + catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + <%end%> + LuaAPI.lua_pushboolean(L, false); + return 1; + } + <% end %> + + <%if type.IsArray or ((newindexers.Count or 0) > 0) then%> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + public static int __NewIndexer(RealStatePtr L) + { + <%if type.IsArray or newindexers.Count > 0 then %>ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%> + <%if type.IsArray then + local elementType = type:GetElementType() + %> + try { + if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2) && <%=GetCheckStatement(elementType, 3)%>) + { + int index = (int)LuaAPI.lua_tonumber(L, 2); + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(elementType, 3, "gen_to_be_invoked[index]")%>; + LuaAPI.lua_pushboolean(L, true); + return 1; + } + } + catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + <%elseif newindexers.Count > 0 then%> + try { + <%ForEachCsList(newindexers, function(newindexer) + local keyType = newindexer:GetParameters()[0].ParameterType + local valueType = newindexer:GetParameters()[1].ParameterType + %> + if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(keyType, 2)%> && <%=GetCheckStatement(valueType, 3)%>) + { + + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(keyType, 2, "key", true)%>; + <%if IsStruct(valueType) then%><%=GetCasterStatement(valueType, 3, "gen_value", true)%>; + gen_to_be_invoked[key] = gen_value;<%else + %><%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;<%end%> + LuaAPI.lua_pushboolean(L, true); + return 1; + } + <%end)%> + } + catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + <%end%> + LuaAPI.lua_pushboolean(L, false); + return 1; + } + <% end %> + + <%ForEachCsList(operators, function(operator) %> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int <%=OpNameMap[operator.Name]%>(RealStatePtr L) + { + <% if operator.Name ~= "op_UnaryNegation" and operator.Name ~= "op_OnesComplement" then %> + try { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + <%ForEachCsList(operator.Overloads, function(overload) + local left_param = overload:GetParameters()[0] + local right_param = overload:GetParameters()[1] + %> + + if (<%=GetCheckStatement(left_param.ParameterType, 1)%> && <%=GetCheckStatement(right_param.ParameterType, 2)%>) + { + <%=GetCasterStatement(left_param.ParameterType, 1, "leftside", true)%>; + <%=GetCasterStatement(right_param.ParameterType, 2, "rightside", true)%>; + + <%=GetPushStatement(overload.ReturnType, "leftside " .. OpCallNameMap[operator.Name] .. " rightside")%>; + + return 1; + } + <%end)%> + } + catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + return LuaAPI.luaL_error(L, "invalid arguments to right hand of <%=OpCallNameMap[operator.Name]%> operator, need <%=CsFullTypeName(type)%>!"); + <%else%> + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + try { + <%=GetCasterStatement(type, 1, "rightside", true)%>; + <%=GetPushStatement(operator.Overloads[0].ReturnType, OpCallNameMap[operator.Name] .. " rightside")%>; + } catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + return 1; + <%end%> + } + <%end)%> + + <%ForEachCsList(methods, function(method)%> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int _m_<%=method.Name%>(RealStatePtr L) + { + try { + <% + local need_obj = not method.IsStatic + if MethodCallNeedTranslator(method) then + %> + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + <%end%> + <%if need_obj then%> + <%=GetSelfStatement(type)%>; + <%end%> + <%if method.Overloads.Count > 1 then%> + int gen_param_count = LuaAPI.lua_gettop(L); + <%end%> + <%ForEachCsList(method.Overloads, function(overload, oi) + local parameters = MethodParameters(overload) + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local param_offset = method.IsStatic and 0 or 1 + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local in_pos = 0 + local has_return = (overload.ReturnType.FullName ~= "System.Void") + local def_count = method.DefaultValues[oi] + local param_count = parameters.Length + local real_param_count = param_count - def_count + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + if method.Overloads.Count > 1 then + %>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num+param_offset-def_count - (has_v_params and 1 or 0)%><% + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + local parameterType = parameter.ParameterType + if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1; + %>&& <%=GetCheckStatement(parameterType , in_pos+param_offset, has_v_params and pi == param_count - 1)%><% + end + end)%>) <%end%> + { + <%if overload.Name == "get_Item" and overload.IsSpecialName then + local keyType = overload:GetParameters()[0].ParameterType%> + <%=GetCasterStatement(keyType, 2, "key", true)%>; + <%=GetPushStatement(overload.ReturnType, "gen_to_be_invoked[key]")%>; + <%elseif overload.Name == "set_Item" and overload.IsSpecialName then + local keyType = overload:GetParameters()[0].ParameterType + local valueType = overload:GetParameters()[1].ParameterType%> + <%=GetCasterStatement(keyType, 2, "key", true)%>; + <%=GetCasterStatement(valueType, 3, "gen_value", true)%>; + gen_to_be_invoked[key] = gen_value; + <% else + in_pos = 0; + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + %><%if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + %><%=GetCasterStatement(parameter.ParameterType, in_pos+param_offset, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%><% + else%><%=CsFullTypeName(parameter.ParameterType)%> <%=LocalName(parameter.Name)%><%end%>; + <%end)%> + <% + if has_return then + %> var gen_ret = <% + end + %><%if method.IsStatic then + %><%=CsFullTypeName(type).."."..UnK(overload.Name)%><% + else + %>gen_to_be_invoked.<%=UnK(overload.Name)%><% + end%>( <%ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + if pi ~= 0 then %>, <% end; if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end) %> ); + <% + if has_return then + %> <%=GetPushStatement(overload.ReturnType, "gen_ret")%>; + <% + end + local in_pos = 0 + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + end + if parameter.ParameterType.IsByRef then + %><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>; + <%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then + %><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, LocalName(parameter.Name))%>; + <%end%> + <% + end + end) + end + %> + <%if NeedUpdate(type) and not method.IsStatic then%> + <%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>; + <%end%> + + return <%=out_num+(has_return and 1 or 0)%>; + } + <% end)%> + } catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + <%if method.Overloads.Count > 1 then%> + return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=method.Overloads[0].Name%>!"); + <%end%> + } + <% end)%> + + + <%ForEachCsList(getters, function(getter) + if getter.IsStatic and getter.ReadOnly then return end --readonly static + %> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int _g_get_<%=getter.Name%>(RealStatePtr L) + { + try { + <%if AccessorNeedTranslator(getter) then %> ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%> + <%if not getter.IsStatic then%> + <%=GetSelfStatement(type)%>; + <%=GetPushStatement(getter.Type, "gen_to_be_invoked."..UnK(getter.Name))%>;<% else %> <%=GetPushStatement(getter.Type, CsFullTypeName(type).."."..UnK(getter.Name))%>;<% end%> + } catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + return 1; + } + <%end)%> + + <%ForEachCsList(setters, function(setter) + local is_struct = IsStruct(setter.Type) + %> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int _s_set_<%=setter.Name%>(RealStatePtr L) + { + try { + <%if AccessorNeedTranslator(setter) then %>ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%> + <%if not setter.IsStatic then %> + <%=GetSelfStatement(type)%>; + <%if is_struct then %><%=GetCasterStatement(setter.Type, 2, "gen_value", true)%>; + gen_to_be_invoked.<%=UnK(setter.Name)%> = gen_value;<% else + %><%=GetCasterStatement(setter.Type, 2, "gen_to_be_invoked." .. UnK(setter.Name))%>;<%end + else + if is_struct then %><%=GetCasterStatement(setter.Type, 1, "gen_value", true)%>; + <%=CsFullTypeName(type)%>.<%=UnK(setter.Name)%> = gen_value;<%else + %> <%=GetCasterStatement(setter.Type, 1, CsFullTypeName(type) .."." .. UnK(setter.Name))%>;<%end + end%> + <%if NeedUpdate(type) and not setter.IsStatic then%> + <%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>; + <%end%> + } catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + return 0; + } + <%end)%> + + <%ForEachCsList(events, function(event) if not event.IsStatic then %> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int _e_<%=event.Name%>(RealStatePtr L) + { + try { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + int gen_param_count = LuaAPI.lua_gettop(L); + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(event.Type, 3, "gen_delegate", true)%>; + if (gen_delegate == null) { + return LuaAPI.luaL_error(L, "#3 need <%=CsFullTypeName(event.Type)%>!"); + } + + if (gen_param_count == 3) + { + <%if event.CanAdd then%> + if (LuaAPI.xlua_is_eq_str(L, 2, "+")) { + gen_to_be_invoked.<%=UnK(event.Name)%> += gen_delegate; + return 0; + } + <%end%> + <%if event.CanRemove then%> + if (LuaAPI.xlua_is_eq_str(L, 2, "-")) { + gen_to_be_invoked.<%=UnK(event.Name)%> -= gen_delegate; + return 0; + } + <%end%> + } + } catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!"); + return 0; + } + <%end end)%> + + <%ForEachCsList(events, function(event) if event.IsStatic then %> + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int _e_<%=event.Name%>(RealStatePtr L) + { + try { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + int gen_param_count = LuaAPI.lua_gettop(L); + <%=GetCasterStatement(event.Type, 2, "gen_delegate", true)%>; + if (gen_delegate == null) { + return LuaAPI.luaL_error(L, "#2 need <%=CsFullTypeName(event.Type)%>!"); + } + + <%if event.CanAdd then%> + if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "+")) { + <%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> += gen_delegate; + return 0; + } + <%end%> + <%if event.CanRemove then%> + if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "-")) { + <%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> -= gen_delegate; + return 0; + } + <%end%> + } catch(System.Exception gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + gen_e); + } + return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!"); + } + <%end end)%> + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrap.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrap.tpl.txt.meta new file mode 100644 index 0000000..28dd949 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrap.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 202bffd7081f6ad4fb1606c7d649c3fb +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrapGCM.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrapGCM.tpl.txt new file mode 100644 index 0000000..ce52ee1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrapGCM.tpl.txt @@ -0,0 +1,517 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using XLua; +using System.Collections.Generic; +<%ForEachCsList(namespaces, function(namespace)%>using <%=namespace%>;<%end)%> +<% +require "TemplateCommon" + +local OpNameMap = { + op_Addition = "__AddMeta", + op_Subtraction = "__SubMeta", + op_Multiply = "__MulMeta", + op_Division = "__DivMeta", + op_Equality = "__EqMeta", + op_UnaryNegation = "__UnmMeta", + op_LessThan = "__LTMeta", + op_LessThanOrEqual = "__LEMeta", + op_Modulus = "__ModMeta", + op_BitwiseAnd = "__BandMeta", + op_BitwiseOr = "__BorMeta", + op_ExclusiveOr = "__BxorMeta", + op_OnesComplement = "__BnotMeta", + op_LeftShift = "__ShlMeta", + op_RightShift = "__ShrMeta", +} + +local OpCallNameMap = { + op_Addition = "+", + op_Subtraction = "-", + op_Multiply = "*", + op_Division = "/", + op_Equality = "==", + op_UnaryNegation = "-", + op_LessThan = "<", + op_LessThanOrEqual = "<=", + op_Modulus = "%", + op_BitwiseAnd = "&", + op_BitwiseOr = "|", + op_ExclusiveOr = "^", + op_OnesComplement = "~", + op_LeftShift = "<<", + op_RightShift = ">>", +} + +local obj_method_count = 0 +local obj_getter_count = 0 +local obj_setter_count = 0 +local meta_func_count = operators.Count +local cls_field_count = 1 +local cls_getter_count = 0 +local cls_setter_count = 0 + +ForEachCsList(methods, function(method) + if method.IsStatic then + cls_field_count = cls_field_count + 1 + else + obj_method_count = obj_method_count + 1 + end +end) + +ForEachCsList(events, function(event) + if event.IsStatic then + cls_field_count = cls_field_count + 1 + else + obj_method_count = obj_method_count + 1 + end +end) + +ForEachCsList(getters, function(getter) + if getter.IsStatic then + if getter.ReadOnly then + cls_field_count = cls_field_count + 1 + else + cls_getter_count = cls_getter_count + 1 + end + else + obj_getter_count = obj_getter_count + 1 + end +end) + +ForEachCsList(setters, function(setter) + if setter.IsStatic then + cls_setter_count = cls_setter_count + 1 + else + obj_setter_count = obj_setter_count + 1 + end +end) + +ForEachCsList(lazymembers, function(lazymember) + if lazymember.IsStatic == 'true' then + if 'CLS_IDX' == lazymember.Index then + cls_field_count = cls_field_count + 1 + elseif 'CLS_GETTER_IDX' == lazymember.Index then + cls_getter_count = cls_getter_count + 1 + elseif 'CLS_SETTER_IDX' == lazymember.Index then + cls_setter_count = cls_setter_count + 1 + end + else + if 'METHOD_IDX' == lazymember.Index then + obj_method_count = obj_method_count + 1 + elseif 'GETTER_IDX' == lazymember.Index then + obj_getter_count = obj_getter_count + 1 + elseif 'SETTER_IDX' == lazymember.Index then + obj_setter_count = obj_setter_count + 1 + end + end +end) + +local v_type_name = CSVariableName(type) +local generic_arg_list, type_constraints = GenericArgumentList(type) + +%> +namespace XLua +{ + public partial class ObjectTranslator + { + public void __Register<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L) <%=type_constraints%> + { + System.Type type = typeof(<%=CsFullTypeName(type)%>); + Utils.BeginObjectRegister(type, L, this, <%=meta_func_count%>, <%=obj_method_count%>, <%=obj_getter_count%>, <%=obj_setter_count%>); + <%ForEachCsList(operators, function(operator)%>Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "<%=(OpNameMap[operator.Name]):gsub('Meta', ''):lower()%>", <%=v_type_name%><%=OpNameMap[operator.Name]%><%=generic_arg_list%>); + <%end)%> + <%ForEachCsList(methods, function(method) if not method.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=method.Name%>", <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>); + <% end end)%> + <%ForEachCsList(events, function(event) if not event.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=event.Name%>", <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>); + <% end end)%> + <%ForEachCsList(getters, function(getter) if not getter.IsStatic then %>Utils.RegisterFunc(L, Utils.GETTER_IDX, "<%=getter.Name%>", <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>); + <%end end)%> + <%ForEachCsList(setters, function(setter) if not setter.IsStatic then %>Utils.RegisterFunc(L, Utils.SETTER_IDX, "<%=setter.Name%>", <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>); + <%end end)%> + <%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'false' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>); + <%end end)%> + Utils.EndObjectRegister(type, L, this, <% if type.IsArray or ((indexers.Count or 0) > 0) then %>__CSIndexer<%=v_type_name%><%=generic_arg_list%><%else%>null<%end%>, <%if type.IsArray or ((newindexers.Count or 0) > 0) then%>__NewIndexer<%=v_type_name%><%=generic_arg_list%><%else%>null<%end%>, + null, null, null); + + Utils.BeginClassRegister(type, L, __CreateInstance<%=v_type_name%><%=generic_arg_list%>, <%=cls_field_count%>, <%=cls_getter_count%>, <%=cls_setter_count%>); + <%ForEachCsList(methods, function(method) if method.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=method.Overloads[0].Name%>", <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>); + <% end end)%> + <%ForEachCsList(events, function(event) if event.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=event.Name%>", <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>); + <% end end)%> + <%ForEachCsList(getters, function(getter) if getter.IsStatic and getter.ReadOnly then %>Utils.RegisterObject(L, this, Utils.CLS_IDX, "<%=getter.Name%>", <%=CsFullTypeName(type).."."..getter.Name%>); + <%end end)%> + <%ForEachCsList(getters, function(getter) if getter.IsStatic and (not getter.ReadOnly) then %>Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "<%=getter.Name%>", <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>); + <%end end)%> + <%ForEachCsList(setters, function(setter) if setter.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "<%=setter.Name%>", <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>); + <%end end)%> + <%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'true' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>); + <%end end)%> + Utils.EndClassRegister(type, L, this); + } + + int __CreateInstance<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + <% + if constructors.Count == 0 and (not type.IsValueType) then + %>return LuaAPI.luaL_error(L, "<%=CsFullTypeName(type)%> does not have a constructor!");<% + else %> + ObjectTranslator translator = this; + <% + local hasZeroParamsCtor = false + ForEachCsList(constructors, function(constructor, ci) + local parameters = constructor:GetParameters() + if parameters.Length == 0 then + hasZeroParamsCtor = true + end + local def_count = constructor_def_vals[ci] + local param_count = parameters.Length + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local real_param_count = param_count - def_count + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + local in_pos = 0 + %>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num + 1 - def_count - (has_v_params and 1 or 0)%><%ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + local parameterType = parameter.ParameterType + if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1 + %> && <%=GetCheckStatement(parameterType, in_pos+1, has_v_params and pi == param_count - 1)%><% + end + end)%>) + { + <%ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + %><%=GetCasterStatement(parameter.ParameterType, pi+2, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%>; + <%end)%> + var gen_ret = new <%=CsFullTypeName(type)%>(<%ForEachCsList(parameters, function(parameter, pi) if pi >= real_param_count then return end; if pi ~=0 then %><%=', '%><% end ;if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end)%>); + <%=GetPushStatement(type, "gen_ret")%>; + <%local in_pos = 0 + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + end + if parameter.ParameterType.IsByRef then + %><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>; + <%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then + %><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+1, LocalName(parameter.Name))%>; + <%end%> + <% + end + end) + %> + return <%=out_num + 1%>; + } + <%end) + if (not hasZeroParamsCtor) and type.IsValueType then + %> + if (gen_param_count == 1) + { + <%=GetPushStatement(type, "default(" .. CsFullTypeName(type).. ")")%>; + return 1; + } + <%end%> + + return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%> constructor!"); + <% end %> + } + + <% if type.IsArray or ((indexers.Count or 0) > 0) then %> + int __CSIndexer<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + <%if type.IsArray then %> + ObjectTranslator translator = this; + if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2)) + { + int index = (int)LuaAPI.lua_tonumber(L, 2); + <%=GetSelfStatement(type)%>; + LuaAPI.lua_pushboolean(L, true); + <%=GetPushStatement(type:GetElementType(), "gen_to_be_invoked[index]")%>; + return 2; + } + <%elseif indexers.Count > 0 then + %>ObjectTranslator translator = this; + <% + ForEachCsList(indexers, function(indexer) + local paramter = indexer:GetParameters()[0] + %> + if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(paramter.ParameterType, 2)%>) + { + + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(paramter.ParameterType, 2, "index", true)%>; + LuaAPI.lua_pushboolean(L, true); + <%=GetPushStatement(indexer.ReturnType, "gen_to_be_invoked[index]")%>; + return 2; + } + <%end) + end%> + LuaAPI.lua_pushboolean(L, false); + return 1; + } + <% end %> + + <%if type.IsArray or ((newindexers.Count or 0) > 0) then%> + int __NewIndexer<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + <%if type.IsArray or newindexers.Count > 0 then %>ObjectTranslator translator = this;<%end%> + <%if type.IsArray then + local elementType = type:GetElementType() + %> + if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2) && <%=GetCheckStatement(elementType, 3)%>) + { + int index = (int)LuaAPI.lua_tonumber(L, 2); + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(elementType, 3, "gen_to_be_invoked[index]")%>; + LuaAPI.lua_pushboolean(L, true); + return 1; + } + <%elseif newindexers.Count > 0 then%> + <%ForEachCsList(newindexers, function(newindexer) + local keyType = newindexer:GetParameters()[0].ParameterType + local valueType = newindexer:GetParameters()[1].ParameterType + %> + if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(keyType, 2)%> && <%=GetCheckStatement(valueType, 3)%>) + { + + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(keyType, 2, "key", true)%>; + <%if IsStruct(valueType) then%><%=GetCasterStatement(valueType, 3, "gen_value", true)%>; + gen_to_be_invoked[key] = gen_value;<%else + %><%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;<%end%> + LuaAPI.lua_pushboolean(L, true); + return 1; + } + <%end) + end%> + LuaAPI.lua_pushboolean(L, false); + return 1; + } + <% end %> + + <%ForEachCsList(operators, function(operator) %> + int <%=v_type_name%><%=OpNameMap[operator.Name]%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + ObjectTranslator translator = this; + <% if operator.Name ~= "op_UnaryNegation" and operator.Name ~= "op_OnesComplement" then + ForEachCsList(operator.Overloads, function(overload) + local left_param = overload:GetParameters()[0] + local right_param = overload:GetParameters()[1] + %> + if (<%=GetCheckStatement(left_param.ParameterType, 1)%> && <%=GetCheckStatement(right_param.ParameterType, 2)%>) + { + <%=GetCasterStatement(left_param.ParameterType, 1, "leftside", true)%>; + <%=GetCasterStatement(right_param.ParameterType, 2, "rightside", true)%>; + + <%=GetPushStatement(overload.ReturnType, "leftside " .. OpCallNameMap[operator.Name] .. " rightside")%>; + + return 1; + } + <%end)%> + return LuaAPI.luaL_error(L, "invalid arguments to right hand of <%=OpCallNameMap[operator.Name]%> operator, need <%=CsFullTypeName(type)%>!"); + <%else%> + <%=GetCasterStatement(type, 1, "rightside", true)%>; + <%=GetPushStatement(operator.Overloads[0].ReturnType, OpCallNameMap[operator.Name] .. " rightside")%>; + return 1; + <%end%> + } + <%end)%> + + <%ForEachCsList(methods, function(method)%> + int <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + <% + local need_obj = not method.IsStatic + if MethodCallNeedTranslator(method) then + %> + ObjectTranslator translator = this; + <%end%> + <%if need_obj then%> + <%=GetSelfStatement(type)%>; + <%end%> + <%ForEachCsList(method.Overloads, function(overload, oi) + local parameters = MethodParameters(overload) + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local param_offset = method.IsStatic and 0 or 1 + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local in_pos = 0 + local has_return = (overload.ReturnType.FullName ~= "System.Void") + local def_count = method.DefaultValues[oi] + local param_count = parameters.Length + local real_param_count = param_count - def_count + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + if method.Overloads.Count > 1 then + %>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num+param_offset-def_count - (has_v_params and 1 or 0)%><% + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + local parameterType = parameter.ParameterType + if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1; + %>&& <%=GetCheckStatement(parameterType , in_pos+param_offset, has_v_params and pi == param_count - 1)%><% + end + end)%>) <%end%> + { + <%if overload.Name == "get_Item" and overload.IsSpecialName then + local keyType = overload:GetParameters()[0].ParameterType%> + <%=GetCasterStatement(keyType, 2, "key", true)%>; + <%=GetPushStatement(overload.ReturnType, "gen_to_be_invoked[key]")%>; + <%elseif overload.Name == "set_Item" and overload.IsSpecialName then + local keyType = overload:GetParameters()[0].ParameterType + local valueType = overload:GetParameters()[1].ParameterType%> + <%=GetCasterStatement(keyType, 2, "key", true)%>; + <%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>; + <% else + in_pos = 0; + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + %><%if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + %><%=GetCasterStatement(parameter.ParameterType, in_pos+param_offset, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%><% + else%><%=CsFullTypeName(parameter.ParameterType)%> <%=LocalName(parameter.Name)%><%end%>; + <%end)%> + <% + if has_return then + %>var gen_ret = <% + end + %><%if method.IsStatic then + %><%=CsFullTypeName(type).."."..UnK(overload.Name)%><% + else + %>gen_to_be_invoked.<%=UnK(overload.Name)%><% + end%>( <%ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + if pi ~= 0 then %>, <% end; if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end) %> ); + <% + if has_return then + %><%=GetPushStatement(overload.ReturnType, "gen_ret")%>; + <% + end + local in_pos = 0 + ForEachCsList(parameters, function(parameter, pi) + if pi >= real_param_count then return end + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + end + if parameter.ParameterType.IsByRef then + %><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>; + <%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then + %><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, LocalName(parameter.Name))%>; + <%end%> + <% + end + end) + end + %> + <%if NeedUpdate(type) and not method.IsStatic then%> + <%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>; + <%end%> + + return <%=out_num+(has_return and 1 or 0)%>; + } + <% end)%> + <%if method.Overloads.Count > 1 then%> + return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=method.Overloads[0].Name%>!"); + <%end%> + } + <% end)%> + + + <%ForEachCsList(getters, function(getter) + if getter.IsStatic and getter.ReadOnly then return end --readonly static + %> + int <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + <%if AccessorNeedTranslator(getter) then %>ObjectTranslator translator = this;<%end%> + <%if not getter.IsStatic then%> + <%=GetSelfStatement(type)%>; + <%=GetPushStatement(getter.Type, "gen_to_be_invoked."..UnK(getter.Name))%>;<% else %> <%=GetPushStatement(getter.Type, CsFullTypeName(type).."."..UnK(getter.Name))%>;<% end%> + return 1; + } + <%end)%> + + <%ForEachCsList(setters, function(setter) + local is_struct = IsStruct(setter.Type) + %> + int <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + <%if AccessorNeedTranslator(setter) then %>ObjectTranslator translator = this;<%end%> + <%if not setter.IsStatic then %> + <%=GetSelfStatement(type)%>; + <%if is_struct then %><%=GetCasterStatement(setter.Type, 2, "gen_value", true)%>; + gen_to_be_invoked.<%=UnK(setter.Name)%> = gen_value;<% else + %><%=GetCasterStatement(setter.Type, 2, "gen_to_be_invoked." .. UnK(setter.Name))%>;<%end + else + if is_struct then %><%=GetCasterStatement(setter.Type, 1, "gen_value", true)%>; + <%=CsFullTypeName(type)%>.<%=UnK(setter.Name)%> = gen_value;<%else + %><%=GetCasterStatement(setter.Type, 1, CsFullTypeName(type) .."." .. UnK(setter.Name))%>;<%end + end%> + <%if NeedUpdate(type) and not setter.IsStatic then%> + <%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>; + <%end%> + return 0; + } + <%end)%> + + <%ForEachCsList(events, function(event) if not event.IsStatic then %> + int <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + ObjectTranslator translator = this; + <%=GetSelfStatement(type)%>; + <%=GetCasterStatement(event.Type, 3, "gen_delegate", true)%>; + if (gen_delegate == null) { + return LuaAPI.luaL_error(L, "#3 need <%=CsFullTypeName(event.Type)%>!"); + } + + if (gen_param_count == 3) + { + <%if event.CanAdd then%> + if (LuaAPI.xlua_is_eq_str(L, 2, "+")) { + gen_to_be_invoked.<%=UnK(event.Name)%> += gen_delegate; + return 0; + } + <%end%> + <%if event.CanRemove then%> + if (LuaAPI.xlua_is_eq_str(L, 2, "-")) { + gen_to_be_invoked.<%=UnK(event.Name)%> -= gen_delegate; + return 0; + } + <%end%> + } + LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!"); + return 0; + } + <%end end)%> + + <%ForEachCsList(events, function(event) if event.IsStatic then %> + int <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%> + { + ObjectTranslator translator = this; + <%=GetCasterStatement(event.Type, 2, "gen_delegate", true)%>; + if (gen_delegate == null) { + return LuaAPI.luaL_error(L, "#2 need <%=CsFullTypeName(event.Type)%>!"); + } + + <%if event.CanAdd then%> + if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "+")) { + <%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> += gen_delegate; + return 0; + } + <%end%> + <%if event.CanRemove then%> + if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "-")) { + <%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> -= gen_delegate; + return 0; + } + <%end%> + return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!"); + } + <%end end)%> + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrapGCM.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrapGCM.tpl.txt.meta new file mode 100644 index 0000000..17491e7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaClassWrapGCM.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2004350d5563b664382b5030f7efa995 +timeCreated: 1501232428 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateBridge.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateBridge.tpl.txt new file mode 100644 index 0000000..bb65a5e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateBridge.tpl.txt @@ -0,0 +1,104 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +<% +require "TemplateCommon" +%> + +namespace XLua +{ + public partial class DelegateBridge : DelegateBridgeBase + { + <% + ForEachCsList(delegates_groups, function(delegates_group, group_idx) + local delegate = delegates_group.Key + local parameters = delegate:GetParameters() + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local in_pos = 0 + local has_return = (delegate.ReturnType.FullName ~= "System.Void") + local return_type_name = has_return and CsFullTypeName(delegate.ReturnType) or "void" + local out_idx = has_return and 2 or 1 + if has_return then out_num = out_num + 1 end + %> + public <%=return_type_name%> __Gen_Delegate_Imp<%=group_idx%>(<%ForEachCsList(parameters, function(parameter, pi) + if pi ~= 0 then + %>, <% + end + if parameter.IsOut and parameter.ParameterType.IsByRef then + %>out <% + elseif parameter.ParameterType.IsByRef then + %>ref <% + end + %><%=CsFullTypeName(parameter.ParameterType)%> p<%=pi%><% + end) %>) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.rawL; + int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference); + <%if CallNeedTranslator(delegate, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%> + <% + local param_count = parameters.Length + local has_v_params = param_count > 0 and parameters[param_count - 1].IsParamArray + ForEachCsList(parameters, function(parameter, pi) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + %><%=GetPushStatement(parameter.ParameterType, 'p' .. pi, has_v_params and pi == param_count - 1)%>; + <% + end + end) %> + PCall(L, <%=has_v_params and ((in_num - 1) .. " + (p".. (param_count - 1) .. " == null ? 0 : p" .. (param_count - 1) .. ".Length)" ) or in_num%>, <%=out_num%>, errFunc); + + <%ForEachCsList(parameters, function(parameter, pi) + if parameter.IsOut or parameter.ParameterType.IsByRef then + %><%=GetCasterStatement(parameter.ParameterType, "errFunc" .. (" + "..out_idx), 'p' .. pi)%>; + <% + out_idx = out_idx + 1 + end + end) %> + <%if has_return then %><%=GetCasterStatement(delegate.ReturnType, "errFunc + 1", "__gen_ret", true)%>;<% end%> + LuaAPI.lua_settop(L, errFunc - 1); + <%if has_return then %>return __gen_ret;<% end%> +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + <%end)%> + + static DelegateBridge() + { + Gen_Flag = true; + } + + public override Delegate GetDelegateByType(Type type) + { + <% + ForEachCsList(delegates_groups, function(delegates_group, group_idx) + ForEachCsList(delegates_group.Value, function(delegate) + if delegate.DeclaringType then + local delegate_type_name = CsFullTypeName(delegate.DeclaringType) + %> + if (type == typeof(<%=delegate_type_name%>)) + { + return new <%=delegate_type_name%>(__Gen_Delegate_Imp<%=group_idx%>); + } + <% + end + end) + end) + %> + return null; + } + } + +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateBridge.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateBridge.tpl.txt.meta new file mode 100644 index 0000000..890a28b --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateBridge.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d782c5181c6b102438ee570ca5a311f0 +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateWrap.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateWrap.tpl.txt new file mode 100644 index 0000000..7ba1de9 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateWrap.tpl.txt @@ -0,0 +1,128 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using XLua; +using System.Collections.Generic; +<% +require "TemplateCommon" + +local parameters = delegate:GetParameters() +local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) +local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) +local in_pos = 0 +local has_return = (delegate.ReturnType.Name ~= "Void") +%> + +namespace XLua.CSObjectWrap +{ + using Utils = XLua.Utils; + public class <%=CSVariableName(type)%>Wrap + { + public static void __Register(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, 0, 0, 0, 0); + Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, null, null, null, null, null); + + Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, 1, 0, 0); + Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, translator); + } + + static Dictionary __MetaFucntions_Dic = new Dictionary(){ + {"__call", __CallMeta}, + {"__add", __AddMeta}, + {"__sub", __SubMeta}, + }; + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int __CallMeta(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + try { + if(LuaAPI.lua_gettop(L) == <%=in_num+1%> && <%=GetCheckStatement(type, 1)%><% + ForEachCsList(parameters, function(parameter) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1; + %>&& <%=GetCheckStatement(parameter.ParameterType, in_pos+1)%><% + end + end)%>) + { + <% + in_pos = 0; + ForEachCsList(parameters, function(parameter) + %><% + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + %><%=GetCasterStatement(parameter.ParameterType, in_pos+1, parameter.Name, true)%><% + else%><%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%end%>; + <%end)%> + <%=GetSelfStatement(type)%>; + + <% + if has_return then + %> var __cl_gen_ret = <% + end + %> __cl_gen_to_be_invoked( <%ForEachCsList(parameters, function(parameter, pi) if pi ~= 0 then %>, <% end; if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %><%=parameter.Name%><% end) %> ); + <% + if has_return then + %> <%=GetPushStatement(delegate.ReturnType, "__cl_gen_ret")%>; + <% + end + local in_pos = 0 + ForEachCsList(parameters, function(parameter) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + in_pos = in_pos + 1 + end + if parameter.IsOut or parameter.ParameterType.IsByRef then + %><%=GetPushStatement(parameter.ParameterType:GetElementType(), parameter.Name)%>; + <%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then + %><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, parameter.Name)%>; + <%end%> + <% + end + end) + %> + + return <%=out_num+(has_return and 1 or 0)%>; + } + } catch(System.Exception __gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); + } + return LuaAPI.luaL_error(L, "invalid arguments to Delegate <%=CsFullTypeName(type)%>!"); + } + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int __AddMeta(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + try { + <%=GetCasterStatement(type, 1, "leftside", true)%>; + <%=GetCasterStatement(type, 2, "rightside", true)%>; + <%=GetPushStatement(type, "leftside + rightside")%>; + return 1; + } catch(System.Exception __gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); + } + } + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int __SubMeta(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + try { + <%=GetCasterStatement(type, 1, "leftside", true)%>; + <%=GetCasterStatement(type, 2, "rightside", true)%>; + <%=GetPushStatement(type, "leftside - rightside")%>; + return 1; + } catch(System.Exception __gen_e) { + return LuaAPI.luaL_error(L, "c# exception:" + __gen_e); + } + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateWrap.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateWrap.tpl.txt.meta new file mode 100644 index 0000000..65da948 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaDelegateWrap.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 74eb9cd77d56afb4a9834495e3dad87f +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt new file mode 100644 index 0000000..af37659 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt @@ -0,0 +1,102 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using XLua; +using System.Collections.Generic; +<% +require "TemplateCommon" +local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor +%> + +namespace XLua.CSObjectWrap +{ + using Utils = XLua.Utils; + <%ForEachCsList(types, function(type) + local fields = type2fields and type2fields[type] or type:GetFields(enum_or_op(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.Static)) + local fields_to_gen = {} + ForEachCsList(fields, function(field) + if field.Name ~= "value__" and not IsObsolute(field) then + table.insert(fields_to_gen, field) + end + end) + %> + public class <%=CSVariableName(type)%>Wrap + { + public static void __Register(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, 0, 0, 0, 0); + Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, null, null, null, null, null); + + Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, <%=fields.Length + 1%>, 0, 0); +<%if #fields_to_gen <= 20 then%> + <% ForEachCsList(fields, function(field) + if field.Name == "value__" or IsObsolute(field) then return end + %> + Utils.RegisterObject(L, translator, Utils.CLS_IDX, "<%=field.Name%>", <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>); + <%end)%> +<%else%> + Utils.RegisterEnumType(L, typeof(<%=CsFullTypeName(type)%>)); +<%end%> + Utils.RegisterFunc(L, Utils.CLS_IDX, "__CastFrom", __CastFrom); + + Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, translator); + } + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + static int __CastFrom(RealStatePtr L) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + LuaTypes lua_type = LuaAPI.lua_type(L, 1); + if (lua_type == LuaTypes.LUA_TNUMBER) + { + translator.Push<%=CSVariableName(type)%>(L, (<%=CsFullTypeName(type)%>)LuaAPI.xlua_tointeger(L, 1)); + } + <%if #fields_to_gen > 0 then%> + else if(lua_type == LuaTypes.LUA_TSTRING) + { +<%if #fields_to_gen <= 20 then%> + <% + local is_first = true + ForEachCsList(fields, function(field, i) + if field.Name == "value__" or IsObsolute(field) then return end + %><%=(is_first and "" or "else ")%>if (LuaAPI.xlua_is_eq_str(L, 1, "<%=field.Name%>")) + { + translator.Push<%=CSVariableName(type)%>(L, <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>); + } + <% + is_first = false + end) + %>else + { + return LuaAPI.luaL_error(L, "invalid string for <%=CsFullTypeName(type)%>!"); + } +<%else%> + try + { + translator.TranslateToEnumToTop(L, typeof(<%=CsFullTypeName(type)%>), 1); + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "cast to " + typeof(<%=CsFullTypeName(type)%>) + " exception:" + e); + } +<%end%> + } + <%end%> + else + { + return LuaAPI.luaL_error(L, "invalid lua type for <%=CsFullTypeName(type)%>! Expect number or string, got + " + lua_type); + } + + return 1; + } + } + <%end)%> +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt.meta new file mode 100644 index 0000000..c4075e1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 99777b0efc9d4ec4c80979cfb49e6a34 +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrapGCM.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrapGCM.tpl.txt new file mode 100644 index 0000000..9fe8566 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrapGCM.tpl.txt @@ -0,0 +1,99 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using XLua; +using System.Collections.Generic; +<% +require "TemplateCommon" +local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor +%> + +namespace XLua +{ + public partial class ObjectTranslator + { + <%ForEachCsList(types, function(type) + local fields = type2fields and type2fields[type] or type:GetFields(enum_or_op(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.Static)) + local fields_to_gen = {} + ForEachCsList(fields, function(field) + if field.Name ~= "value__" and not IsObsolute(field) then + table.insert(fields_to_gen, field) + end + end) + local v_type_name = CSVariableName(type) + %> + public void __Register<%=v_type_name%>(RealStatePtr L) + { + Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, this, 0, 0, 0, 0); + Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, this, null, null, null, null, null); + + Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, <%=fields.Length + 1%>, 0, 0); +<%if #fields_to_gen <= 20 then%> + <% ForEachCsList(fields, function(field) + if field.Name == "value__" or IsObsolute(field) then return end + %> + Utils.RegisterObject(L, this, Utils.CLS_IDX, "<%=field.Name%>", <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>); + <%end)%> +<%else%> + Utils.RegisterEnumType(L, typeof(<%=CsFullTypeName(type)%>)); +<%end%> + Utils.RegisterFunc(L, Utils.CLS_IDX, "__CastFrom", __CastFrom<%=v_type_name%>); + + Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, this); + } + + int __CastFrom<%=v_type_name%>(RealStatePtr L, int __gen_top) + { + LuaTypes lua_type = LuaAPI.lua_type(L, 1); + if (lua_type == LuaTypes.LUA_TNUMBER) + { + Push<%=v_type_name%>(L, (<%=CsFullTypeName(type)%>)LuaAPI.xlua_tointeger(L, 1)); + } + <%if #fields_to_gen > 0 then%> + else if(lua_type == LuaTypes.LUA_TSTRING) + { +<%if #fields_to_gen <= 20 then%> + <% + local is_first = true + ForEachCsList(fields, function(field, i) + if field.Name == "value__" or IsObsolute(field) then return end + %><%=(is_first and "" or "else ")%>if (LuaAPI.xlua_is_eq_str(L, 1, "<%=field.Name%>")) + { + Push<%=v_type_name%>(L, <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>); + } + <% + is_first = false + end) + %>else + { + return LuaAPI.luaL_error(L, "invalid string for <%=CsFullTypeName(type)%>!"); + } +<%else%> + try + { + TranslateToEnumToTop(L, typeof(<%=CsFullTypeName(type)%>), 1); + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "cast to " + typeof(<%=CsFullTypeName(type)%>) + " exception:" + e); + } +<%end%> + } + <%end%> + else + { + return LuaAPI.luaL_error(L, "invalid lua type for <%=CsFullTypeName(type)%>! Expect number or string, got + " + lua_type); + } + + return 1; + } + <%end)%> + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrapGCM.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrapGCM.tpl.txt.meta new file mode 100644 index 0000000..ac6c45d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaEnumWrapGCM.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 481063a97af538c4689753c4d192ecdd +timeCreated: 1501232428 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaInterfaceBridge.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaInterfaceBridge.tpl.txt new file mode 100644 index 0000000..042e0d8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaInterfaceBridge.tpl.txt @@ -0,0 +1,385 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using XLua; +using System; +<% +require "TemplateCommon" + +%> + +namespace XLua.CSObjectWrap +{ + public class <%=CSVariableName(type)%>Bridge : LuaBase, <%=CsFullTypeName(type)%> + { + public static LuaBase __Create(int reference, LuaEnv luaenv) + { + return new <%=CSVariableName(type)%>Bridge(reference, luaenv); + } + + public <%=CSVariableName(type)%>Bridge(int reference, LuaEnv luaenv) : base(reference, luaenv) + { + } + + <% + ForEachCsList(methods, function(method) + local parameters = method:GetParameters() + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local in_pos = 0 + local has_return = (method.ReturnType.FullName ~= "System.Void") + local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void" + local out_idx = has_return and 2 or 1 + if has_return then out_num = out_num + 1 end + %> + <%=return_type_name%> <%=CsFullTypeName(method.DeclaringType)%>.<%=method.Name%>(<%ForEachCsList(parameters, function(parameter, pi) + if pi ~= 0 then + %>, <% + end + if parameter.IsOut and parameter.ParameterType.IsByRef then + %>out <% + elseif parameter.ParameterType.IsByRef then + %>ref <% + end + %><%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><% + end) %>) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + <%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%> + + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>"); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + luaEnv.ThrowExceptionFromError(err_func - 1); + } + if(!LuaAPI.lua_isfunction(L, -1)) + { + LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>"); + luaEnv.ThrowExceptionFromError(err_func - 1); + } + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.lua_remove(L, -3); + <% + local param_count = parameters.Length + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + + ForEachCsList(parameters, function(parameter, pi) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + %><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>; + <% + end + end) %> + int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + (".. parameters[param_count - 1].Name .. " == null ? 0 : " .. parameters[param_count - 1].Name .. ".Length)" ) or (in_num + 1)%>, <%=out_num%>, err_func); + if (__gen_error != 0) + luaEnv.ThrowExceptionFromError(err_func - 1); + + <%ForEachCsList(parameters, function(parameter) + if parameter.IsOut or parameter.ParameterType.IsByRef then + %><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>; + <% + out_idx = out_idx + 1 + end + end) %> + <%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%> + LuaAPI.lua_settop(L, err_func - 1); + <%if has_return then %>return __gen_ret;<% end%> +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + <%end)%> + + <% + ForEachCsList(propertys, function(property) + %> + <%=CsFullTypeName(property.PropertyType)%> <%=CsFullTypeName(property.DeclaringType)%>.<%=property.Name%> + { + <%if property.CanRead then%> + get + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + <%if not JustLuaType(property.PropertyType) then %>ObjectTranslator translator = luaEnv.translator;<%end%> + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "<%=property.Name%>"); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + luaEnv.ThrowExceptionFromError(oldTop); + } + <%=GetCasterStatement(property.PropertyType, "-1", "__gen_ret", true)%>; + LuaAPI.lua_pop(L, 2); + return __gen_ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + <%end%> + <%if property.CanWrite then%> + set + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + <%if not JustLuaType(property.PropertyType) then %>ObjectTranslator translator = luaEnv.translator;<%end%> + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "<%=property.Name%>"); + <%=GetPushStatement(property.PropertyType, "value")%>; + if (0 != LuaAPI.xlua_psettable(L, -3)) + { + luaEnv.ThrowExceptionFromError(oldTop); + } + LuaAPI.lua_pop(L, 1); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + <%end%> + } + <%end)%> + + <%ForEachCsList(events, function(event) %> + event <%=CsFullTypeName(event.EventHandlerType)%> <%=CsFullTypeName(event.DeclaringType)%>.<%=event.Name%> + {<%local parameters = event:GetAddMethod():GetParameters()%> + add + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + <%if CallNeedTranslator(event:GetAddMethod(), "") then %>ObjectTranslator translator = luaEnv.translator;<%end%> + + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "add_<%=event.Name%>"); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + luaEnv.ThrowExceptionFromError(err_func - 1); + } + if(!LuaAPI.lua_isfunction(L, -1)) + { + LuaAPI.xlua_pushasciistring(L, "no such function add_<%=event.Name%>"); + luaEnv.ThrowExceptionFromError(err_func - 1); + } + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.lua_remove(L, -3); + <% + local param_count = parameters.Length + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + + ForEachCsList(parameters, function(parameter, pi) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + %><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>; + <% + end + end) %> + int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func); + if (__gen_error != 0) + luaEnv.ThrowExceptionFromError(err_func - 1); + + LuaAPI.lua_settop(L, err_func - 1); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + remove + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + <%if CallNeedTranslator(event:GetRemoveMethod(), "") then %>ObjectTranslator translator = luaEnv.translator;<%end%> + + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "remove_<%=event.Name%>"); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + luaEnv.ThrowExceptionFromError(err_func - 1); + } + if(!LuaAPI.lua_isfunction(L, -1)) + { + LuaAPI.xlua_pushasciistring(L, "no such function remove_<%=event.Name%>"); + luaEnv.ThrowExceptionFromError(err_func - 1); + } + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.lua_remove(L, -3); + <% + local param_count = parameters.Length + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + + ForEachCsList(parameters, function(parameter, pi) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + %><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>; + <% + end + end) %> + int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func); + if (__gen_error != 0) + luaEnv.ThrowExceptionFromError(err_func - 1); + + LuaAPI.lua_settop(L, err_func - 1); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + } + <%end)%> + + <%ForEachCsList(indexers, function(indexer) + local ptype = (indexer:GetGetMethod() or indexer:GetSetMethod()):GetParameters()[0].ParameterType + local pname = (indexer:GetGetMethod() or indexer:GetSetMethod()):GetParameters()[0].Name + %> + <%=CsFullTypeName(indexer.PropertyType)%> <%=CsFullTypeName(indexer.DeclaringType)%>.this[<%=CsFullTypeName(ptype)%> <%=pname%>] + {<%if indexer:GetGetMethod() then + local method = indexer:GetGetMethod() + local parameters = method:GetParameters() + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local in_pos = 0 + local has_return = (method.ReturnType.FullName ~= "System.Void") + local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void" + local out_idx = has_return and 2 or 1 + if has_return then out_num = out_num + 1 end + %> + get + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + <%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%> + + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>"); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + luaEnv.ThrowExceptionFromError(err_func - 1); + } + if(!LuaAPI.lua_isfunction(L, -1)) + { + LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>"); + luaEnv.ThrowExceptionFromError(err_func - 1); + } + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.lua_remove(L, -3); + <% + local param_count = parameters.Length + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + + ForEachCsList(parameters, function(parameter, pi) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + %><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>; + <% + end + end) %> + int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + " .. parameters[param_count - 1].Name .. ".Length" ) or (in_num + 1)%>, <%=out_num%>, err_func); + if (__gen_error != 0) + luaEnv.ThrowExceptionFromError(err_func - 1); + + <%ForEachCsList(parameters, function(parameter) + if parameter.IsOut or parameter.ParameterType.IsByRef then + %><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>; + <% + out_idx = out_idx + 1 + end + end) %> + <%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%> + LuaAPI.lua_settop(L, err_func - 1); + <%if has_return then %>return __gen_ret;<% end%> +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + <%end%> + <%if indexer:GetSetMethod() then + local method = indexer:GetSetMethod() + local parameters = method:GetParameters() + local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end) + local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end) + local in_pos = 0 + local has_return = (method.ReturnType.FullName ~= "System.Void") + local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void" + local out_idx = has_return and 2 or 1 + if has_return then out_num = out_num + 1 end + %> + set + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + RealStatePtr L = luaEnv.L; + int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + <%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%> + + LuaAPI.lua_getref(L, luaReference); + LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>"); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + luaEnv.ThrowExceptionFromError(err_func - 1); + } + if(!LuaAPI.lua_isfunction(L, -1)) + { + LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>"); + luaEnv.ThrowExceptionFromError(err_func - 1); + } + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.lua_remove(L, -3); + <% + local param_count = parameters.Length + local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1]) + + ForEachCsList(parameters, function(parameter, pi) + if not (parameter.IsOut and parameter.ParameterType.IsByRef) then + %><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>; + <% + end + end) %> + int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + " .. parameters[param_count - 1].Name .. ".Length" ) or (in_num + 1)%>, <%=out_num%>, err_func); + if (__gen_error != 0) + luaEnv.ThrowExceptionFromError(err_func - 1); + + <%ForEachCsList(parameters, function(parameter) + if parameter.IsOut or parameter.ParameterType.IsByRef then + %><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>; + <% + out_idx = out_idx + 1 + end + end) %> + <%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%> + LuaAPI.lua_settop(L, err_func - 1); + <%if has_return then %>return __gen_ret;<% end%> +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + <%end%> + } + <%end)%> + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaInterfaceBridge.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaInterfaceBridge.tpl.txt.meta new file mode 100644 index 0000000..9c594db --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaInterfaceBridge.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4c0ac248c572140469bb330968d12143 +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegister.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegister.tpl.txt new file mode 100644 index 0000000..68976cd --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegister.tpl.txt @@ -0,0 +1,140 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Collections.Generic; +using System.Reflection; +<% +require "TemplateCommon" +%> + +namespace XLua.CSObjectWrap +{ + public class XLua_Gen_Initer_Register__ + { + <% + local split_method_perfix = 'wrapInit' + local split_method_count = 0 + local wrap_in_split_method = 0 + local max_wrap_in_split_method = 50 + %> + <%ForEachCsList(wraps, function(wrap)%> + <%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator) + { + <%end%> + translator.DelayWrapLoader(typeof(<%=CsFullTypeName(wrap)%>), <%=CSVariableName(wrap)%>Wrap.__Register); + <%if wrap_in_split_method == max_wrap_in_split_method then + wrap_in_split_method = 0 + split_method_count = split_method_count + 1 + %> + } + <%else + wrap_in_split_method = wrap_in_split_method + 1 + end + end)%> + <% if generic_wraps then + for generic_def, instances in pairs(generic_wraps) do + for _, args in ipairs(instances) do + local generic_arg_list = "<" + ForEachCsList(args, function(generic_arg, gai) + if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end + generic_arg_list = generic_arg_list .. CsFullTypeName(generic_arg) + end) + generic_arg_list = generic_arg_list .. ">" + + %> + <%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator) + { + <%end%> + translator.DelayWrapLoader(typeof(<%=generic_def.Name:gsub("`%d+", "") .. generic_arg_list%>), <%=CSVariableName(generic_def)%>Wrap<%=generic_arg_list%>.__Register); + <%if wrap_in_split_method == max_wrap_in_split_method then + wrap_in_split_method = 0 + split_method_count = split_method_count + 1 + %> + } + <%else + wrap_in_split_method = wrap_in_split_method + 1 + end + end + end + end%> + + <%if wrap_in_split_method ~= 0 then + split_method_count = split_method_count + 1 + %>}<%end%> + + static void Init(LuaEnv luaenv, ObjectTranslator translator) + { + <%for i = 1, split_method_count do%> + <%=split_method_perfix%><%=(i - 1)%>(luaenv, translator); + <%end%> + <%ForEachCsList(itf_bridges, function(itf_bridge)%> + translator.AddInterfaceBridgeCreator(typeof(<%=CsFullTypeName(itf_bridge)%>), <%=CSVariableName(itf_bridge)%>Bridge.__Create); + <%end)%> + } + + static XLua_Gen_Initer_Register__() + { + XLua.LuaEnv.AddIniter(Init); + } + + + } + +} +namespace XLua +{ + public partial class ObjectTranslator + { + static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__(); + static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}} + } + + internal partial class InternalGlobals + { + <% + local type_to_methods = {} + local seq_tbl = {} + ForEachCsList(extension_methods, function(extension_method, idx) + local parameters = extension_method:GetParameters() + local type = parameters[0].ParameterType + if not type_to_methods[type] then + type_to_methods[type] = {type = type} + table.insert(seq_tbl, type_to_methods[type]) + end + table.insert(type_to_methods[type], {method = extension_method, index = idx}) + %> + delegate <%=CsFullTypeName(extension_method.ReturnType)%> __GEN_DELEGATE<%=idx%>(<%ForEachCsList(parameters, function(parameter, pi) + %><%if pi ~= 0 then%>, <%end%><%if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %> <%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><% + end)%>); + <%end)%> + static InternalGlobals() + { + extensionMethodMap = new Dictionary>() + { + <%for _, methods_info in ipairs(seq_tbl) do%> + {typeof(<%=CsFullTypeName(methods_info.type)%>), new List(){ + <% for _, method_info in ipairs(methods_info) do%> + new __GEN_DELEGATE<%=method_info.index%>(<%=CsFullTypeName(method_info.method.DeclaringType)%>.<%=method_info.method.Name%>) +#if UNITY_WSA && !UNITY_EDITOR + .GetMethodInfo(), +#else + .Method, +#endif + <% end%> + }}, + <%end%> + }; + + genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet; + genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegister.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegister.tpl.txt.meta new file mode 100644 index 0000000..a39844f --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegister.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a920cd220e906ab4da3d846d831e1a06 +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegisterGCM.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegisterGCM.tpl.txt new file mode 100644 index 0000000..bb5b6c0 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegisterGCM.tpl.txt @@ -0,0 +1,140 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Collections.Generic; +using System.Reflection; +<% +require "TemplateCommon" +%> + +namespace XLua.CSObjectWrap +{ + public class XLua_Gen_Initer_Register__ + { + <% + local split_method_perfix = 'wrapInit' + local split_method_count = 0 + local wrap_in_split_method = 0 + local max_wrap_in_split_method = 50 + %> + <%ForEachCsList(wraps, function(wrap)%> + <%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator) + { + <%end%> + translator.DelayWrapLoader(typeof(<%=CsFullTypeName(wrap)%>), translator.__Register<%=CSVariableName(wrap)%>); + <%if wrap_in_split_method == max_wrap_in_split_method then + wrap_in_split_method = 0 + split_method_count = split_method_count + 1 + %> + } + <%else + wrap_in_split_method = wrap_in_split_method + 1 + end + end)%> + <% if generic_wraps then + for generic_def, instances in pairs(generic_wraps) do + for _, args in ipairs(instances) do + local generic_arg_list = "<" + ForEachCsList(args, function(generic_arg, gai) + if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end + generic_arg_list = generic_arg_list .. CsFullTypeName(generic_arg) + end) + generic_arg_list = generic_arg_list .. ">" + + %> + <%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator) + { + <%end%> + translator.DelayWrapLoader(typeof(<%=generic_def.Name:gsub("`%d+", "") .. generic_arg_list%>), translator.__Register<%=CSVariableName(generic_def)%><%=generic_arg_list%>); + <%if wrap_in_split_method == max_wrap_in_split_method then + wrap_in_split_method = 0 + split_method_count = split_method_count + 1 + %> + } + <%else + wrap_in_split_method = wrap_in_split_method + 1 + end + end + end + end%> + + <%if wrap_in_split_method ~= 0 then + split_method_count = split_method_count + 1 + %>}<%end%> + + static void Init(LuaEnv luaenv, ObjectTranslator translator) + { + <%for i = 1, split_method_count do%> + <%=split_method_perfix%><%=(i - 1)%>(luaenv, translator); + <%end%> + <%ForEachCsList(itf_bridges, function(itf_bridge)%> + translator.AddInterfaceBridgeCreator(typeof(<%=CsFullTypeName(itf_bridge)%>), <%=CSVariableName(itf_bridge)%>Bridge.__Create); + <%end)%> + } + + static XLua_Gen_Initer_Register__() + { + XLua.LuaEnv.AddIniter(Init); + } + + + } + +} +namespace XLua +{ + public partial class ObjectTranslator + { + static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__(); + static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}} + } + + internal partial class InternalGlobals + { + <% + local type_to_methods = {} + local seq_tbl = {} + ForEachCsList(extension_methods, function(extension_method, idx) + local parameters = extension_method:GetParameters() + local type = parameters[0].ParameterType + if not type_to_methods[type] then + type_to_methods[type] = {type = type} + table.insert(seq_tbl, type_to_methods[type]) + end + table.insert(type_to_methods[type], {method = extension_method, index = idx}) + %> + delegate <%=CsFullTypeName(extension_method.ReturnType)%> __GEN_DELEGATE<%=idx%>(<%ForEachCsList(parameters, function(parameter, pi) + %><%if pi ~= 0 then%>, <%end%><%if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %> <%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><% + end)%>); + <%end)%> + static InternalGlobals() + { + extensionMethodMap = new Dictionary>() + { + <%for _, methods_info in ipairs(seq_tbl) do%> + {typeof(<%=CsFullTypeName(methods_info.type)%>), new List(){ + <% for _, method_info in ipairs(methods_info) do%> + new __GEN_DELEGATE<%=method_info.index%>(<%=CsFullTypeName(method_info.method.DeclaringType)%>.<%=method_info.method.Name%>) +#if UNITY_WSA && !UNITY_EDITOR + .GetMethodInfo(), +#else + .Method, +#endif + <% end%> + }}, + <%end%> + }; + + genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet; + genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegisterGCM.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegisterGCM.tpl.txt.meta new file mode 100644 index 0000000..a700667 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaRegisterGCM.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ac01d697b362a174eac5c56a5bde7d00 +timeCreated: 1501232428 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaWrapPusher.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaWrapPusher.tpl.txt new file mode 100644 index 0000000..d272fa1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaWrapPusher.tpl.txt @@ -0,0 +1,233 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +<% +require "TemplateCommon" +%> + +namespace XLua +{ + public partial class ObjectTranslator + { + <%if purevaluetypes.Count > 0 then + local init_class_name = "IniterAdder" .. CSVariableName(purevaluetypes[0].Type) + %> + class <%=init_class_name%> + { + static <%=init_class_name%>() + { + LuaEnv.AddIniter(Init); + } + + static void Init(LuaEnv luaenv, ObjectTranslator translator) + { + <%ForEachCsList(purevaluetypes, function(type_info) + if not type_info.Type.IsValueType then return end + local full_type_name = CsFullTypeName(type_info.Type)%> + translator.RegisterPushAndGetAndUpdate<<%=full_type_name%>>(translator.Push<%=CSVariableName(type_info.Type)%>, translator.Get, translator.Update<%=CSVariableName(type_info.Type)%>);<% + end)%> + <%ForEachCsList(tableoptimzetypes, function(type_info) + local full_type_name = CsFullTypeName(type_info.Type)%> + translator.RegisterCaster<<%=full_type_name%>>(translator.Get);<% + end)%> + } + } + + static <%=init_class_name%> s_<%=init_class_name%>_dumb_obj = new <%=init_class_name%>(); + static <%=init_class_name%> <%=init_class_name%>_dumb_obj {get{return s_<%=init_class_name%>_dumb_obj;}} + <%end%> + + <%ForEachCsList(purevaluetypes, function(type_info) + local type_id_var_name = CSVariableName(type_info.Type) .. '_TypeID' + local enum_ref_var_name = CSVariableName(type_info.Type)..'_EnumRef' + local full_type_name = CsFullTypeName(type_info.Type) + local is_enum = type_info.Type.IsEnum + %>int <%=type_id_var_name%> = -1;<%if is_enum then%> + int <%=enum_ref_var_name%> = -1; + <%end%> + public void Push<%=CSVariableName(type_info.Type)%>(RealStatePtr L, <%=full_type_name%> val) + { + if (<%=type_id_var_name%> == -1) + { + bool is_first; + <%=type_id_var_name%> = getTypeId(L, typeof(<%=full_type_name%>), out is_first); + <%if is_enum then%> + if (<%=enum_ref_var_name%> == -1) + { + Utils.LoadCSTable(L, typeof(<%=full_type_name%>)); + <%=enum_ref_var_name%> = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + } + <%end%> + } + <%if is_enum then%> + if (LuaAPI.xlua_tryget_cachedud(L, (int)val, <%=enum_ref_var_name%>) == 1) + { + return; + } + <% + end + if type_info.Flag == CS.XLua.OptimizeFlag.PackAsTable then + %> + <%if PushObjectNeedTranslator(type_info) then %> ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%> + LuaAPI.xlua_pushcstable(L, <%=type_info.FieldInfos.Count%>, <%=type_id_var_name%>); + <%ForEachCsList(type_info.FieldInfos, function(fieldInfo)%> + LuaAPI.xlua_pushasciistring(L, "<%=fieldInfo.Name%>"); + <%=GetPushStatement(fieldInfo.Type, "val."..fieldInfo.Name)%>; + LuaAPI.lua_rawset(L, -3); + <%end)%> + <%else%> + IntPtr buff = LuaAPI.xlua_pushstruct(L, <%=is_enum and 4 or type_info.Size%>, <%=type_id_var_name%>); + if (!CopyByValue.Pack(buff, 0, <%=is_enum and "(int)" or ""%>val)) + { + throw new Exception("pack fail fail for <%=full_type_name%> ,value="+val); + } + <% + end + if is_enum then + %> + LuaAPI.lua_getref(L, <%=enum_ref_var_name%>); + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.xlua_rawseti(L, -2, (int)val); + LuaAPI.lua_pop(L, 1); + <%end%> + } + + public void Get(RealStatePtr L, int index, out <%=full_type_name%> val) + { + LuaTypes type = LuaAPI.lua_type(L, index); + if (type == LuaTypes.LUA_TUSERDATA ) + { + if (LuaAPI.xlua_gettypeid(L, index) != <%=type_id_var_name%>) + { + throw new Exception("invalid userdata for <%=full_type_name%>"); + } + + IntPtr buff = LuaAPI.lua_touserdata(L, index);<%if is_enum then%> + int e; + <%end%>if (!CopyByValue.UnPack(buff, 0, out <%=is_enum and "e" or "val"%>)) + { + throw new Exception("unpack fail for <%=full_type_name%>"); + }<%if is_enum then%> + val = (<%=full_type_name%>)e; + <%end%> + }<%if not is_enum then%> + else if (type ==LuaTypes.LUA_TTABLE) + { + CopyByValue.UnPack(this, L, index, out val); + }<%end%> + else + { + val = (<%=full_type_name%>)objectCasters.GetCaster(typeof(<%=full_type_name%>))(L, index, null); + } + } + + public void Update<%=CSVariableName(type_info.Type)%>(RealStatePtr L, int index, <%=full_type_name%> val) + { + <%if type_info.Flag == CS.XLua.OptimizeFlag.PackAsTable then%> + if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TTABLE) + { + return; + } + <%else%> + if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) + { + if (LuaAPI.xlua_gettypeid(L, index) != <%=type_id_var_name%>) + { + throw new Exception("invalid userdata for <%=full_type_name%>"); + } + + IntPtr buff = LuaAPI.lua_touserdata(L, index); + if (!CopyByValue.Pack(buff, 0, <%=is_enum and "(int)" or ""%>val)) + { + throw new Exception("pack fail for <%=full_type_name%> ,value="+val); + } + } + <%end%> + else + { + throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index)); + } + } + + <%end)%> + // table cast optimze + <%ForEachCsList(tableoptimzetypes, function(type_info) + local full_type_name = CsFullTypeName(type_info.Type) + %> + public void Get(RealStatePtr L, int index, out <%=full_type_name%> val) + { + LuaTypes type = LuaAPI.lua_type(L, index); + if (type == LuaTypes.LUA_TUSERDATA ) + { + val = (<%=full_type_name%>)FastGetCSObj(L, index); + } + else if (type == LuaTypes.LUA_TTABLE) + { + val = new <%=full_type_name%>(); + int top = LuaAPI.lua_gettop(L); + <%ForEachCsList(type_info.Fields, function(fieldInfo)%> + if (Utils.LoadField(L, index, "<%=fieldInfo.Name%>")) + { + Get(L, top + 1, out val.<%=fieldInfo.Name%>); + } + LuaAPI.lua_pop(L, 1); + <%end)%> + }<%if not type_info.Type.IsValueType then%> + else if (type == LuaTypes.LUA_TNIL || type == LuaTypes.LUA_TNONE) + { + val = null; + }<%end%> + else + { + throw new Exception("can not cast " + LuaAPI.lua_type(L, index) + " to " + typeof(<%=full_type_name%>)); + } + } + <%end)%> + + } + + public partial class StaticLuaCallbacks + { + internal static bool __tryArrayGet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int index) + { + <%ForEachCsList(purevaluetypes, function(type_info, idx) + if not type_info.Type.IsValueType then return end + local full_type_name = CsFullTypeName(type_info.Type) + %> + <%=(idx == 0 and '' or 'else ')%>if (type == typeof(<%=full_type_name%>[])) + { + <%=full_type_name%>[] array = obj as <%=full_type_name%>[]; + translator.Push<%=CSVariableName(type_info.Type)%>(L, array[index]); + return true; + }<% + end)%> + return false; + } + + internal static bool __tryArraySet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int array_idx, int obj_idx) + { + <% + local is_first = true + ForEachCsList(purevaluetypes, tableoptimzetypes, function(type_info) + local full_type_name = CsFullTypeName(type_info.Type) + %> + <%=(is_first and '' or 'else ')%>if (type == typeof(<%=full_type_name%>[])) + { + <%=full_type_name%>[] array = obj as <%=full_type_name%>[]; + translator.Get(L, obj_idx, out array[array_idx]); + return true; + }<% + is_first = false + end)%> + return false; + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaWrapPusher.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaWrapPusher.tpl.txt.meta new file mode 100644 index 0000000..adf840e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/LuaWrapPusher.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4f116850ed7726c46980355c3fcdf5e7 +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/PackUnpack.tpl.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/PackUnpack.tpl.txt new file mode 100644 index 0000000..3c4ec59 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/PackUnpack.tpl.txt @@ -0,0 +1,123 @@ +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +<% +require "TemplateCommon" +%> + +namespace XLua +{ + public static partial class CopyByValue + { + <%ForEachCsList(type_infos, function(type_info) + local full_type_name = CsFullTypeName(type_info.Type) + %> + <%if type_info.IsRoot then + ForEachCsList(type_info.FieldInfos, function(fieldInfo) fieldInfo.Name = UnK(fieldInfo.Name) end) + %> + public static void UnPack(ObjectTranslator translator, RealStatePtr L, int idx, out <%=full_type_name%> val) + { + val = new <%=full_type_name%>(); + int top = LuaAPI.lua_gettop(L); + <%ForEachCsList(type_info.FieldInfos, function(fieldInfo)%> + if (Utils.LoadField(L, idx, "<%=fieldInfo.Name%>")) + { + <%if fieldInfo.IsField then%> + translator.Get(L, top + 1, out val.<%=fieldInfo.Name%>); + <%else%> + var <%=fieldInfo.Name%> = val.<%=fieldInfo.Name%>; + translator.Get(L, top + 1, out <%=fieldInfo.Name%>); + val.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>; + <%end%> + } + LuaAPI.lua_pop(L, 1); + <%end)%> + } + <%end%> + public static bool Pack(IntPtr buff, int offset, <%=full_type_name%> field) + { + <% + local offset_inner = 0 + if not type_info.FieldGroup then + ForEachCsList(type_info.FieldInfos, function(fieldInfo) + %> + if(!Pack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, field.<%=fieldInfo.Name%>)) + { + return false; + } + <% + offset_inner = offset_inner + fieldInfo.Size + end) + else + ForEachCsList(type_info.FieldGroup, function(group) + %> + if(!LuaAPI.xlua_pack_float<%=(group.Count == 1 and "" or group.Count)%>(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%><% + ForEachCsList(group, function(fieldInfo, i) + %>, field.<%=fieldInfo.Name%><% + end) + %>)) + { + return false; + } + <% + offset_inner = offset_inner + group.Count * 4 + end) + end%> + return true; + } + public static bool UnPack(IntPtr buff, int offset, out <%=full_type_name%> field) + { + field = default(<%=full_type_name%>); + <% + local offset_inner = 0 + if not type_info.FieldGroup then + ForEachCsList(type_info.FieldInfos, function(fieldInfo) + if fieldInfo.IsField then + %> + if(!UnPack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, out field.<%=fieldInfo.Name%>)) + { + return false; + } + <%else%> + var <%=fieldInfo.Name%> = field.<%=fieldInfo.Name%>; + if(!UnPack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, out <%=fieldInfo.Name%>)) + { + return false; + } + field.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>; + <% + end + offset_inner = offset_inner + fieldInfo.Size + end) + else + ForEachCsList(type_info.FieldGroup, function(group) + %> + <%ForEachCsList(group, function(fieldInfo)%>float <%=fieldInfo.Name%> = default(float); + <%end)%> + if(!LuaAPI.xlua_unpack_float<%=(group.Count == 1 and "" or group.Count)%>(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%><% + ForEachCsList(group, function(fieldInfo) + %>, out <%=fieldInfo.Name%><% + end) + %>)) + { + return false; + } + <%ForEachCsList(group, function(fieldInfo)%>field.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>; + <%end)%> + <% + offset_inner = offset_inner + group.Count * 4 + end) + end%> + return true; + } + <%end)%> + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/PackUnpack.tpl.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/PackUnpack.tpl.txt.meta new file mode 100644 index 0000000..1bff6bc --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/PackUnpack.tpl.txt.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 70278270105141e4fbaefc60244e5b3d +timeCreated: 1481620508 +licenseType: Pro +TextScriptImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/TemplateCommon.lua.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/TemplateCommon.lua.txt new file mode 100644 index 0000000..43e43bb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/TemplateCommon.lua.txt @@ -0,0 +1,471 @@ +-- Tencent is pleased to support the open source community by making xLua available. +-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. +-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +-- http://opensource.org/licenses/MIT +-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +local friendlyNameMap = { + ["System.Object"] = "object", + ["System.String"] = "string", + ["System.Boolean"] = "bool", + ["System.Byte"] = "byte", + ["System.Char"] = "char", + ["System.Decimal"] = "decimal", + ["System.Double"] = "double", + ["System.Int16"] = "short", + ["System.Int32"] = "int", + ["System.Int64"] = "long", + ["System.SByte"] = "sbyte", + ["System.Single"] = "float", + ["System.UInt16"] = "ushort", + ["System.UInt32"] = "uint", + ["System.UInt64"] = "ulong", + ["System.Void"] = "void", +} + +local csKeywords = { +"abstract", "as", "base", "bool", +"break", "byte", "case", "catch", +"char", "checked", "class", "const", +"continue", "decimal", "default", "delegate", +"do", "double", "else", "enum", +"event", "explicit", "extern", "false", +"finally", "fixed", "float", "for", +"foreach", "goto", "if", "implicit", +"in", "int", "interface", +"internal", "is", "lock", "long", +"namespace", "new", "null", "object", +"operator", "out", "override", +"params", "private", "protected", "public", +"readonly", "ref", "return", "sbyte", +"sealed", "short", "sizeof", "stackalloc", +"static", "string", "struct", "switch", +"this", "throw", "true", "try", +"typeof", "uint", "ulong", "unchecked", +"unsafe", "ushort", "using", "virtual", +"void", "volatile", "while" +} + +for _, kw in ipairs(csKeywords) do + csKeywords[kw] = '@'..kw +end +for i = 1, #csKeywords do + csKeywords[i] = nil +end + +function UnK(symbol) + return csKeywords[symbol] or symbol +end + +local fixChecker = { + --["System.String"] = "LuaAPI.lua_isstring", + ["System.Boolean"] = "LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type", + ["System.Byte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.Char"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + --["System.Decimal"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.Double"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.Int16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.Int32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + --["System.Int64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.SByte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.Single"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.UInt16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.UInt32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + --["System.UInt64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type", + ["System.IntPtr"] = "LuaTypes.LUA_TLIGHTUSERDATA == LuaAPI.lua_type", +} + +local typedCaster = { + ["System.Byte"] = "LuaAPI.xlua_tointeger", + ["System.Char"] = "LuaAPI.xlua_tointeger", + ["System.Int16"] = "LuaAPI.xlua_tointeger", + ["System.SByte"] = "LuaAPI.xlua_tointeger", + ["System.Single"] = "LuaAPI.lua_tonumber", + ["System.UInt16"] = "LuaAPI.xlua_tointeger", +} + +local fixCaster = { + ["System.Double"] = "LuaAPI.lua_tonumber", + ["System.String"] = "LuaAPI.lua_tostring", + ["System.Boolean"] = "LuaAPI.lua_toboolean", + ["System.Byte[]"] = "LuaAPI.lua_tobytes", + ["System.IntPtr"] = "LuaAPI.lua_touserdata", + ["System.UInt32"] = "LuaAPI.xlua_touint", + ["System.UInt64"] = "LuaAPI.lua_touint64", + ["System.Int32"] = "LuaAPI.xlua_tointeger", + ["System.Int64"] = "LuaAPI.lua_toint64", +} + +local fixPush = { + ["System.Byte"] = "LuaAPI.xlua_pushinteger", + ["System.Char"] = "LuaAPI.xlua_pushinteger", + ["System.Int16"] = "LuaAPI.xlua_pushinteger", + ["System.Int32"] = "LuaAPI.xlua_pushinteger", + ["System.Int64"] = "LuaAPI.lua_pushint64", + ["System.SByte"] = "LuaAPI.xlua_pushinteger", + ["System.Single"] = "LuaAPI.lua_pushnumber", + ["System.UInt16"] = "LuaAPI.xlua_pushinteger", + ["System.UInt32"] = "LuaAPI.xlua_pushuint", + ["System.UInt64"] = "LuaAPI.lua_pushuint64", + ["System.Double"] = "LuaAPI.lua_pushnumber", + ["System.String"] = "LuaAPI.lua_pushstring", + ["System.Byte[]"] = "LuaAPI.lua_pushstring", + ["System.Boolean"] = "LuaAPI.lua_pushboolean", + ["System.IntPtr"] = "LuaAPI.lua_pushlightuserdata", + ["System.Decimal"] = "translator.PushDecimal", + ["System.Object"] = "translator.PushAny", +} + +local notranslator = { + ["System.Byte"] = true, + ["System.Char"] = true, + ["System.Int16"] = true, + ["System.Int32"] = true, + ["System.Int64"] = true, + ["System.SByte"] = true, + ["System.Single"] = true, + ["System.UInt16"] = true, + ["System.UInt32"] = true, + ["System.UInt64"] = true, + ["System.Double"] = true, + ["System.String"] = true, + ["System.Boolean"] = true, + ["System.Void"] = true, + ["System.IntPtr"] = true, + ["System.Byte[]"] = true, +} + +function ForEachCsList(...) + local list_count = select('#', ...) - 1 + local callback = select(list_count + 1, ...) + for i = 1, list_count do + local list = select(i, ...) + for i = 0, (list.Count or list.Length) - 1 do + callback(list[i], i) + end + end +end + +function CalcCsList(list, predicate) + local count = 0 + for i = 0, (list.Count or list.Length) - 1 do + if predicate(list[i], i) then count = count + 1 end + end + return count +end + +function IfAny(list, predicate) + for i = 0, (list.Count or list.Length) - 1 do + if predicate(list[i], i) then return true end + end + return false +end + +local genPushAndUpdateTypes + +function SetGenPushAndUpdateTypes(list) + genPushAndUpdateTypes = {} + ForEachCsList(list, function(t) + genPushAndUpdateTypes[t] = true + end) +end + +local xLuaClasses +function SetXLuaClasses(list) + xLuaClasses = {} + ForEachCsList(list, function(t) + xLuaClasses[t.Name] = true + end) +end + +local objType = typeof(CS.System.Object) +local valueType = typeof(CS.System.ValueType) + +local function _CsFullTypeName(t) + if t.IsArray then + local element_name, element_is_array = _CsFullTypeName(t:GetElementType()) + if element_is_array then + local bracket_pos = element_name:find('%[') + return element_name:sub(1, bracket_pos - 1) .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']' .. element_name:sub(bracket_pos, -1), true + else + return element_name .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']', true + end + elseif t.IsByRef then + return _CsFullTypeName(t:GetElementType()) + elseif t.IsGenericParameter then + return (t.BaseType == objType or t.BaseType == valueType) and t.Name or _CsFullTypeName(t.BaseType) --TODO:应该判断是否类型约束 + end + + local name = t.FullName:gsub("&", ""):gsub("%+", ".") + if not t.IsGenericType then + return friendlyNameMap[name] or name + end + local genericParameter = "" + ForEachCsList(t:GetGenericArguments(), function(at, ati) + if ati ~= 0 then genericParameter = genericParameter .. ', ' end + genericParameter = genericParameter .. _CsFullTypeName(at) + end) + return name:gsub("`%d+", '<' .. genericParameter .. '>'):gsub("%[[^,%]].*", ""), false +end + +function CsFullTypeName(t) + if t.DeclaringType then + local name = _CsFullTypeName(t) + local declaringTypeName = _CsFullTypeName(t.DeclaringType); + return xLuaClasses[declaringTypeName] and ("global::" .. name) or name + else + local name = _CsFullTypeName(t) + return xLuaClasses[name] and ("global::" .. name) or name + end +end + +function CSVariableName(t) + if t.IsArray then + return CSVariableName(t:GetElementType()) .. '_'.. t:GetArrayRank() ..'_' + end + return t:ToString():gsub("&", ""):gsub("%+", ""):gsub("`", "_"):gsub("%.", ""):gsub("%[", "_"):gsub("%]", "_"):gsub(",", "") +end + +local function getSafeFullName(t) + if t == nil then + return "" + end + + if t.IsGenericParameter then + return t.BaseType == objType and t.Name or getSafeFullName(t.BaseType) + end + + if not t.FullName then return "" end + + return t.FullName:gsub("&", "") +end + +function GetCheckStatement(t, idx, is_v_params) + local cond_start = is_v_params and "(LuaTypes.LUA_TNONE == LuaAPI.lua_type(L, ".. idx ..") || " or "" + local cond_end = is_v_params and ")" or "" + local testname = getSafeFullName(t) + if testname == "System.String" or testname == "System.Byte[]" then + return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TSTRING)" .. cond_end + elseif testname == "System.Int64" then + return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isint64(L, ".. idx .."))" .. cond_end + elseif testname == "System.UInt64" then + return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isuint64(L, ".. idx .."))" .. cond_end + elseif testname == "System.Decimal" then + return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || translator.IsDecimal(L, ".. idx .."))" .. cond_end + elseif testname == "XLua.LuaTable" then + return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TTABLE)" .. cond_end + elseif testname == "XLua.LuaFunction" then + return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TFUNCTION)" .. cond_end + end + return cond_start .. (fixChecker[testname] or ("translator.Assignable<" .. CsFullTypeName(t).. ">")) .. "(L, ".. idx ..")" .. cond_end +end + +local delegateType = typeof(CS.System.Delegate) +local ExtensionAttribute = typeof(CS.System.Runtime.CompilerServices.ExtensionAttribute) + +function IsExtensionMethod(method) + return method:IsDefined(ExtensionAttribute, false) +end + +function IsDelegate(t) + return delegateType:IsAssignableFrom(t) +end + +function MethodParameters(method) + if not IsExtensionMethod(method) then + return method:GetParameters() + else + local parameters = method:GetParameters() + if parameters[0].ParameterType.IsInterface then + return parameters + end + local ret = {} + for i = 1, parameters.Length - 1 do + ret[i - 1] = parameters[i] + end + ret.Length = parameters.Length - 1 + return ret + end +end + +function IsStruct(t) + if t.IsByRef then t = t:GetElementType() end + return t.IsValueType and not t.IsPrimitive +end + +function NeedUpdate(t) + if t.IsByRef then t = t:GetElementType() end + return t.IsValueType and not t.IsPrimitive and not t.IsEnum and t ~= typeof(CS.System.Decimal) +end + +function GetCasterStatement(t, idx, var_name, need_declare, is_v_params) + local testname = getSafeFullName(t) + local statement = "" + local is_struct = IsStruct(t) + + if need_declare then + statement = CsFullTypeName(t) .. " " .. var_name + if is_struct and not typedCaster[testname] and not fixCaster[testname] then + statement = statement .. ";" + else + statement = statement .. " = " + end + elseif not is_struct then + statement = var_name .. " = " + end + + if is_v_params then + return statement .. "translator.GetParams<" .. CsFullTypeName(t:GetElementType()).. ">" .. "(L, ".. idx ..")" + elseif typedCaster[testname] then + return statement .. "(" .. CsFullTypeName(t) .. ")" ..typedCaster[testname] .. "(L, ".. idx ..")" + elseif IsDelegate(t) then + return statement .. "translator.GetDelegate<" .. CsFullTypeName(t).. ">" .. "(L, ".. idx ..")" + elseif fixCaster[testname] then + return statement .. fixCaster[testname] .. "(L, ".. idx ..")" + elseif testname == "System.Object" then + return statement .. "translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))" + elseif is_struct then + return statement .. "translator.Get(L, ".. idx ..", out " .. var_name .. ")" + elseif t.IsGenericParameter and not t.DeclaringMethod then + return statement .. "translator.GetByType<"..t.Name..">(L, ".. idx ..")" + else + return statement .. "("..CsFullTypeName(t)..")translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))" + end +end + +local paramsAttriType = typeof(CS.System.ParamArrayAttribute) +function IsParams(pi) + if (not pi.IsDefined) then + return pi.IsParamArray + end + return pi:IsDefined(paramsAttriType, false) +end + +local obsoluteAttriType = typeof(CS.System.ObsoleteAttribute) +function IsObsolute(f) + return f:IsDefined(obsoluteAttriType, false) +end + +local objectType = typeof(CS.System.Object) +function GetSelfStatement(t) + local fulltypename = CsFullTypeName(t) + local is_struct = IsStruct(t) + if is_struct then + return fulltypename .. " gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked)" + else + if t == objectType then + return "object gen_to_be_invoked = translator.FastGetCSObj(L, 1)" + else + return fulltypename .. " gen_to_be_invoked = (" .. fulltypename .. ")translator.FastGetCSObj(L, 1)" + end + end + +end + +local GetNullableUnderlyingType = CS.System.Nullable.GetUnderlyingType + +function GetPushStatement(t, variable, is_v_params) + if is_v_params then + local item_push = GetPushStatement(t:GetElementType(), variable..'[__gen_i]') + return 'if ('.. variable ..' != null) { for (int __gen_i = 0; __gen_i < ' .. variable .. '.Length; ++__gen_i) ' .. item_push .. '; }' + end + if t.IsByRef then t = t:GetElementType() end + local testname = getSafeFullName(t) + if fixPush[testname] then + return fixPush[testname] .. "(L, ".. variable ..")" + elseif genPushAndUpdateTypes[t] then + return "translator.Push".. CSVariableName(t) .."(L, "..variable..")" + elseif t.IsGenericParameter and not t.DeclaringMethod then + return "translator.PushByType(L, "..variable..")" + elseif t.IsInterface or GetNullableUnderlyingType(t) then + return "translator.PushAny(L, "..variable..")" + else + return "translator.Push(L, "..variable..")" + end +end + +function GetUpdateStatement(t, idx, variable) + if t.IsByRef then t = t:GetElementType() end + if typeof(CS.System.Decimal) == t then error('Decimal not update!') end + if genPushAndUpdateTypes[t] then + return "translator.Update".. CSVariableName(t) .."(L, ".. idx ..", "..variable..")" + else + return "translator.Update(L, ".. idx ..", "..variable..")" + end +end + +function JustLuaType(t) + return notranslator[getSafeFullName(t)] +end + +function CallNeedTranslator(overload, isdelegate) + if not overload.IsStatic and not isdelegate then return true end + local ret_type_name = getSafeFullName(overload.ReturnType) + if not notranslator[ret_type_name] then return true end + local parameters = overload:GetParameters() + return IfAny(overload:GetParameters(), function(parameter) + return IsParams(parameter) or (not notranslator[getSafeFullName(parameter.ParameterType)]) + end) +end + +function MethodCallNeedTranslator(method) + return IfAny(method.Overloads, function(overload) return CallNeedTranslator(overload) end) +end + +function AccessorNeedTranslator(accessor) + return not accessor.IsStatic or not JustLuaType(accessor.Type) +end + +function PushObjectNeedTranslator(type_info) + return IfAny(type_info.FieldInfos, function(field_info) return not JustLuaType(field_info.Type) end) +end + +local GenericParameterAttributes = CS.System.Reflection.GenericParameterAttributes +local enum_and_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__band +local has_generic_flag = function(f1, f2) + return (f1 ~= GenericParameterAttributes.None) and (enum_and_op(f1, f2) == f2) +end + +function GenericArgumentList(type) + local generic_arg_list = "" + local type_constraints = "" + if type.IsGenericTypeDefinition then + generic_arg_list = "<" + + local constraints = {} + + ForEachCsList(type:GetGenericArguments(), function(generic_arg, gai) + local constraint = {} + if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end + + generic_arg_list = generic_arg_list .. generic_arg.Name + + if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.ReferenceTypeConstraint) then + table.insert(constraint, 'class') + end + if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then + table.insert(constraint, 'struct') + end + ForEachCsList(generic_arg:GetGenericParameterConstraints(), function(gpc) + if gpc ~= typeof(CS.System.ValueType) or not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then + table.insert(constraint, CsFullTypeName(gpc)) + end + end) + if not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) and has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.DefaultConstructorConstraint) then + table.insert(constraint, 'new()') + end + if #constraint > 0 then + table.insert(constraints, 'where ' .. generic_arg.Name .. ' : ' .. table.concat(constraint, ',')) + end + end) + generic_arg_list = generic_arg_list .. ">" + if #constraints > 0 then + type_constraints = table.concat(constraints, ',') + end + end + return generic_arg_list, type_constraints +end + +function LocalName(name) + return "_" .. name +end diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/TemplateCommon.lua.txt.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/TemplateCommon.lua.txt.meta new file mode 100644 index 0000000..dbc9972 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/Template/TemplateCommon.lua.txt.meta @@ -0,0 +1,4 @@ +fileFormatVersion: 2 +guid: 1594c11a3b545cd4381fec0acf282ca8 +TextScriptImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/TemplateRef.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/TemplateRef.cs new file mode 100644 index 0000000..7e439b5 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/TemplateRef.cs @@ -0,0 +1,20 @@ +using UnityEngine; +using System.Collections; +namespace XLua +{ + public class TemplateRef : ScriptableObject + { + public TextAsset LuaClassWrap; + public TextAsset LuaClassWrapGCM; + public TextAsset LuaDelegateBridge; + public TextAsset LuaDelegateWrap; + public TextAsset LuaEnumWrap; + public TextAsset LuaEnumWrapGCM; + public TextAsset LuaInterfaceBridge; + public TextAsset LuaRegister; + public TextAsset LuaRegisterGCM; + public TextAsset LuaWrapPusher; + public TextAsset PackUnpack; + public TextAsset TemplateCommon; + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/TemplateRef.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/TemplateRef.cs.meta new file mode 100644 index 0000000..99f57c4 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Editor/TemplateRef.cs.meta @@ -0,0 +1,25 @@ +fileFormatVersion: 2 +guid: 4038bd6d53e34594fbf86f311f3a56ff +timeCreated: 1501232546 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: + - LuaClassWrap: {fileID: 4900000, guid: 8503038eabbabe44dac0f5f749d4411a, type: 3} + - LuaClassWrapGCM: {fileID: 4900000, guid: 2bd79d95fd859724283926ad8fa4df30, type: 3} + - LuaDelegateBridge: {fileID: 4900000, guid: 3d992756e2469044484be75f78e4e556, type: 3} + - LuaDelegateWrap: {fileID: 4900000, guid: 33b33e1cd617f794b8c801a32f3b2539, type: 3} + - LuaEnumWrap: {fileID: 4900000, guid: ae16c73aad9a21a44aef65decb7e4928, type: 3} + - LuaEnumWrapGCM: {fileID: 4900000, guid: ea84a5ee7abf8e347a810eb7848add46, type: 3} + - LuaInterfaceBridge: {fileID: 4900000, guid: 7165d08e91378494dadeb10e5338accb, + type: 3} + - LuaRegister: {fileID: 4900000, guid: e416b82ec9fe340458f97cf1e3468ef7, type: 3} + - LuaRegisterGCM: {fileID: 4900000, guid: 46c7366d55afbf1459674448d92c44c8, type: 3} + - LuaWrapPusher: {fileID: 4900000, guid: d1a916469d261d447972d287b6c5b7a0, type: 3} + - PackUnpack: {fileID: 4900000, guid: c9ef7e8f2a3b37744aad49b99370c16b, type: 3} + - TemplateCommon: {fileID: 4900000, guid: cb41d53afe75a9443b182e284298feeb, type: 3} + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenAttributes.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenAttributes.cs new file mode 100644 index 0000000..09c7c3b --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenAttributes.cs @@ -0,0 +1,168 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +using System; +using System.Collections.Generic; + +namespace XLua +{ + public enum GenFlag + { + No = 0, + [Obsolete("use GCOptimizeAttribute instead")] + GCOptimize = 1 + } + + //如果你要生成Lua调用CSharp的代码,加这个标签 + public class LuaCallCSharpAttribute : Attribute + { + GenFlag flag; + public GenFlag Flag { + get + { + return flag; + } + } + + public LuaCallCSharpAttribute(GenFlag flag = GenFlag.No) + { + this.flag = flag; + } + } + + //生成CSharp调用Lua,加这标签 + //[AttributeUsage(AttributeTargets.Delegate | AttributeTargets.Interface)] + public class CSharpCallLuaAttribute : Attribute + { + } + + //如果某属性、方法不需要生成,加这个标签 + public class BlackListAttribute : Attribute + { + + } + + [Flags] + public enum OptimizeFlag + { + Default = 0, + PackAsTable = 1 + } + + //如果想对struct生成免GC代码,加这个标签 + public class GCOptimizeAttribute : Attribute + { + OptimizeFlag flag; + public OptimizeFlag Flag + { + get + { + return flag; + } + } + + public GCOptimizeAttribute(OptimizeFlag flag = OptimizeFlag.Default) + { + this.flag = flag; + } + } + + //如果想在反射下使用,加这个标签 + public class ReflectionUseAttribute : Attribute + { + + } + + //只能标注Dictionary>的field或者property + public class DoNotGenAttribute : Attribute + { + + } + + public class AdditionalPropertiesAttribute : Attribute + { + + } + + [Flags] + public enum HotfixFlag + { + Stateless = 0, + [Obsolete("use xlua.util.state instead!", true)] + Stateful = 1, + ValueTypeBoxing = 2, + IgnoreProperty = 4, + IgnoreNotPublic = 8, + Inline = 16, + IntKey = 32, + AdaptByDelegate = 64, + IgnoreCompilerGenerated = 128, + NoBaseProxy = 256, + } + + public class HotfixAttribute : Attribute + { + HotfixFlag flag; + public HotfixFlag Flag + { + get + { + return flag; + } + } + + public HotfixAttribute(HotfixFlag e = HotfixFlag.Stateless) + { + flag = e; + } + } + + [AttributeUsage(AttributeTargets.Delegate)] + internal class HotfixDelegateAttribute : Attribute + { + } + +#if !XLUA_GENERAL + public static class SysGenConfig + { + [GCOptimize] + static List GCOptimize + { + get + { + return new List() { + typeof(UnityEngine.Vector2), + typeof(UnityEngine.Vector3), + typeof(UnityEngine.Vector4), + typeof(UnityEngine.Color), + typeof(UnityEngine.Quaternion), + typeof(UnityEngine.Ray), + typeof(UnityEngine.Bounds), + typeof(UnityEngine.Ray2D), + }; + } + } + + [AdditionalProperties] + static Dictionary> AdditionalProperties + { + get + { + return new Dictionary>() + { + { typeof(UnityEngine.Ray), new List() { "origin", "direction" } }, + { typeof(UnityEngine.Ray2D), new List() { "origin", "direction" } }, + { typeof(UnityEngine.Bounds), new List() { "center", "extents" } }, + }; + } + } + } +#endif +} + + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenAttributes.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenAttributes.cs.meta new file mode 100644 index 0000000..3b8ee47 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenAttributes.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a312a2f4c3eed5e4880103231d6f455f +timeCreated: 1452509750 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenericDelegateBridge.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenericDelegateBridge.cs new file mode 100644 index 0000000..5ab08c8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenericDelegateBridge.cs @@ -0,0 +1,255 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +using System; +using LuaAPI = XLua.LuaDLL.Lua; + +namespace XLua { + public partial class DelegateBridge : DelegateBridgeBase { + public void Action() { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + int error = LuaAPI.lua_pcall(L, 0, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void Action(T1 p1) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + int error = LuaAPI.lua_pcall(L, 1, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void Action(T1 p1, T2 p2) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + translator.PushByType(L, p2); + int error = LuaAPI.lua_pcall(L, 2, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void Action(T1 p1, T2 p2, T3 p3) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + translator.PushByType(L, p2); + translator.PushByType(L, p3); + int error = LuaAPI.lua_pcall(L, 3, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void Action(T1 p1, T2 p2, T3 p3, T4 p4) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + translator.PushByType(L, p2); + translator.PushByType(L, p3); + translator.PushByType(L, p4); + int error = LuaAPI.lua_pcall(L, 4, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + + public TResult Func() { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + int error = LuaAPI.lua_pcall(L, 0, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try { + translator.Get(L, -1, out ret); + } catch (Exception e) { + throw e; + } finally { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public TResult Func(T1 p1) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + int error = LuaAPI.lua_pcall(L, 1, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try { + translator.Get(L, -1, out ret); + } catch (Exception e) { + throw e; + } finally { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public TResult Func(T1 p1, T2 p2) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + translator.PushByType(L, p2); + int error = LuaAPI.lua_pcall(L, 2, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try { + translator.Get(L, -1, out ret); + } catch (Exception e) { + throw e; + } finally { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public TResult Func(T1 p1, T2 p2, T3 p3) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + translator.PushByType(L, p2); + translator.PushByType(L, p3); + int error = LuaAPI.lua_pcall(L, 3, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try { + translator.Get(L, -1, out ret); + } catch (Exception e) { + throw e; + } finally { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public TResult Func(T1 p1, T2 p2, T3 p3, T4 p4) { +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnv.luaEnvLock) { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, p1); + translator.PushByType(L, p2); + translator.PushByType(L, p3); + translator.PushByType(L, p4); + int error = LuaAPI.lua_pcall(L, 4, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try { + translator.Get(L, -1, out ret); + } catch (Exception e) { + throw e; + } finally { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + } +} + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenericDelegateBridge.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenericDelegateBridge.cs.meta new file mode 100644 index 0000000..930ca1d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/GenericDelegateBridge.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 88d1d0efaf062594393e852546484f80 +timeCreated: 1537950363 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/InternalGlobals.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/InternalGlobals.cs new file mode 100644 index 0000000..74fc3e7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/InternalGlobals.cs @@ -0,0 +1,69 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace XLua +{ + internal partial class InternalGlobals + { +#if !THREAD_SAFE && !HOTFIX_ENABLE + internal static byte[] strBuff = new byte[256]; +#endif + + internal delegate bool TryArrayGet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int index); + internal delegate bool TryArraySet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int array_idx, int obj_idx); + internal static volatile TryArrayGet genTryArrayGetPtr = null; + internal static volatile TryArraySet genTryArraySetPtr = null; + + internal static volatile ObjectTranslatorPool objectTranslatorPool = new ObjectTranslatorPool(); + + internal static volatile int LUA_REGISTRYINDEX = -10000; + + internal static volatile Dictionary supportOp = new Dictionary() + { + { "op_Addition", "__add" }, + { "op_Subtraction", "__sub" }, + { "op_Multiply", "__mul" }, + { "op_Division", "__div" }, + { "op_Equality", "__eq" }, + { "op_UnaryNegation", "__unm" }, + { "op_LessThan", "__lt" }, + { "op_LessThanOrEqual", "__le" }, + { "op_Modulus", "__mod" }, + { "op_BitwiseAnd", "__band" }, + { "op_BitwiseOr", "__bor" }, + { "op_ExclusiveOr", "__bxor" }, + { "op_OnesComplement", "__bnot" }, + { "op_LeftShift", "__shl" }, + { "op_RightShift", "__shr" }, + }; + + internal static volatile Dictionary> extensionMethodMap = null; + +#if GEN_CODE_MINIMIZE + internal static volatile LuaDLL.CSharpWrapperCaller CSharpWrapperCallerPtr = new LuaDLL.CSharpWrapperCaller(StaticLuaCallbacks.CSharpWrapperCallerImpl); +#endif + + internal static volatile LuaCSFunction LazyReflectionWrap = new LuaCSFunction(Utils.LazyReflectionCall); + } + +} + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/InternalGlobals.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/InternalGlobals.cs.meta new file mode 100644 index 0000000..ada2a41 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/InternalGlobals.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f211b513df4849a4b837ca724eb9b53a +timeCreated: 1496994941 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaAsset.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaAsset.cs new file mode 100644 index 0000000..ed04acb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaAsset.cs @@ -0,0 +1,65 @@ +using System; +using System.Security.Cryptography; +using UnityEngine; + +[Serializable] +public class LuaAsset : ScriptableObject +{ + public static string LuaDecodeKey = "LuaDecodeKey"; //TODO: use a safe method to hide decode key + public static string[] LuaSearchingPaths = new []{ + "lua/", + "lua/utility/", + }; + + public bool encode = true; + public byte[] data; + + public byte[] GetDecodeBytes() + { + byte[] decode = this.data; + + // TODO: your decode function + decode = encode ? Security.XXTEA.Decrypt(this.data, LuaAsset.LuaDecodeKey) : this.data; + + return data; + } + + public static byte[] Require(ref string luapath) + { + return Require(luapath); + } + + public static byte[] Require(string luapath, string search = "", int retry = 0) + { + if(string.IsNullOrEmpty(luapath)) + return null; + + var LuaExtension = ".lua"; + + if(luapath.EndsWith(LuaExtension)) + { + luapath = luapath.Remove(luapath.LastIndexOf(LuaExtension)); + } + + byte[] bytes = null; + var assetName = search + luapath.Replace(".", "/") + LuaExtension; + { + //TODO: your bundle load method + // var asset = AssetSys.GetAssetSync(assetName); + var asset = Resources.Load(assetName); + if (asset != null) + { + bytes = asset.GetDecodeBytes(); + } + } + + // try next searching path + if(bytes == null && retry < LuaSearchingPaths.Length) + { + bytes = Require(luapath, LuaSearchingPaths[retry], 1+retry); + } + + Debug.Assert(bytes != null, $"{luapath} not found."); + return bytes; + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaAsset.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaAsset.cs.meta new file mode 100644 index 0000000..9fdcc30 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaAsset.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 59708e44aedfb35418d2f0d2867d7699 +timeCreated: 1614328670 \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaBase.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaBase.cs new file mode 100644 index 0000000..0c44382 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaBase.cs @@ -0,0 +1,117 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; + +namespace XLua +{ + public abstract class LuaBase : IDisposable + { + protected bool disposed; + protected readonly int luaReference; + protected readonly LuaEnv luaEnv; + +#if UNITY_EDITOR || XLUA_GENERAL + protected int _errorFuncRef { get { return luaEnv.errorFuncRef; } } + protected RealStatePtr _L { get { return luaEnv.L; } } + protected ObjectTranslator _translator { get { return luaEnv.translator; } } +#endif + + public LuaBase(int reference, LuaEnv luaenv) + { + luaReference = reference; + luaEnv = luaenv; + } + + ~LuaBase() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + public virtual void Dispose(bool disposeManagedResources) + { + if (!disposed) + { + if (luaReference != 0) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + bool is_delegate = this is DelegateBridgeBase; + if (disposeManagedResources) + { + luaEnv.translator.ReleaseLuaBase(luaEnv.L, luaReference, is_delegate); + } + else //will dispse by LuaEnv.GC + { + luaEnv.equeueGCAction(new LuaEnv.GCAction { Reference = luaReference, IsDelegate = is_delegate }); + } +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + disposed = true; + } + } + + public override bool Equals(object o) + { + if (o != null && this.GetType() == o.GetType()) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + LuaBase rhs = (LuaBase)o; + var L = luaEnv.L; + if (L != rhs.luaEnv.L) + return false; + int top = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, rhs.luaReference); + LuaAPI.lua_getref(L, luaReference); + int equal = LuaAPI.lua_rawequal(L, -1, -2); + LuaAPI.lua_settop(L, top); + return (equal != 0); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + else return false; + } + + public override int GetHashCode() + { + LuaAPI.lua_getref(luaEnv.L, luaReference); + var pointer = LuaAPI.lua_topointer(luaEnv.L, -1); + LuaAPI.lua_pop(luaEnv.L, 1); + return pointer.ToInt32(); + } + + internal virtual void push(RealStatePtr L) + { + LuaAPI.lua_getref(L, luaReference); + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaBase.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaBase.cs.meta new file mode 100644 index 0000000..194b492 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaBase.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 102d75bcb5f92d8439e725d598793310 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaDLL.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaDLL.cs new file mode 100644 index 0000000..73c8fdf --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaDLL.cs @@ -0,0 +1,599 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +namespace XLua.LuaDLL +{ + + using System; + using System.Runtime.InteropServices; + using System.Text; + using XLua; + +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR) + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate int lua_CSFunction(IntPtr L); + +#if GEN_CODE_MINIMIZE + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate int CSharpWrapperCaller(IntPtr L, int funcidx, int top); +#endif +#else + public delegate int lua_CSFunction(IntPtr L); + +#if GEN_CODE_MINIMIZE + public delegate int CSharpWrapperCaller(IntPtr L, int funcidx, int top); +#endif +#endif + + + public partial class Lua + { +#if (UNITY_IPHONE || UNITY_TVOS || UNITY_WEBGL || UNITY_SWITCH) && !UNITY_EDITOR + const string LUADLL = "__Internal"; +#else + const string LUADLL = "xlua"; +#endif + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_tothread(IntPtr L, int index); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_get_lib_version(); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int lua_gc(IntPtr L, LuaGCOptions what, int data); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_getupvalue(IntPtr L, int funcindex, int n); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_setupvalue(IntPtr L, int funcindex, int n); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int lua_pushthread(IntPtr L); + + public static bool lua_isfunction(IntPtr L, int stackPos) + { + return lua_type(L, stackPos) == LuaTypes.LUA_TFUNCTION; + } + + public static bool lua_islightuserdata(IntPtr L, int stackPos) + { + return lua_type(L, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA; + } + + public static bool lua_istable(IntPtr L, int stackPos) + { + return lua_type(L, stackPos) == LuaTypes.LUA_TTABLE; + } + + public static bool lua_isthread(IntPtr L, int stackPos) + { + return lua_type(L, stackPos) == LuaTypes.LUA_TTHREAD; + } + + public static int luaL_error(IntPtr L, string message) //[-0, +1, m] + { + xlua_csharp_str_error(L, message); + return 0; + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int lua_setfenv(IntPtr L, int stackPos); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr luaL_newstate(); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_close(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] //[-0, +0, m] + public static extern void luaopen_xlua(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] //[-0, +0, m] + public static extern void luaL_openlibs(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern uint xlua_objlen(IntPtr L, int stackPos); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_createtable(IntPtr L, int narr, int nrec);//[-0, +0, m] + + public static void lua_newtable(IntPtr L)//[-0, +0, m] + { + lua_createtable(L, 0, 0); + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_getglobal(IntPtr L, string name);//[-1, +0, m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_setglobal(IntPtr L, string name);//[-1, +0, m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_getloaders(IntPtr L); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_settop(IntPtr L, int newTop); + + public static void lua_pop(IntPtr L, int amount) + { + lua_settop(L, -(amount) - 1); + } + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_insert(IntPtr L, int newTop); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_remove(IntPtr L, int index); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int lua_rawget(IntPtr L, int index); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_rawset(IntPtr L, int index);//[-2, +0, m] + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int lua_setmetatable(IntPtr L, int objIndex); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int lua_rawequal(IntPtr L, int index1, int index2); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_pushvalue(IntPtr L, int index); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_pushcclosure(IntPtr L, IntPtr fn, int n);//[-n, +1, m] + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_replace(IntPtr L, int index); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int lua_gettop(IntPtr L); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern LuaTypes lua_type(IntPtr L, int index); + + public static bool lua_isnil(IntPtr L, int index) + { + return (lua_type(L,index)==LuaTypes.LUA_TNIL); + } + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern bool lua_isnumber(IntPtr L, int index); + + public static bool lua_isboolean(IntPtr L, int index) + { + return lua_type(L,index)==LuaTypes.LUA_TBOOLEAN; + } + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int luaL_ref(IntPtr L, int registryIndex); + + public static int luaL_ref(IntPtr L)//[-1, +0, m] + { + return luaL_ref(L,LuaIndexes.LUA_REGISTRYINDEX); + } + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void xlua_rawgeti(IntPtr L, int tableIndex, long index); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void xlua_rawseti(IntPtr L, int tableIndex, long index);//[-1, +0, m] + + public static void lua_getref(IntPtr L, int reference) + { + xlua_rawgeti(L,LuaIndexes.LUA_REGISTRYINDEX,reference); + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int pcall_prepare(IntPtr L, int error_func_ref, int func_ref); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void luaL_unref(IntPtr L, int registryIndex, int reference); + + public static void lua_unref(IntPtr L, int reference) + { + luaL_unref(L,LuaIndexes.LUA_REGISTRYINDEX,reference); + } + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern bool lua_isstring(IntPtr L, int index); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool lua_isinteger(IntPtr L, int index); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_pushnil(IntPtr L); + + public static void lua_pushstdcallcfunction(IntPtr L, lua_CSFunction function, int n = 0)//[-0, +1, m] + { +#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR) + GCHandle.Alloc(function); +#endif + IntPtr fn = Marshal.GetFunctionPointerForDelegate(function); + xlua_push_csharp_function(L, fn, n); + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_upvalueindex(int n); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int lua_pcall(IntPtr L, int nArgs, int nResults, int errfunc); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern double lua_tonumber(IntPtr L, int index); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_tointeger(IntPtr L, int index); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern uint xlua_touint(IntPtr L, int index); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern bool lua_toboolean(IntPtr L, int index); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_topointer(IntPtr L, int index); + + [DllImport(LUADLL,CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_tolstring(IntPtr L, int index, out IntPtr strLen);//[-0, +0, m] + + public static string lua_tostring(IntPtr L, int index) + { + IntPtr strlen; + + IntPtr str = lua_tolstring(L, index, out strlen); + if (str != IntPtr.Zero) + { +#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR) + int len = strlen.ToInt32(); + byte[] buffer = new byte[len]; + Marshal.Copy(str, buffer, 0, len); + return Encoding.UTF8.GetString(buffer); +#else + string ret = Marshal.PtrToStringAnsi(str, strlen.ToInt32()); + if (ret == null) + { + int len = strlen.ToInt32(); + byte[] buffer = new byte[len]; + Marshal.Copy(str, buffer, 0, len); + return Encoding.UTF8.GetString(buffer); + } + return ret; +#endif + } + else + { + return null; + } + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_atpanic(IntPtr L, lua_CSFunction panicf); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_pushnumber(IntPtr L, double number); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_pushboolean(IntPtr L, bool value); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_pushinteger(IntPtr L, int value); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_pushuint(IntPtr L, uint value); + +#if NATIVE_LUA_PUSHSTRING + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_pushstring(IntPtr L, string str); +#else + public static void lua_pushstring(IntPtr L, string str) //业务使用 + { + if (str == null) + { + lua_pushnil(L); + } + else + { +#if !THREAD_SAFE && !HOTFIX_ENABLE + if (Encoding.UTF8.GetByteCount(str) > InternalGlobals.strBuff.Length) + { + byte[] bytes = Encoding.UTF8.GetBytes(str); + xlua_pushlstring(L, bytes, bytes.Length); + } + else + { + int bytes_len = Encoding.UTF8.GetBytes(str, 0, str.Length, InternalGlobals.strBuff, 0); + xlua_pushlstring(L, InternalGlobals.strBuff, bytes_len); + } +#else + var bytes = Encoding.UTF8.GetBytes(str); + xlua_pushlstring(L, bytes, bytes.Length); +#endif + } + } +#endif + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_pushlstring(IntPtr L, byte[] str, int size); + + public static void xlua_pushasciistring(IntPtr L, string str) // for inner use only + { + if (str == null) + { + lua_pushnil(L); + } + else + { +#if NATIVE_LUA_PUSHSTRING + lua_pushstring(L, str); +#else +#if !THREAD_SAFE && !HOTFIX_ENABLE + int str_len = str.Length; + if (InternalGlobals.strBuff.Length < str_len) + { + InternalGlobals.strBuff = new byte[str_len]; + } + + int bytes_len = Encoding.UTF8.GetBytes(str, 0, str_len, InternalGlobals.strBuff, 0); + xlua_pushlstring(L, InternalGlobals.strBuff, bytes_len); +#else + var bytes = Encoding.UTF8.GetBytes(str); + xlua_pushlstring(L, bytes, bytes.Length); +#endif +#endif + } + } + + public static void lua_pushstring(IntPtr L, byte[] str) + { + if (str == null) + { + lua_pushnil(L); + } + else + { + xlua_pushlstring(L, str, str.Length); + } + } + + public static byte[] lua_tobytes(IntPtr L, int index)//[-0, +0, m] + { + if (lua_type(L, index) == LuaTypes.LUA_TSTRING) + { + IntPtr strlen; + IntPtr str = lua_tolstring(L, index, out strlen); + if (str != IntPtr.Zero) + { + int buff_len = strlen.ToInt32(); + byte[] buffer = new byte[buff_len]; + Marshal.Copy(str, buffer, 0, buff_len); + return buffer; + } + } + return null; + } + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int luaL_newmetatable(IntPtr L, string meta);//[-0, +1, m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_pgettable(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_psettable(IntPtr L, int idx); + + public static void luaL_getmetatable(IntPtr L, string meta) + { + xlua_pushasciistring(L, meta); + lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xluaL_loadbuffer(IntPtr L, byte[] buff, int size, string name); + + public static int luaL_loadbuffer(IntPtr L, string buff, string name)//[-0, +1, m] + { + byte[] bytes = Encoding.UTF8.GetBytes(buff); + return xluaL_loadbuffer(L, bytes, bytes.Length, name); + } + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int xlua_tocsobj_safe(IntPtr L,int obj);//[-0, +0, m] + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int xlua_tocsobj_fast(IntPtr L,int obj); + + public static int lua_error(IntPtr L) + { + xlua_csharp_error(L); + return 0; + } + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool lua_checkstack(IntPtr L,int extra);//[-0, +0, m] + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern int lua_next(IntPtr L,int index);//[-1, +(2|0), e] + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void lua_pushlightuserdata(IntPtr L, IntPtr udata); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern IntPtr xlua_tag(); + + [DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)] + public static extern void luaL_where (IntPtr L, int level);//[-0, +1, m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_tryget_cachedud(IntPtr L, int key, int cache_ref); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_pushcsobj(IntPtr L, int key, int meta_ref, bool need_cache, int cache_ref);//[-0, +1, m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m] + public static extern int gen_obj_indexer(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m] + public static extern int gen_obj_newindexer(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m] + public static extern int gen_cls_indexer(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m] + public static extern int gen_cls_newindexer(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m] + public static extern int get_error_func_ref(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m] + public static extern int load_error_func(IntPtr L, int Ref); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int luaopen_i64lib(IntPtr L);//[,,m] + +#if (!UNITY_SWITCH && !UNITY_WEBGL) || UNITY_EDITOR + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int luaopen_socket_core(IntPtr L);//[,,m] +#endif + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_pushint64(IntPtr L, long n);//[,,m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void lua_pushuint64(IntPtr L, ulong n);//[,,m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool lua_isint64(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool lua_isuint64(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern long lua_toint64(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern ulong lua_touint64(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_push_csharp_function(IntPtr L, IntPtr fn, int n);//[-0,+1,m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_csharp_str_error(IntPtr L, string message);//[-0,+1,m] + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[-0,+0,m] + public static extern int xlua_csharp_error(IntPtr L); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_int8_t(IntPtr buff, int offset, byte field); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_int8_t(IntPtr buff, int offset, out byte field); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_int16_t(IntPtr buff, int offset, short field); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_int16_t(IntPtr buff, int offset, out short field); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_int32_t(IntPtr buff, int offset, int field); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_int32_t(IntPtr buff, int offset, out int field); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_int64_t(IntPtr buff, int offset, long field); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_int64_t(IntPtr buff, int offset, out long field); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_float(IntPtr buff, int offset, float field); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_float(IntPtr buff, int offset, out float field); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_double(IntPtr buff, int offset, double field); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_double(IntPtr buff, int offset, out double field); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr xlua_pushstruct(IntPtr L, uint size, int meta_ref); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_pushcstable(IntPtr L, uint field_count, int meta_ref); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr lua_touserdata(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_gettypeid(IntPtr L, int idx); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_get_registry_index(); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_pgettable_bypath(IntPtr L, int idx, string path); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern int xlua_psettable_bypath(IntPtr L, int idx, string path); + + //[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + //public static extern void xlua_pushbuffer(IntPtr L, byte[] buff); + + //对于Unity,仅浮点组成的struct较多,这几个api用于优化这类struct + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_float2(IntPtr buff, int offset, float f1, float f2); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_float2(IntPtr buff, int offset, out float f1, out float f2); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_float3(IntPtr buff, int offset, float f1, float f2, float f3); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_float3(IntPtr buff, int offset, out float f1, out float f2, out float f3); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_float4(IntPtr buff, int offset, float f1, float f2, float f3, float f4); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_float4(IntPtr buff, int offset, out float f1, out float f2, out float f3, out float f4); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_float5(IntPtr buff, int offset, float f1, float f2, float f3, float f4, float f5); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_float5(IntPtr buff, int offset, out float f1, out float f2, out float f3, out float f4, out float f5); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_float6(IntPtr buff, int offset, float f1, float f2, float f3, float f4, float f5, float f6); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_float6(IntPtr buff, int offset, out float f1, out float f2, out float f3, out float f4, out float f5, out float f6); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_pack_decimal(IntPtr buff, int offset, ref decimal dec); + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_unpack_decimal(IntPtr buff, int offset, out byte scale, out byte sign, out int hi32, out ulong lo64); + + public static bool xlua_is_eq_str(IntPtr L, int index, string str) + { + return xlua_is_eq_str(L, index, str, str.Length); + } + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern bool xlua_is_eq_str(IntPtr L, int index, string str, int str_len); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern IntPtr xlua_gl(IntPtr L); + +#if GEN_CODE_MINIMIZE + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_set_csharp_wrapper_caller(IntPtr wrapper); + + [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] + public static extern void xlua_push_csharp_wrapper(IntPtr L, int wrapperID); + + public static void xlua_set_csharp_wrapper_caller(CSharpWrapperCaller wrapper_caller) + { +#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR) + GCHandle.Alloc(wrapper); +#endif + xlua_set_csharp_wrapper_caller(Marshal.GetFunctionPointerForDelegate(wrapper_caller)); + } +#endif + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaDLL.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaDLL.cs.meta new file mode 100644 index 0000000..76da50a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaDLL.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cb215be11dcf02b43855782fa20fc921 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaEnv.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaEnv.cs new file mode 100644 index 0000000..cdadb26 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaEnv.cs @@ -0,0 +1,747 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + + +namespace XLua +{ + using System; + using System.Collections.Generic; + + public class LuaEnv : IDisposable + { + public const string CSHARP_NAMESPACE = "xlua_csharp_namespace"; + public const string MAIN_SHREAD = "xlua_main_thread"; + + internal RealStatePtr rawL; + + internal RealStatePtr L + { + get + { + if (rawL == RealStatePtr.Zero) + { + throw new InvalidOperationException("this lua env had disposed!"); + } + return rawL; + } + } + + private LuaTable _G; + + internal ObjectTranslator translator; + + internal int errorFuncRef = -1; + +#if THREAD_SAFE || HOTFIX_ENABLE + internal /*static*/ object luaLock = new object(); + + internal object luaEnvLock + { + get + { + return luaLock; + } + } +#endif + + const int LIB_VERSION_EXPECT = 105; + + public LuaEnv() + { + if (LuaAPI.xlua_get_lib_version() != LIB_VERSION_EXPECT) + { + throw new InvalidProgramException("wrong lib version expect:" + + LIB_VERSION_EXPECT + " but got:" + LuaAPI.xlua_get_lib_version()); + } + +#if THREAD_SAFE || HOTFIX_ENABLE + lock(luaEnvLock) +#endif + { + LuaIndexes.LUA_REGISTRYINDEX = LuaAPI.xlua_get_registry_index(); +#if GEN_CODE_MINIMIZE + LuaAPI.xlua_set_csharp_wrapper_caller(InternalGlobals.CSharpWrapperCallerPtr); +#endif + // Create State + rawL = LuaAPI.luaL_newstate(); + + //Init Base Libs + LuaAPI.luaopen_xlua(rawL); + LuaAPI.luaopen_i64lib(rawL); + + translator = new ObjectTranslator(this, rawL); + translator.createFunctionMetatable(rawL); + translator.OpenLib(rawL); + ObjectTranslatorPool.Instance.Add(rawL, translator); + + LuaAPI.lua_atpanic(rawL, StaticLuaCallbacks.Panic); + +#if !XLUA_GENERAL + LuaAPI.lua_pushstdcallcfunction(rawL, StaticLuaCallbacks.Print); + if (0 != LuaAPI.xlua_setglobal(rawL, "print")) + { + throw new Exception("call xlua_setglobal fail!"); + } +#endif + + //template engine lib register + TemplateEngine.LuaTemplate.OpenLib(rawL); + + AddSearcher(StaticLuaCallbacks.LoadBuiltinLib, 2); // just after the preload searcher + AddSearcher(StaticLuaCallbacks.LoadFromCustomLoaders, 3); +#if !XLUA_GENERAL + AddSearcher(StaticLuaCallbacks.LoadFromResource, 4); + AddSearcher(StaticLuaCallbacks.LoadFromStreamingAssetsPath, -1); +#endif + DoString(init_xlua, "Init"); + init_xlua = null; + +#if (!UNITY_SWITCH && !UNITY_WEBGL) || UNITY_EDITOR + AddBuildin("socket.core", StaticLuaCallbacks.LoadSocketCore); + AddBuildin("socket", StaticLuaCallbacks.LoadSocketCore); +#endif + + AddBuildin("CS", StaticLuaCallbacks.LoadCS); + + LuaAPI.lua_newtable(rawL); //metatable of indexs and newindexs functions + LuaAPI.xlua_pushasciistring(rawL, "__index"); + LuaAPI.lua_pushstdcallcfunction(rawL, StaticLuaCallbacks.MetaFuncIndex); + LuaAPI.lua_rawset(rawL, -3); + + LuaAPI.xlua_pushasciistring(rawL, Utils.LuaIndexsFieldName); + LuaAPI.lua_newtable(rawL); + LuaAPI.lua_pushvalue(rawL, -3); + LuaAPI.lua_setmetatable(rawL, -2); + LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX); + + LuaAPI.xlua_pushasciistring(rawL, Utils.LuaNewIndexsFieldName); + LuaAPI.lua_newtable(rawL); + LuaAPI.lua_pushvalue(rawL, -3); + LuaAPI.lua_setmetatable(rawL, -2); + LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX); + + LuaAPI.xlua_pushasciistring(rawL, Utils.LuaClassIndexsFieldName); + LuaAPI.lua_newtable(rawL); + LuaAPI.lua_pushvalue(rawL, -3); + LuaAPI.lua_setmetatable(rawL, -2); + LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX); + + LuaAPI.xlua_pushasciistring(rawL, Utils.LuaClassNewIndexsFieldName); + LuaAPI.lua_newtable(rawL); + LuaAPI.lua_pushvalue(rawL, -3); + LuaAPI.lua_setmetatable(rawL, -2); + LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX); + + LuaAPI.lua_pop(rawL, 1); // pop metatable of indexs and newindexs functions + + LuaAPI.xlua_pushasciistring(rawL, MAIN_SHREAD); + LuaAPI.lua_pushthread(rawL); + LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX); + + LuaAPI.xlua_pushasciistring(rawL, CSHARP_NAMESPACE); + if (0 != LuaAPI.xlua_getglobal(rawL, "CS")) + { + throw new Exception("get CS fail!"); + } + LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX); + +#if !XLUA_GENERAL && (!UNITY_WSA || UNITY_EDITOR) + translator.Alias(typeof(Type), "System.MonoType"); +#endif + + if (0 != LuaAPI.xlua_getglobal(rawL, "_G")) + { + throw new Exception("get _G fail!"); + } + translator.Get(rawL, -1, out _G); + LuaAPI.lua_pop(rawL, 1); + + errorFuncRef = LuaAPI.get_error_func_ref(rawL); + + if (initers != null) + { + for (int i = 0; i < initers.Count; i++) + { + initers[i](this, translator); + } + } + + translator.CreateArrayMetatable(rawL); + translator.CreateDelegateMetatable(rawL); + translator.CreateEnumerablePairs(rawL); + } + } + + private static List> initers = null; + + public static void AddIniter(Action initer) + { + if (initers == null) + { + initers = new List>(); + } + initers.Add(initer); + } + + public LuaTable Global + { + get + { + return _G; + } + } + + public T LoadString(byte[] chunk, string chunkName = "chunk", LuaTable env = null) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + if (typeof(T) != typeof(LuaFunction) && !typeof(T).IsSubclassOf(typeof(Delegate))) + { + throw new InvalidOperationException(typeof(T).Name + " is not a delegate type nor LuaFunction"); + } + var _L = L; + int oldTop = LuaAPI.lua_gettop(_L); + + if (LuaAPI.xluaL_loadbuffer(_L, chunk, chunk.Length, chunkName) != 0) + ThrowExceptionFromError(oldTop); + + if (env != null) + { + env.push(_L); + LuaAPI.lua_setfenv(_L, -2); + } + + T result = (T)translator.GetObject(_L, -1, typeof(T)); + LuaAPI.lua_settop(_L, oldTop); + + return result; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public T LoadString(string chunk, string chunkName = "chunk", LuaTable env = null) + { + byte[] bytes = System.Text.Encoding.UTF8.GetBytes(chunk); + return LoadString(bytes, chunkName, env); + } + + public LuaFunction LoadString(string chunk, string chunkName = "chunk", LuaTable env = null) + { + return LoadString(chunk, chunkName, env); + } + + public object[] DoString(byte[] chunk, string chunkName = "chunk", LuaTable env = null) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + var _L = L; + int oldTop = LuaAPI.lua_gettop(_L); + int errFunc = LuaAPI.load_error_func(_L, errorFuncRef); + if (LuaAPI.xluaL_loadbuffer(_L, chunk, chunk.Length, chunkName) == 0) + { + if (env != null) + { + env.push(_L); + LuaAPI.lua_setfenv(_L, -2); + } + + if (LuaAPI.lua_pcall(_L, 0, -1, errFunc) == 0) + { + LuaAPI.lua_remove(_L, errFunc); + return translator.popValues(_L, oldTop); + } + else + ThrowExceptionFromError(oldTop); + } + else + ThrowExceptionFromError(oldTop); + + return null; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public object[] DoString(string chunk, string chunkName = "chunk", LuaTable env = null) + { + byte[] bytes = System.Text.Encoding.UTF8.GetBytes(chunk); + return DoString(bytes, chunkName, env); + } + + private void AddSearcher(LuaCSFunction searcher, int index) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + var _L = L; + //insert the loader + LuaAPI.xlua_getloaders(_L); + if (!LuaAPI.lua_istable(_L, -1)) + { + throw new Exception("Can not set searcher!"); + } + uint len = LuaAPI.xlua_objlen(_L, -1); + index = index < 0 ? (int)(len + index + 2) : index; + for (int e = (int)len + 1; e > index; e--) + { + LuaAPI.xlua_rawgeti(_L, -1, e - 1); + LuaAPI.xlua_rawseti(_L, -2, e); + } + LuaAPI.lua_pushstdcallcfunction(_L, searcher); + LuaAPI.xlua_rawseti(_L, -2, index); + LuaAPI.lua_pop(_L, 1); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void Alias(Type type, string alias) + { + translator.Alias(type, alias); + } + +#if !XLUA_GENERAL + int last_check_point = 0; + + int max_check_per_tick = 20; + + static bool ObjectValidCheck(object obj) + { + return (!(obj is UnityEngine.Object)) || ((obj as UnityEngine.Object) != null); + } + + Func object_valid_checker = new Func(ObjectValidCheck); +#endif + + public void Tick() + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + var _L = L; + lock (refQueue) + { + while (refQueue.Count > 0) + { + GCAction gca = refQueue.Dequeue(); + translator.ReleaseLuaBase(_L, gca.Reference, gca.IsDelegate); + } + } +#if !XLUA_GENERAL + last_check_point = translator.objects.Check(last_check_point, max_check_per_tick, object_valid_checker, translator.reverseMap); +#endif +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + //API + public void GC() + { + Tick(); + } + + public LuaTable NewTable() + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + var _L = L; + int oldTop = LuaAPI.lua_gettop(_L); + + LuaAPI.lua_newtable(_L); + LuaTable returnVal = (LuaTable)translator.GetObject(_L, -1, typeof(LuaTable)); + + LuaAPI.lua_settop(_L, oldTop); + return returnVal; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + private bool disposed = false; + + public void Dispose() + { + FullGc(); + System.GC.Collect(); + System.GC.WaitForPendingFinalizers(); + + Dispose(true); + + System.GC.Collect(); + System.GC.WaitForPendingFinalizers(); + } + + public virtual void Dispose(bool dispose) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + if (disposed) return; + Tick(); + + if (!translator.AllDelegateBridgeReleased()) + { + throw new InvalidOperationException("try to dispose a LuaEnv with C# callback!"); + } + + ObjectTranslatorPool.Instance.Remove(L); + + LuaAPI.lua_close(L); + translator = null; + + rawL = IntPtr.Zero; + + disposed = true; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void ThrowExceptionFromError(int oldTop) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + object err = translator.GetObject(L, -1); + LuaAPI.lua_settop(L, oldTop); + + // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved) + Exception ex = err as Exception; + if (ex != null) throw ex; + + // A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it + if (err == null) err = "Unknown Lua Error"; + throw new LuaException(err.ToString()); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + internal struct GCAction + { + public int Reference; + public bool IsDelegate; + } + + Queue refQueue = new Queue(); + + internal void equeueGCAction(GCAction action) + { + lock (refQueue) + { + refQueue.Enqueue(action); + } + } + + private string init_xlua = @" + local metatable = {} + local rawget = rawget + local setmetatable = setmetatable + local import_type = xlua.import_type + local import_generic_type = xlua.import_generic_type + local load_assembly = xlua.load_assembly + + function metatable:__index(key) + local fqn = rawget(self,'.fqn') + fqn = ((fqn and fqn .. '.') or '') .. key + + local obj = import_type(fqn) + + if obj == nil then + -- It might be an assembly, so we load it too. + obj = { ['.fqn'] = fqn } + setmetatable(obj, metatable) + elseif obj == true then + return rawget(self, key) + end + + -- Cache this lookup + rawset(self, key, obj) + return obj + end + + function metatable:__newindex() + error('No such type: ' .. rawget(self,'.fqn'), 2) + end + + -- A non-type has been called; e.g. foo = System.Foo() + function metatable:__call(...) + local n = select('#', ...) + local fqn = rawget(self,'.fqn') + if n > 0 then + local gt = import_generic_type(fqn, ...) + if gt then + return rawget(CS, gt) + end + end + error('No such type: ' .. fqn, 2) + end + + CS = CS or {} + setmetatable(CS, metatable) + + typeof = function(t) return t.UnderlyingSystemType end + cast = xlua.cast + if not setfenv or not getfenv then + local function getfunction(level) + local info = debug.getinfo(level + 1, 'f') + return info and info.func + end + + function setfenv(fn, env) + if type(fn) == 'number' then fn = getfunction(fn + 1) end + local i = 1 + while true do + local name = debug.getupvalue(fn, i) + if name == '_ENV' then + debug.upvaluejoin(fn, i, (function() + return env + end), 1) + break + elseif not name then + break + end + + i = i + 1 + end + + return fn + end + + function getfenv(fn) + if type(fn) == 'number' then fn = getfunction(fn + 1) end + local i = 1 + while true do + local name, val = debug.getupvalue(fn, i) + if name == '_ENV' then + return val + elseif not name then + break + end + i = i + 1 + end + end + end + + xlua.hotfix = function(cs, field, func) + if func == nil then func = false end + local tbl = (type(field) == 'table') and field or {[field] = func} + for k, v in pairs(tbl) do + local cflag = '' + if k == '.ctor' then + cflag = '_c' + k = 'ctor' + end + local f = type(v) == 'function' and v or nil + xlua.access(cs, cflag .. '__Hotfix0_'..k, f) -- at least one + pcall(function() + for i = 1, 99 do + xlua.access(cs, cflag .. '__Hotfix'..i..'_'..k, f) + end + end) + end + xlua.private_accessible(cs) + end + xlua.getmetatable = function(cs) + return xlua.metatable_operation(cs) + end + xlua.setmetatable = function(cs, mt) + return xlua.metatable_operation(cs, mt) + end + xlua.setclass = function(parent, name, impl) + impl.UnderlyingSystemType = parent[name].UnderlyingSystemType + rawset(parent, name, impl) + end + + local base_mt = { + __index = function(t, k) + local csobj = t['__csobj'] + local func = csobj['<>xLuaBaseProxy_'..k] + return function(_, ...) + return func(csobj, ...) + end + end + } + base = function(csobj) + return setmetatable({__csobj = csobj}, base_mt) + end + "; + + public delegate byte[] CustomLoader(ref string filepath); + + internal List customLoaders = new List(); + + //loader : CustomLoader filepathrefͣrequireIJҪֵ֧ԣҪʵ· + // ֵnullظԴ޺ʵļ򷵻UTF8byte[] + public void AddLoader(CustomLoader loader) + { + customLoaders.Add(loader); + } + + internal Dictionary buildin_initer = new Dictionary(); + + public void AddBuildin(string name, LuaCSFunction initer) + { + if (!Utils.IsStaticPInvokeCSFunction(initer)) + { + throw new Exception("initer must be static and has MonoPInvokeCallback Attribute!"); + } + buildin_initer.Add(name, initer); + } + + //The garbage-collector pause controls how long the collector waits before starting a new cycle. + //Larger values make the collector less aggressive. Values smaller than 100 mean the collector + //will not wait to start a new cycle. A value of 200 means that the collector waits for the total + //memory in use to double before starting a new cycle. + public int GcPause + { + get + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + int val = LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, 200); + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, val); + return val; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + set + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, value); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + } + + //The step multiplier controls the relative speed of the collector relative to memory allocation. + //Larger values make the collector more aggressive but also increase the size of each incremental + //step. Values smaller than 100 make the collector too slow and can result in the collector never + //finishing a cycle. The default, 200, means that the collector runs at "twice" the speed of memory + //allocation. + public int GcStepmul + { + get + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + int val = LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, 200); + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, val); + return val; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + set + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, value); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + } + + public void FullGc() + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCCOLLECT, 0); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void StopGc() + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSTOP, 0); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void RestartGc() + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCRESTART, 0); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public bool GcStep(int data) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + return LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSTEP, data) != 0; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public int Memroy + { + get + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnvLock) + { +#endif + return LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCCOUNT, 0); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaEnv.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaEnv.cs.meta new file mode 100644 index 0000000..d419280 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaEnv.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 324ace1419c9a5741a8b4419244d9955 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaException.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaException.cs new file mode 100644 index 0000000..819a6bb --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaException.cs @@ -0,0 +1,19 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +using System; + +namespace XLua +{ + [Serializable] + public class LuaException : Exception + { + public LuaException(string message) : base(message) + {} + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaException.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaException.cs.meta new file mode 100644 index 0000000..af0ca05 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaException.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6bfec99343cfaa743b38f8258d4e731d +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaFunction.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaFunction.cs new file mode 100644 index 0000000..a89190c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaFunction.cs @@ -0,0 +1,235 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Collections.Generic; + +namespace XLua +{ + public partial class LuaFunction : LuaBase + { + public LuaFunction(int reference, LuaEnv luaenv) : base(reference, luaenv) + { + } + + //Action和Func是方便使用的无gc api,如果需要用到out,ref参数,建议使用delegate + //如果需要其它个数的Action和Func, 这个类声明为partial,可以自己加 + public void Action(T a) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, a); + int error = LuaAPI.lua_pcall(L, 1, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public TResult Func(T a) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, a); + int error = LuaAPI.lua_pcall(L, 1, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try + { + translator.Get(L, -1, out ret); + } + catch (Exception e) + { + throw e; + } + finally + { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void Action(T1 a1, T2 a2) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, a1); + translator.PushByType(L, a2); + int error = LuaAPI.lua_pcall(L, 2, 0, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public TResult Func(T1 a1, T2 a2) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, a1); + translator.PushByType(L, a2); + int error = LuaAPI.lua_pcall(L, 2, 1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + TResult ret; + try + { + translator.Get(L, -1, out ret); + } + catch (Exception e) + { + throw e; + } + finally + { + LuaAPI.lua_settop(L, oldTop); + } + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + //deprecated + public object[] Call(object[] args, Type[] returnTypes) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + int nArgs = 0; + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + + int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef); + LuaAPI.lua_getref(L, luaReference); + if (args != null) + { + nArgs = args.Length; + for (int i = 0; i < args.Length; i++) + { + translator.PushAny(L, args[i]); + } + } + int error = LuaAPI.lua_pcall(L, nArgs, -1, errFunc); + if (error != 0) + luaEnv.ThrowExceptionFromError(oldTop); + + LuaAPI.lua_remove(L, errFunc); + if (returnTypes != null) + return translator.popValues(L, oldTop, returnTypes); + else + return translator.popValues(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + //deprecated + public object[] Call(params object[] args) + { + return Call(args, null); + } + + public T Cast() + { + if (!typeof(T).IsSubclassOf(typeof(Delegate))) + { + throw new InvalidOperationException(typeof(T).Name + " is not a delegate type"); + } +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + push(L); + T ret = (T)translator.GetObject(L, -1, typeof(T)); + LuaAPI.lua_pop(luaEnv.L, 1); + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void SetEnv(LuaTable env) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + push(L); + env.push(L); + LuaAPI.lua_setfenv(L, -2); + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + internal override void push(RealStatePtr L) + { + LuaAPI.lua_getref(L, luaReference); + } + + public override string ToString() + { + return "function :" + luaReference; + } + } + +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaFunction.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaFunction.cs.meta new file mode 100644 index 0000000..b070e00 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaFunction.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9b3c9ca45e262d04eaf9b7ef4eb94d7d +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaTable.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaTable.cs new file mode 100644 index 0000000..6e17c97 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaTable.cs @@ -0,0 +1,378 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace XLua +{ + public partial class LuaTable : LuaBase + { + public LuaTable(int reference, LuaEnv luaenv) : base(reference, luaenv) + { + } + + // no boxing version get + public void Get(TKey key, out TValue value) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, key); + + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + string err = LuaAPI.lua_tostring(L, -1); + LuaAPI.lua_settop(L, oldTop); + throw new Exception("get field [" + key + "] error:" + err); + } + + LuaTypes lua_type = LuaAPI.lua_type(L, -1); + Type type_of_value = typeof(TValue); + if (lua_type == LuaTypes.LUA_TNIL && type_of_value.IsValueType()) + { + throw new InvalidCastException("can not assign nil to " + type_of_value.GetFriendlyName()); + } + + try + { + translator.Get(L, -1, out value); + } + catch (Exception e) + { + throw e; + } + finally + { + LuaAPI.lua_settop(L, oldTop); + } +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + // no boxing version get + public bool ContainsKey(TKey key) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, key); + + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + string err = LuaAPI.lua_tostring(L, -1); + LuaAPI.lua_settop(L, oldTop); + throw new Exception("get field [" + key + "] error:" + err); + } + + bool ret = LuaAPI.lua_type(L, -1) != LuaTypes.LUA_TNIL; + + LuaAPI.lua_settop(L, oldTop); + + return ret; + +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + //no boxing version set + public void Set(TKey key, TValue value) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + var translator = luaEnv.translator; + + LuaAPI.lua_getref(L, luaReference); + translator.PushByType(L, key); + translator.PushByType(L, value); + + if (0 != LuaAPI.xlua_psettable(L, -3)) + { + luaEnv.ThrowExceptionFromError(oldTop); + } + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + + public T GetInPath(string path) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + if (0 != LuaAPI.xlua_pgettable_bypath(L, -1, path)) + { + luaEnv.ThrowExceptionFromError(oldTop); + } + LuaTypes lua_type = LuaAPI.lua_type(L, -1); + if (lua_type == LuaTypes.LUA_TNIL && typeof(T).IsValueType()) + { + throw new InvalidCastException("can not assign nil to " + typeof(T).GetFriendlyName()); + } + + T value; + try + { + translator.Get(L, -1, out value); + } + catch (Exception e) + { + throw e; + } + finally + { + LuaAPI.lua_settop(L, oldTop); + } + return value; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public void SetInPath(string path, T val) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + luaEnv.translator.PushByType(L, val); + if (0 != LuaAPI.xlua_psettable_bypath(L, -2, path)) + { + luaEnv.ThrowExceptionFromError(oldTop); + } + + LuaAPI.lua_settop(L, oldTop); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + [Obsolete("use no boxing version: GetInPath/SetInPath Get/Set instead!")] + public object this[string field] + { + get + { + return GetInPath(field); + } + set + { + SetInPath(field, value); + } + } + + [Obsolete("use no boxing version: GetInPath/SetInPath Get/Set instead!")] + public object this[object field] + { + get + { + return Get(field); + } + set + { + Set(field, value); + } + } + + public void ForEach(Action action) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + try + { + LuaAPI.lua_getref(L, luaReference); + LuaAPI.lua_pushnil(L); + while (LuaAPI.lua_next(L, -2) != 0) + { + if (translator.Assignable(L, -2)) + { + TKey key; + TValue val; + translator.Get(L, -2, out key); + translator.Get(L, -1, out val); + action(key, val); + } + LuaAPI.lua_pop(L, 1); + } + } + finally + { + LuaAPI.lua_settop(L, oldTop); + } +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public int Length + { + get + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + var L = luaEnv.L; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + var len = (int)LuaAPI.xlua_objlen(L, -1); + LuaAPI.lua_settop(L, oldTop); + return len; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + } + +#if THREAD_SAFE || HOTFIX_ENABLE + [Obsolete("not thread safe!", true)] +#endif + public IEnumerable GetKeys() + { + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + LuaAPI.lua_pushnil(L); + while (LuaAPI.lua_next(L, -2) != 0) + { + yield return translator.GetObject(L, -2); + LuaAPI.lua_pop(L, 1); + } + LuaAPI.lua_settop(L, oldTop); + } + +#if THREAD_SAFE || HOTFIX_ENABLE + [Obsolete("not thread safe!", true)] +#endif + public IEnumerable GetKeys() + { + var L = luaEnv.L; + var translator = luaEnv.translator; + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.lua_getref(L, luaReference); + LuaAPI.lua_pushnil(L); + while (LuaAPI.lua_next(L, -2) != 0) + { + if (translator.Assignable(L, -2)) + { + T v; + translator.Get(L, -2, out v); + yield return v; + } + LuaAPI.lua_pop(L, 1); + } + LuaAPI.lua_settop(L, oldTop); + } + + [Obsolete("use no boxing version: Get !")] + public T Get(object key) + { + T ret; + Get(key, out ret); + return ret; + } + + public TValue Get(TKey key) + { + TValue ret; + Get(key, out ret); + return ret; + } + + public TValue Get(string key) + { + TValue ret; + Get(key, out ret); + return ret; + } + + public void SetMetaTable(LuaTable metaTable) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + push(luaEnv.L); + metaTable.push(luaEnv.L); + LuaAPI.lua_setmetatable(luaEnv.L, -2); + LuaAPI.lua_pop(luaEnv.L, 1); +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + public T Cast() + { + var L = luaEnv.L; + var translator = luaEnv.translator; +#if THREAD_SAFE || HOTFIX_ENABLE + lock (luaEnv.luaEnvLock) + { +#endif + push(L); + T ret = (T)translator.GetObject(L, -1, typeof(T)); + LuaAPI.lua_pop(luaEnv.L, 1); + return ret; +#if THREAD_SAFE || HOTFIX_ENABLE + } +#endif + } + + internal override void push(RealStatePtr L) + { + LuaAPI.lua_getref(L, luaReference); + } + public override string ToString() + { + return "table :" + luaReference; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaTable.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaTable.cs.meta new file mode 100644 index 0000000..bb62f8d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/LuaTable.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 102ce1734f900d34abe8823fbed6a771 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/MethodWarpsCache.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/MethodWarpsCache.cs new file mode 100644 index 0000000..da0dd88 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/MethodWarpsCache.cs @@ -0,0 +1,583 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System.Collections.Generic; +using System; +using System.Reflection; + +namespace XLua +{ + public class OverloadMethodWrap + { + ObjectTranslator translator; + Type targetType; + MethodBase method; + + ObjectCheck[] checkArray; + ObjectCast[] castArray; + + int[] inPosArray; + int[] outPosArray; + + bool[] isOptionalArray; + + object[] defaultValueArray; + + bool isVoid = true; + + int luaStackPosStart = 1; + + bool targetNeeded = false; + + object[] args; + + int[] refPos; + + Type paramsType = null; + + public bool HasDefalutValue{ get; private set; } + + public OverloadMethodWrap(ObjectTranslator translator, Type targetType, MethodBase method) + { + this.translator = translator; + this.targetType = targetType; + this.method = method; + HasDefalutValue = false; + } + + public void Init(ObjectCheckers objCheckers, ObjectCasters objCasters) + { + if ((typeof(Delegate) != targetType && typeof(Delegate).IsAssignableFrom(targetType)) || + !method.IsStatic || method.IsConstructor) + { + luaStackPosStart = 2; + if (!method.IsConstructor) + { + targetNeeded = true; + } + } + + var paramInfos = method.GetParameters(); + refPos = new int[paramInfos.Length]; + + List inPosList = new List(); + List outPosList = new List(); + + List paramsChecks = new List(); + List paramsCasts = new List(); + List isOptionalList = new List(); + List defaultValueList = new List(); + + for(int i = 0; i < paramInfos.Length; i++) + { + refPos[i] = -1; + if (!paramInfos[i].IsIn && paramInfos[i].IsOut) // out parameter + { + outPosList.Add(i); + } + else + { + if(paramInfos[i].ParameterType.IsByRef) + { + var ttype = paramInfos[i].ParameterType.GetElementType(); + if(CopyByValue.IsStruct(ttype) && ttype != typeof(decimal)) + { + refPos[i] = inPosList.Count; + } + outPosList.Add(i); + } + + inPosList.Add(i); + var paramType = paramInfos[i].IsDefined(typeof(ParamArrayAttribute), false) || (!paramInfos[i].ParameterType.IsArray && paramInfos[i].ParameterType.IsByRef ) ? + paramInfos[i].ParameterType.GetElementType() : paramInfos[i].ParameterType; + paramsChecks.Add (objCheckers.GetChecker(paramType)); + paramsCasts.Add (objCasters.GetCaster(paramType)); + isOptionalList.Add(paramInfos[i].IsOptional); + var defalutValue = paramInfos[i].DefaultValue; + if (paramInfos[i].IsOptional) + { + if (defalutValue != null && defalutValue.GetType() != paramInfos[i].ParameterType) + { + defalutValue = defalutValue.GetType() == typeof(Missing) ? (paramInfos[i].ParameterType.IsValueType() ? Activator.CreateInstance(paramInfos[i].ParameterType) : Missing.Value) + : Convert.ChangeType(defalutValue, paramInfos[i].ParameterType); + } + HasDefalutValue = true; + } + defaultValueList.Add(paramInfos[i].IsOptional ? defalutValue : null); + } + } + checkArray = paramsChecks.ToArray(); + castArray = paramsCasts.ToArray(); + inPosArray = inPosList.ToArray(); + outPosArray = outPosList.ToArray(); + isOptionalArray = isOptionalList.ToArray(); + defaultValueArray = defaultValueList.ToArray(); + + if (paramInfos.Length > 0 && paramInfos[paramInfos.Length - 1].IsDefined(typeof(ParamArrayAttribute), false)) + { + paramsType = paramInfos[paramInfos.Length - 1].ParameterType.GetElementType(); + } + + args = new object[paramInfos.Length]; + + if (method is MethodInfo) //constructor is not MethodInfo? + { + isVoid = (method as MethodInfo).ReturnType == typeof(void); + } + else if(method is ConstructorInfo) + { + isVoid = false; + } + } + + public bool Check(RealStatePtr L) + { + int luaTop = LuaAPI.lua_gettop(L); + int luaStackPos = luaStackPosStart; + + for(int i = 0; i < checkArray.Length; i++) + { + if ((i == (checkArray.Length - 1)) && (paramsType != null)) + { + break; + } + if(luaStackPos > luaTop && !isOptionalArray[i]) + { + return false; + } + else if(luaStackPos <= luaTop && !checkArray[i](L, luaStackPos)) + { + return false; + } + + if (luaStackPos <= luaTop || !isOptionalArray[i]) + { + luaStackPos++; + } + } + + return paramsType != null ? (luaStackPos < luaTop + 1 ? + checkArray[checkArray.Length - 1](L, luaStackPos) : true) : luaStackPos == luaTop + 1; + } + + public int Call(RealStatePtr L) + { + try + { +#if UNITY_EDITOR && !DISABLE_OBSOLETE_WARNING + if (method.IsDefined(typeof(ObsoleteAttribute), true)) + { + ObsoleteAttribute info = Attribute.GetCustomAttribute(method, typeof(ObsoleteAttribute)) as ObsoleteAttribute; + UnityEngine.Debug.LogWarning("Obsolete Method [" + method.DeclaringType.ToString() + "." + method.Name + "]: " + info.Message); + } +#endif + object target = null; + MethodBase toInvoke = method; + + if (luaStackPosStart > 1) + { + target = translator.FastGetCSObj(L, 1); + if (target is Delegate) + { + Delegate delegateInvoke = (Delegate)target; +#if UNITY_WSA && !UNITY_EDITOR + toInvoke = delegateInvoke.GetMethodInfo(); +#else + toInvoke = delegateInvoke.Method; +#endif + } + } + + + int luaTop = LuaAPI.lua_gettop(L); + int luaStackPos = luaStackPosStart; + + for (int i = 0; i < castArray.Length; i++) + { + //UnityEngine.Debug.Log("inPos:" + inPosArray[i]); + if (luaStackPos > luaTop) //after check + { + if (paramsType != null && i == castArray.Length - 1) + { + args[inPosArray[i]] = Array.CreateInstance(paramsType, 0); + } + else + { + args[inPosArray[i]] = defaultValueArray[i]; + } + } + else + { + if (paramsType != null && i == castArray.Length - 1) + { + args[inPosArray[i]] = translator.GetParams(L, luaStackPos, paramsType); + } + else + { + args[inPosArray[i]] = castArray[i](L, luaStackPos, null); + } + luaStackPos++; + } + //UnityEngine.Debug.Log("value:" + args[inPosArray[i]]); + } + + object ret = null; + + + ret = toInvoke.IsConstructor ? ((ConstructorInfo)method).Invoke(args) : method.Invoke(targetNeeded ? target : null, args); + + if (targetNeeded && targetType.IsValueType()) + { + translator.Update(L, 1, target); + } + + int nRet = 0; + + if (!isVoid) + { + //UnityEngine.Debug.Log(toInvoke.ToString() + " ret:" + ret); + translator.PushAny(L, ret); + nRet++; + } + + for (int i = 0; i < outPosArray.Length; i++) + { + if (refPos[outPosArray[i]] != -1) + { + translator.Update(L, luaStackPosStart + refPos[outPosArray[i]], args[outPosArray[i]]); + } + translator.PushAny(L, args[outPosArray[i]]); + nRet++; + } + + return nRet; + } + finally + { + for(int i = 0; i < args.Length; i++) + { + args[i] = null; + } + } + } + } + + public class MethodWrap + { + private string methodName; + private List overloads = new List(); + private bool forceCheck; + + public MethodWrap(string methodName, List overloads, bool forceCheck) + { + this.methodName = methodName; + this.overloads = overloads; + this.forceCheck = forceCheck; + } + + public int Call(RealStatePtr L) + { + try + { + if (overloads.Count == 1 && !overloads[0].HasDefalutValue && !forceCheck) return overloads[0].Call(L); + + for (int i = 0; i < overloads.Count; ++i) + { + var overload = overloads[i]; + if (overload.Check(L)) + { + return overload.Call(L); + } + } + return LuaAPI.luaL_error(L, "invalid arguments to " + methodName); + } + catch (System.Reflection.TargetInvocationException e) + { + return LuaAPI.luaL_error(L, "c# exception:" + e.InnerException.Message + ",stack:" + e.InnerException.StackTrace); + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace); + } + } + } + + public class MethodWrapsCache + { + ObjectTranslator translator; + ObjectCheckers objCheckers; + ObjectCasters objCasters; + + Dictionary constructorCache = new Dictionary(); + Dictionary> methodsCache = new Dictionary>(); + Dictionary delegateCache = new Dictionary(); + + public MethodWrapsCache(ObjectTranslator translator, ObjectCheckers objCheckers, ObjectCasters objCasters) + { + this.translator = translator; + this.objCheckers = objCheckers; + this.objCasters = objCasters; + } + + public LuaCSFunction GetConstructorWrap(Type type) + { + //UnityEngine.Debug.LogWarning("GetConstructor:" + type); + if (!constructorCache.ContainsKey(type)) + { + var constructors = type.GetConstructors(); + if (type.IsAbstract() || constructors == null || constructors.Length == 0) + { + if (type.IsValueType()) + { + constructorCache[type] = (L) => + { + translator.PushAny(L, Activator.CreateInstance(type)); + return 1; + }; + } + else + { + return null; + } + } + else + { + LuaCSFunction ctor = _GenMethodWrap(type, ".ctor", constructors, true).Call; + + if (type.IsValueType()) + { + bool hasZeroParamsCtor = false; + for (int i = 0; i < constructors.Length; i++) + { + if (constructors[i].GetParameters().Length == 0) + { + hasZeroParamsCtor = true; + break; + } + } + if (hasZeroParamsCtor) + { + constructorCache[type] = ctor; + } + else + { + constructorCache[type] = (L) => + { + if (LuaAPI.lua_gettop(L) == 1) + { + translator.PushAny(L, Activator.CreateInstance(type)); + return 1; + } + else + { + return ctor(L); + } + }; + } + } + else + { + constructorCache[type] = ctor; + } + } + } + return constructorCache[type]; + } + + public LuaCSFunction GetMethodWrap(Type type, string methodName) + { + //UnityEngine.Debug.LogWarning("GetMethodWrap:" + type + " " + methodName); + if (!methodsCache.ContainsKey(type)) + { + methodsCache[type] = new Dictionary(); + } + var methodsOfType = methodsCache[type]; + if (!methodsOfType.ContainsKey(methodName)) + { + MemberInfo[] methods = type.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase); + if (methods == null || methods.Length == 0 || +#if UNITY_WSA && !UNITY_EDITOR + methods[0] is MethodBase +#else + methods[0].MemberType != MemberTypes.Method +#endif + ) + { + return null; + } + methodsOfType[methodName] = _GenMethodWrap(type, methodName, methods).Call; + } + return methodsOfType[methodName]; + } + + public LuaCSFunction GetMethodWrapInCache(Type type, string methodName) + { + //string retriKey = type.ToString() + "." + methodName; + //return methodsCache.ContainsKey(retriKey) ? methodsCache[retriKey] : null; + if (!methodsCache.ContainsKey(type)) + { + methodsCache[type] = new Dictionary(); + } + var methodsOfType = methodsCache[type]; + return methodsOfType.ContainsKey(methodName) ? methodsOfType[methodName] : null; + } + + public LuaCSFunction GetDelegateWrap(Type type) + { + //UnityEngine.Debug.LogWarning("GetDelegateWrap:" + type ); + if (!typeof(Delegate).IsAssignableFrom(type)) + { + return null; + } + if (!delegateCache.ContainsKey(type)) + { + delegateCache[type] = _GenMethodWrap(type, type.ToString(), new MethodBase[] { type.GetMethod("Invoke") }).Call; + } + return delegateCache[type]; + } + + public LuaCSFunction GetEventWrap(Type type, string eventName) + { + if (!methodsCache.ContainsKey(type)) + { + methodsCache[type] = new Dictionary(); + } + + var methodsOfType = methodsCache[type]; + if (!methodsOfType.ContainsKey(eventName)) + { + { + EventInfo eventInfo = type.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic); + if (eventInfo == null) + { + throw new Exception(type.Name + " has no event named: " + eventName); + } + int start_idx = 0; + + MethodInfo add = eventInfo.GetAddMethod(true); + MethodInfo remove = eventInfo.GetRemoveMethod(true); + + if (add == null && remove == null) + { + throw new Exception(type.Name + "'s " + eventName + " has either add nor remove"); + } + + bool is_static = add != null ? add.IsStatic : remove.IsStatic; + if (!is_static) start_idx = 1; + + methodsOfType[eventName] = (L) => + { + object obj = null; + + if (!is_static) + { + obj = translator.GetObject(L, 1, type); + if (obj == null) + { + return LuaAPI.luaL_error(L, "invalid #1, needed:" + type); + } + } + + try + { + object handlerDelegate = translator.CreateDelegateBridge(L, eventInfo.EventHandlerType, start_idx + 2); + if (handlerDelegate == null) + { + return LuaAPI.luaL_error(L, "invalid #" + (start_idx + 2) + ", needed:" + eventInfo.EventHandlerType); + } + switch (LuaAPI.lua_tostring(L, start_idx + 1)) + { + case "+": + if (add == null) + { + return LuaAPI.luaL_error(L, "no add for event " + eventName); + } + add.Invoke(obj, new object[] { handlerDelegate }); + break; + case "-": + if (remove == null) + { + return LuaAPI.luaL_error(L, "no remove for event " + eventName); + } + remove.Invoke(obj, new object[] { handlerDelegate }); + break; + default: + return LuaAPI.luaL_error(L, "invalid #" + (start_idx + 1) + ", needed: '+' or '-'" + eventInfo.EventHandlerType); + } + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception:" + e + ",stack:" + e.StackTrace); + } + + return 0; + }; + } + } + return methodsOfType[eventName]; + } + + public MethodWrap _GenMethodWrap(Type type, string methodName, IEnumerable methodBases, bool forceCheck = false) + { + List overloads = new List(); + foreach(var methodBase in methodBases) + { + var mb = methodBase as MethodBase; + if (mb == null) + continue; + + if (mb.IsGenericMethodDefinition +#if !ENABLE_IL2CPP + && !tryMakeGenericMethod(ref mb) +#endif + ) + continue; + + var overload = new OverloadMethodWrap(translator, type, mb); + overload.Init(objCheckers, objCasters); + overloads.Add(overload); + } + return new MethodWrap(methodName, overloads, forceCheck); + } + + private static bool tryMakeGenericMethod(ref MethodBase method) + { + try + { + if (!(method is MethodInfo) || !Utils.IsSupportedMethod(method as MethodInfo) ) + { + return false; + } + var genericArguments = method.GetGenericArguments(); + var constraintedArgumentTypes = new Type[genericArguments.Length]; + for (var i = 0; i < genericArguments.Length; i++) + { + var argumentType = genericArguments[i]; + var parameterConstraints = argumentType.GetGenericParameterConstraints(); + constraintedArgumentTypes[i] = parameterConstraints[0]; + } + method = ((MethodInfo)method).MakeGenericMethod(constraintedArgumentTypes); + return true; + } + catch (Exception) + { + return false; + } + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/MethodWarpsCache.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/MethodWarpsCache.cs.meta new file mode 100644 index 0000000..ae2644b --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/MethodWarpsCache.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fd981f2aed778df4789e0bb7edd43130 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectCasters.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectCasters.cs new file mode 100644 index 0000000..39d3fff --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectCasters.cs @@ -0,0 +1,738 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System.Collections; +using System.Collections.Generic; +using System; +using System.Reflection; + +namespace XLua +{ + public delegate bool ObjectCheck(RealStatePtr L, int idx); + + public delegate object ObjectCast(RealStatePtr L, int idx, object target); // if target is null, will new one + + public class ObjectCheckers + { + Dictionary checkersMap = new Dictionary(); + ObjectTranslator translator; + + public ObjectCheckers(ObjectTranslator translator) + { + this.translator = translator; + checkersMap[typeof(sbyte)] = numberCheck; + checkersMap[typeof(byte)] = numberCheck; + checkersMap[typeof(short)] = numberCheck; + checkersMap[typeof(ushort)] = numberCheck; + checkersMap[typeof(int)] = numberCheck; + checkersMap[typeof(uint)] = numberCheck; + checkersMap[typeof(long)] = int64Check; + checkersMap[typeof(ulong)] = uint64Check; + checkersMap[typeof(double)] = numberCheck; + checkersMap[typeof(char)] = numberCheck; + checkersMap[typeof(float)] = numberCheck; + checkersMap[typeof(decimal)] = decimalCheck; + checkersMap[typeof(bool)] = boolCheck; + checkersMap[typeof(string)] = strCheck; + checkersMap[typeof(object)] = objectCheck; + checkersMap[typeof(byte[])] = bytesCheck; + checkersMap[typeof(IntPtr)] = intptrCheck; + + checkersMap[typeof(LuaTable)] = luaTableCheck; + checkersMap[typeof(LuaFunction)] = luaFunctionCheck; + } + + private static bool objectCheck(RealStatePtr L, int idx) + { + return true; + } + + private bool luaTableCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA && translator.SafeGetCSObj(L, idx) is LuaTable); + } + + private bool numberCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER; + } + + private bool decimalCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER || translator.IsDecimal(L, idx); + } + + private bool strCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING || LuaAPI.lua_isnil(L, idx); + } + + private bool bytesCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING || LuaAPI.lua_isnil(L, idx) || (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA && translator.SafeGetCSObj(L, idx) is byte[]); + } + + private bool boolCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TBOOLEAN; + } + + private bool int64Check(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER || LuaAPI.lua_isint64(L, idx); + } + + private bool uint64Check(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER || LuaAPI.lua_isuint64(L, idx); + } + + private bool luaFunctionCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_isfunction(L, idx) || (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA && translator.SafeGetCSObj(L, idx) is LuaFunction); + } + + private bool intptrCheck(RealStatePtr L, int idx) + { + return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TLIGHTUSERDATA; + } + + private ObjectCheck genChecker(Type type) + { + ObjectCheck fixTypeCheck = (RealStatePtr L, int idx) => + { + if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA) + { + object obj = translator.SafeGetCSObj(L, idx); + if (obj != null) + { + return type.IsAssignableFrom(obj.GetType()); + } + else + { + Type type_of_obj = translator.GetTypeOf(L, idx); + if (type_of_obj != null) return type.IsAssignableFrom(type_of_obj); + } + } + return false; + }; + + if (!type.IsAbstract() && typeof(Delegate).IsAssignableFrom(type)) + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_isfunction(L, idx) || fixTypeCheck(L, idx); + }; + } + else if (type.IsEnum()) + { + return fixTypeCheck; + } + else if (type.IsInterface()) + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx); + }; + } + else + { + if ((type.IsClass() && type.GetConstructor(System.Type.EmptyTypes) != null)) //class has default construtor + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx); + }; + } + else if (type.IsValueType()) + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx); + }; + } + else if (type.IsArray) + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx); + }; + } + else + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_isnil(L, idx) || fixTypeCheck(L, idx); + }; + } + } + } + + public ObjectCheck genNullableChecker(ObjectCheck oc) + { + return (RealStatePtr L, int idx) => + { + return LuaAPI.lua_isnil(L, idx) || oc(L, idx); + }; + } + + public ObjectCheck GetChecker(Type type) + { + if (type.IsByRef) type = type.GetElementType(); + + Type underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType != null) + { + return genNullableChecker(GetChecker(underlyingType)); + } + ObjectCheck oc; + if (!checkersMap.TryGetValue(type, out oc)) + { + oc = genChecker(type); + checkersMap.Add(type, oc); + } + return oc; + } + } + + public class ObjectCasters + { + Dictionary castersMap = new Dictionary(); + ObjectTranslator translator; + + public ObjectCasters(ObjectTranslator translator) + { + this.translator = translator; + castersMap[typeof(char)] = charCaster; + castersMap[typeof(sbyte)] = sbyteCaster; + castersMap[typeof(byte)] = byteCaster; + castersMap[typeof(short)] = shortCaster; + castersMap[typeof(ushort)] = ushortCaster; + castersMap[typeof(int)] = intCaster; + castersMap[typeof(uint)] = uintCaster; + castersMap[typeof(long)] = longCaster; + castersMap[typeof(ulong)] = ulongCaster; + castersMap[typeof(double)] = getDouble; + castersMap[typeof(float)] = floatCaster; + castersMap[typeof(decimal)] = decimalCaster; + castersMap[typeof(bool)] = getBoolean; + castersMap[typeof(string)] = getString; + castersMap[typeof(object)] = getObject; + castersMap[typeof(byte[])] = getBytes; + castersMap[typeof(IntPtr)] = getIntptr; + //special type + castersMap[typeof(LuaTable)] = getLuaTable; + castersMap[typeof(LuaFunction)] = getLuaFunction; + } + + private static object charCaster(RealStatePtr L, int idx, object target) + { + return (char)LuaAPI.xlua_tointeger(L, idx); + } + + private static object sbyteCaster(RealStatePtr L, int idx, object target) + { + return (sbyte)LuaAPI.xlua_tointeger(L, idx); + } + + private static object byteCaster(RealStatePtr L, int idx, object target) + { + return (byte)LuaAPI.xlua_tointeger(L, idx); + } + + private static object shortCaster(RealStatePtr L, int idx, object target) + { + return (short)LuaAPI.xlua_tointeger(L, idx); + } + + private static object ushortCaster(RealStatePtr L, int idx, object target) + { + return (ushort)LuaAPI.xlua_tointeger(L, idx); + } + + private static object intCaster(RealStatePtr L, int idx, object target) + { + return LuaAPI.xlua_tointeger(L, idx); + } + + private static object uintCaster(RealStatePtr L, int idx, object target) + { + return LuaAPI.xlua_touint(L, idx); + } + + private static object longCaster(RealStatePtr L, int idx, object target) + { + return LuaAPI.lua_toint64(L, idx); + } + + private static object ulongCaster(RealStatePtr L, int idx, object target) + { + return LuaAPI.lua_touint64(L, idx); + } + + private static object getDouble(RealStatePtr L, int idx, object target) + { + return LuaAPI.lua_tonumber(L, idx); + } + + private static object floatCaster(RealStatePtr L, int idx, object target) + { + return (float)LuaAPI.lua_tonumber(L, idx); + } + + private object decimalCaster(RealStatePtr L, int idx, object target) + { + decimal ret; + translator.Get(L, idx, out ret); + return ret; + } + + private static object getBoolean(RealStatePtr L, int idx, object target) + { + return LuaAPI.lua_toboolean(L, idx); + } + + private static object getString(RealStatePtr L, int idx, object target) + { + return LuaAPI.lua_tostring(L, idx); + } + + private object getBytes(RealStatePtr L, int idx, object target) + { + if(LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING) + { + return LuaAPI.lua_tobytes(L, idx); + } + object obj = translator.SafeGetCSObj(L, idx); + return (obj is RawObject) ? (obj as RawObject).Target : obj as byte[]; + } + + private object getIntptr(RealStatePtr L, int idx, object target) + { + return LuaAPI.lua_touserdata(L, idx); + } + + private object getObject(RealStatePtr L, int idx, object target) + { + //return translator.getObject(L, idx); //TODO: translator.getObject move to here?? + LuaTypes type = (LuaTypes)LuaAPI.lua_type(L, idx); + switch (type) + { + case LuaTypes.LUA_TNUMBER: + { + if (LuaAPI.lua_isint64(L, idx)) + { + return LuaAPI.lua_toint64(L, idx); + } + else if(LuaAPI.lua_isinteger(L, idx)) + { + return LuaAPI.xlua_tointeger(L, idx); + } + else + { + return LuaAPI.lua_tonumber(L, idx); + } + } + case LuaTypes.LUA_TSTRING: + { + return LuaAPI.lua_tostring(L, idx); + } + case LuaTypes.LUA_TBOOLEAN: + { + return LuaAPI.lua_toboolean(L, idx); + } + case LuaTypes.LUA_TTABLE: + { + return getLuaTable(L, idx, null); + } + case LuaTypes.LUA_TFUNCTION: + { + return getLuaFunction(L, idx, null); + } + case LuaTypes.LUA_TUSERDATA: + { + if (LuaAPI.lua_isint64(L, idx)) + { + return LuaAPI.lua_toint64(L, idx); + } + else if(LuaAPI.lua_isuint64(L, idx)) + { + return LuaAPI.lua_touint64(L, idx); + } + else + { + object obj = translator.SafeGetCSObj(L, idx); + return (obj is RawObject) ? (obj as RawObject).Target : obj; + } + } + default: + return null; + } + } + + private object getLuaTable(RealStatePtr L, int idx, object target) + { + if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA) + { + object obj = translator.SafeGetCSObj(L, idx); + return (obj != null && obj is LuaTable) ? obj : null; + } + if (!LuaAPI.lua_istable(L, idx)) + { + return null; + } + LuaAPI.lua_pushvalue(L, idx); + return new LuaTable(LuaAPI.luaL_ref(L), translator.luaEnv); + } + + private object getLuaFunction(RealStatePtr L, int idx, object target) + { + if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA) + { + object obj = translator.SafeGetCSObj(L, idx); + return (obj != null && obj is LuaFunction) ? obj : null; + } + if (!LuaAPI.lua_isfunction(L, idx)) + { + return null; + } + LuaAPI.lua_pushvalue(L, idx); + return new LuaFunction(LuaAPI.luaL_ref(L), translator.luaEnv); + } + + public void AddCaster(Type type, ObjectCast oc) + { + castersMap[type] = oc; + } + + private ObjectCast genCaster(Type type) + { + ObjectCast fixTypeGetter = (RealStatePtr L, int idx, object target) => + { + if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA) + { + object obj = translator.SafeGetCSObj(L, idx); + return (obj != null && type.IsAssignableFrom(obj.GetType())) ? obj : null; + } + return null; + }; + + if (typeof(Delegate).IsAssignableFrom(type)) + { + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_isfunction(L, idx)) + { + return null; + } + + return translator.CreateDelegateBridge(L, type, idx); + }; + } + else if (typeof(DelegateBridgeBase).IsAssignableFrom(type)) + { + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_isfunction(L, idx)) + { + return null; + } + + return translator.CreateDelegateBridge(L, null, idx); + }; + } + else if (type.IsInterface()) + { + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_istable(L, idx)) + { + return null; + } + return translator.CreateInterfaceBridge(L, type, idx); + }; + } + else if (type.IsEnum()) + { + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + LuaTypes lua_type = LuaAPI.lua_type(L, idx); + if (lua_type == LuaTypes.LUA_TSTRING) + { + return Enum.Parse(type, LuaAPI.lua_tostring(L, idx)); + } + else if (lua_type == LuaTypes.LUA_TNUMBER) + { + return Enum.ToObject(type, LuaAPI.xlua_tointeger(L, idx)); + } + throw new InvalidCastException("invalid value for enum " + type); + }; + } + else if (type.IsArray) + { + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_istable(L, idx)) + { + return null; + } + + uint len = LuaAPI.xlua_objlen(L, idx); + int n = LuaAPI.lua_gettop(L); + idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index + Type et = type.GetElementType(); + ObjectCast elementCaster = GetCaster(et); + Array ary = target == null ? Array.CreateInstance(et, (int)len) : target as Array; + if (!LuaAPI.lua_checkstack(L, 1)) + { + throw new Exception("stack overflow while cast to Array"); + } + for (int i = 0; i < len; ++i) + { + LuaAPI.lua_pushnumber(L, i + 1); + LuaAPI.lua_rawget(L, idx); + if (et.IsPrimitive()) + { + if (!StaticLuaCallbacks.TryPrimitiveArraySet(type, L, ary, i, n + 1)) + { + ary.SetValue(elementCaster(L, n + 1, null), i); + } + } + else + { + if (InternalGlobals.genTryArraySetPtr == null + || !InternalGlobals.genTryArraySetPtr(type, L, translator, ary, i, n + 1)) + { + ary.SetValue(elementCaster(L, n + 1, null), i); + } + } + LuaAPI.lua_pop(L, 1); + } + return ary; + }; + } + else if (typeof(IList).IsAssignableFrom(type) && type.IsGenericType()) + { + Type elementType = type.GetGenericArguments()[0]; + ObjectCast elementCaster = GetCaster(elementType); + + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_istable(L, idx)) + { + return null; + } + + obj = target == null ? Activator.CreateInstance(type) : target; + int n = LuaAPI.lua_gettop(L); + idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index + IList list = obj as IList; + + + uint len = LuaAPI.xlua_objlen(L, idx); + if (!LuaAPI.lua_checkstack(L, 1)) + { + throw new Exception("stack overflow while cast to IList"); + } + for (int i = 0; i < len; ++i) + { + LuaAPI.lua_pushnumber(L, i + 1); + LuaAPI.lua_rawget(L, idx); + if (i < list.Count && target != null) + { + if (translator.Assignable(L, n + 1, elementType)) + { + list[i] = elementCaster(L, n + 1, list[i]); ; + } + } + else + { + if (translator.Assignable(L, n + 1, elementType)) + { + list.Add(elementCaster(L, n + 1, null)); + } + } + LuaAPI.lua_pop(L, 1); + } + return obj; + }; + } + else if (typeof(IDictionary).IsAssignableFrom(type) && type.IsGenericType()) + { + Type keyType = type.GetGenericArguments()[0]; + ObjectCast keyCaster = GetCaster(keyType); + Type valueType = type.GetGenericArguments()[1]; + ObjectCast valueCaster = GetCaster(valueType); + + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_istable(L, idx)) + { + return null; + } + + IDictionary dic = (target == null ? Activator.CreateInstance(type) : target) as IDictionary; + int n = LuaAPI.lua_gettop(L); + idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index + + LuaAPI.lua_pushnil(L); + if (!LuaAPI.lua_checkstack(L, 1)) + { + throw new Exception("stack overflow while cast to IDictionary"); + } + while (LuaAPI.lua_next(L, idx) != 0) + { + if (translator.Assignable(L, n + 1, keyType) && translator.Assignable(L, n + 2, valueType)) + { + object k = keyCaster(L, n + 1, null); + dic[k] = valueCaster(L, n + 2, !dic.Contains(k) ? null : dic[k]); + } + LuaAPI.lua_pop(L, 1); // removes value, keeps key for next iteration + } + return dic; + }; + } + else if ((type.IsClass() && type.GetConstructor(System.Type.EmptyTypes) != null) || (type.IsValueType() && !type.IsEnum())) //class has default construtor + { + return (RealStatePtr L, int idx, object target) => + { + object obj = fixTypeGetter(L, idx, target); + if (obj != null) return obj; + + if (!LuaAPI.lua_istable(L, idx)) + { + return null; + } + + obj = target == null ? Activator.CreateInstance(type) : target; + + int n = LuaAPI.lua_gettop(L); + idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index + if (!LuaAPI.lua_checkstack(L, 1)) + { + throw new Exception("stack overflow while cast to " + type); + } + /*foreach (PropertyInfo prop in type.GetProperties()) + { + var _setMethod = prop.GetSetMethod(); + + if (_setMethod == null || + _setMethod.IsPrivate) + { + continue; + } + + LuaAPI.xlua_pushasciistring(L, prop.Name); + LuaAPI.lua_rawget(L, idx); + if (!LuaAPI.lua_isnil(L, -1)) + { + try + { + prop.SetValue(obj, GetCaster(prop.PropertyType)(L, n + 1, + target == null || prop.PropertyType.IsPrimitive() || prop.PropertyType == typeof(string) ? null : prop.GetValue(obj, null)), null); + } + catch (Exception e) + { + throw new Exception("exception in tran " + prop.Name + ", msg=" + e.Message); + } + } + LuaAPI.lua_pop(L, 1); + }*/ + foreach (FieldInfo field in type.GetFields()) + { + LuaAPI.xlua_pushasciistring(L, field.Name); + LuaAPI.lua_rawget(L, idx); + if (!LuaAPI.lua_isnil(L, -1)) + { + try + { + field.SetValue(obj, GetCaster(field.FieldType)(L, n + 1, + target == null || field.FieldType.IsPrimitive() || field.FieldType == typeof(string) ? null : field.GetValue(obj))); + } + catch (Exception e) + { + throw new Exception("exception in tran " + field.Name + ", msg=" + e.Message); + } + } + LuaAPI.lua_pop(L, 1); + } + + return obj; + }; + } + else + { + return fixTypeGetter; + } + } + + ObjectCast genNullableCaster(ObjectCast oc) + { + return (RealStatePtr L, int idx, object target) => + { + if (LuaAPI.lua_isnil(L, idx)) + { + return null; + } + else + { + return oc(L, idx, target); + } + }; + } + + public ObjectCast GetCaster(Type type) + { + if (type.IsByRef) type = type.GetElementType(); + + Type underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType != null) + { + return genNullableCaster(GetCaster(underlyingType)); + } + ObjectCast oc; + if (!castersMap.TryGetValue(type, out oc)) + { + oc = genCaster(type); + castersMap.Add(type, oc); + } + return oc; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectCasters.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectCasters.cs.meta new file mode 100644 index 0000000..6eedc5d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectCasters.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 34e9e7e9f8082934081581f64d8d0b86 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectPool.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectPool.cs new file mode 100644 index 0000000..04f31cf --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectPool.cs @@ -0,0 +1,164 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace XLua +{ + public class ObjectPool + { + const int LIST_END = -1; + const int ALLOCED = -2; + struct Slot + { + public int next; + public object obj; + + public Slot(int next, object obj) + { + this.next = next; + this.obj = obj; + } + } + + private Slot[] list = new Slot[512]; + private int freelist = LIST_END; + private int count = 0; + + public object this[int i] + { + get + { + if (i >= 0 && i < count) + { + return list[i].obj; + } + + return null; + } + } + + public void Clear() + { + freelist = LIST_END; + count = 0; + list = new Slot[512]; + } + + void extend_capacity() + { + Slot[] new_list = new Slot[list.Length * 2]; + for (int i = 0; i < list.Length; i++) + { + new_list[i] = list[i]; + } + list = new_list; + } + + public int Add(object obj) + { + int index = LIST_END; + + if (freelist != LIST_END) + { + index = freelist; + list[index].obj = obj; + freelist = list[index].next; + list[index].next = ALLOCED; + } + else + { + if (count == list.Length) + { + extend_capacity(); + } + index = count; + list[index] = new Slot(ALLOCED, obj); + count = index + 1; + } + + return index; + } + + public bool TryGetValue(int index, out object obj) + { + if (index >= 0 && index < count && list[index].next == ALLOCED) + { + obj = list[index].obj; + return true; + } + + obj = null; + return false; + } + + public object Get(int index) + { + if (index >= 0 && index < count) + { + return list[index].obj; + } + return null; + } + + public object Remove(int index) + { + if (index >= 0 && index < count && list[index].next == ALLOCED) + { + object o = list[index].obj; + list[index].obj = null; + list[index].next = freelist; + freelist = index; + return o; + } + + return null; + } + + public object Replace(int index, object o) + { + if (index >= 0 && index < count) + { + object obj = list[index].obj; + list[index].obj = o; + return obj; + } + + return null; + } + + public int Check(int check_pos, int max_check, Func checker, Dictionary reverse_map) + { + if (count == 0) + { + return 0; + } + for (int i = 0; i < Math.Min(max_check, count); ++i) + { + check_pos %= count; + if (list[check_pos].next == ALLOCED && !Object.ReferenceEquals(list[check_pos].obj, null)) + { + if (!checker(list[check_pos].obj)) + { + object obj = Replace(check_pos, null); + int obj_index; + if (reverse_map.TryGetValue(obj, out obj_index) && obj_index == check_pos) + { + reverse_map.Remove(obj); + } + } + } + ++check_pos; + } + + return check_pos %= count; + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectPool.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectPool.cs.meta new file mode 100644 index 0000000..e3c02a8 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectPool.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b4d49b7e1bdf27247a3f01c25605e73a +timeCreated: 1480296949 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslator.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslator.cs new file mode 100644 index 0000000..02b7624 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslator.cs @@ -0,0 +1,1717 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + + +namespace XLua +{ + using System; + using System.Collections; + using System.Reflection; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + + class ReferenceEqualsComparer : IEqualityComparer + { + public new bool Equals(object o1, object o2) + { + return object.ReferenceEquals(o1, o2); + } + public int GetHashCode(object obj) + { + return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj); + } + } + +#pragma warning disable 414 + public class MonoPInvokeCallbackAttribute : System.Attribute + { + private Type type; + public MonoPInvokeCallbackAttribute(Type t) { type = t; } + } +#pragma warning restore 414 + + public enum LuaTypes + { + LUA_TNONE = -1, + LUA_TNIL = 0, + LUA_TNUMBER = 3, + LUA_TSTRING = 4, + LUA_TBOOLEAN = 1, + LUA_TTABLE = 5, + LUA_TFUNCTION = 6, + LUA_TUSERDATA = 7, + LUA_TTHREAD = 8, + LUA_TLIGHTUSERDATA = 2 + } + + public enum LuaGCOptions + { + LUA_GCSTOP = 0, + LUA_GCRESTART = 1, + LUA_GCCOLLECT = 2, + LUA_GCCOUNT = 3, + LUA_GCCOUNTB = 4, + LUA_GCSTEP = 5, + LUA_GCSETPAUSE = 6, + LUA_GCSETSTEPMUL = 7, + } + + public enum LuaThreadStatus + { + LUA_RESUME_ERROR = -1, + LUA_OK = 0, + LUA_YIELD = 1, + LUA_ERRRUN = 2, + LUA_ERRSYNTAX = 3, + LUA_ERRMEM = 4, + LUA_ERRERR = 5, + } + + sealed class LuaIndexes + { + public static int LUA_REGISTRYINDEX + { + get + { + return InternalGlobals.LUA_REGISTRYINDEX; + } + set + { + InternalGlobals.LUA_REGISTRYINDEX = value; + } + } + } + +#if GEN_CODE_MINIMIZE + public delegate int CSharpWrapper(IntPtr L, int top); +#endif + + public partial class ObjectTranslator + { + internal MethodWrapsCache methodWrapsCache; + internal ObjectCheckers objectCheckers; + internal ObjectCasters objectCasters; + + internal readonly ObjectPool objects = new ObjectPool(); + internal readonly Dictionary reverseMap = new Dictionary(new ReferenceEqualsComparer()); + internal LuaEnv luaEnv; + internal StaticLuaCallbacks metaFunctions; + internal List assemblies; + private LuaCSFunction importTypeFunction,loadAssemblyFunction, castFunction; + //延迟加载 + private readonly Dictionary> delayWrap = new Dictionary>(); + + private readonly Dictionary> interfaceBridgeCreators = new Dictionary>(); + + //无法访问的类,比如声明成internal,可以用其接口、基类的生成代码来访问 + private readonly Dictionary aliasCfg = new Dictionary(); + + public void DelayWrapLoader(Type type, Action loader) + { + delayWrap[type] = loader; + } + + public void AddInterfaceBridgeCreator(Type type, Func creator) + { + interfaceBridgeCreators.Add(type, creator); + } + + Dictionary loaded_types = new Dictionary(); + public bool TryDelayWrapLoader(RealStatePtr L, Type type) + { + if (loaded_types.ContainsKey(type)) return true; + loaded_types.Add(type, true); + + LuaAPI.luaL_newmetatable(L, type.FullName); //先建一个metatable,因为加载过程可能会需要用到 + LuaAPI.lua_pop(L, 1); + + Action loader; + int top = LuaAPI.lua_gettop(L); + if (delayWrap.TryGetValue(type, out loader)) + { + delayWrap.Remove(type); + loader(L); + } + else + { +#if !GEN_CODE_MINIMIZE && !ENABLE_IL2CPP && (UNITY_EDITOR || XLUA_GENERAL) && !FORCE_REFLECTION && !NET_STANDARD_2_0 + if (!DelegateBridge.Gen_Flag && !type.IsEnum() && !typeof(Delegate).IsAssignableFrom(type) && Utils.IsPublic(type)) + { + Type wrap = ce.EmitTypeWrap(type); + MethodInfo method = wrap.GetMethod("__Register", BindingFlags.Static | BindingFlags.Public); + method.Invoke(null, new object[] { L }); + } + else + { + Utils.ReflectionWrap(L, type, privateAccessibleFlags.Contains(type)); + } +#else + Utils.ReflectionWrap(L, type, privateAccessibleFlags.Contains(type)); +#endif +#if NOT_GEN_WARNING + if (!typeof(Delegate).IsAssignableFrom(type)) + { +#if !XLUA_GENERAL + UnityEngine.Debug.LogWarning(string.Format("{0} not gen, using reflection instead", type)); +#else + System.Console.WriteLine(string.Format("Warning: {0} not gen, using reflection instead", type)); +#endif + } +#endif + } + if (top != LuaAPI.lua_gettop(L)) + { + throw new Exception("top change, before:" + top + ", after:" + LuaAPI.lua_gettop(L)); + } + + foreach (var nested_type in type.GetNestedTypes(BindingFlags.Public)) + { + if (nested_type.IsGenericTypeDefinition()) + { + continue; + } + GetTypeId(L, nested_type); + } + + return true; + } + + public void Alias(Type type, string alias) + { + Type alias_type = FindType(alias); + if (alias_type == null) + { + throw new ArgumentException("Can not find " + alias); + } + aliasCfg[alias_type] = type; + } + + public int cacheRef; + + void addAssemblieByName(IEnumerable assemblies_usorted, string name) + { + foreach(var assemblie in assemblies_usorted) + { + if (assemblie.FullName.StartsWith(name) && !assemblies.Contains(assemblie)) + { + assemblies.Add(assemblie); + break; + } + } + } + + public ObjectTranslator(LuaEnv luaenv,RealStatePtr L) + { +#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR) + var dumb_field = typeof(ObjectTranslator).GetField("s_gen_reg_dumb_obj", BindingFlags.Static| BindingFlags.DeclaredOnly | BindingFlags.NonPublic); + if (dumb_field != null) + { + dumb_field.GetValue(null); + } +#endif + assemblies = new List(); + +#if (UNITY_WSA && !ENABLE_IL2CPP) && !UNITY_EDITOR + var assemblies_usorted = Utils.GetAssemblies(); +#else + assemblies.Add(Assembly.GetExecutingAssembly()); + var assemblies_usorted = AppDomain.CurrentDomain.GetAssemblies(); +#endif + addAssemblieByName(assemblies_usorted, "mscorlib,"); + addAssemblieByName(assemblies_usorted, "System,"); + addAssemblieByName(assemblies_usorted, "System.Core,"); + foreach (Assembly assembly in assemblies_usorted) + { + if (!assemblies.Contains(assembly)) + { + assemblies.Add(assembly); + } + } + + this.luaEnv=luaenv; + objectCasters = new ObjectCasters(this); + objectCheckers = new ObjectCheckers(this); + methodWrapsCache = new MethodWrapsCache(this, objectCheckers, objectCasters); + metaFunctions=new StaticLuaCallbacks(); + + importTypeFunction = new LuaCSFunction(StaticLuaCallbacks.ImportType); + loadAssemblyFunction = new LuaCSFunction(StaticLuaCallbacks.LoadAssembly); + castFunction = new LuaCSFunction(StaticLuaCallbacks.Cast); + + LuaAPI.lua_newtable(L); + LuaAPI.lua_newtable(L); + LuaAPI.xlua_pushasciistring(L, "__mode"); + LuaAPI.xlua_pushasciistring(L, "v"); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_setmetatable(L, -2); + cacheRef = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + + initCSharpCallLua(); + } + + internal enum LOGLEVEL{ + NO, + INFO, + WARN, + ERROR + } + +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + Type delegate_birdge_type; + + class CompareByArgRet : IEqualityComparer + { + public bool Equals(MethodInfo x, MethodInfo y) + { + return Utils.IsParamsMatch(x, y); + } + public int GetHashCode(MethodInfo method) + { + int hc = 0; + hc += method.ReturnType.GetHashCode(); + foreach (var pi in method.GetParameters()) + { + hc += pi.ParameterType.GetHashCode(); + } + return hc; + } + } +#endif + + void initCSharpCallLua() + { +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + delegate_birdge_type = typeof(DelegateBridge); + if (!DelegateBridge.Gen_Flag) + { + List cs_call_lua = new List(); + foreach (var type in Utils.GetAllTypes()) + { + if(type.IsDefined(typeof(CSharpCallLuaAttribute), false)) + { + cs_call_lua.Add(type); + } + + if (!type.IsAbstract || !type.IsSealed) continue; + + var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < fields.Length; i++) + { + var field = fields[i]; + if (field.IsDefined(typeof(CSharpCallLuaAttribute), false) && (typeof(IEnumerable)).IsAssignableFrom(field.FieldType)) + { + cs_call_lua.AddRange(field.GetValue(null) as IEnumerable); + } + } + + var props = type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < props.Length; i++) + { + var prop = props[i]; + if (prop.IsDefined(typeof(CSharpCallLuaAttribute), false) && (typeof(IEnumerable)).IsAssignableFrom(prop.PropertyType)) + { + cs_call_lua.AddRange(prop.GetValue(null, null) as IEnumerable); + } + } + } + IEnumerable> groups = (from type in cs_call_lua + where typeof(Delegate).IsAssignableFrom(type) && type != typeof(Delegate) && type != typeof(MulticastDelegate) + where !type.GetMethod("Invoke").GetParameters().Any(paramInfo => paramInfo.ParameterType.IsGenericParameter) + select type).GroupBy(t => t.GetMethod("Invoke"), new CompareByArgRet()); + + ce.SetGenInterfaces(cs_call_lua.Where(type=>type.IsInterface()).ToList()); + delegate_birdge_type = ce.EmitDelegateImpl(groups); + } +#endif + } + +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + CodeEmit ce = new CodeEmit(); +#endif + MethodInfo[] genericAction = null; + MethodInfo[] genericFunc = null; + Dictionary> delegateCreatorCache + = new Dictionary>(); + + Func getCreatorUsingGeneric(DelegateBridgeBase bridge, Type delegateType, MethodInfo delegateMethod) + { + Func genericDelegateCreator = null; + + if (genericAction == null) + { + var methods = typeof(DelegateBridge).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); + genericAction = methods.Where(m => m.Name == "Action").OrderBy(m => m.GetParameters().Length).ToArray(); + genericFunc = methods.Where(m => m.Name == "Func").OrderBy(m => m.GetParameters().Length).ToArray(); + } + if (genericAction.Length != 5 || genericFunc.Length != 5) + { + return null; + } + var parameters = delegateMethod.GetParameters(); +#if !XLUA_GENERAL + if ((delegateMethod.ReturnType.IsValueType() && delegateMethod.ReturnType != typeof(void)) || parameters.Length > 4) + { + genericDelegateCreator = (x) => null; + } + else +#endif + { + foreach (var pinfo in parameters) + { + if (pinfo.ParameterType.IsValueType() || pinfo.IsOut || pinfo.ParameterType.IsByRef) + { + genericDelegateCreator = (x) => null; + break; + } + } + if (genericDelegateCreator == null) + { + var typeArgs = parameters.Select(pinfo => pinfo.ParameterType); + MethodInfo genericMethodInfo = null; + if (delegateMethod.ReturnType == typeof(void)) + { + genericMethodInfo = genericAction[parameters.Length]; + } + else + { + genericMethodInfo = genericFunc[parameters.Length]; + typeArgs = typeArgs.Concat(new Type[] { delegateMethod.ReturnType }); + } + if (genericMethodInfo.IsGenericMethodDefinition) + { + var methodInfo = genericMethodInfo.MakeGenericMethod(typeArgs.ToArray()); + genericDelegateCreator = (o) => +#if !UNITY_WSA || UNITY_EDITOR + Delegate.CreateDelegate(delegateType, o, methodInfo); +#else + methodInfo.CreateDelegate(delegateType, bridge); +#endif + } + else + { + genericDelegateCreator = (o) => +#if !UNITY_WSA || UNITY_EDITOR + Delegate.CreateDelegate(delegateType, o, genericMethodInfo); +#else + genericMethodInfo.CreateDelegate(delegateType, o); +#endif + } + } + } + + return genericDelegateCreator; + } + + Delegate getDelegate(DelegateBridgeBase bridge, Type delegateType) + { + Delegate ret = bridge.GetDelegateByType(delegateType); + + if (ret != null) + { + return ret; + } + + if (delegateType == typeof(Delegate) || delegateType == typeof(MulticastDelegate)) + { + return null; + } + + Func delegateCreator; + if (!delegateCreatorCache.TryGetValue(delegateType, out delegateCreator)) + { + // get by parameters + MethodInfo delegateMethod = delegateType.GetMethod("Invoke"); + var methods = bridge.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(m => !m.IsGenericMethodDefinition && (m.Name.StartsWith("__Gen_Delegate_Imp") || m.Name == "Action")).ToArray(); + for (int i = 0; i < methods.Length; i++) + { + if (!methods[i].IsConstructor && Utils.IsParamsMatch(delegateMethod, methods[i])) + { + var foundMethod = methods[i]; + delegateCreator = (o) => +#if !UNITY_WSA || UNITY_EDITOR + Delegate.CreateDelegate(delegateType, o, foundMethod); +#else + foundMethod.CreateDelegate(delegateType, o); +#endif + break; + } + } + + if (delegateCreator == null) + { + delegateCreator = getCreatorUsingGeneric(bridge, delegateType, delegateMethod); + } + delegateCreatorCache.Add(delegateType, delegateCreator); + } + + ret = delegateCreator(bridge); + if (ret != null) + { + return ret; + } + + throw new InvalidCastException("This type must add to CSharpCallLua: " + delegateType.GetFriendlyName()); + } + Dictionary delegate_bridges = new Dictionary(); + public object CreateDelegateBridge(RealStatePtr L, Type delegateType, int idx) + { + LuaAPI.lua_pushvalue(L, idx); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + if (!LuaAPI.lua_isnil(L, -1)) + { + int referenced = LuaAPI.xlua_tointeger(L, -1); + LuaAPI.lua_pop(L, 1); + + if (delegate_bridges[referenced].IsAlive) + { + if (delegateType == null) + { + return delegate_bridges[referenced].Target; + } + DelegateBridgeBase exist_bridge = delegate_bridges[referenced].Target as DelegateBridgeBase; + Delegate exist_delegate; + if (exist_bridge.TryGetDelegate(delegateType, out exist_delegate)) + { + return exist_delegate; + } + else + { + exist_delegate = getDelegate(exist_bridge, delegateType); + exist_bridge.AddDelegate(delegateType, exist_delegate); + return exist_delegate; + } + } + } + else + { + LuaAPI.lua_pop(L, 1); + } + + LuaAPI.lua_pushvalue(L, idx); + int reference = LuaAPI.luaL_ref(L); + LuaAPI.lua_pushvalue(L, idx); + LuaAPI.lua_pushnumber(L, reference); + LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); + DelegateBridgeBase bridge; + try + { +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + if (!DelegateBridge.Gen_Flag) + { + bridge = Activator.CreateInstance(delegate_birdge_type, new object[] { reference, luaEnv }) as DelegateBridgeBase; + } + else +#endif + { + bridge = new DelegateBridge(reference, luaEnv); + } + } + catch(Exception e) + { + LuaAPI.lua_pushvalue(L, idx); + LuaAPI.lua_pushnil(L); + LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.lua_pushnil(L); + LuaAPI.xlua_rawseti(L, LuaIndexes.LUA_REGISTRYINDEX, reference); + throw e; + } + if (delegateType == null) + { + delegate_bridges[reference] = new WeakReference(bridge); + return bridge; + } + try { + var ret = getDelegate(bridge, delegateType); + bridge.AddDelegate(delegateType, ret); + delegate_bridges[reference] = new WeakReference(bridge); + return ret; + } + catch(Exception e) + { + bridge.Dispose(); + throw e; + } + } + + public bool AllDelegateBridgeReleased() + { + foreach (var kv in delegate_bridges) + { + if (kv.Value.IsAlive) + { + return false; + } + } + return true; + } + + public void ReleaseLuaBase(RealStatePtr L, int reference, bool is_delegate) + { + if(is_delegate) + { + LuaAPI.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, reference); + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_pop(L, 1); + } + else + { + LuaAPI.lua_pushvalue(L, -1); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + if (LuaAPI.lua_type(L, -1) == LuaTypes.LUA_TNUMBER && LuaAPI.xlua_tointeger(L, -1) == reference) // + { + //UnityEngine.Debug.LogWarning("release delegate ref = " + luaReference); + LuaAPI.lua_pop(L, 1);// pop LUA_REGISTRYINDEX[func] + LuaAPI.lua_pushnil(L); + LuaAPI.lua_rawset(L, LuaIndexes.LUA_REGISTRYINDEX); // LUA_REGISTRYINDEX[func] = nil + } + else //another Delegate ref the function before the GC tick + { + LuaAPI.lua_pop(L, 2); // pop LUA_REGISTRYINDEX[func] & func + } + } + + LuaAPI.lua_unref(L, reference); + delegate_bridges.Remove(reference); + } + else + { + LuaAPI.lua_unref(L, reference); + } + } + + public object CreateInterfaceBridge(RealStatePtr L, Type interfaceType, int idx) + { + Func creator; + + if (!interfaceBridgeCreators.TryGetValue(interfaceType, out creator)) + { +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + var bridgeType = ce.EmitInterfaceImpl(interfaceType); + creator = (int reference, LuaEnv luaenv) => + { + return Activator.CreateInstance(bridgeType, new object[] { reference, luaEnv }) as LuaBase; + }; + interfaceBridgeCreators.Add(interfaceType, creator); +#else + throw new InvalidCastException("This type must add to CSharpCallLua: " + interfaceType); +#endif + } + LuaAPI.lua_pushvalue(L, idx); + return creator(LuaAPI.luaL_ref(L), luaEnv); + } + + int common_array_meta = -1; + public void CreateArrayMetatable(RealStatePtr L) + { + Utils.BeginObjectRegister(null, L, this, 0, 0, 1, 0, common_array_meta); + Utils.RegisterFunc(L, Utils.GETTER_IDX, "Length", StaticLuaCallbacks.ArrayLength); + Utils.EndObjectRegister(null, L, this, null, null, + typeof(System.Array), StaticLuaCallbacks.ArrayIndexer, StaticLuaCallbacks.ArrayNewIndexer); + } + + int common_delegate_meta = -1; + public void CreateDelegateMetatable(RealStatePtr L) + { + Utils.BeginObjectRegister(null, L, this, 3, 0, 0, 0, common_delegate_meta); + Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__call", StaticLuaCallbacks.DelegateCall); + Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__add", StaticLuaCallbacks.DelegateCombine); + Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "__sub", StaticLuaCallbacks.DelegateRemove); + Utils.EndObjectRegister(null, L, this, null, null, + typeof(System.MulticastDelegate), null, null); + } + + int enumerable_pairs_func = -1; + + internal void CreateEnumerablePairs(RealStatePtr L) + { + LuaFunction func = luaEnv.DoString(@" + return function(obj) + local isKeyValuePair + local function lua_iter(cs_iter, k) + if cs_iter:MoveNext() then + local current = cs_iter.Current + if isKeyValuePair == nil then + if type(current) == 'userdata' then + local t = current:GetType() + isKeyValuePair = t.Name == 'KeyValuePair`2' and t.Namespace == 'System.Collections.Generic' + else + isKeyValuePair = false + end + --print(current, isKeyValuePair) + end + if isKeyValuePair then + return current.Key, current.Value + else + return k + 1, current + end + end + end + return lua_iter, obj:GetEnumerator(), -1 + end + ")[0] as LuaFunction; + func.push(L); + enumerable_pairs_func = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + func.Dispose(); + } + + public void OpenLib(RealStatePtr L) + { + if (0 != LuaAPI.xlua_getglobal(L, "xlua")) + { + throw new Exception("call xlua_getglobal fail!" + LuaAPI.lua_tostring(L, -1)); + } + LuaAPI.xlua_pushasciistring(L, "import_type"); + LuaAPI.lua_pushstdcallcfunction(L,importTypeFunction); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "import_generic_type"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.ImportGenericType); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "cast"); + LuaAPI.lua_pushstdcallcfunction(L, castFunction); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "load_assembly"); + LuaAPI.lua_pushstdcallcfunction(L,loadAssemblyFunction); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "access"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.XLuaAccess); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "private_accessible"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.XLuaPrivateAccessible); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "metatable_operation"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.XLuaMetatableOperation); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "tofunction"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.ToFunction); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "get_generic_method"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.GetGenericMethod); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "release"); + LuaAPI.lua_pushstdcallcfunction(L, StaticLuaCallbacks.ReleaseCsObject); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + + LuaAPI.lua_createtable(L, 1, 4); // 4 for __gc, __tostring, __index, __newindex + common_array_meta = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.lua_createtable(L, 1, 4); // 4 for __gc, __tostring, __index, __newindex + common_delegate_meta = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + } + + internal void createFunctionMetatable(RealStatePtr L) + { + LuaAPI.lua_newtable(L); + LuaAPI.xlua_pushasciistring(L,"__gc"); + LuaAPI.lua_pushstdcallcfunction(L,metaFunctions.GcMeta); + LuaAPI.lua_rawset(L,-3); + LuaAPI.lua_pushlightuserdata(L, LuaAPI.xlua_tag()); + LuaAPI.lua_pushnumber(L, 1); + LuaAPI.lua_rawset(L, -3); + + LuaAPI.lua_pushvalue(L, -1); + int type_id = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.lua_pushnumber(L, type_id); + LuaAPI.xlua_rawseti(L, -2, 1); + LuaAPI.lua_pop(L, 1); + + typeIdMap.Add(typeof(LuaCSFunction), type_id); + } + + internal Type FindType(string className, bool isQualifiedName = false) + { + foreach (Assembly assembly in assemblies) + { + Type klass = assembly.GetType(className); + + if (klass!=null) + { + return klass; + } + } + int p1 = className.IndexOf('['); + if (p1 > 0 && !isQualifiedName) + { + string qualified_name = className.Substring(0, p1 + 1); + string[] generic_params = className.Substring(p1 + 1, className.Length - qualified_name.Length - 1).Split(','); + for(int i = 0; i < generic_params.Length; i++) + { + Type generic_param = FindType(generic_params[i].Trim()); + if (generic_param == null) + { + return null; + } + if (i != 0 ) + { + qualified_name += ", "; + } + qualified_name = qualified_name + "[" + generic_param.AssemblyQualifiedName + "]"; + } + qualified_name += "]"; + return FindType(qualified_name, true); + } + return null; + } + + bool hasMethod(Type type, string methodName) + { + foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) + { + if (method.Name == methodName) + { + return true; + } + } + return false; + } + + internal void collectObject(int obj_index_to_collect) + { + object o; + + if (objects.TryGetValue(obj_index_to_collect, out o)) + { + objects.Remove(obj_index_to_collect); + + if (o != null) + { + int obj_index; + //lua gc是先把weak table移除后再调用__gc,这期间同一个对象可能再次push到lua,关联到新的index + bool is_enum = o.GetType().IsEnum(); + if ((is_enum ? enumMap.TryGetValue(o, out obj_index) : reverseMap.TryGetValue(o, out obj_index)) + && obj_index == obj_index_to_collect) + { + if (is_enum) + { + enumMap.Remove(o); + } + else + { + reverseMap.Remove(o); + } + } + } + } + } + + int addObject(object obj, bool is_valuetype, bool is_enum) + { + int index = objects.Add(obj); + if (is_enum) + { + enumMap[obj] = index; + } + else if (!is_valuetype) + { + reverseMap[obj] = index; + } + + return index; + } + + internal object GetObject(RealStatePtr L,int index) + { + return (objectCasters.GetCaster(typeof(object))(L, index, null)); + } + + public Type GetTypeOf(RealStatePtr L, int idx) + { + Type type = null; + int type_id = LuaAPI.xlua_gettypeid(L, idx); + if (type_id != -1) + { + typeMap.TryGetValue(type_id, out type); + } + return type; + } + + public bool Assignable(RealStatePtr L, int index) + { + return Assignable(L, index, typeof(T)); + } + + public bool Assignable(RealStatePtr L, int index, Type type) + { + if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) // 快路径 + { + int udata = LuaAPI.xlua_tocsobj_safe(L, index); + object obj; + if (udata != -1 && objects.TryGetValue(udata, out obj)) + { + RawObject rawObject = obj as RawObject; + if (rawObject != null) + { + obj = rawObject.Target; + } + if (obj == null) + { + return !type.IsValueType(); + } + return type.IsAssignableFrom(obj.GetType()); + } + + int type_id = LuaAPI.xlua_gettypeid(L, index); + Type type_of_struct; + if (type_id != -1 && typeMap.TryGetValue(type_id, out type_of_struct)) // is struct + { + return type.IsAssignableFrom(type_of_struct); + } + } + + return objectCheckers.GetChecker(type)(L, index); + } + + public object GetObject(RealStatePtr L, int index, Type type) + { + int udata = LuaAPI.xlua_tocsobj_safe(L, index); + + if (udata != -1) + { + object obj = objects.Get(udata); + RawObject rawObject = obj as RawObject; + return rawObject == null ? obj : rawObject.Target; + } + else + { + if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) + { + GetCSObject get; + int type_id = LuaAPI.xlua_gettypeid(L, index); + if (type_id != -1 && type_id == decimal_type_id) + { + decimal d; + Get(L, index, out d); + return d; + } + Type type_of_struct; + if (type_id != -1 && typeMap.TryGetValue(type_id, out type_of_struct) && type.IsAssignableFrom(type_of_struct) && custom_get_funcs.TryGetValue(type, out get)) + { + return get(L, index); + } + } + return (objectCasters.GetCaster(type)(L, index, null)); + } + } + + public void Get(RealStatePtr L, int index, out T v) + { + Func get_func; + if (tryGetGetFuncByType(typeof(T), out get_func)) + { + v = get_func(L, index); + } + else + { + v = (T)GetObject(L, index, typeof(T)); + } + } + + public void PushByType(RealStatePtr L, T v) + { + Action push_func; + if (tryGetPushFuncByType(typeof(T), out push_func)) + { + push_func(L, v); + } + else + { + PushAny(L, v); + } + } + +#if GENERIC_SHARING + public T GetByType(RealStatePtr L, int index) + { + Func get_func; + if (tryGetGetFuncByType(typeof(T), out get_func)) + { + return get_func(L, index); + } + else + { + return (T)GetObject(L, index, typeof(T)); + } + } +#endif + + public T[] GetParams(RealStatePtr L, int index) + { + T[] ret = new T[Math.Max(LuaAPI.lua_gettop(L) - index + 1, 0)]; + for(int i = 0; i < ret.Length; i++) + { + Get(L, index + i, out ret[i]); + } + return ret; + } + + public Array GetParams(RealStatePtr L, int index, Type type) //反射版本 + { + Array ret = Array.CreateInstance(type, Math.Max(LuaAPI.lua_gettop(L) - index + 1, 0)); //这个函数,长度为0的话,返回null + for (int i = 0; i < ret.Length; i++) + { + ret.SetValue(GetObject(L, index + i, type), i); + } + return ret; + } +#if UNITY_EDITOR || XLUA_GENERAL + public void PushParams(RealStatePtr L, Array ary) + { + if (ary != null) + { + for (int i = 0; i < ary.Length; i++) + { + PushAny(L, ary.GetValue(i)); + } + } + } +#endif + + public T GetDelegate(RealStatePtr L, int index) where T :class + { + + if (LuaAPI.lua_isfunction(L, index)) + { + return CreateDelegateBridge(L, typeof(T), index) as T; + } + else if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA) + { + return (T)SafeGetCSObj(L, index); + } + else + { + return null; + } + } + + Dictionary typeIdMap = new Dictionary(); + + //only store the type id to type map for struct + Dictionary typeMap = new Dictionary(); + + public int GetTypeId(RealStatePtr L, Type type) + { + bool isFirst; + return getTypeId(L, type, out isFirst); + } + + HashSet privateAccessibleFlags = new HashSet(); + + public void PrivateAccessible(RealStatePtr L, Type type) + { + if (!privateAccessibleFlags.Contains(type)) //未处理 + { + privateAccessibleFlags.Add(type); + if (typeIdMap.ContainsKey(type)) //loaded + { + Utils.MakePrivateAccessible(L, type); + } + } + } + + internal int getTypeId(RealStatePtr L, Type type, out bool is_first, LOGLEVEL log_level = LOGLEVEL.WARN) + { + int type_id; + is_first = false; + if (!typeIdMap.TryGetValue(type, out type_id)) // no reference + { + if (type.IsArray) + { + if (common_array_meta == -1) throw new Exception("Fatal Exception! Array Metatable not inited!"); + return common_array_meta; + } + if (typeof(MulticastDelegate).IsAssignableFrom(type)) + { + if (common_delegate_meta == -1) throw new Exception("Fatal Exception! Delegate Metatable not inited!"); + TryDelayWrapLoader(L, type); + return common_delegate_meta; + } + + is_first = true; + Type alias_type = null; + aliasCfg.TryGetValue(type, out alias_type); + LuaAPI.luaL_getmetatable(L, alias_type == null ? type.FullName : alias_type.FullName); + + if (LuaAPI.lua_isnil(L, -1)) //no meta yet, try to use reflection meta + { + LuaAPI.lua_pop(L, 1); + + if (TryDelayWrapLoader(L, alias_type == null ? type : alias_type)) + { + LuaAPI.luaL_getmetatable(L, alias_type == null ? type.FullName : alias_type.FullName); + } + else + { + throw new Exception("Fatal: can not load metatable of type:" + type); + } + } + + //循环依赖,自身依赖自己的class,比如有个自身类型的静态readonly对象。 + if (typeIdMap.TryGetValue(type, out type_id)) + { + LuaAPI.lua_pop(L, 1); + } + else + { + if (type.IsEnum()) + { + LuaAPI.xlua_pushasciistring(L, "__band"); + LuaAPI.lua_pushstdcallcfunction(L, metaFunctions.EnumAndMeta); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "__bor"); + LuaAPI.lua_pushstdcallcfunction(L, metaFunctions.EnumOrMeta); + LuaAPI.lua_rawset(L, -3); + } + if (typeof(IEnumerable).IsAssignableFrom(type)) + { + LuaAPI.xlua_pushasciistring(L, "__pairs"); + LuaAPI.lua_getref(L, enumerable_pairs_func); + LuaAPI.lua_rawset(L, -3); + } + LuaAPI.lua_pushvalue(L, -1); + type_id = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.lua_pushnumber(L, type_id); + LuaAPI.xlua_rawseti(L, -2, 1); + LuaAPI.lua_pop(L, 1); + + if (type.IsValueType()) + { + typeMap.Add(type_id, type); + } + + typeIdMap.Add(type, type_id); + } + } + return type_id; + } + + void pushPrimitive(RealStatePtr L, object o) + { + if (o is sbyte || o is byte || o is short || o is ushort || + o is int) + { + int i = Convert.ToInt32(o); + LuaAPI.xlua_pushinteger(L, i); + } + else if (o is uint) + { + LuaAPI.xlua_pushuint(L, (uint)o); + } + else if (o is float || o is double) + { + double d = Convert.ToDouble(o); + LuaAPI.lua_pushnumber(L, d); + } + else if (o is IntPtr) + { + LuaAPI.lua_pushlightuserdata(L, (IntPtr)o); + } + else if (o is char) + { + LuaAPI.xlua_pushinteger(L, (char)o); + } + else if (o is long) + { + LuaAPI.lua_pushint64(L, Convert.ToInt64(o)); + } + else if (o is ulong) + { + LuaAPI.lua_pushuint64(L, Convert.ToUInt64(o)); + } + else if (o is bool) + { + bool b = (bool)o; + LuaAPI.lua_pushboolean(L, b); + } + else + { + throw new Exception("No support type " + o.GetType()); + } + } + + public void PushAny(RealStatePtr L, object o) + { + if (o == null) + { + LuaAPI.lua_pushnil(L); + return; + } + + Type type = o.GetType(); + if (type.IsPrimitive()) + { + pushPrimitive(L, o); + } + else if (o is string) + { + LuaAPI.lua_pushstring(L, o as string); + } + else if (type == typeof(byte[])) + { + LuaAPI.lua_pushstring(L, o as byte[]); + } + else if (o is decimal) + { + PushDecimal(L, (decimal)o); + } + else if (o is LuaBase) + { + ((LuaBase)o).push(L); + } + else if (o is LuaCSFunction) + { + Push(L, o as LuaCSFunction); + } + else if (o is ValueType) + { + PushCSObject push; + if (custom_push_funcs.TryGetValue(o.GetType(), out push)) + { + push(L, o); + } + else + { + Push(L, o); + } + } + else + { + Push(L, o); + } + } + + Dictionary enumMap = new Dictionary(); + + public int TranslateToEnumToTop(RealStatePtr L, Type type, int idx) + { + object res = null; + LuaTypes lt = (LuaTypes)LuaAPI.lua_type(L, idx); + if (lt == LuaTypes.LUA_TNUMBER) + { + int ival = (int)LuaAPI.lua_tonumber(L, idx); + res = Enum.ToObject(type, ival); + } + else if (lt == LuaTypes.LUA_TSTRING) + { + string sflags = LuaAPI.lua_tostring(L, idx); + res = Enum.Parse(type, sflags); + } + else + { + return LuaAPI.luaL_error(L, "#1 argument must be a integer or a string"); + } + PushAny(L, res); + return 1; + } + + public void Push(RealStatePtr L, LuaCSFunction o) + { + if (Utils.IsStaticPInvokeCSFunction(o)) + { + LuaAPI.lua_pushstdcallcfunction(L, o); + } + else + { + Push(L, (object)o); + LuaAPI.lua_pushstdcallcfunction(L, metaFunctions.StaticCSFunctionWraper, 1); + } + } + + public void Push(RealStatePtr L, LuaBase o) + { + if (o == null) + { + LuaAPI.lua_pushnil(L); + } + else + { + o.push(L); + } + } + + public void Push(RealStatePtr L, object o) + { + if (o == null) + { + LuaAPI.lua_pushnil(L); + return; + } + + int index = -1; + Type type = o.GetType(); +#if !UNITY_WSA || UNITY_EDITOR + bool is_enum = type.IsEnum; + bool is_valuetype = type.IsValueType; +#else + bool is_enum = type.GetTypeInfo().IsEnum; + bool is_valuetype = type.GetTypeInfo().IsValueType; +#endif + bool needcache = !is_valuetype || is_enum; + if (needcache && (is_enum ? enumMap.TryGetValue(o, out index) : reverseMap.TryGetValue(o, out index))) + { + if (LuaAPI.xlua_tryget_cachedud(L, index, cacheRef) == 1) + { + return; + } + //这里实在太经典了,weaktable先删除,然后GC会延迟调用,当index会循环利用的时候,不注释这行将会导致重复释放 + //collectObject(index); + } + + bool is_first; + int type_id = getTypeId(L, type, out is_first); + + //如果一个type的定义含本身静态readonly实例时,getTypeId会push一个实例,这时候应该用这个实例 + if (is_first && needcache && (is_enum ? enumMap.TryGetValue(o, out index) : reverseMap.TryGetValue(o, out index))) + { + if (LuaAPI.xlua_tryget_cachedud(L, index, cacheRef) == 1) + { + return; + } + } + + index = addObject(o, is_valuetype, is_enum); + LuaAPI.xlua_pushcsobj(L, index, type_id, needcache, cacheRef); + } + + public void PushObject(RealStatePtr L, object o, int type_id) + { + if (o == null) + { + LuaAPI.lua_pushnil(L); + return; + } + + int index = -1; + if (reverseMap.TryGetValue(o, out index)) + { + if (LuaAPI.xlua_tryget_cachedud(L, index, cacheRef) == 1) + { + return; + } + } + + index = addObject(o, false, false); + + LuaAPI.xlua_pushcsobj(L, index, type_id, true, cacheRef); + } + + public void Update(RealStatePtr L, int index, object obj) + { + int udata = LuaAPI.xlua_tocsobj_fast(L, index); + + if (udata != -1) + { + objects.Replace(udata, obj); + } + else + { + UpdateCSObject update; + if (custom_update_funcs.TryGetValue(obj.GetType(), out update)) + { + update(L, index, obj); + } + else + { + throw new Exception("can not update [" + obj + "]"); + } + } + } + + private object getCsObj(RealStatePtr L, int index, int udata) + { + object obj; + if (udata == -1) + { + if (LuaAPI.lua_type(L, index) != LuaTypes.LUA_TUSERDATA) return null; + + Type type = GetTypeOf(L, index); + if (type == typeof(decimal)) + { + decimal v; + Get(L, index, out v); + return v; + } + GetCSObject get; + if (type != null && custom_get_funcs.TryGetValue(type, out get)) + { + return get(L, index); + } + else + { + return null; + } + } + else if (objects.TryGetValue(udata, out obj)) + { +#if !UNITY_5 && !XLUA_GENERAL && !UNITY_2017 && !UNITY_2017_1_OR_NEWER && !UNITY_2018 + if (obj != null && obj is UnityEngine.Object && ((obj as UnityEngine.Object) == null)) + { + //throw new UnityEngine.MissingReferenceException("The object of type '"+ obj.GetType().Name +"' has been destroyed but you are still trying to access it."); + return null; + } +#endif + return obj; + } + return null; + } + + internal object SafeGetCSObj(RealStatePtr L, int index) + { + return getCsObj(L, index, LuaAPI.xlua_tocsobj_safe(L, index)); + } + + internal object FastGetCSObj(RealStatePtr L,int index) + { + return getCsObj(L, index, LuaAPI.xlua_tocsobj_fast(L,index)); + } + + internal void ReleaseCSObj(RealStatePtr L, int index) + { + int udata = LuaAPI.xlua_tocsobj_safe(L, index); + if (udata != -1) + { + object o = objects.Replace(udata, null); + if (o != null && reverseMap.ContainsKey(o)) + { + reverseMap.Remove(o); + } + } + } + + List fix_cs_functions = new List(); + + internal LuaCSFunction GetFixCSFunction(int index) + { + return fix_cs_functions[index]; + } + + internal void PushFixCSFunction(RealStatePtr L, LuaCSFunction func) + { + if (func == null) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.xlua_pushinteger(L, fix_cs_functions.Count); + fix_cs_functions.Add(func); + LuaAPI.lua_pushstdcallcfunction(L, metaFunctions.FixCSFunctionWraper, 1); + } + } + +#if GEN_CODE_MINIMIZE + CSharpWrapper[] csharpWrapper = new CSharpWrapper[0]; + int csharpWrapperSize = 0; + + internal int CallCSharpWrapper(RealStatePtr L, int funcidx, int top) + { + return csharpWrapper[funcidx](L, top); + } + + void ensureCSharpWrapperCapacity(int min) + { + if (csharpWrapper.Length < min) + { + int num = (csharpWrapper.Length == 0) ? 4 : (csharpWrapper.Length * 2); + if (num > 2146435071) + { + num = 2146435071; + } + if (num < min) + { + num = min; + } + + var array = new CSharpWrapper[num]; + Array.Copy(csharpWrapper, 0, array, 0, csharpWrapper.Length); + csharpWrapper = array; + } + } + + internal void PushCSharpWrapper(RealStatePtr L, CSharpWrapper func) + { + if (func == null) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.xlua_push_csharp_wrapper(L, csharpWrapperSize); + ensureCSharpWrapperCapacity(csharpWrapperSize + 1); + csharpWrapper[csharpWrapperSize++] = func; + } + } +#endif + + internal object[] popValues(RealStatePtr L,int oldTop) + { + int newTop=LuaAPI.lua_gettop(L); + if(oldTop==newTop) + { + return null; + } + else + { + ArrayList returnValues=new ArrayList(); + for(int i=oldTop+1;i<=newTop;i++) + { + returnValues.Add(GetObject(L,i)); + } + LuaAPI.lua_settop(L,oldTop); + return returnValues.ToArray(); + } + } + + internal object[] popValues(RealStatePtr L,int oldTop,Type[] popTypes) + { + int newTop=LuaAPI.lua_gettop(L); + if(oldTop==newTop) + { + return null; + } + else + { + int iTypes; + ArrayList returnValues=new ArrayList(); + if(popTypes[0] == typeof(void)) + iTypes=1; + else + iTypes=0; + for(int i=oldTop+1;i<=newTop;i++) + { + returnValues.Add(GetObject(L,i,popTypes[iTypes])); + iTypes++; + } + LuaAPI.lua_settop(L,oldTop); + return returnValues.ToArray(); + } + } + + public delegate void PushCSObject(RealStatePtr L, object obj); + public delegate object GetCSObject(RealStatePtr L, int idx); + public delegate void UpdateCSObject(RealStatePtr L, int idx, object obj); + + private Dictionary custom_push_funcs = new Dictionary(); + private Dictionary custom_get_funcs = new Dictionary(); + private Dictionary custom_update_funcs = new Dictionary(); + + void registerCustomOp(Type type, PushCSObject push, GetCSObject get, UpdateCSObject update) + { + if (push != null) custom_push_funcs.Add(type, push); + if (get != null) custom_get_funcs.Add(type, get); + if (update != null) custom_update_funcs.Add(type, update); + } + + public bool HasCustomOp(Type type) + { + return custom_push_funcs.ContainsKey(type); + } + + private Dictionary push_func_with_type = null; + + bool tryGetPushFuncByType(Type type, out T func) where T : class + { + if (push_func_with_type == null) + { + push_func_with_type = new Dictionary() + { + {typeof(int), new Action(LuaAPI.xlua_pushinteger) }, + {typeof(double), new Action(LuaAPI.lua_pushnumber) }, + {typeof(string), new Action(LuaAPI.lua_pushstring) }, + {typeof(byte[]), new Action(LuaAPI.lua_pushstring) }, + {typeof(bool), new Action(LuaAPI.lua_pushboolean) }, + {typeof(long), new Action(LuaAPI.lua_pushint64) }, + {typeof(ulong), new Action(LuaAPI.lua_pushuint64) }, + {typeof(IntPtr), new Action(LuaAPI.lua_pushlightuserdata) }, + {typeof(decimal), new Action(PushDecimal) }, + {typeof(byte), new Action((L, v) => LuaAPI.xlua_pushinteger(L, v)) }, + {typeof(sbyte), new Action((L, v) => LuaAPI.xlua_pushinteger(L, v)) }, + {typeof(char), new Action((L, v) => LuaAPI.xlua_pushinteger(L, v)) }, + {typeof(short), new Action((L, v) => LuaAPI.xlua_pushinteger(L, v)) }, + {typeof(ushort), new Action((L, v) => LuaAPI.xlua_pushinteger(L, v)) }, + {typeof(uint), new Action(LuaAPI.xlua_pushuint) }, + {typeof(float), new Action((L, v) => LuaAPI.lua_pushnumber(L, v)) }, + }; + } + + Delegate obj; + if (push_func_with_type.TryGetValue(type, out obj)) + { + func = obj as T; + return true; + } + else + { + func = null; + return false; + } + } + + private Dictionary get_func_with_type = null; + + bool tryGetGetFuncByType(Type type, out T func) where T : class + { + if (get_func_with_type == null) + { + get_func_with_type = new Dictionary() + { + {typeof(int), new Func(LuaAPI.xlua_tointeger) }, + {typeof(double), new Func(LuaAPI.lua_tonumber) }, + {typeof(string), new Func(LuaAPI.lua_tostring) }, + {typeof(byte[]), new Func(LuaAPI.lua_tobytes) }, + {typeof(bool), new Func(LuaAPI.lua_toboolean) }, + {typeof(long), new Func(LuaAPI.lua_toint64) }, + {typeof(ulong), new Func(LuaAPI.lua_touint64) }, + {typeof(IntPtr), new Func(LuaAPI.lua_touserdata) }, + {typeof(decimal), new Func((L, idx) => { + decimal ret; + Get(L, idx, out ret); + return ret; + }) }, + {typeof(byte), new Func((L, idx) => (byte)LuaAPI.xlua_tointeger(L, idx) ) }, + {typeof(sbyte), new Func((L, idx) => (sbyte)LuaAPI.xlua_tointeger(L, idx) ) }, + {typeof(char), new Func((L, idx) => (char)LuaAPI.xlua_tointeger(L, idx) ) }, + {typeof(short), new Func((L, idx) => (short)LuaAPI.xlua_tointeger(L, idx) ) }, + {typeof(ushort), new Func((L, idx) => (ushort)LuaAPI.xlua_tointeger(L, idx) ) }, + {typeof(uint), new Func(LuaAPI.xlua_touint) }, + {typeof(float), new Func((L, idx) => (float)LuaAPI.lua_tonumber(L, idx) ) }, + }; + } + + Delegate obj; + if (get_func_with_type.TryGetValue(type, out obj)) + { + func = obj as T; + return true; + } + else + { + func = null; + return false; + } + } + + + public delegate void GetFunc(RealStatePtr L, int idx, out T val); + + public void RegisterPushAndGetAndUpdate(Action push, GetFunc get, Action update) + { + Type type = typeof(T); + Action org_push; + Func org_get; + if (tryGetPushFuncByType(type, out org_push) || tryGetGetFuncByType(type, out org_get)) + { + throw new InvalidOperationException("push or get of " + type + " has register!"); + } + push_func_with_type.Add(type, push); + get_func_with_type.Add(type, new Func((L, idx) => { + T ret; + get(L, idx, out ret); + return ret; + })); + + registerCustomOp(type, + (RealStatePtr L, object obj) => { + push(L, (T)obj); + }, + (RealStatePtr L, int idx) => { + T val; + get(L, idx, out val); + return val; + }, + (RealStatePtr L, int idx, object obj) => { + update(L, idx, (T)obj); + } + ); + } + + public void RegisterCaster(GetFunc get) + { + objectCasters.AddCaster(typeof(T), (L, idx, o) => + { + T obj; + get(L, idx, out obj); + return obj; + }); + } + + int decimal_type_id = -1; + + public void PushDecimal(RealStatePtr L, decimal val) + { + if (decimal_type_id == -1) + { + bool is_first; + decimal_type_id = getTypeId(L, typeof(decimal), out is_first); + } + IntPtr buff = LuaAPI.xlua_pushstruct(L, 16, decimal_type_id); + if (!CopyByValue.Pack(buff, 0, val)) + { + throw new Exception("pack fail for decimal ,value=" + val); + } + + } + + public bool IsDecimal(RealStatePtr L, int index) + { + if (decimal_type_id == -1) return false; + return LuaAPI.xlua_gettypeid(L, index) == decimal_type_id; + } + + public decimal GetDecimal(RealStatePtr L, int index) + { + decimal ret; + Get(L, index, out ret); + return ret; + } + + public void Get(RealStatePtr L, int index, out decimal val) + { + LuaTypes lua_type = LuaAPI.lua_type(L, index); + if (lua_type == LuaTypes.LUA_TUSERDATA) + { + if (LuaAPI.xlua_gettypeid(L, index) != decimal_type_id) + { + throw new Exception("invalid userdata for decimal!"); + } + + IntPtr buff = LuaAPI.lua_touserdata(L, index); + + if (!CopyByValue.UnPack(buff, 0, out val)) + { + throw new Exception("unpack decimal fail!"); + } + } + else if(lua_type == LuaTypes.LUA_TNUMBER) + { + if (LuaAPI.lua_isint64(L, index)) + { + val = (decimal)LuaAPI.lua_toint64(L, index); + } + else + { + val = (decimal)LuaAPI.lua_tonumber(L, index); // has gc + } + } + else + { + throw new Exception("invalid lua value for decimal, LuaType=" + lua_type); + } + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslator.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslator.cs.meta new file mode 100644 index 0000000..0355bf7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslator.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4aa5fdc5a4a25c24f82bed4a3e7ade91 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslatorPool.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslatorPool.cs new file mode 100644 index 0000000..578726d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslatorPool.cs @@ -0,0 +1,114 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System.Collections.Generic; +using System; + +namespace XLua +{ + public class ObjectTranslatorPool + { +#if !SINGLE_ENV + private Dictionary translators = new Dictionary(); + RealStatePtr lastPtr = default(RealStatePtr); +#endif + ObjectTranslator lastTranslator = default(ObjectTranslator); + + public static ObjectTranslatorPool Instance + { + get + { + return InternalGlobals.objectTranslatorPool; + } + } + +#if UNITY_EDITOR || XLUA_GENERAL + public static ObjectTranslator FindTranslator(RealStatePtr L) + { + return InternalGlobals.objectTranslatorPool.Find(L); + } +#endif + + public ObjectTranslatorPool () + { + } + + public void Add (RealStatePtr L, ObjectTranslator translator) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (this) +#endif + { + lastTranslator = translator; +#if !SINGLE_ENV + var ptr = LuaAPI.xlua_gl(L); + lastPtr = ptr; + translators.Add(ptr , new WeakReference(translator)); +#endif + } + } + + public ObjectTranslator Find (RealStatePtr L) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (this) +#endif + { +#if SINGLE_ENV + return lastTranslator; +#else + var ptr = LuaAPI.xlua_gl(L); + if (lastPtr == ptr) return lastTranslator; + if (translators.ContainsKey(ptr)) + { + lastPtr = ptr; + lastTranslator = translators[ptr].Target as ObjectTranslator; + return lastTranslator; + } + + return null; +#endif + } + } + + public void Remove (RealStatePtr L) + { +#if THREAD_SAFE || HOTFIX_ENABLE + lock (this) +#endif + { +#if SINGLE_ENV + lastTranslator = default(ObjectTranslator); +#else + var ptr = LuaAPI.xlua_gl(L); + if (!translators.ContainsKey (ptr)) + return; + + if (lastPtr == ptr) + { + lastPtr = default(RealStatePtr); + lastTranslator = default(ObjectTranslator); + } + + translators.Remove(ptr); +#endif + } + } + } +} + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslatorPool.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslatorPool.cs.meta new file mode 100644 index 0000000..5162c6e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/ObjectTranslatorPool.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c6cbfbc4eba749d4f975bd12a64ab2f3 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/RawObject.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/RawObject.cs new file mode 100644 index 0000000..6f99314 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/RawObject.cs @@ -0,0 +1,106 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +namespace XLua +{ + public interface RawObject + { + object Target { get; } + } +} + +namespace XLua.Cast +{ + public class Any : RawObject + { + T mTarget; + + public Any(T i) + { + mTarget = i; + } + + public object Target + { + get + { + return mTarget; + } + } + } + + public class Byte : Any + { + public Byte(byte i) : base(i) + { + } + } + + public class SByte : Any + { + public SByte(sbyte i) : base(i) + { + } + } + + public class Char : Any + { + public Char(char i) : base(i) + { + } + } + + public class Int16 : Any + { + public Int16(short i) : base(i) + { + } + } + + public class UInt16 : Any + { + public UInt16(ushort i) : base(i) + { + } + } + + public class Int32 : Any + { + public Int32(int i) : base(i) + { + } + } + + public class UInt32 : Any + { + public UInt32(uint i) : base(i) + { + } + } + + public class Int64 : Any + { + public Int64(long i) : base(i) + { + } + } + + public class UInt64 : Any + { + public UInt64(ulong i) : base(i) + { + } + } + + public class Float : Any + { + public Float(float i) : base(i) + { + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/RawObject.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/RawObject.cs.meta new file mode 100644 index 0000000..09898bc --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/RawObject.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f78a41fd6f847504a8102996482647b4 +timeCreated: 1498116130 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/SignatureLoader.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/SignatureLoader.cs new file mode 100644 index 0000000..f8ee7ec --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/SignatureLoader.cs @@ -0,0 +1,73 @@ +#if !UNITY_WSA || UNITY_EDITOR +using System.Security.Cryptography; +#else +using Windows.Security.Cryptography; +using Windows.Security.Cryptography.Core; +#endif +using System; + +namespace XLua +{ + public class SignatureLoader + { + private LuaEnv.CustomLoader userLoader; +#if !UNITY_WSA || UNITY_EDITOR + RSACryptoServiceProvider rsa; + SHA1 sha; +#else + AsymmetricKeyAlgorithmProvider rsa; + CryptographicKey key; +#endif + + public SignatureLoader(string publicKey, LuaEnv.CustomLoader loader) + { +#if !UNITY_WSA || UNITY_EDITOR + rsa = new RSACryptoServiceProvider(); + rsa.ImportCspBlob(Convert.FromBase64String(publicKey)); + sha = new SHA1CryptoServiceProvider(); +#else + rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1); + key = rsa.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey); +#endif + userLoader = loader; + } + + + byte[] load_and_verify(ref string filepath) + { + byte[] data = userLoader(ref filepath); + if (data == null) + { + return null; + } + if (data.Length < 128) + { + throw new InvalidProgramException(filepath + " length less than 128!"); + } + + byte[] sig = new byte[128]; + byte[] filecontent = new byte[data.Length - 128]; + Array.Copy(data, sig, 128); + Array.Copy(data, 128, filecontent, 0, filecontent.Length); + +#if !UNITY_WSA || UNITY_EDITOR + if (!rsa.VerifyData(filecontent, sha, sig)) + { + throw new InvalidProgramException(filepath + " has invalid signature!"); + } +#else + if (!CryptographicEngine.VerifySignature(key, CryptographicBuffer.CreateFromByteArray(filecontent), CryptographicBuffer.CreateFromByteArray(sig))) + { + throw new InvalidProgramException(filepath + " has invalid signature!"); + } +#endif + return filecontent; + } + + + public static implicit operator LuaEnv.CustomLoader(SignatureLoader signatureLoader) + { + return signatureLoader.load_and_verify; + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/SignatureLoader.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/SignatureLoader.cs.meta new file mode 100644 index 0000000..fc1d80e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/SignatureLoader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6e28dadf07647e0488e2457f588007fb +timeCreated: 1489222429 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/StaticLuaCallbacks.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/StaticLuaCallbacks.cs new file mode 100644 index 0000000..4e25a8c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/StaticLuaCallbacks.cs @@ -0,0 +1,1240 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +namespace XLua +{ + using System; + using System.IO; + using System.Reflection; + + public partial class StaticLuaCallbacks + { + internal LuaCSFunction GcMeta, ToStringMeta, EnumAndMeta, EnumOrMeta; + + internal LuaCSFunction StaticCSFunctionWraper, FixCSFunctionWraper; + + internal LuaCSFunction DelegateCtor; + + public StaticLuaCallbacks() + { + GcMeta = new LuaCSFunction(StaticLuaCallbacks.LuaGC); + ToStringMeta = new LuaCSFunction(StaticLuaCallbacks.ToString); + EnumAndMeta = new LuaCSFunction(EnumAnd); + EnumOrMeta = new LuaCSFunction(EnumOr); + StaticCSFunctionWraper = new LuaCSFunction(StaticLuaCallbacks.StaticCSFunction); + FixCSFunctionWraper = new LuaCSFunction(StaticLuaCallbacks.FixCSFunction); + DelegateCtor = new LuaCSFunction(DelegateConstructor); + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int EnumAnd(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object left = translator.FastGetCSObj(L, 1); + object right = translator.FastGetCSObj(L, 2); + Type typeOfLeft = left.GetType(); + if (!typeOfLeft.IsEnum() || typeOfLeft != right.GetType()) + { + return LuaAPI.luaL_error(L, "invalid argument for Enum BitwiseAnd"); + } + translator.PushAny(L, Enum.ToObject(typeOfLeft, Convert.ToInt64(left) & Convert.ToInt64(right))); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in Enum BitwiseAnd:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int EnumOr(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object left = translator.FastGetCSObj(L, 1); + object right = translator.FastGetCSObj(L, 2); + Type typeOfLeft = left.GetType(); + if (!typeOfLeft.IsEnum() || typeOfLeft != right.GetType()) + { + return LuaAPI.luaL_error(L, "invalid argument for Enum BitwiseOr"); + } + translator.PushAny(L, Enum.ToObject(typeOfLeft, Convert.ToInt64(left) | Convert.ToInt64(right))); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in Enum BitwiseOr:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + static int StaticCSFunction(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + LuaCSFunction func = (LuaCSFunction)translator.FastGetCSObj(L, LuaAPI.xlua_upvalueindex(1)); + return func(L); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in StaticCSFunction:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + static int FixCSFunction(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + int idx = LuaAPI.xlua_tointeger(L, LuaAPI.xlua_upvalueindex(1)); + LuaCSFunction func = (LuaCSFunction)translator.GetFixCSFunction(idx); + return func(L); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in FixCSFunction:" + e); + } + } + +#if GEN_CODE_MINIMIZE + [MonoPInvokeCallback(typeof(LuaDLL.CSharpWrapperCaller))] + internal static int CSharpWrapperCallerImpl(RealStatePtr L, int funcidx, int top) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + return translator.CallCSharpWrapper(L, funcidx, top); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception:" + e); + } + } +#endif + +#if GEN_CODE_MINIMIZE + public static int DelegateCall(RealStatePtr L, int top) +#else + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int DelegateCall(RealStatePtr L) +#endif + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object objDelegate = translator.FastGetCSObj(L, 1); + if (objDelegate == null || !(objDelegate is Delegate)) + { + return LuaAPI.luaL_error(L, "trying to invoke a value that is not delegate nor callable"); + } + return translator.methodWrapsCache.GetDelegateWrap(objDelegate.GetType())(L); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in DelegateCall:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int LuaGC(RealStatePtr L) + { + try + { + int udata = LuaAPI.xlua_tocsobj_safe(L, 1); + if (udata != -1) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + if ( translator != null ) + { + translator.collectObject(udata); + } + } + return 0; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in LuaGC:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ToString(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object obj = translator.FastGetCSObj(L, 1); + translator.PushAny(L, obj != null ? (obj.ToString() + ": " + obj.GetHashCode()) : ""); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in ToString:" + e); + } + } + +#if GEN_CODE_MINIMIZE + public static int DelegateCombine(RealStatePtr L, int top) +#else + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int DelegateCombine(RealStatePtr L) +#endif + { + try + { + var translator = ObjectTranslatorPool.Instance.Find(L); + Type type = translator.FastGetCSObj(L, LuaAPI.lua_type(L, 1) == LuaTypes.LUA_TUSERDATA ? 1 : 2).GetType(); + Delegate d1 = translator.GetObject(L, 1, type) as Delegate; + Delegate d2 = translator.GetObject(L, 2, type) as Delegate; + if (d1 == null || d2 == null) + { + return LuaAPI.luaL_error(L, "one parameter must be a delegate, other one must be delegate or function"); + } + translator.PushAny(L, Delegate.Combine(d1, d2)); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in DelegateCombine:" + e); + } + } + +#if GEN_CODE_MINIMIZE + public static int DelegateRemove(RealStatePtr L, int top) +#else + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int DelegateRemove(RealStatePtr L) +#endif + { + try + { + var translator = ObjectTranslatorPool.Instance.Find(L); + Delegate d1 = translator.FastGetCSObj(L, 1) as Delegate; + if (d1 == null) + { + return LuaAPI.luaL_error(L, "#1 parameter must be a delegate"); + } + Delegate d2 = translator.GetObject(L, 2, d1.GetType()) as Delegate; + if (d2 == null) + { + return LuaAPI.luaL_error(L, "#2 parameter must be a delegate or a function "); + } + translator.PushAny(L, Delegate.Remove(d1, d2)); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in DelegateRemove:" + e); + } + } + + static bool tryPrimitiveArrayGet(Type type, RealStatePtr L, object obj, int index) + { + bool ok = true; + + if (type == typeof(int[])) + { + int[] array = obj as int[]; + LuaAPI.xlua_pushinteger(L, array[index]); + } + else if (type == typeof(float[])) + { + float[] array = obj as float[]; + LuaAPI.lua_pushnumber(L, array[index]); + } + else if (type == typeof(double[])) + { + double[] array = obj as double[]; + LuaAPI.lua_pushnumber(L, array[index]); + } + else if (type == typeof(bool[])) + { + bool[] array = obj as bool[]; + LuaAPI.lua_pushboolean(L, array[index]); + } + else if (type == typeof(long[])) + { + long[] array = obj as long[]; + LuaAPI.lua_pushint64(L, array[index]); + } + else if (type == typeof(ulong[])) + { + ulong[] array = obj as ulong[]; + LuaAPI.lua_pushuint64(L, array[index]); + } + else if (type == typeof(sbyte[])) + { + sbyte[] array = obj as sbyte[]; + LuaAPI.xlua_pushinteger(L, array[index]); + } + else if (type == typeof(short[])) + { + short[] array = obj as short[]; + LuaAPI.xlua_pushinteger(L, array[index]); + } + else if (type == typeof(ushort[])) + { + ushort[] array = obj as ushort[]; + LuaAPI.xlua_pushinteger(L, array[index]); + } + else if (type == typeof(char[])) + { + char[] array = obj as char[]; + LuaAPI.xlua_pushinteger(L, array[index]); + } + else if (type == typeof(uint[])) + { + uint[] array = obj as uint[]; + LuaAPI.xlua_pushuint(L, array[index]); + } + else if (type == typeof(IntPtr[])) + { + IntPtr[] array = obj as IntPtr[]; + LuaAPI.lua_pushlightuserdata(L, array[index]); + } + else if (type == typeof(decimal[])) + { + decimal[] array = obj as decimal[]; + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + translator.PushDecimal(L, array[index]); + } + else if (type == typeof(string[])) + { + string[] array = obj as string[]; + LuaAPI.lua_pushstring(L, array[index]); + } + else + { + ok = false; + } + return ok; + } + +#if GEN_CODE_MINIMIZE + public static int ArrayIndexer(RealStatePtr L, int top) +#else + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ArrayIndexer(RealStatePtr L) +#endif + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + System.Array array = (System.Array)translator.FastGetCSObj(L, 1); + + if (array == null) + { + return LuaAPI.luaL_error(L, "#1 parameter is not a array!"); + } + + int i = LuaAPI.xlua_tointeger(L, 2); + + if (i >= array.Length) + { + return LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length); + } + + Type type = array.GetType(); + if (tryPrimitiveArrayGet(type, L, array, i)) + { + return 1; + } + + if (InternalGlobals.genTryArrayGetPtr != null) + { + try + { + if (InternalGlobals.genTryArrayGetPtr(type, L, translator, array, i)) + { + return 1; + } + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace); + } + } + + object ret = array.GetValue(i); + translator.PushAny(L, ret); + + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in ArrayIndexer:" + e); + } + } + + + public static bool TryPrimitiveArraySet(Type type, RealStatePtr L, object obj, int array_idx, int obj_idx) + { + bool ok = true; + + LuaTypes lua_type = LuaAPI.lua_type(L, obj_idx); + + if (type == typeof(int[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + int[] array = obj as int[]; + array[array_idx] = LuaAPI.xlua_tointeger(L, obj_idx); + } + else if (type == typeof(float[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + float[] array = obj as float[]; + array[array_idx] = (float)LuaAPI.lua_tonumber(L, obj_idx); + } + else if (type == typeof(double[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + double[] array = obj as double[]; + array[array_idx] = LuaAPI.lua_tonumber(L, obj_idx); ; + } + else if (type == typeof(bool[]) && lua_type == LuaTypes.LUA_TBOOLEAN) + { + bool[] array = obj as bool[]; + array[array_idx] = LuaAPI.lua_toboolean(L, obj_idx); + } + else if (type == typeof(long[]) && LuaAPI.lua_isint64(L, obj_idx)) + { + long[] array = obj as long[]; + array[array_idx] = LuaAPI.lua_toint64(L, obj_idx); + } + else if (type == typeof(ulong[]) && LuaAPI.lua_isuint64(L, obj_idx)) + { + ulong[] array = obj as ulong[]; + array[array_idx] = LuaAPI.lua_touint64(L, obj_idx); + } + else if (type == typeof(sbyte[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + sbyte[] array = obj as sbyte[]; + array[array_idx] = (sbyte)LuaAPI.xlua_tointeger(L, obj_idx); + } + else if (type == typeof(short[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + short[] array = obj as short[]; + array[array_idx] = (short)LuaAPI.xlua_tointeger(L, obj_idx); + } + else if (type == typeof(ushort[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + ushort[] array = obj as ushort[]; + array[array_idx] = (ushort)LuaAPI.xlua_tointeger(L, obj_idx); + } + else if (type == typeof(char[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + char[] array = obj as char[]; + array[array_idx] = (char)LuaAPI.xlua_tointeger(L, obj_idx); + } + else if (type == typeof(uint[]) && lua_type == LuaTypes.LUA_TNUMBER) + { + uint[] array = obj as uint[]; + array[array_idx] = LuaAPI.xlua_touint(L, obj_idx); + } + else if (type == typeof(IntPtr[]) && lua_type == LuaTypes.LUA_TLIGHTUSERDATA) + { + IntPtr[] array = obj as IntPtr[]; + array[array_idx] = LuaAPI.lua_touserdata(L, obj_idx); + } + else if (type == typeof(decimal[])) + { + decimal[] array = obj as decimal[]; + if (lua_type == LuaTypes.LUA_TNUMBER) + { + array[array_idx] = (decimal)LuaAPI.lua_tonumber(L, obj_idx); + } + + if (lua_type == LuaTypes.LUA_TUSERDATA) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + if (translator.IsDecimal(L, obj_idx)) + { + translator.Get(L, obj_idx, out array[array_idx]); + } + else + { + ok = false; + } + } + else + { + ok = false; + } + } + else if (type == typeof(string[]) && lua_type == LuaTypes.LUA_TSTRING) + { + string[] array = obj as string[]; + array[array_idx] = LuaAPI.lua_tostring(L, obj_idx); + } + else + { + ok = false; + } + return ok; + } + +#if GEN_CODE_MINIMIZE + public static int ArrayNewIndexer(RealStatePtr L, int top) +#else + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ArrayNewIndexer(RealStatePtr L) +#endif + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + System.Array array = (System.Array)translator.FastGetCSObj(L, 1); + + if (array == null) + { + return LuaAPI.luaL_error(L, "#1 parameter is not a array!"); + } + + int i = LuaAPI.xlua_tointeger(L, 2); + + if (i >= array.Length) + { + return LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length); + } + + Type type = array.GetType(); + if (TryPrimitiveArraySet(type, L, array, i, 3)) + { + return 0; + } + + if (InternalGlobals.genTryArraySetPtr != null) + { + try + { + if (InternalGlobals.genTryArraySetPtr(type, L, translator, array, i, 3)) + { + return 0; + } + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace); + } + } + + object val = translator.GetObject(L, 3, type.GetElementType()); + array.SetValue(val, i); + + return 0; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in ArrayNewIndexer:" + e); + } + } + +#if GEN_CODE_MINIMIZE + public static int ArrayLength(RealStatePtr L, int top) +#else + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ArrayLength(RealStatePtr L) +#endif + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + System.Array array = (System.Array)translator.FastGetCSObj(L, 1); + LuaAPI.xlua_pushinteger(L, array.Length); + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in ArrayLength:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int MetaFuncIndex(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type = translator.FastGetCSObj(L, 2) as Type; + if (type == null) + { + return LuaAPI.luaL_error(L, "#2 param need a System.Type!"); + } + //UnityEngine.Debug.Log("============================load type by __index:" + type); + //translator.TryDelayWrapLoader(L, type); + translator.GetTypeId(L, type); + LuaAPI.lua_pushvalue(L, 2); + LuaAPI.lua_rawget(L, 1); + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in MetaFuncIndex:" + e); + } + } + + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int Panic(RealStatePtr L) + { + string reason = String.Format("unprotected error in call to Lua API ({0})", LuaAPI.lua_tostring(L, -1)); + throw new LuaException(reason); + } + +#if !XLUA_GENERAL + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int Print(RealStatePtr L) + { + try + { + int n = LuaAPI.lua_gettop(L); + string s = String.Empty; + + if (0 != LuaAPI.xlua_getglobal(L, "tostring")) + { + return LuaAPI.luaL_error(L, "can not get tostring in print:"); + } + + for (int i = 1; i <= n; i++) + { + LuaAPI.lua_pushvalue(L, -1); /* function to be called */ + LuaAPI.lua_pushvalue(L, i); /* value to print */ + if (0 != LuaAPI.lua_pcall(L, 1, 1, 0)) + { + return LuaAPI.lua_error(L); + } + s += LuaAPI.lua_tostring(L, -1); + + if (i != n) s += "\t"; + + LuaAPI.lua_pop(L, 1); /* pop result */ + } + UnityEngine.Debug.Log("LUA: " + s); + return 0; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in print:" + e); + } + } +#endif + +#if (!UNITY_SWITCH && !UNITY_WEBGL) || UNITY_EDITOR + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LoadSocketCore(RealStatePtr L) + { + return LuaAPI.luaopen_socket_core(L); + } +#endif + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LoadCS(RealStatePtr L) + { + LuaAPI.xlua_pushasciistring(L, LuaEnv.CSHARP_NAMESPACE); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + return 1; + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LoadBuiltinLib(RealStatePtr L) + { + try + { + string builtin_lib = LuaAPI.lua_tostring(L, 1); + + LuaEnv self = ObjectTranslatorPool.Instance.Find(L).luaEnv; + + LuaCSFunction initer; + + if (self.buildin_initer.TryGetValue(builtin_lib, out initer)) + { + LuaAPI.lua_pushstdcallcfunction(L, initer); + } + else + { + LuaAPI.lua_pushstring(L, string.Format( + "\n\tno such builtin lib '{0}'", builtin_lib)); + } + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in LoadBuiltinLib:" + e); + } + } + +#if !XLUA_GENERAL + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LoadFromResource(RealStatePtr L) + { + try + { + string filename = LuaAPI.lua_tostring(L, 1).Replace('.', '/') + ".lua"; + + // Load with Unity3D resources + UnityEngine.TextAsset file = (UnityEngine.TextAsset)UnityEngine.Resources.Load(filename); + if (file == null) + { + LuaAPI.lua_pushstring(L, string.Format( + "\n\tno such resource '{0}'", filename)); + } + else + { + if (LuaAPI.xluaL_loadbuffer(L, file.bytes, file.bytes.Length, "@" + filename) != 0) + { + return LuaAPI.luaL_error(L, String.Format("error loading module {0} from resource, {1}", + LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); + } + } + + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in LoadFromResource:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LoadFromStreamingAssetsPath(RealStatePtr L) + { + try + { + string filename = LuaAPI.lua_tostring(L, 1).Replace('.', '/') + ".lua"; + var filepath = UnityEngine.Application.streamingAssetsPath + "/" + filename; +#if UNITY_ANDROID && !UNITY_EDITOR + UnityEngine.WWW www = new UnityEngine.WWW(filepath); + while (true) + { + if (www.isDone || !string.IsNullOrEmpty(www.error)) + { + System.Threading.Thread.Sleep(50); //�Ƚ�hacker������ + if (!string.IsNullOrEmpty(www.error)) + { + LuaAPI.lua_pushstring(L, string.Format( + "\n\tno such file '{0}' in streamingAssetsPath!", filename)); + } + else + { + UnityEngine.Debug.LogWarning("load lua file from StreamingAssets is obsolete, filename:" + filename); + if (LuaAPI.xluaL_loadbuffer(L, www.bytes, www.bytes.Length , "@" + filename) != 0) + { + return LuaAPI.luaL_error(L, String.Format("error loading module {0} from streamingAssetsPath, {1}", + LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); + } + } + break; + } + } +#else + if (File.Exists(filepath)) + { + // string text = File.ReadAllText(filepath); + var bytes = File.ReadAllBytes(filepath); + + UnityEngine.Debug.LogWarning("load lua file from StreamingAssets is obsolete, filename:" + filename); + if (LuaAPI.xluaL_loadbuffer(L, bytes, bytes.Length, "@" + filename) != 0) + { + return LuaAPI.luaL_error(L, String.Format("error loading module {0} from streamingAssetsPath, {1}", + LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); + } + } + else + { + LuaAPI.lua_pushstring(L, string.Format( + "\n\tno such file '{0}' in streamingAssetsPath!", filename)); + } +#endif + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in LoadFromStreamingAssetsPath:" + e); + } + } +#endif + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LoadFromCustomLoaders(RealStatePtr L) + { + try + { + string filename = LuaAPI.lua_tostring(L, 1); + + LuaEnv self = ObjectTranslatorPool.Instance.Find(L).luaEnv; + + foreach (var loader in self.customLoaders) + { + string real_file_path = filename; + byte[] bytes = loader(ref real_file_path); + if (bytes != null) + { + if (LuaAPI.xluaL_loadbuffer(L, bytes, bytes.Length, "@" + real_file_path) != 0) + { + return LuaAPI.luaL_error(L, String.Format("error loading module {0} from CustomLoader, {1}", + LuaAPI.lua_tostring(L, 1), LuaAPI.lua_tostring(L, -1))); + } + return 1; + } + } + LuaAPI.lua_pushstring(L, string.Format( + "\n\tno such file '{0}' in CustomLoaders!", filename)); + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in LoadFromCustomLoaders:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int LoadAssembly(RealStatePtr L) + { +#if UNITY_WSA && !UNITY_EDITOR + return LuaAPI.luaL_error(L, "xlua.load_assembly no support in uwp!"); +#else + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + string assemblyName = LuaAPI.lua_tostring(L, 1); + + Assembly assembly = null; + + try + { + assembly = Assembly.Load(assemblyName); + } + catch (BadImageFormatException) + { + // The assemblyName was invalid. It is most likely a path. + } + + if (assembly == null) + { + assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName)); + } + + if (assembly != null && !translator.assemblies.Contains(assembly)) + { + translator.assemblies.Add(assembly); + } + return 0; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.load_assembly:" + e); + } +#endif + } + + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ImportType(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + string className = LuaAPI.lua_tostring(L, 1); + Type type = translator.FindType(className); + if (type != null) + { + if (translator.GetTypeId(L, type) >= 0) + { + LuaAPI.lua_pushboolean(L, true); + } + else + { + return LuaAPI.luaL_error(L, "can not load type " + type); + } + } + else + { + LuaAPI.lua_pushnil(L); + } + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.import_type:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ImportGenericType(RealStatePtr L) + { + try + { + int top = LuaAPI.lua_gettop(L); + if (top < 2) return LuaAPI.luaL_error(L, "import generic type need at lease 2 arguments"); + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + string className = LuaAPI.lua_tostring(L, 1); + if (className.EndsWith("<>")) className = className.Substring(0, className.Length - 2); + Type genericDef = translator.FindType(className + "`" + (top - 1)); + if (genericDef == null || !genericDef.IsGenericTypeDefinition()) + { + LuaAPI.lua_pushnil(L); + } + else + { + Type[] typeArguments = new Type[top - 1]; + for(int i = 2; i <= top; i++) + { + + typeArguments[i - 2] = getType(L, translator, i); + if (typeArguments[i - 2] == null) + { + return LuaAPI.luaL_error(L, "param need a type"); + } + } + Type genericInc = genericDef.MakeGenericType(typeArguments); + translator.GetTypeId(L, genericInc); + translator.PushAny(L, genericInc); + } + + return 1; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.import_type:" + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int Cast(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type; + translator.Get(L, 2, out type); + + if (type == null) + { + return LuaAPI.luaL_error(L, "#2 param[" + LuaAPI.lua_tostring(L, 2) + "]is not valid type indicator"); + } + LuaAPI.luaL_getmetatable(L, type.FullName); + if (LuaAPI.lua_isnil(L, -1)) + { + return LuaAPI.luaL_error(L, "no gen code for " + LuaAPI.lua_tostring(L, 2)); + } + LuaAPI.lua_setmetatable(L, 1); + return 0; + } + catch (System.Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.cast:" + e); + } + } + + static Type getType(RealStatePtr L, ObjectTranslator translator, int idx) + { + if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TTABLE) + { + LuaTable tbl; + translator.Get(L, idx, out tbl); + return tbl.Get("UnderlyingSystemType"); + } + else if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING) + { + string className = LuaAPI.lua_tostring(L, idx); + return translator.FindType(className); + } + else if (translator.GetObject(L, idx) is Type) + { + return translator.GetObject(L, idx) as Type; + } + else + { + return null; + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int XLuaAccess(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type = getType(L, translator, 1); + object obj = null; + if (type == null && LuaAPI.lua_type(L, 1) == LuaTypes.LUA_TUSERDATA) + { + obj = translator.SafeGetCSObj(L, 1); + if (obj == null) + { + return LuaAPI.luaL_error(L, "xlua.access, #1 parameter must a type/c# object/string"); + } + type = obj.GetType(); + } + + if (type == null) + { + return LuaAPI.luaL_error(L, "xlua.access, can not find c# type"); + } + + string fieldName = LuaAPI.lua_tostring(L, 2); + + BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + + if (LuaAPI.lua_gettop(L) > 2) // set + { + var field = type.GetField(fieldName, bindingFlags); + if (field != null) + { + field.SetValue(obj, translator.GetObject(L, 3, field.FieldType)); + return 0; + } + var prop = type.GetProperty(fieldName, bindingFlags); + if (prop != null) + { + prop.SetValue(obj, translator.GetObject(L, 3, prop.PropertyType), null); + return 0; + } + } + else + { + var field = type.GetField(fieldName, bindingFlags); + if (field != null) + { + translator.PushAny(L, field.GetValue(obj)); + return 1; + } + var prop = type.GetProperty(fieldName, bindingFlags); + if (prop != null) + { + translator.PushAny(L, prop.GetValue(obj, null)); + return 1; + } + } + return LuaAPI.luaL_error(L, "xlua.access, no field " + fieldName); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.access: " + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int XLuaPrivateAccessible(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type = getType(L, translator, 1); ; + if (type == null) + { + return LuaAPI.luaL_error(L, "xlua.private_accessible, can not find c# type"); + } + + while(type != null) + { + translator.PrivateAccessible(L, type); + type = type.BaseType(); + } + return 0; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.private_accessible: " + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int XLuaMetatableOperation(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type = getType(L, translator, 1); + if (type == null) + { + return LuaAPI.luaL_error(L, "xlua.metatable_operation, can not find c# type"); + } + + bool is_first = false; + int type_id = translator.getTypeId(L, type, out is_first); + + var param_num = LuaAPI.lua_gettop(L); + + if (param_num == 1) //get + { + LuaAPI.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, type_id); + return 1; + } + else if (param_num == 2) //set + { + if (LuaAPI.lua_type(L, 2) != LuaTypes.LUA_TTABLE) + { + return LuaAPI.luaL_error(L, "argument #2 must be a table"); + } + LuaAPI.lua_pushnumber(L, type_id); + LuaAPI.xlua_rawseti(L, 2, 1); + LuaAPI.xlua_rawseti(L, LuaIndexes.LUA_REGISTRYINDEX, type_id); + return 0; + } + else + { + return LuaAPI.luaL_error(L, "invalid argument num for xlua.metatable_operation: " + param_num); + } + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.metatable_operation: " + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int DelegateConstructor(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type = getType(L, translator, 1); + if (type == null || !typeof(Delegate).IsAssignableFrom(type)) + { + return LuaAPI.luaL_error(L, "delegate constructor: #1 argument must be a Delegate's type"); + } + translator.PushAny(L, translator.GetObject(L, 2, type)); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in delegate constructor: " + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ToFunction(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + MethodBase m; + translator.Get(L, 1, out m); + if (m == null) + { + return LuaAPI.luaL_error(L, "ToFunction: #1 argument must be a MethodBase"); + } + translator.PushFixCSFunction(L, + new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(m.DeclaringType, m.Name, new MethodBase[] { m }).Call)); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in ToFunction: " + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int GenericMethodWraper(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + MethodInfo genericMethod; + translator.Get(L, LuaAPI.xlua_upvalueindex(1), out genericMethod); + int n = LuaAPI.lua_gettop(L); + Type[] typeArguments = new Type[n]; + for(int i = 0; i < n; i++) + { + Type type = getType(L, translator, i + 1); + if (type == null) + { + return LuaAPI.luaL_error(L, "param #" + (i + 1) + " is not a type"); + } + typeArguments[i] = type; + } + var method = genericMethod.MakeGenericMethod(typeArguments); + translator.PushFixCSFunction(L, + new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(method.DeclaringType, method.Name, new MethodBase[] { method }).Call)); + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in GenericMethodWraper: " + e); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int GetGenericMethod(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type = getType(L, translator, 1); + if (type == null) + { + return LuaAPI.luaL_error(L, "xlua.get_generic_method, can not find c# type"); + } + string methodName = LuaAPI.lua_tostring(L, 2); + if (string.IsNullOrEmpty(methodName)) + { + return LuaAPI.luaL_error(L, "xlua.get_generic_method, #2 param need a string"); + } + System.Collections.Generic.List matchMethods = new System.Collections.Generic.List(); + var allMethods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); + for(int i = 0; i < allMethods.Length; i++) + { + var method = allMethods[i]; + if (method.Name == methodName && method.IsGenericMethodDefinition) + { + matchMethods.Add(method); + } + } + + int methodIdx = 0; + + if (matchMethods.Count == 0) + { + LuaAPI.lua_pushnil(L); + } + else + { + if (LuaAPI.lua_isinteger(L, 3)) + { + methodIdx = LuaAPI.xlua_tointeger(L, 3); + } + translator.PushAny(L, matchMethods[methodIdx]); + LuaAPI.lua_pushstdcallcfunction(L, GenericMethodWraper, 1); + } + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in xlua.get_generic_method: " + e); + } + return 1; + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + public static int ReleaseCsObject(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + translator.ReleaseCSObj(L, 1); + return 0; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in ReleaseCsObject: " + e); + } + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/StaticLuaCallbacks.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/StaticLuaCallbacks.cs.meta new file mode 100644 index 0000000..bde97f1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/StaticLuaCallbacks.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f980a03d194bc1648a427b1b69f16c88 +timeCreated: 1469175028 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine.meta new file mode 100644 index 0000000..9171a67 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 0cf053c9b20ce404a82943aa02ed6fb3 +folderAsset: yes +DefaultImporter: + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine/TemplateEngine.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine/TemplateEngine.cs new file mode 100644 index 0000000..783c8a6 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine/TemplateEngine.cs @@ -0,0 +1,258 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +using System; +using System.Linq; +using System.Text.RegularExpressions; +using System.Collections.Generic; +using System.Collections; +using System.Text; +using XLua; + +namespace XLua.TemplateEngine +{ + public enum TokenType + { + Code, Eval, Text + } + + public class Chunk + { + public TokenType Type {get; private set;} + public string Text { get; private set; } + public Chunk(TokenType type, string text) + { + Type = type; + Text = text; + } + } + + class TemplateFormatException : Exception + { + public TemplateFormatException(string message) + { + } + } + + public class Parser + { + public static string RegexString + { + get; + private set; + } + + static Parser() + { + RegexString = GetRegexString(); + } + + /// + /// Replaces special characters with their literal representation. + /// + /// Resulting string. + /// Input string. + static string EscapeString(string input) + { + var output = input + .Replace("\\", @"\\") + .Replace("\'", @"\'") + .Replace("\"", @"\""") + .Replace("\n", @"\n") + .Replace("\t", @"\t") + .Replace("\r", @"\r") + .Replace("\b", @"\b") + .Replace("\f", @"\f") + .Replace("\a", @"\a") + .Replace("\v", @"\v") + .Replace("\0", @"\0"); + /* var surrogateMin = (char)0xD800; + var surrogateMax = (char)0xDFFF; + for (char sur = surrogateMin; sur <= surrogateMax; sur++) + output.Replace(sur, '\uFFFD');*/ + return output; + } + + static string GetRegexString() + { + string regexBadUnopened = @"(?((?!<%).)*%>)"; + string regexText = @"(?((?!<%).)+)"; + string regexNoCode = @"(?<%=?%>)"; + string regexCode = @"<%(?[^=]((?!<%|%>).)*)%>"; + string regexEval = @"<%=(?((?!<%|%>).)*)%>"; + string regexBadUnclosed = @"(?<%.*)"; + string regexBadEmpty = @"(?^$)"; + + return '(' + regexBadUnopened + + '|' + regexText + + '|' + regexNoCode + + '|' + regexCode + + '|' + regexEval + + '|' + regexBadUnclosed + + '|' + regexBadEmpty + + ")*"; + } + + /// + /// Parses the string into regex groups, + /// stores group:value pairs in List of Chunk + /// List of group:value pairs.; + /// + public static List Parse(string snippet) + { + Regex templateRegex = new Regex( + RegexString, + RegexOptions.ExplicitCapture | RegexOptions.Singleline + ); + Match matches = templateRegex.Match(snippet); + + if (matches.Groups["error"].Length > 0) + { + throw new TemplateFormatException("Messed up brackets"); + } + + List Chunks = matches.Groups["code"].Captures + .Cast() + .Select(p => new { Type = TokenType.Code, p.Value, p.Index }) + .Concat(matches.Groups["text"].Captures + .Cast() + .Select(p => new { Type = TokenType.Text, Value = EscapeString(p.Value), p.Index })) + .Concat(matches.Groups["eval"].Captures + .Cast() + .Select(p => new { Type = TokenType.Eval, p.Value, p.Index })) + .OrderBy(p => p.Index) + .Select(m => new Chunk(m.Type, m.Value)) + .ToList(); + + if (Chunks.Count == 0) + { + throw new TemplateFormatException("Empty template"); + } + return Chunks; + } + } + + public class LuaTemplate + { + public static string ComposeCode(List chunks) + { + StringBuilder code = new StringBuilder(); + + code.Append("local __text_gen = {}\r\n"); + foreach (var chunk in chunks) + { + switch (chunk.Type) + { + case TokenType.Text: + code.Append("table.insert(__text_gen, \"" + chunk.Text + "\")\r\n"); + break; + case TokenType.Eval: + code.Append("table.insert(__text_gen, tostring(" + chunk.Text + "))\r\n"); + break; + case TokenType.Code: + code.Append(chunk.Text + "\r\n"); + break; + } + } + + code.Append("return table.concat(__text_gen)\r\n"); + //UnityEngine.Debug.Log("code compose:"+code.ToString()); + return code.ToString(); + } + + public static LuaFunction Compile(LuaEnv luaenv, string snippet) + { + return luaenv.LoadString(ComposeCode(Parser.Parse(snippet)), "luatemplate"); + } + + public static string Execute(LuaFunction compiledTemplate, LuaTable parameters) + { + compiledTemplate.SetEnv(parameters); + object[] result = compiledTemplate.Call(); + System.Diagnostics.Debug.Assert(result.Length == 1); + return result[0].ToString(); + } + + public static string Execute(LuaFunction compiledTemplate) + { + object[] result = compiledTemplate.Call(); + System.Diagnostics.Debug.Assert(result.Length == 1); + return result[0].ToString(); + } + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + public static int Compile(RealStatePtr L) + { + string snippet = LuaAPI.lua_tostring(L, 1); + + string code; + try + { + code = ComposeCode(Parser.Parse(snippet)); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, String.Format("template compile error:{0}\r\n", e.Message)); + } + //UnityEngine.Debug.Log("code=" + code); + if (LuaAPI.luaL_loadbuffer(L, code, "luatemplate") != 0) + { + return LuaAPI.lua_error(L); + } + return 1; + } + + [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] + public static int Execute(RealStatePtr L) + { + if (!LuaAPI.lua_isfunction(L, 1)) + { + return LuaAPI.luaL_error(L, "invalid compiled template, function needed!\r\n"); + } + if (LuaAPI.lua_istable(L, 2)) + { + LuaAPI.lua_setfenv(L, 1); + } + LuaAPI.lua_pcall(L, 0, 1, 0); + return 1; + } + + static LuaCSFunction templateCompileFunction = Compile; + static LuaCSFunction templateExecuteFunction = Execute; + + public static void OpenLib(RealStatePtr L) + { + LuaAPI.lua_newtable(L); + LuaAPI.xlua_pushasciistring(L, "compile"); + LuaAPI.lua_pushstdcallcfunction(L, templateCompileFunction); + LuaAPI.lua_rawset(L, -3); + LuaAPI.xlua_pushasciistring(L, "execute"); + LuaAPI.lua_pushstdcallcfunction(L, templateExecuteFunction); + LuaAPI.lua_rawset(L, -3); + if (0 != LuaAPI.xlua_setglobal(L, "template")) + { + throw new Exception("call xlua_setglobal fail!"); + } + } + } +} + + + + + diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine/TemplateEngine.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine/TemplateEngine.cs.meta new file mode 100644 index 0000000..ab56526 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TemplateEngine/TemplateEngine.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5b1d9d27b7e270340815d4e432943f8c +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TypeExtensions.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TypeExtensions.cs new file mode 100644 index 0000000..823bf20 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TypeExtensions.cs @@ -0,0 +1,162 @@ +using System; +using System.Linq; +using System.Reflection; + +namespace XLua +{ + + internal static class TypeExtensions + { + public static bool IsValueType(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsValueType; +#else + return type.GetTypeInfo().IsValueType; +#endif + } + + public static bool IsEnum(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsEnum; +#else + return type.GetTypeInfo().IsEnum; +#endif + } + + public static bool IsPrimitive(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsPrimitive; +#else + return type.GetTypeInfo().IsPrimitive; +#endif + } + + public static bool IsAbstract(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsAbstract; +#else + return type.GetTypeInfo().IsAbstract; +#endif + } + + public static bool IsSealed(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsSealed; +#else + return type.GetTypeInfo().IsSealed; +#endif + } + + public static bool IsInterface(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsInterface; +#else + return type.GetTypeInfo().IsInterface; +#endif + } + + public static bool IsClass(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsClass; +#else + return type.GetTypeInfo().IsClass; +#endif + } + + public static Type BaseType(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.BaseType; +#else + return type.GetTypeInfo().BaseType; +#endif + } + + public static bool IsGenericType(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsGenericType; +#else + return type.GetTypeInfo().IsGenericType; +#endif + } + + public static bool IsGenericTypeDefinition(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsGenericTypeDefinition; +#else + return type.GetTypeInfo().IsGenericTypeDefinition; +#endif + } + +#if UNITY_WSA && !UNITY_EDITOR + public static bool IsSubclassOf(this Type type, Type c) + { + return type.GetTypeInfo().IsSubclassOf(c); + } + + public static bool IsDefined(this Type type, Type attributeType, bool inherit) + { + return type.GetTypeInfo().IsDefined(attributeType, inherit); + } + + public static Type[] GetGenericParameterConstraints(this Type type) + { + return type.GetTypeInfo().GetGenericParameterConstraints(); + } +#endif + + public static bool IsNestedPublic(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsNestedPublic; +#else + return type.GetTypeInfo().IsNestedPublic; +#endif + } + + public static bool IsPublic(this Type type) + { +#if !UNITY_WSA || UNITY_EDITOR + return type.IsPublic; +#else + return type.GetTypeInfo().IsPublic; +#endif + } + + public static string GetFriendlyName(this Type type) + { + if (type == typeof(int)) + return "int"; + else if (type == typeof(short)) + return "short"; + else if (type == typeof(byte)) + return "byte"; + else if (type == typeof(bool)) + return "bool"; + else if (type == typeof(long)) + return "long"; + else if (type == typeof(float)) + return "float"; + else if (type == typeof(double)) + return "double"; + else if (type == typeof(decimal)) + return "decimal"; + else if (type == typeof(string)) + return "string"; + else if (type.IsGenericType()) + return type.FullName.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments() + .Select(x => GetFriendlyName(x)).ToArray()) + ">"; + else + return type.FullName; + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TypeExtensions.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TypeExtensions.cs.meta new file mode 100644 index 0000000..6c900c1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/TypeExtensions.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dc1bfa8d6f6e01948b80214122862647 +timeCreated: 1489998065 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Utils.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Utils.cs new file mode 100644 index 0000000..7de99fd --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Utils.cs @@ -0,0 +1,1539 @@ +/* + * Tencent is pleased to support the open source community by making xLua available. + * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. + * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at + * http://opensource.org/licenses/MIT + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. +*/ + +using System.Collections.Generic; +using System; +using System.Reflection; +using System.Linq; +using System.Runtime.CompilerServices; + +#if USE_UNI_LUA +using LuaAPI = UniLua.Lua; +using RealStatePtr = UniLua.ILuaState; +using LuaCSFunction = UniLua.CSharpFunctionDelegate; +#else +using LuaAPI = XLua.LuaDLL.Lua; +using RealStatePtr = System.IntPtr; +using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; +#endif + +namespace XLua +{ + public enum LazyMemberTypes + { + Method, + FieldGet, + FieldSet, + PropertyGet, + PropertySet, + Event, + } + + public static partial class Utils + { + public static bool LoadField(RealStatePtr L, int idx, string field_name) + { + idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index + LuaAPI.xlua_pushasciistring(L, field_name); + LuaAPI.lua_rawget(L, idx); + return !LuaAPI.lua_isnil(L, -1); + } + + public static RealStatePtr GetMainState(RealStatePtr L) + { + RealStatePtr ret = default(RealStatePtr); + LuaAPI.xlua_pushasciistring(L, LuaEnv.MAIN_SHREAD); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + if (LuaAPI.lua_isthread(L, -1)) + { + ret = LuaAPI.lua_tothread(L, -1); + } + LuaAPI.lua_pop(L, 1); + return ret; + } + +#if (UNITY_WSA && !ENABLE_IL2CPP) && !UNITY_EDITOR + public static List _assemblies; + public static List GetAssemblies() + { + if (_assemblies == null) + { + System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() => + { + _assemblies = GetAssemblyList().Result; + }); + t.Start(); + t.Wait(); + } + return _assemblies; + + } + public static async System.Threading.Tasks.Task> GetAssemblyList() + { + List assemblies = new List(); + //return assemblies; + var files = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFilesAsync(); + if (files == null) + return assemblies; + + foreach (var file in files.Where(file => file.FileType == ".dll" || file.FileType == ".exe")) + { + try + { + assemblies.Add(Assembly.Load(new AssemblyName(file.DisplayName))); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine(ex.Message); + } + + } + return assemblies; + } + public static IEnumerable GetAllTypes(bool exclude_generic_definition = true) + { + var assemblies = GetAssemblies(); + return from assembly in assemblies + where !(assembly.IsDynamic) + from type in assembly.GetTypes() + where exclude_generic_definition ? !type.GetTypeInfo().IsGenericTypeDefinition : true + select type; + } +#else + public static List GetAllTypes(bool exclude_generic_definition = true) + { + List allTypes = new List(); + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + for (int i = 0; i < assemblies.Length; i++) + { + try + { +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + if (!(assemblies[i].ManifestModule is System.Reflection.Emit.ModuleBuilder)) + { +#endif + allTypes.AddRange(assemblies[i].GetTypes() + .Where(type => exclude_generic_definition ? !type.IsGenericTypeDefinition() : true) + ); +#if (UNITY_EDITOR || XLUA_GENERAL) && !NET_STANDARD_2_0 + } +#endif + } + catch (Exception) + { + } + } + + return allTypes; + } +#endif + + static LuaCSFunction genFieldGetter(Type type, FieldInfo field) + { + if (field.IsStatic) + { + return (RealStatePtr L) => + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + translator.PushAny(L, field.GetValue(null)); + return 1; + }; + } + else + { + return (RealStatePtr L) => + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object obj = translator.FastGetCSObj(L, 1); + if (obj == null || !type.IsInstanceOfType(obj)) + { + return LuaAPI.luaL_error(L, "Expected type " + type + ", but got " + (obj == null ? "null" : obj.GetType().ToString()) + ", while get field " + field); + } + + translator.PushAny(L, field.GetValue(obj)); + return 1; + }; + } + } + + static LuaCSFunction genFieldSetter(Type type, FieldInfo field) + { + if (field.IsStatic) + { + return (RealStatePtr L) => + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object val = translator.GetObject(L, 1, field.FieldType); + if (field.FieldType.IsValueType() && Nullable.GetUnderlyingType(field.FieldType) == null && val == null) + { + return LuaAPI.luaL_error(L, type.Name + "." + field.Name + " Expected type " + field.FieldType); + } + field.SetValue(null, val); + return 0; + }; + } + else + { + return (RealStatePtr L) => + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + + object obj = translator.FastGetCSObj(L, 1); + if (obj == null || !type.IsInstanceOfType(obj)) + { + return LuaAPI.luaL_error(L, "Expected type " + type + ", but got " + (obj == null ? "null" : obj.GetType().ToString()) + ", while set field " + field); + } + + object val = translator.GetObject(L, 2, field.FieldType); + if (field.FieldType.IsValueType() && Nullable.GetUnderlyingType(field.FieldType) == null && val == null) + { + return LuaAPI.luaL_error(L, type.Name + "." + field.Name + " Expected type " + field.FieldType); + } + field.SetValue(obj, val); + if (type.IsValueType()) + { + translator.Update(L, 1, obj); + } + return 0; + }; + } + } + + static LuaCSFunction genItemGetter(Type type, PropertyInfo[] props) + { + props = props.Where(prop => !prop.GetIndexParameters()[0].ParameterType.IsAssignableFrom(typeof(string))).ToArray(); + if (props.Length == 0) + { + return null; + } + Type[] params_type = new Type[props.Length]; + for (int i = 0; i < props.Length; i++) + { + params_type[i] = props[i].GetIndexParameters()[0].ParameterType; + } + object[] arg = new object[1] { null }; + return (RealStatePtr L) => + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object obj = translator.FastGetCSObj(L, 1); + if (obj == null || !type.IsInstanceOfType(obj)) + { + return LuaAPI.luaL_error(L, "Expected type " + type + ", but got " + (obj == null ? "null" : obj.GetType().ToString()) + ", while get prop " + props[0].Name); + } + + for (int i = 0; i < props.Length; i++) + { + if (!translator.Assignable(L, 2, params_type[i])) + { + continue; + } + else + { + PropertyInfo prop = props[i]; + try + { + object index = translator.GetObject(L, 2, params_type[i]); + arg[0] = index; + object ret = prop.GetValue(obj, arg); + LuaAPI.lua_pushboolean(L, true); + translator.PushAny(L, ret); + return 2; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "try to get " + type + "." + prop.Name + " throw a exception:" + e + ",stack:" + e.StackTrace); + } + } + } + + LuaAPI.lua_pushboolean(L, false); + return 1; + }; + } + + static LuaCSFunction genItemSetter(Type type, PropertyInfo[] props) + { + props = props.Where(prop => !prop.GetIndexParameters()[0].ParameterType.IsAssignableFrom(typeof(string))).ToArray(); + if (props.Length == 0) + { + return null; + } + Type[] params_type = new Type[props.Length]; + for (int i = 0; i < props.Length; i++) + { + params_type[i] = props[i].GetIndexParameters()[0].ParameterType; + } + object[] arg = new object[1] { null }; + return (RealStatePtr L) => + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + object obj = translator.FastGetCSObj(L, 1); + if (obj == null || !type.IsInstanceOfType(obj)) + { + return LuaAPI.luaL_error(L, "Expected type " + type + ", but got " + (obj == null ? "null" : obj.GetType().ToString()) + ", while set prop " + props[0].Name); + } + + for (int i = 0; i < props.Length; i++) + { + if (!translator.Assignable(L, 2, params_type[i])) + { + continue; + } + else + { + PropertyInfo prop = props[i]; + try + { + arg[0] = translator.GetObject(L, 2, params_type[i]); + object val = translator.GetObject(L, 3, prop.PropertyType); + if (val == null) + { + return LuaAPI.luaL_error(L, type.Name + "." + prop.Name + " Expected type " + prop.PropertyType); + } + prop.SetValue(obj, val, arg); + LuaAPI.lua_pushboolean(L, true); + + return 1; + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "try to set " + type + "." + prop.Name + " throw a exception:" + e + ",stack:" + e.StackTrace); + } + } + } + + LuaAPI.lua_pushboolean(L, false); + return 1; + }; + } + + static LuaCSFunction genEnumCastFrom(Type type) + { + return (RealStatePtr L) => + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + return translator.TranslateToEnumToTop(L, type, 1); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "cast to " + type + " exception:" + e); + } + }; + } + + internal static IEnumerable GetExtensionMethodsOf(Type type_to_be_extend) + { + if (InternalGlobals.extensionMethodMap == null) + { + List type_def_extention_method = new List(); + + IEnumerator enumerator = GetAllTypes().GetEnumerator(); + + while (enumerator.MoveNext()) + { + Type type = enumerator.Current; + if (type.IsDefined(typeof(ExtensionAttribute), false) && ( + type.IsDefined(typeof(ReflectionUseAttribute), false) +#if UNITY_EDITOR || XLUA_GENERAL + || type.IsDefined(typeof(LuaCallCSharpAttribute), false) +#endif + )) + { + type_def_extention_method.Add(type); + } + + if (!type.IsAbstract() || !type.IsSealed()) continue; + + var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < fields.Length; i++) + { + var field = fields[i]; + if ((field.IsDefined(typeof(ReflectionUseAttribute), false) +#if UNITY_EDITOR || XLUA_GENERAL + || field.IsDefined(typeof(LuaCallCSharpAttribute), false) +#endif + ) && (typeof(IEnumerable)).IsAssignableFrom(field.FieldType)) + { + type_def_extention_method.AddRange((field.GetValue(null) as IEnumerable) + .Where(t => t.IsDefined(typeof(ExtensionAttribute), false))); + } + } + + var props = type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); + for (int i = 0; i < props.Length; i++) + { + var prop = props[i]; + if ((prop.IsDefined(typeof(ReflectionUseAttribute), false) +#if UNITY_EDITOR || XLUA_GENERAL + || prop.IsDefined(typeof(LuaCallCSharpAttribute), false) +#endif + ) && (typeof(IEnumerable)).IsAssignableFrom(prop.PropertyType)) + { + type_def_extention_method.AddRange((prop.GetValue(null, null) as IEnumerable) + .Where(t => t.IsDefined(typeof(ExtensionAttribute), false))); + } + } + } + enumerator.Dispose(); + + InternalGlobals.extensionMethodMap = (from type in type_def_extention_method + from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) + where method.IsDefined(typeof(ExtensionAttribute), false) && IsSupportedMethod(method) + group method by getExtendedType(method)).ToDictionary(g => g.Key, g => g as IEnumerable); + } + IEnumerable ret = null; + InternalGlobals.extensionMethodMap.TryGetValue(type_to_be_extend, out ret); + return ret; + } + + struct MethodKey + { + public string Name; + public bool IsStatic; + } + + static void makeReflectionWrap(RealStatePtr L, Type type, int cls_field, int cls_getter, int cls_setter, + int obj_field, int obj_getter, int obj_setter, int obj_meta, out LuaCSFunction item_getter, out LuaCSFunction item_setter, BindingFlags access) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + BindingFlags flag = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | access; + FieldInfo[] fields = type.GetFields(flag); + EventInfo[] all_events = type.GetEvents(flag | BindingFlags.Public | BindingFlags.NonPublic); + + LuaAPI.lua_checkstack(L, 2); + + for (int i = 0; i < fields.Length; ++i) + { + FieldInfo field = fields[i]; + string fieldName = field.Name; + // skip hotfix inject field + if (field.IsStatic && (field.Name.StartsWith("__Hotfix") || field.Name.StartsWith("_c__Hotfix")) && typeof(Delegate).IsAssignableFrom(field.FieldType)) + { + continue; + } + if (all_events.Any(e => e.Name == fieldName)) + { + fieldName = "&" + fieldName; + } + + if (field.IsStatic && (field.IsInitOnly || field.IsLiteral)) + { + LuaAPI.xlua_pushasciistring(L, fieldName); + translator.PushAny(L, field.GetValue(null)); + LuaAPI.lua_rawset(L, cls_field); + } + else + { + LuaAPI.xlua_pushasciistring(L, fieldName); + translator.PushFixCSFunction(L, genFieldGetter(type, field)); + LuaAPI.lua_rawset(L, field.IsStatic ? cls_getter : obj_getter); + + LuaAPI.xlua_pushasciistring(L, fieldName); + translator.PushFixCSFunction(L, genFieldSetter(type, field)); + LuaAPI.lua_rawset(L, field.IsStatic ? cls_setter : obj_setter); + } + } + + EventInfo[] events = type.GetEvents(flag); + for (int i = 0; i < events.Length; ++i) + { + EventInfo eventInfo = events[i]; + LuaAPI.xlua_pushasciistring(L, eventInfo.Name); + translator.PushFixCSFunction(L, translator.methodWrapsCache.GetEventWrap(type, eventInfo.Name)); + bool is_static = (eventInfo.GetAddMethod(true) != null) ? eventInfo.GetAddMethod(true).IsStatic : eventInfo.GetRemoveMethod(true).IsStatic; + LuaAPI.lua_rawset(L, is_static ? cls_field : obj_field); + } + + List items = new List(); + PropertyInfo[] props = type.GetProperties(flag); + for (int i = 0; i < props.Length; ++i) + { + PropertyInfo prop = props[i]; + if (prop.GetIndexParameters().Length > 0) + { + items.Add(prop); + } + } + + var item_array = items.ToArray(); + item_getter = item_array.Length > 0 ? genItemGetter(type, item_array) : null; + item_setter = item_array.Length > 0 ? genItemSetter(type, item_array) : null; + MethodInfo[] methods = type.GetMethods(flag); + if (access == BindingFlags.NonPublic) + { + methods = type.GetMethods(flag | BindingFlags.Public).Join(methods, p => p.Name, q => q.Name, (p, q) => p).ToArray(); + } + Dictionary> pending_methods = new Dictionary>(); + for (int i = 0; i < methods.Length; ++i) + { + MethodInfo method = methods[i]; + string method_name = method.Name; + + MethodKey method_key = new MethodKey { Name = method_name, IsStatic = method.IsStatic }; + List overloads; + if (pending_methods.TryGetValue(method_key, out overloads)) + { + overloads.Add(method); + continue; + } + + //indexer + if (method.IsSpecialName && ((method.Name == "get_Item" && method.GetParameters().Length == 1) || (method.Name == "set_Item" && method.GetParameters().Length == 2))) + { + if (!method.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) + { + continue; + } + } + + if ((method_name.StartsWith("add_") || method_name.StartsWith("remove_")) && method.IsSpecialName) + { + continue; + } + + if (method_name.StartsWith("op_") && method.IsSpecialName) // 操作符 + { + if (InternalGlobals.supportOp.ContainsKey(method_name)) + { + if (overloads == null) + { + overloads = new List(); + pending_methods.Add(method_key, overloads); + } + overloads.Add(method); + } + continue; + } + else if (method_name.StartsWith("get_") && method.IsSpecialName && method.GetParameters().Length != 1) // getter of property + { + string prop_name = method.Name.Substring(4); + LuaAPI.xlua_pushasciistring(L, prop_name); + translator.PushFixCSFunction(L, translator.methodWrapsCache._GenMethodWrap(method.DeclaringType, prop_name, new MethodBase[] { method }).Call); + LuaAPI.lua_rawset(L, method.IsStatic ? cls_getter : obj_getter); + } + else if (method_name.StartsWith("set_") && method.IsSpecialName && method.GetParameters().Length != 2) // setter of property + { + string prop_name = method.Name.Substring(4); + LuaAPI.xlua_pushasciistring(L, prop_name); + translator.PushFixCSFunction(L, translator.methodWrapsCache._GenMethodWrap(method.DeclaringType, prop_name, new MethodBase[] { method }).Call); + LuaAPI.lua_rawset(L, method.IsStatic ? cls_setter : obj_setter); + } + else if (method_name == ".ctor" && method.IsConstructor) + { + continue; + } + else + { + if (overloads == null) + { + overloads = new List(); + pending_methods.Add(method_key, overloads); + } + overloads.Add(method); + } + } + + + IEnumerable extend_methods = GetExtensionMethodsOf(type); + if (extend_methods != null) + { + foreach (var extend_method in extend_methods) + { + MethodKey method_key = new MethodKey { Name = extend_method.Name, IsStatic = false }; + List overloads; + if (pending_methods.TryGetValue(method_key, out overloads)) + { + overloads.Add(extend_method); + continue; + } + else + { + overloads = new List() { extend_method }; + pending_methods.Add(method_key, overloads); + } + } + } + + foreach (var kv in pending_methods) + { + if (kv.Key.Name.StartsWith("op_")) // 操作符 + { + LuaAPI.xlua_pushasciistring(L, InternalGlobals.supportOp[kv.Key.Name]); + translator.PushFixCSFunction(L, + new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(type, kv.Key.Name, kv.Value.ToArray()).Call)); + LuaAPI.lua_rawset(L, obj_meta); + } + else + { + LuaAPI.xlua_pushasciistring(L, kv.Key.Name); + translator.PushFixCSFunction(L, + new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(type, kv.Key.Name, kv.Value.ToArray()).Call)); + LuaAPI.lua_rawset(L, kv.Key.IsStatic ? cls_field : obj_field); + } + } + } + + public static void loadUpvalue(RealStatePtr L, Type type, string metafunc, int index) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + LuaAPI.xlua_pushasciistring(L, metafunc); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + translator.Push(L, type); + LuaAPI.lua_rawget(L, -2); + LuaAPI.lua_remove(L, -2); + for (int i = 1; i <= index; i++) + { + LuaAPI.lua_getupvalue(L, -i, i); + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_pop(L, 1); + LuaAPI.lua_newtable(L); + LuaAPI.lua_pushvalue(L, -1); + LuaAPI.lua_setupvalue(L, -i - 2, i); + } + } + for (int i = 0; i < index; i++) + { + LuaAPI.lua_remove(L, -2); + } + } + + public static void RegisterEnumType(RealStatePtr L, Type type) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + foreach (var name in Enum.GetNames(type)) + { + RegisterObject(L, translator, Utils.CLS_IDX, name, Enum.Parse(type, name)); + } + } + + + public static void MakePrivateAccessible(RealStatePtr L, Type type) + { + LuaAPI.lua_checkstack(L, 20); + + int oldTop = LuaAPI.lua_gettop(L); + + LuaAPI.luaL_getmetatable(L, type.FullName); + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_settop(L, oldTop); + throw new Exception("can not find the metatable for " + type); + } + int obj_meta = LuaAPI.lua_gettop(L); + + LoadCSTable(L, type); + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_settop(L, oldTop); + throw new Exception("can not find the class for " + type); + } + int cls_field = LuaAPI.lua_gettop(L); + + loadUpvalue(L, type, LuaIndexsFieldName, 2); + int obj_getter = LuaAPI.lua_gettop(L); + loadUpvalue(L, type, LuaIndexsFieldName, 1); + int obj_field = LuaAPI.lua_gettop(L); + + loadUpvalue(L, type, LuaNewIndexsFieldName, 1); + int obj_setter = LuaAPI.lua_gettop(L); + + loadUpvalue(L, type, LuaClassIndexsFieldName, 1); + int cls_getter = LuaAPI.lua_gettop(L); + + loadUpvalue(L, type, LuaClassNewIndexsFieldName, 1); + int cls_setter = LuaAPI.lua_gettop(L); + + LuaCSFunction item_getter; + LuaCSFunction item_setter; + makeReflectionWrap(L, type, cls_field, cls_getter, cls_setter, obj_field, obj_getter, obj_setter, obj_meta, + out item_getter, out item_setter, BindingFlags.NonPublic); + LuaAPI.lua_settop(L, oldTop); + + foreach (var nested_type in type.GetNestedTypes(BindingFlags.NonPublic)) + { + if ((!nested_type.IsAbstract() && typeof(Delegate).IsAssignableFrom(nested_type)) + || nested_type.IsGenericTypeDefinition()) + { + continue; + } + ObjectTranslatorPool.Instance.Find(L).TryDelayWrapLoader(L, nested_type); + MakePrivateAccessible(L, nested_type); + } + } + + [MonoPInvokeCallback(typeof(LuaCSFunction))] + internal static int LazyReflectionCall(RealStatePtr L) + { + try + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + Type type; + translator.Get(L, LuaAPI.xlua_upvalueindex(1), out type); + LazyMemberTypes memberType = (LazyMemberTypes)LuaAPI.xlua_tointeger(L, LuaAPI.xlua_upvalueindex(2)); + string memberName = LuaAPI.lua_tostring(L, LuaAPI.xlua_upvalueindex(3)); + bool isStatic = LuaAPI.lua_toboolean(L, LuaAPI.xlua_upvalueindex(4)); + LuaCSFunction wrap = null; + //UnityEngine.Debug.Log(">>>>> " + type + " " + memberName); + + switch (memberType) + { + case LazyMemberTypes.Method: + var members = type.GetMember(memberName); + if (members == null || members.Length == 0) + { + return LuaAPI.luaL_error(L, "can not find " + memberName + " for " + type); + } + IEnumerable methods = members; + if (!isStatic) + { + var extensionMethods = GetExtensionMethodsOf(type); + if (extensionMethods != null) + { + methods = methods.Concat(extensionMethods.Where(m => m.Name == memberName).Cast()); + } + } + wrap = new LuaCSFunction(translator.methodWrapsCache._GenMethodWrap(type, memberName, methods.ToArray()).Call); + if (isStatic) + { + LoadCSTable(L, type); + } + else + { + loadUpvalue(L, type, LuaIndexsFieldName, 1); + } + if (LuaAPI.lua_isnil(L, -1)) + { + return LuaAPI.luaL_error(L, "can not find the meta info for " + type); + } + break; + case LazyMemberTypes.FieldGet: + case LazyMemberTypes.FieldSet: + var field = type.GetField(memberName); + if (field == null) + { + return LuaAPI.luaL_error(L, "can not find " + memberName + " for " + type); + } + if (isStatic) + { + if (memberType == LazyMemberTypes.FieldGet) + { + loadUpvalue(L, type, LuaClassIndexsFieldName, 1); + } + else + { + loadUpvalue(L, type, LuaClassNewIndexsFieldName, 1); + } + } + else + { + if (memberType == LazyMemberTypes.FieldGet) + { + loadUpvalue(L, type, LuaIndexsFieldName, 2); + } + else + { + loadUpvalue(L, type, LuaNewIndexsFieldName, 1); + } + } + + wrap = (memberType == LazyMemberTypes.FieldGet) ? genFieldGetter(type, field) : genFieldSetter(type, field); + + break; + case LazyMemberTypes.PropertyGet: + case LazyMemberTypes.PropertySet: + var prop = type.GetProperty(memberName); + if (prop == null) + { + return LuaAPI.luaL_error(L, "can not find " + memberName + " for " + type); + } + if (isStatic) + { + if (memberType == LazyMemberTypes.PropertyGet) + { + loadUpvalue(L, type, LuaClassIndexsFieldName, 1); + } + else + { + loadUpvalue(L, type, LuaClassNewIndexsFieldName, 1); + } + } + else + { + if (memberType == LazyMemberTypes.PropertyGet) + { + loadUpvalue(L, type, LuaIndexsFieldName, 2); + } + else + { + loadUpvalue(L, type, LuaNewIndexsFieldName, 1); + } + } + + if (LuaAPI.lua_isnil(L, -1)) + { + return LuaAPI.luaL_error(L, "can not find the meta info for " + type); + } + + wrap = translator.methodWrapsCache._GenMethodWrap(prop.DeclaringType, prop.Name, new MethodBase[] { (memberType == LazyMemberTypes.PropertyGet) ? prop.GetGetMethod() : prop.GetSetMethod() }).Call; + break; + case LazyMemberTypes.Event: + var eventInfo = type.GetEvent(memberName); + if (eventInfo == null) + { + return LuaAPI.luaL_error(L, "can not find " + memberName + " for " + type); + } + if (isStatic) + { + LoadCSTable(L, type); + } + else + { + loadUpvalue(L, type, LuaIndexsFieldName, 1); + } + if (LuaAPI.lua_isnil(L, -1)) + { + return LuaAPI.luaL_error(L, "can not find the meta info for " + type); + } + wrap = translator.methodWrapsCache.GetEventWrap(type, eventInfo.Name); + break; + default: + return LuaAPI.luaL_error(L, "unsupport member type" + memberType); + } + + LuaAPI.xlua_pushasciistring(L, memberName); + translator.PushFixCSFunction(L, wrap); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + return wrap(L); + } + catch (Exception e) + { + return LuaAPI.luaL_error(L, "c# exception in LazyReflectionCall:" + e); + } + } + + public static void ReflectionWrap(RealStatePtr L, Type type, bool privateAccessible) + { + LuaAPI.lua_checkstack(L, 20); + + int top_enter = LuaAPI.lua_gettop(L); + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + //create obj meta table + LuaAPI.luaL_getmetatable(L, type.FullName); + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_pop(L, 1); + LuaAPI.luaL_newmetatable(L, type.FullName); + } + LuaAPI.lua_pushlightuserdata(L, LuaAPI.xlua_tag()); + LuaAPI.lua_pushnumber(L, 1); + LuaAPI.lua_rawset(L, -3); + int obj_meta = LuaAPI.lua_gettop(L); + + LuaAPI.lua_newtable(L); + int cls_meta = LuaAPI.lua_gettop(L); + + LuaAPI.lua_newtable(L); + int obj_field = LuaAPI.lua_gettop(L); + LuaAPI.lua_newtable(L); + int obj_getter = LuaAPI.lua_gettop(L); + LuaAPI.lua_newtable(L); + int obj_setter = LuaAPI.lua_gettop(L); + LuaAPI.lua_newtable(L); + int cls_field = LuaAPI.lua_gettop(L); + //set cls_field to namespace + SetCSTable(L, type, cls_field); + //finish set cls_field to namespace + LuaAPI.lua_newtable(L); + int cls_getter = LuaAPI.lua_gettop(L); + LuaAPI.lua_newtable(L); + int cls_setter = LuaAPI.lua_gettop(L); + + LuaCSFunction item_getter; + LuaCSFunction item_setter; + makeReflectionWrap(L, type, cls_field, cls_getter, cls_setter, obj_field, obj_getter, obj_setter, obj_meta, + out item_getter, out item_setter, privateAccessible ? (BindingFlags.Public | BindingFlags.NonPublic) : BindingFlags.Public); + + // init obj metatable + LuaAPI.xlua_pushasciistring(L, "__gc"); + LuaAPI.lua_pushstdcallcfunction(L, translator.metaFunctions.GcMeta); + LuaAPI.lua_rawset(L, obj_meta); + + LuaAPI.xlua_pushasciistring(L, "__tostring"); + LuaAPI.lua_pushstdcallcfunction(L, translator.metaFunctions.ToStringMeta); + LuaAPI.lua_rawset(L, obj_meta); + + LuaAPI.xlua_pushasciistring(L, "__index"); + LuaAPI.lua_pushvalue(L, obj_field); + LuaAPI.lua_pushvalue(L, obj_getter); + translator.PushFixCSFunction(L, item_getter); + translator.PushAny(L, type.BaseType()); + LuaAPI.xlua_pushasciistring(L, LuaIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.lua_pushnil(L); + LuaAPI.gen_obj_indexer(L); + //store in lua indexs function tables + LuaAPI.xlua_pushasciistring(L, LuaIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + LuaAPI.lua_rawset(L, obj_meta); // set __index + + LuaAPI.xlua_pushasciistring(L, "__newindex"); + LuaAPI.lua_pushvalue(L, obj_setter); + translator.PushFixCSFunction(L, item_setter); + translator.Push(L, type.BaseType()); + LuaAPI.xlua_pushasciistring(L, LuaNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.lua_pushnil(L); + LuaAPI.gen_obj_newindexer(L); + //store in lua newindexs function tables + LuaAPI.xlua_pushasciistring(L, LuaNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + LuaAPI.lua_rawset(L, obj_meta); // set __newindex + //finish init obj metatable + + LuaAPI.xlua_pushasciistring(L, "UnderlyingSystemType"); + translator.PushAny(L, type); + LuaAPI.lua_rawset(L, cls_field); + + if (type != null && type.IsEnum()) + { + LuaAPI.xlua_pushasciistring(L, "__CastFrom"); + translator.PushFixCSFunction(L, genEnumCastFrom(type)); + LuaAPI.lua_rawset(L, cls_field); + } + + //init class meta + LuaAPI.xlua_pushasciistring(L, "__index"); + LuaAPI.lua_pushvalue(L, cls_getter); + LuaAPI.lua_pushvalue(L, cls_field); + translator.Push(L, type.BaseType()); + LuaAPI.xlua_pushasciistring(L, LuaClassIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.gen_cls_indexer(L); + //store in lua indexs function tables + LuaAPI.xlua_pushasciistring(L, LuaClassIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + LuaAPI.lua_rawset(L, cls_meta); // set __index + + LuaAPI.xlua_pushasciistring(L, "__newindex"); + LuaAPI.lua_pushvalue(L, cls_setter); + translator.Push(L, type.BaseType()); + LuaAPI.xlua_pushasciistring(L, LuaClassNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.gen_cls_newindexer(L); + //store in lua newindexs function tables + LuaAPI.xlua_pushasciistring(L, LuaClassNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + LuaAPI.lua_rawset(L, cls_meta); // set __newindex + + LuaCSFunction constructor = typeof(Delegate).IsAssignableFrom(type) ? translator.metaFunctions.DelegateCtor : translator.methodWrapsCache.GetConstructorWrap(type); + if (constructor == null) + { + constructor = (RealStatePtr LL) => + { + return LuaAPI.luaL_error(LL, "No constructor for " + type); + }; + } + + LuaAPI.xlua_pushasciistring(L, "__call"); + translator.PushFixCSFunction(L, constructor); + LuaAPI.lua_rawset(L, cls_meta); + + LuaAPI.lua_pushvalue(L, cls_meta); + LuaAPI.lua_setmetatable(L, cls_field); + + LuaAPI.lua_pop(L, 8); + + System.Diagnostics.Debug.Assert(top_enter == LuaAPI.lua_gettop(L)); + } + + //meta: -4, method:-3, getter: -2, setter: -1 + public static void BeginObjectRegister(Type type, RealStatePtr L, ObjectTranslator translator, int meta_count, int method_count, int getter_count, + int setter_count, int type_id = -1) + { + if (type == null) + { + if (type_id == -1) throw new Exception("Fatal: must provide a type of type_id"); + LuaAPI.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, type_id); + } + else + { + LuaAPI.luaL_getmetatable(L, type.FullName); + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_pop(L, 1); + LuaAPI.luaL_newmetatable(L, type.FullName); + } + } + LuaAPI.lua_pushlightuserdata(L, LuaAPI.xlua_tag()); + LuaAPI.lua_pushnumber(L, 1); + LuaAPI.lua_rawset(L, -3); + + if ((type == null || !translator.HasCustomOp(type)) && type != typeof(decimal)) + { + LuaAPI.xlua_pushasciistring(L, "__gc"); + LuaAPI.lua_pushstdcallcfunction(L, translator.metaFunctions.GcMeta); + LuaAPI.lua_rawset(L, -3); + } + + LuaAPI.xlua_pushasciistring(L, "__tostring"); + LuaAPI.lua_pushstdcallcfunction(L, translator.metaFunctions.ToStringMeta); + LuaAPI.lua_rawset(L, -3); + + if (method_count == 0) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.lua_createtable(L, 0, method_count); + } + + if (getter_count == 0) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.lua_createtable(L, 0, getter_count); + } + + if (setter_count == 0) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.lua_createtable(L, 0, setter_count); + } + } + + static int abs_idx(int top, int idx) + { + return idx > 0 ? idx : top + idx + 1; + } + + public const int OBJ_META_IDX = -4; + public const int METHOD_IDX = -3; + public const int GETTER_IDX = -2; + public const int SETTER_IDX = -1; + +#if GEN_CODE_MINIMIZE + public static void EndObjectRegister(Type type, RealStatePtr L, ObjectTranslator translator, CSharpWrapper csIndexer, + CSharpWrapper csNewIndexer, Type base_type, CSharpWrapper arrayIndexer, CSharpWrapper arrayNewIndexer) +#else + public static void EndObjectRegister(Type type, RealStatePtr L, ObjectTranslator translator, LuaCSFunction csIndexer, + LuaCSFunction csNewIndexer, Type base_type, LuaCSFunction arrayIndexer, LuaCSFunction arrayNewIndexer) +#endif + { + int top = LuaAPI.lua_gettop(L); + int meta_idx = abs_idx(top, OBJ_META_IDX); + int method_idx = abs_idx(top, METHOD_IDX); + int getter_idx = abs_idx(top, GETTER_IDX); + int setter_idx = abs_idx(top, SETTER_IDX); + + //begin index gen + LuaAPI.xlua_pushasciistring(L, "__index"); + LuaAPI.lua_pushvalue(L, method_idx); + LuaAPI.lua_pushvalue(L, getter_idx); + + if (csIndexer == null) + { + LuaAPI.lua_pushnil(L); + } + else + { +#if GEN_CODE_MINIMIZE + translator.PushCSharpWrapper(L, csIndexer); +#else + LuaAPI.lua_pushstdcallcfunction(L, csIndexer); +#endif + } + + translator.Push(L, type == null ? base_type : type.BaseType()); + + LuaAPI.xlua_pushasciistring(L, LuaIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + if (arrayIndexer == null) + { + LuaAPI.lua_pushnil(L); + } + else + { +#if GEN_CODE_MINIMIZE + translator.PushCSharpWrapper(L, arrayIndexer); +#else + LuaAPI.lua_pushstdcallcfunction(L, arrayIndexer); +#endif + } + + LuaAPI.gen_obj_indexer(L); + + if (type != null) + { + LuaAPI.xlua_pushasciistring(L, LuaIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);//store in lua indexs function tables + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + } + + LuaAPI.lua_rawset(L, meta_idx); + //end index gen + + //begin newindex gen + LuaAPI.xlua_pushasciistring(L, "__newindex"); + LuaAPI.lua_pushvalue(L, setter_idx); + + if (csNewIndexer == null) + { + LuaAPI.lua_pushnil(L); + } + else + { +#if GEN_CODE_MINIMIZE + translator.PushCSharpWrapper(L, csNewIndexer); +#else + LuaAPI.lua_pushstdcallcfunction(L, csNewIndexer); +#endif + } + + translator.Push(L, type == null ? base_type : type.BaseType()); + + LuaAPI.xlua_pushasciistring(L, LuaNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + + if (arrayNewIndexer == null) + { + LuaAPI.lua_pushnil(L); + } + else + { +#if GEN_CODE_MINIMIZE + translator.PushCSharpWrapper(L, arrayNewIndexer); +#else + LuaAPI.lua_pushstdcallcfunction(L, arrayNewIndexer); +#endif + } + + LuaAPI.gen_obj_newindexer(L); + + if (type != null) + { + LuaAPI.xlua_pushasciistring(L, LuaNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);//store in lua newindexs function tables + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + } + + LuaAPI.lua_rawset(L, meta_idx); + //end new index gen + LuaAPI.lua_pop(L, 4); + } + +#if GEN_CODE_MINIMIZE + public static void RegisterFunc(RealStatePtr L, int idx, string name, CSharpWrapper func) + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + idx = abs_idx(LuaAPI.lua_gettop(L), idx); + LuaAPI.xlua_pushasciistring(L, name); + translator.PushCSharpWrapper(L, func); + LuaAPI.lua_rawset(L, idx); + } +#else + public static void RegisterFunc(RealStatePtr L, int idx, string name, LuaCSFunction func) + { + idx = abs_idx(LuaAPI.lua_gettop(L), idx); + LuaAPI.xlua_pushasciistring(L, name); + LuaAPI.lua_pushstdcallcfunction(L, func); + LuaAPI.lua_rawset(L, idx); + } +#endif + + public static void RegisterLazyFunc(RealStatePtr L, int idx, string name, Type type, LazyMemberTypes memberType, bool isStatic) + { + idx = abs_idx(LuaAPI.lua_gettop(L), idx); + LuaAPI.xlua_pushasciistring(L, name); + + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + translator.PushAny(L, type); + LuaAPI.xlua_pushinteger(L, (int)memberType); + LuaAPI.lua_pushstring(L, name); + LuaAPI.lua_pushboolean(L, isStatic); + LuaAPI.lua_pushstdcallcfunction(L, InternalGlobals.LazyReflectionWrap, 4); + LuaAPI.lua_rawset(L, idx); + } + + public static void RegisterObject(RealStatePtr L, ObjectTranslator translator, int idx, string name, object obj) + { + idx = abs_idx(LuaAPI.lua_gettop(L), idx); + LuaAPI.xlua_pushasciistring(L, name); + translator.PushAny(L, obj); + LuaAPI.lua_rawset(L, idx); + } + +#if GEN_CODE_MINIMIZE + public static void BeginClassRegister(Type type, RealStatePtr L, CSharpWrapper creator, int class_field_count, + int static_getter_count, int static_setter_count) +#else + public static void BeginClassRegister(Type type, RealStatePtr L, LuaCSFunction creator, int class_field_count, + int static_getter_count, int static_setter_count) +#endif + { + ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); + LuaAPI.lua_createtable(L, 0, class_field_count); + + LuaAPI.xlua_pushasciistring(L, "UnderlyingSystemType"); + translator.PushAny(L, type); + LuaAPI.lua_rawset(L, -3); + + int cls_table = LuaAPI.lua_gettop(L); + + SetCSTable(L, type, cls_table); + + LuaAPI.lua_createtable(L, 0, 3); + int meta_table = LuaAPI.lua_gettop(L); + if (creator != null) + { + LuaAPI.xlua_pushasciistring(L, "__call"); +#if GEN_CODE_MINIMIZE + translator.PushCSharpWrapper(L, creator); +#else + LuaAPI.lua_pushstdcallcfunction(L, creator); +#endif + LuaAPI.lua_rawset(L, -3); + } + + if (static_getter_count == 0) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.lua_createtable(L, 0, static_getter_count); + } + + if (static_setter_count == 0) + { + LuaAPI.lua_pushnil(L); + } + else + { + LuaAPI.lua_createtable(L, 0, static_setter_count); + } + LuaAPI.lua_pushvalue(L, meta_table); + LuaAPI.lua_setmetatable(L, cls_table); + } + + public const int CLS_IDX = -4; + public const int CLS_META_IDX = -3; + public const int CLS_GETTER_IDX = -2; + public const int CLS_SETTER_IDX = -1; + + public static void EndClassRegister(Type type, RealStatePtr L, ObjectTranslator translator) + { + int top = LuaAPI.lua_gettop(L); + int cls_idx = abs_idx(top, CLS_IDX); + int cls_getter_idx = abs_idx(top, CLS_GETTER_IDX); + int cls_setter_idx = abs_idx(top, CLS_SETTER_IDX); + int cls_meta_idx = abs_idx(top, CLS_META_IDX); + + //begin cls index + LuaAPI.xlua_pushasciistring(L, "__index"); + LuaAPI.lua_pushvalue(L, cls_getter_idx); + LuaAPI.lua_pushvalue(L, cls_idx); + translator.Push(L, type.BaseType()); + LuaAPI.xlua_pushasciistring(L, LuaClassIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.gen_cls_indexer(L); + + LuaAPI.xlua_pushasciistring(L, LuaClassIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);//store in lua indexs function tables + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + + LuaAPI.lua_rawset(L, cls_meta_idx); + //end cls index + + //begin cls newindex + LuaAPI.xlua_pushasciistring(L, "__newindex"); + LuaAPI.lua_pushvalue(L, cls_setter_idx); + translator.Push(L, type.BaseType()); + LuaAPI.xlua_pushasciistring(L, LuaClassNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + LuaAPI.gen_cls_newindexer(L); + + LuaAPI.xlua_pushasciistring(L, LuaClassNewIndexsFieldName); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);//store in lua newindexs function tables + translator.Push(L, type); + LuaAPI.lua_pushvalue(L, -3); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + + LuaAPI.lua_rawset(L, cls_meta_idx); + //end cls newindex + + LuaAPI.lua_pop(L, 4); + } + + static List getPathOfType(Type type) + { + List path = new List(); + + if (type.Namespace != null) + { + path.AddRange(type.Namespace.Split(new char[] { '.' })); + } + + string class_name = type.ToString().Substring(type.Namespace == null ? 0 : type.Namespace.Length + 1); + + if (type.IsNested) + { + path.AddRange(class_name.Split(new char[] { '+' })); + } + else + { + path.Add(class_name); + } + return path; + } + + public static void LoadCSTable(RealStatePtr L, Type type) + { + int oldTop = LuaAPI.lua_gettop(L); + LuaAPI.xlua_pushasciistring(L, LuaEnv.CSHARP_NAMESPACE); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + + List path = getPathOfType(type); + + for (int i = 0; i < path.Count; ++i) + { + LuaAPI.xlua_pushasciistring(L, path[i]); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + LuaAPI.lua_settop(L, oldTop); + LuaAPI.lua_pushnil(L); + return; + } + if (!LuaAPI.lua_istable(L, -1) && i < path.Count - 1) + { + LuaAPI.lua_settop(L, oldTop); + LuaAPI.lua_pushnil(L); + return; + } + LuaAPI.lua_remove(L, -2); + } + } + + public static void SetCSTable(RealStatePtr L, Type type, int cls_table) + { + int oldTop = LuaAPI.lua_gettop(L); + cls_table = abs_idx(oldTop, cls_table); + LuaAPI.xlua_pushasciistring(L, LuaEnv.CSHARP_NAMESPACE); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + + List path = getPathOfType(type); + + for (int i = 0; i < path.Count - 1; ++i) + { + LuaAPI.xlua_pushasciistring(L, path[i]); + if (0 != LuaAPI.xlua_pgettable(L, -2)) + { + var err = LuaAPI.lua_tostring(L, -1); + LuaAPI.lua_settop(L, oldTop); + throw new Exception("SetCSTable for [" + type + "] error: " + err); + } + if (LuaAPI.lua_isnil(L, -1)) + { + LuaAPI.lua_pop(L, 1); + LuaAPI.lua_createtable(L, 0, 0); + LuaAPI.xlua_pushasciistring(L, path[i]); + LuaAPI.lua_pushvalue(L, -2); + LuaAPI.lua_rawset(L, -4); + } + else if (!LuaAPI.lua_istable(L, -1)) + { + LuaAPI.lua_settop(L, oldTop); + throw new Exception("SetCSTable for [" + type + "] error: ancestors is not a table!"); + } + LuaAPI.lua_remove(L, -2); + } + + LuaAPI.xlua_pushasciistring(L, path[path.Count - 1]); + LuaAPI.lua_pushvalue(L, cls_table); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + + LuaAPI.xlua_pushasciistring(L, LuaEnv.CSHARP_NAMESPACE); + LuaAPI.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX); + ObjectTranslatorPool.Instance.Find(L).PushAny(L, type); + LuaAPI.lua_pushvalue(L, cls_table); + LuaAPI.lua_rawset(L, -3); + LuaAPI.lua_pop(L, 1); + } + + public const string LuaIndexsFieldName = "LuaIndexs"; + + public const string LuaNewIndexsFieldName = "LuaNewIndexs"; + + public const string LuaClassIndexsFieldName = "LuaClassIndexs"; + + public const string LuaClassNewIndexsFieldName = "LuaClassNewIndexs"; + + public static bool IsParamsMatch(MethodInfo delegateMethod, MethodInfo bridgeMethod) + { + if (delegateMethod == null || bridgeMethod == null) + { + return false; + } + if (delegateMethod.ReturnType != bridgeMethod.ReturnType) + { + return false; + } + ParameterInfo[] delegateParams = delegateMethod.GetParameters(); + ParameterInfo[] bridgeParams = bridgeMethod.GetParameters(); + if (delegateParams.Length != bridgeParams.Length) + { + return false; + } + + for (int i = 0; i < delegateParams.Length; i++) + { + if (delegateParams[i].ParameterType != bridgeParams[i].ParameterType || delegateParams[i].IsOut != bridgeParams[i].IsOut) + { + return false; + } + } + + var lastPos = delegateParams.Length - 1; + return lastPos < 0 || delegateParams[lastPos].IsDefined(typeof(ParamArrayAttribute), false) == bridgeParams[lastPos].IsDefined(typeof(ParamArrayAttribute), false); + } + + public static bool IsSupportedMethod(MethodInfo method) + { + if (!method.ContainsGenericParameters) + return true; + var methodParameters = method.GetParameters(); + var returnType = method.ReturnType; + var hasValidGenericParameter = false; + var returnTypeValid = !returnType.IsGenericParameter; + for (var i = 0; i < methodParameters.Length; i++) + { + var parameterType = methodParameters[i].ParameterType; + if (parameterType.IsGenericParameter) + { + var parameterConstraints = parameterType.GetGenericParameterConstraints(); + if (parameterConstraints.Length == 0) return false; + foreach (var parameterConstraint in parameterConstraints) + { + if (!parameterConstraint.IsClass() || (parameterConstraint == typeof(ValueType))) + return false; + } + hasValidGenericParameter = true; + if (!returnTypeValid) + { + if (parameterType == returnType) + { + returnTypeValid = true; + } + } + } + } + return hasValidGenericParameter && returnTypeValid; + } + + public static MethodInfo MakeGenericMethodWithConstraints(MethodInfo method) + { + try + { + var genericArguments = method.GetGenericArguments(); + var constraintedArgumentTypes = new Type[genericArguments.Length]; + for (var i = 0; i < genericArguments.Length; i++) + { + var argumentType = genericArguments[i]; + var parameterConstraints = argumentType.GetGenericParameterConstraints(); + constraintedArgumentTypes[i] = parameterConstraints[0]; + } + return method.MakeGenericMethod(constraintedArgumentTypes); + } + catch (Exception) + { + return null; + } + } + + private static Type getExtendedType(MethodInfo method) + { + var type = method.GetParameters()[0].ParameterType; + if (!type.IsGenericParameter) + return type; + var parameterConstraints = type.GetGenericParameterConstraints(); + if (parameterConstraints.Length == 0) + throw new InvalidOperationException(); + + var firstParameterConstraint = parameterConstraints[0]; + if (!firstParameterConstraint.IsClass()) + throw new InvalidOperationException(); + return firstParameterConstraint; + } + + public static bool IsStaticPInvokeCSFunction(LuaCSFunction csFunction) + { +#if UNITY_WSA && !UNITY_EDITOR + return csFunction.GetMethodInfo().IsStatic && csFunction.GetMethodInfo().GetCustomAttribute() != null; +#else + return csFunction.Method.IsStatic && Attribute.IsDefined(csFunction.Method, typeof(MonoPInvokeCallbackAttribute)); +#endif + } + + public static bool IsPublic(Type type) + { + if (type.IsNested) + { + if (!type.IsNestedPublic()) return false; + return IsPublic(type.DeclaringType); + } + if (type.IsGenericType()) + { + var gas = type.GetGenericArguments(); + for (int i = 0; i < gas.Length; i++) + { + if (!IsPublic(gas[i])) + { + return false; + } + } + } + return type.IsPublic(); + } + } +} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Utils.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Utils.cs.meta new file mode 100644 index 0000000..48a62f2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/Src/Utils.cs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 35288ec7283a01b4c9b9489df2e23c6e +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util.meta new file mode 100644 index 0000000..8da2bfd --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ac066b0ba0bed9649a0f5b985ff1a206 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util/Xxtea.cs b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util/Xxtea.cs new file mode 100644 index 0000000..c5a1402 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util/Xxtea.cs @@ -0,0 +1,193 @@ +/**********************************************************\ +| | +| XXTEA.cs | +| | +| XXTEA encryption algorithm library for .NET. | +| | +| Encryption Algorithm Authors: | +| David J. Wheeler | +| Roger M. Needham | +| | +| Code Author: Ma Bingyao | +| LastModified: Mar 10, 2015 | +| | +\**********************************************************/ + +namespace Security { + using System; + using System.Text; + + public sealed class XXTEA { + private static readonly UTF8Encoding utf8 = new UTF8Encoding(); + + private const UInt32 delta = 0x9E3779B9; + + private static UInt32 MX(UInt32 sum, UInt32 y, UInt32 z, Int32 p, UInt32 e, UInt32[] k) { + return (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z); + } + + private XXTEA() { + } + + public static Byte[] Encrypt(Byte[] data, Byte[] key) { + if (data.Length == 0) { + return data; + } + return ToByteArray(Encrypt(ToUInt32Array(data, true), ToUInt32Array(FixKey(key), false)), false); + } + + public static Byte[] Encrypt(String data, Byte[] key) { + return Encrypt(utf8.GetBytes(data), key); + } + + public static Byte[] Encrypt(Byte[] data, String key) { + return Encrypt(data, utf8.GetBytes(key)); + } + + public static Byte[] Encrypt(String data, String key) { + return Encrypt(utf8.GetBytes(data), utf8.GetBytes(key)); + } + + public static String EncryptToBase64String(Byte[] data, Byte[] key) { + return Convert.ToBase64String(Encrypt(data, key)); + } + + public static String EncryptToBase64String(String data, Byte[] key) { + return Convert.ToBase64String(Encrypt(data, key)); + } + + public static String EncryptToBase64String(Byte[] data, String key) { + return Convert.ToBase64String(Encrypt(data, key)); + } + + public static String EncryptToBase64String(String data, String key) { + return Convert.ToBase64String(Encrypt(data, key)); + } + + public static Byte[] Decrypt(Byte[] data, Byte[] key) { + if (data.Length == 0) { + return data; + } + return ToByteArray(Decrypt(ToUInt32Array(data, false), ToUInt32Array(FixKey(key), false)), true); + } + + public static Byte[] Decrypt(Byte[] data, String key) { + return Decrypt(data, utf8.GetBytes(key)); + } + + public static Byte[] DecryptBase64String(String data, Byte[] key) { + return Decrypt(Convert.FromBase64String(data), key); + } + + public static Byte[] DecryptBase64String(String data, String key) { + return Decrypt(Convert.FromBase64String(data), key); + } + + public static String DecryptToString(Byte[] data, Byte[] key) { + return utf8.GetString(Decrypt(data, key)); + } + + public static String DecryptToString(Byte[] data, String key) { + return utf8.GetString(Decrypt(data, key)); + } + + public static String DecryptBase64StringToString(String data, Byte[] key) { + return utf8.GetString(DecryptBase64String(data, key)); + } + + public static String DecryptBase64StringToString(String data, String key) { + return utf8.GetString(DecryptBase64String(data, key)); + } + + private static UInt32[] Encrypt(UInt32[] v, UInt32[] k) { + Int32 n = v.Length - 1; + if (n < 1) { + return v; + } + UInt32 z = v[n], y, sum = 0, e; + Int32 p, q = 6 + 52 / (n + 1); + unchecked { + while (0 < q--) { + sum += delta; + e = sum >> 2 & 3; + for (p = 0; p < n; p++) { + y = v[p + 1]; + z = v[p] += MX(sum, y, z, p, e, k); + } + y = v[0]; + z = v[n] += MX(sum, y, z, p, e, k); + } + } + return v; + } + + private static UInt32[] Decrypt(UInt32[] v, UInt32[] k) { + Int32 n = v.Length - 1; + if (n < 1) { + return v; + } + UInt32 z, y = v[0], sum, e; + Int32 p, q = 6 + 52 / (n + 1); + unchecked { + sum = (UInt32)(q * delta); + while (sum != 0) { + e = sum >> 2 & 3; + for (p = n; p > 0; p--) { + z = v[p - 1]; + y = v[p] -= MX(sum, y, z, p, e, k); + } + z = v[n]; + y = v[0] -= MX(sum, y, z, p, e, k); + sum -= delta; + } + } + return v; + } + + private static Byte[] FixKey(Byte[] key) { + if (key.Length == 16) return key; + Byte[] fixedkey = new Byte[16]; + if (key.Length < 16) { + key.CopyTo(fixedkey, 0); + } + else { + Array.Copy(key, 0, fixedkey, 0, 16); + } + return fixedkey; + } + + private static UInt32[] ToUInt32Array(Byte[] data, Boolean includeLength) { + Int32 length = data.Length; + Int32 n = (((length & 3) == 0) ? (length >> 2) : ((length >> 2) + 1)); + UInt32[] result; + if (includeLength) { + result = new UInt32[n + 1]; + result[n] = (UInt32)length; + } + else { + result = new UInt32[n]; + } + for (Int32 i = 0; i < length; i++) { + result[i >> 2] |= (UInt32)data[i] << ((i & 3) << 3); + } + return result; + } + + private static Byte[] ToByteArray(UInt32[] data, Boolean includeLength) { + Int32 n = data.Length << 2; + if (includeLength) { + Int32 m = (Int32)data[data.Length - 1]; + n -= 4; + if ((m < n - 3) || (m > n)) { + return null; + } + n = m; + } + Byte[] result = new Byte[n]; + for (Int32 i = 0; i < n; i++) { + result[i] = (Byte)(data[i >> 2] >> ((i & 3) << 3)); + } + return result; + } + } +} \ No newline at end of file diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util/Xxtea.cs.meta b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util/Xxtea.cs.meta new file mode 100644 index 0000000..9a7bcd4 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/Assets/XLua/util/Xxtea.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bb841ca90a67119448580ccfc58f1bd7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/AudioManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/AudioManager.asset new file mode 100644 index 0000000..07ebfb0 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/AudioManager.asset @@ -0,0 +1,19 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!11 &1 +AudioManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Volume: 1 + Rolloff Scale: 1 + Doppler Factor: 1 + Default Speaker Mode: 2 + m_SampleRate: 0 + m_DSPBufferSize: 1024 + m_VirtualVoiceCount: 512 + m_RealVoiceCount: 32 + m_SpatializerPlugin: + m_AmbisonicDecoderPlugin: + m_DisableAudio: 0 + m_VirtualizeEffects: 1 + m_RequestedDSPBufferSize: 1024 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ClusterInputManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ClusterInputManager.asset new file mode 100644 index 0000000..e7886b2 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ClusterInputManager.asset @@ -0,0 +1,6 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!236 &1 +ClusterInputManager: + m_ObjectHideFlags: 0 + m_Inputs: [] diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/DynamicsManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/DynamicsManager.asset new file mode 100644 index 0000000..cdc1f3e --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/DynamicsManager.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!55 &1 +PhysicsManager: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_Gravity: {x: 0, y: -9.81, z: 0} + m_DefaultMaterial: {fileID: 0} + m_BounceThreshold: 2 + m_SleepThreshold: 0.005 + m_DefaultContactOffset: 0.01 + m_DefaultSolverIterations: 6 + m_DefaultSolverVelocityIterations: 1 + m_QueriesHitBackfaces: 0 + m_QueriesHitTriggers: 1 + m_EnableAdaptiveForce: 0 + m_ClothInterCollisionDistance: 0 + m_ClothInterCollisionStiffness: 0 + m_ContactsGeneration: 1 + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + m_AutoSimulation: 1 + m_AutoSyncTransforms: 0 + m_ReuseCollisionCallbacks: 1 + m_ClothInterCollisionSettingsToggle: 0 + m_ContactPairsMode: 0 + m_BroadphaseType: 0 + m_WorldBounds: + m_Center: {x: 0, y: 0, z: 0} + m_Extent: {x: 250, y: 250, z: 250} + m_WorldSubdivisions: 8 + m_FrictionType: 0 + m_EnableEnhancedDeterminism: 0 + m_EnableUnifiedHeightmaps: 1 + m_DefaultMaxAngluarSpeed: 7 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/EditorBuildSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/EditorBuildSettings.asset new file mode 100644 index 0000000..0147887 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/EditorBuildSettings.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1045 &1 +EditorBuildSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Scenes: [] + m_configObjects: {} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/EditorSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/EditorSettings.asset new file mode 100644 index 0000000..f920544 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/EditorSettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!159 &1 +EditorSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_ExternalVersionControlSupport: Visible Meta Files + m_SerializationMode: 2 + m_LineEndingsForNewScripts: 0 + m_DefaultBehaviorMode: 0 + m_PrefabRegularEnvironment: {fileID: 0} + m_PrefabUIEnvironment: {fileID: 0} + m_SpritePackerMode: 0 + m_SpritePackerPaddingPower: 1 + m_EtcTextureCompressorBehavior: 1 + m_EtcTextureFastCompressor: 1 + m_EtcTextureNormalCompressor: 2 + m_EtcTextureBestCompressor: 4 + m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;rsp;asmref + m_ProjectGenerationRootNamespace: + m_CollabEditorSettings: + inProgressEnabled: 1 + m_EnableTextureStreamingInEditMode: 1 + m_EnableTextureStreamingInPlayMode: 1 + m_AsyncShaderCompilation: 1 + m_EnterPlayModeOptionsEnabled: 0 + m_EnterPlayModeOptions: 3 + m_ShowLightmapResolutionOverlay: 1 + m_UseLegacyProbeSampleCount: 0 + m_AssetPipelineMode: 1 + m_CacheServerMode: 0 + m_CacheServerEndpoint: + m_CacheServerNamespacePrefix: default + m_CacheServerEnableDownload: 1 + m_CacheServerEnableUpload: 1 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/GraphicsSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/GraphicsSettings.asset new file mode 100644 index 0000000..43369e3 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/GraphicsSettings.asset @@ -0,0 +1,63 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!30 &1 +GraphicsSettings: + m_ObjectHideFlags: 0 + serializedVersion: 13 + m_Deferred: + m_Mode: 1 + m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0} + m_DeferredReflections: + m_Mode: 1 + m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0} + m_ScreenSpaceShadows: + m_Mode: 1 + m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0} + m_LegacyDeferred: + m_Mode: 1 + m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0} + m_DepthNormals: + m_Mode: 1 + m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0} + m_MotionVectors: + m_Mode: 1 + m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0} + m_LightHalo: + m_Mode: 1 + m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0} + m_LensFlare: + m_Mode: 1 + m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0} + m_AlwaysIncludedShaders: + - {fileID: 7, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0} + m_PreloadedShaders: [] + m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000, + type: 0} + m_CustomRenderPipeline: {fileID: 0} + m_TransparencySortMode: 0 + m_TransparencySortAxis: {x: 0, y: 0, z: 1} + m_DefaultRenderingPath: 1 + m_DefaultMobileRenderingPath: 1 + m_TierSettings: [] + m_LightmapStripping: 0 + m_FogStripping: 0 + m_InstancingStripping: 0 + m_LightmapKeepPlain: 1 + m_LightmapKeepDirCombined: 1 + m_LightmapKeepDynamicPlain: 1 + m_LightmapKeepDynamicDirCombined: 1 + m_LightmapKeepShadowMask: 1 + m_LightmapKeepSubtractive: 1 + m_FogKeepLinear: 1 + m_FogKeepExp: 1 + m_FogKeepExp2: 1 + m_AlbedoSwatchInfos: [] + m_LightsUseLinearIntensity: 0 + m_LightsUseColorTemperature: 0 + m_LogWhenShaderIsCompiled: 0 + m_AllowEnlightenSupportForUpgradedProject: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/InputManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/InputManager.asset new file mode 100644 index 0000000..17c8f53 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/InputManager.asset @@ -0,0 +1,295 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!13 &1 +InputManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Axes: + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: left + positiveButton: right + altNegativeButton: a + altPositiveButton: d + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: down + positiveButton: up + altNegativeButton: s + altPositiveButton: w + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left ctrl + altNegativeButton: + altPositiveButton: mouse 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left alt + altNegativeButton: + altPositiveButton: mouse 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left shift + altNegativeButton: + altPositiveButton: mouse 2 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: space + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse X + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse Y + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse ScrollWheel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 2 + joyNum: 0 + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 0 + type: 2 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 1 + type: 2 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 0 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 1 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 2 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 3 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: return + altNegativeButton: + altPositiveButton: joystick button 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: enter + altNegativeButton: + altPositiveButton: space + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Cancel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: escape + altNegativeButton: + altPositiveButton: joystick button 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/NavMeshAreas.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/NavMeshAreas.asset new file mode 100644 index 0000000..3b0b7c3 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/NavMeshAreas.asset @@ -0,0 +1,91 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!126 &1 +NavMeshProjectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + areas: + - name: Walkable + cost: 1 + - name: Not Walkable + cost: 1 + - name: Jump + cost: 2 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + m_LastAgentTypeID: -887442657 + m_Settings: + - serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.75 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_SettingNames: + - Humanoid diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/PackageManagerSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/PackageManagerSettings.asset new file mode 100644 index 0000000..6920e3a --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/PackageManagerSettings.asset @@ -0,0 +1,38 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &1 +MonoBehaviour: + m_ObjectHideFlags: 61 + 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: 13964, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_ScopedRegistriesSettingsExpanded: 1 + oneTimeWarningShown: 0 + m_Registries: + - m_Id: main + m_Name: + m_Url: https://packages.unity.com + m_Scopes: [] + m_IsDefault: 1 + m_UserSelectedRegistryName: + m_UserAddingNewScopedRegistry: 0 + m_RegistryInfoDraft: + m_ErrorMessage: + m_Original: + m_Id: + m_Name: + m_Url: + m_Scopes: [] + m_IsDefault: 0 + m_Modified: 0 + m_Name: + m_Url: + m_Scopes: + - + m_SelectedScopeIndex: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/Physics2DSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/Physics2DSettings.asset new file mode 100644 index 0000000..47880b1 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/Physics2DSettings.asset @@ -0,0 +1,56 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!19 &1 +Physics2DSettings: + m_ObjectHideFlags: 0 + serializedVersion: 4 + m_Gravity: {x: 0, y: -9.81} + m_DefaultMaterial: {fileID: 0} + m_VelocityIterations: 8 + m_PositionIterations: 3 + m_VelocityThreshold: 1 + m_MaxLinearCorrection: 0.2 + m_MaxAngularCorrection: 8 + m_MaxTranslationSpeed: 100 + m_MaxRotationSpeed: 360 + m_BaumgarteScale: 0.2 + m_BaumgarteTimeOfImpactScale: 0.75 + m_TimeToSleep: 0.5 + m_LinearSleepTolerance: 0.01 + m_AngularSleepTolerance: 2 + m_DefaultContactOffset: 0.01 + m_JobOptions: + serializedVersion: 2 + useMultithreading: 0 + useConsistencySorting: 0 + m_InterpolationPosesPerJob: 100 + m_NewContactsPerJob: 30 + m_CollideContactsPerJob: 100 + m_ClearFlagsPerJob: 200 + m_ClearBodyForcesPerJob: 200 + m_SyncDiscreteFixturesPerJob: 50 + m_SyncContinuousFixturesPerJob: 50 + m_FindNearestContactsPerJob: 100 + m_UpdateTriggerContactsPerJob: 100 + m_IslandSolverCostThreshold: 100 + m_IslandSolverBodyCostScale: 1 + m_IslandSolverContactCostScale: 10 + m_IslandSolverJointCostScale: 10 + m_IslandSolverBodiesPerJob: 50 + m_IslandSolverContactsPerJob: 50 + m_AutoSimulation: 1 + m_QueriesHitTriggers: 1 + m_QueriesStartInColliders: 1 + m_CallbacksOnDisable: 1 + m_ReuseCollisionCallbacks: 1 + m_AutoSyncTransforms: 0 + m_AlwaysShowColliders: 0 + m_ShowColliderSleep: 1 + m_ShowColliderContacts: 0 + m_ShowColliderAABB: 0 + m_ContactArrowScale: 0.2 + m_ColliderAwakeColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.7529412} + m_ColliderAsleepColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.36078432} + m_ColliderContactColor: {r: 1, g: 0, b: 1, a: 0.6862745} + m_ColliderAABBColor: {r: 1, g: 1, b: 0, a: 0.2509804} + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/PresetManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/PresetManager.asset new file mode 100644 index 0000000..67a94da --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/PresetManager.asset @@ -0,0 +1,7 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1386491679 &1 +PresetManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_DefaultPresets: {} diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ProjectSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ProjectSettings.asset new file mode 100644 index 0000000..4740be7 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ProjectSettings.asset @@ -0,0 +1,705 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!129 &1 +PlayerSettings: + m_ObjectHideFlags: 0 + serializedVersion: 20 + productGUID: 7614f5f55ee855b4e94f6df86708d76a + AndroidProfiler: 0 + AndroidFilterTouchesWhenObscured: 0 + AndroidEnableSustainedPerformanceMode: 0 + defaultScreenOrientation: 4 + targetDevice: 2 + useOnDemandResources: 0 + accelerometerFrequency: 60 + companyName: DefaultCompany + productName: behaviortreevisualizer + defaultCursor: {fileID: 0} + cursorHotspot: {x: 0, y: 0} + m_SplashScreenBackgroundColor: {r: 0.13725491, g: 0.12156863, b: 0.1254902, a: 1} + m_ShowUnitySplashScreen: 1 + m_ShowUnitySplashLogo: 1 + m_SplashScreenOverlayOpacity: 1 + m_SplashScreenAnimation: 1 + m_SplashScreenLogoStyle: 1 + m_SplashScreenDrawMode: 0 + m_SplashScreenBackgroundAnimationZoom: 1 + m_SplashScreenLogoAnimationZoom: 1 + m_SplashScreenBackgroundLandscapeAspect: 1 + m_SplashScreenBackgroundPortraitAspect: 1 + m_SplashScreenBackgroundLandscapeUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenBackgroundPortraitUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenLogos: [] + m_VirtualRealitySplashScreen: {fileID: 0} + m_HolographicTrackingLossScreen: {fileID: 0} + defaultScreenWidth: 1024 + defaultScreenHeight: 768 + defaultScreenWidthWeb: 960 + defaultScreenHeightWeb: 600 + m_StereoRenderingPath: 0 + m_ActiveColorSpace: 0 + m_MTRendering: 1 + m_StackTraceTypes: 010000000100000001000000010000000100000001000000 + iosShowActivityIndicatorOnLoading: -1 + androidShowActivityIndicatorOnLoading: -1 + iosUseCustomAppBackgroundBehavior: 0 + iosAllowHTTPDownload: 1 + allowedAutorotateToPortrait: 1 + allowedAutorotateToPortraitUpsideDown: 1 + allowedAutorotateToLandscapeRight: 1 + allowedAutorotateToLandscapeLeft: 1 + useOSAutorotation: 1 + use32BitDisplayBuffer: 1 + preserveFramebufferAlpha: 0 + disableDepthAndStencilBuffers: 0 + androidStartInFullscreen: 1 + androidRenderOutsideSafeArea: 1 + androidUseSwappy: 0 + androidBlitType: 0 + defaultIsNativeResolution: 1 + macRetinaSupport: 1 + runInBackground: 1 + captureSingleScreen: 0 + muteOtherAudioSources: 0 + Prepare IOS For Recording: 0 + Force IOS Speakers When Recording: 0 + deferSystemGesturesMode: 0 + hideHomeButton: 0 + submitAnalytics: 1 + usePlayerLog: 1 + bakeCollisionMeshes: 0 + forceSingleInstance: 0 + useFlipModelSwapchain: 1 + resizableWindow: 0 + useMacAppStoreValidation: 0 + macAppStoreCategory: public.app-category.games + gpuSkinning: 1 + xboxPIXTextureCapture: 0 + xboxEnableAvatar: 0 + xboxEnableKinect: 0 + xboxEnableKinectAutoTracking: 0 + xboxEnableFitness: 0 + visibleInBackground: 1 + allowFullscreenSwitch: 1 + fullscreenMode: 1 + xboxSpeechDB: 0 + xboxEnableHeadOrientation: 0 + xboxEnableGuest: 0 + xboxEnablePIXSampling: 0 + metalFramebufferOnly: 0 + xboxOneResolution: 0 + xboxOneSResolution: 0 + xboxOneXResolution: 3 + xboxOneMonoLoggingLevel: 0 + xboxOneLoggingLevel: 1 + xboxOneDisableEsram: 0 + xboxOneEnableTypeOptimization: 0 + xboxOnePresentImmediateThreshold: 0 + switchQueueCommandMemory: 0 + switchQueueControlMemory: 16384 + switchQueueComputeMemory: 262144 + switchNVNShaderPoolsGranularity: 33554432 + switchNVNDefaultPoolsGranularity: 16777216 + switchNVNOtherPoolsGranularity: 16777216 + switchNVNMaxPublicTextureIDCount: 0 + switchNVNMaxPublicSamplerIDCount: 0 + stadiaPresentMode: 0 + stadiaTargetFramerate: 0 + vulkanNumSwapchainBuffers: 3 + vulkanEnableSetSRGBWrite: 0 + vulkanEnableLateAcquireNextImage: 0 + m_SupportedAspectRatios: + 4:3: 1 + 5:4: 1 + 16:10: 1 + 16:9: 1 + Others: 1 + bundleVersion: 0.1 + preloadedAssets: [] + metroInputSource: 0 + wsaTransparentSwapchain: 0 + m_HolographicPauseOnTrackingLoss: 1 + xboxOneDisableKinectGpuReservation: 1 + xboxOneEnable7thCore: 1 + vrSettings: + cardboard: + depthFormat: 0 + enableTransitionView: 0 + daydream: + depthFormat: 0 + useSustainedPerformanceMode: 0 + enableVideoLayer: 0 + useProtectedVideoMemory: 0 + minimumSupportedHeadTracking: 0 + maximumSupportedHeadTracking: 1 + hololens: + depthFormat: 1 + depthBufferSharingEnabled: 1 + lumin: + depthFormat: 0 + frameTiming: 2 + enableGLCache: 0 + glCacheMaxBlobSize: 524288 + glCacheMaxFileSize: 8388608 + oculus: + sharedDepthBuffer: 1 + dashSupport: 1 + lowOverheadMode: 0 + protectedContext: 0 + v2Signing: 1 + enable360StereoCapture: 0 + isWsaHolographicRemotingEnabled: 0 + enableFrameTimingStats: 0 + useHDRDisplay: 0 + D3DHDRBitDepth: 0 + m_ColorGamuts: 00000000 + targetPixelDensity: 30 + resolutionScalingMode: 0 + androidSupportedAspectRatio: 1 + androidMaxAspectRatio: 2.1 + applicationIdentifier: {} + buildNumber: {} + AndroidBundleVersionCode: 1 + AndroidMinSdkVersion: 19 + AndroidTargetSdkVersion: 0 + AndroidPreferredInstallLocation: 1 + aotOptions: + stripEngineCode: 1 + iPhoneStrippingLevel: 0 + iPhoneScriptCallOptimization: 0 + ForceInternetPermission: 0 + ForceSDCardPermission: 0 + CreateWallpaper: 0 + APKExpansionFiles: 0 + keepLoadedShadersAlive: 0 + StripUnusedMeshComponents: 1 + VertexChannelCompressionMask: 4054 + iPhoneSdkVersion: 988 + iOSTargetOSVersionString: 10.0 + tvOSSdkVersion: 0 + tvOSRequireExtendedGameController: 0 + tvOSTargetOSVersionString: 10.0 + uIPrerenderedIcon: 0 + uIRequiresPersistentWiFi: 0 + uIRequiresFullScreen: 1 + uIStatusBarHidden: 1 + uIExitOnSuspend: 0 + uIStatusBarStyle: 0 + appleTVSplashScreen: {fileID: 0} + appleTVSplashScreen2x: {fileID: 0} + tvOSSmallIconLayers: [] + tvOSSmallIconLayers2x: [] + tvOSLargeIconLayers: [] + tvOSLargeIconLayers2x: [] + tvOSTopShelfImageLayers: [] + tvOSTopShelfImageLayers2x: [] + tvOSTopShelfImageWideLayers: [] + tvOSTopShelfImageWideLayers2x: [] + iOSLaunchScreenType: 0 + iOSLaunchScreenPortrait: {fileID: 0} + iOSLaunchScreenLandscape: {fileID: 0} + iOSLaunchScreenBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreenFillPct: 100 + iOSLaunchScreenSize: 100 + iOSLaunchScreenCustomXibPath: + iOSLaunchScreeniPadType: 0 + iOSLaunchScreeniPadImage: {fileID: 0} + iOSLaunchScreeniPadBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreeniPadFillPct: 100 + iOSLaunchScreeniPadSize: 100 + iOSLaunchScreeniPadCustomXibPath: + iOSUseLaunchScreenStoryboard: 0 + iOSLaunchScreenCustomStoryboardPath: + iOSDeviceRequirements: [] + iOSURLSchemes: [] + iOSBackgroundModes: 0 + iOSMetalForceHardShadows: 0 + metalEditorSupport: 1 + metalAPIValidation: 1 + iOSRenderExtraFrameOnPause: 0 + iosCopyPluginsCodeInsteadOfSymlink: 0 + appleDeveloperTeamID: + iOSManualSigningProvisioningProfileID: + tvOSManualSigningProvisioningProfileID: + iOSManualSigningProvisioningProfileType: 0 + tvOSManualSigningProvisioningProfileType: 0 + appleEnableAutomaticSigning: 0 + iOSRequireARKit: 0 + iOSAutomaticallyDetectAndAddCapabilities: 1 + appleEnableProMotion: 0 + clonedFromGUID: c0afd0d1d80e3634a9dac47e8a0426ea + templatePackageId: com.unity.template.3d@4.2.8 + templateDefaultScene: Assets/Scenes/SampleScene.unity + AndroidTargetArchitectures: 1 + AndroidSplashScreenScale: 0 + androidSplashScreen: {fileID: 0} + AndroidKeystoreName: + AndroidKeyaliasName: + AndroidBuildApkPerCpuArchitecture: 0 + AndroidTVCompatibility: 0 + AndroidIsGame: 1 + AndroidEnableTango: 0 + androidEnableBanner: 1 + androidUseLowAccuracyLocation: 0 + androidUseCustomKeystore: 0 + m_AndroidBanners: + - width: 320 + height: 180 + banner: {fileID: 0} + androidGamepadSupportLevel: 0 + AndroidValidateAppBundleSize: 1 + AndroidAppBundleSizeToValidate: 150 + m_BuildTargetIcons: [] + m_BuildTargetPlatformIcons: [] + m_BuildTargetBatching: + - m_BuildTarget: Standalone + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: tvOS + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: Android + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: iPhone + m_StaticBatching: 1 + m_DynamicBatching: 0 + - m_BuildTarget: WebGL + m_StaticBatching: 0 + m_DynamicBatching: 0 + m_BuildTargetGraphicsJobs: + - m_BuildTarget: MacStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: Switch + m_GraphicsJobs: 1 + - m_BuildTarget: MetroSupport + m_GraphicsJobs: 1 + - m_BuildTarget: AppleTVSupport + m_GraphicsJobs: 0 + - m_BuildTarget: BJMSupport + m_GraphicsJobs: 1 + - m_BuildTarget: LinuxStandaloneSupport + m_GraphicsJobs: 1 + - m_BuildTarget: PS4Player + m_GraphicsJobs: 1 + - m_BuildTarget: iOSSupport + m_GraphicsJobs: 0 + - m_BuildTarget: WindowsStandaloneSupport + m_GraphicsJobs: 1 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobs: 1 + - m_BuildTarget: LuminSupport + m_GraphicsJobs: 0 + - m_BuildTarget: AndroidPlayer + m_GraphicsJobs: 0 + - m_BuildTarget: WebGLSupport + m_GraphicsJobs: 0 + m_BuildTargetGraphicsJobMode: + - m_BuildTarget: PS4Player + m_GraphicsJobMode: 0 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobMode: 0 + m_BuildTargetGraphicsAPIs: + - m_BuildTarget: AndroidPlayer + m_APIs: 150000000b000000 + m_Automatic: 0 + - m_BuildTarget: iOSSupport + m_APIs: 10000000 + m_Automatic: 1 + - m_BuildTarget: AppleTVSupport + m_APIs: 10000000 + m_Automatic: 0 + - m_BuildTarget: WebGLSupport + m_APIs: 0b000000 + m_Automatic: 1 + m_BuildTargetVRSettings: + - m_BuildTarget: Standalone + m_Enabled: 0 + m_Devices: + - Oculus + - OpenVR + openGLRequireES31: 0 + openGLRequireES31AEP: 0 + openGLRequireES32: 0 + m_TemplateCustomTags: {} + mobileMTRendering: + Android: 1 + iPhone: 1 + tvOS: 1 + m_BuildTargetGroupLightmapEncodingQuality: [] + m_BuildTargetGroupLightmapSettings: [] + playModeTestRunnerEnabled: 0 + runPlayModeTestAsEditModeTest: 0 + actionOnDotNetUnhandledException: 1 + enableInternalProfiler: 0 + logObjCUncaughtExceptions: 1 + enableCrashReportAPI: 0 + cameraUsageDescription: + locationUsageDescription: + microphoneUsageDescription: + switchNetLibKey: + switchSocketMemoryPoolSize: 6144 + switchSocketAllocatorPoolSize: 128 + switchSocketConcurrencyLimit: 14 + switchScreenResolutionBehavior: 2 + switchUseCPUProfiler: 0 + switchApplicationID: 0x01004b9000490000 + switchNSODependencies: + switchTitleNames_0: + switchTitleNames_1: + switchTitleNames_2: + switchTitleNames_3: + switchTitleNames_4: + switchTitleNames_5: + switchTitleNames_6: + switchTitleNames_7: + switchTitleNames_8: + switchTitleNames_9: + switchTitleNames_10: + switchTitleNames_11: + switchTitleNames_12: + switchTitleNames_13: + switchTitleNames_14: + switchTitleNames_15: + switchPublisherNames_0: + switchPublisherNames_1: + switchPublisherNames_2: + switchPublisherNames_3: + switchPublisherNames_4: + switchPublisherNames_5: + switchPublisherNames_6: + switchPublisherNames_7: + switchPublisherNames_8: + switchPublisherNames_9: + switchPublisherNames_10: + switchPublisherNames_11: + switchPublisherNames_12: + switchPublisherNames_13: + switchPublisherNames_14: + switchPublisherNames_15: + switchIcons_0: {fileID: 0} + switchIcons_1: {fileID: 0} + switchIcons_2: {fileID: 0} + switchIcons_3: {fileID: 0} + switchIcons_4: {fileID: 0} + switchIcons_5: {fileID: 0} + switchIcons_6: {fileID: 0} + switchIcons_7: {fileID: 0} + switchIcons_8: {fileID: 0} + switchIcons_9: {fileID: 0} + switchIcons_10: {fileID: 0} + switchIcons_11: {fileID: 0} + 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} + switchSmallIcons_3: {fileID: 0} + switchSmallIcons_4: {fileID: 0} + switchSmallIcons_5: {fileID: 0} + switchSmallIcons_6: {fileID: 0} + switchSmallIcons_7: {fileID: 0} + switchSmallIcons_8: {fileID: 0} + switchSmallIcons_9: {fileID: 0} + switchSmallIcons_10: {fileID: 0} + switchSmallIcons_11: {fileID: 0} + switchSmallIcons_12: {fileID: 0} + switchSmallIcons_13: {fileID: 0} + switchSmallIcons_14: {fileID: 0} + switchSmallIcons_15: {fileID: 0} + switchManualHTML: + switchAccessibleURLs: + switchLegalInformation: + switchMainThreadStackSize: 1048576 + switchPresenceGroupId: + switchLogoHandling: 0 + switchReleaseVersion: 0 + switchDisplayVersion: 1.0.0 + switchStartupUserAccount: 0 + switchTouchScreenUsage: 0 + switchSupportedLanguagesMask: 0 + switchLogoType: 0 + switchApplicationErrorCodeCategory: + switchUserAccountSaveDataSize: 0 + switchUserAccountSaveDataJournalSize: 0 + switchApplicationAttribute: 0 + switchCardSpecSize: -1 + switchCardSpecClock: -1 + switchRatingsMask: 0 + switchRatingsInt_0: 0 + switchRatingsInt_1: 0 + switchRatingsInt_2: 0 + switchRatingsInt_3: 0 + switchRatingsInt_4: 0 + switchRatingsInt_5: 0 + switchRatingsInt_6: 0 + switchRatingsInt_7: 0 + switchRatingsInt_8: 0 + switchRatingsInt_9: 0 + switchRatingsInt_10: 0 + switchRatingsInt_11: 0 + switchRatingsInt_12: 0 + switchLocalCommunicationIds_0: + switchLocalCommunicationIds_1: + switchLocalCommunicationIds_2: + switchLocalCommunicationIds_3: + switchLocalCommunicationIds_4: + switchLocalCommunicationIds_5: + switchLocalCommunicationIds_6: + switchLocalCommunicationIds_7: + switchParentalControl: 0 + switchAllowsScreenshot: 1 + switchAllowsVideoCapturing: 1 + switchAllowsRuntimeAddOnContentInstall: 0 + switchDataLossConfirmation: 0 + switchUserAccountLockEnabled: 0 + switchSystemResourceMemory: 16777216 + switchSupportedNpadStyles: 22 + switchNativeFsCacheSize: 32 + switchIsHoldTypeHorizontal: 0 + switchSupportedNpadCount: 8 + switchSocketConfigEnabled: 0 + switchTcpInitialSendBufferSize: 32 + switchTcpInitialReceiveBufferSize: 64 + switchTcpAutoSendBufferSizeMax: 256 + switchTcpAutoReceiveBufferSizeMax: 256 + switchUdpSendBufferSize: 9 + switchUdpReceiveBufferSize: 42 + switchSocketBufferEfficiency: 4 + switchSocketInitializeEnabled: 1 + switchNetworkInterfaceManagerInitializeEnabled: 1 + switchPlayerConnectionEnabled: 1 + switchUseMicroSleepForYield: 1 + switchMicroSleepForYieldTime: 25 + ps4NPAgeRating: 12 + ps4NPTitleSecret: + ps4NPTrophyPackPath: + ps4ParentalLevel: 11 + ps4ContentID: ED1633-NPXX51362_00-0000000000000000 + ps4Category: 0 + ps4MasterVersion: 01.00 + ps4AppVersion: 01.00 + ps4AppType: 0 + ps4ParamSfxPath: + ps4VideoOutPixelFormat: 0 + ps4VideoOutInitialWidth: 1920 + ps4VideoOutBaseModeInitialWidth: 1920 + ps4VideoOutReprojectionRate: 60 + ps4PronunciationXMLPath: + ps4PronunciationSIGPath: + ps4BackgroundImagePath: + ps4StartupImagePath: + ps4StartupImagesFolder: + ps4IconImagesFolder: + ps4SaveDataImagePath: + ps4SdkOverride: + ps4BGMPath: + ps4ShareFilePath: + ps4ShareOverlayImagePath: + ps4PrivacyGuardImagePath: + ps4ExtraSceSysFile: + ps4NPtitleDatPath: + ps4RemotePlayKeyAssignment: -1 + ps4RemotePlayKeyMappingDir: + ps4PlayTogetherPlayerCount: 0 + ps4EnterButtonAssignment: 1 + ps4ApplicationParam1: 0 + ps4ApplicationParam2: 0 + ps4ApplicationParam3: 0 + ps4ApplicationParam4: 0 + ps4DownloadDataSize: 0 + ps4GarlicHeapSize: 2048 + ps4ProGarlicHeapSize: 2560 + playerPrefsMaxSize: 32768 + ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ + ps4pnSessions: 1 + ps4pnPresence: 1 + ps4pnFriends: 1 + ps4pnGameCustomData: 1 + playerPrefsSupport: 0 + enableApplicationExit: 0 + resetTempFolder: 1 + restrictedAudioUsageRights: 0 + ps4UseResolutionFallback: 0 + ps4ReprojectionSupport: 0 + ps4UseAudio3dBackend: 0 + ps4UseLowGarlicFragmentationMode: 1 + ps4SocialScreenEnabled: 0 + ps4ScriptOptimizationLevel: 0 + ps4Audio3dVirtualSpeakerCount: 14 + ps4attribCpuUsage: 0 + ps4PatchPkgPath: + ps4PatchLatestPkgPath: + ps4PatchChangeinfoPath: + ps4PatchDayOne: 0 + ps4attribUserManagement: 0 + ps4attribMoveSupport: 0 + ps4attrib3DSupport: 0 + ps4attribShareSupport: 0 + ps4attribExclusiveVR: 0 + ps4disableAutoHideSplash: 0 + ps4videoRecordingFeaturesUsed: 0 + ps4contentSearchFeaturesUsed: 0 + ps4CompatibilityPS5: 0 + ps4AllowPS5Detection: 0 + ps4GPU800MHz: 1 + ps4attribEyeToEyeDistanceSettingVR: 0 + ps4IncludedModules: [] + ps4attribVROutputEnabled: 0 + ps5ParamFilePath: + ps5VideoOutPixelFormat: 0 + ps5VideoOutInitialWidth: 1920 + ps5VideoOutOutputMode: 1 + ps5BackgroundImagePath: + ps5StartupImagePath: + ps5Pic2Path: + ps5StartupImagesFolder: + ps5IconImagesFolder: + ps5SaveDataImagePath: + ps5SdkOverride: + ps5BGMPath: + ps5ShareOverlayImagePath: + ps5NPConfigZipPath: + ps5Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ + ps5UseResolutionFallback: 0 + ps5UseAudio3dBackend: 0 + ps5ScriptOptimizationLevel: 2 + ps5Audio3dVirtualSpeakerCount: 14 + ps5UpdateReferencePackage: + ps5disableAutoHideSplash: 0 + ps5OperatingSystemCanDisableSplashScreen: 0 + ps5IncludedModules: [] + ps5SharedBinaryContentLabels: [] + ps5SharedBinarySystemFolders: [] + monoEnv: + splashScreenBackgroundSourceLandscape: {fileID: 0} + splashScreenBackgroundSourcePortrait: {fileID: 0} + blurSplashScreenBackground: 1 + spritePackerPolicy: + webGLMemorySize: 16 + webGLExceptionSupport: 1 + webGLNameFilesAsHashes: 0 + webGLDataCaching: 1 + webGLDebugSymbols: 0 + webGLEmscriptenArgs: + webGLModulesDirectory: + webGLTemplate: APPLICATION:Default + webGLAnalyzeBuildSize: 0 + webGLUseEmbeddedResources: 0 + webGLCompressionFormat: 1 + webGLLinkerTarget: 1 + webGLThreadsSupport: 0 + webGLWasmStreaming: 0 + scriptingDefineSymbols: {} + platformArchitecture: {} + scriptingBackend: {} + il2cppCompilerConfiguration: {} + managedStrippingLevel: {} + incrementalIl2cppBuild: {} + suppressCommonWarnings: 1 + allowUnsafeCode: 0 + additionalIl2CppArgs: + scriptingRuntimeVersion: 1 + gcIncremental: 0 + assemblyVersionValidation: 1 + gcWBarrierValidation: 0 + apiCompatibilityLevelPerPlatform: + Standalone: 3 + m_RenderingPath: 1 + m_MobileRenderingPath: 1 + metroPackageName: Template_3D + metroPackageVersion: + metroCertificatePath: + metroCertificatePassword: + metroCertificateSubject: + metroCertificateIssuer: + metroCertificateNotAfter: 0000000000000000 + metroApplicationDescription: Template_3D + wsaImages: {} + metroTileShortName: + metroTileShowName: 0 + metroMediumTileShowName: 0 + metroLargeTileShowName: 0 + metroWideTileShowName: 0 + metroSupportStreamingInstall: 0 + metroLastRequiredScene: 0 + metroDefaultTileSize: 1 + metroTileForegroundText: 2 + metroTileBackgroundColor: {r: 0.13333334, g: 0.17254902, b: 0.21568628, a: 0} + metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628, + a: 1} + metroSplashScreenUseBackgroundColor: 0 + platformCapabilities: {} + metroTargetDeviceFamilies: {} + metroFTAName: + metroFTAFileTypes: [] + metroProtocolName: + XboxOneProductId: + XboxOneUpdateKey: + XboxOneSandboxId: + XboxOneContentId: + XboxOneTitleId: + XboxOneSCId: + XboxOneGameOsOverridePath: + XboxOnePackagingOverridePath: + XboxOneAppManifestOverridePath: + XboxOneVersion: 1.0.0.0 + XboxOnePackageEncryption: 0 + XboxOnePackageUpdateGranularity: 2 + XboxOneDescription: + XboxOneLanguage: + - enus + XboxOneCapability: [] + XboxOneGameRating: {} + XboxOneIsContentPackage: 0 + XboxOneEnhancedXboxCompatibilityMode: 0 + XboxOneEnableGPUVariability: 1 + XboxOneSockets: {} + XboxOneSplashScreen: {fileID: 0} + XboxOneAllowedProductIds: [] + XboxOnePersistentLocalStorageSize: 0 + XboxOneXTitleMemory: 8 + XboxOneOverrideIdentityName: + XboxOneOverrideIdentityPublisher: + vrEditorSettings: + daydream: + daydreamIconForeground: {fileID: 0} + daydreamIconBackground: {fileID: 0} + cloudServicesEnabled: + UNet: 1 + luminIcon: + m_Name: + m_ModelFolderPath: + m_PortalFolderPath: + luminCert: + m_CertPath: + m_SignPackage: 1 + luminIsChannelApp: 0 + luminVersion: + m_VersionCode: 1 + m_VersionName: + apiCompatibilityLevel: 6 + cloudProjectId: + framebufferDepthMemorylessMode: 0 + projectName: + organizationId: + cloudEnabled: 0 + enableNativePlatformBackendsForNewInputSystem: 0 + disableOldInputManagerSupport: 0 + legacyClampBlendShapeWeights: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ProjectVersion.txt b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ProjectVersion.txt new file mode 100644 index 0000000..7b855c6 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/ProjectVersion.txt @@ -0,0 +1,2 @@ +m_EditorVersion: 2019.4.30f1 +m_EditorVersionWithRevision: 2019.4.30f1 (e8c891080a1f) diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/QualitySettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/QualitySettings.asset new file mode 100644 index 0000000..7b7658d --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/QualitySettings.asset @@ -0,0 +1,232 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!47 &1 +QualitySettings: + m_ObjectHideFlags: 0 + serializedVersion: 5 + m_CurrentQuality: 5 + m_QualitySettings: + - serializedVersion: 2 + name: Very Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 15 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 1 + textureQuality: 1 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.3 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 4 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.4 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 16 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Medium + pixelLightCount: 1 + shadows: 1 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 1 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 0.7 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 64 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: High + pixelLightCount: 2 + shadows: 2 + shadowResolution: 1 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 40 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 1 + antiAliasing: 0 + softParticles: 0 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 1 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 256 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Very High + pixelLightCount: 3 + shadows: 2 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 70 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 2 + antiAliasing: 2 + softParticles: 1 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 1.5 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 1024 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Ultra + pixelLightCount: 4 + shadows: 2 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 4 + shadowDistance: 150 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 2 + antiAliasing: 2 + softParticles: 1 + softVegetation: 1 + realtimeReflectionProbes: 1 + billboardsFaceCameraPosition: 1 + vSyncCount: 1 + lodBias: 2 + maximumLODLevel: 0 + streamingMipmapsActive: 0 + streamingMipmapsAddAllCameras: 1 + streamingMipmapsMemoryBudget: 512 + streamingMipmapsRenderersPerFrame: 512 + streamingMipmapsMaxLevelReduction: 2 + streamingMipmapsMaxFileIORequests: 1024 + particleRaycastBudget: 4096 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + asyncUploadPersistentBuffer: 1 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + m_PerPlatformDefaultQuality: + Android: 2 + Lumin: 5 + Nintendo 3DS: 5 + Nintendo Switch: 5 + PS4: 5 + PSP2: 2 + Stadia: 5 + Standalone: 5 + WebGL: 3 + Windows Store Apps: 5 + XboxOne: 5 + iPhone: 2 + tvOS: 2 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/TagManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/TagManager.asset new file mode 100644 index 0000000..1c92a78 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/TagManager.asset @@ -0,0 +1,43 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!78 &1 +TagManager: + serializedVersion: 2 + tags: [] + layers: + - Default + - TransparentFX + - Ignore Raycast + - + - Water + - UI + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + m_SortingLayers: + - name: Default + uniqueID: 0 + locked: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/TimeManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/TimeManager.asset new file mode 100644 index 0000000..558a017 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/TimeManager.asset @@ -0,0 +1,9 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!5 &1 +TimeManager: + m_ObjectHideFlags: 0 + Fixed Timestep: 0.02 + Maximum Allowed Timestep: 0.33333334 + m_TimeScale: 1 + Maximum Particle Timestep: 0.03 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/UnityConnectSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/UnityConnectSettings.asset new file mode 100644 index 0000000..fa0b146 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/UnityConnectSettings.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!310 &1 +UnityConnectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 1 + m_Enabled: 0 + m_TestMode: 0 + 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_TestInitMode: 0 + CrashReportingSettings: + m_EventUrl: https://perf-events.cloud.unity3d.com + m_Enabled: 0 + m_LogBufferSize: 10 + m_CaptureEditorExceptions: 1 + UnityPurchasingSettings: + m_Enabled: 0 + m_TestMode: 0 + UnityAnalyticsSettings: + m_Enabled: 0 + m_TestMode: 0 + m_InitializeOnStartup: 1 + UnityAdsSettings: + m_Enabled: 0 + m_InitializeOnStartup: 1 + m_TestMode: 0 + m_IosGameId: + m_AndroidGameId: + m_GameIds: {} + m_GameId: + PerformanceReportingSettings: + m_Enabled: 0 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/VFXManager.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/VFXManager.asset new file mode 100644 index 0000000..3a95c98 --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/VFXManager.asset @@ -0,0 +1,12 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!937362698 &1 +VFXManager: + m_ObjectHideFlags: 0 + m_IndirectShader: {fileID: 0} + m_CopyBufferShader: {fileID: 0} + m_SortShader: {fileID: 0} + m_StripUpdateShader: {fileID: 0} + m_RenderPipeSettingsPath: + m_FixedTimeStep: 0.016666668 + m_MaxDeltaTime: 0.05 diff --git a/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/XRSettings.asset b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/XRSettings.asset new file mode 100644 index 0000000..482590c --- /dev/null +++ b/com.wug.behaviortreevisualizer/Samples~/NPC Sample 2019.4/ProjectSettings/XRSettings.asset @@ -0,0 +1,10 @@ +{ + "m_SettingKeys": [ + "VR Device Disabled", + "VR Device User Alert" + ], + "m_SettingValues": [ + "False", + "False" + ] +} \ No newline at end of file