diff --git a/.gitignore b/.gitignore index 23fae005..7a44f0f7 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ sysinfo.txt *.apk *.unitypackage .DS_Store +/.idea/ diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 4c1111c0..00000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Unity Editor", - "type": "unity", - "path": "/Users/guzhu/Documents/FairyGUI-unity-git/Library/EditorInstance.json", - "request": "launch" - }, - { - "name": "Windows Player", - "type": "unity", - "request": "launch" - }, - { - "name": "OSX Player", - "type": "unity", - "request": "launch" - }, - { - "name": "Linux Player", - "type": "unity", - "request": "launch" - }, - { - "name": "iOS Player", - "type": "unity", - "request": "launch" - }, - { - "name": "Android Player", - "type": "unity", - "request": "launch" - } - ] -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 067df49d..00000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "files.exclude": - { - "**/.DS_Store":true, - "**/.git":true, - "**/.gitmodules":true, - "**/*.booproj":true, - "**/*.pidb":true, - "**/*.suo":true, - "**/*.user":true, - "**/*.userprefs":true, - "**/*.unityproj":true, - "**/*.dll":true, - "**/*.exe":true, - "**/*.pdf":true, - "**/*.mid":true, - "**/*.midi":true, - "**/*.wav":true, - "**/*.gif":true, - "**/*.ico":true, - "**/*.jpg":true, - "**/*.jpeg":true, - "**/*.png":true, - "**/*.psd":true, - "**/*.tga":true, - "**/*.tif":true, - "**/*.tiff":true, - "**/*.3ds":true, - "**/*.3DS":true, - "**/*.fbx":true, - "**/*.FBX":true, - "**/*.lxo":true, - "**/*.LXO":true, - "**/*.ma":true, - "**/*.MA":true, - "**/*.obj":true, - "**/*.OBJ":true, - "**/*.asset":true, - "**/*.cubemap":true, - "**/*.flare":true, - "**/*.mat":true, - "**/*.meta":true, - "**/*.prefab":true, - "**/*.unity":true, - "build/":true, - "Build/":true, - "Library/":true, - "library/":true, - "obj/":true, - "Obj/":true, - "ProjectSettings/":true, - "temp/":true, - "Temp/":true, - "Extensions/":true - }, - "csharp.referencesCodeLens.enabled": false -} \ No newline at end of file diff --git a/Assets/Examples/Bag/BagMain.cs b/Assets/Examples/Bag/BagMain.cs index 7675052b..1f4d434b 100644 --- a/Assets/Examples/Bag/BagMain.cs +++ b/Assets/Examples/Bag/BagMain.cs @@ -1,36 +1,36 @@ -using UnityEngine; -using FairyGUI; - -/// -/// A game bag demo, demonstrated how to customize loader to load icons not in the UI package. -/// -public class BagMain : MonoBehaviour -{ - GComponent _mainView; - BagWindow _bagWindow; - - void Awake() - { - //Register custom loader class - UIObjectFactory.SetLoaderExtension(typeof(MyGLoader)); - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - GRoot.inst.SetContentScaleFactor(1136, 640); - _mainView = this.GetComponent().ui; - - _bagWindow = new BagWindow(); - _mainView.GetChild("bagBtn").onClick.Add(() => { _bagWindow.Show(); }); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +/// +/// A game bag demo, demonstrated how to customize loader to load icons not in the UI package. +/// +public class BagMain : MonoBehaviour +{ + GComponent _mainView; + BagWindow _bagWindow; + + void Awake() + { + //Register custom loader class + UIObjectFactory.SetLoaderExtension(typeof(MyGLoader)); + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + GRoot.inst.SetContentScaleFactor(1136, 640); + _mainView = this.GetComponent().ui; + + _bagWindow = new BagWindow(); + _mainView.GetChild("bagBtn").onClick.Add(() => { _bagWindow.Show(); }); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Bag/BagWindow.cs b/Assets/Examples/Bag/BagWindow.cs index 2cbccfd9..6b809f6f 100644 --- a/Assets/Examples/Bag/BagWindow.cs +++ b/Assets/Examples/Bag/BagWindow.cs @@ -1,49 +1,49 @@ -using FairyGUI; -using UnityEngine; - -public class BagWindow : Window -{ - GList _list; - - public BagWindow() - { - } - - protected override void OnInit() - { - this.contentPane = UIPackage.CreateObject("Bag", "BagWin").asCom; - this.Center(); - this.modal = true; - - _list = this.contentPane.GetChild("list").asList; - _list.onClickItem.Add(__clickItem); - _list.itemRenderer = RenderListItem; - _list.numItems = 45; - } - - void RenderListItem(int index, GObject obj) - { - GButton button = (GButton)obj; - button.icon = "i" + UnityEngine.Random.Range(0, 10); - button.title = "" + UnityEngine.Random.Range(0, 100); - } - - override protected void DoShowAnimation() - { - this.SetScale(0.1f, 0.1f); - this.SetPivot(0.5f, 0.5f); - this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown); - } - - override protected void DoHideAnimation() - { - this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately); - } - - void __clickItem(EventContext context) - { - GButton item = (GButton)context.data; - this.contentPane.GetChild("n11").asLoader.url = item.icon; - this.contentPane.GetChild("n13").text = item.icon; - } -} +using FairyGUI; +using UnityEngine; + +public class BagWindow : Window +{ + GList _list; + + public BagWindow() + { + } + + protected override void OnInit() + { + this.contentPane = UIPackage.CreateObject("Bag", "BagWin").asCom; + this.Center(); + this.modal = true; + + _list = this.contentPane.GetChild("list").asList; + _list.onClickItem.Add(__clickItem); + _list.itemRenderer = RenderListItem; + _list.numItems = 45; + } + + void RenderListItem(int index, GObject obj) + { + GButton button = (GButton)obj; + button.icon = "i" + UnityEngine.Random.Range(0, 10); + button.title = "" + UnityEngine.Random.Range(0, 100); + } + + override protected void DoShowAnimation() + { + this.SetScale(0.1f, 0.1f); + this.SetPivot(0.5f, 0.5f); + this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown); + } + + override protected void DoHideAnimation() + { + this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately); + } + + void __clickItem(EventContext context) + { + GButton item = (GButton)context.data; + this.contentPane.GetChild("n11").asLoader.url = item.icon; + this.contentPane.GetChild("n13").text = item.icon; + } +} diff --git a/Assets/Examples/Bag/IconManager.cs b/Assets/Examples/Bag/IconManager.cs index 3c8816c8..4259ebf9 100644 --- a/Assets/Examples/Bag/IconManager.cs +++ b/Assets/Examples/Bag/IconManager.cs @@ -1,184 +1,184 @@ -using UnityEngine; -using System.Collections; -using System.Collections.Generic; -using FairyGUI; -#if UNITY_5_4_OR_NEWER -using UnityEngine.Networking; -#endif - -public delegate void LoadCompleteCallback(NTexture texture); -public delegate void LoadErrorCallback(string error); - -/// -/// Use to load icons from asset bundle, and pool them -/// -public class IconManager : MonoBehaviour -{ - static IconManager _instance; - public static IconManager inst - { - get - { - if (_instance == null) - { - GameObject go = new GameObject("IconManager"); - DontDestroyOnLoad(go); - _instance = go.AddComponent(); - } - return _instance; - } - } - - public const int POOL_CHECK_TIME = 30; - public const int MAX_POOL_SIZE = 10; - - List _items; - bool _started; - Hashtable _pool; - string _basePath; - - void Awake() - { - _items = new List(); - _pool = new Hashtable(); - _basePath = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/"; - if (Application.platform != RuntimePlatform.Android) - _basePath = "file:///" + _basePath; - - StartCoroutine(FreeIdleIcons()); - } - - public void LoadIcon(string url, - LoadCompleteCallback onSuccess, - LoadErrorCallback onFail) - { - LoadItem item = new LoadItem(); - item.url = url; - item.onSuccess = onSuccess; - item.onFail = onFail; - _items.Add(item); - if (!_started) - StartCoroutine(Run()); - } - - IEnumerator Run() - { - _started = true; - - LoadItem item = null; - while (true) - { - if (_items.Count > 0) - { - item = _items[0]; - _items.RemoveAt(0); - } - else - break; - - if (_pool.ContainsKey(item.url)) - { - //Debug.Log("hit " + item.url); - - NTexture texture = (NTexture)_pool[item.url]; - texture.refCount++; - - if (item.onSuccess != null) - item.onSuccess(texture); - - continue; - } - - string url = _basePath + item.url + ".ab"; -#if UNITY_2017_2_OR_NEWER -#if UNITY_2018_1_OR_NEWER - UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url); -#else - UnityWebRequest www = UnityWebRequest.GetAssetBundle(url); -#endif - yield return www.SendWebRequest(); - - if (!www.isNetworkError && !www.isHttpError) - { - AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www); -#else - WWW www = new WWW(url); - yield return www; - - if (string.IsNullOrEmpty(www.error)) - { - AssetBundle bundle = www.assetBundle; -#endif - - if (bundle == null) - { - Debug.LogWarning("Run Window->Build FairyGUI example Bundles first."); - if (item.onFail != null) - item.onFail(www.error); - continue; - } -#if (UNITY_5 || UNITY_5_3_OR_NEWER) - NTexture texture = new NTexture(bundle.LoadAllAssets()[0]); -#else - NTexture texture = new NTexture((Texture2D)bundle.mainAsset); -#endif - texture.refCount++; - bundle.Unload(false); - - _pool[item.url] = texture; - - if (item.onSuccess != null) - item.onSuccess(texture); - } - else - { - if (item.onFail != null) - item.onFail(www.error); - } - } - - _started = false; - } - - IEnumerator FreeIdleIcons() - { - yield return new WaitForSeconds(POOL_CHECK_TIME); //check the pool every 30 seconds - - int cnt = _pool.Count; - if (cnt > MAX_POOL_SIZE) - { - ArrayList toRemove = null; - foreach (DictionaryEntry de in _pool) - { - string key = (string)de.Key; - NTexture texture = (NTexture)de.Value; - if (texture.refCount == 0) - { - if (toRemove == null) - toRemove = new ArrayList(); - toRemove.Add(key); - texture.Dispose(); - - //Debug.Log("free icon " + de.Key); - - cnt--; - if (cnt <= 8) - break; - } - } - if (toRemove != null) - { - foreach (string key in toRemove) - _pool.Remove(key); - } - } - } - -} - -class LoadItem -{ - public string url; - public LoadCompleteCallback onSuccess; - public LoadErrorCallback onFail; -} +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using FairyGUI; +#if UNITY_5_4_OR_NEWER +using UnityEngine.Networking; +#endif + +public delegate void LoadCompleteCallback(NTexture texture); +public delegate void LoadErrorCallback(string error); + +/// +/// Use to load icons from asset bundle, and pool them +/// +public class IconManager : MonoBehaviour +{ + static IconManager _instance; + public static IconManager inst + { + get + { + if (_instance == null) + { + GameObject go = new GameObject("IconManager"); + DontDestroyOnLoad(go); + _instance = go.AddComponent(); + } + return _instance; + } + } + + public const int POOL_CHECK_TIME = 30; + public const int MAX_POOL_SIZE = 10; + + List _items; + bool _started; + Hashtable _pool; + string _basePath; + + void Awake() + { + _items = new List(); + _pool = new Hashtable(); + _basePath = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/"; + if (Application.platform != RuntimePlatform.Android) + _basePath = "file:///" + _basePath; + + StartCoroutine(FreeIdleIcons()); + } + + public void LoadIcon(string url, + LoadCompleteCallback onSuccess, + LoadErrorCallback onFail) + { + LoadItem item = new LoadItem(); + item.url = url; + item.onSuccess = onSuccess; + item.onFail = onFail; + _items.Add(item); + if (!_started) + StartCoroutine(Run()); + } + + IEnumerator Run() + { + _started = true; + + LoadItem item = null; + while (true) + { + if (_items.Count > 0) + { + item = _items[0]; + _items.RemoveAt(0); + } + else + break; + + if (_pool.ContainsKey(item.url)) + { + //Debug.Log("hit " + item.url); + + NTexture texture = (NTexture)_pool[item.url]; + texture.refCount++; + + if (item.onSuccess != null) + item.onSuccess(texture); + + continue; + } + + string url = _basePath + item.url + ".ab"; +#if UNITY_2017_2_OR_NEWER +#if UNITY_2018_1_OR_NEWER + UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url); +#else + UnityWebRequest www = UnityWebRequest.GetAssetBundle(url); +#endif + yield return www.SendWebRequest(); + + if (!www.isNetworkError && !www.isHttpError) + { + AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www); +#else + WWW www = new WWW(url); + yield return www; + + if (string.IsNullOrEmpty(www.error)) + { + AssetBundle bundle = www.assetBundle; +#endif + + if (bundle == null) + { + Debug.LogWarning("Run Window->Build FairyGUI example Bundles first."); + if (item.onFail != null) + item.onFail(www.error); + continue; + } +#if (UNITY_5 || UNITY_5_3_OR_NEWER) + NTexture texture = new NTexture(bundle.LoadAllAssets()[0]); +#else + NTexture texture = new NTexture((Texture2D)bundle.mainAsset); +#endif + texture.refCount++; + bundle.Unload(false); + + _pool[item.url] = texture; + + if (item.onSuccess != null) + item.onSuccess(texture); + } + else + { + if (item.onFail != null) + item.onFail(www.error); + } + } + + _started = false; + } + + IEnumerator FreeIdleIcons() + { + yield return new WaitForSeconds(POOL_CHECK_TIME); //check the pool every 30 seconds + + int cnt = _pool.Count; + if (cnt > MAX_POOL_SIZE) + { + ArrayList toRemove = null; + foreach (DictionaryEntry de in _pool) + { + string key = (string)de.Key; + NTexture texture = (NTexture)de.Value; + if (texture.refCount == 0) + { + if (toRemove == null) + toRemove = new ArrayList(); + toRemove.Add(key); + texture.Dispose(); + + //Debug.Log("free icon " + de.Key); + + cnt--; + if (cnt <= 8) + break; + } + } + if (toRemove != null) + { + foreach (string key in toRemove) + _pool.Remove(key); + } + } + } + +} + +class LoadItem +{ + public string url; + public LoadCompleteCallback onSuccess; + public LoadErrorCallback onFail; +} diff --git a/Assets/Examples/Bag/MyGLoader.cs b/Assets/Examples/Bag/MyGLoader.cs index 9d4e7634..67cff271 100644 --- a/Assets/Examples/Bag/MyGLoader.cs +++ b/Assets/Examples/Bag/MyGLoader.cs @@ -1,33 +1,33 @@ -using UnityEngine; -using FairyGUI; -using System.IO; - -/// -/// Extend the ability of GLoader -/// -public class MyGLoader : GLoader -{ - protected override void LoadExternal() - { - IconManager.inst.LoadIcon(this.url, OnLoadSuccess, OnLoadFail); - } - - protected override void FreeExternal(NTexture texture) - { - texture.refCount--; - } - - void OnLoadSuccess(NTexture texture) - { - if (string.IsNullOrEmpty(this.url)) - return; - - this.onExternalLoadSuccess(texture); - } - - void OnLoadFail(string error) - { - Debug.Log("load " + this.url + " failed: " + error); - this.onExternalLoadFailed(); - } -} +using UnityEngine; +using FairyGUI; +using System.IO; + +/// +/// Extend the ability of GLoader +/// +public class MyGLoader : GLoader +{ + protected override void LoadExternal() + { + IconManager.inst.LoadIcon(this.url, OnLoadSuccess, OnLoadFail); + } + + protected override void FreeExternal(NTexture texture) + { + texture.refCount--; + } + + void OnLoadSuccess(NTexture texture) + { + if (string.IsNullOrEmpty(this.url)) + return; + + this.onExternalLoadSuccess(texture); + } + + void OnLoadFail(string error) + { + Debug.Log("load " + this.url + " failed: " + error); + this.onExternalLoadFailed(); + } +} diff --git a/Assets/Examples/Basics/BasicsMain.cs b/Assets/Examples/Basics/BasicsMain.cs index 3e3af636..e211ca1b 100644 --- a/Assets/Examples/Basics/BasicsMain.cs +++ b/Assets/Examples/Basics/BasicsMain.cs @@ -1,441 +1,441 @@ -using UnityEngine; -using System.Collections.Generic; -using FairyGUI; - -public class BasicsMain : MonoBehaviour -{ - private GComponent _mainView; - private GObject _backBtn; - private GComponent _demoContainer; - private Controller _viewController; - private Dictionary _demoObjects; - - public Gradient lineGradient; - - void Awake() - { -#if (UNITY_5 || UNITY_5_3_OR_NEWER) - //Use the font names directly - UIConfig.defaultFont = "Microsoft YaHei"; -#else - //Need to put a ttf file into Resources folder. Here is the file name of the ttf file. - UIConfig.defaultFont = "afont"; -#endif - UIPackage.AddPackage("UI/Basics"); - - UIConfig.verticalScrollBar = "ui://Basics/ScrollBar_VT"; - UIConfig.horizontalScrollBar = "ui://Basics/ScrollBar_HZ"; - UIConfig.popupMenu = "ui://Basics/PopupMenu"; - UIConfig.buttonSound = (NAudioClip)UIPackage.GetItemAsset("Basics", "click"); - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _backBtn = _mainView.GetChild("btn_Back"); - _backBtn.visible = false; - _backBtn.onClick.Add(onClickBack); - - _demoContainer = _mainView.GetChild("container").asCom; - _viewController = _mainView.GetController("c1"); - - _demoObjects = new Dictionary(); - - int cnt = _mainView.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = _mainView.GetChildAt(i); - if (obj.group != null && obj.group.name == "btns") - obj.onClick.Add(runDemo); - } - } - - private void runDemo(EventContext context) - { - string type = ((GObject)(context.sender)).name.Substring(4); - GComponent obj; - if (!_demoObjects.TryGetValue(type, out obj)) - { - obj = UIPackage.CreateObject("Basics", "Demo_" + type).asCom; - _demoObjects[type] = obj; - } - - _demoContainer.RemoveChildren(); - _demoContainer.AddChild(obj); - _viewController.selectedIndex = 1; - _backBtn.visible = true; - - switch (type) - { - case "Graph": - PlayGraph(); - break; - - case "Button": - PlayButton(); - break; - - case "Text": - PlayText(); - break; - - case "Grid": - PlayGrid(); - break; - - case "Transition": - PlayTransition(); - break; - - case "Window": - PlayWindow(); - break; - - case "Popup": - PlayPopup(); - break; - - case "Drag&Drop": - PlayDragDrop(); - break; - - case "Depth": - PlayDepth(); - break; - - case "ProgressBar": - PlayProgressBar(); - break; - } - } - - private void onClickBack() - { - _viewController.selectedIndex = 0; - _backBtn.visible = false; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } - - //----------------------------- - private void PlayGraph() - { - GComponent obj = _demoObjects["Graph"]; - - Shape shape; - - shape = obj.GetChild("pie").asGraph.shape; - EllipseMesh ellipse = shape.graphics.GetMeshFactory(); - ellipse.startDegree = 30; - ellipse.endDegreee = 300; - shape.graphics.SetMeshDirty(); - - shape = obj.GetChild("trapezoid").asGraph.shape; - PolygonMesh trapezoid = shape.graphics.GetMeshFactory(); - trapezoid.usePercentPositions = true; - trapezoid.points.Clear(); - trapezoid.points.Add(new Vector2(0f, 1f)); - trapezoid.points.Add(new Vector2(0.3f, 0)); - trapezoid.points.Add(new Vector2(0.7f, 0)); - trapezoid.points.Add(new Vector2(1f, 1f)); - trapezoid.texcoords.Clear(); - trapezoid.texcoords.AddRange(VertexBuffer.NormalizedUV); - shape.graphics.SetMeshDirty(); - shape.graphics.texture = (NTexture)UIPackage.GetItemAsset("Basics", "change"); - - shape = obj.GetChild("line").asGraph.shape; - LineMesh line = shape.graphics.GetMeshFactory(); - line.lineWidthCurve = AnimationCurve.Linear(0, 25, 1, 10); - line.roundEdge = true; - line.gradient = lineGradient; - line.path.Create(new GPathPoint[] { - new GPathPoint(new Vector3(0, 120, 0)), - new GPathPoint(new Vector3(20, 120, 0)), - new GPathPoint(new Vector3(100, 100, 0)), - new GPathPoint(new Vector3(180, 30, 0)), - new GPathPoint(new Vector3(100, 0, 0)), - new GPathPoint(new Vector3(20, 30, 0)), - new GPathPoint(new Vector3(100, 100, 0)), - new GPathPoint(new Vector3(180, 120, 0)), - new GPathPoint(new Vector3(200, 120, 0)), - }); - shape.graphics.SetMeshDirty(); - GTween.To(0, 1, 5).SetEase(EaseType.Linear).SetTarget(shape.graphics).OnUpdate((GTweener t) => - { - ((NGraphics)t.target).GetMeshFactory().fillEnd = t.value.x; - ((NGraphics)t.target).SetMeshDirty(); - }); - - shape = obj.GetChild("line2").asGraph.shape; - LineMesh line2 = shape.graphics.GetMeshFactory(); - line2.lineWidth = 3; - line2.roundEdge = true; - line2.path.Create(new GPathPoint[] { - new GPathPoint(new Vector3(0, 120, 0), GPathPoint.CurveType.Straight), - new GPathPoint(new Vector3(60, 30, 0), GPathPoint.CurveType.Straight), - new GPathPoint(new Vector3(80, 90, 0), GPathPoint.CurveType.Straight), - new GPathPoint(new Vector3(140, 30, 0), GPathPoint.CurveType.Straight), - new GPathPoint(new Vector3(160, 90, 0), GPathPoint.CurveType.Straight), - new GPathPoint(new Vector3(220, 30, 0), GPathPoint.CurveType.Straight) - }); - shape.graphics.SetMeshDirty(); - - GObject image = obj.GetChild("line3"); - LineMesh line3 = image.displayObject.graphics.GetMeshFactory(); - line3.lineWidth = 30; - line3.roundEdge = false; - line3.path.Create(new GPathPoint[] { - new GPathPoint(new Vector3(0, 30, 0), new Vector3(50, -30), new Vector3(150, -50)), - new GPathPoint(new Vector3(200, 30, 0), new Vector3(300, 130)), - new GPathPoint(new Vector3(400, 30, 0)) - }); - image.displayObject.graphics.SetMeshDirty(); - } - - //----------------------------- - private void PlayButton() - { - GComponent obj = _demoObjects["Button"]; - obj.GetChild("n34").onClick.Add(() => { UnityEngine.Debug.Log("click button"); }); - } - - //------------------------------ - private void PlayText() - { - GComponent obj = _demoObjects["Text"]; - obj.GetChild("n12").asRichTextField.onClickLink.Add((EventContext context) => - { - GRichTextField t = context.sender as GRichTextField; - t.text = "[img]ui://Basics/pet[/img][color=#FF0000]You click the link[/color]:" + context.data; - }); - obj.GetChild("n25").onClick.Add(() => - { - obj.GetChild("n24").text = obj.GetChild("n22").text; - }); - } - - //------------------------------ - private void PlayGrid() - { - GComponent obj = _demoObjects["Grid"]; - GList list1 = obj.GetChild("list1").asList; - list1.RemoveChildrenToPool(); - string[] testNames = System.Enum.GetNames(typeof(RuntimePlatform)); - Color[] testColor = new Color[] { Color.yellow, Color.red, Color.white, Color.cyan }; - int cnt = testNames.Length; - for (int i = 0; i < cnt; i++) - { - GButton item = list1.AddItemFromPool().asButton; - item.GetChild("t0").text = "" + (i + 1); - item.GetChild("t1").text = testNames[i]; - item.GetChild("t2").asTextField.color = testColor[UnityEngine.Random.Range(0, 4)]; - item.GetChild("star").asProgress.value = (int)((float)UnityEngine.Random.Range(1, 4) / 3f * 100); - } - - GList list2 = obj.GetChild("list2").asList; - list2.RemoveChildrenToPool(); - for (int i = 0; i < cnt; i++) - { - GButton item = list2.AddItemFromPool().asButton; - item.GetChild("cb").asButton.selected = false; - item.GetChild("t1").text = testNames[i]; - item.GetChild("mc").asMovieClip.playing = i % 2 == 0; - item.GetChild("t3").text = "" + UnityEngine.Random.Range(0, 10000); - } - } - - //------------------------------ - private void PlayTransition() - { - GComponent obj = _demoObjects["Transition"]; - obj.GetChild("n2").asCom.GetTransition("t0").Play(int.MaxValue, 0, null); - obj.GetChild("n3").asCom.GetTransition("peng").Play(int.MaxValue, 0, null); - - obj.onAddedToStage.Add(() => - { - obj.GetChild("n2").asCom.GetTransition("t0").Stop(); - obj.GetChild("n3").asCom.GetTransition("peng").Stop(); - }); - } - - //------------------------------ - private Window _winA; - private Window _winB; - private void PlayWindow() - { - GComponent obj = _demoObjects["Window"]; - obj.GetChild("n0").onClick.Add(() => - { - if (_winA == null) - _winA = new Window1(); - _winA.Show(); - }); - - obj.GetChild("n1").onClick.Add(() => - { - if (_winB == null) - _winB = new Window2(); - _winB.Show(); - }); - } - - //------------------------------ - private PopupMenu _pm; - private GComponent _popupCom; - private void PlayPopup() - { - if (_pm == null) - { - _pm = new PopupMenu(); - _pm.AddItem("Item 1", __clickMenu); - _pm.AddItem("Item 2", __clickMenu); - _pm.AddItem("Item 3", __clickMenu); - _pm.AddItem("Item 4", __clickMenu); - } - - if (_popupCom == null) - { - _popupCom = UIPackage.CreateObject("Basics", "Component12").asCom; - _popupCom.Center(); - } - GComponent obj = _demoObjects["Popup"]; - obj.GetChild("n0").onClick.Add((EventContext context) => - { - _pm.Show((GObject)context.sender, PopupDirection.Down); - }); - - obj.GetChild("n1").onClick.Add(() => - { - GRoot.inst.ShowPopup(_popupCom); - }); - - - obj.onRightClick.Add(() => - { - _pm.Show(); - }); - } - - private void __clickMenu(EventContext context) - { - GObject itemObject = (GObject)context.data; - UnityEngine.Debug.Log("click " + itemObject.text); - } - - //------------------------------ - Vector2 startPos; - private void PlayDepth() - { - GComponent obj = _demoObjects["Depth"]; - GComponent testContainer = obj.GetChild("n22").asCom; - GObject fixedObj = testContainer.GetChild("n0"); - fixedObj.sortingOrder = 100; - fixedObj.draggable = true; - - int numChildren = testContainer.numChildren; - int i = 0; - while (i < numChildren) - { - GObject child = testContainer.GetChildAt(i); - if (child != fixedObj) - { - testContainer.RemoveChildAt(i); - numChildren--; - } - else - i++; - } - startPos = new Vector2(fixedObj.x, fixedObj.y); - - obj.GetChild("btn0").onClick.Add(() => - { - GGraph graph = new GGraph(); - startPos.x += 10; - startPos.y += 10; - graph.xy = startPos; - graph.DrawRect(150, 150, 1, Color.black, Color.red); - obj.GetChild("n22").asCom.AddChild(graph); - }); - - obj.GetChild("btn1").onClick.Add(() => - { - GGraph graph = new GGraph(); - startPos.x += 10; - startPos.y += 10; - graph.xy = startPos; - graph.DrawRect(150, 150, 1, Color.black, Color.green); - graph.sortingOrder = 200; - obj.GetChild("n22").asCom.AddChild(graph); - }); - } - - //------------------------------ - private void PlayDragDrop() - { - GComponent obj = _demoObjects["Drag&Drop"]; - obj.GetChild("a").draggable = true; - - GButton b = obj.GetChild("b").asButton; - b.draggable = true; - b.onDragStart.Add((EventContext context) => - { - //Cancel the original dragging, and start a new one with a agent. - context.PreventDefault(); - - DragDropManager.inst.StartDrag(b, b.icon, b.icon, (int)context.data); - }); - - GButton c = obj.GetChild("c").asButton; - c.icon = null; - c.onDrop.Add((EventContext context) => - { - c.icon = (string)context.data; - }); - - GObject bounds = obj.GetChild("n7"); - Rect rect = bounds.TransformRect(new Rect(0, 0, bounds.width, bounds.height), GRoot.inst); - - //---!!Because at this time the container is on the right side of the stage and beginning to move to left(transition), so we need to caculate the final position - rect.x -= obj.parent.x; - //---- - - GButton d = obj.GetChild("d").asButton; - d.draggable = true; - d.dragBounds = rect; - } - - //------------------------------ - private void PlayProgressBar() - { - GComponent obj = _demoObjects["ProgressBar"]; - Timers.inst.Add(0.001f, 0, __playProgress); - obj.onRemovedFromStage.Add(() => { Timers.inst.Remove(__playProgress); }); - } - - void __playProgress(object param) - { - GComponent obj = _demoObjects["ProgressBar"]; - int cnt = obj.numChildren; - for (int i = 0; i < cnt; i++) - { - GProgressBar child = obj.GetChildAt(i) as GProgressBar; - if (child != null) - { - - child.value += 1; - if (child.value > child.max) - child.value = 0; - } - } - } +using UnityEngine; +using System.Collections.Generic; +using FairyGUI; + +public class BasicsMain : MonoBehaviour +{ + private GComponent _mainView; + private GObject _backBtn; + private GComponent _demoContainer; + private Controller _viewController; + private Dictionary _demoObjects; + + public Gradient lineGradient; + + void Awake() + { +#if (UNITY_5 || UNITY_5_3_OR_NEWER) + //Use the font names directly + UIConfig.defaultFont = "Microsoft YaHei"; +#else + //Need to put a ttf file into Resources folder. Here is the file name of the ttf file. + UIConfig.defaultFont = "afont"; +#endif + UIPackage.AddPackage("UI/Basics"); + + UIConfig.verticalScrollBar = "ui://Basics/ScrollBar_VT"; + UIConfig.horizontalScrollBar = "ui://Basics/ScrollBar_HZ"; + UIConfig.popupMenu = "ui://Basics/PopupMenu"; + UIConfig.buttonSound = (NAudioClip)UIPackage.GetItemAsset("Basics", "click"); + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _backBtn = _mainView.GetChild("btn_Back"); + _backBtn.visible = false; + _backBtn.onClick.Add(onClickBack); + + _demoContainer = _mainView.GetChild("container").asCom; + _viewController = _mainView.GetController("c1"); + + _demoObjects = new Dictionary(); + + int cnt = _mainView.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = _mainView.GetChildAt(i); + if (obj.group != null && obj.group.name == "btns") + obj.onClick.Add(runDemo); + } + } + + private void runDemo(EventContext context) + { + string type = ((GObject)(context.sender)).name.Substring(4); + GComponent obj; + if (!_demoObjects.TryGetValue(type, out obj)) + { + obj = UIPackage.CreateObject("Basics", "Demo_" + type).asCom; + _demoObjects[type] = obj; + } + + _demoContainer.RemoveChildren(); + _demoContainer.AddChild(obj); + _viewController.selectedIndex = 1; + _backBtn.visible = true; + + switch (type) + { + case "Graph": + PlayGraph(); + break; + + case "Button": + PlayButton(); + break; + + case "Text": + PlayText(); + break; + + case "Grid": + PlayGrid(); + break; + + case "Transition": + PlayTransition(); + break; + + case "Window": + PlayWindow(); + break; + + case "Popup": + PlayPopup(); + break; + + case "Drag&Drop": + PlayDragDrop(); + break; + + case "Depth": + PlayDepth(); + break; + + case "ProgressBar": + PlayProgressBar(); + break; + } + } + + private void onClickBack() + { + _viewController.selectedIndex = 0; + _backBtn.visible = false; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } + + //----------------------------- + private void PlayGraph() + { + GComponent obj = _demoObjects["Graph"]; + + Shape shape; + + shape = obj.GetChild("pie").asGraph.shape; + EllipseMesh ellipse = shape.graphics.GetMeshFactory(); + ellipse.startDegree = 30; + ellipse.endDegreee = 300; + shape.graphics.SetMeshDirty(); + + shape = obj.GetChild("trapezoid").asGraph.shape; + PolygonMesh trapezoid = shape.graphics.GetMeshFactory(); + trapezoid.usePercentPositions = true; + trapezoid.points.Clear(); + trapezoid.points.Add(new Vector2(0f, 1f)); + trapezoid.points.Add(new Vector2(0.3f, 0)); + trapezoid.points.Add(new Vector2(0.7f, 0)); + trapezoid.points.Add(new Vector2(1f, 1f)); + trapezoid.texcoords.Clear(); + trapezoid.texcoords.AddRange(VertexBuffer.NormalizedUV); + shape.graphics.SetMeshDirty(); + shape.graphics.texture = (NTexture)UIPackage.GetItemAsset("Basics", "change"); + + shape = obj.GetChild("line").asGraph.shape; + LineMesh line = shape.graphics.GetMeshFactory(); + line.lineWidthCurve = AnimationCurve.Linear(0, 25, 1, 10); + line.roundEdge = true; + line.gradient = lineGradient; + line.path.Create(new GPathPoint[] { + new GPathPoint(new Vector3(0, 120, 0)), + new GPathPoint(new Vector3(20, 120, 0)), + new GPathPoint(new Vector3(100, 100, 0)), + new GPathPoint(new Vector3(180, 30, 0)), + new GPathPoint(new Vector3(100, 0, 0)), + new GPathPoint(new Vector3(20, 30, 0)), + new GPathPoint(new Vector3(100, 100, 0)), + new GPathPoint(new Vector3(180, 120, 0)), + new GPathPoint(new Vector3(200, 120, 0)), + }); + shape.graphics.SetMeshDirty(); + GTween.To(0, 1, 5).SetEase(EaseType.Linear).SetTarget(shape.graphics).OnUpdate((GTweener t) => + { + ((NGraphics)t.target).GetMeshFactory().fillEnd = t.value.x; + ((NGraphics)t.target).SetMeshDirty(); + }); + + shape = obj.GetChild("line2").asGraph.shape; + LineMesh line2 = shape.graphics.GetMeshFactory(); + line2.lineWidth = 3; + line2.roundEdge = true; + line2.path.Create(new GPathPoint[] { + new GPathPoint(new Vector3(0, 120, 0), GPathPoint.CurveType.Straight), + new GPathPoint(new Vector3(60, 30, 0), GPathPoint.CurveType.Straight), + new GPathPoint(new Vector3(80, 90, 0), GPathPoint.CurveType.Straight), + new GPathPoint(new Vector3(140, 30, 0), GPathPoint.CurveType.Straight), + new GPathPoint(new Vector3(160, 90, 0), GPathPoint.CurveType.Straight), + new GPathPoint(new Vector3(220, 30, 0), GPathPoint.CurveType.Straight) + }); + shape.graphics.SetMeshDirty(); + + GObject image = obj.GetChild("line3"); + LineMesh line3 = image.displayObject.graphics.GetMeshFactory(); + line3.lineWidth = 30; + line3.roundEdge = false; + line3.path.Create(new GPathPoint[] { + new GPathPoint(new Vector3(0, 30, 0), new Vector3(50, -30), new Vector3(150, -50)), + new GPathPoint(new Vector3(200, 30, 0), new Vector3(300, 130)), + new GPathPoint(new Vector3(400, 30, 0)) + }); + image.displayObject.graphics.SetMeshDirty(); + } + + //----------------------------- + private void PlayButton() + { + GComponent obj = _demoObjects["Button"]; + obj.GetChild("n34").onClick.Add(() => { UnityEngine.Debug.Log("click button"); }); + } + + //------------------------------ + private void PlayText() + { + GComponent obj = _demoObjects["Text"]; + obj.GetChild("n12").asRichTextField.onClickLink.Add((EventContext context) => + { + GRichTextField t = context.sender as GRichTextField; + t.text = "[img]ui://Basics/pet[/img][color=#FF0000]You click the link[/color]:" + context.data; + }); + obj.GetChild("n25").onClick.Add(() => + { + obj.GetChild("n24").text = obj.GetChild("n22").text; + }); + } + + //------------------------------ + private void PlayGrid() + { + GComponent obj = _demoObjects["Grid"]; + GList list1 = obj.GetChild("list1").asList; + list1.RemoveChildrenToPool(); + string[] testNames = System.Enum.GetNames(typeof(RuntimePlatform)); + Color[] testColor = new Color[] { Color.yellow, Color.red, Color.white, Color.cyan }; + int cnt = testNames.Length; + for (int i = 0; i < cnt; i++) + { + GButton item = list1.AddItemFromPool().asButton; + item.GetChild("t0").text = "" + (i + 1); + item.GetChild("t1").text = testNames[i]; + item.GetChild("t2").asTextField.color = testColor[UnityEngine.Random.Range(0, 4)]; + item.GetChild("star").asProgress.value = (int)((float)UnityEngine.Random.Range(1, 4) / 3f * 100); + } + + GList list2 = obj.GetChild("list2").asList; + list2.RemoveChildrenToPool(); + for (int i = 0; i < cnt; i++) + { + GButton item = list2.AddItemFromPool().asButton; + item.GetChild("cb").asButton.selected = false; + item.GetChild("t1").text = testNames[i]; + item.GetChild("mc").asMovieClip.playing = i % 2 == 0; + item.GetChild("t3").text = "" + UnityEngine.Random.Range(0, 10000); + } + } + + //------------------------------ + private void PlayTransition() + { + GComponent obj = _demoObjects["Transition"]; + obj.GetChild("n2").asCom.GetTransition("t0").Play(int.MaxValue, 0, null); + obj.GetChild("n3").asCom.GetTransition("peng").Play(int.MaxValue, 0, null); + + obj.onAddedToStage.Add(() => + { + obj.GetChild("n2").asCom.GetTransition("t0").Stop(); + obj.GetChild("n3").asCom.GetTransition("peng").Stop(); + }); + } + + //------------------------------ + private Window _winA; + private Window _winB; + private void PlayWindow() + { + GComponent obj = _demoObjects["Window"]; + obj.GetChild("n0").onClick.Add(() => + { + if (_winA == null) + _winA = new Window1(); + _winA.Show(); + }); + + obj.GetChild("n1").onClick.Add(() => + { + if (_winB == null) + _winB = new Window2(); + _winB.Show(); + }); + } + + //------------------------------ + private PopupMenu _pm; + private GComponent _popupCom; + private void PlayPopup() + { + if (_pm == null) + { + _pm = new PopupMenu(); + _pm.AddItem("Item 1", __clickMenu); + _pm.AddItem("Item 2", __clickMenu); + _pm.AddItem("Item 3", __clickMenu); + _pm.AddItem("Item 4", __clickMenu); + } + + if (_popupCom == null) + { + _popupCom = UIPackage.CreateObject("Basics", "Component12").asCom; + _popupCom.Center(); + } + GComponent obj = _demoObjects["Popup"]; + obj.GetChild("n0").onClick.Add((EventContext context) => + { + _pm.Show((GObject)context.sender, PopupDirection.Down); + }); + + obj.GetChild("n1").onClick.Add(() => + { + GRoot.inst.ShowPopup(_popupCom); + }); + + + obj.onRightClick.Add(() => + { + _pm.Show(); + }); + } + + private void __clickMenu(EventContext context) + { + GObject itemObject = (GObject)context.data; + UnityEngine.Debug.Log("click " + itemObject.text); + } + + //------------------------------ + Vector2 startPos; + private void PlayDepth() + { + GComponent obj = _demoObjects["Depth"]; + GComponent testContainer = obj.GetChild("n22").asCom; + GObject fixedObj = testContainer.GetChild("n0"); + fixedObj.sortingOrder = 100; + fixedObj.draggable = true; + + int numChildren = testContainer.numChildren; + int i = 0; + while (i < numChildren) + { + GObject child = testContainer.GetChildAt(i); + if (child != fixedObj) + { + testContainer.RemoveChildAt(i); + numChildren--; + } + else + i++; + } + startPos = new Vector2(fixedObj.x, fixedObj.y); + + obj.GetChild("btn0").onClick.Add(() => + { + GGraph graph = new GGraph(); + startPos.x += 10; + startPos.y += 10; + graph.xy = startPos; + graph.DrawRect(150, 150, 1, Color.black, Color.red); + obj.GetChild("n22").asCom.AddChild(graph); + }); + + obj.GetChild("btn1").onClick.Add(() => + { + GGraph graph = new GGraph(); + startPos.x += 10; + startPos.y += 10; + graph.xy = startPos; + graph.DrawRect(150, 150, 1, Color.black, Color.green); + graph.sortingOrder = 200; + obj.GetChild("n22").asCom.AddChild(graph); + }); + } + + //------------------------------ + private void PlayDragDrop() + { + GComponent obj = _demoObjects["Drag&Drop"]; + obj.GetChild("a").draggable = true; + + GButton b = obj.GetChild("b").asButton; + b.draggable = true; + b.onDragStart.Add((EventContext context) => + { + //Cancel the original dragging, and start a new one with a agent. + context.PreventDefault(); + + DragDropManager.inst.StartDrag(b, b.icon, b.icon, (int)context.data); + }); + + GButton c = obj.GetChild("c").asButton; + c.icon = null; + c.onDrop.Add((EventContext context) => + { + c.icon = (string)context.data; + }); + + GObject bounds = obj.GetChild("n7"); + Rect rect = bounds.TransformRect(new Rect(0, 0, bounds.width, bounds.height), GRoot.inst); + + //---!!Because at this time the container is on the right side of the stage and beginning to move to left(transition), so we need to caculate the final position + rect.x -= obj.parent.x; + //---- + + GButton d = obj.GetChild("d").asButton; + d.draggable = true; + d.dragBounds = rect; + } + + //------------------------------ + private void PlayProgressBar() + { + GComponent obj = _demoObjects["ProgressBar"]; + Timers.inst.Add(0.001f, 0, __playProgress); + obj.onRemovedFromStage.Add(() => { Timers.inst.Remove(__playProgress); }); + } + + void __playProgress(object param) + { + GComponent obj = _demoObjects["ProgressBar"]; + int cnt = obj.numChildren; + for (int i = 0; i < cnt; i++) + { + GProgressBar child = obj.GetChildAt(i) as GProgressBar; + if (child != null) + { + + child.value += 1; + if (child.value > child.max) + child.value = 0; + } + } + } } \ No newline at end of file diff --git a/Assets/Examples/Basics/Window1.cs b/Assets/Examples/Basics/Window1.cs index fab5de33..318878f9 100644 --- a/Assets/Examples/Basics/Window1.cs +++ b/Assets/Examples/Basics/Window1.cs @@ -1,29 +1,29 @@ -using System; -using System.Collections.Generic; -using FairyGUI; - -public class Window1 : Window -{ - public Window1() - { - } - - protected override void OnInit() - { - this.contentPane = UIPackage.CreateObject("Basics", "WindowA").asCom; - this.Center(); - } - - override protected void OnShown() - { - GList list = this.contentPane.GetChild("n6").asList; - list.RemoveChildrenToPool(); - - for (int i = 0; i < 6; i++) - { - GButton item = list.AddItemFromPool().asButton; - item.title = "" + i; - item.icon = UIPackage.GetItemURL("Basics", "r4"); - } - } -} +using System; +using System.Collections.Generic; +using FairyGUI; + +public class Window1 : Window +{ + public Window1() + { + } + + protected override void OnInit() + { + this.contentPane = UIPackage.CreateObject("Basics", "WindowA").asCom; + this.Center(); + } + + override protected void OnShown() + { + GList list = this.contentPane.GetChild("n6").asList; + list.RemoveChildrenToPool(); + + for (int i = 0; i < 6; i++) + { + GButton item = list.AddItemFromPool().asButton; + item.title = "" + i; + item.icon = UIPackage.GetItemURL("Basics", "r4"); + } + } +} diff --git a/Assets/Examples/Basics/Window2.cs b/Assets/Examples/Basics/Window2.cs index 590c4851..df1a5efa 100644 --- a/Assets/Examples/Basics/Window2.cs +++ b/Assets/Examples/Basics/Window2.cs @@ -1,39 +1,39 @@ -using System; -using System.Collections.Generic; -using FairyGUI; -using UnityEngine; - -public class Window2 : Window -{ - public Window2() - { - } - - protected override void OnInit() - { - this.contentPane = UIPackage.CreateObject("Basics", "WindowB").asCom; - this.Center(); - } - - override protected void DoShowAnimation() - { - this.SetScale(0.1f, 0.1f); - this.SetPivot(0.5f, 0.5f); - this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown); - } - - override protected void DoHideAnimation() - { - this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately); - } - - override protected void OnShown() - { - contentPane.GetTransition("t1").Play(); - } - - override protected void OnHide() - { - contentPane.GetTransition("t1").Stop(); - } -} +using System; +using System.Collections.Generic; +using FairyGUI; +using UnityEngine; + +public class Window2 : Window +{ + public Window2() + { + } + + protected override void OnInit() + { + this.contentPane = UIPackage.CreateObject("Basics", "WindowB").asCom; + this.Center(); + } + + override protected void DoShowAnimation() + { + this.SetScale(0.1f, 0.1f); + this.SetPivot(0.5f, 0.5f); + this.TweenScale(new Vector2(1, 1), 0.3f).OnComplete(this.OnShown); + } + + override protected void DoHideAnimation() + { + this.TweenScale(new Vector2(0.1f, 0.1f), 0.3f).OnComplete(this.HideImmediately); + } + + override protected void OnShown() + { + contentPane.GetTransition("t1").Play(); + } + + override protected void OnHide() + { + contentPane.GetTransition("t1").Stop(); + } +} diff --git a/Assets/Examples/BundleUsage/BundleUsageMain.cs b/Assets/Examples/BundleUsage/BundleUsageMain.cs index 3b5634d2..a107bf7c 100644 --- a/Assets/Examples/BundleUsage/BundleUsageMain.cs +++ b/Assets/Examples/BundleUsage/BundleUsageMain.cs @@ -1,75 +1,75 @@ -using System.Collections; -using UnityEngine; -using FairyGUI; -#if UNITY_5_4_OR_NEWER -using UnityEngine.Networking; -#endif - -/// -/// Demonstrated how to load UI package from assetbundle. The bundle can be build from the Window Menu->Build FairyGUI example bundles. -/// -class BundleUsageMain : MonoBehaviour -{ - GComponent _mainView; - - void Start() - { - Application.targetFrameRate = 60; - - Stage.inst.onKeyDown.Add(OnKeyDown); - - StartCoroutine(LoadUIPackage()); - } - - IEnumerator LoadUIPackage() - { - string url = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/bundleusage.ab"; - if (Application.platform != RuntimePlatform.Android) - url = "file:///" + url; - -#if UNITY_2017_2_OR_NEWER -#if UNITY_2018_1_OR_NEWER - UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url); -#else - UnityWebRequest www = UnityWebRequest.GetAssetBundle(url); -#endif - yield return www.SendWebRequest(); - - if (!www.isNetworkError && !www.isHttpError) - { - AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www); -#else - WWW www = new WWW(url); - yield return www; - - if (string.IsNullOrEmpty(www.error)) - { - AssetBundle bundle = www.assetBundle; -#endif - if (bundle == null) - { - Debug.LogWarning("Run Window->Build FairyGUI example Bundles first."); - yield return 0; - } - UIPackage.AddPackage(bundle); - - _mainView = UIPackage.CreateObject("BundleUsage", "Main").asCom; - _mainView.fairyBatching = true; - _mainView.SetSize(GRoot.inst.width, GRoot.inst.height); - _mainView.AddRelation(GRoot.inst, RelationType.Size); - - GRoot.inst.AddChild(_mainView); - _mainView.GetTransition("t0").Play(); - } - else - Debug.LogError(www.error); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } -} +using System.Collections; +using UnityEngine; +using FairyGUI; +#if UNITY_5_4_OR_NEWER +using UnityEngine.Networking; +#endif + +/// +/// Demonstrated how to load UI package from assetbundle. The bundle can be build from the Window Menu->Build FairyGUI example bundles. +/// +class BundleUsageMain : MonoBehaviour +{ + GComponent _mainView; + + void Start() + { + Application.targetFrameRate = 60; + + Stage.inst.onKeyDown.Add(OnKeyDown); + + StartCoroutine(LoadUIPackage()); + } + + IEnumerator LoadUIPackage() + { + string url = Application.streamingAssetsPath.Replace("\\", "/") + "/fairygui-examples/bundleusage.ab"; + if (Application.platform != RuntimePlatform.Android) + url = "file:///" + url; + +#if UNITY_2017_2_OR_NEWER +#if UNITY_2018_1_OR_NEWER + UnityWebRequest www = UnityWebRequestAssetBundle.GetAssetBundle(url); +#else + UnityWebRequest www = UnityWebRequest.GetAssetBundle(url); +#endif + yield return www.SendWebRequest(); + + if (!www.isNetworkError && !www.isHttpError) + { + AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www); +#else + WWW www = new WWW(url); + yield return www; + + if (string.IsNullOrEmpty(www.error)) + { + AssetBundle bundle = www.assetBundle; +#endif + if (bundle == null) + { + Debug.LogWarning("Run Window->Build FairyGUI example Bundles first."); + yield return 0; + } + UIPackage.AddPackage(bundle); + + _mainView = UIPackage.CreateObject("BundleUsage", "Main").asCom; + _mainView.fairyBatching = true; + _mainView.SetSize(GRoot.inst.width, GRoot.inst.height); + _mainView.AddRelation(GRoot.inst, RelationType.Size); + + GRoot.inst.AddChild(_mainView); + _mainView.GetTransition("t0").Play(); + } + else + Debug.LogError(www.error); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } +} diff --git a/Assets/Examples/Cooldown/CooldownMain.cs b/Assets/Examples/Cooldown/CooldownMain.cs index 3a6102b6..b540b93d 100644 --- a/Assets/Examples/Cooldown/CooldownMain.cs +++ b/Assets/Examples/Cooldown/CooldownMain.cs @@ -1,57 +1,57 @@ -using UnityEngine; -using FairyGUI; -public class CooldownMain : MonoBehaviour -{ - GComponent _mainView; - - GButton _btn0; - GImage _mask0; - float _time1; - - GButton _btn1; - GImage _mask1; - float _time2; - - void Start() - { - Application.targetFrameRate = 60; - - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.gameObject.GetComponent().ui; - - _btn0 = _mainView.GetChild("b0").asButton; - _btn0.icon = "Cooldown/k0"; - _time1 = 5; - _mask0 = _btn0.GetChild("mask").asImage; - - _btn1 = _mainView.GetChild("b1").asButton; - _btn1.icon = "Cooldown/k1"; - _time2 = 10; - _mask1 = _btn1.GetChild("mask").asImage; - - } - - void Update() - { - _time1 -= Time.deltaTime; - if (_time1 < 0) - _time1 = 5; - _mask0.fillAmount = 1 - (5 - _time1) / 5f; - - _time2 -= Time.deltaTime; - if (_time2 < 0) - _time2 = 10; - _btn1.text = string.Empty + Mathf.RoundToInt(_time2); - _mask1.fillAmount = 1 - (10 - _time2) / 10f; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } - +using UnityEngine; +using FairyGUI; +public class CooldownMain : MonoBehaviour +{ + GComponent _mainView; + + GButton _btn0; + GImage _mask0; + float _time1; + + GButton _btn1; + GImage _mask1; + float _time2; + + void Start() + { + Application.targetFrameRate = 60; + + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.gameObject.GetComponent().ui; + + _btn0 = _mainView.GetChild("b0").asButton; + _btn0.icon = "Cooldown/k0"; + _time1 = 5; + _mask0 = _btn0.GetChild("mask").asImage; + + _btn1 = _mainView.GetChild("b1").asButton; + _btn1.icon = "Cooldown/k1"; + _time2 = 10; + _mask1 = _btn1.GetChild("mask").asImage; + + } + + void Update() + { + _time1 -= Time.deltaTime; + if (_time1 < 0) + _time1 = 5; + _mask0.fillAmount = 1 - (5 - _time1) / 5f; + + _time2 -= Time.deltaTime; + if (_time2 < 0) + _time2 = 10; + _btn1.text = string.Empty + Mathf.RoundToInt(_time2); + _mask1.fillAmount = 1 - (10 - _time2) / 10f; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } + } \ No newline at end of file diff --git a/Assets/Examples/Curve/CurveMain.cs b/Assets/Examples/Curve/CurveMain.cs index 2f736a02..0b5803b0 100644 --- a/Assets/Examples/Curve/CurveMain.cs +++ b/Assets/Examples/Curve/CurveMain.cs @@ -1,58 +1,58 @@ -using UnityEngine; -using FairyGUI; - -public class CurveMain : MonoBehaviour -{ - GComponent _mainView; - GList _list; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _list = _mainView.GetChild("list").asList; - _list.SetVirtualAndLoop(); - _list.itemRenderer = RenderListItem; - _list.numItems = 5; - _list.scrollPane.onScroll.Add(DoSpecialEffect); - - DoSpecialEffect(); - } - - void DoSpecialEffect() - { - //change the scale according to the distance to middle - float midX = _list.scrollPane.posX + _list.viewWidth / 2; - int cnt = _list.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = _list.GetChildAt(i); - float dist = Mathf.Abs(midX - obj.x - obj.width / 2); - if (dist > obj.width) //no intersection - obj.SetScale(1, 1); - else - { - float ss = 1 + (1 - dist / obj.width) * 0.24f; - obj.SetScale(ss, ss); - } - } - } - - void RenderListItem(int index, GObject obj) - { - GButton item = (GButton)obj; - item.SetPivot(0.5f, 0.5f); - item.icon = UIPackage.GetItemURL("Curve", "n" + (index + 1)); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class CurveMain : MonoBehaviour +{ + GComponent _mainView; + GList _list; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _list = _mainView.GetChild("list").asList; + _list.SetVirtualAndLoop(); + _list.itemRenderer = RenderListItem; + _list.numItems = 5; + _list.scrollPane.onScroll.Add(DoSpecialEffect); + + DoSpecialEffect(); + } + + void DoSpecialEffect() + { + //change the scale according to the distance to middle + float midX = _list.scrollPane.posX + _list.viewWidth / 2; + int cnt = _list.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = _list.GetChildAt(i); + float dist = Mathf.Abs(midX - obj.x - obj.width / 2); + if (dist > obj.width) //no intersection + obj.SetScale(1, 1); + else + { + float ss = 1 + (1 - dist / obj.width) * 0.24f; + obj.SetScale(ss, ss); + } + } + } + + void RenderListItem(int index, GObject obj) + { + GButton item = (GButton)obj; + item.SetPivot(0.5f, 0.5f); + item.icon = UIPackage.GetItemURL("Curve", "n" + (index + 1)); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/CutScene/CutSceneMain.cs b/Assets/Examples/CutScene/CutSceneMain.cs index a9aacab6..a1cfafd8 100644 --- a/Assets/Examples/CutScene/CutSceneMain.cs +++ b/Assets/Examples/CutScene/CutSceneMain.cs @@ -1,28 +1,28 @@ -using System.Collections; -using UnityEngine; -using FairyGUI; - -/// -/// Demonstrated the simple flow of a game. -/// -public class CutSceneMain : MonoBehaviour -{ - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - UIPackage.AddPackage("UI/CutScene"); - - LevelManager.inst.Init(); - LevelManager.inst.LoadLevel("scene1"); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using System.Collections; +using UnityEngine; +using FairyGUI; + +/// +/// Demonstrated the simple flow of a game. +/// +public class CutSceneMain : MonoBehaviour +{ + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + UIPackage.AddPackage("UI/CutScene"); + + LevelManager.inst.Init(); + LevelManager.inst.LoadLevel("scene1"); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/CutScene/LevelManager.cs b/Assets/Examples/CutScene/LevelManager.cs index 53afda87..a08c2a13 100644 --- a/Assets/Examples/CutScene/LevelManager.cs +++ b/Assets/Examples/CutScene/LevelManager.cs @@ -1,82 +1,82 @@ -using System.Collections; -using UnityEngine; -#if UNITY_5_3_OR_NEWER -using UnityEngine.SceneManagement; -#endif -using FairyGUI; - -public class LevelManager : MonoBehaviour -{ - static LevelManager _instance; - public static LevelManager inst - { - get - { - if (_instance == null) - { - GameObject go = new GameObject("LevelManager"); - DontDestroyOnLoad(go); - _instance = go.AddComponent(); - } - return _instance; - } - } - - GComponent _cutSceneView; - GComponent _mainView; - - public LevelManager() - { - } - - public void Init() - { - _cutSceneView = UIPackage.CreateObject("CutScene", "CutScene").asCom; - _cutSceneView.SetSize(GRoot.inst.width, GRoot.inst.height); - _cutSceneView.AddRelation(GRoot.inst, RelationType.Size); - - _mainView = UIPackage.CreateObject("CutScene", "Main").asCom; - _mainView.SetSize(GRoot.inst.width, GRoot.inst.height); - _mainView.AddRelation(GRoot.inst, RelationType.Size); - - _mainView.GetChild("n0").onClick.Add(() => - { - LoadLevel("scene1"); - }); - - _mainView.GetChild("n1").onClick.Add(() => - { - LoadLevel("scene2"); - }); - } - - public void LoadLevel(string levelName) - { - StartCoroutine(DoLoad(levelName)); - GRoot.inst.AddChild(_cutSceneView); - } - - IEnumerator DoLoad(string sceneName) - { - GRoot.inst.AddChild(_cutSceneView); - GProgressBar pb = _cutSceneView.GetChild("pb").asProgress; - pb.value = 0; -#if UNITY_5_3_OR_NEWER - AsyncOperation op = SceneManager.LoadSceneAsync(sceneName); -#else - AsyncOperation op = Application.LoadLevelAsync(sceneName); -#endif - float startTime = Time.time; - while (!op.isDone || pb.value != 100) - { - int value = (int)((Time.time - startTime) * 100f / 3f); - if (value > 100) - value = 100; - pb.value = value; - yield return null; - } - - GRoot.inst.RemoveChild(_cutSceneView); - GRoot.inst.AddChild(_mainView); - } -} +using System.Collections; +using UnityEngine; +#if UNITY_5_3_OR_NEWER +using UnityEngine.SceneManagement; +#endif +using FairyGUI; + +public class LevelManager : MonoBehaviour +{ + static LevelManager _instance; + public static LevelManager inst + { + get + { + if (_instance == null) + { + GameObject go = new GameObject("LevelManager"); + DontDestroyOnLoad(go); + _instance = go.AddComponent(); + } + return _instance; + } + } + + GComponent _cutSceneView; + GComponent _mainView; + + public LevelManager() + { + } + + public void Init() + { + _cutSceneView = UIPackage.CreateObject("CutScene", "CutScene").asCom; + _cutSceneView.SetSize(GRoot.inst.width, GRoot.inst.height); + _cutSceneView.AddRelation(GRoot.inst, RelationType.Size); + + _mainView = UIPackage.CreateObject("CutScene", "Main").asCom; + _mainView.SetSize(GRoot.inst.width, GRoot.inst.height); + _mainView.AddRelation(GRoot.inst, RelationType.Size); + + _mainView.GetChild("n0").onClick.Add(() => + { + LoadLevel("scene1"); + }); + + _mainView.GetChild("n1").onClick.Add(() => + { + LoadLevel("scene2"); + }); + } + + public void LoadLevel(string levelName) + { + StartCoroutine(DoLoad(levelName)); + GRoot.inst.AddChild(_cutSceneView); + } + + IEnumerator DoLoad(string sceneName) + { + GRoot.inst.AddChild(_cutSceneView); + GProgressBar pb = _cutSceneView.GetChild("pb").asProgress; + pb.value = 0; +#if UNITY_5_3_OR_NEWER + AsyncOperation op = SceneManager.LoadSceneAsync(sceneName); +#else + AsyncOperation op = Application.LoadLevelAsync(sceneName); +#endif + float startTime = Time.time; + while (!op.isDone || pb.value != 100) + { + int value = (int)((Time.time - startTime) * 100f / 3f); + if (value > 100) + value = 100; + pb.value = value; + yield return null; + } + + GRoot.inst.RemoveChild(_cutSceneView); + GRoot.inst.AddChild(_mainView); + } +} diff --git a/Assets/Examples/Editor/BuildAssetBundles.cs b/Assets/Examples/Editor/BuildAssetBundles.cs index 2cef9b1f..2a59e3c3 100644 --- a/Assets/Examples/Editor/BuildAssetBundles.cs +++ b/Assets/Examples/Editor/BuildAssetBundles.cs @@ -1,38 +1,38 @@ -using UnityEngine; -using UnityEditor; -using System.IO; - -public class BuildAssetBundles -{ - [MenuItem("Window/Build FairyGUI Example Bundles")] - public static void Builde() - { -#if (UNITY_5 || UNITY_5_3_OR_NEWER) - for (int i = 0; i < 10; i++) - { - AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i" + i + ".png").assetBundleName = "fairygui-examples/i" + i + ".ab"; - } - - AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes").assetBundleName = "fairygui-examples/bundleusage.ab"; - AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png").assetBundleName = "fairygui-examples/bundleusage.ab"; - - BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.None, BuildTarget.Android); -#else - for (int i = 0; i < 10; i++) - { - Object obj = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i"+i+".png", typeof(Object)); - BuildPipeline.BuildAssetBundle(obj, null, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/i" + i + ".ab"), - BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android); - } - - Object mainAsset = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes", typeof(Object)); - Object[] assets = new Object[] { - AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png", typeof(Object)) - }; - - BuildPipeline.BuildAssetBundle(mainAsset, assets, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/bundleusage.ab"), - BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android); - AssetDatabase.Refresh(); -#endif - } +using UnityEngine; +using UnityEditor; +using System.IO; + +public class BuildAssetBundles +{ + [MenuItem("Window/Build FairyGUI Example Bundles")] + public static void Builde() + { +#if (UNITY_5 || UNITY_5_3_OR_NEWER) + for (int i = 0; i < 10; i++) + { + AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i" + i + ".png").assetBundleName = "fairygui-examples/i" + i + ".ab"; + } + + AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes").assetBundleName = "fairygui-examples/bundleusage.ab"; + AssetImporter.GetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png").assetBundleName = "fairygui-examples/bundleusage.ab"; + + BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, BuildAssetBundleOptions.None, BuildTarget.Android); +#else + for (int i = 0; i < 10; i++) + { + Object obj = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/Icons/i"+i+".png", typeof(Object)); + BuildPipeline.BuildAssetBundle(obj, null, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/i" + i + ".ab"), + BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android); + } + + Object mainAsset = AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_fui.bytes", typeof(Object)); + Object[] assets = new Object[] { + AssetDatabase.LoadAssetAtPath("Assets/FairyGUI/Examples/Resources/UI/BundleUsage_atlas0.png", typeof(Object)) + }; + + BuildPipeline.BuildAssetBundle(mainAsset, assets, Path.Combine(Application.streamingAssetsPath, "fairygui-examples/bundleusage.ab"), + BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android); + AssetDatabase.Refresh(); +#endif + } } \ No newline at end of file diff --git a/Assets/Examples/EmitNumbers/EmitComponent.cs b/Assets/Examples/EmitNumbers/EmitComponent.cs index 0d54701a..2910a789 100644 --- a/Assets/Examples/EmitNumbers/EmitComponent.cs +++ b/Assets/Examples/EmitNumbers/EmitComponent.cs @@ -1,94 +1,94 @@ -using UnityEngine; -using FairyGUI; - -public class EmitComponent : GComponent -{ - GLoader _symbolLoader; - GTextField _numberText; - Transform _owner; - - const float OFFSET_ADDITION = 2.2f; - static Vector2 JITTER_FACTOR = new Vector2(80, 80); - - public EmitComponent() - { - this.touchable = false; - - _symbolLoader = new GLoader(); - _symbolLoader.autoSize = true; - AddChild(_symbolLoader); - - _numberText = new GTextField(); - _numberText.autoSize = AutoSizeType.Both; - - AddChild(_numberText); - } - - public void SetHurt(Transform owner, int type, long hurt, bool critical) - { - _owner = owner; - - TextFormat tf = _numberText.textFormat; - if (type == 0) - tf.font = EmitManager.inst.hurtFont1; - else - tf.font = EmitManager.inst.hurtFont2; - _numberText.textFormat = tf; - _numberText.text = "-" + hurt; - - if (critical) - _symbolLoader.url = EmitManager.inst.criticalSign; - else - _symbolLoader.url = ""; - - UpdateLayout(); - - this.alpha = 1; - UpdatePosition(Vector2.zero); - Vector2 rnd = Vector2.Scale(UnityEngine.Random.insideUnitCircle, JITTER_FACTOR); - int toX = (int)rnd.x * 2; - int toY = (int)rnd.y * 2; - - EmitManager.inst.view.AddChild(this); - GTween.To(Vector2.zero, new Vector2(toX, toY), 1f).SetTarget(this) - .OnUpdate((GTweener tweener) => { this.UpdatePosition(tweener.value.vec2); }).OnComplete(this.OnCompleted); - this.TweenFade(0, 0.5f).SetDelay(0.5f); - } - - void UpdateLayout() - { - this.SetSize(_symbolLoader.width + _numberText.width, Mathf.Max(_symbolLoader.height, _numberText.height)); - _numberText.SetXY(_symbolLoader.width > 0 ? (_symbolLoader.width + 2) : 0, - (this.height - _numberText.height) / 2); - _symbolLoader.y = (this.height - _symbolLoader.height) / 2; - } - - void UpdatePosition(Vector2 pos) - { - Vector3 ownerPos = _owner.position; - ownerPos.y += OFFSET_ADDITION; - Vector3 screenPos = Camera.main.WorldToScreenPoint(ownerPos); - screenPos.y = Screen.height - screenPos.y; //convert to Stage coordinates system - - Vector3 pt = GRoot.inst.GlobalToLocal(screenPos); - this.SetXY(Mathf.RoundToInt(pt.x + pos.x - this.actualWidth / 2), Mathf.RoundToInt(pt.y + pos.y - this.height)); - } - - void OnCompleted() - { - _owner = null; - EmitManager.inst.view.RemoveChild(this); - EmitManager.inst.ReturnComponent(this); - } - - public void Cancel() - { - _owner = null; - if (this.parent != null) - { - GTween.Kill(this); - EmitManager.inst.view.RemoveChild(this); - } - EmitManager.inst.ReturnComponent(this); - } +using UnityEngine; +using FairyGUI; + +public class EmitComponent : GComponent +{ + GLoader _symbolLoader; + GTextField _numberText; + Transform _owner; + + const float OFFSET_ADDITION = 2.2f; + static Vector2 JITTER_FACTOR = new Vector2(80, 80); + + public EmitComponent() + { + this.touchable = false; + + _symbolLoader = new GLoader(); + _symbolLoader.autoSize = true; + AddChild(_symbolLoader); + + _numberText = new GTextField(); + _numberText.autoSize = AutoSizeType.Both; + + AddChild(_numberText); + } + + public void SetHurt(Transform owner, int type, long hurt, bool critical) + { + _owner = owner; + + TextFormat tf = _numberText.textFormat; + if (type == 0) + tf.font = EmitManager.inst.hurtFont1; + else + tf.font = EmitManager.inst.hurtFont2; + _numberText.textFormat = tf; + _numberText.text = "-" + hurt; + + if (critical) + _symbolLoader.url = EmitManager.inst.criticalSign; + else + _symbolLoader.url = ""; + + UpdateLayout(); + + this.alpha = 1; + UpdatePosition(Vector2.zero); + Vector2 rnd = Vector2.Scale(UnityEngine.Random.insideUnitCircle, JITTER_FACTOR); + int toX = (int)rnd.x * 2; + int toY = (int)rnd.y * 2; + + EmitManager.inst.view.AddChild(this); + GTween.To(Vector2.zero, new Vector2(toX, toY), 1f).SetTarget(this) + .OnUpdate((GTweener tweener) => { this.UpdatePosition(tweener.value.vec2); }).OnComplete(this.OnCompleted); + this.TweenFade(0, 0.5f).SetDelay(0.5f); + } + + void UpdateLayout() + { + this.SetSize(_symbolLoader.width + _numberText.width, Mathf.Max(_symbolLoader.height, _numberText.height)); + _numberText.SetXY(_symbolLoader.width > 0 ? (_symbolLoader.width + 2) : 0, + (this.height - _numberText.height) / 2); + _symbolLoader.y = (this.height - _symbolLoader.height) / 2; + } + + void UpdatePosition(Vector2 pos) + { + Vector3 ownerPos = _owner.position; + ownerPos.y += OFFSET_ADDITION; + Vector3 screenPos = Camera.main.WorldToScreenPoint(ownerPos); + screenPos.y = Screen.height - screenPos.y; //convert to Stage coordinates system + + Vector3 pt = GRoot.inst.GlobalToLocal(screenPos); + this.SetXY(Mathf.RoundToInt(pt.x + pos.x - this.actualWidth / 2), Mathf.RoundToInt(pt.y + pos.y - this.height)); + } + + void OnCompleted() + { + _owner = null; + EmitManager.inst.view.RemoveChild(this); + EmitManager.inst.ReturnComponent(this); + } + + public void Cancel() + { + _owner = null; + if (this.parent != null) + { + GTween.Kill(this); + EmitManager.inst.view.RemoveChild(this); + } + EmitManager.inst.ReturnComponent(this); + } } \ No newline at end of file diff --git a/Assets/Examples/EmitNumbers/EmitManager.cs b/Assets/Examples/EmitNumbers/EmitManager.cs index 19ea95e0..ef12b53e 100644 --- a/Assets/Examples/EmitNumbers/EmitManager.cs +++ b/Assets/Examples/EmitNumbers/EmitManager.cs @@ -1,50 +1,50 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI; - -public class EmitManager -{ - static EmitManager _instance; - public static EmitManager inst - { - get - { - if (_instance == null) - _instance = new EmitManager(); - return _instance; - } - } - - public string hurtFont1; - public string hurtFont2; - public string criticalSign; - - public GComponent view { get; private set; } - - private readonly Stack _componentPool = new Stack(); - - public EmitManager() - { - hurtFont1 = "ui://EmitNumbers/number1"; - hurtFont2 = "ui://EmitNumbers/number2"; - criticalSign = "ui://EmitNumbers/critical"; - - view = new GComponent(); - GRoot.inst.AddChild(view); - } - - public void Emit(Transform owner, int type, long hurt, bool critical) - { - EmitComponent ec; - if (_componentPool.Count > 0) - ec = _componentPool.Pop(); - else - ec = new EmitComponent(); - ec.SetHurt(owner, type, hurt, critical); - } - - public void ReturnComponent(EmitComponent com) - { - _componentPool.Push(com); - } +using System.Collections.Generic; +using UnityEngine; +using FairyGUI; + +public class EmitManager +{ + static EmitManager _instance; + public static EmitManager inst + { + get + { + if (_instance == null) + _instance = new EmitManager(); + return _instance; + } + } + + public string hurtFont1; + public string hurtFont2; + public string criticalSign; + + public GComponent view { get; private set; } + + private readonly Stack _componentPool = new Stack(); + + public EmitManager() + { + hurtFont1 = "ui://EmitNumbers/number1"; + hurtFont2 = "ui://EmitNumbers/number2"; + criticalSign = "ui://EmitNumbers/critical"; + + view = new GComponent(); + GRoot.inst.AddChild(view); + } + + public void Emit(Transform owner, int type, long hurt, bool critical) + { + EmitComponent ec; + if (_componentPool.Count > 0) + ec = _componentPool.Pop(); + else + ec = new EmitComponent(); + ec.SetHurt(owner, type, hurt, critical); + } + + public void ReturnComponent(EmitComponent com) + { + _componentPool.Push(com); + } } \ No newline at end of file diff --git a/Assets/Examples/EmitNumbers/EmitNumbersMain.cs b/Assets/Examples/EmitNumbers/EmitNumbersMain.cs index af07bcac..f1cdcdf3 100644 --- a/Assets/Examples/EmitNumbers/EmitNumbersMain.cs +++ b/Assets/Examples/EmitNumbers/EmitNumbersMain.cs @@ -1,44 +1,44 @@ -using System.Collections; -using UnityEngine; -using FairyGUI; - -public class EmitNumbersMain : MonoBehaviour -{ - Transform _npc1; - Transform _npc2; - bool _finished; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _npc1 = GameObject.Find("npc1").transform; - _npc2 = GameObject.Find("npc2").transform; - - StartCoroutine(RunTest()); - } - - void OnDisable() - { - _finished = true; - } - - IEnumerator RunTest() - { - while (!_finished) - { - EmitManager.inst.Emit(_npc1, 0, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5); - EmitManager.inst.Emit(_npc2, 1, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5); - yield return new WaitForSeconds(0.3f); - } - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using System.Collections; +using UnityEngine; +using FairyGUI; + +public class EmitNumbersMain : MonoBehaviour +{ + Transform _npc1; + Transform _npc2; + bool _finished; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _npc1 = GameObject.Find("npc1").transform; + _npc2 = GameObject.Find("npc2").transform; + + StartCoroutine(RunTest()); + } + + void OnDisable() + { + _finished = true; + } + + IEnumerator RunTest() + { + while (!_finished) + { + EmitManager.inst.Emit(_npc1, 0, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5); + EmitManager.inst.Emit(_npc2, 1, UnityEngine.Random.Range(100, 100000), UnityEngine.Random.Range(0, 10) == 5); + yield return new WaitForSeconds(0.3f); + } + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Emoji/EmojiMain.cs b/Assets/Examples/Emoji/EmojiMain.cs index b26160c5..94897138 100644 --- a/Assets/Examples/Emoji/EmojiMain.cs +++ b/Assets/Examples/Emoji/EmojiMain.cs @@ -1,196 +1,196 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI; - -public class EmojiMain : MonoBehaviour -{ - GComponent _mainView; - GList _list; - GTextInput _input1; - GTextInput _input2; - GComponent _emojiSelectUI1; - GComponent _emojiSelectUI2; - - class Message - { - public string sender; - public string senderIcon; - public string msg; - public bool fromMe; - } - List _messages; - - Dictionary _emojies; - - void Awake() - { - UIPackage.AddPackage("UI/Emoji"); - - UIConfig.verticalScrollBar = "ui://Emoji/ScrollBar_VT"; - UIConfig.defaultScrollBarDisplay = ScrollBarDisplayType.Auto; - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _messages = new List(); - - _mainView = this.GetComponent().ui; - - _list = _mainView.GetChild("list").asList; - _list.SetVirtual(); - _list.itemProvider = GetListItemResource; - _list.itemRenderer = RenderListItem; - - _input1 = _mainView.GetChild("input1").asTextInput; - _input1.onKeyDown.Add(__inputKeyDown1); - - _input2 = _mainView.GetChild("input2").asTextInput; - _input2.onKeyDown.Add(__inputKeyDown2); - - //作为demo,这里只添加了部分表情素材 - _emojies = new Dictionary(); - for (uint i = 0x1f600; i < 0x1f637; i++) - { - string url = UIPackage.GetItemURL("Emoji", Convert.ToString(i, 16)); - if (url != null) - _emojies.Add(i, new Emoji(url)); - } - _input2.emojies = _emojies; - - _mainView.GetChild("btnSend1").onClick.Add(__clickSendBtn1); - _mainView.GetChild("btnSend2").onClick.Add(__clickSendBtn2); - - _mainView.GetChild("btnEmoji1").onClick.Add(__clickEmojiBtn1); - _mainView.GetChild("btnEmoji2").onClick.Add(__clickEmojiBtn2); - - _emojiSelectUI1 = UIPackage.CreateObject("Emoji", "EmojiSelectUI").asCom; - _emojiSelectUI1.fairyBatching = true; - _emojiSelectUI1.GetChild("list").asList.onClickItem.Add(__clickEmoji1); - - _emojiSelectUI2 = UIPackage.CreateObject("Emoji", "EmojiSelectUI_ios").asCom; - _emojiSelectUI2.fairyBatching = true; - _emojiSelectUI2.GetChild("list").asList.onClickItem.Add(__clickEmoji2); - } - - void AddMsg(string sender, string senderIcon, string msg, bool fromMe) - { - bool isScrollBottom = _list.scrollPane.isBottomMost; - - Message newMessage = new Message(); - newMessage.sender = sender; - newMessage.senderIcon = senderIcon; - newMessage.msg = msg; - newMessage.fromMe = fromMe; - _messages.Add(newMessage); - - if (newMessage.fromMe) - { - if (_messages.Count == 1 || UnityEngine.Random.Range(0f, 1f) < 0.5f) - { - Message replyMessage = new Message(); - replyMessage.sender = "FairyGUI"; - replyMessage.senderIcon = "r1"; - replyMessage.msg = "Today is a good day. \U0001f600"; - replyMessage.fromMe = false; - _messages.Add(replyMessage); - } - } - - if (_messages.Count > 100) - _messages.RemoveRange(0, _messages.Count - 100); - - _list.numItems = _messages.Count; - - if (isScrollBottom) - _list.scrollPane.ScrollBottom(); - } - - string GetListItemResource(int index) - { - Message msg = _messages[index]; - if (msg.fromMe) - return "ui://Emoji/chatRight"; - else - return "ui://Emoji/chatLeft"; - } - - void RenderListItem(int index, GObject obj) - { - GButton item = (GButton)obj; - Message msg = _messages[index]; - if (!msg.fromMe) - item.GetChild("name").text = msg.sender; - item.icon = UIPackage.GetItemURL("Emoji", msg.senderIcon); - - //Recaculate the text width - GRichTextField tf = item.GetChild("msg").asRichTextField; - tf.emojies = _emojies; - tf.text = EmojiParser.inst.Parse(msg.msg); - } - - void __clickSendBtn1(EventContext context) - { - string msg = _input1.text; - if (msg.Length == 0) - return; - - AddMsg("Unity", "r0", msg, true); - _input1.text = ""; - } - - void __clickSendBtn2(EventContext context) - { - string msg = _input2.text; - if (msg.Length == 0) - return; - - AddMsg("Unity", "r0", msg, true); - _input2.text = ""; - } - - void __clickEmojiBtn1(EventContext context) - { - GRoot.inst.ShowPopup(_emojiSelectUI1, (GObject)context.sender, PopupDirection.Up); - } - - void __clickEmojiBtn2(EventContext context) - { - GRoot.inst.ShowPopup(_emojiSelectUI2, (GObject)context.sender, PopupDirection.Up); - } - - void __clickEmoji1(EventContext context) - { - GButton item = (GButton)context.data; - _input1.ReplaceSelection("[:" + item.text + "]"); - } - - void __clickEmoji2(EventContext context) - { - GButton item = (GButton)context.data; - _input2.ReplaceSelection(Char.ConvertFromUtf32(Convert.ToInt32(UIPackage.GetItemByURL(item.icon).name, 16))); - } - - void __inputKeyDown1(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Return) - _mainView.GetChild("btnSend1").onClick.Call(); - } - - void __inputKeyDown2(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Return) - _mainView.GetChild("btnSend2").onClick.Call(); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI; + +public class EmojiMain : MonoBehaviour +{ + GComponent _mainView; + GList _list; + GTextInput _input1; + GTextInput _input2; + GComponent _emojiSelectUI1; + GComponent _emojiSelectUI2; + + class Message + { + public string sender; + public string senderIcon; + public string msg; + public bool fromMe; + } + List _messages; + + Dictionary _emojies; + + void Awake() + { + UIPackage.AddPackage("UI/Emoji"); + + UIConfig.verticalScrollBar = "ui://Emoji/ScrollBar_VT"; + UIConfig.defaultScrollBarDisplay = ScrollBarDisplayType.Auto; + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _messages = new List(); + + _mainView = this.GetComponent().ui; + + _list = _mainView.GetChild("list").asList; + _list.SetVirtual(); + _list.itemProvider = GetListItemResource; + _list.itemRenderer = RenderListItem; + + _input1 = _mainView.GetChild("input1").asTextInput; + _input1.onKeyDown.Add(__inputKeyDown1); + + _input2 = _mainView.GetChild("input2").asTextInput; + _input2.onKeyDown.Add(__inputKeyDown2); + + //作为demo,这里只添加了部分表情素材 + _emojies = new Dictionary(); + for (uint i = 0x1f600; i < 0x1f637; i++) + { + string url = UIPackage.GetItemURL("Emoji", Convert.ToString(i, 16)); + if (url != null) + _emojies.Add(i, new Emoji(url)); + } + _input2.emojies = _emojies; + + _mainView.GetChild("btnSend1").onClick.Add(__clickSendBtn1); + _mainView.GetChild("btnSend2").onClick.Add(__clickSendBtn2); + + _mainView.GetChild("btnEmoji1").onClick.Add(__clickEmojiBtn1); + _mainView.GetChild("btnEmoji2").onClick.Add(__clickEmojiBtn2); + + _emojiSelectUI1 = UIPackage.CreateObject("Emoji", "EmojiSelectUI").asCom; + _emojiSelectUI1.fairyBatching = true; + _emojiSelectUI1.GetChild("list").asList.onClickItem.Add(__clickEmoji1); + + _emojiSelectUI2 = UIPackage.CreateObject("Emoji", "EmojiSelectUI_ios").asCom; + _emojiSelectUI2.fairyBatching = true; + _emojiSelectUI2.GetChild("list").asList.onClickItem.Add(__clickEmoji2); + } + + void AddMsg(string sender, string senderIcon, string msg, bool fromMe) + { + bool isScrollBottom = _list.scrollPane.isBottomMost; + + Message newMessage = new Message(); + newMessage.sender = sender; + newMessage.senderIcon = senderIcon; + newMessage.msg = msg; + newMessage.fromMe = fromMe; + _messages.Add(newMessage); + + if (newMessage.fromMe) + { + if (_messages.Count == 1 || UnityEngine.Random.Range(0f, 1f) < 0.5f) + { + Message replyMessage = new Message(); + replyMessage.sender = "FairyGUI"; + replyMessage.senderIcon = "r1"; + replyMessage.msg = "Today is a good day. \U0001f600"; + replyMessage.fromMe = false; + _messages.Add(replyMessage); + } + } + + if (_messages.Count > 100) + _messages.RemoveRange(0, _messages.Count - 100); + + _list.numItems = _messages.Count; + + if (isScrollBottom) + _list.scrollPane.ScrollBottom(); + } + + string GetListItemResource(int index) + { + Message msg = _messages[index]; + if (msg.fromMe) + return "ui://Emoji/chatRight"; + else + return "ui://Emoji/chatLeft"; + } + + void RenderListItem(int index, GObject obj) + { + GButton item = (GButton)obj; + Message msg = _messages[index]; + if (!msg.fromMe) + item.GetChild("name").text = msg.sender; + item.icon = UIPackage.GetItemURL("Emoji", msg.senderIcon); + + //Recaculate the text width + GRichTextField tf = item.GetChild("msg").asRichTextField; + tf.emojies = _emojies; + tf.text = EmojiParser.inst.Parse(msg.msg); + } + + void __clickSendBtn1(EventContext context) + { + string msg = _input1.text; + if (msg.Length == 0) + return; + + AddMsg("Unity", "r0", msg, true); + _input1.text = ""; + } + + void __clickSendBtn2(EventContext context) + { + string msg = _input2.text; + if (msg.Length == 0) + return; + + AddMsg("Unity", "r0", msg, true); + _input2.text = ""; + } + + void __clickEmojiBtn1(EventContext context) + { + GRoot.inst.ShowPopup(_emojiSelectUI1, (GObject)context.sender, PopupDirection.Up); + } + + void __clickEmojiBtn2(EventContext context) + { + GRoot.inst.ShowPopup(_emojiSelectUI2, (GObject)context.sender, PopupDirection.Up); + } + + void __clickEmoji1(EventContext context) + { + GButton item = (GButton)context.data; + _input1.ReplaceSelection("[:" + item.text + "]"); + } + + void __clickEmoji2(EventContext context) + { + GButton item = (GButton)context.data; + _input2.ReplaceSelection(Char.ConvertFromUtf32(Convert.ToInt32(UIPackage.GetItemByURL(item.icon).name, 16))); + } + + void __inputKeyDown1(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Return) + _mainView.GetChild("btnSend1").onClick.Call(); + } + + void __inputKeyDown2(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Return) + _mainView.GetChild("btnSend2").onClick.Call(); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Emoji/EmojiParser.cs b/Assets/Examples/Emoji/EmojiParser.cs index 64a672e6..93a4e809 100644 --- a/Assets/Examples/Emoji/EmojiParser.cs +++ b/Assets/Examples/Emoji/EmojiParser.cs @@ -1,31 +1,31 @@ -using FairyGUI; -using FairyGUI.Utils; - -public class EmojiParser : UBBParser -{ - static EmojiParser _instance; - public new static EmojiParser inst - { - get - { - if (_instance == null) - _instance = new EmojiParser(); - return _instance; - } - } - - private static string[] TAGS = new string[] - { "88","am","bs","bz","ch","cool","dhq","dn","fd","gz","han","hx","hxiao","hxiu" }; - public EmojiParser () - { - foreach (string ss in TAGS) - { - this.handlers[":"+ss] = OnTag_Emoji; - } - } - - string OnTag_Emoji(string tagName, bool end, string attr) - { - return ""; - } +using FairyGUI; +using FairyGUI.Utils; + +public class EmojiParser : UBBParser +{ + static EmojiParser _instance; + public new static EmojiParser inst + { + get + { + if (_instance == null) + _instance = new EmojiParser(); + return _instance; + } + } + + private static string[] TAGS = new string[] + { "88","am","bs","bz","ch","cool","dhq","dn","fd","gz","han","hx","hxiao","hxiu" }; + public EmojiParser () + { + foreach (string ss in TAGS) + { + this.handlers[":"+ss] = OnTag_Emoji; + } + } + + string OnTag_Emoji(string tagName, bool end, string attr) + { + return ""; + } } \ No newline at end of file diff --git a/Assets/Examples/Extension/ExtensionMain.cs b/Assets/Examples/Extension/ExtensionMain.cs index 8a5156f5..231c54b1 100644 --- a/Assets/Examples/Extension/ExtensionMain.cs +++ b/Assets/Examples/Extension/ExtensionMain.cs @@ -1,55 +1,55 @@ -using UnityEngine; -using FairyGUI; - -public class ExtensionMain : MonoBehaviour -{ - GComponent _mainView; - GList _list; - - void Awake() - { - UIPackage.AddPackage("UI/Extension"); - UIObjectFactory.SetPackageItemExtension("ui://Extension/mailItem", typeof(MailItem)); - - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _list = _mainView.GetChild("mailList").asList; - for (int i = 0; i < 10; i++) - { - MailItem item = (MailItem)_list.AddItemFromPool(); - item.setFetched(i % 3 == 0); - item.setRead(i % 2 == 0); - item.setTime("5 Nov 2015 16:24:33"); - item.title = "Mail title here"; - } - - _list.EnsureBoundsCorrect(); - float delay = 0f; - for (int i = 0; i < 10; i++) - { - MailItem item = (MailItem)_list.GetChildAt(i); - if (_list.IsChildInView(item)) - { - item.PlayEffect(delay); - delay += 0.2f; - } - else - break; - } - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class ExtensionMain : MonoBehaviour +{ + GComponent _mainView; + GList _list; + + void Awake() + { + UIPackage.AddPackage("UI/Extension"); + UIObjectFactory.SetPackageItemExtension("ui://Extension/mailItem", typeof(MailItem)); + + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _list = _mainView.GetChild("mailList").asList; + for (int i = 0; i < 10; i++) + { + MailItem item = (MailItem)_list.AddItemFromPool(); + item.setFetched(i % 3 == 0); + item.setRead(i % 2 == 0); + item.setTime("5 Nov 2015 16:24:33"); + item.title = "Mail title here"; + } + + _list.EnsureBoundsCorrect(); + float delay = 0f; + for (int i = 0; i < 10; i++) + { + MailItem item = (MailItem)_list.GetChildAt(i); + if (_list.IsChildInView(item)) + { + item.PlayEffect(delay); + delay += 0.2f; + } + else + break; + } + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Extension/MailItem.cs b/Assets/Examples/Extension/MailItem.cs index dd95a6b7..a67c34c4 100644 --- a/Assets/Examples/Extension/MailItem.cs +++ b/Assets/Examples/Extension/MailItem.cs @@ -1,41 +1,41 @@ -using UnityEngine; -using FairyGUI; - -public class MailItem : GButton -{ - GTextField _timeText; - Controller _readController; - Controller _fetchController; - Transition _trans; - - public override void ConstructFromXML(FairyGUI.Utils.XML cxml) - { - base.ConstructFromXML(cxml); - - _timeText = this.GetChild("timeText").asTextField; - _readController = this.GetController("IsRead"); - _fetchController = this.GetController("c1"); - _trans = this.GetTransition("t0"); - } - - public void setTime(string value) - { - _timeText.text = value; - } - - public void setRead(bool value) - { - _readController.selectedIndex = value ? 1 : 0; - } - - public void setFetched(bool value) - { - _fetchController.selectedIndex = value ? 1 : 0; - } - - public void PlayEffect(float delay) - { - this.visible = false; - _trans.Play(1, delay, null); - } -} +using UnityEngine; +using FairyGUI; + +public class MailItem : GButton +{ + GTextField _timeText; + Controller _readController; + Controller _fetchController; + Transition _trans; + + public override void ConstructFromXML(FairyGUI.Utils.XML cxml) + { + base.ConstructFromXML(cxml); + + _timeText = this.GetChild("timeText").asTextField; + _readController = this.GetController("IsRead"); + _fetchController = this.GetController("c1"); + _trans = this.GetTransition("t0"); + } + + public void setTime(string value) + { + _timeText.text = value; + } + + public void setRead(bool value) + { + _readController.selectedIndex = value ? 1 : 0; + } + + public void setFetched(bool value) + { + _fetchController.selectedIndex = value ? 1 : 0; + } + + public void PlayEffect(float delay) + { + this.visible = false; + _trans.Play(1, delay, null); + } +} diff --git a/Assets/Examples/Filter/FilterMain.cs b/Assets/Examples/Filter/FilterMain.cs index 3aa27bb5..16f101a3 100644 --- a/Assets/Examples/Filter/FilterMain.cs +++ b/Assets/Examples/Filter/FilterMain.cs @@ -1,78 +1,78 @@ -using UnityEngine; -using FairyGUI; - -public class FilterMain : MonoBehaviour -{ - GComponent _mainView; - GSlider _s0; - GSlider _s1; - GSlider _s2; - GSlider _s3; - GSlider _s4; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - UIPackage.AddPackage("UI/Filter"); - } - - void Start() - { - _mainView = this.GetComponent().ui; - - BlurFilter blurFilter = new BlurFilter(); - blurFilter.blurSize = 2; - _mainView.GetChild("n21").filter = blurFilter; - - _s0 = _mainView.GetChild("s0").asSlider; - _s1 = _mainView.GetChild("s1").asSlider; - _s2 = _mainView.GetChild("s2").asSlider; - _s3 = _mainView.GetChild("s3").asSlider; - _s4 = _mainView.GetChild("s4").asSlider; - - _s0.value = 100; - _s1.value = 100; - _s2.value = 100; - _s3.value = 200; - _s4.value = 20; - - _s0.onChanged.Add(__sliderChanged); - _s1.onChanged.Add(__sliderChanged); - _s2.onChanged.Add(__sliderChanged); - _s3.onChanged.Add(__sliderChanged); - _s4.onChanged.Add(__sliderChanged); - } - - void __sliderChanged(EventContext context) - { - int cnt = _mainView.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = _mainView.GetChildAt(i); - if (obj.filter is ColorFilter) - { - ColorFilter filter = (ColorFilter)obj.filter; - filter.Reset(); - filter.AdjustBrightness((float)(_s0.value - 100) / 100f); - filter.AdjustContrast((float)(_s1.value - 100) / 100f); - filter.AdjustSaturation((float)(_s2.value - 100) / 100f); - filter.AdjustHue((float)(_s3.value - 100) / 100f); - } - else if (obj.filter is BlurFilter) - { - BlurFilter filter = (BlurFilter)obj.filter; - filter.blurSize = (float)_s4.value / 100; - } - } - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class FilterMain : MonoBehaviour +{ + GComponent _mainView; + GSlider _s0; + GSlider _s1; + GSlider _s2; + GSlider _s3; + GSlider _s4; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + UIPackage.AddPackage("UI/Filter"); + } + + void Start() + { + _mainView = this.GetComponent().ui; + + BlurFilter blurFilter = new BlurFilter(); + blurFilter.blurSize = 2; + _mainView.GetChild("n21").filter = blurFilter; + + _s0 = _mainView.GetChild("s0").asSlider; + _s1 = _mainView.GetChild("s1").asSlider; + _s2 = _mainView.GetChild("s2").asSlider; + _s3 = _mainView.GetChild("s3").asSlider; + _s4 = _mainView.GetChild("s4").asSlider; + + _s0.value = 100; + _s1.value = 100; + _s2.value = 100; + _s3.value = 200; + _s4.value = 20; + + _s0.onChanged.Add(__sliderChanged); + _s1.onChanged.Add(__sliderChanged); + _s2.onChanged.Add(__sliderChanged); + _s3.onChanged.Add(__sliderChanged); + _s4.onChanged.Add(__sliderChanged); + } + + void __sliderChanged(EventContext context) + { + int cnt = _mainView.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = _mainView.GetChildAt(i); + if (obj.filter is ColorFilter) + { + ColorFilter filter = (ColorFilter)obj.filter; + filter.Reset(); + filter.AdjustBrightness((float)(_s0.value - 100) / 100f); + filter.AdjustContrast((float)(_s1.value - 100) / 100f); + filter.AdjustSaturation((float)(_s2.value - 100) / 100f); + filter.AdjustHue((float)(_s3.value - 100) / 100f); + } + else if (obj.filter is BlurFilter) + { + BlurFilter filter = (BlurFilter)obj.filter; + filter.blurSize = (float)_s4.value / 100; + } + } + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Gesture/GestureMain.cs b/Assets/Examples/Gesture/GestureMain.cs index 565071db..85015b72 100644 --- a/Assets/Examples/Gesture/GestureMain.cs +++ b/Assets/Examples/Gesture/GestureMain.cs @@ -1,115 +1,115 @@ -using UnityEngine; -using FairyGUI; - -public class GestureMain : MonoBehaviour -{ - GComponent _mainView; - Transform _ball; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - UIPackage.AddPackage("UI/Gesture"); - } - - void Start() - { - _mainView = this.GetComponent().ui; - GObject holder = _mainView.GetChild("holder"); - - _ball = GameObject.Find("Globe").transform; - - SwipeGesture gesture1 = new SwipeGesture(holder); - gesture1.onMove.Add(OnSwipeMove); - gesture1.onEnd.Add(OnSwipeEnd); - - LongPressGesture gesture2 = new LongPressGesture(holder); - gesture2.once = false; - gesture2.onAction.Add(OnHold); - - PinchGesture gesture3 = new PinchGesture(holder); - gesture3.onAction.Add(OnPinch); - - RotationGesture gesture4 = new RotationGesture(holder); - gesture4.onAction.Add(OnRotate); - } - - void OnSwipeMove(EventContext context) - { - SwipeGesture gesture = (SwipeGesture)context.sender; - Vector3 v = new Vector3(); - if (Mathf.Abs(gesture.delta.x) > Mathf.Abs(gesture.delta.y)) - { - v.y = -Mathf.Round(gesture.delta.x); - if (Mathf.Abs(v.y) < 2) //消除手抖的影响 - return; - } - else - { - v.x = -Mathf.Round(gesture.delta.y); - if (Mathf.Abs(v.x) < 2) - return; - } - _ball.Rotate(v, Space.World); - } - - void OnSwipeEnd(EventContext context) - { - SwipeGesture gesture = (SwipeGesture)context.sender; - Vector3 v = new Vector3(); - if (Mathf.Abs(gesture.velocity.x) > Mathf.Abs(gesture.velocity.y)) - { - v.y = -Mathf.Round(Mathf.Sign(gesture.velocity.x) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.x))); - if (Mathf.Abs(v.y) < 2) - return; - } - else - { - v.x = -Mathf.Round(Mathf.Sign(gesture.velocity.y) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.y))); - if (Mathf.Abs(v.x) < 2) - return; - } - - GTween.To(v, Vector3.zero, 0.3f).SetTarget(_ball).OnUpdate( - (GTweener tweener) => - { - _ball.Rotate(tweener.deltaValue.vec3, Space.World); - }); - } - - void OnHold(EventContext context) - { - GTween.Shake(_ball.transform.localPosition, 0.05f, 0.5f).SetTarget(_ball).OnUpdate( - (GTweener tweener) => - { - _ball.transform.localPosition = new Vector3(tweener.value.x, tweener.value.y, _ball.transform.localPosition.z); - }); - } - - void OnPinch(EventContext context) - { - GTween.Kill(_ball); - - PinchGesture gesture = (PinchGesture)context.sender; - float newValue = Mathf.Clamp(_ball.localScale.x + gesture.delta, 0.3f, 2); - _ball.localScale = new Vector3(newValue, newValue, newValue); - } - - void OnRotate(EventContext context) - { - GTween.Kill(_ball); - - RotationGesture gesture = (RotationGesture)context.sender; - _ball.Rotate(Vector3.forward, -gesture.delta, Space.World); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class GestureMain : MonoBehaviour +{ + GComponent _mainView; + Transform _ball; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + UIPackage.AddPackage("UI/Gesture"); + } + + void Start() + { + _mainView = this.GetComponent().ui; + GObject holder = _mainView.GetChild("holder"); + + _ball = GameObject.Find("Globe").transform; + + SwipeGesture gesture1 = new SwipeGesture(holder); + gesture1.onMove.Add(OnSwipeMove); + gesture1.onEnd.Add(OnSwipeEnd); + + LongPressGesture gesture2 = new LongPressGesture(holder); + gesture2.once = false; + gesture2.onAction.Add(OnHold); + + PinchGesture gesture3 = new PinchGesture(holder); + gesture3.onAction.Add(OnPinch); + + RotationGesture gesture4 = new RotationGesture(holder); + gesture4.onAction.Add(OnRotate); + } + + void OnSwipeMove(EventContext context) + { + SwipeGesture gesture = (SwipeGesture)context.sender; + Vector3 v = new Vector3(); + if (Mathf.Abs(gesture.delta.x) > Mathf.Abs(gesture.delta.y)) + { + v.y = -Mathf.Round(gesture.delta.x); + if (Mathf.Abs(v.y) < 2) //消除手抖的影响 + return; + } + else + { + v.x = -Mathf.Round(gesture.delta.y); + if (Mathf.Abs(v.x) < 2) + return; + } + _ball.Rotate(v, Space.World); + } + + void OnSwipeEnd(EventContext context) + { + SwipeGesture gesture = (SwipeGesture)context.sender; + Vector3 v = new Vector3(); + if (Mathf.Abs(gesture.velocity.x) > Mathf.Abs(gesture.velocity.y)) + { + v.y = -Mathf.Round(Mathf.Sign(gesture.velocity.x) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.x))); + if (Mathf.Abs(v.y) < 2) + return; + } + else + { + v.x = -Mathf.Round(Mathf.Sign(gesture.velocity.y) * Mathf.Sqrt(Mathf.Abs(gesture.velocity.y))); + if (Mathf.Abs(v.x) < 2) + return; + } + + GTween.To(v, Vector3.zero, 0.3f).SetTarget(_ball).OnUpdate( + (GTweener tweener) => + { + _ball.Rotate(tweener.deltaValue.vec3, Space.World); + }); + } + + void OnHold(EventContext context) + { + GTween.Shake(_ball.transform.localPosition, 0.05f, 0.5f).SetTarget(_ball).OnUpdate( + (GTweener tweener) => + { + _ball.transform.localPosition = new Vector3(tweener.value.x, tweener.value.y, _ball.transform.localPosition.z); + }); + } + + void OnPinch(EventContext context) + { + GTween.Kill(_ball); + + PinchGesture gesture = (PinchGesture)context.sender; + float newValue = Mathf.Clamp(_ball.localScale.x + gesture.delta, 0.3f, 2); + _ball.localScale = new Vector3(newValue, newValue, newValue); + } + + void OnRotate(EventContext context) + { + GTween.Kill(_ball); + + RotationGesture gesture = (RotationGesture)context.sender; + _ball.Rotate(Vector3.forward, -gesture.delta, Space.World); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Guide/GuideMain.cs b/Assets/Examples/Guide/GuideMain.cs index 140cbb6c..896236ff 100644 --- a/Assets/Examples/Guide/GuideMain.cs +++ b/Assets/Examples/Guide/GuideMain.cs @@ -1,44 +1,44 @@ -using UnityEngine; -using FairyGUI; - -public class GuideMain : MonoBehaviour -{ - GComponent _mainView; - GComponent _guideLayer; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _guideLayer = UIPackage.CreateObject("Guide", "GuideLayer").asCom; - _guideLayer.SetSize(GRoot.inst.width, GRoot.inst.height); - _guideLayer.AddRelation(GRoot.inst, RelationType.Size); - - GObject bagBtn = _mainView.GetChild("bagBtn"); - bagBtn.onClick.Add(() => - { - _guideLayer.RemoveFromParent(); - }); - - _mainView.GetChild("n2").onClick.Add(() => - { - GRoot.inst.AddChild(_guideLayer); //!!Before using TransformRect(or GlobalToLocal), the object must be added first - Rect rect = bagBtn.TransformRect(new Rect(0, 0, bagBtn.width, bagBtn.height), _guideLayer); - - GObject window = _guideLayer.GetChild("window"); - window.size = new Vector2((int)rect.size.x, (int)rect.size.y); - window.TweenMove(new Vector2((int)rect.position.x, (int)rect.position.y), 0.5f); - }); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class GuideMain : MonoBehaviour +{ + GComponent _mainView; + GComponent _guideLayer; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _guideLayer = UIPackage.CreateObject("Guide", "GuideLayer").asCom; + _guideLayer.SetSize(GRoot.inst.width, GRoot.inst.height); + _guideLayer.AddRelation(GRoot.inst, RelationType.Size); + + GObject bagBtn = _mainView.GetChild("bagBtn"); + bagBtn.onClick.Add(() => + { + _guideLayer.RemoveFromParent(); + }); + + _mainView.GetChild("n2").onClick.Add(() => + { + GRoot.inst.AddChild(_guideLayer); //!!Before using TransformRect(or GlobalToLocal), the object must be added first + Rect rect = bagBtn.TransformRect(new Rect(0, 0, bagBtn.width, bagBtn.height), _guideLayer); + + GObject window = _guideLayer.GetChild("window"); + window.size = new Vector2((int)rect.size.x, (int)rect.size.y); + window.TweenMove(new Vector2((int)rect.position.x, (int)rect.position.y), 0.5f); + }); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/HeadBar/HeadBarMain.cs b/Assets/Examples/HeadBar/HeadBarMain.cs index 69acbcba..47b1fc40 100644 --- a/Assets/Examples/HeadBar/HeadBarMain.cs +++ b/Assets/Examples/HeadBar/HeadBarMain.cs @@ -1,34 +1,34 @@ -using UnityEngine; -using FairyGUI; - -public class HeadBarMain : MonoBehaviour -{ - GComponent _mainView; - - void Start() - { - Application.targetFrameRate = 60; - - Stage.inst.onKeyDown.Add(OnKeyDown); - - Transform npc = GameObject.Find("npc1").transform; - UIPanel panel = npc.Find("HeadBar").GetComponent(); - panel.ui.GetChild("name").text = "Long [color=#FFFFFF]Long[/color][img]ui://HeadBar/cool[/img] Name"; - panel.ui.GetChild("blood").asProgress.value = 75; - panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/task"; - - npc = GameObject.Find("npc2").transform; - panel = npc.Find("HeadBar").GetComponent(); - panel.ui.GetChild("name").text = "Man2"; - panel.ui.GetChild("blood").asProgress.value = 25; - panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/fighting"; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class HeadBarMain : MonoBehaviour +{ + GComponent _mainView; + + void Start() + { + Application.targetFrameRate = 60; + + Stage.inst.onKeyDown.Add(OnKeyDown); + + Transform npc = GameObject.Find("npc1").transform; + UIPanel panel = npc.Find("HeadBar").GetComponent(); + panel.ui.GetChild("name").text = "Long [color=#FFFFFF]Long[/color][img]ui://HeadBar/cool[/img] Name"; + panel.ui.GetChild("blood").asProgress.value = 75; + panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/task"; + + npc = GameObject.Find("npc2").transform; + panel = npc.Find("HeadBar").GetComponent(); + panel.ui.GetChild("name").text = "Man2"; + panel.ui.GetChild("blood").asProgress.value = 25; + panel.ui.GetChild("sign").asLoader.url = "ui://HeadBar/fighting"; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/HitTest/HitTestMain.cs b/Assets/Examples/HitTest/HitTestMain.cs index 9b36c76c..c72eb113 100644 --- a/Assets/Examples/HitTest/HitTestMain.cs +++ b/Assets/Examples/HitTest/HitTestMain.cs @@ -1,40 +1,40 @@ -using UnityEngine; -using FairyGUI; - -public class HitTestMain : MonoBehaviour -{ - Transform cube; - - void Start() - { - Application.targetFrameRate = 60; - - cube = GameObject.Find("Cube").transform; - - Stage.inst.onTouchBegin.Add(OnTouchBegin); - } - - void OnTouchBegin() - { - if (!Stage.isTouchOnUI) - { - RaycastHit hit; - Ray ray = Camera.main.ScreenPointToRay(new Vector2(Stage.inst.touchPosition.x, Screen.height - Stage.inst.touchPosition.y)); - if (Physics.Raycast(ray, out hit)) - { - if (hit.transform == cube) - { - Debug.Log("Hit the cube"); - } - } - } - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class HitTestMain : MonoBehaviour +{ + Transform cube; + + void Start() + { + Application.targetFrameRate = 60; + + cube = GameObject.Find("Cube").transform; + + Stage.inst.onTouchBegin.Add(OnTouchBegin); + } + + void OnTouchBegin() + { + if (!Stage.isTouchOnUI) + { + RaycastHit hit; + Ray ray = Camera.main.ScreenPointToRay(new Vector2(Stage.inst.touchPosition.x, Screen.height - Stage.inst.touchPosition.y)); + if (Physics.Raycast(ray, out hit)) + { + if (hit.transform == cube) + { + Debug.Log("Hit the cube"); + } + } + } + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Joystick/JoystickMain.cs b/Assets/Examples/Joystick/JoystickMain.cs index 4c03b67a..6e60f2b7 100644 --- a/Assets/Examples/Joystick/JoystickMain.cs +++ b/Assets/Examples/Joystick/JoystickMain.cs @@ -1,42 +1,42 @@ -using UnityEngine; -using FairyGUI; - -public class JoystickMain : MonoBehaviour -{ - GComponent _mainView; - GTextField _text; - JoystickModule _joystick; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _text = _mainView.GetChild("n9").asTextField; - - _joystick = new JoystickModule(_mainView); - _joystick.onMove.Add(__joystickMove); - _joystick.onEnd.Add(__joystickEnd); - } - - void __joystickMove(EventContext context) - { - float degree = (float)context.data; - _text.text = "" + degree; - } - - void __joystickEnd() - { - _text.text = ""; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class JoystickMain : MonoBehaviour +{ + GComponent _mainView; + GTextField _text; + JoystickModule _joystick; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _text = _mainView.GetChild("n9").asTextField; + + _joystick = new JoystickModule(_mainView); + _joystick.onMove.Add(__joystickMove); + _joystick.onEnd.Add(__joystickEnd); + } + + void __joystickMove(EventContext context) + { + float degree = (float)context.data; + _text.text = "" + degree; + } + + void __joystickEnd() + { + _text.text = ""; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Joystick/JoystickModule.cs b/Assets/Examples/Joystick/JoystickModule.cs index 2b8d1899..52e00af2 100644 --- a/Assets/Examples/Joystick/JoystickModule.cs +++ b/Assets/Examples/Joystick/JoystickModule.cs @@ -1,159 +1,159 @@ -using FairyGUI; -using UnityEngine; - -public class JoystickModule : EventDispatcher -{ - float _InitX; - float _InitY; - float _startStageX; - float _startStageY; - float _lastStageX; - float _lastStageY; - GButton _button; - GObject _touchArea; - GObject _thumb; - GObject _center; - int touchId; - GTweener _tweener; - - public EventListener onMove { get; private set; } - public EventListener onEnd { get; private set; } - - public int radius { get; set; } - - public JoystickModule(GComponent mainView) - { - onMove = new EventListener(this, "onMove"); - onEnd = new EventListener(this, "onEnd"); - - _button = mainView.GetChild("joystick").asButton; - _button.changeStateOnClick = false; - _thumb = _button.GetChild("thumb"); - _touchArea = mainView.GetChild("joystick_touch"); - _center = mainView.GetChild("joystick_center"); - - _InitX = _center.x + _center.width / 2; - _InitY = _center.y + _center.height / 2; - touchId = -1; - radius = 150; - - _touchArea.onTouchBegin.Add(this.OnTouchBegin); - _touchArea.onTouchMove.Add(this.OnTouchMove); - _touchArea.onTouchEnd.Add(this.OnTouchEnd); - } - - public void Trigger(EventContext context) - { - OnTouchBegin(context); - } - - private void OnTouchBegin(EventContext context) - { - if (touchId == -1)//First touch - { - InputEvent evt = (InputEvent)context.data; - touchId = evt.touchId; - - if (_tweener != null) - { - _tweener.Kill(); - _tweener = null; - } - - Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y)); - float bx = pt.x; - float by = pt.y; - _button.selected = true; - - if (bx < 0) - bx = 0; - else if (bx > _touchArea.width) - bx = _touchArea.width; - - if (by > GRoot.inst.height) - by = GRoot.inst.height; - else if (by < _touchArea.y) - by = _touchArea.y; - - _lastStageX = bx; - _lastStageY = by; - _startStageX = bx; - _startStageY = by; - - _center.visible = true; - _center.SetXY(bx - _center.width / 2, by - _center.height / 2); - _button.SetXY(bx - _button.width / 2, by - _button.height / 2); - - float deltaX = bx - _InitX; - float deltaY = by - _InitY; - float degrees = Mathf.Atan2(deltaY, deltaX) * 180 / Mathf.PI; - _thumb.rotation = degrees + 90; - - context.CaptureTouch(); - } - } - - private void OnTouchEnd(EventContext context) - { - InputEvent inputEvt = (InputEvent)context.data; - if (touchId != -1 && inputEvt.touchId == touchId) - { - touchId = -1; - _thumb.rotation = _thumb.rotation + 180; - _center.visible = false; - _tweener = _button.TweenMove(new Vector2(_InitX - _button.width / 2, _InitY - _button.height / 2), 0.3f).OnComplete(() => - { - _tweener = null; - _button.selected = false; - _thumb.rotation = 0; - _center.visible = true; - _center.SetXY(_InitX - _center.width / 2, _InitY - _center.height / 2); - } - ); - - this.onEnd.Call(); - } - } - - private void OnTouchMove(EventContext context) - { - InputEvent evt = (InputEvent)context.data; - if (touchId != -1 && evt.touchId == touchId) - { - Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y)); - float bx = pt.x; - float by = pt.y; - float moveX = bx - _lastStageX; - float moveY = by - _lastStageY; - _lastStageX = bx; - _lastStageY = by; - float buttonX = _button.x + moveX; - float buttonY = _button.y + moveY; - - float offsetX = buttonX + _button.width / 2 - _startStageX; - float offsetY = buttonY + _button.height / 2 - _startStageY; - - float rad = Mathf.Atan2(offsetY, offsetX); - float degree = rad * 180 / Mathf.PI; - _thumb.rotation = degree + 90; - - float maxX = radius * Mathf.Cos(rad); - float maxY = radius * Mathf.Sin(rad); - if (Mathf.Abs(offsetX) > Mathf.Abs(maxX)) - offsetX = maxX; - if (Mathf.Abs(offsetY) > Mathf.Abs(maxY)) - offsetY = maxY; - - buttonX = _startStageX + offsetX; - buttonY = _startStageY + offsetY; - if (buttonX < 0) - buttonX = 0; - if (buttonY > GRoot.inst.height) - buttonY = GRoot.inst.height; - - _button.SetXY(buttonX - _button.width / 2, buttonY - _button.height / 2); - - this.onMove.Call(degree); - } - } +using FairyGUI; +using UnityEngine; + +public class JoystickModule : EventDispatcher +{ + float _InitX; + float _InitY; + float _startStageX; + float _startStageY; + float _lastStageX; + float _lastStageY; + GButton _button; + GObject _touchArea; + GObject _thumb; + GObject _center; + int touchId; + GTweener _tweener; + + public EventListener onMove { get; private set; } + public EventListener onEnd { get; private set; } + + public int radius { get; set; } + + public JoystickModule(GComponent mainView) + { + onMove = new EventListener(this, "onMove"); + onEnd = new EventListener(this, "onEnd"); + + _button = mainView.GetChild("joystick").asButton; + _button.changeStateOnClick = false; + _thumb = _button.GetChild("thumb"); + _touchArea = mainView.GetChild("joystick_touch"); + _center = mainView.GetChild("joystick_center"); + + _InitX = _center.x + _center.width / 2; + _InitY = _center.y + _center.height / 2; + touchId = -1; + radius = 150; + + _touchArea.onTouchBegin.Add(this.OnTouchBegin); + _touchArea.onTouchMove.Add(this.OnTouchMove); + _touchArea.onTouchEnd.Add(this.OnTouchEnd); + } + + public void Trigger(EventContext context) + { + OnTouchBegin(context); + } + + private void OnTouchBegin(EventContext context) + { + if (touchId == -1)//First touch + { + InputEvent evt = (InputEvent)context.data; + touchId = evt.touchId; + + if (_tweener != null) + { + _tweener.Kill(); + _tweener = null; + } + + Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y)); + float bx = pt.x; + float by = pt.y; + _button.selected = true; + + if (bx < 0) + bx = 0; + else if (bx > _touchArea.width) + bx = _touchArea.width; + + if (by > GRoot.inst.height) + by = GRoot.inst.height; + else if (by < _touchArea.y) + by = _touchArea.y; + + _lastStageX = bx; + _lastStageY = by; + _startStageX = bx; + _startStageY = by; + + _center.visible = true; + _center.SetXY(bx - _center.width / 2, by - _center.height / 2); + _button.SetXY(bx - _button.width / 2, by - _button.height / 2); + + float deltaX = bx - _InitX; + float deltaY = by - _InitY; + float degrees = Mathf.Atan2(deltaY, deltaX) * 180 / Mathf.PI; + _thumb.rotation = degrees + 90; + + context.CaptureTouch(); + } + } + + private void OnTouchEnd(EventContext context) + { + InputEvent inputEvt = (InputEvent)context.data; + if (touchId != -1 && inputEvt.touchId == touchId) + { + touchId = -1; + _thumb.rotation = _thumb.rotation + 180; + _center.visible = false; + _tweener = _button.TweenMove(new Vector2(_InitX - _button.width / 2, _InitY - _button.height / 2), 0.3f).OnComplete(() => + { + _tweener = null; + _button.selected = false; + _thumb.rotation = 0; + _center.visible = true; + _center.SetXY(_InitX - _center.width / 2, _InitY - _center.height / 2); + } + ); + + this.onEnd.Call(); + } + } + + private void OnTouchMove(EventContext context) + { + InputEvent evt = (InputEvent)context.data; + if (touchId != -1 && evt.touchId == touchId) + { + Vector2 pt = GRoot.inst.GlobalToLocal(new Vector2(evt.x, evt.y)); + float bx = pt.x; + float by = pt.y; + float moveX = bx - _lastStageX; + float moveY = by - _lastStageY; + _lastStageX = bx; + _lastStageY = by; + float buttonX = _button.x + moveX; + float buttonY = _button.y + moveY; + + float offsetX = buttonX + _button.width / 2 - _startStageX; + float offsetY = buttonY + _button.height / 2 - _startStageY; + + float rad = Mathf.Atan2(offsetY, offsetX); + float degree = rad * 180 / Mathf.PI; + _thumb.rotation = degree + 90; + + float maxX = radius * Mathf.Cos(rad); + float maxY = radius * Mathf.Sin(rad); + if (Mathf.Abs(offsetX) > Mathf.Abs(maxX)) + offsetX = maxX; + if (Mathf.Abs(offsetY) > Mathf.Abs(maxY)) + offsetY = maxY; + + buttonX = _startStageX + offsetX; + buttonY = _startStageY + offsetY; + if (buttonX < 0) + buttonX = 0; + if (buttonY > GRoot.inst.height) + buttonY = GRoot.inst.height; + + _button.SetXY(buttonX - _button.width / 2, buttonY - _button.height / 2); + + this.onMove.Call(degree); + } + } } \ No newline at end of file diff --git a/Assets/Examples/LoopList/LoopListMain.cs b/Assets/Examples/LoopList/LoopListMain.cs index a9a061cb..0ae15a1d 100644 --- a/Assets/Examples/LoopList/LoopListMain.cs +++ b/Assets/Examples/LoopList/LoopListMain.cs @@ -1,63 +1,63 @@ -using UnityEngine; -using FairyGUI; - -public class LoopListMain : MonoBehaviour -{ - GComponent _mainView; - GList _list; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - UIPackage.AddPackage("UI/LoopList"); - - _mainView = this.GetComponent().ui; - - _list = _mainView.GetChild("list").asList; - _list.SetVirtualAndLoop(); - - _list.itemRenderer = RenderListItem; - _list.numItems = 5; - _list.scrollPane.onScroll.Add(DoSpecialEffect); - - DoSpecialEffect(); - } - - void DoSpecialEffect() - { - //change the scale according to the distance to middle - float midX = _list.scrollPane.posX + _list.viewWidth / 2; - int cnt = _list.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = _list.GetChildAt(i); - float dist = Mathf.Abs(midX - obj.x - obj.width / 2); - if (dist > obj.width) //no intersection - obj.SetScale(1, 1); - else - { - float ss = 1 + (1 - dist / obj.width) * 0.24f; - obj.SetScale(ss, ss); - } - } - - _mainView.GetChild("n3").text = "" + ((_list.GetFirstChildInView() + 1) % _list.numItems); - } - - void RenderListItem(int index, GObject obj) - { - GButton item = (GButton)obj; - item.SetPivot(0.5f, 0.5f); - item.icon = UIPackage.GetItemURL("LoopList", "n" + (index + 1)); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class LoopListMain : MonoBehaviour +{ + GComponent _mainView; + GList _list; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + UIPackage.AddPackage("UI/LoopList"); + + _mainView = this.GetComponent().ui; + + _list = _mainView.GetChild("list").asList; + _list.SetVirtualAndLoop(); + + _list.itemRenderer = RenderListItem; + _list.numItems = 5; + _list.scrollPane.onScroll.Add(DoSpecialEffect); + + DoSpecialEffect(); + } + + void DoSpecialEffect() + { + //change the scale according to the distance to middle + float midX = _list.scrollPane.posX + _list.viewWidth / 2; + int cnt = _list.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = _list.GetChildAt(i); + float dist = Mathf.Abs(midX - obj.x - obj.width / 2); + if (dist > obj.width) //no intersection + obj.SetScale(1, 1); + else + { + float ss = 1 + (1 - dist / obj.width) * 0.24f; + obj.SetScale(ss, ss); + } + } + + _mainView.GetChild("n3").text = "" + ((_list.GetFirstChildInView() + 1) % _list.numItems); + } + + void RenderListItem(int index, GObject obj) + { + GButton item = (GButton)obj; + item.SetPivot(0.5f, 0.5f); + item.icon = UIPackage.GetItemURL("LoopList", "n" + (index + 1)); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/ModalWaiting/ModalWaitingMain.cs b/Assets/Examples/ModalWaiting/ModalWaitingMain.cs index b22020ef..969e55c6 100644 --- a/Assets/Examples/ModalWaiting/ModalWaitingMain.cs +++ b/Assets/Examples/ModalWaiting/ModalWaitingMain.cs @@ -1,47 +1,47 @@ -using System.Collections; -using UnityEngine; -using FairyGUI; - -public class ModalWaitingMain : MonoBehaviour -{ - GComponent _mainView; - Window4 _testWin; - - void Awake() - { - UIPackage.AddPackage("UI/ModalWaiting"); - UIConfig.globalModalWaiting = "ui://ModalWaiting/GlobalModalWaiting"; - UIConfig.windowModalWaiting = "ui://ModalWaiting/WindowModalWaiting"; - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _testWin = new Window4(); - - _mainView.GetChild("n0").onClick.Add(() => { _testWin.Show(); }); - - StartCoroutine(WaitSomeTime()); - } - - IEnumerator WaitSomeTime() - { - GRoot.inst.ShowModalWait(); - - yield return new WaitForSeconds(3); - - GRoot.inst.CloseModalWait(); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using System.Collections; +using UnityEngine; +using FairyGUI; + +public class ModalWaitingMain : MonoBehaviour +{ + GComponent _mainView; + Window4 _testWin; + + void Awake() + { + UIPackage.AddPackage("UI/ModalWaiting"); + UIConfig.globalModalWaiting = "ui://ModalWaiting/GlobalModalWaiting"; + UIConfig.windowModalWaiting = "ui://ModalWaiting/WindowModalWaiting"; + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _testWin = new Window4(); + + _mainView.GetChild("n0").onClick.Add(() => { _testWin.Show(); }); + + StartCoroutine(WaitSomeTime()); + } + + IEnumerator WaitSomeTime() + { + GRoot.inst.ShowModalWait(); + + yield return new WaitForSeconds(3); + + GRoot.inst.CloseModalWait(); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/ModalWaiting/Window4.cs b/Assets/Examples/ModalWaiting/Window4.cs index 66db15f3..a6fad6da 100644 --- a/Assets/Examples/ModalWaiting/Window4.cs +++ b/Assets/Examples/ModalWaiting/Window4.cs @@ -1,20 +1,20 @@ -using FairyGUI; - -public class Window4 : Window -{ - public Window4() - { - } - - protected override void OnInit() - { - this.contentPane = UIPackage.CreateObject("ModalWaiting", "TestWin").asCom; - this.contentPane.GetChild("n1").onClick.Add(OnClick); - } - - void OnClick() - { - this.ShowModalWait(); - Timers.inst.Add(3, 1, (object param) => { this.CloseModalWait(); }); - } -} +using FairyGUI; + +public class Window4 : Window +{ + public Window4() + { + } + + protected override void OnInit() + { + this.contentPane = UIPackage.CreateObject("ModalWaiting", "TestWin").asCom; + this.contentPane.GetChild("n1").onClick.Add(OnClick); + } + + void OnClick() + { + this.ShowModalWait(); + Timers.inst.Add(3, 1, (object param) => { this.CloseModalWait(); }); + } +} diff --git a/Assets/Examples/Model/ModelMain.cs b/Assets/Examples/Model/ModelMain.cs index 63b53776..0d7382dd 100644 --- a/Assets/Examples/Model/ModelMain.cs +++ b/Assets/Examples/Model/ModelMain.cs @@ -1,30 +1,30 @@ -using UnityEngine; -using FairyGUI; - -public class ModelMain : MonoBehaviour -{ - GComponent _mainView; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - Object prefab = Resources.Load("Role/npc"); - GameObject go = (GameObject)Object.Instantiate(prefab); - go.transform.localPosition = new Vector3(61, -89, 1000); //set z to far from UICamera is important! - go.transform.localScale = new Vector3(180, 180, 180); - go.transform.localEulerAngles = new Vector3(0, 100, 0); - _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go)); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class ModelMain : MonoBehaviour +{ + GComponent _mainView; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + Object prefab = Resources.Load("Role/npc"); + GameObject go = (GameObject)Object.Instantiate(prefab); + go.transform.localPosition = new Vector3(61, -89, 1000); //set z to far from UICamera is important! + go.transform.localScale = new Vector3(180, 180, 180); + go.transform.localEulerAngles = new Vector3(0, 100, 0); + _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go)); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Particles/CoolComponent.cs b/Assets/Examples/Particles/CoolComponent.cs index 3cab713c..6dd1a183 100644 --- a/Assets/Examples/Particles/CoolComponent.cs +++ b/Assets/Examples/Particles/CoolComponent.cs @@ -1,16 +1,16 @@ -using UnityEngine; -using FairyGUI; - -public class CoolComponent : GComponent -{ - public override void ConstructFromXML(FairyGUI.Utils.XML cxml) - { - base.ConstructFromXML(cxml); - - GGraph graph = this.GetChild("effect").asGraph; - - Object prefab = Resources.Load("Flame"); - GameObject go = (GameObject)Object.Instantiate(prefab); - graph.SetNativeObject(new GoWrapper(go)); - } -} +using UnityEngine; +using FairyGUI; + +public class CoolComponent : GComponent +{ + public override void ConstructFromXML(FairyGUI.Utils.XML cxml) + { + base.ConstructFromXML(cxml); + + GGraph graph = this.GetChild("effect").asGraph; + + Object prefab = Resources.Load("Flame"); + GameObject go = (GameObject)Object.Instantiate(prefab); + graph.SetNativeObject(new GoWrapper(go)); + } +} diff --git a/Assets/Examples/Particles/ParticlesMain.cs b/Assets/Examples/Particles/ParticlesMain.cs index 9d1b2364..c2db0873 100644 --- a/Assets/Examples/Particles/ParticlesMain.cs +++ b/Assets/Examples/Particles/ParticlesMain.cs @@ -1,37 +1,37 @@ -using UnityEngine; -using FairyGUI; - -public class ParticlesMain : MonoBehaviour -{ - GComponent _mainView; - - void Awake() - { - UIPackage.AddPackage("UI/Particles"); - - UIObjectFactory.SetPackageItemExtension("ui://Particles/CoolComponent", typeof(CoolComponent)); - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - Object prefab = Resources.Load("Flame"); - GameObject go = (GameObject)Object.Instantiate(prefab); - _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go)); - - _mainView.GetChild("c0").draggable = true; - _mainView.GetChild("c1").draggable = true; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class ParticlesMain : MonoBehaviour +{ + GComponent _mainView; + + void Awake() + { + UIPackage.AddPackage("UI/Particles"); + + UIObjectFactory.SetPackageItemExtension("ui://Particles/CoolComponent", typeof(CoolComponent)); + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + Object prefab = Resources.Load("Flame"); + GameObject go = (GameObject)Object.Instantiate(prefab); + _mainView.GetChild("holder").asGraph.SetNativeObject(new GoWrapper(go)); + + _mainView.GetChild("c0").draggable = true; + _mainView.GetChild("c1").draggable = true; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Perspetive/PerspectiveMain.cs b/Assets/Examples/Perspetive/PerspectiveMain.cs index 4a71a662..0357efd9 100644 --- a/Assets/Examples/Perspetive/PerspectiveMain.cs +++ b/Assets/Examples/Perspetive/PerspectiveMain.cs @@ -1,29 +1,29 @@ -using UnityEngine; -using FairyGUI; - -public class PerspectiveMain : MonoBehaviour -{ - GList _list; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - //GComponent g1 = GameObject.Find("UIPanel1").GetComponent().ui; - - GComponent g2 = GameObject.Find("UIPanel2").GetComponent().ui; - _list = g2.GetChild("mailList").asList; - _list.SetVirtual(); - _list.itemRenderer = (int index, GObject obj) => { obj.text = index + " Mail title here"; }; - _list.numItems = 20; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class PerspectiveMain : MonoBehaviour +{ + GList _list; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + //GComponent g1 = GameObject.Find("UIPanel1").GetComponent().ui; + + GComponent g2 = GameObject.Find("UIPanel2").GetComponent().ui; + _list = g2.GetChild("mailList").asList; + _list.SetVirtual(); + _list.itemRenderer = (int index, GObject obj) => { obj.text = index + " Mail title here"; }; + _list.numItems = 20; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/PullToRefresh/PullToRefreshMain.cs b/Assets/Examples/PullToRefresh/PullToRefreshMain.cs index 97cf9412..762f9177 100644 --- a/Assets/Examples/PullToRefresh/PullToRefreshMain.cs +++ b/Assets/Examples/PullToRefresh/PullToRefreshMain.cs @@ -1,98 +1,98 @@ -using UnityEngine; -using FairyGUI; - -public class PullToRefreshMain : MonoBehaviour -{ - GComponent _mainView; - GList _list1; - GList _list2; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - UIObjectFactory.SetPackageItemExtension("ui://PullToRefresh/Header", typeof(ScrollPaneHeader)); - } - - void Start() - { - _mainView = this.GetComponent().ui; - - _list1 = _mainView.GetChild("list1").asList; - _list1.itemRenderer = RenderListItem1; - _list1.SetVirtual(); - _list1.numItems = 1; - _list1.scrollPane.onPullDownRelease.Add(OnPullDownToRefresh); - - _list2 = _mainView.GetChild("list2").asList; - _list2.itemRenderer = RenderListItem2; - _list2.SetVirtual(); - _list2.numItems = 1; - _list2.scrollPane.onPullUpRelease.Add(OnPullUpToRefresh); - } - - void RenderListItem1(int index, GObject obj) - { - GButton item = obj.asButton; - item.title = "Item " + (_list1.numItems - index - 1); - } - - void RenderListItem2(int index, GObject obj) - { - GButton item = obj.asButton; - item.title = "Item " + index; - } - - void OnPullDownToRefresh() - { - ScrollPaneHeader header = (ScrollPaneHeader)_list1.scrollPane.header; - if (header.ReadyToRefresh) - { - header.SetRefreshStatus(2); - _list1.scrollPane.LockHeader(header.sourceHeight); - - //Simulate a async resquest - Timers.inst.Add(2, 1, (object param) => - { - _list1.numItems += 5; - - //Refresh completed - header.SetRefreshStatus(3); - _list1.scrollPane.LockHeader(35); - - Timers.inst.Add(2, 1, (object param2) => - { - header.SetRefreshStatus(0); - _list1.scrollPane.LockHeader(0); - }); - }); - } - } - - void OnPullUpToRefresh() - { - GComponent footer = (GComponent)_list2.scrollPane.footer; - - footer.GetController("c1").selectedIndex = 1; - _list2.scrollPane.LockFooter(footer.sourceHeight); - - //Simulate a async resquest - Timers.inst.Add(2, 1, (object param) => - { - _list2.numItems += 5; - - //Refresh completed - footer.GetController("c1").selectedIndex = 0; - _list2.scrollPane.LockFooter(0); - }); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class PullToRefreshMain : MonoBehaviour +{ + GComponent _mainView; + GList _list1; + GList _list2; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + UIObjectFactory.SetPackageItemExtension("ui://PullToRefresh/Header", typeof(ScrollPaneHeader)); + } + + void Start() + { + _mainView = this.GetComponent().ui; + + _list1 = _mainView.GetChild("list1").asList; + _list1.itemRenderer = RenderListItem1; + _list1.SetVirtual(); + _list1.numItems = 1; + _list1.scrollPane.onPullDownRelease.Add(OnPullDownToRefresh); + + _list2 = _mainView.GetChild("list2").asList; + _list2.itemRenderer = RenderListItem2; + _list2.SetVirtual(); + _list2.numItems = 1; + _list2.scrollPane.onPullUpRelease.Add(OnPullUpToRefresh); + } + + void RenderListItem1(int index, GObject obj) + { + GButton item = obj.asButton; + item.title = "Item " + (_list1.numItems - index - 1); + } + + void RenderListItem2(int index, GObject obj) + { + GButton item = obj.asButton; + item.title = "Item " + index; + } + + void OnPullDownToRefresh() + { + ScrollPaneHeader header = (ScrollPaneHeader)_list1.scrollPane.header; + if (header.ReadyToRefresh) + { + header.SetRefreshStatus(2); + _list1.scrollPane.LockHeader(header.sourceHeight); + + //Simulate a async resquest + Timers.inst.Add(2, 1, (object param) => + { + _list1.numItems += 5; + + //Refresh completed + header.SetRefreshStatus(3); + _list1.scrollPane.LockHeader(35); + + Timers.inst.Add(2, 1, (object param2) => + { + header.SetRefreshStatus(0); + _list1.scrollPane.LockHeader(0); + }); + }); + } + } + + void OnPullUpToRefresh() + { + GComponent footer = (GComponent)_list2.scrollPane.footer; + + footer.GetController("c1").selectedIndex = 1; + _list2.scrollPane.LockFooter(footer.sourceHeight); + + //Simulate a async resquest + Timers.inst.Add(2, 1, (object param) => + { + _list2.numItems += 5; + + //Refresh completed + footer.GetController("c1").selectedIndex = 0; + _list2.scrollPane.LockFooter(0); + }); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs b/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs index 34420657..66e1d834 100644 --- a/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs +++ b/Assets/Examples/PullToRefresh/ScrollPaneHeader.cs @@ -1,37 +1,37 @@ -using FairyGUI; -using UnityEngine; - -public class ScrollPaneHeader : GComponent -{ - Controller _c1; - - public override void ConstructFromXML(FairyGUI.Utils.XML xml) - { - base.ConstructFromXML(xml); - - _c1 = this.GetController("c1"); - - this.onSizeChanged.Add(OnSizeChanged); - } - - void OnSizeChanged() - { - if (_c1.selectedIndex == 2 || _c1.selectedIndex == 3) - return; - - if (this.height > this.sourceHeight) - _c1.selectedIndex = 1; - else - _c1.selectedIndex = 0; - } - - public bool ReadyToRefresh - { - get { return _c1.selectedIndex == 1; } - } - - public void SetRefreshStatus(int value) - { - _c1.selectedIndex = value; - } -} +using FairyGUI; +using UnityEngine; + +public class ScrollPaneHeader : GComponent +{ + Controller _c1; + + public override void ConstructFromXML(FairyGUI.Utils.XML xml) + { + base.ConstructFromXML(xml); + + _c1 = this.GetController("c1"); + + this.onSizeChanged.Add(OnSizeChanged); + } + + void OnSizeChanged() + { + if (_c1.selectedIndex == 2 || _c1.selectedIndex == 3) + return; + + if (this.height > this.sourceHeight) + _c1.selectedIndex = 1; + else + _c1.selectedIndex = 0; + } + + public bool ReadyToRefresh + { + get { return _c1.selectedIndex == 1; } + } + + public void SetRefreshStatus(int value) + { + _c1.selectedIndex = value; + } +} diff --git a/Assets/Examples/RenderTexture/RenderImage.cs b/Assets/Examples/RenderTexture/RenderImage.cs index c28bab8e..5b8f035b 100644 --- a/Assets/Examples/RenderTexture/RenderImage.cs +++ b/Assets/Examples/RenderTexture/RenderImage.cs @@ -1,292 +1,292 @@ -using FairyGUI; -using FairyGUI.Utils; -using System.Collections; -using UnityEngine; - -public class RenderImage -{ - public Transform modelRoot { get; private set; } - - Camera _camera; - Image _image; - Transform _root; - Transform _background; - Transform _model; - RenderTexture _renderTexture; - int _width; - int _height; - bool _cacheTexture; - float _rotating; - - const int RENDER_LAYER = 0; - const int HIDDEN_LAYER = 10; - - public RenderImage(GGraph holder) - { - _width = (int)holder.width; - _height = (int)holder.height; - _cacheTexture = true; - - this._image = new Image(); - holder.SetNativeObject(this._image); - - Object prefab = Resources.Load("RenderTexture/RenderImageCamera"); - GameObject go = (GameObject)Object.Instantiate(prefab); - _camera = go.GetComponent(); - _camera.transform.position = new Vector3(0, 1000, 0); - _camera.cullingMask = 1 << RENDER_LAYER; - _camera.enabled = false; - Object.DontDestroyOnLoad(_camera.gameObject); - - this._root = new GameObject("RenderImage").transform; - this._root.SetParent(_camera.transform, false); - SetLayer(this._root.gameObject, HIDDEN_LAYER); - - this.modelRoot = new GameObject("model_root").transform; - this.modelRoot.SetParent(this._root, false); - - this._background = new GameObject("background").transform; - this._background.SetParent(this._root, false); - - this._image.onAddedToStage.Add(OnAddedToStage); - this._image.onRemovedFromStage.Add(OnRemoveFromStage); - - if (this._image.stage != null) - OnAddedToStage(); - else - _camera.gameObject.SetActive(false); - } - - public void Dispose() - { - Object.Destroy(_camera.gameObject); - DestroyTexture(); - - this._image.Dispose(); - this._image = null; - } - - /// - /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture, - /// you can set a maximunm two images for background. - /// Be careful if your image is 9 grid scaling, you must make sure the place holder is inside the middle box(dont cover from border to middle). - /// - /// - public void SetBackground(GObject image) - { - SetBackground(image, null); - } - - /// - /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture, - /// you can set a maximunm two images for background. - /// - /// - /// - public void SetBackground(GObject image1, GObject image2) - { - Image source1 = (Image)image1.displayObject; - Image source2 = image2 != null ? (Image)image2.displayObject : null; - - Vector3 pos = _background.position; - pos.z = _camera.farClipPlane; - _background.position = pos; - - Vector2[] uv = new Vector2[4]; - Vector2[] uv2 = null; - - Rect rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source1); - Rect uvRect = GetImageUVRect(source1, rect, uv); - - if (source2 != null) - { - rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source2); - uv2 = new Vector2[4]; - GetImageUVRect(source2, rect, uv2); - } - - Vector3[] vertices = new Vector3[4]; - for (int i = 0; i < 4; i++) - { - Vector2 v = uv[i]; - vertices[i] = new Vector3((v.x - uvRect.x) / uvRect.width * 2 - 1, - (v.y - uvRect.y) / uvRect.height * 2 - 1, 0); - } - - Mesh mesh = new Mesh(); - mesh.vertices = vertices; - mesh.uv = uv; - if (uv2 != null) - mesh.uv2 = uv2; - mesh.colors32 = new Color32[] { Color.white, Color.white, Color.white, Color.white }; - mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 }; - - MeshFilter meshFilter = this._background.gameObject.GetComponent(); - if (meshFilter == null) - meshFilter = this._background.gameObject.AddComponent(); - meshFilter.mesh = mesh; - MeshRenderer meshRenderer = this._background.gameObject.GetComponent(); - if (meshRenderer == null) - meshRenderer = this._background.gameObject.AddComponent(); -#if (UNITY_5 || UNITY_5_3_OR_NEWER) - meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; -#else - meshRenderer.castShadows = false; -#endif - meshRenderer.receiveShadows = false; - Shader shader = Shader.Find("Game/FullScreen"); - Material mat = new Material(shader); - mat.mainTexture = source1.texture.nativeTexture; - if (source2 != null) - mat.SetTexture("_Tex2", source2.texture.nativeTexture); - meshRenderer.material = mat; - } - - Rect GetImageUVRect(Image image, Rect localRect, Vector2[] uv) - { - Rect imageRect = new Rect(0, 0, image.size.x, image.size.y); - Rect bound = ToolSet.Intersection(ref imageRect, ref localRect); - Rect uvRect = image.texture.uvRect; - - if (image.scale9Grid != null) - { - Rect gridRect = (Rect)image.scale9Grid; - float sourceW = image.texture.width; - float sourceH = image.texture.height; - uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMin / sourceW), - Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMax) / sourceH), - Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMax / sourceW), - Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMin) / sourceH)); - - float vw = imageRect.width - (sourceW - gridRect.width); - float vh = imageRect.height - (sourceH - gridRect.height); - uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.x - gridRect.x) / vw), - Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax - (sourceH - gridRect.yMax)) / vh), - Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.xMax - gridRect.x) / vw), - Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin - gridRect.y) / vh)); - } - else - { - uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMin / imageRect.width), - Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax) / imageRect.height), - Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMax / imageRect.width), - Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin) / imageRect.height)); - } - - uv[0] = uvRect.position; - uv[1] = new Vector2(uvRect.xMin, uvRect.yMax); - uv[2] = new Vector2(uvRect.xMax, uvRect.yMax); - uv[3] = new Vector2(uvRect.xMax, uvRect.yMin); - - if (image.texture.rotated) - ToolSet.RotateUV(uv, ref image.texture.uvRect); - - return uvRect; - } - - public void LoadModel(string model) - { - this.UnloadModel(); - - Object prefab = Resources.Load(model); - GameObject go = ((GameObject)Object.Instantiate(prefab)); - _model = go.transform; - _model.SetParent(this.modelRoot, false); - } - - public void UnloadModel() - { - if (_model != null) - { - Object.Destroy(_model.gameObject); - _model = null; - } - _rotating = 0; - } - - public void StartRotate(float delta) - { - _rotating = delta; - } - - public void StopRotate() - { - _rotating = 0; - } - - void CreateTexture() - { - if (_renderTexture != null) - return; - - _renderTexture = new RenderTexture(_width, _height, 24, RenderTextureFormat.ARGB32) - { - antiAliasing = 1, - filterMode = FilterMode.Bilinear, - anisoLevel = 0, - useMipMap = false - }; - this._image.texture = new NTexture(_renderTexture); - this._image.blendMode = BlendMode.Off; - } - - void DestroyTexture() - { - if (_renderTexture != null) - { - Object.Destroy(_renderTexture); - _renderTexture = null; - this._image.texture = null; - } - } - - void OnAddedToStage() - { - if (_renderTexture == null) - CreateTexture(); - - Timers.inst.AddUpdate(this.Render); - _camera.gameObject.SetActive(true); - - Render(); - } - - void OnRemoveFromStage() - { - if (!_cacheTexture) - DestroyTexture(); - - Timers.inst.Remove(this.Render); - _camera.gameObject.SetActive(false); - } - - void Render(object param = null) - { - if (_rotating != 0 && this.modelRoot != null) - { - Vector3 localRotation = this.modelRoot.localRotation.eulerAngles; - localRotation.y += _rotating; - this.modelRoot.localRotation = Quaternion.Euler(localRotation); - } - - SetLayer(this._root.gameObject, RENDER_LAYER); - - _camera.targetTexture = this._renderTexture; - RenderTexture old = RenderTexture.active; - RenderTexture.active = this._renderTexture; - GL.Clear(true, true, Color.clear); - _camera.Render(); - RenderTexture.active = old; - - SetLayer(this._root.gameObject, HIDDEN_LAYER); - } - - void SetLayer(GameObject go, int layer) - { - Transform[] transforms = go.GetComponentsInChildren(true); - foreach (Transform t in transforms) - { - t.gameObject.layer = layer; - } - } +using FairyGUI; +using FairyGUI.Utils; +using System.Collections; +using UnityEngine; + +public class RenderImage +{ + public Transform modelRoot { get; private set; } + + Camera _camera; + Image _image; + Transform _root; + Transform _background; + Transform _model; + RenderTexture _renderTexture; + int _width; + int _height; + bool _cacheTexture; + float _rotating; + + const int RENDER_LAYER = 0; + const int HIDDEN_LAYER = 10; + + public RenderImage(GGraph holder) + { + _width = (int)holder.width; + _height = (int)holder.height; + _cacheTexture = true; + + this._image = new Image(); + holder.SetNativeObject(this._image); + + Object prefab = Resources.Load("RenderTexture/RenderImageCamera"); + GameObject go = (GameObject)Object.Instantiate(prefab); + _camera = go.GetComponent(); + _camera.transform.position = new Vector3(0, 1000, 0); + _camera.cullingMask = 1 << RENDER_LAYER; + _camera.enabled = false; + Object.DontDestroyOnLoad(_camera.gameObject); + + this._root = new GameObject("RenderImage").transform; + this._root.SetParent(_camera.transform, false); + SetLayer(this._root.gameObject, HIDDEN_LAYER); + + this.modelRoot = new GameObject("model_root").transform; + this.modelRoot.SetParent(this._root, false); + + this._background = new GameObject("background").transform; + this._background.SetParent(this._root, false); + + this._image.onAddedToStage.Add(OnAddedToStage); + this._image.onRemovedFromStage.Add(OnRemoveFromStage); + + if (this._image.stage != null) + OnAddedToStage(); + else + _camera.gameObject.SetActive(false); + } + + public void Dispose() + { + Object.Destroy(_camera.gameObject); + DestroyTexture(); + + this._image.Dispose(); + this._image = null; + } + + /// + /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture, + /// you can set a maximunm two images for background. + /// Be careful if your image is 9 grid scaling, you must make sure the place holder is inside the middle box(dont cover from border to middle). + /// + /// + public void SetBackground(GObject image) + { + SetBackground(image, null); + } + + /// + /// The rendertexture is not transparent. So if you want to the UI elements can be seen in the back of the models/particles in rendertexture, + /// you can set a maximunm two images for background. + /// + /// + /// + public void SetBackground(GObject image1, GObject image2) + { + Image source1 = (Image)image1.displayObject; + Image source2 = image2 != null ? (Image)image2.displayObject : null; + + Vector3 pos = _background.position; + pos.z = _camera.farClipPlane; + _background.position = pos; + + Vector2[] uv = new Vector2[4]; + Vector2[] uv2 = null; + + Rect rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source1); + Rect uvRect = GetImageUVRect(source1, rect, uv); + + if (source2 != null) + { + rect = _image.TransformRect(new Rect(0, 0, this._width, this._height), source2); + uv2 = new Vector2[4]; + GetImageUVRect(source2, rect, uv2); + } + + Vector3[] vertices = new Vector3[4]; + for (int i = 0; i < 4; i++) + { + Vector2 v = uv[i]; + vertices[i] = new Vector3((v.x - uvRect.x) / uvRect.width * 2 - 1, + (v.y - uvRect.y) / uvRect.height * 2 - 1, 0); + } + + Mesh mesh = new Mesh(); + mesh.vertices = vertices; + mesh.uv = uv; + if (uv2 != null) + mesh.uv2 = uv2; + mesh.colors32 = new Color32[] { Color.white, Color.white, Color.white, Color.white }; + mesh.triangles = new int[] { 0, 1, 2, 2, 3, 0 }; + + MeshFilter meshFilter = this._background.gameObject.GetComponent(); + if (meshFilter == null) + meshFilter = this._background.gameObject.AddComponent(); + meshFilter.mesh = mesh; + MeshRenderer meshRenderer = this._background.gameObject.GetComponent(); + if (meshRenderer == null) + meshRenderer = this._background.gameObject.AddComponent(); +#if (UNITY_5 || UNITY_5_3_OR_NEWER) + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; +#else + meshRenderer.castShadows = false; +#endif + meshRenderer.receiveShadows = false; + Shader shader = Shader.Find("Game/FullScreen"); + Material mat = new Material(shader); + mat.mainTexture = source1.texture.nativeTexture; + if (source2 != null) + mat.SetTexture("_Tex2", source2.texture.nativeTexture); + meshRenderer.material = mat; + } + + Rect GetImageUVRect(Image image, Rect localRect, Vector2[] uv) + { + Rect imageRect = new Rect(0, 0, image.size.x, image.size.y); + Rect bound = ToolSet.Intersection(ref imageRect, ref localRect); + Rect uvRect = image.texture.uvRect; + + if (image.scale9Grid != null) + { + Rect gridRect = (Rect)image.scale9Grid; + float sourceW = image.texture.width; + float sourceH = image.texture.height; + uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMin / sourceW), + Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMax) / sourceH), + Mathf.Lerp(uvRect.xMin, uvRect.xMax, gridRect.xMax / sourceW), + Mathf.Lerp(uvRect.yMin, uvRect.yMax, (sourceH - gridRect.yMin) / sourceH)); + + float vw = imageRect.width - (sourceW - gridRect.width); + float vh = imageRect.height - (sourceH - gridRect.height); + uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.x - gridRect.x) / vw), + Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax - (sourceH - gridRect.yMax)) / vh), + Mathf.Lerp(uvRect.xMin, uvRect.xMax, (bound.xMax - gridRect.x) / vw), + Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin - gridRect.y) / vh)); + } + else + { + uvRect = Rect.MinMaxRect(Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMin / imageRect.width), + Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMax) / imageRect.height), + Mathf.Lerp(uvRect.xMin, uvRect.xMax, bound.xMax / imageRect.width), + Mathf.Lerp(uvRect.yMin, uvRect.yMax, (imageRect.height - bound.yMin) / imageRect.height)); + } + + uv[0] = uvRect.position; + uv[1] = new Vector2(uvRect.xMin, uvRect.yMax); + uv[2] = new Vector2(uvRect.xMax, uvRect.yMax); + uv[3] = new Vector2(uvRect.xMax, uvRect.yMin); + + if (image.texture.rotated) + ToolSet.RotateUV(uv, ref image.texture.uvRect); + + return uvRect; + } + + public void LoadModel(string model) + { + this.UnloadModel(); + + Object prefab = Resources.Load(model); + GameObject go = ((GameObject)Object.Instantiate(prefab)); + _model = go.transform; + _model.SetParent(this.modelRoot, false); + } + + public void UnloadModel() + { + if (_model != null) + { + Object.Destroy(_model.gameObject); + _model = null; + } + _rotating = 0; + } + + public void StartRotate(float delta) + { + _rotating = delta; + } + + public void StopRotate() + { + _rotating = 0; + } + + void CreateTexture() + { + if (_renderTexture != null) + return; + + _renderTexture = new RenderTexture(_width, _height, 24, RenderTextureFormat.ARGB32) + { + antiAliasing = 1, + filterMode = FilterMode.Bilinear, + anisoLevel = 0, + useMipMap = false + }; + this._image.texture = new NTexture(_renderTexture); + this._image.blendMode = BlendMode.Off; + } + + void DestroyTexture() + { + if (_renderTexture != null) + { + Object.Destroy(_renderTexture); + _renderTexture = null; + this._image.texture = null; + } + } + + void OnAddedToStage() + { + if (_renderTexture == null) + CreateTexture(); + + Timers.inst.AddUpdate(this.Render); + _camera.gameObject.SetActive(true); + + Render(); + } + + void OnRemoveFromStage() + { + if (!_cacheTexture) + DestroyTexture(); + + Timers.inst.Remove(this.Render); + _camera.gameObject.SetActive(false); + } + + void Render(object param = null) + { + if (_rotating != 0 && this.modelRoot != null) + { + Vector3 localRotation = this.modelRoot.localRotation.eulerAngles; + localRotation.y += _rotating; + this.modelRoot.localRotation = Quaternion.Euler(localRotation); + } + + SetLayer(this._root.gameObject, RENDER_LAYER); + + _camera.targetTexture = this._renderTexture; + RenderTexture old = RenderTexture.active; + RenderTexture.active = this._renderTexture; + GL.Clear(true, true, Color.clear); + _camera.Render(); + RenderTexture.active = old; + + SetLayer(this._root.gameObject, HIDDEN_LAYER); + } + + void SetLayer(GameObject go, int layer) + { + Transform[] transforms = go.GetComponentsInChildren(true); + foreach (Transform t in transforms) + { + t.gameObject.layer = layer; + } + } } \ No newline at end of file diff --git a/Assets/Examples/RenderTexture/RenderTextureMain.cs b/Assets/Examples/RenderTexture/RenderTextureMain.cs index 2e55c4a3..fbfc24f3 100644 --- a/Assets/Examples/RenderTexture/RenderTextureMain.cs +++ b/Assets/Examples/RenderTexture/RenderTextureMain.cs @@ -1,28 +1,28 @@ -using UnityEngine; -using FairyGUI; - -public class RenderTextureMain : MonoBehaviour -{ - GComponent _mainView; - Window3 _testWin; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _testWin = new Window3(); - - _mainView.GetChild("n2").onClick.Add(() => { _testWin.Show(); }); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class RenderTextureMain : MonoBehaviour +{ + GComponent _mainView; + Window3 _testWin; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _testWin = new Window3(); + + _mainView.GetChild("n2").onClick.Add(() => { _testWin.Show(); }); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/RenderTexture/Window3.cs b/Assets/Examples/RenderTexture/Window3.cs index d2ec1548..9180c2a2 100644 --- a/Assets/Examples/RenderTexture/Window3.cs +++ b/Assets/Examples/RenderTexture/Window3.cs @@ -1,52 +1,52 @@ -using System; -using System.Collections.Generic; -using FairyGUI; -using UnityEngine; - -public class Window3 : Window -{ - RenderImage _renderImage; - - public Window3() - { - } - - protected override void OnInit() - { - this.contentPane = UIPackage.CreateObject("RenderTexture", "TestWin").asCom; - this.SetXY(200, 50); - - _renderImage = new RenderImage(contentPane.GetChild("holder").asGraph); - //RenderImage是不透明的,可以设置最多两张图片作为背景图 - _renderImage.SetBackground(contentPane.GetChild("frame").asCom.GetChild("n0"), contentPane.GetChild("n20")); - - contentPane.GetChild("btnLeft").onTouchBegin.Add(__clickLeft); - contentPane.GetChild("btnRight").onTouchBegin.Add(__clickRight); - } - - override protected void OnShown() - { - _renderImage.LoadModel("Role/npc"); - _renderImage.modelRoot.localPosition = new Vector3(0, -1.0f, 5f); - _renderImage.modelRoot.localScale = new Vector3(1, 1, 1); - _renderImage.modelRoot.localRotation = Quaternion.Euler(0, 120, 0); - } - - void __clickLeft() - { - _renderImage.StartRotate(-2); - Stage.inst.onTouchEnd.Add(__touchEnd); - } - - void __clickRight() - { - _renderImage.StartRotate(2); - Stage.inst.onTouchEnd.Add(__touchEnd); - } - - void __touchEnd() - { - _renderImage.StopRotate(); - Stage.inst.onTouchEnd.Remove(__touchEnd); - } -} +using System; +using System.Collections.Generic; +using FairyGUI; +using UnityEngine; + +public class Window3 : Window +{ + RenderImage _renderImage; + + public Window3() + { + } + + protected override void OnInit() + { + this.contentPane = UIPackage.CreateObject("RenderTexture", "TestWin").asCom; + this.SetXY(200, 50); + + _renderImage = new RenderImage(contentPane.GetChild("holder").asGraph); + //RenderImage是不透明的,可以设置最多两张图片作为背景图 + _renderImage.SetBackground(contentPane.GetChild("frame").asCom.GetChild("n0"), contentPane.GetChild("n20")); + + contentPane.GetChild("btnLeft").onTouchBegin.Add(__clickLeft); + contentPane.GetChild("btnRight").onTouchBegin.Add(__clickRight); + } + + override protected void OnShown() + { + _renderImage.LoadModel("Role/npc"); + _renderImage.modelRoot.localPosition = new Vector3(0, -1.0f, 5f); + _renderImage.modelRoot.localScale = new Vector3(1, 1, 1); + _renderImage.modelRoot.localRotation = Quaternion.Euler(0, 120, 0); + } + + void __clickLeft() + { + _renderImage.StartRotate(-2); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + + void __clickRight() + { + _renderImage.StartRotate(2); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + + void __touchEnd() + { + _renderImage.StopRotate(); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } +} diff --git a/Assets/Examples/ScrollPane/ScrollPaneMain.cs b/Assets/Examples/ScrollPane/ScrollPaneMain.cs index 22daf45f..ee947d93 100644 --- a/Assets/Examples/ScrollPane/ScrollPaneMain.cs +++ b/Assets/Examples/ScrollPane/ScrollPaneMain.cs @@ -1,113 +1,113 @@ -using UnityEngine; -using FairyGUI; - -public class ScrollPaneMain : MonoBehaviour -{ - GComponent _mainView; - GList _list; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - } - - void Start() - { - _mainView = this.GetComponent().ui; - - _list = _mainView.GetChild("list").asList; - _list.itemRenderer = RenderListItem; - _list.SetVirtual(); - _list.numItems = 1000; - _list.onTouchBegin.Add(OnClickList); - - _mainView.GetChild("box").asCom.onDrop.Add(OnDrop); - - LongPressGesture gesture = new LongPressGesture(_list); - gesture.once = true; - gesture.trigger = 1f; - gesture.onAction.Add(OnLongPress); - } - - void RenderListItem(int index, GObject obj) - { - GButton item = obj.asButton; - item.title = "Item " + index; - item.scrollPane.posX = 0; //reset scroll pos - - //Be carefull, RenderListItem is calling repeatedly, dont call 'Add' here! - //请注意,RenderListItem是重复调用的,不要使用Add增加侦听! - item.GetChild("b0").onClick.Set(OnClickStick); - item.GetChild("b1").onClick.Set(OnClickDelete); - } - - void OnClickList(EventContext context) - { - //find out if there is an item in edit status - //查找是否有项目处于编辑状态 - int cnt = _list.numChildren; - for (int i = 0; i < cnt; i++) - { - GButton item = _list.GetChildAt(i).asButton; - if (item.scrollPane.posX != 0) - { - //Check if clicked on the button - if (item.GetChild("b0").asButton.IsAncestorOf(GRoot.inst.touchTarget) - || item.GetChild("b1").asButton.IsAncestorOf(GRoot.inst.touchTarget)) - { - return; - } - item.scrollPane.SetPosX(0, true); - //avoid scroll pane default behavior - //取消滚动面板可能发生的拉动。 - item.scrollPane.CancelDragging(); - _list.scrollPane.CancelDragging(); - break; - } - } - } - - void OnLongPress(EventContext context) - { - //find out which item is under finger - //逐层往上知道查到点击了那个item - GObject obj = GRoot.inst.touchTarget; - GObject p = obj.parent; - while (p != null) - { - if (p == _list) - break; - - p = p.parent; - } - - if (p == null) - return; - Debug.Log(obj.text); - DragDropManager.inst.StartDrag(obj, obj.icon, obj.text); - } - - void OnDrop(EventContext context) - { - _mainView.GetChild("txt").text = "Drop " + (string)context.data; - } - - void OnClickStick(EventContext context) - { - _mainView.GetChild("txt").text = "Stick " + (((GObject)context.sender).parent).text; - } - - void OnClickDelete(EventContext context) - { - _mainView.GetChild("txt").text = "Delete " + (((GObject)context.sender).parent).text; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class ScrollPaneMain : MonoBehaviour +{ + GComponent _mainView; + GList _list; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + } + + void Start() + { + _mainView = this.GetComponent().ui; + + _list = _mainView.GetChild("list").asList; + _list.itemRenderer = RenderListItem; + _list.SetVirtual(); + _list.numItems = 1000; + _list.onTouchBegin.Add(OnClickList); + + _mainView.GetChild("box").asCom.onDrop.Add(OnDrop); + + LongPressGesture gesture = new LongPressGesture(_list); + gesture.once = true; + gesture.trigger = 1f; + gesture.onAction.Add(OnLongPress); + } + + void RenderListItem(int index, GObject obj) + { + GButton item = obj.asButton; + item.title = "Item " + index; + item.scrollPane.posX = 0; //reset scroll pos + + //Be carefull, RenderListItem is calling repeatedly, dont call 'Add' here! + //请注意,RenderListItem是重复调用的,不要使用Add增加侦听! + item.GetChild("b0").onClick.Set(OnClickStick); + item.GetChild("b1").onClick.Set(OnClickDelete); + } + + void OnClickList(EventContext context) + { + //find out if there is an item in edit status + //查找是否有项目处于编辑状态 + int cnt = _list.numChildren; + for (int i = 0; i < cnt; i++) + { + GButton item = _list.GetChildAt(i).asButton; + if (item.scrollPane.posX != 0) + { + //Check if clicked on the button + if (item.GetChild("b0").asButton.IsAncestorOf(GRoot.inst.touchTarget) + || item.GetChild("b1").asButton.IsAncestorOf(GRoot.inst.touchTarget)) + { + return; + } + item.scrollPane.SetPosX(0, true); + //avoid scroll pane default behavior + //取消滚动面板可能发生的拉动。 + item.scrollPane.CancelDragging(); + _list.scrollPane.CancelDragging(); + break; + } + } + } + + void OnLongPress(EventContext context) + { + //find out which item is under finger + //逐层往上知道查到点击了那个item + GObject obj = GRoot.inst.touchTarget; + GObject p = obj.parent; + while (p != null) + { + if (p == _list) + break; + + p = p.parent; + } + + if (p == null) + return; + Debug.Log(obj.text); + DragDropManager.inst.StartDrag(obj, obj.icon, obj.text); + } + + void OnDrop(EventContext context) + { + _mainView.GetChild("txt").text = "Drop " + (string)context.data; + } + + void OnClickStick(EventContext context) + { + _mainView.GetChild("txt").text = "Stick " + (((GObject)context.sender).parent).text; + } + + void OnClickDelete(EventContext context) + { + _mainView.GetChild("txt").text = "Delete " + (((GObject)context.sender).parent).text; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/Transition/TransitionMain.cs b/Assets/Examples/Transition/TransitionMain.cs index 468c6383..cd4fdf39 100644 --- a/Assets/Examples/Transition/TransitionMain.cs +++ b/Assets/Examples/Transition/TransitionMain.cs @@ -1,105 +1,105 @@ -using UnityEngine; -using FairyGUI; - -public class TransitionMain : MonoBehaviour -{ - GComponent _mainView; - GGroup _btnGroup; - GComponent _g1; - GComponent _g2; - GComponent _g3; - GComponent _g4; - GComponent _g5; - GComponent _g6; - - float _startValue; - float _endValue; - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _btnGroup = _mainView.GetChild("g0").asGroup; - - _g1 = UIPackage.CreateObject("Transition", "BOSS").asCom; - _g2 = UIPackage.CreateObject("Transition", "BOSS_SKILL").asCom; - _g3 = UIPackage.CreateObject("Transition", "TRAP").asCom; - - _g4 = UIPackage.CreateObject("Transition", "GoodHit").asCom; - _g5 = UIPackage.CreateObject("Transition", "PowerUp").asCom; - _g5.GetTransition("t0").SetHook("play_num_now", __playNum); - - _g6 = UIPackage.CreateObject("Transition", "PathDemo").asCom; - - _mainView.GetChild("btn0").onClick.Add(() => { __play(_g1); }); - _mainView.GetChild("btn1").onClick.Add(() => { __play(_g2); }); - _mainView.GetChild("btn2").onClick.Add(() => { __play(_g3); }); - _mainView.GetChild("btn3").onClick.Add(__play4); - _mainView.GetChild("btn4").onClick.Add(__play5); - _mainView.GetChild("btn5").onClick.Add(() => { __play(_g6); }); - } - - void __play(GComponent target) - { - _btnGroup.visible = false; - GRoot.inst.AddChild(target); - Transition t = target.GetTransition("t0"); - - t.Play(() => - { - _btnGroup.visible = true; - GRoot.inst.RemoveChild(target); - }); - } - - void __play4() - { - _btnGroup.visible = false; - _g4.x = GRoot.inst.width - _g4.width - 20; - _g4.y = 100; - GRoot.inst.AddChild(_g4); - Transition t = _g4.GetTransition("t0"); - t.Play(3, 0, () => - { - _btnGroup.visible = true; - GRoot.inst.RemoveChild(_g4); - }); - } - - void __play5() - { - _btnGroup.visible = false; - _g5.x = 20; - _g5.y = GRoot.inst.height - _g5.height - 100; - GRoot.inst.AddChild(_g5); - Transition t = _g5.GetTransition("t0"); - _startValue = 10000; - int add = UnityEngine.Random.Range(1000, 3000); - _endValue = _startValue + add; - _g5.GetChild("value").text = "" + _startValue; - _g5.GetChild("add_value").text = "" + add; - t.Play(() => - { - _btnGroup.visible = true; - GRoot.inst.RemoveChild(_g5); - }); - } - - void __playNum() - { - GTween.To(_startValue, _endValue, 0.3f).SetEase(EaseType.Linear) - .OnUpdate((GTweener tweener) => { _g5.GetChild("value").text = "" + Mathf.Floor(tweener.value.x); }); - - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class TransitionMain : MonoBehaviour +{ + GComponent _mainView; + GGroup _btnGroup; + GComponent _g1; + GComponent _g2; + GComponent _g3; + GComponent _g4; + GComponent _g5; + GComponent _g6; + + float _startValue; + float _endValue; + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _btnGroup = _mainView.GetChild("g0").asGroup; + + _g1 = UIPackage.CreateObject("Transition", "BOSS").asCom; + _g2 = UIPackage.CreateObject("Transition", "BOSS_SKILL").asCom; + _g3 = UIPackage.CreateObject("Transition", "TRAP").asCom; + + _g4 = UIPackage.CreateObject("Transition", "GoodHit").asCom; + _g5 = UIPackage.CreateObject("Transition", "PowerUp").asCom; + _g5.GetTransition("t0").SetHook("play_num_now", __playNum); + + _g6 = UIPackage.CreateObject("Transition", "PathDemo").asCom; + + _mainView.GetChild("btn0").onClick.Add(() => { __play(_g1); }); + _mainView.GetChild("btn1").onClick.Add(() => { __play(_g2); }); + _mainView.GetChild("btn2").onClick.Add(() => { __play(_g3); }); + _mainView.GetChild("btn3").onClick.Add(__play4); + _mainView.GetChild("btn4").onClick.Add(__play5); + _mainView.GetChild("btn5").onClick.Add(() => { __play(_g6); }); + } + + void __play(GComponent target) + { + _btnGroup.visible = false; + GRoot.inst.AddChild(target); + Transition t = target.GetTransition("t0"); + + t.Play(() => + { + _btnGroup.visible = true; + GRoot.inst.RemoveChild(target); + }); + } + + void __play4() + { + _btnGroup.visible = false; + _g4.x = GRoot.inst.width - _g4.width - 20; + _g4.y = 100; + GRoot.inst.AddChild(_g4); + Transition t = _g4.GetTransition("t0"); + t.Play(3, 0, () => + { + _btnGroup.visible = true; + GRoot.inst.RemoveChild(_g4); + }); + } + + void __play5() + { + _btnGroup.visible = false; + _g5.x = 20; + _g5.y = GRoot.inst.height - _g5.height - 100; + GRoot.inst.AddChild(_g5); + Transition t = _g5.GetTransition("t0"); + _startValue = 10000; + int add = UnityEngine.Random.Range(1000, 3000); + _endValue = _startValue + add; + _g5.GetChild("value").text = "" + _startValue; + _g5.GetChild("add_value").text = "" + add; + t.Play(() => + { + _btnGroup.visible = true; + GRoot.inst.RemoveChild(_g5); + }); + } + + void __playNum() + { + GTween.To(_startValue, _endValue, 0.3f).SetEase(EaseType.Linear) + .OnUpdate((GTweener tweener) => { _g5.GetChild("value").text = "" + Mathf.Floor(tweener.value.x); }); + + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/TreeView/TreeViewMain.cs b/Assets/Examples/TreeView/TreeViewMain.cs index 819552ad..02959d9e 100644 --- a/Assets/Examples/TreeView/TreeViewMain.cs +++ b/Assets/Examples/TreeView/TreeViewMain.cs @@ -1,92 +1,92 @@ -using UnityEngine; -using FairyGUI; - -public class TreeViewMain : MonoBehaviour -{ - GComponent _mainView; - GTree _tree1; - GTree _tree2; - string _fileURL; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - } - - void Start() - { - _mainView = this.GetComponent().ui; - - _fileURL = "ui://TreeView/file"; - - _tree1 = _mainView.GetChild("tree").asTree; - _tree1.onClickItem.Add(__clickNode); - _tree2 = _mainView.GetChild("tree2").asTree; - _tree2.onClickItem.Add(__clickNode); - _tree2.treeNodeRender = RenderTreeNode; - - GTreeNode topNode = new GTreeNode(true); - topNode.data = "I'm a top node"; - _tree2.rootNode.AddChild(topNode); - for (int i = 0; i < 5; i++) - { - GTreeNode node = new GTreeNode(false); - node.data = "Hello " + i; - topNode.AddChild(node); - } - - GTreeNode aFolderNode = new GTreeNode(true); - aFolderNode.data = "A folder node"; - topNode.AddChild(aFolderNode); - for (int i = 0; i < 5; i++) - { - GTreeNode node = new GTreeNode(false); - node.data = "Good " + i; - aFolderNode.AddChild(node); - } - - for (int i = 0; i < 3; i++) - { - GTreeNode node = new GTreeNode(false); - node.data = "World " + i; - topNode.AddChild(node); - } - - GTreeNode anotherTopNode = new GTreeNode(false); - anotherTopNode.data = new string[] { "I'm a top node too", "ui://TreeView/heart" }; - _tree2.rootNode.AddChild(anotherTopNode); - } - - void RenderTreeNode(GTreeNode node, GComponent obj) - { - if (node.isFolder) - { - obj.text = (string)node.data; - } - else if (node.data is string[]) - { - obj.icon = ((string[])node.data)[1]; - obj.text = ((string[])node.data)[0]; - } - else - { - obj.icon = _fileURL; - obj.text = (string)node.data; - } - } - - void __clickNode(EventContext context) - { - GTreeNode node = ((GObject)context.data).treeNode; - Debug.Log(node.text); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class TreeViewMain : MonoBehaviour +{ + GComponent _mainView; + GTree _tree1; + GTree _tree2; + string _fileURL; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + } + + void Start() + { + _mainView = this.GetComponent().ui; + + _fileURL = "ui://TreeView/file"; + + _tree1 = _mainView.GetChild("tree").asTree; + _tree1.onClickItem.Add(__clickNode); + _tree2 = _mainView.GetChild("tree2").asTree; + _tree2.onClickItem.Add(__clickNode); + _tree2.treeNodeRender = RenderTreeNode; + + GTreeNode topNode = new GTreeNode(true); + topNode.data = "I'm a top node"; + _tree2.rootNode.AddChild(topNode); + for (int i = 0; i < 5; i++) + { + GTreeNode node = new GTreeNode(false); + node.data = "Hello " + i; + topNode.AddChild(node); + } + + GTreeNode aFolderNode = new GTreeNode(true); + aFolderNode.data = "A folder node"; + topNode.AddChild(aFolderNode); + for (int i = 0; i < 5; i++) + { + GTreeNode node = new GTreeNode(false); + node.data = "Good " + i; + aFolderNode.AddChild(node); + } + + for (int i = 0; i < 3; i++) + { + GTreeNode node = new GTreeNode(false); + node.data = "World " + i; + topNode.AddChild(node); + } + + GTreeNode anotherTopNode = new GTreeNode(false); + anotherTopNode.data = new string[] { "I'm a top node too", "ui://TreeView/heart" }; + _tree2.rootNode.AddChild(anotherTopNode); + } + + void RenderTreeNode(GTreeNode node, GComponent obj) + { + if (node.isFolder) + { + obj.text = (string)node.data; + } + else if (node.data is string[]) + { + obj.icon = ((string[])node.data)[1]; + obj.text = ((string[])node.data)[0]; + } + else + { + obj.icon = _fileURL; + obj.text = (string)node.data; + } + } + + void __clickNode(EventContext context) + { + GTreeNode node = ((GObject)context.data).treeNode; + Debug.Log(node.text); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/TurnCard/Card.cs b/Assets/Examples/TurnCard/Card.cs index 4a094fdb..508a20bf 100644 --- a/Assets/Examples/TurnCard/Card.cs +++ b/Assets/Examples/TurnCard/Card.cs @@ -1,73 +1,73 @@ -using FairyGUI; - -public class Card : GButton -{ - GObject _back; - GObject _front; - - public override void ConstructFromXML(FairyGUI.Utils.XML xml) - { - base.ConstructFromXML(xml); - - _back = GetChild("n0"); - _front = GetChild("icon"); - _front.visible = false; - } - - public bool opened - { - get - { - return _front.visible; - } - - set - { - GTween.Kill(this); - - _front.visible = value; - _back.visible = !value; - } - } - - public void SetPerspective() - { - _front.displayObject.perspective = true; - _back.displayObject.perspective = true; - } - - public void Turn() - { - if (GTween.IsTweening(this)) - return; - - bool toOpen = !_front.visible; - GTween.To(0, 180, 0.8f).SetTarget(this).SetEase(EaseType.QuadOut).OnUpdate(TurnInTween).SetUserData(toOpen); - } - - void TurnInTween(GTweener tweener) - { - bool toOpen = (bool)tweener.userData; - float v = tweener.value.x; - if (toOpen) - { - _back.rotationY = v; - _front.rotationY = -180 + v; - if (v > 90) - { - _front.visible = true; - _back.visible = false; - } - } - else - { - _back.rotationY = -180 + v; - _front.rotationY = v; - if (v > 90) - { - _front.visible = false; - _back.visible = true; - } - } - } +using FairyGUI; + +public class Card : GButton +{ + GObject _back; + GObject _front; + + public override void ConstructFromXML(FairyGUI.Utils.XML xml) + { + base.ConstructFromXML(xml); + + _back = GetChild("n0"); + _front = GetChild("icon"); + _front.visible = false; + } + + public bool opened + { + get + { + return _front.visible; + } + + set + { + GTween.Kill(this); + + _front.visible = value; + _back.visible = !value; + } + } + + public void SetPerspective() + { + _front.displayObject.perspective = true; + _back.displayObject.perspective = true; + } + + public void Turn() + { + if (GTween.IsTweening(this)) + return; + + bool toOpen = !_front.visible; + GTween.To(0, 180, 0.8f).SetTarget(this).SetEase(EaseType.QuadOut).OnUpdate(TurnInTween).SetUserData(toOpen); + } + + void TurnInTween(GTweener tweener) + { + bool toOpen = (bool)tweener.userData; + float v = tweener.value.x; + if (toOpen) + { + _back.rotationY = v; + _front.rotationY = -180 + v; + if (v > 90) + { + _front.visible = true; + _back.visible = false; + } + } + else + { + _back.rotationY = -180 + v; + _front.rotationY = v; + if (v > 90) + { + _front.visible = false; + _back.visible = true; + } + } + } } \ No newline at end of file diff --git a/Assets/Examples/TurnCard/TurnCardMain.cs b/Assets/Examples/TurnCard/TurnCardMain.cs index 550cfa9a..6cba9217 100644 --- a/Assets/Examples/TurnCard/TurnCardMain.cs +++ b/Assets/Examples/TurnCard/TurnCardMain.cs @@ -1,45 +1,45 @@ -using UnityEngine; -using FairyGUI; - -public class TurnCardMain : MonoBehaviour -{ - GComponent _mainView; - Card _c0; - Card _c1; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - UIPackage.AddPackage("UI/TurnCard"); - UIObjectFactory.SetPackageItemExtension("ui://TurnCard/CardComponent", typeof(Card)); - } - - void Start() - { - _mainView = this.GetComponent().ui; - - _c0 = (Card)_mainView.GetChild("c0"); - - _c1 = (Card)_mainView.GetChild("c1"); - _c1.SetPerspective(); - - _c0.onClick.Add(__clickCard); - _c1.onClick.Add(__clickCard); - } - - void __clickCard(EventContext context) - { - Card card = (Card)context.sender; - card.Turn(); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class TurnCardMain : MonoBehaviour +{ + GComponent _mainView; + Card _c0; + Card _c1; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + UIPackage.AddPackage("UI/TurnCard"); + UIObjectFactory.SetPackageItemExtension("ui://TurnCard/CardComponent", typeof(Card)); + } + + void Start() + { + _mainView = this.GetComponent().ui; + + _c0 = (Card)_mainView.GetChild("c0"); + + _c1 = (Card)_mainView.GetChild("c1"); + _c1.SetPerspective(); + + _c0.onClick.Add(__clickCard); + _c1.onClick.Add(__clickCard); + } + + void __clickCard(EventContext context) + { + Card card = (Card)context.sender; + card.Turn(); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/TurnPage/BookPage.cs b/Assets/Examples/TurnPage/BookPage.cs index f96dde44..f975e840 100644 --- a/Assets/Examples/TurnPage/BookPage.cs +++ b/Assets/Examples/TurnPage/BookPage.cs @@ -1,46 +1,46 @@ -using UnityEngine; -using FairyGUI; - -class BookPage : GComponent -{ - Controller _style; - GoWrapper _modelWrapper; - GObject _pageNumber; - - public override void ConstructFromXML(FairyGUI.Utils.XML xml) - { - base.ConstructFromXML(xml); - - _style = GetController("style"); - - _pageNumber = GetChild("pn"); - - _modelWrapper = new GoWrapper(); - GetChild("model").asGraph.SetNativeObject(_modelWrapper); - } - - public void render(int pageIndex) - { - _pageNumber.text = (pageIndex + 1).ToString(); - - if (pageIndex == 0) - _style.selectedIndex = 0; //pic page - else if (pageIndex == 2) - { - if (_modelWrapper.wrapTarget == null) - { - Object prefab = Resources.Load("Role/npc3"); - GameObject go = (GameObject)Object.Instantiate(prefab); - go.transform.localPosition = new Vector3(0, 0, 1000); - go.transform.localScale = new Vector3(120, 120, 120); - go.transform.localEulerAngles = new Vector3(0, 100, 0); - - _modelWrapper.SetWrapTarget(go, true); - } - - _style.selectedIndex = 2; //show a model - } - else - _style.selectedIndex = 1; //empty page - } -} +using UnityEngine; +using FairyGUI; + +class BookPage : GComponent +{ + Controller _style; + GoWrapper _modelWrapper; + GObject _pageNumber; + + public override void ConstructFromXML(FairyGUI.Utils.XML xml) + { + base.ConstructFromXML(xml); + + _style = GetController("style"); + + _pageNumber = GetChild("pn"); + + _modelWrapper = new GoWrapper(); + GetChild("model").asGraph.SetNativeObject(_modelWrapper); + } + + public void render(int pageIndex) + { + _pageNumber.text = (pageIndex + 1).ToString(); + + if (pageIndex == 0) + _style.selectedIndex = 0; //pic page + else if (pageIndex == 2) + { + if (_modelWrapper.wrapTarget == null) + { + Object prefab = Resources.Load("Role/npc3"); + GameObject go = (GameObject)Object.Instantiate(prefab); + go.transform.localPosition = new Vector3(0, 0, 1000); + go.transform.localScale = new Vector3(120, 120, 120); + go.transform.localEulerAngles = new Vector3(0, 100, 0); + + _modelWrapper.SetWrapTarget(go, true); + } + + _style.selectedIndex = 2; //show a model + } + else + _style.selectedIndex = 1; //empty page + } +} diff --git a/Assets/Examples/TurnPage/FairyBook.cs b/Assets/Examples/TurnPage/FairyBook.cs index 6b47225c..7bb6348a 100644 --- a/Assets/Examples/TurnPage/FairyBook.cs +++ b/Assets/Examples/TurnPage/FairyBook.cs @@ -1,1225 +1,1225 @@ -using System; -using FairyGUI; -using FairyGUI.Utils; -using UnityEngine; - -/// -/// Achieving the effect of turning over books. Use virtual mechanism to support unlimited pages. Support covers. -/// -public class FairyBook : GComponent -{ - /// - /// - /// - /// - /// - public delegate void PageRenderer(int index, GComponent page); - - /// - /// - /// - public PageRenderer pageRenderer; - - /// - /// - /// - public static float EffectDuration = 0.5f; - - /// - /// - /// - public enum Paper - { - Soft, - Hard - } - - public enum CoverType - { - Front, - Back - } - - enum CoverStatus - { - Hidden, - ShowingFront, - ShowingBack - } - - enum CoverTurningOp - { - None, - ShowFront, - HideFront, - ShowBack, - HideBack - } - - enum Corner - { - INVALID, - TL, - BL, - TR, - BR - } - - GComponent _pagesContainer; - string _pageResource; - int _pageWidth; - int _pageHeight; - - int _pageCount; - int _currentPage; - Paper _paper; - - int _turningTarget; - float _turningAmount; - CoverTurningOp _coverTurningOp; - GPath _turningPath; - - GComponent[] _objects; - GGraph _mask1; - GGraph _mask2; - GObject _softShadow; - int[] _objectIndice; - int[] _objectNewIndice; - - Corner _draggingCorner; - Vector2 _dragPoint; - float _touchDownTime; - - GComponent _frontCover; - GComponent _backCover; - Vector2 _frontCoverPos; - Vector2 _backCoverPos; - CoverStatus _coverStatus; - - EventListener _onTurnComplete; - - public override void ConstructFromXML(XML xml) - { - base.ConstructFromXML(xml); - - _pagesContainer = GetChild("pages").asCom; - if (_pagesContainer == null) - { - Debug.LogError("Not a valid book resource"); - return; - } - - GComponent obj1 = _pagesContainer.GetChild("left").asCom; - GComponent obj2 = _pagesContainer.GetChild("right").asCom; - if (obj1 == null || obj2 == null || obj1.resourceURL != obj2.resourceURL - || obj1.width != obj2.width || obj2.x != obj1.x + obj1.width) - { - Debug.LogError("Not a valid book resource"); - return; - } - - obj1.displayObject.home = this.displayObject.cachedTransform; - obj2.displayObject.home = this.displayObject.cachedTransform; - _pagesContainer.RemoveChild(obj1); - _pagesContainer.RemoveChild(obj2); - - _frontCover = GetChild("frontCover") as GComponent; - if (_frontCover != null) - _frontCoverPos = _frontCover.position; - _backCover = GetChild("backCover") as GComponent; - if (_backCover != null) - _backCoverPos = _backCover.position; - - _objects = new GComponent[4] { obj1, obj2, null, null }; - _objectIndice = new int[4] { -1, -1, -1, -1 }; - _objectNewIndice = new int[4]; - _turningTarget = -1; - _currentPage = -1; - - _pageWidth = (int)obj1.width; - _pageHeight = (int)obj1.height; - _pageResource = obj1.resourceURL; - - _mask1 = new GGraph(); - _mask1.displayObject.home = this.displayObject.cachedTransform; - _mask1.SetSize(_pageWidth, _pageHeight); - - _mask2 = new GGraph(); - _mask2.displayObject.home = this.displayObject.cachedTransform; - _mask2.SetSize(_pageWidth, _pageHeight); - - SetupHotspot(GetChild("hotspot_tl"), Corner.TL); - SetupHotspot(GetChild("hotspot_bl"), Corner.BL); - SetupHotspot(GetChild("hotspot_tr"), Corner.TR); - SetupHotspot(GetChild("hotspot_br"), Corner.BR); - } - - public override void Dispose() - { - for (int i = 0; i < 4; i++) - { - if (_objects[i] != null) - _objects[i].Dispose(); - - } - _mask1.Dispose(); - _mask2.Dispose(); - if (_softShadow != null) - _softShadow.Dispose(); - - base.Dispose(); - } - - /// - /// - /// - public EventListener onTurnComplete - { - get { return _onTurnComplete ?? (_onTurnComplete = new EventListener(this, "onTurnComplete")); } - } - - /// - /// - /// - /// - public void SetSoftShadowResource(string res) - { - _softShadow = UIPackage.CreateObjectFromURL(res); - _softShadow.height = Mathf.Sqrt(Mathf.Pow(_pageWidth, 2) + Mathf.Pow(_pageHeight, 2)) + 60; - _softShadow.displayObject.home = this.displayObject.cachedTransform; - _softShadow.sortingOrder = int.MaxValue; - } - - /// - /// - /// - public Paper pageSoftness - { - get { return _paper; } - set { _paper = value; } - } - - /// - /// - /// - public int pageCount - { - get { return _pageCount; } - set - { - if (_pageCount % 2 != 0) - throw new System.Exception("Page count must be even!"); - - _pageCount = value; - } - } - - /// - /// - /// - public int currentPage - { - get { return _currentPage; } - set - { - if (value < 0 || value > _pageCount - 1) - throw new Exception("Page index out of bounds: " + value); - - if (_currentPage != value) - { - GTween.Kill(this, true); - - _currentPage = value; - _coverStatus = CoverStatus.Hidden; - - RenderPages(); - } - } - } - - /// - /// - /// - /// - public void TurnTo(int pageIndex) - { - if (pageIndex < 0 || pageIndex > _pageCount - 1) - throw new Exception("Page index out of bounds: " + pageIndex); - - GTween.Kill(this, true); - - if (_coverStatus == CoverStatus.ShowingFront) - { - _coverTurningOp = CoverTurningOp.HideFront; - _draggingCorner = Corner.BR; - } - else if (_coverStatus == CoverStatus.ShowingBack) - { - _coverTurningOp = CoverTurningOp.HideBack; - _draggingCorner = Corner.BL; - } - - int tt1 = _currentPage; - if (_currentPage % 2 == 0) - tt1--; - int tt2 = pageIndex; - if (pageIndex % 2 == 0) - tt2--; - if (tt1 == tt2) - { - _currentPage = pageIndex; - _turningTarget = -1; - } - else - { - _turningTarget = pageIndex; - if (_turningTarget < _currentPage) - _draggingCorner = Corner.BL; - else - _draggingCorner = Corner.BR; - } - - if (_draggingCorner == Corner.INVALID) - return; - - StartTween(); - } - - /// - /// - /// - public void TurnNext() - { - GTween.Kill(this, true); - - if (isCoverShowing(CoverType.Front)) - TurnTo(0); - else if (_currentPage == _pageCount - 1) - ShowCover(CoverType.Back, true); - else if (_currentPage % 2 == 0) - TurnTo(_currentPage + 1); - else - TurnTo(_currentPage + 2); - } - - /// - /// - /// - public void TurnPrevious() - { - GTween.Kill(this, true); - - if (isCoverShowing(CoverType.Back)) - TurnTo(_pageCount - 1); - else if (_currentPage == 0) - ShowCover(CoverType.Front, true); - else if (_currentPage % 2 == 0) - TurnTo(_currentPage - 2); - else - TurnTo(_currentPage - 1); - } - - /// - /// - /// - /// - /// - public void ShowCover(CoverType cover, bool turnEffect) - { - GTween.Kill(this, true); - - if (_frontCover == null) - return; - - if (turnEffect) - { - if (cover == CoverType.Front) - { - if (_coverStatus == CoverStatus.ShowingFront) - return; - - _coverTurningOp = CoverTurningOp.ShowFront; - _draggingCorner = Corner.BL; - _currentPage = 0; - } - else - { - if (_coverStatus == CoverStatus.ShowingBack) - return; - - _coverTurningOp = CoverTurningOp.ShowBack; - _draggingCorner = Corner.BR; - _currentPage = _pageCount - 1; - } - - StartTween(); - } - else - { - if (cover == CoverType.Front) - { - _currentPage = 0; - _coverStatus = CoverStatus.ShowingFront; - } - else - { - _currentPage = _pageCount - 1; - _coverStatus = CoverStatus.ShowingBack; - } - RenderPages(); - } - } - - /// - /// - /// - /// - /// - public bool isCoverShowing(CoverType cover) - { - return cover == CoverType.Front ? (_coverStatus == CoverStatus.ShowingFront) : (_coverStatus == CoverStatus.ShowingBack); - } - - void StartTween() - { - _turningAmount = 0; - RenderPages(); - Vector2 source = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None); - Vector2 target; - if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL) - target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None); - else - target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None); - - if (_turningPath == null) - _turningPath = new GPath(); - Vector2 mid = new Vector2(source.x + (target.x - source.x) / 2, target.y - 50); - _turningPath.Create(new GPathPoint(source), new GPathPoint(mid), new GPathPoint(target)); - GTween.To(source, target, EffectDuration).SetUserData(true).SetTarget(this) - .SetPath(_turningPath) - .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete); - } - - void OnTurnUpdate(GTweener tweener) - { - _dragPoint = tweener.value.vec2; - _turningAmount = _dragPoint.x / (_coverTurningOp != CoverTurningOp.None ? _frontCover.width * 2 : _pageWidth * 2); - if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR) - _turningAmount = 1 - _turningAmount; - PlayTurnEffect(); - } - - void OnTurnComplete(GTweener tweener) - { - bool suc = (bool)tweener.userData; - _draggingCorner = Corner.INVALID; - if (suc && _turningTarget != -1) - _currentPage = _turningTarget; - if (suc && _coverTurningOp != CoverTurningOp.None) - { - if (_coverTurningOp == CoverTurningOp.ShowFront) - _coverStatus = CoverStatus.ShowingFront; - else if (_coverTurningOp == CoverTurningOp.ShowBack) - _coverStatus = CoverStatus.ShowingBack; - else - _coverStatus = CoverStatus.Hidden; - } - _coverTurningOp = CoverTurningOp.None; - _turningTarget = -1; - - RenderPages(); - - DispatchEvent("onTurnComplete"); - } - - void PlayTurnEffect() - { - if (_coverTurningOp != CoverTurningOp.None) - PlayCoverEffect(); - - if (_turningTarget != -1) - { - if (_paper == Paper.Hard) - PlayHardEffect(); - else - PlaySoftEffect(); - } - } - - void PlayCoverEffect() - { - float amount = Mathf.Clamp01(_turningAmount); - float ratio; - bool isLeft; - GComponent turningObj = (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront) ? _frontCover : _backCover; - PolygonMesh mesh = GetHardMesh(turningObj); - - if (amount < 0.5f) - { - ratio = 1 - amount * 2; - isLeft = _coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideBack; - } - else - { - ratio = (amount - 0.5f) * 2; - isLeft = _coverTurningOp == CoverTurningOp.HideFront || _coverTurningOp == CoverTurningOp.ShowBack; - } - - if (turningObj == _frontCover) - SetCoverStatus(turningObj, CoverType.Front, !isLeft); - else - SetCoverStatus(turningObj, CoverType.Back, isLeft); - - mesh.points.Clear(); - mesh.texcoords.Clear(); - if (isLeft) - { - float topOffset = 1f / 8 * (1 - ratio); - float xOffset = 1 - ratio; - mesh.Add(new Vector2(xOffset, 1 + topOffset)); - mesh.Add(new Vector2(xOffset, -topOffset)); - mesh.Add(new Vector2(1, 0)); - mesh.Add(new Vector2(1, 1)); - } - else - { - float topOffset = 1f / 8 * (1 - ratio); - mesh.Add(new Vector2(0, 1)); - mesh.Add(new Vector2(0, 0)); - mesh.Add(new Vector2(ratio, -topOffset)); - mesh.Add(new Vector2(ratio, 1 + topOffset)); - } - - mesh.texcoords.AddRange(VertexBuffer.NormalizedUV); - } - - void PlayHardEffect() - { - float amount = Mathf.Clamp01(_turningAmount); - float ratio; - bool isLeft; - GComponent turningObj; - PolygonMesh mesh; - if (amount < 0.5f) - { - ratio = 1 - amount * 2; - isLeft = _turningTarget < _currentPage; - - turningObj = _objects[2]; - mesh = GetHardMesh(turningObj); - GetHardMesh(_objects[3]).points.Clear(); - } - else - { - ratio = (amount - 0.5f) * 2; - isLeft = _turningTarget > _currentPage; - - turningObj = _objects[3]; - mesh = GetHardMesh(turningObj); - GetHardMesh(_objects[2]).points.Clear(); - } - - mesh.points.Clear(); - mesh.texcoords.Clear(); - if (isLeft) - { - turningObj.x = 0; - - float topOffset = 1f / 8 * (1 - ratio); - float xOffset = 1 - ratio; - mesh.Add(new Vector2(xOffset, 1 + topOffset)); - mesh.Add(new Vector2(xOffset, -topOffset)); - mesh.Add(new Vector2(1, 0)); - mesh.Add(new Vector2(1, 1)); - } - else - { - turningObj.x = _pageWidth; - - float topOffset = 1f / 8 * (1 - ratio); - mesh.Add(new Vector2(0, 1)); - mesh.Add(new Vector2(0, 0)); - mesh.Add(new Vector2(ratio, -topOffset)); - mesh.Add(new Vector2(ratio, 1 + topOffset)); - } - - mesh.texcoords.AddRange(VertexBuffer.NormalizedUV); - } - - void FlipPoint(ref Vector2 pt, float w, float h) - { - switch (_draggingCorner) - { - case Corner.TL: - pt.x = w - pt.x; - pt.y = h - pt.y; - break; - case Corner.BL: - pt.x = w - pt.x; - break; - case Corner.TR: - pt.y = h - pt.y; - break; - } - } - - void PlaySoftEffect() - { - GComponent turningObj1 = _objects[2]; - GComponent turningObj2 = _objects[3]; - PolygonMesh mesh1 = GetSoftMesh(turningObj1); - PolygonMesh mesh2 = GetSoftMesh(turningObj2); - - /** - * a - * / \ - * f(0,0)------/ b--g(w,0) - * | / / | - * | / / | - * | c / | - * | \ / | - * | \ / | - * e(0,h)-----d--------h(w,h) - */ - Vector2 pa, pb, pc, pd, pe, pf, pg, ph; - float k, angle; - bool threePoints = false; - - pc = _dragPoint; - pe = new Vector2(0, _pageHeight); - pf = Vector2.zero; - pg = new Vector2(_pageWidth, 0); - ph = new Vector2(_pageWidth, _pageHeight); - - FlipPoint(ref pc, _pageWidth * 2, _pageHeight); - pc.x -= _pageWidth; - if (pc.x >= _pageWidth) - return; - - k = (ph.y - pc.y) / (ph.x - pc.x); - float k2 = 1 + Mathf.Pow(k, 2); - float min; - min = ph.x - _pageWidth * 2 / k2; - if (pc.x < min) - { - pc.x = min; - if (pc.x >= _pageWidth) - return; - pc.y = ph.y - k * (ph.x - pc.x); - } - - min = ph.x - (_pageWidth + _pageHeight * k) * 2 / k2; - if (pc.x < min) - { - pc.x = min; - if (pc.x >= _pageWidth) - return; - pc.y = ph.y - k * (ph.x - pc.x); - } - - angle = Mathf.Atan(k) * Mathf.Rad2Deg; - pd = new Vector2(_pageWidth - k2 * (ph.x - pc.x) / 2, _pageHeight); - pb = new Vector2(pd.x + _pageHeight * k, 0); - pa = new Vector2(); - - if (pb.x > _pageWidth) - { - pb.x = _pageWidth; - pa = new Vector2(_pageWidth, _pageHeight - (_pageWidth - pd.x) / k); - threePoints = true; - } - - FlipPoint(ref pa, _pageWidth, _pageHeight); - FlipPoint(ref pb, _pageWidth, _pageHeight); - FlipPoint(ref pd, _pageWidth, _pageHeight); - FlipPoint(ref pc, _pageWidth, _pageHeight); - if (_draggingCorner == Corner.BL || _draggingCorner == Corner.TL) - angle = -angle; - - switch (_draggingCorner) - { - case Corner.BR: - { - turningObj1.SetPivot(0, 0, true); - turningObj1.position = new Vector2(_pageWidth, 0); - - turningObj2.SetPivot(0, 1, true); - turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y); - turningObj2.rotation = 2 * angle; - - if (_softShadow != null) - { - _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true); - _softShadow.position = new Vector2(Vector2.Distance(pc, pd), _pageHeight); - _softShadow.rotation = -angle; - if (_softShadow.x > _pageWidth - 20) - _softShadow.alpha = (_pageWidth - _softShadow.x) / 20; - else - _softShadow.alpha = 1; - } - - mesh1.points.Clear(); - mesh1.Add(pe); - mesh1.Add(pf); - mesh1.Add(pb); - if (threePoints) - mesh1.Add(pa); - mesh1.Add(pd); - - mesh2.points.Clear(); - mesh2.Add(new Vector2(Vector2.Distance(pc, pd), _pageHeight)); - mesh2.Add(new Vector2(0, _pageHeight)); - if (threePoints) - mesh2.Add(new Vector2(0, _pageHeight - Vector2.Distance(pc, pa))); - else - { - mesh2.Add(new Vector2(0, 0)); - mesh2.Add(new Vector2(Vector2.Distance(pg, pb), 0)); - } - break; - } - case Corner.TR: - { - turningObj1.SetPivot(0, 0, true); - turningObj1.position = new Vector2(_pageWidth, 0); - - turningObj2.SetPivot(0, 0, true); - turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y); - turningObj2.rotation = -2 * angle; - - if (_softShadow != null) - { - _softShadow.SetPivot(1, 30 / _softShadow.height, true); - _softShadow.position = new Vector2(Vector2.Distance(pc, pd), 0); - _softShadow.rotation = angle; - if (_softShadow.x > _pageWidth - 20) - _softShadow.alpha = (_pageWidth - _softShadow.x) / 20; - else - _softShadow.alpha = 1; - } - - mesh1.points.Clear(); - mesh1.Add(pe); - mesh1.Add(pf); - mesh1.Add(pd); - if (threePoints) - mesh1.Add(pa); - mesh1.Add(pb); - - mesh2.points.Clear(); - if (threePoints) - mesh2.Add(new Vector2(0, Vector2.Distance(pc, pa))); - else - { - mesh2.Add(new Vector2(Vector2.Distance(pb, ph), _pageHeight)); - mesh2.Add(new Vector2(0, _pageHeight)); - } - mesh2.Add(new Vector2(0, 0)); - mesh2.Add(new Vector2(Vector2.Distance(pc, pd), 0)); - break; - } - case Corner.BL: - { - turningObj1.SetPivot(0, 0, true); - turningObj1.position = Vector2.zero; - - turningObj2.SetPivot(1, 1, true); - turningObj2.position = pc; - turningObj2.rotation = 2 * angle; - - if (_softShadow != null) - { - _softShadow.SetPivot(1, 30 / _softShadow.height, true); - _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight); - _softShadow.rotation = 180 - angle; - if (_softShadow.x < 20) - _softShadow.alpha = (_softShadow.x - 20) / 20; - else - _softShadow.alpha = 1; - } - - mesh1.points.Clear(); - mesh1.Add(pb); - mesh1.Add(pg); - mesh1.Add(ph); - mesh1.Add(pd); - if (threePoints) - mesh1.Add(pa); - - mesh2.points.Clear(); - if (!threePoints) - { - mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pf, pb), 0)); - mesh2.Add(new Vector2(_pageWidth, 0)); - } - else - mesh2.Add(new Vector2(_pageWidth, _pageHeight - Vector2.Distance(pc, pa))); - mesh2.Add(new Vector2(_pageWidth, _pageHeight)); - mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight)); - break; - } - case Corner.TL: - { - turningObj1.SetPivot(0, 0, true); - turningObj1.position = Vector2.zero; - - turningObj2.SetPivot(1, 0, true); - turningObj2.position = pc; - turningObj2.rotation = -2 * angle; - - if (_softShadow != null) - { - _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true); - _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0); - _softShadow.rotation = 180 + angle; - if (_softShadow.x < 20) - _softShadow.alpha = (_softShadow.x - 20) / 20; - else - _softShadow.alpha = 1; - } - - mesh1.points.Clear(); - mesh1.Add(pd); - mesh1.Add(pg); - mesh1.Add(ph); - mesh1.Add(pb); - if (threePoints) - mesh1.Add(pa); - - mesh2.points.Clear(); - mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0)); - mesh2.Add(new Vector2(_pageWidth, 0)); - if (threePoints) - mesh2.Add(new Vector2(_pageWidth, Vector2.Distance(pc, pa))); - else - { - mesh2.Add(new Vector2(_pageWidth, _pageHeight)); - mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pe, pb), _pageHeight)); - } - break; - } - } - } - - void RenderPages() - { - RenderCovers(); - - if (_softShadow != null) - _softShadow.RemoveFromParent(); - - int curPage = _currentPage; - if (curPage % 2 == 0) - curPage--; - - int leftPage, rightPage, turningPageBack, turningPageFront; - leftPage = curPage; - rightPage = leftPage < _pageCount - 1 ? (leftPage + 1) : -1; - - if (_turningTarget != -1) - { - int tt = _turningTarget; - if (tt % 2 == 0) - tt = tt - 1; - - if (tt == curPage) - { - _currentPage = _turningTarget; - turningPageBack = turningPageFront = -1; - } - else if (tt > leftPage) - { - turningPageFront = tt; - turningPageBack = rightPage; - rightPage = tt < _pageCount - 1 ? (tt + 1) : -1; - } - else - { - turningPageFront = tt > 0 ? (tt + 1) : 0; - turningPageBack = leftPage; - leftPage = tt > 0 ? tt : -1; - } - } - else - { - turningPageBack = turningPageFront = -1; - } - - _objectNewIndice[0] = leftPage; - _objectNewIndice[1] = rightPage; - _objectNewIndice[2] = turningPageBack; - _objectNewIndice[3] = turningPageFront; - - for (int i = 0; i < 4; i++) - { - int pageIndex = _objectNewIndice[i]; - if (pageIndex != -1) - { - for (int j = 0; j < 4; j++) - { - int pageIndex2 = _objectIndice[j]; - if (pageIndex2 == pageIndex) - { - if (j != i) - { - _objectIndice[j] = _objectIndice[i]; - _objectIndice[i] = pageIndex; - - GComponent tmp = _objects[j]; - _objects[j] = _objects[i]; - _objects[i] = tmp; - } - break; - } - } - } - } - - for (int i = 0; i < 4; i++) - { - GComponent obj = _objects[i]; - int oldIndex = _objectIndice[i]; - int index = _objectNewIndice[i]; - _objectIndice[i] = index; - if (index == -1) - { - if (obj != null) - obj.RemoveFromParent(); - } - else if (oldIndex != index) - { - if (obj == null) - { - obj = UIPackage.CreateObjectFromURL(_pageResource).asCom; - obj.displayObject.home = this.displayObject.cachedTransform; - _objects[i] = obj; - } - - _pagesContainer.AddChild(obj); - pageRenderer(index, obj); - } - else - { - if (obj.parent == null) - { - _pagesContainer.AddChild(obj); - pageRenderer(index, obj); - } - else - _pagesContainer.AddChild(obj); - } - - if (obj != null && obj.parent != null) - { - Controller c1 = obj.GetController("side"); - if (c1 != null) - { - if (index == 0) - c1.selectedPage = "first"; - else if (index == _pageCount - 1) - c1.selectedPage = "last"; - else - c1.selectedPage = (index % 2 == 0) ? "right" : "left"; - } - - if (i == 0 || i == 1) - SetPageNormal(obj, i == 0); - else if (_paper == Paper.Soft) - SetPageSoft(obj, i == 2); - else - SetPageHard(obj, i == 2); - } - } - } - - void RenderCovers() - { - if (_frontCover != null) - { - if (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront) - { - SetPageHard(_frontCover, true); - SetCoverStatus(_frontCover, CoverType.Front, _coverTurningOp == CoverTurningOp.HideFront); - } - else - { - if (_frontCover.displayObject.cacheAsBitmap) - SetCoverNormal(_frontCover, CoverType.Front); - - SetCoverStatus(_frontCover, CoverType.Front, _coverStatus == CoverStatus.ShowingFront); - } - } - - if (_backCover != null) - { - if (_coverTurningOp == CoverTurningOp.ShowBack || _coverTurningOp == CoverTurningOp.HideBack) - { - SetPageHard(_backCover, true); - SetCoverStatus(_backCover, CoverType.Back, _coverTurningOp == CoverTurningOp.HideBack); - } - else - { - if (_backCover.displayObject.cacheAsBitmap) - SetCoverNormal(_backCover, CoverType.Back); - - SetCoverStatus(_backCover, CoverType.Back, _coverStatus == CoverStatus.ShowingBack); - } - } - } - - void SetupHotspot(GObject obj, Corner corner) - { - if (obj == null) - return; - - obj.data = corner; - - obj.onTouchBegin.Add(__touchBegin); - obj.onTouchMove.Add(__touchMove); - obj.onTouchEnd.Add(__touchEnd); - } - - void SetPageHard(GComponent obj, bool front) - { - obj.touchable = false; - obj.displayObject.cacheAsBitmap = true; - if (obj.mask != null) - { - obj.mask.RemoveFromParent(); - obj.mask = null; - } - - PolygonMesh mesh = obj.displayObject.paintingGraphics.GetMeshFactory(); - mesh.usePercentPositions = true; - mesh.points.Clear(); - mesh.texcoords.Clear(); - obj.displayObject.paintingGraphics.SetMeshDirty(); - - if (front) - { - mesh.points.AddRange(VertexBuffer.NormalizedPosition); - mesh.texcoords.AddRange(VertexBuffer.NormalizedUV); - } - } - - void SetPageSoft(GComponent obj, bool front) - { - obj.touchable = false; - obj.displayObject.cacheAsBitmap = false; - DisplayObject mask = front ? _mask1.displayObject : _mask2.displayObject; - obj.mask = mask; - - PolygonMesh mesh = mask.graphics.GetMeshFactory(); - mesh.usePercentPositions = false; - mesh.points.Clear(); - mesh.texcoords.Clear(); - mask.graphics.SetMeshDirty(); - - if (front) - { - mesh.Add(new Vector2(0, _pageHeight)); - mesh.Add(Vector2.zero); - mesh.Add(new Vector2(_pageWidth, 0)); - mesh.Add(new Vector2(_pageWidth, _pageHeight)); - } - else if (_softShadow != null) - obj.AddChild(_softShadow); - } - - void SetPageNormal(GComponent obj, bool left) - { - obj.displayObject.cacheAsBitmap = false; - obj.touchable = true; - obj.SetPivot(0, 0, true); - if (left) - obj.SetXY(0, 0); - else - obj.SetXY(_pageWidth, 0); - obj.rotation = 0; - if (obj.mask != null) - { - obj.mask.RemoveFromParent(); - obj.mask = null; - } - } - - void SetCoverStatus(GComponent obj, CoverType coverType, bool show) - { - Controller c = obj.GetController("side"); - if (show) - { - if (c.selectedIndex != 0) - { - obj.position = coverType == CoverType.Front ? _backCoverPos : _frontCoverPos; - obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer) + 1); - c.selectedIndex = 0; //front - - if (obj.displayObject.cacheAsBitmap) - obj.displayObject.cacheAsBitmap = true; //refresh - } - } - else - { - if (c.selectedIndex != 1) - { - obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos; - obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer)); - c.selectedIndex = 1; //back - - if (obj.displayObject.cacheAsBitmap) - obj.displayObject.cacheAsBitmap = true; //refresh - } - } - } - - void SetCoverNormal(GComponent obj, CoverType coverType) - { - obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos; - obj.displayObject.cacheAsBitmap = false; - obj.touchable = true; - obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer)); - obj.GetController("side").selectedIndex = 1; //back - } - - PolygonMesh GetHardMesh(GComponent obj) - { - obj.displayObject.paintingGraphics.SetMeshDirty(); - return obj.displayObject.paintingGraphics.GetMeshFactory(); - } - - PolygonMesh GetSoftMesh(GComponent obj) - { - obj.mask.graphics.SetMeshDirty(); - return obj.mask.graphics.GetMeshFactory(); - } - - void UpdateDragPosition(Vector2 pos) - { - if (_coverTurningOp != CoverTurningOp.None) - { - _dragPoint = GlobalToLocal(pos) - _frontCoverPos; - _turningAmount = _dragPoint.x / (2 * _frontCover.width); - } - else - { - _dragPoint = _pagesContainer.GlobalToLocal(pos); - _turningAmount = _dragPoint.x / (2 * _pageWidth); - } - - if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR) - _turningAmount = 1 - _turningAmount; - } - - Vector2 GetCornerPosition(Corner corner, bool isCover) - { - float w = isCover ? _frontCover.width : _pageWidth; - float h = isCover ? _frontCover.height : _pageHeight; - Vector2 pt; - switch (corner) - { - case Corner.BL: - pt = new Vector2(0, h); - break; - - case Corner.TR: - pt = new Vector2(w * 2, 0); - break; - - case Corner.BR: - pt = new Vector2(w * 2, h); - break; - - default: - pt = Vector2.zero; - break; - } - - return pt; - } - - void __touchBegin(EventContext context) - { - GTween.Kill(this, true); - - _draggingCorner = (Corner)((GObject)context.sender).data; - if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL) - { - if (_coverStatus == CoverStatus.ShowingBack) - { - _coverTurningOp = CoverTurningOp.HideBack; - } - else if (_objectNewIndice[0] == -1) - { - if (_frontCover != null && _coverStatus != CoverStatus.ShowingFront) - _coverTurningOp = CoverTurningOp.ShowFront; - else - _draggingCorner = Corner.INVALID; - } - else - { - _turningTarget = _objectNewIndice[0] - 2; - if (_turningTarget < 0) - _turningTarget = 0; - } - } - else - { - if (_coverStatus == CoverStatus.ShowingFront) - { - _coverTurningOp = CoverTurningOp.HideFront; - } - else if (_objectNewIndice[1] == -1) - { - if (_backCover != null && _coverStatus != CoverStatus.ShowingBack) - _coverTurningOp = CoverTurningOp.ShowBack; - else - _draggingCorner = Corner.INVALID; - } - else - { - _turningTarget = _objectNewIndice[1] + 1; - } - } - - if (_draggingCorner != Corner.INVALID) - { - _touchDownTime = Time.unscaledTime; - UpdateDragPosition(context.inputEvent.position); - RenderPages(); - PlayTurnEffect(); - - context.CaptureTouch(); - } - } - - void __touchMove(EventContext context) - { - if (_draggingCorner != Corner.INVALID) - { - UpdateDragPosition(context.inputEvent.position); - PlayTurnEffect(); - } - } - - void __touchEnd(EventContext context) - { - if (_draggingCorner != Corner.INVALID) - { - bool suc = _turningAmount > 0.4f || (Time.unscaledTime - _touchDownTime < 0.35f); - Vector2 target; - if (suc) - { - if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL) - target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None); - else - target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None); - } - else - target = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None); - - float duration = Mathf.Max(EffectDuration * 0.5f, Mathf.Abs(target.x - _dragPoint.x) / (_pageWidth * 2) * EffectDuration); - GTween.To(_dragPoint, target, duration).SetTarget(this).SetUserData(suc) - .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete); - } - } +using System; +using FairyGUI; +using FairyGUI.Utils; +using UnityEngine; + +/// +/// Achieving the effect of turning over books. Use virtual mechanism to support unlimited pages. Support covers. +/// +public class FairyBook : GComponent +{ + /// + /// + /// + /// + /// + public delegate void PageRenderer(int index, GComponent page); + + /// + /// + /// + public PageRenderer pageRenderer; + + /// + /// + /// + public static float EffectDuration = 0.5f; + + /// + /// + /// + public enum Paper + { + Soft, + Hard + } + + public enum CoverType + { + Front, + Back + } + + enum CoverStatus + { + Hidden, + ShowingFront, + ShowingBack + } + + enum CoverTurningOp + { + None, + ShowFront, + HideFront, + ShowBack, + HideBack + } + + enum Corner + { + INVALID, + TL, + BL, + TR, + BR + } + + GComponent _pagesContainer; + string _pageResource; + int _pageWidth; + int _pageHeight; + + int _pageCount; + int _currentPage; + Paper _paper; + + int _turningTarget; + float _turningAmount; + CoverTurningOp _coverTurningOp; + GPath _turningPath; + + GComponent[] _objects; + GGraph _mask1; + GGraph _mask2; + GObject _softShadow; + int[] _objectIndice; + int[] _objectNewIndice; + + Corner _draggingCorner; + Vector2 _dragPoint; + float _touchDownTime; + + GComponent _frontCover; + GComponent _backCover; + Vector2 _frontCoverPos; + Vector2 _backCoverPos; + CoverStatus _coverStatus; + + EventListener _onTurnComplete; + + public override void ConstructFromXML(XML xml) + { + base.ConstructFromXML(xml); + + _pagesContainer = GetChild("pages").asCom; + if (_pagesContainer == null) + { + Debug.LogError("Not a valid book resource"); + return; + } + + GComponent obj1 = _pagesContainer.GetChild("left").asCom; + GComponent obj2 = _pagesContainer.GetChild("right").asCom; + if (obj1 == null || obj2 == null || obj1.resourceURL != obj2.resourceURL + || obj1.width != obj2.width || obj2.x != obj1.x + obj1.width) + { + Debug.LogError("Not a valid book resource"); + return; + } + + obj1.displayObject.home = this.displayObject.cachedTransform; + obj2.displayObject.home = this.displayObject.cachedTransform; + _pagesContainer.RemoveChild(obj1); + _pagesContainer.RemoveChild(obj2); + + _frontCover = GetChild("frontCover") as GComponent; + if (_frontCover != null) + _frontCoverPos = _frontCover.position; + _backCover = GetChild("backCover") as GComponent; + if (_backCover != null) + _backCoverPos = _backCover.position; + + _objects = new GComponent[4] { obj1, obj2, null, null }; + _objectIndice = new int[4] { -1, -1, -1, -1 }; + _objectNewIndice = new int[4]; + _turningTarget = -1; + _currentPage = -1; + + _pageWidth = (int)obj1.width; + _pageHeight = (int)obj1.height; + _pageResource = obj1.resourceURL; + + _mask1 = new GGraph(); + _mask1.displayObject.home = this.displayObject.cachedTransform; + _mask1.SetSize(_pageWidth, _pageHeight); + + _mask2 = new GGraph(); + _mask2.displayObject.home = this.displayObject.cachedTransform; + _mask2.SetSize(_pageWidth, _pageHeight); + + SetupHotspot(GetChild("hotspot_tl"), Corner.TL); + SetupHotspot(GetChild("hotspot_bl"), Corner.BL); + SetupHotspot(GetChild("hotspot_tr"), Corner.TR); + SetupHotspot(GetChild("hotspot_br"), Corner.BR); + } + + public override void Dispose() + { + for (int i = 0; i < 4; i++) + { + if (_objects[i] != null) + _objects[i].Dispose(); + + } + _mask1.Dispose(); + _mask2.Dispose(); + if (_softShadow != null) + _softShadow.Dispose(); + + base.Dispose(); + } + + /// + /// + /// + public EventListener onTurnComplete + { + get { return _onTurnComplete ?? (_onTurnComplete = new EventListener(this, "onTurnComplete")); } + } + + /// + /// + /// + /// + public void SetSoftShadowResource(string res) + { + _softShadow = UIPackage.CreateObjectFromURL(res); + _softShadow.height = Mathf.Sqrt(Mathf.Pow(_pageWidth, 2) + Mathf.Pow(_pageHeight, 2)) + 60; + _softShadow.displayObject.home = this.displayObject.cachedTransform; + _softShadow.sortingOrder = int.MaxValue; + } + + /// + /// + /// + public Paper pageSoftness + { + get { return _paper; } + set { _paper = value; } + } + + /// + /// + /// + public int pageCount + { + get { return _pageCount; } + set + { + if (_pageCount % 2 != 0) + throw new System.Exception("Page count must be even!"); + + _pageCount = value; + } + } + + /// + /// + /// + public int currentPage + { + get { return _currentPage; } + set + { + if (value < 0 || value > _pageCount - 1) + throw new Exception("Page index out of bounds: " + value); + + if (_currentPage != value) + { + GTween.Kill(this, true); + + _currentPage = value; + _coverStatus = CoverStatus.Hidden; + + RenderPages(); + } + } + } + + /// + /// + /// + /// + public void TurnTo(int pageIndex) + { + if (pageIndex < 0 || pageIndex > _pageCount - 1) + throw new Exception("Page index out of bounds: " + pageIndex); + + GTween.Kill(this, true); + + if (_coverStatus == CoverStatus.ShowingFront) + { + _coverTurningOp = CoverTurningOp.HideFront; + _draggingCorner = Corner.BR; + } + else if (_coverStatus == CoverStatus.ShowingBack) + { + _coverTurningOp = CoverTurningOp.HideBack; + _draggingCorner = Corner.BL; + } + + int tt1 = _currentPage; + if (_currentPage % 2 == 0) + tt1--; + int tt2 = pageIndex; + if (pageIndex % 2 == 0) + tt2--; + if (tt1 == tt2) + { + _currentPage = pageIndex; + _turningTarget = -1; + } + else + { + _turningTarget = pageIndex; + if (_turningTarget < _currentPage) + _draggingCorner = Corner.BL; + else + _draggingCorner = Corner.BR; + } + + if (_draggingCorner == Corner.INVALID) + return; + + StartTween(); + } + + /// + /// + /// + public void TurnNext() + { + GTween.Kill(this, true); + + if (isCoverShowing(CoverType.Front)) + TurnTo(0); + else if (_currentPage == _pageCount - 1) + ShowCover(CoverType.Back, true); + else if (_currentPage % 2 == 0) + TurnTo(_currentPage + 1); + else + TurnTo(_currentPage + 2); + } + + /// + /// + /// + public void TurnPrevious() + { + GTween.Kill(this, true); + + if (isCoverShowing(CoverType.Back)) + TurnTo(_pageCount - 1); + else if (_currentPage == 0) + ShowCover(CoverType.Front, true); + else if (_currentPage % 2 == 0) + TurnTo(_currentPage - 2); + else + TurnTo(_currentPage - 1); + } + + /// + /// + /// + /// + /// + public void ShowCover(CoverType cover, bool turnEffect) + { + GTween.Kill(this, true); + + if (_frontCover == null) + return; + + if (turnEffect) + { + if (cover == CoverType.Front) + { + if (_coverStatus == CoverStatus.ShowingFront) + return; + + _coverTurningOp = CoverTurningOp.ShowFront; + _draggingCorner = Corner.BL; + _currentPage = 0; + } + else + { + if (_coverStatus == CoverStatus.ShowingBack) + return; + + _coverTurningOp = CoverTurningOp.ShowBack; + _draggingCorner = Corner.BR; + _currentPage = _pageCount - 1; + } + + StartTween(); + } + else + { + if (cover == CoverType.Front) + { + _currentPage = 0; + _coverStatus = CoverStatus.ShowingFront; + } + else + { + _currentPage = _pageCount - 1; + _coverStatus = CoverStatus.ShowingBack; + } + RenderPages(); + } + } + + /// + /// + /// + /// + /// + public bool isCoverShowing(CoverType cover) + { + return cover == CoverType.Front ? (_coverStatus == CoverStatus.ShowingFront) : (_coverStatus == CoverStatus.ShowingBack); + } + + void StartTween() + { + _turningAmount = 0; + RenderPages(); + Vector2 source = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None); + Vector2 target; + if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL) + target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None); + else + target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None); + + if (_turningPath == null) + _turningPath = new GPath(); + Vector2 mid = new Vector2(source.x + (target.x - source.x) / 2, target.y - 50); + _turningPath.Create(new GPathPoint(source), new GPathPoint(mid), new GPathPoint(target)); + GTween.To(source, target, EffectDuration).SetUserData(true).SetTarget(this) + .SetPath(_turningPath) + .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete); + } + + void OnTurnUpdate(GTweener tweener) + { + _dragPoint = tweener.value.vec2; + _turningAmount = _dragPoint.x / (_coverTurningOp != CoverTurningOp.None ? _frontCover.width * 2 : _pageWidth * 2); + if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR) + _turningAmount = 1 - _turningAmount; + PlayTurnEffect(); + } + + void OnTurnComplete(GTweener tweener) + { + bool suc = (bool)tweener.userData; + _draggingCorner = Corner.INVALID; + if (suc && _turningTarget != -1) + _currentPage = _turningTarget; + if (suc && _coverTurningOp != CoverTurningOp.None) + { + if (_coverTurningOp == CoverTurningOp.ShowFront) + _coverStatus = CoverStatus.ShowingFront; + else if (_coverTurningOp == CoverTurningOp.ShowBack) + _coverStatus = CoverStatus.ShowingBack; + else + _coverStatus = CoverStatus.Hidden; + } + _coverTurningOp = CoverTurningOp.None; + _turningTarget = -1; + + RenderPages(); + + DispatchEvent("onTurnComplete"); + } + + void PlayTurnEffect() + { + if (_coverTurningOp != CoverTurningOp.None) + PlayCoverEffect(); + + if (_turningTarget != -1) + { + if (_paper == Paper.Hard) + PlayHardEffect(); + else + PlaySoftEffect(); + } + } + + void PlayCoverEffect() + { + float amount = Mathf.Clamp01(_turningAmount); + float ratio; + bool isLeft; + GComponent turningObj = (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront) ? _frontCover : _backCover; + PolygonMesh mesh = GetHardMesh(turningObj); + + if (amount < 0.5f) + { + ratio = 1 - amount * 2; + isLeft = _coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideBack; + } + else + { + ratio = (amount - 0.5f) * 2; + isLeft = _coverTurningOp == CoverTurningOp.HideFront || _coverTurningOp == CoverTurningOp.ShowBack; + } + + if (turningObj == _frontCover) + SetCoverStatus(turningObj, CoverType.Front, !isLeft); + else + SetCoverStatus(turningObj, CoverType.Back, isLeft); + + mesh.points.Clear(); + mesh.texcoords.Clear(); + if (isLeft) + { + float topOffset = 1f / 8 * (1 - ratio); + float xOffset = 1 - ratio; + mesh.Add(new Vector2(xOffset, 1 + topOffset)); + mesh.Add(new Vector2(xOffset, -topOffset)); + mesh.Add(new Vector2(1, 0)); + mesh.Add(new Vector2(1, 1)); + } + else + { + float topOffset = 1f / 8 * (1 - ratio); + mesh.Add(new Vector2(0, 1)); + mesh.Add(new Vector2(0, 0)); + mesh.Add(new Vector2(ratio, -topOffset)); + mesh.Add(new Vector2(ratio, 1 + topOffset)); + } + + mesh.texcoords.AddRange(VertexBuffer.NormalizedUV); + } + + void PlayHardEffect() + { + float amount = Mathf.Clamp01(_turningAmount); + float ratio; + bool isLeft; + GComponent turningObj; + PolygonMesh mesh; + if (amount < 0.5f) + { + ratio = 1 - amount * 2; + isLeft = _turningTarget < _currentPage; + + turningObj = _objects[2]; + mesh = GetHardMesh(turningObj); + GetHardMesh(_objects[3]).points.Clear(); + } + else + { + ratio = (amount - 0.5f) * 2; + isLeft = _turningTarget > _currentPage; + + turningObj = _objects[3]; + mesh = GetHardMesh(turningObj); + GetHardMesh(_objects[2]).points.Clear(); + } + + mesh.points.Clear(); + mesh.texcoords.Clear(); + if (isLeft) + { + turningObj.x = 0; + + float topOffset = 1f / 8 * (1 - ratio); + float xOffset = 1 - ratio; + mesh.Add(new Vector2(xOffset, 1 + topOffset)); + mesh.Add(new Vector2(xOffset, -topOffset)); + mesh.Add(new Vector2(1, 0)); + mesh.Add(new Vector2(1, 1)); + } + else + { + turningObj.x = _pageWidth; + + float topOffset = 1f / 8 * (1 - ratio); + mesh.Add(new Vector2(0, 1)); + mesh.Add(new Vector2(0, 0)); + mesh.Add(new Vector2(ratio, -topOffset)); + mesh.Add(new Vector2(ratio, 1 + topOffset)); + } + + mesh.texcoords.AddRange(VertexBuffer.NormalizedUV); + } + + void FlipPoint(ref Vector2 pt, float w, float h) + { + switch (_draggingCorner) + { + case Corner.TL: + pt.x = w - pt.x; + pt.y = h - pt.y; + break; + case Corner.BL: + pt.x = w - pt.x; + break; + case Corner.TR: + pt.y = h - pt.y; + break; + } + } + + void PlaySoftEffect() + { + GComponent turningObj1 = _objects[2]; + GComponent turningObj2 = _objects[3]; + PolygonMesh mesh1 = GetSoftMesh(turningObj1); + PolygonMesh mesh2 = GetSoftMesh(turningObj2); + + /** + * a + * / \ + * f(0,0)------/ b--g(w,0) + * | / / | + * | / / | + * | c / | + * | \ / | + * | \ / | + * e(0,h)-----d--------h(w,h) + */ + Vector2 pa, pb, pc, pd, pe, pf, pg, ph; + float k, angle; + bool threePoints = false; + + pc = _dragPoint; + pe = new Vector2(0, _pageHeight); + pf = Vector2.zero; + pg = new Vector2(_pageWidth, 0); + ph = new Vector2(_pageWidth, _pageHeight); + + FlipPoint(ref pc, _pageWidth * 2, _pageHeight); + pc.x -= _pageWidth; + if (pc.x >= _pageWidth) + return; + + k = (ph.y - pc.y) / (ph.x - pc.x); + float k2 = 1 + Mathf.Pow(k, 2); + float min; + min = ph.x - _pageWidth * 2 / k2; + if (pc.x < min) + { + pc.x = min; + if (pc.x >= _pageWidth) + return; + pc.y = ph.y - k * (ph.x - pc.x); + } + + min = ph.x - (_pageWidth + _pageHeight * k) * 2 / k2; + if (pc.x < min) + { + pc.x = min; + if (pc.x >= _pageWidth) + return; + pc.y = ph.y - k * (ph.x - pc.x); + } + + angle = Mathf.Atan(k) * Mathf.Rad2Deg; + pd = new Vector2(_pageWidth - k2 * (ph.x - pc.x) / 2, _pageHeight); + pb = new Vector2(pd.x + _pageHeight * k, 0); + pa = new Vector2(); + + if (pb.x > _pageWidth) + { + pb.x = _pageWidth; + pa = new Vector2(_pageWidth, _pageHeight - (_pageWidth - pd.x) / k); + threePoints = true; + } + + FlipPoint(ref pa, _pageWidth, _pageHeight); + FlipPoint(ref pb, _pageWidth, _pageHeight); + FlipPoint(ref pd, _pageWidth, _pageHeight); + FlipPoint(ref pc, _pageWidth, _pageHeight); + if (_draggingCorner == Corner.BL || _draggingCorner == Corner.TL) + angle = -angle; + + switch (_draggingCorner) + { + case Corner.BR: + { + turningObj1.SetPivot(0, 0, true); + turningObj1.position = new Vector2(_pageWidth, 0); + + turningObj2.SetPivot(0, 1, true); + turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y); + turningObj2.rotation = 2 * angle; + + if (_softShadow != null) + { + _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true); + _softShadow.position = new Vector2(Vector2.Distance(pc, pd), _pageHeight); + _softShadow.rotation = -angle; + if (_softShadow.x > _pageWidth - 20) + _softShadow.alpha = (_pageWidth - _softShadow.x) / 20; + else + _softShadow.alpha = 1; + } + + mesh1.points.Clear(); + mesh1.Add(pe); + mesh1.Add(pf); + mesh1.Add(pb); + if (threePoints) + mesh1.Add(pa); + mesh1.Add(pd); + + mesh2.points.Clear(); + mesh2.Add(new Vector2(Vector2.Distance(pc, pd), _pageHeight)); + mesh2.Add(new Vector2(0, _pageHeight)); + if (threePoints) + mesh2.Add(new Vector2(0, _pageHeight - Vector2.Distance(pc, pa))); + else + { + mesh2.Add(new Vector2(0, 0)); + mesh2.Add(new Vector2(Vector2.Distance(pg, pb), 0)); + } + break; + } + case Corner.TR: + { + turningObj1.SetPivot(0, 0, true); + turningObj1.position = new Vector2(_pageWidth, 0); + + turningObj2.SetPivot(0, 0, true); + turningObj2.position = new Vector2(_pageWidth + pc.x, pc.y); + turningObj2.rotation = -2 * angle; + + if (_softShadow != null) + { + _softShadow.SetPivot(1, 30 / _softShadow.height, true); + _softShadow.position = new Vector2(Vector2.Distance(pc, pd), 0); + _softShadow.rotation = angle; + if (_softShadow.x > _pageWidth - 20) + _softShadow.alpha = (_pageWidth - _softShadow.x) / 20; + else + _softShadow.alpha = 1; + } + + mesh1.points.Clear(); + mesh1.Add(pe); + mesh1.Add(pf); + mesh1.Add(pd); + if (threePoints) + mesh1.Add(pa); + mesh1.Add(pb); + + mesh2.points.Clear(); + if (threePoints) + mesh2.Add(new Vector2(0, Vector2.Distance(pc, pa))); + else + { + mesh2.Add(new Vector2(Vector2.Distance(pb, ph), _pageHeight)); + mesh2.Add(new Vector2(0, _pageHeight)); + } + mesh2.Add(new Vector2(0, 0)); + mesh2.Add(new Vector2(Vector2.Distance(pc, pd), 0)); + break; + } + case Corner.BL: + { + turningObj1.SetPivot(0, 0, true); + turningObj1.position = Vector2.zero; + + turningObj2.SetPivot(1, 1, true); + turningObj2.position = pc; + turningObj2.rotation = 2 * angle; + + if (_softShadow != null) + { + _softShadow.SetPivot(1, 30 / _softShadow.height, true); + _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight); + _softShadow.rotation = 180 - angle; + if (_softShadow.x < 20) + _softShadow.alpha = (_softShadow.x - 20) / 20; + else + _softShadow.alpha = 1; + } + + mesh1.points.Clear(); + mesh1.Add(pb); + mesh1.Add(pg); + mesh1.Add(ph); + mesh1.Add(pd); + if (threePoints) + mesh1.Add(pa); + + mesh2.points.Clear(); + if (!threePoints) + { + mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pf, pb), 0)); + mesh2.Add(new Vector2(_pageWidth, 0)); + } + else + mesh2.Add(new Vector2(_pageWidth, _pageHeight - Vector2.Distance(pc, pa))); + mesh2.Add(new Vector2(_pageWidth, _pageHeight)); + mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), _pageHeight)); + break; + } + case Corner.TL: + { + turningObj1.SetPivot(0, 0, true); + turningObj1.position = Vector2.zero; + + turningObj2.SetPivot(1, 0, true); + turningObj2.position = pc; + turningObj2.rotation = -2 * angle; + + if (_softShadow != null) + { + _softShadow.SetPivot(1, (_softShadow.height - 30) / _softShadow.height, true); + _softShadow.position = new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0); + _softShadow.rotation = 180 + angle; + if (_softShadow.x < 20) + _softShadow.alpha = (_softShadow.x - 20) / 20; + else + _softShadow.alpha = 1; + } + + mesh1.points.Clear(); + mesh1.Add(pd); + mesh1.Add(pg); + mesh1.Add(ph); + mesh1.Add(pb); + if (threePoints) + mesh1.Add(pa); + + mesh2.points.Clear(); + mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pc, pd), 0)); + mesh2.Add(new Vector2(_pageWidth, 0)); + if (threePoints) + mesh2.Add(new Vector2(_pageWidth, Vector2.Distance(pc, pa))); + else + { + mesh2.Add(new Vector2(_pageWidth, _pageHeight)); + mesh2.Add(new Vector2(_pageWidth - Vector2.Distance(pe, pb), _pageHeight)); + } + break; + } + } + } + + void RenderPages() + { + RenderCovers(); + + if (_softShadow != null) + _softShadow.RemoveFromParent(); + + int curPage = _currentPage; + if (curPage % 2 == 0) + curPage--; + + int leftPage, rightPage, turningPageBack, turningPageFront; + leftPage = curPage; + rightPage = leftPage < _pageCount - 1 ? (leftPage + 1) : -1; + + if (_turningTarget != -1) + { + int tt = _turningTarget; + if (tt % 2 == 0) + tt = tt - 1; + + if (tt == curPage) + { + _currentPage = _turningTarget; + turningPageBack = turningPageFront = -1; + } + else if (tt > leftPage) + { + turningPageFront = tt; + turningPageBack = rightPage; + rightPage = tt < _pageCount - 1 ? (tt + 1) : -1; + } + else + { + turningPageFront = tt > 0 ? (tt + 1) : 0; + turningPageBack = leftPage; + leftPage = tt > 0 ? tt : -1; + } + } + else + { + turningPageBack = turningPageFront = -1; + } + + _objectNewIndice[0] = leftPage; + _objectNewIndice[1] = rightPage; + _objectNewIndice[2] = turningPageBack; + _objectNewIndice[3] = turningPageFront; + + for (int i = 0; i < 4; i++) + { + int pageIndex = _objectNewIndice[i]; + if (pageIndex != -1) + { + for (int j = 0; j < 4; j++) + { + int pageIndex2 = _objectIndice[j]; + if (pageIndex2 == pageIndex) + { + if (j != i) + { + _objectIndice[j] = _objectIndice[i]; + _objectIndice[i] = pageIndex; + + GComponent tmp = _objects[j]; + _objects[j] = _objects[i]; + _objects[i] = tmp; + } + break; + } + } + } + } + + for (int i = 0; i < 4; i++) + { + GComponent obj = _objects[i]; + int oldIndex = _objectIndice[i]; + int index = _objectNewIndice[i]; + _objectIndice[i] = index; + if (index == -1) + { + if (obj != null) + obj.RemoveFromParent(); + } + else if (oldIndex != index) + { + if (obj == null) + { + obj = UIPackage.CreateObjectFromURL(_pageResource).asCom; + obj.displayObject.home = this.displayObject.cachedTransform; + _objects[i] = obj; + } + + _pagesContainer.AddChild(obj); + pageRenderer(index, obj); + } + else + { + if (obj.parent == null) + { + _pagesContainer.AddChild(obj); + pageRenderer(index, obj); + } + else + _pagesContainer.AddChild(obj); + } + + if (obj != null && obj.parent != null) + { + Controller c1 = obj.GetController("side"); + if (c1 != null) + { + if (index == 0) + c1.selectedPage = "first"; + else if (index == _pageCount - 1) + c1.selectedPage = "last"; + else + c1.selectedPage = (index % 2 == 0) ? "right" : "left"; + } + + if (i == 0 || i == 1) + SetPageNormal(obj, i == 0); + else if (_paper == Paper.Soft) + SetPageSoft(obj, i == 2); + else + SetPageHard(obj, i == 2); + } + } + } + + void RenderCovers() + { + if (_frontCover != null) + { + if (_coverTurningOp == CoverTurningOp.ShowFront || _coverTurningOp == CoverTurningOp.HideFront) + { + SetPageHard(_frontCover, true); + SetCoverStatus(_frontCover, CoverType.Front, _coverTurningOp == CoverTurningOp.HideFront); + } + else + { + if (_frontCover.displayObject.cacheAsBitmap) + SetCoverNormal(_frontCover, CoverType.Front); + + SetCoverStatus(_frontCover, CoverType.Front, _coverStatus == CoverStatus.ShowingFront); + } + } + + if (_backCover != null) + { + if (_coverTurningOp == CoverTurningOp.ShowBack || _coverTurningOp == CoverTurningOp.HideBack) + { + SetPageHard(_backCover, true); + SetCoverStatus(_backCover, CoverType.Back, _coverTurningOp == CoverTurningOp.HideBack); + } + else + { + if (_backCover.displayObject.cacheAsBitmap) + SetCoverNormal(_backCover, CoverType.Back); + + SetCoverStatus(_backCover, CoverType.Back, _coverStatus == CoverStatus.ShowingBack); + } + } + } + + void SetupHotspot(GObject obj, Corner corner) + { + if (obj == null) + return; + + obj.data = corner; + + obj.onTouchBegin.Add(__touchBegin); + obj.onTouchMove.Add(__touchMove); + obj.onTouchEnd.Add(__touchEnd); + } + + void SetPageHard(GComponent obj, bool front) + { + obj.touchable = false; + obj.displayObject.cacheAsBitmap = true; + if (obj.mask != null) + { + obj.mask.RemoveFromParent(); + obj.mask = null; + } + + PolygonMesh mesh = obj.displayObject.paintingGraphics.GetMeshFactory(); + mesh.usePercentPositions = true; + mesh.points.Clear(); + mesh.texcoords.Clear(); + obj.displayObject.paintingGraphics.SetMeshDirty(); + + if (front) + { + mesh.points.AddRange(VertexBuffer.NormalizedPosition); + mesh.texcoords.AddRange(VertexBuffer.NormalizedUV); + } + } + + void SetPageSoft(GComponent obj, bool front) + { + obj.touchable = false; + obj.displayObject.cacheAsBitmap = false; + DisplayObject mask = front ? _mask1.displayObject : _mask2.displayObject; + obj.mask = mask; + + PolygonMesh mesh = mask.graphics.GetMeshFactory(); + mesh.usePercentPositions = false; + mesh.points.Clear(); + mesh.texcoords.Clear(); + mask.graphics.SetMeshDirty(); + + if (front) + { + mesh.Add(new Vector2(0, _pageHeight)); + mesh.Add(Vector2.zero); + mesh.Add(new Vector2(_pageWidth, 0)); + mesh.Add(new Vector2(_pageWidth, _pageHeight)); + } + else if (_softShadow != null) + obj.AddChild(_softShadow); + } + + void SetPageNormal(GComponent obj, bool left) + { + obj.displayObject.cacheAsBitmap = false; + obj.touchable = true; + obj.SetPivot(0, 0, true); + if (left) + obj.SetXY(0, 0); + else + obj.SetXY(_pageWidth, 0); + obj.rotation = 0; + if (obj.mask != null) + { + obj.mask.RemoveFromParent(); + obj.mask = null; + } + } + + void SetCoverStatus(GComponent obj, CoverType coverType, bool show) + { + Controller c = obj.GetController("side"); + if (show) + { + if (c.selectedIndex != 0) + { + obj.position = coverType == CoverType.Front ? _backCoverPos : _frontCoverPos; + obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer) + 1); + c.selectedIndex = 0; //front + + if (obj.displayObject.cacheAsBitmap) + obj.displayObject.cacheAsBitmap = true; //refresh + } + } + else + { + if (c.selectedIndex != 1) + { + obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos; + obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer)); + c.selectedIndex = 1; //back + + if (obj.displayObject.cacheAsBitmap) + obj.displayObject.cacheAsBitmap = true; //refresh + } + } + } + + void SetCoverNormal(GComponent obj, CoverType coverType) + { + obj.position = coverType == CoverType.Front ? _frontCoverPos : _backCoverPos; + obj.displayObject.cacheAsBitmap = false; + obj.touchable = true; + obj.parent.SetChildIndexBefore(obj, obj.parent.GetChildIndex(_pagesContainer)); + obj.GetController("side").selectedIndex = 1; //back + } + + PolygonMesh GetHardMesh(GComponent obj) + { + obj.displayObject.paintingGraphics.SetMeshDirty(); + return obj.displayObject.paintingGraphics.GetMeshFactory(); + } + + PolygonMesh GetSoftMesh(GComponent obj) + { + obj.mask.graphics.SetMeshDirty(); + return obj.mask.graphics.GetMeshFactory(); + } + + void UpdateDragPosition(Vector2 pos) + { + if (_coverTurningOp != CoverTurningOp.None) + { + _dragPoint = GlobalToLocal(pos) - _frontCoverPos; + _turningAmount = _dragPoint.x / (2 * _frontCover.width); + } + else + { + _dragPoint = _pagesContainer.GlobalToLocal(pos); + _turningAmount = _dragPoint.x / (2 * _pageWidth); + } + + if (_draggingCorner == Corner.TR || _draggingCorner == Corner.BR) + _turningAmount = 1 - _turningAmount; + } + + Vector2 GetCornerPosition(Corner corner, bool isCover) + { + float w = isCover ? _frontCover.width : _pageWidth; + float h = isCover ? _frontCover.height : _pageHeight; + Vector2 pt; + switch (corner) + { + case Corner.BL: + pt = new Vector2(0, h); + break; + + case Corner.TR: + pt = new Vector2(w * 2, 0); + break; + + case Corner.BR: + pt = new Vector2(w * 2, h); + break; + + default: + pt = Vector2.zero; + break; + } + + return pt; + } + + void __touchBegin(EventContext context) + { + GTween.Kill(this, true); + + _draggingCorner = (Corner)((GObject)context.sender).data; + if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL) + { + if (_coverStatus == CoverStatus.ShowingBack) + { + _coverTurningOp = CoverTurningOp.HideBack; + } + else if (_objectNewIndice[0] == -1) + { + if (_frontCover != null && _coverStatus != CoverStatus.ShowingFront) + _coverTurningOp = CoverTurningOp.ShowFront; + else + _draggingCorner = Corner.INVALID; + } + else + { + _turningTarget = _objectNewIndice[0] - 2; + if (_turningTarget < 0) + _turningTarget = 0; + } + } + else + { + if (_coverStatus == CoverStatus.ShowingFront) + { + _coverTurningOp = CoverTurningOp.HideFront; + } + else if (_objectNewIndice[1] == -1) + { + if (_backCover != null && _coverStatus != CoverStatus.ShowingBack) + _coverTurningOp = CoverTurningOp.ShowBack; + else + _draggingCorner = Corner.INVALID; + } + else + { + _turningTarget = _objectNewIndice[1] + 1; + } + } + + if (_draggingCorner != Corner.INVALID) + { + _touchDownTime = Time.unscaledTime; + UpdateDragPosition(context.inputEvent.position); + RenderPages(); + PlayTurnEffect(); + + context.CaptureTouch(); + } + } + + void __touchMove(EventContext context) + { + if (_draggingCorner != Corner.INVALID) + { + UpdateDragPosition(context.inputEvent.position); + PlayTurnEffect(); + } + } + + void __touchEnd(EventContext context) + { + if (_draggingCorner != Corner.INVALID) + { + bool suc = _turningAmount > 0.4f || (Time.unscaledTime - _touchDownTime < 0.35f); + Vector2 target; + if (suc) + { + if (_draggingCorner == Corner.TL || _draggingCorner == Corner.BL) + target = GetCornerPosition(_draggingCorner + 2, _coverTurningOp != CoverTurningOp.None); + else + target = GetCornerPosition(_draggingCorner - 2, _coverTurningOp != CoverTurningOp.None); + } + else + target = GetCornerPosition(_draggingCorner, _coverTurningOp != CoverTurningOp.None); + + float duration = Mathf.Max(EffectDuration * 0.5f, Mathf.Abs(target.x - _dragPoint.x) / (_pageWidth * 2) * EffectDuration); + GTween.To(_dragPoint, target, duration).SetTarget(this).SetUserData(suc) + .OnUpdate(OnTurnUpdate).OnComplete(OnTurnComplete); + } + } } \ No newline at end of file diff --git a/Assets/Examples/TurnPage/TurnPageMain.cs b/Assets/Examples/TurnPage/TurnPageMain.cs index e696899b..cb67767a 100644 --- a/Assets/Examples/TurnPage/TurnPageMain.cs +++ b/Assets/Examples/TurnPage/TurnPageMain.cs @@ -1,78 +1,78 @@ -using UnityEngine; -using FairyGUI; - -public class TurnPageMain : MonoBehaviour -{ - GComponent _mainView; - FairyBook _book; - GSlider _slider; - - void Awake() - { - UIPackage.AddPackage("UI/TurnPage"); - UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Book", typeof(FairyBook)); - UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Page", typeof(BookPage)); - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - - _book = (FairyBook)_mainView.GetChild("book"); - _book.SetSoftShadowResource("ui://TurnPage/shadow_soft"); - _book.pageRenderer = RenderPage; - _book.pageCount = 20; - _book.currentPage = 0; - _book.ShowCover(FairyBook.CoverType.Front, false); - _book.onTurnComplete.Add(OnTurnComplete); - - GearBase.disableAllTweenEffect = true; - _mainView.GetController("bookPos").selectedIndex = 1; - GearBase.disableAllTweenEffect = false; - - _mainView.GetChild("btnNext").onClick.Add(() => - { - _book.TurnNext(); - }); - _mainView.GetChild("btnPrev").onClick.Add(() => - { - _book.TurnPrevious(); - }); - - _slider = _mainView.GetChild("pageSlide").asSlider; - _slider.max = _book.pageCount - 1; - _slider.value = 0; - _slider.onGripTouchEnd.Add(() => - { - _book.TurnTo((int)_slider.value); - }); - } - - void OnTurnComplete() - { - _slider.value = _book.currentPage; - - if (_book.isCoverShowing(FairyBook.CoverType.Front)) - _mainView.GetController("bookPos").selectedIndex = 1; - else if (_book.isCoverShowing(FairyBook.CoverType.Back)) - _mainView.GetController("bookPos").selectedIndex = 2; - else - _mainView.GetController("bookPos").selectedIndex = 0; - } - - void RenderPage(int index, GComponent page) - { - ((BookPage)page).render(index); - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class TurnPageMain : MonoBehaviour +{ + GComponent _mainView; + FairyBook _book; + GSlider _slider; + + void Awake() + { + UIPackage.AddPackage("UI/TurnPage"); + UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Book", typeof(FairyBook)); + UIObjectFactory.SetPackageItemExtension("ui://TurnPage/Page", typeof(BookPage)); + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + + _book = (FairyBook)_mainView.GetChild("book"); + _book.SetSoftShadowResource("ui://TurnPage/shadow_soft"); + _book.pageRenderer = RenderPage; + _book.pageCount = 20; + _book.currentPage = 0; + _book.ShowCover(FairyBook.CoverType.Front, false); + _book.onTurnComplete.Add(OnTurnComplete); + + GearBase.disableAllTweenEffect = true; + _mainView.GetController("bookPos").selectedIndex = 1; + GearBase.disableAllTweenEffect = false; + + _mainView.GetChild("btnNext").onClick.Add(() => + { + _book.TurnNext(); + }); + _mainView.GetChild("btnPrev").onClick.Add(() => + { + _book.TurnPrevious(); + }); + + _slider = _mainView.GetChild("pageSlide").asSlider; + _slider.max = _book.pageCount - 1; + _slider.value = 0; + _slider.onGripTouchEnd.Add(() => + { + _book.TurnTo((int)_slider.value); + }); + } + + void OnTurnComplete() + { + _slider.value = _book.currentPage; + + if (_book.isCoverShowing(FairyBook.CoverType.Front)) + _mainView.GetController("bookPos").selectedIndex = 1; + else if (_book.isCoverShowing(FairyBook.CoverType.Back)) + _mainView.GetController("bookPos").selectedIndex = 2; + else + _mainView.GetController("bookPos").selectedIndex = 0; + } + + void RenderPage(int index, GComponent page) + { + ((BookPage)page).render(index); + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/TypingEffect/TypingEffectMain.cs b/Assets/Examples/TypingEffect/TypingEffectMain.cs index e7f49d55..5bdd34b7 100644 --- a/Assets/Examples/TypingEffect/TypingEffectMain.cs +++ b/Assets/Examples/TypingEffect/TypingEffectMain.cs @@ -1,44 +1,44 @@ -using UnityEngine; -using FairyGUI; - -public class TypingEffectMain : MonoBehaviour -{ - GComponent _mainView; - TypingEffect _te1; - TypingEffect _te2; - - void Awake() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - } - - void Start() - { - _mainView = this.GetComponent().ui; - - _te1 = new TypingEffect(_mainView.GetChild("n2").asTextField); - _te1.Start(); - Timers.inst.StartCoroutine(_te1.Print(0.050f)); - - _te2 = new TypingEffect(_mainView.GetChild("n3").asTextField); - _te2.Start(); - Timers.inst.Add(0.050f, 0, PrintText); - } - - void PrintText(object param) - { - if (!_te2.Print()) - { - Timers.inst.Remove(PrintText); - } - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class TypingEffectMain : MonoBehaviour +{ + GComponent _mainView; + TypingEffect _te1; + TypingEffect _te2; + + void Awake() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + } + + void Start() + { + _mainView = this.GetComponent().ui; + + _te1 = new TypingEffect(_mainView.GetChild("n2").asTextField); + _te1.Start(); + Timers.inst.StartCoroutine(_te1.Print(0.050f)); + + _te2 = new TypingEffect(_mainView.GetChild("n3").asTextField); + _te2.Start(); + Timers.inst.Add(0.050f, 0, PrintText); + } + + void PrintText(object param) + { + if (!_te2.Print()) + { + Timers.inst.Remove(PrintText); + } + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Examples/VirtualList/VirtualListMain.cs b/Assets/Examples/VirtualList/VirtualListMain.cs index e7f578a3..17ab325d 100644 --- a/Assets/Examples/VirtualList/VirtualListMain.cs +++ b/Assets/Examples/VirtualList/VirtualListMain.cs @@ -1,48 +1,48 @@ -using UnityEngine; -using FairyGUI; - -public class VirtualListMain : MonoBehaviour -{ - GComponent _mainView; - GList _list; - - void Awake() - { - UIPackage.AddPackage("UI/VirtualList"); - UIObjectFactory.SetPackageItemExtension("ui://VirtualList/mailItem", typeof(MailItem)); - } - - void Start() - { - Application.targetFrameRate = 60; - Stage.inst.onKeyDown.Add(OnKeyDown); - - _mainView = this.GetComponent().ui; - _mainView.GetChild("n6").onClick.Add(() => { _list.AddSelection(500, true); }); - _mainView.GetChild("n7").onClick.Add(() => { _list.scrollPane.ScrollTop(); }); - _mainView.GetChild("n8").onClick.Add(() => { _list.scrollPane.ScrollBottom(); }); - - _list = _mainView.GetChild("mailList").asList; - _list.SetVirtual(); - - _list.itemRenderer = RenderListItem; - _list.numItems = 1000; - } - - void RenderListItem(int index, GObject obj) - { - MailItem item = (MailItem)obj; - item.setFetched(index % 3 == 0); - item.setRead(index % 2 == 0); - item.setTime("5 Nov 2015 16:24:33"); - item.title = index + " Mail title here"; - } - - void OnKeyDown(EventContext context) - { - if (context.inputEvent.keyCode == KeyCode.Escape) - { - Application.Quit(); - } - } +using UnityEngine; +using FairyGUI; + +public class VirtualListMain : MonoBehaviour +{ + GComponent _mainView; + GList _list; + + void Awake() + { + UIPackage.AddPackage("UI/VirtualList"); + UIObjectFactory.SetPackageItemExtension("ui://VirtualList/mailItem", typeof(MailItem)); + } + + void Start() + { + Application.targetFrameRate = 60; + Stage.inst.onKeyDown.Add(OnKeyDown); + + _mainView = this.GetComponent().ui; + _mainView.GetChild("n6").onClick.Add(() => { _list.AddSelection(500, true); }); + _mainView.GetChild("n7").onClick.Add(() => { _list.scrollPane.ScrollTop(); }); + _mainView.GetChild("n8").onClick.Add(() => { _list.scrollPane.ScrollBottom(); }); + + _list = _mainView.GetChild("mailList").asList; + _list.SetVirtual(); + + _list.itemRenderer = RenderListItem; + _list.numItems = 1000; + } + + void RenderListItem(int index, GObject obj) + { + MailItem item = (MailItem)obj; + item.setFetched(index % 3 == 0); + item.setRead(index % 2 == 0); + item.setTime("5 Nov 2015 16:24:33"); + item.title = index + " Mail title here"; + } + + void OnKeyDown(EventContext context) + { + if (context.inputEvent.keyCode == KeyCode.Escape) + { + Application.Quit(); + } + } } \ No newline at end of file diff --git a/Assets/Plugins.meta b/Assets/Plugins.meta new file mode 100644 index 00000000..9a0a3f28 --- /dev/null +++ b/Assets/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aa7ce4582c101d74991bd03b2c83ddf7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/FairyGUI.meta b/Assets/Plugins/FairyGUI.meta new file mode 100644 index 00000000..30e71501 --- /dev/null +++ b/Assets/Plugins/FairyGUI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 28cfe268e20887f4ab63d5c388e88ace +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor.meta b/Assets/Plugins/FairyGUI/Editor.meta similarity index 100% rename from Assets/Scripts/Editor.meta rename to Assets/Plugins/FairyGUI/Editor.meta diff --git a/Assets/Scripts/Editor/DisplayObjectEditor.cs b/Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs similarity index 97% rename from Assets/Scripts/Editor/DisplayObjectEditor.cs rename to Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs index f0a87a1f..a307e67d 100644 --- a/Assets/Scripts/Editor/DisplayObjectEditor.cs +++ b/Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs @@ -1,126 +1,126 @@ -using UnityEngine; -using UnityEditor; -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - [CustomEditor(typeof(DisplayObjectInfo))] - public class DisplayObjectEditor : Editor - { - void OnEnable() - { - } - - public override void OnInspectorGUI() - { - DisplayObject obj = (target as DisplayObjectInfo).displayObject; - if (obj == null) - return; - - EditorGUILayout.LabelField(obj.GetType().Name + ": " + obj.id, (GUIStyle)"OL Title"); - EditorGUILayout.Separator(); - EditorGUI.BeginChangeCheck(); - string name = EditorGUILayout.TextField("Name", obj.name); - if (EditorGUI.EndChangeCheck()) - obj.name = name; - if (obj is Container) - { - EditorGUI.BeginChangeCheck(); - bool fairyBatching = EditorGUILayout.Toggle("FairyBatching", ((Container)obj).fairyBatching); - if (EditorGUI.EndChangeCheck()) - ((Container)obj).fairyBatching = fairyBatching; - } - - GObject gObj = obj.gOwner; - if (gObj != null) - { - EditorGUILayout.Separator(); - EditorGUILayout.LabelField(gObj.GetType().Name + ": " + gObj.id, (GUIStyle)"OL Title"); - EditorGUILayout.Separator(); - - if (!string.IsNullOrEmpty(gObj.resourceURL)) - { - PackageItem pi = UIPackage.GetItemByURL(gObj.resourceURL); - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Resource"); - EditorGUILayout.LabelField(pi.name + "@" + pi.owner.name); - EditorGUILayout.EndHorizontal(); - } - - EditorGUI.BeginChangeCheck(); - name = EditorGUILayout.TextField("Name", gObj.name); - if (EditorGUI.EndChangeCheck()) - gObj.name = name; - - if (gObj.parent != null) - { - string[] options = new string[gObj.parent.numChildren]; - int[] values = new int[options.Length]; - for (int i = 0; i < options.Length; i++) - { - options[i] = i.ToString(); - values[i] = i; - } - EditorGUI.BeginChangeCheck(); - int childIndex = EditorGUILayout.IntPopup("Child Index", gObj.parent.GetChildIndex(gObj), options, values); - if (EditorGUI.EndChangeCheck()) - gObj.parent.SetChildIndex(gObj, childIndex); - } - else - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Child Index"); - EditorGUILayout.LabelField("No Parent"); - EditorGUILayout.EndHorizontal(); - } - - EditorGUI.BeginChangeCheck(); - Vector3 position = EditorGUILayout.Vector3Field("Position", gObj.position); - if (EditorGUI.EndChangeCheck()) - gObj.position = position; - - EditorGUI.BeginChangeCheck(); - Vector3 rotation = EditorGUILayout.Vector3Field("Rotation", new Vector3(gObj.rotationX, gObj.rotationY, gObj.rotation)); - if (EditorGUI.EndChangeCheck()) - { - gObj.rotationX = rotation.x; - gObj.rotationY = rotation.y; - gObj.rotation = rotation.z; - } - - EditorGUI.BeginChangeCheck(); - Vector2 scale = EditorGUILayout.Vector2Field("Scale", gObj.scale); - if (EditorGUI.EndChangeCheck()) - gObj.scale = scale; - - EditorGUI.BeginChangeCheck(); - Vector2 skew = EditorGUILayout.Vector2Field("Skew", gObj.skew); - if (EditorGUI.EndChangeCheck()) - gObj.skew = skew; - - EditorGUI.BeginChangeCheck(); - Vector2 size = EditorGUILayout.Vector2Field("Size", gObj.size); - if (EditorGUI.EndChangeCheck()) - gObj.size = size; - - EditorGUI.BeginChangeCheck(); - Vector2 pivot = EditorGUILayout.Vector2Field("Pivot", gObj.pivot); - if (EditorGUI.EndChangeCheck()) - gObj.pivot = pivot; - - EditorGUI.BeginChangeCheck(); - string text = EditorGUILayout.TextField("Text", gObj.text); - if (EditorGUI.EndChangeCheck()) - gObj.text = text; - - EditorGUI.BeginChangeCheck(); - string icon = EditorGUILayout.TextField("Icon", gObj.icon); - if (EditorGUI.EndChangeCheck()) - gObj.icon = icon; - } - } - } -} +using UnityEngine; +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(DisplayObjectInfo))] + public class DisplayObjectEditor : Editor + { + void OnEnable() + { + } + + public override void OnInspectorGUI() + { + DisplayObject obj = (target as DisplayObjectInfo).displayObject; + if (obj == null) + return; + + EditorGUILayout.LabelField(obj.GetType().Name + ": " + obj.id, (GUIStyle)"OL Title"); + EditorGUILayout.Separator(); + EditorGUI.BeginChangeCheck(); + string name = EditorGUILayout.TextField("Name", obj.name); + if (EditorGUI.EndChangeCheck()) + obj.name = name; + if (obj is Container) + { + EditorGUI.BeginChangeCheck(); + bool fairyBatching = EditorGUILayout.Toggle("FairyBatching", ((Container)obj).fairyBatching); + if (EditorGUI.EndChangeCheck()) + ((Container)obj).fairyBatching = fairyBatching; + } + + GObject gObj = obj.gOwner; + if (gObj != null) + { + EditorGUILayout.Separator(); + EditorGUILayout.LabelField(gObj.GetType().Name + ": " + gObj.id, (GUIStyle)"OL Title"); + EditorGUILayout.Separator(); + + if (!string.IsNullOrEmpty(gObj.resourceURL)) + { + PackageItem pi = UIPackage.GetItemByURL(gObj.resourceURL); + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Resource"); + EditorGUILayout.LabelField(pi.name + "@" + pi.owner.name); + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.BeginChangeCheck(); + name = EditorGUILayout.TextField("Name", gObj.name); + if (EditorGUI.EndChangeCheck()) + gObj.name = name; + + if (gObj.parent != null) + { + string[] options = new string[gObj.parent.numChildren]; + int[] values = new int[options.Length]; + for (int i = 0; i < options.Length; i++) + { + options[i] = i.ToString(); + values[i] = i; + } + EditorGUI.BeginChangeCheck(); + int childIndex = EditorGUILayout.IntPopup("Child Index", gObj.parent.GetChildIndex(gObj), options, values); + if (EditorGUI.EndChangeCheck()) + gObj.parent.SetChildIndex(gObj, childIndex); + } + else + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Child Index"); + EditorGUILayout.LabelField("No Parent"); + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.BeginChangeCheck(); + Vector3 position = EditorGUILayout.Vector3Field("Position", gObj.position); + if (EditorGUI.EndChangeCheck()) + gObj.position = position; + + EditorGUI.BeginChangeCheck(); + Vector3 rotation = EditorGUILayout.Vector3Field("Rotation", new Vector3(gObj.rotationX, gObj.rotationY, gObj.rotation)); + if (EditorGUI.EndChangeCheck()) + { + gObj.rotationX = rotation.x; + gObj.rotationY = rotation.y; + gObj.rotation = rotation.z; + } + + EditorGUI.BeginChangeCheck(); + Vector2 scale = EditorGUILayout.Vector2Field("Scale", gObj.scale); + if (EditorGUI.EndChangeCheck()) + gObj.scale = scale; + + EditorGUI.BeginChangeCheck(); + Vector2 skew = EditorGUILayout.Vector2Field("Skew", gObj.skew); + if (EditorGUI.EndChangeCheck()) + gObj.skew = skew; + + EditorGUI.BeginChangeCheck(); + Vector2 size = EditorGUILayout.Vector2Field("Size", gObj.size); + if (EditorGUI.EndChangeCheck()) + gObj.size = size; + + EditorGUI.BeginChangeCheck(); + Vector2 pivot = EditorGUILayout.Vector2Field("Pivot", gObj.pivot); + if (EditorGUI.EndChangeCheck()) + gObj.pivot = pivot; + + EditorGUI.BeginChangeCheck(); + string text = EditorGUILayout.TextField("Text", gObj.text); + if (EditorGUI.EndChangeCheck()) + gObj.text = text; + + EditorGUI.BeginChangeCheck(); + string icon = EditorGUILayout.TextField("Icon", gObj.icon); + if (EditorGUI.EndChangeCheck()) + gObj.icon = icon; + } + } + } +} diff --git a/Assets/Scripts/Editor/DisplayObjectEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs.meta similarity index 100% rename from Assets/Scripts/Editor/DisplayObjectEditor.cs.meta rename to Assets/Plugins/FairyGUI/Editor/DisplayObjectEditor.cs.meta diff --git a/Assets/Scripts/Editor/EditorToolSet.cs b/Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs similarity index 96% rename from Assets/Scripts/Editor/EditorToolSet.cs rename to Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs index 9910fe82..b736ef6e 100644 --- a/Assets/Scripts/Editor/EditorToolSet.cs +++ b/Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs @@ -1,135 +1,135 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEditor; -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - public class EditorToolSet - { - public static GUIContent[] packagesPopupContents; - - static bool _loaded; - - [InitializeOnLoadMethod] - static void Startup() - { - EditorApplication.update += EditorApplication_Update; - } - - [MenuItem("GameObject/FairyGUI/UI Panel", false, 0)] - static void CreatePanel() - { - EditorApplication.update -= EditorApplication_Update; - EditorApplication.update += EditorApplication_Update; - - StageCamera.CheckMainCamera(); - - GameObject panelObject = new GameObject("UIPanel"); - if (Selection.activeGameObject != null) - { - panelObject.transform.parent = Selection.activeGameObject.transform; - panelObject.layer = Selection.activeGameObject.layer; - } - else - { - int layer = LayerMask.NameToLayer(StageCamera.LayerName); - panelObject.layer = layer; - } - panelObject.AddComponent(); - Selection.objects = new Object[] { panelObject }; - } - - [MenuItem("GameObject/FairyGUI/UI Camera", false, 0)] - static void CreateCamera() - { - StageCamera.CheckMainCamera(); - Selection.objects = new Object[] { StageCamera.main.gameObject }; - } - - [MenuItem("Window/FairyGUI - Refresh Packages And Panels")] - static void RefreshPanels() - { - ReloadPackages(); - } - - static void EditorApplication_Update() - { - if (Application.isPlaying) - return; - - if (_loaded || !EMRenderSupport.hasTarget) - return; - - LoadPackages(); - } - - public static void ReloadPackages() - { - if (!Application.isPlaying) - { - _loaded = false; - LoadPackages(); - Debug.Log("FairyGUI - Refresh Packages And Panels complete."); - } - else - EditorUtility.DisplayDialog("FairyGUI", "Cannot run in play mode.", "OK"); - } - - public static void LoadPackages() - { - if (Application.isPlaying || _loaded) - return; - - EditorApplication.update -= EditorApplication_Update; - EditorApplication.update += EditorApplication_Update; - - _loaded = true; - - UIPackage.RemoveAllPackages(); - FontManager.Clear(); - NTexture.DisposeEmpty(); - UIObjectFactory.Clear(); - - string[] ids = AssetDatabase.FindAssets("_fui t:textAsset"); - int cnt = ids.Length; - for (int i = 0; i < cnt; i++) - { - string assetPath = AssetDatabase.GUIDToAssetPath(ids[i]); - int pos = assetPath.LastIndexOf("_fui"); - if (pos == -1) - continue; - - assetPath = assetPath.Substring(0, pos); - if (AssetDatabase.AssetPathToGUID(assetPath) != null) - UIPackage.AddPackage(assetPath, - (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => - { - destroyMethod = DestroyMethod.Unload; - return AssetDatabase.LoadAssetAtPath(name + extension, type); - } - ); - } - - List pkgs = UIPackage.GetPackages(); - pkgs.Sort(CompareUIPackage); - - cnt = pkgs.Count; - packagesPopupContents = new GUIContent[cnt + 1]; - for (int i = 0; i < cnt; i++) - packagesPopupContents[i] = new GUIContent(pkgs[i].name); - packagesPopupContents[cnt] = new GUIContent("Please Select"); - - EMRenderSupport.Reload(); - } - - static int CompareUIPackage(UIPackage u1, UIPackage u2) - { - return u1.name.CompareTo(u2.name); - } - } - -} +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + public class EditorToolSet + { + public static GUIContent[] packagesPopupContents; + + static bool _loaded; + + [InitializeOnLoadMethod] + static void Startup() + { + EditorApplication.update += EditorApplication_Update; + } + + [MenuItem("GameObject/FairyGUI/UI Panel", false, 0)] + static void CreatePanel() + { + EditorApplication.update -= EditorApplication_Update; + EditorApplication.update += EditorApplication_Update; + + StageCamera.CheckMainCamera(); + + GameObject panelObject = new GameObject("UIPanel"); + if (Selection.activeGameObject != null) + { + panelObject.transform.parent = Selection.activeGameObject.transform; + panelObject.layer = Selection.activeGameObject.layer; + } + else + { + int layer = LayerMask.NameToLayer(StageCamera.LayerName); + panelObject.layer = layer; + } + panelObject.AddComponent(); + Selection.objects = new Object[] { panelObject }; + } + + [MenuItem("GameObject/FairyGUI/UI Camera", false, 0)] + static void CreateCamera() + { + StageCamera.CheckMainCamera(); + Selection.objects = new Object[] { StageCamera.main.gameObject }; + } + + [MenuItem("Window/FairyGUI - Refresh Packages And Panels")] + static void RefreshPanels() + { + ReloadPackages(); + } + + static void EditorApplication_Update() + { + if (Application.isPlaying) + return; + + if (_loaded || !EMRenderSupport.hasTarget) + return; + + LoadPackages(); + } + + public static void ReloadPackages() + { + if (!Application.isPlaying) + { + _loaded = false; + LoadPackages(); + Debug.Log("FairyGUI - Refresh Packages And Panels complete."); + } + else + EditorUtility.DisplayDialog("FairyGUI", "Cannot run in play mode.", "OK"); + } + + public static void LoadPackages() + { + if (Application.isPlaying || _loaded) + return; + + EditorApplication.update -= EditorApplication_Update; + EditorApplication.update += EditorApplication_Update; + + _loaded = true; + + UIPackage.RemoveAllPackages(); + FontManager.Clear(); + NTexture.DisposeEmpty(); + UIObjectFactory.Clear(); + + string[] ids = AssetDatabase.FindAssets("_fui t:textAsset"); + int cnt = ids.Length; + for (int i = 0; i < cnt; i++) + { + string assetPath = AssetDatabase.GUIDToAssetPath(ids[i]); + int pos = assetPath.LastIndexOf("_fui"); + if (pos == -1) + continue; + + assetPath = assetPath.Substring(0, pos); + if (AssetDatabase.AssetPathToGUID(assetPath) != null) + UIPackage.AddPackage(assetPath, + (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => + { + destroyMethod = DestroyMethod.Unload; + return AssetDatabase.LoadAssetAtPath(name + extension, type); + } + ); + } + + List pkgs = UIPackage.GetPackages(); + pkgs.Sort(CompareUIPackage); + + cnt = pkgs.Count; + packagesPopupContents = new GUIContent[cnt + 1]; + for (int i = 0; i < cnt; i++) + packagesPopupContents[i] = new GUIContent(pkgs[i].name); + packagesPopupContents[cnt] = new GUIContent("Please Select"); + + EMRenderSupport.Reload(); + } + + static int CompareUIPackage(UIPackage u1, UIPackage u2) + { + return u1.name.CompareTo(u2.name); + } + } + +} diff --git a/Assets/Scripts/Editor/EditorToolSet.cs.meta b/Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs.meta similarity index 100% rename from Assets/Scripts/Editor/EditorToolSet.cs.meta rename to Assets/Plugins/FairyGUI/Editor/EditorToolSet.cs.meta diff --git a/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef new file mode 100644 index 00000000..6d7246a3 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef @@ -0,0 +1,18 @@ +{ + "name": "FairyGUI.Editor", + "rootNamespace": "", + "references": [ + "GUID:b12c828e10494534a9050867cfc5ed0c" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef.meta b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef.meta new file mode 100644 index 00000000..b333f151 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Editor/FairyGUI.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9b0d782762190cc46bfb2dd2ab152107 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/PackagesWindow.cs b/Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs similarity index 97% rename from Assets/Scripts/Editor/PackagesWindow.cs rename to Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs index 227478a6..0fb36663 100644 --- a/Assets/Scripts/Editor/PackagesWindow.cs +++ b/Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs @@ -1,201 +1,201 @@ -using System.Collections.Generic; -using UnityEngine; -using UnityEditor; -#if UNITY_5_3_OR_NEWER -using UnityEditor.SceneManagement; -#endif -#if UNITY_2018_3_OR_NEWER -using UnityEditor.Experimental.SceneManagement; -#endif -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - public class PackagesWindow : EditorWindow - { - Vector2 scrollPos1; - Vector2 scrollPos2; - GUIStyle itemStyle; - - int selectedPackage; - string selectedPackageName; - string selectedComponentName; - - public PackagesWindow() - { - this.maxSize = new Vector2(550, 400); - this.minSize = new Vector2(550, 400); - } - - public void SetSelection(string packageName, string componentName) - { - selectedPackageName = packageName; - selectedComponentName = componentName; - } - - void OnGUI() - { - if (itemStyle == null) - itemStyle = new GUIStyle(GUI.skin.GetStyle("Tag MenuItem")); - - EditorGUILayout.BeginHorizontal(); - - //package list start------ - EditorGUILayout.BeginHorizontal(); - GUILayout.Space(5); - - EditorGUILayout.BeginVertical(); - GUILayout.Space(10); - - EditorGUILayout.LabelField("Packages", (GUIStyle)"OL Title", GUILayout.Width(300)); - GUILayout.Space(5); - - EditorGUILayout.BeginHorizontal(); - GUILayout.Space(4); - - scrollPos1 = EditorGUILayout.BeginScrollView(scrollPos1, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(300)); - EditorToolSet.LoadPackages(); - List pkgs = UIPackage.GetPackages(); - int cnt = pkgs.Count; - if (cnt == 0) - { - selectedPackage = -1; - selectedPackageName = null; - } - else - { - for (int i = 0; i < cnt; i++) - { - EditorGUILayout.BeginHorizontal(); - if (GUILayout.Toggle(selectedPackageName == pkgs[i].name, pkgs[i].name, itemStyle, GUILayout.ExpandWidth(true))) - { - selectedPackage = i; - selectedPackageName = pkgs[i].name; - } - EditorGUILayout.EndHorizontal(); - } - } - EditorGUILayout.EndScrollView(); - - EditorGUILayout.EndHorizontal(); - - EditorGUILayout.EndVertical(); - - EditorGUILayout.EndHorizontal(); - - //package list end------ - - //component list start------ - - EditorGUILayout.BeginHorizontal(); - GUILayout.Space(5); - - EditorGUILayout.BeginVertical(); - GUILayout.Space(10); - - EditorGUILayout.LabelField("Components", (GUIStyle)"OL Title", GUILayout.Width(220)); - GUILayout.Space(5); - - EditorGUILayout.BeginHorizontal(); - GUILayout.Space(4); - - scrollPos2 = EditorGUILayout.BeginScrollView(scrollPos2, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(220)); - if (selectedPackage >= 0) - { - List items = pkgs[selectedPackage].GetItems(); - int i = 0; - foreach (PackageItem pi in items) - { - if (pi.type == PackageItemType.Component && pi.exported) - { - EditorGUILayout.BeginHorizontal(); - if (GUILayout.Toggle(selectedComponentName == pi.name, pi.name, itemStyle, GUILayout.ExpandWidth(true))) - selectedComponentName = pi.name; - i++; - EditorGUILayout.EndHorizontal(); - } - } - } - EditorGUILayout.EndScrollView(); - - EditorGUILayout.EndHorizontal(); - - EditorGUILayout.EndVertical(); - - EditorGUILayout.EndHorizontal(); - - //component list end------ - - GUILayout.Space(10); - - EditorGUILayout.EndHorizontal(); - - GUILayout.Space(20); - - //buttons start--- - EditorGUILayout.BeginHorizontal(); - - GUILayout.Space(180); - - if (GUILayout.Button("Refresh", GUILayout.Width(100))) - EditorToolSet.ReloadPackages(); - - GUILayout.Space(20); - if (GUILayout.Button("OK", GUILayout.Width(100)) && selectedPackage >= 0) - { - UIPackage selectedPkg = pkgs[selectedPackage]; - string tmp = selectedPkg.assetPath.ToLower(); - string packagePath; - int pos = tmp.LastIndexOf("/resources/"); - if (pos != -1) - packagePath = selectedPkg.assetPath.Substring(pos + 11); - else - { - pos = tmp.IndexOf("resources/"); - if (pos == 0) - packagePath = selectedPkg.assetPath.Substring(pos + 10); - else - packagePath = selectedPkg.assetPath; - } - if (Selection.activeGameObject != null) - { -#if UNITY_2018_3_OR_NEWER - bool isPrefab = PrefabUtility.GetPrefabAssetType(Selection.activeGameObject) != PrefabAssetType.NotAPrefab; -#else - bool isPrefab = PrefabUtility.GetPrefabType(Selection.activeGameObject) == PrefabType.Prefab; -#endif - Selection.activeGameObject.SendMessage("OnUpdateSource", - new object[] { selectedPkg.name, packagePath, selectedComponentName, !isPrefab }, - SendMessageOptions.DontRequireReceiver); - } - -#if UNITY_2018_3_OR_NEWER - PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); - if (prefabStage != null) - EditorSceneManager.MarkSceneDirty(prefabStage.scene); - else - ApplyChange(); -#else - ApplyChange(); -#endif - this.Close(); - } - - EditorGUILayout.EndHorizontal(); - } - - void ApplyChange() - { -#if UNITY_5_3_OR_NEWER - EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); -#elif UNITY_5 - EditorApplication.MarkSceneDirty(); -#else - EditorUtility.SetDirty(Selection.activeGameObject); -#endif - } - } -} +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +#if UNITY_5_3_OR_NEWER +using UnityEditor.SceneManagement; +#endif +#if UNITY_2018_3_OR_NEWER +using UnityEditor.Experimental.SceneManagement; +#endif +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + public class PackagesWindow : EditorWindow + { + Vector2 scrollPos1; + Vector2 scrollPos2; + GUIStyle itemStyle; + + int selectedPackage; + string selectedPackageName; + string selectedComponentName; + + public PackagesWindow() + { + this.maxSize = new Vector2(550, 400); + this.minSize = new Vector2(550, 400); + } + + public void SetSelection(string packageName, string componentName) + { + selectedPackageName = packageName; + selectedComponentName = componentName; + } + + void OnGUI() + { + if (itemStyle == null) + itemStyle = new GUIStyle(GUI.skin.GetStyle("Tag MenuItem")); + + EditorGUILayout.BeginHorizontal(); + + //package list start------ + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(5); + + EditorGUILayout.BeginVertical(); + GUILayout.Space(10); + + EditorGUILayout.LabelField("Packages", (GUIStyle)"OL Title", GUILayout.Width(300)); + GUILayout.Space(5); + + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(4); + + scrollPos1 = EditorGUILayout.BeginScrollView(scrollPos1, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(300)); + EditorToolSet.LoadPackages(); + List pkgs = UIPackage.GetPackages(); + int cnt = pkgs.Count; + if (cnt == 0) + { + selectedPackage = -1; + selectedPackageName = null; + } + else + { + for (int i = 0; i < cnt; i++) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(selectedPackageName == pkgs[i].name, pkgs[i].name, itemStyle, GUILayout.ExpandWidth(true))) + { + selectedPackage = i; + selectedPackageName = pkgs[i].name; + } + EditorGUILayout.EndHorizontal(); + } + } + EditorGUILayout.EndScrollView(); + + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndHorizontal(); + + //package list end------ + + //component list start------ + + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(5); + + EditorGUILayout.BeginVertical(); + GUILayout.Space(10); + + EditorGUILayout.LabelField("Components", (GUIStyle)"OL Title", GUILayout.Width(220)); + GUILayout.Space(5); + + EditorGUILayout.BeginHorizontal(); + GUILayout.Space(4); + + scrollPos2 = EditorGUILayout.BeginScrollView(scrollPos2, (GUIStyle)"CN Box", GUILayout.Height(300), GUILayout.Width(220)); + if (selectedPackage >= 0) + { + List items = pkgs[selectedPackage].GetItems(); + int i = 0; + foreach (PackageItem pi in items) + { + if (pi.type == PackageItemType.Component && pi.exported) + { + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Toggle(selectedComponentName == pi.name, pi.name, itemStyle, GUILayout.ExpandWidth(true))) + selectedComponentName = pi.name; + i++; + EditorGUILayout.EndHorizontal(); + } + } + } + EditorGUILayout.EndScrollView(); + + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndHorizontal(); + + //component list end------ + + GUILayout.Space(10); + + EditorGUILayout.EndHorizontal(); + + GUILayout.Space(20); + + //buttons start--- + EditorGUILayout.BeginHorizontal(); + + GUILayout.Space(180); + + if (GUILayout.Button("Refresh", GUILayout.Width(100))) + EditorToolSet.ReloadPackages(); + + GUILayout.Space(20); + if (GUILayout.Button("OK", GUILayout.Width(100)) && selectedPackage >= 0) + { + UIPackage selectedPkg = pkgs[selectedPackage]; + string tmp = selectedPkg.assetPath.ToLower(); + string packagePath; + int pos = tmp.LastIndexOf("/resources/"); + if (pos != -1) + packagePath = selectedPkg.assetPath.Substring(pos + 11); + else + { + pos = tmp.IndexOf("resources/"); + if (pos == 0) + packagePath = selectedPkg.assetPath.Substring(pos + 10); + else + packagePath = selectedPkg.assetPath; + } + if (Selection.activeGameObject != null) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(Selection.activeGameObject) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(Selection.activeGameObject) == PrefabType.Prefab; +#endif + Selection.activeGameObject.SendMessage("OnUpdateSource", + new object[] { selectedPkg.name, packagePath, selectedComponentName, !isPrefab }, + SendMessageOptions.DontRequireReceiver); + } + +#if UNITY_2018_3_OR_NEWER + PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage(); + if (prefabStage != null) + EditorSceneManager.MarkSceneDirty(prefabStage.scene); + else + ApplyChange(); +#else + ApplyChange(); +#endif + this.Close(); + } + + EditorGUILayout.EndHorizontal(); + } + + void ApplyChange() + { +#if UNITY_5_3_OR_NEWER + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); +#elif UNITY_5 + EditorApplication.MarkSceneDirty(); +#else + EditorUtility.SetDirty(Selection.activeGameObject); +#endif + } + } +} diff --git a/Assets/Scripts/Editor/PackagesWindow.cs.meta b/Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs.meta similarity index 100% rename from Assets/Scripts/Editor/PackagesWindow.cs.meta rename to Assets/Plugins/FairyGUI/Editor/PackagesWindow.cs.meta diff --git a/Assets/Scripts/Editor/StageCameraEditor.cs b/Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs similarity index 95% rename from Assets/Scripts/Editor/StageCameraEditor.cs rename to Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs index 58dba48f..0e7bba90 100644 --- a/Assets/Scripts/Editor/StageCameraEditor.cs +++ b/Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs @@ -1,29 +1,29 @@ -using UnityEditor; -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - [CustomEditor(typeof(StageCamera))] - public class StageCameraEditor : Editor - { - string[] propertyToExclude; - - void OnEnable() - { - propertyToExclude = new string[] { "m_Script" }; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - DrawPropertiesExcluding(serializedObject, propertyToExclude); - - if (serializedObject.ApplyModifiedProperties()) - (target as StageCamera).ApplyModifiedProperties(); - } - } -} +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(StageCamera))] + public class StageCameraEditor : Editor + { + string[] propertyToExclude; + + void OnEnable() + { + propertyToExclude = new string[] { "m_Script" }; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + if (serializedObject.ApplyModifiedProperties()) + (target as StageCamera).ApplyModifiedProperties(); + } + } +} diff --git a/Assets/Scripts/Editor/StageCameraEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs.meta similarity index 100% rename from Assets/Scripts/Editor/StageCameraEditor.cs.meta rename to Assets/Plugins/FairyGUI/Editor/StageCameraEditor.cs.meta diff --git a/Assets/Scripts/Editor/UIConfigEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs similarity index 97% rename from Assets/Scripts/Editor/UIConfigEditor.cs rename to Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs index 279ddb48..dc6a828e 100644 --- a/Assets/Scripts/Editor/UIConfigEditor.cs +++ b/Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs @@ -1,226 +1,226 @@ -using UnityEngine; -using UnityEditor; -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - [CustomEditor(typeof(UIConfig))] - public class UIConfigEditor : Editor - { - string[] propertyToExclude; - bool itemsFoldout; - bool packagesFoldOut; - int errorState; - - private const float kButtonWidth = 18f; - - void OnEnable() - { - propertyToExclude = new string[] { "m_Script", "Items", "PreloadPackages" }; - - itemsFoldout = EditorPrefs.GetBool("itemsFoldOut"); - packagesFoldOut = EditorPrefs.GetBool("packagesFoldOut"); - errorState = 0; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - DrawPropertiesExcluding(serializedObject, propertyToExclude); - - UIConfig config = (UIConfig)target; - - EditorGUILayout.BeginHorizontal(); - EditorGUI.BeginChangeCheck(); - itemsFoldout = EditorGUILayout.Foldout(itemsFoldout, "Config Items"); - if (EditorGUI.EndChangeCheck()) - EditorPrefs.SetBool("itemsFoldOut", itemsFoldout); - EditorGUILayout.EndHorizontal(); - - bool modified = false; - - if (itemsFoldout) - { - Undo.RecordObject(config, "Items"); - - int len = config.Items.Count; - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Add"); - UIConfig.ConfigKey selectedKey = (UIConfig.ConfigKey)EditorGUILayout.EnumPopup((System.Enum)UIConfig.ConfigKey.PleaseSelect); - - if (selectedKey != UIConfig.ConfigKey.PleaseSelect) - { - int index = (int)selectedKey; - - if (index > len - 1) - { - for (int i = len; i < index; i++) - config.Items.Add(new UIConfig.ConfigValue()); - - UIConfig.ConfigValue value = new UIConfig.ConfigValue(); - value.valid = true; - UIConfig.SetDefaultValue(selectedKey, value); - config.Items.Add(value); - } - else - { - UIConfig.ConfigValue value = config.Items[index]; - if (value == null) - { - value = new UIConfig.ConfigValue(); - value.valid = true; - UIConfig.SetDefaultValue(selectedKey, value); - config.Items[index] = value; - } - else if (!value.valid) - { - value.valid = true; - UIConfig.SetDefaultValue(selectedKey, value); - } - } - } - EditorGUILayout.EndHorizontal(); - - for (int i = 0; i < len; i++) - { - UIConfig.ConfigValue value = config.Items[i]; - if (value == null || !value.valid) - continue; - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel(((UIConfig.ConfigKey)i).ToString()); - switch ((UIConfig.ConfigKey)i) - { - case UIConfig.ConfigKey.ClickDragSensitivity: - case UIConfig.ConfigKey.DefaultComboBoxVisibleItemCount: - case UIConfig.ConfigKey.DefaultScrollStep: - case UIConfig.ConfigKey.TouchDragSensitivity: - case UIConfig.ConfigKey.TouchScrollSensitivity: - case UIConfig.ConfigKey.InputCaretSize: - value.i = EditorGUILayout.IntField(value.i); - break; - - case UIConfig.ConfigKey.ButtonSound: - case UIConfig.ConfigKey.GlobalModalWaiting: - case UIConfig.ConfigKey.HorizontalScrollBar: - case UIConfig.ConfigKey.LoaderErrorSign: - case UIConfig.ConfigKey.PopupMenu: - case UIConfig.ConfigKey.PopupMenu_seperator: - case UIConfig.ConfigKey.TooltipsWin: - case UIConfig.ConfigKey.VerticalScrollBar: - case UIConfig.ConfigKey.WindowModalWaiting: - case UIConfig.ConfigKey.DefaultFont: - value.s = EditorGUILayout.TextField(value.s); - break; - - case UIConfig.ConfigKey.DefaultScrollBounceEffect: - case UIConfig.ConfigKey.DefaultScrollTouchEffect: - case UIConfig.ConfigKey.RenderingTextBrighterOnDesktop: - case UIConfig.ConfigKey.AllowSoftnessOnTopOrLeftSide: - case UIConfig.ConfigKey.DepthSupportForPaintingMode: - value.b = EditorGUILayout.Toggle(value.b); - break; - - case UIConfig.ConfigKey.ButtonSoundVolumeScale: - value.f = EditorGUILayout.Slider(value.f, 0, 1); - break; - - case UIConfig.ConfigKey.ModalLayerColor: - case UIConfig.ConfigKey.InputHighlightColor: - value.c = EditorGUILayout.ColorField(value.c); - break; - - case UIConfig.ConfigKey.Branch: - EditorGUI.BeginChangeCheck(); - value.s = EditorGUILayout.TextField(value.s); - if (EditorGUI.EndChangeCheck()) - modified = true; - break; - } - - if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) - { - config.Items[i].Reset(); - UIConfig.SetDefaultValue((UIConfig.ConfigKey)i, config.Items[i]); - modified = true; - } - EditorGUILayout.EndHorizontal(); - } - } - - EditorGUILayout.BeginHorizontal(); - EditorGUI.BeginChangeCheck(); - packagesFoldOut = EditorGUILayout.Foldout(packagesFoldOut, "Preload Packages"); - if (EditorGUI.EndChangeCheck()) - EditorPrefs.SetBool("packagesFoldOut", packagesFoldOut); - EditorGUILayout.EndHorizontal(); - - if (packagesFoldOut) - { - Undo.RecordObject(config, "PreloadPackages"); - - EditorToolSet.LoadPackages(); - - if (EditorToolSet.packagesPopupContents != null) - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Add"); - int selected = EditorGUILayout.Popup(EditorToolSet.packagesPopupContents.Length - 1, EditorToolSet.packagesPopupContents); - EditorGUILayout.EndHorizontal(); - - if (selected != EditorToolSet.packagesPopupContents.Length - 1) - { - UIPackage pkg = UIPackage.GetPackages()[selected]; - string tmp = pkg.assetPath.ToLower(); - int pos = tmp.LastIndexOf("resources/"); - if (pos != -1) - { - string packagePath = pkg.assetPath.Substring(pos + 10); - if (config.PreloadPackages.IndexOf(packagePath) == -1) - config.PreloadPackages.Add(packagePath); - - errorState = 0; - } - else - { - errorState = 10; - } - } - } - - if (errorState > 0) - { - errorState--; - EditorGUILayout.HelpBox("Package is not in resources folder.", MessageType.Warning); - } - - int cnt = config.PreloadPackages.Count; - int pi = 0; - while (pi < cnt) - { - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("" + pi + "."); - config.PreloadPackages[pi] = EditorGUILayout.TextField(config.PreloadPackages[pi]); - if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) - { - config.PreloadPackages.RemoveAt(pi); - cnt--; - } - else - pi++; - EditorGUILayout.EndHorizontal(); - } - } - else - errorState = 0; - - if (serializedObject.ApplyModifiedProperties() || modified) - (target as UIConfig).ApplyModifiedProperties(); - } - } -} +using UnityEngine; +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(UIConfig))] + public class UIConfigEditor : Editor + { + string[] propertyToExclude; + bool itemsFoldout; + bool packagesFoldOut; + int errorState; + + private const float kButtonWidth = 18f; + + void OnEnable() + { + propertyToExclude = new string[] { "m_Script", "Items", "PreloadPackages" }; + + itemsFoldout = EditorPrefs.GetBool("itemsFoldOut"); + packagesFoldOut = EditorPrefs.GetBool("packagesFoldOut"); + errorState = 0; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + UIConfig config = (UIConfig)target; + + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginChangeCheck(); + itemsFoldout = EditorGUILayout.Foldout(itemsFoldout, "Config Items"); + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetBool("itemsFoldOut", itemsFoldout); + EditorGUILayout.EndHorizontal(); + + bool modified = false; + + if (itemsFoldout) + { + Undo.RecordObject(config, "Items"); + + int len = config.Items.Count; + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Add"); + UIConfig.ConfigKey selectedKey = (UIConfig.ConfigKey)EditorGUILayout.EnumPopup((System.Enum)UIConfig.ConfigKey.PleaseSelect); + + if (selectedKey != UIConfig.ConfigKey.PleaseSelect) + { + int index = (int)selectedKey; + + if (index > len - 1) + { + for (int i = len; i < index; i++) + config.Items.Add(new UIConfig.ConfigValue()); + + UIConfig.ConfigValue value = new UIConfig.ConfigValue(); + value.valid = true; + UIConfig.SetDefaultValue(selectedKey, value); + config.Items.Add(value); + } + else + { + UIConfig.ConfigValue value = config.Items[index]; + if (value == null) + { + value = new UIConfig.ConfigValue(); + value.valid = true; + UIConfig.SetDefaultValue(selectedKey, value); + config.Items[index] = value; + } + else if (!value.valid) + { + value.valid = true; + UIConfig.SetDefaultValue(selectedKey, value); + } + } + } + EditorGUILayout.EndHorizontal(); + + for (int i = 0; i < len; i++) + { + UIConfig.ConfigValue value = config.Items[i]; + if (value == null || !value.valid) + continue; + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel(((UIConfig.ConfigKey)i).ToString()); + switch ((UIConfig.ConfigKey)i) + { + case UIConfig.ConfigKey.ClickDragSensitivity: + case UIConfig.ConfigKey.DefaultComboBoxVisibleItemCount: + case UIConfig.ConfigKey.DefaultScrollStep: + case UIConfig.ConfigKey.TouchDragSensitivity: + case UIConfig.ConfigKey.TouchScrollSensitivity: + case UIConfig.ConfigKey.InputCaretSize: + value.i = EditorGUILayout.IntField(value.i); + break; + + case UIConfig.ConfigKey.ButtonSound: + case UIConfig.ConfigKey.GlobalModalWaiting: + case UIConfig.ConfigKey.HorizontalScrollBar: + case UIConfig.ConfigKey.LoaderErrorSign: + case UIConfig.ConfigKey.PopupMenu: + case UIConfig.ConfigKey.PopupMenu_seperator: + case UIConfig.ConfigKey.TooltipsWin: + case UIConfig.ConfigKey.VerticalScrollBar: + case UIConfig.ConfigKey.WindowModalWaiting: + case UIConfig.ConfigKey.DefaultFont: + value.s = EditorGUILayout.TextField(value.s); + break; + + case UIConfig.ConfigKey.DefaultScrollBounceEffect: + case UIConfig.ConfigKey.DefaultScrollTouchEffect: + case UIConfig.ConfigKey.RenderingTextBrighterOnDesktop: + case UIConfig.ConfigKey.AllowSoftnessOnTopOrLeftSide: + case UIConfig.ConfigKey.DepthSupportForPaintingMode: + value.b = EditorGUILayout.Toggle(value.b); + break; + + case UIConfig.ConfigKey.ButtonSoundVolumeScale: + value.f = EditorGUILayout.Slider(value.f, 0, 1); + break; + + case UIConfig.ConfigKey.ModalLayerColor: + case UIConfig.ConfigKey.InputHighlightColor: + value.c = EditorGUILayout.ColorField(value.c); + break; + + case UIConfig.ConfigKey.Branch: + EditorGUI.BeginChangeCheck(); + value.s = EditorGUILayout.TextField(value.s); + if (EditorGUI.EndChangeCheck()) + modified = true; + break; + } + + if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) + { + config.Items[i].Reset(); + UIConfig.SetDefaultValue((UIConfig.ConfigKey)i, config.Items[i]); + modified = true; + } + EditorGUILayout.EndHorizontal(); + } + } + + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginChangeCheck(); + packagesFoldOut = EditorGUILayout.Foldout(packagesFoldOut, "Preload Packages"); + if (EditorGUI.EndChangeCheck()) + EditorPrefs.SetBool("packagesFoldOut", packagesFoldOut); + EditorGUILayout.EndHorizontal(); + + if (packagesFoldOut) + { + Undo.RecordObject(config, "PreloadPackages"); + + EditorToolSet.LoadPackages(); + + if (EditorToolSet.packagesPopupContents != null) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Add"); + int selected = EditorGUILayout.Popup(EditorToolSet.packagesPopupContents.Length - 1, EditorToolSet.packagesPopupContents); + EditorGUILayout.EndHorizontal(); + + if (selected != EditorToolSet.packagesPopupContents.Length - 1) + { + UIPackage pkg = UIPackage.GetPackages()[selected]; + string tmp = pkg.assetPath.ToLower(); + int pos = tmp.LastIndexOf("resources/"); + if (pos != -1) + { + string packagePath = pkg.assetPath.Substring(pos + 10); + if (config.PreloadPackages.IndexOf(packagePath) == -1) + config.PreloadPackages.Add(packagePath); + + errorState = 0; + } + else + { + errorState = 10; + } + } + } + + if (errorState > 0) + { + errorState--; + EditorGUILayout.HelpBox("Package is not in resources folder.", MessageType.Warning); + } + + int cnt = config.PreloadPackages.Count; + int pi = 0; + while (pi < cnt) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("" + pi + "."); + config.PreloadPackages[pi] = EditorGUILayout.TextField(config.PreloadPackages[pi]); + if (GUILayout.Button(new GUIContent("X", "Delete Item"), EditorStyles.miniButtonRight, GUILayout.Width(30))) + { + config.PreloadPackages.RemoveAt(pi); + cnt--; + } + else + pi++; + EditorGUILayout.EndHorizontal(); + } + } + else + errorState = 0; + + if (serializedObject.ApplyModifiedProperties() || modified) + (target as UIConfig).ApplyModifiedProperties(); + } + } +} diff --git a/Assets/Scripts/Editor/UIConfigEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs.meta similarity index 100% rename from Assets/Scripts/Editor/UIConfigEditor.cs.meta rename to Assets/Plugins/FairyGUI/Editor/UIConfigEditor.cs.meta diff --git a/Assets/Scripts/Editor/UIContentScalerEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs similarity index 97% rename from Assets/Scripts/Editor/UIContentScalerEditor.cs rename to Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs index c04277d0..f874c985 100644 --- a/Assets/Scripts/Editor/UIContentScalerEditor.cs +++ b/Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs @@ -1,64 +1,64 @@ -using UnityEditor; -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - [CustomEditor(typeof(UIContentScaler))] - public class UIContentScalerEditor : Editor - { - SerializedProperty scaleMode; - SerializedProperty screenMatchMode; - SerializedProperty designResolutionX; - SerializedProperty designResolutionY; - SerializedProperty fallbackScreenDPI; - SerializedProperty defaultSpriteDPI; - SerializedProperty constantScaleFactor; - SerializedProperty ignoreOrientation; - - string[] propertyToExclude; - - void OnEnable() - { - scaleMode = serializedObject.FindProperty("scaleMode"); - screenMatchMode = serializedObject.FindProperty("screenMatchMode"); - designResolutionX = serializedObject.FindProperty("designResolutionX"); - designResolutionY = serializedObject.FindProperty("designResolutionY"); - fallbackScreenDPI = serializedObject.FindProperty("fallbackScreenDPI"); - defaultSpriteDPI = serializedObject.FindProperty("defaultSpriteDPI"); - constantScaleFactor = serializedObject.FindProperty("constantScaleFactor"); - ignoreOrientation = serializedObject.FindProperty("ignoreOrientation"); - - propertyToExclude = new string[] { "m_Script", "scaleMode", "screenMatchMode", "designResolutionX", "designResolutionY", - "fallbackScreenDPI", "defaultSpriteDPI", "constantScaleFactor", "ignoreOrientation"}; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - DrawPropertiesExcluding(serializedObject, propertyToExclude); - - EditorGUILayout.PropertyField(scaleMode); - if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ScaleWithScreenSize) - { - EditorGUILayout.PropertyField(designResolutionX); - EditorGUILayout.PropertyField(designResolutionY); - EditorGUILayout.PropertyField(screenMatchMode); - EditorGUILayout.PropertyField(ignoreOrientation); - } - else if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ConstantPhysicalSize) - { - EditorGUILayout.PropertyField(fallbackScreenDPI); - EditorGUILayout.PropertyField(defaultSpriteDPI); - } - else - EditorGUILayout.PropertyField(constantScaleFactor); - - if (serializedObject.ApplyModifiedProperties()) - (target as UIContentScaler).ApplyModifiedProperties(); - } - } -} +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(UIContentScaler))] + public class UIContentScalerEditor : Editor + { + SerializedProperty scaleMode; + SerializedProperty screenMatchMode; + SerializedProperty designResolutionX; + SerializedProperty designResolutionY; + SerializedProperty fallbackScreenDPI; + SerializedProperty defaultSpriteDPI; + SerializedProperty constantScaleFactor; + SerializedProperty ignoreOrientation; + + string[] propertyToExclude; + + void OnEnable() + { + scaleMode = serializedObject.FindProperty("scaleMode"); + screenMatchMode = serializedObject.FindProperty("screenMatchMode"); + designResolutionX = serializedObject.FindProperty("designResolutionX"); + designResolutionY = serializedObject.FindProperty("designResolutionY"); + fallbackScreenDPI = serializedObject.FindProperty("fallbackScreenDPI"); + defaultSpriteDPI = serializedObject.FindProperty("defaultSpriteDPI"); + constantScaleFactor = serializedObject.FindProperty("constantScaleFactor"); + ignoreOrientation = serializedObject.FindProperty("ignoreOrientation"); + + propertyToExclude = new string[] { "m_Script", "scaleMode", "screenMatchMode", "designResolutionX", "designResolutionY", + "fallbackScreenDPI", "defaultSpriteDPI", "constantScaleFactor", "ignoreOrientation"}; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + EditorGUILayout.PropertyField(scaleMode); + if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ScaleWithScreenSize) + { + EditorGUILayout.PropertyField(designResolutionX); + EditorGUILayout.PropertyField(designResolutionY); + EditorGUILayout.PropertyField(screenMatchMode); + EditorGUILayout.PropertyField(ignoreOrientation); + } + else if ((UIContentScaler.ScaleMode)scaleMode.enumValueIndex == UIContentScaler.ScaleMode.ConstantPhysicalSize) + { + EditorGUILayout.PropertyField(fallbackScreenDPI); + EditorGUILayout.PropertyField(defaultSpriteDPI); + } + else + EditorGUILayout.PropertyField(constantScaleFactor); + + if (serializedObject.ApplyModifiedProperties()) + (target as UIContentScaler).ApplyModifiedProperties(); + } + } +} diff --git a/Assets/Scripts/Editor/UIContentScalerEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs.meta similarity index 100% rename from Assets/Scripts/Editor/UIContentScalerEditor.cs.meta rename to Assets/Plugins/FairyGUI/Editor/UIContentScalerEditor.cs.meta diff --git a/Assets/Scripts/Editor/UIPainterEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs similarity index 97% rename from Assets/Scripts/Editor/UIPainterEditor.cs rename to Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs index 4de1c544..1f71214e 100644 --- a/Assets/Scripts/Editor/UIPainterEditor.cs +++ b/Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs @@ -1,96 +1,96 @@ -using UnityEngine; -#if UNITY_5_3_OR_NEWER -using UnityEditor.SceneManagement; -#endif -using UnityEditor; -using FairyGUI; - -namespace FairyGUIEditor -{ - /// - /// - /// - [CustomEditor(typeof(UIPainter))] - public class UIPainterEditor : Editor - { - SerializedProperty packageName; - SerializedProperty componentName; - SerializedProperty renderCamera; - SerializedProperty fairyBatching; - SerializedProperty touchDisabled; - SerializedProperty sortingOrder; - - string[] propertyToExclude; - - void OnEnable() - { - packageName = serializedObject.FindProperty("packageName"); - componentName = serializedObject.FindProperty("componentName"); - renderCamera = serializedObject.FindProperty("renderCamera"); - fairyBatching = serializedObject.FindProperty("fairyBatching"); - touchDisabled = serializedObject.FindProperty("touchDisabled"); - sortingOrder = serializedObject.FindProperty("sortingOrder"); - - propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", - "renderCamera", "fairyBatching", "touchDisabled","sortingOrder" - }; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - UIPainter panel = target as UIPainter; - - DrawPropertiesExcluding(serializedObject, propertyToExclude); - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Package Name"); - if (GUILayout.Button(packageName.stringValue, "ObjectField")) - EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); - - if (GUILayout.Button("Clear", GUILayout.Width(50))) - { -#if UNITY_2018_3_OR_NEWER - bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; -#else - bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; -#endif - panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab }); - -#if UNITY_5_3_OR_NEWER - EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); -#elif UNITY_5 - EditorApplication.MarkSceneDirty(); -#else - EditorUtility.SetDirty(panel); -#endif - } - EditorGUILayout.EndHorizontal(); - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Component Name"); - if (GUILayout.Button(componentName.stringValue, "ObjectField")) - EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); - EditorGUILayout.EndHorizontal(); - int oldSortingOrder = panel.sortingOrder; - EditorGUILayout.PropertyField(sortingOrder); - EditorGUILayout.PropertyField(renderCamera); - EditorGUILayout.PropertyField(fairyBatching); - EditorGUILayout.PropertyField(touchDisabled); - - if (serializedObject.ApplyModifiedProperties()) - { -#if UNITY_2018_3_OR_NEWER - bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; -#else - bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; -#endif - if (!isPrefab) - { - panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder); - } - } - } - } -} +using UnityEngine; +#if UNITY_5_3_OR_NEWER +using UnityEditor.SceneManagement; +#endif +using UnityEditor; +using FairyGUI; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(UIPainter))] + public class UIPainterEditor : Editor + { + SerializedProperty packageName; + SerializedProperty componentName; + SerializedProperty renderCamera; + SerializedProperty fairyBatching; + SerializedProperty touchDisabled; + SerializedProperty sortingOrder; + + string[] propertyToExclude; + + void OnEnable() + { + packageName = serializedObject.FindProperty("packageName"); + componentName = serializedObject.FindProperty("componentName"); + renderCamera = serializedObject.FindProperty("renderCamera"); + fairyBatching = serializedObject.FindProperty("fairyBatching"); + touchDisabled = serializedObject.FindProperty("touchDisabled"); + sortingOrder = serializedObject.FindProperty("sortingOrder"); + + propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", + "renderCamera", "fairyBatching", "touchDisabled","sortingOrder" + }; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + UIPainter panel = target as UIPainter; + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Package Name"); + if (GUILayout.Button(packageName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + + if (GUILayout.Button("Clear", GUILayout.Width(50))) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab }); + +#if UNITY_5_3_OR_NEWER + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); +#elif UNITY_5 + EditorApplication.MarkSceneDirty(); +#else + EditorUtility.SetDirty(panel); +#endif + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Component Name"); + if (GUILayout.Button(componentName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + EditorGUILayout.EndHorizontal(); + int oldSortingOrder = panel.sortingOrder; + EditorGUILayout.PropertyField(sortingOrder); + EditorGUILayout.PropertyField(renderCamera); + EditorGUILayout.PropertyField(fairyBatching); + EditorGUILayout.PropertyField(touchDisabled); + + if (serializedObject.ApplyModifiedProperties()) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + if (!isPrefab) + { + panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder); + } + } + } + } +} diff --git a/Assets/Scripts/Editor/UIPainterEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs.meta similarity index 100% rename from Assets/Scripts/Editor/UIPainterEditor.cs.meta rename to Assets/Plugins/FairyGUI/Editor/UIPainterEditor.cs.meta diff --git a/Assets/Scripts/Editor/UIPanelEditor.cs b/Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs similarity index 95% rename from Assets/Scripts/Editor/UIPanelEditor.cs rename to Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs index f563f0a8..572b38ce 100644 --- a/Assets/Scripts/Editor/UIPanelEditor.cs +++ b/Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs @@ -1,163 +1,163 @@ -using UnityEngine; -#if UNITY_5_3_OR_NEWER -using UnityEditor.SceneManagement; -#endif -using UnityEditor; - -namespace FairyGUIEditor -{ - /// - /// - /// - [CustomEditor(typeof(FairyGUI.UIPanel))] - public class UIPanelEditor : Editor - { - SerializedProperty packageName; - SerializedProperty componentName; - SerializedProperty packagePath; - SerializedProperty renderMode; - SerializedProperty renderCamera; - SerializedProperty sortingOrder; - SerializedProperty position; - SerializedProperty scale; - SerializedProperty rotation; - SerializedProperty fairyBatching; - SerializedProperty fitScreen; - SerializedProperty touchDisabled; - SerializedProperty hitTestMode; - SerializedProperty setNativeChildrenOrder; - - string[] propertyToExclude; - - void OnEnable() - { - packageName = serializedObject.FindProperty("packageName"); - componentName = serializedObject.FindProperty("componentName"); - packagePath = serializedObject.FindProperty("packagePath"); - renderMode = serializedObject.FindProperty("renderMode"); - renderCamera = serializedObject.FindProperty("renderCamera"); - sortingOrder = serializedObject.FindProperty("sortingOrder"); - position = serializedObject.FindProperty("position"); - scale = serializedObject.FindProperty("scale"); - rotation = serializedObject.FindProperty("rotation"); - fairyBatching = serializedObject.FindProperty("fairyBatching"); - fitScreen = serializedObject.FindProperty("fitScreen"); - touchDisabled = serializedObject.FindProperty("touchDisabled"); - hitTestMode = serializedObject.FindProperty("hitTestMode"); - setNativeChildrenOrder = serializedObject.FindProperty("setNativeChildrenOrder"); - - - propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", "renderMode", - "renderCamera", "sortingOrder", "position", "scale", "rotation", "fairyBatching", "fitScreen","touchDisabled", - "hitTestMode","cachedUISize","setNativeChildrenOrder" - }; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - FairyGUI.UIPanel panel = target as FairyGUI.UIPanel; - - DrawPropertiesExcluding(serializedObject, propertyToExclude); - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Package Name"); - if (GUILayout.Button(packageName.stringValue, "ObjectField")) - EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); - - if (GUILayout.Button("Clear", GUILayout.Width(50))) - { -#if UNITY_2018_3_OR_NEWER - bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; -#else - bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; -#endif - panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab }); - -#if UNITY_5_3_OR_NEWER - EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); -#elif UNITY_5 - EditorApplication.MarkSceneDirty(); -#else - EditorUtility.SetDirty(panel); -#endif - } - EditorGUILayout.EndHorizontal(); - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Component Name"); - if (GUILayout.Button(componentName.stringValue, "ObjectField")) - EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); - EditorGUILayout.EndHorizontal(); - - EditorGUILayout.BeginHorizontal(); - EditorGUILayout.PrefixLabel("Package Path"); - EditorGUILayout.LabelField(packagePath.stringValue, (GUIStyle)"helpbox"); - EditorGUILayout.EndHorizontal(); - - if (Application.isPlaying) - EditorGUILayout.EnumPopup("Render Mode", panel.container.renderMode); - else - EditorGUILayout.PropertyField(renderMode); - if ((RenderMode)renderMode.enumValueIndex != RenderMode.ScreenSpaceOverlay) - EditorGUILayout.PropertyField(renderCamera); - - int oldSortingOrder = panel.sortingOrder; - EditorGUILayout.PropertyField(sortingOrder); - EditorGUILayout.PropertyField(fairyBatching); - EditorGUILayout.PropertyField(hitTestMode); - EditorGUILayout.PropertyField(touchDisabled); - EditorGUILayout.PropertyField(setNativeChildrenOrder); - EditorGUILayout.Separator(); - EditorGUILayout.LabelField("UI Transform", (GUIStyle)"OL Title"); - EditorGUILayout.Separator(); - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(position); - EditorGUILayout.PropertyField(rotation); - EditorGUILayout.PropertyField(scale); - EditorGUILayout.Space(); - - FairyGUI.FitScreen oldFitScreen = (FairyGUI.FitScreen)fitScreen.enumValueIndex; - EditorGUILayout.PropertyField(fitScreen); - - if (serializedObject.ApplyModifiedProperties()) - { -#if UNITY_2018_3_OR_NEWER - bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; -#else - bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; -#endif - if (!isPrefab) - { - panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder, (FairyGUI.FitScreen)fitScreen.enumValueIndex != oldFitScreen); - } - } - } - - void OnSceneGUI() - { - FairyGUI.UIPanel panel = (target as FairyGUI.UIPanel); - if (panel.container == null) - return; - - Vector3 pos = panel.GetUIWorldPosition(); - float sizeFactor = HandleUtility.GetHandleSize(pos); -#if UNITY_2017_1_OR_NEWER - Vector3 newPos = Handles.FreeMoveHandle(pos, Quaternion.identity, sizeFactor, Vector3.one, Handles.ArrowHandleCap); -#else - Vector3 newPos = Handles.FreeMoveHandle(pos, Quaternion.identity, sizeFactor, Vector3.one, Handles.ArrowCap); -#endif - if (newPos != pos) - { - Vector2 v1 = HandleUtility.WorldToGUIPoint(pos); - Vector2 v2 = HandleUtility.WorldToGUIPoint(newPos); - Vector3 delta = v2 - v1; - delta.x = (int)delta.x; - delta.y = (int)delta.y; - - panel.MoveUI(delta); - } - } - } -} +using UnityEngine; +#if UNITY_5_3_OR_NEWER +using UnityEditor.SceneManagement; +#endif +using UnityEditor; + +namespace FairyGUIEditor +{ + /// + /// + /// + [CustomEditor(typeof(FairyGUI.UIPanel))] + public class UIPanelEditor : Editor + { + SerializedProperty packageName; + SerializedProperty componentName; + SerializedProperty packagePath; + SerializedProperty renderMode; + SerializedProperty renderCamera; + SerializedProperty sortingOrder; + SerializedProperty position; + SerializedProperty scale; + SerializedProperty rotation; + SerializedProperty fairyBatching; + SerializedProperty fitScreen; + SerializedProperty touchDisabled; + SerializedProperty hitTestMode; + SerializedProperty setNativeChildrenOrder; + + string[] propertyToExclude; + + void OnEnable() + { + packageName = serializedObject.FindProperty("packageName"); + componentName = serializedObject.FindProperty("componentName"); + packagePath = serializedObject.FindProperty("packagePath"); + renderMode = serializedObject.FindProperty("renderMode"); + renderCamera = serializedObject.FindProperty("renderCamera"); + sortingOrder = serializedObject.FindProperty("sortingOrder"); + position = serializedObject.FindProperty("position"); + scale = serializedObject.FindProperty("scale"); + rotation = serializedObject.FindProperty("rotation"); + fairyBatching = serializedObject.FindProperty("fairyBatching"); + fitScreen = serializedObject.FindProperty("fitScreen"); + touchDisabled = serializedObject.FindProperty("touchDisabled"); + hitTestMode = serializedObject.FindProperty("hitTestMode"); + setNativeChildrenOrder = serializedObject.FindProperty("setNativeChildrenOrder"); + + + propertyToExclude = new string[] { "m_Script", "packageName", "componentName", "packagePath", "renderMode", + "renderCamera", "sortingOrder", "position", "scale", "rotation", "fairyBatching", "fitScreen","touchDisabled", + "hitTestMode","cachedUISize","setNativeChildrenOrder" + }; + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + + FairyGUI.UIPanel panel = target as FairyGUI.UIPanel; + + DrawPropertiesExcluding(serializedObject, propertyToExclude); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Package Name"); + if (GUILayout.Button(packageName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + + if (GUILayout.Button("Clear", GUILayout.Width(50))) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + panel.SendMessage("OnUpdateSource", new object[] { null, null, null, !isPrefab }); + +#if UNITY_5_3_OR_NEWER + EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); +#elif UNITY_5 + EditorApplication.MarkSceneDirty(); +#else + EditorUtility.SetDirty(panel); +#endif + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Component Name"); + if (GUILayout.Button(componentName.stringValue, "ObjectField")) + EditorWindow.GetWindow(true, "Select a UI Component").SetSelection(packageName.stringValue, componentName.stringValue); + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Package Path"); + EditorGUILayout.LabelField(packagePath.stringValue, (GUIStyle)"helpbox"); + EditorGUILayout.EndHorizontal(); + + if (Application.isPlaying) + EditorGUILayout.EnumPopup("Render Mode", panel.container.renderMode); + else + EditorGUILayout.PropertyField(renderMode); + if ((RenderMode)renderMode.enumValueIndex != RenderMode.ScreenSpaceOverlay) + EditorGUILayout.PropertyField(renderCamera); + + int oldSortingOrder = panel.sortingOrder; + EditorGUILayout.PropertyField(sortingOrder); + EditorGUILayout.PropertyField(fairyBatching); + EditorGUILayout.PropertyField(hitTestMode); + EditorGUILayout.PropertyField(touchDisabled); + EditorGUILayout.PropertyField(setNativeChildrenOrder); + EditorGUILayout.Separator(); + EditorGUILayout.LabelField("UI Transform", (GUIStyle)"OL Title"); + EditorGUILayout.Separator(); + EditorGUI.BeginChangeCheck(); + EditorGUILayout.PropertyField(position); + EditorGUILayout.PropertyField(rotation); + EditorGUILayout.PropertyField(scale); + EditorGUILayout.Space(); + + FairyGUI.FitScreen oldFitScreen = (FairyGUI.FitScreen)fitScreen.enumValueIndex; + EditorGUILayout.PropertyField(fitScreen); + + if (serializedObject.ApplyModifiedProperties()) + { +#if UNITY_2018_3_OR_NEWER + bool isPrefab = PrefabUtility.GetPrefabAssetType(panel) != PrefabAssetType.NotAPrefab; +#else + bool isPrefab = PrefabUtility.GetPrefabType(panel) == PrefabType.Prefab; +#endif + if (!isPrefab) + { + panel.ApplyModifiedProperties(sortingOrder.intValue != oldSortingOrder, (FairyGUI.FitScreen)fitScreen.enumValueIndex != oldFitScreen); + } + } + } + + void OnSceneGUI() + { + FairyGUI.UIPanel panel = (target as FairyGUI.UIPanel); + if (panel.container == null) + return; + + Vector3 pos = panel.GetUIWorldPosition(); + float sizeFactor = HandleUtility.GetHandleSize(pos); +#if UNITY_2017_1_OR_NEWER + var fmh_147_58_638029390776941523 = Quaternion.identity; Vector3 newPos = Handles.FreeMoveHandle(pos,Quaternion.identity, sizeFactor, Vector3.one, Handles.ArrowHandleCap); +#else + Vector3 newPos = Handles.FreeMoveHandle(pos, Quaternion.identity, sizeFactor, Vector3.one, Handles.ArrowCap); +#endif + if (newPos != pos) + { + Vector2 v1 = HandleUtility.WorldToGUIPoint(pos); + Vector2 v2 = HandleUtility.WorldToGUIPoint(newPos); + Vector3 delta = v2 - v1; + delta.x = (int)delta.x; + delta.y = (int)delta.y; + + panel.MoveUI(delta); + } + } + } +} diff --git a/Assets/Scripts/Editor/UIPanelEditor.cs.meta b/Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs.meta similarity index 100% rename from Assets/Scripts/Editor/UIPanelEditor.cs.meta rename to Assets/Plugins/FairyGUI/Editor/UIPanelEditor.cs.meta diff --git a/Assets/Plugins/FairyGUI/Resources.meta b/Assets/Plugins/FairyGUI/Resources.meta new file mode 100644 index 00000000..6e4dc8c9 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Resources.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 66d9312cafc49bf4cad1ccdbb5b6668b +folderAsset: yes +timeCreated: 1446459912 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/FairyGUI/Resources/BillingMode.json b/Assets/Plugins/FairyGUI/Resources/BillingMode.json new file mode 100644 index 00000000..6f4bfb71 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Resources/BillingMode.json @@ -0,0 +1 @@ +{"androidStore":"GooglePlay"} \ No newline at end of file diff --git a/Assets/Plugins/FairyGUI/Resources/BillingMode.json.meta b/Assets/Plugins/FairyGUI/Resources/BillingMode.json.meta new file mode 100644 index 00000000..4a7a6a29 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Resources/BillingMode.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6c5d8b4692a92924cbfe1f97aa2e166b +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Resources/Shaders.meta b/Assets/Plugins/FairyGUI/Resources/Shaders.meta similarity index 100% rename from Assets/Resources/Shaders.meta rename to Assets/Plugins/FairyGUI/Resources/Shaders.meta diff --git a/Assets/Resources/Shaders/AddOn.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/AddOn.meta similarity index 100% rename from Assets/Resources/Shaders/AddOn.meta rename to Assets/Plugins/FairyGUI/Resources/Shaders/AddOn.meta diff --git a/Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader similarity index 100% rename from Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader rename to Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader diff --git a/Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta similarity index 100% rename from Assets/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta rename to Assets/Plugins/FairyGUI/Resources/Shaders/AddOn/FairyGUI-BlurFilter.shader.meta diff --git a/Assets/Resources/Shaders/FairyGUI-BMFont.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader similarity index 100% rename from Assets/Resources/Shaders/FairyGUI-BMFont.shader rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader diff --git a/Assets/Resources/Shaders/FairyGUI-BMFont.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader.meta similarity index 100% rename from Assets/Resources/Shaders/FairyGUI-BMFont.shader.meta rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-BMFont.shader.meta diff --git a/Assets/Resources/Shaders/FairyGUI-Image.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader similarity index 100% rename from Assets/Resources/Shaders/FairyGUI-Image.shader rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader diff --git a/Assets/Resources/Shaders/FairyGUI-Image.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader.meta similarity index 100% rename from Assets/Resources/Shaders/FairyGUI-Image.shader.meta rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Image.shader.meta diff --git a/Assets/Resources/Shaders/FairyGUI-Text.shader b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader similarity index 100% rename from Assets/Resources/Shaders/FairyGUI-Text.shader rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader diff --git a/Assets/Resources/Shaders/FairyGUI-Text.shader.meta b/Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader.meta similarity index 100% rename from Assets/Resources/Shaders/FairyGUI-Text.shader.meta rename to Assets/Plugins/FairyGUI/Resources/Shaders/FairyGUI-Text.shader.meta diff --git a/Assets/Plugins/FairyGUI/Runtime.meta b/Assets/Plugins/FairyGUI/Runtime.meta new file mode 100644 index 00000000..7dbef7f5 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b27cb0bddae3bd247b20a4aa2792119a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/FairyGUI/Runtime/Empty.cs b/Assets/Plugins/FairyGUI/Runtime/Empty.cs new file mode 100644 index 00000000..e69de29b diff --git a/Assets/Plugins/FairyGUI/Runtime/Empty.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Empty.cs.meta new file mode 100644 index 00000000..54d69221 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Runtime/Empty.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f6ce87023a0c1ad41801e927f247abba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Extensions.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions.meta similarity index 100% rename from Assets/Extensions.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions.meta diff --git a/Assets/Extensions/DragonBones.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones.meta similarity index 100% rename from Assets/Extensions/DragonBones.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones.meta diff --git a/Assets/Extensions/DragonBones/DragonBonesLoader.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs similarity index 100% rename from Assets/Extensions/DragonBones/DragonBonesLoader.cs rename to Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs diff --git a/Assets/Extensions/DragonBones/DragonBonesLoader.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs.meta similarity index 100% rename from Assets/Extensions/DragonBones/DragonBonesLoader.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/DragonBones/DragonBonesLoader.cs.meta diff --git a/Assets/Extensions/Spine.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/Spine.meta similarity index 100% rename from Assets/Extensions/Spine.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/Spine.meta diff --git a/Assets/Extensions/Spine/SpineLoader.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs similarity index 100% rename from Assets/Extensions/Spine/SpineLoader.cs rename to Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs diff --git a/Assets/Extensions/Spine/SpineLoader.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs.meta similarity index 100% rename from Assets/Extensions/Spine/SpineLoader.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/Spine/SpineLoader.cs.meta diff --git a/Assets/Extensions/TextMeshPro.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro.meta similarity index 100% rename from Assets/Extensions/TextMeshPro.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro.meta diff --git a/Assets/Extensions/TextMeshPro/Shaders.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders.meta similarity index 100% rename from Assets/Extensions/TextMeshPro/Shaders.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders.meta diff --git a/Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader old mode 100755 new mode 100644 similarity index 100% rename from Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader diff --git a/Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta similarity index 100% rename from Assets/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/Shaders/FairyGUI-TMP.shader.meta diff --git a/Assets/Extensions/TextMeshPro/TMPFont.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs similarity index 100% rename from Assets/Extensions/TextMeshPro/TMPFont.cs rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs diff --git a/Assets/Extensions/TextMeshPro/TMPFont.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs.meta similarity index 100% rename from Assets/Extensions/TextMeshPro/TMPFont.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPFont.cs.meta diff --git a/Assets/Extensions/TextMeshPro/TMPTextFormat.cs b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs similarity index 100% rename from Assets/Extensions/TextMeshPro/TMPTextFormat.cs rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs diff --git a/Assets/Extensions/TextMeshPro/TMPTextFormat.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs.meta similarity index 100% rename from Assets/Extensions/TextMeshPro/TMPTextFormat.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Extensions/TextMeshPro/TMPTextFormat.cs.meta diff --git a/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef new file mode 100644 index 00000000..4c3114a7 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef @@ -0,0 +1,3 @@ +{ + "name": "FairyGUI" +} diff --git a/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef.meta b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef.meta new file mode 100644 index 00000000..b9ec0a58 --- /dev/null +++ b/Assets/Plugins/FairyGUI/Runtime/FairyGUI.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b12c828e10494534a9050867cfc5ed0c +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts.meta similarity index 100% rename from Assets/Scripts.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts.meta diff --git a/Assets/Scripts/Core.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core.meta similarity index 100% rename from Assets/Scripts/Core.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core.meta diff --git a/Assets/Scripts/Core/BlendMode.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs similarity index 97% rename from Assets/Scripts/Core/BlendMode.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs index 9bc414ee..dd725ea5 100644 --- a/Assets/Scripts/Core/BlendMode.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs @@ -1,110 +1,110 @@ -using UnityEngine; -using NativeBlendMode = UnityEngine.Rendering.BlendMode; - -namespace FairyGUI -{ - /*关于BlendMode.Off, 这种模式相当于Blend Off指令的效果。当然,在着色器里使用Blend Off指令可以获得更高的效率, - 但因为Image着色器本身就有多个关键字,复制一个这样的着色器代价太大,所有为了节省Shader数量便增加了这样一种模式,也是可以接受的。 - */ - - /// - /// - /// - public enum BlendMode - { - Normal, - None, - Add, - Multiply, - Screen, - Erase, - Mask, - Below, - Off, - One_OneMinusSrcAlpha, - Custom1, - Custom2, - Custom3 - } - - /// - /// - /// - public class BlendModeUtils - { - public class BlendFactor - { - public NativeBlendMode srcFactor; - public NativeBlendMode dstFactor; - public bool pma; - - public BlendFactor(NativeBlendMode srcFactor, NativeBlendMode dstFactor, bool pma = false) - { - this.srcFactor = srcFactor; - this.dstFactor = dstFactor; - this.pma = pma; - } - } - - //Source指的是被计算的颜色,Destination是已经在屏幕上的颜色。 - //混合结果=Source * factor1 + Destination * factor2 - public static BlendFactor[] Factors = new BlendFactor[] { - //Normal - new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), - //None - new BlendFactor(NativeBlendMode.One, NativeBlendMode.One), - //Add - new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.One), - //Multiply - new BlendFactor(NativeBlendMode.DstColor, NativeBlendMode.OneMinusSrcAlpha, true), - //Screen - new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcColor, true), - //Erase - new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.OneMinusSrcAlpha), - //Mask - new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.SrcAlpha), - //Below - new BlendFactor(NativeBlendMode.OneMinusDstAlpha, NativeBlendMode.DstAlpha), - //Off - new BlendFactor(NativeBlendMode.One, NativeBlendMode.Zero), - //One_OneMinusSrcAlpha - new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcAlpha), - //Custom1 - new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), - //Custom2 - new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), - //Custom3 - new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha) - }; - - /// - /// - /// - /// - /// - public static void Apply(Material mat, BlendMode blendMode) - { - BlendFactor bf = Factors[(int)blendMode]; - mat.SetFloat(ShaderConfig.ID_BlendSrcFactor, (float)bf.srcFactor); - mat.SetFloat(ShaderConfig.ID_BlendDstFactor, (float)bf.dstFactor); - - if (bf.pma) - mat.SetFloat(ShaderConfig.ID_ColorOption, 1); - else - mat.SetFloat(ShaderConfig.ID_ColorOption, 0); - } - - /// - /// - /// - /// - /// - /// - public static void Override(BlendMode blendMode, NativeBlendMode srcFactor, NativeBlendMode dstFactor) - { - BlendFactor bf = Factors[(int)blendMode]; - bf.srcFactor = srcFactor; - bf.dstFactor = dstFactor; - } - } -} +using UnityEngine; +using NativeBlendMode = UnityEngine.Rendering.BlendMode; + +namespace FairyGUI +{ + /*关于BlendMode.Off, 这种模式相当于Blend Off指令的效果。当然,在着色器里使用Blend Off指令可以获得更高的效率, + 但因为Image着色器本身就有多个关键字,复制一个这样的着色器代价太大,所有为了节省Shader数量便增加了这样一种模式,也是可以接受的。 + */ + + /// + /// + /// + public enum BlendMode + { + Normal, + None, + Add, + Multiply, + Screen, + Erase, + Mask, + Below, + Off, + One_OneMinusSrcAlpha, + Custom1, + Custom2, + Custom3 + } + + /// + /// + /// + public class BlendModeUtils + { + public class BlendFactor + { + public NativeBlendMode srcFactor; + public NativeBlendMode dstFactor; + public bool pma; + + public BlendFactor(NativeBlendMode srcFactor, NativeBlendMode dstFactor, bool pma = false) + { + this.srcFactor = srcFactor; + this.dstFactor = dstFactor; + this.pma = pma; + } + } + + //Source指的是被计算的颜色,Destination是已经在屏幕上的颜色。 + //混合结果=Source * factor1 + Destination * factor2 + public static BlendFactor[] Factors = new BlendFactor[] { + //Normal + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), + //None + new BlendFactor(NativeBlendMode.One, NativeBlendMode.One), + //Add + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.One), + //Multiply + new BlendFactor(NativeBlendMode.DstColor, NativeBlendMode.OneMinusSrcAlpha, true), + //Screen + new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcColor, true), + //Erase + new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.OneMinusSrcAlpha), + //Mask + new BlendFactor(NativeBlendMode.Zero, NativeBlendMode.SrcAlpha), + //Below + new BlendFactor(NativeBlendMode.OneMinusDstAlpha, NativeBlendMode.DstAlpha), + //Off + new BlendFactor(NativeBlendMode.One, NativeBlendMode.Zero), + //One_OneMinusSrcAlpha + new BlendFactor(NativeBlendMode.One, NativeBlendMode.OneMinusSrcAlpha), + //Custom1 + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), + //Custom2 + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha), + //Custom3 + new BlendFactor(NativeBlendMode.SrcAlpha, NativeBlendMode.OneMinusSrcAlpha) + }; + + /// + /// + /// + /// + /// + public static void Apply(Material mat, BlendMode blendMode) + { + BlendFactor bf = Factors[(int)blendMode]; + mat.SetFloat(ShaderConfig.ID_BlendSrcFactor, (float)bf.srcFactor); + mat.SetFloat(ShaderConfig.ID_BlendDstFactor, (float)bf.dstFactor); + + if (bf.pma) + mat.SetFloat(ShaderConfig.ID_ColorOption, 1); + else + mat.SetFloat(ShaderConfig.ID_ColorOption, 0); + } + + /// + /// + /// + /// + /// + /// + public static void Override(BlendMode blendMode, NativeBlendMode srcFactor, NativeBlendMode dstFactor) + { + BlendFactor bf = Factors[(int)blendMode]; + bf.srcFactor = srcFactor; + bf.dstFactor = dstFactor; + } + } +} diff --git a/Assets/Scripts/Core/BlendMode.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs.meta similarity index 100% rename from Assets/Scripts/Core/BlendMode.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/BlendMode.cs.meta diff --git a/Assets/Scripts/Core/CaptureCamera.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs similarity index 97% rename from Assets/Scripts/Core/CaptureCamera.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs index 8a91f827..cd550477 100644 --- a/Assets/Scripts/Core/CaptureCamera.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs @@ -1,202 +1,202 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class CaptureCamera : MonoBehaviour - { - /// - /// - /// - [System.NonSerialized] - public Transform cachedTransform; - /// - /// - /// - [System.NonSerialized] - public Camera cachedCamera; - - [System.NonSerialized] - static CaptureCamera _main; - - [System.NonSerialized] - static int _layer = -1; - static int _hiddenLayer = -1; - - public const string Name = "Capture Camera"; - public const string LayerName = "VUI"; - public const string HiddenLayerName = "Hidden VUI"; - - void OnEnable() - { - cachedCamera = this.GetComponent(); - cachedTransform = this.gameObject.transform; - - if (this.gameObject.name == Name) - _main = this; - } - - /// - /// - /// - public static void CheckMain() - { - if (_main != null && _main.cachedCamera != null) - return; - - GameObject go = GameObject.Find(Name); - if (go != null) - { - _main = go.GetComponent(); - return; - } - - GameObject cameraObject = new GameObject(Name); - Camera camera = cameraObject.AddComponent(); - camera.depth = 0; - camera.cullingMask = 1 << layer; - camera.clearFlags = CameraClearFlags.SolidColor; - camera.backgroundColor = Color.clear; - camera.orthographic = true; - camera.orthographicSize = 5; - camera.nearClipPlane = -30; - camera.farClipPlane = 30; - camera.enabled = false; -#if UNITY_5_4_OR_NEWER - camera.stereoTargetEye = StereoTargetEyeMask.None; -#endif - -#if UNITY_5_6_OR_NEWER - camera.allowHDR = false; - camera.allowMSAA = false; -#endif - cameraObject.AddComponent(); - } - - /// - /// - /// - public static int layer - { - get - { - if (_layer == -1) - { - _layer = LayerMask.NameToLayer(LayerName); - if (_layer == -1) - { - _layer = 30; - Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); - } - } - - return _layer; - } - } - - /// - /// - /// - public static int hiddenLayer - { - get - { - if (_hiddenLayer == -1) - { - _hiddenLayer = LayerMask.NameToLayer(HiddenLayerName); - if (_hiddenLayer == -1) - { - Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); - _hiddenLayer = 31; - } - } - - return _hiddenLayer; - } - } - - /// - /// - /// - /// - /// - /// - /// - public static RenderTexture CreateRenderTexture(int width, int height, bool stencilSupport) - { - RenderTexture texture = new RenderTexture(width, height, stencilSupport ? 24 : 0, RenderTextureFormat.ARGB32); - texture.antiAliasing = 1; - texture.filterMode = FilterMode.Bilinear; - texture.anisoLevel = 0; - texture.useMipMap = false; - texture.wrapMode = TextureWrapMode.Clamp; - texture.hideFlags = DisplayObject.hideFlags; - return texture; - } - - /// - /// - /// - /// - /// - /// - /// - public static void Capture(DisplayObject target, RenderTexture texture, float contentHeight, Vector2 offset) - { - CheckMain(); - - Matrix4x4 matrix = target.cachedTransform.localToWorldMatrix; - float scaleX = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude; - float scaleY = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude; - - Vector3 forward; - forward.x = matrix.m02; - forward.y = matrix.m12; - forward.z = matrix.m22; - - Vector3 upwards; - upwards.x = matrix.m01; - upwards.y = matrix.m11; - upwards.z = matrix.m21; - - float halfHeight = contentHeight * 0.5f; - - Camera camera = _main.cachedCamera; - camera.targetTexture = texture; - float aspect = (float)texture.width / texture.height; - camera.aspect = aspect * scaleX / scaleY; - camera.orthographicSize = halfHeight * scaleY; - _main.cachedTransform.localPosition = target.cachedTransform.TransformPoint(halfHeight * aspect - offset.x, -halfHeight + offset.y, 0); - if (forward != Vector3.zero) - _main.cachedTransform.localRotation = Quaternion.LookRotation(forward, upwards); - - int oldLayer = 0; - - if (target.graphics != null) - { - oldLayer = target.graphics.gameObject.layer; - target.graphics.gameObject.layer = CaptureCamera.layer; - } - - if (target is Container) - { - oldLayer = ((Container)target).numChildren > 0 ? ((Container)target).GetChildAt(0).layer : CaptureCamera.hiddenLayer; - ((Container)target).SetChildrenLayer(CaptureCamera.layer); - } - - RenderTexture old = RenderTexture.active; - RenderTexture.active = texture; - GL.Clear(true, true, Color.clear); - camera.Render(); - RenderTexture.active = old; - - if (target.graphics != null) - target.graphics.gameObject.layer = oldLayer; - - if (target is Container) - ((Container)target).SetChildrenLayer(oldLayer); - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class CaptureCamera : MonoBehaviour + { + /// + /// + /// + [System.NonSerialized] + public Transform cachedTransform; + /// + /// + /// + [System.NonSerialized] + public Camera cachedCamera; + + [System.NonSerialized] + static CaptureCamera _main; + + [System.NonSerialized] + static int _layer = -1; + static int _hiddenLayer = -1; + + public const string Name = "Capture Camera"; + public const string LayerName = "VUI"; + public const string HiddenLayerName = "Hidden VUI"; + + void OnEnable() + { + cachedCamera = this.GetComponent(); + cachedTransform = this.gameObject.transform; + + if (this.gameObject.name == Name) + _main = this; + } + + /// + /// + /// + public static void CheckMain() + { + if (_main != null && _main.cachedCamera != null) + return; + + GameObject go = GameObject.Find(Name); + if (go != null) + { + _main = go.GetComponent(); + return; + } + + GameObject cameraObject = new GameObject(Name); + Camera camera = cameraObject.AddComponent(); + camera.depth = 0; + camera.cullingMask = 1 << layer; + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.clear; + camera.orthographic = true; + camera.orthographicSize = 5; + camera.nearClipPlane = -30; + camera.farClipPlane = 30; + camera.enabled = false; +#if UNITY_5_4_OR_NEWER + camera.stereoTargetEye = StereoTargetEyeMask.None; +#endif + +#if UNITY_5_6_OR_NEWER + camera.allowHDR = false; + camera.allowMSAA = false; +#endif + cameraObject.AddComponent(); + } + + /// + /// + /// + public static int layer + { + get + { + if (_layer == -1) + { + _layer = LayerMask.NameToLayer(LayerName); + if (_layer == -1) + { + _layer = 30; + Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); + } + } + + return _layer; + } + } + + /// + /// + /// + public static int hiddenLayer + { + get + { + if (_hiddenLayer == -1) + { + _hiddenLayer = LayerMask.NameToLayer(HiddenLayerName); + if (_hiddenLayer == -1) + { + Debug.LogWarning("Please define two layers named '" + CaptureCamera.LayerName + "' and '" + CaptureCamera.HiddenLayerName + "'"); + _hiddenLayer = 31; + } + } + + return _hiddenLayer; + } + } + + /// + /// + /// + /// + /// + /// + /// + public static RenderTexture CreateRenderTexture(int width, int height, bool stencilSupport) + { + RenderTexture texture = new RenderTexture(width, height, stencilSupport ? 24 : 0, RenderTextureFormat.ARGB32); + texture.antiAliasing = 1; + texture.filterMode = FilterMode.Bilinear; + texture.anisoLevel = 0; + texture.useMipMap = false; + texture.wrapMode = TextureWrapMode.Clamp; + texture.hideFlags = DisplayObject.hideFlags; + return texture; + } + + /// + /// + /// + /// + /// + /// + /// + public static void Capture(DisplayObject target, RenderTexture texture, float contentHeight, Vector2 offset) + { + CheckMain(); + + Matrix4x4 matrix = target.cachedTransform.localToWorldMatrix; + float scaleX = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude; + float scaleY = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude; + + Vector3 forward; + forward.x = matrix.m02; + forward.y = matrix.m12; + forward.z = matrix.m22; + + Vector3 upwards; + upwards.x = matrix.m01; + upwards.y = matrix.m11; + upwards.z = matrix.m21; + + float halfHeight = contentHeight * 0.5f; + + Camera camera = _main.cachedCamera; + camera.targetTexture = texture; + float aspect = (float)texture.width / texture.height; + camera.aspect = aspect * scaleX / scaleY; + camera.orthographicSize = halfHeight * scaleY; + _main.cachedTransform.localPosition = target.cachedTransform.TransformPoint(halfHeight * aspect - offset.x, -halfHeight + offset.y, 0); + if (forward != Vector3.zero) + _main.cachedTransform.localRotation = Quaternion.LookRotation(forward, upwards); + + int oldLayer = 0; + + if (target.graphics != null) + { + oldLayer = target.graphics.gameObject.layer; + target.graphics.gameObject.layer = CaptureCamera.layer; + } + + if (target is Container) + { + oldLayer = ((Container)target).numChildren > 0 ? ((Container)target).GetChildAt(0).layer : CaptureCamera.hiddenLayer; + ((Container)target).SetChildrenLayer(CaptureCamera.layer); + } + + RenderTexture old = RenderTexture.active; + RenderTexture.active = texture; + GL.Clear(true, true, Color.clear); + camera.Render(); + RenderTexture.active = old; + + if (target.graphics != null) + target.graphics.gameObject.layer = oldLayer; + + if (target is Container) + ((Container)target).SetChildrenLayer(oldLayer); + } + } +} diff --git a/Assets/Scripts/Core/CaptureCamera.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs.meta similarity index 100% rename from Assets/Scripts/Core/CaptureCamera.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/CaptureCamera.cs.meta diff --git a/Assets/Scripts/Core/Container.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs similarity index 96% rename from Assets/Scripts/Core/Container.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs index 15417c15..61d6f4c1 100644 --- a/Assets/Scripts/Core/Container.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs @@ -1,1124 +1,1124 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class Container : DisplayObject - { - /// - /// - /// - public RenderMode renderMode; - - /// - /// - /// - public Camera renderCamera; - - /// - /// - /// - public bool opaque; - - /// - /// - /// - public Vector4? clipSoftness; - - /// - /// - /// - public IHitTest hitArea; - - /// - /// - /// - public bool touchChildren; - - /// - /// - /// - public event Action onUpdate; - - /// - /// - /// - public bool reversedMask; - - List _children; - DisplayObject _mask; - Rect? _clipRect; - List _descendants; - - internal int _panelOrder; - internal DisplayObject _lastFocus; - - /// - /// - /// - public Container() - : base() - { - CreateGameObject("Container"); - Init(); - } - - /// - /// - /// - /// - public Container(string gameObjectName) - : base() - { - CreateGameObject(gameObjectName); - Init(); - } - - /// - /// - /// - /// - public Container(GameObject attachTarget) - : base() - { - SetGameObject(attachTarget); - Init(); - } - - void Init() - { - _children = new List(); - touchChildren = true; - } - - /// - /// - /// - public int numChildren - { - get { return _children.Count; } - } - - /// - /// - /// - /// - /// - public DisplayObject AddChild(DisplayObject child) - { - AddChildAt(child, _children.Count); - return child; - } - - /// - /// - /// - /// - /// - /// - public DisplayObject AddChildAt(DisplayObject child, int index) - { - int count = _children.Count; - if (index >= 0 && index <= count) - { - if (child.parent == this) - { - SetChildIndex(child, index); - } - else - { - child.RemoveFromParent(); - if (index == count) - _children.Add(child); - else - _children.Insert(index, child); - child.InternalSetParent(this); - - if (stage != null) - { - if (child is Container) - child.BroadcastEvent("onAddedToStage", null); - else - child.DispatchEvent("onAddedToStage", null); - } - - InvalidateBatchingState(true); - } - return child; - } - else - { - throw new Exception("Invalid child index"); - } - } - - /// - /// - /// - /// - /// - public bool Contains(DisplayObject child) - { - return _children.Contains(child); - } - - /// - /// - /// - /// - /// - public DisplayObject GetChildAt(int index) - { - return _children[index]; - } - - /// - /// - /// - /// - /// - public DisplayObject GetChild(string name) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - if (_children[i].name == name) - return _children[i]; - } - - return null; - } - - /// - /// - /// - /// - public DisplayObject[] GetChildren() - { - return _children.ToArray(); - } - - /// - /// - /// - /// - /// - public int GetChildIndex(DisplayObject child) - { - return _children.IndexOf(child); - } - - /// - /// - /// - /// - /// - public DisplayObject RemoveChild(DisplayObject child) - { - return RemoveChild(child, false); - } - - /// - /// - /// - /// - /// - /// - public DisplayObject RemoveChild(DisplayObject child, bool dispose) - { - if (child.parent != this) - throw new Exception("obj is not a child"); - - int i = _children.IndexOf(child); - if (i >= 0) - return RemoveChildAt(i, dispose); - else - return null; - } - - /// - /// - /// - /// - /// - public DisplayObject RemoveChildAt(int index) - { - return RemoveChildAt(index, false); - } - - /// - /// - /// - /// - /// - /// - public DisplayObject RemoveChildAt(int index, bool dispose) - { - if (index >= 0 && index < _children.Count) - { - DisplayObject child = _children[index]; - - if (stage != null && (child._flags & Flags.Disposed) == 0) - { - if (child is Container) - { - child.BroadcastEvent("onRemovedFromStage", null); - if (child == Stage.inst.focus || ((Container)child).IsAncestorOf(Stage.inst.focus)) - Stage.inst._OnFocusRemoving(this); - } - else - { - child.DispatchEvent("onRemovedFromStage", null); - if (child == Stage.inst.focus) - Stage.inst._OnFocusRemoving(this); - } - } - _children.Remove(child); - InvalidateBatchingState(true); - if (!dispose) - child.InternalSetParent(null); - else - child.Dispose(); - - return child; - } - else - throw new Exception("Invalid child index"); - } - - /// - /// - /// - public void RemoveChildren() - { - RemoveChildren(0, int.MaxValue, false); - } - - /// - /// - /// - /// - /// - /// - public void RemoveChildren(int beginIndex, int endIndex, bool dispose) - { - if (endIndex < 0 || endIndex >= numChildren) - endIndex = numChildren - 1; - - for (int i = beginIndex; i <= endIndex; ++i) - RemoveChildAt(beginIndex, dispose); - } - - /// - /// - /// - /// - /// - public void SetChildIndex(DisplayObject child, int index) - { - int oldIndex = _children.IndexOf(child); - if (oldIndex == index) return; - if (oldIndex == -1) throw new ArgumentException("Not a child of this container"); - _children.RemoveAt(oldIndex); - if (index >= _children.Count) - _children.Add(child); - else - _children.Insert(index, child); - InvalidateBatchingState(true); - } - - /// - /// - /// - /// - /// - public void SwapChildren(DisplayObject child1, DisplayObject child2) - { - int index1 = _children.IndexOf(child1); - int index2 = _children.IndexOf(child2); - if (index1 == -1 || index2 == -1) - throw new Exception("Not a child of this container"); - SwapChildrenAt(index1, index2); - } - - /// - /// - /// - /// - /// - public void SwapChildrenAt(int index1, int index2) - { - DisplayObject obj1 = _children[index1]; - DisplayObject obj2 = _children[index2]; - _children[index1] = obj2; - _children[index2] = obj1; - InvalidateBatchingState(true); - } - - /// - /// - /// - /// - /// - public void ChangeChildrenOrder(IList indice, IList objs) - { - int cnt = objs.Count; - for (int i = 0; i < cnt; i++) - { - DisplayObject obj = objs[i]; - if (obj.parent != this) - throw new Exception("Not a child of this container"); - - _children[indice[i]] = obj; - } - InvalidateBatchingState(true); - } - - /// - /// - /// - /// - public IEnumerator GetDescendants(bool backward) - { - return new DescendantsEnumerator(this, backward); - } - - /// - /// - /// - public Rect? clipRect - { - get { return _clipRect; } - set - { - if (_clipRect != value) - { - _clipRect = value; - UpdateBatchingFlags(); - } - } - } - - /// - /// - /// - public DisplayObject mask - { - get { return _mask; } - set - { - if (_mask != value) - { - _mask = value; - UpdateBatchingFlags(); - } - } - } - - /// - /// - /// - public void CreateGraphics() - { - if (graphics == null) - { - graphics = new NGraphics(this.gameObject); - graphics.texture = NTexture.Empty; - } - } - - public override Rect GetBounds(DisplayObject targetSpace) - { - if (_clipRect != null) - return TransformRect((Rect)_clipRect, targetSpace); - - int count = _children.Count; - - Rect rect; - if (count == 0) - { - Vector2 v = TransformPoint(Vector2.zero, targetSpace); - rect = Rect.MinMaxRect(v.x, v.y, 0, 0); - } - else if (count == 1) - { - rect = _children[0].GetBounds(targetSpace); - } - else - { - float minX = float.MaxValue, maxX = float.MinValue; - float minY = float.MaxValue, maxY = float.MinValue; - - for (int i = 0; i < count; ++i) - { - rect = _children[i].GetBounds(targetSpace); - minX = minX < rect.xMin ? minX : rect.xMin; - maxX = maxX > rect.xMax ? maxX : rect.xMax; - minY = minY < rect.yMin ? minY : rect.yMin; - maxY = maxY > rect.yMax ? maxY : rect.yMax; - } - - rect = Rect.MinMaxRect(minX, minY, maxX, maxY); - } - - return rect; - } - - /// - /// - /// - /// - public Camera GetRenderCamera() - { - if (renderMode == RenderMode.ScreenSpaceOverlay) - return StageCamera.main; - else - { - Camera cam = this.renderCamera; - if (cam == null) - { - if (HitTestContext.cachedMainCamera != null) - cam = HitTestContext.cachedMainCamera; - else - { - cam = Camera.main; - if (cam == null) - cam = StageCamera.main; - } - } - return cam; - } - } - - /// - /// - /// - /// - /// - /// - /// - public DisplayObject HitTest(Vector2 stagePoint, bool forTouch) - { - if (StageCamera.main == null) - { - if (this is Stage) - return this; - else - return null; - } - - HitTestContext.screenPoint = new Vector3(stagePoint.x, Screen.height - stagePoint.y, 0); - if (Display.displays.Length > 1) - { - Vector3 p = Display.RelativeMouseAt(HitTestContext.screenPoint); - if (p != Vector3.zero) - HitTestContext.screenPoint = p; - } - HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(HitTestContext.screenPoint); - HitTestContext.direction = Vector3.back; - HitTestContext.forTouch = forTouch; - HitTestContext.camera = StageCamera.main; - - DisplayObject ret = HitTest(); - if (ret != null) - return ret; - else if (this is Stage) - return this; - else - return null; - } - - override protected DisplayObject HitTest() - { - if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy) - return null; - - if (this.cachedTransform.localScale.x == 0 || this.cachedTransform.localScale.y == 0) - return null; - - Camera savedCamera = HitTestContext.camera; - Vector3 savedWorldPoint = HitTestContext.worldPoint; - Vector3 savedDirection = HitTestContext.direction; - DisplayObject target; - - if (renderMode != RenderMode.ScreenSpaceOverlay || (_flags & Flags.UserGameObject) != 0) - { - Camera cam = GetRenderCamera(); - if (cam.targetDisplay != HitTestContext.screenPoint.z) - return null; - - HitTestContext.camera = cam; - if (renderMode == RenderMode.WorldSpace) - { - Vector3 screenPoint = HitTestContext.camera.WorldToScreenPoint(this.cachedTransform.position); //only for query z value - screenPoint.x = HitTestContext.screenPoint.x; - screenPoint.y = HitTestContext.screenPoint.y; - - //获得本地z轴在世界坐标的方向 - HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(screenPoint); - Ray ray = HitTestContext.camera.ScreenPointToRay(screenPoint); - HitTestContext.direction = Vector3.zero - ray.direction; - } - else if (renderMode == RenderMode.ScreenSpaceCamera) - { - HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(HitTestContext.screenPoint); - } - } - else - { - if (HitTestContext.camera.targetDisplay != HitTestContext.screenPoint.z && !(this is Stage)) - return null; - } - - target = HitTest_Container(); - - HitTestContext.camera = savedCamera; - HitTestContext.worldPoint = savedWorldPoint; - HitTestContext.direction = savedDirection; - - return target; - } - - DisplayObject HitTest_Container() - { - Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); - if (_vertexMatrix != null) - HitTestContext.worldPoint = this.cachedTransform.TransformPoint(new Vector2(localPoint.x, -localPoint.y)); - - if (hitArea != null) - { - if (!hitArea.HitTest(_contentRect, localPoint)) - return null; - - if (hitArea is MeshColliderHitTest) - localPoint = ((MeshColliderHitTest)hitArea).lastHit; - } - else - { - if (_clipRect != null && !((Rect)_clipRect).Contains(localPoint)) - return null; - } - - if (_mask != null) - { - DisplayObject tmp = _mask.InternalHitTestMask(); - if (!reversedMask && tmp == null || reversedMask && tmp != null) - return null; - } - - DisplayObject target = null; - if (touchChildren) - { - int count = _children.Count; - for (int i = count - 1; i >= 0; --i) // front to back! - { - DisplayObject child = _children[i]; - if ((child._flags & Flags.GameObjectDisposed) != 0) - { - child.DisplayDisposedWarning(); - continue; - } - - if (child == _mask || (child._flags & Flags.TouchDisabled) != 0) - continue; - - target = child.InternalHitTest(); - if (target != null) - break; - } - } - - if (target == null && opaque && (hitArea != null || _contentRect.Contains(localPoint))) - target = this; - - return target; - } - - /// - /// - /// - /// - /// - public bool IsAncestorOf(DisplayObject obj) - { - if (obj == null) - return false; - - Container p = obj.parent; - while (p != null) - { - if (p == this) - return true; - - p = p.parent; - } - return false; - } - - /// - /// - /// - public bool fairyBatching - { - get { return (_flags & Flags.FairyBatching) != 0; } - set - { - bool oldValue = (_flags & Flags.FairyBatching) != 0; - if (oldValue != value) - { - if (value) - _flags |= Flags.FairyBatching; - else - _flags &= ~Flags.FairyBatching; - UpdateBatchingFlags(); - } - } - } - - internal void UpdateBatchingFlags() - { - bool oldValue = (_flags & Flags.BatchingRoot) != 0; - bool newValue = (_flags & Flags.FairyBatching) != 0 || _clipRect != null || _mask != null || _paintingMode > 0; - if (newValue) - _flags |= Flags.BatchingRoot; - else - _flags &= ~Flags.BatchingRoot; - if (oldValue != newValue) - { - if (newValue) - _flags |= Flags.BatchingRequested; - else if (_descendants != null) - _descendants.Clear(); - - InvalidateBatchingState(); - } - } - - /// - /// - /// - /// - public void InvalidateBatchingState(bool childrenChanged) - { - if (childrenChanged && (_flags & Flags.BatchingRoot) != 0) - _flags |= Flags.BatchingRequested; - else - { - Container p = this.parent; - while (p != null) - { - if ((p._flags & Flags.BatchingRoot) != 0) - { - p._flags |= Flags.BatchingRequested; - break; - } - - p = p.parent; - } - } - } - - /// - /// - /// - /// - public void SetChildrenLayer(int value) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - DisplayObject child = _children[i]; - child._SetLayerDirect(value); - if ((child is Container) && child._paintingMode == 0) - ((Container)child).SetChildrenLayer(value); - } - } - - override public void Update(UpdateContext context) - { - if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy) - return; - - base.Update(context); - - if (_paintingMode != 0) - { - if ((_flags & Flags.CacheAsBitmap) != 0 && _paintingInfo.flag == 2) - { - if (onUpdate != null) - onUpdate(); - return; - } - - context.EnterPaintingMode(); - } - - if (_mask != null) - { - context.EnterClipping(this.id, reversedMask); - if (_mask.graphics != null) - _mask.graphics._PreUpdateMask(context, _mask.id); - } - else if (_clipRect != null) - context.EnterClipping(this.id, this.TransformRect((Rect)_clipRect, null), clipSoftness); - - float savedAlpha = context.alpha; - context.alpha *= this.alpha; - bool savedGrayed = context.grayed; - context.grayed = context.grayed || this.grayed; - - if ((_flags & Flags.FairyBatching) != 0) - context.batchingDepth++; - - if (context.batchingDepth > 0) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - DisplayObject child = _children[i]; - if ((child._flags & Flags.GameObjectDisposed) != 0) - { - child.DisplayDisposedWarning(); - continue; - } - - if (child.visible) - child.Update(context); - } - } - else - { - if (_mask != null) - _mask.renderingOrder = context.renderingOrder++; - - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - DisplayObject child = _children[i]; - if ((child._flags & Flags.GameObjectDisposed) != 0) - { - child.DisplayDisposedWarning(); - continue; - } - - if (child.visible) - { - if (!(child.graphics != null && child.graphics._maskFlag == 1)) //if not a mask - child.renderingOrder = context.renderingOrder++; - - child.Update(context); - } - } - - if (_mask != null) - { - if (_mask.graphics != null) - _mask.graphics._SetStencilEraserOrder(context.renderingOrder++); - } - } - - if ((_flags & Flags.FairyBatching) != 0) - { - if (context.batchingDepth == 1) - SetRenderingOrder(context); - context.batchingDepth--; - } - - context.alpha = savedAlpha; - context.grayed = savedGrayed; - - if (_clipRect != null || _mask != null) - context.LeaveClipping(); - - if (_paintingMode != 0) - { - context.LeavePaintingMode(); - UpdateContext.OnEnd += _paintingInfo.captureDelegate; - } - - if (onUpdate != null) - onUpdate(); - } - - private void SetRenderingOrder(UpdateContext context) - { - if ((_flags & Flags.BatchingRequested) != 0) - DoFairyBatching(); - - if (_mask != null) - _mask.renderingOrder = context.renderingOrder++; - - int cnt = _descendants.Count; - for (int i = 0; i < cnt; i++) - { - DisplayObject child = _descendants[i]; - if (!(child.graphics != null && child.graphics._maskFlag == 1)) - child.renderingOrder = context.renderingOrder++; - - if ((child._flags & Flags.BatchingRoot) != 0) - ((Container)child).SetRenderingOrder(context); - } - - if (_mask != null) - { - if (_mask.graphics != null) - _mask.graphics._SetStencilEraserOrder(context.renderingOrder++); - } - } - - private void DoFairyBatching() - { - _flags &= ~Flags.BatchingRequested; - - if (_descendants == null) - _descendants = new List(); - else - _descendants.Clear(); - CollectChildren(this, false); - - int cnt = _descendants.Count; - - int i, j, k, m; - object curMat, testMat, lastMat; - DisplayObject current, test; - float[] bound; - for (i = 0; i < cnt; i++) - { - current = _descendants[i]; - bound = current._batchingBounds; - curMat = current.material; - if (curMat == null || (current._flags & Flags.SkipBatching) != 0) - continue; - - k = -1; - lastMat = null; - m = i; - for (j = i - 1; j >= 0; j--) - { - test = _descendants[j]; - if ((test._flags & Flags.SkipBatching) != 0) - break; - - testMat = test.material; - if (testMat != null) - { - if (lastMat != testMat) - { - lastMat = testMat; - m = j + 1; - } - - if (curMat == testMat) - k = m; - } - - if ((bound[0] > test._batchingBounds[0] ? bound[0] : test._batchingBounds[0]) - <= (bound[2] < test._batchingBounds[2] ? bound[2] : test._batchingBounds[2]) - && (bound[1] > test._batchingBounds[1] ? bound[1] : test._batchingBounds[1]) - <= (bound[3] < test._batchingBounds[3] ? bound[3] : test._batchingBounds[3])) - { - if (k == -1) - k = m; - break; - } - } - if (k != -1 && i != k) - { - _descendants.RemoveAt(i); - _descendants.Insert(k, current); - } - } - - //Debug.Log("DoFairyBatching " + cnt + "," + this.cachedTransform.GetInstanceID()); - } - - private void CollectChildren(Container initiator, bool outlineChanged) - { - int count = _children.Count; - for (int i = 0; i < count; i++) - { - DisplayObject child = _children[i]; - if (!child.visible) - continue; - - if (child._batchingBounds == null) - child._batchingBounds = new float[4]; - - if (child is Container) - { - Container container = (Container)child; - if ((container._flags & Flags.BatchingRoot) != 0) - { - initiator._descendants.Add(container); - if (outlineChanged || (container._flags & Flags.OutlineChanged) != 0) - { - Rect rect = container.GetBounds(initiator); - container._batchingBounds[0] = rect.xMin; - container._batchingBounds[1] = rect.yMin; - container._batchingBounds[2] = rect.xMax; - container._batchingBounds[3] = rect.yMax; - } - if ((container._flags & Flags.BatchingRequested) != 0) - container.DoFairyBatching(); - } - else - container.CollectChildren(initiator, outlineChanged || (container._flags & Flags.OutlineChanged) != 0); - } - else if (child != initiator._mask) - { - if (outlineChanged || (child._flags & Flags.OutlineChanged) != 0) - { - Rect rect = child.GetBounds(initiator); - child._batchingBounds[0] = rect.xMin; - child._batchingBounds[1] = rect.yMin; - child._batchingBounds[2] = rect.xMax; - child._batchingBounds[3] = rect.yMax; - } - initiator._descendants.Add(child); - } - - child._flags &= ~Flags.OutlineChanged; - } - } - - public override void Dispose() - { - if ((_flags & Flags.Disposed) != 0) - return; - - base.Dispose(); //Destroy GameObject tree first, avoid destroying each seperately; - - int numChildren = _children.Count; - for (int i = numChildren - 1; i >= 0; --i) - { - DisplayObject obj = _children[i]; - obj.InternalSetParent(null); //Avoid RemoveParent call - obj.Dispose(); - } - } - - /// - /// If true, when the container is focused, tab navigation is lock inside it. - /// - public bool tabStopChildren - { - get { return (_flags & Flags.TabStopChildren) != 0; } - set - { - if (value) - _flags |= Flags.TabStopChildren; - else - _flags &= ~Flags.TabStopChildren; - } - } - - struct DescendantsEnumerator : IEnumerator - { - Container _root; - Container _com; - DisplayObject _current; - int _index; - bool _forward; - - public DescendantsEnumerator(Container root, bool backward) - { - _root = root; - _com = _root; - _current = null; - _forward = !backward; - if (_forward) - _index = 0; - else - _index = _com._children.Count - 1; - } - - public DisplayObject Current - { - get { return _current; } - } - - object IEnumerator.Current - { - get { return _current; } - } - - public bool MoveNext() - { - if (_forward) - { - if (_index >= _com._children.Count) - { - if (_com == _root) - { - _current = null; - return false; - } - - _current = _com; - _com = _com.parent; - _index = _com.GetChildIndex(_current) + 1; - return true; - } - else - { - DisplayObject obj = _com._children[_index]; - if (obj is Container) - { - _com = (Container)obj; - _index = 0; - return MoveNext(); - } - _index++; - _current = obj; - return true; - } - } - else - { - if (_index < 0) - { - if (_com == _root) - { - _current = null; - return false; - } - - _current = _com; - _com = _com.parent; - _index = _com.GetChildIndex(_current) - 1; - return true; - } - else - { - DisplayObject obj = _com._children[_index]; - if (obj is Container) - { - _com = (Container)obj; - _index = _com._children.Count - 1; - return MoveNext(); - } - _index--; - _current = obj; - return true; - } - } - } - - public void Reset() - { - _com = _root; - _current = null; - _index = 0; - } - - public void Dispose() - { - } - } - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class Container : DisplayObject + { + /// + /// + /// + public RenderMode renderMode; + + /// + /// + /// + public Camera renderCamera; + + /// + /// + /// + public bool opaque; + + /// + /// + /// + public Vector4? clipSoftness; + + /// + /// + /// + public IHitTest hitArea; + + /// + /// + /// + public bool touchChildren; + + /// + /// + /// + public event Action onUpdate; + + /// + /// + /// + public bool reversedMask; + + List _children; + DisplayObject _mask; + Rect? _clipRect; + List _descendants; + + internal int _panelOrder; + internal DisplayObject _lastFocus; + + /// + /// + /// + public Container() + : base() + { + CreateGameObject("Container"); + Init(); + } + + /// + /// + /// + /// + public Container(string gameObjectName) + : base() + { + CreateGameObject(gameObjectName); + Init(); + } + + /// + /// + /// + /// + public Container(GameObject attachTarget) + : base() + { + SetGameObject(attachTarget); + Init(); + } + + void Init() + { + _children = new List(); + touchChildren = true; + } + + /// + /// + /// + public int numChildren + { + get { return _children.Count; } + } + + /// + /// + /// + /// + /// + public DisplayObject AddChild(DisplayObject child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// + /// + /// + /// + /// + public DisplayObject AddChildAt(DisplayObject child, int index) + { + int count = _children.Count; + if (index >= 0 && index <= count) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + child.RemoveFromParent(); + if (index == count) + _children.Add(child); + else + _children.Insert(index, child); + child.InternalSetParent(this); + + if (stage != null) + { + if (child is Container) + child.BroadcastEvent("onAddedToStage", null); + else + child.DispatchEvent("onAddedToStage", null); + } + + InvalidateBatchingState(true); + } + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public bool Contains(DisplayObject child) + { + return _children.Contains(child); + } + + /// + /// + /// + /// + /// + public DisplayObject GetChildAt(int index) + { + return _children[index]; + } + + /// + /// + /// + /// + /// + public DisplayObject GetChild(string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + if (_children[i].name == name) + return _children[i]; + } + + return null; + } + + /// + /// + /// + /// + public DisplayObject[] GetChildren() + { + return _children.ToArray(); + } + + /// + /// + /// + /// + /// + public int GetChildIndex(DisplayObject child) + { + return _children.IndexOf(child); + } + + /// + /// + /// + /// + /// + public DisplayObject RemoveChild(DisplayObject child) + { + return RemoveChild(child, false); + } + + /// + /// + /// + /// + /// + /// + public DisplayObject RemoveChild(DisplayObject child, bool dispose) + { + if (child.parent != this) + throw new Exception("obj is not a child"); + + int i = _children.IndexOf(child); + if (i >= 0) + return RemoveChildAt(i, dispose); + else + return null; + } + + /// + /// + /// + /// + /// + public DisplayObject RemoveChildAt(int index) + { + return RemoveChildAt(index, false); + } + + /// + /// + /// + /// + /// + /// + public DisplayObject RemoveChildAt(int index, bool dispose) + { + if (index >= 0 && index < _children.Count) + { + DisplayObject child = _children[index]; + + if (stage != null && (child._flags & Flags.Disposed) == 0) + { + if (child is Container) + { + child.BroadcastEvent("onRemovedFromStage", null); + if (child == Stage.inst.focus || ((Container)child).IsAncestorOf(Stage.inst.focus)) + Stage.inst._OnFocusRemoving(this); + } + else + { + child.DispatchEvent("onRemovedFromStage", null); + if (child == Stage.inst.focus) + Stage.inst._OnFocusRemoving(this); + } + } + _children.Remove(child); + InvalidateBatchingState(true); + if (!dispose) + child.InternalSetParent(null); + else + child.Dispose(); + + return child; + } + else + throw new Exception("Invalid child index"); + } + + /// + /// + /// + public void RemoveChildren() + { + RemoveChildren(0, int.MaxValue, false); + } + + /// + /// + /// + /// + /// + /// + public void RemoveChildren(int beginIndex, int endIndex, bool dispose) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex, dispose); + } + + /// + /// + /// + /// + /// + public void SetChildIndex(DisplayObject child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == index) return; + if (oldIndex == -1) throw new ArgumentException("Not a child of this container"); + _children.RemoveAt(oldIndex); + if (index >= _children.Count) + _children.Add(child); + else + _children.Insert(index, child); + InvalidateBatchingState(true); + } + + /// + /// + /// + /// + /// + public void SwapChildren(DisplayObject child1, DisplayObject child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// + /// + /// + /// + public void SwapChildrenAt(int index1, int index2) + { + DisplayObject obj1 = _children[index1]; + DisplayObject obj2 = _children[index2]; + _children[index1] = obj2; + _children[index2] = obj1; + InvalidateBatchingState(true); + } + + /// + /// + /// + /// + /// + public void ChangeChildrenOrder(IList indice, IList objs) + { + int cnt = objs.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject obj = objs[i]; + if (obj.parent != this) + throw new Exception("Not a child of this container"); + + _children[indice[i]] = obj; + } + InvalidateBatchingState(true); + } + + /// + /// + /// + /// + public IEnumerator GetDescendants(bool backward) + { + return new DescendantsEnumerator(this, backward); + } + + /// + /// + /// + public Rect? clipRect + { + get { return _clipRect; } + set + { + if (_clipRect != value) + { + _clipRect = value; + UpdateBatchingFlags(); + } + } + } + + /// + /// + /// + public DisplayObject mask + { + get { return _mask; } + set + { + if (_mask != value) + { + _mask = value; + UpdateBatchingFlags(); + } + } + } + + /// + /// + /// + public void CreateGraphics() + { + if (graphics == null) + { + graphics = new NGraphics(this.gameObject); + graphics.texture = NTexture.Empty; + } + } + + public override Rect GetBounds(DisplayObject targetSpace) + { + if (_clipRect != null) + return TransformRect((Rect)_clipRect, targetSpace); + + int count = _children.Count; + + Rect rect; + if (count == 0) + { + Vector2 v = TransformPoint(Vector2.zero, targetSpace); + rect = Rect.MinMaxRect(v.x, v.y, 0, 0); + } + else if (count == 1) + { + rect = _children[0].GetBounds(targetSpace); + } + else + { + float minX = float.MaxValue, maxX = float.MinValue; + float minY = float.MaxValue, maxY = float.MinValue; + + for (int i = 0; i < count; ++i) + { + rect = _children[i].GetBounds(targetSpace); + minX = minX < rect.xMin ? minX : rect.xMin; + maxX = maxX > rect.xMax ? maxX : rect.xMax; + minY = minY < rect.yMin ? minY : rect.yMin; + maxY = maxY > rect.yMax ? maxY : rect.yMax; + } + + rect = Rect.MinMaxRect(minX, minY, maxX, maxY); + } + + return rect; + } + + /// + /// + /// + /// + public Camera GetRenderCamera() + { + if (renderMode == RenderMode.ScreenSpaceOverlay) + return StageCamera.main; + else + { + Camera cam = this.renderCamera; + if (cam == null) + { + if (HitTestContext.cachedMainCamera != null) + cam = HitTestContext.cachedMainCamera; + else + { + cam = Camera.main; + if (cam == null) + cam = StageCamera.main; + } + } + return cam; + } + } + + /// + /// + /// + /// + /// + /// + /// + public DisplayObject HitTest(Vector2 stagePoint, bool forTouch) + { + if (StageCamera.main == null) + { + if (this is Stage) + return this; + else + return null; + } + + HitTestContext.screenPoint = new Vector3(stagePoint.x, Screen.height - stagePoint.y, 0); + if (Display.displays.Length > 1) + { + Vector3 p = Display.RelativeMouseAt(HitTestContext.screenPoint); + if (p != Vector3.zero) + HitTestContext.screenPoint = p; + } + HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(HitTestContext.screenPoint); + HitTestContext.direction = Vector3.back; + HitTestContext.forTouch = forTouch; + HitTestContext.camera = StageCamera.main; + + DisplayObject ret = HitTest(); + if (ret != null) + return ret; + else if (this is Stage) + return this; + else + return null; + } + + override protected DisplayObject HitTest() + { + if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy) + return null; + + if (this.cachedTransform.localScale.x == 0 || this.cachedTransform.localScale.y == 0) + return null; + + Camera savedCamera = HitTestContext.camera; + Vector3 savedWorldPoint = HitTestContext.worldPoint; + Vector3 savedDirection = HitTestContext.direction; + DisplayObject target; + + if (renderMode != RenderMode.ScreenSpaceOverlay || (_flags & Flags.UserGameObject) != 0) + { + Camera cam = GetRenderCamera(); + if (cam.targetDisplay != HitTestContext.screenPoint.z) + return null; + + HitTestContext.camera = cam; + if (renderMode == RenderMode.WorldSpace) + { + Vector3 screenPoint = HitTestContext.camera.WorldToScreenPoint(this.cachedTransform.position); //only for query z value + screenPoint.x = HitTestContext.screenPoint.x; + screenPoint.y = HitTestContext.screenPoint.y; + + //获得本地z轴在世界坐标的方向 + HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(screenPoint); + Ray ray = HitTestContext.camera.ScreenPointToRay(screenPoint); + HitTestContext.direction = Vector3.zero - ray.direction; + } + else if (renderMode == RenderMode.ScreenSpaceCamera) + { + HitTestContext.worldPoint = HitTestContext.camera.ScreenToWorldPoint(HitTestContext.screenPoint); + } + } + else + { + if (HitTestContext.camera.targetDisplay != HitTestContext.screenPoint.z && !(this is Stage)) + return null; + } + + target = HitTest_Container(); + + HitTestContext.camera = savedCamera; + HitTestContext.worldPoint = savedWorldPoint; + HitTestContext.direction = savedDirection; + + return target; + } + + DisplayObject HitTest_Container() + { + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + if (_vertexMatrix != null) + HitTestContext.worldPoint = this.cachedTransform.TransformPoint(new Vector2(localPoint.x, -localPoint.y)); + + if (hitArea != null) + { + if (!hitArea.HitTest(_contentRect, localPoint)) + return null; + + if (hitArea is MeshColliderHitTest) + localPoint = ((MeshColliderHitTest)hitArea).lastHit; + } + else + { + if (_clipRect != null && !((Rect)_clipRect).Contains(localPoint)) + return null; + } + + if (_mask != null) + { + DisplayObject tmp = _mask.InternalHitTestMask(); + if (!reversedMask && tmp == null || reversedMask && tmp != null) + return null; + } + + DisplayObject target = null; + if (touchChildren) + { + int count = _children.Count; + for (int i = count - 1; i >= 0; --i) // front to back! + { + DisplayObject child = _children[i]; + if ((child._flags & Flags.GameObjectDisposed) != 0) + { + child.DisplayDisposedWarning(); + continue; + } + + if (child == _mask || (child._flags & Flags.TouchDisabled) != 0) + continue; + + target = child.InternalHitTest(); + if (target != null) + break; + } + } + + if (target == null && opaque && (hitArea != null || _contentRect.Contains(localPoint))) + target = this; + + return target; + } + + /// + /// + /// + /// + /// + public bool IsAncestorOf(DisplayObject obj) + { + if (obj == null) + return false; + + Container p = obj.parent; + while (p != null) + { + if (p == this) + return true; + + p = p.parent; + } + return false; + } + + /// + /// + /// + public bool fairyBatching + { + get { return (_flags & Flags.FairyBatching) != 0; } + set + { + bool oldValue = (_flags & Flags.FairyBatching) != 0; + if (oldValue != value) + { + if (value) + _flags |= Flags.FairyBatching; + else + _flags &= ~Flags.FairyBatching; + UpdateBatchingFlags(); + } + } + } + + internal void UpdateBatchingFlags() + { + bool oldValue = (_flags & Flags.BatchingRoot) != 0; + bool newValue = (_flags & Flags.FairyBatching) != 0 || _clipRect != null || _mask != null || _paintingMode > 0; + if (newValue) + _flags |= Flags.BatchingRoot; + else + _flags &= ~Flags.BatchingRoot; + if (oldValue != newValue) + { + if (newValue) + _flags |= Flags.BatchingRequested; + else if (_descendants != null) + _descendants.Clear(); + + InvalidateBatchingState(); + } + } + + /// + /// + /// + /// + public void InvalidateBatchingState(bool childrenChanged) + { + if (childrenChanged && (_flags & Flags.BatchingRoot) != 0) + _flags |= Flags.BatchingRequested; + else + { + Container p = this.parent; + while (p != null) + { + if ((p._flags & Flags.BatchingRoot) != 0) + { + p._flags |= Flags.BatchingRequested; + break; + } + + p = p.parent; + } + } + } + + /// + /// + /// + /// + public void SetChildrenLayer(int value) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _children[i]; + child._SetLayerDirect(value); + if ((child is Container) && child._paintingMode == 0) + ((Container)child).SetChildrenLayer(value); + } + } + + override public void Update(UpdateContext context) + { + if ((_flags & Flags.UserGameObject) != 0 && !gameObject.activeInHierarchy) + return; + + base.Update(context); + + if (_paintingMode != 0) + { + if ((_flags & Flags.CacheAsBitmap) != 0 && _paintingInfo.flag == 2) + { + if (onUpdate != null) + onUpdate(); + return; + } + + context.EnterPaintingMode(); + } + + if (_mask != null) + { + context.EnterClipping(this.id, reversedMask); + if (_mask.graphics != null) + _mask.graphics._PreUpdateMask(context, _mask.id); + } + else if (_clipRect != null) + context.EnterClipping(this.id, this.TransformRect((Rect)_clipRect, null), clipSoftness); + + float savedAlpha = context.alpha; + context.alpha *= this.alpha; + bool savedGrayed = context.grayed; + context.grayed = context.grayed || this.grayed; + + if ((_flags & Flags.FairyBatching) != 0) + context.batchingDepth++; + + if (context.batchingDepth > 0) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _children[i]; + if ((child._flags & Flags.GameObjectDisposed) != 0) + { + child.DisplayDisposedWarning(); + continue; + } + + if (child.visible) + child.Update(context); + } + } + else + { + if (_mask != null) + _mask.renderingOrder = context.renderingOrder++; + + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _children[i]; + if ((child._flags & Flags.GameObjectDisposed) != 0) + { + child.DisplayDisposedWarning(); + continue; + } + + if (child.visible) + { + if (!(child.graphics != null && child.graphics._maskFlag == 1)) //if not a mask + child.renderingOrder = context.renderingOrder++; + + child.Update(context); + } + } + + if (_mask != null) + { + if (_mask.graphics != null) + _mask.graphics._SetStencilEraserOrder(context.renderingOrder++); + } + } + + if ((_flags & Flags.FairyBatching) != 0) + { + if (context.batchingDepth == 1) + SetRenderingOrder(context); + context.batchingDepth--; + } + + context.alpha = savedAlpha; + context.grayed = savedGrayed; + + if (_clipRect != null || _mask != null) + context.LeaveClipping(); + + if (_paintingMode != 0) + { + context.LeavePaintingMode(); + UpdateContext.OnEnd += _paintingInfo.captureDelegate; + } + + if (onUpdate != null) + onUpdate(); + } + + private void SetRenderingOrder(UpdateContext context) + { + if ((_flags & Flags.BatchingRequested) != 0) + DoFairyBatching(); + + if (_mask != null) + _mask.renderingOrder = context.renderingOrder++; + + int cnt = _descendants.Count; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = _descendants[i]; + if (!(child.graphics != null && child.graphics._maskFlag == 1)) + child.renderingOrder = context.renderingOrder++; + + if ((child._flags & Flags.BatchingRoot) != 0) + ((Container)child).SetRenderingOrder(context); + } + + if (_mask != null) + { + if (_mask.graphics != null) + _mask.graphics._SetStencilEraserOrder(context.renderingOrder++); + } + } + + private void DoFairyBatching() + { + _flags &= ~Flags.BatchingRequested; + + if (_descendants == null) + _descendants = new List(); + else + _descendants.Clear(); + CollectChildren(this, false); + + int cnt = _descendants.Count; + + int i, j, k, m; + object curMat, testMat, lastMat; + DisplayObject current, test; + float[] bound; + for (i = 0; i < cnt; i++) + { + current = _descendants[i]; + bound = current._batchingBounds; + curMat = current.material; + if (curMat == null || (current._flags & Flags.SkipBatching) != 0) + continue; + + k = -1; + lastMat = null; + m = i; + for (j = i - 1; j >= 0; j--) + { + test = _descendants[j]; + if ((test._flags & Flags.SkipBatching) != 0) + break; + + testMat = test.material; + if (testMat != null) + { + if (lastMat != testMat) + { + lastMat = testMat; + m = j + 1; + } + + if (curMat == testMat) + k = m; + } + + if ((bound[0] > test._batchingBounds[0] ? bound[0] : test._batchingBounds[0]) + <= (bound[2] < test._batchingBounds[2] ? bound[2] : test._batchingBounds[2]) + && (bound[1] > test._batchingBounds[1] ? bound[1] : test._batchingBounds[1]) + <= (bound[3] < test._batchingBounds[3] ? bound[3] : test._batchingBounds[3])) + { + if (k == -1) + k = m; + break; + } + } + if (k != -1 && i != k) + { + _descendants.RemoveAt(i); + _descendants.Insert(k, current); + } + } + + //Debug.Log("DoFairyBatching " + cnt + "," + this.cachedTransform.GetInstanceID()); + } + + private void CollectChildren(Container initiator, bool outlineChanged) + { + int count = _children.Count; + for (int i = 0; i < count; i++) + { + DisplayObject child = _children[i]; + if (!child.visible) + continue; + + if (child._batchingBounds == null) + child._batchingBounds = new float[4]; + + if (child is Container) + { + Container container = (Container)child; + if ((container._flags & Flags.BatchingRoot) != 0) + { + initiator._descendants.Add(container); + if (outlineChanged || (container._flags & Flags.OutlineChanged) != 0) + { + Rect rect = container.GetBounds(initiator); + container._batchingBounds[0] = rect.xMin; + container._batchingBounds[1] = rect.yMin; + container._batchingBounds[2] = rect.xMax; + container._batchingBounds[3] = rect.yMax; + } + if ((container._flags & Flags.BatchingRequested) != 0) + container.DoFairyBatching(); + } + else + container.CollectChildren(initiator, outlineChanged || (container._flags & Flags.OutlineChanged) != 0); + } + else if (child != initiator._mask) + { + if (outlineChanged || (child._flags & Flags.OutlineChanged) != 0) + { + Rect rect = child.GetBounds(initiator); + child._batchingBounds[0] = rect.xMin; + child._batchingBounds[1] = rect.yMin; + child._batchingBounds[2] = rect.xMax; + child._batchingBounds[3] = rect.yMax; + } + initiator._descendants.Add(child); + } + + child._flags &= ~Flags.OutlineChanged; + } + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + base.Dispose(); //Destroy GameObject tree first, avoid destroying each seperately; + + int numChildren = _children.Count; + for (int i = numChildren - 1; i >= 0; --i) + { + DisplayObject obj = _children[i]; + obj.InternalSetParent(null); //Avoid RemoveParent call + obj.Dispose(); + } + } + + /// + /// If true, when the container is focused, tab navigation is lock inside it. + /// + public bool tabStopChildren + { + get { return (_flags & Flags.TabStopChildren) != 0; } + set + { + if (value) + _flags |= Flags.TabStopChildren; + else + _flags &= ~Flags.TabStopChildren; + } + } + + struct DescendantsEnumerator : IEnumerator + { + Container _root; + Container _com; + DisplayObject _current; + int _index; + bool _forward; + + public DescendantsEnumerator(Container root, bool backward) + { + _root = root; + _com = _root; + _current = null; + _forward = !backward; + if (_forward) + _index = 0; + else + _index = _com._children.Count - 1; + } + + public DisplayObject Current + { + get { return _current; } + } + + object IEnumerator.Current + { + get { return _current; } + } + + public bool MoveNext() + { + if (_forward) + { + if (_index >= _com._children.Count) + { + if (_com == _root) + { + _current = null; + return false; + } + + _current = _com; + _com = _com.parent; + _index = _com.GetChildIndex(_current) + 1; + return true; + } + else + { + DisplayObject obj = _com._children[_index]; + if (obj is Container) + { + _com = (Container)obj; + _index = 0; + return MoveNext(); + } + _index++; + _current = obj; + return true; + } + } + else + { + if (_index < 0) + { + if (_com == _root) + { + _current = null; + return false; + } + + _current = _com; + _com = _com.parent; + _index = _com.GetChildIndex(_current) - 1; + return true; + } + else + { + DisplayObject obj = _com._children[_index]; + if (obj is Container) + { + _com = (Container)obj; + _index = _com._children.Count - 1; + return MoveNext(); + } + _index--; + _current = obj; + return true; + } + } + } + + public void Reset() + { + _com = _root; + _current = null; + _index = 0; + } + + public void Dispose() + { + } + } + } +} diff --git a/Assets/Scripts/Core/Container.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs.meta similarity index 100% rename from Assets/Scripts/Core/Container.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Container.cs.meta diff --git a/Assets/Scripts/Core/DisplayObject.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs similarity index 96% rename from Assets/Scripts/Core/DisplayObject.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs index 11c79c62..5909a65b 100644 --- a/Assets/Scripts/Core/DisplayObject.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs @@ -1,1878 +1,1878 @@ -using System; -using System.Text; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class DisplayObject : EventDispatcher - { - /// - /// - /// - public string name; - - /// - /// - /// - public Container parent { get; private set; } - - /// - /// - /// - public GameObject gameObject { get; protected set; } - - /// - /// - /// - public Transform cachedTransform { get; protected set; } - - /// - /// - /// - public NGraphics graphics { get; protected set; } - - /// - /// - /// - public NGraphics paintingGraphics { get; protected set; } - - /// - /// - /// - public event Action onPaint; - - /// - /// - /// - public GObject gOwner; - - /// - /// - /// - public uint id; - - bool _visible; - bool _touchable; - Vector2 _pivot; - Vector3 _pivotOffset; - Vector3 _rotation; //由于万向锁,单独旋转一个轴是会影响到其他轴的,所以这里需要单独保存 - Vector2 _skew; - int _renderingOrder; - float _alpha; - bool _grayed; - BlendMode _blendMode; - IFilter _filter; - Transform _home; - string _cursor; - bool _perspective; - int _focalLength; - Vector3 _pixelPerfectAdjustment; - int _checkPixelPerfect; - - EventListener _onClick; - EventListener _onRightClick; - EventListener _onTouchBegin; - EventListener _onTouchMove; - EventListener _onTouchEnd; - EventListener _onRollOver; - EventListener _onRollOut; - EventListener _onMouseWheel; - EventListener _onAddedToStage; - EventListener _onRemovedFromStage; - EventListener _onKeyDown; - EventListener _onClickLink; - EventListener _onFocusIn; - EventListener _onFocusOut; - - protected internal int _paintingMode; //1-滤镜,2-blendMode,4-transformMatrix, 8-cacheAsBitmap - protected internal PaintingInfo _paintingInfo; - protected Rect _contentRect; - protected NGraphics.VertexMatrix _vertexMatrix; - protected internal Flags _flags; - protected internal float[] _batchingBounds; - - internal static uint _gInstanceCounter; - - internal static HideFlags hideFlags = HideFlags.None; - - public DisplayObject() - { - id = _gInstanceCounter++; - - _alpha = 1; - _visible = true; - _touchable = true; - _blendMode = BlendMode.Normal; - _focalLength = 2000; - _flags |= Flags.OutlineChanged; - if (UIConfig.makePixelPerfect) - _flags |= Flags.PixelPerfect; - } - - /// - /// - /// - public EventListener onClick - { - get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } - } - - /// - /// - /// - public EventListener onRightClick - { - get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } - } - - /// - /// - /// - public EventListener onTouchBegin - { - get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } - } - - /// - /// - /// - public EventListener onTouchMove - { - get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } - } - - /// - /// - /// - public EventListener onTouchEnd - { - get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } - } - - /// - /// - /// - public EventListener onRollOver - { - get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } - } - - /// - /// - /// - public EventListener onRollOut - { - get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } - } - - /// - /// - /// - public EventListener onMouseWheel - { - get { return _onMouseWheel ?? (_onMouseWheel = new EventListener(this, "onMouseWheel")); } - } - - /// - /// - /// - public EventListener onAddedToStage - { - get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } - } - - /// - /// - /// - public EventListener onRemovedFromStage - { - get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } - } - - /// - /// - /// - public EventListener onKeyDown - { - get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } - } - - /// - /// - /// - public EventListener onClickLink - { - get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } - } - - /// - /// - /// - public EventListener onFocusIn - { - get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } - } - - /// - /// - /// - public EventListener onFocusOut - { - get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } - - } - - protected void CreateGameObject(string gameObjectName) - { - gameObject = new GameObject(gameObjectName); - cachedTransform = gameObject.transform; - if (Application.isPlaying) - { - UnityEngine.Object.DontDestroyOnLoad(gameObject); - - DisplayObjectInfo info = gameObject.AddComponent(); - info.displayObject = this; - } - gameObject.hideFlags = DisplayObject.hideFlags; - gameObject.SetActive(false); - } - - protected void SetGameObject(GameObject gameObject) - { - this.gameObject = gameObject; - this.cachedTransform = gameObject.transform; - _rotation = cachedTransform.localEulerAngles; - - _flags |= Flags.UserGameObject; - } - - protected void DestroyGameObject() - { - if ((_flags & Flags.UserGameObject) == 0 && gameObject != null) - { - if (Application.isPlaying) - GameObject.Destroy(gameObject); - else - GameObject.DestroyImmediate(gameObject); - gameObject = null; - cachedTransform = null; - } - } - - /// - /// - /// - public float alpha - { - get { return _alpha; } - set { _alpha = value; } - } - - /// - /// - /// - public bool grayed - { - get { return _grayed; } - set { _grayed = value; } - } - - /// - /// - /// - public bool visible - { - get { return _visible; } - set - { - if (_visible != value) - { - _visible = value; - _flags |= Flags.OutlineChanged; - if (parent != null && _visible) - { - gameObject.SetActive(true); - InvalidateBatchingState(); - if (this is Container) - ((Container)this).InvalidateBatchingState(true); - } - else - gameObject.SetActive(false); - } - } - } - - /// - /// - /// - public float x - { - get { return cachedTransform.localPosition.x; } - set - { - SetPosition(value, -cachedTransform.localPosition.y, cachedTransform.localPosition.z); - } - } - - /// - /// - /// - public float y - { - get { return -cachedTransform.localPosition.y; } - set - { - SetPosition(cachedTransform.localPosition.x, value, cachedTransform.localPosition.z); - } - } - - /// - /// - /// - public float z - { - get { return cachedTransform.localPosition.z; } - set - { - SetPosition(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, value); - } - } - - /// - /// - /// - public Vector2 xy - { - get { return new Vector2(this.x, this.y); } - set { SetPosition(value.x, value.y, cachedTransform.localPosition.z); } - } - - /// - /// - /// - public Vector3 position - { - get { return new Vector3(this.x, this.y, this.z); } - set { SetPosition(value.x, value.y, value.z); } - } - - /// - /// - /// - /// - /// - public void SetXY(float xv, float yv) - { - SetPosition(xv, yv, cachedTransform.localPosition.z); - } - - /// - /// - /// - /// - /// - /// - public void SetPosition(float xv, float yv, float zv) - { - Vector3 v = new Vector3(); - v.x = xv; - v.y = -yv; - v.z = zv; - if (v != cachedTransform.localPosition) - { - cachedTransform.localPosition = v; - _flags |= Flags.OutlineChanged; - if ((_flags & Flags.PixelPerfect) != 0) - { - //总在下一帧再完成PixelPerfect,这样当物体在连续运动时,不会因为PixelPerfect而发生抖动。 - _checkPixelPerfect = Time.frameCount; - _pixelPerfectAdjustment = Vector3.zero; - } - } - } - - /// - /// If the object position is align by pixel - /// - public bool pixelPerfect - { - get { return (_flags & Flags.PixelPerfect) != 0; } - set - { - if (value) - _flags |= Flags.PixelPerfect; - else - _flags &= ~Flags.PixelPerfect; - } - } - - /// - /// - /// - public float width - { - get - { - EnsureSizeCorrect(); - return _contentRect.width; - } - set - { - if (!Mathf.Approximately(value, _contentRect.width)) - { - _contentRect.width = value; - _flags |= Flags.WidthChanged; - _flags &= ~Flags.HeightChanged; - OnSizeChanged(); - } - } - } - - /// - /// - /// - public float height - { - get - { - EnsureSizeCorrect(); - return _contentRect.height; - } - set - { - if (!Mathf.Approximately(value, _contentRect.height)) - { - _contentRect.height = value; - _flags &= ~Flags.WidthChanged; - _flags |= Flags.HeightChanged; - OnSizeChanged(); - } - } - } - - /// - /// - /// - public Vector2 size - { - get - { - EnsureSizeCorrect(); - return _contentRect.size; - } - set - { - SetSize(value.x, value.y); - } - } - - /// - /// - /// - /// - /// - public void SetSize(float wv, float hv) - { - if (!Mathf.Approximately(wv, _contentRect.width)) - _flags |= Flags.WidthChanged; - else - _flags &= ~Flags.WidthChanged; - if (!Mathf.Approximately(hv, _contentRect.height)) - _flags |= Flags.HeightChanged; - else - _flags &= ~Flags.HeightChanged; - - if ((_flags & Flags.WidthChanged) != 0 || (_flags & Flags.HeightChanged) != 0) - { - _contentRect.width = wv; - _contentRect.height = hv; - OnSizeChanged(); - } - } - - virtual public void EnsureSizeCorrect() - { - } - - virtual protected void OnSizeChanged() - { - ApplyPivot(); - - if (_paintingInfo != null) - _paintingInfo.flag = 1; - if (graphics != null) - graphics.contentRect = _contentRect; - _flags |= Flags.OutlineChanged; - } - - /// - /// - /// - public float scaleX - { - get { return cachedTransform.localScale.x; } - set - { - Vector3 v = cachedTransform.localScale; - v.x = v.z = ValidateScale(value); - cachedTransform.localScale = v; - _flags |= Flags.OutlineChanged; - ApplyPivot(); - } - } - - /// - /// - /// - public float scaleY - { - get { return cachedTransform.localScale.y; } - set - { - Vector3 v = cachedTransform.localScale; - v.y = ValidateScale(value); - cachedTransform.localScale = v; - _flags |= Flags.OutlineChanged; - ApplyPivot(); - } - } - - /// - /// - /// - /// - /// - public void SetScale(float xv, float yv) - { - Vector3 v = new Vector3(); - v.x = v.z = ValidateScale(xv); - v.y = ValidateScale(yv); - cachedTransform.localScale = v; - _flags |= Flags.OutlineChanged; - ApplyPivot(); - } - - /// - /// 在scale过小情况(极端情况=0),当使用Transform的坐标变换时,变换到世界,再从世界变换到本地,会由于精度问题造成结果错误。 - /// 这种错误会导致Batching错误,因为Batching会使用缓存的outline。 - /// 这里限制一下scale的最小值作为当前解决方案。 - /// 这个方案并不完美,因为限制了本地scale值并不能保证对世界scale不会过小。 - /// - /// - /// - private float ValidateScale(float value) - { - if (value >= 0 && value < 0.001f) - value = 0.001f; - else if (value < 0 && value > -0.001f) - value = -0.001f; - return value; - } - - /// - /// - /// - public Vector2 scale - { - get { return cachedTransform.localScale; } - set - { - SetScale(value.x, value.y); - } - } - - /// - /// - /// - public float rotation - { - get - { - //和Unity默认的旋转方向相反 - return -_rotation.z; - } - set - { - _rotation.z = -value; - _flags |= Flags.OutlineChanged; - if (_perspective) - UpdateTransformMatrix(); - else - { - cachedTransform.localEulerAngles = _rotation; - ApplyPivot(); - } - } - } - - /// - /// - /// - public float rotationX - { - get - { - return _rotation.x; - } - set - { - _rotation.x = value; - _flags |= Flags.OutlineChanged; - if (_perspective) - UpdateTransformMatrix(); - else - { - cachedTransform.localEulerAngles = _rotation; - ApplyPivot(); - } - } - } - - /// - /// - /// - public float rotationY - { - get - { - return _rotation.y; - } - set - { - _rotation.y = value; - _flags |= Flags.OutlineChanged; - if (_perspective) - UpdateTransformMatrix(); - else - { - cachedTransform.localEulerAngles = _rotation; - ApplyPivot(); - } - } - } - - /// - /// - /// - public Vector2 skew - { - get { return _skew; } - set - { - _skew = value; - _flags |= Flags.OutlineChanged; - - if (!Application.isPlaying) //编辑期间不支持!! - return; - - UpdateTransformMatrix(); - } - } - - /// - /// 当对象处于ScreenSpace,也就是使用正交相机渲染时,对象虽然可以绕X轴或者Y轴旋转,但没有透视效果。设置perspective,可以模拟出透视效果。 - /// - public bool perspective - { - get - { - return _perspective; - } - set - { - if (_perspective != value) - { - _perspective = value; - if (_perspective)//屏蔽Unity自身的旋转变换 - cachedTransform.localEulerAngles = Vector3.zero; - else - cachedTransform.localEulerAngles = _rotation; - - ApplyPivot(); - UpdateTransformMatrix(); - } - } - } - - /// - /// - /// - public int focalLength - { - get { return _focalLength; } - set - { - if (value <= 0) - value = 1; - - _focalLength = value; - if (_vertexMatrix != null) - UpdateTransformMatrix(); - } - } - - void UpdateTransformMatrix() - { - Matrix4x4 matrix = Matrix4x4.identity; - if (_skew.x != 0 || _skew.y != 0) - ToolSet.SkewMatrix(ref matrix, _skew.x, _skew.y); - if (_perspective) - matrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one); - if (matrix.isIdentity) - _vertexMatrix = null; - else if (_vertexMatrix == null) - _vertexMatrix = new NGraphics.VertexMatrix(); - - //组件的transformMatrix是通过paintingMode实现的,因为全部通过矩阵变换的话,和unity自身的变换混杂在一起,无力理清。 - if (_vertexMatrix != null) - { - _vertexMatrix.matrix = matrix; - _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength); - - if (graphics == null) - EnterPaintingMode(4, null); - } - else - { - if (graphics == null) - LeavePaintingMode(4); - } - - if (_paintingMode > 0) - { - paintingGraphics.vertexMatrix = _vertexMatrix; - _paintingInfo.flag = 1; - } - else if (graphics != null) - graphics.vertexMatrix = _vertexMatrix; - - _flags |= Flags.OutlineChanged; - } - - /// - /// - /// - public Vector2 pivot - { - get { return _pivot; } - set - { - Vector3 deltaPivot = new Vector2((value.x - _pivot.x) * _contentRect.width, (_pivot.y - value.y) * _contentRect.height); - Vector3 oldOffset = _pivotOffset; - - _pivot = value; - UpdatePivotOffset(); - Vector3 v = cachedTransform.localPosition; - v += oldOffset - _pivotOffset + deltaPivot; - cachedTransform.localPosition = v; - _flags |= Flags.OutlineChanged; - } - } - - void UpdatePivotOffset() - { - float px = _pivot.x * _contentRect.width; - float py = _pivot.y * _contentRect.height; - - //注意这里不用处理skew,因为在顶点变换里有对pivot的处理 - Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, cachedTransform.localRotation, cachedTransform.localScale); - _pivotOffset = matrix.MultiplyPoint(new Vector3(px, -py, 0)); - - if (_vertexMatrix != null) - _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength); - } - - void ApplyPivot() - { - if (_pivot.x != 0 || _pivot.y != 0) - { - Vector3 oldOffset = _pivotOffset; - - UpdatePivotOffset(); - Vector3 v = cachedTransform.localPosition; - - if ((_flags & Flags.PixelPerfect) != 0) - { - v -= _pixelPerfectAdjustment; - _checkPixelPerfect = Time.frameCount; - _pixelPerfectAdjustment = Vector3.zero; - } - - v += oldOffset - _pivotOffset; - cachedTransform.localPosition = v; - _flags |= Flags.OutlineChanged; - } - } - - /// - /// This is the pivot position - /// - public Vector3 location - { - get - { - Vector3 pos = this.position; - pos.x += _pivotOffset.x; - pos.y -= _pivotOffset.y; - pos.z += _pivotOffset.z; - return pos; - } - - set - { - this.SetPosition(value.x - _pivotOffset.x, value.y + _pivotOffset.y, value.z - _pivotOffset.z); - } - } - - /// - /// - /// - virtual public Material material - { - get - { - if (graphics != null) - return graphics.material; - else - return null; - } - set - { - if (graphics != null) - graphics.material = value; - } - } - - /// - /// - /// - virtual public string shader - { - get - { - if (graphics != null) - return graphics.shader; - else - return null; - } - set - { - if (graphics != null) - graphics.shader = value; - } - } - - /// - /// - /// - virtual public int renderingOrder - { - get - { - return _renderingOrder; - } - set - { - if ((_flags & Flags.GameObjectDisposed) != 0) - { - DisplayDisposedWarning(); - return; - } - - _renderingOrder = value; - if (graphics != null) - graphics.sortingOrder = value; - if (_paintingMode > 0) - paintingGraphics.sortingOrder = value; - } - } - - /// - /// - /// - public int layer - { - get - { - if (_paintingMode > 0) - return paintingGraphics.gameObject.layer; - else - return gameObject.layer; - } - set - { - SetLayer(value, false); - } - } - - /// - /// If the object can be focused? - /// - public bool focusable - { - get { return (_flags & Flags.NotFocusable) == 0; } - set - { - if (value) - _flags &= ~Flags.NotFocusable; - else - _flags |= Flags.NotFocusable; - } - } - - /// - /// If the object can be navigated by TAB? - /// - public bool tabStop - { - get { return (_flags & Flags.TabStop) != 0; } - set - { - if (value) - _flags |= Flags.TabStop; - else - _flags &= ~Flags.TabStop; - } - } - - /// - /// If the object focused? - /// - public bool focused - { - get - { - return Stage.inst.focus == this || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.focus); - } - } - - internal bool _AcceptTab() - { - if (_touchable && _visible - && ((_flags & Flags.TabStop) != 0 || (_flags & Flags.TabStopChildren) != 0) - && (_flags & Flags.NotFocusable) == 0) - { - Stage.inst.SetFocus(this, true); - return true; - } - else - return false; - } - - /// - /// - /// - /// - public string cursor - { - get { return _cursor; } - set - { - _cursor = value; - if (Application.isPlaying - && (this == Stage.inst.touchTarget || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.touchTarget))) - { - Stage.inst._ChangeCursor(_cursor); - } - } - } - - /// - /// - /// - public bool isDisposed - { - get { return (_flags & Flags.Disposed) != 0 || gameObject == null; } - } - - internal void InternalSetParent(Container value) - { - if (parent != value) - { - if (value == null && (parent._flags & Flags.Disposed) != 0) - parent = value; - else - { - parent = value; - UpdateHierarchy(); - } - _flags |= Flags.OutlineChanged; - } - } - - /// - /// - /// - public Container topmost - { - get - { - DisplayObject currentObject = this; - while (currentObject.parent != null) - currentObject = currentObject.parent; - return currentObject as Container; - } - } - - /// - /// - /// - public Stage stage - { - get - { - return topmost as Stage; - } - } - - /// - /// - /// - public Container worldSpaceContainer - { - get - { - Container wsc = null; - DisplayObject currentObject = this; - while (currentObject.parent != null) - { - if ((currentObject is Container) && ((Container)currentObject).renderMode == RenderMode.WorldSpace) - { - wsc = (Container)currentObject; - break; - } - currentObject = currentObject.parent; - } - - return wsc; - } - } - - /// - /// - /// - public bool touchable - { - get { return _touchable; } - set - { - if (_touchable != value) - { - _touchable = value; - if (this is Container) - { - ColliderHitTest hitArea = ((Container)this).hitArea as ColliderHitTest; - if (hitArea != null) - hitArea.collider.enabled = value; - } - } - } - } - - /// - /// - /// - /// - public bool touchDisabled - { - get { return (_flags & Flags.TouchDisabled) != 0; } - } - - /// - /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 - /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 - /// - public void EnterPaintingMode() - { - EnterPaintingMode(16384, null, 1); - } - - /// - /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 - /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 - /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 - /// - /// 请求者id - /// 纹理四周的留空。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。 - public void EnterPaintingMode(int requestorId, Margin? extend) - { - EnterPaintingMode(requestorId, extend, 1); - } - - /// - /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 - /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 - /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 - /// - /// 请求者id - /// 扩展纹理。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。 - /// 附加一个缩放系数 - public void EnterPaintingMode(int requestorId, Margin? extend, float scale) - { - bool first = _paintingMode == 0; - _paintingMode |= requestorId; - if (first) - { - if (_paintingInfo == null) - { - _paintingInfo = new PaintingInfo() - { - captureDelegate = Capture, - scale = 1 - }; - } - - if (paintingGraphics == null) - { - if (graphics == null) - paintingGraphics = new NGraphics(this.gameObject); - else - { - GameObject go = new GameObject(this.gameObject.name + " (Painter)"); - go.layer = this.gameObject.layer; - go.transform.SetParent(cachedTransform, false); - go.hideFlags = DisplayObject.hideFlags; - paintingGraphics = new NGraphics(go); - } - } - else - paintingGraphics.enabled = true; - paintingGraphics.vertexMatrix = null; - - if (this is Container) - { - ((Container)this).SetChildrenLayer(CaptureCamera.hiddenLayer); - ((Container)this).UpdateBatchingFlags(); - } - else - this.InvalidateBatchingState(); - - if (graphics != null) - this.gameObject.layer = CaptureCamera.hiddenLayer; - } - if (extend != null) - _paintingInfo.extend = (Margin)extend; - _paintingInfo.scale = scale; - _paintingInfo.flag = 1; - } - - /// - /// 离开绘画模式 - /// - /// - public void LeavePaintingMode(int requestorId) - { - if (_paintingMode == 0 || (_flags & Flags.Disposed) != 0) - return; - - _paintingMode ^= requestorId; - if (_paintingMode == 0) - { - paintingGraphics.enabled = false; - - if (this is Container) - { - ((Container)this).SetChildrenLayer(this.layer); - ((Container)this).UpdateBatchingFlags(); - } - else - this.InvalidateBatchingState(); - - if (graphics != null) - this.gameObject.layer = paintingGraphics.gameObject.layer; - } - } - - /// - /// - /// - public bool paintingMode - { - get { return _paintingMode > 0; } - } - - /// - /// 将整个显示对象(如果是容器,则容器包含的整个显示列表)静态化,所有内容被缓冲到一张纹理上。 - /// DC将保持为1。CPU消耗将降到最低。但对象的任何变化不会更新。 - /// 当cacheAsBitmap已经为true时,再次调用cacheAsBitmap=true将会刷新对象一次。 - /// - public bool cacheAsBitmap - { - get { return (_flags & Flags.CacheAsBitmap) != 0; } - set - { - if (value) - { - _flags |= Flags.CacheAsBitmap; - EnterPaintingMode(8, null, UIContentScaler.scaleFactor); - } - else - { - _flags &= ~Flags.CacheAsBitmap; - LeavePaintingMode(8); - } - } - } - - /// - /// - /// - /// - /// - /// - public Texture2D GetScreenShot(Margin? extend, float scale) - { - EnterPaintingMode(8, null, scale); - UpdatePainting(); - Capture(); - - Texture2D output; - if (paintingGraphics.texture == null) - output = new Texture2D(1, 1, TextureFormat.RGBA32, false, true); - else - { - RenderTexture rt = (RenderTexture)paintingGraphics.texture.nativeTexture; - output = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true); - RenderTexture old = RenderTexture.active; - RenderTexture.active = rt; - output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); - output.Apply(); - RenderTexture.active = old; - } - - LeavePaintingMode(8); - - return output; - } - - /// - /// - /// - public IFilter filter - { - get - { - return _filter; - } - - set - { - if (!Application.isPlaying) //编辑期间不支持!! - return; - - if (value == _filter) - return; - - if (_filter != null) - _filter.Dispose(); - - if (value != null && value.target != null) - value.target.filter = null; - - _filter = value; - if (_filter != null) - _filter.target = this; - } - } - - /// - /// - /// - public BlendMode blendMode - { - get { return _blendMode; } - set - { - _blendMode = value; - InvalidateBatchingState(); - - if (graphics == null) - { - if (_blendMode != BlendMode.Normal) - { - if (!Application.isPlaying) //Not supported in edit mode! - return; - - EnterPaintingMode(2, null); - paintingGraphics.blendMode = _blendMode; - } - else - LeavePaintingMode(2); - } - else - graphics.blendMode = _blendMode; - } - } - - /// - /// - /// - /// - /// - virtual public Rect GetBounds(DisplayObject targetSpace) - { - EnsureSizeCorrect(); - - if (targetSpace == this) // optimization - { - return _contentRect; - } - else if (targetSpace == parent && _rotation.z == 0) - { - return new Rect(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, - _contentRect.width * cachedTransform.localScale.x, _contentRect.height * cachedTransform.localScale.y); - } - else - return TransformRect(_contentRect, targetSpace); - } - - internal DisplayObject InternalHitTest() - { - if (_visible && (!HitTestContext.forTouch || _touchable)) - return HitTest(); - else - return null; - } - - internal DisplayObject InternalHitTestMask() - { - if (_visible) - return HitTest(); - else - return null; - } - - virtual protected DisplayObject HitTest() - { - Rect rect = GetBounds(this); - if (rect.width == 0 || rect.height == 0) - return null; - - Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); - if (rect.Contains(localPoint)) - return this; - else - return null; - } - - /// - /// 将舞台坐标转换为本地坐标 - /// - /// - /// - public Vector2 GlobalToLocal(Vector2 point) - { - Container wsc = this.worldSpaceContainer; - - if (wsc != null)//I am in a world space - { - Camera cam = wsc.GetRenderCamera(); - Vector3 worldPoint; - Vector3 direction; - Vector3 screenPoint = new Vector3(); - screenPoint.x = point.x; - screenPoint.y = Screen.height - point.y; - - if (wsc.hitArea is MeshColliderHitTest) - { - Ray ray = cam.ScreenPointToRay(screenPoint); - RaycastHit hit; - if (((MeshColliderHitTest)wsc.hitArea).collider.Raycast(ray, out hit, 100)) - { - point = new Vector2(hit.textureCoord.x * _contentRect.width, (1 - hit.textureCoord.y) * _contentRect.height); - worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); - direction = Vector3.back; - } - else //当射线没有击中模型时,无法确定本地坐标 - return new Vector2(float.NaN, float.NaN); - } - else - { - screenPoint.z = cam.WorldToScreenPoint(this.cachedTransform.position).z; - worldPoint = cam.ScreenToWorldPoint(screenPoint); - Ray ray = cam.ScreenPointToRay(screenPoint); - direction = Vector3.zero - ray.direction; - } - - return this.WorldToLocal(worldPoint, direction); - } - else //I am in stage space - { - Vector3 worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); - return this.WorldToLocal(worldPoint, Vector3.back); - } - } - - /// - /// 将本地坐标转换为舞台坐标 - /// - /// - /// - public Vector2 LocalToGlobal(Vector2 point) - { - Container wsc = this.worldSpaceContainer; - - Vector3 worldPoint = this.cachedTransform.TransformPoint(point.x, -point.y, 0); - if (wsc != null) - { - if (wsc.hitArea is MeshColliderHitTest) //Not supported for UIPainter, use TransfromPoint instead. - return new Vector2(float.NaN, float.NaN); - - Vector3 screePoint = wsc.GetRenderCamera().WorldToScreenPoint(worldPoint); - return new Vector2(screePoint.x, Stage.inst.size.y - screePoint.y); - } - else - { - point = Stage.inst.cachedTransform.InverseTransformPoint(worldPoint); - point.y = -point.y; - return point; - } - } - - /// - /// 转换世界坐标点到等效的本地xy平面的点。等效的意思是他们在屏幕方向看到的位置一样。 - /// 返回的点是在对象的本地坐标空间,且z=0 - /// - /// - /// - /// - public Vector3 WorldToLocal(Vector3 worldPoint, Vector3 direction) - { - Vector3 localPoint = this.cachedTransform.InverseTransformPoint(worldPoint); - if (localPoint.z != 0) //如果对象绕x轴或y轴旋转过,或者对象是在透视相机,那么z值可能不为0, - { - //将世界坐标的摄影机方向在本地空间上投射,求出与xy平面的交点 - direction = this.cachedTransform.InverseTransformDirection(direction); - float distOnLine = Vector3.Dot(Vector3.zero - localPoint, Vector3.forward) / Vector3.Dot(direction, Vector3.forward); - if (float.IsInfinity(distOnLine)) - return Vector2.zero; - - localPoint = localPoint + direction * distOnLine; - } - else if (_vertexMatrix != null) - { - Vector3 center = _vertexMatrix.cameraPos; - center.z = 0; - center -= _vertexMatrix.matrix.MultiplyPoint(center); - - Matrix4x4 mm = _vertexMatrix.matrix.inverse; - - localPoint -= center; - localPoint = mm.MultiplyPoint(localPoint); - - Vector3 camPos = mm.MultiplyPoint(_vertexMatrix.cameraPos); - Vector3 vec = localPoint - camPos; - float lambda = -camPos.z / vec.z; - localPoint = camPos + lambda * vec; - localPoint.z = 0; - } - localPoint.y = -localPoint.y; - - return localPoint; - } - - /// - /// - /// - /// - /// - public Vector3 LocalToWorld(Vector3 localPoint) - { - localPoint.y = -localPoint.y; - if (_vertexMatrix != null) - { - Vector3 center = _vertexMatrix.cameraPos; - center.z = 0; - center -= _vertexMatrix.matrix.MultiplyPoint(center); - - localPoint = _vertexMatrix.matrix.MultiplyPoint(localPoint); - localPoint += center; - - Vector3 camPos = _vertexMatrix.cameraPos; - Vector3 vec = localPoint - camPos; - float lambda = -camPos.z / vec.z; - localPoint = camPos + lambda * vec; - localPoint.z = 0; - } - - return this.cachedTransform.TransformPoint(localPoint); - } - - /// - /// - /// - /// - /// null if to world space - /// - public Vector2 TransformPoint(Vector2 point, DisplayObject targetSpace) - { - if (targetSpace == this) - return point; - - point = LocalToWorld(point); - if (targetSpace != null) - point = targetSpace.WorldToLocal(point, Vector3.back); - - return point; - } - - /// - /// - /// - /// - /// null if to world space - /// - public Rect TransformRect(Rect rect, DisplayObject targetSpace) - { - if (targetSpace == this) - return rect; - - if (targetSpace == parent && _rotation.z == 0) // optimization - { - Vector3 vec = cachedTransform.localScale; - return new Rect((this.x + rect.x) * vec.x, (this.y + rect.y) * vec.y, - rect.width * vec.x, rect.height * vec.y); - } - else - { - Vector4 vec4 = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue); - - TransformRectPoint(rect.xMin, rect.yMin, targetSpace, ref vec4); - TransformRectPoint(rect.xMax, rect.yMin, targetSpace, ref vec4); - TransformRectPoint(rect.xMin, rect.yMax, targetSpace, ref vec4); - TransformRectPoint(rect.xMax, rect.yMax, targetSpace, ref vec4); - - return Rect.MinMaxRect(vec4.x, vec4.y, vec4.z, vec4.w); - } - } - - protected void TransformRectPoint(float px, float py, DisplayObject targetSpace, ref Vector4 vec4) - { - Vector2 v = TransformPoint(new Vector2(px, py), targetSpace); - - if (vec4.x > v.x) vec4.x = v.x; - if (vec4.z < v.x) vec4.z = v.x; - if (vec4.y > v.y) vec4.y = v.y; - if (vec4.w < v.y) vec4.w = v.y; - } - - /// - /// - /// - public void RemoveFromParent() - { - if (parent != null) - parent.RemoveChild(this); - } - - /// - /// - /// - public void InvalidateBatchingState() - { - if (parent != null) - parent.InvalidateBatchingState(true); - } - - virtual public void Update(UpdateContext context) - { - if (_checkPixelPerfect != 0) - { - if (_rotation == Vector3.zero) - { - Vector3 v = cachedTransform.localPosition; - v.x = Mathf.Round(v.x); - v.y = Mathf.Round(v.y); - _pixelPerfectAdjustment = v - cachedTransform.localPosition; - if (_pixelPerfectAdjustment != Vector3.zero) - cachedTransform.localPosition = v; - } - _checkPixelPerfect = 0; - } - - if (graphics != null) - graphics.Update(context, context.alpha * _alpha, context.grayed | _grayed); - - if (_paintingMode != 0) - { - UpdatePainting(); - - //如果是容器,Capture要等到Container.Update的最后执行,因为容器中可能也有需要Capture的内容,要等他们完成后再进行容器的Capture。 - if (!(this is Container)) - { - if ((_flags & Flags.CacheAsBitmap) == 0 || _paintingInfo.flag != 2) - UpdateContext.OnEnd += _paintingInfo.captureDelegate; - } - - paintingGraphics.Update(context, 1, false); - } - - if (_filter != null) - _filter.Update(); - - Stats.ObjectCount++; - } - - void UpdatePainting() - { - NTexture paintingTexture = paintingGraphics.texture; - if (paintingTexture != null && paintingTexture.disposed) //Texture可能已被Stage.MonitorTexture销毁 - { - paintingTexture = null; - _paintingInfo.flag = 1; - } - - if (_paintingInfo.flag == 1) - { - _paintingInfo.flag = 0; - - //从优化考虑,决定使用绘画模式的容器都需要明确指定大小,而不是自动计算包围。这在UI使用上并没有问题,因为组件总是有固定大小的 - Margin extend = _paintingInfo.extend; - paintingGraphics.contentRect = new Rect(-extend.left, -extend.top, _contentRect.width + extend.left + extend.right, _contentRect.height + extend.top + extend.bottom); - int textureWidth = Mathf.RoundToInt(paintingGraphics.contentRect.width * _paintingInfo.scale); - int textureHeight = Mathf.RoundToInt(paintingGraphics.contentRect.height * _paintingInfo.scale); - if (paintingTexture == null || paintingTexture.width != textureWidth || paintingTexture.height != textureHeight) - { - if (paintingTexture != null) - paintingTexture.Dispose(); - if (textureWidth > 0 && textureHeight > 0) - { - paintingTexture = new NTexture(CaptureCamera.CreateRenderTexture(textureWidth, textureHeight, UIConfig.depthSupportForPaintingMode)); - Stage.inst.MonitorTexture(paintingTexture); - } - else - paintingTexture = null; - paintingGraphics.texture = paintingTexture; - } - } - - if (paintingTexture != null) - paintingTexture.lastActive = Time.time; - } - - void Capture() - { - if (paintingGraphics.texture == null) - return; - - Vector2 offset = new Vector2(_paintingInfo.extend.left, _paintingInfo.extend.top); - CaptureCamera.Capture(this, (RenderTexture)paintingGraphics.texture.nativeTexture, paintingGraphics.contentRect.height, offset); - - _paintingInfo.flag = 2; //2表示已完成一次Capture - if (onPaint != null) - onPaint(); - } - - /// - /// 为对象设置一个默认的父Transform。当对象不在显示列表里时,它的GameObject挂到哪里。 - /// - public Transform home - { - get { return _home; } - set - { - _home = value; - if (value != null && cachedTransform.parent == null) - cachedTransform.SetParent(value, false); - } - } - - void UpdateHierarchy() - { - if ((_flags & Flags.GameObjectDisposed) != 0) - return; - - if ((_flags & Flags.UserGameObject) != 0) - { - //we dont change transform parent of this object - if (gameObject != null) - { - if (parent != null && visible) - gameObject.SetActive(true); - else - gameObject.SetActive(false); - } - } - else if (parent != null) - { - cachedTransform.SetParent(parent.cachedTransform, false); - - if (_visible) - gameObject.SetActive(true); - - int layerValue = parent.gameObject.layer; - if (parent._paintingMode != 0) - layerValue = CaptureCamera.hiddenLayer; - SetLayer(layerValue, true); - } - else if ((_flags & Flags.Disposed) == 0 && this.gameObject != null && !StageEngine.beingQuit) - { - if (Application.isPlaying) - { - if (gOwner == null || gOwner.parent == null)//如果gOwner还有parent的话,说明只是暂时的隐藏 - { - cachedTransform.SetParent(_home, false); - if (_home == null) - UnityEngine.Object.DontDestroyOnLoad(this.gameObject); - } - } - - gameObject.SetActive(false); - } - } - - virtual protected bool SetLayer(int value, bool fromParent) - { - if ((_flags & Flags.LayerSet) != 0) //setted - { - if (fromParent) - return false; - } - else if ((_flags & Flags.LayerFromParent) != 0) //inherit from parent - { - if (!fromParent) - _flags |= Flags.LayerSet; - } - else - { - if (fromParent) - _flags |= Flags.LayerFromParent; - else - _flags |= Flags.LayerSet; - } - - if (_paintingMode > 0) - paintingGraphics.gameObject.layer = value; - else if (gameObject.layer != value) - { - gameObject.layer = value; - if ((this is Container)) - { - int cnt = ((Container)this).numChildren; - for (int i = 0; i < cnt; i++) - { - DisplayObject child = ((Container)this).GetChildAt(i); - child.SetLayer(value, true); - } - } - } - - return true; - } - - internal void _SetLayerDirect(int value) - { - if (_paintingMode > 0) - paintingGraphics.gameObject.layer = value; - else - gameObject.layer = value; - } - - virtual public void Dispose() - { - if ((_flags & Flags.Disposed) != 0) - return; - - _flags |= Flags.Disposed; - RemoveFromParent(); - RemoveEventListeners(); - if (graphics != null) - graphics.Dispose(); - if (_filter != null) - _filter.Dispose(); - if (paintingGraphics != null) - { - if (paintingGraphics.texture != null) - paintingGraphics.texture.Dispose(); - - paintingGraphics.Dispose(); - if (paintingGraphics.gameObject != this.gameObject) - { - if (Application.isPlaying) - UnityEngine.Object.Destroy(paintingGraphics.gameObject); - else - UnityEngine.Object.DestroyImmediate(paintingGraphics.gameObject); - } - } - DestroyGameObject(); - } - - internal void DisplayDisposedWarning() - { - if ((_flags & Flags.DisposedWarning) == 0) - { - _flags |= Flags.DisposedWarning; - - StringBuilder sb = new StringBuilder(); - sb.Append("DisplayObject is still in use but GameObject was disposed. ("); - if (gOwner != null) - { - sb.Append("type=").Append(gOwner.GetType().Name).Append(", x=").Append(gOwner.x).Append(", y=").Append(gOwner.y).Append(", name=").Append(gOwner.name); - if (gOwner.packageItem != null) - sb.Append(", res=" + gOwner.packageItem.name); - } - else - { - sb.Append("id=").Append(id).Append(", type=").Append(this.GetType().Name).Append(", name=").Append(name); - } - sb.Append(")"); - Debug.LogError(sb.ToString()); - } - } - - protected internal class PaintingInfo - { - public Action captureDelegate; //缓存这个delegate,可以防止Capture状态下每帧104B的GC - public Margin extend; - public float scale; - public int flag; - } - - [Flags] - protected internal enum Flags - { - Disposed = 1, - UserGameObject = 2, - TouchDisabled = 4, - OutlineChanged = 8, - UpdatingSize = 0x10, - WidthChanged = 0x20, - HeightChanged = 0x40, - PixelPerfect = 0x80, - LayerSet = 0x100, - LayerFromParent = 0x200, - NotFocusable = 0x400, - TabStop = 0x800, - TabStopChildren = 0x1000, - FairyBatching = 0x2000, - BatchingRequested = 0x4000, - BatchingRoot = 0x8000, - SkipBatching = 0x10000, - CacheAsBitmap = 0x20000, - GameObjectDisposed = 0x40000, - DisposedWarning = 0x80000 - } - } - - /// - /// - /// - public class DisplayObjectInfo : MonoBehaviour - { - /// - /// - /// /// - [System.NonSerialized] - public DisplayObject displayObject; - - private void OnDestroy() - { - if (displayObject != null) - displayObject._flags |= DisplayObject.Flags.GameObjectDisposed; - } - } -} +using System; +using System.Text; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class DisplayObject : EventDispatcher + { + /// + /// + /// + public string name; + + /// + /// + /// + public Container parent { get; private set; } + + /// + /// + /// + public GameObject gameObject { get; protected set; } + + /// + /// + /// + public Transform cachedTransform { get; protected set; } + + /// + /// + /// + public NGraphics graphics { get; protected set; } + + /// + /// + /// + public NGraphics paintingGraphics { get; protected set; } + + /// + /// + /// + public event Action onPaint; + + /// + /// + /// + public GObject gOwner; + + /// + /// + /// + public uint id; + + bool _visible; + bool _touchable; + Vector2 _pivot; + Vector3 _pivotOffset; + Vector3 _rotation; //由于万向锁,单独旋转一个轴是会影响到其他轴的,所以这里需要单独保存 + Vector2 _skew; + int _renderingOrder; + float _alpha; + bool _grayed; + BlendMode _blendMode; + IFilter _filter; + Transform _home; + string _cursor; + bool _perspective; + int _focalLength; + Vector3 _pixelPerfectAdjustment; + int _checkPixelPerfect; + + EventListener _onClick; + EventListener _onRightClick; + EventListener _onTouchBegin; + EventListener _onTouchMove; + EventListener _onTouchEnd; + EventListener _onRollOver; + EventListener _onRollOut; + EventListener _onMouseWheel; + EventListener _onAddedToStage; + EventListener _onRemovedFromStage; + EventListener _onKeyDown; + EventListener _onClickLink; + EventListener _onFocusIn; + EventListener _onFocusOut; + + protected internal int _paintingMode; //1-滤镜,2-blendMode,4-transformMatrix, 8-cacheAsBitmap + protected internal PaintingInfo _paintingInfo; + protected Rect _contentRect; + protected NGraphics.VertexMatrix _vertexMatrix; + protected internal Flags _flags; + protected internal float[] _batchingBounds; + + internal static uint _gInstanceCounter; + + internal static HideFlags hideFlags = HideFlags.None; + + public DisplayObject() + { + id = _gInstanceCounter++; + + _alpha = 1; + _visible = true; + _touchable = true; + _blendMode = BlendMode.Normal; + _focalLength = 2000; + _flags |= Flags.OutlineChanged; + if (UIConfig.makePixelPerfect) + _flags |= Flags.PixelPerfect; + } + + /// + /// + /// + public EventListener onClick + { + get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } + } + + /// + /// + /// + public EventListener onRightClick + { + get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } + } + + /// + /// + /// + public EventListener onTouchBegin + { + get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } + } + + /// + /// + /// + public EventListener onTouchMove + { + get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } + } + + /// + /// + /// + public EventListener onTouchEnd + { + get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } + } + + /// + /// + /// + public EventListener onRollOver + { + get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } + } + + /// + /// + /// + public EventListener onRollOut + { + get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } + } + + /// + /// + /// + public EventListener onMouseWheel + { + get { return _onMouseWheel ?? (_onMouseWheel = new EventListener(this, "onMouseWheel")); } + } + + /// + /// + /// + public EventListener onAddedToStage + { + get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } + } + + /// + /// + /// + public EventListener onRemovedFromStage + { + get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } + } + + /// + /// + /// + public EventListener onKeyDown + { + get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } + } + + /// + /// + /// + public EventListener onClickLink + { + get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } + } + + /// + /// + /// + public EventListener onFocusIn + { + get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } + } + + /// + /// + /// + public EventListener onFocusOut + { + get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } + + } + + protected void CreateGameObject(string gameObjectName) + { + gameObject = new GameObject(gameObjectName); + cachedTransform = gameObject.transform; + if (Application.isPlaying) + { + UnityEngine.Object.DontDestroyOnLoad(gameObject); + + DisplayObjectInfo info = gameObject.AddComponent(); + info.displayObject = this; + } + gameObject.hideFlags = DisplayObject.hideFlags; + gameObject.SetActive(false); + } + + protected void SetGameObject(GameObject gameObject) + { + this.gameObject = gameObject; + this.cachedTransform = gameObject.transform; + _rotation = cachedTransform.localEulerAngles; + + _flags |= Flags.UserGameObject; + } + + protected void DestroyGameObject() + { + if ((_flags & Flags.UserGameObject) == 0 && gameObject != null) + { + if (Application.isPlaying) + GameObject.Destroy(gameObject); + else + GameObject.DestroyImmediate(gameObject); + gameObject = null; + cachedTransform = null; + } + } + + /// + /// + /// + public float alpha + { + get { return _alpha; } + set { _alpha = value; } + } + + /// + /// + /// + public bool grayed + { + get { return _grayed; } + set { _grayed = value; } + } + + /// + /// + /// + public bool visible + { + get { return _visible; } + set + { + if (_visible != value) + { + _visible = value; + _flags |= Flags.OutlineChanged; + if (parent != null && _visible) + { + gameObject.SetActive(true); + InvalidateBatchingState(); + if (this is Container) + ((Container)this).InvalidateBatchingState(true); + } + else + gameObject.SetActive(false); + } + } + } + + /// + /// + /// + public float x + { + get { return cachedTransform.localPosition.x; } + set + { + SetPosition(value, -cachedTransform.localPosition.y, cachedTransform.localPosition.z); + } + } + + /// + /// + /// + public float y + { + get { return -cachedTransform.localPosition.y; } + set + { + SetPosition(cachedTransform.localPosition.x, value, cachedTransform.localPosition.z); + } + } + + /// + /// + /// + public float z + { + get { return cachedTransform.localPosition.z; } + set + { + SetPosition(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, value); + } + } + + /// + /// + /// + public Vector2 xy + { + get { return new Vector2(this.x, this.y); } + set { SetPosition(value.x, value.y, cachedTransform.localPosition.z); } + } + + /// + /// + /// + public Vector3 position + { + get { return new Vector3(this.x, this.y, this.z); } + set { SetPosition(value.x, value.y, value.z); } + } + + /// + /// + /// + /// + /// + public void SetXY(float xv, float yv) + { + SetPosition(xv, yv, cachedTransform.localPosition.z); + } + + /// + /// + /// + /// + /// + /// + public void SetPosition(float xv, float yv, float zv) + { + Vector3 v = new Vector3(); + v.x = xv; + v.y = -yv; + v.z = zv; + if (v != cachedTransform.localPosition) + { + cachedTransform.localPosition = v; + _flags |= Flags.OutlineChanged; + if ((_flags & Flags.PixelPerfect) != 0) + { + //总在下一帧再完成PixelPerfect,这样当物体在连续运动时,不会因为PixelPerfect而发生抖动。 + _checkPixelPerfect = Time.frameCount; + _pixelPerfectAdjustment = Vector3.zero; + } + } + } + + /// + /// If the object position is align by pixel + /// + public bool pixelPerfect + { + get { return (_flags & Flags.PixelPerfect) != 0; } + set + { + if (value) + _flags |= Flags.PixelPerfect; + else + _flags &= ~Flags.PixelPerfect; + } + } + + /// + /// + /// + public float width + { + get + { + EnsureSizeCorrect(); + return _contentRect.width; + } + set + { + if (!Mathf.Approximately(value, _contentRect.width)) + { + _contentRect.width = value; + _flags |= Flags.WidthChanged; + _flags &= ~Flags.HeightChanged; + OnSizeChanged(); + } + } + } + + /// + /// + /// + public float height + { + get + { + EnsureSizeCorrect(); + return _contentRect.height; + } + set + { + if (!Mathf.Approximately(value, _contentRect.height)) + { + _contentRect.height = value; + _flags &= ~Flags.WidthChanged; + _flags |= Flags.HeightChanged; + OnSizeChanged(); + } + } + } + + /// + /// + /// + public Vector2 size + { + get + { + EnsureSizeCorrect(); + return _contentRect.size; + } + set + { + SetSize(value.x, value.y); + } + } + + /// + /// + /// + /// + /// + public void SetSize(float wv, float hv) + { + if (!Mathf.Approximately(wv, _contentRect.width)) + _flags |= Flags.WidthChanged; + else + _flags &= ~Flags.WidthChanged; + if (!Mathf.Approximately(hv, _contentRect.height)) + _flags |= Flags.HeightChanged; + else + _flags &= ~Flags.HeightChanged; + + if ((_flags & Flags.WidthChanged) != 0 || (_flags & Flags.HeightChanged) != 0) + { + _contentRect.width = wv; + _contentRect.height = hv; + OnSizeChanged(); + } + } + + virtual public void EnsureSizeCorrect() + { + } + + virtual protected void OnSizeChanged() + { + ApplyPivot(); + + if (_paintingInfo != null) + _paintingInfo.flag = 1; + if (graphics != null) + graphics.contentRect = _contentRect; + _flags |= Flags.OutlineChanged; + } + + /// + /// + /// + public float scaleX + { + get { return cachedTransform.localScale.x; } + set + { + Vector3 v = cachedTransform.localScale; + v.x = v.z = ValidateScale(value); + cachedTransform.localScale = v; + _flags |= Flags.OutlineChanged; + ApplyPivot(); + } + } + + /// + /// + /// + public float scaleY + { + get { return cachedTransform.localScale.y; } + set + { + Vector3 v = cachedTransform.localScale; + v.y = ValidateScale(value); + cachedTransform.localScale = v; + _flags |= Flags.OutlineChanged; + ApplyPivot(); + } + } + + /// + /// + /// + /// + /// + public void SetScale(float xv, float yv) + { + Vector3 v = new Vector3(); + v.x = v.z = ValidateScale(xv); + v.y = ValidateScale(yv); + cachedTransform.localScale = v; + _flags |= Flags.OutlineChanged; + ApplyPivot(); + } + + /// + /// 在scale过小情况(极端情况=0),当使用Transform的坐标变换时,变换到世界,再从世界变换到本地,会由于精度问题造成结果错误。 + /// 这种错误会导致Batching错误,因为Batching会使用缓存的outline。 + /// 这里限制一下scale的最小值作为当前解决方案。 + /// 这个方案并不完美,因为限制了本地scale值并不能保证对世界scale不会过小。 + /// + /// + /// + private float ValidateScale(float value) + { + if (value >= 0 && value < 0.001f) + value = 0.001f; + else if (value < 0 && value > -0.001f) + value = -0.001f; + return value; + } + + /// + /// + /// + public Vector2 scale + { + get { return cachedTransform.localScale; } + set + { + SetScale(value.x, value.y); + } + } + + /// + /// + /// + public float rotation + { + get + { + //和Unity默认的旋转方向相反 + return -_rotation.z; + } + set + { + _rotation.z = -value; + _flags |= Flags.OutlineChanged; + if (_perspective) + UpdateTransformMatrix(); + else + { + cachedTransform.localEulerAngles = _rotation; + ApplyPivot(); + } + } + } + + /// + /// + /// + public float rotationX + { + get + { + return _rotation.x; + } + set + { + _rotation.x = value; + _flags |= Flags.OutlineChanged; + if (_perspective) + UpdateTransformMatrix(); + else + { + cachedTransform.localEulerAngles = _rotation; + ApplyPivot(); + } + } + } + + /// + /// + /// + public float rotationY + { + get + { + return _rotation.y; + } + set + { + _rotation.y = value; + _flags |= Flags.OutlineChanged; + if (_perspective) + UpdateTransformMatrix(); + else + { + cachedTransform.localEulerAngles = _rotation; + ApplyPivot(); + } + } + } + + /// + /// + /// + public Vector2 skew + { + get { return _skew; } + set + { + _skew = value; + _flags |= Flags.OutlineChanged; + + if (!Application.isPlaying) //编辑期间不支持!! + return; + + UpdateTransformMatrix(); + } + } + + /// + /// 当对象处于ScreenSpace,也就是使用正交相机渲染时,对象虽然可以绕X轴或者Y轴旋转,但没有透视效果。设置perspective,可以模拟出透视效果。 + /// + public bool perspective + { + get + { + return _perspective; + } + set + { + if (_perspective != value) + { + _perspective = value; + if (_perspective)//屏蔽Unity自身的旋转变换 + cachedTransform.localEulerAngles = Vector3.zero; + else + cachedTransform.localEulerAngles = _rotation; + + ApplyPivot(); + UpdateTransformMatrix(); + } + } + } + + /// + /// + /// + public int focalLength + { + get { return _focalLength; } + set + { + if (value <= 0) + value = 1; + + _focalLength = value; + if (_vertexMatrix != null) + UpdateTransformMatrix(); + } + } + + void UpdateTransformMatrix() + { + Matrix4x4 matrix = Matrix4x4.identity; + if (_skew.x != 0 || _skew.y != 0) + ToolSet.SkewMatrix(ref matrix, _skew.x, _skew.y); + if (_perspective) + matrix *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(_rotation), Vector3.one); + if (matrix.isIdentity) + _vertexMatrix = null; + else if (_vertexMatrix == null) + _vertexMatrix = new NGraphics.VertexMatrix(); + + //组件的transformMatrix是通过paintingMode实现的,因为全部通过矩阵变换的话,和unity自身的变换混杂在一起,无力理清。 + if (_vertexMatrix != null) + { + _vertexMatrix.matrix = matrix; + _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength); + + if (graphics == null) + EnterPaintingMode(4, null); + } + else + { + if (graphics == null) + LeavePaintingMode(4); + } + + if (_paintingMode > 0) + { + paintingGraphics.vertexMatrix = _vertexMatrix; + _paintingInfo.flag = 1; + } + else if (graphics != null) + graphics.vertexMatrix = _vertexMatrix; + + _flags |= Flags.OutlineChanged; + } + + /// + /// + /// + public Vector2 pivot + { + get { return _pivot; } + set + { + Vector3 deltaPivot = new Vector2((value.x - _pivot.x) * _contentRect.width, (_pivot.y - value.y) * _contentRect.height); + Vector3 oldOffset = _pivotOffset; + + _pivot = value; + UpdatePivotOffset(); + Vector3 v = cachedTransform.localPosition; + v += oldOffset - _pivotOffset + deltaPivot; + cachedTransform.localPosition = v; + _flags |= Flags.OutlineChanged; + } + } + + void UpdatePivotOffset() + { + float px = _pivot.x * _contentRect.width; + float py = _pivot.y * _contentRect.height; + + //注意这里不用处理skew,因为在顶点变换里有对pivot的处理 + Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, cachedTransform.localRotation, cachedTransform.localScale); + _pivotOffset = matrix.MultiplyPoint(new Vector3(px, -py, 0)); + + if (_vertexMatrix != null) + _vertexMatrix.cameraPos = new Vector3(_pivot.x * _contentRect.width, -_pivot.y * _contentRect.height, _focalLength); + } + + void ApplyPivot() + { + if (_pivot.x != 0 || _pivot.y != 0) + { + Vector3 oldOffset = _pivotOffset; + + UpdatePivotOffset(); + Vector3 v = cachedTransform.localPosition; + + if ((_flags & Flags.PixelPerfect) != 0) + { + v -= _pixelPerfectAdjustment; + _checkPixelPerfect = Time.frameCount; + _pixelPerfectAdjustment = Vector3.zero; + } + + v += oldOffset - _pivotOffset; + cachedTransform.localPosition = v; + _flags |= Flags.OutlineChanged; + } + } + + /// + /// This is the pivot position + /// + public Vector3 location + { + get + { + Vector3 pos = this.position; + pos.x += _pivotOffset.x; + pos.y -= _pivotOffset.y; + pos.z += _pivotOffset.z; + return pos; + } + + set + { + this.SetPosition(value.x - _pivotOffset.x, value.y + _pivotOffset.y, value.z - _pivotOffset.z); + } + } + + /// + /// + /// + virtual public Material material + { + get + { + if (graphics != null) + return graphics.material; + else + return null; + } + set + { + if (graphics != null) + graphics.material = value; + } + } + + /// + /// + /// + virtual public string shader + { + get + { + if (graphics != null) + return graphics.shader; + else + return null; + } + set + { + if (graphics != null) + graphics.shader = value; + } + } + + /// + /// + /// + virtual public int renderingOrder + { + get + { + return _renderingOrder; + } + set + { + if ((_flags & Flags.GameObjectDisposed) != 0) + { + DisplayDisposedWarning(); + return; + } + + _renderingOrder = value; + if (graphics != null) + graphics.sortingOrder = value; + if (_paintingMode > 0) + paintingGraphics.sortingOrder = value; + } + } + + /// + /// + /// + public int layer + { + get + { + if (_paintingMode > 0) + return paintingGraphics.gameObject.layer; + else + return gameObject.layer; + } + set + { + SetLayer(value, false); + } + } + + /// + /// If the object can be focused? + /// + public bool focusable + { + get { return (_flags & Flags.NotFocusable) == 0; } + set + { + if (value) + _flags &= ~Flags.NotFocusable; + else + _flags |= Flags.NotFocusable; + } + } + + /// + /// If the object can be navigated by TAB? + /// + public bool tabStop + { + get { return (_flags & Flags.TabStop) != 0; } + set + { + if (value) + _flags |= Flags.TabStop; + else + _flags &= ~Flags.TabStop; + } + } + + /// + /// If the object focused? + /// + public bool focused + { + get + { + return Stage.inst.focus == this || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.focus); + } + } + + internal bool _AcceptTab() + { + if (_touchable && _visible + && ((_flags & Flags.TabStop) != 0 || (_flags & Flags.TabStopChildren) != 0) + && (_flags & Flags.NotFocusable) == 0) + { + Stage.inst.SetFocus(this, true); + return true; + } + else + return false; + } + + /// + /// + /// + /// + public string cursor + { + get { return _cursor; } + set + { + _cursor = value; + if (Application.isPlaying + && (this == Stage.inst.touchTarget || (this is Container) && ((Container)this).IsAncestorOf(Stage.inst.touchTarget))) + { + Stage.inst._ChangeCursor(_cursor); + } + } + } + + /// + /// + /// + public bool isDisposed + { + get { return (_flags & Flags.Disposed) != 0 || gameObject == null; } + } + + internal void InternalSetParent(Container value) + { + if (parent != value) + { + if (value == null && (parent._flags & Flags.Disposed) != 0) + parent = value; + else + { + parent = value; + UpdateHierarchy(); + } + _flags |= Flags.OutlineChanged; + } + } + + /// + /// + /// + public Container topmost + { + get + { + DisplayObject currentObject = this; + while (currentObject.parent != null) + currentObject = currentObject.parent; + return currentObject as Container; + } + } + + /// + /// + /// + public Stage stage + { + get + { + return topmost as Stage; + } + } + + /// + /// + /// + public Container worldSpaceContainer + { + get + { + Container wsc = null; + DisplayObject currentObject = this; + while (currentObject.parent != null) + { + if ((currentObject is Container) && ((Container)currentObject).renderMode == RenderMode.WorldSpace) + { + wsc = (Container)currentObject; + break; + } + currentObject = currentObject.parent; + } + + return wsc; + } + } + + /// + /// + /// + public bool touchable + { + get { return _touchable; } + set + { + if (_touchable != value) + { + _touchable = value; + if (this is Container) + { + ColliderHitTest hitArea = ((Container)this).hitArea as ColliderHitTest; + if (hitArea != null) + hitArea.collider.enabled = value; + } + } + } + } + + /// + /// + /// + /// + public bool touchDisabled + { + get { return (_flags & Flags.TouchDisabled) != 0; } + } + + /// + /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 + /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 + /// + public void EnterPaintingMode() + { + EnterPaintingMode(16384, null, 1); + } + + /// + /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 + /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 + /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 + /// + /// 请求者id + /// 纹理四周的留空。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。 + public void EnterPaintingMode(int requestorId, Margin? extend) + { + EnterPaintingMode(requestorId, extend, 1); + } + + /// + /// 进入绘画模式,整个对象将画到一张RenderTexture上,然后这种贴图将代替原有的显示内容。 + /// 可以在onPaint回调里对这张纹理进行进一步操作,实现特殊效果。 + /// 可能有多个地方要求进入绘画模式,这里用requestorId加以区别,取值是1、2、4、8、16以此类推。1024内内部保留。用户自定义的id从1024开始。 + /// + /// 请求者id + /// 扩展纹理。如果特殊处理后的内容大于原内容,那么这里的设置可以使纹理扩大。 + /// 附加一个缩放系数 + public void EnterPaintingMode(int requestorId, Margin? extend, float scale) + { + bool first = _paintingMode == 0; + _paintingMode |= requestorId; + if (first) + { + if (_paintingInfo == null) + { + _paintingInfo = new PaintingInfo() + { + captureDelegate = Capture, + scale = 1 + }; + } + + if (paintingGraphics == null) + { + if (graphics == null) + paintingGraphics = new NGraphics(this.gameObject); + else + { + GameObject go = new GameObject(this.gameObject.name + " (Painter)"); + go.layer = this.gameObject.layer; + go.transform.SetParent(cachedTransform, false); + go.hideFlags = DisplayObject.hideFlags; + paintingGraphics = new NGraphics(go); + } + } + else + paintingGraphics.enabled = true; + paintingGraphics.vertexMatrix = null; + + if (this is Container) + { + ((Container)this).SetChildrenLayer(CaptureCamera.hiddenLayer); + ((Container)this).UpdateBatchingFlags(); + } + else + this.InvalidateBatchingState(); + + if (graphics != null) + this.gameObject.layer = CaptureCamera.hiddenLayer; + } + if (extend != null) + _paintingInfo.extend = (Margin)extend; + _paintingInfo.scale = scale; + _paintingInfo.flag = 1; + } + + /// + /// 离开绘画模式 + /// + /// + public void LeavePaintingMode(int requestorId) + { + if (_paintingMode == 0 || (_flags & Flags.Disposed) != 0) + return; + + _paintingMode ^= requestorId; + if (_paintingMode == 0) + { + paintingGraphics.enabled = false; + + if (this is Container) + { + ((Container)this).SetChildrenLayer(this.layer); + ((Container)this).UpdateBatchingFlags(); + } + else + this.InvalidateBatchingState(); + + if (graphics != null) + this.gameObject.layer = paintingGraphics.gameObject.layer; + } + } + + /// + /// + /// + public bool paintingMode + { + get { return _paintingMode > 0; } + } + + /// + /// 将整个显示对象(如果是容器,则容器包含的整个显示列表)静态化,所有内容被缓冲到一张纹理上。 + /// DC将保持为1。CPU消耗将降到最低。但对象的任何变化不会更新。 + /// 当cacheAsBitmap已经为true时,再次调用cacheAsBitmap=true将会刷新对象一次。 + /// + public bool cacheAsBitmap + { + get { return (_flags & Flags.CacheAsBitmap) != 0; } + set + { + if (value) + { + _flags |= Flags.CacheAsBitmap; + EnterPaintingMode(8, null, UIContentScaler.scaleFactor); + } + else + { + _flags &= ~Flags.CacheAsBitmap; + LeavePaintingMode(8); + } + } + } + + /// + /// + /// + /// + /// + /// + public Texture2D GetScreenShot(Margin? extend, float scale) + { + EnterPaintingMode(8, null, scale); + UpdatePainting(); + Capture(); + + Texture2D output; + if (paintingGraphics.texture == null) + output = new Texture2D(1, 1, TextureFormat.RGBA32, false, true); + else + { + RenderTexture rt = (RenderTexture)paintingGraphics.texture.nativeTexture; + output = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false, true); + RenderTexture old = RenderTexture.active; + RenderTexture.active = rt; + output.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); + output.Apply(); + RenderTexture.active = old; + } + + LeavePaintingMode(8); + + return output; + } + + /// + /// + /// + public IFilter filter + { + get + { + return _filter; + } + + set + { + if (!Application.isPlaying) //编辑期间不支持!! + return; + + if (value == _filter) + return; + + if (_filter != null) + _filter.Dispose(); + + if (value != null && value.target != null) + value.target.filter = null; + + _filter = value; + if (_filter != null) + _filter.target = this; + } + } + + /// + /// + /// + public BlendMode blendMode + { + get { return _blendMode; } + set + { + _blendMode = value; + InvalidateBatchingState(); + + if (graphics == null) + { + if (_blendMode != BlendMode.Normal) + { + if (!Application.isPlaying) //Not supported in edit mode! + return; + + EnterPaintingMode(2, null); + paintingGraphics.blendMode = _blendMode; + } + else + LeavePaintingMode(2); + } + else + graphics.blendMode = _blendMode; + } + } + + /// + /// + /// + /// + /// + virtual public Rect GetBounds(DisplayObject targetSpace) + { + EnsureSizeCorrect(); + + if (targetSpace == this) // optimization + { + return _contentRect; + } + else if (targetSpace == parent && _rotation.z == 0) + { + return new Rect(cachedTransform.localPosition.x, -cachedTransform.localPosition.y, + _contentRect.width * cachedTransform.localScale.x, _contentRect.height * cachedTransform.localScale.y); + } + else + return TransformRect(_contentRect, targetSpace); + } + + internal DisplayObject InternalHitTest() + { + if (_visible && (!HitTestContext.forTouch || _touchable)) + return HitTest(); + else + return null; + } + + internal DisplayObject InternalHitTestMask() + { + if (_visible) + return HitTest(); + else + return null; + } + + virtual protected DisplayObject HitTest() + { + Rect rect = GetBounds(this); + if (rect.width == 0 || rect.height == 0) + return null; + + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + if (rect.Contains(localPoint)) + return this; + else + return null; + } + + /// + /// 将舞台坐标转换为本地坐标 + /// + /// + /// + public Vector2 GlobalToLocal(Vector2 point) + { + Container wsc = this.worldSpaceContainer; + + if (wsc != null)//I am in a world space + { + Camera cam = wsc.GetRenderCamera(); + Vector3 worldPoint; + Vector3 direction; + Vector3 screenPoint = new Vector3(); + screenPoint.x = point.x; + screenPoint.y = Screen.height - point.y; + + if (wsc.hitArea is MeshColliderHitTest) + { + Ray ray = cam.ScreenPointToRay(screenPoint); + RaycastHit hit; + if (((MeshColliderHitTest)wsc.hitArea).collider.Raycast(ray, out hit, 100)) + { + point = new Vector2(hit.textureCoord.x * _contentRect.width, (1 - hit.textureCoord.y) * _contentRect.height); + worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); + direction = Vector3.back; + } + else //当射线没有击中模型时,无法确定本地坐标 + return new Vector2(float.NaN, float.NaN); + } + else + { + screenPoint.z = cam.WorldToScreenPoint(this.cachedTransform.position).z; + worldPoint = cam.ScreenToWorldPoint(screenPoint); + Ray ray = cam.ScreenPointToRay(screenPoint); + direction = Vector3.zero - ray.direction; + } + + return this.WorldToLocal(worldPoint, direction); + } + else //I am in stage space + { + Vector3 worldPoint = Stage.inst.cachedTransform.TransformPoint(point.x, -point.y, 0); + return this.WorldToLocal(worldPoint, Vector3.back); + } + } + + /// + /// 将本地坐标转换为舞台坐标 + /// + /// + /// + public Vector2 LocalToGlobal(Vector2 point) + { + Container wsc = this.worldSpaceContainer; + + Vector3 worldPoint = this.cachedTransform.TransformPoint(point.x, -point.y, 0); + if (wsc != null) + { + if (wsc.hitArea is MeshColliderHitTest) //Not supported for UIPainter, use TransfromPoint instead. + return new Vector2(float.NaN, float.NaN); + + Vector3 screePoint = wsc.GetRenderCamera().WorldToScreenPoint(worldPoint); + return new Vector2(screePoint.x, Stage.inst.size.y - screePoint.y); + } + else + { + point = Stage.inst.cachedTransform.InverseTransformPoint(worldPoint); + point.y = -point.y; + return point; + } + } + + /// + /// 转换世界坐标点到等效的本地xy平面的点。等效的意思是他们在屏幕方向看到的位置一样。 + /// 返回的点是在对象的本地坐标空间,且z=0 + /// + /// + /// + /// + public Vector3 WorldToLocal(Vector3 worldPoint, Vector3 direction) + { + Vector3 localPoint = this.cachedTransform.InverseTransformPoint(worldPoint); + if (localPoint.z != 0) //如果对象绕x轴或y轴旋转过,或者对象是在透视相机,那么z值可能不为0, + { + //将世界坐标的摄影机方向在本地空间上投射,求出与xy平面的交点 + direction = this.cachedTransform.InverseTransformDirection(direction); + float distOnLine = Vector3.Dot(Vector3.zero - localPoint, Vector3.forward) / Vector3.Dot(direction, Vector3.forward); + if (float.IsInfinity(distOnLine)) + return Vector2.zero; + + localPoint = localPoint + direction * distOnLine; + } + else if (_vertexMatrix != null) + { + Vector3 center = _vertexMatrix.cameraPos; + center.z = 0; + center -= _vertexMatrix.matrix.MultiplyPoint(center); + + Matrix4x4 mm = _vertexMatrix.matrix.inverse; + + localPoint -= center; + localPoint = mm.MultiplyPoint(localPoint); + + Vector3 camPos = mm.MultiplyPoint(_vertexMatrix.cameraPos); + Vector3 vec = localPoint - camPos; + float lambda = -camPos.z / vec.z; + localPoint = camPos + lambda * vec; + localPoint.z = 0; + } + localPoint.y = -localPoint.y; + + return localPoint; + } + + /// + /// + /// + /// + /// + public Vector3 LocalToWorld(Vector3 localPoint) + { + localPoint.y = -localPoint.y; + if (_vertexMatrix != null) + { + Vector3 center = _vertexMatrix.cameraPos; + center.z = 0; + center -= _vertexMatrix.matrix.MultiplyPoint(center); + + localPoint = _vertexMatrix.matrix.MultiplyPoint(localPoint); + localPoint += center; + + Vector3 camPos = _vertexMatrix.cameraPos; + Vector3 vec = localPoint - camPos; + float lambda = -camPos.z / vec.z; + localPoint = camPos + lambda * vec; + localPoint.z = 0; + } + + return this.cachedTransform.TransformPoint(localPoint); + } + + /// + /// + /// + /// + /// null if to world space + /// + public Vector2 TransformPoint(Vector2 point, DisplayObject targetSpace) + { + if (targetSpace == this) + return point; + + point = LocalToWorld(point); + if (targetSpace != null) + point = targetSpace.WorldToLocal(point, Vector3.back); + + return point; + } + + /// + /// + /// + /// + /// null if to world space + /// + public Rect TransformRect(Rect rect, DisplayObject targetSpace) + { + if (targetSpace == this) + return rect; + + if (targetSpace == parent && _rotation.z == 0) // optimization + { + Vector3 vec = cachedTransform.localScale; + return new Rect((this.x + rect.x) * vec.x, (this.y + rect.y) * vec.y, + rect.width * vec.x, rect.height * vec.y); + } + else + { + Vector4 vec4 = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue); + + TransformRectPoint(rect.xMin, rect.yMin, targetSpace, ref vec4); + TransformRectPoint(rect.xMax, rect.yMin, targetSpace, ref vec4); + TransformRectPoint(rect.xMin, rect.yMax, targetSpace, ref vec4); + TransformRectPoint(rect.xMax, rect.yMax, targetSpace, ref vec4); + + return Rect.MinMaxRect(vec4.x, vec4.y, vec4.z, vec4.w); + } + } + + protected void TransformRectPoint(float px, float py, DisplayObject targetSpace, ref Vector4 vec4) + { + Vector2 v = TransformPoint(new Vector2(px, py), targetSpace); + + if (vec4.x > v.x) vec4.x = v.x; + if (vec4.z < v.x) vec4.z = v.x; + if (vec4.y > v.y) vec4.y = v.y; + if (vec4.w < v.y) vec4.w = v.y; + } + + /// + /// + /// + public void RemoveFromParent() + { + if (parent != null) + parent.RemoveChild(this); + } + + /// + /// + /// + public void InvalidateBatchingState() + { + if (parent != null) + parent.InvalidateBatchingState(true); + } + + virtual public void Update(UpdateContext context) + { + if (_checkPixelPerfect != 0) + { + if (_rotation == Vector3.zero) + { + Vector3 v = cachedTransform.localPosition; + v.x = Mathf.Round(v.x); + v.y = Mathf.Round(v.y); + _pixelPerfectAdjustment = v - cachedTransform.localPosition; + if (_pixelPerfectAdjustment != Vector3.zero) + cachedTransform.localPosition = v; + } + _checkPixelPerfect = 0; + } + + if (graphics != null) + graphics.Update(context, context.alpha * _alpha, context.grayed | _grayed); + + if (_paintingMode != 0) + { + UpdatePainting(); + + //如果是容器,Capture要等到Container.Update的最后执行,因为容器中可能也有需要Capture的内容,要等他们完成后再进行容器的Capture。 + if (!(this is Container)) + { + if ((_flags & Flags.CacheAsBitmap) == 0 || _paintingInfo.flag != 2) + UpdateContext.OnEnd += _paintingInfo.captureDelegate; + } + + paintingGraphics.Update(context, 1, false); + } + + if (_filter != null) + _filter.Update(); + + Stats.ObjectCount++; + } + + void UpdatePainting() + { + NTexture paintingTexture = paintingGraphics.texture; + if (paintingTexture != null && paintingTexture.disposed) //Texture可能已被Stage.MonitorTexture销毁 + { + paintingTexture = null; + _paintingInfo.flag = 1; + } + + if (_paintingInfo.flag == 1) + { + _paintingInfo.flag = 0; + + //从优化考虑,决定使用绘画模式的容器都需要明确指定大小,而不是自动计算包围。这在UI使用上并没有问题,因为组件总是有固定大小的 + Margin extend = _paintingInfo.extend; + paintingGraphics.contentRect = new Rect(-extend.left, -extend.top, _contentRect.width + extend.left + extend.right, _contentRect.height + extend.top + extend.bottom); + int textureWidth = Mathf.RoundToInt(paintingGraphics.contentRect.width * _paintingInfo.scale); + int textureHeight = Mathf.RoundToInt(paintingGraphics.contentRect.height * _paintingInfo.scale); + if (paintingTexture == null || paintingTexture.width != textureWidth || paintingTexture.height != textureHeight) + { + if (paintingTexture != null) + paintingTexture.Dispose(); + if (textureWidth > 0 && textureHeight > 0) + { + paintingTexture = new NTexture(CaptureCamera.CreateRenderTexture(textureWidth, textureHeight, UIConfig.depthSupportForPaintingMode)); + Stage.inst.MonitorTexture(paintingTexture); + } + else + paintingTexture = null; + paintingGraphics.texture = paintingTexture; + } + } + + if (paintingTexture != null) + paintingTexture.lastActive = Time.time; + } + + void Capture() + { + if (paintingGraphics.texture == null) + return; + + Vector2 offset = new Vector2(_paintingInfo.extend.left, _paintingInfo.extend.top); + CaptureCamera.Capture(this, (RenderTexture)paintingGraphics.texture.nativeTexture, paintingGraphics.contentRect.height, offset); + + _paintingInfo.flag = 2; //2表示已完成一次Capture + if (onPaint != null) + onPaint(); + } + + /// + /// 为对象设置一个默认的父Transform。当对象不在显示列表里时,它的GameObject挂到哪里。 + /// + public Transform home + { + get { return _home; } + set + { + _home = value; + if (value != null && cachedTransform.parent == null) + cachedTransform.SetParent(value, false); + } + } + + void UpdateHierarchy() + { + if ((_flags & Flags.GameObjectDisposed) != 0) + return; + + if ((_flags & Flags.UserGameObject) != 0) + { + //we dont change transform parent of this object + if (gameObject != null) + { + if (parent != null && visible) + gameObject.SetActive(true); + else + gameObject.SetActive(false); + } + } + else if (parent != null) + { + cachedTransform.SetParent(parent.cachedTransform, false); + + if (_visible) + gameObject.SetActive(true); + + int layerValue = parent.gameObject.layer; + if (parent._paintingMode != 0) + layerValue = CaptureCamera.hiddenLayer; + SetLayer(layerValue, true); + } + else if ((_flags & Flags.Disposed) == 0 && this.gameObject != null && !StageEngine.beingQuit) + { + if (Application.isPlaying) + { + if (gOwner == null || gOwner.parent == null)//如果gOwner还有parent的话,说明只是暂时的隐藏 + { + cachedTransform.SetParent(_home, false); + if (_home == null) + UnityEngine.Object.DontDestroyOnLoad(this.gameObject); + } + } + + gameObject.SetActive(false); + } + } + + virtual protected bool SetLayer(int value, bool fromParent) + { + if ((_flags & Flags.LayerSet) != 0) //setted + { + if (fromParent) + return false; + } + else if ((_flags & Flags.LayerFromParent) != 0) //inherit from parent + { + if (!fromParent) + _flags |= Flags.LayerSet; + } + else + { + if (fromParent) + _flags |= Flags.LayerFromParent; + else + _flags |= Flags.LayerSet; + } + + if (_paintingMode > 0) + paintingGraphics.gameObject.layer = value; + else if (gameObject.layer != value) + { + gameObject.layer = value; + if ((this is Container)) + { + int cnt = ((Container)this).numChildren; + for (int i = 0; i < cnt; i++) + { + DisplayObject child = ((Container)this).GetChildAt(i); + child.SetLayer(value, true); + } + } + } + + return true; + } + + internal void _SetLayerDirect(int value) + { + if (_paintingMode > 0) + paintingGraphics.gameObject.layer = value; + else + gameObject.layer = value; + } + + virtual public void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + _flags |= Flags.Disposed; + RemoveFromParent(); + RemoveEventListeners(); + if (graphics != null) + graphics.Dispose(); + if (_filter != null) + _filter.Dispose(); + if (paintingGraphics != null) + { + if (paintingGraphics.texture != null) + paintingGraphics.texture.Dispose(); + + paintingGraphics.Dispose(); + if (paintingGraphics.gameObject != this.gameObject) + { + if (Application.isPlaying) + UnityEngine.Object.Destroy(paintingGraphics.gameObject); + else + UnityEngine.Object.DestroyImmediate(paintingGraphics.gameObject); + } + } + DestroyGameObject(); + } + + internal void DisplayDisposedWarning() + { + if ((_flags & Flags.DisposedWarning) == 0) + { + _flags |= Flags.DisposedWarning; + + StringBuilder sb = new StringBuilder(); + sb.Append("DisplayObject is still in use but GameObject was disposed. ("); + if (gOwner != null) + { + sb.Append("type=").Append(gOwner.GetType().Name).Append(", x=").Append(gOwner.x).Append(", y=").Append(gOwner.y).Append(", name=").Append(gOwner.name); + if (gOwner.packageItem != null) + sb.Append(", res=" + gOwner.packageItem.name); + } + else + { + sb.Append("id=").Append(id).Append(", type=").Append(this.GetType().Name).Append(", name=").Append(name); + } + sb.Append(")"); + Debug.LogError(sb.ToString()); + } + } + + protected internal class PaintingInfo + { + public Action captureDelegate; //缓存这个delegate,可以防止Capture状态下每帧104B的GC + public Margin extend; + public float scale; + public int flag; + } + + [Flags] + protected internal enum Flags + { + Disposed = 1, + UserGameObject = 2, + TouchDisabled = 4, + OutlineChanged = 8, + UpdatingSize = 0x10, + WidthChanged = 0x20, + HeightChanged = 0x40, + PixelPerfect = 0x80, + LayerSet = 0x100, + LayerFromParent = 0x200, + NotFocusable = 0x400, + TabStop = 0x800, + TabStopChildren = 0x1000, + FairyBatching = 0x2000, + BatchingRequested = 0x4000, + BatchingRoot = 0x8000, + SkipBatching = 0x10000, + CacheAsBitmap = 0x20000, + GameObjectDisposed = 0x40000, + DisposedWarning = 0x80000 + } + } + + /// + /// + /// + public class DisplayObjectInfo : MonoBehaviour + { + /// + /// + /// /// + [System.NonSerialized] + public DisplayObject displayObject; + + private void OnDestroy() + { + if (displayObject != null) + displayObject._flags |= DisplayObject.Flags.GameObjectDisposed; + } + } +} diff --git a/Assets/Scripts/Core/DisplayObject.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs.meta similarity index 100% rename from Assets/Scripts/Core/DisplayObject.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/DisplayObject.cs.meta diff --git a/Assets/Scripts/Core/GoWrapper.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs similarity index 97% rename from Assets/Scripts/Core/GoWrapper.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs index 077790d6..e80fc194 100644 --- a/Assets/Scripts/Core/GoWrapper.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs @@ -1,389 +1,389 @@ -using UnityEngine; -using System; -using System.Collections; -using System.Collections.Generic; - -namespace FairyGUI -{ - /// - /// GoWrapper is class for wrapping common gameobject into UI display list. - /// - public class GoWrapper : DisplayObject - { - [Obsolete("No need to manually set this flag anymore, coz it will be handled automatically.")] - public bool supportStencil; - - public event Action onUpdate; - public Action> customCloneMaterials; - public Action customRecoverMaterials; - - protected GameObject _wrapTarget; - protected List _renderers; - protected Dictionary _materialsBackup; - protected Canvas _canvas; - protected bool _cloneMaterial; - protected bool _shouldCloneMaterial; - - protected struct RendererInfo - { - public Renderer renderer; - public Material[] materials; - public int sortingOrder; - } - - protected static List helperTransformList = new List(); - - /// - /// - /// - public GoWrapper() - { - // _flags |= Flags.SkipBatching; - - _renderers = new List(); - _materialsBackup = new Dictionary(); - - CreateGameObject("GoWrapper"); - } - - /// - /// - /// - /// 包装对象。 - public GoWrapper(GameObject go) : this() - { - SetWrapTarget(go, false); - } - - /// - /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。 - /// 对象包含的所有材质不会被复制,如果材质已经是公用的,这可能影响到其他对象。如果希望自动复制,改为使用SetWrapTarget(target, true)设置。 - /// - public GameObject wrapTarget - { - get { return _wrapTarget; } - set { SetWrapTarget(value, false); } - } - - [Obsolete("setWrapTarget is deprecated. Use SetWrapTarget instead.")] - public void setWrapTarget(GameObject target, bool cloneMaterial) - { - SetWrapTarget(target, cloneMaterial); - } - - /// - /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。 - /// - /// - /// 如果true,则复制材质,否则直接使用sharedMaterial。 - public void SetWrapTarget(GameObject target, bool cloneMaterial) - { - // set Flags.SkipBatching only target not null - if (target == null) _flags &= ~Flags.SkipBatching; - else _flags |= Flags.SkipBatching; - InvalidateBatchingState(); - - RecoverMaterials(); - - _cloneMaterial = cloneMaterial; - if (_wrapTarget != null) - _wrapTarget.transform.SetParent(null, false); - - _canvas = null; - _wrapTarget = target; - _shouldCloneMaterial = false; - _renderers.Clear(); - - if (_wrapTarget != null) - { - _wrapTarget.transform.SetParent(this.cachedTransform, false); - _canvas = _wrapTarget.GetComponent(); - if (_canvas != null) - { - _canvas.renderMode = RenderMode.WorldSpace; - _canvas.worldCamera = StageCamera.main; - _canvas.overrideSorting = true; - - RectTransform rt = _canvas.GetComponent(); - rt.pivot = new Vector2(0, 1); - rt.position = new Vector3(0, 0, 0); - this.SetSize(rt.rect.width, rt.rect.height); - } - else - { - CacheRenderers(); - this.SetSize(0, 0); - } - - SetGoLayers(this.layer); - } - } - - /// - /// GoWrapper will cache all renderers of your gameobject on constructor. - /// If your gameobject change laterly, call this function to update the cache. - /// GoWrapper会在构造函数里查询你的gameobject所有的Renderer并保存。如果你的gameobject - /// 后续发生了改变,调用这个函数通知GoWrapper重新查询和保存。 - /// - public void CacheRenderers() - { - if (_canvas != null) - return; - - RecoverMaterials(); - _renderers.Clear(); - - Renderer[] items = _wrapTarget.GetComponentsInChildren(true); - - int cnt = items.Length; - _renderers.Capacity = cnt; - for (int i = 0; i < cnt; i++) - { - Renderer r = items[i]; - Material[] mats = r.sharedMaterials; - RendererInfo ri = new RendererInfo() - { - renderer = r, - materials = mats, - sortingOrder = r.sortingOrder - }; - _renderers.Add(ri); - - if (!_cloneMaterial && mats != null - && ((r is SkinnedMeshRenderer) || (r is MeshRenderer))) - { - int mcnt = mats.Length; - for (int j = 0; j < mcnt; j++) - { - Material mat = mats[j]; - if (mat != null && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects - mat.renderQueue = 3000; - } - } - } - _renderers.Sort((RendererInfo c1, RendererInfo c2) => - { - return c1.sortingOrder - c2.sortingOrder; - }); - - _shouldCloneMaterial = _cloneMaterial; - } - - void CloneMaterials() - { - _shouldCloneMaterial = false; - - int cnt = _renderers.Count; - for (int i = 0; i < cnt; i++) - { - RendererInfo ri = _renderers[i]; - Material[] mats = ri.materials; - if (mats == null) - continue; - - bool shouldSetRQ = (ri.renderer is SkinnedMeshRenderer) || (ri.renderer is MeshRenderer); - - int mcnt = mats.Length; - for (int j = 0; j < mcnt; j++) - { - Material mat = mats[j]; - if (mat == null) - continue; - - //确保相同的材质不会复制两次 - Material newMat; - if (!_materialsBackup.TryGetValue(mat, out newMat)) - { - newMat = new Material(mat); - _materialsBackup[mat] = newMat; - } - mats[j] = newMat; - - if (shouldSetRQ && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects - newMat.renderQueue = 3000; - } - - if (customCloneMaterials != null) - customCloneMaterials.Invoke(_materialsBackup); - else if (ri.renderer != null) - ri.renderer.sharedMaterials = mats; - } - } - - void RecoverMaterials() - { - if (_materialsBackup.Count == 0) - return; - - int cnt = _renderers.Count; - for (int i = 0; i < cnt; i++) - { - RendererInfo ri = _renderers[i]; - if (ri.renderer == null) - continue; - - Material[] mats = ri.materials; - if (mats == null) - continue; - - int mcnt = mats.Length; - for (int j = 0; j < mcnt; j++) - { - Material mat = mats[j]; - - foreach (KeyValuePair kv in _materialsBackup) - { - if (kv.Value == mat) - mats[j] = kv.Key; - } - } - - if (customRecoverMaterials != null) - customRecoverMaterials.Invoke(); - else - ri.renderer.sharedMaterials = mats; - } - - foreach (KeyValuePair kv in _materialsBackup) - Material.DestroyImmediate(kv.Value); - - _materialsBackup.Clear(); - } - - public override int renderingOrder - { - get - { - return base.renderingOrder; - } - set - { - base.renderingOrder = value; - - if (_canvas != null) - _canvas.sortingOrder = value; - else - { - int cnt = _renderers.Count; - for (int i = 0; i < cnt; i++) - { - RendererInfo ri = _renderers[i]; - if (ri.renderer != null) - { - if (i != 0 && _renderers[i].sortingOrder != _renderers[i - 1].sortingOrder) - value = UpdateContext.current.renderingOrder++; - ri.renderer.sortingOrder = value; - } - } - } - } - } - - override protected bool SetLayer(int value, bool fromParent) - { - if (base.SetLayer(value, fromParent)) - { - SetGoLayers(value); - return true; - } - else - return false; - } - - protected void SetGoLayers(int layer) - { - if (_wrapTarget == null) - return; - - _wrapTarget.GetComponentsInChildren(true, helperTransformList); - int cnt = helperTransformList.Count; - for (int i = 0; i < cnt; i++) - helperTransformList[i].gameObject.layer = layer; - helperTransformList.Clear(); - } - - override public void Update(UpdateContext context) - { - if (onUpdate != null) - onUpdate(context); - - if (_shouldCloneMaterial) - CloneMaterials(); - - ApplyClipping(context); - - base.Update(context); - } - - private List helperMaterials = new List(); - virtual protected void ApplyClipping(UpdateContext context) - { -#if UNITY_2018_2_OR_NEWER - int cnt = _renderers.Count; - for (int i = 0; i < cnt; i++) - { - Renderer renderer = _renderers[i].renderer; - if (renderer == null) - continue; - - if (customCloneMaterials != null) - helperMaterials.AddRange(_materialsBackup.Values); - else - renderer.GetSharedMaterials(helperMaterials); - - int cnt2 = helperMaterials.Count; - for (int j = 0; j < cnt2; j++) - { - Material mat = helperMaterials[j]; - if (mat != null) - context.ApplyClippingProperties(mat, false); - } - - helperMaterials.Clear(); - } -#else - int cnt = _renderers.Count; - for (int i = 0; i < cnt; i++) - { - Material[] mats = _renderers[i].materials; - if (mats == null) - continue; - - int cnt2 = mats.Length; - for (int j = 0; j < cnt2; j++) - { - Material mat = mats[j]; - if (mat != null) - context.ApplyClippingProperties(mat, false); - } - } -#endif - } - - public override void Dispose() - { - if ((_flags & Flags.Disposed) != 0) - return; - - if (_wrapTarget != null) - { - UnityEngine.Object.Destroy(_wrapTarget); - _wrapTarget = null; - - if (_materialsBackup.Count > 0) - { //如果有备份,说明材质是复制出来的,应该删除 - foreach (KeyValuePair kv in _materialsBackup) - Material.DestroyImmediate(kv.Value); - } - } - - _renderers = null; - _materialsBackup = null; - _canvas = null; - customCloneMaterials = null; - customRecoverMaterials = null; - - base.Dispose(); - } - } +using UnityEngine; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// GoWrapper is class for wrapping common gameobject into UI display list. + /// + public class GoWrapper : DisplayObject + { + [Obsolete("No need to manually set this flag anymore, coz it will be handled automatically.")] + public bool supportStencil; + + public event Action onUpdate; + public Action> customCloneMaterials; + public Action customRecoverMaterials; + + protected GameObject _wrapTarget; + protected List _renderers; + protected Dictionary _materialsBackup; + protected Canvas _canvas; + protected bool _cloneMaterial; + protected bool _shouldCloneMaterial; + + protected struct RendererInfo + { + public Renderer renderer; + public Material[] materials; + public int sortingOrder; + } + + protected static List helperTransformList = new List(); + + /// + /// + /// + public GoWrapper() + { + // _flags |= Flags.SkipBatching; + + _renderers = new List(); + _materialsBackup = new Dictionary(); + + CreateGameObject("GoWrapper"); + } + + /// + /// + /// + /// 包装对象。 + public GoWrapper(GameObject go) : this() + { + SetWrapTarget(go, false); + } + + /// + /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。 + /// 对象包含的所有材质不会被复制,如果材质已经是公用的,这可能影响到其他对象。如果希望自动复制,改为使用SetWrapTarget(target, true)设置。 + /// + public GameObject wrapTarget + { + get { return _wrapTarget; } + set { SetWrapTarget(value, false); } + } + + [Obsolete("setWrapTarget is deprecated. Use SetWrapTarget instead.")] + public void setWrapTarget(GameObject target, bool cloneMaterial) + { + SetWrapTarget(target, cloneMaterial); + } + + /// + /// 设置包装对象。注意如果原来有包装对象,设置新的包装对象后,原来的包装对象只会被删除引用,但不会被销毁。 + /// + /// + /// 如果true,则复制材质,否则直接使用sharedMaterial。 + public void SetWrapTarget(GameObject target, bool cloneMaterial) + { + // set Flags.SkipBatching only target not null + if (target == null) _flags &= ~Flags.SkipBatching; + else _flags |= Flags.SkipBatching; + InvalidateBatchingState(); + + RecoverMaterials(); + + _cloneMaterial = cloneMaterial; + if (_wrapTarget != null) + _wrapTarget.transform.SetParent(null, false); + + _canvas = null; + _wrapTarget = target; + _shouldCloneMaterial = false; + _renderers.Clear(); + + if (_wrapTarget != null) + { + _wrapTarget.transform.SetParent(this.cachedTransform, false); + _canvas = _wrapTarget.GetComponent(); + if (_canvas != null) + { + _canvas.renderMode = RenderMode.WorldSpace; + _canvas.worldCamera = StageCamera.main; + _canvas.overrideSorting = true; + + RectTransform rt = _canvas.GetComponent(); + rt.pivot = new Vector2(0, 1); + rt.position = new Vector3(0, 0, 0); + this.SetSize(rt.rect.width, rt.rect.height); + } + else + { + CacheRenderers(); + this.SetSize(0, 0); + } + + SetGoLayers(this.layer); + } + } + + /// + /// GoWrapper will cache all renderers of your gameobject on constructor. + /// If your gameobject change laterly, call this function to update the cache. + /// GoWrapper会在构造函数里查询你的gameobject所有的Renderer并保存。如果你的gameobject + /// 后续发生了改变,调用这个函数通知GoWrapper重新查询和保存。 + /// + public void CacheRenderers() + { + if (_canvas != null) + return; + + RecoverMaterials(); + _renderers.Clear(); + + Renderer[] items = _wrapTarget.GetComponentsInChildren(true); + + int cnt = items.Length; + _renderers.Capacity = cnt; + for (int i = 0; i < cnt; i++) + { + Renderer r = items[i]; + Material[] mats = r.sharedMaterials; + RendererInfo ri = new RendererInfo() + { + renderer = r, + materials = mats, + sortingOrder = r.sortingOrder + }; + _renderers.Add(ri); + + if (!_cloneMaterial && mats != null + && ((r is SkinnedMeshRenderer) || (r is MeshRenderer))) + { + int mcnt = mats.Length; + for (int j = 0; j < mcnt; j++) + { + Material mat = mats[j]; + if (mat != null && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects + mat.renderQueue = 3000; + } + } + } + _renderers.Sort((RendererInfo c1, RendererInfo c2) => + { + return c1.sortingOrder - c2.sortingOrder; + }); + + _shouldCloneMaterial = _cloneMaterial; + } + + void CloneMaterials() + { + _shouldCloneMaterial = false; + + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + RendererInfo ri = _renderers[i]; + Material[] mats = ri.materials; + if (mats == null) + continue; + + bool shouldSetRQ = (ri.renderer is SkinnedMeshRenderer) || (ri.renderer is MeshRenderer); + + int mcnt = mats.Length; + for (int j = 0; j < mcnt; j++) + { + Material mat = mats[j]; + if (mat == null) + continue; + + //确保相同的材质不会复制两次 + Material newMat; + if (!_materialsBackup.TryGetValue(mat, out newMat)) + { + newMat = new Material(mat); + _materialsBackup[mat] = newMat; + } + mats[j] = newMat; + + if (shouldSetRQ && mat.renderQueue != 3000) //Set the object rendering in Transparent Queue as UI objects + newMat.renderQueue = 3000; + } + + if (customCloneMaterials != null) + customCloneMaterials.Invoke(_materialsBackup); + else if (ri.renderer != null) + ri.renderer.sharedMaterials = mats; + } + } + + void RecoverMaterials() + { + if (_materialsBackup.Count == 0) + return; + + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + RendererInfo ri = _renderers[i]; + if (ri.renderer == null) + continue; + + Material[] mats = ri.materials; + if (mats == null) + continue; + + int mcnt = mats.Length; + for (int j = 0; j < mcnt; j++) + { + Material mat = mats[j]; + + foreach (KeyValuePair kv in _materialsBackup) + { + if (kv.Value == mat) + mats[j] = kv.Key; + } + } + + if (customRecoverMaterials != null) + customRecoverMaterials.Invoke(); + else + ri.renderer.sharedMaterials = mats; + } + + foreach (KeyValuePair kv in _materialsBackup) + Material.DestroyImmediate(kv.Value); + + _materialsBackup.Clear(); + } + + public override int renderingOrder + { + get + { + return base.renderingOrder; + } + set + { + base.renderingOrder = value; + + if (_canvas != null) + _canvas.sortingOrder = value; + else + { + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + RendererInfo ri = _renderers[i]; + if (ri.renderer != null) + { + if (i != 0 && _renderers[i].sortingOrder != _renderers[i - 1].sortingOrder) + value = UpdateContext.current.renderingOrder++; + ri.renderer.sortingOrder = value; + } + } + } + } + } + + override protected bool SetLayer(int value, bool fromParent) + { + if (base.SetLayer(value, fromParent)) + { + SetGoLayers(value); + return true; + } + else + return false; + } + + protected void SetGoLayers(int layer) + { + if (_wrapTarget == null) + return; + + _wrapTarget.GetComponentsInChildren(true, helperTransformList); + int cnt = helperTransformList.Count; + for (int i = 0; i < cnt; i++) + helperTransformList[i].gameObject.layer = layer; + helperTransformList.Clear(); + } + + override public void Update(UpdateContext context) + { + if (onUpdate != null) + onUpdate(context); + + if (_shouldCloneMaterial) + CloneMaterials(); + + ApplyClipping(context); + + base.Update(context); + } + + private List helperMaterials = new List(); + virtual protected void ApplyClipping(UpdateContext context) + { +#if UNITY_2018_2_OR_NEWER + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + Renderer renderer = _renderers[i].renderer; + if (renderer == null) + continue; + + if (customCloneMaterials != null) + helperMaterials.AddRange(_materialsBackup.Values); + else + renderer.GetSharedMaterials(helperMaterials); + + int cnt2 = helperMaterials.Count; + for (int j = 0; j < cnt2; j++) + { + Material mat = helperMaterials[j]; + if (mat != null) + context.ApplyClippingProperties(mat, false); + } + + helperMaterials.Clear(); + } +#else + int cnt = _renderers.Count; + for (int i = 0; i < cnt; i++) + { + Material[] mats = _renderers[i].materials; + if (mats == null) + continue; + + int cnt2 = mats.Length; + for (int j = 0; j < cnt2; j++) + { + Material mat = mats[j]; + if (mat != null) + context.ApplyClippingProperties(mat, false); + } + } +#endif + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + if (_wrapTarget != null) + { + UnityEngine.Object.Destroy(_wrapTarget); + _wrapTarget = null; + + if (_materialsBackup.Count > 0) + { //如果有备份,说明材质是复制出来的,应该删除 + foreach (KeyValuePair kv in _materialsBackup) + Material.DestroyImmediate(kv.Value); + } + } + + _renderers = null; + _materialsBackup = null; + _canvas = null; + customCloneMaterials = null; + customRecoverMaterials = null; + + base.Dispose(); + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Core/GoWrapper.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs.meta similarity index 100% rename from Assets/Scripts/Core/GoWrapper.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/GoWrapper.cs.meta diff --git a/Assets/Scripts/Core/HitTest.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest.meta similarity index 100% rename from Assets/Scripts/Core/HitTest.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest.meta diff --git a/Assets/Scripts/Core/HitTest/ColliderHitTest.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ColliderHitTest.cs similarity index 95% rename from Assets/Scripts/Core/HitTest/ColliderHitTest.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ColliderHitTest.cs index 56f32016..cc7f4914 100644 --- a/Assets/Scripts/Core/HitTest/ColliderHitTest.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ColliderHitTest.cs @@ -1,33 +1,33 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class ColliderHitTest : IHitTest - { - /// - /// - /// - public Collider collider; - - /// - /// - /// - /// - /// - /// - virtual public bool HitTest(Rect contentRect, Vector2 localPoint) - { - RaycastHit hit; - if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit)) - return false; - - if (hit.collider != collider) - return false; - - return true; - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class ColliderHitTest : IHitTest + { + /// + /// + /// + public Collider collider; + + /// + /// + /// + /// + /// + /// + virtual public bool HitTest(Rect contentRect, Vector2 localPoint) + { + RaycastHit hit; + if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit)) + return false; + + if (hit.collider != collider) + return false; + + return true; + } + } +} diff --git a/Assets/Scripts/Core/HitTest/ColliderHitTest.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ColliderHitTest.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/ColliderHitTest.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ColliderHitTest.cs.meta diff --git a/Assets/Scripts/Core/HitTest/HitTestContext.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/HitTestContext.cs similarity index 96% rename from Assets/Scripts/Core/HitTest/HitTestContext.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/HitTestContext.cs index 790c7c48..fd343caa 100644 --- a/Assets/Scripts/Core/HitTest/HitTestContext.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/HitTestContext.cs @@ -1,79 +1,79 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class HitTestContext - { - //set before hit test - public static Vector3 screenPoint; - public static Vector3 worldPoint; - public static Vector3 direction; - public static bool forTouch; - public static Camera camera; - - public static int layerMask = -1; - public static float maxDistance = Mathf.Infinity; - - public static Camera cachedMainCamera; - - static Dictionary raycastHits = new Dictionary(); - - /// - /// - /// - /// - /// - /// - public static bool GetRaycastHitFromCache(Camera camera, out RaycastHit hit) - { - RaycastHit? hitRef; - if (!raycastHits.TryGetValue(camera, out hitRef)) - { - Ray ray = camera.ScreenPointToRay(screenPoint); - if (Physics.Raycast(ray, out hit, maxDistance, layerMask)) - { - raycastHits[camera] = hit; - return true; - } - else - { - raycastHits[camera] = null; - return false; - } - } - else if (hitRef == null) - { - hit = new RaycastHit(); - return false; - } - else - { - hit = (RaycastHit)hitRef; - return true; - } - } - - /// - /// - /// - /// - /// - public static void CacheRaycastHit(Camera camera, ref RaycastHit hit) - { - raycastHits[camera] = hit; - } - - /// - /// - /// - public static void ClearRaycastHitCache() - { - raycastHits.Clear(); - } - } - -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class HitTestContext + { + //set before hit test + public static Vector3 screenPoint; + public static Vector3 worldPoint; + public static Vector3 direction; + public static bool forTouch; + public static Camera camera; + + public static int layerMask = -1; + public static float maxDistance = Mathf.Infinity; + + public static Camera cachedMainCamera; + + static Dictionary raycastHits = new Dictionary(); + + /// + /// + /// + /// + /// + /// + public static bool GetRaycastHitFromCache(Camera camera, out RaycastHit hit) + { + RaycastHit? hitRef; + if (!raycastHits.TryGetValue(camera, out hitRef)) + { + Ray ray = camera.ScreenPointToRay(screenPoint); + if (Physics.Raycast(ray, out hit, maxDistance, layerMask)) + { + raycastHits[camera] = hit; + return true; + } + else + { + raycastHits[camera] = null; + return false; + } + } + else if (hitRef == null) + { + hit = new RaycastHit(); + return false; + } + else + { + hit = (RaycastHit)hitRef; + return true; + } + } + + /// + /// + /// + /// + /// + public static void CacheRaycastHit(Camera camera, ref RaycastHit hit) + { + raycastHits[camera] = hit; + } + + /// + /// + /// + public static void ClearRaycastHitCache() + { + raycastHits.Clear(); + } + } + +} diff --git a/Assets/Scripts/Core/HitTest/HitTestContext.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/HitTestContext.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/HitTestContext.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/HitTestContext.cs.meta diff --git a/Assets/Scripts/Core/HitTest/IHitTest.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/IHitTest.cs similarity index 94% rename from Assets/Scripts/Core/HitTest/IHitTest.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/IHitTest.cs index 0487b07c..6b57e5f6 100644 --- a/Assets/Scripts/Core/HitTest/IHitTest.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/IHitTest.cs @@ -1,27 +1,27 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public enum HitTestMode - { - Default, - Raycast - } - - /// - /// - /// - public interface IHitTest - { - /// - /// - /// - /// - /// - /// - bool HitTest(Rect contentRect, Vector2 localPoint); - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public enum HitTestMode + { + Default, + Raycast + } + + /// + /// + /// + public interface IHitTest + { + /// + /// + /// + /// + /// + /// + bool HitTest(Rect contentRect, Vector2 localPoint); + } +} diff --git a/Assets/Scripts/Core/HitTest/IHitTest.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/IHitTest.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/IHitTest.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/IHitTest.cs.meta diff --git a/Assets/Scripts/Core/HitTest/MeshColliderHitTest.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/MeshColliderHitTest.cs similarity index 96% rename from Assets/Scripts/Core/HitTest/MeshColliderHitTest.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/MeshColliderHitTest.cs index 1f03c2a1..00d8644d 100644 --- a/Assets/Scripts/Core/HitTest/MeshColliderHitTest.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/MeshColliderHitTest.cs @@ -1,43 +1,43 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class MeshColliderHitTest : ColliderHitTest - { - public Vector2 lastHit; - - /// - /// - /// - /// - public MeshColliderHitTest(MeshCollider collider) - { - this.collider = collider; - } - - /// - /// - /// - /// - /// - /// - override public bool HitTest(Rect contentRect, Vector2 localPoint) - { - RaycastHit hit; - if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit)) - return false; - - if (hit.collider != collider) - return false; - - lastHit = new Vector2(hit.textureCoord.x * contentRect.width, (1 - hit.textureCoord.y) * contentRect.height); - HitTestContext.direction = Vector3.back; - HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(new Vector2(lastHit.x, Screen.height - lastHit.y)); - - return true; - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class MeshColliderHitTest : ColliderHitTest + { + public Vector2 lastHit; + + /// + /// + /// + /// + public MeshColliderHitTest(MeshCollider collider) + { + this.collider = collider; + } + + /// + /// + /// + /// + /// + /// + override public bool HitTest(Rect contentRect, Vector2 localPoint) + { + RaycastHit hit; + if (!HitTestContext.GetRaycastHitFromCache(HitTestContext.camera, out hit)) + return false; + + if (hit.collider != collider) + return false; + + lastHit = new Vector2(hit.textureCoord.x * contentRect.width, (1 - hit.textureCoord.y) * contentRect.height); + HitTestContext.direction = Vector3.back; + HitTestContext.worldPoint = StageCamera.main.ScreenToWorldPoint(new Vector2(lastHit.x, Screen.height - lastHit.y)); + + return true; + } + } +} diff --git a/Assets/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/MeshColliderHitTest.cs.meta diff --git a/Assets/Scripts/Core/HitTest/PixelHitTest.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/PixelHitTest.cs similarity index 96% rename from Assets/Scripts/Core/HitTest/PixelHitTest.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/PixelHitTest.cs index 34ca9468..f4a719ca 100644 --- a/Assets/Scripts/Core/HitTest/PixelHitTest.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/PixelHitTest.cs @@ -1,82 +1,82 @@ -using FairyGUI.Utils; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class PixelHitTestData - { - public int pixelWidth; - public float scale; - public byte[] pixels; - public int pixelsLength; - public int pixelsOffset; - - public void Load(ByteBuffer ba) - { - ba.ReadInt(); - pixelWidth = ba.ReadInt(); - scale = 1.0f / ba.ReadByte(); - pixels = ba.buffer; - pixelsLength = ba.ReadInt(); - pixelsOffset = ba.position; - ba.Skip(pixelsLength); - } - } - - /// - /// - /// - public class PixelHitTest : IHitTest - { - public int offsetX; - public int offsetY; - public float sourceWidth; - public float sourceHeight; - - PixelHitTestData _data; - - /// - /// - /// - /// - /// - /// - public PixelHitTest(PixelHitTestData data, int offsetX, int offsetY, float sourceWidth, float sourceHeight) - { - _data = data; - this.offsetX = offsetX; - this.offsetY = offsetY; - this.sourceWidth = sourceWidth; - this.sourceHeight = sourceHeight; - } - - /// - /// - /// - /// - /// - /// - public bool HitTest(Rect contentRect, Vector2 localPoint) - { - if (!contentRect.Contains(localPoint)) - return false; - - int x = Mathf.FloorToInt((localPoint.x * sourceWidth / contentRect.width - offsetX) * _data.scale); - int y = Mathf.FloorToInt((localPoint.y * sourceHeight / contentRect.height - offsetY) * _data.scale); - if (x < 0 || y < 0 || x >= _data.pixelWidth) - return false; - - int pos = y * _data.pixelWidth + x; - int pos2 = pos / 8; - int pos3 = pos % 8; - - if (pos2 >= 0 && pos2 < _data.pixelsLength) - return ((_data.pixels[_data.pixelsOffset + pos2] >> pos3) & 0x1) > 0; - else - return false; - } - } -} +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PixelHitTestData + { + public int pixelWidth; + public float scale; + public byte[] pixels; + public int pixelsLength; + public int pixelsOffset; + + public void Load(ByteBuffer ba) + { + ba.ReadInt(); + pixelWidth = ba.ReadInt(); + scale = 1.0f / ba.ReadByte(); + pixels = ba.buffer; + pixelsLength = ba.ReadInt(); + pixelsOffset = ba.position; + ba.Skip(pixelsLength); + } + } + + /// + /// + /// + public class PixelHitTest : IHitTest + { + public int offsetX; + public int offsetY; + public float sourceWidth; + public float sourceHeight; + + PixelHitTestData _data; + + /// + /// + /// + /// + /// + /// + public PixelHitTest(PixelHitTestData data, int offsetX, int offsetY, float sourceWidth, float sourceHeight) + { + _data = data; + this.offsetX = offsetX; + this.offsetY = offsetY; + this.sourceWidth = sourceWidth; + this.sourceHeight = sourceHeight; + } + + /// + /// + /// + /// + /// + /// + public bool HitTest(Rect contentRect, Vector2 localPoint) + { + if (!contentRect.Contains(localPoint)) + return false; + + int x = Mathf.FloorToInt((localPoint.x * sourceWidth / contentRect.width - offsetX) * _data.scale); + int y = Mathf.FloorToInt((localPoint.y * sourceHeight / contentRect.height - offsetY) * _data.scale); + if (x < 0 || y < 0 || x >= _data.pixelWidth) + return false; + + int pos = y * _data.pixelWidth + x; + int pos2 = pos / 8; + int pos3 = pos % 8; + + if (pos2 >= 0 && pos2 < _data.pixelsLength) + return ((_data.pixels[_data.pixelsOffset + pos2] >> pos3) & 0x1) > 0; + else + return false; + } + } +} diff --git a/Assets/Scripts/Core/HitTest/PixelHitTest.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/PixelHitTest.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/PixelHitTest.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/PixelHitTest.cs.meta diff --git a/Assets/Scripts/Core/HitTest/RectHitTest.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/RectHitTest.cs similarity index 95% rename from Assets/Scripts/Core/HitTest/RectHitTest.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/RectHitTest.cs index 539beba4..80e9f1f0 100644 --- a/Assets/Scripts/Core/HitTest/RectHitTest.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/RectHitTest.cs @@ -1,26 +1,26 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class RectHitTest : IHitTest - { - /// - /// - /// - public Rect rect; - - /// - /// - /// - /// - /// - /// - public bool HitTest(Rect contentRect, Vector2 localPoint) - { - return rect.Contains(localPoint); - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class RectHitTest : IHitTest + { + /// + /// + /// + public Rect rect; + + /// + /// + /// + /// + /// + /// + public bool HitTest(Rect contentRect, Vector2 localPoint) + { + return rect.Contains(localPoint); + } + } +} diff --git a/Assets/Scripts/Core/HitTest/RectHitTest.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/RectHitTest.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/RectHitTest.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/RectHitTest.cs.meta diff --git a/Assets/Scripts/Core/HitTest/ShapeHitTest.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ShapeHitTest.cs similarity index 100% rename from Assets/Scripts/Core/HitTest/ShapeHitTest.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ShapeHitTest.cs diff --git a/Assets/Scripts/Core/HitTest/ShapeHitTest.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ShapeHitTest.cs.meta similarity index 100% rename from Assets/Scripts/Core/HitTest/ShapeHitTest.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/HitTest/ShapeHitTest.cs.meta diff --git a/Assets/Scripts/Core/Image.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Image.cs similarity index 96% rename from Assets/Scripts/Core/Image.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Image.cs index 7672a8ab..3125aa45 100644 --- a/Assets/Scripts/Core/Image.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Image.cs @@ -1,436 +1,436 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class Image : DisplayObject, IMeshFactory - { - protected Rect? _scale9Grid; - protected bool _scaleByTile; - protected Vector2 _textureScale; - protected int _tileGridIndice; - protected FillMesh _fillMesh; - - public Image() : this(null) - { - } - - /// - /// - /// - /// - public Image(NTexture texture) - : base() - { - _flags |= Flags.TouchDisabled; - - CreateGameObject("Image"); - graphics = new NGraphics(gameObject); - graphics.shader = ShaderConfig.imageShader; - graphics.meshFactory = this; - - _textureScale = Vector2.one; - - if (texture != null) - UpdateTexture(texture); - } - - /// - /// - /// - public NTexture texture - { - get { return graphics.texture; } - set - { - UpdateTexture(value); - } - } - - public Vector2 textureScale - { - get { return _textureScale; } - set - { - _textureScale = value; - graphics.SetMeshDirty(); - } - } - - /// - /// - /// - public Color color - { - get - { - return graphics.color; - } - set - { - graphics.color = value; - graphics.Tint(); - } - } - - /// - /// - /// - public FillMethod fillMethod - { - get { return _fillMesh != null ? _fillMesh.method : FillMethod.None; } - set - { - if (_fillMesh == null) - { - if (value == FillMethod.None) - return; - - _fillMesh = new FillMesh(); - } - if (_fillMesh.method != value) - { - _fillMesh.method = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public int fillOrigin - { - get { return _fillMesh != null ? _fillMesh.origin : 0; } - set - { - if (_fillMesh == null) - _fillMesh = new FillMesh(); - - if (_fillMesh.origin != value) - { - _fillMesh.origin = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public bool fillClockwise - { - get { return _fillMesh != null ? _fillMesh.clockwise : true; } - set - { - if (_fillMesh == null) - _fillMesh = new FillMesh(); - - if (_fillMesh.clockwise != value) - { - _fillMesh.clockwise = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public float fillAmount - { - get { return _fillMesh != null ? _fillMesh.amount : 0; } - set - { - if (_fillMesh == null) - _fillMesh = new FillMesh(); - - if (_fillMesh.amount != value) - { - _fillMesh.amount = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public Rect? scale9Grid - { - get { return _scale9Grid; } - set - { - if (_scale9Grid != value) - { - _scale9Grid = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public bool scaleByTile - { - get { return _scaleByTile; } - set - { - if (_scaleByTile != value) - { - _scaleByTile = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public int tileGridIndice - { - get { return _tileGridIndice; } - set - { - if (_tileGridIndice != value) - { - _tileGridIndice = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public void SetNativeSize() - { - if (graphics.texture != null) - SetSize(graphics.texture.width, graphics.texture.height); - else - SetSize(0, 0); - } - - virtual protected void UpdateTexture(NTexture value) - { - if (value == graphics.texture) - return; - - graphics.texture = value; - _textureScale = Vector2.one; - if (_contentRect.width == 0) - SetNativeSize(); - InvalidateBatchingState(); - } - - public void OnPopulateMesh(VertexBuffer vb) - { - if (_fillMesh != null && _fillMesh.method != FillMethod.None) - { - _fillMesh.OnPopulateMesh(vb); - } - else if (_scaleByTile) - { - NTexture texture = graphics.texture; - if (texture.root == texture - && texture.nativeTexture != null - && texture.nativeTexture.wrapMode == TextureWrapMode.Repeat) - { - Rect uvRect = vb.uvRect; - uvRect.width *= vb.contentRect.width / texture.width * _textureScale.x; - uvRect.height *= vb.contentRect.height / texture.height * _textureScale.y; - - vb.AddQuad(vb.contentRect, vb.vertexColor, uvRect); - vb.AddTriangles(); - } - else - { - Rect contentRect = vb.contentRect; - contentRect.width *= _textureScale.x; - contentRect.height *= _textureScale.y; - - TileFill(vb, contentRect, vb.uvRect, texture.width, texture.height); - vb.AddTriangles(); - } - } - else if (_scale9Grid != null) - { - SliceFill(vb); - } - else - graphics.OnPopulateMesh(vb); - } - - static int[] TRIANGLES_9_GRID = new int[] { - 4,0,1,1,5,4, - 5,1,2,2,6,5, - 6,2,3,3,7,6, - 8,4,5,5,9,8, - 9,5,6,6,10,9, - 10,6,7,7,11,10, - 12,8,9,9,13,12, - 13,9,10,10,14,13, - 14,10,11, - 11,15,14 - }; - - static int[] gridTileIndice = new int[] { -1, 0, -1, 2, 4, 3, -1, 1, -1 }; - static float[] gridX = new float[4]; - static float[] gridY = new float[4]; - static float[] gridTexX = new float[4]; - static float[] gridTexY = new float[4]; - - public void SliceFill(VertexBuffer vb) - { - NTexture texture = graphics.texture; - Rect gridRect = (Rect)_scale9Grid; - Rect contentRect = vb.contentRect; - contentRect.width *= _textureScale.x; - contentRect.height *= _textureScale.y; - Rect uvRect = vb.uvRect; - - float sourceW = texture.width; - float sourceH = texture.height; - - if (graphics.flip != FlipType.None) - { - if (graphics.flip == FlipType.Horizontal || graphics.flip == FlipType.Both) - { - gridRect.x = sourceW - gridRect.xMax; - gridRect.xMax = gridRect.x + gridRect.width; - } - - if (graphics.flip == FlipType.Vertical || graphics.flip == FlipType.Both) - { - gridRect.y = sourceH - gridRect.yMax; - gridRect.yMax = gridRect.y + gridRect.height; - } - } - - float sx = uvRect.width / sourceW; - float sy = uvRect.height / sourceH; - float xMax = uvRect.xMax; - float yMax = uvRect.yMax; - float xMax2 = gridRect.xMax; - float yMax2 = gridRect.yMax; - - gridTexX[0] = uvRect.x; - gridTexX[1] = uvRect.x + gridRect.x * sx; - gridTexX[2] = uvRect.x + xMax2 * sx; - gridTexX[3] = xMax; - gridTexY[0] = yMax; - gridTexY[1] = yMax - gridRect.y * sy; - gridTexY[2] = yMax - yMax2 * sy; - gridTexY[3] = uvRect.y; - - if (contentRect.width >= (sourceW - gridRect.width)) - { - gridX[1] = gridRect.x; - gridX[2] = contentRect.width - (sourceW - xMax2); - gridX[3] = contentRect.width; - } - else - { - float tmp = gridRect.x / (sourceW - xMax2); - tmp = contentRect.width * tmp / (1 + tmp); - gridX[1] = tmp; - gridX[2] = tmp; - gridX[3] = contentRect.width; - } - - if (contentRect.height >= (sourceH - gridRect.height)) - { - gridY[1] = gridRect.y; - gridY[2] = contentRect.height - (sourceH - yMax2); - gridY[3] = contentRect.height; - } - else - { - float tmp = gridRect.y / (sourceH - yMax2); - tmp = contentRect.height * tmp / (1 + tmp); - gridY[1] = tmp; - gridY[2] = tmp; - gridY[3] = contentRect.height; - } - - if (_tileGridIndice == 0) - { - for (int cy = 0; cy < 4; cy++) - { - for (int cx = 0; cx < 4; cx++) - vb.AddVert(new Vector2(gridX[cx] / _textureScale.x, gridY[cy] / _textureScale.y), vb.vertexColor, new Vector2(gridTexX[cx], gridTexY[cy])); - } - vb.AddTriangles(TRIANGLES_9_GRID); - } - else - { - Rect drawRect; - Rect texRect; - int row, col; - int part; - - for (int pi = 0; pi < 9; pi++) - { - col = pi % 3; - row = pi / 3; - part = gridTileIndice[pi]; - drawRect = Rect.MinMaxRect(gridX[col], gridY[row], gridX[col + 1], gridY[row + 1]); - texRect = Rect.MinMaxRect(gridTexX[col], gridTexY[row + 1], gridTexX[col + 1], gridTexY[row]); - - if (part != -1 && (_tileGridIndice & (1 << part)) != 0) - { - TileFill(vb, drawRect, texRect, - (part == 0 || part == 1 || part == 4) ? gridRect.width : drawRect.width, - (part == 2 || part == 3 || part == 4) ? gridRect.height : drawRect.height); - } - else - { - drawRect.x /= _textureScale.x; - drawRect.y /= _textureScale.y; - drawRect.width /= _textureScale.x; - drawRect.height /= _textureScale.y; - - vb.AddQuad(drawRect, vb.vertexColor, texRect); - } - } - - vb.AddTriangles(); - } - } - - void TileFill(VertexBuffer vb, Rect contentRect, Rect uvRect, float sourceW, float sourceH) - { - int hc = Mathf.CeilToInt(contentRect.width / sourceW); - int vc = Mathf.CeilToInt(contentRect.height / sourceH); - float tailWidth = contentRect.width - (hc - 1) * sourceW; - float tailHeight = contentRect.height - (vc - 1) * sourceH; - float xMax = uvRect.xMax; - float yMax = uvRect.yMax; - - for (int i = 0; i < hc; i++) - { - for (int j = 0; j < vc; j++) - { - Rect uvTmp = uvRect; - if (i == hc - 1) - uvTmp.xMax = Mathf.Lerp(uvRect.x, xMax, tailWidth / sourceW); - if (j == vc - 1) - uvTmp.yMin = Mathf.Lerp(uvRect.y, yMax, 1 - tailHeight / sourceH); - - Rect drawRect = new Rect(contentRect.x + i * sourceW, contentRect.y + j * sourceH, - i == (hc - 1) ? tailWidth : sourceW, j == (vc - 1) ? tailHeight : sourceH); - - drawRect.x /= _textureScale.x; - drawRect.y /= _textureScale.y; - drawRect.width /= _textureScale.x; - drawRect.height /= _textureScale.y; - - vb.AddQuad(drawRect, vb.vertexColor, uvTmp); - } - } - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class Image : DisplayObject, IMeshFactory + { + protected Rect? _scale9Grid; + protected bool _scaleByTile; + protected Vector2 _textureScale; + protected int _tileGridIndice; + protected FillMesh _fillMesh; + + public Image() : this(null) + { + } + + /// + /// + /// + /// + public Image(NTexture texture) + : base() + { + _flags |= Flags.TouchDisabled; + + CreateGameObject("Image"); + graphics = new NGraphics(gameObject); + graphics.shader = ShaderConfig.imageShader; + graphics.meshFactory = this; + + _textureScale = Vector2.one; + + if (texture != null) + UpdateTexture(texture); + } + + /// + /// + /// + public NTexture texture + { + get { return graphics.texture; } + set + { + UpdateTexture(value); + } + } + + public Vector2 textureScale + { + get { return _textureScale; } + set + { + _textureScale = value; + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + public Color color + { + get + { + return graphics.color; + } + set + { + graphics.color = value; + graphics.Tint(); + } + } + + /// + /// + /// + public FillMethod fillMethod + { + get { return _fillMesh != null ? _fillMesh.method : FillMethod.None; } + set + { + if (_fillMesh == null) + { + if (value == FillMethod.None) + return; + + _fillMesh = new FillMesh(); + } + if (_fillMesh.method != value) + { + _fillMesh.method = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public int fillOrigin + { + get { return _fillMesh != null ? _fillMesh.origin : 0; } + set + { + if (_fillMesh == null) + _fillMesh = new FillMesh(); + + if (_fillMesh.origin != value) + { + _fillMesh.origin = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public bool fillClockwise + { + get { return _fillMesh != null ? _fillMesh.clockwise : true; } + set + { + if (_fillMesh == null) + _fillMesh = new FillMesh(); + + if (_fillMesh.clockwise != value) + { + _fillMesh.clockwise = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public float fillAmount + { + get { return _fillMesh != null ? _fillMesh.amount : 0; } + set + { + if (_fillMesh == null) + _fillMesh = new FillMesh(); + + if (_fillMesh.amount != value) + { + _fillMesh.amount = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public Rect? scale9Grid + { + get { return _scale9Grid; } + set + { + if (_scale9Grid != value) + { + _scale9Grid = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public bool scaleByTile + { + get { return _scaleByTile; } + set + { + if (_scaleByTile != value) + { + _scaleByTile = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public int tileGridIndice + { + get { return _tileGridIndice; } + set + { + if (_tileGridIndice != value) + { + _tileGridIndice = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public void SetNativeSize() + { + if (graphics.texture != null) + SetSize(graphics.texture.width, graphics.texture.height); + else + SetSize(0, 0); + } + + virtual protected void UpdateTexture(NTexture value) + { + if (value == graphics.texture) + return; + + graphics.texture = value; + _textureScale = Vector2.one; + if (_contentRect.width == 0) + SetNativeSize(); + InvalidateBatchingState(); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (_fillMesh != null && _fillMesh.method != FillMethod.None) + { + _fillMesh.OnPopulateMesh(vb); + } + else if (_scaleByTile) + { + NTexture texture = graphics.texture; + if (texture.root == texture + && texture.nativeTexture != null + && texture.nativeTexture.wrapMode == TextureWrapMode.Repeat) + { + Rect uvRect = vb.uvRect; + uvRect.width *= vb.contentRect.width / texture.width * _textureScale.x; + uvRect.height *= vb.contentRect.height / texture.height * _textureScale.y; + + vb.AddQuad(vb.contentRect, vb.vertexColor, uvRect); + vb.AddTriangles(); + } + else + { + Rect contentRect = vb.contentRect; + contentRect.width *= _textureScale.x; + contentRect.height *= _textureScale.y; + + TileFill(vb, contentRect, vb.uvRect, texture.width, texture.height); + vb.AddTriangles(); + } + } + else if (_scale9Grid != null) + { + SliceFill(vb); + } + else + graphics.OnPopulateMesh(vb); + } + + static int[] TRIANGLES_9_GRID = new int[] { + 4,0,1,1,5,4, + 5,1,2,2,6,5, + 6,2,3,3,7,6, + 8,4,5,5,9,8, + 9,5,6,6,10,9, + 10,6,7,7,11,10, + 12,8,9,9,13,12, + 13,9,10,10,14,13, + 14,10,11, + 11,15,14 + }; + + static int[] gridTileIndice = new int[] { -1, 0, -1, 2, 4, 3, -1, 1, -1 }; + static float[] gridX = new float[4]; + static float[] gridY = new float[4]; + static float[] gridTexX = new float[4]; + static float[] gridTexY = new float[4]; + + public void SliceFill(VertexBuffer vb) + { + NTexture texture = graphics.texture; + Rect gridRect = (Rect)_scale9Grid; + Rect contentRect = vb.contentRect; + contentRect.width *= _textureScale.x; + contentRect.height *= _textureScale.y; + Rect uvRect = vb.uvRect; + + float sourceW = texture.width; + float sourceH = texture.height; + + if (graphics.flip != FlipType.None) + { + if (graphics.flip == FlipType.Horizontal || graphics.flip == FlipType.Both) + { + gridRect.x = sourceW - gridRect.xMax; + gridRect.xMax = gridRect.x + gridRect.width; + } + + if (graphics.flip == FlipType.Vertical || graphics.flip == FlipType.Both) + { + gridRect.y = sourceH - gridRect.yMax; + gridRect.yMax = gridRect.y + gridRect.height; + } + } + + float sx = uvRect.width / sourceW; + float sy = uvRect.height / sourceH; + float xMax = uvRect.xMax; + float yMax = uvRect.yMax; + float xMax2 = gridRect.xMax; + float yMax2 = gridRect.yMax; + + gridTexX[0] = uvRect.x; + gridTexX[1] = uvRect.x + gridRect.x * sx; + gridTexX[2] = uvRect.x + xMax2 * sx; + gridTexX[3] = xMax; + gridTexY[0] = yMax; + gridTexY[1] = yMax - gridRect.y * sy; + gridTexY[2] = yMax - yMax2 * sy; + gridTexY[3] = uvRect.y; + + if (contentRect.width >= (sourceW - gridRect.width)) + { + gridX[1] = gridRect.x; + gridX[2] = contentRect.width - (sourceW - xMax2); + gridX[3] = contentRect.width; + } + else + { + float tmp = gridRect.x / (sourceW - xMax2); + tmp = contentRect.width * tmp / (1 + tmp); + gridX[1] = tmp; + gridX[2] = tmp; + gridX[3] = contentRect.width; + } + + if (contentRect.height >= (sourceH - gridRect.height)) + { + gridY[1] = gridRect.y; + gridY[2] = contentRect.height - (sourceH - yMax2); + gridY[3] = contentRect.height; + } + else + { + float tmp = gridRect.y / (sourceH - yMax2); + tmp = contentRect.height * tmp / (1 + tmp); + gridY[1] = tmp; + gridY[2] = tmp; + gridY[3] = contentRect.height; + } + + if (_tileGridIndice == 0) + { + for (int cy = 0; cy < 4; cy++) + { + for (int cx = 0; cx < 4; cx++) + vb.AddVert(new Vector2(gridX[cx] / _textureScale.x, gridY[cy] / _textureScale.y), vb.vertexColor, new Vector2(gridTexX[cx], gridTexY[cy])); + } + vb.AddTriangles(TRIANGLES_9_GRID); + } + else + { + Rect drawRect; + Rect texRect; + int row, col; + int part; + + for (int pi = 0; pi < 9; pi++) + { + col = pi % 3; + row = pi / 3; + part = gridTileIndice[pi]; + drawRect = Rect.MinMaxRect(gridX[col], gridY[row], gridX[col + 1], gridY[row + 1]); + texRect = Rect.MinMaxRect(gridTexX[col], gridTexY[row + 1], gridTexX[col + 1], gridTexY[row]); + + if (part != -1 && (_tileGridIndice & (1 << part)) != 0) + { + TileFill(vb, drawRect, texRect, + (part == 0 || part == 1 || part == 4) ? gridRect.width : drawRect.width, + (part == 2 || part == 3 || part == 4) ? gridRect.height : drawRect.height); + } + else + { + drawRect.x /= _textureScale.x; + drawRect.y /= _textureScale.y; + drawRect.width /= _textureScale.x; + drawRect.height /= _textureScale.y; + + vb.AddQuad(drawRect, vb.vertexColor, texRect); + } + } + + vb.AddTriangles(); + } + } + + void TileFill(VertexBuffer vb, Rect contentRect, Rect uvRect, float sourceW, float sourceH) + { + int hc = Mathf.CeilToInt(contentRect.width / sourceW); + int vc = Mathf.CeilToInt(contentRect.height / sourceH); + float tailWidth = contentRect.width - (hc - 1) * sourceW; + float tailHeight = contentRect.height - (vc - 1) * sourceH; + float xMax = uvRect.xMax; + float yMax = uvRect.yMax; + + for (int i = 0; i < hc; i++) + { + for (int j = 0; j < vc; j++) + { + Rect uvTmp = uvRect; + if (i == hc - 1) + uvTmp.xMax = Mathf.Lerp(uvRect.x, xMax, tailWidth / sourceW); + if (j == vc - 1) + uvTmp.yMin = Mathf.Lerp(uvRect.y, yMax, 1 - tailHeight / sourceH); + + Rect drawRect = new Rect(contentRect.x + i * sourceW, contentRect.y + j * sourceH, + i == (hc - 1) ? tailWidth : sourceW, j == (vc - 1) ? tailHeight : sourceH); + + drawRect.x /= _textureScale.x; + drawRect.y /= _textureScale.y; + drawRect.width /= _textureScale.x; + drawRect.height /= _textureScale.y; + + vb.AddQuad(drawRect, vb.vertexColor, uvTmp); + } + } + } + } +} diff --git a/Assets/Scripts/Core/Image.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Image.cs.meta similarity index 100% rename from Assets/Scripts/Core/Image.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Image.cs.meta diff --git a/Assets/Scripts/Core/MaterialManager.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MaterialManager.cs similarity index 96% rename from Assets/Scripts/Core/MaterialManager.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MaterialManager.cs index f2d8030b..a60d3cff 100644 --- a/Assets/Scripts/Core/MaterialManager.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MaterialManager.cs @@ -1,243 +1,243 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace FairyGUI -{ - [Flags] - public enum MaterialFlags - { - Clipped = 1, - SoftClipped = 2, - StencilTest = 4, - AlphaMask = 8, - Grayed = 16, - ColorFilter = 32 - } - - /// - /// Every texture-shader combination has a MaterialManager. - /// - public class MaterialManager - { - public event Action onCreateNewMaterial; - - public bool firstMaterialInFrame; - - NTexture _texture; - Shader _shader; - List _addKeywords; - Dictionary> _materials; - bool _combineTexture; - - class MaterialRef - { - public Material material; - public int frame; - public BlendMode blendMode; - public uint group; - } - - const int internalKeywordsCount = 6; - static string[] internalKeywords = new[] { "CLIPPED", "SOFT_CLIPPED", null, "ALPHA_MASK", "GRAYED", "COLOR_FILTER" }; - - /// - /// - /// - /// - /// - internal MaterialManager(NTexture texture, Shader shader) - { - _texture = texture; - _shader = shader; - _materials = new Dictionary>(); - _combineTexture = texture.alphaTexture != null; - } - - /// - /// - /// - /// - /// - public int GetFlagsByKeywords(IList keywords) - { - if (_addKeywords == null) - _addKeywords = new List(); - - int flags = 0; - for (int i = 0; i < keywords.Count; i++) - { - string s = keywords[i]; - if (string.IsNullOrEmpty(s)) - continue; - int j = _addKeywords.IndexOf(s); - if (j == -1) - { - j = _addKeywords.Count; - _addKeywords.Add(s); - } - flags += (1 << (j + internalKeywordsCount)); - } - - return flags; - } - - /// - /// - /// - /// - /// - /// - /// - public Material GetMaterial(int flags, BlendMode blendMode, uint group) - { - if (blendMode != BlendMode.Normal && BlendModeUtils.Factors[(int)blendMode].pma) - flags |= (int)MaterialFlags.ColorFilter; - - List items; - if (!_materials.TryGetValue(flags, out items)) - { - items = new List(); - _materials[flags] = items; - } - - int frameId = Time.frameCount; - int cnt = items.Count; - MaterialRef result = null; - for (int i = 0; i < cnt; i++) - { - MaterialRef item = items[i]; - - if (item.group == group && item.blendMode == blendMode) - { - if (item.frame != frameId) - { - firstMaterialInFrame = true; - item.frame = frameId; - } - else - firstMaterialInFrame = false; - - if (_combineTexture) - item.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); - - return item.material; - } - else if (result == null && (item.frame > frameId || item.frame < frameId - 1)) //collect materials if it is unused in last frame - result = item; - } - - if (result == null) - { - result = new MaterialRef() { material = CreateMaterial(flags) }; - items.Add(result); - } - else if (_combineTexture) - result.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); - - if (result.blendMode != blendMode) - { - BlendModeUtils.Apply(result.material, blendMode); - result.blendMode = blendMode; - } - - result.group = group; - result.frame = frameId; - firstMaterialInFrame = true; - return result.material; - } - - /// - /// - /// - /// - Material CreateMaterial(int flags) - { - Material mat = new Material(_shader); - - mat.mainTexture = _texture.nativeTexture; - if (_texture.alphaTexture != null) - { - mat.EnableKeyword("COMBINED"); - mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); - } - - for (int i = 0; i < internalKeywordsCount; i++) - { - if ((flags & (1 << i)) != 0) - { - string s = internalKeywords[i]; - if (s != null) - mat.EnableKeyword(s); - } - } - if (_addKeywords != null) - { - int keywordCnt = _addKeywords.Count; - for (int i = 0; i < keywordCnt; i++) - { - if ((flags & (1 << (i + internalKeywordsCount))) != 0) - mat.EnableKeyword(_addKeywords[i]); - } - } - - mat.hideFlags = DisplayObject.hideFlags; - if (onCreateNewMaterial != null) - onCreateNewMaterial(mat); - - return mat; - } - - /// - /// - /// - public void DestroyMaterials() - { - var iter = _materials.GetEnumerator(); - while (iter.MoveNext()) - { - List items = iter.Current.Value; - if (Application.isPlaying) - { - int cnt = items.Count; - for (int j = 0; j < cnt; j++) - Object.Destroy(items[j].material); - } - else - { - int cnt = items.Count; - for (int j = 0; j < cnt; j++) - Object.DestroyImmediate(items[j].material); - } - items.Clear(); - } - iter.Dispose(); - } - - /// - /// - /// - public void RefreshMaterials() - { - _combineTexture = _texture.alphaTexture != null; - var iter = _materials.GetEnumerator(); - while (iter.MoveNext()) - { - List items = iter.Current.Value; - int cnt = items.Count; - for (int j = 0; j < cnt; j++) - { - Material mat = items[j].material; - mat.mainTexture = _texture.nativeTexture; - if (_combineTexture) - { - mat.EnableKeyword("COMBINED"); - mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); - } - } - } - iter.Dispose(); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace FairyGUI +{ + [Flags] + public enum MaterialFlags + { + Clipped = 1, + SoftClipped = 2, + StencilTest = 4, + AlphaMask = 8, + Grayed = 16, + ColorFilter = 32 + } + + /// + /// Every texture-shader combination has a MaterialManager. + /// + public class MaterialManager + { + public event Action onCreateNewMaterial; + + public bool firstMaterialInFrame; + + NTexture _texture; + Shader _shader; + List _addKeywords; + Dictionary> _materials; + bool _combineTexture; + + class MaterialRef + { + public Material material; + public int frame; + public BlendMode blendMode; + public uint group; + } + + const int internalKeywordsCount = 6; + static string[] internalKeywords = new[] { "CLIPPED", "SOFT_CLIPPED", null, "ALPHA_MASK", "GRAYED", "COLOR_FILTER" }; + + /// + /// + /// + /// + /// + internal MaterialManager(NTexture texture, Shader shader) + { + _texture = texture; + _shader = shader; + _materials = new Dictionary>(); + _combineTexture = texture.alphaTexture != null; + } + + /// + /// + /// + /// + /// + public int GetFlagsByKeywords(IList keywords) + { + if (_addKeywords == null) + _addKeywords = new List(); + + int flags = 0; + for (int i = 0; i < keywords.Count; i++) + { + string s = keywords[i]; + if (string.IsNullOrEmpty(s)) + continue; + int j = _addKeywords.IndexOf(s); + if (j == -1) + { + j = _addKeywords.Count; + _addKeywords.Add(s); + } + flags += (1 << (j + internalKeywordsCount)); + } + + return flags; + } + + /// + /// + /// + /// + /// + /// + /// + public Material GetMaterial(int flags, BlendMode blendMode, uint group) + { + if (blendMode != BlendMode.Normal && BlendModeUtils.Factors[(int)blendMode].pma) + flags |= (int)MaterialFlags.ColorFilter; + + List items; + if (!_materials.TryGetValue(flags, out items)) + { + items = new List(); + _materials[flags] = items; + } + + int frameId = Time.frameCount; + int cnt = items.Count; + MaterialRef result = null; + for (int i = 0; i < cnt; i++) + { + MaterialRef item = items[i]; + + if (item.group == group && item.blendMode == blendMode) + { + if (item.frame != frameId) + { + firstMaterialInFrame = true; + item.frame = frameId; + } + else + firstMaterialInFrame = false; + + if (_combineTexture) + item.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + + return item.material; + } + else if (result == null && (item.frame > frameId || item.frame < frameId - 1)) //collect materials if it is unused in last frame + result = item; + } + + if (result == null) + { + result = new MaterialRef() { material = CreateMaterial(flags) }; + items.Add(result); + } + else if (_combineTexture) + result.material.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + + if (result.blendMode != blendMode) + { + BlendModeUtils.Apply(result.material, blendMode); + result.blendMode = blendMode; + } + + result.group = group; + result.frame = frameId; + firstMaterialInFrame = true; + return result.material; + } + + /// + /// + /// + /// + Material CreateMaterial(int flags) + { + Material mat = new Material(_shader); + + mat.mainTexture = _texture.nativeTexture; + if (_texture.alphaTexture != null) + { + mat.EnableKeyword("COMBINED"); + mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + } + + for (int i = 0; i < internalKeywordsCount; i++) + { + if ((flags & (1 << i)) != 0) + { + string s = internalKeywords[i]; + if (s != null) + mat.EnableKeyword(s); + } + } + if (_addKeywords != null) + { + int keywordCnt = _addKeywords.Count; + for (int i = 0; i < keywordCnt; i++) + { + if ((flags & (1 << (i + internalKeywordsCount))) != 0) + mat.EnableKeyword(_addKeywords[i]); + } + } + + mat.hideFlags = DisplayObject.hideFlags; + if (onCreateNewMaterial != null) + onCreateNewMaterial(mat); + + return mat; + } + + /// + /// + /// + public void DestroyMaterials() + { + var iter = _materials.GetEnumerator(); + while (iter.MoveNext()) + { + List items = iter.Current.Value; + if (Application.isPlaying) + { + int cnt = items.Count; + for (int j = 0; j < cnt; j++) + Object.Destroy(items[j].material); + } + else + { + int cnt = items.Count; + for (int j = 0; j < cnt; j++) + Object.DestroyImmediate(items[j].material); + } + items.Clear(); + } + iter.Dispose(); + } + + /// + /// + /// + public void RefreshMaterials() + { + _combineTexture = _texture.alphaTexture != null; + var iter = _materials.GetEnumerator(); + while (iter.MoveNext()) + { + List items = iter.Current.Value; + int cnt = items.Count; + for (int j = 0; j < cnt; j++) + { + Material mat = items[j].material; + mat.mainTexture = _texture.nativeTexture; + if (_combineTexture) + { + mat.EnableKeyword("COMBINED"); + mat.SetTexture(ShaderConfig.ID_AlphaTex, _texture.alphaTexture); + } + } + } + iter.Dispose(); + } + } +} diff --git a/Assets/Scripts/Core/MaterialManager.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MaterialManager.cs.meta similarity index 100% rename from Assets/Scripts/Core/MaterialManager.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MaterialManager.cs.meta diff --git a/Assets/Scripts/Core/Mesh.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh.meta similarity index 100% rename from Assets/Scripts/Core/Mesh.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh.meta diff --git a/Assets/Scripts/Core/Mesh/CompositeMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/CompositeMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/CompositeMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/CompositeMesh.cs index e205083c..3578ec46 100644 --- a/Assets/Scripts/Core/Mesh/CompositeMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/CompositeMesh.cs @@ -1,75 +1,75 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class CompositeMesh : IMeshFactory, IHitTest - { - /// - /// - /// - public readonly List elements; - - /// - /// If it is -1, means all elements are active, otherwise, only the specific element is active - /// - public int activeIndex; - - public CompositeMesh() - { - elements = new List(); - activeIndex = -1; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - int cnt = elements.Count; - if (cnt == 1) - elements[0].OnPopulateMesh(vb); - else - { - VertexBuffer vb2 = VertexBuffer.Begin(vb); - - for (int i = 0; i < cnt; i++) - { - if (activeIndex == -1 || i == activeIndex) - { - vb2.Clear(); - elements[i].OnPopulateMesh(vb2); - vb.Append(vb2); - } - } - - vb2.End(); - } - } - - public bool HitTest(Rect contentRect, Vector2 point) - { - if (!contentRect.Contains(point)) - return false; - - bool flag = false; - int cnt = elements.Count; - for (int i = 0; i < cnt; i++) - { - if (activeIndex == -1 || i == activeIndex) - { - IHitTest ht = elements[i] as IHitTest; - if (ht != null) - { - if (ht.HitTest(contentRect, point)) - return true; - } - else - flag = true; - } - } - - return flag; - } - } +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class CompositeMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public readonly List elements; + + /// + /// If it is -1, means all elements are active, otherwise, only the specific element is active + /// + public int activeIndex; + + public CompositeMesh() + { + elements = new List(); + activeIndex = -1; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + int cnt = elements.Count; + if (cnt == 1) + elements[0].OnPopulateMesh(vb); + else + { + VertexBuffer vb2 = VertexBuffer.Begin(vb); + + for (int i = 0; i < cnt; i++) + { + if (activeIndex == -1 || i == activeIndex) + { + vb2.Clear(); + elements[i].OnPopulateMesh(vb2); + vb.Append(vb2); + } + } + + vb2.End(); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (!contentRect.Contains(point)) + return false; + + bool flag = false; + int cnt = elements.Count; + for (int i = 0; i < cnt; i++) + { + if (activeIndex == -1 || i == activeIndex) + { + IHitTest ht = elements[i] as IHitTest; + if (ht != null) + { + if (ht.HitTest(contentRect, point)) + return true; + } + else + flag = true; + } + } + + return flag; + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Core/Mesh/CompositeMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/CompositeMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/CompositeMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/CompositeMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/EllipseMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/EllipseMesh.cs similarity index 97% rename from Assets/Scripts/Core/Mesh/EllipseMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/EllipseMesh.cs index b9df224e..2510321c 100644 --- a/Assets/Scripts/Core/Mesh/EllipseMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/EllipseMesh.cs @@ -1,200 +1,200 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class EllipseMesh : IMeshFactory, IHitTest - { - /// - /// - /// - public Rect? drawRect; - - /// - /// - /// - public float lineWidth; - - /// - /// - /// - public Color32 lineColor; - - /// - /// - /// - public Color32? centerColor; - - /// - /// - /// - public Color32? fillColor; - - /// - /// - /// - public float startDegree; - - /// - /// - /// - public float endDegreee; - - static int[] SECTOR_CENTER_TRIANGLES = new int[] { - 0, 4, 1, - 0, 3, 4, - 0, 2, 3, - 0, 8, 5, - 0, 7, 8, - 0, 6, 7, - 6, 5, 2, - 2, 1, 6 - }; - - public EllipseMesh() - { - lineColor = Color.black; - startDegree = 0; - endDegreee = 360; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; - Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; - - float sectionStart = Mathf.Clamp(startDegree, 0, 360); - float sectionEnd = Mathf.Clamp(endDegreee, 0, 360); - bool clipped = sectionStart > 0 || sectionEnd < 360; - sectionStart = sectionStart * Mathf.Deg2Rad; - sectionEnd = sectionEnd * Mathf.Deg2Rad; - Color32 centerColor2 = centerColor == null ? color : (Color32)centerColor; - - float radiusX = rect.width / 2; - float radiusY = rect.height / 2; - int sides = Mathf.CeilToInt(Mathf.PI * (radiusX + radiusY) / 4); - sides = Mathf.Clamp(sides, 40, 800); - float angleDelta = 2 * Mathf.PI / sides; - float angle = 0; - float lineAngle = 0; - - if (lineWidth > 0 && clipped) - { - lineAngle = lineWidth / Mathf.Max(radiusX, radiusY); - sectionStart += lineAngle; - sectionEnd -= lineAngle; - } - - int vpos = vb.currentVertCount; - float centerX = rect.x + radiusX; - float centerY = rect.y + radiusY; - vb.AddVert(new Vector3(centerX, centerY, 0), centerColor2); - for (int i = 0; i < sides; i++) - { - if (angle < sectionStart) - angle = sectionStart; - else if (angle > sectionEnd) - angle = sectionEnd; - Vector3 vec = new Vector3(Mathf.Cos(angle) * (radiusX - lineWidth) + centerX, Mathf.Sin(angle) * (radiusY - lineWidth) + centerY, 0); - vb.AddVert(vec, color); - if (lineWidth > 0) - { - vb.AddVert(vec, lineColor); - vb.AddVert(new Vector3(Mathf.Cos(angle) * radiusX + centerX, Mathf.Sin(angle) * radiusY + centerY, 0), lineColor); - } - angle += angleDelta; - } - - if (lineWidth > 0) - { - int cnt = sides * 3; - for (int i = 0; i < cnt; i += 3) - { - if (i != cnt - 3) - { - vb.AddTriangle(0, i + 1, i + 4); - vb.AddTriangle(i + 5, i + 2, i + 3); - vb.AddTriangle(i + 3, i + 6, i + 5); - } - else if (!clipped) - { - vb.AddTriangle(0, i + 1, 1); - vb.AddTriangle(2, i + 2, i + 3); - vb.AddTriangle(i + 3, 3, 2); - } - else - { - vb.AddTriangle(0, i + 1, i + 1); - vb.AddTriangle(i + 2, i + 2, i + 3); - vb.AddTriangle(i + 3, i + 3, i + 2); - } - } - } - else - { - for (int i = 0; i < sides; i++) - { - if (i != sides - 1) - vb.AddTriangle(0, i + 1, i + 2); - else if (!clipped) - vb.AddTriangle(0, i + 1, 1); - else - vb.AddTriangle(0, i + 1, i + 1); - } - } - - if (lineWidth > 0 && clipped) - { - //扇形内边缘的线条 - - vb.AddVert(new Vector3(radiusX, radiusY, 0), lineColor); - float centerRadius = lineWidth * 0.5f; - - sectionStart -= lineAngle; - angle = sectionStart + lineAngle * 0.5f + Mathf.PI * 0.5f; - vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); - angle -= Mathf.PI; - vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); - vb.AddVert(new Vector3(Mathf.Cos(sectionStart) * radiusX + radiusX, Mathf.Sin(sectionStart) * radiusY + radiusY, 0), lineColor); - vb.AddVert(vb.GetPosition(vpos + 3), lineColor); - - sectionEnd += lineAngle; - angle = sectionEnd - lineAngle * 0.5f + Mathf.PI * 0.5f; - vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); - angle -= Mathf.PI; - vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); - vb.AddVert(vb.GetPosition(vpos + sides * 3), lineColor); - vb.AddVert(new Vector3(Mathf.Cos(sectionEnd) * radiusX + radiusX, Mathf.Sin(sectionEnd) * radiusY + radiusY, 0), lineColor); - - vb.AddTriangles(SECTOR_CENTER_TRIANGLES, sides * 3 + 1); - } - } - - public bool HitTest(Rect contentRect, Vector2 point) - { - if (!contentRect.Contains(point)) - return false; - - float radiusX = contentRect.width * 0.5f; - float raduisY = contentRect.height * 0.5f; - float xx = point.x - radiusX - contentRect.x; - float yy = point.y - raduisY - contentRect.y; - if (Mathf.Pow(xx / radiusX, 2) + Mathf.Pow(yy / raduisY, 2) < 1) - { - if (startDegree != 0 || endDegreee != 360) - { - float deg = Mathf.Atan2(yy, xx) * Mathf.Rad2Deg; - if (deg < 0) - deg += 360; - return deg >= startDegree && deg <= endDegreee; - } - else - return true; - } - - return false; - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class EllipseMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? centerColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public float startDegree; + + /// + /// + /// + public float endDegreee; + + static int[] SECTOR_CENTER_TRIANGLES = new int[] { + 0, 4, 1, + 0, 3, 4, + 0, 2, 3, + 0, 8, 5, + 0, 7, 8, + 0, 6, 7, + 6, 5, 2, + 2, 1, 6 + }; + + public EllipseMesh() + { + lineColor = Color.black; + startDegree = 0; + endDegreee = 360; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + + float sectionStart = Mathf.Clamp(startDegree, 0, 360); + float sectionEnd = Mathf.Clamp(endDegreee, 0, 360); + bool clipped = sectionStart > 0 || sectionEnd < 360; + sectionStart = sectionStart * Mathf.Deg2Rad; + sectionEnd = sectionEnd * Mathf.Deg2Rad; + Color32 centerColor2 = centerColor == null ? color : (Color32)centerColor; + + float radiusX = rect.width / 2; + float radiusY = rect.height / 2; + int sides = Mathf.CeilToInt(Mathf.PI * (radiusX + radiusY) / 4); + sides = Mathf.Clamp(sides, 40, 800); + float angleDelta = 2 * Mathf.PI / sides; + float angle = 0; + float lineAngle = 0; + + if (lineWidth > 0 && clipped) + { + lineAngle = lineWidth / Mathf.Max(radiusX, radiusY); + sectionStart += lineAngle; + sectionEnd -= lineAngle; + } + + int vpos = vb.currentVertCount; + float centerX = rect.x + radiusX; + float centerY = rect.y + radiusY; + vb.AddVert(new Vector3(centerX, centerY, 0), centerColor2); + for (int i = 0; i < sides; i++) + { + if (angle < sectionStart) + angle = sectionStart; + else if (angle > sectionEnd) + angle = sectionEnd; + Vector3 vec = new Vector3(Mathf.Cos(angle) * (radiusX - lineWidth) + centerX, Mathf.Sin(angle) * (radiusY - lineWidth) + centerY, 0); + vb.AddVert(vec, color); + if (lineWidth > 0) + { + vb.AddVert(vec, lineColor); + vb.AddVert(new Vector3(Mathf.Cos(angle) * radiusX + centerX, Mathf.Sin(angle) * radiusY + centerY, 0), lineColor); + } + angle += angleDelta; + } + + if (lineWidth > 0) + { + int cnt = sides * 3; + for (int i = 0; i < cnt; i += 3) + { + if (i != cnt - 3) + { + vb.AddTriangle(0, i + 1, i + 4); + vb.AddTriangle(i + 5, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 6, i + 5); + } + else if (!clipped) + { + vb.AddTriangle(0, i + 1, 1); + vb.AddTriangle(2, i + 2, i + 3); + vb.AddTriangle(i + 3, 3, 2); + } + else + { + vb.AddTriangle(0, i + 1, i + 1); + vb.AddTriangle(i + 2, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 3, i + 2); + } + } + } + else + { + for (int i = 0; i < sides; i++) + { + if (i != sides - 1) + vb.AddTriangle(0, i + 1, i + 2); + else if (!clipped) + vb.AddTriangle(0, i + 1, 1); + else + vb.AddTriangle(0, i + 1, i + 1); + } + } + + if (lineWidth > 0 && clipped) + { + //扇形内边缘的线条 + + vb.AddVert(new Vector3(radiusX, radiusY, 0), lineColor); + float centerRadius = lineWidth * 0.5f; + + sectionStart -= lineAngle; + angle = sectionStart + lineAngle * 0.5f + Mathf.PI * 0.5f; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + angle -= Mathf.PI; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + vb.AddVert(new Vector3(Mathf.Cos(sectionStart) * radiusX + radiusX, Mathf.Sin(sectionStart) * radiusY + radiusY, 0), lineColor); + vb.AddVert(vb.GetPosition(vpos + 3), lineColor); + + sectionEnd += lineAngle; + angle = sectionEnd - lineAngle * 0.5f + Mathf.PI * 0.5f; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + angle -= Mathf.PI; + vb.AddVert(new Vector3(Mathf.Cos(angle) * centerRadius + radiusX, Mathf.Sin(angle) * centerRadius + radiusY, 0), lineColor); + vb.AddVert(vb.GetPosition(vpos + sides * 3), lineColor); + vb.AddVert(new Vector3(Mathf.Cos(sectionEnd) * radiusX + radiusX, Mathf.Sin(sectionEnd) * radiusY + radiusY, 0), lineColor); + + vb.AddTriangles(SECTOR_CENTER_TRIANGLES, sides * 3 + 1); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (!contentRect.Contains(point)) + return false; + + float radiusX = contentRect.width * 0.5f; + float raduisY = contentRect.height * 0.5f; + float xx = point.x - radiusX - contentRect.x; + float yy = point.y - raduisY - contentRect.y; + if (Mathf.Pow(xx / radiusX, 2) + Mathf.Pow(yy / raduisY, 2) < 1) + { + if (startDegree != 0 || endDegreee != 360) + { + float deg = Mathf.Atan2(yy, xx) * Mathf.Rad2Deg; + if (deg < 0) + deg += 360; + return deg >= startDegree && deg <= endDegreee; + } + else + return true; + } + + return false; + } + } +} diff --git a/Assets/Scripts/Core/Mesh/EllipseMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/EllipseMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/EllipseMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/EllipseMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/FillMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/FillMesh.cs similarity index 97% rename from Assets/Scripts/Core/Mesh/FillMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/FillMesh.cs index 61ca4e51..85c89608 100644 --- a/Assets/Scripts/Core/Mesh/FillMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/FillMesh.cs @@ -1,400 +1,400 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class FillMesh : IMeshFactory - { - /// - /// - /// - public FillMethod method; - - /// - /// - /// - public int origin; - - /// - /// - /// - public float amount; - - /// - /// - /// - public bool clockwise; - - public FillMesh() - { - clockwise = true; - amount = 1; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - float amount = Mathf.Clamp01(this.amount); - switch (method) - { - case FillMethod.Horizontal: - FillHorizontal(vb, vb.contentRect, origin, amount); - break; - - case FillMethod.Vertical: - FillVertical(vb, vb.contentRect, origin, amount); - break; - - case FillMethod.Radial90: - FillRadial90(vb, vb.contentRect, (Origin90)origin, amount, clockwise); - break; - - case FillMethod.Radial180: - FillRadial180(vb, vb.contentRect, (Origin180)origin, amount, clockwise); - break; - - case FillMethod.Radial360: - FillRadial360(vb, vb.contentRect, (Origin360)origin, amount, clockwise); - break; - } - } - - static void FillHorizontal(VertexBuffer vb, Rect vertRect, int origin, float amount) - { - float a = vertRect.width * amount; - if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom) - vertRect.x += (vertRect.width - a); - vertRect.width = a; - - vb.AddQuad(vertRect); - vb.AddTriangles(); - } - - static void FillVertical(VertexBuffer vb, Rect vertRect, int origin, float amount) - { - float a = vertRect.height * amount; - if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom) - vertRect.y += (vertRect.height - a); - vertRect.height = a; - - vb.AddQuad(vertRect); - vb.AddTriangles(); - } - - //4 vertex - static void FillRadial90(VertexBuffer vb, Rect vertRect, Origin90 origin, float amount, bool clockwise) - { - bool flipX = origin == Origin90.TopRight || origin == Origin90.BottomRight; - bool flipY = origin == Origin90.BottomLeft || origin == Origin90.BottomRight; - if (flipX != flipY) - clockwise = !clockwise; - - float ratio = clockwise ? amount : (1 - amount); - float tan = Mathf.Tan(Mathf.PI * 0.5f * ratio); - bool thresold = false; - if (ratio != 1) - thresold = (vertRect.height / vertRect.width - tan) > 0; - if (!clockwise) - thresold = !thresold; - float x = vertRect.x + (ratio == 0 ? float.MaxValue : (vertRect.height / tan)); - float y = vertRect.y + (ratio == 1 ? float.MaxValue : (vertRect.width * tan)); - float x2 = x; - float y2 = y; - if (flipX) - x2 = vertRect.width - x; - if (flipY) - y2 = vertRect.height - y; - float xMin = flipX ? (vertRect.width - vertRect.x) : vertRect.xMin; - float yMin = flipY ? (vertRect.height - vertRect.y) : vertRect.yMin; - float xMax = flipX ? -vertRect.xMin : vertRect.xMax; - float yMax = flipY ? -vertRect.yMin : vertRect.yMax; - - vb.AddVert(new Vector3(xMin, yMin, 0)); - - if (clockwise) - vb.AddVert(new Vector3(xMax, yMin, 0)); - - if (y > vertRect.yMax) - { - if (thresold) - vb.AddVert(new Vector3(x2, yMax, 0)); - else - vb.AddVert(new Vector3(xMax, yMax, 0)); - } - else - vb.AddVert(new Vector3(xMax, y2, 0)); - - if (x > vertRect.xMax) - { - if (thresold) - vb.AddVert(new Vector3(xMax, y2, 0)); - else - vb.AddVert(new Vector3(xMax, yMax, 0)); - } - else - vb.AddVert(new Vector3(x2, yMax, 0)); - - if (!clockwise) - vb.AddVert(new Vector3(xMin, yMax, 0)); - - if (flipX == flipY) - { - vb.AddTriangle(0, 1, 2); - vb.AddTriangle(0, 2, 3); - } - else - { - vb.AddTriangle(2, 1, 0); - vb.AddTriangle(3, 2, 0); - } - } - - //8 vertex - static void FillRadial180(VertexBuffer vb, Rect vertRect, Origin180 origin, float amount, bool clockwise) - { - switch (origin) - { - case Origin180.Top: - if (amount <= 0.5f) - { - vertRect.width /= 2; - if (clockwise) - vertRect.x += vertRect.width; - - FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.TopRight, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-4); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.width /= 2; - if (!clockwise) - vertRect.x += vertRect.width; - - FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.TopLeft, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.x += vertRect.width; - else - vertRect.x -= vertRect.width; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - - case Origin180.Bottom: - if (amount <= 0.5f) - { - vertRect.width /= 2; - if (!clockwise) - vertRect.x += vertRect.width; - - FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.BottomLeft, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-4); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.width /= 2; - if (clockwise) - vertRect.x += vertRect.width; - - FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.BottomRight, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.x -= vertRect.width; - else - vertRect.x += vertRect.width; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - - case Origin180.Left: - if (amount <= 0.5f) - { - vertRect.height /= 2; - if (!clockwise) - vertRect.y += vertRect.height; - - FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.TopLeft, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-4); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.height /= 2; - if (clockwise) - vertRect.y += vertRect.height; - - FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.BottomLeft, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.y -= vertRect.height; - else - vertRect.y += vertRect.height; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - - case Origin180.Right: - if (amount <= 0.5f) - { - vertRect.height /= 2; - if (clockwise) - vertRect.y += vertRect.height; - - FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.BottomRight, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-4); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.height /= 2; - if (!clockwise) - vertRect.y += vertRect.height; - - FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.TopRight, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.y += vertRect.height; - else - vertRect.y -= vertRect.height; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - } - } - - //12 vertex - static void FillRadial360(VertexBuffer vb, Rect vertRect, Origin360 origin, float amount, bool clockwise) - { - switch (origin) - { - case Origin360.Top: - if (amount < 0.5f) - { - vertRect.width /= 2; - if (clockwise) - vertRect.x += vertRect.width; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-8); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.width /= 2; - if (!clockwise) - vertRect.x += vertRect.width; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.x += vertRect.width; - else - vertRect.x -= vertRect.width; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - - break; - - case Origin360.Bottom: - if (amount < 0.5f) - { - vertRect.width /= 2; - if (!clockwise) - vertRect.x += vertRect.width; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-8); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.width /= 2; - if (clockwise) - vertRect.x += vertRect.width; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.x -= vertRect.width; - else - vertRect.x += vertRect.width; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - - case Origin360.Left: - if (amount < 0.5f) - { - vertRect.height /= 2; - if (!clockwise) - vertRect.y += vertRect.height; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-8); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.height /= 2; - if (clockwise) - vertRect.y += vertRect.height; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.y -= vertRect.height; - else - vertRect.y += vertRect.height; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - - case Origin360.Right: - if (amount < 0.5f) - { - vertRect.height /= 2; - if (clockwise) - vertRect.y += vertRect.height; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, amount / 0.5f, clockwise); - Vector3 vec = vb.GetPosition(-8); - vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); - vb.AddTriangles(-4); - } - else - { - vertRect.height /= 2; - if (!clockwise) - vertRect.y += vertRect.height; - - FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, (amount - 0.5f) / 0.5f, clockwise); - - if (clockwise) - vertRect.y += vertRect.height; - else - vertRect.y -= vertRect.height; - vb.AddQuad(vertRect); - vb.AddTriangles(-4); - } - break; - } - } - } +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class FillMesh : IMeshFactory + { + /// + /// + /// + public FillMethod method; + + /// + /// + /// + public int origin; + + /// + /// + /// + public float amount; + + /// + /// + /// + public bool clockwise; + + public FillMesh() + { + clockwise = true; + amount = 1; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + float amount = Mathf.Clamp01(this.amount); + switch (method) + { + case FillMethod.Horizontal: + FillHorizontal(vb, vb.contentRect, origin, amount); + break; + + case FillMethod.Vertical: + FillVertical(vb, vb.contentRect, origin, amount); + break; + + case FillMethod.Radial90: + FillRadial90(vb, vb.contentRect, (Origin90)origin, amount, clockwise); + break; + + case FillMethod.Radial180: + FillRadial180(vb, vb.contentRect, (Origin180)origin, amount, clockwise); + break; + + case FillMethod.Radial360: + FillRadial360(vb, vb.contentRect, (Origin360)origin, amount, clockwise); + break; + } + } + + static void FillHorizontal(VertexBuffer vb, Rect vertRect, int origin, float amount) + { + float a = vertRect.width * amount; + if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom) + vertRect.x += (vertRect.width - a); + vertRect.width = a; + + vb.AddQuad(vertRect); + vb.AddTriangles(); + } + + static void FillVertical(VertexBuffer vb, Rect vertRect, int origin, float amount) + { + float a = vertRect.height * amount; + if ((OriginHorizontal)origin == OriginHorizontal.Right || (OriginVertical)origin == OriginVertical.Bottom) + vertRect.y += (vertRect.height - a); + vertRect.height = a; + + vb.AddQuad(vertRect); + vb.AddTriangles(); + } + + //4 vertex + static void FillRadial90(VertexBuffer vb, Rect vertRect, Origin90 origin, float amount, bool clockwise) + { + bool flipX = origin == Origin90.TopRight || origin == Origin90.BottomRight; + bool flipY = origin == Origin90.BottomLeft || origin == Origin90.BottomRight; + if (flipX != flipY) + clockwise = !clockwise; + + float ratio = clockwise ? amount : (1 - amount); + float tan = Mathf.Tan(Mathf.PI * 0.5f * ratio); + bool thresold = false; + if (ratio != 1) + thresold = (vertRect.height / vertRect.width - tan) > 0; + if (!clockwise) + thresold = !thresold; + float x = vertRect.x + (ratio == 0 ? float.MaxValue : (vertRect.height / tan)); + float y = vertRect.y + (ratio == 1 ? float.MaxValue : (vertRect.width * tan)); + float x2 = x; + float y2 = y; + if (flipX) + x2 = vertRect.width - x; + if (flipY) + y2 = vertRect.height - y; + float xMin = flipX ? (vertRect.width - vertRect.x) : vertRect.xMin; + float yMin = flipY ? (vertRect.height - vertRect.y) : vertRect.yMin; + float xMax = flipX ? -vertRect.xMin : vertRect.xMax; + float yMax = flipY ? -vertRect.yMin : vertRect.yMax; + + vb.AddVert(new Vector3(xMin, yMin, 0)); + + if (clockwise) + vb.AddVert(new Vector3(xMax, yMin, 0)); + + if (y > vertRect.yMax) + { + if (thresold) + vb.AddVert(new Vector3(x2, yMax, 0)); + else + vb.AddVert(new Vector3(xMax, yMax, 0)); + } + else + vb.AddVert(new Vector3(xMax, y2, 0)); + + if (x > vertRect.xMax) + { + if (thresold) + vb.AddVert(new Vector3(xMax, y2, 0)); + else + vb.AddVert(new Vector3(xMax, yMax, 0)); + } + else + vb.AddVert(new Vector3(x2, yMax, 0)); + + if (!clockwise) + vb.AddVert(new Vector3(xMin, yMax, 0)); + + if (flipX == flipY) + { + vb.AddTriangle(0, 1, 2); + vb.AddTriangle(0, 2, 3); + } + else + { + vb.AddTriangle(2, 1, 0); + vb.AddTriangle(3, 2, 0); + } + } + + //8 vertex + static void FillRadial180(VertexBuffer vb, Rect vertRect, Origin180 origin, float amount, bool clockwise) + { + switch (origin) + { + case Origin180.Top: + if (amount <= 0.5f) + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.TopRight, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.TopLeft, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x += vertRect.width; + else + vertRect.x -= vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin180.Bottom: + if (amount <= 0.5f) + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.BottomLeft, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.BottomRight, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x -= vertRect.width; + else + vertRect.x += vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin180.Left: + if (amount <= 0.5f) + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomLeft : Origin90.TopLeft, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopLeft : Origin90.BottomLeft, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y -= vertRect.height; + else + vertRect.y += vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin180.Right: + if (amount <= 0.5f) + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.TopRight : Origin90.BottomRight, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-4); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial90(vb, vertRect, clockwise ? Origin90.BottomRight : Origin90.TopRight, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y += vertRect.height; + else + vertRect.y -= vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + } + } + + //12 vertex + static void FillRadial360(VertexBuffer vb, Rect vertRect, Origin360 origin, float amount, bool clockwise) + { + switch (origin) + { + case Origin360.Top: + if (amount < 0.5f) + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x += vertRect.width; + else + vertRect.x -= vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + + break; + + case Origin360.Bottom: + if (amount < 0.5f) + { + vertRect.width /= 2; + if (!clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Right : Origin180.Left, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.width /= 2; + if (clockwise) + vertRect.x += vertRect.width; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Left : Origin180.Right, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.x -= vertRect.width; + else + vertRect.x += vertRect.width; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin360.Left: + if (amount < 0.5f) + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y -= vertRect.height; + else + vertRect.y += vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + + case Origin360.Right: + if (amount < 0.5f) + { + vertRect.height /= 2; + if (clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Top : Origin180.Bottom, amount / 0.5f, clockwise); + Vector3 vec = vb.GetPosition(-8); + vb.AddQuad(new Rect(vec.x, vec.y, 0, 0)); + vb.AddTriangles(-4); + } + else + { + vertRect.height /= 2; + if (!clockwise) + vertRect.y += vertRect.height; + + FillRadial180(vb, vertRect, clockwise ? Origin180.Bottom : Origin180.Top, (amount - 0.5f) / 0.5f, clockwise); + + if (clockwise) + vertRect.y += vertRect.height; + else + vertRect.y -= vertRect.height; + vb.AddQuad(vertRect); + vb.AddTriangles(-4); + } + break; + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Core/Mesh/FillMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/FillMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/FillMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/FillMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/LineMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/LineMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/LineMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/LineMesh.cs index 773f829a..2da619aa 100644 --- a/Assets/Scripts/Core/Mesh/LineMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/LineMesh.cs @@ -1,179 +1,179 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// Inspired by kim ki won (http://mypi.ruliweb.daum.net/mypi.htm?id=newtypekorea) - /// - public class LineMesh : IMeshFactory - { - /// - /// - /// - public GPath path; - - /// - /// - /// - public float lineWidth; - - /// - /// - /// - public AnimationCurve lineWidthCurve; - - /// - /// - /// - public Gradient gradient; - - /// - /// - /// - public bool roundEdge; - - /// - /// - /// - public float fillStart; - - /// - /// - /// - public float fillEnd; - - /// - /// - /// - public float pointDensity; - - /// - /// - /// - public bool repeatFill; - - static List points = new List(); - static List ts = new List(); - - public LineMesh() - { - path = new GPath(); - lineWidth = 2; - fillStart = 0; - fillEnd = 1; - pointDensity = 0.1f; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - Vector2 uvMin = vb.uvRect.position; - Vector2 uvMax = new Vector2(vb.uvRect.xMax, vb.uvRect.yMax); - float uvRatio = path.length / vb.textureSize.x; - - int segCount = path.segmentCount; - float t = 0; - float lw = lineWidth; - float u; - for (int si = 0; si < segCount; si++) - { - float ratio = path.GetSegmentLength(si) / path.length; - float t0 = Mathf.Clamp(fillStart - t, 0, ratio) / ratio; - float t1 = Mathf.Clamp(fillEnd - t, 0, ratio) / ratio; - if (t0 >= t1) - { - t += ratio; - continue; - } - - points.Clear(); - ts.Clear(); - path.GetPointsInSegment(si, t0, t1, points, ts, pointDensity); - int cnt = points.Count; - - Color c0 = vb.vertexColor; - Color c1 = vb.vertexColor; - if (gradient != null) - c0 = gradient.Evaluate(t); - if (lineWidthCurve != null) - lw = lineWidthCurve.Evaluate(t); - - if (roundEdge && si == 0 && t0 == 0) - DrawRoundEdge(vb, points[0], points[1], lw, c0, uvMin); - - int vertCount = vb.currentVertCount; - for (int i = 1; i < cnt; i++) - { - Vector3 p0 = points[i - 1]; - Vector3 p1 = points[i]; - int k = vertCount + (i - 1) * 2; - float tc = t + ratio * ts[i]; - - Vector3 lineVector = p1 - p0; - Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); - widthVector.Normalize(); - - if (i == 1) - { - if (repeatFill) - u = tc * uvRatio * uvMax.x; - else - u = Mathf.Lerp(uvMin.x, uvMax.x, t + ratio * ts[i - 1]); - vb.AddVert(p0 - widthVector * lw * 0.5f, c0, new Vector2(u, uvMax.y)); - vb.AddVert(p0 + widthVector * lw * 0.5f, c0, new Vector2(u, uvMin.y)); - - if (si != 0) //joint - { - vb.AddTriangle(k - 2, k - 1, k + 1); - vb.AddTriangle(k - 2, k + 1, k); - } - } - if (gradient != null) - c1 = gradient.Evaluate(tc); - - if (lineWidthCurve != null) - lw = lineWidthCurve.Evaluate(tc); - - if (repeatFill) - u = tc * uvRatio * uvMax.x; - else - u = Mathf.Lerp(uvMin.x, uvMax.x, tc); - vb.AddVert(p1 - widthVector * lw * 0.5f, c1, new Vector2(u, uvMax.y)); - vb.AddVert(p1 + widthVector * lw * 0.5f, c1, new Vector2(u, uvMin.y)); - - vb.AddTriangle(k, k + 1, k + 3); - vb.AddTriangle(k, k + 3, k + 2); - } - - if (roundEdge && si == segCount - 1 && t1 == 1) - DrawRoundEdge(vb, points[cnt - 1], points[cnt - 2], lw, c1, uvMax); - - t += ratio; - } - } - - void DrawRoundEdge(VertexBuffer vb, Vector2 p0, Vector2 p1, float lw, Color32 color, Vector2 uv) - { - Vector2 widthVector = Vector3.Cross(p0 - p1, new Vector3(0, 0, 1)); - widthVector.Normalize(); - widthVector = widthVector * lw / 2f; - Vector2 lineVector = (p0 - p1).normalized * lw / 2f; - - int sides = Mathf.CeilToInt(Mathf.PI * lw / 2); - if (sides < 6) - sides = 6; - int current = vb.currentVertCount; - float angleUnit = Mathf.PI / (sides - 1); - - vb.AddVert(p0, color, uv); - vb.AddVert(p0 + widthVector, color, uv); - - for (int n = 0; n < sides; n++) - { - vb.AddVert(p0 + Mathf.Cos(angleUnit * n) * widthVector + Mathf.Sin(angleUnit * n) * lineVector, color, uv); - vb.AddTriangle(current, current + 1 + n, current + 2 + n); - } - } - } -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// Inspired by kim ki won (http://mypi.ruliweb.daum.net/mypi.htm?id=newtypekorea) + /// + public class LineMesh : IMeshFactory + { + /// + /// + /// + public GPath path; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public AnimationCurve lineWidthCurve; + + /// + /// + /// + public Gradient gradient; + + /// + /// + /// + public bool roundEdge; + + /// + /// + /// + public float fillStart; + + /// + /// + /// + public float fillEnd; + + /// + /// + /// + public float pointDensity; + + /// + /// + /// + public bool repeatFill; + + static List points = new List(); + static List ts = new List(); + + public LineMesh() + { + path = new GPath(); + lineWidth = 2; + fillStart = 0; + fillEnd = 1; + pointDensity = 0.1f; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Vector2 uvMin = vb.uvRect.position; + Vector2 uvMax = new Vector2(vb.uvRect.xMax, vb.uvRect.yMax); + float uvRatio = path.length / vb.textureSize.x; + + int segCount = path.segmentCount; + float t = 0; + float lw = lineWidth; + float u; + for (int si = 0; si < segCount; si++) + { + float ratio = path.GetSegmentLength(si) / path.length; + float t0 = Mathf.Clamp(fillStart - t, 0, ratio) / ratio; + float t1 = Mathf.Clamp(fillEnd - t, 0, ratio) / ratio; + if (t0 >= t1) + { + t += ratio; + continue; + } + + points.Clear(); + ts.Clear(); + path.GetPointsInSegment(si, t0, t1, points, ts, pointDensity); + int cnt = points.Count; + + Color c0 = vb.vertexColor; + Color c1 = vb.vertexColor; + if (gradient != null) + c0 = gradient.Evaluate(t); + if (lineWidthCurve != null) + lw = lineWidthCurve.Evaluate(t); + + if (roundEdge && si == 0 && t0 == 0) + DrawRoundEdge(vb, points[0], points[1], lw, c0, uvMin); + + int vertCount = vb.currentVertCount; + for (int i = 1; i < cnt; i++) + { + Vector3 p0 = points[i - 1]; + Vector3 p1 = points[i]; + int k = vertCount + (i - 1) * 2; + float tc = t + ratio * ts[i]; + + Vector3 lineVector = p1 - p0; + Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); + widthVector.Normalize(); + + if (i == 1) + { + if (repeatFill) + u = tc * uvRatio * uvMax.x; + else + u = Mathf.Lerp(uvMin.x, uvMax.x, t + ratio * ts[i - 1]); + vb.AddVert(p0 - widthVector * lw * 0.5f, c0, new Vector2(u, uvMax.y)); + vb.AddVert(p0 + widthVector * lw * 0.5f, c0, new Vector2(u, uvMin.y)); + + if (si != 0) //joint + { + vb.AddTriangle(k - 2, k - 1, k + 1); + vb.AddTriangle(k - 2, k + 1, k); + } + } + if (gradient != null) + c1 = gradient.Evaluate(tc); + + if (lineWidthCurve != null) + lw = lineWidthCurve.Evaluate(tc); + + if (repeatFill) + u = tc * uvRatio * uvMax.x; + else + u = Mathf.Lerp(uvMin.x, uvMax.x, tc); + vb.AddVert(p1 - widthVector * lw * 0.5f, c1, new Vector2(u, uvMax.y)); + vb.AddVert(p1 + widthVector * lw * 0.5f, c1, new Vector2(u, uvMin.y)); + + vb.AddTriangle(k, k + 1, k + 3); + vb.AddTriangle(k, k + 3, k + 2); + } + + if (roundEdge && si == segCount - 1 && t1 == 1) + DrawRoundEdge(vb, points[cnt - 1], points[cnt - 2], lw, c1, uvMax); + + t += ratio; + } + } + + void DrawRoundEdge(VertexBuffer vb, Vector2 p0, Vector2 p1, float lw, Color32 color, Vector2 uv) + { + Vector2 widthVector = Vector3.Cross(p0 - p1, new Vector3(0, 0, 1)); + widthVector.Normalize(); + widthVector = widthVector * lw / 2f; + Vector2 lineVector = (p0 - p1).normalized * lw / 2f; + + int sides = Mathf.CeilToInt(Mathf.PI * lw / 2); + if (sides < 6) + sides = 6; + int current = vb.currentVertCount; + float angleUnit = Mathf.PI / (sides - 1); + + vb.AddVert(p0, color, uv); + vb.AddVert(p0 + widthVector, color, uv); + + for (int n = 0; n < sides; n++) + { + vb.AddVert(p0 + Mathf.Cos(angleUnit * n) * widthVector + Mathf.Sin(angleUnit * n) * lineVector, color, uv); + vb.AddTriangle(current, current + 1 + n, current + 2 + n); + } + } + } +} diff --git a/Assets/Scripts/Core/Mesh/LineMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/LineMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/LineMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/LineMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/MeshFactory.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/MeshFactory.cs similarity index 94% rename from Assets/Scripts/Core/Mesh/MeshFactory.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/MeshFactory.cs index 22cbc849..ce688abe 100644 --- a/Assets/Scripts/Core/Mesh/MeshFactory.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/MeshFactory.cs @@ -1,15 +1,15 @@ - -namespace FairyGUI -{ - /// - /// - /// - public interface IMeshFactory - { - /// - /// - /// - /// - void OnPopulateMesh(VertexBuffer vb); - } -} + +namespace FairyGUI +{ + /// + /// + /// + public interface IMeshFactory + { + /// + /// + /// + /// + void OnPopulateMesh(VertexBuffer vb); + } +} diff --git a/Assets/Scripts/Core/Mesh/MeshFactory.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/MeshFactory.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/MeshFactory.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/MeshFactory.cs.meta diff --git a/Assets/Scripts/Core/Mesh/PlaneMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PlaneMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/PlaneMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PlaneMesh.cs index c35bbb6a..4062bf85 100644 --- a/Assets/Scripts/Core/Mesh/PlaneMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PlaneMesh.cs @@ -1,51 +1,51 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class PlaneMesh : IMeshFactory - { - public int gridSize = 30; - - public void OnPopulateMesh(VertexBuffer vb) - { - float w = vb.contentRect.width; - float h = vb.contentRect.height; - float xMax = vb.contentRect.xMax; - float yMax = vb.contentRect.yMax; - int hc = (int)Mathf.Min(Mathf.CeilToInt(w / gridSize), 9); - int vc = (int)Mathf.Min(Mathf.CeilToInt(h / gridSize), 9); - int eachPartX = Mathf.FloorToInt(w / hc); - int eachPartY = Mathf.FloorToInt(h / vc); - float x, y; - for (int i = 0; i <= vc; i++) - { - if (i == vc) - y = yMax; - else - y = vb.contentRect.y + i * eachPartY; - for (int j = 0; j <= hc; j++) - { - if (j == hc) - x = xMax; - else - x = vb.contentRect.x + j * eachPartX; - vb.AddVert(new Vector3(x, y, 0)); - } - } - - for (int i = 0; i < vc; i++) - { - int k = i * (hc + 1); - for (int j = 1; j <= hc; j++) - { - int m = k + j; - vb.AddTriangle(m - 1, m, m + hc); - vb.AddTriangle(m, m + hc + 1, m + hc); - } - } - } - } +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PlaneMesh : IMeshFactory + { + public int gridSize = 30; + + public void OnPopulateMesh(VertexBuffer vb) + { + float w = vb.contentRect.width; + float h = vb.contentRect.height; + float xMax = vb.contentRect.xMax; + float yMax = vb.contentRect.yMax; + int hc = (int)Mathf.Min(Mathf.CeilToInt(w / gridSize), 9); + int vc = (int)Mathf.Min(Mathf.CeilToInt(h / gridSize), 9); + int eachPartX = Mathf.FloorToInt(w / hc); + int eachPartY = Mathf.FloorToInt(h / vc); + float x, y; + for (int i = 0; i <= vc; i++) + { + if (i == vc) + y = yMax; + else + y = vb.contentRect.y + i * eachPartY; + for (int j = 0; j <= hc; j++) + { + if (j == hc) + x = xMax; + else + x = vb.contentRect.x + j * eachPartX; + vb.AddVert(new Vector3(x, y, 0)); + } + } + + for (int i = 0; i < vc; i++) + { + int k = i * (hc + 1); + for (int j = 1; j <= hc; j++) + { + int m = k + j; + vb.AddTriangle(m - 1, m, m + hc); + vb.AddTriangle(m, m + hc + 1, m + hc); + } + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Core/Mesh/PlaneMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PlaneMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/PlaneMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PlaneMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/PolygonMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PolygonMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/PolygonMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PolygonMesh.cs index 10bab73b..006e756e 100644 --- a/Assets/Scripts/Core/Mesh/PolygonMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PolygonMesh.cs @@ -1,291 +1,291 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class PolygonMesh : IMeshFactory, IHitTest - { - /// - /// points must be in clockwise order, and must start from bottom-left if stretchUV is set. - /// - public readonly List points; - - /// - /// if you dont want to provide uv, leave it empty. - /// - public readonly List texcoords; - - /// - /// - /// - public float lineWidth; - - /// - /// - /// - public Color32 lineColor; - - /// - /// - /// - public Color32? fillColor; - - /// - /// - /// - public Color32[] colors; - - /// - /// - /// - public bool usePercentPositions; - - static List sRestIndices = new List(); - - public PolygonMesh() - { - points = new List(); - texcoords = new List(); - } - - /// - /// - /// - /// - public void Add(Vector2 point) - { - points.Add(point); - } - - /// - /// - /// - /// - /// - public void Add(Vector2 point, Vector2 texcoord) - { - points.Add(point); - texcoords.Add(texcoord); - } - - public void OnPopulateMesh(VertexBuffer vb) - { - int numVertices = points.Count; - if (numVertices < 3) - return; - - int restIndexPos, numRestIndices; - Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; - - float w = vb.contentRect.width; - float h = vb.contentRect.height; - bool useTexcoords = texcoords.Count >= numVertices; - bool fullUV = true; - for (int i = 0; i < numVertices; i++) - { - Vector3 vec = new Vector3(points[i].x, points[i].y, 0); - if (usePercentPositions) - { - vec.x *= w; - vec.y *= h; - } - if (useTexcoords) - { - Vector2 uv = texcoords[i]; - if (uv.x != 0 && uv.x != 1 || uv.y != 0 && uv.y != 1) - fullUV = false; - uv.x = Mathf.Lerp(vb.uvRect.x, vb.uvRect.xMax, uv.x); - uv.y = Mathf.Lerp(vb.uvRect.y, vb.uvRect.yMax, uv.y); - vb.AddVert(vec, color, uv); - } - else - vb.AddVert(vec, color); - } - - if (useTexcoords && fullUV && numVertices == 4) - vb._isArbitraryQuad = true; - - // Algorithm "Ear clipping method" described here: - // -> https://en.wikipedia.org/wiki/Polygon_triangulation - // - // Implementation inspired by: - // -> http://polyk.ivank.net - // -> Starling - - sRestIndices.Clear(); - for (int i = 0; i < numVertices; ++i) - sRestIndices.Add(i); - - restIndexPos = 0; - numRestIndices = numVertices; - - Vector2 a, b, c, p; - int otherIndex; - bool earFound; - int i0, i1, i2; - - while (numRestIndices > 3) - { - earFound = false; - i0 = sRestIndices[restIndexPos % numRestIndices]; - i1 = sRestIndices[(restIndexPos + 1) % numRestIndices]; - i2 = sRestIndices[(restIndexPos + 2) % numRestIndices]; - - a = points[i0]; - b = points[i1]; - c = points[i2]; - - if ((a.y - b.y) * (c.x - b.x) + (b.x - a.x) * (c.y - b.y) >= 0) - { - earFound = true; - for (int i = 3; i < numRestIndices; ++i) - { - otherIndex = sRestIndices[(restIndexPos + i) % numRestIndices]; - p = points[otherIndex]; - - if (IsPointInTriangle(ref p, ref a, ref b, ref c)) - { - earFound = false; - break; - } - } - } - - if (earFound) - { - vb.AddTriangle(i0, i1, i2); - sRestIndices.RemoveAt((restIndexPos + 1) % numRestIndices); - - numRestIndices--; - restIndexPos = 0; - } - else - { - restIndexPos++; - if (restIndexPos == numRestIndices) break; // no more ears - } - } - vb.AddTriangle(sRestIndices[0], sRestIndices[1], sRestIndices[2]); - - if (colors != null) - vb.RepeatColors(colors, 0, vb.currentVertCount); - - if (lineWidth > 0) - DrawOutline(vb); - } - - void DrawOutline(VertexBuffer vb) - { - int numVertices = points.Count; - int start = vb.currentVertCount - numVertices; - int k = vb.currentVertCount; - for (int i = 0; i < numVertices; i++) - { - Vector3 p0 = vb.vertices[start + i]; - p0.y = -p0.y; - Vector3 p1; - if (i < numVertices - 1) - p1 = vb.vertices[start + i + 1]; - else - p1 = vb.vertices[start]; - p1.y = -p1.y; - - Vector3 lineVector = p1 - p0; - Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); - widthVector.Normalize(); - - vb.AddVert(p0 - widthVector * lineWidth * 0.5f, lineColor); - vb.AddVert(p0 + widthVector * lineWidth * 0.5f, lineColor); - vb.AddVert(p1 - widthVector * lineWidth * 0.5f, lineColor); - vb.AddVert(p1 + widthVector * lineWidth * 0.5f, lineColor); - - k += 4; - vb.AddTriangle(k - 4, k - 3, k - 1); - vb.AddTriangle(k - 4, k - 1, k - 2); - - //joint - if (i != 0) - { - vb.AddTriangle(k - 6, k - 5, k - 3); - vb.AddTriangle(k - 6, k - 3, k - 4); - } - if (i == numVertices - 1) - { - start += numVertices; - vb.AddTriangle(k - 2, k - 1, start + 1); - vb.AddTriangle(k - 2, start + 1, start); - } - } - } - - bool IsPointInTriangle(ref Vector2 p, ref Vector2 a, ref Vector2 b, ref Vector2 c) - { - // From Starling - // This algorithm is described well in this article: - // http://www.blackpawn.com/texts/pointinpoly/default.html - - float v0x = c.x - a.x; - float v0y = c.y - a.y; - float v1x = b.x - a.x; - float v1y = b.y - a.y; - float v2x = p.x - a.x; - float v2y = p.y - a.y; - - float dot00 = v0x * v0x + v0y * v0y; - float dot01 = v0x * v1x + v0y * v1y; - float dot02 = v0x * v2x + v0y * v2y; - float dot11 = v1x * v1x + v1y * v1y; - float dot12 = v1x * v2x + v1y * v2y; - - float invDen = 1.0f / (dot00 * dot11 - dot01 * dot01); - float u = (dot11 * dot02 - dot01 * dot12) * invDen; - float v = (dot00 * dot12 - dot01 * dot02) * invDen; - - return (u >= 0) && (v >= 0) && (u + v < 1); - } - - public bool HitTest(Rect contentRect, Vector2 point) - { - if (!contentRect.Contains(point)) - return false; - - // Algorithm & implementation thankfully taken from: - // -> http://alienryderflex.com/polygon/ - // inspired by Starling - int len = points.Count; - int i; - int j = len - 1; - bool oddNodes = false; - float w = contentRect.width; - float h = contentRect.height; - - for (i = 0; i < len; ++i) - { - float ix = points[i].x; - float iy = points[i].y; - float jx = points[j].x; - float jy = points[j].y; - if (usePercentPositions) - { - ix *= w; - iy *= h; - ix *= w; - iy *= h; - } - - if ((iy < point.y && jy >= point.y || jy < point.y && iy >= point.y) && (ix <= point.x || jx <= point.x)) - { - if (ix + (point.y - iy) / (jy - iy) * (jx - ix) < point.x) - oddNodes = !oddNodes; - } - - j = i; - } - - return oddNodes; - } - } -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PolygonMesh : IMeshFactory, IHitTest + { + /// + /// points must be in clockwise order, and must start from bottom-left if stretchUV is set. + /// + public readonly List points; + + /// + /// if you dont want to provide uv, leave it empty. + /// + public readonly List texcoords; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public Color32[] colors; + + /// + /// + /// + public bool usePercentPositions; + + static List sRestIndices = new List(); + + public PolygonMesh() + { + points = new List(); + texcoords = new List(); + } + + /// + /// + /// + /// + public void Add(Vector2 point) + { + points.Add(point); + } + + /// + /// + /// + /// + /// + public void Add(Vector2 point, Vector2 texcoord) + { + points.Add(point); + texcoords.Add(texcoord); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + int numVertices = points.Count; + if (numVertices < 3) + return; + + int restIndexPos, numRestIndices; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + + float w = vb.contentRect.width; + float h = vb.contentRect.height; + bool useTexcoords = texcoords.Count >= numVertices; + bool fullUV = true; + for (int i = 0; i < numVertices; i++) + { + Vector3 vec = new Vector3(points[i].x, points[i].y, 0); + if (usePercentPositions) + { + vec.x *= w; + vec.y *= h; + } + if (useTexcoords) + { + Vector2 uv = texcoords[i]; + if (uv.x != 0 && uv.x != 1 || uv.y != 0 && uv.y != 1) + fullUV = false; + uv.x = Mathf.Lerp(vb.uvRect.x, vb.uvRect.xMax, uv.x); + uv.y = Mathf.Lerp(vb.uvRect.y, vb.uvRect.yMax, uv.y); + vb.AddVert(vec, color, uv); + } + else + vb.AddVert(vec, color); + } + + if (useTexcoords && fullUV && numVertices == 4) + vb._isArbitraryQuad = true; + + // Algorithm "Ear clipping method" described here: + // -> https://en.wikipedia.org/wiki/Polygon_triangulation + // + // Implementation inspired by: + // -> http://polyk.ivank.net + // -> Starling + + sRestIndices.Clear(); + for (int i = 0; i < numVertices; ++i) + sRestIndices.Add(i); + + restIndexPos = 0; + numRestIndices = numVertices; + + Vector2 a, b, c, p; + int otherIndex; + bool earFound; + int i0, i1, i2; + + while (numRestIndices > 3) + { + earFound = false; + i0 = sRestIndices[restIndexPos % numRestIndices]; + i1 = sRestIndices[(restIndexPos + 1) % numRestIndices]; + i2 = sRestIndices[(restIndexPos + 2) % numRestIndices]; + + a = points[i0]; + b = points[i1]; + c = points[i2]; + + if ((a.y - b.y) * (c.x - b.x) + (b.x - a.x) * (c.y - b.y) >= 0) + { + earFound = true; + for (int i = 3; i < numRestIndices; ++i) + { + otherIndex = sRestIndices[(restIndexPos + i) % numRestIndices]; + p = points[otherIndex]; + + if (IsPointInTriangle(ref p, ref a, ref b, ref c)) + { + earFound = false; + break; + } + } + } + + if (earFound) + { + vb.AddTriangle(i0, i1, i2); + sRestIndices.RemoveAt((restIndexPos + 1) % numRestIndices); + + numRestIndices--; + restIndexPos = 0; + } + else + { + restIndexPos++; + if (restIndexPos == numRestIndices) break; // no more ears + } + } + vb.AddTriangle(sRestIndices[0], sRestIndices[1], sRestIndices[2]); + + if (colors != null) + vb.RepeatColors(colors, 0, vb.currentVertCount); + + if (lineWidth > 0) + DrawOutline(vb); + } + + void DrawOutline(VertexBuffer vb) + { + int numVertices = points.Count; + int start = vb.currentVertCount - numVertices; + int k = vb.currentVertCount; + for (int i = 0; i < numVertices; i++) + { + Vector3 p0 = vb.vertices[start + i]; + p0.y = -p0.y; + Vector3 p1; + if (i < numVertices - 1) + p1 = vb.vertices[start + i + 1]; + else + p1 = vb.vertices[start]; + p1.y = -p1.y; + + Vector3 lineVector = p1 - p0; + Vector3 widthVector = Vector3.Cross(lineVector, new Vector3(0, 0, 1)); + widthVector.Normalize(); + + vb.AddVert(p0 - widthVector * lineWidth * 0.5f, lineColor); + vb.AddVert(p0 + widthVector * lineWidth * 0.5f, lineColor); + vb.AddVert(p1 - widthVector * lineWidth * 0.5f, lineColor); + vb.AddVert(p1 + widthVector * lineWidth * 0.5f, lineColor); + + k += 4; + vb.AddTriangle(k - 4, k - 3, k - 1); + vb.AddTriangle(k - 4, k - 1, k - 2); + + //joint + if (i != 0) + { + vb.AddTriangle(k - 6, k - 5, k - 3); + vb.AddTriangle(k - 6, k - 3, k - 4); + } + if (i == numVertices - 1) + { + start += numVertices; + vb.AddTriangle(k - 2, k - 1, start + 1); + vb.AddTriangle(k - 2, start + 1, start); + } + } + } + + bool IsPointInTriangle(ref Vector2 p, ref Vector2 a, ref Vector2 b, ref Vector2 c) + { + // From Starling + // This algorithm is described well in this article: + // http://www.blackpawn.com/texts/pointinpoly/default.html + + float v0x = c.x - a.x; + float v0y = c.y - a.y; + float v1x = b.x - a.x; + float v1y = b.y - a.y; + float v2x = p.x - a.x; + float v2y = p.y - a.y; + + float dot00 = v0x * v0x + v0y * v0y; + float dot01 = v0x * v1x + v0y * v1y; + float dot02 = v0x * v2x + v0y * v2y; + float dot11 = v1x * v1x + v1y * v1y; + float dot12 = v1x * v2x + v1y * v2y; + + float invDen = 1.0f / (dot00 * dot11 - dot01 * dot01); + float u = (dot11 * dot02 - dot01 * dot12) * invDen; + float v = (dot00 * dot12 - dot01 * dot02) * invDen; + + return (u >= 0) && (v >= 0) && (u + v < 1); + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (!contentRect.Contains(point)) + return false; + + // Algorithm & implementation thankfully taken from: + // -> http://alienryderflex.com/polygon/ + // inspired by Starling + int len = points.Count; + int i; + int j = len - 1; + bool oddNodes = false; + float w = contentRect.width; + float h = contentRect.height; + + for (i = 0; i < len; ++i) + { + float ix = points[i].x; + float iy = points[i].y; + float jx = points[j].x; + float jy = points[j].y; + if (usePercentPositions) + { + ix *= w; + iy *= h; + ix *= w; + iy *= h; + } + + if ((iy < point.y && jy >= point.y || jy < point.y && iy >= point.y) && (ix <= point.x || jx <= point.x)) + { + if (ix + (point.y - iy) / (jy - iy) * (jx - ix) < point.x) + oddNodes = !oddNodes; + } + + j = i; + } + + return oddNodes; + } + } +} diff --git a/Assets/Scripts/Core/Mesh/PolygonMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PolygonMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/PolygonMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/PolygonMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/RectMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RectMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/RectMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RectMesh.cs index 409cc0c5..4702552d 100644 --- a/Assets/Scripts/Core/Mesh/RectMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RectMesh.cs @@ -1,85 +1,85 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class RectMesh : IMeshFactory, IHitTest - { - /// - /// - /// - public Rect? drawRect; - - /// - /// - /// - public float lineWidth; - - /// - /// - /// - public Color32 lineColor; - - /// - /// - /// - public Color32? fillColor; - - /// - /// - /// - public Color32[] colors; - - public RectMesh() - { - lineColor = Color.black; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; - Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; - if (lineWidth == 0) - { - if (color.a != 0)//optimized - vb.AddQuad(rect, color); - } - else - { - Rect part; - - //left,right - part = new Rect(rect.x, rect.y, lineWidth, rect.height); - vb.AddQuad(part, lineColor); - part = new Rect(rect.xMax - lineWidth, rect.y, lineWidth, rect.height); - vb.AddQuad(part, lineColor); - - //top, bottom - part = new Rect(rect.x + lineWidth, rect.y, rect.width - lineWidth * 2, lineWidth); - vb.AddQuad(part, lineColor); - part = new Rect(rect.x + lineWidth, rect.yMax - lineWidth, rect.width - lineWidth * 2, lineWidth); - vb.AddQuad(part, lineColor); - - //middle - if (color.a != 0)//optimized - { - part = Rect.MinMaxRect(rect.x + lineWidth, rect.y + lineWidth, rect.xMax - lineWidth, rect.yMax - lineWidth); - if (part.width > 0 && part.height > 0) - vb.AddQuad(part, color); - } - } - - if (colors != null) - vb.RepeatColors(colors, 0, vb.currentVertCount); - - vb.AddTriangles(); - } - - public bool HitTest(Rect contentRect, Vector2 point) - { - return contentRect.Contains(point); - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class RectMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public Color32[] colors; + + public RectMesh() + { + lineColor = Color.black; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + if (lineWidth == 0) + { + if (color.a != 0)//optimized + vb.AddQuad(rect, color); + } + else + { + Rect part; + + //left,right + part = new Rect(rect.x, rect.y, lineWidth, rect.height); + vb.AddQuad(part, lineColor); + part = new Rect(rect.xMax - lineWidth, rect.y, lineWidth, rect.height); + vb.AddQuad(part, lineColor); + + //top, bottom + part = new Rect(rect.x + lineWidth, rect.y, rect.width - lineWidth * 2, lineWidth); + vb.AddQuad(part, lineColor); + part = new Rect(rect.x + lineWidth, rect.yMax - lineWidth, rect.width - lineWidth * 2, lineWidth); + vb.AddQuad(part, lineColor); + + //middle + if (color.a != 0)//optimized + { + part = Rect.MinMaxRect(rect.x + lineWidth, rect.y + lineWidth, rect.xMax - lineWidth, rect.yMax - lineWidth); + if (part.width > 0 && part.height > 0) + vb.AddQuad(part, color); + } + } + + if (colors != null) + vb.RepeatColors(colors, 0, vb.currentVertCount); + + vb.AddTriangles(); + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + return contentRect.Contains(point); + } + } +} diff --git a/Assets/Scripts/Core/Mesh/RectMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RectMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/RectMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RectMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/RegularPolygonMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RegularPolygonMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/RegularPolygonMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RegularPolygonMesh.cs index 8998a639..61259816 100644 --- a/Assets/Scripts/Core/Mesh/RegularPolygonMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RegularPolygonMesh.cs @@ -1,128 +1,128 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class RegularPolygonMesh : IMeshFactory, IHitTest - { - /// - /// - /// - public Rect? drawRect; - - /// - /// - /// - public int sides; - - /// - /// - /// - public float lineWidth; - - /// - /// - /// - public Color32 lineColor; - - /// - /// - /// - public Color32? centerColor; - - /// - /// - /// - public Color32? fillColor; - - /// - /// - /// - public float[] distances; - - /// - /// - /// - public float rotation; - - public RegularPolygonMesh() - { - sides = 3; - lineColor = Color.black; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - if (distances != null && distances.Length < sides) - { - Debug.LogError("distances.Length 0) - { - vb.AddVert(vec, lineColor); - - xv = Mathf.Cos(angle) * r + centerX; - yv = Mathf.Sin(angle) * r + centerY; - vb.AddVert(new Vector3(xv, yv, 0), lineColor); - } - angle += angleDelta; - } - - if (lineWidth > 0) - { - int tmp = sides * 3; - for (int i = 0; i < tmp; i += 3) - { - if (i != tmp - 3) - { - vb.AddTriangle(0, i + 1, i + 4); - vb.AddTriangle(i + 5, i + 2, i + 3); - vb.AddTriangle(i + 3, i + 6, i + 5); - } - else - { - vb.AddTriangle(0, i + 1, 1); - vb.AddTriangle(2, i + 2, i + 3); - vb.AddTriangle(i + 3, 3, 2); - } - } - } - else - { - for (int i = 0; i < sides; i++) - vb.AddTriangle(0, i + 1, (i == sides - 1) ? 1 : i + 2); - } - } - - public bool HitTest(Rect contentRect, Vector2 point) - { - if (drawRect != null) - return ((Rect)drawRect).Contains(point); - else - return contentRect.Contains(point); - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class RegularPolygonMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public int sides; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? centerColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public float[] distances; + + /// + /// + /// + public float rotation; + + public RegularPolygonMesh() + { + sides = 3; + lineColor = Color.black; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (distances != null && distances.Length < sides) + { + Debug.LogError("distances.Length 0) + { + vb.AddVert(vec, lineColor); + + xv = Mathf.Cos(angle) * r + centerX; + yv = Mathf.Sin(angle) * r + centerY; + vb.AddVert(new Vector3(xv, yv, 0), lineColor); + } + angle += angleDelta; + } + + if (lineWidth > 0) + { + int tmp = sides * 3; + for (int i = 0; i < tmp; i += 3) + { + if (i != tmp - 3) + { + vb.AddTriangle(0, i + 1, i + 4); + vb.AddTriangle(i + 5, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 6, i + 5); + } + else + { + vb.AddTriangle(0, i + 1, 1); + vb.AddTriangle(2, i + 2, i + 3); + vb.AddTriangle(i + 3, 3, 2); + } + } + } + else + { + for (int i = 0; i < sides; i++) + vb.AddTriangle(0, i + 1, (i == sides - 1) ? 1 : i + 2); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (drawRect != null) + return ((Rect)drawRect).Contains(point); + else + return contentRect.Contains(point); + } + } +} diff --git a/Assets/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RegularPolygonMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/RoundedRectMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RoundedRectMesh.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/RoundedRectMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RoundedRectMesh.cs index 256b6117..542b9309 100644 --- a/Assets/Scripts/Core/Mesh/RoundedRectMesh.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RoundedRectMesh.cs @@ -1,177 +1,177 @@ -using UnityEngine; - -namespace FairyGUI -{ - public class RoundedRectMesh : IMeshFactory, IHitTest - { - /// - /// - /// - public Rect? drawRect; - - /// - /// - /// - public float lineWidth; - - /// - /// - /// - public Color32 lineColor; - - /// - /// - /// - public Color32? fillColor; - - /// - /// - /// - public float topLeftRadius; - - /// - /// - /// - public float topRightRadius; - - /// - /// - /// - public float bottomLeftRadius; - - /// - /// - /// - public float bottomRightRadius; - - public RoundedRectMesh() - { - lineColor = Color.black; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; - Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; - - float radiusX = rect.width / 2; - float radiusY = rect.height / 2; - float cornerMaxRadius = Mathf.Min(radiusX, radiusY); - float centerX = radiusX + rect.x; - float centerY = radiusY + rect.y; - - vb.AddVert(new Vector3(centerX, centerY, 0), color); - - int cnt = vb.currentVertCount; - for (int i = 0; i < 4; i++) - { - float radius = 0; - switch (i) - { - case 0: - radius = bottomRightRadius; - break; - - case 1: - radius = bottomLeftRadius; - break; - - case 2: - radius = topLeftRadius; - break; - - case 3: - radius = topRightRadius; - break; - } - radius = Mathf.Min(cornerMaxRadius, radius); - - float offsetX = rect.x; - float offsetY = rect.y; - - if (i == 0 || i == 3) - offsetX = rect.xMax - radius * 2; - if (i == 0 || i == 1) - offsetY = rect.yMax - radius * 2; - - if (radius != 0) - { - int partNumSides = Mathf.Max(1, Mathf.CeilToInt(Mathf.PI * radius / 8)) + 1; - float angleDelta = Mathf.PI / 2 / partNumSides; - float angle = Mathf.PI / 2 * i; - float startAngle = angle; - - for (int j = 1; j <= partNumSides; j++) - { - if (j == partNumSides) //消除精度误差带来的不对齐 - angle = startAngle + Mathf.PI / 2; - Vector3 v1 = new Vector3(offsetX + Mathf.Cos(angle) * (radius - lineWidth) + radius, - offsetY + Mathf.Sin(angle) * (radius - lineWidth) + radius, 0); - vb.AddVert(v1, color); - if (lineWidth != 0) - { - vb.AddVert(v1, lineColor); - vb.AddVert(new Vector3(offsetX + Mathf.Cos(angle) * radius + radius, - offsetY + Mathf.Sin(angle) * radius + radius, 0), lineColor); - } - angle += angleDelta; - } - } - else - { - Vector3 v1 = new Vector3(offsetX, offsetY, 0); - if (lineWidth != 0) - { - if (i == 0 || i == 3) - offsetX -= lineWidth; - else - offsetX += lineWidth; - if (i == 0 || i == 1) - offsetY -= lineWidth; - else - offsetY += lineWidth; - Vector3 v2 = new Vector3(offsetX, offsetY, 0); - vb.AddVert(v2, color); - vb.AddVert(v2, lineColor); - vb.AddVert(v1, lineColor); - } - else - vb.AddVert(v1, color); - } - } - cnt = vb.currentVertCount - cnt; - - if (lineWidth > 0) - { - for (int i = 0; i < cnt; i += 3) - { - if (i != cnt - 3) - { - vb.AddTriangle(0, i + 1, i + 4); - vb.AddTriangle(i + 5, i + 2, i + 3); - vb.AddTriangle(i + 3, i + 6, i + 5); - } - else - { - vb.AddTriangle(0, i + 1, 1); - vb.AddTriangle(2, i + 2, i + 3); - vb.AddTriangle(i + 3, 3, 2); - } - } - } - else - { - for (int i = 0; i < cnt; i++) - vb.AddTriangle(0, i + 1, (i == cnt - 1) ? 1 : i + 2); - } - } - - public bool HitTest(Rect contentRect, Vector2 point) - { - if (drawRect != null) - return ((Rect)drawRect).Contains(point); - else - return contentRect.Contains(point); - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + public class RoundedRectMesh : IMeshFactory, IHitTest + { + /// + /// + /// + public Rect? drawRect; + + /// + /// + /// + public float lineWidth; + + /// + /// + /// + public Color32 lineColor; + + /// + /// + /// + public Color32? fillColor; + + /// + /// + /// + public float topLeftRadius; + + /// + /// + /// + public float topRightRadius; + + /// + /// + /// + public float bottomLeftRadius; + + /// + /// + /// + public float bottomRightRadius; + + public RoundedRectMesh() + { + lineColor = Color.black; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = drawRect != null ? (Rect)drawRect : vb.contentRect; + Color32 color = fillColor != null ? (Color32)fillColor : vb.vertexColor; + + float radiusX = rect.width / 2; + float radiusY = rect.height / 2; + float cornerMaxRadius = Mathf.Min(radiusX, radiusY); + float centerX = radiusX + rect.x; + float centerY = radiusY + rect.y; + + vb.AddVert(new Vector3(centerX, centerY, 0), color); + + int cnt = vb.currentVertCount; + for (int i = 0; i < 4; i++) + { + float radius = 0; + switch (i) + { + case 0: + radius = bottomRightRadius; + break; + + case 1: + radius = bottomLeftRadius; + break; + + case 2: + radius = topLeftRadius; + break; + + case 3: + radius = topRightRadius; + break; + } + radius = Mathf.Min(cornerMaxRadius, radius); + + float offsetX = rect.x; + float offsetY = rect.y; + + if (i == 0 || i == 3) + offsetX = rect.xMax - radius * 2; + if (i == 0 || i == 1) + offsetY = rect.yMax - radius * 2; + + if (radius != 0) + { + int partNumSides = Mathf.Max(1, Mathf.CeilToInt(Mathf.PI * radius / 8)) + 1; + float angleDelta = Mathf.PI / 2 / partNumSides; + float angle = Mathf.PI / 2 * i; + float startAngle = angle; + + for (int j = 1; j <= partNumSides; j++) + { + if (j == partNumSides) //消除精度误差带来的不对齐 + angle = startAngle + Mathf.PI / 2; + Vector3 v1 = new Vector3(offsetX + Mathf.Cos(angle) * (radius - lineWidth) + radius, + offsetY + Mathf.Sin(angle) * (radius - lineWidth) + radius, 0); + vb.AddVert(v1, color); + if (lineWidth != 0) + { + vb.AddVert(v1, lineColor); + vb.AddVert(new Vector3(offsetX + Mathf.Cos(angle) * radius + radius, + offsetY + Mathf.Sin(angle) * radius + radius, 0), lineColor); + } + angle += angleDelta; + } + } + else + { + Vector3 v1 = new Vector3(offsetX, offsetY, 0); + if (lineWidth != 0) + { + if (i == 0 || i == 3) + offsetX -= lineWidth; + else + offsetX += lineWidth; + if (i == 0 || i == 1) + offsetY -= lineWidth; + else + offsetY += lineWidth; + Vector3 v2 = new Vector3(offsetX, offsetY, 0); + vb.AddVert(v2, color); + vb.AddVert(v2, lineColor); + vb.AddVert(v1, lineColor); + } + else + vb.AddVert(v1, color); + } + } + cnt = vb.currentVertCount - cnt; + + if (lineWidth > 0) + { + for (int i = 0; i < cnt; i += 3) + { + if (i != cnt - 3) + { + vb.AddTriangle(0, i + 1, i + 4); + vb.AddTriangle(i + 5, i + 2, i + 3); + vb.AddTriangle(i + 3, i + 6, i + 5); + } + else + { + vb.AddTriangle(0, i + 1, 1); + vb.AddTriangle(2, i + 2, i + 3); + vb.AddTriangle(i + 3, 3, 2); + } + } + } + else + { + for (int i = 0; i < cnt; i++) + vb.AddTriangle(0, i + 1, (i == cnt - 1) ? 1 : i + 2); + } + } + + public bool HitTest(Rect contentRect, Vector2 point) + { + if (drawRect != null) + return ((Rect)drawRect).Contains(point); + else + return contentRect.Contains(point); + } + } +} diff --git a/Assets/Scripts/Core/Mesh/RoundedRectMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RoundedRectMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/RoundedRectMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/RoundedRectMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/StraightLineMesh.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/StraightLineMesh.cs similarity index 100% rename from Assets/Scripts/Core/Mesh/StraightLineMesh.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/StraightLineMesh.cs diff --git a/Assets/Scripts/Core/Mesh/StraightLineMesh.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/StraightLineMesh.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/StraightLineMesh.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/StraightLineMesh.cs.meta diff --git a/Assets/Scripts/Core/Mesh/VertexBuffer.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/VertexBuffer.cs similarity index 96% rename from Assets/Scripts/Core/Mesh/VertexBuffer.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/VertexBuffer.cs index b62005ad..f379f2cc 100644 --- a/Assets/Scripts/Core/Mesh/VertexBuffer.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/VertexBuffer.cs @@ -1,441 +1,441 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public sealed class VertexBuffer - { - /// - /// - /// - public Rect contentRect; - - /// - /// - /// - public Rect uvRect; - - /// - /// - /// - public Color32 vertexColor; - - /// - /// - /// - public Vector2 textureSize; - - /// - /// - /// - public readonly List vertices; - - /// - /// - /// - public readonly List colors; - - /// - /// - /// - public readonly List uvs; - - /// - /// - /// - public readonly List uvs2; - - /// - /// - /// - public readonly List triangles; - - static public Vector2[] NormalizedUV = new Vector2[] { - new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) }; - - static public Vector2[] NormalizedPosition = new Vector2[] { - new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1) }; - - internal bool _alphaInVertexColor; - internal bool _isArbitraryQuad; - - static Stack _pool = new Stack(); - - /// - /// - /// - /// - public static VertexBuffer Begin() - { - if (_pool.Count > 0) - { - VertexBuffer inst = _pool.Pop(); - inst.Clear(); - return inst; - } - else - return new VertexBuffer(); - } - - /// - /// - /// - /// - public static VertexBuffer Begin(VertexBuffer source) - { - VertexBuffer vb = Begin(); - vb.contentRect = source.contentRect; - vb.uvRect = source.uvRect; - vb.vertexColor = source.vertexColor; - vb.textureSize = source.textureSize; - - return vb; - } - - private VertexBuffer() - { - vertices = new List(); - colors = new List(); - uvs = new List(); - uvs2 = new List(); - triangles = new List(); - } - - /// - /// - /// - public void End() - { - _pool.Push(this); - } - - /// - /// - /// - public void Clear() - { - vertices.Clear(); - colors.Clear(); - uvs.Clear(); - uvs2.Clear(); - triangles.Clear(); - - _isArbitraryQuad = false; - _alphaInVertexColor = false; - } - - /// - /// - /// - public int currentVertCount - { - get - { - return vertices.Count; - } - } - - /// - /// - /// - /// - public void AddVert(Vector3 position) - { - position.y = -position.y; - vertices.Add(position); - colors.Add(vertexColor); - if (vertexColor.a != 255) - _alphaInVertexColor = true; - uvs.Add(new Vector2( - Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), - Mathf.Lerp(uvRect.yMax, uvRect.yMin, (-position.y - contentRect.yMin) / contentRect.height))); - } - - /// - /// - /// - /// - /// - public void AddVert(Vector3 position, Color32 color) - { - position.y = -position.y; - vertices.Add(position); - colors.Add(color); - if (color.a != 255) - _alphaInVertexColor = true; - uvs.Add(new Vector2( - Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), - Mathf.Lerp(uvRect.yMax, uvRect.yMin, (-position.y - contentRect.yMin) / contentRect.height))); - } - - /// - /// - /// - /// - /// - /// - public void AddVert(Vector3 position, Color32 color, Vector2 uv) - { - position.y = -position.y; - vertices.Add(position); - uvs.Add(new Vector2(uv.x, uv.y)); - colors.Add(color); - if (color.a != 255) - _alphaInVertexColor = true; - } - - /// - /// - /// 1---2 - /// | / | - /// 0---3 - /// - /// - public void AddQuad(Rect vertRect) - { - AddVert(new Vector3(vertRect.xMin, vertRect.yMax, 0f)); - AddVert(new Vector3(vertRect.xMin, vertRect.yMin, 0f)); - AddVert(new Vector3(vertRect.xMax, vertRect.yMin, 0f)); - AddVert(new Vector3(vertRect.xMax, vertRect.yMax, 0f)); - } - - /// - /// - /// - /// - /// - public void AddQuad(Rect vertRect, Color32 color) - { - AddVert(new Vector3(vertRect.xMin, vertRect.yMax, 0f), color); - AddVert(new Vector3(vertRect.xMin, vertRect.yMin, 0f), color); - AddVert(new Vector3(vertRect.xMax, vertRect.yMin, 0f), color); - AddVert(new Vector3(vertRect.xMax, vertRect.yMax, 0f), color); - } - - /// - /// - /// - /// - /// - /// - public void AddQuad(Rect vertRect, Color32 color, Rect uvRect) - { - vertices.Add(new Vector3(vertRect.xMin, -vertRect.yMax, 0f)); - vertices.Add(new Vector3(vertRect.xMin, -vertRect.yMin, 0f)); - vertices.Add(new Vector3(vertRect.xMax, -vertRect.yMin, 0f)); - vertices.Add(new Vector3(vertRect.xMax, -vertRect.yMax, 0f)); - - uvs.Add(new Vector2(uvRect.xMin, uvRect.yMin)); - uvs.Add(new Vector2(uvRect.xMin, uvRect.yMax)); - uvs.Add(new Vector2(uvRect.xMax, uvRect.yMax)); - uvs.Add(new Vector2(uvRect.xMax, uvRect.yMin)); - - colors.Add(color); - colors.Add(color); - colors.Add(color); - colors.Add(color); - - if (color.a != 255) - _alphaInVertexColor = true; - } - - static List helperV4List = new List(4) { Vector4.zero, Vector4.zero, Vector4.zero, Vector4.zero }; - internal List FixUVForArbitraryQuad() - { - //ref1 http://www.reedbeta.com/blog/quadrilateral-interpolation-part-1/ - //ref2 https://bitlush.com/blog/arbitrary-quadrilaterals-in-opengl-es-2-0 - - Vector4 qq = Vector4.one; - Vector2 a = vertices[2] - vertices[0]; - Vector2 b = vertices[1] - vertices[3]; - Vector2 c = vertices[0] - vertices[3]; - - float cross = a.x * b.y - a.y * b.x; - if (cross != 0) - { - float s = (a.x * c.y - a.y * c.x) / cross; - if (s > 0 && s < 1) - { - float t = (b.x * c.y - b.y * c.x) / cross; - if (t > 0 && t < 1) - { - qq.x = 1 / (1 - t); - qq.y = 1 / s; - qq.z = 1 / t; - qq.w = 1 / (1 - s); - } - } - } - - for (int i = 0; i < 4; i++) - { - Vector4 v = uvs[i]; - float q = qq[i]; - v.x *= q; - v.y *= q; - v.w = q; - helperV4List[i] = v; - } - - return helperV4List; - } - - /// - /// - /// - /// - /// - /// - public void RepeatColors(Color32[] value, int startIndex, int count) - { - int len = Mathf.Min(startIndex + count, vertices.Count); - int colorCount = value.Length; - int k = 0; - for (int i = startIndex; i < len; i++) - { - Color32 c = value[(k++) % colorCount]; - colors[i] = c; - if (c.a != 255) - _alphaInVertexColor = true; - } - } - - /// - /// - /// - /// - /// - /// - public void AddTriangle(int idx0, int idx1, int idx2) - { - triangles.Add(idx0); - triangles.Add(idx1); - triangles.Add(idx2); - } - - /// - /// - /// - /// - /// - public void AddTriangles(int[] idxList, int startVertexIndex = 0) - { - if (startVertexIndex != 0) - { - if (startVertexIndex < 0) - startVertexIndex = vertices.Count + startVertexIndex; - - int cnt = idxList.Length; - for (int i = 0; i < cnt; i++) - triangles.Add(idxList[i] + startVertexIndex); - } - else - triangles.AddRange(idxList); - } - - /// - /// - /// - /// - public void AddTriangles(int startVertexIndex = 0) - { - int cnt = vertices.Count; - if (startVertexIndex < 0) - startVertexIndex = cnt + startVertexIndex; - - for (int i = startVertexIndex; i < cnt; i += 4) - { - triangles.Add(i); - triangles.Add(i + 1); - triangles.Add(i + 2); - - triangles.Add(i + 2); - triangles.Add(i + 3); - triangles.Add(i); - } - } - - /// - /// - /// - /// - /// - public Vector3 GetPosition(int index) - { - if (index < 0) - index = vertices.Count + index; - - Vector3 vec = vertices[index]; - vec.y = -vec.y; - return vec; - } - - /// - /// - /// - /// - /// - /// - public Vector2 GetUVAtPosition(Vector2 position, bool usePercent) - { - if (usePercent) - { - return new Vector2(Mathf.Lerp(uvRect.xMin, uvRect.xMax, position.x), - Mathf.Lerp(uvRect.yMax, uvRect.yMin, position.y)); - } - else - return new Vector2(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), - Mathf.Lerp(uvRect.yMax, uvRect.yMin, (position.y - contentRect.yMin) / contentRect.height)); - } - - /// - /// - /// - /// - public void Append(VertexBuffer vb) - { - int len = vertices.Count; - vertices.AddRange(vb.vertices); - uvs.AddRange(vb.uvs); - uvs2.AddRange(vb.uvs2); - colors.AddRange(vb.colors); - if (len != 0) - { - int len1 = vb.triangles.Count; - for (int i = 0; i < len1; i++) - triangles.Add(vb.triangles[i] + len); - } - else - triangles.AddRange(vb.triangles); - - if (vb._alphaInVertexColor) - _alphaInVertexColor = true; - } - - /// - /// - /// - /// - public void Insert(VertexBuffer vb) - { - vertices.InsertRange(0, vb.vertices); - uvs.InsertRange(0, vb.uvs); - uvs2.InsertRange(0, vb.uvs2); - colors.InsertRange(0, vb.colors); - int len = triangles.Count; - if (len != 0) - { - int len1 = vb.vertices.Count; - for (int i = 0; i < len; i++) - triangles[i] += len1; - } - triangles.InsertRange(0, vb.triangles); - - if (vb._alphaInVertexColor) - _alphaInVertexColor = true; - } - } -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public sealed class VertexBuffer + { + /// + /// + /// + public Rect contentRect; + + /// + /// + /// + public Rect uvRect; + + /// + /// + /// + public Color32 vertexColor; + + /// + /// + /// + public Vector2 textureSize; + + /// + /// + /// + public readonly List vertices; + + /// + /// + /// + public readonly List colors; + + /// + /// + /// + public readonly List uvs; + + /// + /// + /// + public readonly List uvs2; + + /// + /// + /// + public readonly List triangles; + + static public Vector2[] NormalizedUV = new Vector2[] { + new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) }; + + static public Vector2[] NormalizedPosition = new Vector2[] { + new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1) }; + + internal bool _alphaInVertexColor; + internal bool _isArbitraryQuad; + + static Stack _pool = new Stack(); + + /// + /// + /// + /// + public static VertexBuffer Begin() + { + if (_pool.Count > 0) + { + VertexBuffer inst = _pool.Pop(); + inst.Clear(); + return inst; + } + else + return new VertexBuffer(); + } + + /// + /// + /// + /// + public static VertexBuffer Begin(VertexBuffer source) + { + VertexBuffer vb = Begin(); + vb.contentRect = source.contentRect; + vb.uvRect = source.uvRect; + vb.vertexColor = source.vertexColor; + vb.textureSize = source.textureSize; + + return vb; + } + + private VertexBuffer() + { + vertices = new List(); + colors = new List(); + uvs = new List(); + uvs2 = new List(); + triangles = new List(); + } + + /// + /// + /// + public void End() + { + _pool.Push(this); + } + + /// + /// + /// + public void Clear() + { + vertices.Clear(); + colors.Clear(); + uvs.Clear(); + uvs2.Clear(); + triangles.Clear(); + + _isArbitraryQuad = false; + _alphaInVertexColor = false; + } + + /// + /// + /// + public int currentVertCount + { + get + { + return vertices.Count; + } + } + + /// + /// + /// + /// + public void AddVert(Vector3 position) + { + position.y = -position.y; + vertices.Add(position); + colors.Add(vertexColor); + if (vertexColor.a != 255) + _alphaInVertexColor = true; + uvs.Add(new Vector2( + Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, (-position.y - contentRect.yMin) / contentRect.height))); + } + + /// + /// + /// + /// + /// + public void AddVert(Vector3 position, Color32 color) + { + position.y = -position.y; + vertices.Add(position); + colors.Add(color); + if (color.a != 255) + _alphaInVertexColor = true; + uvs.Add(new Vector2( + Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, (-position.y - contentRect.yMin) / contentRect.height))); + } + + /// + /// + /// + /// + /// + /// + public void AddVert(Vector3 position, Color32 color, Vector2 uv) + { + position.y = -position.y; + vertices.Add(position); + uvs.Add(new Vector2(uv.x, uv.y)); + colors.Add(color); + if (color.a != 255) + _alphaInVertexColor = true; + } + + /// + /// + /// 1---2 + /// | / | + /// 0---3 + /// + /// + public void AddQuad(Rect vertRect) + { + AddVert(new Vector3(vertRect.xMin, vertRect.yMax, 0f)); + AddVert(new Vector3(vertRect.xMin, vertRect.yMin, 0f)); + AddVert(new Vector3(vertRect.xMax, vertRect.yMin, 0f)); + AddVert(new Vector3(vertRect.xMax, vertRect.yMax, 0f)); + } + + /// + /// + /// + /// + /// + public void AddQuad(Rect vertRect, Color32 color) + { + AddVert(new Vector3(vertRect.xMin, vertRect.yMax, 0f), color); + AddVert(new Vector3(vertRect.xMin, vertRect.yMin, 0f), color); + AddVert(new Vector3(vertRect.xMax, vertRect.yMin, 0f), color); + AddVert(new Vector3(vertRect.xMax, vertRect.yMax, 0f), color); + } + + /// + /// + /// + /// + /// + /// + public void AddQuad(Rect vertRect, Color32 color, Rect uvRect) + { + vertices.Add(new Vector3(vertRect.xMin, -vertRect.yMax, 0f)); + vertices.Add(new Vector3(vertRect.xMin, -vertRect.yMin, 0f)); + vertices.Add(new Vector3(vertRect.xMax, -vertRect.yMin, 0f)); + vertices.Add(new Vector3(vertRect.xMax, -vertRect.yMax, 0f)); + + uvs.Add(new Vector2(uvRect.xMin, uvRect.yMin)); + uvs.Add(new Vector2(uvRect.xMin, uvRect.yMax)); + uvs.Add(new Vector2(uvRect.xMax, uvRect.yMax)); + uvs.Add(new Vector2(uvRect.xMax, uvRect.yMin)); + + colors.Add(color); + colors.Add(color); + colors.Add(color); + colors.Add(color); + + if (color.a != 255) + _alphaInVertexColor = true; + } + + static List helperV4List = new List(4) { Vector4.zero, Vector4.zero, Vector4.zero, Vector4.zero }; + internal List FixUVForArbitraryQuad() + { + //ref1 http://www.reedbeta.com/blog/quadrilateral-interpolation-part-1/ + //ref2 https://bitlush.com/blog/arbitrary-quadrilaterals-in-opengl-es-2-0 + + Vector4 qq = Vector4.one; + Vector2 a = vertices[2] - vertices[0]; + Vector2 b = vertices[1] - vertices[3]; + Vector2 c = vertices[0] - vertices[3]; + + float cross = a.x * b.y - a.y * b.x; + if (cross != 0) + { + float s = (a.x * c.y - a.y * c.x) / cross; + if (s > 0 && s < 1) + { + float t = (b.x * c.y - b.y * c.x) / cross; + if (t > 0 && t < 1) + { + qq.x = 1 / (1 - t); + qq.y = 1 / s; + qq.z = 1 / t; + qq.w = 1 / (1 - s); + } + } + } + + for (int i = 0; i < 4; i++) + { + Vector4 v = uvs[i]; + float q = qq[i]; + v.x *= q; + v.y *= q; + v.w = q; + helperV4List[i] = v; + } + + return helperV4List; + } + + /// + /// + /// + /// + /// + /// + public void RepeatColors(Color32[] value, int startIndex, int count) + { + int len = Mathf.Min(startIndex + count, vertices.Count); + int colorCount = value.Length; + int k = 0; + for (int i = startIndex; i < len; i++) + { + Color32 c = value[(k++) % colorCount]; + colors[i] = c; + if (c.a != 255) + _alphaInVertexColor = true; + } + } + + /// + /// + /// + /// + /// + /// + public void AddTriangle(int idx0, int idx1, int idx2) + { + triangles.Add(idx0); + triangles.Add(idx1); + triangles.Add(idx2); + } + + /// + /// + /// + /// + /// + public void AddTriangles(int[] idxList, int startVertexIndex = 0) + { + if (startVertexIndex != 0) + { + if (startVertexIndex < 0) + startVertexIndex = vertices.Count + startVertexIndex; + + int cnt = idxList.Length; + for (int i = 0; i < cnt; i++) + triangles.Add(idxList[i] + startVertexIndex); + } + else + triangles.AddRange(idxList); + } + + /// + /// + /// + /// + public void AddTriangles(int startVertexIndex = 0) + { + int cnt = vertices.Count; + if (startVertexIndex < 0) + startVertexIndex = cnt + startVertexIndex; + + for (int i = startVertexIndex; i < cnt; i += 4) + { + triangles.Add(i); + triangles.Add(i + 1); + triangles.Add(i + 2); + + triangles.Add(i + 2); + triangles.Add(i + 3); + triangles.Add(i); + } + } + + /// + /// + /// + /// + /// + public Vector3 GetPosition(int index) + { + if (index < 0) + index = vertices.Count + index; + + Vector3 vec = vertices[index]; + vec.y = -vec.y; + return vec; + } + + /// + /// + /// + /// + /// + /// + public Vector2 GetUVAtPosition(Vector2 position, bool usePercent) + { + if (usePercent) + { + return new Vector2(Mathf.Lerp(uvRect.xMin, uvRect.xMax, position.x), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, position.y)); + } + else + return new Vector2(Mathf.Lerp(uvRect.xMin, uvRect.xMax, (position.x - contentRect.xMin) / contentRect.width), + Mathf.Lerp(uvRect.yMax, uvRect.yMin, (position.y - contentRect.yMin) / contentRect.height)); + } + + /// + /// + /// + /// + public void Append(VertexBuffer vb) + { + int len = vertices.Count; + vertices.AddRange(vb.vertices); + uvs.AddRange(vb.uvs); + uvs2.AddRange(vb.uvs2); + colors.AddRange(vb.colors); + if (len != 0) + { + int len1 = vb.triangles.Count; + for (int i = 0; i < len1; i++) + triangles.Add(vb.triangles[i] + len); + } + else + triangles.AddRange(vb.triangles); + + if (vb._alphaInVertexColor) + _alphaInVertexColor = true; + } + + /// + /// + /// + /// + public void Insert(VertexBuffer vb) + { + vertices.InsertRange(0, vb.vertices); + uvs.InsertRange(0, vb.uvs); + uvs2.InsertRange(0, vb.uvs2); + colors.InsertRange(0, vb.colors); + int len = triangles.Count; + if (len != 0) + { + int len1 = vb.vertices.Count; + for (int i = 0; i < len; i++) + triangles[i] += len1; + } + triangles.InsertRange(0, vb.triangles); + + if (vb._alphaInVertexColor) + _alphaInVertexColor = true; + } + } +} diff --git a/Assets/Scripts/Core/Mesh/VertexBuffer.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/VertexBuffer.cs.meta similarity index 100% rename from Assets/Scripts/Core/Mesh/VertexBuffer.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Mesh/VertexBuffer.cs.meta diff --git a/Assets/Scripts/Core/MovieClip.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MovieClip.cs similarity index 96% rename from Assets/Scripts/Core/MovieClip.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MovieClip.cs index fd4d1e8b..3a571e20 100644 --- a/Assets/Scripts/Core/MovieClip.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MovieClip.cs @@ -1,414 +1,414 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class MovieClip : Image - { - /// - /// - /// - public class Frame - { - public NTexture texture; - public float addDelay; - } - - /// - /// - /// - public float interval; - - /// - /// - /// - public bool swing; - - /// - /// - /// - public float repeatDelay; - - /// - /// - /// - public float timeScale; - - /// - /// Whether to ignore Unity time scale. - /// - public bool ignoreEngineTimeScale; - - Frame[] _frames; - int _frameCount; - int _frame; - bool _playing; - int _start; - int _end; - int _times; - int _endAt; - int _status; //0-none, 1-next loop, 2-ending, 3-ended - - float _frameElapsed; //当前帧延迟 - bool _reversed; - int _repeatedCount; - TimerCallback _timerDelegate; - - EventListener _onPlayEnd; - - /// - /// - /// - public MovieClip() - { - interval = 0.1f; - _playing = true; - _timerDelegate = OnTimer; - timeScale = 1; - ignoreEngineTimeScale = false; - - if (Application.isPlaying) - { - onAddedToStage.Add(OnAddedToStage); - onRemovedFromStage.Add(OnRemoveFromStage); - } - - SetPlaySettings(); - } - - /// - /// - /// - public EventListener onPlayEnd - { - get { return _onPlayEnd ?? (_onPlayEnd = new EventListener(this, "onPlayEnd")); } - } - - /// - /// - /// - public Frame[] frames - { - get - { - return _frames; - } - set - { - _frames = value; - _scale9Grid = null; - _scaleByTile = false; - - if (_frames == null) - { - _frameCount = 0; - graphics.texture = null; - CheckTimer(); - return; - } - _frameCount = frames.Length; - - if (_end == -1 || _end > _frameCount - 1) - _end = _frameCount - 1; - if (_endAt == -1 || _endAt > _frameCount - 1) - _endAt = _frameCount - 1; - - if (_frame < 0 || _frame > _frameCount - 1) - _frame = _frameCount - 1; - - InvalidateBatchingState(); - - _frameElapsed = 0; - _repeatedCount = 0; - _reversed = false; - - DrawFrame(); - CheckTimer(); - } - } - - /// - /// - /// - public bool playing - { - get { return _playing; } - set - { - if (_playing != value) - { - _playing = value; - CheckTimer(); - } - } - } - - /// - /// - /// - public int frame - { - get { return _frame; } - set - { - if (_frame != value) - { - if (_frames != null && value >= _frameCount) - value = _frameCount - 1; - - _frame = value; - _frameElapsed = 0; - DrawFrame(); - } - } - } - - /// - /// - /// - public void Rewind() - { - _frame = 0; - _frameElapsed = 0; - _reversed = false; - _repeatedCount = 0; - DrawFrame(); - } - - /// - /// - /// - /// - public void SyncStatus(MovieClip anotherMc) - { - _frame = anotherMc._frame; - _frameElapsed = anotherMc._frameElapsed; - _reversed = anotherMc._reversed; - _repeatedCount = anotherMc._repeatedCount; - DrawFrame(); - } - - /// - /// - /// - /// - public void Advance(float time) - { - int beginFrame = _frame; - bool beginReversed = _reversed; - float backupTime = time; - while (true) - { - float tt = interval + _frames[_frame].addDelay; - if (_frame == 0 && _repeatedCount > 0) - tt += repeatDelay; - if (time < tt) - { - _frameElapsed = 0; - break; - } - - time -= tt; - - if (swing) - { - if (_reversed) - { - _frame--; - if (_frame <= 0) - { - _frame = 0; - _repeatedCount++; - _reversed = !_reversed; - } - } - else - { - _frame++; - if (_frame > _frameCount - 1) - { - _frame = Mathf.Max(0, _frameCount - 2); - _repeatedCount++; - _reversed = !_reversed; - } - } - } - else - { - _frame++; - if (_frame > _frameCount - 1) - { - _frame = 0; - _repeatedCount++; - } - } - - if (_frame == beginFrame && _reversed == beginReversed) //走了一轮了 - { - float roundTime = backupTime - time; //这就是一轮需要的时间 - time -= Mathf.FloorToInt(time / roundTime) * roundTime; //跳过 - } - } - - DrawFrame(); - } - - /// - /// - /// - public void SetPlaySettings() - { - SetPlaySettings(0, -1, 0, -1); - } - - /// - /// 从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) - /// - /// - /// - /// - /// - public void SetPlaySettings(int start, int end, int times, int endAt) - { - _start = start; - _end = end; - if (_end == -1 || _end > _frameCount - 1) - _end = _frameCount - 1; - _times = times; - _endAt = endAt; - if (_endAt == -1) - _endAt = _end; - _status = 0; - this.frame = start; - } - - void OnAddedToStage() - { - if (_playing && _frameCount > 0) - Timers.inst.AddUpdate(_timerDelegate); - } - - void OnRemoveFromStage() - { - Timers.inst.Remove(_timerDelegate); - } - - void CheckTimer() - { - if (!Application.isPlaying) - return; - - if (_playing && _frameCount > 0 && this.stage != null) - Timers.inst.AddUpdate(_timerDelegate); - else - Timers.inst.Remove(_timerDelegate); - } - - void OnTimer(object param) - { - if (!_playing || _frameCount == 0 || _status == 3) - return; - - float dt; - if (ignoreEngineTimeScale) - { - dt = Time.unscaledDeltaTime; - if (dt > 0.1f) - dt = 0.1f; - } - else - dt = Time.deltaTime; - if (timeScale != 1) - dt *= timeScale; - - _frameElapsed += dt; - float tt = interval + _frames[_frame].addDelay; - if (_frame == 0 && _repeatedCount > 0) - tt += repeatDelay; - if (_frameElapsed < tt) - return; - - _frameElapsed -= tt; - if (_frameElapsed > interval) - _frameElapsed = interval; - - if (swing) - { - if (_reversed) - { - _frame--; - if (_frame <= 0) - { - _frame = 0; - _repeatedCount++; - _reversed = !_reversed; - } - } - else - { - _frame++; - if (_frame > _frameCount - 1) - { - _frame = Mathf.Max(0, _frameCount - 2); - _repeatedCount++; - _reversed = !_reversed; - } - } - } - else - { - _frame++; - if (_frame > _frameCount - 1) - { - _frame = 0; - _repeatedCount++; - } - } - - if (_status == 1) //new loop - { - _frame = _start; - _frameElapsed = 0; - _status = 0; - DrawFrame(); - } - else if (_status == 2) //ending - { - _frame = _endAt; - _frameElapsed = 0; - _status = 3; //ended - DrawFrame(); - - DispatchEvent("onPlayEnd", null); - } - else - { - DrawFrame(); - if (_frame == _end) - { - if (_times > 0) - { - _times--; - if (_times == 0) - _status = 2; //ending - else - _status = 1; //new loop - } - else if (_start != 0) - _status = 1; //new loop - } - } - } - - void DrawFrame() - { - if (_frameCount > 0) - { - Frame frame = _frames[_frame]; - graphics.texture = frame.texture; - } - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class MovieClip : Image + { + /// + /// + /// + public class Frame + { + public NTexture texture; + public float addDelay; + } + + /// + /// + /// + public float interval; + + /// + /// + /// + public bool swing; + + /// + /// + /// + public float repeatDelay; + + /// + /// + /// + public float timeScale; + + /// + /// Whether to ignore Unity time scale. + /// + public bool ignoreEngineTimeScale; + + Frame[] _frames; + int _frameCount; + int _frame; + bool _playing; + int _start; + int _end; + int _times; + int _endAt; + int _status; //0-none, 1-next loop, 2-ending, 3-ended + + float _frameElapsed; //当前帧延迟 + bool _reversed; + int _repeatedCount; + TimerCallback _timerDelegate; + + EventListener _onPlayEnd; + + /// + /// + /// + public MovieClip() + { + interval = 0.1f; + _playing = true; + _timerDelegate = OnTimer; + timeScale = 1; + ignoreEngineTimeScale = false; + + if (Application.isPlaying) + { + onAddedToStage.Add(OnAddedToStage); + onRemovedFromStage.Add(OnRemoveFromStage); + } + + SetPlaySettings(); + } + + /// + /// + /// + public EventListener onPlayEnd + { + get { return _onPlayEnd ?? (_onPlayEnd = new EventListener(this, "onPlayEnd")); } + } + + /// + /// + /// + public Frame[] frames + { + get + { + return _frames; + } + set + { + _frames = value; + _scale9Grid = null; + _scaleByTile = false; + + if (_frames == null) + { + _frameCount = 0; + graphics.texture = null; + CheckTimer(); + return; + } + _frameCount = frames.Length; + + if (_end == -1 || _end > _frameCount - 1) + _end = _frameCount - 1; + if (_endAt == -1 || _endAt > _frameCount - 1) + _endAt = _frameCount - 1; + + if (_frame < 0 || _frame > _frameCount - 1) + _frame = _frameCount - 1; + + InvalidateBatchingState(); + + _frameElapsed = 0; + _repeatedCount = 0; + _reversed = false; + + DrawFrame(); + CheckTimer(); + } + } + + /// + /// + /// + public bool playing + { + get { return _playing; } + set + { + if (_playing != value) + { + _playing = value; + CheckTimer(); + } + } + } + + /// + /// + /// + public int frame + { + get { return _frame; } + set + { + if (_frame != value) + { + if (_frames != null && value >= _frameCount) + value = _frameCount - 1; + + _frame = value; + _frameElapsed = 0; + DrawFrame(); + } + } + } + + /// + /// + /// + public void Rewind() + { + _frame = 0; + _frameElapsed = 0; + _reversed = false; + _repeatedCount = 0; + DrawFrame(); + } + + /// + /// + /// + /// + public void SyncStatus(MovieClip anotherMc) + { + _frame = anotherMc._frame; + _frameElapsed = anotherMc._frameElapsed; + _reversed = anotherMc._reversed; + _repeatedCount = anotherMc._repeatedCount; + DrawFrame(); + } + + /// + /// + /// + /// + public void Advance(float time) + { + int beginFrame = _frame; + bool beginReversed = _reversed; + float backupTime = time; + while (true) + { + float tt = interval + _frames[_frame].addDelay; + if (_frame == 0 && _repeatedCount > 0) + tt += repeatDelay; + if (time < tt) + { + _frameElapsed = 0; + break; + } + + time -= tt; + + if (swing) + { + if (_reversed) + { + _frame--; + if (_frame <= 0) + { + _frame = 0; + _repeatedCount++; + _reversed = !_reversed; + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = Mathf.Max(0, _frameCount - 2); + _repeatedCount++; + _reversed = !_reversed; + } + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = 0; + _repeatedCount++; + } + } + + if (_frame == beginFrame && _reversed == beginReversed) //走了一轮了 + { + float roundTime = backupTime - time; //这就是一轮需要的时间 + time -= Mathf.FloorToInt(time / roundTime) * roundTime; //跳过 + } + } + + DrawFrame(); + } + + /// + /// + /// + public void SetPlaySettings() + { + SetPlaySettings(0, -1, 0, -1); + } + + /// + /// 从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) + /// + /// + /// + /// + /// + public void SetPlaySettings(int start, int end, int times, int endAt) + { + _start = start; + _end = end; + if (_end == -1 || _end > _frameCount - 1) + _end = _frameCount - 1; + _times = times; + _endAt = endAt; + if (_endAt == -1) + _endAt = _end; + _status = 0; + this.frame = start; + } + + void OnAddedToStage() + { + if (_playing && _frameCount > 0) + Timers.inst.AddUpdate(_timerDelegate); + } + + void OnRemoveFromStage() + { + Timers.inst.Remove(_timerDelegate); + } + + void CheckTimer() + { + if (!Application.isPlaying) + return; + + if (_playing && _frameCount > 0 && this.stage != null) + Timers.inst.AddUpdate(_timerDelegate); + else + Timers.inst.Remove(_timerDelegate); + } + + void OnTimer(object param) + { + if (!_playing || _frameCount == 0 || _status == 3) + return; + + float dt; + if (ignoreEngineTimeScale) + { + dt = Time.unscaledDeltaTime; + if (dt > 0.1f) + dt = 0.1f; + } + else + dt = Time.deltaTime; + if (timeScale != 1) + dt *= timeScale; + + _frameElapsed += dt; + float tt = interval + _frames[_frame].addDelay; + if (_frame == 0 && _repeatedCount > 0) + tt += repeatDelay; + if (_frameElapsed < tt) + return; + + _frameElapsed -= tt; + if (_frameElapsed > interval) + _frameElapsed = interval; + + if (swing) + { + if (_reversed) + { + _frame--; + if (_frame <= 0) + { + _frame = 0; + _repeatedCount++; + _reversed = !_reversed; + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = Mathf.Max(0, _frameCount - 2); + _repeatedCount++; + _reversed = !_reversed; + } + } + } + else + { + _frame++; + if (_frame > _frameCount - 1) + { + _frame = 0; + _repeatedCount++; + } + } + + if (_status == 1) //new loop + { + _frame = _start; + _frameElapsed = 0; + _status = 0; + DrawFrame(); + } + else if (_status == 2) //ending + { + _frame = _endAt; + _frameElapsed = 0; + _status = 3; //ended + DrawFrame(); + + DispatchEvent("onPlayEnd", null); + } + else + { + DrawFrame(); + if (_frame == _end) + { + if (_times > 0) + { + _times--; + if (_times == 0) + _status = 2; //ending + else + _status = 1; //new loop + } + else if (_start != 0) + _status = 1; //new loop + } + } + } + + void DrawFrame() + { + if (_frameCount > 0) + { + Frame frame = _frames[_frame]; + graphics.texture = frame.texture; + } + } + } +} diff --git a/Assets/Scripts/Core/MovieClip.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MovieClip.cs.meta similarity index 100% rename from Assets/Scripts/Core/MovieClip.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/MovieClip.cs.meta diff --git a/Assets/Scripts/Core/NAudioClip.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NAudioClip.cs similarity index 96% rename from Assets/Scripts/Core/NAudioClip.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NAudioClip.cs index f98e1b61..1f712aa6 100644 --- a/Assets/Scripts/Core/NAudioClip.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NAudioClip.cs @@ -1,67 +1,67 @@ -using System; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class NAudioClip - { - public static Action CustomDestroyMethod; - - /// - /// - /// - public DestroyMethod destroyMethod; - - /// - /// - /// - public AudioClip nativeClip; - - /// - /// - /// - /// - public NAudioClip(AudioClip audioClip) - { - nativeClip = audioClip; - } - - /// - /// - /// - public void Unload() - { - if (nativeClip == null) - return; - - if (destroyMethod == DestroyMethod.Unload) - Resources.UnloadAsset(nativeClip); - else if (destroyMethod == DestroyMethod.Destroy) - UnityEngine.Object.DestroyImmediate(nativeClip, true); - else if (destroyMethod == DestroyMethod.Custom) - { - if (CustomDestroyMethod == null) - Debug.LogWarning("NAudioClip.CustomDestroyMethod must be set to handle DestroyMethod.Custom"); - else - CustomDestroyMethod(nativeClip); - } - - nativeClip = null; - } - - /// - /// - /// - /// - public void Reload(AudioClip audioClip) - { - if (nativeClip != null && nativeClip != audioClip) - Unload(); - - nativeClip = audioClip; - } - } -} +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class NAudioClip + { + public static Action CustomDestroyMethod; + + /// + /// + /// + public DestroyMethod destroyMethod; + + /// + /// + /// + public AudioClip nativeClip; + + /// + /// + /// + /// + public NAudioClip(AudioClip audioClip) + { + nativeClip = audioClip; + } + + /// + /// + /// + public void Unload() + { + if (nativeClip == null) + return; + + if (destroyMethod == DestroyMethod.Unload) + Resources.UnloadAsset(nativeClip); + else if (destroyMethod == DestroyMethod.Destroy) + UnityEngine.Object.DestroyImmediate(nativeClip, true); + else if (destroyMethod == DestroyMethod.Custom) + { + if (CustomDestroyMethod == null) + Debug.LogWarning("NAudioClip.CustomDestroyMethod must be set to handle DestroyMethod.Custom"); + else + CustomDestroyMethod(nativeClip); + } + + nativeClip = null; + } + + /// + /// + /// + /// + public void Reload(AudioClip audioClip) + { + if (nativeClip != null && nativeClip != audioClip) + Unload(); + + nativeClip = audioClip; + } + } +} diff --git a/Assets/Scripts/Core/NAudioClip.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NAudioClip.cs.meta similarity index 100% rename from Assets/Scripts/Core/NAudioClip.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NAudioClip.cs.meta diff --git a/Assets/Scripts/Core/NGraphics.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NGraphics.cs similarity index 96% rename from Assets/Scripts/Core/NGraphics.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NGraphics.cs index ca692754..8366dfe1 100644 --- a/Assets/Scripts/Core/NGraphics.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NGraphics.cs @@ -1,842 +1,842 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; -using Object = UnityEngine.Object; - -namespace FairyGUI -{ - /// - /// - /// - public class NGraphics : IMeshFactory - { - /// - /// - /// - public GameObject gameObject { get; private set; } - - /// - /// - /// - public MeshFilter meshFilter { get; private set; } - - /// - /// - /// - public MeshRenderer meshRenderer { get; private set; } - - /// - /// - /// - public Mesh mesh { get; private set; } - - /// - /// - /// - public BlendMode blendMode; - - /// - /// 不参与剪裁 - /// - public bool dontClip; - - /// - /// 当Mesh更新时触发 - /// - public event Action meshModifier; - - NTexture _texture; - string _shader; - Material _material; - int _customMatarial; //0-none, 1-common, 2-support internal mask, 128-owns material - MaterialManager _manager; - string[] _shaderKeywords; - int _materialFlags; - IMeshFactory _meshFactory; - - float _alpha; - Color _color; - bool _meshDirty; - Rect _contentRect; - FlipType _flip; - - public class VertexMatrix - { - public Vector3 cameraPos; - public Matrix4x4 matrix; - } - VertexMatrix _vertexMatrix; - - bool hasAlphaBackup; - List _alphaBackup; //透明度改变需要通过修改顶点颜色实现,但顶点颜色本身可能就带有透明度,所以这里要有一个备份 - - internal int _maskFlag; - StencilEraser _stencilEraser; - -#if !UNITY_5_6_OR_NEWER - Color32[] _colors; -#endif - - MaterialPropertyBlock _propertyBlock; - bool _blockUpdated; - - /// - /// - /// - /// - public NGraphics(GameObject gameObject) - { - this.gameObject = gameObject; - - _alpha = 1f; - _shader = ShaderConfig.imageShader; - _color = Color.white; - _meshFactory = this; - - meshFilter = gameObject.AddComponent(); - meshRenderer = gameObject.AddComponent(); - meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; - meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; - meshRenderer.receiveShadows = false; - - mesh = new Mesh(); - mesh.name = gameObject.name; - mesh.MarkDynamic(); - - meshFilter.mesh = mesh; - - meshFilter.hideFlags = DisplayObject.hideFlags; - meshRenderer.hideFlags = DisplayObject.hideFlags; - mesh.hideFlags = DisplayObject.hideFlags; - - Stats.LatestGraphicsCreation++; - } - - /// - /// - /// - public IMeshFactory meshFactory - { - get { return _meshFactory; } - set - { - if (_meshFactory != value) - { - _meshFactory = value; - _meshDirty = true; - } - } - } - - /// - /// - /// - /// - /// - public T GetMeshFactory() where T : IMeshFactory, new() - { - if (!(_meshFactory is T)) - { - _meshFactory = new T(); - _meshDirty = true; - } - return (T)_meshFactory; - } - - /// - /// - /// - public Rect contentRect - { - get { return _contentRect; } - set - { - _contentRect = value; - _meshDirty = true; - } - } - - /// - /// - /// - public FlipType flip - { - get { return _flip; } - set - { - if (_flip != value) - { - _flip = value; - _meshDirty = true; - } - } - } - - /// - /// - /// - public NTexture texture - { - get { return _texture; } - set - { - if (_texture != value) - { - if (value != null) - value.AddRef(); - if (_texture != null) - _texture.ReleaseRef(); - - _texture = value; - if (_customMatarial != 0 && _material != null) - _material.mainTexture = _texture != null ? _texture.nativeTexture : null; - _meshDirty = true; - UpdateManager(); - } - } - } - - /// - /// - /// - public string shader - { - get { return _shader; } - set - { - _shader = value; - UpdateManager(); - } - } - - /// - /// - /// - /// - /// - public void SetShaderAndTexture(string shader, NTexture texture) - { - _shader = shader; - if (_texture != texture) - this.texture = texture; - else - UpdateManager(); - } - - /// - /// - /// - public Material material - { - get - { - if (_customMatarial == 0 && _material == null && _manager != null) - _material = _manager.GetMaterial(_materialFlags, blendMode, 0); - return _material; - } - set - { - if ((_customMatarial & 128) != 0 && _material != null) - Object.DestroyImmediate(_material); - - _material = value; - if (_material != null) - { - _customMatarial = 1; - if (_material.HasProperty(ShaderConfig.ID_Stencil) || _material.HasProperty(ShaderConfig.ID_ClipBox)) - _customMatarial |= 2; - - meshRenderer.sharedMaterial = _material; - if (_texture != null) - _material.mainTexture = _texture.nativeTexture; - } - else - { - _customMatarial = 0; - meshRenderer.sharedMaterial = null; - } - } - } - - /// - /// Same as material property except that ownership is transferred to this object. - /// - /// - public void SetMaterial(Material material) - { - this.material = material; - _customMatarial |= 128; - } - - /// - /// - /// - public string[] materialKeywords - { - get { return _shaderKeywords; } - set - { - _shaderKeywords = value; - UpdateMaterialFlags(); - } - } - - /// - /// - /// - /// - /// - public void ToggleKeyword(string keyword, bool enabled) - { - if (enabled) - { - if (_shaderKeywords == null) - { - _shaderKeywords = new string[] { keyword }; - UpdateMaterialFlags(); - } - else if (Array.IndexOf(_shaderKeywords, keyword) == -1) - { - Array.Resize(ref _shaderKeywords, _shaderKeywords.Length + 1); - _shaderKeywords[_shaderKeywords.Length - 1] = keyword; - UpdateMaterialFlags(); - } - } - else - { - if (_shaderKeywords != null) - { - int i = Array.IndexOf(_shaderKeywords, keyword); - if (i != -1) - { - _shaderKeywords[i] = null; - UpdateMaterialFlags(); - } - } - } - } - - void UpdateManager() - { - if (_texture != null) - _manager = _texture.GetMaterialManager(_shader); - else - _manager = null; - UpdateMaterialFlags(); - } - - void UpdateMaterialFlags() - { - if (_customMatarial != 0) - { - if (material != null) - material.shaderKeywords = _shaderKeywords; - } - else if (_shaderKeywords != null && _manager != null) - _materialFlags = _manager.GetFlagsByKeywords(_shaderKeywords); - else - _materialFlags = 0; - } - - /// - /// - /// - public bool enabled - { - get { return meshRenderer.enabled; } - set { meshRenderer.enabled = value; } - } - - /// - /// - /// - public int sortingOrder - { - get { return meshRenderer.sortingOrder; } - set { meshRenderer.sortingOrder = value; } - } - - /// - /// - /// - /// - internal void _SetStencilEraserOrder(int value) - { - _stencilEraser.meshRenderer.sortingOrder = value; - } - - /// - /// - /// - /// - public Color color - { - get { return _color; } - set { _color = value; } - } - - /// - /// - /// - public void Tint() - { - if (_meshDirty) - return; - - int vertCount = mesh.vertexCount; - if (vertCount == 0) - return; - -#if !UNITY_5_6_OR_NEWER - Color32[] colors = _colors; - if (colors == null) - colors = mesh.colors32; -#else - VertexBuffer vb = VertexBuffer.Begin(); - mesh.GetColors(vb.colors); - List colors = vb.colors; -#endif - for (int i = 0; i < vertCount; i++) - { - Color32 col = _color; - col.a = (byte)(_alpha * (hasAlphaBackup ? _alphaBackup[i] : (byte)255)); - colors[i] = col; - } - -#if !UNITY_5_6_OR_NEWER - mesh.colors32 = colors; -#else - mesh.SetColors(vb.colors); - vb.End(); -#endif - } - - void ChangeAlpha(float value) - { - _alpha = value; - - int vertCount = mesh.vertexCount; - if (vertCount == 0) - return; - -#if !UNITY_5_6_OR_NEWER - Color32[] colors = _colors; - if (colors == null) - colors = mesh.colors32; -#else - VertexBuffer vb = VertexBuffer.Begin(); - mesh.GetColors(vb.colors); - List colors = vb.colors; -#endif - for (int i = 0; i < vertCount; i++) - { - Color32 col = colors[i]; - col.a = (byte)(_alpha * (hasAlphaBackup ? _alphaBackup[i] : (byte)255)); - colors[i] = col; - } - -#if !UNITY_5_6_OR_NEWER - mesh.colors32 = colors; -#else - mesh.SetColors(vb.colors); - vb.End(); -#endif - } - - /// - /// - /// - public VertexMatrix vertexMatrix - { - get { return _vertexMatrix; } - set - { - _vertexMatrix = value; - _meshDirty = true; - } - } - - /// - /// - /// - /// - public MaterialPropertyBlock materialPropertyBlock - { - get - { - if (_propertyBlock == null) - _propertyBlock = new MaterialPropertyBlock(); - - _blockUpdated = true; - return _propertyBlock; - } - } - - /// - /// - /// - public void SetMeshDirty() - { - _meshDirty = true; - } - - /// - /// - /// - /// - public bool UpdateMesh() - { - if (_meshDirty) - { - UpdateMeshNow(); - return true; - } - else - return false; - } - - /// - /// - /// - public void Dispose() - { - if (mesh != null) - { - if (Application.isPlaying) - Object.Destroy(mesh); - else - Object.DestroyImmediate(mesh); - mesh = null; - } - if ((_customMatarial & 128) != 0 && _material != null) - Object.DestroyImmediate(_material); - - if (_texture != null) - { - _texture.ReleaseRef(); - _texture = null; - } - - _manager = null; - _material = null; - meshRenderer = null; - meshFilter = null; - _stencilEraser = null; - meshModifier = null; - } - - /// - /// - /// - /// - /// - /// - public void Update(UpdateContext context, float alpha, bool grayed) - { - Stats.GraphicsCount++; - - if (_meshDirty) - { - _alpha = alpha; - UpdateMeshNow(); - } - else if (_alpha != alpha) - ChangeAlpha(alpha); - - if (_propertyBlock != null && _blockUpdated) - { - meshRenderer.SetPropertyBlock(_propertyBlock); - _blockUpdated = false; - } - - if (_customMatarial != 0) - { - if ((_customMatarial & 2) != 0 && _material != null) - context.ApplyClippingProperties(_material, false); - } - else - { - if (_manager != null) - { - if (_maskFlag == 1) - { - _material = _manager.GetMaterial((int)MaterialFlags.AlphaMask | _materialFlags, BlendMode.Normal, context.clipInfo.clipId); - context.ApplyAlphaMaskProperties(_material, false); - } - else - { - int matFlags = _materialFlags; - if (grayed) - matFlags |= (int)MaterialFlags.Grayed; - - if (context.clipped) - { - if (context.stencilReferenceValue > 0) - matFlags |= (int)MaterialFlags.StencilTest; - if (context.rectMaskDepth > 0) - { - if (context.clipInfo.soft) - matFlags |= (int)MaterialFlags.SoftClipped; - else - matFlags |= (int)MaterialFlags.Clipped; - } - - _material = _manager.GetMaterial(matFlags, blendMode, context.clipInfo.clipId); - if (_manager.firstMaterialInFrame) - context.ApplyClippingProperties(_material, true); - } - else - _material = _manager.GetMaterial(matFlags, blendMode, 0); - } - } - else - _material = null; - - if (!Material.ReferenceEquals(_material, meshRenderer.sharedMaterial)) - meshRenderer.sharedMaterial = _material; - } - - if (_maskFlag != 0) - { - if (_maskFlag == 1) - _maskFlag = 2; - else - { - if (_stencilEraser != null) - _stencilEraser.enabled = false; - - _maskFlag = 0; - } - } - } - - internal void _PreUpdateMask(UpdateContext context, uint maskId) - { - //_maskFlag: 0-new mask, 1-active mask, 2-mask complete - if (_maskFlag == 0) - { - if (_stencilEraser == null) - { - _stencilEraser = new StencilEraser(gameObject.transform); - _stencilEraser.meshFilter.mesh = mesh; - } - else - _stencilEraser.enabled = true; - } - - _maskFlag = 1; - - if (_manager != null) - { - //这里使用maskId而不是clipInfo.clipId,是因为遮罩有两个用途,一个是写入遮罩,一个是擦除,两个不能用同一个材质 - Material mat = _manager.GetMaterial((int)MaterialFlags.AlphaMask | _materialFlags, BlendMode.Normal, maskId); - if (!Material.ReferenceEquals(mat, _stencilEraser.meshRenderer.sharedMaterial)) - _stencilEraser.meshRenderer.sharedMaterial = mat; - - context.ApplyAlphaMaskProperties(mat, true); - } - } - - void UpdateMeshNow() - { - _meshDirty = false; - - if (_texture == null || _meshFactory == null) - { - if (mesh.vertexCount > 0) - { - mesh.Clear(); - - if (meshModifier != null) - meshModifier(); - } - return; - } - - VertexBuffer vb = VertexBuffer.Begin(); - vb.contentRect = _contentRect; - vb.uvRect = _texture.uvRect; - if (_texture != null) - vb.textureSize = new Vector2(_texture.width, _texture.height); - else - vb.textureSize = new Vector2(0, 0); - if (_flip != FlipType.None) - { - if (_flip == FlipType.Horizontal || _flip == FlipType.Both) - { - float tmp = vb.uvRect.xMin; - vb.uvRect.xMin = vb.uvRect.xMax; - vb.uvRect.xMax = tmp; - } - if (_flip == FlipType.Vertical || _flip == FlipType.Both) - { - float tmp = vb.uvRect.yMin; - vb.uvRect.yMin = vb.uvRect.yMax; - vb.uvRect.yMax = tmp; - } - } - vb.vertexColor = _color; - _meshFactory.OnPopulateMesh(vb); - - int vertCount = vb.currentVertCount; - if (vertCount == 0) - { - if (mesh.vertexCount > 0) - { - mesh.Clear(); - - if (meshModifier != null) - meshModifier(); - } - vb.End(); - return; - } - - if (_texture.rotated) - { - float xMin = _texture.uvRect.xMin; - float yMin = _texture.uvRect.yMin; - float yMax = _texture.uvRect.yMax; - float tmp; - for (int i = 0; i < vertCount; i++) - { - Vector2 vec = vb.uvs[i]; - tmp = vec.y; - vec.y = yMin + vec.x - xMin; - vec.x = xMin + yMax - tmp; - vb.uvs[i] = vec; - } - } - - hasAlphaBackup = vb._alphaInVertexColor; - if (hasAlphaBackup) - { - if (_alphaBackup == null) - _alphaBackup = new List(); - else - _alphaBackup.Clear(); - for (int i = 0; i < vertCount; i++) - { - Color32 col = vb.colors[i]; - _alphaBackup.Add(col.a); - - col.a = (byte)(col.a * _alpha); - vb.colors[i] = col; - } - } - else if (_alpha != 1) - { - for (int i = 0; i < vertCount; i++) - { - Color32 col = vb.colors[i]; - col.a = (byte)(col.a * _alpha); - vb.colors[i] = col; - } - } - - if (_vertexMatrix != null) - { - Vector3 camPos = _vertexMatrix.cameraPos; - Vector3 center = new Vector3(camPos.x, camPos.y, 0); - center -= _vertexMatrix.matrix.MultiplyPoint(center); - for (int i = 0; i < vertCount; i++) - { - Vector3 pt = vb.vertices[i]; - pt = _vertexMatrix.matrix.MultiplyPoint(pt); - pt += center; - Vector3 vec = pt - camPos; - float lambda = -camPos.z / vec.z; - pt.x = camPos.x + lambda * vec.x; - pt.y = camPos.y + lambda * vec.y; - pt.z = 0; - - vb.vertices[i] = pt; - } - } - - mesh.Clear(); - -#if UNITY_5_2 || UNITY_5_3_OR_NEWER - mesh.SetVertices(vb.vertices); - if (vb._isArbitraryQuad) - mesh.SetUVs(0, vb.FixUVForArbitraryQuad()); - else - mesh.SetUVs(0, vb.uvs); - mesh.SetColors(vb.colors); - mesh.SetTriangles(vb.triangles, 0); - if (vb.uvs2.Count == vb.uvs.Count) - mesh.SetUVs(1, vb.uvs2); - -#if !UNITY_5_6_OR_NEWER - _colors = null; -#endif -#else - Vector3[] vertices = new Vector3[vertCount]; - Vector2[] uv = new Vector2[vertCount]; - _colors = new Color32[vertCount]; - int[] triangles = new int[vb.triangles.Count]; - - vb.vertices.CopyTo(vertices); - vb.uvs.CopyTo(uv); - vb.colors.CopyTo(_colors); - vb.triangles.CopyTo(triangles); - - mesh.vertices = vertices; - mesh.uv = uv; - mesh.triangles = triangles; - mesh.colors32 = _colors; - - if(vb.uvs2.Count==uv.Length) - { - uv = new Vector2[vertCount]; - vb.uvs2.CopyTo(uv); - mesh.uv2 = uv; - } -#endif - vb.End(); - - if (meshModifier != null) - meshModifier(); - } - - public void OnPopulateMesh(VertexBuffer vb) - { - Rect rect = texture.GetDrawRect(vb.contentRect); - - vb.AddQuad(rect, vb.vertexColor, vb.uvRect); - vb.AddTriangles(); - vb._isArbitraryQuad = _vertexMatrix != null; - } - - class StencilEraser - { - public GameObject gameObject; - public MeshFilter meshFilter; - public MeshRenderer meshRenderer; - - public StencilEraser(Transform parent) - { - gameObject = new GameObject("StencilEraser"); - gameObject.transform.SetParent(parent, false); - - meshFilter = gameObject.AddComponent(); - meshRenderer = gameObject.AddComponent(); - meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; - meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; - meshRenderer.receiveShadows = false; - - gameObject.layer = parent.gameObject.layer; - gameObject.hideFlags = parent.gameObject.hideFlags; - meshFilter.hideFlags = parent.gameObject.hideFlags; - meshRenderer.hideFlags = parent.gameObject.hideFlags; - } - - public bool enabled - { - get { return meshRenderer.enabled; } - set { meshRenderer.enabled = value; } - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; +using Object = UnityEngine.Object; + +namespace FairyGUI +{ + /// + /// + /// + public class NGraphics : IMeshFactory + { + /// + /// + /// + public GameObject gameObject { get; private set; } + + /// + /// + /// + public MeshFilter meshFilter { get; private set; } + + /// + /// + /// + public MeshRenderer meshRenderer { get; private set; } + + /// + /// + /// + public Mesh mesh { get; private set; } + + /// + /// + /// + public BlendMode blendMode; + + /// + /// 不参与剪裁 + /// + public bool dontClip; + + /// + /// 当Mesh更新时触发 + /// + public event Action meshModifier; + + NTexture _texture; + string _shader; + Material _material; + int _customMatarial; //0-none, 1-common, 2-support internal mask, 128-owns material + MaterialManager _manager; + string[] _shaderKeywords; + int _materialFlags; + IMeshFactory _meshFactory; + + float _alpha; + Color _color; + bool _meshDirty; + Rect _contentRect; + FlipType _flip; + + public class VertexMatrix + { + public Vector3 cameraPos; + public Matrix4x4 matrix; + } + VertexMatrix _vertexMatrix; + + bool hasAlphaBackup; + List _alphaBackup; //透明度改变需要通过修改顶点颜色实现,但顶点颜色本身可能就带有透明度,所以这里要有一个备份 + + internal int _maskFlag; + StencilEraser _stencilEraser; + +#if !UNITY_5_6_OR_NEWER + Color32[] _colors; +#endif + + MaterialPropertyBlock _propertyBlock; + bool _blockUpdated; + + /// + /// + /// + /// + public NGraphics(GameObject gameObject) + { + this.gameObject = gameObject; + + _alpha = 1f; + _shader = ShaderConfig.imageShader; + _color = Color.white; + _meshFactory = this; + + meshFilter = gameObject.AddComponent(); + meshRenderer = gameObject.AddComponent(); + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + meshRenderer.receiveShadows = false; + + mesh = new Mesh(); + mesh.name = gameObject.name; + mesh.MarkDynamic(); + + meshFilter.mesh = mesh; + + meshFilter.hideFlags = DisplayObject.hideFlags; + meshRenderer.hideFlags = DisplayObject.hideFlags; + mesh.hideFlags = DisplayObject.hideFlags; + + Stats.LatestGraphicsCreation++; + } + + /// + /// + /// + public IMeshFactory meshFactory + { + get { return _meshFactory; } + set + { + if (_meshFactory != value) + { + _meshFactory = value; + _meshDirty = true; + } + } + } + + /// + /// + /// + /// + /// + public T GetMeshFactory() where T : IMeshFactory, new() + { + if (!(_meshFactory is T)) + { + _meshFactory = new T(); + _meshDirty = true; + } + return (T)_meshFactory; + } + + /// + /// + /// + public Rect contentRect + { + get { return _contentRect; } + set + { + _contentRect = value; + _meshDirty = true; + } + } + + /// + /// + /// + public FlipType flip + { + get { return _flip; } + set + { + if (_flip != value) + { + _flip = value; + _meshDirty = true; + } + } + } + + /// + /// + /// + public NTexture texture + { + get { return _texture; } + set + { + if (_texture != value) + { + if (value != null) + value.AddRef(); + if (_texture != null) + _texture.ReleaseRef(); + + _texture = value; + if (_customMatarial != 0 && _material != null) + _material.mainTexture = _texture != null ? _texture.nativeTexture : null; + _meshDirty = true; + UpdateManager(); + } + } + } + + /// + /// + /// + public string shader + { + get { return _shader; } + set + { + _shader = value; + UpdateManager(); + } + } + + /// + /// + /// + /// + /// + public void SetShaderAndTexture(string shader, NTexture texture) + { + _shader = shader; + if (_texture != texture) + this.texture = texture; + else + UpdateManager(); + } + + /// + /// + /// + public Material material + { + get + { + if (_customMatarial == 0 && _material == null && _manager != null) + _material = _manager.GetMaterial(_materialFlags, blendMode, 0); + return _material; + } + set + { + if ((_customMatarial & 128) != 0 && _material != null) + Object.DestroyImmediate(_material); + + _material = value; + if (_material != null) + { + _customMatarial = 1; + if (_material.HasProperty(ShaderConfig.ID_Stencil) || _material.HasProperty(ShaderConfig.ID_ClipBox)) + _customMatarial |= 2; + + meshRenderer.sharedMaterial = _material; + if (_texture != null) + _material.mainTexture = _texture.nativeTexture; + } + else + { + _customMatarial = 0; + meshRenderer.sharedMaterial = null; + } + } + } + + /// + /// Same as material property except that ownership is transferred to this object. + /// + /// + public void SetMaterial(Material material) + { + this.material = material; + _customMatarial |= 128; + } + + /// + /// + /// + public string[] materialKeywords + { + get { return _shaderKeywords; } + set + { + _shaderKeywords = value; + UpdateMaterialFlags(); + } + } + + /// + /// + /// + /// + /// + public void ToggleKeyword(string keyword, bool enabled) + { + if (enabled) + { + if (_shaderKeywords == null) + { + _shaderKeywords = new string[] { keyword }; + UpdateMaterialFlags(); + } + else if (Array.IndexOf(_shaderKeywords, keyword) == -1) + { + Array.Resize(ref _shaderKeywords, _shaderKeywords.Length + 1); + _shaderKeywords[_shaderKeywords.Length - 1] = keyword; + UpdateMaterialFlags(); + } + } + else + { + if (_shaderKeywords != null) + { + int i = Array.IndexOf(_shaderKeywords, keyword); + if (i != -1) + { + _shaderKeywords[i] = null; + UpdateMaterialFlags(); + } + } + } + } + + void UpdateManager() + { + if (_texture != null) + _manager = _texture.GetMaterialManager(_shader); + else + _manager = null; + UpdateMaterialFlags(); + } + + void UpdateMaterialFlags() + { + if (_customMatarial != 0) + { + if (material != null) + material.shaderKeywords = _shaderKeywords; + } + else if (_shaderKeywords != null && _manager != null) + _materialFlags = _manager.GetFlagsByKeywords(_shaderKeywords); + else + _materialFlags = 0; + } + + /// + /// + /// + public bool enabled + { + get { return meshRenderer.enabled; } + set { meshRenderer.enabled = value; } + } + + /// + /// + /// + public int sortingOrder + { + get { return meshRenderer.sortingOrder; } + set { meshRenderer.sortingOrder = value; } + } + + /// + /// + /// + /// + internal void _SetStencilEraserOrder(int value) + { + _stencilEraser.meshRenderer.sortingOrder = value; + } + + /// + /// + /// + /// + public Color color + { + get { return _color; } + set { _color = value; } + } + + /// + /// + /// + public void Tint() + { + if (_meshDirty) + return; + + int vertCount = mesh.vertexCount; + if (vertCount == 0) + return; + +#if !UNITY_5_6_OR_NEWER + Color32[] colors = _colors; + if (colors == null) + colors = mesh.colors32; +#else + VertexBuffer vb = VertexBuffer.Begin(); + mesh.GetColors(vb.colors); + List colors = vb.colors; +#endif + for (int i = 0; i < vertCount; i++) + { + Color32 col = _color; + col.a = (byte)(_alpha * (hasAlphaBackup ? _alphaBackup[i] : (byte)255)); + colors[i] = col; + } + +#if !UNITY_5_6_OR_NEWER + mesh.colors32 = colors; +#else + mesh.SetColors(vb.colors); + vb.End(); +#endif + } + + void ChangeAlpha(float value) + { + _alpha = value; + + int vertCount = mesh.vertexCount; + if (vertCount == 0) + return; + +#if !UNITY_5_6_OR_NEWER + Color32[] colors = _colors; + if (colors == null) + colors = mesh.colors32; +#else + VertexBuffer vb = VertexBuffer.Begin(); + mesh.GetColors(vb.colors); + List colors = vb.colors; +#endif + for (int i = 0; i < vertCount; i++) + { + Color32 col = colors[i]; + col.a = (byte)(_alpha * (hasAlphaBackup ? _alphaBackup[i] : (byte)255)); + colors[i] = col; + } + +#if !UNITY_5_6_OR_NEWER + mesh.colors32 = colors; +#else + mesh.SetColors(vb.colors); + vb.End(); +#endif + } + + /// + /// + /// + public VertexMatrix vertexMatrix + { + get { return _vertexMatrix; } + set + { + _vertexMatrix = value; + _meshDirty = true; + } + } + + /// + /// + /// + /// + public MaterialPropertyBlock materialPropertyBlock + { + get + { + if (_propertyBlock == null) + _propertyBlock = new MaterialPropertyBlock(); + + _blockUpdated = true; + return _propertyBlock; + } + } + + /// + /// + /// + public void SetMeshDirty() + { + _meshDirty = true; + } + + /// + /// + /// + /// + public bool UpdateMesh() + { + if (_meshDirty) + { + UpdateMeshNow(); + return true; + } + else + return false; + } + + /// + /// + /// + public void Dispose() + { + if (mesh != null) + { + if (Application.isPlaying) + Object.Destroy(mesh); + else + Object.DestroyImmediate(mesh); + mesh = null; + } + if ((_customMatarial & 128) != 0 && _material != null) + Object.DestroyImmediate(_material); + + if (_texture != null) + { + _texture.ReleaseRef(); + _texture = null; + } + + _manager = null; + _material = null; + meshRenderer = null; + meshFilter = null; + _stencilEraser = null; + meshModifier = null; + } + + /// + /// + /// + /// + /// + /// + public void Update(UpdateContext context, float alpha, bool grayed) + { + Stats.GraphicsCount++; + + if (_meshDirty) + { + _alpha = alpha; + UpdateMeshNow(); + } + else if (_alpha != alpha) + ChangeAlpha(alpha); + + if (_propertyBlock != null && _blockUpdated) + { + meshRenderer.SetPropertyBlock(_propertyBlock); + _blockUpdated = false; + } + + if (_customMatarial != 0) + { + if ((_customMatarial & 2) != 0 && _material != null) + context.ApplyClippingProperties(_material, false); + } + else + { + if (_manager != null) + { + if (_maskFlag == 1) + { + _material = _manager.GetMaterial((int)MaterialFlags.AlphaMask | _materialFlags, BlendMode.Normal, context.clipInfo.clipId); + context.ApplyAlphaMaskProperties(_material, false); + } + else + { + int matFlags = _materialFlags; + if (grayed) + matFlags |= (int)MaterialFlags.Grayed; + + if (context.clipped) + { + if (context.stencilReferenceValue > 0) + matFlags |= (int)MaterialFlags.StencilTest; + if (context.rectMaskDepth > 0) + { + if (context.clipInfo.soft) + matFlags |= (int)MaterialFlags.SoftClipped; + else + matFlags |= (int)MaterialFlags.Clipped; + } + + _material = _manager.GetMaterial(matFlags, blendMode, context.clipInfo.clipId); + if (_manager.firstMaterialInFrame) + context.ApplyClippingProperties(_material, true); + } + else + _material = _manager.GetMaterial(matFlags, blendMode, 0); + } + } + else + _material = null; + + if (!Material.ReferenceEquals(_material, meshRenderer.sharedMaterial)) + meshRenderer.sharedMaterial = _material; + } + + if (_maskFlag != 0) + { + if (_maskFlag == 1) + _maskFlag = 2; + else + { + if (_stencilEraser != null) + _stencilEraser.enabled = false; + + _maskFlag = 0; + } + } + } + + internal void _PreUpdateMask(UpdateContext context, uint maskId) + { + //_maskFlag: 0-new mask, 1-active mask, 2-mask complete + if (_maskFlag == 0) + { + if (_stencilEraser == null) + { + _stencilEraser = new StencilEraser(gameObject.transform); + _stencilEraser.meshFilter.mesh = mesh; + } + else + _stencilEraser.enabled = true; + } + + _maskFlag = 1; + + if (_manager != null) + { + //这里使用maskId而不是clipInfo.clipId,是因为遮罩有两个用途,一个是写入遮罩,一个是擦除,两个不能用同一个材质 + Material mat = _manager.GetMaterial((int)MaterialFlags.AlphaMask | _materialFlags, BlendMode.Normal, maskId); + if (!Material.ReferenceEquals(mat, _stencilEraser.meshRenderer.sharedMaterial)) + _stencilEraser.meshRenderer.sharedMaterial = mat; + + context.ApplyAlphaMaskProperties(mat, true); + } + } + + void UpdateMeshNow() + { + _meshDirty = false; + + if (_texture == null || _meshFactory == null) + { + if (mesh.vertexCount > 0) + { + mesh.Clear(); + + if (meshModifier != null) + meshModifier(); + } + return; + } + + VertexBuffer vb = VertexBuffer.Begin(); + vb.contentRect = _contentRect; + vb.uvRect = _texture.uvRect; + if (_texture != null) + vb.textureSize = new Vector2(_texture.width, _texture.height); + else + vb.textureSize = new Vector2(0, 0); + if (_flip != FlipType.None) + { + if (_flip == FlipType.Horizontal || _flip == FlipType.Both) + { + float tmp = vb.uvRect.xMin; + vb.uvRect.xMin = vb.uvRect.xMax; + vb.uvRect.xMax = tmp; + } + if (_flip == FlipType.Vertical || _flip == FlipType.Both) + { + float tmp = vb.uvRect.yMin; + vb.uvRect.yMin = vb.uvRect.yMax; + vb.uvRect.yMax = tmp; + } + } + vb.vertexColor = _color; + _meshFactory.OnPopulateMesh(vb); + + int vertCount = vb.currentVertCount; + if (vertCount == 0) + { + if (mesh.vertexCount > 0) + { + mesh.Clear(); + + if (meshModifier != null) + meshModifier(); + } + vb.End(); + return; + } + + if (_texture.rotated) + { + float xMin = _texture.uvRect.xMin; + float yMin = _texture.uvRect.yMin; + float yMax = _texture.uvRect.yMax; + float tmp; + for (int i = 0; i < vertCount; i++) + { + Vector2 vec = vb.uvs[i]; + tmp = vec.y; + vec.y = yMin + vec.x - xMin; + vec.x = xMin + yMax - tmp; + vb.uvs[i] = vec; + } + } + + hasAlphaBackup = vb._alphaInVertexColor; + if (hasAlphaBackup) + { + if (_alphaBackup == null) + _alphaBackup = new List(); + else + _alphaBackup.Clear(); + for (int i = 0; i < vertCount; i++) + { + Color32 col = vb.colors[i]; + _alphaBackup.Add(col.a); + + col.a = (byte)(col.a * _alpha); + vb.colors[i] = col; + } + } + else if (_alpha != 1) + { + for (int i = 0; i < vertCount; i++) + { + Color32 col = vb.colors[i]; + col.a = (byte)(col.a * _alpha); + vb.colors[i] = col; + } + } + + if (_vertexMatrix != null) + { + Vector3 camPos = _vertexMatrix.cameraPos; + Vector3 center = new Vector3(camPos.x, camPos.y, 0); + center -= _vertexMatrix.matrix.MultiplyPoint(center); + for (int i = 0; i < vertCount; i++) + { + Vector3 pt = vb.vertices[i]; + pt = _vertexMatrix.matrix.MultiplyPoint(pt); + pt += center; + Vector3 vec = pt - camPos; + float lambda = -camPos.z / vec.z; + pt.x = camPos.x + lambda * vec.x; + pt.y = camPos.y + lambda * vec.y; + pt.z = 0; + + vb.vertices[i] = pt; + } + } + + mesh.Clear(); + +#if UNITY_5_2 || UNITY_5_3_OR_NEWER + mesh.SetVertices(vb.vertices); + if (vb._isArbitraryQuad) + mesh.SetUVs(0, vb.FixUVForArbitraryQuad()); + else + mesh.SetUVs(0, vb.uvs); + mesh.SetColors(vb.colors); + mesh.SetTriangles(vb.triangles, 0); + if (vb.uvs2.Count == vb.uvs.Count) + mesh.SetUVs(1, vb.uvs2); + +#if !UNITY_5_6_OR_NEWER + _colors = null; +#endif +#else + Vector3[] vertices = new Vector3[vertCount]; + Vector2[] uv = new Vector2[vertCount]; + _colors = new Color32[vertCount]; + int[] triangles = new int[vb.triangles.Count]; + + vb.vertices.CopyTo(vertices); + vb.uvs.CopyTo(uv); + vb.colors.CopyTo(_colors); + vb.triangles.CopyTo(triangles); + + mesh.vertices = vertices; + mesh.uv = uv; + mesh.triangles = triangles; + mesh.colors32 = _colors; + + if(vb.uvs2.Count==uv.Length) + { + uv = new Vector2[vertCount]; + vb.uvs2.CopyTo(uv); + mesh.uv2 = uv; + } +#endif + vb.End(); + + if (meshModifier != null) + meshModifier(); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + Rect rect = texture.GetDrawRect(vb.contentRect); + + vb.AddQuad(rect, vb.vertexColor, vb.uvRect); + vb.AddTriangles(); + vb._isArbitraryQuad = _vertexMatrix != null; + } + + class StencilEraser + { + public GameObject gameObject; + public MeshFilter meshFilter; + public MeshRenderer meshRenderer; + + public StencilEraser(Transform parent) + { + gameObject = new GameObject("StencilEraser"); + gameObject.transform.SetParent(parent, false); + + meshFilter = gameObject.AddComponent(); + meshRenderer = gameObject.AddComponent(); + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + meshRenderer.receiveShadows = false; + + gameObject.layer = parent.gameObject.layer; + gameObject.hideFlags = parent.gameObject.hideFlags; + meshFilter.hideFlags = parent.gameObject.hideFlags; + meshRenderer.hideFlags = parent.gameObject.hideFlags; + } + + public bool enabled + { + get { return meshRenderer.enabled; } + set { meshRenderer.enabled = value; } + } + } + } +} diff --git a/Assets/Scripts/Core/NGraphics.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NGraphics.cs.meta similarity index 100% rename from Assets/Scripts/Core/NGraphics.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NGraphics.cs.meta diff --git a/Assets/Scripts/Core/NTexture.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NTexture.cs similarity index 96% rename from Assets/Scripts/Core/NTexture.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NTexture.cs index 22e55329..deb0150c 100644 --- a/Assets/Scripts/Core/NTexture.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NTexture.cs @@ -1,521 +1,521 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace FairyGUI -{ - /// - /// - /// - public enum DestroyMethod - { - Destroy, - Unload, - None, - ReleaseTemp, - Custom - } - - /// - /// - /// - public class NTexture - { - /// - /// This event will trigger when a texture is destroying if its destroyMethod is Custom - /// - public static event Action CustomDestroyMethod; - - /// - /// - /// - public Rect uvRect; - - /// - /// - /// - public bool rotated; - - /// - /// - /// - public int refCount; - - /// - /// - /// - public float lastActive; - - /// - /// - /// - public DestroyMethod destroyMethod; - - /// - /// This event will trigger when texture reloaded and size changed. - /// - public event Action onSizeChanged; - - /// - /// This event will trigger when ref count is zero. - /// - public event Action onRelease; - - Texture _nativeTexture; - Texture _alphaTexture; - - Rect _region; - Vector2 _offset; - Vector2 _originalSize; - - NTexture _root; - Dictionary _materialManagers; - - internal static Texture2D CreateEmptyTexture() - { - Texture2D emptyTexture = new Texture2D(1, 1, TextureFormat.RGB24, false); - emptyTexture.name = "White Texture"; - emptyTexture.hideFlags = DisplayObject.hideFlags; - emptyTexture.SetPixel(0, 0, Color.white); - emptyTexture.Apply(); - return emptyTexture; - } - - static NTexture _empty; - - /// - /// - /// - public static NTexture Empty - { - get - { - if (_empty == null) - _empty = new NTexture(CreateEmptyTexture()); - - return _empty; - } - } - - /// - /// - /// - public static void DisposeEmpty() - { - if (_empty != null) - { - NTexture tmp = _empty; - _empty = null; - tmp.Dispose(); - } - } - - /// - /// - /// - /// - public NTexture(Texture texture) : this(texture, null, 1, 1) - { - } - - /// - /// - /// - /// - /// - /// - public NTexture(Texture texture, Texture alphaTexture, float xScale, float yScale) - { - _root = this; - _nativeTexture = texture; - _alphaTexture = alphaTexture; - uvRect = new Rect(0, 0, xScale, yScale); - if (yScale < 0) - { - uvRect.y = -yScale; - uvRect.yMax = 0; - } - if (xScale < 0) - { - uvRect.x = -xScale; - uvRect.xMax = 0; - } - if (_nativeTexture != null) - _originalSize = new Vector2(_nativeTexture.width, _nativeTexture.height); - _region = new Rect(0, 0, _originalSize.x, _originalSize.y); - } - - /// - /// - /// - /// - /// - public NTexture(Texture texture, Rect region) - { - _root = this; - _nativeTexture = texture; - _region = region; - _originalSize = new Vector2(_region.width, _region.height); - if (_nativeTexture != null) - uvRect = new Rect(region.x / _nativeTexture.width, 1 - region.yMax / _nativeTexture.height, - region.width / _nativeTexture.width, region.height / _nativeTexture.height); - else - uvRect.Set(0, 0, 1, 1); - } - - /// - /// - /// - /// - /// - /// - public NTexture(NTexture root, Rect region, bool rotated) - { - _root = root; - this.rotated = rotated; - region.x += root._region.x; - region.y += root._region.y; - uvRect = new Rect(region.x * root.uvRect.width / root.width, 1 - region.yMax * root.uvRect.height / root.height, - region.width * root.uvRect.width / root.width, region.height * root.uvRect.height / root.height); - if (rotated) - { - float tmp = region.width; - region.width = region.height; - region.height = tmp; - - tmp = uvRect.width; - uvRect.width = uvRect.height; - uvRect.height = tmp; - } - _region = region; - _originalSize = _region.size; - } - - /// - /// - /// - /// - /// - /// - /// - /// - public NTexture(NTexture root, Rect region, bool rotated, Vector2 originalSize, Vector2 offset) - : this(root, region, rotated) - { - _originalSize = originalSize; - _offset = offset; - } - - /// - /// - /// - /// - public NTexture(Sprite sprite) - { - Rect rect = sprite.textureRect; - rect.y = sprite.texture.height - rect.yMax; - - _root = this; - _nativeTexture = sprite.texture; - _region = rect; - _originalSize = new Vector2(_region.width, _region.height); - uvRect = new Rect(_region.x / _nativeTexture.width, 1 - _region.yMax / _nativeTexture.height, - _region.width / _nativeTexture.width, _region.height / _nativeTexture.height); - } - - /// - /// - /// - public int width - { - get { return (int)_region.width; } - } - - /// - /// - /// - public int height - { - get { return (int)_region.height; } - } - - /// - /// - /// - public Vector2 offset - { - get { return _offset; } - set { _offset = value; } - } - - /// - /// - /// - public Vector2 originalSize - { - get { return _originalSize; } - set { _originalSize = value; } - } - - /// - /// - /// - /// - /// - public Rect GetDrawRect(Rect drawRect) - { - if (_originalSize.x == _region.width && _originalSize.y == _region.height) - return drawRect; - - float sx = drawRect.width / _originalSize.x; - float sy = drawRect.height / _originalSize.y; - return new Rect(_offset.x * sx, _offset.y * sy, _region.width * sx, _region.height * sy); - } - - /// - /// - /// - /// - public void GetUV(Vector2[] uv) - { - uv[0] = uvRect.position; - uv[1] = new Vector2(uvRect.xMin, uvRect.yMax); - uv[2] = new Vector2(uvRect.xMax, uvRect.yMax); - uv[3] = new Vector2(uvRect.xMax, uvRect.yMin); - if (rotated) - { - float xMin = uvRect.xMin; - float yMin = uvRect.yMin; - float yMax = uvRect.yMax; - - float tmp; - for (int i = 0; i < 4; i++) - { - Vector2 m = uv[i]; - tmp = m.y; - m.y = yMin + m.x - xMin; - m.x = xMin + yMax - tmp; - uv[i] = m; - } - } - } - - /// - /// - /// - public NTexture root - { - get { return _root; } - } - - /// - /// - /// - public bool disposed - { - get { return _root == null; } - } - - /// - /// - /// - public Texture nativeTexture - { - get { return _root != null ? _root._nativeTexture : null; } - } - - /// - /// - /// - public Texture alphaTexture - { - get { return _root != null ? _root._alphaTexture : null; } - } - - /// - /// - /// - public MaterialManager GetMaterialManager(string shaderName) - { - if (_root != this) - { - if (_root == null) - return null; - else - return _root.GetMaterialManager(shaderName); - } - - if (_materialManagers == null) - _materialManagers = new Dictionary(); - - MaterialManager mm; - if (!_materialManagers.TryGetValue(shaderName, out mm)) - { - mm = new MaterialManager(this, ShaderConfig.GetShader(shaderName)); - _materialManagers.Add(shaderName, mm); - } - - return mm; - } - - /// - /// - /// - public void Unload() - { - Unload(false); - } - - /// - /// - /// - public void Unload(bool destroyMaterials) - { - if (this == _empty) - return; - - if (_root != this) - throw new Exception("Unload is not allow to call on none root NTexture."); - - if (_nativeTexture != null) - { - DestroyTexture(); - - if (destroyMaterials) - DestroyMaterials(); - else - RefreshMaterials(); - } - } - - /// - /// - /// - /// - /// - public void Reload(Texture nativeTexture, Texture alphaTexture) - { - if (_root != this) - throw new System.Exception("Reload is not allow to call on none root NTexture."); - - if (_nativeTexture != null && _nativeTexture != nativeTexture) - DestroyTexture(); - - _nativeTexture = nativeTexture; - _alphaTexture = alphaTexture; - - Vector2 lastSize = _originalSize; - if (_nativeTexture != null) - _originalSize = new Vector2(_nativeTexture.width, _nativeTexture.height); - else - _originalSize = Vector2.zero; - _region = new Rect(0, 0, _originalSize.x, _originalSize.y); - - RefreshMaterials(); - - if (onSizeChanged != null && lastSize != _originalSize) - onSizeChanged(this); - } - - void DestroyTexture() - { - switch (destroyMethod) - { - case DestroyMethod.Destroy: - Object.DestroyImmediate(_nativeTexture, true); - if (_alphaTexture != null) - Object.DestroyImmediate(_alphaTexture, true); - break; - case DestroyMethod.Unload: - Resources.UnloadAsset(_nativeTexture); - if (_alphaTexture != null) - Resources.UnloadAsset(_alphaTexture); - break; - case DestroyMethod.ReleaseTemp: - RenderTexture.ReleaseTemporary((RenderTexture)_nativeTexture); - if (_alphaTexture is RenderTexture) - RenderTexture.ReleaseTemporary((RenderTexture)_alphaTexture); - break; - case DestroyMethod.Custom: - if (CustomDestroyMethod == null) - Debug.LogWarning("NTexture.CustomDestroyMethod must be set to handle DestroyMethod.Custom"); - else - { - CustomDestroyMethod(_nativeTexture); - if (_alphaTexture != null) - CustomDestroyMethod(_alphaTexture); - } - break; - } - - _nativeTexture = null; - _alphaTexture = null; - } - - void RefreshMaterials() - { - if (_materialManagers != null && _materialManagers.Count > 0) - { - Dictionary.Enumerator iter = _materialManagers.GetEnumerator(); - while (iter.MoveNext()) - iter.Current.Value.RefreshMaterials(); - iter.Dispose(); - } - } - - void DestroyMaterials() - { - if (_materialManagers != null && _materialManagers.Count > 0) - { - Dictionary.Enumerator iter = _materialManagers.GetEnumerator(); - while (iter.MoveNext()) - iter.Current.Value.DestroyMaterials(); - iter.Dispose(); - } - } - - public void AddRef() - { - if (_root == null) //disposed - return; - - if (_root != this && refCount == 0) - _root.AddRef(); - - refCount++; - } - - public void ReleaseRef() - { - if (_root == null) //disposed - return; - - refCount--; - - if (refCount == 0) - { - if (_root != this) - _root.ReleaseRef(); - - if (onRelease != null) - onRelease(this); - } - } - - /// - /// - /// - public void Dispose() - { - if (this == _empty) - return; - - if (_root == this) - Unload(true); - _root = null; - onSizeChanged = null; - onRelease = null; - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace FairyGUI +{ + /// + /// + /// + public enum DestroyMethod + { + Destroy, + Unload, + None, + ReleaseTemp, + Custom + } + + /// + /// + /// + public class NTexture + { + /// + /// This event will trigger when a texture is destroying if its destroyMethod is Custom + /// + public static event Action CustomDestroyMethod; + + /// + /// + /// + public Rect uvRect; + + /// + /// + /// + public bool rotated; + + /// + /// + /// + public int refCount; + + /// + /// + /// + public float lastActive; + + /// + /// + /// + public DestroyMethod destroyMethod; + + /// + /// This event will trigger when texture reloaded and size changed. + /// + public event Action onSizeChanged; + + /// + /// This event will trigger when ref count is zero. + /// + public event Action onRelease; + + Texture _nativeTexture; + Texture _alphaTexture; + + Rect _region; + Vector2 _offset; + Vector2 _originalSize; + + NTexture _root; + Dictionary _materialManagers; + + internal static Texture2D CreateEmptyTexture() + { + Texture2D emptyTexture = new Texture2D(1, 1, TextureFormat.RGB24, false); + emptyTexture.name = "White Texture"; + emptyTexture.hideFlags = DisplayObject.hideFlags; + emptyTexture.SetPixel(0, 0, Color.white); + emptyTexture.Apply(); + return emptyTexture; + } + + static NTexture _empty; + + /// + /// + /// + public static NTexture Empty + { + get + { + if (_empty == null) + _empty = new NTexture(CreateEmptyTexture()); + + return _empty; + } + } + + /// + /// + /// + public static void DisposeEmpty() + { + if (_empty != null) + { + NTexture tmp = _empty; + _empty = null; + tmp.Dispose(); + } + } + + /// + /// + /// + /// + public NTexture(Texture texture) : this(texture, null, 1, 1) + { + } + + /// + /// + /// + /// + /// + /// + public NTexture(Texture texture, Texture alphaTexture, float xScale, float yScale) + { + _root = this; + _nativeTexture = texture; + _alphaTexture = alphaTexture; + uvRect = new Rect(0, 0, xScale, yScale); + if (yScale < 0) + { + uvRect.y = -yScale; + uvRect.yMax = 0; + } + if (xScale < 0) + { + uvRect.x = -xScale; + uvRect.xMax = 0; + } + if (_nativeTexture != null) + _originalSize = new Vector2(_nativeTexture.width, _nativeTexture.height); + _region = new Rect(0, 0, _originalSize.x, _originalSize.y); + } + + /// + /// + /// + /// + /// + public NTexture(Texture texture, Rect region) + { + _root = this; + _nativeTexture = texture; + _region = region; + _originalSize = new Vector2(_region.width, _region.height); + if (_nativeTexture != null) + uvRect = new Rect(region.x / _nativeTexture.width, 1 - region.yMax / _nativeTexture.height, + region.width / _nativeTexture.width, region.height / _nativeTexture.height); + else + uvRect.Set(0, 0, 1, 1); + } + + /// + /// + /// + /// + /// + /// + public NTexture(NTexture root, Rect region, bool rotated) + { + _root = root; + this.rotated = rotated; + region.x += root._region.x; + region.y += root._region.y; + uvRect = new Rect(region.x * root.uvRect.width / root.width, 1 - region.yMax * root.uvRect.height / root.height, + region.width * root.uvRect.width / root.width, region.height * root.uvRect.height / root.height); + if (rotated) + { + float tmp = region.width; + region.width = region.height; + region.height = tmp; + + tmp = uvRect.width; + uvRect.width = uvRect.height; + uvRect.height = tmp; + } + _region = region; + _originalSize = _region.size; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public NTexture(NTexture root, Rect region, bool rotated, Vector2 originalSize, Vector2 offset) + : this(root, region, rotated) + { + _originalSize = originalSize; + _offset = offset; + } + + /// + /// + /// + /// + public NTexture(Sprite sprite) + { + Rect rect = sprite.textureRect; + rect.y = sprite.texture.height - rect.yMax; + + _root = this; + _nativeTexture = sprite.texture; + _region = rect; + _originalSize = new Vector2(_region.width, _region.height); + uvRect = new Rect(_region.x / _nativeTexture.width, 1 - _region.yMax / _nativeTexture.height, + _region.width / _nativeTexture.width, _region.height / _nativeTexture.height); + } + + /// + /// + /// + public int width + { + get { return (int)_region.width; } + } + + /// + /// + /// + public int height + { + get { return (int)_region.height; } + } + + /// + /// + /// + public Vector2 offset + { + get { return _offset; } + set { _offset = value; } + } + + /// + /// + /// + public Vector2 originalSize + { + get { return _originalSize; } + set { _originalSize = value; } + } + + /// + /// + /// + /// + /// + public Rect GetDrawRect(Rect drawRect) + { + if (_originalSize.x == _region.width && _originalSize.y == _region.height) + return drawRect; + + float sx = drawRect.width / _originalSize.x; + float sy = drawRect.height / _originalSize.y; + return new Rect(_offset.x * sx, _offset.y * sy, _region.width * sx, _region.height * sy); + } + + /// + /// + /// + /// + public void GetUV(Vector2[] uv) + { + uv[0] = uvRect.position; + uv[1] = new Vector2(uvRect.xMin, uvRect.yMax); + uv[2] = new Vector2(uvRect.xMax, uvRect.yMax); + uv[3] = new Vector2(uvRect.xMax, uvRect.yMin); + if (rotated) + { + float xMin = uvRect.xMin; + float yMin = uvRect.yMin; + float yMax = uvRect.yMax; + + float tmp; + for (int i = 0; i < 4; i++) + { + Vector2 m = uv[i]; + tmp = m.y; + m.y = yMin + m.x - xMin; + m.x = xMin + yMax - tmp; + uv[i] = m; + } + } + } + + /// + /// + /// + public NTexture root + { + get { return _root; } + } + + /// + /// + /// + public bool disposed + { + get { return _root == null; } + } + + /// + /// + /// + public Texture nativeTexture + { + get { return _root != null ? _root._nativeTexture : null; } + } + + /// + /// + /// + public Texture alphaTexture + { + get { return _root != null ? _root._alphaTexture : null; } + } + + /// + /// + /// + public MaterialManager GetMaterialManager(string shaderName) + { + if (_root != this) + { + if (_root == null) + return null; + else + return _root.GetMaterialManager(shaderName); + } + + if (_materialManagers == null) + _materialManagers = new Dictionary(); + + MaterialManager mm; + if (!_materialManagers.TryGetValue(shaderName, out mm)) + { + mm = new MaterialManager(this, ShaderConfig.GetShader(shaderName)); + _materialManagers.Add(shaderName, mm); + } + + return mm; + } + + /// + /// + /// + public void Unload() + { + Unload(false); + } + + /// + /// + /// + public void Unload(bool destroyMaterials) + { + if (this == _empty) + return; + + if (_root != this) + throw new Exception("Unload is not allow to call on none root NTexture."); + + if (_nativeTexture != null) + { + DestroyTexture(); + + if (destroyMaterials) + DestroyMaterials(); + else + RefreshMaterials(); + } + } + + /// + /// + /// + /// + /// + public void Reload(Texture nativeTexture, Texture alphaTexture) + { + if (_root != this) + throw new System.Exception("Reload is not allow to call on none root NTexture."); + + if (_nativeTexture != null && _nativeTexture != nativeTexture) + DestroyTexture(); + + _nativeTexture = nativeTexture; + _alphaTexture = alphaTexture; + + Vector2 lastSize = _originalSize; + if (_nativeTexture != null) + _originalSize = new Vector2(_nativeTexture.width, _nativeTexture.height); + else + _originalSize = Vector2.zero; + _region = new Rect(0, 0, _originalSize.x, _originalSize.y); + + RefreshMaterials(); + + if (onSizeChanged != null && lastSize != _originalSize) + onSizeChanged(this); + } + + void DestroyTexture() + { + switch (destroyMethod) + { + case DestroyMethod.Destroy: + Object.DestroyImmediate(_nativeTexture, true); + if (_alphaTexture != null) + Object.DestroyImmediate(_alphaTexture, true); + break; + case DestroyMethod.Unload: + Resources.UnloadAsset(_nativeTexture); + if (_alphaTexture != null) + Resources.UnloadAsset(_alphaTexture); + break; + case DestroyMethod.ReleaseTemp: + RenderTexture.ReleaseTemporary((RenderTexture)_nativeTexture); + if (_alphaTexture is RenderTexture) + RenderTexture.ReleaseTemporary((RenderTexture)_alphaTexture); + break; + case DestroyMethod.Custom: + if (CustomDestroyMethod == null) + Debug.LogWarning("NTexture.CustomDestroyMethod must be set to handle DestroyMethod.Custom"); + else + { + CustomDestroyMethod(_nativeTexture); + if (_alphaTexture != null) + CustomDestroyMethod(_alphaTexture); + } + break; + } + + _nativeTexture = null; + _alphaTexture = null; + } + + void RefreshMaterials() + { + if (_materialManagers != null && _materialManagers.Count > 0) + { + Dictionary.Enumerator iter = _materialManagers.GetEnumerator(); + while (iter.MoveNext()) + iter.Current.Value.RefreshMaterials(); + iter.Dispose(); + } + } + + void DestroyMaterials() + { + if (_materialManagers != null && _materialManagers.Count > 0) + { + Dictionary.Enumerator iter = _materialManagers.GetEnumerator(); + while (iter.MoveNext()) + iter.Current.Value.DestroyMaterials(); + iter.Dispose(); + } + } + + public void AddRef() + { + if (_root == null) //disposed + return; + + if (_root != this && refCount == 0) + _root.AddRef(); + + refCount++; + } + + public void ReleaseRef() + { + if (_root == null) //disposed + return; + + refCount--; + + if (refCount == 0) + { + if (_root != this) + _root.ReleaseRef(); + + if (onRelease != null) + onRelease(this); + } + } + + /// + /// + /// + public void Dispose() + { + if (this == _empty) + return; + + if (_root == this) + Unload(true); + _root = null; + onSizeChanged = null; + onRelease = null; + } + } +} diff --git a/Assets/Scripts/Core/NTexture.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NTexture.cs.meta similarity index 100% rename from Assets/Scripts/Core/NTexture.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/NTexture.cs.meta diff --git a/Assets/Scripts/Core/ShaderConfig.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/ShaderConfig.cs similarity index 96% rename from Assets/Scripts/Core/ShaderConfig.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/ShaderConfig.cs index da77dd56..6b548492 100644 --- a/Assets/Scripts/Core/ShaderConfig.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/ShaderConfig.cs @@ -1,95 +1,95 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public static class ShaderConfig - { - /// - /// - /// - /// - /// - public delegate Shader GetFunction(string name); - - /// - /// - /// - public static GetFunction Get = Shader.Find; - - /// - /// - /// - public static string imageShader = "FairyGUI/Image"; - - /// - /// - /// - public static string textShader = "FairyGUI/Text"; - - /// - /// - /// - public static string bmFontShader = "FairyGUI/BMFont"; - - /// - /// - /// - public static string TMPFontShader = "FairyGUI/TMP"; - - public static int ID_ClipBox; - public static int ID_ClipSoftness; - public static int ID_AlphaTex; - public static int ID_StencilComp; - public static int ID_Stencil; - public static int ID_StencilOp; - public static int ID_StencilReadMask; - public static int ID_ColorMask; - public static int ID_ColorMatrix; - public static int ID_ColorOffset; - public static int ID_BlendSrcFactor; - public static int ID_BlendDstFactor; - public static int ID_ColorOption; - - public static int ID_Stencil2; - - static ShaderConfig() - { - ID_ClipBox = Shader.PropertyToID("_ClipBox"); - ID_ClipSoftness = Shader.PropertyToID("_ClipSoftness"); - ID_AlphaTex = Shader.PropertyToID("_AlphaTex"); - ID_StencilComp = Shader.PropertyToID("_StencilComp"); - ID_Stencil = Shader.PropertyToID("_Stencil"); - ID_StencilOp = Shader.PropertyToID("_StencilOp"); - ID_StencilReadMask = Shader.PropertyToID("_StencilReadMask"); - ID_ColorMask = Shader.PropertyToID("_ColorMask"); - ID_ColorMatrix = Shader.PropertyToID("_ColorMatrix"); - ID_ColorOffset = Shader.PropertyToID("_ColorOffset"); - ID_BlendSrcFactor = Shader.PropertyToID("_BlendSrcFactor"); - ID_BlendDstFactor = Shader.PropertyToID("_BlendDstFactor"); - ID_ColorOption = Shader.PropertyToID("_ColorOption"); - - ID_Stencil2 = Shader.PropertyToID("_StencilRef"); - } - - /// - /// - /// - /// - /// - public static Shader GetShader(string name) - { - Shader shader = Get(name); - if (shader == null) - { - Debug.LogWarning("FairyGUI: shader not found: " + name); - shader = Shader.Find("UI/Default"); - } - shader.hideFlags = DisplayObject.hideFlags; - - return shader; - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public static class ShaderConfig + { + /// + /// + /// + /// + /// + public delegate Shader GetFunction(string name); + + /// + /// + /// + public static GetFunction Get = Shader.Find; + + /// + /// + /// + public static string imageShader = "FairyGUI/Image"; + + /// + /// + /// + public static string textShader = "FairyGUI/Text"; + + /// + /// + /// + public static string bmFontShader = "FairyGUI/BMFont"; + + /// + /// + /// + public static string TMPFontShader = "FairyGUI/TMP"; + + public static int ID_ClipBox; + public static int ID_ClipSoftness; + public static int ID_AlphaTex; + public static int ID_StencilComp; + public static int ID_Stencil; + public static int ID_StencilOp; + public static int ID_StencilReadMask; + public static int ID_ColorMask; + public static int ID_ColorMatrix; + public static int ID_ColorOffset; + public static int ID_BlendSrcFactor; + public static int ID_BlendDstFactor; + public static int ID_ColorOption; + + public static int ID_Stencil2; + + static ShaderConfig() + { + ID_ClipBox = Shader.PropertyToID("_ClipBox"); + ID_ClipSoftness = Shader.PropertyToID("_ClipSoftness"); + ID_AlphaTex = Shader.PropertyToID("_AlphaTex"); + ID_StencilComp = Shader.PropertyToID("_StencilComp"); + ID_Stencil = Shader.PropertyToID("_Stencil"); + ID_StencilOp = Shader.PropertyToID("_StencilOp"); + ID_StencilReadMask = Shader.PropertyToID("_StencilReadMask"); + ID_ColorMask = Shader.PropertyToID("_ColorMask"); + ID_ColorMatrix = Shader.PropertyToID("_ColorMatrix"); + ID_ColorOffset = Shader.PropertyToID("_ColorOffset"); + ID_BlendSrcFactor = Shader.PropertyToID("_BlendSrcFactor"); + ID_BlendDstFactor = Shader.PropertyToID("_BlendDstFactor"); + ID_ColorOption = Shader.PropertyToID("_ColorOption"); + + ID_Stencil2 = Shader.PropertyToID("_StencilRef"); + } + + /// + /// + /// + /// + /// + public static Shader GetShader(string name) + { + Shader shader = Get(name); + if (shader == null) + { + Debug.LogWarning("FairyGUI: shader not found: " + name); + shader = Shader.Find("UI/Default"); + } + shader.hideFlags = DisplayObject.hideFlags; + + return shader; + } + } +} diff --git a/Assets/Scripts/Core/ShaderConfig.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/ShaderConfig.cs.meta similarity index 100% rename from Assets/Scripts/Core/ShaderConfig.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/ShaderConfig.cs.meta diff --git a/Assets/Scripts/Core/Shape.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Shape.cs similarity index 96% rename from Assets/Scripts/Core/Shape.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Shape.cs index 5999084b..36a89d0c 100644 --- a/Assets/Scripts/Core/Shape.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Shape.cs @@ -1,250 +1,250 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class Shape : DisplayObject - { - /// - /// - /// - public Shape() - { - CreateGameObject("Shape"); - graphics = new NGraphics(gameObject); - graphics.texture = NTexture.Empty; - graphics.meshFactory = null; - } - - /// - /// - /// - public Color color - { - get - { - return graphics.color; - } - set - { - graphics.color = value; - graphics.SetMeshDirty(); - } - } - - /// - /// - /// - /// - /// - /// - public void DrawRect(float lineSize, Color lineColor, Color fillColor) - { - RectMesh mesh = graphics.GetMeshFactory(); - mesh.lineWidth = lineSize; - mesh.lineColor = lineColor; - mesh.fillColor = null; - mesh.colors = null; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - public void DrawRect(float lineSize, Color32[] colors) - { - RectMesh mesh = graphics.GetMeshFactory(); - mesh.lineWidth = lineSize; - mesh.colors = colors; - - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void DrawRoundRect(float lineSize, Color lineColor, Color fillColor, - float topLeftRadius, float topRightRadius, float bottomLeftRadius, float bottomRightRadius) - { - RoundedRectMesh mesh = graphics.GetMeshFactory(); - mesh.lineWidth = lineSize; - mesh.lineColor = lineColor; - mesh.fillColor = null; - mesh.topLeftRadius = topLeftRadius; - mesh.topRightRadius = topRightRadius; - mesh.bottomLeftRadius = bottomLeftRadius; - mesh.bottomRightRadius = bottomRightRadius; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - public void DrawEllipse(Color fillColor) - { - EllipseMesh mesh = graphics.GetMeshFactory(); - mesh.lineWidth = 0; - mesh.startDegree = 0; - mesh.endDegreee = 360; - mesh.fillColor = null; - mesh.centerColor = null; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void DrawEllipse(float lineSize, Color centerColor, Color lineColor, Color fillColor, float startDegree, float endDegree) - { - EllipseMesh mesh = graphics.GetMeshFactory(); - mesh.lineWidth = lineSize; - if (centerColor.Equals(fillColor)) - mesh.centerColor = null; - else - mesh.centerColor = centerColor; - mesh.lineColor = lineColor; - mesh.fillColor = null; - mesh.startDegree = startDegree; - mesh.endDegreee = endDegree; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - public void DrawPolygon(IList points, Color fillColor) - { - PolygonMesh mesh = graphics.GetMeshFactory(); - mesh.points.Clear(); - mesh.points.AddRange(points); - mesh.fillColor = null; - mesh.colors = null; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - public void DrawPolygon(IList points, Color32[] colors) - { - PolygonMesh mesh = graphics.GetMeshFactory(); - mesh.points.Clear(); - mesh.points.AddRange(points); - mesh.fillColor = null; - mesh.colors = colors; - - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - /// - /// - public void DrawPolygon(IList points, Color fillColor, float lineSize, Color lineColor) - { - PolygonMesh mesh = graphics.GetMeshFactory(); - mesh.points.Clear(); - mesh.points.AddRange(points); - mesh.fillColor = null; - mesh.lineWidth = lineSize; - mesh.lineColor = lineColor; - mesh.colors = null; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void DrawRegularPolygon(int sides, float lineSize, Color centerColor, Color lineColor, Color fillColor, float rotation, float[] distances) - { - RegularPolygonMesh mesh = graphics.GetMeshFactory(); - mesh.sides = sides; - mesh.lineWidth = lineSize; - mesh.centerColor = centerColor; - mesh.lineColor = lineColor; - mesh.fillColor = null; - mesh.rotation = rotation; - mesh.distances = distances; - - graphics.color = fillColor; - graphics.SetMeshDirty(); - } - - /// - /// - /// - public void Clear() - { - graphics.meshFactory = null; - } - - /// - /// - /// - public bool isEmpty - { - get { return graphics.meshFactory == null; } - } - - protected override DisplayObject HitTest() - { - if (graphics.meshFactory == null) - return null; - - Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); - - IHitTest ht = graphics.meshFactory as IHitTest; - if (ht != null) - return ht.HitTest(_contentRect, localPoint) ? this : null; - else if (_contentRect.Contains(localPoint)) - return this; - else - return null; - } - } -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class Shape : DisplayObject + { + /// + /// + /// + public Shape() + { + CreateGameObject("Shape"); + graphics = new NGraphics(gameObject); + graphics.texture = NTexture.Empty; + graphics.meshFactory = null; + } + + /// + /// + /// + public Color color + { + get + { + return graphics.color; + } + set + { + graphics.color = value; + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + /// + /// + /// + public void DrawRect(float lineSize, Color lineColor, Color fillColor) + { + RectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.colors = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + public void DrawRect(float lineSize, Color32[] colors) + { + RectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + mesh.colors = colors; + + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawRoundRect(float lineSize, Color lineColor, Color fillColor, + float topLeftRadius, float topRightRadius, float bottomLeftRadius, float bottomRightRadius) + { + RoundedRectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.topLeftRadius = topLeftRadius; + mesh.topRightRadius = topRightRadius; + mesh.bottomLeftRadius = bottomLeftRadius; + mesh.bottomRightRadius = bottomRightRadius; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + public void DrawEllipse(Color fillColor) + { + EllipseMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = 0; + mesh.startDegree = 0; + mesh.endDegreee = 360; + mesh.fillColor = null; + mesh.centerColor = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawEllipse(float lineSize, Color centerColor, Color lineColor, Color fillColor, float startDegree, float endDegree) + { + EllipseMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = lineSize; + if (centerColor.Equals(fillColor)) + mesh.centerColor = null; + else + mesh.centerColor = centerColor; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.startDegree = startDegree; + mesh.endDegreee = endDegree; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + public void DrawPolygon(IList points, Color fillColor) + { + PolygonMesh mesh = graphics.GetMeshFactory(); + mesh.points.Clear(); + mesh.points.AddRange(points); + mesh.fillColor = null; + mesh.colors = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + public void DrawPolygon(IList points, Color32[] colors) + { + PolygonMesh mesh = graphics.GetMeshFactory(); + mesh.points.Clear(); + mesh.points.AddRange(points); + mesh.fillColor = null; + mesh.colors = colors; + + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + public void DrawPolygon(IList points, Color fillColor, float lineSize, Color lineColor) + { + PolygonMesh mesh = graphics.GetMeshFactory(); + mesh.points.Clear(); + mesh.points.AddRange(points); + mesh.fillColor = null; + mesh.lineWidth = lineSize; + mesh.lineColor = lineColor; + mesh.colors = null; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawRegularPolygon(int sides, float lineSize, Color centerColor, Color lineColor, Color fillColor, float rotation, float[] distances) + { + RegularPolygonMesh mesh = graphics.GetMeshFactory(); + mesh.sides = sides; + mesh.lineWidth = lineSize; + mesh.centerColor = centerColor; + mesh.lineColor = lineColor; + mesh.fillColor = null; + mesh.rotation = rotation; + mesh.distances = distances; + + graphics.color = fillColor; + graphics.SetMeshDirty(); + } + + /// + /// + /// + public void Clear() + { + graphics.meshFactory = null; + } + + /// + /// + /// + public bool isEmpty + { + get { return graphics.meshFactory == null; } + } + + protected override DisplayObject HitTest() + { + if (graphics.meshFactory == null) + return null; + + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + + IHitTest ht = graphics.meshFactory as IHitTest; + if (ht != null) + return ht.HitTest(_contentRect, localPoint) ? this : null; + else if (_contentRect.Contains(localPoint)) + return this; + else + return null; + } + } +} diff --git a/Assets/Scripts/Core/Shape.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Shape.cs.meta similarity index 100% rename from Assets/Scripts/Core/Shape.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Shape.cs.meta diff --git a/Assets/Scripts/Core/Stage.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stage.cs similarity index 96% rename from Assets/Scripts/Core/Stage.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stage.cs index 6e192b96..0541cf50 100644 --- a/Assets/Scripts/Core/Stage.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stage.cs @@ -72,7 +72,7 @@ public static Stage inst { get { - if (_inst == null) + if (_inst == null || _inst.gameObject == null) Instantiate(); return _inst; @@ -84,7 +84,7 @@ public static Stage inst /// public static void Instantiate() { - if (_inst == null) + if (_inst == null || _inst.gameObject == null) { _inst = new Stage(); GRoot._inst = new GRoot(); diff --git a/Assets/Scripts/Core/Stage.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stage.cs.meta similarity index 100% rename from Assets/Scripts/Core/Stage.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stage.cs.meta diff --git a/Assets/Scripts/Core/StageCamera.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageCamera.cs similarity index 96% rename from Assets/Scripts/Core/StageCamera.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageCamera.cs index 506c5f8a..f6f7467b 100644 --- a/Assets/Scripts/Core/StageCamera.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageCamera.cs @@ -1,196 +1,196 @@ -using System; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// Stage Camera is an orthographic camera for UI rendering. - /// - [ExecuteInEditMode] - [AddComponentMenu("FairyGUI/UI Camera")] - public class StageCamera : MonoBehaviour - { - /// - /// - /// - public bool constantSize = true; - - /// - /// - /// - [NonSerialized] - public float unitsPerPixel = 0.02f; - - [NonSerialized] - public Transform cachedTransform; - [NonSerialized] - public Camera cachedCamera; - - [NonSerialized] - int screenWidth; - [NonSerialized] - int screenHeight; - [NonSerialized] - bool isMain; - [NonSerialized] - Display _display; - - /// - /// - /// - [NonSerialized] - public static Camera main; - - /// - /// - /// - [NonSerialized] - public static int screenSizeVer = 1; - - public const string Name = "Stage Camera"; - public const string LayerName = "UI"; - - public static float DefaultCameraSize = 5; - public static float DefaultUnitsPerPixel = 0.02f; - - void OnEnable() - { - cachedTransform = this.transform; - cachedCamera = this.GetComponent(); - if (this.gameObject.name == Name) - { - main = cachedCamera; - isMain = true; - } - - if (Display.displays.Length > 1 && cachedCamera.targetDisplay != 0 && cachedCamera.targetDisplay < Display.displays.Length) - _display = Display.displays[cachedCamera.targetDisplay]; - - if (_display == null) - OnScreenSizeChanged(Screen.width, Screen.height); - else - OnScreenSizeChanged(_display.renderingWidth, _display.renderingHeight); - } - - void Update() - { - if (_display == null) - { - if (screenWidth != Screen.width || screenHeight != Screen.height) - OnScreenSizeChanged(Screen.width, Screen.height); - } - else - { - if (screenWidth != _display.renderingWidth || screenHeight != _display.renderingHeight) - OnScreenSizeChanged(_display.renderingWidth, _display.renderingHeight); - } - } - - void OnScreenSizeChanged(int newWidth, int newHeight) - { - if (newWidth == 0 || newHeight == 0) - return; - - screenWidth = newWidth; - screenHeight = newHeight; - - if (constantSize) - { - cachedCamera.orthographicSize = DefaultCameraSize; - unitsPerPixel = cachedCamera.orthographicSize * 2 / screenHeight; - } - else - { - unitsPerPixel = DefaultUnitsPerPixel; - cachedCamera.orthographicSize = screenHeight / 2 * unitsPerPixel; - } - cachedTransform.localPosition = new Vector3(cachedCamera.orthographicSize * screenWidth / screenHeight, -cachedCamera.orthographicSize); - - if (isMain) - { - screenSizeVer++; - if (Application.isPlaying) - Stage.inst.HandleScreenSizeChanged(screenWidth, screenHeight, unitsPerPixel); - else - { - UIContentScaler scaler = GameObject.FindObjectOfType(); - if (scaler != null) - scaler.ApplyChange(); - else - UIContentScaler.scaleFactor = 1; - } - } - } - - void OnRenderObject() - { - //Update和OnGUI在EditMode的调用都不那么及时,OnRenderObject则比较频繁,可以保证界面及时刷新。所以使用OnRenderObject - if (isMain && !Application.isPlaying) - { - EMRenderSupport.Update(); - } - } - - public void ApplyModifiedProperties() - { - screenWidth = 0; //force OnScreenSizeChanged called in next update - } - - /// - /// Check if there is a stage camera in the scene. If none, create one. - /// - public static void CheckMainCamera() - { - if (GameObject.Find(Name) == null) - { - int layer = LayerMask.NameToLayer(LayerName); - CreateCamera(Name, 1 << layer); - } - - HitTestContext.cachedMainCamera = Camera.main; - } - - /// - /// - /// - public static void CheckCaptureCamera() - { - if (GameObject.Find(Name) == null) - { - int layer = LayerMask.NameToLayer(LayerName); - CreateCamera(Name, 1 << layer); - } - } - - /// - /// - /// - /// - /// - /// - public static Camera CreateCamera(string name, int cullingMask) - { - GameObject cameraObject = new GameObject(name); - Camera camera = cameraObject.AddComponent(); - camera.depth = 1; - camera.cullingMask = cullingMask; - camera.clearFlags = CameraClearFlags.Depth; - camera.orthographic = true; - camera.orthographicSize = DefaultCameraSize; - camera.nearClipPlane = -30; - camera.farClipPlane = 30; - -#if UNITY_5_4_OR_NEWER - camera.stereoTargetEye = StereoTargetEyeMask.None; -#endif - -#if UNITY_5_6_OR_NEWER - camera.allowHDR = false; - camera.allowMSAA = false; -#endif - cameraObject.AddComponent(); - - return camera; - } - } -} +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Stage Camera is an orthographic camera for UI rendering. + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Camera")] + public class StageCamera : MonoBehaviour + { + /// + /// + /// + public bool constantSize = true; + + /// + /// + /// + [NonSerialized] + public float unitsPerPixel = 0.02f; + + [NonSerialized] + public Transform cachedTransform; + [NonSerialized] + public Camera cachedCamera; + + [NonSerialized] + int screenWidth; + [NonSerialized] + int screenHeight; + [NonSerialized] + bool isMain; + [NonSerialized] + Display _display; + + /// + /// + /// + [NonSerialized] + public static Camera main; + + /// + /// + /// + [NonSerialized] + public static int screenSizeVer = 1; + + public const string Name = "Stage Camera"; + public const string LayerName = "UI"; + + public static float DefaultCameraSize = 5; + public static float DefaultUnitsPerPixel = 0.02f; + + void OnEnable() + { + cachedTransform = this.transform; + cachedCamera = this.GetComponent(); + if (this.gameObject.name == Name) + { + main = cachedCamera; + isMain = true; + } + + if (Display.displays.Length > 1 && cachedCamera.targetDisplay != 0 && cachedCamera.targetDisplay < Display.displays.Length) + _display = Display.displays[cachedCamera.targetDisplay]; + + if (_display == null) + OnScreenSizeChanged(Screen.width, Screen.height); + else + OnScreenSizeChanged(_display.renderingWidth, _display.renderingHeight); + } + + void Update() + { + if (_display == null) + { + if (screenWidth != Screen.width || screenHeight != Screen.height) + OnScreenSizeChanged(Screen.width, Screen.height); + } + else + { + if (screenWidth != _display.renderingWidth || screenHeight != _display.renderingHeight) + OnScreenSizeChanged(_display.renderingWidth, _display.renderingHeight); + } + } + + void OnScreenSizeChanged(int newWidth, int newHeight) + { + if (newWidth == 0 || newHeight == 0) + return; + + screenWidth = newWidth; + screenHeight = newHeight; + + if (constantSize) + { + cachedCamera.orthographicSize = DefaultCameraSize; + unitsPerPixel = cachedCamera.orthographicSize * 2 / screenHeight; + } + else + { + unitsPerPixel = DefaultUnitsPerPixel; + cachedCamera.orthographicSize = screenHeight / 2 * unitsPerPixel; + } + cachedTransform.localPosition = new Vector3(cachedCamera.orthographicSize * screenWidth / screenHeight, -cachedCamera.orthographicSize); + + if (isMain) + { + screenSizeVer++; + if (Application.isPlaying) + Stage.inst.HandleScreenSizeChanged(screenWidth, screenHeight, unitsPerPixel); + else + { + UIContentScaler scaler = GameObject.FindObjectOfType(); + if (scaler != null) + scaler.ApplyChange(); + else + UIContentScaler.scaleFactor = 1; + } + } + } + + void OnRenderObject() + { + //Update和OnGUI在EditMode的调用都不那么及时,OnRenderObject则比较频繁,可以保证界面及时刷新。所以使用OnRenderObject + if (isMain && !Application.isPlaying) + { + EMRenderSupport.Update(); + } + } + + public void ApplyModifiedProperties() + { + screenWidth = 0; //force OnScreenSizeChanged called in next update + } + + /// + /// Check if there is a stage camera in the scene. If none, create one. + /// + public static void CheckMainCamera() + { + if (GameObject.Find(Name) == null) + { + int layer = LayerMask.NameToLayer(LayerName); + CreateCamera(Name, 1 << layer); + } + + HitTestContext.cachedMainCamera = Camera.main; + } + + /// + /// + /// + public static void CheckCaptureCamera() + { + if (GameObject.Find(Name) == null) + { + int layer = LayerMask.NameToLayer(LayerName); + CreateCamera(Name, 1 << layer); + } + } + + /// + /// + /// + /// + /// + /// + public static Camera CreateCamera(string name, int cullingMask) + { + GameObject cameraObject = new GameObject(name); + Camera camera = cameraObject.AddComponent(); + camera.depth = 1; + camera.cullingMask = cullingMask; + camera.clearFlags = CameraClearFlags.Depth; + camera.orthographic = true; + camera.orthographicSize = DefaultCameraSize; + camera.nearClipPlane = -30; + camera.farClipPlane = 30; + +#if UNITY_5_4_OR_NEWER + camera.stereoTargetEye = StereoTargetEyeMask.None; +#endif + +#if UNITY_5_6_OR_NEWER + camera.allowHDR = false; + camera.allowMSAA = false; +#endif + cameraObject.AddComponent(); + + return camera; + } + } +} diff --git a/Assets/Scripts/Core/StageCamera.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageCamera.cs.meta similarity index 100% rename from Assets/Scripts/Core/StageCamera.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageCamera.cs.meta diff --git a/Assets/Scripts/Core/StageEngine.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageEngine.cs similarity index 74% rename from Assets/Scripts/Core/StageEngine.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageEngine.cs index 9dc31b57..7ef2c856 100644 --- a/Assets/Scripts/Core/StageEngine.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageEngine.cs @@ -1,4 +1,5 @@ -using UnityEngine; +using System; +using UnityEngine; namespace FairyGUI { @@ -43,6 +44,11 @@ void OnApplicationQuit() { beingQuit = true; UIPackage.RemoveAllPackages(); + + // * 确保编辑器就算不刷新domain也能清理掉. + // ! 有点难改先放弃修改了. + // FontManager.Clear(); + // TweenManager.Destroy(); } } } diff --git a/Assets/Scripts/Core/StageEngine.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageEngine.cs.meta similarity index 100% rename from Assets/Scripts/Core/StageEngine.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/StageEngine.cs.meta diff --git a/Assets/Scripts/Core/Stats.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stats.cs similarity index 94% rename from Assets/Scripts/Core/Stats.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stats.cs index 8f5f6aab..16a15b41 100644 --- a/Assets/Scripts/Core/Stats.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stats.cs @@ -1,29 +1,29 @@ - -namespace FairyGUI -{ - /// - /// - /// - public class Stats - { - /// - /// - /// - public static int ObjectCount; - - /// - /// - /// - public static int GraphicsCount; - - /// - /// - /// - public static int LatestObjectCreation; - - /// - /// - /// - public static int LatestGraphicsCreation; - } -} + +namespace FairyGUI +{ + /// + /// + /// + public class Stats + { + /// + /// + /// + public static int ObjectCount; + + /// + /// + /// + public static int GraphicsCount; + + /// + /// + /// + public static int LatestObjectCreation; + + /// + /// + /// + public static int LatestGraphicsCreation; + } +} diff --git a/Assets/Scripts/Core/Stats.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stats.cs.meta similarity index 100% rename from Assets/Scripts/Core/Stats.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Stats.cs.meta diff --git a/Assets/Scripts/Core/Text.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text.meta similarity index 100% rename from Assets/Scripts/Core/Text.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text.meta diff --git a/Assets/Scripts/Core/Text/BaseFont.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BaseFont.cs similarity index 96% rename from Assets/Scripts/Core/Text/BaseFont.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BaseFont.cs index 27ddfea2..6e1e11c7 100644 --- a/Assets/Scripts/Core/Text/BaseFont.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BaseFont.cs @@ -1,108 +1,108 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// Base class for all kind of fonts. - /// - public class BaseFont - { - /// - /// The name of this font object. - /// - public string name; - - /// - /// The texture of this font object. - /// - public NTexture mainTexture; - - /// - /// Can this font be tinted? Will be true for dynamic font and fonts generated by BMFont. - /// - public bool canTint; - - /// - /// If true, it will use extra vertices to enhance bold effect - /// - public bool customBold; - - /// - /// If true, it will use extra vertices to enhance bold effect ONLY when it is in italic style. - /// - public bool customBoldAndItalic; - - /// - /// If true, it will use extra vertices(4 direction) to enhance outline effect - /// - public bool customOutline; - - /// - /// The shader for this font object. - /// - public string shader; - - /// - /// Keep text crisp. - /// - public bool keepCrisp; - - /// - /// - /// - public int version; - - protected internal static bool textRebuildFlag; - - protected const float SupScale = 0.58f; - protected const float SupOffset = 0.33f; - - virtual public void UpdateGraphics(NGraphics graphics) - { - } - - virtual public void SetFormat(TextFormat format, float fontSizeScale) - { - } - - virtual public void PrepareCharacters(string text) - { - } - - virtual public bool GetGlyph(char ch, out float width, out float height, out float baseline) - { - width = 0; - height = 0; - baseline = 0; - return false; - } - - virtual public int DrawGlyph(float x, float y, - List vertList, List uvList, List uv2List, List colList) - { - return 0; - } - - virtual public int DrawLine(float x, float y, float width, int fontSize, int type, - List vertList, List uvList, List uv2List, List colList) - { - return 0; - } - - virtual public bool HasCharacter(char ch) - { - return false; - } - - virtual public int GetLineHeight(int size) - { - return 0; - } - - virtual public void Dispose() - { - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Base class for all kind of fonts. + /// + public class BaseFont + { + /// + /// The name of this font object. + /// + public string name; + + /// + /// The texture of this font object. + /// + public NTexture mainTexture; + + /// + /// Can this font be tinted? Will be true for dynamic font and fonts generated by BMFont. + /// + public bool canTint; + + /// + /// If true, it will use extra vertices to enhance bold effect + /// + public bool customBold; + + /// + /// If true, it will use extra vertices to enhance bold effect ONLY when it is in italic style. + /// + public bool customBoldAndItalic; + + /// + /// If true, it will use extra vertices(4 direction) to enhance outline effect + /// + public bool customOutline; + + /// + /// The shader for this font object. + /// + public string shader; + + /// + /// Keep text crisp. + /// + public bool keepCrisp; + + /// + /// + /// + public int version; + + protected internal static bool textRebuildFlag; + + protected const float SupScale = 0.58f; + protected const float SupOffset = 0.33f; + + virtual public void UpdateGraphics(NGraphics graphics) + { + } + + virtual public void SetFormat(TextFormat format, float fontSizeScale) + { + } + + virtual public void PrepareCharacters(string text) + { + } + + virtual public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + width = 0; + height = 0; + baseline = 0; + return false; + } + + virtual public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + return 0; + } + + virtual public int DrawLine(float x, float y, float width, int fontSize, int type, + List vertList, List uvList, List uv2List, List colList) + { + return 0; + } + + virtual public bool HasCharacter(char ch) + { + return false; + } + + virtual public int GetLineHeight(int size) + { + return 0; + } + + virtual public void Dispose() + { + } + } +} diff --git a/Assets/Scripts/Core/Text/BaseFont.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BaseFont.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/BaseFont.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BaseFont.cs.meta diff --git a/Assets/Scripts/Core/Text/BitmapFont.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BitmapFont.cs similarity index 96% rename from Assets/Scripts/Core/Text/BitmapFont.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BitmapFont.cs index 2268fe13..92069acb 100644 --- a/Assets/Scripts/Core/Text/BitmapFont.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BitmapFont.cs @@ -1,177 +1,177 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class BitmapFont : BaseFont - { - /// - /// - /// - public class BMGlyph - { - public float x; - public float y; - public float width; - public float height; - public int advance; - public int lineHeight; - public Vector2[] uv = new Vector2[4]; - public int channel;//0-n/a, 1-r,2-g,3-b,4-alpha - } - - /// - /// - /// - public int size; - - /// - /// - /// - public bool resizable; - - /// - /// Font generated by BMFont use channels. - /// - public bool hasChannel; - - protected Dictionary _dict; - protected BMGlyph _glyph; - float _scale; - - public BitmapFont() - { - this.canTint = true; - this.hasChannel = false; - this.customOutline = true; - this.shader = ShaderConfig.bmFontShader; - - _dict = new Dictionary(); - _scale = 1; - } - - public void AddChar(char ch, BMGlyph glyph) - { - _dict[ch] = glyph; - } - - override public void SetFormat(TextFormat format, float fontSizeScale) - { - if (resizable) - _scale = (float)format.size / size * fontSizeScale; - else - _scale = fontSizeScale; - - if (canTint) - format.FillVertexColors(vertexColors); - } - - override public bool GetGlyph(char ch, out float width, out float height, out float baseline) - { - if (ch == ' ') - { - width = Mathf.RoundToInt(size * _scale / 2); - height = Mathf.RoundToInt(size * _scale); - baseline = height; - _glyph = null; - return true; - } - else if (_dict.TryGetValue((int)ch, out _glyph)) - { - width = Mathf.RoundToInt(_glyph.advance * _scale); - height = Mathf.RoundToInt(_glyph.lineHeight * _scale); - baseline = height; - return true; - } - else - { - width = 0; - height = 0; - baseline = 0; - return false; - } - } - - static Vector3 bottomLeft; - static Vector3 topLeft; - static Vector3 topRight; - static Vector3 bottomRight; - - static Color32[] vertexColors = new Color32[4]; - - override public int DrawGlyph(float x, float y, - List vertList, List uvList, List uv2List, List colList) - { - if (_glyph == null) //space - return 0; - - topLeft.x = x + _glyph.x * _scale; - topLeft.y = y + (_glyph.lineHeight - _glyph.y) * _scale; - bottomRight.x = x + (_glyph.x + _glyph.width) * _scale; - bottomRight.y = topLeft.y - _glyph.height * _scale; - - topRight.x = bottomRight.x; - topRight.y = topLeft.y; - bottomLeft.x = topLeft.x; - bottomLeft.y = bottomRight.y; - - vertList.Add(bottomLeft); - vertList.Add(topLeft); - vertList.Add(topRight); - vertList.Add(bottomRight); - - uvList.AddRange(_glyph.uv); - - if (hasChannel) - { - Vector2 channel = new Vector2(_glyph.channel, 0); - uv2List.Add(channel); - uv2List.Add(channel); - uv2List.Add(channel); - uv2List.Add(channel); - } - - if (canTint) - { - colList.Add(vertexColors[0]); - colList.Add(vertexColors[1]); - colList.Add(vertexColors[2]); - colList.Add(vertexColors[3]); - } - else - { - colList.Add(Color.white); - colList.Add(Color.white); - colList.Add(Color.white); - colList.Add(Color.white); - } - - return 4; - } - - override public bool HasCharacter(char ch) - { - return ch == ' ' || _dict.ContainsKey((int)ch); - } - - override public int GetLineHeight(int size) - { - if (_dict.Count > 0) - { - using (var et = _dict.GetEnumerator()) - { - et.MoveNext(); - if (resizable) - return Mathf.RoundToInt((float)et.Current.Value.lineHeight * size / this.size); - else - return et.Current.Value.lineHeight; - } - } - else - return 0; - } - } -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class BitmapFont : BaseFont + { + /// + /// + /// + public class BMGlyph + { + public float x; + public float y; + public float width; + public float height; + public int advance; + public int lineHeight; + public Vector2[] uv = new Vector2[4]; + public int channel;//0-n/a, 1-r,2-g,3-b,4-alpha + } + + /// + /// + /// + public int size; + + /// + /// + /// + public bool resizable; + + /// + /// Font generated by BMFont use channels. + /// + public bool hasChannel; + + protected Dictionary _dict; + protected BMGlyph _glyph; + float _scale; + + public BitmapFont() + { + this.canTint = true; + this.hasChannel = false; + this.customOutline = true; + this.shader = ShaderConfig.bmFontShader; + + _dict = new Dictionary(); + _scale = 1; + } + + public void AddChar(char ch, BMGlyph glyph) + { + _dict[ch] = glyph; + } + + override public void SetFormat(TextFormat format, float fontSizeScale) + { + if (resizable) + _scale = (float)format.size / size * fontSizeScale; + else + _scale = fontSizeScale; + + if (canTint) + format.FillVertexColors(vertexColors); + } + + override public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + if (ch == ' ') + { + width = Mathf.RoundToInt(size * _scale / 2); + height = Mathf.RoundToInt(size * _scale); + baseline = height; + _glyph = null; + return true; + } + else if (_dict.TryGetValue((int)ch, out _glyph)) + { + width = Mathf.RoundToInt(_glyph.advance * _scale); + height = Mathf.RoundToInt(_glyph.lineHeight * _scale); + baseline = height; + return true; + } + else + { + width = 0; + height = 0; + baseline = 0; + return false; + } + } + + static Vector3 bottomLeft; + static Vector3 topLeft; + static Vector3 topRight; + static Vector3 bottomRight; + + static Color32[] vertexColors = new Color32[4]; + + override public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + if (_glyph == null) //space + return 0; + + topLeft.x = x + _glyph.x * _scale; + topLeft.y = y + (_glyph.lineHeight - _glyph.y) * _scale; + bottomRight.x = x + (_glyph.x + _glyph.width) * _scale; + bottomRight.y = topLeft.y - _glyph.height * _scale; + + topRight.x = bottomRight.x; + topRight.y = topLeft.y; + bottomLeft.x = topLeft.x; + bottomLeft.y = bottomRight.y; + + vertList.Add(bottomLeft); + vertList.Add(topLeft); + vertList.Add(topRight); + vertList.Add(bottomRight); + + uvList.AddRange(_glyph.uv); + + if (hasChannel) + { + Vector2 channel = new Vector2(_glyph.channel, 0); + uv2List.Add(channel); + uv2List.Add(channel); + uv2List.Add(channel); + uv2List.Add(channel); + } + + if (canTint) + { + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + } + else + { + colList.Add(Color.white); + colList.Add(Color.white); + colList.Add(Color.white); + colList.Add(Color.white); + } + + return 4; + } + + override public bool HasCharacter(char ch) + { + return ch == ' ' || _dict.ContainsKey((int)ch); + } + + override public int GetLineHeight(int size) + { + if (_dict.Count > 0) + { + using (var et = _dict.GetEnumerator()) + { + et.MoveNext(); + if (resizable) + return Mathf.RoundToInt((float)et.Current.Value.lineHeight * size / this.size); + else + return et.Current.Value.lineHeight; + } + } + else + return 0; + } + } +} diff --git a/Assets/Scripts/Core/Text/BitmapFont.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BitmapFont.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/BitmapFont.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/BitmapFont.cs.meta diff --git a/Assets/Scripts/Core/Text/DynamicFont.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/DynamicFont.cs similarity index 97% rename from Assets/Scripts/Core/Text/DynamicFont.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/DynamicFont.cs index 7e7f4600..19f91693 100644 --- a/Assets/Scripts/Core/Text/DynamicFont.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/DynamicFont.cs @@ -1,385 +1,385 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class DynamicFont : BaseFont - { - Font _font; - int _size; - float _ascent; - float _lineHeight; - float _scale; - TextFormat _format; - FontStyle _style; - bool _boldVertice; - CharacterInfo _char; - CharacterInfo _lineChar; - bool _gotLineChar; - - public DynamicFont() - { - this.canTint = true; - this.keepCrisp = true; - this.customOutline = true; - this.shader = ShaderConfig.textShader; - } - - /// - /// - /// - /// - /// - /// - public DynamicFont(string name, Font font) : this() - { - this.name = name; - this.nativeFont = font; - } - - override public void Dispose() - { - Font.textureRebuilt -= textureRebuildCallback; - } - - public Font nativeFont - { - get { return _font; } - set - { - if (_font != null) - Font.textureRebuilt -= textureRebuildCallback; - - _font = value; - Font.textureRebuilt += textureRebuildCallback; - _font.hideFlags = DisplayObject.hideFlags; - _font.material.hideFlags = DisplayObject.hideFlags; - _font.material.mainTexture.hideFlags = DisplayObject.hideFlags; - - if (mainTexture != null) - mainTexture.Dispose(); - mainTexture = new NTexture(_font.material.mainTexture); - mainTexture.destroyMethod = DestroyMethod.None; - - // _ascent = _font.ascent; - // _lineHeight = _font.lineHeight; - _ascent = _font.fontSize; - _lineHeight = _font.fontSize * 1.25f; - } - } - - override public void SetFormat(TextFormat format, float fontSizeScale) - { - _format = format; - float size = format.size * fontSizeScale; - if (keepCrisp) - size *= UIContentScaler.scaleFactor; - if (_format.specialStyle == TextFormat.SpecialStyle.Subscript || _format.specialStyle == TextFormat.SpecialStyle.Superscript) - size *= SupScale; - _size = Mathf.FloorToInt(size); - if (_size == 0) - _size = 1; - _scale = (float)_size / _font.fontSize; - - if (format.bold && !customBold) - { - if (format.italic) - { - if (customBoldAndItalic) - _style = FontStyle.Italic; - else - _style = FontStyle.BoldAndItalic; - } - else - _style = FontStyle.Bold; - } - else - { - if (format.italic) - _style = FontStyle.Italic; - else - _style = FontStyle.Normal; - } - - _boldVertice = format.bold && (customBold || (format.italic && customBoldAndItalic)); - format.FillVertexColors(vertexColors); - } - - override public void PrepareCharacters(string text) - { - _font.RequestCharactersInTexture(text, _size, _style); - } - - override public bool GetGlyph(char ch, out float width, out float height, out float baseline) - { - if (!_font.GetCharacterInfo(ch, out _char, _size, _style)) - { - if (ch == ' ') - { - //space may not be prepared, try again - _font.RequestCharactersInTexture(" ", _size, _style); - _font.GetCharacterInfo(ch, out _char, _size, _style); - } - else - { - width = height = baseline = 0; - return false; - } - } - - width = _char.advance; - height = _lineHeight * _scale; - baseline = _ascent * _scale; - if (_boldVertice) - width++; - - if (_format.specialStyle == TextFormat.SpecialStyle.Subscript) - { - height /= SupScale; - baseline /= SupScale; - } - else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript) - { - height = height / SupScale + baseline * SupOffset; - baseline *= (SupOffset + 1 / SupScale); - } - - height = Mathf.RoundToInt(height); - baseline = Mathf.RoundToInt(baseline); - - if (keepCrisp) - { - width /= UIContentScaler.scaleFactor; - height /= UIContentScaler.scaleFactor; - baseline /= UIContentScaler.scaleFactor; - } - - return true; - } - - static Vector3 bottomLeft; - static Vector3 topLeft; - static Vector3 topRight; - static Vector3 bottomRight; - - static Vector2 uvBottomLeft; - static Vector2 uvTopLeft; - static Vector2 uvTopRight; - static Vector2 uvBottomRight; - - static Color32[] vertexColors = new Color32[4]; - - static Vector3[] BOLD_OFFSET = new Vector3[] - { - new Vector3(-0.5f, 0f, 0f), - new Vector3(0.5f, 0f, 0f), - new Vector3(0f, -0.5f, 0f), - new Vector3(0f, 0.5f, 0f) - }; - - override public int DrawGlyph(float x, float y, - List vertList, List uvList, List uv2List, List colList) - { - topLeft.x = _char.minX; - topLeft.y = _char.maxY; - bottomRight.x = _char.maxX; - if (_char.glyphWidth == 0) //zero width, space etc - bottomRight.x = topLeft.x + _size / 2; - bottomRight.y = _char.minY; - - if (keepCrisp) - { - topLeft /= UIContentScaler.scaleFactor; - bottomRight /= UIContentScaler.scaleFactor; - } - - if (_format.specialStyle == TextFormat.SpecialStyle.Subscript) - y = y - Mathf.RoundToInt(_ascent * _scale * SupOffset); - else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript) - y = y + Mathf.RoundToInt(_ascent * _scale * (1 / SupScale - 1 + SupOffset)); - - topLeft.x += x; - topLeft.y += y; - bottomRight.x += x; - bottomRight.y += y; - - topRight.x = bottomRight.x; - topRight.y = topLeft.y; - bottomLeft.x = topLeft.x; - bottomLeft.y = bottomRight.y; - - vertList.Add(bottomLeft); - vertList.Add(topLeft); - vertList.Add(topRight); - vertList.Add(bottomRight); - - uvBottomLeft = _char.uvBottomLeft; - uvTopLeft = _char.uvTopLeft; - uvTopRight = _char.uvTopRight; - uvBottomRight = _char.uvBottomRight; - - uvList.Add(uvBottomLeft); - uvList.Add(uvTopLeft); - uvList.Add(uvTopRight); - uvList.Add(uvBottomRight); - - colList.Add(vertexColors[0]); - colList.Add(vertexColors[1]); - colList.Add(vertexColors[2]); - colList.Add(vertexColors[3]); - - if (_boldVertice) - { - for (int b = 0; b < 4; b++) - { - Vector3 boldOffset = BOLD_OFFSET[b]; - - vertList.Add(bottomLeft + boldOffset); - vertList.Add(topLeft + boldOffset); - vertList.Add(topRight + boldOffset); - vertList.Add(bottomRight + boldOffset); - - uvList.Add(uvBottomLeft); - uvList.Add(uvTopLeft); - uvList.Add(uvTopRight); - uvList.Add(uvBottomRight); - - colList.Add(vertexColors[0]); - colList.Add(vertexColors[1]); - colList.Add(vertexColors[2]); - colList.Add(vertexColors[3]); - } - - return 20; - } - else - return 4; - } - - override public int DrawLine(float x, float y, float width, int fontSize, int type, - List vertList, List uvList, List uv2List, List colList) - { - if (!_gotLineChar) - { - _gotLineChar = true; - _font.RequestCharactersInTexture("_", 50, FontStyle.Normal); - _font.GetCharacterInfo('_', out _lineChar, 50, FontStyle.Normal); - } - - float thickness; - float offset; - - thickness = Mathf.Max(1, fontSize / 16f); //guest underline size - if (type == 0) - offset = Mathf.RoundToInt(_lineChar.minY * (float)fontSize / 50 + thickness); - else - offset = Mathf.RoundToInt(_ascent * 0.4f * fontSize / _font.fontSize); - if (thickness < 1) - thickness = 1; - - topLeft.x = x; - topLeft.y = y + offset; - bottomRight.x = x + width; - bottomRight.y = topLeft.y - thickness; - - topRight.x = bottomRight.x; - topRight.y = topLeft.y; - bottomLeft.x = topLeft.x; - bottomLeft.y = bottomRight.y; - - vertList.Add(bottomLeft); - vertList.Add(topLeft); - vertList.Add(topRight); - vertList.Add(bottomRight); - - uvBottomLeft = _lineChar.uvBottomLeft; - uvTopLeft = _lineChar.uvTopLeft; - uvTopRight = _lineChar.uvTopRight; - uvBottomRight = _lineChar.uvBottomRight; - - //取中点的UV - Vector2 u0; - if (_lineChar.uvBottomLeft.x != _lineChar.uvBottomRight.x) - u0.x = (_lineChar.uvBottomLeft.x + _lineChar.uvBottomRight.x) * 0.5f; - else - u0.x = (_lineChar.uvBottomLeft.x + _lineChar.uvTopLeft.x) * 0.5f; - - if (_lineChar.uvBottomLeft.y != _lineChar.uvTopLeft.y) - u0.y = (_lineChar.uvBottomLeft.y + _lineChar.uvTopLeft.y) * 0.5f; - else - u0.y = (_lineChar.uvBottomLeft.y + _lineChar.uvBottomRight.y) * 0.5f; - - uvList.Add(u0); - uvList.Add(u0); - uvList.Add(u0); - uvList.Add(u0); - - colList.Add(vertexColors[0]); - colList.Add(vertexColors[1]); - colList.Add(vertexColors[2]); - colList.Add(vertexColors[3]); - - if (_boldVertice) - { - for (int b = 0; b < 4; b++) - { - Vector3 boldOffset = BOLD_OFFSET[b]; - - vertList.Add(bottomLeft + boldOffset); - vertList.Add(topLeft + boldOffset); - vertList.Add(topRight + boldOffset); - vertList.Add(bottomRight + boldOffset); - - uvList.Add(u0); - uvList.Add(u0); - uvList.Add(u0); - uvList.Add(u0); - - colList.Add(vertexColors[0]); - colList.Add(vertexColors[1]); - colList.Add(vertexColors[2]); - colList.Add(vertexColors[3]); - } - - return 20; - } - else - return 4; - } - - override public bool HasCharacter(char ch) - { - return _font.HasCharacter(ch); - } - - override public int GetLineHeight(int size) - { - return Mathf.RoundToInt(_lineHeight * size / _font.fontSize); - } - - void textureRebuildCallback(Font targetFont) - { - if (_font != targetFont) - return; - - if (mainTexture == null || !Application.isPlaying) - { - mainTexture = new NTexture(_font.material.mainTexture); - mainTexture.destroyMethod = DestroyMethod.None; - } - else - mainTexture.Reload(_font.material.mainTexture, null); - - _gotLineChar = false; - - textRebuildFlag = true; - version++; - - //Debug.Log("Font texture rebuild: " + name + "," + mainTexture.width + "," + mainTexture.height); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class DynamicFont : BaseFont + { + Font _font; + int _size; + float _ascent; + float _lineHeight; + float _scale; + TextFormat _format; + FontStyle _style; + bool _boldVertice; + CharacterInfo _char; + CharacterInfo _lineChar; + bool _gotLineChar; + + public DynamicFont() + { + this.canTint = true; + this.keepCrisp = true; + this.customOutline = true; + this.shader = ShaderConfig.textShader; + } + + /// + /// + /// + /// + /// + /// + public DynamicFont(string name, Font font) : this() + { + this.name = name; + this.nativeFont = font; + } + + override public void Dispose() + { + Font.textureRebuilt -= textureRebuildCallback; + } + + public Font nativeFont + { + get { return _font; } + set + { + if (_font != null) + Font.textureRebuilt -= textureRebuildCallback; + + _font = value; + Font.textureRebuilt += textureRebuildCallback; + _font.hideFlags = DisplayObject.hideFlags; + _font.material.hideFlags = DisplayObject.hideFlags; + _font.material.mainTexture.hideFlags = DisplayObject.hideFlags; + + if (mainTexture != null) + mainTexture.Dispose(); + mainTexture = new NTexture(_font.material.mainTexture); + mainTexture.destroyMethod = DestroyMethod.None; + + // _ascent = _font.ascent; + // _lineHeight = _font.lineHeight; + _ascent = _font.fontSize; + _lineHeight = _font.fontSize * 1.25f; + } + } + + override public void SetFormat(TextFormat format, float fontSizeScale) + { + _format = format; + float size = format.size * fontSizeScale; + if (keepCrisp) + size *= UIContentScaler.scaleFactor; + if (_format.specialStyle == TextFormat.SpecialStyle.Subscript || _format.specialStyle == TextFormat.SpecialStyle.Superscript) + size *= SupScale; + _size = Mathf.FloorToInt(size); + if (_size == 0) + _size = 1; + _scale = (float)_size / _font.fontSize; + + if (format.bold && !customBold) + { + if (format.italic) + { + if (customBoldAndItalic) + _style = FontStyle.Italic; + else + _style = FontStyle.BoldAndItalic; + } + else + _style = FontStyle.Bold; + } + else + { + if (format.italic) + _style = FontStyle.Italic; + else + _style = FontStyle.Normal; + } + + _boldVertice = format.bold && (customBold || (format.italic && customBoldAndItalic)); + format.FillVertexColors(vertexColors); + } + + override public void PrepareCharacters(string text) + { + _font.RequestCharactersInTexture(text, _size, _style); + } + + override public bool GetGlyph(char ch, out float width, out float height, out float baseline) + { + if (!_font.GetCharacterInfo(ch, out _char, _size, _style)) + { + if (ch == ' ') + { + //space may not be prepared, try again + _font.RequestCharactersInTexture(" ", _size, _style); + _font.GetCharacterInfo(ch, out _char, _size, _style); + } + else + { + width = height = baseline = 0; + return false; + } + } + + width = _char.advance; + height = _lineHeight * _scale; + baseline = _ascent * _scale; + if (_boldVertice) + width++; + + if (_format.specialStyle == TextFormat.SpecialStyle.Subscript) + { + height /= SupScale; + baseline /= SupScale; + } + else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript) + { + height = height / SupScale + baseline * SupOffset; + baseline *= (SupOffset + 1 / SupScale); + } + + height = Mathf.RoundToInt(height); + baseline = Mathf.RoundToInt(baseline); + + if (keepCrisp) + { + width /= UIContentScaler.scaleFactor; + height /= UIContentScaler.scaleFactor; + baseline /= UIContentScaler.scaleFactor; + } + + return true; + } + + static Vector3 bottomLeft; + static Vector3 topLeft; + static Vector3 topRight; + static Vector3 bottomRight; + + static Vector2 uvBottomLeft; + static Vector2 uvTopLeft; + static Vector2 uvTopRight; + static Vector2 uvBottomRight; + + static Color32[] vertexColors = new Color32[4]; + + static Vector3[] BOLD_OFFSET = new Vector3[] + { + new Vector3(-0.5f, 0f, 0f), + new Vector3(0.5f, 0f, 0f), + new Vector3(0f, -0.5f, 0f), + new Vector3(0f, 0.5f, 0f) + }; + + override public int DrawGlyph(float x, float y, + List vertList, List uvList, List uv2List, List colList) + { + topLeft.x = _char.minX; + topLeft.y = _char.maxY; + bottomRight.x = _char.maxX; + if (_char.glyphWidth == 0) //zero width, space etc + bottomRight.x = topLeft.x + _size / 2; + bottomRight.y = _char.minY; + + if (keepCrisp) + { + topLeft /= UIContentScaler.scaleFactor; + bottomRight /= UIContentScaler.scaleFactor; + } + + if (_format.specialStyle == TextFormat.SpecialStyle.Subscript) + y = y - Mathf.RoundToInt(_ascent * _scale * SupOffset); + else if (_format.specialStyle == TextFormat.SpecialStyle.Superscript) + y = y + Mathf.RoundToInt(_ascent * _scale * (1 / SupScale - 1 + SupOffset)); + + topLeft.x += x; + topLeft.y += y; + bottomRight.x += x; + bottomRight.y += y; + + topRight.x = bottomRight.x; + topRight.y = topLeft.y; + bottomLeft.x = topLeft.x; + bottomLeft.y = bottomRight.y; + + vertList.Add(bottomLeft); + vertList.Add(topLeft); + vertList.Add(topRight); + vertList.Add(bottomRight); + + uvBottomLeft = _char.uvBottomLeft; + uvTopLeft = _char.uvTopLeft; + uvTopRight = _char.uvTopRight; + uvBottomRight = _char.uvBottomRight; + + uvList.Add(uvBottomLeft); + uvList.Add(uvTopLeft); + uvList.Add(uvTopRight); + uvList.Add(uvBottomRight); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + + if (_boldVertice) + { + for (int b = 0; b < 4; b++) + { + Vector3 boldOffset = BOLD_OFFSET[b]; + + vertList.Add(bottomLeft + boldOffset); + vertList.Add(topLeft + boldOffset); + vertList.Add(topRight + boldOffset); + vertList.Add(bottomRight + boldOffset); + + uvList.Add(uvBottomLeft); + uvList.Add(uvTopLeft); + uvList.Add(uvTopRight); + uvList.Add(uvBottomRight); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + } + + return 20; + } + else + return 4; + } + + override public int DrawLine(float x, float y, float width, int fontSize, int type, + List vertList, List uvList, List uv2List, List colList) + { + if (!_gotLineChar) + { + _gotLineChar = true; + _font.RequestCharactersInTexture("_", 50, FontStyle.Normal); + _font.GetCharacterInfo('_', out _lineChar, 50, FontStyle.Normal); + } + + float thickness; + float offset; + + thickness = Mathf.Max(1, fontSize / 16f); //guest underline size + if (type == 0) + offset = Mathf.RoundToInt(_lineChar.minY * (float)fontSize / 50 + thickness); + else + offset = Mathf.RoundToInt(_ascent * 0.4f * fontSize / _font.fontSize); + if (thickness < 1) + thickness = 1; + + topLeft.x = x; + topLeft.y = y + offset; + bottomRight.x = x + width; + bottomRight.y = topLeft.y - thickness; + + topRight.x = bottomRight.x; + topRight.y = topLeft.y; + bottomLeft.x = topLeft.x; + bottomLeft.y = bottomRight.y; + + vertList.Add(bottomLeft); + vertList.Add(topLeft); + vertList.Add(topRight); + vertList.Add(bottomRight); + + uvBottomLeft = _lineChar.uvBottomLeft; + uvTopLeft = _lineChar.uvTopLeft; + uvTopRight = _lineChar.uvTopRight; + uvBottomRight = _lineChar.uvBottomRight; + + //取中点的UV + Vector2 u0; + if (_lineChar.uvBottomLeft.x != _lineChar.uvBottomRight.x) + u0.x = (_lineChar.uvBottomLeft.x + _lineChar.uvBottomRight.x) * 0.5f; + else + u0.x = (_lineChar.uvBottomLeft.x + _lineChar.uvTopLeft.x) * 0.5f; + + if (_lineChar.uvBottomLeft.y != _lineChar.uvTopLeft.y) + u0.y = (_lineChar.uvBottomLeft.y + _lineChar.uvTopLeft.y) * 0.5f; + else + u0.y = (_lineChar.uvBottomLeft.y + _lineChar.uvBottomRight.y) * 0.5f; + + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + + if (_boldVertice) + { + for (int b = 0; b < 4; b++) + { + Vector3 boldOffset = BOLD_OFFSET[b]; + + vertList.Add(bottomLeft + boldOffset); + vertList.Add(topLeft + boldOffset); + vertList.Add(topRight + boldOffset); + vertList.Add(bottomRight + boldOffset); + + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + uvList.Add(u0); + + colList.Add(vertexColors[0]); + colList.Add(vertexColors[1]); + colList.Add(vertexColors[2]); + colList.Add(vertexColors[3]); + } + + return 20; + } + else + return 4; + } + + override public bool HasCharacter(char ch) + { + return _font.HasCharacter(ch); + } + + override public int GetLineHeight(int size) + { + return Mathf.RoundToInt(_lineHeight * size / _font.fontSize); + } + + void textureRebuildCallback(Font targetFont) + { + if (_font != targetFont) + return; + + if (mainTexture == null || !Application.isPlaying) + { + mainTexture = new NTexture(_font.material.mainTexture); + mainTexture.destroyMethod = DestroyMethod.None; + } + else + mainTexture.Reload(_font.material.mainTexture, null); + + _gotLineChar = false; + + textRebuildFlag = true; + version++; + + //Debug.Log("Font texture rebuild: " + name + "," + mainTexture.width + "," + mainTexture.height); + } + } +} diff --git a/Assets/Scripts/Core/Text/DynamicFont.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/DynamicFont.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/DynamicFont.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/DynamicFont.cs.meta diff --git a/Assets/Scripts/Core/Text/Emoji.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/Emoji.cs similarity index 95% rename from Assets/Scripts/Core/Text/Emoji.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/Emoji.cs index a335fa0c..e5341c03 100644 --- a/Assets/Scripts/Core/Text/Emoji.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/Emoji.cs @@ -1,48 +1,48 @@ -using System; -using System.Collections.Generic; - -namespace FairyGUI -{ - /// - /// - /// - public class Emoji - { - /// - /// 代表图片资源url。 - /// - public string url; - - /// - /// 图片宽度。不设置(0)则表示使用原始宽度。 - /// - public int width; - - /// - /// 图片高度。不设置(0)则表示使用原始高度。 - /// - public int height; - - /// - /// - /// - /// - /// - /// - public Emoji(string url, int width, int height) - { - this.url = url; - this.width = width; - this.height = height; - } - - /// - /// - /// - /// - public Emoji(string url) - { - this.url = url; - } - } -} +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + public class Emoji + { + /// + /// 代表图片资源url。 + /// + public string url; + + /// + /// 图片宽度。不设置(0)则表示使用原始宽度。 + /// + public int width; + + /// + /// 图片高度。不设置(0)则表示使用原始高度。 + /// + public int height; + + /// + /// + /// + /// + /// + /// + public Emoji(string url, int width, int height) + { + this.url = url; + this.width = width; + this.height = height; + } + + /// + /// + /// + /// + public Emoji(string url) + { + this.url = url; + } + } +} diff --git a/Assets/Scripts/Core/Text/Emoji.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/Emoji.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/Emoji.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/Emoji.cs.meta diff --git a/Assets/Scripts/Core/Text/FontManager.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/FontManager.cs similarity index 96% rename from Assets/Scripts/Core/Text/FontManager.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/FontManager.cs index d584905b..c9852235 100644 --- a/Assets/Scripts/Core/Text/FontManager.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/FontManager.cs @@ -1,146 +1,146 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class FontManager - { - public static Dictionary sFontFactory = new Dictionary(); - - /// - /// - /// - /// - /// - static public void RegisterFont(BaseFont font, string alias = null) - { - sFontFactory[font.name] = font; - if (alias != null) - sFontFactory[alias] = font; - } - - /// - /// - /// - /// - static public void UnregisterFont(BaseFont font) - { - List toDelete = new List(); - foreach (KeyValuePair kv in sFontFactory) - { - if (kv.Value == font) - toDelete.Add(kv.Key); - } - - foreach (string key in toDelete) - sFontFactory.Remove(key); - } - - /// - /// - /// - /// - /// - static public BaseFont GetFont(string name) - { - BaseFont font; - if (name.StartsWith(UIPackage.URL_PREFIX)) - { - font = UIPackage.GetItemAssetByURL(name) as BaseFont; - if (font != null) - return font; - } - - if (sFontFactory.TryGetValue(name, out font)) - return font; - - object asset = Resources.Load(name); - if (asset == null) - asset = Resources.Load("Fonts/" + name); - - //Try to use new API in Uinty5 to load - if (asset == null) - { - if (name.IndexOf(",") != -1) - { - string[] arr = name.Split(','); - int cnt = arr.Length; - for (int i = 0; i < cnt; i++) - arr[i] = arr[i].Trim(); - asset = Font.CreateDynamicFontFromOSFont(arr, 16); - } - else - asset = Font.CreateDynamicFontFromOSFont(name, 16); - } - - if (asset == null) - return Fallback(name); - - if (asset is Font) - { - font = new DynamicFont(); - font.name = name; - sFontFactory.Add(name, font); - - ((DynamicFont)font).nativeFont = (Font)asset; - } -#if FAIRYGUI_TMPRO - else if (asset is TMPro.TMP_FontAsset) - { - font = new TMPFont(); - font.name = name; - sFontFactory.Add(name, font); - ((TMPFont)font).fontAsset = (TMPro.TMP_FontAsset)asset; - } -#endif - else - { - if (asset.GetType().Name.Contains("TMP_FontAsset")) - Debug.LogWarning("To enable TextMeshPro support, add script define symbol: FAIRYGUI_TMPRO"); - - return Fallback(name); - } - - return font; - } - - static BaseFont Fallback(string name) - { - if (name != UIConfig.defaultFont) - { - BaseFont ff; - if (sFontFactory.TryGetValue(UIConfig.defaultFont, out ff)) - { - sFontFactory[name] = ff; - return ff; - } - } - - Font asset = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); - if (asset == null) - throw new Exception("Failed to load font '" + name + "'"); - - BaseFont font = new DynamicFont(); - font.name = name; - ((DynamicFont)font).nativeFont = asset; - - sFontFactory.Add(name, font); - return font; - } - - /// - /// - /// - static public void Clear() - { - foreach (KeyValuePair kv in sFontFactory) - kv.Value.Dispose(); - - sFontFactory.Clear(); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class FontManager + { + public static Dictionary sFontFactory = new Dictionary(); + + /// + /// + /// + /// + /// + static public void RegisterFont(BaseFont font, string alias = null) + { + sFontFactory[font.name] = font; + if (alias != null) + sFontFactory[alias] = font; + } + + /// + /// + /// + /// + static public void UnregisterFont(BaseFont font) + { + List toDelete = new List(); + foreach (KeyValuePair kv in sFontFactory) + { + if (kv.Value == font) + toDelete.Add(kv.Key); + } + + foreach (string key in toDelete) + sFontFactory.Remove(key); + } + + /// + /// + /// + /// + /// + static public BaseFont GetFont(string name) + { + BaseFont font; + if (name.StartsWith(UIPackage.URL_PREFIX)) + { + font = UIPackage.GetItemAssetByURL(name) as BaseFont; + if (font != null) + return font; + } + + if (sFontFactory.TryGetValue(name, out font)) + return font; + + object asset = Resources.Load(name); + if (asset == null) + asset = Resources.Load("Fonts/" + name); + + //Try to use new API in Uinty5 to load + if (asset == null) + { + if (name.IndexOf(",") != -1) + { + string[] arr = name.Split(','); + int cnt = arr.Length; + for (int i = 0; i < cnt; i++) + arr[i] = arr[i].Trim(); + asset = Font.CreateDynamicFontFromOSFont(arr, 16); + } + else + asset = Font.CreateDynamicFontFromOSFont(name, 16); + } + + if (asset == null) + return Fallback(name); + + if (asset is Font) + { + font = new DynamicFont(); + font.name = name; + sFontFactory.Add(name, font); + + ((DynamicFont)font).nativeFont = (Font)asset; + } +#if FAIRYGUI_TMPRO + else if (asset is TMPro.TMP_FontAsset) + { + font = new TMPFont(); + font.name = name; + sFontFactory.Add(name, font); + ((TMPFont)font).fontAsset = (TMPro.TMP_FontAsset)asset; + } +#endif + else + { + if (asset.GetType().Name.Contains("TMP_FontAsset")) + Debug.LogWarning("To enable TextMeshPro support, add script define symbol: FAIRYGUI_TMPRO"); + + return Fallback(name); + } + + return font; + } + + static BaseFont Fallback(string name) + { + if (name != UIConfig.defaultFont) + { + BaseFont ff; + if (sFontFactory.TryGetValue(UIConfig.defaultFont, out ff)) + { + sFontFactory[name] = ff; + return ff; + } + } + + Font asset = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); + if (asset == null) + throw new Exception("Failed to load font '" + name + "'"); + + BaseFont font = new DynamicFont(); + font.name = name; + ((DynamicFont)font).nativeFont = asset; + + sFontFactory.Add(name, font); + return font; + } + + /// + /// + /// + static public void Clear() + { + foreach (KeyValuePair kv in sFontFactory) + kv.Value.Dispose(); + + sFontFactory.Clear(); + } + } +} diff --git a/Assets/Scripts/Core/Text/FontManager.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/FontManager.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/FontManager.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/FontManager.cs.meta diff --git a/Assets/Scripts/Core/Text/IKeyboard.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/IKeyboard.cs similarity index 96% rename from Assets/Scripts/Core/Text/IKeyboard.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/IKeyboard.cs index 66f7e2f8..15d3f85c 100644 --- a/Assets/Scripts/Core/Text/IKeyboard.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/IKeyboard.cs @@ -1,42 +1,42 @@ -namespace FairyGUI -{ - /// - /// 用于文本输入的键盘接口 - /// - public interface IKeyboard - { - /// - /// 键盘已收回,输入已完成 - /// - bool done { get; } - - /// - /// 是否支持在光标处输入。如果为true,GetInput返回的是在当前光标处需要插入的文本,如果为false,GetInput返回的是整个文本。 - /// - bool supportsCaret { get; } - - /// - /// 用户输入的文本。 - /// - /// - string GetInput(); - - /// - /// 打开键盘 - /// - /// - /// - /// - /// - /// - /// - /// - /// - void Open(string text, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int keyboardType, bool hideInput); - - /// - /// 关闭键盘 - /// - void Close(); - } -} +namespace FairyGUI +{ + /// + /// 用于文本输入的键盘接口 + /// + public interface IKeyboard + { + /// + /// 键盘已收回,输入已完成 + /// + bool done { get; } + + /// + /// 是否支持在光标处输入。如果为true,GetInput返回的是在当前光标处需要插入的文本,如果为false,GetInput返回的是整个文本。 + /// + bool supportsCaret { get; } + + /// + /// 用户输入的文本。 + /// + /// + string GetInput(); + + /// + /// 打开键盘 + /// + /// + /// + /// + /// + /// + /// + /// + /// + void Open(string text, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int keyboardType, bool hideInput); + + /// + /// 关闭键盘 + /// + void Close(); + } +} diff --git a/Assets/Scripts/Core/Text/IKeyboard.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/IKeyboard.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/IKeyboard.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/IKeyboard.cs.meta diff --git a/Assets/Scripts/Core/Text/InputTextField.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/InputTextField.cs similarity index 96% rename from Assets/Scripts/Core/Text/InputTextField.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/InputTextField.cs index f23594b9..b0c2b63b 100644 --- a/Assets/Scripts/Core/Text/InputTextField.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/InputTextField.cs @@ -1,1569 +1,1569 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// 接收用户输入的文本控件。因为支持直接输入表情,所以从RichTextField派生。 - /// - public class InputTextField : RichTextField - { - /// - /// - /// - public int maxLength { get; set; } - - /// - /// 如果是true,则当文本获得焦点时,弹出键盘进行输入,如果是false则不会。 - /// 默认是使用Stage.keyboardInput的值。 - /// - public bool keyboardInput { get; set; } - - /// - /// - /// - public int keyboardType { get; set; } - - /// - /// - /// - public bool hideInput { get; set; } - - /// - /// - /// - public bool disableIME { get; set; } - - /// - /// - /// - public bool mouseWheelEnabled { get; set; } - - /// - /// - /// - public static Action onCopy; - - /// - /// - /// - public static Action onPaste; - - /// - /// - /// - public static PopupMenu contextMenu; - - string _text; - string _restrict; - Regex _restrictPattern; - bool _displayAsPassword; - string _promptText; - string _decodedPromptText; - int _border; - int _corner; - Color _borderColor; - Color _backgroundColor; - bool _editable; - - bool _editing; - int _caretPosition; - int _selectionStart; - int _composing; - char _highSurrogateChar; - string _textBeforeEdit; - - EventListener _onChanged; - EventListener _onSubmit; - - Shape _caret; - SelectionShape _selectionShape; - float _nextBlink; - - const int GUTTER_X = 2; - const int GUTTER_Y = 2; - - public InputTextField() - { - gameObject.name = "InputTextField"; - - _text = string.Empty; - maxLength = 0; - _editable = true; - _composing = 0; - keyboardInput = Stage.keyboardInput; - _borderColor = Color.black; - _backgroundColor = Color.clear; - mouseWheelEnabled = true; - this.tabStop = true; - cursor = "text-ibeam"; - - /* 因为InputTextField定义了ClipRect,而ClipRect是四周缩进了2个像素的(GUTTER),默认的点击测试 - * 是使用ClipRect的,那会造成无法点击四周的空白区域。所以这里自定义了一个HitArea - */ - this.hitArea = new RectHitTest(); - this.touchChildren = false; - - onFocusIn.Add(__focusIn); - onFocusOut.AddCapture(__focusOut); - onKeyDown.Add(__keydown); - onTouchBegin.AddCapture(__touchBegin); - onTouchMove.AddCapture(__touchMove); - onMouseWheel.Add(__mouseWheel); - onClick.Add(__click); - onRightClick.Add(__rightClick); - } - - /// - /// - /// - public EventListener onChanged - { - get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } - } - - /// - /// - /// - public EventListener onSubmit - { - get { return _onSubmit ?? (_onSubmit = new EventListener(this, "onSubmit")); } - } - - /// - /// - /// - public override string text - { - get - { - return _text; - } - set - { - _text = value; - ClearSelection(); - UpdateText(); - } - } - - /// - /// - /// - public override TextFormat textFormat - { - get - { - return base.textFormat; - } - set - { - base.textFormat = value; - if (_editing) - { - _caret.height = textField.textFormat.size; - _caret.DrawRect(0, Color.clear, textField.textFormat.color); - } - } - } - - /// - /// - /// - public string restrict - { - get { return _restrict; } - set - { - _restrict = value; - if (string.IsNullOrEmpty(_restrict)) - _restrictPattern = null; - else - _restrictPattern = new Regex(value); - } - } - - /// - /// - /// - public int caretPosition - { - get - { - textField.Redraw(); - return _caretPosition; - } - set - { - SetSelection(value, 0); - } - } - - public int selectionBeginIndex - { - get { return _selectionStart < _caretPosition ? _selectionStart : _caretPosition; } - } - - public int selectionEndIndex - { - get { return _selectionStart < _caretPosition ? _caretPosition : _selectionStart; } - } - - /// - /// - /// - public string promptText - { - get - { - return _promptText; - } - set - { - _promptText = value; - if (!string.IsNullOrEmpty(_promptText)) - _decodedPromptText = UBBParser.inst.Parse(XMLUtils.EncodeString(_promptText)); - else - _decodedPromptText = null; - UpdateText(); - } - } - - /// - /// - /// - public bool displayAsPassword - { - get { return _displayAsPassword; } - set - { - if (_displayAsPassword != value) - { - _displayAsPassword = value; - UpdateText(); - } - } - } - - /// - /// - /// - public bool editable - { - get { return _editable; } - set - { - _editable = value; - if (_caret != null) - _caret.visible = _editable; - } - } - - /// - /// - /// - public int border - { - get { return _border; } - set - { - _border = value; - UpdateShape(); - } - } - - /// - /// - /// - public int corner - { - get { return _corner; } - set - { - _corner = value; - UpdateShape(); - } - } - - /// - /// - /// - public Color borderColor - { - get { return _borderColor; } - set - { - _borderColor = value; - UpdateShape(); - } - } - - /// - /// - /// - public Color backgroundColor - { - get { return _backgroundColor; } - set - { - _backgroundColor = value; - UpdateShape(); - } - } - - void UpdateShape() - { - if (_border > 0 || _backgroundColor.a > 0) - { - CreateGraphics(); - - graphics.enabled = true; - RoundedRectMesh mesh = graphics.GetMeshFactory(); - mesh.lineWidth = _border; - mesh.lineColor = _borderColor; - mesh.fillColor = _backgroundColor; - mesh.topLeftRadius = mesh.topRightRadius = mesh.bottomLeftRadius = mesh.bottomRightRadius = corner; - graphics.SetMeshDirty(); - } - else - { - if (graphics != null) - graphics.enabled = false; - } - } - - /// - /// - /// - /// - /// -1 means the rest count from start - public void SetSelection(int start, int length) - { - if (!_editing) - Stage.inst.focus = this; - - _selectionStart = start; - _caretPosition = length < 0 ? int.MaxValue : (start + length); - if (!textField.Redraw()) - { - int cnt = textField.charPositions.Count; - if (_caretPosition >= cnt) - _caretPosition = cnt - 1; - if (_selectionStart >= cnt) - _selectionStart = cnt - 1; - UpdateCaret(); - } - } - - /// - /// - /// - /// - public void ReplaceSelection(string value) - { - if (keyboardInput && Stage.keyboardInput && !Stage.inst.keyboard.supportsCaret) - { - this.text = _text + value; - OnChanged(); - return; - } - - if (!_editing) - Stage.inst.focus = this; - - textField.Redraw(); - - int t0, t1; - if (_selectionStart != _caretPosition) - { - if (_selectionStart < _caretPosition) - { - t0 = _selectionStart; - t1 = _caretPosition; - _caretPosition = _selectionStart; - } - else - { - t0 = _caretPosition; - t1 = _selectionStart; - _selectionStart = _caretPosition; - } - } - else - { - if (string.IsNullOrEmpty(value)) - return; - - t0 = t1 = _caretPosition; - } - - StringBuilder buffer = new StringBuilder(); - GetPartialText(0, t0, buffer); - if (!string.IsNullOrEmpty(value)) - { - value = ValidateInput(value); - buffer.Append(value); - - _caretPosition += GetTextlength(value); - } - GetPartialText(t1 + _composing, -1, buffer); - - string newText = buffer.ToString(); - if (maxLength > 0) - { - string newText2 = TruncateText(newText, maxLength); - if (newText2.Length != newText.Length) - _caretPosition += (newText2.Length - newText.Length); - newText = newText2; - } - - this.text = newText; - OnChanged(); - } - - /// - /// - /// - /// - public void ReplaceText(string value) - { - if (value == _text) - return; - - if (value == null) - value = string.Empty; - - value = ValidateInput(value); - - if (maxLength > 0) - value = TruncateText(value, maxLength); - - _caretPosition = value.Length; - - this.text = value; - OnChanged(); - } - - void GetPartialText(int startIndex, int endIndex, StringBuilder buffer) - { - int elementCount = textField.htmlElements.Count; - int lastIndex = startIndex; - string tt; - if (_displayAsPassword) - tt = _text; - else - tt = textField.parsedText; - if (endIndex < 0) - endIndex = tt.Length; - for (int i = 0; i < elementCount; i++) - { - HtmlElement element = textField.htmlElements[i]; - if (element.htmlObject != null && element.text != null) - { - if (element.charIndex >= startIndex && element.charIndex < endIndex) - { - buffer.Append(tt.Substring(lastIndex, element.charIndex - lastIndex)); - buffer.Append(element.text); - lastIndex = element.charIndex + 1; - } - } - } - if (lastIndex < tt.Length) - buffer.Append(tt.Substring(lastIndex, endIndex - lastIndex)); - } - - int GetTextlength(string value) - { - int textLen = value.Length; - int ret = textLen; - for (int i = 0; i < textLen; i++) - { - if (char.IsHighSurrogate(value[i])) - ret--; - } - return ret; - } - - string TruncateText(string value, int length) - { - int textLen = value.Length; - int len = 0; - int i = 0; - while (i < textLen) - { - if (len == length) - return value.Substring(0, i); - - if (char.IsHighSurrogate(value[i])) - i++; - i++; - len++; - } - return value; - } - - string ValidateInput(string source) - { - if (_restrict != null) - { - StringBuilder sb = new StringBuilder(); - Match mc = _restrictPattern.Match(source); - int lastPos = 0; - string s; - while (mc != Match.Empty) - { - if (mc.Index != lastPos) - { - //保留tab和回车 - for (int i = lastPos; i < mc.Index; i++) - { - if (source[i] == '\n' || source[i] == '\t') - sb.Append(source[i]); - } - } - - s = mc.ToString(); - lastPos = mc.Index + s.Length; - sb.Append(s); - - mc = mc.NextMatch(); - } - for (int i = lastPos; i < source.Length; i++) - { - if (source[i] == '\n' || source[i] == '\t') - sb.Append(source[i]); - } - - return sb.ToString(); - } - else - return source; - } - - void UpdateText() - { - if (!_editing && _text.Length == 0 && !string.IsNullOrEmpty(_decodedPromptText)) - { - textField.htmlText = _decodedPromptText; - return; - } - - if (_displayAsPassword) - textField.text = EncodePasswordText(_text); - else - textField.text = _text; - - _composing = Input.compositionString.Length; - if (_composing > 0) - { - StringBuilder buffer = new StringBuilder(); - GetPartialText(0, _caretPosition, buffer); - buffer.Append(Input.compositionString); - GetPartialText(_caretPosition, -1, buffer); - - textField.text = buffer.ToString(); - } - } - - string EncodePasswordText(string value) - { - int textLen = value.Length; - StringBuilder tmp = new StringBuilder(textLen); - int i = 0; - while (i < textLen) - { - char c = value[i]; - if (c == '\n') - tmp.Append(c); - else - { - if (char.IsHighSurrogate(c)) - i++; - tmp.Append("*"); - } - i++; - } - return tmp.ToString(); - } - - void ClearSelection() - { - if (_selectionStart != _caretPosition) - { - if (_selectionShape != null) - _selectionShape.Clear(); - _selectionStart = _caretPosition; - } - } - - public string GetSelection() - { - if (_selectionStart == _caretPosition) - return string.Empty; - - StringBuilder buffer = new StringBuilder(); - if (_selectionStart < _caretPosition) - GetPartialText(_selectionStart, _caretPosition, buffer); - else - GetPartialText(_caretPosition, _selectionStart, buffer); - return buffer.ToString(); - } - - void Scroll(int hScroll, int vScroll) - { - vScroll = Mathf.Clamp(vScroll, 0, textField.lines.Count - 1); - TextField.LineInfo line = textField.lines[vScroll]; - hScroll = Mathf.Clamp(hScroll, 0, line.charCount - 1); - - TextField.CharPosition cp = GetCharPosition(line.charIndex + hScroll); - Vector2 pt = GetCharLocation(cp); - MoveContent(new Vector2(GUTTER_X - pt.x, GUTTER_Y - pt.y), false); - } - - void AdjustCaret(TextField.CharPosition cp, bool moveSelectionHeader = false) - { - _caretPosition = cp.charIndex; - if (moveSelectionHeader) - _selectionStart = _caretPosition; - - UpdateCaret(); - } - - void UpdateCaret(bool forceUpdate = false) - { - TextField.CharPosition cp; - if (_editing) - cp = GetCharPosition(_caretPosition + Input.compositionString.Length); - else - cp = GetCharPosition(_caretPosition); - - Vector2 pos = GetCharLocation(cp); - TextField.LineInfo line = textField.lines[cp.lineIndex]; - Vector2 offset = pos + textField.xy; - - if (offset.x < textField.textFormat.size) - offset.x += Mathf.Min(50, _contentRect.width * 0.5f); - else if (offset.x > _contentRect.width - GUTTER_X - textField.textFormat.size) - offset.x -= Mathf.Min(50, _contentRect.width * 0.5f); - - if (offset.x < GUTTER_X) - offset.x = GUTTER_X; - else if (offset.x > _contentRect.width - GUTTER_X) - offset.x = Mathf.Max(GUTTER_X, _contentRect.width - GUTTER_X); - - if (offset.y < GUTTER_Y) - offset.y = GUTTER_Y; - else if (offset.y + line.height >= _contentRect.height - GUTTER_Y) - offset.y = Mathf.Max(GUTTER_Y, _contentRect.height - line.height - GUTTER_Y); - - MoveContent(offset - pos, forceUpdate); - - if (_editing) - { - _caret.position = textField.xy + pos; - _caret.height = line.height > 0 ? line.height : textField.textFormat.size; - - if (_editable) - { - Vector2 cursorPos = _caret.LocalToWorld(new Vector2(0, _caret.height)); - cursorPos = StageCamera.main.WorldToScreenPoint(cursorPos); -#if !UNITY_2019_OR_NEWER - if (Stage.devicePixelRatio == 1) - { -#endif - cursorPos.y = Screen.height - cursorPos.y; - cursorPos = cursorPos / Stage.devicePixelRatio; - Input.compositionCursorPos = cursorPos + new Vector2(0, 20); -#if !UNITY_2019_OR_NEWER - } - else - Input.compositionCursorPos = cursorPos - new Vector2(0, 20); -#endif - } - - _nextBlink = Time.time + 0.5f; - _caret.graphics.enabled = true; - - UpdateSelection(cp); - } - } - - void MoveContent(Vector2 pos, bool forceUpdate) - { - float ox = textField.x; - float oy = textField.y; - float nx = pos.x; - float ny = pos.y; - float rectWidth = _contentRect.width - 1; //-1 to avoid cursor be clipped - if (rectWidth - nx > textField.textWidth) - nx = rectWidth - textField.textWidth; - if (_contentRect.height - ny > textField.textHeight) - ny = _contentRect.height - textField.textHeight; - if (nx > 0) - nx = 0; - if (ny > 0) - ny = 0; - nx = (int)nx; - ny = (int)ny; - - if (nx != ox || ny != oy || forceUpdate) - { - if (_caret != null) - { - _caret.SetXY(nx + _caret.x - ox, ny + _caret.y - oy); - _selectionShape.SetXY(nx, ny); - } - textField.SetXY(nx, ny); - - List elements = textField.htmlElements; - int count = elements.Count; - for (int i = 0; i < count; i++) - { - HtmlElement element = elements[i]; - if (element.htmlObject != null) - element.htmlObject.SetPosition(element.position.x + nx, element.position.y + ny); - } - } - } - - void UpdateSelection(TextField.CharPosition cp) - { - if (_selectionStart == _caretPosition) - { - _selectionShape.Clear(); - return; - } - - TextField.CharPosition start; - if (_editing && Input.compositionString.Length > 0) - { - if (_selectionStart < _caretPosition) - { - cp = GetCharPosition(_caretPosition); - start = GetCharPosition(_selectionStart); - } - else - start = GetCharPosition(_selectionStart + Input.compositionString.Length); - } - else - start = GetCharPosition(_selectionStart); - if (start.charIndex > cp.charIndex) - { - TextField.CharPosition tmp = start; - start = cp; - cp = tmp; - } - - Vector2 v1 = GetCharLocation(start); - Vector2 v2 = GetCharLocation(cp); - - _selectionShape.rects.Clear(); - textField.GetLinesShape(start.lineIndex, v1.x, cp.lineIndex, v2.x, false, _selectionShape.rects); - _selectionShape.Refresh(); - } - - TextField.CharPosition GetCharPosition(int caretIndex) - { - if (caretIndex < 0) - caretIndex = 0; - else if (caretIndex >= textField.charPositions.Count) - caretIndex = textField.charPositions.Count - 1; - - return textField.charPositions[caretIndex]; - } - - /// - /// 通过本地坐标获得字符索引位置 - /// - /// 本地坐标 - /// - TextField.CharPosition GetCharPosition(Vector2 location) - { - if (textField.charPositions.Count <= 1) - return textField.charPositions[0]; - - location.x -= textField.x; - location.y -= textField.y; - - List lines = textField.lines; - int len = lines.Count; - TextField.LineInfo line; - int i; - for (i = 0; i < len; i++) - { - line = lines[i]; - if (line.y + line.height > location.y) - break; - } - if (i == len) - i = len - 1; - - int lineIndex = i; - - len = textField.charPositions.Count; - TextField.CharPosition v; - int firstInLine = -1; - for (i = 0; i < len; i++) - { - v = textField.charPositions[i]; - if (v.lineIndex == lineIndex) - { - if (firstInLine == -1) - firstInLine = i; - if (v.offsetX + v.width * 0.5f > location.x) - return v; - } - else if (firstInLine != -1) - return v; - } - - return textField.charPositions[i - 1]; - } - - /// - /// 获得字符的坐标。 - /// - /// - /// - Vector2 GetCharLocation(TextField.CharPosition cp) - { - TextField.LineInfo line = textField.lines[cp.lineIndex]; - Vector2 pos; - if (line.charCount == 0 || textField.charPositions.Count == 0) - { - if (textField.align == AlignType.Center) - pos.x = (int)(_contentRect.width / 2); - else - pos.x = GUTTER_X; - } - else - { - TextField.CharPosition v = textField.charPositions[Math.Min(cp.charIndex, textField.charPositions.Count - 1)]; - pos.x = v.offsetX; - } - pos.y = line.y; - return pos; - } - - override internal void RefreshObjects() - { - base.RefreshObjects(); - - if (_editing) - { - SetChildIndex(_selectionShape, 0); - SetChildIndex(_caret, this.numChildren - 1); - } - - int cnt = textField.charPositions.Count; - if (_caretPosition >= cnt) - _caretPosition = cnt - 1; - if (_selectionStart >= cnt) - _selectionStart = cnt - 1; - - UpdateCaret(true); - } - - protected void OnChanged() - { - DispatchEvent("onChanged", null); - - TextInputHistory.inst.MarkChanged(this); - } - - protected override void OnSizeChanged() - { - base.OnSizeChanged(); - - Rect rect = _contentRect; - rect.x += GUTTER_X; - rect.y += GUTTER_Y; - rect.width -= GUTTER_X * 2; - rect.height -= GUTTER_Y * 2; - this.clipRect = rect; - ((RectHitTest)this.hitArea).rect = _contentRect; - } - - public override void Update(UpdateContext context) - { - base.Update(context); - - if (_editing) - { - if (_nextBlink < Time.time) - { - _nextBlink = Time.time + 0.5f; - _caret.graphics.enabled = !_caret.graphics.enabled; - } - } - } - - public override void Dispose() - { - if ((_flags & Flags.Disposed) != 0) - return; - - _editing = false; - if (_caret != null) - { - _caret.Dispose(); - _selectionShape.Dispose(); - } - - base.Dispose(); - } - - void DoCopy(string value) - { - if (onCopy != null) - { - onCopy(this, value); - return; - } - -#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR - TextEditor textEditor = new TextEditor(); -#if UNITY_5_3_OR_NEWER - textEditor.text = value; -#else - textEditor.content = new GUIContent(value); -#endif - textEditor.OnFocus(); - textEditor.Copy(); -#endif - } - - void DoPaste() - { - if (onPaste != null) - { - onPaste(this); - return; - } - -#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR - TextEditor textEditor = new TextEditor(); -#if UNITY_5_3_OR_NEWER - textEditor.text = string.Empty; -#else - textEditor.content = new GUIContent(string.Empty); -#endif - textEditor.multiline = !textField.singleLine; - textEditor.Paste(); -#if UNITY_5_3_OR_NEWER - string value = textEditor.text; -#else - string value = textEditor.content.text; -#endif - if (!string.IsNullOrEmpty(value)) - ReplaceSelection(value); -#endif - } - - void CreateCaret() - { - _caret = new Shape(); - _caret.gameObject.name = "Caret"; - _caret.touchable = false; - _caret._flags |= Flags.SkipBatching; - _caret.xy = textField.xy; - - _selectionShape = new SelectionShape(); - _selectionShape.gameObject.name = "Selection"; - _selectionShape.color = UIConfig.inputHighlightColor; - _selectionShape._flags |= Flags.SkipBatching; - _selectionShape.touchable = false; - _selectionShape.xy = textField.xy; - } - - void __touchBegin(EventContext context) - { - if (!_editing || textField.charPositions.Count <= 1 - || keyboardInput && Stage.keyboardInput && !Stage.inst.keyboard.supportsCaret - || context.inputEvent.button != 0) - return; - - ClearSelection(); - - Vector3 v = Stage.inst.touchPosition; - v = this.GlobalToLocal(v); - TextField.CharPosition cp = GetCharPosition(v); - - AdjustCaret(cp, true); - - context.CaptureTouch(); - } - - void __touchMove(EventContext context) - { - if (!_editing) - return; - - Vector3 v = Stage.inst.touchPosition; - v = this.GlobalToLocal(v); - if (float.IsNaN(v.x)) - return; - - TextField.CharPosition cp = GetCharPosition(v); - if (cp.charIndex != _caretPosition) - AdjustCaret(cp); - } - - void __mouseWheel(EventContext context) - { - if (_editing && mouseWheelEnabled) - { - context.StopPropagation(); - - TextField.CharPosition cp = GetCharPosition(new Vector2(GUTTER_X, GUTTER_Y)); - int vScroll = cp.lineIndex; - int hScroll = cp.charIndex - textField.lines[cp.lineIndex].charIndex; - if (context.inputEvent.mouseWheelDelta < 0) - vScroll--; - else - vScroll++; - Scroll(hScroll, vScroll); - } - } - - void __focusIn(EventContext context) - { - if (!Application.isPlaying) - return; - - _editing = true; - _textBeforeEdit = _text; - - if (_caret == null) - CreateCaret(); - - if (!string.IsNullOrEmpty(_promptText)) - UpdateText(); - - float caretSize; - //如果界面缩小过,光标很容易看不见,这里放大一下 - if (UIConfig.inputCaretSize == 1 && UIContentScaler.scaleFactor < 1) - caretSize = UIConfig.inputCaretSize / UIContentScaler.scaleFactor; - else - caretSize = UIConfig.inputCaretSize; - _caret.SetSize(caretSize, textField.textFormat.size); - _caret.DrawRect(0, Color.clear, textField.textFormat.color); - _caret.visible = _editable; - AddChild(_caret); - - _selectionShape.Clear(); - AddChildAt(_selectionShape, 0); - - if (!textField.Redraw()) - { - TextField.CharPosition cp = GetCharPosition(_caretPosition); - AdjustCaret(cp); - } - - if (Stage.keyboardInput) - { - if (keyboardInput) - { - if (_editable) - Stage.inst.OpenKeyboard(_text, false, _displayAsPassword ? false : !textField.singleLine, - _displayAsPassword, false, null, keyboardType, hideInput); - - SetSelection(0, -1); - } - } - else - { - if (!disableIME && !_displayAsPassword) - Input.imeCompositionMode = IMECompositionMode.On; - else - Input.imeCompositionMode = IMECompositionMode.Off; - _composing = 0; - - if ((string)context.data == "key") //select all if got focus by tab key - SetSelection(0, -1); - - TextInputHistory.inst.StartRecord(this); - } - } - - void __focusOut(EventContext contxt) - { - if (!_editing) - return; - - _editing = false; - if (Stage.keyboardInput) - { - if (keyboardInput) - Stage.inst.CloseKeyboard(); - } - else - { - Input.imeCompositionMode = IMECompositionMode.Auto; - TextInputHistory.inst.StopRecord(this); - } - - if (!string.IsNullOrEmpty(_promptText)) - UpdateText(); - - _caret.RemoveFromParent(); - _selectionShape.RemoveFromParent(); - - if (contextMenu != null && contextMenu.contentPane.onStage) - contextMenu.Hide(); - } - - void __keydown(EventContext context) - { - if (!_editing) - return; - - if (HandleKey(context.inputEvent)) - context.StopPropagation(); - } - - bool HandleKey(InputEvent evt) - { - bool keyCodeHandled = true; - switch (evt.keyCode) - { - case KeyCode.Backspace: - { - if (evt.command) - { - //for mac:CMD+Backspace=Delete - if (_selectionStart == _caretPosition && _caretPosition < textField.charPositions.Count - 1) - _selectionStart = _caretPosition + 1; - } - else - { - if (_selectionStart == _caretPosition && _caretPosition > 0) - _selectionStart = _caretPosition - 1; - } - if (_editable) - ReplaceSelection(null); - break; - } - - case KeyCode.Delete: - { - if (_selectionStart == _caretPosition && _caretPosition < textField.charPositions.Count - 1) - _selectionStart = _caretPosition + 1; - if (_editable) - ReplaceSelection(null); - break; - } - - case KeyCode.LeftArrow: - { - if (!evt.shift) - ClearSelection(); - if (_caretPosition > 0) - { - if (evt.command) //mac keyboard - { - TextField.CharPosition cp = GetCharPosition(_caretPosition); - TextField.LineInfo line = textField.lines[cp.lineIndex]; - cp = GetCharPosition(new Vector2(int.MinValue, line.y + textField.y)); - AdjustCaret(cp, !evt.shift); - } - else - { - TextField.CharPosition cp = GetCharPosition(_caretPosition - 1); - AdjustCaret(cp, !evt.shift); - } - } - break; - } - - case KeyCode.RightArrow: - { - if (!evt.shift) - ClearSelection(); - if (_caretPosition < textField.charPositions.Count - 1) - { - if (evt.command) - { - TextField.CharPosition cp = GetCharPosition(_caretPosition); - TextField.LineInfo line = textField.lines[cp.lineIndex]; - cp = GetCharPosition(new Vector2(int.MaxValue, line.y + textField.y)); - AdjustCaret(cp, !evt.shift); - } - else - { - TextField.CharPosition cp = GetCharPosition(_caretPosition + 1); - AdjustCaret(cp, !evt.shift); - } - } - break; - } - - case KeyCode.UpArrow: - { - if (!evt.shift) - ClearSelection(); - - TextField.CharPosition cp = GetCharPosition(_caretPosition); - if (cp.lineIndex > 0) - { - TextField.LineInfo line = textField.lines[cp.lineIndex - 1]; - cp = GetCharPosition(new Vector2(_caret.x, line.y + textField.y)); - AdjustCaret(cp, !evt.shift); - } - break; - } - - case KeyCode.DownArrow: - { - if (!evt.shift) - ClearSelection(); - - TextField.CharPosition cp = GetCharPosition(_caretPosition); - if (cp.lineIndex == textField.lines.Count - 1) - cp.charIndex = textField.charPositions.Count - 1; - else - { - TextField.LineInfo line = textField.lines[cp.lineIndex + 1]; - cp = GetCharPosition(new Vector2(_caret.x, line.y + textField.y)); - } - AdjustCaret(cp, !evt.shift); - break; - } - - case KeyCode.PageUp: - { - ClearSelection(); - break; - } - - case KeyCode.PageDown: - { - ClearSelection(); - break; - } - - case KeyCode.Home: - { - if (!evt.shift) - ClearSelection(); - - TextField.CharPosition cp = GetCharPosition(_caretPosition); - TextField.LineInfo line = textField.lines[cp.lineIndex]; - cp = GetCharPosition(new Vector2(int.MinValue, line.y + textField.y)); - AdjustCaret(cp, !evt.shift); - break; - } - - case KeyCode.End: - { - if (!evt.shift) - ClearSelection(); - - TextField.CharPosition cp = GetCharPosition(_caretPosition); - TextField.LineInfo line = textField.lines[cp.lineIndex]; - cp = GetCharPosition(new Vector2(int.MaxValue, line.y + textField.y)); - AdjustCaret(cp, !evt.shift); - - break; - } - - //Select All - case KeyCode.A: - { - if (evt.ctrlOrCmd) - { - _selectionStart = 0; - AdjustCaret(GetCharPosition(int.MaxValue)); - } - break; - } - - //Copy - case KeyCode.C: - { - if (evt.ctrlOrCmd && !_displayAsPassword) - { - string s = GetSelection(); - if (!string.IsNullOrEmpty(s)) - DoCopy(s); - } - break; - } - - //Paste - case KeyCode.V: - { - if (evt.ctrlOrCmd && _editable) - DoPaste(); - break; - } - - //Cut - case KeyCode.X: - { - if (evt.ctrlOrCmd && !_displayAsPassword) - { - string s = GetSelection(); - if (!string.IsNullOrEmpty(s)) - { - DoCopy(s); - if (_editable) - ReplaceSelection(null); - } - } - break; - } - - case KeyCode.Z: - { - if (evt.ctrlOrCmd && _editable) - { - if (evt.shift) - TextInputHistory.inst.Redo(this); - else - TextInputHistory.inst.Undo(this); - } - break; - } - - case KeyCode.Y: - { - if (evt.ctrlOrCmd && _editable) - TextInputHistory.inst.Redo(this); - break; - } - - case KeyCode.Return: - case KeyCode.KeypadEnter: - { - if (textField.singleLine) - { - Stage.inst.focus = parent; - DispatchEvent("onSubmit", null); - DispatchEvent("onKeyDown", null); //for backward compatibility - } - break; - } - - case KeyCode.Tab: - { - if (textField.singleLine) - { - Stage.inst.DoKeyNavigate(evt.shift); - keyCodeHandled = false; - } - break; - } - - case KeyCode.Escape: - { - this.text = _textBeforeEdit; - Stage.inst.focus = parent; - break; - } - - default: - keyCodeHandled = (int)evt.keyCode <= 272 && !evt.ctrlOrCmd; - break; - } - - char c = evt.character; - if (c != 0) - { - if (evt.ctrlOrCmd) - return true; - - if (c == '\r' || c == 3) - c = '\n'; - - if (c == 25)/*shift+tab*/ - c = '\t'; - - if (c == 27/*escape*/ || textField.singleLine && (c == '\n' || c == '\t')) - return true; - - if (char.IsHighSurrogate(c)) - { - _highSurrogateChar = c; - return true; - } - - if (_editable) - { - if (char.IsLowSurrogate(c)) - ReplaceSelection(char.ConvertFromUtf32(((int)c & 0x03FF) + ((((int)_highSurrogateChar & 0x03FF) + 0x40) << 10))); - else - ReplaceSelection(c.ToString()); - } - - return true; - } - else - { - if (Input.compositionString.Length > 0 && _editable) - { - int composing = _composing; - _composing = Input.compositionString.Length; - - StringBuilder buffer = new StringBuilder(); - GetPartialText(0, _caretPosition, buffer); - buffer.Append(Input.compositionString); - GetPartialText(_caretPosition + composing, -1, buffer); - - textField.text = buffer.ToString(); - } - - return keyCodeHandled; - } - } - - internal void CheckComposition() - { - if (_composing != 0 && Input.compositionString.Length == 0) - UpdateText(); - } - - void __click(EventContext context) - { - if (_editing && context.inputEvent.isDoubleClick) - { - context.StopPropagation(); - _selectionStart = 0; - AdjustCaret(GetCharPosition(int.MaxValue)); - } - } - - void __rightClick(EventContext context) - { - if (contextMenu != null) - { - context.StopPropagation(); - contextMenu.Show(); - } - } - } - - class TextInputHistory - { - static TextInputHistory _inst; - public static TextInputHistory inst - { - get - { - if (_inst == null) - _inst = new TextInputHistory(); - return _inst; - } - } - - List _undoBuffer; - List _redoBuffer; - string _currentText; - InputTextField _textField; - bool _lock; - int _changedFrame; - - public const int maxHistoryLength = 5; - - public TextInputHistory() - { - _undoBuffer = new List(); - _redoBuffer = new List(); - } - - public void StartRecord(InputTextField textField) - { - _undoBuffer.Clear(); - _redoBuffer.Clear(); - _textField = textField; - _lock = false; - _currentText = textField.text; - _changedFrame = 0; - } - - public void MarkChanged(InputTextField textField) - { - if (_textField != textField) - return; - - if (_lock) - return; - - string newText = _textField.text; - if (_currentText == newText) - return; - - if (_changedFrame != Time.frameCount) - { - _changedFrame = Time.frameCount; - _undoBuffer.Add(_currentText); - if (_undoBuffer.Count > maxHistoryLength) - _undoBuffer.RemoveAt(0); - } - else - { - int cnt = _undoBuffer.Count; - if (cnt > 0 && newText == _undoBuffer[cnt - 1]) - _undoBuffer.RemoveAt(cnt - 1); - } - _currentText = newText; - } - - public void StopRecord(InputTextField textField) - { - if (_textField != textField) - return; - - _undoBuffer.Clear(); - _redoBuffer.Clear(); - _textField = null; - _currentText = null; - } - - public void Undo(InputTextField textField) - { - if (_textField != textField) - return; - - if (_undoBuffer.Count == 0) - return; - - string text = _undoBuffer[_undoBuffer.Count - 1]; - _undoBuffer.RemoveAt(_undoBuffer.Count - 1); - _redoBuffer.Add(_currentText); - _lock = true; - int caretPos = _textField.caretPosition; - _textField.text = text; - int dlen = text.Length - _currentText.Length; - if (dlen < 0) - _textField.caretPosition = caretPos + dlen; - _currentText = text; - _lock = false; - } - - public void Redo(InputTextField textField) - { - if (_textField != textField) - return; - - if (_redoBuffer.Count == 0) - return; - - string text = _redoBuffer[_redoBuffer.Count - 1]; - _redoBuffer.RemoveAt(_redoBuffer.Count - 1); - _undoBuffer.Add(_currentText); - _lock = true; - int caretPos = _textField.caretPosition; - _textField.text = text; - int dlen = text.Length - _currentText.Length; - if (dlen > 0) - _textField.caretPosition = caretPos + dlen; - _currentText = text; - _lock = false; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// 接收用户输入的文本控件。因为支持直接输入表情,所以从RichTextField派生。 + /// + public class InputTextField : RichTextField + { + /// + /// + /// + public int maxLength { get; set; } + + /// + /// 如果是true,则当文本获得焦点时,弹出键盘进行输入,如果是false则不会。 + /// 默认是使用Stage.keyboardInput的值。 + /// + public bool keyboardInput { get; set; } + + /// + /// + /// + public int keyboardType { get; set; } + + /// + /// + /// + public bool hideInput { get; set; } + + /// + /// + /// + public bool disableIME { get; set; } + + /// + /// + /// + public bool mouseWheelEnabled { get; set; } + + /// + /// + /// + public static Action onCopy; + + /// + /// + /// + public static Action onPaste; + + /// + /// + /// + public static PopupMenu contextMenu; + + string _text; + string _restrict; + Regex _restrictPattern; + bool _displayAsPassword; + string _promptText; + string _decodedPromptText; + int _border; + int _corner; + Color _borderColor; + Color _backgroundColor; + bool _editable; + + bool _editing; + int _caretPosition; + int _selectionStart; + int _composing; + char _highSurrogateChar; + string _textBeforeEdit; + + EventListener _onChanged; + EventListener _onSubmit; + + Shape _caret; + SelectionShape _selectionShape; + float _nextBlink; + + const int GUTTER_X = 2; + const int GUTTER_Y = 2; + + public InputTextField() + { + gameObject.name = "InputTextField"; + + _text = string.Empty; + maxLength = 0; + _editable = true; + _composing = 0; + keyboardInput = Stage.keyboardInput; + _borderColor = Color.black; + _backgroundColor = Color.clear; + mouseWheelEnabled = true; + this.tabStop = true; + cursor = "text-ibeam"; + + /* 因为InputTextField定义了ClipRect,而ClipRect是四周缩进了2个像素的(GUTTER),默认的点击测试 + * 是使用ClipRect的,那会造成无法点击四周的空白区域。所以这里自定义了一个HitArea + */ + this.hitArea = new RectHitTest(); + this.touchChildren = false; + + onFocusIn.Add(__focusIn); + onFocusOut.AddCapture(__focusOut); + onKeyDown.Add(__keydown); + onTouchBegin.AddCapture(__touchBegin); + onTouchMove.AddCapture(__touchMove); + onMouseWheel.Add(__mouseWheel); + onClick.Add(__click); + onRightClick.Add(__rightClick); + } + + /// + /// + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// + /// + public EventListener onSubmit + { + get { return _onSubmit ?? (_onSubmit = new EventListener(this, "onSubmit")); } + } + + /// + /// + /// + public override string text + { + get + { + return _text; + } + set + { + _text = value; + ClearSelection(); + UpdateText(); + } + } + + /// + /// + /// + public override TextFormat textFormat + { + get + { + return base.textFormat; + } + set + { + base.textFormat = value; + if (_editing) + { + _caret.height = textField.textFormat.size; + _caret.DrawRect(0, Color.clear, textField.textFormat.color); + } + } + } + + /// + /// + /// + public string restrict + { + get { return _restrict; } + set + { + _restrict = value; + if (string.IsNullOrEmpty(_restrict)) + _restrictPattern = null; + else + _restrictPattern = new Regex(value); + } + } + + /// + /// + /// + public int caretPosition + { + get + { + textField.Redraw(); + return _caretPosition; + } + set + { + SetSelection(value, 0); + } + } + + public int selectionBeginIndex + { + get { return _selectionStart < _caretPosition ? _selectionStart : _caretPosition; } + } + + public int selectionEndIndex + { + get { return _selectionStart < _caretPosition ? _caretPosition : _selectionStart; } + } + + /// + /// + /// + public string promptText + { + get + { + return _promptText; + } + set + { + _promptText = value; + if (!string.IsNullOrEmpty(_promptText)) + _decodedPromptText = UBBParser.inst.Parse(XMLUtils.EncodeString(_promptText)); + else + _decodedPromptText = null; + UpdateText(); + } + } + + /// + /// + /// + public bool displayAsPassword + { + get { return _displayAsPassword; } + set + { + if (_displayAsPassword != value) + { + _displayAsPassword = value; + UpdateText(); + } + } + } + + /// + /// + /// + public bool editable + { + get { return _editable; } + set + { + _editable = value; + if (_caret != null) + _caret.visible = _editable; + } + } + + /// + /// + /// + public int border + { + get { return _border; } + set + { + _border = value; + UpdateShape(); + } + } + + /// + /// + /// + public int corner + { + get { return _corner; } + set + { + _corner = value; + UpdateShape(); + } + } + + /// + /// + /// + public Color borderColor + { + get { return _borderColor; } + set + { + _borderColor = value; + UpdateShape(); + } + } + + /// + /// + /// + public Color backgroundColor + { + get { return _backgroundColor; } + set + { + _backgroundColor = value; + UpdateShape(); + } + } + + void UpdateShape() + { + if (_border > 0 || _backgroundColor.a > 0) + { + CreateGraphics(); + + graphics.enabled = true; + RoundedRectMesh mesh = graphics.GetMeshFactory(); + mesh.lineWidth = _border; + mesh.lineColor = _borderColor; + mesh.fillColor = _backgroundColor; + mesh.topLeftRadius = mesh.topRightRadius = mesh.bottomLeftRadius = mesh.bottomRightRadius = corner; + graphics.SetMeshDirty(); + } + else + { + if (graphics != null) + graphics.enabled = false; + } + } + + /// + /// + /// + /// + /// -1 means the rest count from start + public void SetSelection(int start, int length) + { + if (!_editing) + Stage.inst.focus = this; + + _selectionStart = start; + _caretPosition = length < 0 ? int.MaxValue : (start + length); + if (!textField.Redraw()) + { + int cnt = textField.charPositions.Count; + if (_caretPosition >= cnt) + _caretPosition = cnt - 1; + if (_selectionStart >= cnt) + _selectionStart = cnt - 1; + UpdateCaret(); + } + } + + /// + /// + /// + /// + public void ReplaceSelection(string value) + { + if (keyboardInput && Stage.keyboardInput && !Stage.inst.keyboard.supportsCaret) + { + this.text = _text + value; + OnChanged(); + return; + } + + if (!_editing) + Stage.inst.focus = this; + + textField.Redraw(); + + int t0, t1; + if (_selectionStart != _caretPosition) + { + if (_selectionStart < _caretPosition) + { + t0 = _selectionStart; + t1 = _caretPosition; + _caretPosition = _selectionStart; + } + else + { + t0 = _caretPosition; + t1 = _selectionStart; + _selectionStart = _caretPosition; + } + } + else + { + if (string.IsNullOrEmpty(value)) + return; + + t0 = t1 = _caretPosition; + } + + StringBuilder buffer = new StringBuilder(); + GetPartialText(0, t0, buffer); + if (!string.IsNullOrEmpty(value)) + { + value = ValidateInput(value); + buffer.Append(value); + + _caretPosition += GetTextlength(value); + } + GetPartialText(t1 + _composing, -1, buffer); + + string newText = buffer.ToString(); + if (maxLength > 0) + { + string newText2 = TruncateText(newText, maxLength); + if (newText2.Length != newText.Length) + _caretPosition += (newText2.Length - newText.Length); + newText = newText2; + } + + this.text = newText; + OnChanged(); + } + + /// + /// + /// + /// + public void ReplaceText(string value) + { + if (value == _text) + return; + + if (value == null) + value = string.Empty; + + value = ValidateInput(value); + + if (maxLength > 0) + value = TruncateText(value, maxLength); + + _caretPosition = value.Length; + + this.text = value; + OnChanged(); + } + + void GetPartialText(int startIndex, int endIndex, StringBuilder buffer) + { + int elementCount = textField.htmlElements.Count; + int lastIndex = startIndex; + string tt; + if (_displayAsPassword) + tt = _text; + else + tt = textField.parsedText; + if (endIndex < 0) + endIndex = tt.Length; + for (int i = 0; i < elementCount; i++) + { + HtmlElement element = textField.htmlElements[i]; + if (element.htmlObject != null && element.text != null) + { + if (element.charIndex >= startIndex && element.charIndex < endIndex) + { + buffer.Append(tt.Substring(lastIndex, element.charIndex - lastIndex)); + buffer.Append(element.text); + lastIndex = element.charIndex + 1; + } + } + } + if (lastIndex < tt.Length) + buffer.Append(tt.Substring(lastIndex, endIndex - lastIndex)); + } + + int GetTextlength(string value) + { + int textLen = value.Length; + int ret = textLen; + for (int i = 0; i < textLen; i++) + { + if (char.IsHighSurrogate(value[i])) + ret--; + } + return ret; + } + + string TruncateText(string value, int length) + { + int textLen = value.Length; + int len = 0; + int i = 0; + while (i < textLen) + { + if (len == length) + return value.Substring(0, i); + + if (char.IsHighSurrogate(value[i])) + i++; + i++; + len++; + } + return value; + } + + string ValidateInput(string source) + { + if (_restrict != null) + { + StringBuilder sb = new StringBuilder(); + Match mc = _restrictPattern.Match(source); + int lastPos = 0; + string s; + while (mc != Match.Empty) + { + if (mc.Index != lastPos) + { + //保留tab和回车 + for (int i = lastPos; i < mc.Index; i++) + { + if (source[i] == '\n' || source[i] == '\t') + sb.Append(source[i]); + } + } + + s = mc.ToString(); + lastPos = mc.Index + s.Length; + sb.Append(s); + + mc = mc.NextMatch(); + } + for (int i = lastPos; i < source.Length; i++) + { + if (source[i] == '\n' || source[i] == '\t') + sb.Append(source[i]); + } + + return sb.ToString(); + } + else + return source; + } + + void UpdateText() + { + if (!_editing && _text.Length == 0 && !string.IsNullOrEmpty(_decodedPromptText)) + { + textField.htmlText = _decodedPromptText; + return; + } + + if (_displayAsPassword) + textField.text = EncodePasswordText(_text); + else + textField.text = _text; + + _composing = Input.compositionString.Length; + if (_composing > 0) + { + StringBuilder buffer = new StringBuilder(); + GetPartialText(0, _caretPosition, buffer); + buffer.Append(Input.compositionString); + GetPartialText(_caretPosition, -1, buffer); + + textField.text = buffer.ToString(); + } + } + + string EncodePasswordText(string value) + { + int textLen = value.Length; + StringBuilder tmp = new StringBuilder(textLen); + int i = 0; + while (i < textLen) + { + char c = value[i]; + if (c == '\n') + tmp.Append(c); + else + { + if (char.IsHighSurrogate(c)) + i++; + tmp.Append("*"); + } + i++; + } + return tmp.ToString(); + } + + void ClearSelection() + { + if (_selectionStart != _caretPosition) + { + if (_selectionShape != null) + _selectionShape.Clear(); + _selectionStart = _caretPosition; + } + } + + public string GetSelection() + { + if (_selectionStart == _caretPosition) + return string.Empty; + + StringBuilder buffer = new StringBuilder(); + if (_selectionStart < _caretPosition) + GetPartialText(_selectionStart, _caretPosition, buffer); + else + GetPartialText(_caretPosition, _selectionStart, buffer); + return buffer.ToString(); + } + + void Scroll(int hScroll, int vScroll) + { + vScroll = Mathf.Clamp(vScroll, 0, textField.lines.Count - 1); + TextField.LineInfo line = textField.lines[vScroll]; + hScroll = Mathf.Clamp(hScroll, 0, line.charCount - 1); + + TextField.CharPosition cp = GetCharPosition(line.charIndex + hScroll); + Vector2 pt = GetCharLocation(cp); + MoveContent(new Vector2(GUTTER_X - pt.x, GUTTER_Y - pt.y), false); + } + + void AdjustCaret(TextField.CharPosition cp, bool moveSelectionHeader = false) + { + _caretPosition = cp.charIndex; + if (moveSelectionHeader) + _selectionStart = _caretPosition; + + UpdateCaret(); + } + + void UpdateCaret(bool forceUpdate = false) + { + TextField.CharPosition cp; + if (_editing) + cp = GetCharPosition(_caretPosition + Input.compositionString.Length); + else + cp = GetCharPosition(_caretPosition); + + Vector2 pos = GetCharLocation(cp); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + Vector2 offset = pos + textField.xy; + + if (offset.x < textField.textFormat.size) + offset.x += Mathf.Min(50, _contentRect.width * 0.5f); + else if (offset.x > _contentRect.width - GUTTER_X - textField.textFormat.size) + offset.x -= Mathf.Min(50, _contentRect.width * 0.5f); + + if (offset.x < GUTTER_X) + offset.x = GUTTER_X; + else if (offset.x > _contentRect.width - GUTTER_X) + offset.x = Mathf.Max(GUTTER_X, _contentRect.width - GUTTER_X); + + if (offset.y < GUTTER_Y) + offset.y = GUTTER_Y; + else if (offset.y + line.height >= _contentRect.height - GUTTER_Y) + offset.y = Mathf.Max(GUTTER_Y, _contentRect.height - line.height - GUTTER_Y); + + MoveContent(offset - pos, forceUpdate); + + if (_editing) + { + _caret.position = textField.xy + pos; + _caret.height = line.height > 0 ? line.height : textField.textFormat.size; + + if (_editable) + { + Vector2 cursorPos = _caret.LocalToWorld(new Vector2(0, _caret.height)); + cursorPos = StageCamera.main.WorldToScreenPoint(cursorPos); +#if !UNITY_2019_OR_NEWER + if (Stage.devicePixelRatio == 1) + { +#endif + cursorPos.y = Screen.height - cursorPos.y; + cursorPos = cursorPos / Stage.devicePixelRatio; + Input.compositionCursorPos = cursorPos + new Vector2(0, 20); +#if !UNITY_2019_OR_NEWER + } + else + Input.compositionCursorPos = cursorPos - new Vector2(0, 20); +#endif + } + + _nextBlink = Time.time + 0.5f; + _caret.graphics.enabled = true; + + UpdateSelection(cp); + } + } + + void MoveContent(Vector2 pos, bool forceUpdate) + { + float ox = textField.x; + float oy = textField.y; + float nx = pos.x; + float ny = pos.y; + float rectWidth = _contentRect.width - 1; //-1 to avoid cursor be clipped + if (rectWidth - nx > textField.textWidth) + nx = rectWidth - textField.textWidth; + if (_contentRect.height - ny > textField.textHeight) + ny = _contentRect.height - textField.textHeight; + if (nx > 0) + nx = 0; + if (ny > 0) + ny = 0; + nx = (int)nx; + ny = (int)ny; + + if (nx != ox || ny != oy || forceUpdate) + { + if (_caret != null) + { + _caret.SetXY(nx + _caret.x - ox, ny + _caret.y - oy); + _selectionShape.SetXY(nx, ny); + } + textField.SetXY(nx, ny); + + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (element.htmlObject != null) + element.htmlObject.SetPosition(element.position.x + nx, element.position.y + ny); + } + } + } + + void UpdateSelection(TextField.CharPosition cp) + { + if (_selectionStart == _caretPosition) + { + _selectionShape.Clear(); + return; + } + + TextField.CharPosition start; + if (_editing && Input.compositionString.Length > 0) + { + if (_selectionStart < _caretPosition) + { + cp = GetCharPosition(_caretPosition); + start = GetCharPosition(_selectionStart); + } + else + start = GetCharPosition(_selectionStart + Input.compositionString.Length); + } + else + start = GetCharPosition(_selectionStart); + if (start.charIndex > cp.charIndex) + { + TextField.CharPosition tmp = start; + start = cp; + cp = tmp; + } + + Vector2 v1 = GetCharLocation(start); + Vector2 v2 = GetCharLocation(cp); + + _selectionShape.rects.Clear(); + textField.GetLinesShape(start.lineIndex, v1.x, cp.lineIndex, v2.x, false, _selectionShape.rects); + _selectionShape.Refresh(); + } + + TextField.CharPosition GetCharPosition(int caretIndex) + { + if (caretIndex < 0) + caretIndex = 0; + else if (caretIndex >= textField.charPositions.Count) + caretIndex = textField.charPositions.Count - 1; + + return textField.charPositions[caretIndex]; + } + + /// + /// 通过本地坐标获得字符索引位置 + /// + /// 本地坐标 + /// + TextField.CharPosition GetCharPosition(Vector2 location) + { + if (textField.charPositions.Count <= 1) + return textField.charPositions[0]; + + location.x -= textField.x; + location.y -= textField.y; + + List lines = textField.lines; + int len = lines.Count; + TextField.LineInfo line; + int i; + for (i = 0; i < len; i++) + { + line = lines[i]; + if (line.y + line.height > location.y) + break; + } + if (i == len) + i = len - 1; + + int lineIndex = i; + + len = textField.charPositions.Count; + TextField.CharPosition v; + int firstInLine = -1; + for (i = 0; i < len; i++) + { + v = textField.charPositions[i]; + if (v.lineIndex == lineIndex) + { + if (firstInLine == -1) + firstInLine = i; + if (v.offsetX + v.width * 0.5f > location.x) + return v; + } + else if (firstInLine != -1) + return v; + } + + return textField.charPositions[i - 1]; + } + + /// + /// 获得字符的坐标。 + /// + /// + /// + Vector2 GetCharLocation(TextField.CharPosition cp) + { + TextField.LineInfo line = textField.lines[cp.lineIndex]; + Vector2 pos; + if (line.charCount == 0 || textField.charPositions.Count == 0) + { + if (textField.align == AlignType.Center) + pos.x = (int)(_contentRect.width / 2); + else + pos.x = GUTTER_X; + } + else + { + TextField.CharPosition v = textField.charPositions[Math.Min(cp.charIndex, textField.charPositions.Count - 1)]; + pos.x = v.offsetX; + } + pos.y = line.y; + return pos; + } + + override internal void RefreshObjects() + { + base.RefreshObjects(); + + if (_editing) + { + SetChildIndex(_selectionShape, 0); + SetChildIndex(_caret, this.numChildren - 1); + } + + int cnt = textField.charPositions.Count; + if (_caretPosition >= cnt) + _caretPosition = cnt - 1; + if (_selectionStart >= cnt) + _selectionStart = cnt - 1; + + UpdateCaret(true); + } + + protected void OnChanged() + { + DispatchEvent("onChanged", null); + + TextInputHistory.inst.MarkChanged(this); + } + + protected override void OnSizeChanged() + { + base.OnSizeChanged(); + + Rect rect = _contentRect; + rect.x += GUTTER_X; + rect.y += GUTTER_Y; + rect.width -= GUTTER_X * 2; + rect.height -= GUTTER_Y * 2; + this.clipRect = rect; + ((RectHitTest)this.hitArea).rect = _contentRect; + } + + public override void Update(UpdateContext context) + { + base.Update(context); + + if (_editing) + { + if (_nextBlink < Time.time) + { + _nextBlink = Time.time + 0.5f; + _caret.graphics.enabled = !_caret.graphics.enabled; + } + } + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + _editing = false; + if (_caret != null) + { + _caret.Dispose(); + _selectionShape.Dispose(); + } + + base.Dispose(); + } + + void DoCopy(string value) + { + if (onCopy != null) + { + onCopy(this, value); + return; + } + +#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR + TextEditor textEditor = new TextEditor(); +#if UNITY_5_3_OR_NEWER + textEditor.text = value; +#else + textEditor.content = new GUIContent(value); +#endif + textEditor.OnFocus(); + textEditor.Copy(); +#endif + } + + void DoPaste() + { + if (onPaste != null) + { + onPaste(this); + return; + } + +#if UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_EDITOR + TextEditor textEditor = new TextEditor(); +#if UNITY_5_3_OR_NEWER + textEditor.text = string.Empty; +#else + textEditor.content = new GUIContent(string.Empty); +#endif + textEditor.multiline = !textField.singleLine; + textEditor.Paste(); +#if UNITY_5_3_OR_NEWER + string value = textEditor.text; +#else + string value = textEditor.content.text; +#endif + if (!string.IsNullOrEmpty(value)) + ReplaceSelection(value); +#endif + } + + void CreateCaret() + { + _caret = new Shape(); + _caret.gameObject.name = "Caret"; + _caret.touchable = false; + _caret._flags |= Flags.SkipBatching; + _caret.xy = textField.xy; + + _selectionShape = new SelectionShape(); + _selectionShape.gameObject.name = "Selection"; + _selectionShape.color = UIConfig.inputHighlightColor; + _selectionShape._flags |= Flags.SkipBatching; + _selectionShape.touchable = false; + _selectionShape.xy = textField.xy; + } + + void __touchBegin(EventContext context) + { + if (!_editing || textField.charPositions.Count <= 1 + || keyboardInput && Stage.keyboardInput && !Stage.inst.keyboard.supportsCaret + || context.inputEvent.button != 0) + return; + + ClearSelection(); + + Vector3 v = Stage.inst.touchPosition; + v = this.GlobalToLocal(v); + TextField.CharPosition cp = GetCharPosition(v); + + AdjustCaret(cp, true); + + context.CaptureTouch(); + } + + void __touchMove(EventContext context) + { + if (!_editing) + return; + + Vector3 v = Stage.inst.touchPosition; + v = this.GlobalToLocal(v); + if (float.IsNaN(v.x)) + return; + + TextField.CharPosition cp = GetCharPosition(v); + if (cp.charIndex != _caretPosition) + AdjustCaret(cp); + } + + void __mouseWheel(EventContext context) + { + if (_editing && mouseWheelEnabled) + { + context.StopPropagation(); + + TextField.CharPosition cp = GetCharPosition(new Vector2(GUTTER_X, GUTTER_Y)); + int vScroll = cp.lineIndex; + int hScroll = cp.charIndex - textField.lines[cp.lineIndex].charIndex; + if (context.inputEvent.mouseWheelDelta < 0) + vScroll--; + else + vScroll++; + Scroll(hScroll, vScroll); + } + } + + void __focusIn(EventContext context) + { + if (!Application.isPlaying) + return; + + _editing = true; + _textBeforeEdit = _text; + + if (_caret == null) + CreateCaret(); + + if (!string.IsNullOrEmpty(_promptText)) + UpdateText(); + + float caretSize; + //如果界面缩小过,光标很容易看不见,这里放大一下 + if (UIConfig.inputCaretSize == 1 && UIContentScaler.scaleFactor < 1) + caretSize = UIConfig.inputCaretSize / UIContentScaler.scaleFactor; + else + caretSize = UIConfig.inputCaretSize; + _caret.SetSize(caretSize, textField.textFormat.size); + _caret.DrawRect(0, Color.clear, textField.textFormat.color); + _caret.visible = _editable; + AddChild(_caret); + + _selectionShape.Clear(); + AddChildAt(_selectionShape, 0); + + if (!textField.Redraw()) + { + TextField.CharPosition cp = GetCharPosition(_caretPosition); + AdjustCaret(cp); + } + + if (Stage.keyboardInput) + { + if (keyboardInput) + { + if (_editable) + Stage.inst.OpenKeyboard(_text, false, _displayAsPassword ? false : !textField.singleLine, + _displayAsPassword, false, null, keyboardType, hideInput); + + SetSelection(0, -1); + } + } + else + { + if (!disableIME && !_displayAsPassword) + Input.imeCompositionMode = IMECompositionMode.On; + else + Input.imeCompositionMode = IMECompositionMode.Off; + _composing = 0; + + if ((string)context.data == "key") //select all if got focus by tab key + SetSelection(0, -1); + + TextInputHistory.inst.StartRecord(this); + } + } + + void __focusOut(EventContext contxt) + { + if (!_editing) + return; + + _editing = false; + if (Stage.keyboardInput) + { + if (keyboardInput) + Stage.inst.CloseKeyboard(); + } + else + { + Input.imeCompositionMode = IMECompositionMode.Auto; + TextInputHistory.inst.StopRecord(this); + } + + if (!string.IsNullOrEmpty(_promptText)) + UpdateText(); + + _caret.RemoveFromParent(); + _selectionShape.RemoveFromParent(); + + if (contextMenu != null && contextMenu.contentPane.onStage) + contextMenu.Hide(); + } + + void __keydown(EventContext context) + { + if (!_editing) + return; + + if (HandleKey(context.inputEvent)) + context.StopPropagation(); + } + + bool HandleKey(InputEvent evt) + { + bool keyCodeHandled = true; + switch (evt.keyCode) + { + case KeyCode.Backspace: + { + if (evt.command) + { + //for mac:CMD+Backspace=Delete + if (_selectionStart == _caretPosition && _caretPosition < textField.charPositions.Count - 1) + _selectionStart = _caretPosition + 1; + } + else + { + if (_selectionStart == _caretPosition && _caretPosition > 0) + _selectionStart = _caretPosition - 1; + } + if (_editable) + ReplaceSelection(null); + break; + } + + case KeyCode.Delete: + { + if (_selectionStart == _caretPosition && _caretPosition < textField.charPositions.Count - 1) + _selectionStart = _caretPosition + 1; + if (_editable) + ReplaceSelection(null); + break; + } + + case KeyCode.LeftArrow: + { + if (!evt.shift) + ClearSelection(); + if (_caretPosition > 0) + { + if (evt.command) //mac keyboard + { + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MinValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + } + else + { + TextField.CharPosition cp = GetCharPosition(_caretPosition - 1); + AdjustCaret(cp, !evt.shift); + } + } + break; + } + + case KeyCode.RightArrow: + { + if (!evt.shift) + ClearSelection(); + if (_caretPosition < textField.charPositions.Count - 1) + { + if (evt.command) + { + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MaxValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + } + else + { + TextField.CharPosition cp = GetCharPosition(_caretPosition + 1); + AdjustCaret(cp, !evt.shift); + } + } + break; + } + + case KeyCode.UpArrow: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + if (cp.lineIndex > 0) + { + TextField.LineInfo line = textField.lines[cp.lineIndex - 1]; + cp = GetCharPosition(new Vector2(_caret.x, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + } + break; + } + + case KeyCode.DownArrow: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + if (cp.lineIndex == textField.lines.Count - 1) + cp.charIndex = textField.charPositions.Count - 1; + else + { + TextField.LineInfo line = textField.lines[cp.lineIndex + 1]; + cp = GetCharPosition(new Vector2(_caret.x, line.y + textField.y)); + } + AdjustCaret(cp, !evt.shift); + break; + } + + case KeyCode.PageUp: + { + ClearSelection(); + break; + } + + case KeyCode.PageDown: + { + ClearSelection(); + break; + } + + case KeyCode.Home: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MinValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + break; + } + + case KeyCode.End: + { + if (!evt.shift) + ClearSelection(); + + TextField.CharPosition cp = GetCharPosition(_caretPosition); + TextField.LineInfo line = textField.lines[cp.lineIndex]; + cp = GetCharPosition(new Vector2(int.MaxValue, line.y + textField.y)); + AdjustCaret(cp, !evt.shift); + + break; + } + + //Select All + case KeyCode.A: + { + if (evt.ctrlOrCmd) + { + _selectionStart = 0; + AdjustCaret(GetCharPosition(int.MaxValue)); + } + break; + } + + //Copy + case KeyCode.C: + { + if (evt.ctrlOrCmd && !_displayAsPassword) + { + string s = GetSelection(); + if (!string.IsNullOrEmpty(s)) + DoCopy(s); + } + break; + } + + //Paste + case KeyCode.V: + { + if (evt.ctrlOrCmd && _editable) + DoPaste(); + break; + } + + //Cut + case KeyCode.X: + { + if (evt.ctrlOrCmd && !_displayAsPassword) + { + string s = GetSelection(); + if (!string.IsNullOrEmpty(s)) + { + DoCopy(s); + if (_editable) + ReplaceSelection(null); + } + } + break; + } + + case KeyCode.Z: + { + if (evt.ctrlOrCmd && _editable) + { + if (evt.shift) + TextInputHistory.inst.Redo(this); + else + TextInputHistory.inst.Undo(this); + } + break; + } + + case KeyCode.Y: + { + if (evt.ctrlOrCmd && _editable) + TextInputHistory.inst.Redo(this); + break; + } + + case KeyCode.Return: + case KeyCode.KeypadEnter: + { + if (textField.singleLine) + { + Stage.inst.focus = parent; + DispatchEvent("onSubmit", null); + DispatchEvent("onKeyDown", null); //for backward compatibility + } + break; + } + + case KeyCode.Tab: + { + if (textField.singleLine) + { + Stage.inst.DoKeyNavigate(evt.shift); + keyCodeHandled = false; + } + break; + } + + case KeyCode.Escape: + { + this.text = _textBeforeEdit; + Stage.inst.focus = parent; + break; + } + + default: + keyCodeHandled = (int)evt.keyCode <= 272 && !evt.ctrlOrCmd; + break; + } + + char c = evt.character; + if (c != 0) + { + if (evt.ctrlOrCmd) + return true; + + if (c == '\r' || c == 3) + c = '\n'; + + if (c == 25)/*shift+tab*/ + c = '\t'; + + if (c == 27/*escape*/ || textField.singleLine && (c == '\n' || c == '\t')) + return true; + + if (char.IsHighSurrogate(c)) + { + _highSurrogateChar = c; + return true; + } + + if (_editable) + { + if (char.IsLowSurrogate(c)) + ReplaceSelection(char.ConvertFromUtf32(((int)c & 0x03FF) + ((((int)_highSurrogateChar & 0x03FF) + 0x40) << 10))); + else + ReplaceSelection(c.ToString()); + } + + return true; + } + else + { + if (Input.compositionString.Length > 0 && _editable) + { + int composing = _composing; + _composing = Input.compositionString.Length; + + StringBuilder buffer = new StringBuilder(); + GetPartialText(0, _caretPosition, buffer); + buffer.Append(Input.compositionString); + GetPartialText(_caretPosition + composing, -1, buffer); + + textField.text = buffer.ToString(); + } + + return keyCodeHandled; + } + } + + internal void CheckComposition() + { + if (_composing != 0 && Input.compositionString.Length == 0) + UpdateText(); + } + + void __click(EventContext context) + { + if (_editing && context.inputEvent.isDoubleClick) + { + context.StopPropagation(); + _selectionStart = 0; + AdjustCaret(GetCharPosition(int.MaxValue)); + } + } + + void __rightClick(EventContext context) + { + if (contextMenu != null) + { + context.StopPropagation(); + contextMenu.Show(); + } + } + } + + class TextInputHistory + { + static TextInputHistory _inst; + public static TextInputHistory inst + { + get + { + if (_inst == null) + _inst = new TextInputHistory(); + return _inst; + } + } + + List _undoBuffer; + List _redoBuffer; + string _currentText; + InputTextField _textField; + bool _lock; + int _changedFrame; + + public const int maxHistoryLength = 5; + + public TextInputHistory() + { + _undoBuffer = new List(); + _redoBuffer = new List(); + } + + public void StartRecord(InputTextField textField) + { + _undoBuffer.Clear(); + _redoBuffer.Clear(); + _textField = textField; + _lock = false; + _currentText = textField.text; + _changedFrame = 0; + } + + public void MarkChanged(InputTextField textField) + { + if (_textField != textField) + return; + + if (_lock) + return; + + string newText = _textField.text; + if (_currentText == newText) + return; + + if (_changedFrame != Time.frameCount) + { + _changedFrame = Time.frameCount; + _undoBuffer.Add(_currentText); + if (_undoBuffer.Count > maxHistoryLength) + _undoBuffer.RemoveAt(0); + } + else + { + int cnt = _undoBuffer.Count; + if (cnt > 0 && newText == _undoBuffer[cnt - 1]) + _undoBuffer.RemoveAt(cnt - 1); + } + _currentText = newText; + } + + public void StopRecord(InputTextField textField) + { + if (_textField != textField) + return; + + _undoBuffer.Clear(); + _redoBuffer.Clear(); + _textField = null; + _currentText = null; + } + + public void Undo(InputTextField textField) + { + if (_textField != textField) + return; + + if (_undoBuffer.Count == 0) + return; + + string text = _undoBuffer[_undoBuffer.Count - 1]; + _undoBuffer.RemoveAt(_undoBuffer.Count - 1); + _redoBuffer.Add(_currentText); + _lock = true; + int caretPos = _textField.caretPosition; + _textField.text = text; + int dlen = text.Length - _currentText.Length; + if (dlen < 0) + _textField.caretPosition = caretPos + dlen; + _currentText = text; + _lock = false; + } + + public void Redo(InputTextField textField) + { + if (_textField != textField) + return; + + if (_redoBuffer.Count == 0) + return; + + string text = _redoBuffer[_redoBuffer.Count - 1]; + _redoBuffer.RemoveAt(_redoBuffer.Count - 1); + _undoBuffer.Add(_currentText); + _lock = true; + int caretPos = _textField.caretPosition; + _textField.text = text; + int dlen = text.Length - _currentText.Length; + if (dlen > 0) + _textField.caretPosition = caretPos + dlen; + _currentText = text; + _lock = false; + } + } +} diff --git a/Assets/Scripts/Core/Text/InputTextField.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/InputTextField.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/InputTextField.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/InputTextField.cs.meta diff --git a/Assets/Scripts/Core/Text/RTLSupport.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RTLSupport.cs similarity index 97% rename from Assets/Scripts/Core/Text/RTLSupport.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RTLSupport.cs index 2fc9042d..38198bc8 100644 --- a/Assets/Scripts/Core/Text/RTLSupport.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RTLSupport.cs @@ -1,701 +1,701 @@ -/******************************************************************** - Copyright (c) 2018, Tadpole Studio - All rights reserved - - 文件名称: RTL.cs - 说 明: RTL字符转换 - - 版 本: 1.00 - 时 间: 2018/2/24 9:02:12 - 作 者: AQ QQ:355010366 - 概 述: 新建 - -*********************************************************************/ -using System; -using System.Collections.Generic; -using System.Text; - -namespace FairyGUI -{ - public class RTLSupport - { - internal enum CharState - { - isolated, - final, - lead, - middle, - } - - // Bidirectional Character Types - public enum DirectionType - { - UNKNOW = 0, - LTR, - RTL, - NEUTRAL, - } - -#if RTL_TEXT_SUPPORT - public static DirectionType BaseDirection = DirectionType.RTL; // 主体语言是否是RTL的语言 -#else - public static DirectionType BaseDirection = DirectionType.UNKNOW; -#endif - private static bool isCharsInitialized = false; - private static Dictionary mapping = new Dictionary(); - - private static List listFinal = new List(); - private static List listRep = new List(); - private static StringBuilder sbRep = new StringBuilder(); - private static StringBuilder sbN = new StringBuilder(); - private static StringBuilder sbFinal = new StringBuilder(); - private static StringBuilder sbReverse = new StringBuilder(); - - public static bool IsArabicLetter(char ch) - { - if (ch >= 0x600 && ch <= 0x6ff) - { - if ((ch >= 0x660 && ch <= 0x66D) || (ch >= 0x6f0 && ch <= 0x6f9)) // 标准阿拉伯语数字和东阿拉伯语数字 [2019/3/1/ 17:45:18 by aq_1000] - { - return false; - } - return true; - } - else if (ch >= 0x750 && ch <= 0x77f) - return true; - else if (ch >= 0xfb50 && ch <= 0xfc3f) - return true; - else if (ch >= 0xfe70 && ch <= 0xfefc) - return true; - return false; - } - - public static string ConvertNumber(string strNumber) - { - sbRep.Length = 0; - foreach (char ch in strNumber) - { - int un = ch; - if (un == 0x66c || ch == ',') // 去掉逗号 - continue; - else if (un == 0x660 || un == 0x6f0) - sbRep.Append('0'); - else if (un == 0x661 || un == 0x6f1) - sbRep.Append('1'); - else if (un == 0x662 || un == 0x6f2) - sbRep.Append('2'); - else if (un == 0x663 || un == 0x6f3) - sbRep.Append('3'); - else if (un == 0x664 || un == 0x6f4) - sbRep.Append('4'); - else if (un == 0x665 || un == 0x6f5) - sbRep.Append('5'); - else if (un == 0x666 || un == 0x6f6) - sbRep.Append('6'); - else if (un == 0x667 || un == 0x6f7) - sbRep.Append('7'); - else if (un == 0x668 || un == 0x6f8) - sbRep.Append('8'); - else if (un == 0x669 || un == 0x6f9) - sbRep.Append('9'); - else - sbRep.Append(ch); - } - return sbRep.ToString(); - } - - public static bool ContainsArabicLetters(string text) - { - foreach (char character in text) - { - if (character >= 0x600 && character <= 0x6ff) - return true; - - if (character >= 0x750 && character <= 0x77f) - return true; - - if (character >= 0xfb50 && character <= 0xfc3f) - return true; - - if (character >= 0xfe70 && character <= 0xfefc) - return true; - } - return false; - } - - // 检测文本主方向 - public static DirectionType DetectTextDirection(string text) - { - bool isContainRTL = false; - bool isContainLTR = false; - foreach (char ch in text) - { - if (IsArabicLetter(ch)) - { - isContainRTL = true; - if (isContainLTR) - break; - } - else if (char.IsLetter(ch)) - { - isContainLTR = true; - if (isContainRTL) - break; - } - } - if (!isContainRTL) - return DirectionType.UNKNOW; // 这边unknow暂时代表文本一个RTL字符都没有,无需进行RTL转换 - else if (!isContainLTR) - return DirectionType.RTL; - return BaseDirection; - } - - private static bool CheckSeparator(char input) - { - if (!IsArabicLetter(input)) - { - return true; - } - else - { - return (input == '،') || (input == '?') || (input == '؟'); - } - - // if ((input != ' ') && (input != '\t') && (input != '!') && (input != '.') && - // (input != '،') && (input != '?') && (input != '؟') && - // !_IsBracket(input) && // 括号也算 [2018/8/1/ 15:12:20 by aq_1000] - // !_IsNeutrality(input)) - // { - // return false; - // } - // return true; - } - - private static bool CheckSpecific(char input) - { - int num = input; - if ((num != 0x622) && (num != 0x623) && (num != 0x627) && (num != 0x62f) && (num != 0x625) && - (num != 0x630) && (num != 0x631) && (num != 0x632) && (num != 0x698) && (num != 0x648) && - !_CheckSoundmark(input)) - { - return false; - } - return true; - } - - private static bool _CheckSoundmark(char ch) - { - int un = ch; - return (un >= 0x610 && un <= 0x61e) || (un >= 0x64b && un <= 0x65f); - } - - public static string DoMapping(string input) - { - if (!isCharsInitialized) - { - isCharsInitialized = true; - InitChars(); - } - - // 伊斯兰教真主安拉在阿拉伯文里写作الله - // 键盘输入时输入 ل (lam) + ل (lam) + ه (ha) 后会自动转换成带记号的符号。 [2018/3/13 20:03:45 --By aq_1000] - if (input == "الله") - { - input = "ﷲ"; - } - - sbFinal.Length = 0; - sbFinal.Append(input); - char perChar = '\0'; - for (int i = 0; i < sbFinal.Length; i++) - { - if (!mapping.ContainsKey(sbFinal[i])) - { - perChar = sbFinal[i]; - continue; - } - - if ((i + 1) == sbFinal.Length) - { - if (sbFinal.Length == 1) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; - } - else if (CheckSeparator(perChar) || CheckSpecific(perChar)) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.final]; - } - } - else if (i == 0) - { - if (!CheckSeparator(sbFinal[i + 1])) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; - } - } - else if (CheckSeparator(sbFinal[i + 1])) - { - if (CheckSeparator(perChar) || CheckSpecific(perChar)) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.final]; - } - } - else if (CheckSeparator(perChar)) - { - if (CheckSeparator(sbFinal[i + 1])) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; - } - } - else if (CheckSpecific(sbFinal[i + 1])) - { - if (CheckSeparator(perChar) || CheckSpecific(perChar)) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.middle]; - } - } - else if (CheckSpecific(perChar)) - { - if (CheckSeparator(sbFinal[i + 1])) - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; - } - } - else - { - perChar = sbFinal[i]; - sbFinal[i] = mapping[sbFinal[i]][(int)CharState.middle]; - } - } - return sbFinal.ToString(); - } - - // 主体语言是LTR - public static string ConvertLineL(string source) - { - listFinal.Clear(); - listRep.Clear(); - sbRep.Length = 0; - sbN.Length = 0; - int iReplace = 0; - DirectionType ePre = DirectionType.LTR; - char nextChar = '\0'; - for (int j = 0; j < source.Length; j++) - { - if (j < source.Length - 1) - nextChar = source[j + 1]; - else - nextChar = '\0'; - char item = source[j]; - DirectionType eCType = _GetDirection(item, nextChar, ePre, DirectionType.LTR); - if (eCType == DirectionType.RTL) - { - if (sbRep.Length == 0) - { - listFinal.Add('\x00bf'); - iReplace++; - } - - if (sbN.Length > 0) - sbRep.Append(sbN.ToString()); - sbN.Length = 0; - sbRep.Append(item); - } - else if (eCType == DirectionType.LTR) - { - if (sbRep.Length > 0) - { - listRep.Add(sbRep.ToString()); - } - sbRep.Length = 0; - - if (sbN.Length > 0) - { - for (int n = 0; n < sbN.Length; ++n) - { - listFinal.Add(sbN[n]); - } - } - sbN.Length = 0; - - // item = _ProcessBracket(item); // 文本主方向为LTR的话,括号不需要翻转 [2018/12/20/ 17:03:23 by aq_1000] - listFinal.Add(item); - } - else - { - sbN.Append(item); - } - ePre = eCType; - } - if (sbRep.Length > 0) - { - listRep.Add(sbRep.ToString()); - } - - // 一行中都只有中立字符的情况,就直接返回中立字符 [2018/12/6/ 16:34:38 by aq_1000] - if (sbN.Length > 0) - { - for (int n = 0; n < sbN.Length; ++n) - { - listFinal.Add(sbN[n]); - } - } - - sbRep.Length = 0; - sbN.Length = 0; - sbFinal.Length = 0; - sbFinal.Append(listFinal.ToArray()); - for (int m = 0; m < iReplace; m++) - { - for (int n = 0; n < sbFinal.Length; n++) - { - if (sbFinal[n] == '\x00bf') - { - sbRep.Length = 0; - sbRep.Append(_Reverse(listRep[0])); - listRep.RemoveAt(0); - - // 字符串反向的时候造成末尾空格跑到词首 [2018/4/11 20:04:35 --By aq_1000] - sbN.Length = 0; - for (int num4 = 0; num4 < sbRep.Length; num4++) - { - if (!_IsNeutrality(sbRep[num4])) - break; - sbN.Append(sbRep[num4]); - } - if (sbN.Length > 0) // 词首空格重新放到词尾 - { - sbRep.Remove(0, sbN.Length); - for (int iSpace = sbN.Length - 1; iSpace >= 0; --iSpace) // 空格也要取反 - { - sbRep.Append(sbN[iSpace]); - } - } - - sbFinal.Replace(sbFinal[n].ToString(), sbRep.ToString(), n, 1); - break; - } - } - } - return sbFinal.ToString(); - } - - // 主体语言是RTL,整个文本就从右往左读,LTR语言就作为嵌入语段处理 - public static string ConvertLineR(string source) - { - listFinal.Clear(); - listRep.Clear(); - sbRep.Length = 0; - sbN.Length = 0; - int iReplace = 0; - DirectionType ePre = DirectionType.RTL; - char nextChar = '\0'; - for (int j = 0; j < source.Length; j++) - { - if (j < source.Length - 1) - nextChar = source[j + 1]; - else - nextChar = '\0'; - char item = source[j]; - DirectionType eCType = _GetDirection(item, nextChar, ePre, DirectionType.RTL); - if (eCType == DirectionType.LTR) - { - if (sbRep.Length == 0) - { - listFinal.Add('\x00bf'); - iReplace++; - } - - if (sbN.Length > 0) - sbRep.Append(sbN.ToString()); - sbN.Length = 0; - sbRep.Append(item); - } - else if (eCType == DirectionType.RTL) - { - if (sbRep.Length > 0) - { - listRep.Add(sbRep.ToString()); - } - sbRep.Length = 0; - - if (sbN.Length > 0) - { - for (int n = 0; n < sbN.Length; ++n) - { - listFinal.Add(sbN[n]); - } - } - sbN.Length = 0; - - item = _ProcessBracket(item); - listFinal.Add(item); - } - else - { - sbN.Append(item); - } - ePre = eCType; - } - if (sbRep.Length > 0) - { - listRep.Add(sbRep.ToString()); - } - - // 一行中都只有中立字符的情况,就直接返回中立字符 [2018/12/6/ 16:34:38 by aq_1000] - if (sbN.Length > 0) - { - for (int n = 0; n < sbN.Length; ++n) - { - listFinal.Add(sbN[n]); - } - } - - sbFinal.Length = 0; - sbFinal.Append(listFinal.ToArray()); - for (int m = 0; m < iReplace; m++) - { - for (int n = 0; n < sbFinal.Length; n++) - { - if (sbFinal[n] == '\x00bf') - { - sbRep.Length = 0; - sbRep.Append(_Reverse(listRep[0])); - listRep.RemoveAt(0); - - // 字符串反向的时候造成末尾空格跑到词首 [2018/4/11 20:04:35 --By aq_1000] - sbN.Length = 0; - for (int num4 = 0; num4 < sbRep.Length; num4++) - { - if (!_IsNeutrality(sbRep[num4])) - break; - sbN.Append(sbRep[num4]); - } - if (sbN.Length > 0) // 词首空格重新放到词尾 - { - sbRep.Remove(0, sbN.Length); - for (int iSpace = sbN.Length - 1; iSpace >= 0; --iSpace) // 空格也要取反 - { - sbRep.Append(sbN[iSpace]); - } - } - - sbFinal.Replace(sbFinal[n].ToString(), sbRep.ToString(), n, 1); - break; - } - } - } - return sbFinal.ToString(); - } - - - private static string _Reverse(string source) - { - sbReverse.Length = 0; - int len = source.Length; - int i = len - 1; - while (i >= 0) - { - char ch = source[i]; - if (ch == '\r' && i != len - 1 && source[i + 1] == '\n') - { - i--; - continue; - } - - if (char.IsLowSurrogate(ch)) //不要反向高低代理对 - { - sbReverse.Append(source[i - 1]); - sbReverse.Append(ch); - i--; - } - else - sbReverse.Append(ch); - i--; - } - - return sbReverse.ToString(); - } - - private static void InitChars() - { - // {isolated,final,lead,middle} [2018/11/27 16:04:18 --By aq_1000] - mapping.Add(0x621, new char[4] { (char)0xFE80, (char)0xFE8A, (char)0xFE8B, (char)0xFE8C }); // Hamza - mapping.Add(0x627, new char[4] { (char)0xFE8D, (char)0xFE8E, (char)0xFE8D, (char)0xFE8E }); // Alef - mapping.Add(0x623, new char[4] { (char)0xFE83, (char)0xFE84, (char)0xFE83, (char)0xFE84 }); // AlefHamza - mapping.Add(0x624, new char[4] { (char)0xFE85, (char)0xFE85, (char)0xFE85, (char)0xFE85 }); // WawHamza - mapping.Add(0x625, new char[4] { (char)0xFE87, (char)0xFE87, (char)0xFE87, (char)0xFE87 }); // AlefMaksoor - mapping.Add(0x649, new char[4] { (char)0xFBFC, (char)0xFBFD, (char)0xFBFE, (char)0xFBFF }); // AlefMagsora - mapping.Add(0x626, new char[4] { (char)0xFE89, (char)0xFE8A, (char)0xFE8B, (char)0xFE8C }); // HamzaNabera - mapping.Add(0x628, new char[4] { (char)0xFE8F, (char)0xFE90, (char)0xFE91, (char)0xFE92 }); // Ba - mapping.Add(0x62A, new char[4] { (char)0xFE95, (char)0xFE96, (char)0xFE97, (char)0xFE98 }); // Ta - mapping.Add(0x62B, new char[4] { (char)0xFE99, (char)0xFE9A, (char)0xFE9B, (char)0xFE9C }); // Tha2 - mapping.Add(0x62C, new char[4] { (char)0xFE9D, (char)0xFE9E, (char)0xFE9F, (char)0xFEA0 }); // Jeem - mapping.Add(0x62D, new char[4] { (char)0xFEA1, (char)0xFEA2, (char)0xFEA3, (char)0xFEA4 }); // H7aa - mapping.Add(0x62E, new char[4] { (char)0xFEA5, (char)0xFEA6, (char)0xFEA7, (char)0xFEA8 }); // Khaa2 - mapping.Add(0x62F, new char[4] { (char)0xFEA9, (char)0xFEAA, (char)0xFEA9, (char)0xFEAA }); // Dal - mapping.Add(0x630, new char[4] { (char)0xFEAB, (char)0xFEAC, (char)0xFEAB, (char)0xFEAC }); // Thal - mapping.Add(0x631, new char[4] { (char)0xFEAD, (char)0xFEAE, (char)0xFEAD, (char)0xFEAD }); // Ra2 - mapping.Add(0x632, new char[4] { (char)0xFEAF, (char)0xFEB0, (char)0xFEAF, (char)0xFEB0 }); // Zeen - mapping.Add(0x633, new char[4] { (char)0xFEB1, (char)0xFEB2, (char)0xFEB3, (char)0xFEB4 }); // Seen - mapping.Add(0x634, new char[4] { (char)0xFEB5, (char)0xFEB6, (char)0xFEB7, (char)0xFEB8 }); // Sheen - mapping.Add(0x635, new char[4] { (char)0xFEB9, (char)0xFEBA, (char)0xFEBB, (char)0xFEBC }); // S9a - mapping.Add(0x636, new char[4] { (char)0xFEBD, (char)0xFEBE, (char)0xFEBF, (char)0xFEC0 }); // Dha - mapping.Add(0x637, new char[4] { (char)0xFEC1, (char)0xFEC2, (char)0xFEC3, (char)0xFEC4 }); // T6a - mapping.Add(0x638, new char[4] { (char)0xFEC5, (char)0xFEC6, (char)0xFEC7, (char)0xFEC8 }); // T6ha - mapping.Add(0x639, new char[4] { (char)0xFEC9, (char)0xFECA, (char)0xFECB, (char)0xFECC }); // Ain - mapping.Add(0x63A, new char[4] { (char)0xFECD, (char)0xFECE, (char)0xFECF, (char)0xFED0 }); // Gain - mapping.Add(0x641, new char[4] { (char)0xFED1, (char)0xFED2, (char)0xFED3, (char)0xFED4 }); // Fa - mapping.Add(0x642, new char[4] { (char)0xFED5, (char)0xFED6, (char)0xFED7, (char)0xFED8 }); // Gaf - mapping.Add(0x643, new char[4] { (char)0xFED9, (char)0xFEDA, (char)0xFEDB, (char)0xFEDC }); // Kaf - mapping.Add(0x644, new char[4] { (char)0xFEDD, (char)0xFEDE, (char)0xFEDF, (char)0xFEE0 }); // Lam - mapping.Add(0x645, new char[4] { (char)0xFEE1, (char)0xFEE2, (char)0xFEE3, (char)0xFEE4 }); // Meem - mapping.Add(0x646, new char[4] { (char)0xFEE5, (char)0xFEE6, (char)0xFEE7, (char)0xFEE8 }); // Noon - mapping.Add(0x647, new char[4] { (char)0xFEE9, (char)0xFEEA, (char)0xFEEB, (char)0xFEEC }); // Ha - mapping.Add(0x648, new char[4] { (char)0xFEED, (char)0xFEEE, (char)0xFEED, (char)0xFEEE }); // Waw - mapping.Add(0x64A, new char[4] { (char)0xFEF1, (char)0xFEF2, (char)0xFEF3, (char)0xFEF4 }); // Ya - mapping.Add(0x622, new char[4] { (char)0xFE81, (char)0xFE81, (char)0xFE81, (char)0xFE81 }); // AlefMad - mapping.Add(0x629, new char[4] { (char)0xFE93, (char)0xFE94, (char)0xFE94, (char)0xFE94 }); // TaMarboota // 该字符只会出现在末尾 [2018/4/10 16:04:18 --By aq_1000] - mapping.Add(0x67E, new char[4] { (char)0xFB56, (char)0xFB57, (char)0xFB58, (char)0xFB59 }); // PersianPe - mapping.Add(0x686, new char[4] { (char)0xFB7A, (char)0xFB7B, (char)0xFB7C, (char)0xFB7D }); // PersianChe - mapping.Add(0x698, new char[4] { (char)0xFB8A, (char)0xFB8B, (char)0xFB8A, (char)0xFB8B }); // PersianZe - mapping.Add(0x6AF, new char[4] { (char)0xFB92, (char)0xFB93, (char)0xFB94, (char)0xFB95 }); // PersianGaf - mapping.Add(0x6A9, new char[4] { (char)0xFB8E, (char)0xFB8F, (char)0xFB90, (char)0xFB91 }); // PersianGaf2 - - mapping.Add(0x6BE, new char[4] { (char)0xFEE9, (char)0xFEEA, (char)0xFEEB, (char)0xFEEC }); - mapping.Add(0x6CC, new char[4] { (char)0xFBFC, (char)0xFBFD, (char)0xFBFE, (char)0xFBFF }); - } - - // 是否中立方向字符 - private static bool _IsNeutrality(char uc) - { - return (uc == ':' || uc == ':' || uc == ' ' || /*uc == '%' ||*/ /*uc == '+' ||*/ /*uc == '-' ||*/ uc == '\n' || uc == '\r' || uc == '\t' || uc == '@' || - (uc >= 0x2600 && uc <= 0x27BF)); // 表情符号 - } - - // 是否句末标点符号 - private static bool _IsEndPunctuation(char uc, char nextChar) - { - if (uc == '.') - return _IsNeutrality(nextChar); - return (uc == '!' || uc == '!' || uc == '。' || uc == '،' || uc == '?' || uc == '؟'); - } - - // 判断字符方向 - private static DirectionType _GetDirection(char uc, char nextChar, DirectionType ePre, DirectionType eBase) - { - DirectionType eCType = ePre; - int uni = uc; - - if (_IsBracket(uc) || _IsEndPunctuation(uc, nextChar)) - { - eCType = eBase; // 括号和句末标点符号,方向根据上个字符为准 [2018/12/26/ 15:56:24 by aq_1000] - } - else if ((uni >= 0x660) && (uni <= 0x66D)) - { - eCType = DirectionType.LTR; - } - else if (IsArabicLetter(uc) || uc == '+' /*|| uc == '-'*/ || uc == '%') - { - eCType = DirectionType.RTL; - } - else if (uc == '-') - { - if (char.IsNumber(nextChar)) - eCType = DirectionType.LTR; - else - eCType = DirectionType.RTL; - } - else if (_IsNeutrality(uc)) // 中立方向字符,方向就和上一个字符一样 [2018/3/24 16:03:27 --By aq_1000] - { - if (ePre == DirectionType.UNKNOW || ePre == DirectionType.NEUTRAL) - { - if (char.IsNumber(nextChar)) // 数字都是弱LTR方向符,开头中立字符后面紧跟着数字的话,中立字符方向算文本主方向 [IsDigit()只是0-9] [2018/12/20/ 16:32:32 by aq_1000] - { - eCType = BaseDirection; - } - else - eCType = DirectionType.NEUTRAL; - } - else - eCType = ePre; - } - else - eCType = DirectionType.LTR; - - return eCType; - } - - // 是否括号 - private static bool _IsBracket(char uc) - { - return (uc == ')' || uc == '(' || uc == ')' || uc == '(' || - uc == ']' || uc == '[' || uc == '】' || uc == '【' || - uc == '}' || uc == '{' || - // uc == '≥' || uc == '≤' || uc == '>' || uc == '<' || - uc == '》' || uc == '《' || uc == '“' || uc == '”' || uc == '"'); - } - - // 这些配对符,在从右至左排列中应该逆序显示 - private static char _ProcessBracket(char uc) - { - if (uc == '[') return ']'; - else if (uc == ']') return '['; - else if (uc == '【') return '】'; - else if (uc == '】') return '【'; - else if (uc == '{') return '}'; - else if (uc == '}') return '{'; - else if (uc == '(') return ')'; - else if (uc == ')') return '('; - else if (uc == '(') return ')'; - else if (uc == ')') return '('; - else if (uc == '<') return '>'; - else if (uc == '>') return '<'; - else if (uc == '《') return '》'; - else if (uc == '》') return '《'; - else if (uc == '≤') return '≥'; - else if (uc == '≥') return '≤'; - else if (uc == '”') return '“'; - else if (uc == '”') return '“'; - else return uc; - } - } -} - +/******************************************************************** + Copyright (c) 2018, Tadpole Studio + All rights reserved + + 文件名称: RTL.cs + 说 明: RTL字符转换 + + 版 本: 1.00 + 时 间: 2018/2/24 9:02:12 + 作 者: AQ QQ:355010366 + 概 述: 新建 + +*********************************************************************/ +using System; +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI +{ + public class RTLSupport + { + internal enum CharState + { + isolated, + final, + lead, + middle, + } + + // Bidirectional Character Types + public enum DirectionType + { + UNKNOW = 0, + LTR, + RTL, + NEUTRAL, + } + +#if RTL_TEXT_SUPPORT + public static DirectionType BaseDirection = DirectionType.RTL; // 主体语言是否是RTL的语言 +#else + public static DirectionType BaseDirection = DirectionType.UNKNOW; +#endif + private static bool isCharsInitialized = false; + private static Dictionary mapping = new Dictionary(); + + private static List listFinal = new List(); + private static List listRep = new List(); + private static StringBuilder sbRep = new StringBuilder(); + private static StringBuilder sbN = new StringBuilder(); + private static StringBuilder sbFinal = new StringBuilder(); + private static StringBuilder sbReverse = new StringBuilder(); + + public static bool IsArabicLetter(char ch) + { + if (ch >= 0x600 && ch <= 0x6ff) + { + if ((ch >= 0x660 && ch <= 0x66D) || (ch >= 0x6f0 && ch <= 0x6f9)) // 标准阿拉伯语数字和东阿拉伯语数字 [2019/3/1/ 17:45:18 by aq_1000] + { + return false; + } + return true; + } + else if (ch >= 0x750 && ch <= 0x77f) + return true; + else if (ch >= 0xfb50 && ch <= 0xfc3f) + return true; + else if (ch >= 0xfe70 && ch <= 0xfefc) + return true; + return false; + } + + public static string ConvertNumber(string strNumber) + { + sbRep.Length = 0; + foreach (char ch in strNumber) + { + int un = ch; + if (un == 0x66c || ch == ',') // 去掉逗号 + continue; + else if (un == 0x660 || un == 0x6f0) + sbRep.Append('0'); + else if (un == 0x661 || un == 0x6f1) + sbRep.Append('1'); + else if (un == 0x662 || un == 0x6f2) + sbRep.Append('2'); + else if (un == 0x663 || un == 0x6f3) + sbRep.Append('3'); + else if (un == 0x664 || un == 0x6f4) + sbRep.Append('4'); + else if (un == 0x665 || un == 0x6f5) + sbRep.Append('5'); + else if (un == 0x666 || un == 0x6f6) + sbRep.Append('6'); + else if (un == 0x667 || un == 0x6f7) + sbRep.Append('7'); + else if (un == 0x668 || un == 0x6f8) + sbRep.Append('8'); + else if (un == 0x669 || un == 0x6f9) + sbRep.Append('9'); + else + sbRep.Append(ch); + } + return sbRep.ToString(); + } + + public static bool ContainsArabicLetters(string text) + { + foreach (char character in text) + { + if (character >= 0x600 && character <= 0x6ff) + return true; + + if (character >= 0x750 && character <= 0x77f) + return true; + + if (character >= 0xfb50 && character <= 0xfc3f) + return true; + + if (character >= 0xfe70 && character <= 0xfefc) + return true; + } + return false; + } + + // 检测文本主方向 + public static DirectionType DetectTextDirection(string text) + { + bool isContainRTL = false; + bool isContainLTR = false; + foreach (char ch in text) + { + if (IsArabicLetter(ch)) + { + isContainRTL = true; + if (isContainLTR) + break; + } + else if (char.IsLetter(ch)) + { + isContainLTR = true; + if (isContainRTL) + break; + } + } + if (!isContainRTL) + return DirectionType.UNKNOW; // 这边unknow暂时代表文本一个RTL字符都没有,无需进行RTL转换 + else if (!isContainLTR) + return DirectionType.RTL; + return BaseDirection; + } + + private static bool CheckSeparator(char input) + { + if (!IsArabicLetter(input)) + { + return true; + } + else + { + return (input == '،') || (input == '?') || (input == '؟'); + } + + // if ((input != ' ') && (input != '\t') && (input != '!') && (input != '.') && + // (input != '،') && (input != '?') && (input != '؟') && + // !_IsBracket(input) && // 括号也算 [2018/8/1/ 15:12:20 by aq_1000] + // !_IsNeutrality(input)) + // { + // return false; + // } + // return true; + } + + private static bool CheckSpecific(char input) + { + int num = input; + if ((num != 0x622) && (num != 0x623) && (num != 0x627) && (num != 0x62f) && (num != 0x625) && + (num != 0x630) && (num != 0x631) && (num != 0x632) && (num != 0x698) && (num != 0x648) && + !_CheckSoundmark(input)) + { + return false; + } + return true; + } + + private static bool _CheckSoundmark(char ch) + { + int un = ch; + return (un >= 0x610 && un <= 0x61e) || (un >= 0x64b && un <= 0x65f); + } + + public static string DoMapping(string input) + { + if (!isCharsInitialized) + { + isCharsInitialized = true; + InitChars(); + } + + // 伊斯兰教真主安拉在阿拉伯文里写作الله + // 键盘输入时输入 ل (lam) + ل (lam) + ه (ha) 后会自动转换成带记号的符号。 [2018/3/13 20:03:45 --By aq_1000] + if (input == "الله") + { + input = "ﷲ"; + } + + sbFinal.Length = 0; + sbFinal.Append(input); + char perChar = '\0'; + for (int i = 0; i < sbFinal.Length; i++) + { + if (!mapping.ContainsKey(sbFinal[i])) + { + perChar = sbFinal[i]; + continue; + } + + if ((i + 1) == sbFinal.Length) + { + if (sbFinal.Length == 1) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else if (CheckSeparator(perChar) || CheckSpecific(perChar)) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.final]; + } + } + else if (i == 0) + { + if (!CheckSeparator(sbFinal[i + 1])) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + } + else if (CheckSeparator(sbFinal[i + 1])) + { + if (CheckSeparator(perChar) || CheckSpecific(perChar)) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.final]; + } + } + else if (CheckSeparator(perChar)) + { + if (CheckSeparator(sbFinal[i + 1])) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + } + else if (CheckSpecific(sbFinal[i + 1])) + { + if (CheckSeparator(perChar) || CheckSpecific(perChar)) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.middle]; + } + } + else if (CheckSpecific(perChar)) + { + if (CheckSeparator(sbFinal[i + 1])) + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.isolated]; + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.lead]; + } + } + else + { + perChar = sbFinal[i]; + sbFinal[i] = mapping[sbFinal[i]][(int)CharState.middle]; + } + } + return sbFinal.ToString(); + } + + // 主体语言是LTR + public static string ConvertLineL(string source) + { + listFinal.Clear(); + listRep.Clear(); + sbRep.Length = 0; + sbN.Length = 0; + int iReplace = 0; + DirectionType ePre = DirectionType.LTR; + char nextChar = '\0'; + for (int j = 0; j < source.Length; j++) + { + if (j < source.Length - 1) + nextChar = source[j + 1]; + else + nextChar = '\0'; + char item = source[j]; + DirectionType eCType = _GetDirection(item, nextChar, ePre, DirectionType.LTR); + if (eCType == DirectionType.RTL) + { + if (sbRep.Length == 0) + { + listFinal.Add('\x00bf'); + iReplace++; + } + + if (sbN.Length > 0) + sbRep.Append(sbN.ToString()); + sbN.Length = 0; + sbRep.Append(item); + } + else if (eCType == DirectionType.LTR) + { + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + sbRep.Length = 0; + + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + sbN.Length = 0; + + // item = _ProcessBracket(item); // 文本主方向为LTR的话,括号不需要翻转 [2018/12/20/ 17:03:23 by aq_1000] + listFinal.Add(item); + } + else + { + sbN.Append(item); + } + ePre = eCType; + } + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + + // 一行中都只有中立字符的情况,就直接返回中立字符 [2018/12/6/ 16:34:38 by aq_1000] + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + + sbRep.Length = 0; + sbN.Length = 0; + sbFinal.Length = 0; + sbFinal.Append(listFinal.ToArray()); + for (int m = 0; m < iReplace; m++) + { + for (int n = 0; n < sbFinal.Length; n++) + { + if (sbFinal[n] == '\x00bf') + { + sbRep.Length = 0; + sbRep.Append(_Reverse(listRep[0])); + listRep.RemoveAt(0); + + // 字符串反向的时候造成末尾空格跑到词首 [2018/4/11 20:04:35 --By aq_1000] + sbN.Length = 0; + for (int num4 = 0; num4 < sbRep.Length; num4++) + { + if (!_IsNeutrality(sbRep[num4])) + break; + sbN.Append(sbRep[num4]); + } + if (sbN.Length > 0) // 词首空格重新放到词尾 + { + sbRep.Remove(0, sbN.Length); + for (int iSpace = sbN.Length - 1; iSpace >= 0; --iSpace) // 空格也要取反 + { + sbRep.Append(sbN[iSpace]); + } + } + + sbFinal.Replace(sbFinal[n].ToString(), sbRep.ToString(), n, 1); + break; + } + } + } + return sbFinal.ToString(); + } + + // 主体语言是RTL,整个文本就从右往左读,LTR语言就作为嵌入语段处理 + public static string ConvertLineR(string source) + { + listFinal.Clear(); + listRep.Clear(); + sbRep.Length = 0; + sbN.Length = 0; + int iReplace = 0; + DirectionType ePre = DirectionType.RTL; + char nextChar = '\0'; + for (int j = 0; j < source.Length; j++) + { + if (j < source.Length - 1) + nextChar = source[j + 1]; + else + nextChar = '\0'; + char item = source[j]; + DirectionType eCType = _GetDirection(item, nextChar, ePre, DirectionType.RTL); + if (eCType == DirectionType.LTR) + { + if (sbRep.Length == 0) + { + listFinal.Add('\x00bf'); + iReplace++; + } + + if (sbN.Length > 0) + sbRep.Append(sbN.ToString()); + sbN.Length = 0; + sbRep.Append(item); + } + else if (eCType == DirectionType.RTL) + { + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + sbRep.Length = 0; + + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + sbN.Length = 0; + + item = _ProcessBracket(item); + listFinal.Add(item); + } + else + { + sbN.Append(item); + } + ePre = eCType; + } + if (sbRep.Length > 0) + { + listRep.Add(sbRep.ToString()); + } + + // 一行中都只有中立字符的情况,就直接返回中立字符 [2018/12/6/ 16:34:38 by aq_1000] + if (sbN.Length > 0) + { + for (int n = 0; n < sbN.Length; ++n) + { + listFinal.Add(sbN[n]); + } + } + + sbFinal.Length = 0; + sbFinal.Append(listFinal.ToArray()); + for (int m = 0; m < iReplace; m++) + { + for (int n = 0; n < sbFinal.Length; n++) + { + if (sbFinal[n] == '\x00bf') + { + sbRep.Length = 0; + sbRep.Append(_Reverse(listRep[0])); + listRep.RemoveAt(0); + + // 字符串反向的时候造成末尾空格跑到词首 [2018/4/11 20:04:35 --By aq_1000] + sbN.Length = 0; + for (int num4 = 0; num4 < sbRep.Length; num4++) + { + if (!_IsNeutrality(sbRep[num4])) + break; + sbN.Append(sbRep[num4]); + } + if (sbN.Length > 0) // 词首空格重新放到词尾 + { + sbRep.Remove(0, sbN.Length); + for (int iSpace = sbN.Length - 1; iSpace >= 0; --iSpace) // 空格也要取反 + { + sbRep.Append(sbN[iSpace]); + } + } + + sbFinal.Replace(sbFinal[n].ToString(), sbRep.ToString(), n, 1); + break; + } + } + } + return sbFinal.ToString(); + } + + + private static string _Reverse(string source) + { + sbReverse.Length = 0; + int len = source.Length; + int i = len - 1; + while (i >= 0) + { + char ch = source[i]; + if (ch == '\r' && i != len - 1 && source[i + 1] == '\n') + { + i--; + continue; + } + + if (char.IsLowSurrogate(ch)) //不要反向高低代理对 + { + sbReverse.Append(source[i - 1]); + sbReverse.Append(ch); + i--; + } + else + sbReverse.Append(ch); + i--; + } + + return sbReverse.ToString(); + } + + private static void InitChars() + { + // {isolated,final,lead,middle} [2018/11/27 16:04:18 --By aq_1000] + mapping.Add(0x621, new char[4] { (char)0xFE80, (char)0xFE8A, (char)0xFE8B, (char)0xFE8C }); // Hamza + mapping.Add(0x627, new char[4] { (char)0xFE8D, (char)0xFE8E, (char)0xFE8D, (char)0xFE8E }); // Alef + mapping.Add(0x623, new char[4] { (char)0xFE83, (char)0xFE84, (char)0xFE83, (char)0xFE84 }); // AlefHamza + mapping.Add(0x624, new char[4] { (char)0xFE85, (char)0xFE85, (char)0xFE85, (char)0xFE85 }); // WawHamza + mapping.Add(0x625, new char[4] { (char)0xFE87, (char)0xFE87, (char)0xFE87, (char)0xFE87 }); // AlefMaksoor + mapping.Add(0x649, new char[4] { (char)0xFBFC, (char)0xFBFD, (char)0xFBFE, (char)0xFBFF }); // AlefMagsora + mapping.Add(0x626, new char[4] { (char)0xFE89, (char)0xFE8A, (char)0xFE8B, (char)0xFE8C }); // HamzaNabera + mapping.Add(0x628, new char[4] { (char)0xFE8F, (char)0xFE90, (char)0xFE91, (char)0xFE92 }); // Ba + mapping.Add(0x62A, new char[4] { (char)0xFE95, (char)0xFE96, (char)0xFE97, (char)0xFE98 }); // Ta + mapping.Add(0x62B, new char[4] { (char)0xFE99, (char)0xFE9A, (char)0xFE9B, (char)0xFE9C }); // Tha2 + mapping.Add(0x62C, new char[4] { (char)0xFE9D, (char)0xFE9E, (char)0xFE9F, (char)0xFEA0 }); // Jeem + mapping.Add(0x62D, new char[4] { (char)0xFEA1, (char)0xFEA2, (char)0xFEA3, (char)0xFEA4 }); // H7aa + mapping.Add(0x62E, new char[4] { (char)0xFEA5, (char)0xFEA6, (char)0xFEA7, (char)0xFEA8 }); // Khaa2 + mapping.Add(0x62F, new char[4] { (char)0xFEA9, (char)0xFEAA, (char)0xFEA9, (char)0xFEAA }); // Dal + mapping.Add(0x630, new char[4] { (char)0xFEAB, (char)0xFEAC, (char)0xFEAB, (char)0xFEAC }); // Thal + mapping.Add(0x631, new char[4] { (char)0xFEAD, (char)0xFEAE, (char)0xFEAD, (char)0xFEAD }); // Ra2 + mapping.Add(0x632, new char[4] { (char)0xFEAF, (char)0xFEB0, (char)0xFEAF, (char)0xFEB0 }); // Zeen + mapping.Add(0x633, new char[4] { (char)0xFEB1, (char)0xFEB2, (char)0xFEB3, (char)0xFEB4 }); // Seen + mapping.Add(0x634, new char[4] { (char)0xFEB5, (char)0xFEB6, (char)0xFEB7, (char)0xFEB8 }); // Sheen + mapping.Add(0x635, new char[4] { (char)0xFEB9, (char)0xFEBA, (char)0xFEBB, (char)0xFEBC }); // S9a + mapping.Add(0x636, new char[4] { (char)0xFEBD, (char)0xFEBE, (char)0xFEBF, (char)0xFEC0 }); // Dha + mapping.Add(0x637, new char[4] { (char)0xFEC1, (char)0xFEC2, (char)0xFEC3, (char)0xFEC4 }); // T6a + mapping.Add(0x638, new char[4] { (char)0xFEC5, (char)0xFEC6, (char)0xFEC7, (char)0xFEC8 }); // T6ha + mapping.Add(0x639, new char[4] { (char)0xFEC9, (char)0xFECA, (char)0xFECB, (char)0xFECC }); // Ain + mapping.Add(0x63A, new char[4] { (char)0xFECD, (char)0xFECE, (char)0xFECF, (char)0xFED0 }); // Gain + mapping.Add(0x641, new char[4] { (char)0xFED1, (char)0xFED2, (char)0xFED3, (char)0xFED4 }); // Fa + mapping.Add(0x642, new char[4] { (char)0xFED5, (char)0xFED6, (char)0xFED7, (char)0xFED8 }); // Gaf + mapping.Add(0x643, new char[4] { (char)0xFED9, (char)0xFEDA, (char)0xFEDB, (char)0xFEDC }); // Kaf + mapping.Add(0x644, new char[4] { (char)0xFEDD, (char)0xFEDE, (char)0xFEDF, (char)0xFEE0 }); // Lam + mapping.Add(0x645, new char[4] { (char)0xFEE1, (char)0xFEE2, (char)0xFEE3, (char)0xFEE4 }); // Meem + mapping.Add(0x646, new char[4] { (char)0xFEE5, (char)0xFEE6, (char)0xFEE7, (char)0xFEE8 }); // Noon + mapping.Add(0x647, new char[4] { (char)0xFEE9, (char)0xFEEA, (char)0xFEEB, (char)0xFEEC }); // Ha + mapping.Add(0x648, new char[4] { (char)0xFEED, (char)0xFEEE, (char)0xFEED, (char)0xFEEE }); // Waw + mapping.Add(0x64A, new char[4] { (char)0xFEF1, (char)0xFEF2, (char)0xFEF3, (char)0xFEF4 }); // Ya + mapping.Add(0x622, new char[4] { (char)0xFE81, (char)0xFE81, (char)0xFE81, (char)0xFE81 }); // AlefMad + mapping.Add(0x629, new char[4] { (char)0xFE93, (char)0xFE94, (char)0xFE94, (char)0xFE94 }); // TaMarboota // 该字符只会出现在末尾 [2018/4/10 16:04:18 --By aq_1000] + mapping.Add(0x67E, new char[4] { (char)0xFB56, (char)0xFB57, (char)0xFB58, (char)0xFB59 }); // PersianPe + mapping.Add(0x686, new char[4] { (char)0xFB7A, (char)0xFB7B, (char)0xFB7C, (char)0xFB7D }); // PersianChe + mapping.Add(0x698, new char[4] { (char)0xFB8A, (char)0xFB8B, (char)0xFB8A, (char)0xFB8B }); // PersianZe + mapping.Add(0x6AF, new char[4] { (char)0xFB92, (char)0xFB93, (char)0xFB94, (char)0xFB95 }); // PersianGaf + mapping.Add(0x6A9, new char[4] { (char)0xFB8E, (char)0xFB8F, (char)0xFB90, (char)0xFB91 }); // PersianGaf2 + + mapping.Add(0x6BE, new char[4] { (char)0xFEE9, (char)0xFEEA, (char)0xFEEB, (char)0xFEEC }); + mapping.Add(0x6CC, new char[4] { (char)0xFBFC, (char)0xFBFD, (char)0xFBFE, (char)0xFBFF }); + } + + // 是否中立方向字符 + private static bool _IsNeutrality(char uc) + { + return (uc == ':' || uc == ':' || uc == ' ' || /*uc == '%' ||*/ /*uc == '+' ||*/ /*uc == '-' ||*/ uc == '\n' || uc == '\r' || uc == '\t' || uc == '@' || + (uc >= 0x2600 && uc <= 0x27BF)); // 表情符号 + } + + // 是否句末标点符号 + private static bool _IsEndPunctuation(char uc, char nextChar) + { + if (uc == '.') + return _IsNeutrality(nextChar); + return (uc == '!' || uc == '!' || uc == '。' || uc == '،' || uc == '?' || uc == '؟'); + } + + // 判断字符方向 + private static DirectionType _GetDirection(char uc, char nextChar, DirectionType ePre, DirectionType eBase) + { + DirectionType eCType = ePre; + int uni = uc; + + if (_IsBracket(uc) || _IsEndPunctuation(uc, nextChar)) + { + eCType = eBase; // 括号和句末标点符号,方向根据上个字符为准 [2018/12/26/ 15:56:24 by aq_1000] + } + else if ((uni >= 0x660) && (uni <= 0x66D)) + { + eCType = DirectionType.LTR; + } + else if (IsArabicLetter(uc) || uc == '+' /*|| uc == '-'*/ || uc == '%') + { + eCType = DirectionType.RTL; + } + else if (uc == '-') + { + if (char.IsNumber(nextChar)) + eCType = DirectionType.LTR; + else + eCType = DirectionType.RTL; + } + else if (_IsNeutrality(uc)) // 中立方向字符,方向就和上一个字符一样 [2018/3/24 16:03:27 --By aq_1000] + { + if (ePre == DirectionType.UNKNOW || ePre == DirectionType.NEUTRAL) + { + if (char.IsNumber(nextChar)) // 数字都是弱LTR方向符,开头中立字符后面紧跟着数字的话,中立字符方向算文本主方向 [IsDigit()只是0-9] [2018/12/20/ 16:32:32 by aq_1000] + { + eCType = BaseDirection; + } + else + eCType = DirectionType.NEUTRAL; + } + else + eCType = ePre; + } + else + eCType = DirectionType.LTR; + + return eCType; + } + + // 是否括号 + private static bool _IsBracket(char uc) + { + return (uc == ')' || uc == '(' || uc == ')' || uc == '(' || + uc == ']' || uc == '[' || uc == '】' || uc == '【' || + uc == '}' || uc == '{' || + // uc == '≥' || uc == '≤' || uc == '>' || uc == '<' || + uc == '》' || uc == '《' || uc == '“' || uc == '”' || uc == '"'); + } + + // 这些配对符,在从右至左排列中应该逆序显示 + private static char _ProcessBracket(char uc) + { + if (uc == '[') return ']'; + else if (uc == ']') return '['; + else if (uc == '【') return '】'; + else if (uc == '】') return '【'; + else if (uc == '{') return '}'; + else if (uc == '}') return '{'; + else if (uc == '(') return ')'; + else if (uc == ')') return '('; + else if (uc == '(') return ')'; + else if (uc == ')') return '('; + else if (uc == '<') return '>'; + else if (uc == '>') return '<'; + else if (uc == '《') return '》'; + else if (uc == '》') return '《'; + else if (uc == '≤') return '≥'; + else if (uc == '≥') return '≤'; + else if (uc == '”') return '“'; + else if (uc == '”') return '“'; + else return uc; + } + } +} + diff --git a/Assets/Scripts/Core/Text/RTLSupport.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RTLSupport.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/RTLSupport.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RTLSupport.cs.meta diff --git a/Assets/Scripts/Core/Text/RichTextField.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RichTextField.cs similarity index 96% rename from Assets/Scripts/Core/Text/RichTextField.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RichTextField.cs index 3769359b..1603ee67 100644 --- a/Assets/Scripts/Core/Text/RichTextField.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RichTextField.cs @@ -1,216 +1,216 @@ -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class RichTextField : Container - { - /// - /// - /// - public IHtmlPageContext htmlPageContext { get; set; } - - /// - /// - /// - public HtmlParseOptions htmlParseOptions { get; private set; } - - /// - /// - /// - public Dictionary emojies { get; set; } - - /// - /// - /// - public TextField textField { get; private set; } - - public RichTextField() - { - gameObject.name = "RichTextField"; - this.opaque = true; - - htmlPageContext = HtmlPageContext.inst; - htmlParseOptions = new HtmlParseOptions(); - - this.textField = new TextField(); - textField.EnableRichSupport(this); - AddChild(textField); - } - - /// - /// - /// - virtual public string text - { - get { return textField.text; } - set { textField.text = value; } - } - - /// - /// - /// - virtual public string htmlText - { - get { return textField.htmlText; } - set { textField.htmlText = value; } - } - - /// - /// - /// - virtual public TextFormat textFormat - { - get { return textField.textFormat; } - set { textField.textFormat = value; } - } - - /// - /// - /// - /// - /// - public HtmlElement GetHtmlElement(string name) - { - List elements = textField.htmlElements; - int count = elements.Count; - for (int i = 0; i < count; i++) - { - HtmlElement element = elements[i]; - if (name.Equals(element.name, System.StringComparison.OrdinalIgnoreCase)) - return element; - } - - return null; - } - - /// - /// - /// - /// - /// - public HtmlElement GetHtmlElementAt(int index) - { - return textField.htmlElements[index]; - } - - /// - /// - /// - public int htmlElementCount - { - get { return textField.htmlElements.Count; } - } - - /// - /// - /// - /// - /// - public void ShowHtmlObject(int index, bool show) - { - HtmlElement element = textField.htmlElements[index]; - if (element.htmlObject != null && element.type != HtmlElementType.Link) - { - //set hidden flag - if (show) - element.status &= 253; //~(1<<1) - else - element.status |= 2; - - if ((element.status & 3) == 0) //not (hidden and clipped) - { - if ((element.status & 4) == 0) //not added - { - element.status |= 4; - element.htmlObject.Add(); - } - } - else - { - if ((element.status & 4) != 0) //added - { - element.status &= 251; - element.htmlObject.Remove(); - } - } - } - } - - public override void EnsureSizeCorrect() - { - textField.EnsureSizeCorrect(); - } - - override protected void OnSizeChanged() - { - textField.size = _contentRect.size; //千万不可以调用this.size,后者会触发EnsureSizeCorrect - - base.OnSizeChanged(); - } - - public override void Update(UpdateContext context) - { - textField.Redraw(); - - base.Update(context); - } - - public override void Dispose() - { - if ((_flags & Flags.Disposed) != 0) - return; - - CleanupObjects(); - - base.Dispose(); - } - - internal void CleanupObjects() - { - List elements = textField.htmlElements; - int count = elements.Count; - for (int i = 0; i < count; i++) - { - HtmlElement element = elements[i]; - if (element.htmlObject != null) - { - element.htmlObject.Remove(); - htmlPageContext.FreeObject(element.htmlObject); - } - } - } - - virtual internal void RefreshObjects() - { - List elements = textField.htmlElements; - int count = elements.Count; - for (int i = 0; i < count; i++) - { - HtmlElement element = elements[i]; - if (element.htmlObject != null) - { - if ((element.status & 3) == 0) //not (hidden and clipped) - { - if ((element.status & 4) == 0) //not added - { - element.status |= 4; - element.htmlObject.Add(); - } - } - else - { - if ((element.status & 4) != 0) //added - { - element.status &= 251; - element.htmlObject.Remove(); - } - } - } - } - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class RichTextField : Container + { + /// + /// + /// + public IHtmlPageContext htmlPageContext { get; set; } + + /// + /// + /// + public HtmlParseOptions htmlParseOptions { get; private set; } + + /// + /// + /// + public Dictionary emojies { get; set; } + + /// + /// + /// + public TextField textField { get; private set; } + + public RichTextField() + { + gameObject.name = "RichTextField"; + this.opaque = true; + + htmlPageContext = HtmlPageContext.inst; + htmlParseOptions = new HtmlParseOptions(); + + this.textField = new TextField(); + textField.EnableRichSupport(this); + AddChild(textField); + } + + /// + /// + /// + virtual public string text + { + get { return textField.text; } + set { textField.text = value; } + } + + /// + /// + /// + virtual public string htmlText + { + get { return textField.htmlText; } + set { textField.htmlText = value; } + } + + /// + /// + /// + virtual public TextFormat textFormat + { + get { return textField.textFormat; } + set { textField.textFormat = value; } + } + + /// + /// + /// + /// + /// + public HtmlElement GetHtmlElement(string name) + { + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (name.Equals(element.name, System.StringComparison.OrdinalIgnoreCase)) + return element; + } + + return null; + } + + /// + /// + /// + /// + /// + public HtmlElement GetHtmlElementAt(int index) + { + return textField.htmlElements[index]; + } + + /// + /// + /// + public int htmlElementCount + { + get { return textField.htmlElements.Count; } + } + + /// + /// + /// + /// + /// + public void ShowHtmlObject(int index, bool show) + { + HtmlElement element = textField.htmlElements[index]; + if (element.htmlObject != null && element.type != HtmlElementType.Link) + { + //set hidden flag + if (show) + element.status &= 253; //~(1<<1) + else + element.status |= 2; + + if ((element.status & 3) == 0) //not (hidden and clipped) + { + if ((element.status & 4) == 0) //not added + { + element.status |= 4; + element.htmlObject.Add(); + } + } + else + { + if ((element.status & 4) != 0) //added + { + element.status &= 251; + element.htmlObject.Remove(); + } + } + } + } + + public override void EnsureSizeCorrect() + { + textField.EnsureSizeCorrect(); + } + + override protected void OnSizeChanged() + { + textField.size = _contentRect.size; //千万不可以调用this.size,后者会触发EnsureSizeCorrect + + base.OnSizeChanged(); + } + + public override void Update(UpdateContext context) + { + textField.Redraw(); + + base.Update(context); + } + + public override void Dispose() + { + if ((_flags & Flags.Disposed) != 0) + return; + + CleanupObjects(); + + base.Dispose(); + } + + internal void CleanupObjects() + { + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (element.htmlObject != null) + { + element.htmlObject.Remove(); + htmlPageContext.FreeObject(element.htmlObject); + } + } + } + + virtual internal void RefreshObjects() + { + List elements = textField.htmlElements; + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + if (element.htmlObject != null) + { + if ((element.status & 3) == 0) //not (hidden and clipped) + { + if ((element.status & 4) == 0) //not added + { + element.status |= 4; + element.htmlObject.Add(); + } + } + else + { + if ((element.status & 4) != 0) //added + { + element.status &= 251; + element.htmlObject.Remove(); + } + } + } + } + } + } +} diff --git a/Assets/Scripts/Core/Text/RichTextField.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RichTextField.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/RichTextField.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/RichTextField.cs.meta diff --git a/Assets/Scripts/Core/Text/SelectionShape.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/SelectionShape.cs similarity index 96% rename from Assets/Scripts/Core/Text/SelectionShape.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/SelectionShape.cs index ab9dddf7..90b8548a 100644 --- a/Assets/Scripts/Core/Text/SelectionShape.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/SelectionShape.cs @@ -1,94 +1,94 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class SelectionShape : DisplayObject, IMeshFactory - { - public readonly List rects; - - public SelectionShape() - { - CreateGameObject("SelectionShape"); - graphics = new NGraphics(gameObject); - graphics.texture = NTexture.Empty; - graphics.meshFactory = this; - - rects = new List(); - } - - /// - /// - /// - public Color color - { - get - { - return graphics.color; - } - set - { - graphics.color = value; - graphics.Tint(); - } - } - - public void Refresh() - { - int count = rects.Count; - if (count > 0) - { - Rect rect = new Rect(); - rect = rects[0]; - Rect tmp; - for (int i = 1; i < count; i++) - { - tmp = rects[i]; - rect = ToolSet.Union(ref rect, ref tmp); - } - SetSize(rect.xMax, rect.yMax); - } - else - SetSize(0, 0); - graphics.SetMeshDirty(); - } - - public void Clear() - { - rects.Clear(); - graphics.SetMeshDirty(); - } - - public void OnPopulateMesh(VertexBuffer vb) - { - int count = rects.Count; - if (count == 0 || this.color == Color.clear) - return; - - for (int i = 0; i < count; i++) - vb.AddQuad(rects[i]); - vb.AddTriangles(); - } - - protected override DisplayObject HitTest() - { - Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); - - if (_contentRect.Contains(localPoint)) - { - int count = rects.Count; - for (int i = 0; i < count; i++) - { - if (rects[i].Contains(localPoint)) - return this; - } - } - - return null; - } - } -} +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class SelectionShape : DisplayObject, IMeshFactory + { + public readonly List rects; + + public SelectionShape() + { + CreateGameObject("SelectionShape"); + graphics = new NGraphics(gameObject); + graphics.texture = NTexture.Empty; + graphics.meshFactory = this; + + rects = new List(); + } + + /// + /// + /// + public Color color + { + get + { + return graphics.color; + } + set + { + graphics.color = value; + graphics.Tint(); + } + } + + public void Refresh() + { + int count = rects.Count; + if (count > 0) + { + Rect rect = new Rect(); + rect = rects[0]; + Rect tmp; + for (int i = 1; i < count; i++) + { + tmp = rects[i]; + rect = ToolSet.Union(ref rect, ref tmp); + } + SetSize(rect.xMax, rect.yMax); + } + else + SetSize(0, 0); + graphics.SetMeshDirty(); + } + + public void Clear() + { + rects.Clear(); + graphics.SetMeshDirty(); + } + + public void OnPopulateMesh(VertexBuffer vb) + { + int count = rects.Count; + if (count == 0 || this.color == Color.clear) + return; + + for (int i = 0; i < count; i++) + vb.AddQuad(rects[i]); + vb.AddTriangles(); + } + + protected override DisplayObject HitTest() + { + Vector2 localPoint = WorldToLocal(HitTestContext.worldPoint, HitTestContext.direction); + + if (_contentRect.Contains(localPoint)) + { + int count = rects.Count; + for (int i = 0; i < count; i++) + { + if (rects[i].Contains(localPoint)) + return this; + } + } + + return null; + } + } +} diff --git a/Assets/Scripts/Core/Text/SelectionShape.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/SelectionShape.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/SelectionShape.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/SelectionShape.cs.meta diff --git a/Assets/Scripts/Core/Text/TextField.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextField.cs similarity index 97% rename from Assets/Scripts/Core/Text/TextField.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextField.cs index 3fd25cc6..59e44e3a 100644 --- a/Assets/Scripts/Core/Text/TextField.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextField.cs @@ -1,1701 +1,1701 @@ -using System; -using System.Collections.Generic; -using System.Text; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class TextField : DisplayObject, IMeshFactory - { - VertAlignType _verticalAlign; - TextFormat _textFormat; - bool _input; - string _text; - AutoSizeType _autoSize; - bool _wordWrap; - bool _singleLine; - bool _html; - RTLSupport.DirectionType _textDirection; - int _maxWidth; - - List _elements; - List _lines; - List _charPositions; - - BaseFont _font; - float _textWidth; - float _textHeight; - bool _textChanged; - float _yOffset; - float _fontSizeScale; - float _renderScale; - int _fontVersion; - string _parsedText; - int _ellipsisCharIndex; - - RichTextField _richTextField; - - const int GUTTER_X = 2; - const int GUTTER_Y = 2; - const float IMAGE_BASELINE = 0.8f; - const int ELLIPSIS_LENGTH = 2; - static float[] STROKE_OFFSET = new float[] - { - -1, 0, 1, 0, - 0, -1, 0, 1, - -1, -1, 1, -1, - -1, 1, 1, 1 - }; - static List sLineChars = new List(); - - public TextField() - { - _flags |= Flags.TouchDisabled; - - _textFormat = new TextFormat(); - _fontSizeScale = 1; - _renderScale = UIContentScaler.scaleFactor; - - _wordWrap = false; - _text = string.Empty; - _parsedText = string.Empty; - - _elements = new List(0); - _lines = new List(1); - - CreateGameObject("TextField"); - graphics = new NGraphics(gameObject); - graphics.meshFactory = this; - } - - internal void EnableRichSupport(RichTextField richTextField) - { - _richTextField = richTextField; - if (richTextField is InputTextField) - { - _input = true; - EnableCharPositionSupport(); - } - } - - public void EnableCharPositionSupport() - { - if (_charPositions == null) - { - _charPositions = new List(); - _textChanged = true; - } - } - - /// - /// - /// - public TextFormat textFormat - { - get { return _textFormat; } - set - { - _textFormat = value; - ApplyFormat(); - } - } - - /// - /// - /// - public void ApplyFormat() - { - string fontName = _textFormat.font; - if (string.IsNullOrEmpty(fontName)) - fontName = UIConfig.defaultFont; - BaseFont newFont = FontManager.GetFont(fontName); - if (_font != newFont) - { - _font = newFont; - _fontVersion = _font.version; - graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); - } - - if (!string.IsNullOrEmpty(_text)) - _textChanged = true; - } - - /// - /// - /// - public AlignType align - { - get { return _textFormat.align; } - set - { - if (_textFormat.align != value) - { - _textFormat.align = value; - if (!string.IsNullOrEmpty(_text)) - _textChanged = true; - } - } - } - - /// - /// - /// - public VertAlignType verticalAlign - { - get - { - return _verticalAlign; - } - set - { - if (_verticalAlign != value) - { - _verticalAlign = value; - if (!_textChanged) - ApplyVertAlign(); - } - } - } - - /// - /// - /// - public string text - { - get { return _text; } - set - { - if (_text == value && !_html) - return; - - _text = value; - _textChanged = true; - _html = false; - } - } - - /// - /// - /// - public string htmlText - { - get { return _text; } - set - { - if (_text == value && _html) - return; - - _text = value; - _textChanged = true; - _html = true; - } - } - - public string parsedText - { - get { return _parsedText; } - } - - /// - /// - /// - public AutoSizeType autoSize - { - get { return _autoSize; } - set - { - if (_autoSize != value) - { - _autoSize = value; - _textChanged = true; - } - } - } - - /// - /// - /// - public bool wordWrap - { - get { return _wordWrap; } - set - { - if (_wordWrap != value) - { - _wordWrap = value; - _textChanged = true; - } - } - } - - /// - /// - /// - public bool singleLine - { - get { return _singleLine; } - set - { - if (_singleLine != value) - { - _singleLine = value; - _textChanged = true; - } - } - } - - /// - /// - /// - public float stroke - { - get - { - return _textFormat.outline; - } - set - { - if (_textFormat.outline != value) - { - _textFormat.outline = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public Color strokeColor - { - get - { - return _textFormat.outlineColor; - } - set - { - if (_textFormat.outlineColor != value) - { - _textFormat.outlineColor = value; - graphics.SetMeshDirty(); - } - } - } - - /// - /// - /// - public Vector2 shadowOffset - { - get - { - return _textFormat.shadowOffset; - } - set - { - _textFormat.shadowOffset = value; - graphics.SetMeshDirty(); - } - } - - /// - /// - /// - public float textWidth - { - get - { - if (_textChanged) - BuildLines(); - - return _textWidth; - } - } - - /// - /// - /// - public float textHeight - { - get - { - if (_textChanged) - BuildLines(); - - return _textHeight; - } - } - - /// - /// - /// - public int maxWidth - { - get { return _maxWidth; } - set - { - if (_maxWidth != value) - { - _maxWidth = value; - _textChanged = true; - } - } - } - - /// - /// - /// - public List htmlElements - { - get - { - if (_textChanged) - BuildLines(); - - return _elements; - } - } - - /// - /// - /// - public List lines - { - get - { - if (_textChanged) - BuildLines(); - - return _lines; - } - } - - /// - /// - /// - public List charPositions - { - get - { - if (_textChanged) - BuildLines(); - - graphics.UpdateMesh(); - - return _charPositions; - } - } - - /// - /// - /// - public RichTextField richTextField - { - get { return _richTextField; } - } - - /// - /// - /// - public bool Redraw() - { - if (_font == null) - { - _font = FontManager.GetFont(UIConfig.defaultFont); - graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); - _fontVersion = _font.version; - _textChanged = true; - } - - if (_font.keepCrisp && _renderScale != UIContentScaler.scaleFactor) - _textChanged = true; - - if (_font.version != _fontVersion) - { - _fontVersion = _font.version; - if (_font.mainTexture != graphics.texture) - { - graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); - InvalidateBatchingState(); - } - - _textChanged = true; - } - - if (_textChanged) - BuildLines(); - - return graphics.UpdateMesh(); - } - - /// - /// - /// - public bool HasCharacter(char ch) - { - return _font.HasCharacter(ch); - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void GetLinesShape(int startLine, float startCharX, int endLine, float endCharX, - bool clipped, - List resultRects) - { - LineInfo line1 = _lines[startLine]; - LineInfo line2 = _lines[endLine]; - bool leftAlign = _textFormat.align == AlignType.Left; - if (startLine == endLine) - { - Rect r = Rect.MinMaxRect(startCharX, line1.y, endCharX, line1.y + line1.height); - if (clipped) - resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); - else - resultRects.Add(r); - } - else if (startLine == endLine - 1) - { - Rect r = Rect.MinMaxRect(startCharX, line1.y, leftAlign ? (GUTTER_X + line1.width) : _contentRect.xMax, line1.y + line1.height); - if (clipped) - resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); - else - resultRects.Add(r); - r = Rect.MinMaxRect(GUTTER_X, line1.y + line1.height, endCharX, line2.y + line2.height); - if (clipped) - resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); - else - resultRects.Add(r); - } - else - { - Rect r = Rect.MinMaxRect(startCharX, line1.y, leftAlign ? (GUTTER_X + line1.width) : _contentRect.xMax, line1.y + line1.height); - if (clipped) - resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); - else - resultRects.Add(r); - for (int i = startLine + 1; i < endLine; i++) - { - LineInfo line = _lines[i]; - r = Rect.MinMaxRect(GUTTER_X, r.yMax, leftAlign ? (GUTTER_X + line.width) : _contentRect.xMax, line.y + line.height); - if (clipped) - resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); - else - resultRects.Add(r); - } - r = Rect.MinMaxRect(GUTTER_X, r.yMax, endCharX, line2.y + line2.height); - if (clipped) - resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); - else - resultRects.Add(r); - } - } - - override protected void OnSizeChanged() - { - if ((_flags & Flags.UpdatingSize) == 0) - { - if (_autoSize == AutoSizeType.Shrink || _autoSize == AutoSizeType.Ellipsis || _wordWrap && (_flags & Flags.WidthChanged) != 0) - _textChanged = true; - else if (_autoSize != AutoSizeType.None) - graphics.SetMeshDirty(); - - if (_verticalAlign != VertAlignType.Top) - ApplyVertAlign(); - } - - base.OnSizeChanged(); - } - - public override void EnsureSizeCorrect() - { - if (_textChanged && _autoSize != AutoSizeType.None) - BuildLines(); - } - - public override void Update(UpdateContext context) - { - if (_richTextField == null) //如果是richTextField,会在update前主动调用了Redraw - Redraw(); - - base.Update(context); - } - - /// - /// 准备字体纹理 - /// - void RequestText() - { - if (!_html) - { - _font.SetFormat(_textFormat, _fontSizeScale); - _font.PrepareCharacters(_parsedText); - if (_autoSize == AutoSizeType.Ellipsis) - _font.PrepareCharacters("…"); - } - else - { - int count = _elements.Count; - for (int i = 0; i < count; i++) - { - HtmlElement element = _elements[i]; - if (element.type == HtmlElementType.Text) - { - _font.SetFormat(element.format, _fontSizeScale); - _font.PrepareCharacters(element.text); - if (_autoSize == AutoSizeType.Ellipsis) - _font.PrepareCharacters("…"); - } - } - } - } - - void BuildLines() - { - if (_font == null) - { - _font = FontManager.GetFont(UIConfig.defaultFont); - _fontVersion = _font.version; - graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); - } - - _textChanged = false; - graphics.SetMeshDirty(); - _renderScale = UIContentScaler.scaleFactor; - _fontSizeScale = 1; - _ellipsisCharIndex = -1; - - Cleanup(); - - if (_text.Length == 0) - { - LineInfo emptyLine = LineInfo.Borrow(); - emptyLine.width = 0; - emptyLine.height = _font.GetLineHeight(_textFormat.size); - emptyLine.charIndex = emptyLine.charCount = 0; - emptyLine.y = emptyLine.y2 = GUTTER_Y; - _lines.Add(emptyLine); - - _textWidth = _textHeight = 0; - } - else - { - ParseText(); - BuildLines2(); - - if (_autoSize == AutoSizeType.Shrink) - DoShrink(); - } - - if (_autoSize == AutoSizeType.Both) - { - _flags |= Flags.UpdatingSize; - if (_richTextField != null) - { - if (_input) - { - float w = Mathf.Max(_textFormat.size, _textWidth); - float h = Mathf.Max(_font.GetLineHeight(_textFormat.size) + GUTTER_Y * 2, _textHeight); - _richTextField.SetSize(w, h); - } - else - _richTextField.SetSize(_textWidth, _textHeight); - } - else - SetSize(_textWidth, _textHeight); - InvalidateBatchingState(); - _flags &= ~Flags.UpdatingSize; - } - else if (_autoSize == AutoSizeType.Height) - { - _flags |= Flags.UpdatingSize; - if (_richTextField != null) - { - if (_input) - _richTextField.height = Mathf.Max(_font.GetLineHeight(_textFormat.size) + GUTTER_Y * 2, _textHeight); - else - _richTextField.height = _textHeight; - } - else - this.height = _textHeight; - InvalidateBatchingState(); - _flags &= ~Flags.UpdatingSize; - } - - _yOffset = 0; - ApplyVertAlign(); - } - - void ParseText() - { -#if RTL_TEXT_SUPPORT - _textDirection = RTLSupport.DetectTextDirection(_text); -#endif - if (_html) - { - HtmlParser.inst.Parse(_text, _textFormat, _elements, - _richTextField != null ? _richTextField.htmlParseOptions : null); - - _parsedText = string.Empty; - } - else - _parsedText = _text; - - int elementCount = _elements.Count; - if (elementCount == 0) - { - if (_textDirection != RTLSupport.DirectionType.UNKNOW) - _parsedText = RTLSupport.DoMapping(_parsedText); - - bool flag = _input || _richTextField != null && _richTextField.emojies != null; - if (!flag) - { - //检查文本中是否有需要转换的字符,如果没有,节省一个new StringBuilder的操作。 - int cnt = _parsedText.Length; - for (int i = 0; i < cnt; i++) - { - char ch = _parsedText[i]; - if (ch == '\r' || char.IsHighSurrogate(ch)) - { - flag = true; - break; - } - } - } - - if (flag) - { - StringBuilder buffer = new StringBuilder(); - ParseText(buffer, _parsedText, -1); - elementCount = _elements.Count; - _parsedText = buffer.ToString(); - } - } - else - { - StringBuilder buffer = new StringBuilder(); - int i = 0; - while (i < elementCount) - { - HtmlElement element = _elements[i]; - element.charIndex = buffer.Length; - if (element.type == HtmlElementType.Text) - { - if (_textDirection != RTLSupport.DirectionType.UNKNOW) - element.text = RTLSupport.DoMapping(element.text); - - i = ParseText(buffer, element.text, i); - elementCount = _elements.Count; - } - else if (element.isEntity) - buffer.Append(' '); - i++; - } - _parsedText = buffer.ToString(); - -#if RTL_TEXT_SUPPORT - // element.text拼接完后再进行一次判断文本主语序,避免html标签存在把文本变成混合文本 [2018/12/12/ 16:47:42 by aq_1000] - _textDirection = RTLSupport.DetectTextDirection(_parsedText); -#endif - } - } - - void BuildLines2() - { - float letterSpacing = _textFormat.letterSpacing * _fontSizeScale; - float lineSpacing = (_textFormat.lineSpacing - 1) * _fontSizeScale; - float rectWidth = _contentRect.width - GUTTER_X * 2; - float rectHeight = _contentRect.height > 0 ? Mathf.Max(_contentRect.height, _font.GetLineHeight(_textFormat.size)) : 0; - float glyphWidth = 0, glyphHeight = 0, baseline = 0; - short wordLen = 0; - bool wordPossible = false; - float posx = 0; - bool checkEdge = _autoSize == AutoSizeType.Ellipsis; - - TextFormat format = _textFormat; - _font.SetFormat(format, _fontSizeScale); - bool wrap = _wordWrap && !_singleLine; - if (_maxWidth > 0) - { - wrap = true; - rectWidth = _maxWidth - GUTTER_X * 2; - } - _textWidth = _textHeight = 0; - - RequestText(); - - int elementCount = _elements.Count; - int elementIndex = 0; - HtmlElement element = null; - if (elementCount > 0) - element = _elements[elementIndex]; - int textLength = _parsedText.Length; - - LineInfo line = LineInfo.Borrow(); - _lines.Add(line); - line.y = line.y2 = GUTTER_Y; - sLineChars.Clear(); - - for (int charIndex = 0; charIndex < textLength; charIndex++) - { - char ch = _parsedText[charIndex]; - - glyphWidth = glyphHeight = baseline = 0; - - while (element != null && element.charIndex == charIndex) - { - if (element.type == HtmlElementType.Text) - { - format = element.format; - _font.SetFormat(format, _fontSizeScale); - } - else - { - IHtmlObject htmlObject = element.htmlObject; - if (_richTextField != null && htmlObject == null) - { - element.space = (int)(rectWidth - line.width - 4); - htmlObject = _richTextField.htmlPageContext.CreateObject(_richTextField, element); - element.htmlObject = htmlObject; - } - if (htmlObject != null) - { - glyphWidth = htmlObject.width + 2; - glyphHeight = htmlObject.height; - baseline = glyphHeight * IMAGE_BASELINE; - } - - if (element.isEntity) - ch = '\0'; //indicate it is a place holder - } - - elementIndex++; - if (elementIndex < elementCount) - element = _elements[elementIndex]; - else - element = null; - } - - if (ch == '\0' || ch == '\n') - { - wordPossible = false; - } - else if (_font.GetGlyph(ch == '\t' ? ' ' : ch, out glyphWidth, out glyphHeight, out baseline)) - { - if (ch == '\t') - glyphWidth *= 4; - - if (wordPossible) - { - if (char.IsWhiteSpace(ch)) - { - wordLen = 0; - } - else if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' - || ch >= '0' && ch <= '9' - || ch == '.' || ch == '"' || ch == '\'' - || format.specialStyle == TextFormat.SpecialStyle.Subscript - || format.specialStyle == TextFormat.SpecialStyle.Superscript - || _textDirection != RTLSupport.DirectionType.UNKNOW && RTLSupport.IsArabicLetter(ch)) - { - wordLen++; - } - else - wordPossible = false; - } - else if (char.IsWhiteSpace(ch)) - { - wordLen = 0; - wordPossible = true; - } - else if (format.specialStyle == TextFormat.SpecialStyle.Subscript - || format.specialStyle == TextFormat.SpecialStyle.Superscript) - { - if (sLineChars.Count > 0) - { - wordLen = 2; //避免上标和下标折到下一行 - wordPossible = true; - } - } - else - wordPossible = false; - } - else - wordPossible = false; - - sLineChars.Add(new LineCharInfo() { width = glyphWidth, height = glyphHeight, baseline = baseline }); - if (glyphWidth != 0) - { - if (posx != 0) - posx += letterSpacing; - posx += glyphWidth; - } - - if (ch == '\n' && !_singleLine) - { - UpdateLineInfo(line, letterSpacing, sLineChars.Count); - - LineInfo newLine = LineInfo.Borrow(); - _lines.Add(newLine); - newLine.y = line.y + (line.height + lineSpacing); - if (newLine.y < GUTTER_Y) //lineSpacing maybe negative - newLine.y = GUTTER_Y; - newLine.y2 = newLine.y; - newLine.charIndex = line.charIndex + line.charCount; - - if (checkEdge && line.y + line.height < rectHeight) - _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); - - sLineChars.Clear(); - wordPossible = false; - posx = 0; - line = newLine; - } - else if (posx > rectWidth) - { - if (wrap) - { - int lineCharCount = sLineChars.Count; - int toMoveChars; - - if (wordPossible && wordLen < 20 && lineCharCount > 2) //if word had broken, move word to new line - { - toMoveChars = wordLen; - //we caculate the line width WITHOUT the tailing space - UpdateLineInfo(line, letterSpacing, lineCharCount - (toMoveChars + 1)); - line.charCount++; //but keep it in this line. - } - else - { - toMoveChars = lineCharCount > 1 ? 1 : 0; //if only one char here, we cant move it to new line - UpdateLineInfo(line, letterSpacing, lineCharCount - toMoveChars); - } - - LineInfo newLine = LineInfo.Borrow(); - _lines.Add(newLine); - newLine.y = line.y + (line.height + lineSpacing); - if (newLine.y < GUTTER_Y) - newLine.y = GUTTER_Y; - newLine.y2 = newLine.y; - newLine.charIndex = line.charIndex + line.charCount; - - posx = 0; - if (toMoveChars != 0) - { - for (int i = line.charCount; i < lineCharCount; i++) - { - LineCharInfo ci = sLineChars[i]; - if (posx != 0) - posx += letterSpacing; - posx += ci.width; - } - - sLineChars.RemoveRange(0, line.charCount); - } - else - sLineChars.Clear(); - - if (checkEdge && line.y + line.height < rectHeight) - _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); - - wordPossible = false; - line = newLine; - } - else if (checkEdge && _ellipsisCharIndex == -1) - _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); - } - } - - UpdateLineInfo(line, letterSpacing, sLineChars.Count); - - if (_textWidth > 0) - _textWidth += GUTTER_X * 2; - _textHeight = line.y + line.height + GUTTER_Y; - - if (checkEdge && _textWidth <= _contentRect.width && _textHeight <= _contentRect.height + GUTTER_Y) - _ellipsisCharIndex = -1; - - _textWidth = Mathf.RoundToInt(_textWidth); - _textHeight = Mathf.RoundToInt(_textHeight); - } - - void UpdateLineInfo(LineInfo line, float letterSpacing, int cnt) - { - for (int i = 0; i < cnt; i++) - { - LineCharInfo ci = sLineChars[i]; - if (ci.baseline > line.baseline) - { - line.height += (ci.baseline - line.baseline); - line.baseline = ci.baseline; - } - - if (ci.height - ci.baseline > line.height - line.baseline) - line.height += (ci.height - ci.baseline - (line.height - line.baseline)); - - if (ci.width > 0) - { - if (line.width != 0) - line.width += letterSpacing; - line.width += ci.width; - } - } - - if (line.height == 0) - { - if (_lines.Count == 1) - line.height = _textFormat.size; - else - line.height = _lines[_lines.Count - 2].height; - } - - if (line.width > _textWidth) - _textWidth = line.width; - - line.charCount = (short)cnt; - } - - void DoShrink() - { - if (_lines.Count > 1 && _textHeight > _contentRect.height) - { - //多行的情况,涉及到自动换行,得用二分法查找最合适的比例,会消耗多一点计算资源 - int low = 0; - int high = _textFormat.size; - - //先尝试猜测一个比例 - _fontSizeScale = Mathf.Sqrt(_contentRect.height / _textHeight); - int cur = Mathf.FloorToInt(_fontSizeScale * _textFormat.size); - - while (true) - { - LineInfo.Return(_lines); - BuildLines2(); - - if (_textWidth > _contentRect.width || _textHeight > _contentRect.height) - high = cur; - else - low = cur; - if (high - low > 1 || high != low && cur == high) - { - cur = low + (high - low) / 2; - _fontSizeScale = (float)cur / _textFormat.size; - } - else - break; - } - } - else if (_textWidth > _contentRect.width) - { - _fontSizeScale = _contentRect.width / _textWidth; - - LineInfo.Return(_lines); - BuildLines2(); - - if (_textWidth > _contentRect.width) //如果还超出,缩小一点再来一次 - { - int size = Mathf.FloorToInt(_textFormat.size * _fontSizeScale); - size--; - _fontSizeScale = (float)size / _textFormat.size; - - LineInfo.Return(_lines); - BuildLines2(); - } - } - } - - int ParseText(StringBuilder buffer, string source, int elementIndex) - { - int textLength = source.Length; - int j = 0; - int appendPos = 0; - bool hasEmojies = _richTextField != null && _richTextField.emojies != null; - while (j < textLength) - { - char ch = source[j]; - if (ch == '\r') - { - buffer.Append(source, appendPos, j - appendPos); - if (j != textLength - 1 && source[j + 1] == '\n') - j++; - appendPos = j + 1; - buffer.Append('\n'); - } - else - { - bool highSurrogate = char.IsHighSurrogate(ch); - if (hasEmojies) - { - uint emojiKey = 0; - Emoji emoji; - if (highSurrogate) - emojiKey = ((uint)source[j + 1] & 0x03FF) + ((((uint)ch & 0x03FF) + 0x40) << 10); - else - emojiKey = ch; - if (_richTextField.emojies.TryGetValue(emojiKey, out emoji)) - { - HtmlElement imageElement = HtmlElement.GetElement(HtmlElementType.Image); - imageElement.Set("src", emoji.url); - if (emoji.width != 0) - imageElement.Set("width", emoji.width); - if (emoji.height != 0) - imageElement.Set("height", emoji.height); - if (highSurrogate) - imageElement.text = source.Substring(j, 2); - else - imageElement.text = source.Substring(j, 1); - imageElement.format.align = _textFormat.align; - _elements.Insert(++elementIndex, imageElement); - - buffer.Append(source, appendPos, j - appendPos); - appendPos = j; - imageElement.charIndex = buffer.Length; - } - } - - if (highSurrogate) - { - buffer.Append(source, appendPos, j - appendPos); - appendPos = j + 2; - j++;//跳过lowSurrogate - buffer.Append(' '); - } - } - j++; - } - if (appendPos < textLength) - buffer.Append(source, appendPos, j - appendPos); - - return elementIndex; - } - - public void OnPopulateMesh(VertexBuffer vb) - { - if (_textWidth == 0 && _lines.Count == 1) - { - if (_charPositions != null) - { - _charPositions.Clear(); - _charPositions.Add(new CharPosition()); - } - - if (_richTextField != null) - _richTextField.RefreshObjects(); - - return; - } - - float letterSpacing = _textFormat.letterSpacing * _fontSizeScale; - TextFormat format = _textFormat; - _font.SetFormat(format, _fontSizeScale); - _font.UpdateGraphics(graphics); - - float rectWidth = _contentRect.width > 0 ? (_contentRect.width - GUTTER_X * 2) : 0; - float rectHeight = _contentRect.height > 0 ? Mathf.Max(_contentRect.height, _font.GetLineHeight(format.size)) : 0; - - if (_charPositions != null) - _charPositions.Clear(); - - List vertList = vb.vertices; - List uvList = vb.uvs; - List uv2List = vb.uvs2; - List colList = vb.colors; - - HtmlLink currentLink = null; - float linkStartX = 0; - int linkStartLine = 0; - - float posx = 0; - float indent_x; - bool clipping = !_input && (_autoSize == AutoSizeType.None || _autoSize == AutoSizeType.Ellipsis); - bool lineClipped; - AlignType lineAlign; - float glyphWidth, glyphHeight, baseline; - short vertCount; - float underlineStart; - float strikethroughStart; - int minFontSize; - int maxFontSize; - string rtlLine = null; - - int elementIndex = 0; - int elementCount = _elements.Count; - HtmlElement element = null; - if (elementCount > 0) - element = _elements[elementIndex]; - - int lineCount = _lines.Count; - for (int i = 0; i < lineCount; ++i) - { - LineInfo line = _lines[i]; - if (line.charCount == 0) - continue; - - lineClipped = clipping && i != 0 && line.y + line.height > rectHeight; - lineAlign = format.align; - if (element != null && element.charIndex == line.charIndex) - lineAlign = element.format.align; - else - lineAlign = format.align; - - if (_textDirection == RTLSupport.DirectionType.RTL) - { - if (lineAlign == AlignType.Center) - indent_x = (int)((rectWidth + line.width) / 2); - else if (lineAlign == AlignType.Right) - indent_x = rectWidth; - else - indent_x = line.width + GUTTER_X * 2; - - if (indent_x > rectWidth) - indent_x = rectWidth; - - posx = indent_x - GUTTER_X; - } - else - { - if (lineAlign == AlignType.Center) - indent_x = (int)((rectWidth - line.width) / 2); - else if (lineAlign == AlignType.Right) - indent_x = rectWidth - line.width; - else - indent_x = 0; - - if (indent_x < 0) - indent_x = 0; - - posx = GUTTER_X + indent_x; - } - - int lineCharCount = line.charCount; - underlineStart = posx; - strikethroughStart = posx; - minFontSize = maxFontSize = format.size; - - if (_textDirection != RTLSupport.DirectionType.UNKNOW) - { - rtlLine = _parsedText.Substring(line.charIndex, lineCharCount); - if (_textDirection == RTLSupport.DirectionType.RTL) - rtlLine = RTLSupport.ConvertLineR(rtlLine); - else - rtlLine = RTLSupport.ConvertLineL(rtlLine); - lineCharCount = rtlLine.Length; - } - - for (int j = 0; j < lineCharCount; j++) - { - int charIndex = line.charIndex + j; - char ch = rtlLine != null ? rtlLine[j] : _parsedText[charIndex]; - bool isEllipsis = charIndex == _ellipsisCharIndex; - - while (element != null && charIndex == element.charIndex) - { - if (element.type == HtmlElementType.Text) - { - vertCount = 0; - if (format.underline != element.format.underline) - { - if (format.underline) - { - if (!lineClipped) - { - float lineWidth; - if (_textDirection == RTLSupport.DirectionType.UNKNOW) - lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - underlineStart; - else - lineWidth = underlineStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); - if (lineWidth > 0) - vertCount += (short)_font.DrawLine(underlineStart < posx ? underlineStart : posx, -(line.y + line.baseline), lineWidth, - maxFontSize, 0, vertList, uvList, uv2List, colList); - } - maxFontSize = 0; - } - else - underlineStart = posx; - } - - if (format.strikethrough != element.format.strikethrough) - { - if (format.strikethrough) - { - if (!lineClipped) - { - float lineWidth; - if (_textDirection == RTLSupport.DirectionType.UNKNOW) - lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - strikethroughStart; - else - lineWidth = strikethroughStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); - if (lineWidth > 0) - vertCount += (short)_font.DrawLine(strikethroughStart < posx ? strikethroughStart : posx, -(line.y + line.baseline), lineWidth, - minFontSize, 1, vertList, uvList, uv2List, colList); - } - minFontSize = int.MaxValue; - } - else - strikethroughStart = posx; - } - - if (vertCount > 0 && _charPositions != null) - { - CharPosition cp = _charPositions[_charPositions.Count - 1]; - cp.vertCount += vertCount; - _charPositions[_charPositions.Count - 1] = cp; - } - - format = element.format; - minFontSize = Math.Min(minFontSize, format.size); - maxFontSize = Math.Max(maxFontSize, format.size); - _font.SetFormat(format, _fontSizeScale); - } - else if (element.type == HtmlElementType.Link) - { - currentLink = (HtmlLink)element.htmlObject; - if (currentLink != null) - { - element.position = Vector2.zero; - currentLink.SetPosition(0, 0); - linkStartX = posx; - linkStartLine = i; - } - } - else if (element.type == HtmlElementType.LinkEnd) - { - if (currentLink != null) - { - currentLink.SetArea(linkStartLine, linkStartX, i, posx); - currentLink = null; - } - } - else - { - IHtmlObject htmlObj = element.htmlObject; - if (htmlObj != null) - { - if (_textDirection == RTLSupport.DirectionType.RTL) - posx -= htmlObj.width - 2; - - if (_charPositions != null) - { - CharPosition cp = new CharPosition(); - cp.lineIndex = (short)i; - cp.charIndex = _charPositions.Count; - cp.imgIndex = (short)(elementIndex + 1); - cp.offsetX = posx; - cp.width = (short)htmlObj.width; - _charPositions.Add(cp); - } - - if (isEllipsis || lineClipped || clipping && (posx < GUTTER_X || posx > GUTTER_X && posx + htmlObj.width > _contentRect.width - GUTTER_X)) - element.status |= 1; - else - element.status &= 254; - - element.position = new Vector2(posx + 1, line.y + line.baseline - htmlObj.height * IMAGE_BASELINE); - htmlObj.SetPosition(element.position.x, element.position.y); - - if (_textDirection == RTLSupport.DirectionType.RTL) - posx -= letterSpacing; - else - posx += htmlObj.width + letterSpacing + 2; - } - } - - if (element.isEntity) - ch = '\0'; - - elementIndex++; - if (elementIndex < elementCount) - element = _elements[elementIndex]; - else - element = null; - } - - if (isEllipsis) - ch = '…'; - else if (ch == '\0') - continue; - - if (_font.GetGlyph(ch == '\t' ? ' ' : ch, out glyphWidth, out glyphHeight, out baseline)) - { - if (ch == '\t') - glyphWidth *= 4; - - if (!isEllipsis) - { - if (_textDirection == RTLSupport.DirectionType.RTL) - { - if (lineClipped || clipping && (rectWidth < 7 || posx != (indent_x - GUTTER_X)) && posx < GUTTER_X - 0.5f) //超出区域,剪裁 - { - posx -= (letterSpacing + glyphWidth); - continue; - } - - posx -= glyphWidth; - } - else - { - if (lineClipped || clipping && (rectWidth < 7 || posx != (GUTTER_X + indent_x)) && posx + glyphWidth > _contentRect.width - GUTTER_X + 0.5f) //超出区域,剪裁 - { - posx += letterSpacing + glyphWidth; - continue; - } - } - } - - vertCount = (short)_font.DrawGlyph(posx, -(line.y + line.baseline), vertList, uvList, uv2List, colList); - - if (_charPositions != null) - { - CharPosition cp = new CharPosition(); - cp.lineIndex = (short)i; - cp.charIndex = _charPositions.Count; - cp.vertCount = vertCount; - cp.offsetX = posx; - cp.width = (short)glyphWidth; - _charPositions.Add(cp); - } - - if (_textDirection == RTLSupport.DirectionType.RTL) - posx -= letterSpacing; - else - posx += letterSpacing + glyphWidth; - } - else //if GetGlyph failed - { - if (_charPositions != null) - { - CharPosition cp = new CharPosition(); - cp.lineIndex = (short)i; - cp.charIndex = _charPositions.Count; - cp.offsetX = posx; - _charPositions.Add(cp); - } - - if (_textDirection == RTLSupport.DirectionType.RTL) - posx -= letterSpacing; - else - posx += letterSpacing; - } - - if (isEllipsis) - lineClipped = true; - }//text loop - - if (!lineClipped) - { - vertCount = 0; - if (format.underline) - { - float lineWidth; - if (_textDirection == RTLSupport.DirectionType.UNKNOW) - lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - underlineStart; - else - lineWidth = underlineStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); - if (lineWidth > 0) - vertCount += (short)_font.DrawLine(underlineStart < posx ? underlineStart : posx, -(line.y + line.baseline), lineWidth, - maxFontSize, 0, vertList, uvList, uv2List, colList); - } - - if (format.strikethrough) - { - float lineWidth; - if (_textDirection == RTLSupport.DirectionType.UNKNOW) - lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - strikethroughStart; - else - lineWidth = strikethroughStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); - if (lineWidth > 0) - vertCount += (short)_font.DrawLine(strikethroughStart < posx ? strikethroughStart : posx, -(line.y + line.baseline), lineWidth, - minFontSize, 1, vertList, uvList, uv2List, colList); - } - - if (vertCount > 0 && _charPositions != null) - { - CharPosition cp = _charPositions[_charPositions.Count - 1]; - cp.vertCount += vertCount; - _charPositions[_charPositions.Count - 1] = cp; - } - } - - }//line loop - - if (element != null && element.type == HtmlElementType.LinkEnd && currentLink != null) - currentLink.SetArea(linkStartLine, linkStartX, lineCount - 1, posx); - - if (_charPositions != null) - { - CharPosition cp = new CharPosition(); - cp.lineIndex = (short)(lineCount - 1); - cp.charIndex = _charPositions.Count; - cp.offsetX = posx; - _charPositions.Add(cp); - } - - int count = vertList.Count; - if (count > 65000) - { - Debug.LogWarning("Text is too large. A mesh may not have more than 65000 vertices."); - vertList.RemoveRange(65000, count - 65000); - colList.RemoveRange(65000, count - 65000); - uvList.RemoveRange(65000, count - 65000); - if (uv2List.Count > 0) - uv2List.RemoveRange(65000, count - 65000); - count = 65000; - } - - if (_font.customOutline) - { - bool hasShadow = _textFormat.shadowOffset.x != 0 || _textFormat.shadowOffset.y != 0; - int allocCount = count; - int drawDirs = 0; - if (_textFormat.outline != 0) - { - drawDirs = UIConfig.enhancedTextOutlineEffect ? 8 : 4; - allocCount += count * drawDirs; - } - if (hasShadow) - allocCount += count; - if (allocCount > 65000) - { - Debug.LogWarning("Text is too large. Outline/shadow effect cannot be completed."); - allocCount = count; - } - - if (allocCount != count) - { - VertexBuffer vb2 = VertexBuffer.Begin(); - List vertList2 = vb2.vertices; - List colList2 = vb2.colors; - - Color32 col = _textFormat.outlineColor; - float outline = _textFormat.outline; - if (outline != 0) - { - for (int j = 0; j < drawDirs; j++) - { - for (int i = 0; i < count; i++) - { - Vector3 vert = vertList[i]; - vertList2.Add(new Vector3(vert.x + STROKE_OFFSET[j * 2] * outline, vert.y + STROKE_OFFSET[j * 2 + 1] * outline, 0)); - colList2.Add(col); - } - - vb2.uvs.AddRange(uvList); - if (uv2List.Count > 0) - vb2.uvs2.AddRange(uv2List); - } - } - - if (hasShadow) - { - col = _textFormat.shadowColor; - Vector2 offset = _textFormat.shadowOffset; - for (int i = 0; i < count; i++) - { - Vector3 vert = vertList[i]; - vertList2.Add(new Vector3(vert.x + offset.x, vert.y - offset.y, 0)); - colList2.Add(col); - } - - vb2.uvs.AddRange(uvList); - if (uv2List.Count > 0) - vb2.uvs2.AddRange(uv2List); - } - - vb.Insert(vb2); - vb2.End(); - } - } - - vb.AddTriangles(); - - if (_richTextField != null) - _richTextField.RefreshObjects(); - } - - void Cleanup() - { - if (_richTextField != null) - _richTextField.CleanupObjects(); - - HtmlElement.ReturnElements(_elements); - LineInfo.Return(_lines); - _textWidth = 0; - _textHeight = 0; - _parsedText = string.Empty; - _textDirection = RTLSupport.DirectionType.UNKNOW; - - if (_charPositions != null) - _charPositions.Clear(); - } - - void ApplyVertAlign() - { - float oldOffset = _yOffset; - if (_autoSize == AutoSizeType.Both || _autoSize == AutoSizeType.Height - || _verticalAlign == VertAlignType.Top) - _yOffset = 0; - else - { - float dh; - if (_textHeight == 0 && _lines.Count > 0) - dh = _contentRect.height - _lines[0].height; - else - dh = _contentRect.height - _textHeight; - if (dh < 0) - dh = 0; - if (_verticalAlign == VertAlignType.Middle) - _yOffset = (int)(dh / 2); - else - _yOffset = dh; - } - - if (oldOffset != _yOffset) - { - int cnt = _lines.Count; - for (int i = 0; i < cnt; i++) - _lines[i].y = _lines[i].y2 + _yOffset; - - graphics.SetMeshDirty(); - } - } - - /// - /// - /// - public class LineInfo - { - /// - /// 行的宽度 - /// - public float width; - - /// - /// 行的高度 - /// - public float height; - - /// - /// 文字渲染基线 - /// - public float baseline; - - /// - /// 行首的字符索引 - /// - public int charIndex; - - /// - /// 行包括的字符个数 - /// - public short charCount; - - /// - /// 行的y轴位置 - /// - public float y; - - /// - /// 行的y轴位置的备份 - /// - internal float y2; - - static Stack pool = new Stack(); - - /// - /// - /// - /// - public static LineInfo Borrow() - { - if (pool.Count > 0) - { - LineInfo ret = pool.Pop(); - ret.width = ret.height = ret.baseline = 0; - ret.y = ret.y2 = 0; - ret.charIndex = ret.charCount = 0; - return ret; - } - else - return new LineInfo(); - } - - /// - /// - /// - /// - public static void Return(LineInfo value) - { - pool.Push(value); - } - - /// - /// - /// - /// - public static void Return(List values) - { - int cnt = values.Count; - for (int i = 0; i < cnt; i++) - pool.Push(values[i]); - - values.Clear(); - } - } - - /// - /// - /// - public struct LineCharInfo - { - public float width; - public float height; - public float baseline; - } - - /// - /// - /// - public struct CharPosition - { - /// - /// 字符索引 - /// - public int charIndex; - - /// - /// 字符所在的行索引 - /// - public short lineIndex; - - /// - /// 字符的x偏移 - /// - public float offsetX; - - /// - /// 字符占用的顶点数量。 - /// - public short vertCount; - - /// - /// 字符的宽度 - /// - public short width; - - /// - /// 大于0表示图片索引。 - /// - public short imgIndex; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class TextField : DisplayObject, IMeshFactory + { + VertAlignType _verticalAlign; + TextFormat _textFormat; + bool _input; + string _text; + AutoSizeType _autoSize; + bool _wordWrap; + bool _singleLine; + bool _html; + RTLSupport.DirectionType _textDirection; + int _maxWidth; + + List _elements; + List _lines; + List _charPositions; + + BaseFont _font; + float _textWidth; + float _textHeight; + bool _textChanged; + float _yOffset; + float _fontSizeScale; + float _renderScale; + int _fontVersion; + string _parsedText; + int _ellipsisCharIndex; + + RichTextField _richTextField; + + const int GUTTER_X = 2; + const int GUTTER_Y = 2; + const float IMAGE_BASELINE = 0.8f; + const int ELLIPSIS_LENGTH = 2; + static float[] STROKE_OFFSET = new float[] + { + -1, 0, 1, 0, + 0, -1, 0, 1, + -1, -1, 1, -1, + -1, 1, 1, 1 + }; + static List sLineChars = new List(); + + public TextField() + { + _flags |= Flags.TouchDisabled; + + _textFormat = new TextFormat(); + _fontSizeScale = 1; + _renderScale = UIContentScaler.scaleFactor; + + _wordWrap = false; + _text = string.Empty; + _parsedText = string.Empty; + + _elements = new List(0); + _lines = new List(1); + + CreateGameObject("TextField"); + graphics = new NGraphics(gameObject); + graphics.meshFactory = this; + } + + internal void EnableRichSupport(RichTextField richTextField) + { + _richTextField = richTextField; + if (richTextField is InputTextField) + { + _input = true; + EnableCharPositionSupport(); + } + } + + public void EnableCharPositionSupport() + { + if (_charPositions == null) + { + _charPositions = new List(); + _textChanged = true; + } + } + + /// + /// + /// + public TextFormat textFormat + { + get { return _textFormat; } + set + { + _textFormat = value; + ApplyFormat(); + } + } + + /// + /// + /// + public void ApplyFormat() + { + string fontName = _textFormat.font; + if (string.IsNullOrEmpty(fontName)) + fontName = UIConfig.defaultFont; + BaseFont newFont = FontManager.GetFont(fontName); + if (_font != newFont) + { + _font = newFont; + _fontVersion = _font.version; + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + } + + if (!string.IsNullOrEmpty(_text)) + _textChanged = true; + } + + /// + /// + /// + public AlignType align + { + get { return _textFormat.align; } + set + { + if (_textFormat.align != value) + { + _textFormat.align = value; + if (!string.IsNullOrEmpty(_text)) + _textChanged = true; + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get + { + return _verticalAlign; + } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + if (!_textChanged) + ApplyVertAlign(); + } + } + } + + /// + /// + /// + public string text + { + get { return _text; } + set + { + if (_text == value && !_html) + return; + + _text = value; + _textChanged = true; + _html = false; + } + } + + /// + /// + /// + public string htmlText + { + get { return _text; } + set + { + if (_text == value && _html) + return; + + _text = value; + _textChanged = true; + _html = true; + } + } + + public string parsedText + { + get { return _parsedText; } + } + + /// + /// + /// + public AutoSizeType autoSize + { + get { return _autoSize; } + set + { + if (_autoSize != value) + { + _autoSize = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public bool wordWrap + { + get { return _wordWrap; } + set + { + if (_wordWrap != value) + { + _wordWrap = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public bool singleLine + { + get { return _singleLine; } + set + { + if (_singleLine != value) + { + _singleLine = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public float stroke + { + get + { + return _textFormat.outline; + } + set + { + if (_textFormat.outline != value) + { + _textFormat.outline = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public Color strokeColor + { + get + { + return _textFormat.outlineColor; + } + set + { + if (_textFormat.outlineColor != value) + { + _textFormat.outlineColor = value; + graphics.SetMeshDirty(); + } + } + } + + /// + /// + /// + public Vector2 shadowOffset + { + get + { + return _textFormat.shadowOffset; + } + set + { + _textFormat.shadowOffset = value; + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + public float textWidth + { + get + { + if (_textChanged) + BuildLines(); + + return _textWidth; + } + } + + /// + /// + /// + public float textHeight + { + get + { + if (_textChanged) + BuildLines(); + + return _textHeight; + } + } + + /// + /// + /// + public int maxWidth + { + get { return _maxWidth; } + set + { + if (_maxWidth != value) + { + _maxWidth = value; + _textChanged = true; + } + } + } + + /// + /// + /// + public List htmlElements + { + get + { + if (_textChanged) + BuildLines(); + + return _elements; + } + } + + /// + /// + /// + public List lines + { + get + { + if (_textChanged) + BuildLines(); + + return _lines; + } + } + + /// + /// + /// + public List charPositions + { + get + { + if (_textChanged) + BuildLines(); + + graphics.UpdateMesh(); + + return _charPositions; + } + } + + /// + /// + /// + public RichTextField richTextField + { + get { return _richTextField; } + } + + /// + /// + /// + public bool Redraw() + { + if (_font == null) + { + _font = FontManager.GetFont(UIConfig.defaultFont); + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + _fontVersion = _font.version; + _textChanged = true; + } + + if (_font.keepCrisp && _renderScale != UIContentScaler.scaleFactor) + _textChanged = true; + + if (_font.version != _fontVersion) + { + _fontVersion = _font.version; + if (_font.mainTexture != graphics.texture) + { + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + InvalidateBatchingState(); + } + + _textChanged = true; + } + + if (_textChanged) + BuildLines(); + + return graphics.UpdateMesh(); + } + + /// + /// + /// + public bool HasCharacter(char ch) + { + return _font.HasCharacter(ch); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void GetLinesShape(int startLine, float startCharX, int endLine, float endCharX, + bool clipped, + List resultRects) + { + LineInfo line1 = _lines[startLine]; + LineInfo line2 = _lines[endLine]; + bool leftAlign = _textFormat.align == AlignType.Left; + if (startLine == endLine) + { + Rect r = Rect.MinMaxRect(startCharX, line1.y, endCharX, line1.y + line1.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + else if (startLine == endLine - 1) + { + Rect r = Rect.MinMaxRect(startCharX, line1.y, leftAlign ? (GUTTER_X + line1.width) : _contentRect.xMax, line1.y + line1.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + r = Rect.MinMaxRect(GUTTER_X, line1.y + line1.height, endCharX, line2.y + line2.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + else + { + Rect r = Rect.MinMaxRect(startCharX, line1.y, leftAlign ? (GUTTER_X + line1.width) : _contentRect.xMax, line1.y + line1.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + for (int i = startLine + 1; i < endLine; i++) + { + LineInfo line = _lines[i]; + r = Rect.MinMaxRect(GUTTER_X, r.yMax, leftAlign ? (GUTTER_X + line.width) : _contentRect.xMax, line.y + line.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + r = Rect.MinMaxRect(GUTTER_X, r.yMax, endCharX, line2.y + line2.height); + if (clipped) + resultRects.Add(ToolSet.Intersection(ref r, ref _contentRect)); + else + resultRects.Add(r); + } + } + + override protected void OnSizeChanged() + { + if ((_flags & Flags.UpdatingSize) == 0) + { + if (_autoSize == AutoSizeType.Shrink || _autoSize == AutoSizeType.Ellipsis || _wordWrap && (_flags & Flags.WidthChanged) != 0) + _textChanged = true; + else if (_autoSize != AutoSizeType.None) + graphics.SetMeshDirty(); + + if (_verticalAlign != VertAlignType.Top) + ApplyVertAlign(); + } + + base.OnSizeChanged(); + } + + public override void EnsureSizeCorrect() + { + if (_textChanged && _autoSize != AutoSizeType.None) + BuildLines(); + } + + public override void Update(UpdateContext context) + { + if (_richTextField == null) //如果是richTextField,会在update前主动调用了Redraw + Redraw(); + + base.Update(context); + } + + /// + /// 准备字体纹理 + /// + void RequestText() + { + if (!_html) + { + _font.SetFormat(_textFormat, _fontSizeScale); + _font.PrepareCharacters(_parsedText); + if (_autoSize == AutoSizeType.Ellipsis) + _font.PrepareCharacters("…"); + } + else + { + int count = _elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = _elements[i]; + if (element.type == HtmlElementType.Text) + { + _font.SetFormat(element.format, _fontSizeScale); + _font.PrepareCharacters(element.text); + if (_autoSize == AutoSizeType.Ellipsis) + _font.PrepareCharacters("…"); + } + } + } + } + + void BuildLines() + { + if (_font == null) + { + _font = FontManager.GetFont(UIConfig.defaultFont); + _fontVersion = _font.version; + graphics.SetShaderAndTexture(_font.shader, _font.mainTexture); + } + + _textChanged = false; + graphics.SetMeshDirty(); + _renderScale = UIContentScaler.scaleFactor; + _fontSizeScale = 1; + _ellipsisCharIndex = -1; + + Cleanup(); + + if (_text.Length == 0) + { + LineInfo emptyLine = LineInfo.Borrow(); + emptyLine.width = 0; + emptyLine.height = _font.GetLineHeight(_textFormat.size); + emptyLine.charIndex = emptyLine.charCount = 0; + emptyLine.y = emptyLine.y2 = GUTTER_Y; + _lines.Add(emptyLine); + + _textWidth = _textHeight = 0; + } + else + { + ParseText(); + BuildLines2(); + + if (_autoSize == AutoSizeType.Shrink) + DoShrink(); + } + + if (_autoSize == AutoSizeType.Both) + { + _flags |= Flags.UpdatingSize; + if (_richTextField != null) + { + if (_input) + { + float w = Mathf.Max(_textFormat.size, _textWidth); + float h = Mathf.Max(_font.GetLineHeight(_textFormat.size) + GUTTER_Y * 2, _textHeight); + _richTextField.SetSize(w, h); + } + else + _richTextField.SetSize(_textWidth, _textHeight); + } + else + SetSize(_textWidth, _textHeight); + InvalidateBatchingState(); + _flags &= ~Flags.UpdatingSize; + } + else if (_autoSize == AutoSizeType.Height) + { + _flags |= Flags.UpdatingSize; + if (_richTextField != null) + { + if (_input) + _richTextField.height = Mathf.Max(_font.GetLineHeight(_textFormat.size) + GUTTER_Y * 2, _textHeight); + else + _richTextField.height = _textHeight; + } + else + this.height = _textHeight; + InvalidateBatchingState(); + _flags &= ~Flags.UpdatingSize; + } + + _yOffset = 0; + ApplyVertAlign(); + } + + void ParseText() + { +#if RTL_TEXT_SUPPORT + _textDirection = RTLSupport.DetectTextDirection(_text); +#endif + if (_html) + { + HtmlParser.inst.Parse(_text, _textFormat, _elements, + _richTextField != null ? _richTextField.htmlParseOptions : null); + + _parsedText = string.Empty; + } + else + _parsedText = _text; + + int elementCount = _elements.Count; + if (elementCount == 0) + { + if (_textDirection != RTLSupport.DirectionType.UNKNOW) + _parsedText = RTLSupport.DoMapping(_parsedText); + + bool flag = _input || _richTextField != null && _richTextField.emojies != null; + if (!flag) + { + //检查文本中是否有需要转换的字符,如果没有,节省一个new StringBuilder的操作。 + int cnt = _parsedText.Length; + for (int i = 0; i < cnt; i++) + { + char ch = _parsedText[i]; + if (ch == '\r' || char.IsHighSurrogate(ch)) + { + flag = true; + break; + } + } + } + + if (flag) + { + StringBuilder buffer = new StringBuilder(); + ParseText(buffer, _parsedText, -1); + elementCount = _elements.Count; + _parsedText = buffer.ToString(); + } + } + else + { + StringBuilder buffer = new StringBuilder(); + int i = 0; + while (i < elementCount) + { + HtmlElement element = _elements[i]; + element.charIndex = buffer.Length; + if (element.type == HtmlElementType.Text) + { + if (_textDirection != RTLSupport.DirectionType.UNKNOW) + element.text = RTLSupport.DoMapping(element.text); + + i = ParseText(buffer, element.text, i); + elementCount = _elements.Count; + } + else if (element.isEntity) + buffer.Append(' '); + i++; + } + _parsedText = buffer.ToString(); + +#if RTL_TEXT_SUPPORT + // element.text拼接完后再进行一次判断文本主语序,避免html标签存在把文本变成混合文本 [2018/12/12/ 16:47:42 by aq_1000] + _textDirection = RTLSupport.DetectTextDirection(_parsedText); +#endif + } + } + + void BuildLines2() + { + float letterSpacing = _textFormat.letterSpacing * _fontSizeScale; + float lineSpacing = (_textFormat.lineSpacing - 1) * _fontSizeScale; + float rectWidth = _contentRect.width - GUTTER_X * 2; + float rectHeight = _contentRect.height > 0 ? Mathf.Max(_contentRect.height, _font.GetLineHeight(_textFormat.size)) : 0; + float glyphWidth = 0, glyphHeight = 0, baseline = 0; + short wordLen = 0; + bool wordPossible = false; + float posx = 0; + bool checkEdge = _autoSize == AutoSizeType.Ellipsis; + + TextFormat format = _textFormat; + _font.SetFormat(format, _fontSizeScale); + bool wrap = _wordWrap && !_singleLine; + if (_maxWidth > 0) + { + wrap = true; + rectWidth = _maxWidth - GUTTER_X * 2; + } + _textWidth = _textHeight = 0; + + RequestText(); + + int elementCount = _elements.Count; + int elementIndex = 0; + HtmlElement element = null; + if (elementCount > 0) + element = _elements[elementIndex]; + int textLength = _parsedText.Length; + + LineInfo line = LineInfo.Borrow(); + _lines.Add(line); + line.y = line.y2 = GUTTER_Y; + sLineChars.Clear(); + + for (int charIndex = 0; charIndex < textLength; charIndex++) + { + char ch = _parsedText[charIndex]; + + glyphWidth = glyphHeight = baseline = 0; + + while (element != null && element.charIndex == charIndex) + { + if (element.type == HtmlElementType.Text) + { + format = element.format; + _font.SetFormat(format, _fontSizeScale); + } + else + { + IHtmlObject htmlObject = element.htmlObject; + if (_richTextField != null && htmlObject == null) + { + element.space = (int)(rectWidth - line.width - 4); + htmlObject = _richTextField.htmlPageContext.CreateObject(_richTextField, element); + element.htmlObject = htmlObject; + } + if (htmlObject != null) + { + glyphWidth = htmlObject.width + 2; + glyphHeight = htmlObject.height; + baseline = glyphHeight * IMAGE_BASELINE; + } + + if (element.isEntity) + ch = '\0'; //indicate it is a place holder + } + + elementIndex++; + if (elementIndex < elementCount) + element = _elements[elementIndex]; + else + element = null; + } + + if (ch == '\0' || ch == '\n') + { + wordPossible = false; + } + else if (_font.GetGlyph(ch == '\t' ? ' ' : ch, out glyphWidth, out glyphHeight, out baseline)) + { + if (ch == '\t') + glyphWidth *= 4; + + if (wordPossible) + { + if (char.IsWhiteSpace(ch)) + { + wordLen = 0; + } + else if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' + || ch >= '0' && ch <= '9' + || ch == '.' || ch == '"' || ch == '\'' + || format.specialStyle == TextFormat.SpecialStyle.Subscript + || format.specialStyle == TextFormat.SpecialStyle.Superscript + || _textDirection != RTLSupport.DirectionType.UNKNOW && RTLSupport.IsArabicLetter(ch)) + { + wordLen++; + } + else + wordPossible = false; + } + else if (char.IsWhiteSpace(ch)) + { + wordLen = 0; + wordPossible = true; + } + else if (format.specialStyle == TextFormat.SpecialStyle.Subscript + || format.specialStyle == TextFormat.SpecialStyle.Superscript) + { + if (sLineChars.Count > 0) + { + wordLen = 2; //避免上标和下标折到下一行 + wordPossible = true; + } + } + else + wordPossible = false; + } + else + wordPossible = false; + + sLineChars.Add(new LineCharInfo() { width = glyphWidth, height = glyphHeight, baseline = baseline }); + if (glyphWidth != 0) + { + if (posx != 0) + posx += letterSpacing; + posx += glyphWidth; + } + + if (ch == '\n' && !_singleLine) + { + UpdateLineInfo(line, letterSpacing, sLineChars.Count); + + LineInfo newLine = LineInfo.Borrow(); + _lines.Add(newLine); + newLine.y = line.y + (line.height + lineSpacing); + if (newLine.y < GUTTER_Y) //lineSpacing maybe negative + newLine.y = GUTTER_Y; + newLine.y2 = newLine.y; + newLine.charIndex = line.charIndex + line.charCount; + + if (checkEdge && line.y + line.height < rectHeight) + _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); + + sLineChars.Clear(); + wordPossible = false; + posx = 0; + line = newLine; + } + else if (posx > rectWidth) + { + if (wrap) + { + int lineCharCount = sLineChars.Count; + int toMoveChars; + + if (wordPossible && wordLen < 20 && lineCharCount > 2) //if word had broken, move word to new line + { + toMoveChars = wordLen; + //we caculate the line width WITHOUT the tailing space + UpdateLineInfo(line, letterSpacing, lineCharCount - (toMoveChars + 1)); + line.charCount++; //but keep it in this line. + } + else + { + toMoveChars = lineCharCount > 1 ? 1 : 0; //if only one char here, we cant move it to new line + UpdateLineInfo(line, letterSpacing, lineCharCount - toMoveChars); + } + + LineInfo newLine = LineInfo.Borrow(); + _lines.Add(newLine); + newLine.y = line.y + (line.height + lineSpacing); + if (newLine.y < GUTTER_Y) + newLine.y = GUTTER_Y; + newLine.y2 = newLine.y; + newLine.charIndex = line.charIndex + line.charCount; + + posx = 0; + if (toMoveChars != 0) + { + for (int i = line.charCount; i < lineCharCount; i++) + { + LineCharInfo ci = sLineChars[i]; + if (posx != 0) + posx += letterSpacing; + posx += ci.width; + } + + sLineChars.RemoveRange(0, line.charCount); + } + else + sLineChars.Clear(); + + if (checkEdge && line.y + line.height < rectHeight) + _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); + + wordPossible = false; + line = newLine; + } + else if (checkEdge && _ellipsisCharIndex == -1) + _ellipsisCharIndex = line.charIndex + Math.Max(0, line.charCount - ELLIPSIS_LENGTH); + } + } + + UpdateLineInfo(line, letterSpacing, sLineChars.Count); + + if (_textWidth > 0) + _textWidth += GUTTER_X * 2; + _textHeight = line.y + line.height + GUTTER_Y; + + if (checkEdge && _textWidth <= _contentRect.width && _textHeight <= _contentRect.height + GUTTER_Y) + _ellipsisCharIndex = -1; + + _textWidth = Mathf.RoundToInt(_textWidth); + _textHeight = Mathf.RoundToInt(_textHeight); + } + + void UpdateLineInfo(LineInfo line, float letterSpacing, int cnt) + { + for (int i = 0; i < cnt; i++) + { + LineCharInfo ci = sLineChars[i]; + if (ci.baseline > line.baseline) + { + line.height += (ci.baseline - line.baseline); + line.baseline = ci.baseline; + } + + if (ci.height - ci.baseline > line.height - line.baseline) + line.height += (ci.height - ci.baseline - (line.height - line.baseline)); + + if (ci.width > 0) + { + if (line.width != 0) + line.width += letterSpacing; + line.width += ci.width; + } + } + + if (line.height == 0) + { + if (_lines.Count == 1) + line.height = _textFormat.size; + else + line.height = _lines[_lines.Count - 2].height; + } + + if (line.width > _textWidth) + _textWidth = line.width; + + line.charCount = (short)cnt; + } + + void DoShrink() + { + if (_lines.Count > 1 && _textHeight > _contentRect.height) + { + //多行的情况,涉及到自动换行,得用二分法查找最合适的比例,会消耗多一点计算资源 + int low = 0; + int high = _textFormat.size; + + //先尝试猜测一个比例 + _fontSizeScale = Mathf.Sqrt(_contentRect.height / _textHeight); + int cur = Mathf.FloorToInt(_fontSizeScale * _textFormat.size); + + while (true) + { + LineInfo.Return(_lines); + BuildLines2(); + + if (_textWidth > _contentRect.width || _textHeight > _contentRect.height) + high = cur; + else + low = cur; + if (high - low > 1 || high != low && cur == high) + { + cur = low + (high - low) / 2; + _fontSizeScale = (float)cur / _textFormat.size; + } + else + break; + } + } + else if (_textWidth > _contentRect.width) + { + _fontSizeScale = _contentRect.width / _textWidth; + + LineInfo.Return(_lines); + BuildLines2(); + + if (_textWidth > _contentRect.width) //如果还超出,缩小一点再来一次 + { + int size = Mathf.FloorToInt(_textFormat.size * _fontSizeScale); + size--; + _fontSizeScale = (float)size / _textFormat.size; + + LineInfo.Return(_lines); + BuildLines2(); + } + } + } + + int ParseText(StringBuilder buffer, string source, int elementIndex) + { + int textLength = source.Length; + int j = 0; + int appendPos = 0; + bool hasEmojies = _richTextField != null && _richTextField.emojies != null; + while (j < textLength) + { + char ch = source[j]; + if (ch == '\r') + { + buffer.Append(source, appendPos, j - appendPos); + if (j != textLength - 1 && source[j + 1] == '\n') + j++; + appendPos = j + 1; + buffer.Append('\n'); + } + else + { + bool highSurrogate = char.IsHighSurrogate(ch); + if (hasEmojies) + { + uint emojiKey = 0; + Emoji emoji; + if (highSurrogate) + emojiKey = ((uint)source[j + 1] & 0x03FF) + ((((uint)ch & 0x03FF) + 0x40) << 10); + else + emojiKey = ch; + if (_richTextField.emojies.TryGetValue(emojiKey, out emoji)) + { + HtmlElement imageElement = HtmlElement.GetElement(HtmlElementType.Image); + imageElement.Set("src", emoji.url); + if (emoji.width != 0) + imageElement.Set("width", emoji.width); + if (emoji.height != 0) + imageElement.Set("height", emoji.height); + if (highSurrogate) + imageElement.text = source.Substring(j, 2); + else + imageElement.text = source.Substring(j, 1); + imageElement.format.align = _textFormat.align; + _elements.Insert(++elementIndex, imageElement); + + buffer.Append(source, appendPos, j - appendPos); + appendPos = j; + imageElement.charIndex = buffer.Length; + } + } + + if (highSurrogate) + { + buffer.Append(source, appendPos, j - appendPos); + appendPos = j + 2; + j++;//跳过lowSurrogate + buffer.Append(' '); + } + } + j++; + } + if (appendPos < textLength) + buffer.Append(source, appendPos, j - appendPos); + + return elementIndex; + } + + public void OnPopulateMesh(VertexBuffer vb) + { + if (_textWidth == 0 && _lines.Count == 1) + { + if (_charPositions != null) + { + _charPositions.Clear(); + _charPositions.Add(new CharPosition()); + } + + if (_richTextField != null) + _richTextField.RefreshObjects(); + + return; + } + + float letterSpacing = _textFormat.letterSpacing * _fontSizeScale; + TextFormat format = _textFormat; + _font.SetFormat(format, _fontSizeScale); + _font.UpdateGraphics(graphics); + + float rectWidth = _contentRect.width > 0 ? (_contentRect.width - GUTTER_X * 2) : 0; + float rectHeight = _contentRect.height > 0 ? Mathf.Max(_contentRect.height, _font.GetLineHeight(format.size)) : 0; + + if (_charPositions != null) + _charPositions.Clear(); + + List vertList = vb.vertices; + List uvList = vb.uvs; + List uv2List = vb.uvs2; + List colList = vb.colors; + + HtmlLink currentLink = null; + float linkStartX = 0; + int linkStartLine = 0; + + float posx = 0; + float indent_x; + bool clipping = !_input && (_autoSize == AutoSizeType.None || _autoSize == AutoSizeType.Ellipsis); + bool lineClipped; + AlignType lineAlign; + float glyphWidth, glyphHeight, baseline; + short vertCount; + float underlineStart; + float strikethroughStart; + int minFontSize; + int maxFontSize; + string rtlLine = null; + + int elementIndex = 0; + int elementCount = _elements.Count; + HtmlElement element = null; + if (elementCount > 0) + element = _elements[elementIndex]; + + int lineCount = _lines.Count; + for (int i = 0; i < lineCount; ++i) + { + LineInfo line = _lines[i]; + if (line.charCount == 0) + continue; + + lineClipped = clipping && i != 0 && line.y + line.height > rectHeight; + lineAlign = format.align; + if (element != null && element.charIndex == line.charIndex) + lineAlign = element.format.align; + else + lineAlign = format.align; + + if (_textDirection == RTLSupport.DirectionType.RTL) + { + if (lineAlign == AlignType.Center) + indent_x = (int)((rectWidth + line.width) / 2); + else if (lineAlign == AlignType.Right) + indent_x = rectWidth; + else + indent_x = line.width + GUTTER_X * 2; + + if (indent_x > rectWidth) + indent_x = rectWidth; + + posx = indent_x - GUTTER_X; + } + else + { + if (lineAlign == AlignType.Center) + indent_x = (int)((rectWidth - line.width) / 2); + else if (lineAlign == AlignType.Right) + indent_x = rectWidth - line.width; + else + indent_x = 0; + + if (indent_x < 0) + indent_x = 0; + + posx = GUTTER_X + indent_x; + } + + int lineCharCount = line.charCount; + underlineStart = posx; + strikethroughStart = posx; + minFontSize = maxFontSize = format.size; + + if (_textDirection != RTLSupport.DirectionType.UNKNOW) + { + rtlLine = _parsedText.Substring(line.charIndex, lineCharCount); + if (_textDirection == RTLSupport.DirectionType.RTL) + rtlLine = RTLSupport.ConvertLineR(rtlLine); + else + rtlLine = RTLSupport.ConvertLineL(rtlLine); + lineCharCount = rtlLine.Length; + } + + for (int j = 0; j < lineCharCount; j++) + { + int charIndex = line.charIndex + j; + char ch = rtlLine != null ? rtlLine[j] : _parsedText[charIndex]; + bool isEllipsis = charIndex == _ellipsisCharIndex; + + while (element != null && charIndex == element.charIndex) + { + if (element.type == HtmlElementType.Text) + { + vertCount = 0; + if (format.underline != element.format.underline) + { + if (format.underline) + { + if (!lineClipped) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - underlineStart; + else + lineWidth = underlineStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine(underlineStart < posx ? underlineStart : posx, -(line.y + line.baseline), lineWidth, + maxFontSize, 0, vertList, uvList, uv2List, colList); + } + maxFontSize = 0; + } + else + underlineStart = posx; + } + + if (format.strikethrough != element.format.strikethrough) + { + if (format.strikethrough) + { + if (!lineClipped) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - strikethroughStart; + else + lineWidth = strikethroughStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine(strikethroughStart < posx ? strikethroughStart : posx, -(line.y + line.baseline), lineWidth, + minFontSize, 1, vertList, uvList, uv2List, colList); + } + minFontSize = int.MaxValue; + } + else + strikethroughStart = posx; + } + + if (vertCount > 0 && _charPositions != null) + { + CharPosition cp = _charPositions[_charPositions.Count - 1]; + cp.vertCount += vertCount; + _charPositions[_charPositions.Count - 1] = cp; + } + + format = element.format; + minFontSize = Math.Min(minFontSize, format.size); + maxFontSize = Math.Max(maxFontSize, format.size); + _font.SetFormat(format, _fontSizeScale); + } + else if (element.type == HtmlElementType.Link) + { + currentLink = (HtmlLink)element.htmlObject; + if (currentLink != null) + { + element.position = Vector2.zero; + currentLink.SetPosition(0, 0); + linkStartX = posx; + linkStartLine = i; + } + } + else if (element.type == HtmlElementType.LinkEnd) + { + if (currentLink != null) + { + currentLink.SetArea(linkStartLine, linkStartX, i, posx); + currentLink = null; + } + } + else + { + IHtmlObject htmlObj = element.htmlObject; + if (htmlObj != null) + { + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= htmlObj.width - 2; + + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)i; + cp.charIndex = _charPositions.Count; + cp.imgIndex = (short)(elementIndex + 1); + cp.offsetX = posx; + cp.width = (short)htmlObj.width; + _charPositions.Add(cp); + } + + if (isEllipsis || lineClipped || clipping && (posx < GUTTER_X || posx > GUTTER_X && posx + htmlObj.width > _contentRect.width - GUTTER_X)) + element.status |= 1; + else + element.status &= 254; + + element.position = new Vector2(posx + 1, line.y + line.baseline - htmlObj.height * IMAGE_BASELINE); + htmlObj.SetPosition(element.position.x, element.position.y); + + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= letterSpacing; + else + posx += htmlObj.width + letterSpacing + 2; + } + } + + if (element.isEntity) + ch = '\0'; + + elementIndex++; + if (elementIndex < elementCount) + element = _elements[elementIndex]; + else + element = null; + } + + if (isEllipsis) + ch = '…'; + else if (ch == '\0') + continue; + + if (_font.GetGlyph(ch == '\t' ? ' ' : ch, out glyphWidth, out glyphHeight, out baseline)) + { + if (ch == '\t') + glyphWidth *= 4; + + if (!isEllipsis) + { + if (_textDirection == RTLSupport.DirectionType.RTL) + { + if (lineClipped || clipping && (rectWidth < 7 || posx != (indent_x - GUTTER_X)) && posx < GUTTER_X - 0.5f) //超出区域,剪裁 + { + posx -= (letterSpacing + glyphWidth); + continue; + } + + posx -= glyphWidth; + } + else + { + if (lineClipped || clipping && (rectWidth < 7 || posx != (GUTTER_X + indent_x)) && posx + glyphWidth > _contentRect.width - GUTTER_X + 0.5f) //超出区域,剪裁 + { + posx += letterSpacing + glyphWidth; + continue; + } + } + } + + vertCount = (short)_font.DrawGlyph(posx, -(line.y + line.baseline), vertList, uvList, uv2List, colList); + + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)i; + cp.charIndex = _charPositions.Count; + cp.vertCount = vertCount; + cp.offsetX = posx; + cp.width = (short)glyphWidth; + _charPositions.Add(cp); + } + + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= letterSpacing; + else + posx += letterSpacing + glyphWidth; + } + else //if GetGlyph failed + { + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)i; + cp.charIndex = _charPositions.Count; + cp.offsetX = posx; + _charPositions.Add(cp); + } + + if (_textDirection == RTLSupport.DirectionType.RTL) + posx -= letterSpacing; + else + posx += letterSpacing; + } + + if (isEllipsis) + lineClipped = true; + }//text loop + + if (!lineClipped) + { + vertCount = 0; + if (format.underline) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - underlineStart; + else + lineWidth = underlineStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine(underlineStart < posx ? underlineStart : posx, -(line.y + line.baseline), lineWidth, + maxFontSize, 0, vertList, uvList, uv2List, colList); + } + + if (format.strikethrough) + { + float lineWidth; + if (_textDirection == RTLSupport.DirectionType.UNKNOW) + lineWidth = (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx) - strikethroughStart; + else + lineWidth = strikethroughStart - (clipping ? Mathf.Clamp(posx, GUTTER_X, GUTTER_X + rectWidth) : posx); + if (lineWidth > 0) + vertCount += (short)_font.DrawLine(strikethroughStart < posx ? strikethroughStart : posx, -(line.y + line.baseline), lineWidth, + minFontSize, 1, vertList, uvList, uv2List, colList); + } + + if (vertCount > 0 && _charPositions != null) + { + CharPosition cp = _charPositions[_charPositions.Count - 1]; + cp.vertCount += vertCount; + _charPositions[_charPositions.Count - 1] = cp; + } + } + + }//line loop + + if (element != null && element.type == HtmlElementType.LinkEnd && currentLink != null) + currentLink.SetArea(linkStartLine, linkStartX, lineCount - 1, posx); + + if (_charPositions != null) + { + CharPosition cp = new CharPosition(); + cp.lineIndex = (short)(lineCount - 1); + cp.charIndex = _charPositions.Count; + cp.offsetX = posx; + _charPositions.Add(cp); + } + + int count = vertList.Count; + if (count > 65000) + { + Debug.LogWarning("Text is too large. A mesh may not have more than 65000 vertices."); + vertList.RemoveRange(65000, count - 65000); + colList.RemoveRange(65000, count - 65000); + uvList.RemoveRange(65000, count - 65000); + if (uv2List.Count > 0) + uv2List.RemoveRange(65000, count - 65000); + count = 65000; + } + + if (_font.customOutline) + { + bool hasShadow = _textFormat.shadowOffset.x != 0 || _textFormat.shadowOffset.y != 0; + int allocCount = count; + int drawDirs = 0; + if (_textFormat.outline != 0) + { + drawDirs = UIConfig.enhancedTextOutlineEffect ? 8 : 4; + allocCount += count * drawDirs; + } + if (hasShadow) + allocCount += count; + if (allocCount > 65000) + { + Debug.LogWarning("Text is too large. Outline/shadow effect cannot be completed."); + allocCount = count; + } + + if (allocCount != count) + { + VertexBuffer vb2 = VertexBuffer.Begin(); + List vertList2 = vb2.vertices; + List colList2 = vb2.colors; + + Color32 col = _textFormat.outlineColor; + float outline = _textFormat.outline; + if (outline != 0) + { + for (int j = 0; j < drawDirs; j++) + { + for (int i = 0; i < count; i++) + { + Vector3 vert = vertList[i]; + vertList2.Add(new Vector3(vert.x + STROKE_OFFSET[j * 2] * outline, vert.y + STROKE_OFFSET[j * 2 + 1] * outline, 0)); + colList2.Add(col); + } + + vb2.uvs.AddRange(uvList); + if (uv2List.Count > 0) + vb2.uvs2.AddRange(uv2List); + } + } + + if (hasShadow) + { + col = _textFormat.shadowColor; + Vector2 offset = _textFormat.shadowOffset; + for (int i = 0; i < count; i++) + { + Vector3 vert = vertList[i]; + vertList2.Add(new Vector3(vert.x + offset.x, vert.y - offset.y, 0)); + colList2.Add(col); + } + + vb2.uvs.AddRange(uvList); + if (uv2List.Count > 0) + vb2.uvs2.AddRange(uv2List); + } + + vb.Insert(vb2); + vb2.End(); + } + } + + vb.AddTriangles(); + + if (_richTextField != null) + _richTextField.RefreshObjects(); + } + + void Cleanup() + { + if (_richTextField != null) + _richTextField.CleanupObjects(); + + HtmlElement.ReturnElements(_elements); + LineInfo.Return(_lines); + _textWidth = 0; + _textHeight = 0; + _parsedText = string.Empty; + _textDirection = RTLSupport.DirectionType.UNKNOW; + + if (_charPositions != null) + _charPositions.Clear(); + } + + void ApplyVertAlign() + { + float oldOffset = _yOffset; + if (_autoSize == AutoSizeType.Both || _autoSize == AutoSizeType.Height + || _verticalAlign == VertAlignType.Top) + _yOffset = 0; + else + { + float dh; + if (_textHeight == 0 && _lines.Count > 0) + dh = _contentRect.height - _lines[0].height; + else + dh = _contentRect.height - _textHeight; + if (dh < 0) + dh = 0; + if (_verticalAlign == VertAlignType.Middle) + _yOffset = (int)(dh / 2); + else + _yOffset = dh; + } + + if (oldOffset != _yOffset) + { + int cnt = _lines.Count; + for (int i = 0; i < cnt; i++) + _lines[i].y = _lines[i].y2 + _yOffset; + + graphics.SetMeshDirty(); + } + } + + /// + /// + /// + public class LineInfo + { + /// + /// 行的宽度 + /// + public float width; + + /// + /// 行的高度 + /// + public float height; + + /// + /// 文字渲染基线 + /// + public float baseline; + + /// + /// 行首的字符索引 + /// + public int charIndex; + + /// + /// 行包括的字符个数 + /// + public short charCount; + + /// + /// 行的y轴位置 + /// + public float y; + + /// + /// 行的y轴位置的备份 + /// + internal float y2; + + static Stack pool = new Stack(); + + /// + /// + /// + /// + public static LineInfo Borrow() + { + if (pool.Count > 0) + { + LineInfo ret = pool.Pop(); + ret.width = ret.height = ret.baseline = 0; + ret.y = ret.y2 = 0; + ret.charIndex = ret.charCount = 0; + return ret; + } + else + return new LineInfo(); + } + + /// + /// + /// + /// + public static void Return(LineInfo value) + { + pool.Push(value); + } + + /// + /// + /// + /// + public static void Return(List values) + { + int cnt = values.Count; + for (int i = 0; i < cnt; i++) + pool.Push(values[i]); + + values.Clear(); + } + } + + /// + /// + /// + public struct LineCharInfo + { + public float width; + public float height; + public float baseline; + } + + /// + /// + /// + public struct CharPosition + { + /// + /// 字符索引 + /// + public int charIndex; + + /// + /// 字符所在的行索引 + /// + public short lineIndex; + + /// + /// 字符的x偏移 + /// + public float offsetX; + + /// + /// 字符占用的顶点数量。 + /// + public short vertCount; + + /// + /// 字符的宽度 + /// + public short width; + + /// + /// 大于0表示图片索引。 + /// + public short imgIndex; + } + } +} diff --git a/Assets/Scripts/Core/Text/TextField.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextField.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/TextField.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextField.cs.meta diff --git a/Assets/Scripts/Core/Text/TextFormat.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextFormat.cs similarity index 96% rename from Assets/Scripts/Core/Text/TextFormat.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextFormat.cs index 1a00dda4..a61a4aab 100644 --- a/Assets/Scripts/Core/Text/TextFormat.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextFormat.cs @@ -1,175 +1,175 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public partial class TextFormat - { - public enum SpecialStyle - { - None, - Superscript, - Subscript - } - - /// - /// - /// - public int size; - - /// - /// - /// - public string font; - - /// - /// - /// - public Color color; - - /// - /// - /// - public int lineSpacing; - - /// - /// - /// - public int letterSpacing; - - /// - /// - /// - public bool bold; - - /// - /// - /// - public bool underline; - - /// - /// - /// - public bool italic; - - /// - /// - /// - public bool strikethrough; - - /// - /// - /// - public Color32[] gradientColor; - - /// - /// - /// - public AlignType align; - - /// - /// - /// - public SpecialStyle specialStyle; - - /// - /// - /// - public float outline; - - /// - /// - /// - public Color outlineColor; - - /// - /// - /// - public Vector2 shadowOffset; - - /// - /// - /// - public Color shadowColor; - - public TextFormat() - { - color = Color.black; - size = 12; - lineSpacing = 3; - outlineColor = shadowColor = Color.black; - } - - /// - /// - /// - /// - public void SetColor(uint value) - { - uint rr = (value >> 16) & 0x0000ff; - uint gg = (value >> 8) & 0x0000ff; - uint bb = value & 0x0000ff; - float r = rr / 255.0f; - float g = gg / 255.0f; - float b = bb / 255.0f; - color = new Color(r, g, b, 1); - } - - /// - /// - /// - /// - /// - public bool EqualStyle(TextFormat aFormat) - { - return size == aFormat.size && color == aFormat.color - && bold == aFormat.bold && underline == aFormat.underline - && italic == aFormat.italic - && strikethrough == aFormat.strikethrough - && gradientColor == aFormat.gradientColor - && align == aFormat.align - && specialStyle == aFormat.specialStyle; - } - - /// - /// Only base NOT all formats will be copied - /// - /// - public void CopyFrom(TextFormat source) - { - this.size = source.size; - this.font = source.font; - this.color = source.color; - this.lineSpacing = source.lineSpacing; - this.letterSpacing = source.letterSpacing; - this.bold = source.bold; - this.underline = source.underline; - this.italic = source.italic; - this.strikethrough = source.strikethrough; - if (source.gradientColor != null) - { - this.gradientColor = new Color32[4]; - source.gradientColor.CopyTo(this.gradientColor, 0); - } - else - this.gradientColor = null; - this.align = source.align; - this.specialStyle = source.specialStyle; - } - - public void FillVertexColors(Color32[] vertexColors) - { - if (gradientColor == null) - vertexColors[0] = vertexColors[1] = vertexColors[2] = vertexColors[3] = color; - else - { - vertexColors[0] = gradientColor[1]; - vertexColors[1] = gradientColor[0]; - vertexColors[2] = gradientColor[2]; - vertexColors[3] = gradientColor[3]; - } - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public partial class TextFormat + { + public enum SpecialStyle + { + None, + Superscript, + Subscript + } + + /// + /// + /// + public int size; + + /// + /// + /// + public string font; + + /// + /// + /// + public Color color; + + /// + /// + /// + public int lineSpacing; + + /// + /// + /// + public int letterSpacing; + + /// + /// + /// + public bool bold; + + /// + /// + /// + public bool underline; + + /// + /// + /// + public bool italic; + + /// + /// + /// + public bool strikethrough; + + /// + /// + /// + public Color32[] gradientColor; + + /// + /// + /// + public AlignType align; + + /// + /// + /// + public SpecialStyle specialStyle; + + /// + /// + /// + public float outline; + + /// + /// + /// + public Color outlineColor; + + /// + /// + /// + public Vector2 shadowOffset; + + /// + /// + /// + public Color shadowColor; + + public TextFormat() + { + color = Color.black; + size = 12; + lineSpacing = 3; + outlineColor = shadowColor = Color.black; + } + + /// + /// + /// + /// + public void SetColor(uint value) + { + uint rr = (value >> 16) & 0x0000ff; + uint gg = (value >> 8) & 0x0000ff; + uint bb = value & 0x0000ff; + float r = rr / 255.0f; + float g = gg / 255.0f; + float b = bb / 255.0f; + color = new Color(r, g, b, 1); + } + + /// + /// + /// + /// + /// + public bool EqualStyle(TextFormat aFormat) + { + return size == aFormat.size && color == aFormat.color + && bold == aFormat.bold && underline == aFormat.underline + && italic == aFormat.italic + && strikethrough == aFormat.strikethrough + && gradientColor == aFormat.gradientColor + && align == aFormat.align + && specialStyle == aFormat.specialStyle; + } + + /// + /// Only base NOT all formats will be copied + /// + /// + public void CopyFrom(TextFormat source) + { + this.size = source.size; + this.font = source.font; + this.color = source.color; + this.lineSpacing = source.lineSpacing; + this.letterSpacing = source.letterSpacing; + this.bold = source.bold; + this.underline = source.underline; + this.italic = source.italic; + this.strikethrough = source.strikethrough; + if (source.gradientColor != null) + { + this.gradientColor = new Color32[4]; + source.gradientColor.CopyTo(this.gradientColor, 0); + } + else + this.gradientColor = null; + this.align = source.align; + this.specialStyle = source.specialStyle; + } + + public void FillVertexColors(Color32[] vertexColors) + { + if (gradientColor == null) + vertexColors[0] = vertexColors[1] = vertexColors[2] = vertexColors[3] = color; + else + { + vertexColors[0] = gradientColor[1]; + vertexColors[1] = gradientColor[0]; + vertexColors[2] = gradientColor[2]; + vertexColors[3] = gradientColor[3]; + } + } + } +} diff --git a/Assets/Scripts/Core/Text/TextFormat.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextFormat.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/TextFormat.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TextFormat.cs.meta diff --git a/Assets/Scripts/Core/Text/TouchScreenKeyboard.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TouchScreenKeyboard.cs similarity index 96% rename from Assets/Scripts/Core/Text/TouchScreenKeyboard.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TouchScreenKeyboard.cs index 209718bf..dd637ab2 100644 --- a/Assets/Scripts/Core/Text/TouchScreenKeyboard.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TouchScreenKeyboard.cs @@ -1,65 +1,65 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class TouchScreenKeyboard : IKeyboard - { - UnityEngine.TouchScreenKeyboard _keyboard; - - public bool done - { -#if UNITY_2017_2_OR_NEWER - get - { - return _keyboard == null - || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.Done - || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.Canceled - || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.LostFocus; - } -#else - get { return _keyboard == null || _keyboard.done || _keyboard.wasCanceled; } -#endif - } - - public bool supportsCaret - { - get { return false; } - } - - public string GetInput() - { - if (_keyboard != null) - { - string s = _keyboard.text; - - if (this.done) - _keyboard = null; - - return s; - } - else - return null; - } - - public void Open(string text, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int keyboardType, bool hideInput) - { - if (_keyboard != null) - return; - - UnityEngine.TouchScreenKeyboard.hideInput = hideInput; - _keyboard = UnityEngine.TouchScreenKeyboard.Open(text, (TouchScreenKeyboardType)keyboardType, autocorrection, multiline, secure, alert, textPlaceholder); - } - - public void Close() - { - if (_keyboard != null) - { - _keyboard.active = false; - _keyboard = null; - } - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class TouchScreenKeyboard : IKeyboard + { + UnityEngine.TouchScreenKeyboard _keyboard; + + public bool done + { +#if UNITY_2017_2_OR_NEWER + get + { + return _keyboard == null + || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.Done + || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.Canceled + || _keyboard.status == UnityEngine.TouchScreenKeyboard.Status.LostFocus; + } +#else + get { return _keyboard == null || _keyboard.done || _keyboard.wasCanceled; } +#endif + } + + public bool supportsCaret + { + get { return false; } + } + + public string GetInput() + { + if (_keyboard != null) + { + string s = _keyboard.text; + + if (this.done) + _keyboard = null; + + return s; + } + else + return null; + } + + public void Open(string text, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int keyboardType, bool hideInput) + { + if (_keyboard != null) + return; + + UnityEngine.TouchScreenKeyboard.hideInput = hideInput; + _keyboard = UnityEngine.TouchScreenKeyboard.Open(text, (TouchScreenKeyboardType)keyboardType, autocorrection, multiline, secure, alert, textPlaceholder); + } + + public void Close() + { + if (_keyboard != null) + { + _keyboard.active = false; + _keyboard = null; + } + } + } +} diff --git a/Assets/Scripts/Core/Text/TouchScreenKeyboard.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TouchScreenKeyboard.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/TouchScreenKeyboard.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TouchScreenKeyboard.cs.meta diff --git a/Assets/Scripts/Core/Text/TypingEffect.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TypingEffect.cs similarity index 96% rename from Assets/Scripts/Core/Text/TypingEffect.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TypingEffect.cs index 7d76bfb7..b4b3a154 100644 --- a/Assets/Scripts/Core/Text/TypingEffect.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TypingEffect.cs @@ -1,248 +1,248 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// 文字打字效果。先调用Start,然后Print。 - /// - public class TypingEffect - { - protected TextField _textField; - protected Vector3[] _backupVerts; - protected Vector3[] _vertices; - - protected bool _stroke; - protected bool _shadow; - - protected int _printIndex; - protected int _mainLayerStart; - protected int _strokeLayerStart; - protected int _strokeDrawDirs; - protected int _vertIndex; - protected int _mainLayerVertCount; - - protected bool _started; - - /// - /// - /// - /// - public TypingEffect(TextField textField) - { - _textField = textField; - _textField.EnableCharPositionSupport(); - } - - /// - /// - /// - /// - public TypingEffect(GTextField textField) - { - if (textField is GRichTextField) - _textField = ((RichTextField)textField.displayObject).textField; - else - _textField = (TextField)textField.displayObject; - _textField.EnableCharPositionSupport(); - } - - /// - /// 总输出次数 - /// - public int totalTimes - { - get - { - int times = 0; - List charPositions = _textField.charPositions; - for (int i = 0; i < charPositions.Count - 1; i++) - { - if (charPositions[i].imgIndex > 0) //这是一个图片 - times++; - else if (!char.IsWhiteSpace(_textField.parsedText[i])) - times++; - } - return times; - } - } - - /// - /// 开始打字效果。可以重复调用重复启动。 - /// - public void Start() - { - _textField.graphics.meshModifier -= OnMeshModified; - _textField.Redraw(); - _textField.graphics.meshModifier += OnMeshModified; - - _stroke = false; - _shadow = false; - _strokeDrawDirs = 4; - _mainLayerStart = 0; - _mainLayerVertCount = 0; - _printIndex = 0; - _vertIndex = 0; - _started = true; - - int vertCount = _textField.graphics.mesh.vertexCount; - _backupVerts = _textField.graphics.mesh.vertices; - if (_vertices == null || _vertices.Length != vertCount) - _vertices = new Vector3[vertCount]; - Vector3 zero = Vector3.zero; - for (int i = 0; i < vertCount; i++) - _vertices[i] = zero; - _textField.graphics.mesh.vertices = _vertices; - - //隐藏所有混排的对象 - if (_textField.richTextField != null) - { - int ec = _textField.richTextField.htmlElementCount; - for (int i = 0; i < ec; i++) - _textField.richTextField.ShowHtmlObject(i, false); - } - - int charCount = _textField.charPositions.Count; - for (int i = 0; i < charCount; i++) - { - TextField.CharPosition cp = _textField.charPositions[i]; - _mainLayerVertCount += cp.vertCount; - } - - if (_mainLayerVertCount < vertCount) //说明有描边或者阴影 - { - int repeat = vertCount / _mainLayerVertCount; - _stroke = repeat > 2; - _shadow = repeat % 2 == 0; - _mainLayerStart = vertCount - vertCount / repeat; - _strokeLayerStart = _shadow ? (vertCount / repeat) : 0; - _strokeDrawDirs = repeat > 8 ? 8 : 4; - } - } - - /// - /// 输出一个字符。如果已经没有剩余的字符,返回false。 - /// - /// - public bool Print() - { - if (!_started) - return false; - - TextField.CharPosition cp; - List charPositions = _textField.charPositions; - int listCnt = charPositions.Count; - - while (_printIndex < listCnt - 1) //最后一个是占位的,无效的,所以-1 - { - cp = charPositions[_printIndex++]; - if (cp.vertCount > 0) - output(cp.vertCount); - if (cp.imgIndex > 0) //这是一个图片 - { - _textField.richTextField.ShowHtmlObject(cp.imgIndex - 1, true); - return true; - } - else if (!char.IsWhiteSpace(_textField.parsedText[_printIndex - 1])) - return true; - } - - Cancel(); - return false; - } - - private void output(int vertCount) - { - int start, end; - - start = _mainLayerStart + _vertIndex; - end = start + vertCount; - for (int i = start; i < end; i++) - _vertices[i] = _backupVerts[i]; - - if (_stroke) - { - start = _strokeLayerStart + _vertIndex; - end = start + vertCount; - for (int i = start; i < end; i++) - { - for (int j = 0; j < _strokeDrawDirs; j++) - { - int k = i + _mainLayerVertCount * j; - _vertices[k] = _backupVerts[k]; - } - } - } - - if (_shadow) - { - start = _vertIndex; - end = start + vertCount; - for (int i = start; i < end; i++) - { - _vertices[i] = _backupVerts[i]; - } - } - - _textField.graphics.mesh.vertices = _vertices; - - _vertIndex += vertCount; - } - - /// - /// 打印的协程。 - /// - /// 每个字符输出的时间间隔 - /// - public IEnumerator Print(float interval) - { - while (Print()) - yield return new WaitForSeconds(interval); - } - - /// - /// 使用固定时间间隔完成整个打印过程。 - /// - /// - public void PrintAll(float interval) - { - Timers.inst.StartCoroutine(Print(interval)); - } - - public void Cancel() - { - if (!_started) - return; - - _started = false; - _textField.graphics.meshModifier -= OnMeshModified; - _textField.graphics.SetMeshDirty(); - } - - /// - /// 当打字过程中,文本可能会由于字体纹理更改而发生字体重建,要处理这种情况。 - /// 图片对象不需要处理,因为HtmlElement.status里设定的隐藏标志不会因为Mesh更新而被冲掉。 - /// - void OnMeshModified() - { - if (_textField.graphics.mesh.vertexCount != _backupVerts.Length) //可能文字都改了 - { - Cancel(); - return; - } - - _backupVerts = _textField.graphics.mesh.vertices; - - int vertCount = _vertices.Length; - Vector3 zero = Vector3.zero; - for (int i = 0; i < vertCount; i++) - { - if (_vertices[i] != zero) - _vertices[i] = _backupVerts[i]; - } - - _textField.graphics.mesh.vertices = _vertices; - } - } -} +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 文字打字效果。先调用Start,然后Print。 + /// + public class TypingEffect + { + protected TextField _textField; + protected Vector3[] _backupVerts; + protected Vector3[] _vertices; + + protected bool _stroke; + protected bool _shadow; + + protected int _printIndex; + protected int _mainLayerStart; + protected int _strokeLayerStart; + protected int _strokeDrawDirs; + protected int _vertIndex; + protected int _mainLayerVertCount; + + protected bool _started; + + /// + /// + /// + /// + public TypingEffect(TextField textField) + { + _textField = textField; + _textField.EnableCharPositionSupport(); + } + + /// + /// + /// + /// + public TypingEffect(GTextField textField) + { + if (textField is GRichTextField) + _textField = ((RichTextField)textField.displayObject).textField; + else + _textField = (TextField)textField.displayObject; + _textField.EnableCharPositionSupport(); + } + + /// + /// 总输出次数 + /// + public int totalTimes + { + get + { + int times = 0; + List charPositions = _textField.charPositions; + for (int i = 0; i < charPositions.Count - 1; i++) + { + if (charPositions[i].imgIndex > 0) //这是一个图片 + times++; + else if (!char.IsWhiteSpace(_textField.parsedText[i])) + times++; + } + return times; + } + } + + /// + /// 开始打字效果。可以重复调用重复启动。 + /// + public void Start() + { + _textField.graphics.meshModifier -= OnMeshModified; + _textField.Redraw(); + _textField.graphics.meshModifier += OnMeshModified; + + _stroke = false; + _shadow = false; + _strokeDrawDirs = 4; + _mainLayerStart = 0; + _mainLayerVertCount = 0; + _printIndex = 0; + _vertIndex = 0; + _started = true; + + int vertCount = _textField.graphics.mesh.vertexCount; + _backupVerts = _textField.graphics.mesh.vertices; + if (_vertices == null || _vertices.Length != vertCount) + _vertices = new Vector3[vertCount]; + Vector3 zero = Vector3.zero; + for (int i = 0; i < vertCount; i++) + _vertices[i] = zero; + _textField.graphics.mesh.vertices = _vertices; + + //隐藏所有混排的对象 + if (_textField.richTextField != null) + { + int ec = _textField.richTextField.htmlElementCount; + for (int i = 0; i < ec; i++) + _textField.richTextField.ShowHtmlObject(i, false); + } + + int charCount = _textField.charPositions.Count; + for (int i = 0; i < charCount; i++) + { + TextField.CharPosition cp = _textField.charPositions[i]; + _mainLayerVertCount += cp.vertCount; + } + + if (_mainLayerVertCount < vertCount) //说明有描边或者阴影 + { + int repeat = vertCount / _mainLayerVertCount; + _stroke = repeat > 2; + _shadow = repeat % 2 == 0; + _mainLayerStart = vertCount - vertCount / repeat; + _strokeLayerStart = _shadow ? (vertCount / repeat) : 0; + _strokeDrawDirs = repeat > 8 ? 8 : 4; + } + } + + /// + /// 输出一个字符。如果已经没有剩余的字符,返回false。 + /// + /// + public bool Print() + { + if (!_started) + return false; + + TextField.CharPosition cp; + List charPositions = _textField.charPositions; + int listCnt = charPositions.Count; + + while (_printIndex < listCnt - 1) //最后一个是占位的,无效的,所以-1 + { + cp = charPositions[_printIndex++]; + if (cp.vertCount > 0) + output(cp.vertCount); + if (cp.imgIndex > 0) //这是一个图片 + { + _textField.richTextField.ShowHtmlObject(cp.imgIndex - 1, true); + return true; + } + else if (!char.IsWhiteSpace(_textField.parsedText[_printIndex - 1])) + return true; + } + + Cancel(); + return false; + } + + private void output(int vertCount) + { + int start, end; + + start = _mainLayerStart + _vertIndex; + end = start + vertCount; + for (int i = start; i < end; i++) + _vertices[i] = _backupVerts[i]; + + if (_stroke) + { + start = _strokeLayerStart + _vertIndex; + end = start + vertCount; + for (int i = start; i < end; i++) + { + for (int j = 0; j < _strokeDrawDirs; j++) + { + int k = i + _mainLayerVertCount * j; + _vertices[k] = _backupVerts[k]; + } + } + } + + if (_shadow) + { + start = _vertIndex; + end = start + vertCount; + for (int i = start; i < end; i++) + { + _vertices[i] = _backupVerts[i]; + } + } + + _textField.graphics.mesh.vertices = _vertices; + + _vertIndex += vertCount; + } + + /// + /// 打印的协程。 + /// + /// 每个字符输出的时间间隔 + /// + public IEnumerator Print(float interval) + { + while (Print()) + yield return new WaitForSeconds(interval); + } + + /// + /// 使用固定时间间隔完成整个打印过程。 + /// + /// + public void PrintAll(float interval) + { + Timers.inst.StartCoroutine(Print(interval)); + } + + public void Cancel() + { + if (!_started) + return; + + _started = false; + _textField.graphics.meshModifier -= OnMeshModified; + _textField.graphics.SetMeshDirty(); + } + + /// + /// 当打字过程中,文本可能会由于字体纹理更改而发生字体重建,要处理这种情况。 + /// 图片对象不需要处理,因为HtmlElement.status里设定的隐藏标志不会因为Mesh更新而被冲掉。 + /// + void OnMeshModified() + { + if (_textField.graphics.mesh.vertexCount != _backupVerts.Length) //可能文字都改了 + { + Cancel(); + return; + } + + _backupVerts = _textField.graphics.mesh.vertices; + + int vertCount = _vertices.Length; + Vector3 zero = Vector3.zero; + for (int i = 0; i < vertCount; i++) + { + if (_vertices[i] != zero) + _vertices[i] = _backupVerts[i]; + } + + _textField.graphics.mesh.vertices = _vertices; + } + } +} diff --git a/Assets/Scripts/Core/Text/TypingEffect.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TypingEffect.cs.meta similarity index 100% rename from Assets/Scripts/Core/Text/TypingEffect.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/Text/TypingEffect.cs.meta diff --git a/Assets/Scripts/Core/UpdateContext.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/UpdateContext.cs similarity index 97% rename from Assets/Scripts/Core/UpdateContext.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/UpdateContext.cs index 5c51124f..b00c886e 100644 --- a/Assets/Scripts/Core/UpdateContext.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/UpdateContext.cs @@ -1,310 +1,310 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// UpdateContext is for internal use. - /// - public class UpdateContext - { - public struct ClipInfo - { - public Rect rect; - public Vector4 clipBox; - public bool soft; - public Vector4 softness;//left-top-right-bottom - public uint clipId; - public int rectMaskDepth; - public int referenceValue; - public bool reversed; - } - - Stack _clipStack; - - public bool clipped; - public ClipInfo clipInfo; - - public int renderingOrder; - public int batchingDepth; - public int rectMaskDepth; - public int stencilReferenceValue; - public int stencilCompareValue; - - public float alpha; - public bool grayed; - - public static UpdateContext current; - public static bool working; - - public static event Action OnBegin; - public static event Action OnEnd; - - static Action _tmpBegin; - - public UpdateContext() - { - _clipStack = new Stack(); - } - - /// - /// - /// - public void Begin() - { - current = this; - - renderingOrder = 0; - batchingDepth = 0; - rectMaskDepth = 0; - stencilReferenceValue = 0; - alpha = 1; - grayed = false; - - clipped = false; - _clipStack.Clear(); - - Stats.ObjectCount = 0; - Stats.GraphicsCount = 0; - - _tmpBegin = OnBegin; - OnBegin = null; - - //允许OnBegin里再次Add,这里没有做死锁检查 - while (_tmpBegin != null) - { - _tmpBegin.Invoke(); - _tmpBegin = OnBegin; - OnBegin = null; - } - - working = true; - } - - /// - /// - /// - public void End() - { - working = false; - - if (OnEnd != null) - OnEnd.Invoke(); - - OnEnd = null; - } - - /// - /// - /// - /// - /// - /// - public void EnterClipping(uint clipId, Rect clipRect, Vector4? softness) - { - _clipStack.Push(clipInfo); - - if (rectMaskDepth > 0) - clipRect = ToolSet.Intersection(ref clipInfo.rect, ref clipRect); - - clipped = true; - clipInfo.rectMaskDepth = ++rectMaskDepth; - /* clipPos = xy * clipBox.zw + clipBox.xy - * 利用这个公式,使clipPos变为当前顶点距离剪切区域中心的距离值,剪切区域的大小为2x2 - * 那么abs(clipPos)>1的都是在剪切区域外 - */ - clipInfo.rect = clipRect; - clipRect.x = clipRect.x + clipRect.width * 0.5f; - clipRect.y = clipRect.y + clipRect.height * 0.5f; - clipRect.width *= 0.5f; - clipRect.height *= 0.5f; - if (clipRect.width == 0 || clipRect.height == 0) - clipInfo.clipBox = new Vector4(-2, -2, 0, 0); - else - clipInfo.clipBox = new Vector4(-clipRect.x / clipRect.width, -clipRect.y / clipRect.height, - 1.0f / clipRect.width, 1.0f / clipRect.height); - clipInfo.clipId = clipId; - clipInfo.soft = softness != null; - if (clipInfo.soft) - { - clipInfo.softness = (Vector4)softness; - float vx = clipInfo.rect.width * Screen.height * 0.25f; - float vy = clipInfo.rect.height * Screen.height * 0.25f; - - if (clipInfo.softness.x > 0) - clipInfo.softness.x = vx / clipInfo.softness.x; - else - clipInfo.softness.x = 10000f; - - if (clipInfo.softness.y > 0) - clipInfo.softness.y = vy / clipInfo.softness.y; - else - clipInfo.softness.y = 10000f; - - if (clipInfo.softness.z > 0) - clipInfo.softness.z = vx / clipInfo.softness.z; - else - clipInfo.softness.z = 10000f; - - if (clipInfo.softness.w > 0) - clipInfo.softness.w = vy / clipInfo.softness.w; - else - clipInfo.softness.w = 10000f; - } - } - - /// - /// - /// - /// - /// - public void EnterClipping(uint clipId, bool reversedMask) - { - _clipStack.Push(clipInfo); - - if (stencilReferenceValue == 0) - stencilReferenceValue = 1; - else - stencilReferenceValue = stencilReferenceValue << 1; - - if (reversedMask) - { - if (clipInfo.reversed) - stencilCompareValue = (stencilReferenceValue >> 1) - 1; - else - stencilCompareValue = stencilReferenceValue - 1; - } - else - stencilCompareValue = (stencilReferenceValue << 1) - 1; - - clipInfo.clipId = clipId; - clipInfo.referenceValue = stencilReferenceValue; - clipInfo.reversed = reversedMask; - clipped = true; - } - - /// - /// - /// - public void LeaveClipping() - { - clipInfo = _clipStack.Pop(); - stencilReferenceValue = clipInfo.referenceValue; - rectMaskDepth = clipInfo.rectMaskDepth; - clipped = stencilReferenceValue != 0 || rectMaskDepth != 0; - } - - public void EnterPaintingMode() - { - //Reset clipping - _clipStack.Push(clipInfo); - - clipInfo.rectMaskDepth = 0; - clipInfo.referenceValue = 0; - clipInfo.reversed = false; - clipped = false; - } - - public void LeavePaintingMode() - { - clipInfo = _clipStack.Pop(); - stencilReferenceValue = clipInfo.referenceValue; - rectMaskDepth = clipInfo.rectMaskDepth; - clipped = stencilReferenceValue != 0 || rectMaskDepth != 0; - } - - public void ApplyClippingProperties(Material mat, bool isStdMaterial) - { - if (rectMaskDepth > 0) //在矩形剪裁下,且不是遮罩对象 - { - mat.SetVector(ShaderConfig.ID_ClipBox, clipInfo.clipBox); - if (clipInfo.soft) - mat.SetVector(ShaderConfig.ID_ClipSoftness, clipInfo.softness); - } - - if (stencilReferenceValue > 0) - { - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); - mat.SetInt(ShaderConfig.ID_Stencil, stencilCompareValue); - mat.SetInt(ShaderConfig.ID_Stencil2, stencilCompareValue); - mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Keep); - mat.SetInt(ShaderConfig.ID_StencilReadMask, stencilReferenceValue | (stencilReferenceValue - 1)); - mat.SetInt(ShaderConfig.ID_ColorMask, 15); - } - else - { - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Always); - mat.SetInt(ShaderConfig.ID_Stencil, 0); - mat.SetInt(ShaderConfig.ID_Stencil2, 0); - mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Keep); - mat.SetInt(ShaderConfig.ID_StencilReadMask, 255); - mat.SetInt(ShaderConfig.ID_ColorMask, 15); - } - - if (!isStdMaterial) - { - if (rectMaskDepth > 0) - { - if (clipInfo.soft) - mat.EnableKeyword("SOFT_CLIPPED"); - else - mat.EnableKeyword("CLIPPED"); - } - else - { - mat.DisableKeyword("CLIPPED"); - mat.DisableKeyword("SOFT_CLIPPED"); - } - } - } - - public void ApplyAlphaMaskProperties(Material mat, bool erasing) - { - if (!erasing) - { - if (stencilReferenceValue == 1) - { - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Always); - mat.SetInt(ShaderConfig.ID_Stencil, 1); - mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); - mat.SetInt(ShaderConfig.ID_StencilReadMask, 255); - mat.SetInt(ShaderConfig.ID_ColorMask, 0); - } - else - { - if (stencilReferenceValue != 0 & _clipStack.Peek().reversed) - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.NotEqual); - else - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); - mat.SetInt(ShaderConfig.ID_Stencil, stencilReferenceValue | (stencilReferenceValue - 1)); - mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); - mat.SetInt(ShaderConfig.ID_StencilReadMask, stencilReferenceValue - 1); - mat.SetInt(ShaderConfig.ID_ColorMask, 0); - } - } - else - { - if (stencilReferenceValue != 0 & _clipStack.Peek().reversed) - { - int refValue = stencilReferenceValue | (stencilReferenceValue - 1); - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); - mat.SetInt(ShaderConfig.ID_Stencil, refValue); - mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Zero); - mat.SetInt(ShaderConfig.ID_StencilReadMask, refValue); - mat.SetInt(ShaderConfig.ID_ColorMask, 0); - } - else - { - int refValue = stencilReferenceValue - 1; - mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); - mat.SetInt(ShaderConfig.ID_Stencil, refValue); - mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); - mat.SetInt(ShaderConfig.ID_StencilReadMask, refValue); - mat.SetInt(ShaderConfig.ID_ColorMask, 0); - } - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// UpdateContext is for internal use. + /// + public class UpdateContext + { + public struct ClipInfo + { + public Rect rect; + public Vector4 clipBox; + public bool soft; + public Vector4 softness;//left-top-right-bottom + public uint clipId; + public int rectMaskDepth; + public int referenceValue; + public bool reversed; + } + + Stack _clipStack; + + public bool clipped; + public ClipInfo clipInfo; + + public int renderingOrder; + public int batchingDepth; + public int rectMaskDepth; + public int stencilReferenceValue; + public int stencilCompareValue; + + public float alpha; + public bool grayed; + + public static UpdateContext current; + public static bool working; + + public static event Action OnBegin; + public static event Action OnEnd; + + static Action _tmpBegin; + + public UpdateContext() + { + _clipStack = new Stack(); + } + + /// + /// + /// + public void Begin() + { + current = this; + + renderingOrder = 0; + batchingDepth = 0; + rectMaskDepth = 0; + stencilReferenceValue = 0; + alpha = 1; + grayed = false; + + clipped = false; + _clipStack.Clear(); + + Stats.ObjectCount = 0; + Stats.GraphicsCount = 0; + + _tmpBegin = OnBegin; + OnBegin = null; + + //允许OnBegin里再次Add,这里没有做死锁检查 + while (_tmpBegin != null) + { + _tmpBegin.Invoke(); + _tmpBegin = OnBegin; + OnBegin = null; + } + + working = true; + } + + /// + /// + /// + public void End() + { + working = false; + + if (OnEnd != null) + OnEnd.Invoke(); + + OnEnd = null; + } + + /// + /// + /// + /// + /// + /// + public void EnterClipping(uint clipId, Rect clipRect, Vector4? softness) + { + _clipStack.Push(clipInfo); + + if (rectMaskDepth > 0) + clipRect = ToolSet.Intersection(ref clipInfo.rect, ref clipRect); + + clipped = true; + clipInfo.rectMaskDepth = ++rectMaskDepth; + /* clipPos = xy * clipBox.zw + clipBox.xy + * 利用这个公式,使clipPos变为当前顶点距离剪切区域中心的距离值,剪切区域的大小为2x2 + * 那么abs(clipPos)>1的都是在剪切区域外 + */ + clipInfo.rect = clipRect; + clipRect.x = clipRect.x + clipRect.width * 0.5f; + clipRect.y = clipRect.y + clipRect.height * 0.5f; + clipRect.width *= 0.5f; + clipRect.height *= 0.5f; + if (clipRect.width == 0 || clipRect.height == 0) + clipInfo.clipBox = new Vector4(-2, -2, 0, 0); + else + clipInfo.clipBox = new Vector4(-clipRect.x / clipRect.width, -clipRect.y / clipRect.height, + 1.0f / clipRect.width, 1.0f / clipRect.height); + clipInfo.clipId = clipId; + clipInfo.soft = softness != null; + if (clipInfo.soft) + { + clipInfo.softness = (Vector4)softness; + float vx = clipInfo.rect.width * Screen.height * 0.25f; + float vy = clipInfo.rect.height * Screen.height * 0.25f; + + if (clipInfo.softness.x > 0) + clipInfo.softness.x = vx / clipInfo.softness.x; + else + clipInfo.softness.x = 10000f; + + if (clipInfo.softness.y > 0) + clipInfo.softness.y = vy / clipInfo.softness.y; + else + clipInfo.softness.y = 10000f; + + if (clipInfo.softness.z > 0) + clipInfo.softness.z = vx / clipInfo.softness.z; + else + clipInfo.softness.z = 10000f; + + if (clipInfo.softness.w > 0) + clipInfo.softness.w = vy / clipInfo.softness.w; + else + clipInfo.softness.w = 10000f; + } + } + + /// + /// + /// + /// + /// + public void EnterClipping(uint clipId, bool reversedMask) + { + _clipStack.Push(clipInfo); + + if (stencilReferenceValue == 0) + stencilReferenceValue = 1; + else + stencilReferenceValue = stencilReferenceValue << 1; + + if (reversedMask) + { + if (clipInfo.reversed) + stencilCompareValue = (stencilReferenceValue >> 1) - 1; + else + stencilCompareValue = stencilReferenceValue - 1; + } + else + stencilCompareValue = (stencilReferenceValue << 1) - 1; + + clipInfo.clipId = clipId; + clipInfo.referenceValue = stencilReferenceValue; + clipInfo.reversed = reversedMask; + clipped = true; + } + + /// + /// + /// + public void LeaveClipping() + { + clipInfo = _clipStack.Pop(); + stencilReferenceValue = clipInfo.referenceValue; + rectMaskDepth = clipInfo.rectMaskDepth; + clipped = stencilReferenceValue != 0 || rectMaskDepth != 0; + } + + public void EnterPaintingMode() + { + //Reset clipping + _clipStack.Push(clipInfo); + + clipInfo.rectMaskDepth = 0; + clipInfo.referenceValue = 0; + clipInfo.reversed = false; + clipped = false; + } + + public void LeavePaintingMode() + { + clipInfo = _clipStack.Pop(); + stencilReferenceValue = clipInfo.referenceValue; + rectMaskDepth = clipInfo.rectMaskDepth; + clipped = stencilReferenceValue != 0 || rectMaskDepth != 0; + } + + public void ApplyClippingProperties(Material mat, bool isStdMaterial) + { + if (rectMaskDepth > 0) //在矩形剪裁下,且不是遮罩对象 + { + mat.SetVector(ShaderConfig.ID_ClipBox, clipInfo.clipBox); + if (clipInfo.soft) + mat.SetVector(ShaderConfig.ID_ClipSoftness, clipInfo.softness); + } + + if (stencilReferenceValue > 0) + { + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, stencilCompareValue); + mat.SetInt(ShaderConfig.ID_Stencil2, stencilCompareValue); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Keep); + mat.SetInt(ShaderConfig.ID_StencilReadMask, stencilReferenceValue | (stencilReferenceValue - 1)); + mat.SetInt(ShaderConfig.ID_ColorMask, 15); + } + else + { + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Always); + mat.SetInt(ShaderConfig.ID_Stencil, 0); + mat.SetInt(ShaderConfig.ID_Stencil2, 0); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Keep); + mat.SetInt(ShaderConfig.ID_StencilReadMask, 255); + mat.SetInt(ShaderConfig.ID_ColorMask, 15); + } + + if (!isStdMaterial) + { + if (rectMaskDepth > 0) + { + if (clipInfo.soft) + mat.EnableKeyword("SOFT_CLIPPED"); + else + mat.EnableKeyword("CLIPPED"); + } + else + { + mat.DisableKeyword("CLIPPED"); + mat.DisableKeyword("SOFT_CLIPPED"); + } + } + } + + public void ApplyAlphaMaskProperties(Material mat, bool erasing) + { + if (!erasing) + { + if (stencilReferenceValue == 1) + { + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Always); + mat.SetInt(ShaderConfig.ID_Stencil, 1); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); + mat.SetInt(ShaderConfig.ID_StencilReadMask, 255); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + else + { + if (stencilReferenceValue != 0 & _clipStack.Peek().reversed) + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.NotEqual); + else + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, stencilReferenceValue | (stencilReferenceValue - 1)); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); + mat.SetInt(ShaderConfig.ID_StencilReadMask, stencilReferenceValue - 1); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + } + else + { + if (stencilReferenceValue != 0 & _clipStack.Peek().reversed) + { + int refValue = stencilReferenceValue | (stencilReferenceValue - 1); + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, refValue); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Zero); + mat.SetInt(ShaderConfig.ID_StencilReadMask, refValue); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + else + { + int refValue = stencilReferenceValue - 1; + mat.SetInt(ShaderConfig.ID_StencilComp, (int)UnityEngine.Rendering.CompareFunction.Equal); + mat.SetInt(ShaderConfig.ID_Stencil, refValue); + mat.SetInt(ShaderConfig.ID_StencilOp, (int)UnityEngine.Rendering.StencilOp.Replace); + mat.SetInt(ShaderConfig.ID_StencilReadMask, refValue); + mat.SetInt(ShaderConfig.ID_ColorMask, 0); + } + } + } + } +} diff --git a/Assets/Scripts/Core/UpdateContext.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Core/UpdateContext.cs.meta similarity index 100% rename from Assets/Scripts/Core/UpdateContext.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Core/UpdateContext.cs.meta diff --git a/Assets/Scripts/Event.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event.meta similarity index 100% rename from Assets/Scripts/Event.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event.meta diff --git a/Assets/Scripts/Event/EventBridge.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventBridge.cs similarity index 96% rename from Assets/Scripts/Event/EventBridge.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventBridge.cs index df0003c6..38bd08a8 100644 --- a/Assets/Scripts/Event/EventBridge.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventBridge.cs @@ -1,176 +1,176 @@ -#if FAIRYGUI_TOLUA -using System; -using LuaInterface; -#endif - -namespace FairyGUI -{ - /// - /// - /// - class EventBridge - { - public EventDispatcher owner; - - EventCallback0 _callback0; - EventCallback1 _callback1; - EventCallback1 _captureCallback; - internal bool _dispatching; - - public EventBridge(EventDispatcher owner) - { - this.owner = owner; - } - - public void AddCapture(EventCallback1 callback) - { - _captureCallback -= callback; - _captureCallback += callback; - } - - public void RemoveCapture(EventCallback1 callback) - { - _captureCallback -= callback; - } - - public void Add(EventCallback1 callback) - { - _callback1 -= callback; - _callback1 += callback; - } - - public void Remove(EventCallback1 callback) - { - _callback1 -= callback; - } - - public void Add(EventCallback0 callback) - { - _callback0 -= callback; - _callback0 += callback; - } - - public void Remove(EventCallback0 callback) - { - _callback0 -= callback; - } - -#if FAIRYGUI_TOLUA - public void Add(LuaFunction func, LuaTable self) - { - EventCallback1 callback; - if(self != null) - callback = (EventCallback1)DelegateTraits.Create(func, self); - else - callback = (EventCallback1)DelegateTraits.Create(func); - _callback1 -= callback; - _callback1 += callback; - } - - public void Add(LuaFunction func, GComponent self) - { - if (self._peerTable == null) - throw new Exception("self is not connected to lua."); - - Add(func, self._peerTable); - } - - public void Remove(LuaFunction func, LuaTable self) - { - LuaState state = func.GetLuaState(); - LuaDelegate target; - if (self != null) - target = state.GetLuaDelegate(func, self); - else - target = state.GetLuaDelegate(func); - - Delegate[] ds = _callback1.GetInvocationList(); - - for (int i = 0; i < ds.Length; i++) - { - LuaDelegate ld = ds[i].Target as LuaDelegate; - if (ld != null && ld.Equals(target)) - { - _callback1 = (EventCallback1)Delegate.Remove(_callback1, ds[i]); - //DelayDispose will cause problem - //state.DelayDispose(ld.func); - //if (ld.self != null) - // state.DelayDispose(ld.self); - break; - } - } - } - - public void Remove(LuaFunction func, GComponent self) - { - if (self._peerTable == null) - throw new Exception("self is not connected to lua."); - - Remove(func, self._peerTable); - } -#endif - - public bool isEmpty - { - get { return _callback1 == null && _callback0 == null && _captureCallback == null; } - } - - public void Clear() - { -#if FAIRYGUI_TOLUA - //if (_callback1 != null) - //{ - // Delegate[] ds = _callback1.GetInvocationList(); - // for (int i = 0; i < ds.Length; i++) - // { - // LuaDelegate ld = ds[i].Target as LuaDelegate; - // if (ld != null) - // { - // LuaState state = ld.func.GetLuaState(); - // state.DelayDispose(ld.func); - // if (ld.self != null) - // state.DelayDispose(ld.self); - // } - // } - //} -#endif - _callback1 = null; - _callback0 = null; - _captureCallback = null; - } - - public void CallInternal(EventContext context) - { - _dispatching = true; - context.sender = owner; - try - { - if (_callback1 != null) - _callback1(context); - if (_callback0 != null) - _callback0(); - } - finally - { - _dispatching = false; - } - } - - public void CallCaptureInternal(EventContext context) - { - if (_captureCallback == null) - return; - - _dispatching = true; - context.sender = owner; - try - { - _captureCallback(context); - } - finally - { - _dispatching = false; - } - } - } -} +#if FAIRYGUI_TOLUA +using System; +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + class EventBridge + { + public EventDispatcher owner; + + EventCallback0 _callback0; + EventCallback1 _callback1; + EventCallback1 _captureCallback; + internal bool _dispatching; + + public EventBridge(EventDispatcher owner) + { + this.owner = owner; + } + + public void AddCapture(EventCallback1 callback) + { + _captureCallback -= callback; + _captureCallback += callback; + } + + public void RemoveCapture(EventCallback1 callback) + { + _captureCallback -= callback; + } + + public void Add(EventCallback1 callback) + { + _callback1 -= callback; + _callback1 += callback; + } + + public void Remove(EventCallback1 callback) + { + _callback1 -= callback; + } + + public void Add(EventCallback0 callback) + { + _callback0 -= callback; + _callback0 += callback; + } + + public void Remove(EventCallback0 callback) + { + _callback0 -= callback; + } + +#if FAIRYGUI_TOLUA + public void Add(LuaFunction func, LuaTable self) + { + EventCallback1 callback; + if(self != null) + callback = (EventCallback1)DelegateTraits.Create(func, self); + else + callback = (EventCallback1)DelegateTraits.Create(func); + _callback1 -= callback; + _callback1 += callback; + } + + public void Add(LuaFunction func, GComponent self) + { + if (self._peerTable == null) + throw new Exception("self is not connected to lua."); + + Add(func, self._peerTable); + } + + public void Remove(LuaFunction func, LuaTable self) + { + LuaState state = func.GetLuaState(); + LuaDelegate target; + if (self != null) + target = state.GetLuaDelegate(func, self); + else + target = state.GetLuaDelegate(func); + + Delegate[] ds = _callback1.GetInvocationList(); + + for (int i = 0; i < ds.Length; i++) + { + LuaDelegate ld = ds[i].Target as LuaDelegate; + if (ld != null && ld.Equals(target)) + { + _callback1 = (EventCallback1)Delegate.Remove(_callback1, ds[i]); + //DelayDispose will cause problem + //state.DelayDispose(ld.func); + //if (ld.self != null) + // state.DelayDispose(ld.self); + break; + } + } + } + + public void Remove(LuaFunction func, GComponent self) + { + if (self._peerTable == null) + throw new Exception("self is not connected to lua."); + + Remove(func, self._peerTable); + } +#endif + + public bool isEmpty + { + get { return _callback1 == null && _callback0 == null && _captureCallback == null; } + } + + public void Clear() + { +#if FAIRYGUI_TOLUA + //if (_callback1 != null) + //{ + // Delegate[] ds = _callback1.GetInvocationList(); + // for (int i = 0; i < ds.Length; i++) + // { + // LuaDelegate ld = ds[i].Target as LuaDelegate; + // if (ld != null) + // { + // LuaState state = ld.func.GetLuaState(); + // state.DelayDispose(ld.func); + // if (ld.self != null) + // state.DelayDispose(ld.self); + // } + // } + //} +#endif + _callback1 = null; + _callback0 = null; + _captureCallback = null; + } + + public void CallInternal(EventContext context) + { + _dispatching = true; + context.sender = owner; + try + { + if (_callback1 != null) + _callback1(context); + if (_callback0 != null) + _callback0(); + } + finally + { + _dispatching = false; + } + } + + public void CallCaptureInternal(EventContext context) + { + if (_captureCallback == null) + return; + + _dispatching = true; + context.sender = owner; + try + { + _captureCallback(context); + } + finally + { + _dispatching = false; + } + } + } +} diff --git a/Assets/Scripts/Event/EventBridge.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventBridge.cs.meta similarity index 100% rename from Assets/Scripts/Event/EventBridge.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventBridge.cs.meta diff --git a/Assets/Scripts/Event/EventContext.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventContext.cs similarity index 95% rename from Assets/Scripts/Event/EventContext.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventContext.cs index f5e4ad3d..0750dc3f 100644 --- a/Assets/Scripts/Event/EventContext.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventContext.cs @@ -1,94 +1,94 @@ -using System.Collections.Generic; - -namespace FairyGUI -{ - /// - /// - /// - public class EventContext - { - /// - /// - /// - public EventDispatcher sender { get; internal set; } - - /// - /// / - /// - public object initiator { get; internal set; } - - /// - /// / - /// - public InputEvent inputEvent { get; internal set; } - - /// - /// - /// - public string type; - - /// - /// - /// - public object data; - - internal bool _defaultPrevented; - internal bool _stopsPropagation; - internal bool _touchCapture; - - internal List callChain = new List(); - - /// - /// - /// - public void StopPropagation() - { - _stopsPropagation = true; - } - - /// - /// - /// - public void PreventDefault() - { - _defaultPrevented = true; - } - - /// - /// - /// - public void CaptureTouch() - { - _touchCapture = true; - } - - /// - /// - /// - public bool isDefaultPrevented - { - get { return _defaultPrevented; } - } - - static Stack pool = new Stack(); - internal static EventContext Get() - { - if (pool.Count > 0) - { - EventContext context = pool.Pop(); - context._stopsPropagation = false; - context._defaultPrevented = false; - context._touchCapture = false; - return context; - } - else - return new EventContext(); - } - - internal static void Return(EventContext value) - { - pool.Push(value); - } - } - -} +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + public class EventContext + { + /// + /// + /// + public EventDispatcher sender { get; internal set; } + + /// + /// / + /// + public object initiator { get; internal set; } + + /// + /// / + /// + public InputEvent inputEvent { get; internal set; } + + /// + /// + /// + public string type; + + /// + /// + /// + public object data; + + internal bool _defaultPrevented; + internal bool _stopsPropagation; + internal bool _touchCapture; + + internal List callChain = new List(); + + /// + /// + /// + public void StopPropagation() + { + _stopsPropagation = true; + } + + /// + /// + /// + public void PreventDefault() + { + _defaultPrevented = true; + } + + /// + /// + /// + public void CaptureTouch() + { + _touchCapture = true; + } + + /// + /// + /// + public bool isDefaultPrevented + { + get { return _defaultPrevented; } + } + + static Stack pool = new Stack(); + internal static EventContext Get() + { + if (pool.Count > 0) + { + EventContext context = pool.Pop(); + context._stopsPropagation = false; + context._defaultPrevented = false; + context._touchCapture = false; + return context; + } + else + return new EventContext(); + } + + internal static void Return(EventContext value) + { + pool.Push(value); + } + } + +} diff --git a/Assets/Scripts/Event/EventContext.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventContext.cs.meta similarity index 100% rename from Assets/Scripts/Event/EventContext.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventContext.cs.meta diff --git a/Assets/Scripts/Event/EventDispatcher.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventDispatcher.cs similarity index 96% rename from Assets/Scripts/Event/EventDispatcher.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventDispatcher.cs index ceb90b82..916db4ab 100644 --- a/Assets/Scripts/Event/EventDispatcher.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventDispatcher.cs @@ -1,515 +1,515 @@ -using System; -using System.Collections.Generic; - -namespace FairyGUI -{ - public delegate void EventCallback0(); - public delegate void EventCallback1(EventContext context); - - /// - /// - /// - public class EventDispatcher : IEventDispatcher - { - Dictionary _dic; - - public EventDispatcher() - { - } - - /// - /// - /// - /// - /// - public void AddEventListener(string strType, EventCallback1 callback) - { - GetBridge(strType).Add(callback); - } - - /// - /// - /// - /// - /// - public void AddEventListener(string strType, EventCallback0 callback) - { - GetBridge(strType).Add(callback); - } - - /// - /// - /// - /// - /// - public void RemoveEventListener(string strType, EventCallback1 callback) - { - if (_dic == null) - return; - - EventBridge bridge = null; - if (_dic.TryGetValue(strType, out bridge)) - bridge.Remove(callback); - } - - /// - /// - /// - /// - /// - public void RemoveEventListener(string strType, EventCallback0 callback) - { - if (_dic == null) - return; - - EventBridge bridge = null; - if (_dic.TryGetValue(strType, out bridge)) - bridge.Remove(callback); - } - - /// - /// - /// - /// - /// - public void AddCapture(string strType, EventCallback1 callback) - { - GetBridge(strType).AddCapture(callback); - } - - /// - /// - /// - /// - /// - public void RemoveCapture(string strType, EventCallback1 callback) - { - if (_dic == null) - return; - - EventBridge bridge = null; - if (_dic.TryGetValue(strType, out bridge)) - bridge.RemoveCapture(callback); - } - - /// - /// - /// - public void RemoveEventListeners() - { - RemoveEventListeners(null); - } - - /// - /// - /// - /// - public void RemoveEventListeners(string strType) - { - if (_dic == null) - return; - - if (strType != null) - { - EventBridge bridge; - if (_dic.TryGetValue(strType, out bridge)) - bridge.Clear(); - } - else - { - foreach (KeyValuePair kv in _dic) - kv.Value.Clear(); - } - } - - /// - /// - /// - /// - /// - public bool hasEventListeners(string strType) - { - EventBridge bridge = TryGetEventBridge(strType); - if (bridge == null) - return false; - - return !bridge.isEmpty; - } - - /// - /// - /// - /// - /// - public bool isDispatching(string strType) - { - EventBridge bridge = TryGetEventBridge(strType); - if (bridge == null) - return false; - - return bridge._dispatching; - } - - internal EventBridge TryGetEventBridge(string strType) - { - if (_dic == null) - return null; - - EventBridge bridge = null; - _dic.TryGetValue(strType, out bridge); - return bridge; - } - - internal EventBridge GetEventBridge(string strType) - { - if (_dic == null) - _dic = new Dictionary(); - - EventBridge bridge = null; - if (!_dic.TryGetValue(strType, out bridge)) - { - bridge = new EventBridge(this); - _dic[strType] = bridge; - } - return bridge; - } - - /// - /// - /// - /// - /// - public bool DispatchEvent(string strType) - { - return DispatchEvent(strType, null); - } - - /// - /// - /// - /// - /// - /// - public bool DispatchEvent(string strType, object data) - { - return InternalDispatchEvent(strType, null, data, null); - } - - public bool DispatchEvent(string strType, object data, object initiator) - { - return InternalDispatchEvent(strType, null, data, initiator); - } - - static InputEvent sCurrentInputEvent = new InputEvent(); - - internal bool InternalDispatchEvent(string strType, EventBridge bridge, object data, object initiator) - { - if (bridge == null) - bridge = TryGetEventBridge(strType); - - EventBridge gBridge = null; - if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) - gBridge = ((DisplayObject)this).gOwner.TryGetEventBridge(strType); - - bool b1 = bridge != null && !bridge.isEmpty; - bool b2 = gBridge != null && !gBridge.isEmpty; - if (b1 || b2) - { - EventContext context = EventContext.Get(); - context.initiator = initiator != null ? initiator : this; - context.type = strType; - context.data = data; - if (data is InputEvent) - sCurrentInputEvent = (InputEvent)data; - context.inputEvent = sCurrentInputEvent; - - if (b1) - { - bridge.CallCaptureInternal(context); - bridge.CallInternal(context); - } - - if (b2) - { - gBridge.CallCaptureInternal(context); - gBridge.CallInternal(context); - } - - EventContext.Return(context); - context.initiator = null; - context.sender = null; - context.data = null; - - return context._defaultPrevented; - } - else - return false; - } - - /// - /// - /// - /// - /// - public bool DispatchEvent(EventContext context) - { - EventBridge bridge = TryGetEventBridge(context.type); - EventBridge gBridge = null; - if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) - gBridge = ((DisplayObject)this).gOwner.TryGetEventBridge(context.type); - - EventDispatcher savedSender = context.sender; - - if (bridge != null && !bridge.isEmpty) - { - bridge.CallCaptureInternal(context); - bridge.CallInternal(context); - } - - if (gBridge != null && !gBridge.isEmpty) - { - gBridge.CallCaptureInternal(context); - gBridge.CallInternal(context); - } - - context.sender = savedSender; - return context._defaultPrevented; - } - - /// - /// - /// - /// - /// - /// - /// - internal bool BubbleEvent(string strType, object data, List addChain) - { - EventContext context = EventContext.Get(); - context.initiator = this; - - context.type = strType; - context.data = data; - if (data is InputEvent) - sCurrentInputEvent = (InputEvent)data; - context.inputEvent = sCurrentInputEvent; - List bubbleChain = context.callChain; - bubbleChain.Clear(); - - GetChainBridges(strType, bubbleChain, true); - - int length = bubbleChain.Count; - for (int i = length - 1; i >= 0; i--) - { - bubbleChain[i].CallCaptureInternal(context); - if (context._touchCapture) - { - context._touchCapture = false; - if (strType == "onTouchBegin") - Stage.inst.AddTouchMonitor(context.inputEvent.touchId, bubbleChain[i].owner); - } - } - - if (!context._stopsPropagation) - { - for (int i = 0; i < length; ++i) - { - bubbleChain[i].CallInternal(context); - - if (context._touchCapture) - { - context._touchCapture = false; - if (strType == "onTouchBegin") - Stage.inst.AddTouchMonitor(context.inputEvent.touchId, bubbleChain[i].owner); - } - - if (context._stopsPropagation) - break; - } - - if (addChain != null) - { - length = addChain.Count; - for (int i = 0; i < length; ++i) - { - EventBridge bridge = addChain[i]; - if (bubbleChain.IndexOf(bridge) == -1) - { - bridge.CallCaptureInternal(context); - bridge.CallInternal(context); - } - } - } - } - - EventContext.Return(context); - context.initiator = null; - context.sender = null; - context.data = null; - return context._defaultPrevented; - } - - /// - /// - /// - /// - /// - /// - public bool BubbleEvent(string strType, object data) - { - return BubbleEvent(strType, data, null); - } - - /// - /// - /// - /// - /// - /// - public bool BroadcastEvent(string strType, object data) - { - EventContext context = EventContext.Get(); - context.initiator = this; - context.type = strType; - context.data = data; - if (data is InputEvent) - sCurrentInputEvent = (InputEvent)data; - context.inputEvent = sCurrentInputEvent; - List bubbleChain = context.callChain; - bubbleChain.Clear(); - - if (this is Container) - GetChildEventBridges(strType, (Container)this, bubbleChain); - else if (this is GComponent) - GetChildEventBridges(strType, (GComponent)this, bubbleChain); - - int length = bubbleChain.Count; - for (int i = 0; i < length; ++i) - bubbleChain[i].CallInternal(context); - - EventContext.Return(context); - context.initiator = null; - context.sender = null; - context.data = null; - return context._defaultPrevented; - } - - EventBridge GetBridge(string strType) - { - if (strType == null) - throw new Exception("event type cant be null"); - - if (_dic == null) - _dic = new Dictionary(); - - EventBridge bridge = null; - if (!_dic.TryGetValue(strType, out bridge)) - { - bridge = new EventBridge(this); - _dic[strType] = bridge; - } - - return bridge; - } - - static void GetChildEventBridges(string strType, Container container, List bridges) - { - EventBridge bridge = container.TryGetEventBridge(strType); - if (bridge != null) - bridges.Add(bridge); - if (container.gOwner != null) - { - bridge = container.gOwner.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - bridges.Add(bridge); - } - - int count = container.numChildren; - for (int i = 0; i < count; ++i) - { - DisplayObject obj = container.GetChildAt(i); - if (obj is Container) - GetChildEventBridges(strType, (Container)obj, bridges); - else - { - bridge = obj.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - bridges.Add(bridge); - - if (obj.gOwner != null) - { - bridge = obj.gOwner.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - bridges.Add(bridge); - } - } - } - } - - static void GetChildEventBridges(string strType, GComponent container, List bridges) - { - EventBridge bridge = container.TryGetEventBridge(strType); - if (bridge != null) - bridges.Add(bridge); - - int count = container.numChildren; - for (int i = 0; i < count; ++i) - { - GObject obj = container.GetChildAt(i); - if (obj is GComponent) - GetChildEventBridges(strType, (GComponent)obj, bridges); - else - { - bridge = obj.TryGetEventBridge(strType); - if (bridge != null) - bridges.Add(bridge); - } - } - } - - internal void GetChainBridges(string strType, List chain, bool bubble) - { - EventBridge bridge = TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - chain.Add(bridge); - - if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) - { - bridge = ((DisplayObject)this).gOwner.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - chain.Add(bridge); - } - - if (!bubble) - return; - - if (this is DisplayObject) - { - DisplayObject element = (DisplayObject)this; - while ((element = element.parent) != null) - { - bridge = element.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - chain.Add(bridge); - - if (element.gOwner != null) - { - bridge = element.gOwner.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - chain.Add(bridge); - } - } - } - else if (this is GObject) - { - GObject element = (GObject)this; - while ((element = element.parent) != null) - { - bridge = element.TryGetEventBridge(strType); - if (bridge != null && !bridge.isEmpty) - chain.Add(bridge); - } - } - } - } -} +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + public delegate void EventCallback0(); + public delegate void EventCallback1(EventContext context); + + /// + /// + /// + public class EventDispatcher : IEventDispatcher + { + Dictionary _dic; + + public EventDispatcher() + { + } + + /// + /// + /// + /// + /// + public void AddEventListener(string strType, EventCallback1 callback) + { + GetBridge(strType).Add(callback); + } + + /// + /// + /// + /// + /// + public void AddEventListener(string strType, EventCallback0 callback) + { + GetBridge(strType).Add(callback); + } + + /// + /// + /// + /// + /// + public void RemoveEventListener(string strType, EventCallback1 callback) + { + if (_dic == null) + return; + + EventBridge bridge = null; + if (_dic.TryGetValue(strType, out bridge)) + bridge.Remove(callback); + } + + /// + /// + /// + /// + /// + public void RemoveEventListener(string strType, EventCallback0 callback) + { + if (_dic == null) + return; + + EventBridge bridge = null; + if (_dic.TryGetValue(strType, out bridge)) + bridge.Remove(callback); + } + + /// + /// + /// + /// + /// + public void AddCapture(string strType, EventCallback1 callback) + { + GetBridge(strType).AddCapture(callback); + } + + /// + /// + /// + /// + /// + public void RemoveCapture(string strType, EventCallback1 callback) + { + if (_dic == null) + return; + + EventBridge bridge = null; + if (_dic.TryGetValue(strType, out bridge)) + bridge.RemoveCapture(callback); + } + + /// + /// + /// + public void RemoveEventListeners() + { + RemoveEventListeners(null); + } + + /// + /// + /// + /// + public void RemoveEventListeners(string strType) + { + if (_dic == null) + return; + + if (strType != null) + { + EventBridge bridge; + if (_dic.TryGetValue(strType, out bridge)) + bridge.Clear(); + } + else + { + foreach (KeyValuePair kv in _dic) + kv.Value.Clear(); + } + } + + /// + /// + /// + /// + /// + public bool hasEventListeners(string strType) + { + EventBridge bridge = TryGetEventBridge(strType); + if (bridge == null) + return false; + + return !bridge.isEmpty; + } + + /// + /// + /// + /// + /// + public bool isDispatching(string strType) + { + EventBridge bridge = TryGetEventBridge(strType); + if (bridge == null) + return false; + + return bridge._dispatching; + } + + internal EventBridge TryGetEventBridge(string strType) + { + if (_dic == null) + return null; + + EventBridge bridge = null; + _dic.TryGetValue(strType, out bridge); + return bridge; + } + + internal EventBridge GetEventBridge(string strType) + { + if (_dic == null) + _dic = new Dictionary(); + + EventBridge bridge = null; + if (!_dic.TryGetValue(strType, out bridge)) + { + bridge = new EventBridge(this); + _dic[strType] = bridge; + } + return bridge; + } + + /// + /// + /// + /// + /// + public bool DispatchEvent(string strType) + { + return DispatchEvent(strType, null); + } + + /// + /// + /// + /// + /// + /// + public bool DispatchEvent(string strType, object data) + { + return InternalDispatchEvent(strType, null, data, null); + } + + public bool DispatchEvent(string strType, object data, object initiator) + { + return InternalDispatchEvent(strType, null, data, initiator); + } + + static InputEvent sCurrentInputEvent = new InputEvent(); + + internal bool InternalDispatchEvent(string strType, EventBridge bridge, object data, object initiator) + { + if (bridge == null) + bridge = TryGetEventBridge(strType); + + EventBridge gBridge = null; + if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) + gBridge = ((DisplayObject)this).gOwner.TryGetEventBridge(strType); + + bool b1 = bridge != null && !bridge.isEmpty; + bool b2 = gBridge != null && !gBridge.isEmpty; + if (b1 || b2) + { + EventContext context = EventContext.Get(); + context.initiator = initiator != null ? initiator : this; + context.type = strType; + context.data = data; + if (data is InputEvent) + sCurrentInputEvent = (InputEvent)data; + context.inputEvent = sCurrentInputEvent; + + if (b1) + { + bridge.CallCaptureInternal(context); + bridge.CallInternal(context); + } + + if (b2) + { + gBridge.CallCaptureInternal(context); + gBridge.CallInternal(context); + } + + EventContext.Return(context); + context.initiator = null; + context.sender = null; + context.data = null; + + return context._defaultPrevented; + } + else + return false; + } + + /// + /// + /// + /// + /// + public bool DispatchEvent(EventContext context) + { + EventBridge bridge = TryGetEventBridge(context.type); + EventBridge gBridge = null; + if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) + gBridge = ((DisplayObject)this).gOwner.TryGetEventBridge(context.type); + + EventDispatcher savedSender = context.sender; + + if (bridge != null && !bridge.isEmpty) + { + bridge.CallCaptureInternal(context); + bridge.CallInternal(context); + } + + if (gBridge != null && !gBridge.isEmpty) + { + gBridge.CallCaptureInternal(context); + gBridge.CallInternal(context); + } + + context.sender = savedSender; + return context._defaultPrevented; + } + + /// + /// + /// + /// + /// + /// + /// + internal bool BubbleEvent(string strType, object data, List addChain) + { + EventContext context = EventContext.Get(); + context.initiator = this; + + context.type = strType; + context.data = data; + if (data is InputEvent) + sCurrentInputEvent = (InputEvent)data; + context.inputEvent = sCurrentInputEvent; + List bubbleChain = context.callChain; + bubbleChain.Clear(); + + GetChainBridges(strType, bubbleChain, true); + + int length = bubbleChain.Count; + for (int i = length - 1; i >= 0; i--) + { + bubbleChain[i].CallCaptureInternal(context); + if (context._touchCapture) + { + context._touchCapture = false; + if (strType == "onTouchBegin") + Stage.inst.AddTouchMonitor(context.inputEvent.touchId, bubbleChain[i].owner); + } + } + + if (!context._stopsPropagation) + { + for (int i = 0; i < length; ++i) + { + bubbleChain[i].CallInternal(context); + + if (context._touchCapture) + { + context._touchCapture = false; + if (strType == "onTouchBegin") + Stage.inst.AddTouchMonitor(context.inputEvent.touchId, bubbleChain[i].owner); + } + + if (context._stopsPropagation) + break; + } + + if (addChain != null) + { + length = addChain.Count; + for (int i = 0; i < length; ++i) + { + EventBridge bridge = addChain[i]; + if (bubbleChain.IndexOf(bridge) == -1) + { + bridge.CallCaptureInternal(context); + bridge.CallInternal(context); + } + } + } + } + + EventContext.Return(context); + context.initiator = null; + context.sender = null; + context.data = null; + return context._defaultPrevented; + } + + /// + /// + /// + /// + /// + /// + public bool BubbleEvent(string strType, object data) + { + return BubbleEvent(strType, data, null); + } + + /// + /// + /// + /// + /// + /// + public bool BroadcastEvent(string strType, object data) + { + EventContext context = EventContext.Get(); + context.initiator = this; + context.type = strType; + context.data = data; + if (data is InputEvent) + sCurrentInputEvent = (InputEvent)data; + context.inputEvent = sCurrentInputEvent; + List bubbleChain = context.callChain; + bubbleChain.Clear(); + + if (this is Container) + GetChildEventBridges(strType, (Container)this, bubbleChain); + else if (this is GComponent) + GetChildEventBridges(strType, (GComponent)this, bubbleChain); + + int length = bubbleChain.Count; + for (int i = 0; i < length; ++i) + bubbleChain[i].CallInternal(context); + + EventContext.Return(context); + context.initiator = null; + context.sender = null; + context.data = null; + return context._defaultPrevented; + } + + EventBridge GetBridge(string strType) + { + if (strType == null) + throw new Exception("event type cant be null"); + + if (_dic == null) + _dic = new Dictionary(); + + EventBridge bridge = null; + if (!_dic.TryGetValue(strType, out bridge)) + { + bridge = new EventBridge(this); + _dic[strType] = bridge; + } + + return bridge; + } + + static void GetChildEventBridges(string strType, Container container, List bridges) + { + EventBridge bridge = container.TryGetEventBridge(strType); + if (bridge != null) + bridges.Add(bridge); + if (container.gOwner != null) + { + bridge = container.gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + bridges.Add(bridge); + } + + int count = container.numChildren; + for (int i = 0; i < count; ++i) + { + DisplayObject obj = container.GetChildAt(i); + if (obj is Container) + GetChildEventBridges(strType, (Container)obj, bridges); + else + { + bridge = obj.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + bridges.Add(bridge); + + if (obj.gOwner != null) + { + bridge = obj.gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + bridges.Add(bridge); + } + } + } + } + + static void GetChildEventBridges(string strType, GComponent container, List bridges) + { + EventBridge bridge = container.TryGetEventBridge(strType); + if (bridge != null) + bridges.Add(bridge); + + int count = container.numChildren; + for (int i = 0; i < count; ++i) + { + GObject obj = container.GetChildAt(i); + if (obj is GComponent) + GetChildEventBridges(strType, (GComponent)obj, bridges); + else + { + bridge = obj.TryGetEventBridge(strType); + if (bridge != null) + bridges.Add(bridge); + } + } + } + + internal void GetChainBridges(string strType, List chain, bool bubble) + { + EventBridge bridge = TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + + if ((this is DisplayObject) && ((DisplayObject)this).gOwner != null) + { + bridge = ((DisplayObject)this).gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + } + + if (!bubble) + return; + + if (this is DisplayObject) + { + DisplayObject element = (DisplayObject)this; + while ((element = element.parent) != null) + { + bridge = element.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + + if (element.gOwner != null) + { + bridge = element.gOwner.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + } + } + } + else if (this is GObject) + { + GObject element = (GObject)this; + while ((element = element.parent) != null) + { + bridge = element.TryGetEventBridge(strType); + if (bridge != null && !bridge.isEmpty) + chain.Add(bridge); + } + } + } + } +} diff --git a/Assets/Scripts/Event/EventDispatcher.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventDispatcher.cs.meta similarity index 100% rename from Assets/Scripts/Event/EventDispatcher.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventDispatcher.cs.meta diff --git a/Assets/Scripts/Event/EventListener.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventListener.cs similarity index 95% rename from Assets/Scripts/Event/EventListener.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventListener.cs index ffd33755..4082688f 100644 --- a/Assets/Scripts/Event/EventListener.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventListener.cs @@ -1,267 +1,267 @@ -#if FAIRYGUI_TOLUA -using LuaInterface; -#endif - -namespace FairyGUI -{ - /// - /// - /// - public class EventListener - { - EventBridge _bridge; - string _type; - - public EventListener(EventDispatcher owner, string type) - { - _bridge = owner.GetEventBridge(type); - _type = type; - } - - /// - /// - /// - public string type - { - get { return _type; } - } - - /// - /// - /// - /// - public void AddCapture(EventCallback1 callback) - { - _bridge.AddCapture(callback); - } - - /// - /// - /// - /// - public void RemoveCapture(EventCallback1 callback) - { - _bridge.RemoveCapture(callback); - } - - /// - /// - /// - /// - public void Add(EventCallback1 callback) - { - _bridge.Add(callback); - } - - /// - /// - /// - /// - public void Remove(EventCallback1 callback) - { - _bridge.Remove(callback); - } - - /// - /// - /// - /// -#if FAIRYGUI_TOLUA - [NoToLua] -#endif - public void Add(EventCallback0 callback) - { - _bridge.Add(callback); - } - - /// - /// - /// - /// -#if FAIRYGUI_TOLUA - [NoToLua] -#endif - public void Remove(EventCallback0 callback) - { - _bridge.Remove(callback); - } - - /// - /// - /// - /// - public void Set(EventCallback1 callback) - { - _bridge.Clear(); - if (callback != null) - _bridge.Add(callback); - } - - /// - /// - /// - /// -#if FAIRYGUI_TOLUA - [NoToLua] -#endif - public void Set(EventCallback0 callback) - { - _bridge.Clear(); - if (callback != null) - _bridge.Add(callback); - } - -#if FAIRYGUI_TOLUA - /// - /// - /// - /// - /// - public void Add(LuaFunction func, LuaTable self) - { - _bridge.Add(func, self); - } - - /// - /// - /// - /// - /// - public void Add(LuaFunction func, GComponent self) - { - _bridge.Add(func, self); - } - - /// - /// - /// - /// - /// - public void Remove(LuaFunction func, LuaTable self) - { - _bridge.Remove(func, self); - } - - /// - /// - /// - /// - /// - public void Remove(LuaFunction func, GComponent self) - { - _bridge.Remove(func, self); - } - - /// - /// - /// - /// - /// - public void Set(LuaFunction func, LuaTable self) - { - _bridge.Clear(); - if (func != null) - Add(func, self); - } - - /// - /// - /// - /// - /// - public void Set(LuaFunction func, GComponent self) - { - _bridge.Clear(); - if (func != null) - Add(func, self); - } -#endif - - /// - /// - /// - public bool isEmpty - { - get - { - return !_bridge.owner.hasEventListeners(_type); - } - } - - /// - /// - /// - public bool isDispatching - { - get - { - return _bridge.owner.isDispatching(_type); - } - } - - /// - /// - /// - public void Clear() - { - _bridge.Clear(); - } - - /// - /// - /// - /// - public bool Call() - { - return _bridge.owner.InternalDispatchEvent(_type, _bridge, null, null); - } - - /// - /// - /// - /// - /// - public bool Call(object data) - { - return _bridge.owner.InternalDispatchEvent(_type, _bridge, data, null); - } - - /// - /// - /// - /// - /// - public bool BubbleCall(object data) - { - return _bridge.owner.BubbleEvent(_type, data); - } - - /// - /// - /// - /// - public bool BubbleCall() - { - return _bridge.owner.BubbleEvent(_type, null); - } - - /// - /// - /// - /// - /// - public bool BroadcastCall(object data) - { - return _bridge.owner.BroadcastEvent(_type, data); - } - - /// - /// - /// - /// - public bool BroadcastCall() - { - return _bridge.owner.BroadcastEvent(_type, null); - } - } -} +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public class EventListener + { + EventBridge _bridge; + string _type; + + public EventListener(EventDispatcher owner, string type) + { + _bridge = owner.GetEventBridge(type); + _type = type; + } + + /// + /// + /// + public string type + { + get { return _type; } + } + + /// + /// + /// + /// + public void AddCapture(EventCallback1 callback) + { + _bridge.AddCapture(callback); + } + + /// + /// + /// + /// + public void RemoveCapture(EventCallback1 callback) + { + _bridge.RemoveCapture(callback); + } + + /// + /// + /// + /// + public void Add(EventCallback1 callback) + { + _bridge.Add(callback); + } + + /// + /// + /// + /// + public void Remove(EventCallback1 callback) + { + _bridge.Remove(callback); + } + + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public void Add(EventCallback0 callback) + { + _bridge.Add(callback); + } + + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public void Remove(EventCallback0 callback) + { + _bridge.Remove(callback); + } + + /// + /// + /// + /// + public void Set(EventCallback1 callback) + { + _bridge.Clear(); + if (callback != null) + _bridge.Add(callback); + } + + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public void Set(EventCallback0 callback) + { + _bridge.Clear(); + if (callback != null) + _bridge.Add(callback); + } + +#if FAIRYGUI_TOLUA + /// + /// + /// + /// + /// + public void Add(LuaFunction func, LuaTable self) + { + _bridge.Add(func, self); + } + + /// + /// + /// + /// + /// + public void Add(LuaFunction func, GComponent self) + { + _bridge.Add(func, self); + } + + /// + /// + /// + /// + /// + public void Remove(LuaFunction func, LuaTable self) + { + _bridge.Remove(func, self); + } + + /// + /// + /// + /// + /// + public void Remove(LuaFunction func, GComponent self) + { + _bridge.Remove(func, self); + } + + /// + /// + /// + /// + /// + public void Set(LuaFunction func, LuaTable self) + { + _bridge.Clear(); + if (func != null) + Add(func, self); + } + + /// + /// + /// + /// + /// + public void Set(LuaFunction func, GComponent self) + { + _bridge.Clear(); + if (func != null) + Add(func, self); + } +#endif + + /// + /// + /// + public bool isEmpty + { + get + { + return !_bridge.owner.hasEventListeners(_type); + } + } + + /// + /// + /// + public bool isDispatching + { + get + { + return _bridge.owner.isDispatching(_type); + } + } + + /// + /// + /// + public void Clear() + { + _bridge.Clear(); + } + + /// + /// + /// + /// + public bool Call() + { + return _bridge.owner.InternalDispatchEvent(_type, _bridge, null, null); + } + + /// + /// + /// + /// + /// + public bool Call(object data) + { + return _bridge.owner.InternalDispatchEvent(_type, _bridge, data, null); + } + + /// + /// + /// + /// + /// + public bool BubbleCall(object data) + { + return _bridge.owner.BubbleEvent(_type, data); + } + + /// + /// + /// + /// + public bool BubbleCall() + { + return _bridge.owner.BubbleEvent(_type, null); + } + + /// + /// + /// + /// + /// + public bool BroadcastCall(object data) + { + return _bridge.owner.BroadcastEvent(_type, data); + } + + /// + /// + /// + /// + public bool BroadcastCall() + { + return _bridge.owner.BroadcastEvent(_type, null); + } + } +} diff --git a/Assets/Scripts/Event/EventListener.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventListener.cs.meta similarity index 100% rename from Assets/Scripts/Event/EventListener.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/EventListener.cs.meta diff --git a/Assets/Scripts/Event/IEventDispatcher.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/IEventDispatcher.cs similarity index 97% rename from Assets/Scripts/Event/IEventDispatcher.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/IEventDispatcher.cs index eb259010..21854447 100644 --- a/Assets/Scripts/Event/IEventDispatcher.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/IEventDispatcher.cs @@ -1,20 +1,20 @@ -using System; -using System.Collections.Generic; - -namespace FairyGUI -{ - /// - /// - /// - public interface IEventDispatcher - { - void AddEventListener(string strType, EventCallback0 callback); - void AddEventListener(string strType, EventCallback1 callback); - void RemoveEventListener(string strType, EventCallback0 callback); - void RemoveEventListener(string strType, EventCallback1 callback); - bool DispatchEvent(EventContext context); - bool DispatchEvent(string strType); - bool DispatchEvent(string strType, object data); - bool DispatchEvent(string strType, object data, object initiator); - } -} +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + public interface IEventDispatcher + { + void AddEventListener(string strType, EventCallback0 callback); + void AddEventListener(string strType, EventCallback1 callback); + void RemoveEventListener(string strType, EventCallback0 callback); + void RemoveEventListener(string strType, EventCallback1 callback); + bool DispatchEvent(EventContext context); + bool DispatchEvent(string strType); + bool DispatchEvent(string strType, object data); + bool DispatchEvent(string strType, object data, object initiator); + } +} diff --git a/Assets/Scripts/Event/IEventDispatcher.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/IEventDispatcher.cs.meta similarity index 100% rename from Assets/Scripts/Event/IEventDispatcher.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/IEventDispatcher.cs.meta diff --git a/Assets/Scripts/Event/InputEvent.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/InputEvent.cs similarity index 96% rename from Assets/Scripts/Event/InputEvent.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/InputEvent.cs index 236c20a9..4d86de9e 100644 --- a/Assets/Scripts/Event/InputEvent.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/InputEvent.cs @@ -1,149 +1,149 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class InputEvent - { - /// - /// x position in stage coordinates. - /// - public float x { get; internal set; } - - /// - /// y position in stage coordinates. - /// - public float y { get; internal set; } - - /// - /// - /// - public KeyCode keyCode { get; internal set; } - - /// - /// - /// - public char character { get; internal set; } - - /// - /// - /// - public EventModifiers modifiers { get; internal set; } - - /// - /// - /// - public float mouseWheelDelta { get; internal set; } - - /// - /// - /// - public int touchId { get; internal set; } - - /// - /// -1-none,0-left,1-right,2-middle - /// - public int button { get; internal set; } - - /// - /// - /// - /// - public int clickCount { get; internal set; } - - /// - /// Duraion of holding the button. You can read this in touchEnd or click event. - /// - /// - public float holdTime { get; internal set; } - - public InputEvent() - { - touchId = -1; - x = 0; - y = 0; - clickCount = 0; - keyCode = KeyCode.None; - character = '\0'; - modifiers = 0; - mouseWheelDelta = 0; - } - - /// - /// - /// - public Vector2 position - { - get { return new Vector2(x, y); } - } - - /// - /// - /// - public bool isDoubleClick - { - get { return clickCount > 1 && button == 0; } - } - - /// - /// - /// - public bool ctrlOrCmd - { - get - { - return ctrl || command; - } - } - - /// - /// - /// - public bool ctrl - { - get - { - return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl); - } - } - - /// - /// - /// - public bool shift - { - get - { - return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); - } - } - - /// - /// - /// - public bool alt - { - get - { - return Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt); - } - } - - /// - /// - /// - public bool command - { - get - { - //In win, as long as the win key and other keys are pressed at the same time, the getKey will continue to return true. So it can only be shielded. - if (Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXEditor) - return Input.GetKey(KeyCode.LeftCommand) || Input.GetKey(KeyCode.RightCommand); - else - return false; - } - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class InputEvent + { + /// + /// x position in stage coordinates. + /// + public float x { get; internal set; } + + /// + /// y position in stage coordinates. + /// + public float y { get; internal set; } + + /// + /// + /// + public KeyCode keyCode { get; internal set; } + + /// + /// + /// + public char character { get; internal set; } + + /// + /// + /// + public EventModifiers modifiers { get; internal set; } + + /// + /// + /// + public float mouseWheelDelta { get; internal set; } + + /// + /// + /// + public int touchId { get; internal set; } + + /// + /// -1-none,0-left,1-right,2-middle + /// + public int button { get; internal set; } + + /// + /// + /// + /// + public int clickCount { get; internal set; } + + /// + /// Duraion of holding the button. You can read this in touchEnd or click event. + /// + /// + public float holdTime { get; internal set; } + + public InputEvent() + { + touchId = -1; + x = 0; + y = 0; + clickCount = 0; + keyCode = KeyCode.None; + character = '\0'; + modifiers = 0; + mouseWheelDelta = 0; + } + + /// + /// + /// + public Vector2 position + { + get { return new Vector2(x, y); } + } + + /// + /// + /// + public bool isDoubleClick + { + get { return clickCount > 1 && button == 0; } + } + + /// + /// + /// + public bool ctrlOrCmd + { + get + { + return ctrl || command; + } + } + + /// + /// + /// + public bool ctrl + { + get + { + return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl); + } + } + + /// + /// + /// + public bool shift + { + get + { + return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); + } + } + + /// + /// + /// + public bool alt + { + get + { + return Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt); + } + } + + /// + /// + /// + public bool command + { + get + { + //In win, as long as the win key and other keys are pressed at the same time, the getKey will continue to return true. So it can only be shielded. + if (Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXEditor) + return Input.GetKey(KeyCode.LeftCommand) || Input.GetKey(KeyCode.RightCommand); + else + return false; + } + } + } +} diff --git a/Assets/Scripts/Event/InputEvent.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Event/InputEvent.cs.meta similarity index 100% rename from Assets/Scripts/Event/InputEvent.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Event/InputEvent.cs.meta diff --git a/Assets/Scripts/Filter.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter.meta similarity index 100% rename from Assets/Scripts/Filter.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter.meta diff --git a/Assets/Scripts/Filter/BlurFilter.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/BlurFilter.cs similarity index 96% rename from Assets/Scripts/Filter/BlurFilter.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/BlurFilter.cs index 578d5010..b1c1ae2a 100644 --- a/Assets/Scripts/Filter/BlurFilter.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/BlurFilter.cs @@ -1,103 +1,103 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class BlurFilter : IFilter - { - //ref http://blog.csdn.net/u011047171/article/details/47947397 - - /// - /// - /// - public float blurSize; - - DisplayObject _target; - Material _blitMaterial; - - public BlurFilter() - { - blurSize = 1f; - } - - public DisplayObject target - { - get { return _target; } - set - { - _target = value; - _target.EnterPaintingMode(1, null); - _target.onPaint += OnRenderImage; - - _blitMaterial = new Material(ShaderConfig.GetShader("FairyGUI/BlurFilter")); - _blitMaterial.hideFlags = DisplayObject.hideFlags; - } - } - - public void Dispose() - { - _target.LeavePaintingMode(1); - _target.onPaint -= OnRenderImage; - _target = null; - - if (Application.isPlaying) - Material.Destroy(_blitMaterial); - else - Material.DestroyImmediate(_blitMaterial); - } - - public void Update() - { - } - - void FourTapCone(RenderTexture source, RenderTexture dest, int iteration) - { - float off = blurSize * iteration + 0.5f; - Graphics.BlitMultiTap(source, dest, _blitMaterial, - new Vector2(-off, -off), - new Vector2(-off, off), - new Vector2(off, off), - new Vector2(off, -off) - ); - } - - void DownSample4x(RenderTexture source, RenderTexture dest) - { - float off = 1.0f; - Graphics.BlitMultiTap(source, dest, _blitMaterial, - new Vector2(off, off), - new Vector2(-off, off), - new Vector2(off, off), - new Vector2(off, -off) - ); - } - - void OnRenderImage() - { - if (blurSize < 0.01) - return; - - RenderTexture sourceTexture = (RenderTexture)_target.paintingGraphics.texture.nativeTexture; - int rtW = sourceTexture.width / 8; - int rtH = sourceTexture.height / 8; - RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0); - - DownSample4x(sourceTexture, buffer); - - for (int i = 0; i < 2; i++) - { - RenderTexture buffer2 = RenderTexture.GetTemporary(rtW, rtH, 0); - FourTapCone(buffer, buffer2, i); - RenderTexture.ReleaseTemporary(buffer); - buffer = buffer2; - } - Graphics.Blit(buffer, sourceTexture); - - RenderTexture.ReleaseTemporary(buffer); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class BlurFilter : IFilter + { + //ref http://blog.csdn.net/u011047171/article/details/47947397 + + /// + /// + /// + public float blurSize; + + DisplayObject _target; + Material _blitMaterial; + + public BlurFilter() + { + blurSize = 1f; + } + + public DisplayObject target + { + get { return _target; } + set + { + _target = value; + _target.EnterPaintingMode(1, null); + _target.onPaint += OnRenderImage; + + _blitMaterial = new Material(ShaderConfig.GetShader("FairyGUI/BlurFilter")); + _blitMaterial.hideFlags = DisplayObject.hideFlags; + } + } + + public void Dispose() + { + _target.LeavePaintingMode(1); + _target.onPaint -= OnRenderImage; + _target = null; + + if (Application.isPlaying) + Material.Destroy(_blitMaterial); + else + Material.DestroyImmediate(_blitMaterial); + } + + public void Update() + { + } + + void FourTapCone(RenderTexture source, RenderTexture dest, int iteration) + { + float off = blurSize * iteration + 0.5f; + Graphics.BlitMultiTap(source, dest, _blitMaterial, + new Vector2(-off, -off), + new Vector2(-off, off), + new Vector2(off, off), + new Vector2(off, -off) + ); + } + + void DownSample4x(RenderTexture source, RenderTexture dest) + { + float off = 1.0f; + Graphics.BlitMultiTap(source, dest, _blitMaterial, + new Vector2(off, off), + new Vector2(-off, off), + new Vector2(off, off), + new Vector2(off, -off) + ); + } + + void OnRenderImage() + { + if (blurSize < 0.01) + return; + + RenderTexture sourceTexture = (RenderTexture)_target.paintingGraphics.texture.nativeTexture; + int rtW = sourceTexture.width / 8; + int rtH = sourceTexture.height / 8; + RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0); + + DownSample4x(sourceTexture, buffer); + + for (int i = 0; i < 2; i++) + { + RenderTexture buffer2 = RenderTexture.GetTemporary(rtW, rtH, 0); + FourTapCone(buffer, buffer2, i); + RenderTexture.ReleaseTemporary(buffer); + buffer = buffer2; + } + Graphics.Blit(buffer, sourceTexture); + + RenderTexture.ReleaseTemporary(buffer); + } + } +} diff --git a/Assets/Scripts/Filter/BlurFilter.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/BlurFilter.cs.meta similarity index 100% rename from Assets/Scripts/Filter/BlurFilter.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/BlurFilter.cs.meta diff --git a/Assets/Scripts/Filter/ColorFilter.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/ColorFilter.cs similarity index 97% rename from Assets/Scripts/Filter/ColorFilter.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/ColorFilter.cs index 99607e5e..c48bf2e3 100644 --- a/Assets/Scripts/Filter/ColorFilter.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/ColorFilter.cs @@ -1,238 +1,238 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class ColorFilter : IFilter - { - // Most of the color transformation math was taken from the excellent ColorMatrixFilter class in Starling Framework - - DisplayObject _target; - float[] _matrix; - - const float LUMA_R = 0.299f; - const float LUMA_G = 0.587f; - const float LUMA_B = 0.114f; - - static float[] IDENTITY = new float[] { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; - static float[] tmp = new float[20]; - - public ColorFilter() - { - _matrix = new float[20]; - Array.Copy(IDENTITY, _matrix, _matrix.Length); - } - - public DisplayObject target - { - get { return _target; } - set - { - _target = value; - - //这里做一个优化,如果对象是图片或者动画,则通过直接修改目标的材质完成滤镜功能 - if ((_target is Image) || (_target is MovieClip)) - _target.graphics.ToggleKeyword("COLOR_FILTER", true); - else //否则通过绘画模式,需要建立一张RT,所以会有一定消耗 - { - _target.EnterPaintingMode(1, null); - _target.paintingGraphics.ToggleKeyword("COLOR_FILTER", true); - } - - UpdateMatrix(); - } - } - - public void Dispose() - { - if (!_target.isDisposed) - { - if ((_target is Image) || (_target is MovieClip)) - _target.graphics.ToggleKeyword("COLOR_FILTER", false); - else - { - _target.paintingGraphics.ToggleKeyword("COLOR_FILTER", false); - _target.LeavePaintingMode(1); - } - } - - _target = null; - } - - public void Update() - { - } - - public void Invert() - { - _ConcatValues(0, -1, 0, 0, 0, 1); - _ConcatValues(1, 0, -1, 0, 0, 1); - _ConcatValues(2, 0, 0, -1, 0, 1); - _ConcatValues(3, 0, 0, 0, 1, 0); - } - - /// - /// Changes the saturation. Typical values are in the range (-1, 1). - /// Values above zero will raise, values below zero will reduce the saturation. - /// '-1' will produce a grayscale image. - /// - /// - public void AdjustSaturation(float sat) - { - sat += 1; - - float invSat = 1 - sat; - float invLumR = invSat * LUMA_R; - float invLumG = invSat * LUMA_G; - float invLumB = invSat * LUMA_B; - - _ConcatValues(0, (invLumR + sat), invLumG, invLumB, 0, 0); - _ConcatValues(1, invLumR, (invLumG + sat), invLumB, 0, 0); - _ConcatValues(2, invLumR, invLumG, (invLumB + sat), 0, 0); - _ConcatValues(3, 0, 0, 0, 1, 0); - } - - /// - /// Changes the contrast. Typical values are in the range (-1, 1). - /// Values above zero will raise, values below zero will reduce the contrast. - /// - /// - public void AdjustContrast(float value) - { - float s = value + 1; - float o = 128f / 255 * (1 - s); - - _ConcatValues(0, s, 0, 0, 0, o); - _ConcatValues(1, 0, s, 0, 0, o); - _ConcatValues(2, 0, 0, s, 0, o); - _ConcatValues(3, 0, 0, 0, 1, 0); - } - - /// - /// Changes the brightness. Typical values are in the range (-1, 1). - /// Values above zero will make the image brighter, values below zero will make it darker. - /// - /// - public void AdjustBrightness(float value) - { - _ConcatValues(0, 1, 0, 0, 0, value); - _ConcatValues(1, 0, 1, 0, 0, value); - _ConcatValues(2, 0, 0, 1, 0, value); - _ConcatValues(3, 0, 0, 0, 1, 0); - } - - /// - ///Changes the hue of the image. Typical values are in the range (-1, 1). - /// - /// - public void AdjustHue(float value) - { - value *= Mathf.PI; - - float cos = Mathf.Cos(value); - float sin = Mathf.Sin(value); - - _ConcatValues(0, ((LUMA_R + (cos * (1 - LUMA_R))) + (sin * -(LUMA_R))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * -(LUMA_G))), ((LUMA_B + (cos * -(LUMA_B))) + (sin * (1 - LUMA_B))), 0, 0); - _ConcatValues(1, ((LUMA_R + (cos * -(LUMA_R))) + (sin * 0.143f)), ((LUMA_G + (cos * (1 - LUMA_G))) + (sin * 0.14f)), ((LUMA_B + (cos * -(LUMA_B))) + (sin * -0.283f)), 0, 0); - _ConcatValues(2, ((LUMA_R + (cos * -(LUMA_R))) + (sin * -((1 - LUMA_R)))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * LUMA_G)), ((LUMA_B + (cos * (1 - LUMA_B))) + (sin * LUMA_B)), 0, 0); - _ConcatValues(3, 0, 0, 0, 1, 0); - } - - /// - /// Tints the image in a certain color, analog to what can be done in Adobe Animate. - /// - /// the RGB color with which the image should be tinted. - /// the intensity with which tinting should be applied. Range (0, 1). - public void Tint(Color color, float amount = 1.0f) - { - float q = 1 - amount; - - float rA = amount * color.r; - float gA = amount * color.g; - float bA = amount * color.b; - - _ConcatValues(0, q + rA * LUMA_R, rA * LUMA_G, rA * LUMA_B, 0, 0); - _ConcatValues(1, gA * LUMA_R, q + gA * LUMA_G, gA * LUMA_B, 0, 0); - _ConcatValues(2, bA * LUMA_R, bA * LUMA_G, q + bA * LUMA_B, 0, 0); - _ConcatValues(3, 0, 0, 0, 1, 0); - } - - /// - /// Changes the filter matrix back to the identity matrix - /// - public void Reset() - { - Array.Copy(IDENTITY, _matrix, _matrix.Length); - - UpdateMatrix(); - } - - void _ConcatValues(int index, float f0, float f1, float f2, float f3, float f4) - { - int i = index * 5; - for (int x = 0; x < 5; ++x) - { - tmp[i + x] = f0 * _matrix[x] + f1 * _matrix[x + 5] + f2 * _matrix[x + 10] + f3 * _matrix[x + 15] + (x == 4 ? f4 : 0); - } - - if (index == 3) - { - Array.Copy(tmp, _matrix, tmp.Length); - - UpdateMatrix(); - } - } - - /// - /// - /// - /// - public void ConcatValues(params float[] values) - { - int i = 0; - - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 5; ++x) - { - tmp[i + x] = values[i] * _matrix[x] + - values[i + 1] * _matrix[x + 5] + - values[i + 2] * _matrix[x + 10] + - values[i + 3] * _matrix[x + 15] + - (x == 4 ? values[i + 4] : 0); - } - i += 5; - } - Array.Copy(tmp, _matrix, tmp.Length); - - UpdateMatrix(); - } - - void UpdateMatrix() - { - if (_target == null) - return; - - Matrix4x4 matrix = new Matrix4x4(); - matrix.SetRow(0, new Vector4(_matrix[0], _matrix[1], _matrix[2], _matrix[3])); - matrix.SetRow(1, new Vector4(_matrix[5], _matrix[6], _matrix[7], _matrix[8])); - matrix.SetRow(2, new Vector4(_matrix[10], _matrix[11], _matrix[12], _matrix[13])); - matrix.SetRow(3, new Vector4(_matrix[15], _matrix[16], _matrix[17], _matrix[18])); - - Vector4 offset = new Vector4(_matrix[4], _matrix[9], _matrix[14], _matrix[19]); - - MaterialPropertyBlock block; - if ((_target is Image) || (_target is MovieClip)) - block = _target.graphics.materialPropertyBlock; - else - block = _target.paintingGraphics.materialPropertyBlock; - - block.SetMatrix(ShaderConfig.ID_ColorMatrix, matrix); - block.SetVector(ShaderConfig.ID_ColorOffset, offset); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class ColorFilter : IFilter + { + // Most of the color transformation math was taken from the excellent ColorMatrixFilter class in Starling Framework + + DisplayObject _target; + float[] _matrix; + + const float LUMA_R = 0.299f; + const float LUMA_G = 0.587f; + const float LUMA_B = 0.114f; + + static float[] IDENTITY = new float[] { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; + static float[] tmp = new float[20]; + + public ColorFilter() + { + _matrix = new float[20]; + Array.Copy(IDENTITY, _matrix, _matrix.Length); + } + + public DisplayObject target + { + get { return _target; } + set + { + _target = value; + + //这里做一个优化,如果对象是图片或者动画,则通过直接修改目标的材质完成滤镜功能 + if ((_target is Image) || (_target is MovieClip)) + _target.graphics.ToggleKeyword("COLOR_FILTER", true); + else //否则通过绘画模式,需要建立一张RT,所以会有一定消耗 + { + _target.EnterPaintingMode(1, null); + _target.paintingGraphics.ToggleKeyword("COLOR_FILTER", true); + } + + UpdateMatrix(); + } + } + + public void Dispose() + { + if (!_target.isDisposed) + { + if ((_target is Image) || (_target is MovieClip)) + _target.graphics.ToggleKeyword("COLOR_FILTER", false); + else + { + _target.paintingGraphics.ToggleKeyword("COLOR_FILTER", false); + _target.LeavePaintingMode(1); + } + } + + _target = null; + } + + public void Update() + { + } + + public void Invert() + { + _ConcatValues(0, -1, 0, 0, 0, 1); + _ConcatValues(1, 0, -1, 0, 0, 1); + _ConcatValues(2, 0, 0, -1, 0, 1); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the saturation. Typical values are in the range (-1, 1). + /// Values above zero will raise, values below zero will reduce the saturation. + /// '-1' will produce a grayscale image. + /// + /// + public void AdjustSaturation(float sat) + { + sat += 1; + + float invSat = 1 - sat; + float invLumR = invSat * LUMA_R; + float invLumG = invSat * LUMA_G; + float invLumB = invSat * LUMA_B; + + _ConcatValues(0, (invLumR + sat), invLumG, invLumB, 0, 0); + _ConcatValues(1, invLumR, (invLumG + sat), invLumB, 0, 0); + _ConcatValues(2, invLumR, invLumG, (invLumB + sat), 0, 0); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the contrast. Typical values are in the range (-1, 1). + /// Values above zero will raise, values below zero will reduce the contrast. + /// + /// + public void AdjustContrast(float value) + { + float s = value + 1; + float o = 128f / 255 * (1 - s); + + _ConcatValues(0, s, 0, 0, 0, o); + _ConcatValues(1, 0, s, 0, 0, o); + _ConcatValues(2, 0, 0, s, 0, o); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the brightness. Typical values are in the range (-1, 1). + /// Values above zero will make the image brighter, values below zero will make it darker. + /// + /// + public void AdjustBrightness(float value) + { + _ConcatValues(0, 1, 0, 0, 0, value); + _ConcatValues(1, 0, 1, 0, 0, value); + _ConcatValues(2, 0, 0, 1, 0, value); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + ///Changes the hue of the image. Typical values are in the range (-1, 1). + /// + /// + public void AdjustHue(float value) + { + value *= Mathf.PI; + + float cos = Mathf.Cos(value); + float sin = Mathf.Sin(value); + + _ConcatValues(0, ((LUMA_R + (cos * (1 - LUMA_R))) + (sin * -(LUMA_R))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * -(LUMA_G))), ((LUMA_B + (cos * -(LUMA_B))) + (sin * (1 - LUMA_B))), 0, 0); + _ConcatValues(1, ((LUMA_R + (cos * -(LUMA_R))) + (sin * 0.143f)), ((LUMA_G + (cos * (1 - LUMA_G))) + (sin * 0.14f)), ((LUMA_B + (cos * -(LUMA_B))) + (sin * -0.283f)), 0, 0); + _ConcatValues(2, ((LUMA_R + (cos * -(LUMA_R))) + (sin * -((1 - LUMA_R)))), ((LUMA_G + (cos * -(LUMA_G))) + (sin * LUMA_G)), ((LUMA_B + (cos * (1 - LUMA_B))) + (sin * LUMA_B)), 0, 0); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Tints the image in a certain color, analog to what can be done in Adobe Animate. + /// + /// the RGB color with which the image should be tinted. + /// the intensity with which tinting should be applied. Range (0, 1). + public void Tint(Color color, float amount = 1.0f) + { + float q = 1 - amount; + + float rA = amount * color.r; + float gA = amount * color.g; + float bA = amount * color.b; + + _ConcatValues(0, q + rA * LUMA_R, rA * LUMA_G, rA * LUMA_B, 0, 0); + _ConcatValues(1, gA * LUMA_R, q + gA * LUMA_G, gA * LUMA_B, 0, 0); + _ConcatValues(2, bA * LUMA_R, bA * LUMA_G, q + bA * LUMA_B, 0, 0); + _ConcatValues(3, 0, 0, 0, 1, 0); + } + + /// + /// Changes the filter matrix back to the identity matrix + /// + public void Reset() + { + Array.Copy(IDENTITY, _matrix, _matrix.Length); + + UpdateMatrix(); + } + + void _ConcatValues(int index, float f0, float f1, float f2, float f3, float f4) + { + int i = index * 5; + for (int x = 0; x < 5; ++x) + { + tmp[i + x] = f0 * _matrix[x] + f1 * _matrix[x + 5] + f2 * _matrix[x + 10] + f3 * _matrix[x + 15] + (x == 4 ? f4 : 0); + } + + if (index == 3) + { + Array.Copy(tmp, _matrix, tmp.Length); + + UpdateMatrix(); + } + } + + /// + /// + /// + /// + public void ConcatValues(params float[] values) + { + int i = 0; + + for (int y = 0; y < 4; ++y) + { + for (int x = 0; x < 5; ++x) + { + tmp[i + x] = values[i] * _matrix[x] + + values[i + 1] * _matrix[x + 5] + + values[i + 2] * _matrix[x + 10] + + values[i + 3] * _matrix[x + 15] + + (x == 4 ? values[i + 4] : 0); + } + i += 5; + } + Array.Copy(tmp, _matrix, tmp.Length); + + UpdateMatrix(); + } + + void UpdateMatrix() + { + if (_target == null) + return; + + Matrix4x4 matrix = new Matrix4x4(); + matrix.SetRow(0, new Vector4(_matrix[0], _matrix[1], _matrix[2], _matrix[3])); + matrix.SetRow(1, new Vector4(_matrix[5], _matrix[6], _matrix[7], _matrix[8])); + matrix.SetRow(2, new Vector4(_matrix[10], _matrix[11], _matrix[12], _matrix[13])); + matrix.SetRow(3, new Vector4(_matrix[15], _matrix[16], _matrix[17], _matrix[18])); + + Vector4 offset = new Vector4(_matrix[4], _matrix[9], _matrix[14], _matrix[19]); + + MaterialPropertyBlock block; + if ((_target is Image) || (_target is MovieClip)) + block = _target.graphics.materialPropertyBlock; + else + block = _target.paintingGraphics.materialPropertyBlock; + + block.SetMatrix(ShaderConfig.ID_ColorMatrix, matrix); + block.SetVector(ShaderConfig.ID_ColorOffset, offset); + } + } +} diff --git a/Assets/Scripts/Filter/ColorFilter.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/ColorFilter.cs.meta similarity index 100% rename from Assets/Scripts/Filter/ColorFilter.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/ColorFilter.cs.meta diff --git a/Assets/Scripts/Filter/IFilter.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/IFilter.cs similarity index 94% rename from Assets/Scripts/Filter/IFilter.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/IFilter.cs index a4b24d14..f4a6392f 100644 --- a/Assets/Scripts/Filter/IFilter.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/IFilter.cs @@ -1,24 +1,24 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - public interface IFilter - { - /// - /// - /// - DisplayObject target { get; set; } - - /// - /// - /// - void Update(); - - /// - /// - /// - void Dispose(); - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + public interface IFilter + { + /// + /// + /// + DisplayObject target { get; set; } + + /// + /// + /// + void Update(); + + /// + /// + /// + void Dispose(); + } +} diff --git a/Assets/Scripts/Filter/IFilter.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/IFilter.cs.meta similarity index 100% rename from Assets/Scripts/Filter/IFilter.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Filter/IFilter.cs.meta diff --git a/Assets/Scripts/Gesture.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture.meta similarity index 100% rename from Assets/Scripts/Gesture.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture.meta diff --git a/Assets/Scripts/Gesture/LongPressGesture.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/LongPressGesture.cs similarity index 96% rename from Assets/Scripts/Gesture/LongPressGesture.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/LongPressGesture.cs index 58903565..15edb4b9 100644 --- a/Assets/Scripts/Gesture/LongPressGesture.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/LongPressGesture.cs @@ -1,155 +1,155 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// 长按手势。当按下一定时间后(duration),派发onAction,如果once为false,则间隔duration时间持续派发onAction,直到手指释放。 - /// - public class LongPressGesture : EventDispatcher - { - /// - /// - /// - public GObject host { get; private set; } - - /// - /// 当手指按下时派发该事件。 - /// - public EventListener onBegin { get; private set; } - /// - /// 手指离开屏幕时派发该事件。 - /// - public EventListener onEnd { get; private set; } - /// - /// 当手指按下后一段时间后派发该事件。并且在手指离开前按一定周期派发该事件。 - /// - public EventListener onAction { get; private set; } - - /// - /// 第一次派发事件的触发时间。单位秒 - /// - public float trigger; - - /// - /// 派发onAction事件的时间间隔。单位秒。 - /// - public float interval; - - /// - /// 如果为真,则onAction再一次按下释放过程只派发一次。如果为假,则每隔duration时间派发一次。 - /// - public bool once; - - /// - /// 手指按住后,移动超出此半径范围则手势停止。 - /// - public int holdRangeRadius; - - Vector2 _startPoint; - bool _started; - int _touchId; - - public static float TRIGGER = 1.5f; - public static float INTERVAL = 1f; - - public LongPressGesture(GObject host) - { - this.host = host; - trigger = TRIGGER; - interval = INTERVAL; - holdRangeRadius = 50; - Enable(true); - - onBegin = new EventListener(this, "onLongPressBegin"); - onEnd = new EventListener(this, "onLongPressEnd"); - onAction = new EventListener(this, "onLongPressAction"); - } - - public void Dispose() - { - Enable(false); - host = null; - } - - public void Enable(bool value) - { - if (value) - { - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Add(__touchBegin); - Stage.inst.onTouchEnd.Add(__touchEnd); - } - else - { - host.onTouchBegin.Add(__touchBegin); - host.onTouchEnd.Add(__touchEnd); - } - } - else - { - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Remove(__touchBegin); - Stage.inst.onTouchEnd.Remove(__touchEnd); - } - else - { - host.onTouchBegin.Remove(__touchBegin); - host.onTouchEnd.Remove(__touchEnd); - } - Timers.inst.Remove(__timer); - } - } - - public void Cancel() - { - Timers.inst.Remove(__timer); - _started = false; - } - - void __touchBegin(EventContext context) - { - InputEvent evt = context.inputEvent; - _startPoint = host.GlobalToLocal(new Vector2(evt.x, evt.y)); - _started = false; - _touchId = evt.touchId; - - Timers.inst.Add(trigger, 1, __timer); - context.CaptureTouch(); - } - - void __timer(object param) - { - Vector2 pt = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touchId)); - if (Mathf.Pow(pt.x - _startPoint.x, 2) + Mathf.Pow(pt.y - _startPoint.y, 2) > Mathf.Pow(holdRangeRadius, 2)) - { - Timers.inst.Remove(__timer); - return; - } - if (!_started) - { - _started = true; - onBegin.Call(); - - if (!once) - Timers.inst.Add(interval, 0, __timer); - } - - onAction.Call(); - } - - void __touchEnd(EventContext context) - { - Timers.inst.Remove(__timer); - - if (_started) - { - _started = false; - onEnd.Call(); - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 长按手势。当按下一定时间后(duration),派发onAction,如果once为false,则间隔duration时间持续派发onAction,直到手指释放。 + /// + public class LongPressGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当手指按下时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 当手指按下后一段时间后派发该事件。并且在手指离开前按一定周期派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 第一次派发事件的触发时间。单位秒 + /// + public float trigger; + + /// + /// 派发onAction事件的时间间隔。单位秒。 + /// + public float interval; + + /// + /// 如果为真,则onAction再一次按下释放过程只派发一次。如果为假,则每隔duration时间派发一次。 + /// + public bool once; + + /// + /// 手指按住后,移动超出此半径范围则手势停止。 + /// + public int holdRangeRadius; + + Vector2 _startPoint; + bool _started; + int _touchId; + + public static float TRIGGER = 1.5f; + public static float INTERVAL = 1f; + + public LongPressGesture(GObject host) + { + this.host = host; + trigger = TRIGGER; + interval = INTERVAL; + holdRangeRadius = 50; + Enable(true); + + onBegin = new EventListener(this, "onLongPressBegin"); + onEnd = new EventListener(this, "onLongPressEnd"); + onAction = new EventListener(this, "onLongPressAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchEnd.Remove(__touchEnd); + } + Timers.inst.Remove(__timer); + } + } + + public void Cancel() + { + Timers.inst.Remove(__timer); + _started = false; + } + + void __touchBegin(EventContext context) + { + InputEvent evt = context.inputEvent; + _startPoint = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + _started = false; + _touchId = evt.touchId; + + Timers.inst.Add(trigger, 1, __timer); + context.CaptureTouch(); + } + + void __timer(object param) + { + Vector2 pt = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touchId)); + if (Mathf.Pow(pt.x - _startPoint.x, 2) + Mathf.Pow(pt.y - _startPoint.y, 2) > Mathf.Pow(holdRangeRadius, 2)) + { + Timers.inst.Remove(__timer); + return; + } + if (!_started) + { + _started = true; + onBegin.Call(); + + if (!once) + Timers.inst.Add(interval, 0, __timer); + } + + onAction.Call(); + } + + void __touchEnd(EventContext context) + { + Timers.inst.Remove(__timer); + + if (_started) + { + _started = false; + onEnd.Call(); + } + } + } +} diff --git a/Assets/Scripts/Gesture/LongPressGesture.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/LongPressGesture.cs.meta similarity index 100% rename from Assets/Scripts/Gesture/LongPressGesture.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/LongPressGesture.cs.meta diff --git a/Assets/Scripts/Gesture/PinchGesture.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/PinchGesture.cs similarity index 96% rename from Assets/Scripts/Gesture/PinchGesture.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/PinchGesture.cs index 1f6a064e..53cddc9b 100644 --- a/Assets/Scripts/Gesture/PinchGesture.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/PinchGesture.cs @@ -1,156 +1,156 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// 两个指头捏或者放的手势。 - /// - public class PinchGesture : EventDispatcher - { - /// - /// - /// - public GObject host { get; private set; } - - /// - /// 当两个手指开始呈捏手势时派发该事件。 - /// - public EventListener onBegin { get; private set; } - /// - /// 当其中一个手指离开屏幕时派发该事件。 - /// - public EventListener onEnd { get; private set; } - /// - /// 当手势动作时派发该事件。 - /// - public EventListener onAction { get; private set; } - - /// - /// 总共缩放的量。 - /// - public float scale; - - /// - /// 从上次通知后的改变量。 - /// - public float delta; - - float _startDistance; - float _lastScale; - int[] _touches; - bool _started; - bool _touchBegan; - - public PinchGesture(GObject host) - { - this.host = host; - Enable(true); - - _touches = new int[2]; - - onBegin = new EventListener(this, "onPinchBegin"); - onEnd = new EventListener(this, "onPinchEnd"); - onAction = new EventListener(this, "onPinchAction"); - } - - public void Dispose() - { - Enable(false); - host = null; - } - - public void Enable(bool value) - { - if (value) - { - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Add(__touchBegin); - Stage.inst.onTouchMove.Add(__touchMove); - Stage.inst.onTouchEnd.Add(__touchEnd); - } - else - { - host.onTouchBegin.Add(__touchBegin); - host.onTouchMove.Add(__touchMove); - host.onTouchEnd.Add(__touchEnd); - } - } - else - { - _started = false; - _touchBegan = false; - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Remove(__touchBegin); - Stage.inst.onTouchMove.Remove(__touchMove); - Stage.inst.onTouchEnd.Remove(__touchEnd); - } - else - { - host.onTouchBegin.Remove(__touchBegin); - host.onTouchMove.Remove(__touchMove); - host.onTouchEnd.Remove(__touchEnd); - } - } - } - - void __touchBegin(EventContext context) - { - if (Stage.inst.touchCount == 2) - { - if (!_started && !_touchBegan) - { - _touchBegan = true; - Stage.inst.GetAllTouch(_touches); - Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); - Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); - _startDistance = Vector2.Distance(pt1, pt2); - - context.CaptureTouch(); - } - } - } - - void __touchMove(EventContext context) - { - if (!_touchBegan || Stage.inst.touchCount != 2) - return; - - InputEvent evt = context.inputEvent; - Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); - Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); - float dist = Vector2.Distance(pt1, pt2); - - if (!_started && Mathf.Abs(dist - _startDistance) > UIConfig.touchDragSensitivity) - { - _started = true; - scale = 1; - _lastScale = 1; - - onBegin.Call(evt); - } - - if (_started) - { - float ss = dist / _startDistance; - delta = ss - _lastScale; - _lastScale = ss; - this.scale += delta; - onAction.Call(evt); - } - } - - void __touchEnd(EventContext context) - { - _touchBegan = false; - if (_started) - { - _started = false; - onEnd.Call(context.inputEvent); - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 两个指头捏或者放的手势。 + /// + public class PinchGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当两个手指开始呈捏手势时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 当其中一个手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 当手势动作时派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 总共缩放的量。 + /// + public float scale; + + /// + /// 从上次通知后的改变量。 + /// + public float delta; + + float _startDistance; + float _lastScale; + int[] _touches; + bool _started; + bool _touchBegan; + + public PinchGesture(GObject host) + { + this.host = host; + Enable(true); + + _touches = new int[2]; + + onBegin = new EventListener(this, "onPinchBegin"); + onEnd = new EventListener(this, "onPinchEnd"); + onAction = new EventListener(this, "onPinchAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchMove.Add(__touchMove); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchMove.Add(__touchMove); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + _started = false; + _touchBegan = false; + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchMove.Remove(__touchMove); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchMove.Remove(__touchMove); + host.onTouchEnd.Remove(__touchEnd); + } + } + } + + void __touchBegin(EventContext context) + { + if (Stage.inst.touchCount == 2) + { + if (!_started && !_touchBegan) + { + _touchBegan = true; + Stage.inst.GetAllTouch(_touches); + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + _startDistance = Vector2.Distance(pt1, pt2); + + context.CaptureTouch(); + } + } + } + + void __touchMove(EventContext context) + { + if (!_touchBegan || Stage.inst.touchCount != 2) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + float dist = Vector2.Distance(pt1, pt2); + + if (!_started && Mathf.Abs(dist - _startDistance) > UIConfig.touchDragSensitivity) + { + _started = true; + scale = 1; + _lastScale = 1; + + onBegin.Call(evt); + } + + if (_started) + { + float ss = dist / _startDistance; + delta = ss - _lastScale; + _lastScale = ss; + this.scale += delta; + onAction.Call(evt); + } + } + + void __touchEnd(EventContext context) + { + _touchBegan = false; + if (_started) + { + _started = false; + onEnd.Call(context.inputEvent); + } + } + } +} diff --git a/Assets/Scripts/Gesture/PinchGesture.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/PinchGesture.cs.meta similarity index 100% rename from Assets/Scripts/Gesture/PinchGesture.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/PinchGesture.cs.meta diff --git a/Assets/Scripts/Gesture/RotationGesture.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/RotationGesture.cs similarity index 96% rename from Assets/Scripts/Gesture/RotationGesture.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/RotationGesture.cs index 16936f1f..173fe14c 100644 --- a/Assets/Scripts/Gesture/RotationGesture.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/RotationGesture.cs @@ -1,169 +1,169 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// 手指反向操作的手势。 - /// - public class RotationGesture : EventDispatcher - { - /// - /// - /// - public GObject host { get; private set; } - - /// - /// 当两个手指开始呈反向操作时派发该事件。 - /// - public EventListener onBegin { get; private set; } - /// - /// 当其中一个手指离开屏幕时派发该事件。 - /// - public EventListener onEnd { get; private set; } - /// - /// 当手势动作时派发该事件。 - /// - public EventListener onAction { get; private set; } - - /// - /// 总共旋转的角度。 - /// - public float rotation; - - /// - /// 从上次通知后的改变量。 - /// - public float delta; - - /// - /// 是否把变化量强制为整数。默认true。 - /// - public bool snapping; - - Vector2 _startVector; - float _lastRotation; - int[] _touches; - bool _started; - bool _touchBegan; - - public RotationGesture(GObject host) - { - this.host = host; - Enable(true); - - _touches = new int[2]; - snapping = true; - - onBegin = new EventListener(this, "onRotationBegin"); - onEnd = new EventListener(this, "onRotationEnd"); - onAction = new EventListener(this, "onRotationAction"); - } - - public void Dispose() - { - Enable(false); - host = null; - } - - public void Enable(bool value) - { - if (value) - { - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Add(__touchBegin); - Stage.inst.onTouchMove.Add(__touchMove); - Stage.inst.onTouchEnd.Add(__touchEnd); - } - else - { - host.onTouchBegin.Add(__touchBegin); - host.onTouchMove.Add(__touchMove); - host.onTouchEnd.Add(__touchEnd); - } - } - else - { - _started = false; - _touchBegan = false; - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Remove(__touchBegin); - Stage.inst.onTouchMove.Remove(__touchMove); - Stage.inst.onTouchEnd.Remove(__touchEnd); - } - else - { - host.onTouchBegin.Remove(__touchBegin); - host.onTouchMove.Remove(__touchMove); - host.onTouchEnd.Remove(__touchEnd); - } - } - } - - void __touchBegin(EventContext context) - { - if (Stage.inst.touchCount == 2) - { - if (!_started && !_touchBegan) - { - _touchBegan = true; - Stage.inst.GetAllTouch(_touches); - Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); - Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); - _startVector = pt1 - pt2; - - context.CaptureTouch(); - } - } - } - - void __touchMove(EventContext context) - { - if (!_touchBegan || Stage.inst.touchCount != 2) - return; - - InputEvent evt = context.inputEvent; - Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); - Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); - Vector2 vec = pt1 - pt2; - - float rot = Mathf.Rad2Deg * ((Mathf.Atan2(vec.y, vec.x) - Mathf.Atan2(_startVector.y, _startVector.x))); - if (snapping) - { - rot = Mathf.Round(rot); - if (rot == 0) - return; - } - - if (!_started && rot > 5) - { - _started = true; - rotation = 0; - _lastRotation = 0; - - onBegin.Call(evt); - } - - if (_started) - { - delta = rot - _lastRotation; - _lastRotation = rot; - this.rotation += delta; - onAction.Call(evt); - } - } - - void __touchEnd(EventContext context) - { - _touchBegan = false; - if (_started) - { - _started = false; - onEnd.Call(context.inputEvent); - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 手指反向操作的手势。 + /// + public class RotationGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当两个手指开始呈反向操作时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 当其中一个手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 当手势动作时派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 总共旋转的角度。 + /// + public float rotation; + + /// + /// 从上次通知后的改变量。 + /// + public float delta; + + /// + /// 是否把变化量强制为整数。默认true。 + /// + public bool snapping; + + Vector2 _startVector; + float _lastRotation; + int[] _touches; + bool _started; + bool _touchBegan; + + public RotationGesture(GObject host) + { + this.host = host; + Enable(true); + + _touches = new int[2]; + snapping = true; + + onBegin = new EventListener(this, "onRotationBegin"); + onEnd = new EventListener(this, "onRotationEnd"); + onAction = new EventListener(this, "onRotationAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchMove.Add(__touchMove); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchMove.Add(__touchMove); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + _started = false; + _touchBegan = false; + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchMove.Remove(__touchMove); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchMove.Remove(__touchMove); + host.onTouchEnd.Remove(__touchEnd); + } + } + } + + void __touchBegin(EventContext context) + { + if (Stage.inst.touchCount == 2) + { + if (!_started && !_touchBegan) + { + _touchBegan = true; + Stage.inst.GetAllTouch(_touches); + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + _startVector = pt1 - pt2; + + context.CaptureTouch(); + } + } + } + + void __touchMove(EventContext context) + { + if (!_touchBegan || Stage.inst.touchCount != 2) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt1 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[0])); + Vector2 pt2 = host.GlobalToLocal(Stage.inst.GetTouchPosition(_touches[1])); + Vector2 vec = pt1 - pt2; + + float rot = Mathf.Rad2Deg * ((Mathf.Atan2(vec.y, vec.x) - Mathf.Atan2(_startVector.y, _startVector.x))); + if (snapping) + { + rot = Mathf.Round(rot); + if (rot == 0) + return; + } + + if (!_started && rot > 5) + { + _started = true; + rotation = 0; + _lastRotation = 0; + + onBegin.Call(evt); + } + + if (_started) + { + delta = rot - _lastRotation; + _lastRotation = rot; + this.rotation += delta; + onAction.Call(evt); + } + } + + void __touchEnd(EventContext context) + { + _touchBegan = false; + if (_started) + { + _started = false; + onEnd.Call(context.inputEvent); + } + } + } +} diff --git a/Assets/Scripts/Gesture/RotationGesture.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/RotationGesture.cs.meta similarity index 100% rename from Assets/Scripts/Gesture/RotationGesture.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/RotationGesture.cs.meta diff --git a/Assets/Scripts/Gesture/SwipeGesture.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/SwipeGesture.cs similarity index 97% rename from Assets/Scripts/Gesture/SwipeGesture.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/SwipeGesture.cs index 0a80d0a9..96ef55aa 100644 --- a/Assets/Scripts/Gesture/SwipeGesture.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/SwipeGesture.cs @@ -1,228 +1,228 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// 滑动手势。你可以通过onBegin+onMove+onEnd关心整个滑动过程,也可以只使用onAction关注最后的滑动结果。滑动结果包括方向和加速度,可以从position和velocity获得。 - /// 注意onAction仅当滑动超过一定距离(actionDistance)时才触发。 - /// - public class SwipeGesture : EventDispatcher - { - /// - /// - /// - public GObject host { get; private set; } - - /// - /// 当手指开始扫动时派发该事件。 - /// - public EventListener onBegin { get; private set; } - /// - /// 手指离开屏幕时派发该事件。 - /// - public EventListener onEnd { get; private set; } - /// - /// 手指在滑动时派发该事件。 - /// - public EventListener onMove { get; private set; } - /// - /// 当手指从按下到离开经过的距离大于actionDistance时派发该事件。 - /// - public EventListener onAction { get; private set; } - - /// - /// 手指离开时的加速度 - /// - public Vector2 velocity; - - /// - /// 你可以在onBegin事件中设置这个值,那个后续将根据手指移动的距离修改这个值。如果不设置,那position初始为(0,0),反映手指扫过的距离。 - /// - public Vector2 position; - - /// - /// 移动的变化值 - /// - public Vector2 delta; - - /// - /// The min distance to fire onAction event - /// 派发onAction事件的最小距离。如果手指扫过的距离少于此值,onAction不会触发(但onEnd仍然会派发) - /// - public int actionDistance; - - /// - /// 是否把变化量强制为整数。默认true。 - /// - public bool snapping; - - Vector2 _startPoint; - Vector2 _lastPoint; - float _time; - bool _started; - bool _touchBegan; - - public static int ACTION_DISTANCE = 200; - - public SwipeGesture(GObject host) - { - this.host = host; - actionDistance = ACTION_DISTANCE; - snapping = true; - Enable(true); - - onBegin = new EventListener(this, "onSwipeBegin"); - onEnd = new EventListener(this, "onSwipeEnd"); - onMove = new EventListener(this, "onSwipeMove"); - onAction = new EventListener(this, "onnSwipeAction"); - } - - public void Dispose() - { - Enable(false); - host = null; - } - - public void Enable(bool value) - { - if (value) - { - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Add(__touchBegin); - Stage.inst.onTouchMove.Add(__touchMove); - Stage.inst.onTouchEnd.Add(__touchEnd); - } - else - { - host.onTouchBegin.Add(__touchBegin); - host.onTouchMove.Add(__touchMove); - host.onTouchEnd.Add(__touchEnd); - } - } - else - { - _started = false; - _touchBegan = false; - if (host == GRoot.inst) - { - Stage.inst.onTouchBegin.Remove(__touchBegin); - Stage.inst.onTouchMove.Remove(__touchMove); - Stage.inst.onTouchEnd.Remove(__touchEnd); - } - else - { - host.onTouchBegin.Remove(__touchBegin); - host.onTouchMove.Remove(__touchMove); - host.onTouchEnd.Remove(__touchEnd); - } - } - } - - void __touchBegin(EventContext context) - { - if (Stage.inst.touchCount > 1) - { - _touchBegan = false; - if (_started) - { - _started = false; - onEnd.Call(context.inputEvent); - } - return; - } - - InputEvent evt = context.inputEvent; - _startPoint = _lastPoint = host.GlobalToLocal(new Vector2(evt.x, evt.y)); - _lastPoint = _startPoint; - - _time = Time.unscaledTime; - _started = false; - velocity = Vector2.zero; - position = Vector2.zero; - _touchBegan = true; - - context.CaptureTouch(); - } - - void __touchMove(EventContext context) - { - if (!_touchBegan || Stage.inst.touchCount > 1) - return; - - InputEvent evt = context.inputEvent; - Vector2 pt = host.GlobalToLocal(new Vector2(evt.x, evt.y)); - delta = pt - _lastPoint; - if (snapping) - { - delta.x = Mathf.Round(delta.x); - delta.y = Mathf.Round(delta.y); - if (delta.x == 0 && delta.y == 0) - return; - } - - float deltaTime = Time.unscaledDeltaTime; - float elapsed = (Time.unscaledTime - _time) * 60 - 1; - if (elapsed > 1) //速度衰减 - velocity = velocity * Mathf.Pow(0.833f, elapsed); - velocity = Vector3.Lerp(velocity, delta / deltaTime, deltaTime * 10); - _time = Time.unscaledTime; - position += delta; - _lastPoint = pt; - - if (!_started) - { //灵敏度检查,为了和点击区分 - int sensitivity; - if (Stage.touchScreen) - sensitivity = UIConfig.touchDragSensitivity; - else - sensitivity = 5; - - if (Mathf.Abs(delta.x) < sensitivity && Mathf.Abs(delta.y) < sensitivity) - return; - - _started = true; - onBegin.Call(evt); - } - - onMove.Call(evt); - } - - void __touchEnd(EventContext context) - { - _touchBegan = false; - - if (!_started) - return; - - _started = false; - - InputEvent evt = context.inputEvent; - Vector2 pt = host.GlobalToLocal(new Vector2(evt.x, evt.y)); - delta = pt - _lastPoint; - if (snapping) - { - delta.x = Mathf.Round(delta.x); - delta.y = Mathf.Round(delta.y); - } - position += delta; - - //更新速度 - float elapsed = (Time.unscaledTime - _time) * 60 - 1; - if (elapsed > 1) - velocity = velocity * Mathf.Pow(0.833f, elapsed); - if (snapping) - { - velocity.x = Mathf.Round(velocity.x); - velocity.y = Mathf.Round(velocity.y); - } - onEnd.Call(evt); - - pt -= _startPoint; - if (Mathf.Abs(pt.x) > actionDistance || Mathf.Abs(pt.y) > actionDistance) - onAction.Call(evt); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// 滑动手势。你可以通过onBegin+onMove+onEnd关心整个滑动过程,也可以只使用onAction关注最后的滑动结果。滑动结果包括方向和加速度,可以从position和velocity获得。 + /// 注意onAction仅当滑动超过一定距离(actionDistance)时才触发。 + /// + public class SwipeGesture : EventDispatcher + { + /// + /// + /// + public GObject host { get; private set; } + + /// + /// 当手指开始扫动时派发该事件。 + /// + public EventListener onBegin { get; private set; } + /// + /// 手指离开屏幕时派发该事件。 + /// + public EventListener onEnd { get; private set; } + /// + /// 手指在滑动时派发该事件。 + /// + public EventListener onMove { get; private set; } + /// + /// 当手指从按下到离开经过的距离大于actionDistance时派发该事件。 + /// + public EventListener onAction { get; private set; } + + /// + /// 手指离开时的加速度 + /// + public Vector2 velocity; + + /// + /// 你可以在onBegin事件中设置这个值,那个后续将根据手指移动的距离修改这个值。如果不设置,那position初始为(0,0),反映手指扫过的距离。 + /// + public Vector2 position; + + /// + /// 移动的变化值 + /// + public Vector2 delta; + + /// + /// The min distance to fire onAction event + /// 派发onAction事件的最小距离。如果手指扫过的距离少于此值,onAction不会触发(但onEnd仍然会派发) + /// + public int actionDistance; + + /// + /// 是否把变化量强制为整数。默认true。 + /// + public bool snapping; + + Vector2 _startPoint; + Vector2 _lastPoint; + float _time; + bool _started; + bool _touchBegan; + + public static int ACTION_DISTANCE = 200; + + public SwipeGesture(GObject host) + { + this.host = host; + actionDistance = ACTION_DISTANCE; + snapping = true; + Enable(true); + + onBegin = new EventListener(this, "onSwipeBegin"); + onEnd = new EventListener(this, "onSwipeEnd"); + onMove = new EventListener(this, "onSwipeMove"); + onAction = new EventListener(this, "onnSwipeAction"); + } + + public void Dispose() + { + Enable(false); + host = null; + } + + public void Enable(bool value) + { + if (value) + { + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Add(__touchBegin); + Stage.inst.onTouchMove.Add(__touchMove); + Stage.inst.onTouchEnd.Add(__touchEnd); + } + else + { + host.onTouchBegin.Add(__touchBegin); + host.onTouchMove.Add(__touchMove); + host.onTouchEnd.Add(__touchEnd); + } + } + else + { + _started = false; + _touchBegan = false; + if (host == GRoot.inst) + { + Stage.inst.onTouchBegin.Remove(__touchBegin); + Stage.inst.onTouchMove.Remove(__touchMove); + Stage.inst.onTouchEnd.Remove(__touchEnd); + } + else + { + host.onTouchBegin.Remove(__touchBegin); + host.onTouchMove.Remove(__touchMove); + host.onTouchEnd.Remove(__touchEnd); + } + } + } + + void __touchBegin(EventContext context) + { + if (Stage.inst.touchCount > 1) + { + _touchBegan = false; + if (_started) + { + _started = false; + onEnd.Call(context.inputEvent); + } + return; + } + + InputEvent evt = context.inputEvent; + _startPoint = _lastPoint = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + _lastPoint = _startPoint; + + _time = Time.unscaledTime; + _started = false; + velocity = Vector2.zero; + position = Vector2.zero; + _touchBegan = true; + + context.CaptureTouch(); + } + + void __touchMove(EventContext context) + { + if (!_touchBegan || Stage.inst.touchCount > 1) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + delta = pt - _lastPoint; + if (snapping) + { + delta.x = Mathf.Round(delta.x); + delta.y = Mathf.Round(delta.y); + if (delta.x == 0 && delta.y == 0) + return; + } + + float deltaTime = Time.unscaledDeltaTime; + float elapsed = (Time.unscaledTime - _time) * 60 - 1; + if (elapsed > 1) //速度衰减 + velocity = velocity * Mathf.Pow(0.833f, elapsed); + velocity = Vector3.Lerp(velocity, delta / deltaTime, deltaTime * 10); + _time = Time.unscaledTime; + position += delta; + _lastPoint = pt; + + if (!_started) + { //灵敏度检查,为了和点击区分 + int sensitivity; + if (Stage.touchScreen) + sensitivity = UIConfig.touchDragSensitivity; + else + sensitivity = 5; + + if (Mathf.Abs(delta.x) < sensitivity && Mathf.Abs(delta.y) < sensitivity) + return; + + _started = true; + onBegin.Call(evt); + } + + onMove.Call(evt); + } + + void __touchEnd(EventContext context) + { + _touchBegan = false; + + if (!_started) + return; + + _started = false; + + InputEvent evt = context.inputEvent; + Vector2 pt = host.GlobalToLocal(new Vector2(evt.x, evt.y)); + delta = pt - _lastPoint; + if (snapping) + { + delta.x = Mathf.Round(delta.x); + delta.y = Mathf.Round(delta.y); + } + position += delta; + + //更新速度 + float elapsed = (Time.unscaledTime - _time) * 60 - 1; + if (elapsed > 1) + velocity = velocity * Mathf.Pow(0.833f, elapsed); + if (snapping) + { + velocity.x = Mathf.Round(velocity.x); + velocity.y = Mathf.Round(velocity.y); + } + onEnd.Call(evt); + + pt -= _startPoint; + if (Mathf.Abs(pt.x) > actionDistance || Mathf.Abs(pt.y) > actionDistance) + onAction.Call(evt); + } + } +} diff --git a/Assets/Scripts/Gesture/SwipeGesture.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/SwipeGesture.cs.meta similarity index 100% rename from Assets/Scripts/Gesture/SwipeGesture.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Gesture/SwipeGesture.cs.meta diff --git a/Assets/Scripts/Tween.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween.meta similarity index 100% rename from Assets/Scripts/Tween.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween.meta diff --git a/Assets/Scripts/Tween/EaseManager.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseManager.cs similarity index 98% rename from Assets/Scripts/Tween/EaseManager.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseManager.cs index 534143b5..4bd5f154 100644 --- a/Assets/Scripts/Tween/EaseManager.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseManager.cs @@ -1,248 +1,248 @@ -// Author: Daniele Giardini - http://www.demigiant.com -// Created: 2014/07/19 14:11 -// -// License Copyright (c) Daniele Giardini. -// This work is subject to the terms at http://dotween.demigiant.com/license.php -// -// ============================================================= -// Contains Daniele Giardini's C# port of the easing equations created by Robert Penner -// (all easing equations except for Flash, InFlash, OutFlash, InOutFlash, -// which use some parts of Robert Penner's equations but were created by Daniele Giardini) -// http://robertpenner.com/easing, see license below: -// ============================================================= -// -// TERMS OF USE - EASING EQUATIONS -// -// Open source under the BSD License. -// -// Copyright ? 2001 Robert Penner -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// - Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// - Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -// - Neither the name of the author nor the names of contributors may be used to endorse -// or promote products derived from this software without specific prior written permission. -// - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -using System; -using UnityEngine; - -#pragma warning disable 1591 -namespace FairyGUI -{ - public static class EaseManager - { - const float _PiOver2 = Mathf.PI * 0.5f; - const float _TwoPi = Mathf.PI * 2; - - /// - /// Returns a value between 0 and 1 (inclusive) based on the elapsed time and ease selected - /// - public static float Evaluate(EaseType easeType, float time, float duration, - float overshootOrAmplitude = 1.70158f, - float period = 0, - CustomEase customEase = null) - { - if (duration <= 0) - return 1; - - switch (easeType) - { - case EaseType.Linear: - return time / duration; - case EaseType.SineIn: - return -(float)Math.Cos(time / duration * _PiOver2) + 1; - case EaseType.SineOut: - return (float)Math.Sin(time / duration * _PiOver2); - case EaseType.SineInOut: - return -0.5f * ((float)Math.Cos(Mathf.PI * time / duration) - 1); - case EaseType.QuadIn: - return (time /= duration) * time; - case EaseType.QuadOut: - return -(time /= duration) * (time - 2); - case EaseType.QuadInOut: - if ((time /= duration * 0.5f) < 1) return 0.5f * time * time; - return -0.5f * ((--time) * (time - 2) - 1); - case EaseType.CubicIn: - return (time /= duration) * time * time; - case EaseType.CubicOut: - return ((time = time / duration - 1) * time * time + 1); - case EaseType.CubicInOut: - if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time; - return 0.5f * ((time -= 2) * time * time + 2); - case EaseType.QuartIn: - return (time /= duration) * time * time * time; - case EaseType.QuartOut: - return -((time = time / duration - 1) * time * time * time - 1); - case EaseType.QuartInOut: - if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time; - return -0.5f * ((time -= 2) * time * time * time - 2); - case EaseType.QuintIn: - return (time /= duration) * time * time * time * time; - case EaseType.QuintOut: - return ((time = time / duration - 1) * time * time * time * time + 1); - case EaseType.QuintInOut: - if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time * time; - return 0.5f * ((time -= 2) * time * time * time * time + 2); - case EaseType.ExpoIn: - return (time == 0) ? 0 : (float)Math.Pow(2, 10 * (time / duration - 1)); - case EaseType.ExpoOut: - if (time == duration) return 1; - return (-(float)Math.Pow(2, -10 * time / duration) + 1); - case EaseType.ExpoInOut: - if (time == 0) return 0; - if (time == duration) return 1; - if ((time /= duration * 0.5f) < 1) return 0.5f * (float)Math.Pow(2, 10 * (time - 1)); - return 0.5f * (-(float)Math.Pow(2, -10 * --time) + 2); - case EaseType.CircIn: - return -((float)Math.Sqrt(1 - (time /= duration) * time) - 1); - case EaseType.CircOut: - return (float)Math.Sqrt(1 - (time = time / duration - 1) * time); - case EaseType.CircInOut: - if ((time /= duration * 0.5f) < 1) return -0.5f * ((float)Math.Sqrt(1 - time * time) - 1); - return 0.5f * ((float)Math.Sqrt(1 - (time -= 2) * time) + 1); - case EaseType.ElasticIn: - float s0; - if (time == 0) return 0; - if ((time /= duration) == 1) return 1; - if (period == 0) period = duration * 0.3f; - if (overshootOrAmplitude < 1) - { - overshootOrAmplitude = 1; - s0 = period / 4; - } - else s0 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); - return -(overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s0) * _TwoPi / period)); - case EaseType.ElasticOut: - float s1; - if (time == 0) return 0; - if ((time /= duration) == 1) return 1; - if (period == 0) period = duration * 0.3f; - if (overshootOrAmplitude < 1) - { - overshootOrAmplitude = 1; - s1 = period / 4; - } - else s1 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); - return (overshootOrAmplitude * (float)Math.Pow(2, -10 * time) * (float)Math.Sin((time * duration - s1) * _TwoPi / period) + 1); - case EaseType.ElasticInOut: - float s; - if (time == 0) return 0; - if ((time /= duration * 0.5f) == 2) return 1; - if (period == 0) period = duration * (0.3f * 1.5f); - if (overshootOrAmplitude < 1) - { - overshootOrAmplitude = 1; - s = period / 4; - } - else s = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); - if (time < 1) return -0.5f * (overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period)); - return overshootOrAmplitude * (float)Math.Pow(2, -10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period) * 0.5f + 1; - case EaseType.BackIn: - return (time /= duration) * time * ((overshootOrAmplitude + 1) * time - overshootOrAmplitude); - case EaseType.BackOut: - return ((time = time / duration - 1) * time * ((overshootOrAmplitude + 1) * time + overshootOrAmplitude) + 1); - case EaseType.BackInOut: - if ((time /= duration * 0.5f) < 1) return 0.5f * (time * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time - overshootOrAmplitude)); - return 0.5f * ((time -= 2) * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time + overshootOrAmplitude) + 2); - case EaseType.BounceIn: - return Bounce.EaseIn(time, duration); - case EaseType.BounceOut: - return Bounce.EaseOut(time, duration); - case EaseType.BounceInOut: - return Bounce.EaseInOut(time, duration); - - case EaseType.Custom: - return customEase != null ? customEase.Evaluate(time / duration) : (time / duration); - - default: - return -(time /= duration) * (time - 2); - } - } - - /// - /// This class contains a C# port of the easing equations created by Robert Penner (http://robertpenner.com/easing). - /// - static class Bounce - { - /// - /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. - /// - /// - /// Current time (in frames or seconds). - /// - /// - /// Expected easing duration (in frames or seconds). - /// - /// - /// The eased value. - /// - public static float EaseIn(float time, float duration) - { - return 1 - EaseOut(duration - time, duration); - } - - /// - /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. - /// - /// - /// Current time (in frames or seconds). - /// - /// - /// Expected easing duration (in frames or seconds). - /// - /// - /// The eased value. - /// - public static float EaseOut(float time, float duration) - { - if ((time /= duration) < (1 / 2.75f)) - { - return (7.5625f * time * time); - } - if (time < (2 / 2.75f)) - { - return (7.5625f * (time -= (1.5f / 2.75f)) * time + 0.75f); - } - if (time < (2.5f / 2.75f)) - { - return (7.5625f * (time -= (2.25f / 2.75f)) * time + 0.9375f); - } - return (7.5625f * (time -= (2.625f / 2.75f)) * time + 0.984375f); - } - - /// - /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. - /// - /// - /// Current time (in frames or seconds). - /// - /// - /// Expected easing duration (in frames or seconds). - /// - /// - /// The eased value. - /// - public static float EaseInOut(float time, float duration) - { - if (time < duration * 0.5f) - { - return EaseIn(time * 2, duration) * 0.5f; - } - return EaseOut(time * 2 - duration, duration) * 0.5f + 0.5f; - } - } - } +// Author: Daniele Giardini - http://www.demigiant.com +// Created: 2014/07/19 14:11 +// +// License Copyright (c) Daniele Giardini. +// This work is subject to the terms at http://dotween.demigiant.com/license.php +// +// ============================================================= +// Contains Daniele Giardini's C# port of the easing equations created by Robert Penner +// (all easing equations except for Flash, InFlash, OutFlash, InOutFlash, +// which use some parts of Robert Penner's equations but were created by Daniele Giardini) +// http://robertpenner.com/easing, see license below: +// ============================================================= +// +// TERMS OF USE - EASING EQUATIONS +// +// Open source under the BSD License. +// +// Copyright ? 2001 Robert Penner +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +// - Neither the name of the author nor the names of contributors may be used to endorse +// or promote products derived from this software without specific prior written permission. +// - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +using System; +using UnityEngine; + +#pragma warning disable 1591 +namespace FairyGUI +{ + public static class EaseManager + { + const float _PiOver2 = Mathf.PI * 0.5f; + const float _TwoPi = Mathf.PI * 2; + + /// + /// Returns a value between 0 and 1 (inclusive) based on the elapsed time and ease selected + /// + public static float Evaluate(EaseType easeType, float time, float duration, + float overshootOrAmplitude = 1.70158f, + float period = 0, + CustomEase customEase = null) + { + if (duration <= 0) + return 1; + + switch (easeType) + { + case EaseType.Linear: + return time / duration; + case EaseType.SineIn: + return -(float)Math.Cos(time / duration * _PiOver2) + 1; + case EaseType.SineOut: + return (float)Math.Sin(time / duration * _PiOver2); + case EaseType.SineInOut: + return -0.5f * ((float)Math.Cos(Mathf.PI * time / duration) - 1); + case EaseType.QuadIn: + return (time /= duration) * time; + case EaseType.QuadOut: + return -(time /= duration) * (time - 2); + case EaseType.QuadInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time; + return -0.5f * ((--time) * (time - 2) - 1); + case EaseType.CubicIn: + return (time /= duration) * time * time; + case EaseType.CubicOut: + return ((time = time / duration - 1) * time * time + 1); + case EaseType.CubicInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time; + return 0.5f * ((time -= 2) * time * time + 2); + case EaseType.QuartIn: + return (time /= duration) * time * time * time; + case EaseType.QuartOut: + return -((time = time / duration - 1) * time * time * time - 1); + case EaseType.QuartInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time; + return -0.5f * ((time -= 2) * time * time * time - 2); + case EaseType.QuintIn: + return (time /= duration) * time * time * time * time; + case EaseType.QuintOut: + return ((time = time / duration - 1) * time * time * time * time + 1); + case EaseType.QuintInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * time * time * time * time * time; + return 0.5f * ((time -= 2) * time * time * time * time + 2); + case EaseType.ExpoIn: + return (time == 0) ? 0 : (float)Math.Pow(2, 10 * (time / duration - 1)); + case EaseType.ExpoOut: + if (time == duration) return 1; + return (-(float)Math.Pow(2, -10 * time / duration) + 1); + case EaseType.ExpoInOut: + if (time == 0) return 0; + if (time == duration) return 1; + if ((time /= duration * 0.5f) < 1) return 0.5f * (float)Math.Pow(2, 10 * (time - 1)); + return 0.5f * (-(float)Math.Pow(2, -10 * --time) + 2); + case EaseType.CircIn: + return -((float)Math.Sqrt(1 - (time /= duration) * time) - 1); + case EaseType.CircOut: + return (float)Math.Sqrt(1 - (time = time / duration - 1) * time); + case EaseType.CircInOut: + if ((time /= duration * 0.5f) < 1) return -0.5f * ((float)Math.Sqrt(1 - time * time) - 1); + return 0.5f * ((float)Math.Sqrt(1 - (time -= 2) * time) + 1); + case EaseType.ElasticIn: + float s0; + if (time == 0) return 0; + if ((time /= duration) == 1) return 1; + if (period == 0) period = duration * 0.3f; + if (overshootOrAmplitude < 1) + { + overshootOrAmplitude = 1; + s0 = period / 4; + } + else s0 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); + return -(overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s0) * _TwoPi / period)); + case EaseType.ElasticOut: + float s1; + if (time == 0) return 0; + if ((time /= duration) == 1) return 1; + if (period == 0) period = duration * 0.3f; + if (overshootOrAmplitude < 1) + { + overshootOrAmplitude = 1; + s1 = period / 4; + } + else s1 = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); + return (overshootOrAmplitude * (float)Math.Pow(2, -10 * time) * (float)Math.Sin((time * duration - s1) * _TwoPi / period) + 1); + case EaseType.ElasticInOut: + float s; + if (time == 0) return 0; + if ((time /= duration * 0.5f) == 2) return 1; + if (period == 0) period = duration * (0.3f * 1.5f); + if (overshootOrAmplitude < 1) + { + overshootOrAmplitude = 1; + s = period / 4; + } + else s = period / _TwoPi * (float)Math.Asin(1 / overshootOrAmplitude); + if (time < 1) return -0.5f * (overshootOrAmplitude * (float)Math.Pow(2, 10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period)); + return overshootOrAmplitude * (float)Math.Pow(2, -10 * (time -= 1)) * (float)Math.Sin((time * duration - s) * _TwoPi / period) * 0.5f + 1; + case EaseType.BackIn: + return (time /= duration) * time * ((overshootOrAmplitude + 1) * time - overshootOrAmplitude); + case EaseType.BackOut: + return ((time = time / duration - 1) * time * ((overshootOrAmplitude + 1) * time + overshootOrAmplitude) + 1); + case EaseType.BackInOut: + if ((time /= duration * 0.5f) < 1) return 0.5f * (time * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time - overshootOrAmplitude)); + return 0.5f * ((time -= 2) * time * (((overshootOrAmplitude *= (1.525f)) + 1) * time + overshootOrAmplitude) + 2); + case EaseType.BounceIn: + return Bounce.EaseIn(time, duration); + case EaseType.BounceOut: + return Bounce.EaseOut(time, duration); + case EaseType.BounceInOut: + return Bounce.EaseInOut(time, duration); + + case EaseType.Custom: + return customEase != null ? customEase.Evaluate(time / duration) : (time / duration); + + default: + return -(time /= duration) * (time - 2); + } + } + + /// + /// This class contains a C# port of the easing equations created by Robert Penner (http://robertpenner.com/easing). + /// + static class Bounce + { + /// + /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. + /// + /// + /// Current time (in frames or seconds). + /// + /// + /// Expected easing duration (in frames or seconds). + /// + /// + /// The eased value. + /// + public static float EaseIn(float time, float duration) + { + return 1 - EaseOut(duration - time, duration); + } + + /// + /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. + /// + /// + /// Current time (in frames or seconds). + /// + /// + /// Expected easing duration (in frames or seconds). + /// + /// + /// The eased value. + /// + public static float EaseOut(float time, float duration) + { + if ((time /= duration) < (1 / 2.75f)) + { + return (7.5625f * time * time); + } + if (time < (2 / 2.75f)) + { + return (7.5625f * (time -= (1.5f / 2.75f)) * time + 0.75f); + } + if (time < (2.5f / 2.75f)) + { + return (7.5625f * (time -= (2.25f / 2.75f)) * time + 0.9375f); + } + return (7.5625f * (time -= (2.625f / 2.75f)) * time + 0.984375f); + } + + /// + /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. + /// + /// + /// Current time (in frames or seconds). + /// + /// + /// Expected easing duration (in frames or seconds). + /// + /// + /// The eased value. + /// + public static float EaseInOut(float time, float duration) + { + if (time < duration * 0.5f) + { + return EaseIn(time * 2, duration) * 0.5f; + } + return EaseOut(time * 2 - duration, duration) * 0.5f + 0.5f; + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Tween/EaseManager.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseManager.cs.meta similarity index 100% rename from Assets/Scripts/Tween/EaseManager.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseManager.cs.meta diff --git a/Assets/Scripts/Tween/EaseType.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseType.cs similarity index 95% rename from Assets/Scripts/Tween/EaseType.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseType.cs index e7c2b27e..e64c7e01 100644 --- a/Assets/Scripts/Tween/EaseType.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseType.cs @@ -1,141 +1,141 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public enum EaseType - { - Linear, - SineIn, - SineOut, - SineInOut, - QuadIn, - QuadOut, - QuadInOut, - CubicIn, - CubicOut, - CubicInOut, - QuartIn, - QuartOut, - QuartInOut, - QuintIn, - QuintOut, - QuintInOut, - ExpoIn, - ExpoOut, - ExpoInOut, - CircIn, - CircOut, - CircInOut, - ElasticIn, - ElasticOut, - ElasticInOut, - BackIn, - BackOut, - BackInOut, - BounceIn, - BounceOut, - BounceInOut, - Custom - } - - /// - /// - /// - public class CustomEase - { - Vector2[] _points; - int _pointDensity; - - static GPath helperPath = new GPath(); - - /// - /// - /// - /// - public CustomEase(int pointDensity = 200) - { - _points = new Vector2[pointDensity + 1]; - _pointDensity = pointDensity; - } - - /// - /// - /// - /// - public void Create(IEnumerable pathPoints) - { - helperPath.Create(pathPoints); - for (int i = 0; i <= _pointDensity; i++) - { - Vector3 pt = helperPath.GetPointAt(i / (float)_pointDensity); - _points[i] = pt; - } - _points[0] = Vector2.zero; - _points[_pointDensity] = Vector2.one; - - Array.Sort(_points, (Vector2 p1, Vector2 p2) => - { - return p1.x.CompareTo(p2.x); - }); - } - - /// - /// - /// - /// - /// - public float Evaluate(float time) - { - if (time <= 0) - return 0; - else if (time >= 1) - return 1; - - int low = 0; - int high = _pointDensity; - int cur = 0; - while (low != high) - { - cur = low + (int)((high - low) / 2f); - float x = _points[cur].x; - if (time == x) - break; - else if (time > x) - { - if (low == cur) - { - cur = high; - break; - } - low = cur; - } - else - { - if (high == cur) - { - cur = low; - break; - } - high = cur; - } - } - - Vector2 v0 = _points[cur]; - Vector2 v1; - if (cur == _pointDensity) - v1 = Vector2.one; - else - v1 = _points[cur + 1]; - float k = (v1.y - v0.y) / (v1.x - v0.x); - if (float.IsNaN(k)) - k = 0; - - return v0.y + (time - v0.x) * k; - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public enum EaseType + { + Linear, + SineIn, + SineOut, + SineInOut, + QuadIn, + QuadOut, + QuadInOut, + CubicIn, + CubicOut, + CubicInOut, + QuartIn, + QuartOut, + QuartInOut, + QuintIn, + QuintOut, + QuintInOut, + ExpoIn, + ExpoOut, + ExpoInOut, + CircIn, + CircOut, + CircInOut, + ElasticIn, + ElasticOut, + ElasticInOut, + BackIn, + BackOut, + BackInOut, + BounceIn, + BounceOut, + BounceInOut, + Custom + } + + /// + /// + /// + public class CustomEase + { + Vector2[] _points; + int _pointDensity; + + static GPath helperPath = new GPath(); + + /// + /// + /// + /// + public CustomEase(int pointDensity = 200) + { + _points = new Vector2[pointDensity + 1]; + _pointDensity = pointDensity; + } + + /// + /// + /// + /// + public void Create(IEnumerable pathPoints) + { + helperPath.Create(pathPoints); + for (int i = 0; i <= _pointDensity; i++) + { + Vector3 pt = helperPath.GetPointAt(i / (float)_pointDensity); + _points[i] = pt; + } + _points[0] = Vector2.zero; + _points[_pointDensity] = Vector2.one; + + Array.Sort(_points, (Vector2 p1, Vector2 p2) => + { + return p1.x.CompareTo(p2.x); + }); + } + + /// + /// + /// + /// + /// + public float Evaluate(float time) + { + if (time <= 0) + return 0; + else if (time >= 1) + return 1; + + int low = 0; + int high = _pointDensity; + int cur = 0; + while (low != high) + { + cur = low + (int)((high - low) / 2f); + float x = _points[cur].x; + if (time == x) + break; + else if (time > x) + { + if (low == cur) + { + cur = high; + break; + } + low = cur; + } + else + { + if (high == cur) + { + cur = low; + break; + } + high = cur; + } + } + + Vector2 v0 = _points[cur]; + Vector2 v1; + if (cur == _pointDensity) + v1 = Vector2.one; + else + v1 = _points[cur + 1]; + float k = (v1.y - v0.y) / (v1.x - v0.x); + if (float.IsNaN(k)) + k = 0; + + return v0.y + (time - v0.x) * k; + } + } +} diff --git a/Assets/Scripts/Tween/EaseType.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseType.cs.meta similarity index 100% rename from Assets/Scripts/Tween/EaseType.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/EaseType.cs.meta diff --git a/Assets/Scripts/Tween/GPath.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GPath.cs similarity index 96% rename from Assets/Scripts/Tween/GPath.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GPath.cs index 84e9cfe9..daefedfc 100644 --- a/Assets/Scripts/Tween/GPath.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GPath.cs @@ -1,475 +1,475 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - [System.Serializable] - public struct GPathPoint - { - /// - /// - /// - public Vector3 pos; - - /// - /// - /// - public Vector3 control1; - - /// - /// - /// - public Vector3 control2; - - /// - /// - /// - public CurveType curveType; - - /// - /// - /// - public bool smooth; - - /// - /// - /// - public enum CurveType - { - CRSpline, - Bezier, - CubicBezier, - Straight - } - - /// - /// - /// - /// - public GPathPoint(Vector3 pos) - { - this.pos = pos; - this.control1 = Vector3.zero; - this.control2 = Vector3.zero; - this.curveType = CurveType.CRSpline; - this.smooth = true; - } - - /// - /// - /// - /// - /// - public GPathPoint(Vector3 pos, Vector3 control) - { - this.pos = pos; - this.control1 = control; - this.control2 = Vector3.zero; - this.curveType = CurveType.Bezier; - this.smooth = true; - } - - /// - /// - /// - /// - /// - /// - public GPathPoint(Vector3 pos, Vector3 control1, Vector3 control2) - { - this.pos = pos; - this.control1 = control1; - this.control2 = control2; - this.curveType = CurveType.CubicBezier; - this.smooth = true; - } - - /// - /// - /// - /// - /// - public GPathPoint(Vector3 pos, CurveType curveType) - { - this.pos = pos; - this.control1 = Vector3.zero; - this.control2 = Vector3.zero; - this.curveType = curveType; - this.smooth = true; - } - } - - /// - /// - /// - public class GPath - { - protected struct Segment - { - public GPathPoint.CurveType type; - public float length; - public int ptStart; - public int ptCount; - } - - protected List _segments; - protected List _points; - protected float _fullLength; - - static List helperList = new List(); - static List splinePoints = new List(); - - public GPath() - { - _segments = new List(); - _points = new List(); - } - - /// - /// - /// - public float length - { - get { return _fullLength; } - } - - /// - /// - /// - /// - /// - public void Create(GPathPoint pt1, GPathPoint pt2) - { - helperList.Clear(); - helperList.Add(pt1); - helperList.Add(pt2); - Create(helperList); - } - - /// - /// - /// - /// - /// - /// - public void Create(GPathPoint pt1, GPathPoint pt2, GPathPoint pt3) - { - helperList.Clear(); - helperList.Add(pt1); - helperList.Add(pt2); - helperList.Add(pt3); - Create(helperList); - } - - /// - /// - /// - /// - /// - /// - /// - public void Create(GPathPoint pt1, GPathPoint pt2, GPathPoint pt3, GPathPoint pt4) - { - helperList.Clear(); - helperList.Add(pt1); - helperList.Add(pt2); - helperList.Add(pt3); - helperList.Add(pt4); - Create(helperList); - } - - /// - /// - /// - /// - public void Create(IEnumerable points) - { - _segments.Clear(); - _points.Clear(); - splinePoints.Clear(); - _fullLength = 0; - - var et = points.GetEnumerator(); - if (!et.MoveNext()) - return; - - GPathPoint prev = et.Current; - if (prev.curveType == GPathPoint.CurveType.CRSpline) - splinePoints.Add(prev.pos); - - while (et.MoveNext()) - { - GPathPoint current = et.Current; - - if (prev.curveType != GPathPoint.CurveType.CRSpline) - { - Segment seg = new Segment(); - seg.type = prev.curveType; - seg.ptStart = _points.Count; - if (prev.curveType == GPathPoint.CurveType.Straight) - { - seg.ptCount = 2; - _points.Add(prev.pos); - _points.Add(current.pos); - } - else if (prev.curveType == GPathPoint.CurveType.Bezier) - { - seg.ptCount = 3; - _points.Add(prev.pos); - _points.Add(current.pos); - _points.Add(prev.control1); - } - else if (prev.curveType == GPathPoint.CurveType.CubicBezier) - { - seg.ptCount = 4; - _points.Add(prev.pos); - _points.Add(current.pos); - _points.Add(prev.control1); - _points.Add(prev.control2); - } - seg.length = Vector3.Distance(prev.pos, current.pos); - _fullLength += seg.length; - _segments.Add(seg); - } - - if (current.curveType != GPathPoint.CurveType.CRSpline) - { - if (splinePoints.Count > 0) - { - splinePoints.Add(current.pos); - CreateSplineSegment(); - } - } - else - splinePoints.Add(current.pos); - - prev = current; - } - - if (splinePoints.Count > 1) - CreateSplineSegment(); - } - - void CreateSplineSegment() - { - int cnt = splinePoints.Count; - splinePoints.Insert(0, splinePoints[0]); - splinePoints.Add(splinePoints[cnt]); - splinePoints.Add(splinePoints[cnt]); - cnt += 3; - - Segment seg = new Segment(); - seg.type = GPathPoint.CurveType.CRSpline; - seg.ptStart = _points.Count; - seg.ptCount = cnt; - _points.AddRange(splinePoints); - - seg.length = 0; - for (int i = 1; i < cnt; i++) - seg.length += Vector3.Distance(splinePoints[i - 1], splinePoints[i]); - _fullLength += seg.length; - _segments.Add(seg); - splinePoints.Clear(); - } - - /// - /// - /// - public void Clear() - { - _segments.Clear(); - _points.Clear(); - } - - /// - /// - /// - /// - /// - public Vector3 GetPointAt(float t) - { - t = Mathf.Clamp01(t); - int cnt = _segments.Count; - if (cnt == 0) - return Vector3.zero; - - Segment seg; - if (t == 1) - { - seg = _segments[cnt - 1]; - - if (seg.type == GPathPoint.CurveType.Straight) - return Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t); - else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) - return onBezierCurve(seg.ptStart, seg.ptCount, t); - else - return onCRSplineCurve(seg.ptStart, seg.ptCount, t); - } - - float len = t * _fullLength; - Vector3 pt = new Vector3(); - for (int i = 0; i < cnt; i++) - { - seg = _segments[i]; - - len -= seg.length; - if (len < 0) - { - t = 1 + len / seg.length; - - if (seg.type == GPathPoint.CurveType.Straight) - pt = Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t); - else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) - pt = onBezierCurve(seg.ptStart, seg.ptCount, t); - else - pt = onCRSplineCurve(seg.ptStart, seg.ptCount, t); - - break; - } - } - - return pt; - } - - /// - /// - /// - public int segmentCount - { - get { return _segments.Count; } - } - - /// - /// - /// - /// - /// - public float GetSegmentLength(int segmentIndex) - { - return _segments[segmentIndex].length; - } - - /// - /// - /// - /// - /// - /// - /// - /// - public void GetPointsInSegment(int segmentIndex, float t0, float t1, List points, List ts = null, float pointDensity = 0.1f) - { - if (points == null) - points = new List(); - - if (ts != null) - ts.Add(t0); - Segment seg = _segments[segmentIndex]; - if (seg.type == GPathPoint.CurveType.Straight) - { - points.Add(Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t0)); - points.Add(Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t1)); - } - else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) - { - points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t0)); - int SmoothAmount = (int)Mathf.Min(seg.length * pointDensity, 50); - for (int j = 0; j <= SmoothAmount; j++) - { - float t = (float)j / SmoothAmount; - if (t > t0 && t < t1) - { - points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t)); - if (ts != null) - ts.Add(t); - } - } - points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t1)); - } - else - { - points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t0)); - int SmoothAmount = (int)Mathf.Min(seg.length * pointDensity, 50); - for (int j = 0; j <= SmoothAmount; j++) - { - float t = (float)j / SmoothAmount; - if (t > t0 && t < t1) - { - points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t)); - if (ts != null) - ts.Add(t); - } - } - points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t1)); - } - - if (ts != null) - ts.Add(t1); - } - - /// - /// - /// - /// - public void GetAllPoints(List points, float pointDensity = 0.1f) - { - int cnt = _segments.Count; - for (int i = 0; i < cnt; i++) - GetPointsInSegment(i, 0, 1, points, null, pointDensity); - } - - /// - /// Catmull rom spline implementation - /// by Stéphane Drouot, laei - http://games.laei.org - /// - /// Actual translation of math gebrish to C# credit is due to - /// Boon Cotter - http://www.booncotter.com/waypoints-catmull-rom-splines/ - /// - /// This takes a list of vector3 (or an array) and gives a function called .onCurve(t) - /// returning a value on a Catmull-Rom spline for 0 <= t <= 1 - /// - Vector3 onCRSplineCurve(int ptStart, int ptCount, float t) - { - int adjustedIndex = Mathf.FloorToInt(t * (ptCount - 4)) + ptStart; //Since the equation works with 4 points, we adjust the starting point depending on t to return a point on the specific segment - - Vector3 result = new Vector3(); - - Vector3 p0 = _points[adjustedIndex]; - Vector3 p1 = _points[adjustedIndex + 1]; - Vector3 p2 = _points[adjustedIndex + 2]; - Vector3 p3 = _points[adjustedIndex + 3]; - - float adjustedT = (t == 1f) ? 1f : Mathf.Repeat(t * (ptCount - 4), 1f); // Then we adjust t to be that value on that new piece of segment... for t == 1f don't use repeat (that would return 0f); - - float t0 = ((-adjustedT + 2f) * adjustedT - 1f) * adjustedT * 0.5f; - float t1 = (((3f * adjustedT - 5f) * adjustedT) * adjustedT + 2f) * 0.5f; - float t2 = ((-3f * adjustedT + 4f) * adjustedT + 1f) * adjustedT * 0.5f; - float t3 = ((adjustedT - 1f) * adjustedT * adjustedT) * 0.5f; - - result.x = p0.x * t0 + p1.x * t1 + p2.x * t2 + p3.x * t3; - result.y = p0.y * t0 + p1.y * t1 + p2.y * t2 + p3.y * t3; - result.z = p0.z * t0 + p1.z * t1 + p2.z * t2 + p3.z * t3; - - return result; - } - - Vector3 onBezierCurve(int ptStart, int ptCount, float t) - { - float t2 = 1f - t; - Vector3 p0 = _points[ptStart]; - Vector3 p1 = _points[ptStart + 1]; - Vector3 cp0 = _points[ptStart + 2]; - - if (ptCount == 4) - { - Vector3 cp1 = _points[ptStart + 3]; - return t2 * t2 * t2 * p0 + 3f * t2 * t2 * t * cp0 + 3f * t2 * t * t * cp1 + t * t * t * p1; - } - else - return t2 * t2 * p0 + 2f * t2 * t * cp0 + t * t * p1; - } - } +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + [System.Serializable] + public struct GPathPoint + { + /// + /// + /// + public Vector3 pos; + + /// + /// + /// + public Vector3 control1; + + /// + /// + /// + public Vector3 control2; + + /// + /// + /// + public CurveType curveType; + + /// + /// + /// + public bool smooth; + + /// + /// + /// + public enum CurveType + { + CRSpline, + Bezier, + CubicBezier, + Straight + } + + /// + /// + /// + /// + public GPathPoint(Vector3 pos) + { + this.pos = pos; + this.control1 = Vector3.zero; + this.control2 = Vector3.zero; + this.curveType = CurveType.CRSpline; + this.smooth = true; + } + + /// + /// + /// + /// + /// + public GPathPoint(Vector3 pos, Vector3 control) + { + this.pos = pos; + this.control1 = control; + this.control2 = Vector3.zero; + this.curveType = CurveType.Bezier; + this.smooth = true; + } + + /// + /// + /// + /// + /// + /// + public GPathPoint(Vector3 pos, Vector3 control1, Vector3 control2) + { + this.pos = pos; + this.control1 = control1; + this.control2 = control2; + this.curveType = CurveType.CubicBezier; + this.smooth = true; + } + + /// + /// + /// + /// + /// + public GPathPoint(Vector3 pos, CurveType curveType) + { + this.pos = pos; + this.control1 = Vector3.zero; + this.control2 = Vector3.zero; + this.curveType = curveType; + this.smooth = true; + } + } + + /// + /// + /// + public class GPath + { + protected struct Segment + { + public GPathPoint.CurveType type; + public float length; + public int ptStart; + public int ptCount; + } + + protected List _segments; + protected List _points; + protected float _fullLength; + + static List helperList = new List(); + static List splinePoints = new List(); + + public GPath() + { + _segments = new List(); + _points = new List(); + } + + /// + /// + /// + public float length + { + get { return _fullLength; } + } + + /// + /// + /// + /// + /// + public void Create(GPathPoint pt1, GPathPoint pt2) + { + helperList.Clear(); + helperList.Add(pt1); + helperList.Add(pt2); + Create(helperList); + } + + /// + /// + /// + /// + /// + /// + public void Create(GPathPoint pt1, GPathPoint pt2, GPathPoint pt3) + { + helperList.Clear(); + helperList.Add(pt1); + helperList.Add(pt2); + helperList.Add(pt3); + Create(helperList); + } + + /// + /// + /// + /// + /// + /// + /// + public void Create(GPathPoint pt1, GPathPoint pt2, GPathPoint pt3, GPathPoint pt4) + { + helperList.Clear(); + helperList.Add(pt1); + helperList.Add(pt2); + helperList.Add(pt3); + helperList.Add(pt4); + Create(helperList); + } + + /// + /// + /// + /// + public void Create(IEnumerable points) + { + _segments.Clear(); + _points.Clear(); + splinePoints.Clear(); + _fullLength = 0; + + var et = points.GetEnumerator(); + if (!et.MoveNext()) + return; + + GPathPoint prev = et.Current; + if (prev.curveType == GPathPoint.CurveType.CRSpline) + splinePoints.Add(prev.pos); + + while (et.MoveNext()) + { + GPathPoint current = et.Current; + + if (prev.curveType != GPathPoint.CurveType.CRSpline) + { + Segment seg = new Segment(); + seg.type = prev.curveType; + seg.ptStart = _points.Count; + if (prev.curveType == GPathPoint.CurveType.Straight) + { + seg.ptCount = 2; + _points.Add(prev.pos); + _points.Add(current.pos); + } + else if (prev.curveType == GPathPoint.CurveType.Bezier) + { + seg.ptCount = 3; + _points.Add(prev.pos); + _points.Add(current.pos); + _points.Add(prev.control1); + } + else if (prev.curveType == GPathPoint.CurveType.CubicBezier) + { + seg.ptCount = 4; + _points.Add(prev.pos); + _points.Add(current.pos); + _points.Add(prev.control1); + _points.Add(prev.control2); + } + seg.length = Vector3.Distance(prev.pos, current.pos); + _fullLength += seg.length; + _segments.Add(seg); + } + + if (current.curveType != GPathPoint.CurveType.CRSpline) + { + if (splinePoints.Count > 0) + { + splinePoints.Add(current.pos); + CreateSplineSegment(); + } + } + else + splinePoints.Add(current.pos); + + prev = current; + } + + if (splinePoints.Count > 1) + CreateSplineSegment(); + } + + void CreateSplineSegment() + { + int cnt = splinePoints.Count; + splinePoints.Insert(0, splinePoints[0]); + splinePoints.Add(splinePoints[cnt]); + splinePoints.Add(splinePoints[cnt]); + cnt += 3; + + Segment seg = new Segment(); + seg.type = GPathPoint.CurveType.CRSpline; + seg.ptStart = _points.Count; + seg.ptCount = cnt; + _points.AddRange(splinePoints); + + seg.length = 0; + for (int i = 1; i < cnt; i++) + seg.length += Vector3.Distance(splinePoints[i - 1], splinePoints[i]); + _fullLength += seg.length; + _segments.Add(seg); + splinePoints.Clear(); + } + + /// + /// + /// + public void Clear() + { + _segments.Clear(); + _points.Clear(); + } + + /// + /// + /// + /// + /// + public Vector3 GetPointAt(float t) + { + t = Mathf.Clamp01(t); + int cnt = _segments.Count; + if (cnt == 0) + return Vector3.zero; + + Segment seg; + if (t == 1) + { + seg = _segments[cnt - 1]; + + if (seg.type == GPathPoint.CurveType.Straight) + return Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t); + else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) + return onBezierCurve(seg.ptStart, seg.ptCount, t); + else + return onCRSplineCurve(seg.ptStart, seg.ptCount, t); + } + + float len = t * _fullLength; + Vector3 pt = new Vector3(); + for (int i = 0; i < cnt; i++) + { + seg = _segments[i]; + + len -= seg.length; + if (len < 0) + { + t = 1 + len / seg.length; + + if (seg.type == GPathPoint.CurveType.Straight) + pt = Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t); + else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) + pt = onBezierCurve(seg.ptStart, seg.ptCount, t); + else + pt = onCRSplineCurve(seg.ptStart, seg.ptCount, t); + + break; + } + } + + return pt; + } + + /// + /// + /// + public int segmentCount + { + get { return _segments.Count; } + } + + /// + /// + /// + /// + /// + public float GetSegmentLength(int segmentIndex) + { + return _segments[segmentIndex].length; + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void GetPointsInSegment(int segmentIndex, float t0, float t1, List points, List ts = null, float pointDensity = 0.1f) + { + if (points == null) + points = new List(); + + if (ts != null) + ts.Add(t0); + Segment seg = _segments[segmentIndex]; + if (seg.type == GPathPoint.CurveType.Straight) + { + points.Add(Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t0)); + points.Add(Vector3.Lerp(_points[seg.ptStart], _points[seg.ptStart + 1], t1)); + } + else if (seg.type == GPathPoint.CurveType.Bezier || seg.type == GPathPoint.CurveType.CubicBezier) + { + points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t0)); + int SmoothAmount = (int)Mathf.Min(seg.length * pointDensity, 50); + for (int j = 0; j <= SmoothAmount; j++) + { + float t = (float)j / SmoothAmount; + if (t > t0 && t < t1) + { + points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t)); + if (ts != null) + ts.Add(t); + } + } + points.Add(onBezierCurve(seg.ptStart, seg.ptCount, t1)); + } + else + { + points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t0)); + int SmoothAmount = (int)Mathf.Min(seg.length * pointDensity, 50); + for (int j = 0; j <= SmoothAmount; j++) + { + float t = (float)j / SmoothAmount; + if (t > t0 && t < t1) + { + points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t)); + if (ts != null) + ts.Add(t); + } + } + points.Add(onCRSplineCurve(seg.ptStart, seg.ptCount, t1)); + } + + if (ts != null) + ts.Add(t1); + } + + /// + /// + /// + /// + public void GetAllPoints(List points, float pointDensity = 0.1f) + { + int cnt = _segments.Count; + for (int i = 0; i < cnt; i++) + GetPointsInSegment(i, 0, 1, points, null, pointDensity); + } + + /// + /// Catmull rom spline implementation + /// by Stéphane Drouot, laei - http://games.laei.org + /// + /// Actual translation of math gebrish to C# credit is due to + /// Boon Cotter - http://www.booncotter.com/waypoints-catmull-rom-splines/ + /// + /// This takes a list of vector3 (or an array) and gives a function called .onCurve(t) + /// returning a value on a Catmull-Rom spline for 0 <= t <= 1 + /// + Vector3 onCRSplineCurve(int ptStart, int ptCount, float t) + { + int adjustedIndex = Mathf.FloorToInt(t * (ptCount - 4)) + ptStart; //Since the equation works with 4 points, we adjust the starting point depending on t to return a point on the specific segment + + Vector3 result = new Vector3(); + + Vector3 p0 = _points[adjustedIndex]; + Vector3 p1 = _points[adjustedIndex + 1]; + Vector3 p2 = _points[adjustedIndex + 2]; + Vector3 p3 = _points[adjustedIndex + 3]; + + float adjustedT = (t == 1f) ? 1f : Mathf.Repeat(t * (ptCount - 4), 1f); // Then we adjust t to be that value on that new piece of segment... for t == 1f don't use repeat (that would return 0f); + + float t0 = ((-adjustedT + 2f) * adjustedT - 1f) * adjustedT * 0.5f; + float t1 = (((3f * adjustedT - 5f) * adjustedT) * adjustedT + 2f) * 0.5f; + float t2 = ((-3f * adjustedT + 4f) * adjustedT + 1f) * adjustedT * 0.5f; + float t3 = ((adjustedT - 1f) * adjustedT * adjustedT) * 0.5f; + + result.x = p0.x * t0 + p1.x * t1 + p2.x * t2 + p3.x * t3; + result.y = p0.y * t0 + p1.y * t1 + p2.y * t2 + p3.y * t3; + result.z = p0.z * t0 + p1.z * t1 + p2.z * t2 + p3.z * t3; + + return result; + } + + Vector3 onBezierCurve(int ptStart, int ptCount, float t) + { + float t2 = 1f - t; + Vector3 p0 = _points[ptStart]; + Vector3 p1 = _points[ptStart + 1]; + Vector3 cp0 = _points[ptStart + 2]; + + if (ptCount == 4) + { + Vector3 cp1 = _points[ptStart + 3]; + return t2 * t2 * t2 * p0 + 3f * t2 * t2 * t * cp0 + 3f * t2 * t * t * cp1 + t * t * t * p1; + } + else + return t2 * t2 * p0 + 2f * t2 * t * cp0 + t * t * p1; + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Tween/GPath.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GPath.cs.meta similarity index 100% rename from Assets/Scripts/Tween/GPath.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GPath.cs.meta diff --git a/Assets/Scripts/Tween/GTween.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTween.cs similarity index 96% rename from Assets/Scripts/Tween/GTween.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTween.cs index 9bdb54b1..b2d985d3 100644 --- a/Assets/Scripts/Tween/GTween.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTween.cs @@ -1,189 +1,189 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class GTween - { - /// - /// - /// - public static bool catchCallbackExceptions = false; - - /// - /// - /// - /// - /// - /// - /// - public static GTweener To(float startValue, float endValue, float duration) - { - return TweenManager.CreateTween()._To(startValue, endValue, duration); - } - - /// - /// - /// - /// - /// - /// - /// - public static GTweener To(Vector2 startValue, Vector2 endValue, float duration) - { - return TweenManager.CreateTween()._To(startValue, endValue, duration); - } - - /// - /// - /// - /// - /// - /// - /// - public static GTweener To(Vector3 startValue, Vector3 endValue, float duration) - { - return TweenManager.CreateTween()._To(startValue, endValue, duration); - } - - /// - /// - /// - /// - /// - /// - /// - public static GTweener To(Vector4 startValue, Vector4 endValue, float duration) - { - return TweenManager.CreateTween()._To(startValue, endValue, duration); - } - - /// - /// - /// - /// - /// - /// - /// - public static GTweener To(Color startValue, Color endValue, float duration) - { - return TweenManager.CreateTween()._To(startValue, endValue, duration); - } - - /// - /// - /// - /// - /// - /// - /// - public static GTweener ToDouble(double startValue, double endValue, float duration) - { - return TweenManager.CreateTween()._To(startValue, endValue, duration); - } - - /// - /// - /// - /// - /// - public static GTweener DelayedCall(float delay) - { - return TweenManager.CreateTween().SetDelay(delay); - } - - /// - /// - /// - /// - /// - /// - /// - public static GTweener Shake(Vector3 startValue, float amplitude, float duration) - { - return TweenManager.CreateTween()._Shake(startValue, amplitude, duration); - } - - /// - /// - /// - /// - /// - public static bool IsTweening(object target) - { - return TweenManager.IsTweening(target, TweenPropType.None); - } - - /// - /// - /// - /// - /// - /// - public static bool IsTweening(object target, TweenPropType propType) - { - return TweenManager.IsTweening(target, propType); - } - - /// - /// - /// - /// - public static void Kill(object target) - { - TweenManager.KillTweens(target, TweenPropType.None, false); - } - - /// - /// - /// - /// - /// - public static void Kill(object target, bool complete) - { - TweenManager.KillTweens(target, TweenPropType.None, complete); - } - - /// - /// - /// - /// - /// - /// - public static void Kill(object target, TweenPropType propType, bool complete) - { - TweenManager.KillTweens(target, propType, complete); - } - - /// - /// - /// - /// - /// - public static GTweener GetTween(object target) - { - return TweenManager.GetTween(target, TweenPropType.None); - } - - /// - /// - /// - /// - /// - /// - public static GTweener GetTween(object target, TweenPropType propType) - { - return TweenManager.GetTween(target, propType); - } - - /// - /// - /// - public static void Clean() - { - TweenManager.Clean(); - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class GTween + { + /// + /// + /// + public static bool catchCallbackExceptions = false; + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(float startValue, float endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Vector2 startValue, Vector2 endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Vector3 startValue, Vector3 endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Vector4 startValue, Vector4 endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener To(Color startValue, Color endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener ToDouble(double startValue, double endValue, float duration) + { + return TweenManager.CreateTween()._To(startValue, endValue, duration); + } + + /// + /// + /// + /// + /// + public static GTweener DelayedCall(float delay) + { + return TweenManager.CreateTween().SetDelay(delay); + } + + /// + /// + /// + /// + /// + /// + /// + public static GTweener Shake(Vector3 startValue, float amplitude, float duration) + { + return TweenManager.CreateTween()._Shake(startValue, amplitude, duration); + } + + /// + /// + /// + /// + /// + public static bool IsTweening(object target) + { + return TweenManager.IsTweening(target, TweenPropType.None); + } + + /// + /// + /// + /// + /// + /// + public static bool IsTweening(object target, TweenPropType propType) + { + return TweenManager.IsTweening(target, propType); + } + + /// + /// + /// + /// + public static void Kill(object target) + { + TweenManager.KillTweens(target, TweenPropType.None, false); + } + + /// + /// + /// + /// + /// + public static void Kill(object target, bool complete) + { + TweenManager.KillTweens(target, TweenPropType.None, complete); + } + + /// + /// + /// + /// + /// + /// + public static void Kill(object target, TweenPropType propType, bool complete) + { + TweenManager.KillTweens(target, propType, complete); + } + + /// + /// + /// + /// + /// + public static GTweener GetTween(object target) + { + return TweenManager.GetTween(target, TweenPropType.None); + } + + /// + /// + /// + /// + /// + /// + public static GTweener GetTween(object target, TweenPropType propType) + { + return TweenManager.GetTween(target, propType); + } + + /// + /// + /// + public static void Clean() + { + TweenManager.Clean(); + } + } +} diff --git a/Assets/Scripts/Tween/GTween.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTween.cs.meta similarity index 100% rename from Assets/Scripts/Tween/GTween.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTween.cs.meta diff --git a/Assets/Scripts/Tween/GTweener.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTweener.cs similarity index 96% rename from Assets/Scripts/Tween/GTweener.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTweener.cs index cc0c2ee3..33e98b6d 100644 --- a/Assets/Scripts/Tween/GTweener.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTweener.cs @@ -1,859 +1,859 @@ -using System; -using UnityEngine; -#if FAIRYGUI_TOLUA -using LuaInterface; -#endif - -namespace FairyGUI -{ - /// - /// - /// - public delegate void GTweenCallback(); - - /// - /// - /// - /// - public delegate void GTweenCallback1(GTweener tweener); - - /// - /// - /// - public interface ITweenListener - { - /// - /// - /// - /// - void OnTweenStart(GTweener tweener); - - /// - /// - /// - /// - void OnTweenUpdate(GTweener tweener); - - /// - /// - /// - /// - void OnTweenComplete(GTweener tweener); - } - - /// - /// - /// - public class GTweener - { - internal object _target; - internal TweenPropType _propType; - internal bool _killed; - internal bool _paused; - - float _delay; - float _duration; - float _breakpoint; - EaseType _easeType; - float _easeOvershootOrAmplitude; - float _easePeriod; - int _repeat; - bool _yoyo; - float _timeScale; - bool _ignoreEngineTimeScale; - bool _snapping; - object _userData; - GPath _path; - CustomEase _customEase; - - GTweenCallback _onUpdate; - GTweenCallback _onStart; - GTweenCallback _onComplete; - GTweenCallback1 _onUpdate1; - GTweenCallback1 _onStart1; - GTweenCallback1 _onComplete1; - ITweenListener _listener; - - TweenValue _startValue; - TweenValue _endValue; - TweenValue _value; - TweenValue _deltaValue; - int _valueSize; - - bool _started; - int _ended; - float _elapsedTime; - float _normalizedTime; - int _smoothStart; - - public GTweener() - { - _startValue = new TweenValue(); - _endValue = new TweenValue(); - _value = new TweenValue(); - _deltaValue = new TweenValue(); - } - - /// - /// - /// - /// - /// - public GTweener SetDelay(float value) - { - _delay = value; - return this; - } - - /// - /// - /// - public float delay - { - get { return _delay; } - } - - /// - /// - /// - /// - /// - public GTweener SetDuration(float value) - { - _duration = value; - return this; - } - - /// - /// - /// - public float duration - { - get { return _duration; } - } - - /// - /// - /// - /// - /// - public GTweener SetBreakpoint(float value) - { - _breakpoint = value; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetEase(EaseType value) - { - _easeType = value; - return this; - } - - /// - /// - /// - /// - /// - /// - public GTweener SetEase(EaseType value, CustomEase customEase) - { - _easeType = value; - _customEase = customEase; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetEasePeriod(float value) - { - _easePeriod = value; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetEaseOvershootOrAmplitude(float value) - { - _easeOvershootOrAmplitude = value; - return this; - } - - /// - /// - /// - /// - /// - /// - public GTweener SetRepeat(int times, bool yoyo = false) - { - _repeat = times; - _yoyo = yoyo; - return this; - } - - /// - /// - /// - public int repeat - { - get { return _repeat; } - } - - /// - /// - /// - /// - /// - public GTweener SetTimeScale(float value) - { - _timeScale = value; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetIgnoreEngineTimeScale(bool value) - { - _ignoreEngineTimeScale = value; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetSnapping(bool value) - { - _snapping = value; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetPath(GPath value) - { - _path = value; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetTarget(object value) - { - _target = value; - _propType = TweenPropType.None; - return this; - } - - /// - /// - /// - /// - /// - /// - public GTweener SetTarget(object value, TweenPropType propType) - { - _target = value; - _propType = propType; - return this; - } - - /// - /// - /// - public object target - { - get { return _target; } - } - - /// - /// - /// - /// - /// - public GTweener SetUserData(object value) - { - _userData = value; - return this; - } - - /// - /// - /// - public object userData - { - get { return _userData; } - } - - /// - /// - /// - /// - /// -#if FAIRYGUI_TOLUA - [NoToLua] -#endif - public GTweener OnUpdate(GTweenCallback callback) - { - _onUpdate = callback; - return this; - } - - /// - /// - /// - /// - /// -#if FAIRYGUI_TOLUA - [NoToLua] -#endif - public GTweener OnStart(GTweenCallback callback) - { - _onStart = callback; - return this; - } - - /// - /// - /// - /// - /// -#if FAIRYGUI_TOLUA - [NoToLua] -#endif - public GTweener OnComplete(GTweenCallback callback) - { - _onComplete = callback; - return this; - } - - /// - /// - /// - /// - /// - public GTweener OnUpdate(GTweenCallback1 callback) - { - _onUpdate1 = callback; - return this; - } - - /// - /// - /// - /// - /// - public GTweener OnStart(GTweenCallback1 callback) - { - _onStart1 = callback; - return this; - } - - /// - /// - /// - /// - /// - public GTweener OnComplete(GTweenCallback1 callback) - { - _onComplete1 = callback; - return this; - } - - /// - /// - /// - /// - /// - public GTweener SetListener(ITweenListener value) - { - _listener = value; - return this; - } - - /// - /// - /// - public TweenValue startValue - { - get { return _startValue; } - } - - /// - /// - /// - public TweenValue endValue - { - get { return _endValue; } - } - - /// - /// - /// - public TweenValue value - { - get { return _value; } - } - - /// - /// - /// - public TweenValue deltaValue - { - get { return _deltaValue; } - } - - /// - /// - /// - public float normalizedTime - { - get { return _normalizedTime; } - } - - /// - /// - /// - public bool completed - { - get { return _ended != 0; } - } - - /// - /// - /// - public bool allCompleted - { - get { return _ended == 1; } - } - - /// - /// - /// - /// - /// - public GTweener SetPaused(bool paused) - { - _paused = paused; - if (_paused) - _smoothStart = 0; - return this; - } - - /// - /// - /// - /// - public void Seek(float time) - { - if (_killed) - return; - - _elapsedTime = time; - if (_elapsedTime < _delay) - { - if (_started) - _elapsedTime = _delay; - else - return; - } - - Update(); - } - - /// - /// - /// - /// - public void Kill(bool complete = false) - { - if (_killed) - return; - - if (complete) - { - if (_ended == 0) - { - if (_breakpoint >= 0) - _elapsedTime = _delay + _breakpoint; - else if (_repeat >= 0) - _elapsedTime = _delay + _duration * (_repeat + 1); - else - _elapsedTime = _delay + _duration * 2; - Update(); - } - - CallCompleteCallback(); - } - - _killed = true; - } - - internal GTweener _To(float start, float end, float duration) - { - _valueSize = 1; - _startValue.x = start; - _endValue.x = end; - _value.x = start; - _duration = duration; - return this; - } - - internal GTweener _To(Vector2 start, Vector2 end, float duration) - { - _valueSize = 2; - _startValue.vec2 = start; - _endValue.vec2 = end; - _value.vec2 = start; - _duration = duration; - return this; - } - - internal GTweener _To(Vector3 start, Vector3 end, float duration) - { - _valueSize = 3; - _startValue.vec3 = start; - _endValue.vec3 = end; - _value.vec3 = start; - _duration = duration; - return this; - } - - internal GTweener _To(Vector4 start, Vector4 end, float duration) - { - _valueSize = 4; - _startValue.vec4 = start; - _endValue.vec4 = end; - _value.vec4 = start; - _duration = duration; - return this; - } - - internal GTweener _To(Color start, Color end, float duration) - { - _valueSize = 4; - _startValue.color = start; - _endValue.color = end; - _value.color = start; - _duration = duration; - return this; - } - - internal GTweener _To(double start, double end, float duration) - { - _valueSize = 5; - _startValue.d = start; - _endValue.d = end; - _value.d = start; - _duration = duration; - return this; - } - - internal GTweener _Shake(Vector3 start, float amplitude, float duration) - { - _valueSize = 6; - _startValue.vec3 = start; - _startValue.w = amplitude; - _duration = duration; - _easeType = EaseType.Linear; - return this; - } - - internal void _Init() - { - _delay = 0; - _duration = 0; - _breakpoint = -1; - _easeType = EaseType.QuadOut; - _timeScale = 1; - _ignoreEngineTimeScale = false; - _easePeriod = 0; - _easeOvershootOrAmplitude = 1.70158f; - _snapping = false; - _repeat = 0; - _yoyo = false; - _valueSize = 0; - _started = false; - _paused = false; - _killed = false; - _elapsedTime = 0; - _normalizedTime = 0; - _ended = 0; - _path = null; - _customEase = null; - _smoothStart = Time.frameCount == 1 ? 3 : 1;//刚启动时会有多帧的超时 - } - - internal void _Reset() - { - _target = null; - _listener = null; - _userData = null; - _onStart = _onUpdate = _onComplete = null; - _onStart1 = _onUpdate1 = _onComplete1 = null; - } - - internal void _Update() - { - if (_ended != 0) //Maybe completed by seek - { - CallCompleteCallback(); - _killed = true; - return; - } - - float dt; - if (_smoothStart > 0) - { - _smoothStart--; - dt = Mathf.Clamp(Time.unscaledDeltaTime, 0, Application.targetFrameRate > 0 ? (1.0f / Application.targetFrameRate) : 0.016f); - if (!_ignoreEngineTimeScale) - dt *= Time.timeScale; - } - else if (_ignoreEngineTimeScale) - dt = Time.unscaledDeltaTime; - else - dt = Time.deltaTime; - if (_timeScale != 1) - dt *= _timeScale; - if (dt == 0) - return; - - _elapsedTime += dt; - Update(); - - if (_ended != 0) - { - if (!_killed) - { - CallCompleteCallback(); - _killed = true; - } - } - } - - void Update() - { - _ended = 0; - - if (_valueSize == 0) //DelayedCall - { - if (_elapsedTime >= _delay + _duration) - _ended = 1; - - return; - } - - if (!_started) - { - if (_elapsedTime < _delay) - return; - - _started = true; - CallStartCallback(); - if (_killed) - return; - } - - bool reversed = false; - float tt = _elapsedTime - _delay; - if (_breakpoint >= 0 && tt >= _breakpoint) - { - tt = _breakpoint; - _ended = 2; - } - - if (_repeat != 0) - { - int round = Mathf.FloorToInt(tt / _duration); - tt -= _duration * round; - if (_yoyo) - reversed = round % 2 == 1; - - if (_repeat > 0 && _repeat - round < 0) - { - if (_yoyo) - reversed = _repeat % 2 == 1; - tt = _duration; - _ended = 1; - } - } - else if (tt >= _duration) - { - tt = _duration; - _ended = 1; - } - - _normalizedTime = EaseManager.Evaluate(_easeType, reversed ? (_duration - tt) : tt, _duration, - _easeOvershootOrAmplitude, _easePeriod, _customEase); - - _value.SetZero(); - _deltaValue.SetZero(); - - if (_valueSize == 5) - { - double d = _startValue.d + (_endValue.d - _startValue.d) * _normalizedTime; - if (_snapping) - d = Math.Round(d); - _deltaValue.d = d - _value.d; - _value.d = d; - _value.x = (float)d; - } - else if (_valueSize == 6) - { - if (_ended == 0) - { - Vector3 r = UnityEngine.Random.insideUnitSphere; - r.x = r.x > 0 ? 1 : -1; - r.y = r.y > 0 ? 1 : -1; - r.z = r.z > 0 ? 1 : -1; - r *= _startValue.w * (1 - _normalizedTime); - - _deltaValue.vec3 = r; - _value.vec3 = _startValue.vec3 + r; - } - else - _value.vec3 = _startValue.vec3; - } - else if (_path != null) - { - Vector3 vec3 = _path.GetPointAt(_normalizedTime); - if (_snapping) - { - vec3.x = Mathf.Round(vec3.x); - vec3.y = Mathf.Round(vec3.y); - vec3.z = Mathf.Round(vec3.z); - } - _deltaValue.vec3 = vec3 - _value.vec3; - _value.vec3 = vec3; - } - else - { - for (int i = 0; i < _valueSize; i++) - { - float n1 = _startValue[i]; - float n2 = _endValue[i]; - float f = n1 + (n2 - n1) * _normalizedTime; - if (_snapping) - f = Mathf.Round(f); - _deltaValue[i] = f - _value[i]; - _value[i] = f; - } - _value.d = _value.x; - } - - if (_target != null && _propType != TweenPropType.None) - TweenPropTypeUtils.SetProps(_target, _propType, _value); - - CallUpdateCallback(); - } - - void CallStartCallback() - { - if (GTween.catchCallbackExceptions) - { - try - { - if (_onStart1 != null) - _onStart1(this); - if (_onStart != null) - _onStart(); - if (_listener != null) - _listener.OnTweenStart(this); - } - catch (Exception e) - { - Debug.LogWarning("FairyGUI: error in start callback > " + e.Message); - } - } - else - { - if (_onStart1 != null) - _onStart1(this); - if (_onStart != null) - _onStart(); - if (_listener != null) - _listener.OnTweenStart(this); - } - } - - void CallUpdateCallback() - { - if (GTween.catchCallbackExceptions) - { - try - { - if (_onUpdate1 != null) - _onUpdate1(this); - if (_onUpdate != null) - _onUpdate(); - if (_listener != null) - _listener.OnTweenUpdate(this); - } - catch (Exception e) - { - Debug.LogWarning("FairyGUI: error in update callback > " + e.Message); - } - } - else - { - if (_onUpdate1 != null) - _onUpdate1(this); - if (_onUpdate != null) - _onUpdate(); - if (_listener != null) - _listener.OnTweenUpdate(this); - } - } - - void CallCompleteCallback() - { - if (GTween.catchCallbackExceptions) - { - try - { - if (_onComplete1 != null) - _onComplete1(this); - if (_onComplete != null) - _onComplete(); - if (_listener != null) - _listener.OnTweenComplete(this); - } - catch (Exception e) - { - Debug.LogWarning("FairyGUI: error in complete callback > " + e.Message); - } - } - else - { - if (_onComplete1 != null) - _onComplete1(this); - if (_onComplete != null) - _onComplete(); - if (_listener != null) - _listener.OnTweenComplete(this); - } - } - } -} +using System; +using UnityEngine; +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public delegate void GTweenCallback(); + + /// + /// + /// + /// + public delegate void GTweenCallback1(GTweener tweener); + + /// + /// + /// + public interface ITweenListener + { + /// + /// + /// + /// + void OnTweenStart(GTweener tweener); + + /// + /// + /// + /// + void OnTweenUpdate(GTweener tweener); + + /// + /// + /// + /// + void OnTweenComplete(GTweener tweener); + } + + /// + /// + /// + public class GTweener + { + internal object _target; + internal TweenPropType _propType; + internal bool _killed; + internal bool _paused; + + float _delay; + float _duration; + float _breakpoint; + EaseType _easeType; + float _easeOvershootOrAmplitude; + float _easePeriod; + int _repeat; + bool _yoyo; + float _timeScale; + bool _ignoreEngineTimeScale; + bool _snapping; + object _userData; + GPath _path; + CustomEase _customEase; + + GTweenCallback _onUpdate; + GTweenCallback _onStart; + GTweenCallback _onComplete; + GTweenCallback1 _onUpdate1; + GTweenCallback1 _onStart1; + GTweenCallback1 _onComplete1; + ITweenListener _listener; + + TweenValue _startValue; + TweenValue _endValue; + TweenValue _value; + TweenValue _deltaValue; + int _valueSize; + + bool _started; + int _ended; + float _elapsedTime; + float _normalizedTime; + int _smoothStart; + + public GTweener() + { + _startValue = new TweenValue(); + _endValue = new TweenValue(); + _value = new TweenValue(); + _deltaValue = new TweenValue(); + } + + /// + /// + /// + /// + /// + public GTweener SetDelay(float value) + { + _delay = value; + return this; + } + + /// + /// + /// + public float delay + { + get { return _delay; } + } + + /// + /// + /// + /// + /// + public GTweener SetDuration(float value) + { + _duration = value; + return this; + } + + /// + /// + /// + public float duration + { + get { return _duration; } + } + + /// + /// + /// + /// + /// + public GTweener SetBreakpoint(float value) + { + _breakpoint = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetEase(EaseType value) + { + _easeType = value; + return this; + } + + /// + /// + /// + /// + /// + /// + public GTweener SetEase(EaseType value, CustomEase customEase) + { + _easeType = value; + _customEase = customEase; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetEasePeriod(float value) + { + _easePeriod = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetEaseOvershootOrAmplitude(float value) + { + _easeOvershootOrAmplitude = value; + return this; + } + + /// + /// + /// + /// + /// + /// + public GTweener SetRepeat(int times, bool yoyo = false) + { + _repeat = times; + _yoyo = yoyo; + return this; + } + + /// + /// + /// + public int repeat + { + get { return _repeat; } + } + + /// + /// + /// + /// + /// + public GTweener SetTimeScale(float value) + { + _timeScale = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetIgnoreEngineTimeScale(bool value) + { + _ignoreEngineTimeScale = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetSnapping(bool value) + { + _snapping = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetPath(GPath value) + { + _path = value; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetTarget(object value) + { + _target = value; + _propType = TweenPropType.None; + return this; + } + + /// + /// + /// + /// + /// + /// + public GTweener SetTarget(object value, TweenPropType propType) + { + _target = value; + _propType = propType; + return this; + } + + /// + /// + /// + public object target + { + get { return _target; } + } + + /// + /// + /// + /// + /// + public GTweener SetUserData(object value) + { + _userData = value; + return this; + } + + /// + /// + /// + public object userData + { + get { return _userData; } + } + + /// + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public GTweener OnUpdate(GTweenCallback callback) + { + _onUpdate = callback; + return this; + } + + /// + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public GTweener OnStart(GTweenCallback callback) + { + _onStart = callback; + return this; + } + + /// + /// + /// + /// + /// +#if FAIRYGUI_TOLUA + [NoToLua] +#endif + public GTweener OnComplete(GTweenCallback callback) + { + _onComplete = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener OnUpdate(GTweenCallback1 callback) + { + _onUpdate1 = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener OnStart(GTweenCallback1 callback) + { + _onStart1 = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener OnComplete(GTweenCallback1 callback) + { + _onComplete1 = callback; + return this; + } + + /// + /// + /// + /// + /// + public GTweener SetListener(ITweenListener value) + { + _listener = value; + return this; + } + + /// + /// + /// + public TweenValue startValue + { + get { return _startValue; } + } + + /// + /// + /// + public TweenValue endValue + { + get { return _endValue; } + } + + /// + /// + /// + public TweenValue value + { + get { return _value; } + } + + /// + /// + /// + public TweenValue deltaValue + { + get { return _deltaValue; } + } + + /// + /// + /// + public float normalizedTime + { + get { return _normalizedTime; } + } + + /// + /// + /// + public bool completed + { + get { return _ended != 0; } + } + + /// + /// + /// + public bool allCompleted + { + get { return _ended == 1; } + } + + /// + /// + /// + /// + /// + public GTweener SetPaused(bool paused) + { + _paused = paused; + if (_paused) + _smoothStart = 0; + return this; + } + + /// + /// + /// + /// + public void Seek(float time) + { + if (_killed) + return; + + _elapsedTime = time; + if (_elapsedTime < _delay) + { + if (_started) + _elapsedTime = _delay; + else + return; + } + + Update(); + } + + /// + /// + /// + /// + public void Kill(bool complete = false) + { + if (_killed) + return; + + if (complete) + { + if (_ended == 0) + { + if (_breakpoint >= 0) + _elapsedTime = _delay + _breakpoint; + else if (_repeat >= 0) + _elapsedTime = _delay + _duration * (_repeat + 1); + else + _elapsedTime = _delay + _duration * 2; + Update(); + } + + CallCompleteCallback(); + } + + _killed = true; + } + + internal GTweener _To(float start, float end, float duration) + { + _valueSize = 1; + _startValue.x = start; + _endValue.x = end; + _value.x = start; + _duration = duration; + return this; + } + + internal GTweener _To(Vector2 start, Vector2 end, float duration) + { + _valueSize = 2; + _startValue.vec2 = start; + _endValue.vec2 = end; + _value.vec2 = start; + _duration = duration; + return this; + } + + internal GTweener _To(Vector3 start, Vector3 end, float duration) + { + _valueSize = 3; + _startValue.vec3 = start; + _endValue.vec3 = end; + _value.vec3 = start; + _duration = duration; + return this; + } + + internal GTweener _To(Vector4 start, Vector4 end, float duration) + { + _valueSize = 4; + _startValue.vec4 = start; + _endValue.vec4 = end; + _value.vec4 = start; + _duration = duration; + return this; + } + + internal GTweener _To(Color start, Color end, float duration) + { + _valueSize = 4; + _startValue.color = start; + _endValue.color = end; + _value.color = start; + _duration = duration; + return this; + } + + internal GTweener _To(double start, double end, float duration) + { + _valueSize = 5; + _startValue.d = start; + _endValue.d = end; + _value.d = start; + _duration = duration; + return this; + } + + internal GTweener _Shake(Vector3 start, float amplitude, float duration) + { + _valueSize = 6; + _startValue.vec3 = start; + _startValue.w = amplitude; + _duration = duration; + _easeType = EaseType.Linear; + return this; + } + + internal void _Init() + { + _delay = 0; + _duration = 0; + _breakpoint = -1; + _easeType = EaseType.QuadOut; + _timeScale = 1; + _ignoreEngineTimeScale = false; + _easePeriod = 0; + _easeOvershootOrAmplitude = 1.70158f; + _snapping = false; + _repeat = 0; + _yoyo = false; + _valueSize = 0; + _started = false; + _paused = false; + _killed = false; + _elapsedTime = 0; + _normalizedTime = 0; + _ended = 0; + _path = null; + _customEase = null; + _smoothStart = Time.frameCount == 1 ? 3 : 1;//刚启动时会有多帧的超时 + } + + internal void _Reset() + { + _target = null; + _listener = null; + _userData = null; + _onStart = _onUpdate = _onComplete = null; + _onStart1 = _onUpdate1 = _onComplete1 = null; + } + + internal void _Update() + { + if (_ended != 0) //Maybe completed by seek + { + CallCompleteCallback(); + _killed = true; + return; + } + + float dt; + if (_smoothStart > 0) + { + _smoothStart--; + dt = Mathf.Clamp(Time.unscaledDeltaTime, 0, Application.targetFrameRate > 0 ? (1.0f / Application.targetFrameRate) : 0.016f); + if (!_ignoreEngineTimeScale) + dt *= Time.timeScale; + } + else if (_ignoreEngineTimeScale) + dt = Time.unscaledDeltaTime; + else + dt = Time.deltaTime; + if (_timeScale != 1) + dt *= _timeScale; + if (dt == 0) + return; + + _elapsedTime += dt; + Update(); + + if (_ended != 0) + { + if (!_killed) + { + CallCompleteCallback(); + _killed = true; + } + } + } + + void Update() + { + _ended = 0; + + if (_valueSize == 0) //DelayedCall + { + if (_elapsedTime >= _delay + _duration) + _ended = 1; + + return; + } + + if (!_started) + { + if (_elapsedTime < _delay) + return; + + _started = true; + CallStartCallback(); + if (_killed) + return; + } + + bool reversed = false; + float tt = _elapsedTime - _delay; + if (_breakpoint >= 0 && tt >= _breakpoint) + { + tt = _breakpoint; + _ended = 2; + } + + if (_repeat != 0) + { + int round = Mathf.FloorToInt(tt / _duration); + tt -= _duration * round; + if (_yoyo) + reversed = round % 2 == 1; + + if (_repeat > 0 && _repeat - round < 0) + { + if (_yoyo) + reversed = _repeat % 2 == 1; + tt = _duration; + _ended = 1; + } + } + else if (tt >= _duration) + { + tt = _duration; + _ended = 1; + } + + _normalizedTime = EaseManager.Evaluate(_easeType, reversed ? (_duration - tt) : tt, _duration, + _easeOvershootOrAmplitude, _easePeriod, _customEase); + + _value.SetZero(); + _deltaValue.SetZero(); + + if (_valueSize == 5) + { + double d = _startValue.d + (_endValue.d - _startValue.d) * _normalizedTime; + if (_snapping) + d = Math.Round(d); + _deltaValue.d = d - _value.d; + _value.d = d; + _value.x = (float)d; + } + else if (_valueSize == 6) + { + if (_ended == 0) + { + Vector3 r = UnityEngine.Random.insideUnitSphere; + r.x = r.x > 0 ? 1 : -1; + r.y = r.y > 0 ? 1 : -1; + r.z = r.z > 0 ? 1 : -1; + r *= _startValue.w * (1 - _normalizedTime); + + _deltaValue.vec3 = r; + _value.vec3 = _startValue.vec3 + r; + } + else + _value.vec3 = _startValue.vec3; + } + else if (_path != null) + { + Vector3 vec3 = _path.GetPointAt(_normalizedTime); + if (_snapping) + { + vec3.x = Mathf.Round(vec3.x); + vec3.y = Mathf.Round(vec3.y); + vec3.z = Mathf.Round(vec3.z); + } + _deltaValue.vec3 = vec3 - _value.vec3; + _value.vec3 = vec3; + } + else + { + for (int i = 0; i < _valueSize; i++) + { + float n1 = _startValue[i]; + float n2 = _endValue[i]; + float f = n1 + (n2 - n1) * _normalizedTime; + if (_snapping) + f = Mathf.Round(f); + _deltaValue[i] = f - _value[i]; + _value[i] = f; + } + _value.d = _value.x; + } + + if (_target != null && _propType != TweenPropType.None) + TweenPropTypeUtils.SetProps(_target, _propType, _value); + + CallUpdateCallback(); + } + + void CallStartCallback() + { + if (GTween.catchCallbackExceptions) + { + try + { + if (_onStart1 != null) + _onStart1(this); + if (_onStart != null) + _onStart(); + if (_listener != null) + _listener.OnTweenStart(this); + } + catch (Exception e) + { + Debug.LogWarning("FairyGUI: error in start callback > " + e.Message); + } + } + else + { + if (_onStart1 != null) + _onStart1(this); + if (_onStart != null) + _onStart(); + if (_listener != null) + _listener.OnTweenStart(this); + } + } + + void CallUpdateCallback() + { + if (GTween.catchCallbackExceptions) + { + try + { + if (_onUpdate1 != null) + _onUpdate1(this); + if (_onUpdate != null) + _onUpdate(); + if (_listener != null) + _listener.OnTweenUpdate(this); + } + catch (Exception e) + { + Debug.LogWarning("FairyGUI: error in update callback > " + e.Message); + } + } + else + { + if (_onUpdate1 != null) + _onUpdate1(this); + if (_onUpdate != null) + _onUpdate(); + if (_listener != null) + _listener.OnTweenUpdate(this); + } + } + + void CallCompleteCallback() + { + if (GTween.catchCallbackExceptions) + { + try + { + if (_onComplete1 != null) + _onComplete1(this); + if (_onComplete != null) + _onComplete(); + if (_listener != null) + _listener.OnTweenComplete(this); + } + catch (Exception e) + { + Debug.LogWarning("FairyGUI: error in complete callback > " + e.Message); + } + } + else + { + if (_onComplete1 != null) + _onComplete1(this); + if (_onComplete != null) + _onComplete(); + if (_listener != null) + _listener.OnTweenComplete(this); + } + } + } +} diff --git a/Assets/Scripts/Tween/GTweener.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTweener.cs.meta similarity index 100% rename from Assets/Scripts/Tween/GTweener.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/GTweener.cs.meta diff --git a/Assets/Scripts/Tween/TweenManager.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenManager.cs similarity index 100% rename from Assets/Scripts/Tween/TweenManager.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenManager.cs diff --git a/Assets/Scripts/Tween/TweenManager.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenManager.cs.meta similarity index 100% rename from Assets/Scripts/Tween/TweenManager.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenManager.cs.meta diff --git a/Assets/Scripts/Tween/TweenPropType.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenPropType.cs similarity index 95% rename from Assets/Scripts/Tween/TweenPropType.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenPropType.cs index 217ca938..1842267a 100644 --- a/Assets/Scripts/Tween/TweenPropType.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenPropType.cs @@ -1,103 +1,103 @@ -namespace FairyGUI -{ - /// - /// - /// - public enum TweenPropType - { - None, - X, - Y, - Z, - XY, - Position, - Width, - Height, - Size, - ScaleX, - ScaleY, - Scale, - Rotation, - RotationX, - RotationY, - Alpha, - Progress - } - - internal class TweenPropTypeUtils - { - internal static void SetProps(object target, TweenPropType propType, TweenValue value) - { - GObject g = target as GObject; - if (g == null) - return; - - switch (propType) - { - case TweenPropType.X: - g.x = value.x; - break; - - case TweenPropType.Y: - g.y = value.x; - break; - - case TweenPropType.Z: - g.z = value.x; - break; - - case TweenPropType.XY: - g.xy = value.vec2; - break; - - case TweenPropType.Position: - g.position = value.vec3; - break; - - case TweenPropType.Width: - g.width = value.x; - break; - - case TweenPropType.Height: - g.height = value.x; - break; - - case TweenPropType.Size: - g.size = value.vec2; - break; - - case TweenPropType.ScaleX: - g.scaleX = value.x; - break; - - case TweenPropType.ScaleY: - g.scaleY = value.x; - break; - - case TweenPropType.Scale: - g.scale = value.vec2; - break; - - case TweenPropType.Rotation: - g.rotation = value.x; - break; - - case TweenPropType.RotationX: - g.rotationX = value.x; - break; - - case TweenPropType.RotationY: - g.rotationY = value.x; - break; - - case TweenPropType.Alpha: - g.alpha = value.x; - break; - - case TweenPropType.Progress: - g.asProgress.Update(value.d); - break; - } - } - } -} +namespace FairyGUI +{ + /// + /// + /// + public enum TweenPropType + { + None, + X, + Y, + Z, + XY, + Position, + Width, + Height, + Size, + ScaleX, + ScaleY, + Scale, + Rotation, + RotationX, + RotationY, + Alpha, + Progress + } + + internal class TweenPropTypeUtils + { + internal static void SetProps(object target, TweenPropType propType, TweenValue value) + { + GObject g = target as GObject; + if (g == null) + return; + + switch (propType) + { + case TweenPropType.X: + g.x = value.x; + break; + + case TweenPropType.Y: + g.y = value.x; + break; + + case TweenPropType.Z: + g.z = value.x; + break; + + case TweenPropType.XY: + g.xy = value.vec2; + break; + + case TweenPropType.Position: + g.position = value.vec3; + break; + + case TweenPropType.Width: + g.width = value.x; + break; + + case TweenPropType.Height: + g.height = value.x; + break; + + case TweenPropType.Size: + g.size = value.vec2; + break; + + case TweenPropType.ScaleX: + g.scaleX = value.x; + break; + + case TweenPropType.ScaleY: + g.scaleY = value.x; + break; + + case TweenPropType.Scale: + g.scale = value.vec2; + break; + + case TweenPropType.Rotation: + g.rotation = value.x; + break; + + case TweenPropType.RotationX: + g.rotationX = value.x; + break; + + case TweenPropType.RotationY: + g.rotationY = value.x; + break; + + case TweenPropType.Alpha: + g.alpha = value.x; + break; + + case TweenPropType.Progress: + g.asProgress.Update(value.d); + break; + } + } + } +} diff --git a/Assets/Scripts/Tween/TweenPropType.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenPropType.cs.meta similarity index 100% rename from Assets/Scripts/Tween/TweenPropType.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenPropType.cs.meta diff --git a/Assets/Scripts/Tween/TweenValue.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenValue.cs similarity index 95% rename from Assets/Scripts/Tween/TweenValue.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenValue.cs index 9b7f9445..0b18d055 100644 --- a/Assets/Scripts/Tween/TweenValue.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenValue.cs @@ -1,151 +1,151 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class TweenValue - { - /// - /// - /// - public float x; - - /// - /// - /// - public float y; - - /// - /// - /// - public float z; - - /// - /// - /// - public float w; - - /// - /// - /// - public double d; - - public TweenValue() - { - } - - /// - /// - /// - public Vector2 vec2 - { - get { return new Vector2(x, y); } - set - { - x = value.x; - y = value.y; - } - } - - /// - /// - /// - public Vector3 vec3 - { - get { return new Vector3(x, y, z); } - set - { - x = value.x; - y = value.y; - z = value.z; - } - } - - /// - /// - /// - public Vector4 vec4 - { - get { return new Vector4(x, y, z, w); } - set - { - x = value.x; - y = value.y; - z = value.z; - w = value.w; - } - } - - /// - /// - /// - public Color color - { - get { return new Color(x, y, z, w); } - set - { - x = value.r; - y = value.g; - z = value.b; - w = value.a; - } - } - - /// - /// - /// - /// - /// - public float this[int index] - { - get - { - switch (index) - { - case 0: - return x; - case 1: - return y; - case 2: - return z; - case 3: - return w; - default: - throw new System.Exception("Index out of bounds: " + index); - } - } - - set - { - switch (index) - { - case 0: - x = value; - break; - case 1: - y = value; - break; - case 2: - z = value; - break; - case 3: - w = value; - break; - default: - throw new System.Exception("Index out of bounds: " + index); - } - } - } - - /// - /// - /// - public void SetZero() - { - x = y = z = w = 0; - d = 0; - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class TweenValue + { + /// + /// + /// + public float x; + + /// + /// + /// + public float y; + + /// + /// + /// + public float z; + + /// + /// + /// + public float w; + + /// + /// + /// + public double d; + + public TweenValue() + { + } + + /// + /// + /// + public Vector2 vec2 + { + get { return new Vector2(x, y); } + set + { + x = value.x; + y = value.y; + } + } + + /// + /// + /// + public Vector3 vec3 + { + get { return new Vector3(x, y, z); } + set + { + x = value.x; + y = value.y; + z = value.z; + } + } + + /// + /// + /// + public Vector4 vec4 + { + get { return new Vector4(x, y, z, w); } + set + { + x = value.x; + y = value.y; + z = value.z; + w = value.w; + } + } + + /// + /// + /// + public Color color + { + get { return new Color(x, y, z, w); } + set + { + x = value.r; + y = value.g; + z = value.b; + w = value.a; + } + } + + /// + /// + /// + /// + /// + public float this[int index] + { + get + { + switch (index) + { + case 0: + return x; + case 1: + return y; + case 2: + return z; + case 3: + return w; + default: + throw new System.Exception("Index out of bounds: " + index); + } + } + + set + { + switch (index) + { + case 0: + x = value; + break; + case 1: + y = value; + break; + case 2: + z = value; + break; + case 3: + w = value; + break; + default: + throw new System.Exception("Index out of bounds: " + index); + } + } + } + + /// + /// + /// + public void SetZero() + { + x = y = z = w = 0; + d = 0; + } + } +} diff --git a/Assets/Scripts/Tween/TweenValue.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenValue.cs.meta similarity index 100% rename from Assets/Scripts/Tween/TweenValue.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Tween/TweenValue.cs.meta diff --git a/Assets/Scripts/UI.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI.meta similarity index 100% rename from Assets/Scripts/UI.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI.meta diff --git a/Assets/Scripts/UI/Action.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action.meta similarity index 100% rename from Assets/Scripts/UI/Action.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action.meta diff --git a/Assets/Scripts/UI/Action/ChangePageAction.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ChangePageAction.cs similarity index 96% rename from Assets/Scripts/UI/Action/ChangePageAction.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ChangePageAction.cs index 940d0280..a22d5a2a 100644 --- a/Assets/Scripts/UI/Action/ChangePageAction.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ChangePageAction.cs @@ -1,52 +1,52 @@ -using FairyGUI.Utils; - -namespace FairyGUI -{ - public class ChangePageAction : ControllerAction - { - public string objectId; - public string controllerName; - public string targetPage; - - public ChangePageAction() - { - } - - override protected void Enter(Controller controller) - { - if (string.IsNullOrEmpty(controllerName)) - return; - - GComponent gcom; - if (!string.IsNullOrEmpty(objectId)) - gcom = controller.parent.GetChildById(objectId) as GComponent; - else - gcom = controller.parent; - if (gcom != null) - { - Controller cc = gcom.GetController(controllerName); - if (cc != null && cc != controller && !cc.changing) - { - if (this.targetPage == "~1") - { - if (controller.selectedIndex < cc.pageCount) - cc.selectedIndex = controller.selectedIndex; - } - else if (this.targetPage == "~2") - cc.selectedPage = controller.selectedPage; - else - cc.selectedPageId = this.targetPage; - } - } - } - - override public void Setup(ByteBuffer buffer) - { - base.Setup(buffer); - - objectId = buffer.ReadS(); - controllerName = buffer.ReadS(); - targetPage = buffer.ReadS(); - } - } -} +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class ChangePageAction : ControllerAction + { + public string objectId; + public string controllerName; + public string targetPage; + + public ChangePageAction() + { + } + + override protected void Enter(Controller controller) + { + if (string.IsNullOrEmpty(controllerName)) + return; + + GComponent gcom; + if (!string.IsNullOrEmpty(objectId)) + gcom = controller.parent.GetChildById(objectId) as GComponent; + else + gcom = controller.parent; + if (gcom != null) + { + Controller cc = gcom.GetController(controllerName); + if (cc != null && cc != controller && !cc.changing) + { + if (this.targetPage == "~1") + { + if (controller.selectedIndex < cc.pageCount) + cc.selectedIndex = controller.selectedIndex; + } + else if (this.targetPage == "~2") + cc.selectedPage = controller.selectedPage; + else + cc.selectedPageId = this.targetPage; + } + } + } + + override public void Setup(ByteBuffer buffer) + { + base.Setup(buffer); + + objectId = buffer.ReadS(); + controllerName = buffer.ReadS(); + targetPage = buffer.ReadS(); + } + } +} diff --git a/Assets/Scripts/UI/Action/ChangePageAction.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ChangePageAction.cs.meta similarity index 100% rename from Assets/Scripts/UI/Action/ChangePageAction.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ChangePageAction.cs.meta diff --git a/Assets/Scripts/UI/Action/ControllerAction.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ControllerAction.cs similarity index 96% rename from Assets/Scripts/UI/Action/ControllerAction.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ControllerAction.cs index e0d955a9..b713a010 100644 --- a/Assets/Scripts/UI/Action/ControllerAction.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ControllerAction.cs @@ -1,68 +1,68 @@ -using System; -using FairyGUI.Utils; - -namespace FairyGUI -{ - public class ControllerAction - { - public enum ActionType - { - PlayTransition, - ChangePage - } - - public string[] fromPage; - public string[] toPage; - - public static ControllerAction CreateAction(ActionType type) - { - switch (type) - { - case ActionType.PlayTransition: - return new PlayTransitionAction(); - - case ActionType.ChangePage: - return new ChangePageAction(); - } - return null; - } - - public ControllerAction() - { - } - - public void Run(Controller controller, string prevPage, string curPage) - { - if ((fromPage == null || fromPage.Length == 0 || Array.IndexOf(fromPage, prevPage) != -1) - && (toPage == null || toPage.Length == 0 || Array.IndexOf(toPage, curPage) != -1)) - Enter(controller); - else - Leave(controller); - } - - virtual protected void Enter(Controller controller) - { - - } - - virtual protected void Leave(Controller controller) - { - - } - - virtual public void Setup(ByteBuffer buffer) - { - int cnt; - - cnt = buffer.ReadShort(); - fromPage = new string[cnt]; - for (int i = 0; i < cnt; i++) - fromPage[i] = buffer.ReadS(); - - cnt = buffer.ReadShort(); - toPage = new string[cnt]; - for (int i = 0; i < cnt; i++) - toPage[i] = buffer.ReadS(); - } - } -} +using System; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class ControllerAction + { + public enum ActionType + { + PlayTransition, + ChangePage + } + + public string[] fromPage; + public string[] toPage; + + public static ControllerAction CreateAction(ActionType type) + { + switch (type) + { + case ActionType.PlayTransition: + return new PlayTransitionAction(); + + case ActionType.ChangePage: + return new ChangePageAction(); + } + return null; + } + + public ControllerAction() + { + } + + public void Run(Controller controller, string prevPage, string curPage) + { + if ((fromPage == null || fromPage.Length == 0 || Array.IndexOf(fromPage, prevPage) != -1) + && (toPage == null || toPage.Length == 0 || Array.IndexOf(toPage, curPage) != -1)) + Enter(controller); + else + Leave(controller); + } + + virtual protected void Enter(Controller controller) + { + + } + + virtual protected void Leave(Controller controller) + { + + } + + virtual public void Setup(ByteBuffer buffer) + { + int cnt; + + cnt = buffer.ReadShort(); + fromPage = new string[cnt]; + for (int i = 0; i < cnt; i++) + fromPage[i] = buffer.ReadS(); + + cnt = buffer.ReadShort(); + toPage = new string[cnt]; + for (int i = 0; i < cnt; i++) + toPage[i] = buffer.ReadS(); + } + } +} diff --git a/Assets/Scripts/UI/Action/ControllerAction.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ControllerAction.cs.meta similarity index 100% rename from Assets/Scripts/UI/Action/ControllerAction.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/ControllerAction.cs.meta diff --git a/Assets/Scripts/UI/Action/PlayTransitionAction.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/PlayTransitionAction.cs similarity index 96% rename from Assets/Scripts/UI/Action/PlayTransitionAction.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/PlayTransitionAction.cs index 9dca9ddb..cf156610 100644 --- a/Assets/Scripts/UI/Action/PlayTransitionAction.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/PlayTransitionAction.cs @@ -1,52 +1,52 @@ -using FairyGUI.Utils; - -namespace FairyGUI -{ - public class PlayTransitionAction : ControllerAction - { - public string transitionName; - public int playTimes; - public float delay; - public bool stopOnExit; - - private Transition _currentTransition; - - public PlayTransitionAction() - { - playTimes = 1; - delay = 0; - } - - override protected void Enter(Controller controller) - { - Transition trans = controller.parent.GetTransition(transitionName); - if (trans != null) - { - if (_currentTransition != null && _currentTransition.playing) - trans.ChangePlayTimes(playTimes); - else - trans.Play(playTimes, delay, null); - _currentTransition = trans; - } - } - - override protected void Leave(Controller controller) - { - if (stopOnExit && _currentTransition != null) - { - _currentTransition.Stop(); - _currentTransition = null; - } - } - - override public void Setup(ByteBuffer buffer) - { - base.Setup(buffer); - - transitionName = buffer.ReadS(); - playTimes = buffer.ReadInt(); - delay = buffer.ReadFloat(); - stopOnExit = buffer.ReadBool(); - } - } -} +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class PlayTransitionAction : ControllerAction + { + public string transitionName; + public int playTimes; + public float delay; + public bool stopOnExit; + + private Transition _currentTransition; + + public PlayTransitionAction() + { + playTimes = 1; + delay = 0; + } + + override protected void Enter(Controller controller) + { + Transition trans = controller.parent.GetTransition(transitionName); + if (trans != null) + { + if (_currentTransition != null && _currentTransition.playing) + trans.ChangePlayTimes(playTimes); + else + trans.Play(playTimes, delay, null); + _currentTransition = trans; + } + } + + override protected void Leave(Controller controller) + { + if (stopOnExit && _currentTransition != null) + { + _currentTransition.Stop(); + _currentTransition = null; + } + } + + override public void Setup(ByteBuffer buffer) + { + base.Setup(buffer); + + transitionName = buffer.ReadS(); + playTimes = buffer.ReadInt(); + delay = buffer.ReadFloat(); + stopOnExit = buffer.ReadBool(); + } + } +} diff --git a/Assets/Scripts/UI/Action/PlayTransitionAction.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/PlayTransitionAction.cs.meta similarity index 100% rename from Assets/Scripts/UI/Action/PlayTransitionAction.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Action/PlayTransitionAction.cs.meta diff --git a/Assets/Scripts/UI/AsyncCreationHelper.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/AsyncCreationHelper.cs similarity index 97% rename from Assets/Scripts/UI/AsyncCreationHelper.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/AsyncCreationHelper.cs index 4db7a0d1..c415aff9 100644 --- a/Assets/Scripts/UI/AsyncCreationHelper.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/AsyncCreationHelper.cs @@ -1,189 +1,189 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - public class AsyncCreationHelper - { - public static void CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) - { - Timers.inst.StartCoroutine(_CreateObject(item, callback)); - } - - static IEnumerator _CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) - { - Stats.LatestObjectCreation = 0; - Stats.LatestGraphicsCreation = 0; - - float frameTime = UIConfig.frameTimeForAsyncUIConstruction; - - List itemList = new List(); - DisplayListItem di = new DisplayListItem(item, ObjectType.Component); - di.childCount = CollectComponentChildren(item, itemList); - itemList.Add(di); - - int cnt = itemList.Count; - List objectPool = new List(cnt); - GObject obj; - float t = Time.realtimeSinceStartup; - bool alreadyNextFrame = false; - - for (int i = 0; i < cnt; i++) - { - di = itemList[i]; - if (di.packageItem != null) - { - obj = UIObjectFactory.NewObject(di.packageItem); - objectPool.Add(obj); - - UIPackage._constructing++; - if (di.packageItem.type == PackageItemType.Component) - { - int poolStart = objectPool.Count - di.childCount - 1; - - ((GComponent)obj).ConstructFromResource(objectPool, poolStart); - - objectPool.RemoveRange(poolStart, di.childCount); - } - else - { - obj.ConstructFromResource(); - } - UIPackage._constructing--; - } - else - { - obj = UIObjectFactory.NewObject(di.type); - objectPool.Add(obj); - - if (di.type == ObjectType.List && di.listItemCount > 0) - { - int poolStart = objectPool.Count - di.listItemCount - 1; - for (int k = 0; k < di.listItemCount; k++) //把他们都放到pool里,这样GList在创建时就不需要创建对象了 - ((GList)obj).itemPool.ReturnObject(objectPool[k + poolStart]); - objectPool.RemoveRange(poolStart, di.listItemCount); - } - } - - if ((i % 5 == 0) && Time.realtimeSinceStartup - t >= frameTime) - { - yield return null; - t = Time.realtimeSinceStartup; - alreadyNextFrame = true; - } - } - - if (!alreadyNextFrame) //强制至至少下一帧才调用callback,避免调用者逻辑出错 - yield return null; - - callback(objectPool[0]); - } - - /// - /// 收集创建目标对象所需的所有类型信息 - /// - /// - /// - static int CollectComponentChildren(PackageItem item, List list) - { - ByteBuffer buffer = item.rawData; - buffer.Seek(0, 2); - - int dcnt = buffer.ReadShort(); - DisplayListItem di; - PackageItem pi; - for (int i = 0; i < dcnt; i++) - { - int dataLen = buffer.ReadShort(); - int curPos = buffer.position; - - buffer.Seek(curPos, 0); - - ObjectType type = (ObjectType)buffer.ReadByte(); - string src = buffer.ReadS(); - string pkgId = buffer.ReadS(); - - buffer.position = curPos; - - if (src != null) - { - UIPackage pkg; - if (pkgId != null) - pkg = UIPackage.GetById(pkgId); - else - pkg = item.owner; - - pi = pkg != null ? pkg.GetItem(src) : null; - di = new DisplayListItem(pi, type); - - if (pi != null && pi.type == PackageItemType.Component) - di.childCount = CollectComponentChildren(pi, list); - } - else - { - di = new DisplayListItem(null, type); - if (type == ObjectType.List) //list - di.listItemCount = CollectListChildren(buffer, list); - } - - list.Add(di); - buffer.position = curPos + dataLen; - } - - return dcnt; - } - - static int CollectListChildren(ByteBuffer buffer, List list) - { - buffer.Seek(buffer.position, 8); - - string defaultItem = buffer.ReadS(); - int listItemCount = 0; - int itemCount = buffer.ReadShort(); - for (int i = 0; i < itemCount; i++) - { - int nextPos = buffer.ReadShort(); - nextPos += buffer.position; - - string url = buffer.ReadS(); - if (url == null) - url = defaultItem; - if (!string.IsNullOrEmpty(url)) - { - PackageItem pi = UIPackage.GetItemByURL(url); - if (pi != null) - { - DisplayListItem di = new DisplayListItem(pi, pi.objectType); - if (pi.type == PackageItemType.Component) - di.childCount = CollectComponentChildren(pi, list); - - list.Add(di); - listItemCount++; - } - } - buffer.position = nextPos; - } - - return listItemCount; - } - - /// - /// - /// - class DisplayListItem - { - public PackageItem packageItem; - public ObjectType type; - public int childCount; - public int listItemCount; - - public DisplayListItem(PackageItem pi, ObjectType type) - { - this.packageItem = pi; - this.type = type; - } - } - } -} +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class AsyncCreationHelper + { + public static void CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) + { + Timers.inst.StartCoroutine(_CreateObject(item, callback)); + } + + static IEnumerator _CreateObject(PackageItem item, UIPackage.CreateObjectCallback callback) + { + Stats.LatestObjectCreation = 0; + Stats.LatestGraphicsCreation = 0; + + float frameTime = UIConfig.frameTimeForAsyncUIConstruction; + + List itemList = new List(); + DisplayListItem di = new DisplayListItem(item, ObjectType.Component); + di.childCount = CollectComponentChildren(item, itemList); + itemList.Add(di); + + int cnt = itemList.Count; + List objectPool = new List(cnt); + GObject obj; + float t = Time.realtimeSinceStartup; + bool alreadyNextFrame = false; + + for (int i = 0; i < cnt; i++) + { + di = itemList[i]; + if (di.packageItem != null) + { + obj = UIObjectFactory.NewObject(di.packageItem); + objectPool.Add(obj); + + UIPackage._constructing++; + if (di.packageItem.type == PackageItemType.Component) + { + int poolStart = objectPool.Count - di.childCount - 1; + + ((GComponent)obj).ConstructFromResource(objectPool, poolStart); + + objectPool.RemoveRange(poolStart, di.childCount); + } + else + { + obj.ConstructFromResource(); + } + UIPackage._constructing--; + } + else + { + obj = UIObjectFactory.NewObject(di.type); + objectPool.Add(obj); + + if (di.type == ObjectType.List && di.listItemCount > 0) + { + int poolStart = objectPool.Count - di.listItemCount - 1; + for (int k = 0; k < di.listItemCount; k++) //把他们都放到pool里,这样GList在创建时就不需要创建对象了 + ((GList)obj).itemPool.ReturnObject(objectPool[k + poolStart]); + objectPool.RemoveRange(poolStart, di.listItemCount); + } + } + + if ((i % 5 == 0) && Time.realtimeSinceStartup - t >= frameTime) + { + yield return null; + t = Time.realtimeSinceStartup; + alreadyNextFrame = true; + } + } + + if (!alreadyNextFrame) //强制至至少下一帧才调用callback,避免调用者逻辑出错 + yield return null; + + callback(objectPool[0]); + } + + /// + /// 收集创建目标对象所需的所有类型信息 + /// + /// + /// + static int CollectComponentChildren(PackageItem item, List list) + { + ByteBuffer buffer = item.rawData; + buffer.Seek(0, 2); + + int dcnt = buffer.ReadShort(); + DisplayListItem di; + PackageItem pi; + for (int i = 0; i < dcnt; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + buffer.Seek(curPos, 0); + + ObjectType type = (ObjectType)buffer.ReadByte(); + string src = buffer.ReadS(); + string pkgId = buffer.ReadS(); + + buffer.position = curPos; + + if (src != null) + { + UIPackage pkg; + if (pkgId != null) + pkg = UIPackage.GetById(pkgId); + else + pkg = item.owner; + + pi = pkg != null ? pkg.GetItem(src) : null; + di = new DisplayListItem(pi, type); + + if (pi != null && pi.type == PackageItemType.Component) + di.childCount = CollectComponentChildren(pi, list); + } + else + { + di = new DisplayListItem(null, type); + if (type == ObjectType.List) //list + di.listItemCount = CollectListChildren(buffer, list); + } + + list.Add(di); + buffer.position = curPos + dataLen; + } + + return dcnt; + } + + static int CollectListChildren(ByteBuffer buffer, List list) + { + buffer.Seek(buffer.position, 8); + + string defaultItem = buffer.ReadS(); + int listItemCount = 0; + int itemCount = buffer.ReadShort(); + for (int i = 0; i < itemCount; i++) + { + int nextPos = buffer.ReadShort(); + nextPos += buffer.position; + + string url = buffer.ReadS(); + if (url == null) + url = defaultItem; + if (!string.IsNullOrEmpty(url)) + { + PackageItem pi = UIPackage.GetItemByURL(url); + if (pi != null) + { + DisplayListItem di = new DisplayListItem(pi, pi.objectType); + if (pi.type == PackageItemType.Component) + di.childCount = CollectComponentChildren(pi, list); + + list.Add(di); + listItemCount++; + } + } + buffer.position = nextPos; + } + + return listItemCount; + } + + /// + /// + /// + class DisplayListItem + { + public PackageItem packageItem; + public ObjectType type; + public int childCount; + public int listItemCount; + + public DisplayListItem(PackageItem pi, ObjectType type) + { + this.packageItem = pi; + this.type = type; + } + } + } +} diff --git a/Assets/Scripts/UI/AsyncCreationHelper.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/AsyncCreationHelper.cs.meta similarity index 100% rename from Assets/Scripts/UI/AsyncCreationHelper.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/AsyncCreationHelper.cs.meta diff --git a/Assets/Scripts/UI/Controller.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Controller.cs similarity index 96% rename from Assets/Scripts/UI/Controller.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Controller.cs index 94e9ce82..039942a0 100644 --- a/Assets/Scripts/UI/Controller.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Controller.cs @@ -1,440 +1,440 @@ -using System.Collections.Generic; -using FairyGUI.Utils; -using System; - -namespace FairyGUI -{ - /// - /// Controller class. - /// 控制器类。控制器的创建和设计需通过编辑器完成,不建议使用代码创建。 - /// 最常用的方法是通过selectedIndex获得或改变控制器的活动页面。如果要获得控制器页面改变的通知,使用onChanged事件。 - /// - public class Controller : EventDispatcher - { - /// - /// Name of the controller - /// 控制器名称。 - /// - public string name; - - internal GComponent parent; - internal bool autoRadioGroupDepth; - internal bool changing; - - int _selectedIndex; - int _previousIndex; - List _pageIds; - List _pageNames; - List _actions; - - EventListener _onChanged; - - static uint _nextPageId; - - public Controller() - { - _pageIds = new List(); - _pageNames = new List(); - _selectedIndex = -1; - _previousIndex = -1; - } - - public void Dispose() - { - RemoveEventListeners(); - } - - - /// - /// When controller page changed. - /// 当控制器活动页面改变时,此事件被触发。 - /// - public EventListener onChanged - { - get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } - } - - /// - /// Current page index. - /// 获得或设置当前活动页面索引。 - /// - public int selectedIndex - { - get - { - return _selectedIndex; - } - set - { - if (_selectedIndex != value) - { - if (value > _pageIds.Count - 1) - throw new IndexOutOfRangeException("" + value); - - changing = true; - - _previousIndex = _selectedIndex; - _selectedIndex = value; - parent.ApplyController(this); - - DispatchEvent("onChanged", null); - - changing = false; - } - } - } - - /// - /// Set current page index, no onChanged event. - /// 通过索引设置当前活动页面,和selectedIndex的区别在于,这个方法不会触发onChanged事件。 - /// - /// Page index - public void SetSelectedIndex(int value) - { - if (_selectedIndex != value) - { - if (value > _pageIds.Count - 1) - throw new IndexOutOfRangeException("" + value); - - changing = true; - _previousIndex = _selectedIndex; - _selectedIndex = value; - parent.ApplyController(this); - changing = false; - } - } - - /// - /// Set current page by name, no onChanged event. - /// 通过页面名称设置当前活动页面,和selectedPage的区别在于,这个方法不会触发onChanged事件。 - /// - /// Page name - public void SetSelectedPage(string value) - { - int i = _pageNames.IndexOf(value); - if (i == -1) - i = 0; - this.SetSelectedIndex(i); - } - - /// - /// Current page name. - /// 获得当前活动页面名称 - /// - public string selectedPage - { - get - { - if (_selectedIndex == -1) - return null; - else - return _pageNames[_selectedIndex]; - } - set - { - int i = _pageNames.IndexOf(value); - if (i == -1) - i = 0; - this.selectedIndex = i; - } - } - - [Obsolete("Use previousIndex")] - public int previsousIndex - { - get { return _previousIndex; } - } - - /// - /// Previouse page index. - /// 获得上次活动页面索引 - /// - public int previousIndex - { - get { return _previousIndex; } - } - - /// - /// Previous page name. - /// 获得上次活动页面名称。 - /// - public string previousPage - { - get - { - if (_previousIndex == -1) - return null; - else - return _pageNames[_previousIndex]; - } - } - - /// - /// Page count of this controller. - /// 获得页面数量。 - /// - public int pageCount - { - get { return _pageIds.Count; } - } - - /// - /// Get page name by an index. - /// 通过页面索引获得页面名称。 - /// - /// Page index - /// Page Name - public string GetPageName(int index) - { - return _pageNames[index]; - } - - /// - /// Get page id by an index. - /// 通过页面索引获得页面id。 - /// - /// Page index - /// Page Id - public string GetPageId(int index) - { - return _pageIds[index]; - } - - /// - /// Get page id by name - /// - /// - /// - public string GetPageIdByName(string aName) - { - int i = _pageNames.IndexOf(aName); - if (i != -1) - return _pageIds[i]; - else - return null; - } - - /// - /// Add a new page to this controller. - /// - /// Page name - public void AddPage(string name) - { - if (name == null) - name = string.Empty; - - AddPageAt(name, _pageIds.Count); - } - - /// - /// Add a new page to this controller at a certain index. - /// - /// Page name - /// Insert position - public void AddPageAt(string name, int index) - { - string nid = "_" + (_nextPageId++); - if (index == _pageIds.Count) - { - _pageIds.Add(nid); - _pageNames.Add(name); - } - else - { - _pageIds.Insert(index, nid); - _pageNames.Insert(index, name); - } - } - - /// - /// Remove a page. - /// - /// Page name - public void RemovePage(string name) - { - int i = _pageNames.IndexOf(name); - if (i != -1) - { - _pageIds.RemoveAt(i); - _pageNames.RemoveAt(i); - if (_selectedIndex >= _pageIds.Count) - this.selectedIndex = _selectedIndex - 1; - else - parent.ApplyController(this); - } - } - - /// - /// Removes a page at a certain index. - /// - /// - public void RemovePageAt(int index) - { - _pageIds.RemoveAt(index); - _pageNames.RemoveAt(index); - if (_selectedIndex >= _pageIds.Count) - this.selectedIndex = _selectedIndex - 1; - else - parent.ApplyController(this); - } - - /// - /// Remove all pages. - /// - public void ClearPages() - { - _pageIds.Clear(); - _pageNames.Clear(); - if (_selectedIndex != -1) - this.selectedIndex = -1; - else - parent.ApplyController(this); - } - - /// - /// Check if the controller has a page. - /// - /// Page name. - /// - public bool HasPage(string aName) - { - return _pageNames.IndexOf(aName) != -1; - } - - internal int GetPageIndexById(string aId) - { - return _pageIds.IndexOf(aId); - } - - internal string GetPageNameById(string aId) - { - int i = _pageIds.IndexOf(aId); - if (i != -1) - return _pageNames[i]; - else - return null; - } - - internal string selectedPageId - { - get - { - if (_selectedIndex == -1) - return string.Empty; - else - return _pageIds[_selectedIndex]; - } - set - { - int i = _pageIds.IndexOf(value); - if (i != -1) - this.selectedIndex = i; - } - } - - internal string oppositePageId - { - set - { - int i = _pageIds.IndexOf(value); - if (i > 0) - this.selectedIndex = 0; - else if (_pageIds.Count > 1) - this.selectedIndex = 1; - } - } - - internal string previousPageId - { - get - { - if (_previousIndex == -1) - return null; - else - return _pageIds[_previousIndex]; - } - } - - public void RunActions() - { - if (_actions != null) - { - int cnt = _actions.Count; - for (int i = 0; i < cnt; i++) - { - _actions[i].Run(this, previousPageId, selectedPageId); - } - } - } - - public void Setup(ByteBuffer buffer) - { - int beginPos = buffer.position; - buffer.Seek(beginPos, 0); - - name = buffer.ReadS(); - autoRadioGroupDepth = buffer.ReadBool(); - - buffer.Seek(beginPos, 1); - - int cnt = buffer.ReadShort(); - _pageIds.Capacity = cnt; - _pageNames.Capacity = cnt; - for (int i = 0; i < cnt; i++) - { - _pageIds.Add(buffer.ReadS()); - _pageNames.Add(buffer.ReadS()); - } - - int homePageIndex = 0; - if (buffer.version >= 2) - { - int homePageType = buffer.ReadByte(); - switch (homePageType) - { - case 1: - homePageIndex = buffer.ReadShort(); - break; - - case 2: - homePageIndex = _pageNames.IndexOf(UIPackage.branch); - if (homePageIndex == -1) - homePageIndex = 0; - break; - - case 3: - homePageIndex = _pageNames.IndexOf(UIPackage.GetVar(buffer.ReadS())); - if (homePageIndex == -1) - homePageIndex = 0; - break; - } - } - - buffer.Seek(beginPos, 2); - - cnt = buffer.ReadShort(); - if (cnt > 0) - { - if (_actions == null) - _actions = new List(cnt); - - for (int i = 0; i < cnt; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - ControllerAction action = ControllerAction.CreateAction((ControllerAction.ActionType)buffer.ReadByte()); - action.Setup(buffer); - _actions.Add(action); - - buffer.position = nextPos; - } - } - - if (parent != null && _pageIds.Count > 0) - _selectedIndex = homePageIndex; - else - _selectedIndex = -1; - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; +using System; + +namespace FairyGUI +{ + /// + /// Controller class. + /// 控制器类。控制器的创建和设计需通过编辑器完成,不建议使用代码创建。 + /// 最常用的方法是通过selectedIndex获得或改变控制器的活动页面。如果要获得控制器页面改变的通知,使用onChanged事件。 + /// + public class Controller : EventDispatcher + { + /// + /// Name of the controller + /// 控制器名称。 + /// + public string name; + + internal GComponent parent; + internal bool autoRadioGroupDepth; + internal bool changing; + + int _selectedIndex; + int _previousIndex; + List _pageIds; + List _pageNames; + List _actions; + + EventListener _onChanged; + + static uint _nextPageId; + + public Controller() + { + _pageIds = new List(); + _pageNames = new List(); + _selectedIndex = -1; + _previousIndex = -1; + } + + public void Dispose() + { + RemoveEventListeners(); + } + + + /// + /// When controller page changed. + /// 当控制器活动页面改变时,此事件被触发。 + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// Current page index. + /// 获得或设置当前活动页面索引。 + /// + public int selectedIndex + { + get + { + return _selectedIndex; + } + set + { + if (_selectedIndex != value) + { + if (value > _pageIds.Count - 1) + throw new IndexOutOfRangeException("" + value); + + changing = true; + + _previousIndex = _selectedIndex; + _selectedIndex = value; + parent.ApplyController(this); + + DispatchEvent("onChanged", null); + + changing = false; + } + } + } + + /// + /// Set current page index, no onChanged event. + /// 通过索引设置当前活动页面,和selectedIndex的区别在于,这个方法不会触发onChanged事件。 + /// + /// Page index + public void SetSelectedIndex(int value) + { + if (_selectedIndex != value) + { + if (value > _pageIds.Count - 1) + throw new IndexOutOfRangeException("" + value); + + changing = true; + _previousIndex = _selectedIndex; + _selectedIndex = value; + parent.ApplyController(this); + changing = false; + } + } + + /// + /// Set current page by name, no onChanged event. + /// 通过页面名称设置当前活动页面,和selectedPage的区别在于,这个方法不会触发onChanged事件。 + /// + /// Page name + public void SetSelectedPage(string value) + { + int i = _pageNames.IndexOf(value); + if (i == -1) + i = 0; + this.SetSelectedIndex(i); + } + + /// + /// Current page name. + /// 获得当前活动页面名称 + /// + public string selectedPage + { + get + { + if (_selectedIndex == -1) + return null; + else + return _pageNames[_selectedIndex]; + } + set + { + int i = _pageNames.IndexOf(value); + if (i == -1) + i = 0; + this.selectedIndex = i; + } + } + + [Obsolete("Use previousIndex")] + public int previsousIndex + { + get { return _previousIndex; } + } + + /// + /// Previouse page index. + /// 获得上次活动页面索引 + /// + public int previousIndex + { + get { return _previousIndex; } + } + + /// + /// Previous page name. + /// 获得上次活动页面名称。 + /// + public string previousPage + { + get + { + if (_previousIndex == -1) + return null; + else + return _pageNames[_previousIndex]; + } + } + + /// + /// Page count of this controller. + /// 获得页面数量。 + /// + public int pageCount + { + get { return _pageIds.Count; } + } + + /// + /// Get page name by an index. + /// 通过页面索引获得页面名称。 + /// + /// Page index + /// Page Name + public string GetPageName(int index) + { + return _pageNames[index]; + } + + /// + /// Get page id by an index. + /// 通过页面索引获得页面id。 + /// + /// Page index + /// Page Id + public string GetPageId(int index) + { + return _pageIds[index]; + } + + /// + /// Get page id by name + /// + /// + /// + public string GetPageIdByName(string aName) + { + int i = _pageNames.IndexOf(aName); + if (i != -1) + return _pageIds[i]; + else + return null; + } + + /// + /// Add a new page to this controller. + /// + /// Page name + public void AddPage(string name) + { + if (name == null) + name = string.Empty; + + AddPageAt(name, _pageIds.Count); + } + + /// + /// Add a new page to this controller at a certain index. + /// + /// Page name + /// Insert position + public void AddPageAt(string name, int index) + { + string nid = "_" + (_nextPageId++); + if (index == _pageIds.Count) + { + _pageIds.Add(nid); + _pageNames.Add(name); + } + else + { + _pageIds.Insert(index, nid); + _pageNames.Insert(index, name); + } + } + + /// + /// Remove a page. + /// + /// Page name + public void RemovePage(string name) + { + int i = _pageNames.IndexOf(name); + if (i != -1) + { + _pageIds.RemoveAt(i); + _pageNames.RemoveAt(i); + if (_selectedIndex >= _pageIds.Count) + this.selectedIndex = _selectedIndex - 1; + else + parent.ApplyController(this); + } + } + + /// + /// Removes a page at a certain index. + /// + /// + public void RemovePageAt(int index) + { + _pageIds.RemoveAt(index); + _pageNames.RemoveAt(index); + if (_selectedIndex >= _pageIds.Count) + this.selectedIndex = _selectedIndex - 1; + else + parent.ApplyController(this); + } + + /// + /// Remove all pages. + /// + public void ClearPages() + { + _pageIds.Clear(); + _pageNames.Clear(); + if (_selectedIndex != -1) + this.selectedIndex = -1; + else + parent.ApplyController(this); + } + + /// + /// Check if the controller has a page. + /// + /// Page name. + /// + public bool HasPage(string aName) + { + return _pageNames.IndexOf(aName) != -1; + } + + internal int GetPageIndexById(string aId) + { + return _pageIds.IndexOf(aId); + } + + internal string GetPageNameById(string aId) + { + int i = _pageIds.IndexOf(aId); + if (i != -1) + return _pageNames[i]; + else + return null; + } + + internal string selectedPageId + { + get + { + if (_selectedIndex == -1) + return string.Empty; + else + return _pageIds[_selectedIndex]; + } + set + { + int i = _pageIds.IndexOf(value); + if (i != -1) + this.selectedIndex = i; + } + } + + internal string oppositePageId + { + set + { + int i = _pageIds.IndexOf(value); + if (i > 0) + this.selectedIndex = 0; + else if (_pageIds.Count > 1) + this.selectedIndex = 1; + } + } + + internal string previousPageId + { + get + { + if (_previousIndex == -1) + return null; + else + return _pageIds[_previousIndex]; + } + } + + public void RunActions() + { + if (_actions != null) + { + int cnt = _actions.Count; + for (int i = 0; i < cnt; i++) + { + _actions[i].Run(this, previousPageId, selectedPageId); + } + } + } + + public void Setup(ByteBuffer buffer) + { + int beginPos = buffer.position; + buffer.Seek(beginPos, 0); + + name = buffer.ReadS(); + autoRadioGroupDepth = buffer.ReadBool(); + + buffer.Seek(beginPos, 1); + + int cnt = buffer.ReadShort(); + _pageIds.Capacity = cnt; + _pageNames.Capacity = cnt; + for (int i = 0; i < cnt; i++) + { + _pageIds.Add(buffer.ReadS()); + _pageNames.Add(buffer.ReadS()); + } + + int homePageIndex = 0; + if (buffer.version >= 2) + { + int homePageType = buffer.ReadByte(); + switch (homePageType) + { + case 1: + homePageIndex = buffer.ReadShort(); + break; + + case 2: + homePageIndex = _pageNames.IndexOf(UIPackage.branch); + if (homePageIndex == -1) + homePageIndex = 0; + break; + + case 3: + homePageIndex = _pageNames.IndexOf(UIPackage.GetVar(buffer.ReadS())); + if (homePageIndex == -1) + homePageIndex = 0; + break; + } + } + + buffer.Seek(beginPos, 2); + + cnt = buffer.ReadShort(); + if (cnt > 0) + { + if (_actions == null) + _actions = new List(cnt); + + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + ControllerAction action = ControllerAction.CreateAction((ControllerAction.ActionType)buffer.ReadByte()); + action.Setup(buffer); + _actions.Add(action); + + buffer.position = nextPos; + } + } + + if (parent != null && _pageIds.Count > 0) + _selectedIndex = homePageIndex; + else + _selectedIndex = -1; + } + } +} diff --git a/Assets/Scripts/UI/Controller.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Controller.cs.meta similarity index 100% rename from Assets/Scripts/UI/Controller.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Controller.cs.meta diff --git a/Assets/Scripts/UI/DragDropManager.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/DragDropManager.cs similarity index 96% rename from Assets/Scripts/UI/DragDropManager.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/DragDropManager.cs index ff27908b..0cc0df98 100644 --- a/Assets/Scripts/UI/DragDropManager.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/DragDropManager.cs @@ -1,122 +1,122 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// Helper for drag and drop. - /// 这是一个提供特殊拖放功能的功能类。与GObject.draggable不同,拖动开始后,他使用一个替代的图标作为拖动对象。 - /// 当玩家释放鼠标/手指,目标组件会发出一个onDrop事件。 - /// - public class DragDropManager - { - private GLoader _agent; - private object _sourceData; - private GObject _source; - - private static DragDropManager _inst; - public static DragDropManager inst - { - get - { - if (_inst == null) - _inst = new DragDropManager(); - return _inst; - } - } - - public DragDropManager() - { - _agent = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader); - _agent.gameObjectName = "DragDropAgent"; - _agent.SetHome(GRoot.inst); - _agent.touchable = false;//important - _agent.draggable = true; - _agent.SetSize(100, 100); - _agent.SetPivot(0.5f, 0.5f, true); - _agent.align = AlignType.Center; - _agent.verticalAlign = VertAlignType.Middle; - _agent.sortingOrder = int.MaxValue; - _agent.onDragEnd.Add(__dragEnd); - } - - /// - /// Loader object for real dragging. - /// 用于实际拖动的Loader对象。你可以根据实际情况设置loader的大小,对齐等。 - /// - public GLoader dragAgent - { - get { return _agent; } - } - - /// - /// Is dragging? - /// 返回当前是否正在拖动。 - /// - public bool dragging - { - get { return _agent.parent != null; } - } - - /// - /// Start dragging. - /// 开始拖动。 - /// - /// Source object. This is the object which initiated the dragging. - /// Icon to be used as the dragging sign. - /// Custom data. You can get it in the onDrop event data. - /// Copy the touchId from InputEvent to here, if has one. - public void StartDrag(GObject source, string icon, object sourceData, int touchPointID = -1) - { - if (_agent.parent != null) - return; - - _sourceData = sourceData; - _source = source; - _agent.url = icon; - GRoot.inst.AddChild(_agent); - _agent.xy = GRoot.inst.GlobalToLocal(Stage.inst.GetTouchPosition(touchPointID)); - _agent.StartDrag(touchPointID); - } - - /// - /// Cancel dragging. - /// 取消拖动。 - /// - public void Cancel() - { - if (_agent.parent != null) - { - _agent.StopDrag(); - GRoot.inst.RemoveChild(_agent); - _sourceData = null; - } - } - - private void __dragEnd(EventContext evt) - { - if (_agent.parent == null) //cancelled - return; - - GRoot.inst.RemoveChild(_agent); - - object sourceData = _sourceData; - GObject source = _source; - _sourceData = null; - _source = null; - - GObject obj = GRoot.inst.touchTarget; - while (obj != null) - { - if (obj.hasEventListeners("onDrop")) - { - obj.RequestFocus(); - obj.DispatchEvent("onDrop", sourceData, source); - return; - } - obj = obj.parent; - } - } - } +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Helper for drag and drop. + /// 这是一个提供特殊拖放功能的功能类。与GObject.draggable不同,拖动开始后,他使用一个替代的图标作为拖动对象。 + /// 当玩家释放鼠标/手指,目标组件会发出一个onDrop事件。 + /// + public class DragDropManager + { + private GLoader _agent; + private object _sourceData; + private GObject _source; + + private static DragDropManager _inst; + public static DragDropManager inst + { + get + { + if (_inst == null) + _inst = new DragDropManager(); + return _inst; + } + } + + public DragDropManager() + { + _agent = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader); + _agent.gameObjectName = "DragDropAgent"; + _agent.SetHome(GRoot.inst); + _agent.touchable = false;//important + _agent.draggable = true; + _agent.SetSize(100, 100); + _agent.SetPivot(0.5f, 0.5f, true); + _agent.align = AlignType.Center; + _agent.verticalAlign = VertAlignType.Middle; + _agent.sortingOrder = int.MaxValue; + _agent.onDragEnd.Add(__dragEnd); + } + + /// + /// Loader object for real dragging. + /// 用于实际拖动的Loader对象。你可以根据实际情况设置loader的大小,对齐等。 + /// + public GLoader dragAgent + { + get { return _agent; } + } + + /// + /// Is dragging? + /// 返回当前是否正在拖动。 + /// + public bool dragging + { + get { return _agent.parent != null; } + } + + /// + /// Start dragging. + /// 开始拖动。 + /// + /// Source object. This is the object which initiated the dragging. + /// Icon to be used as the dragging sign. + /// Custom data. You can get it in the onDrop event data. + /// Copy the touchId from InputEvent to here, if has one. + public void StartDrag(GObject source, string icon, object sourceData, int touchPointID = -1) + { + if (_agent.parent != null) + return; + + _sourceData = sourceData; + _source = source; + _agent.url = icon; + GRoot.inst.AddChild(_agent); + _agent.xy = GRoot.inst.GlobalToLocal(Stage.inst.GetTouchPosition(touchPointID)); + _agent.StartDrag(touchPointID); + } + + /// + /// Cancel dragging. + /// 取消拖动。 + /// + public void Cancel() + { + if (_agent.parent != null) + { + _agent.StopDrag(); + GRoot.inst.RemoveChild(_agent); + _sourceData = null; + } + } + + private void __dragEnd(EventContext evt) + { + if (_agent.parent == null) //cancelled + return; + + GRoot.inst.RemoveChild(_agent); + + object sourceData = _sourceData; + GObject source = _source; + _sourceData = null; + _source = null; + + GObject obj = GRoot.inst.touchTarget; + while (obj != null) + { + if (obj.hasEventListeners("onDrop")) + { + obj.RequestFocus(); + obj.DispatchEvent("onDrop", sourceData, source); + return; + } + obj = obj.parent; + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/UI/DragDropManager.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/DragDropManager.cs.meta similarity index 100% rename from Assets/Scripts/UI/DragDropManager.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/DragDropManager.cs.meta diff --git a/Assets/Scripts/UI/EMRenderSupport.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/EMRenderSupport.cs similarity index 96% rename from Assets/Scripts/UI/EMRenderSupport.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/EMRenderSupport.cs index da19a177..ae92925a 100644 --- a/Assets/Scripts/UI/EMRenderSupport.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/EMRenderSupport.cs @@ -1,129 +1,129 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public interface EMRenderTarget - { - int EM_sortingOrder { get; } - - void EM_BeforeUpdate(); - void EM_Update(UpdateContext context); - void EM_Reload(); - } - - /// - /// 这是一个在编辑状态下渲染UI的功能类。EM=Edit Mode - /// - public class EMRenderSupport - { - /// - /// - /// - public static bool orderChanged; - - static UpdateContext _updateContext; - static List _targets = new List(); - - /// - /// - /// - public static bool packageListReady { get; private set; } - - /// - /// - /// - public static bool hasTarget - { - get { return _targets.Count > 0; } - } - - /// - /// - /// - /// - public static void Add(EMRenderTarget value) - { - if (!_targets.Contains(value)) - _targets.Add(value); - orderChanged = true; - } - - /// - /// - /// - /// - public static void Remove(EMRenderTarget value) - { - _targets.Remove(value); - } - - /// - /// 由StageCamera调用 - /// - public static void Update() - { - if (Application.isPlaying) - return; - - if (_updateContext == null) - _updateContext = new UpdateContext(); - - if (orderChanged) - { - _targets.Sort(CompareDepth); - orderChanged = false; - } - - int cnt = _targets.Count; - for (int i = 0; i < cnt; i++) - { - EMRenderTarget panel = _targets[i]; - panel.EM_BeforeUpdate(); - } - - if (packageListReady) - { - _updateContext.Begin(); - for (int i = 0; i < cnt; i++) - { - EMRenderTarget panel = _targets[i]; - panel.EM_Update(_updateContext); - } - _updateContext.End(); - } - } - - /// - /// 当发生二进制重载时,或用户点击刷新菜单 - /// - public static void Reload() - { - if (Application.isPlaying) - return; - - UIConfig.ClearResourceRefs(); - UIConfig[] configs = GameObject.FindObjectsOfType(); - foreach (UIConfig config in configs) - config.Load(); - - packageListReady = true; - - int cnt = _targets.Count; - for (int i = 0; i < cnt; i++) - { - EMRenderTarget panel = _targets[i]; - panel.EM_Reload(); - } - } - - static int CompareDepth(EMRenderTarget c1, EMRenderTarget c2) - { - return c1.EM_sortingOrder - c2.EM_sortingOrder; - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public interface EMRenderTarget + { + int EM_sortingOrder { get; } + + void EM_BeforeUpdate(); + void EM_Update(UpdateContext context); + void EM_Reload(); + } + + /// + /// 这是一个在编辑状态下渲染UI的功能类。EM=Edit Mode + /// + public class EMRenderSupport + { + /// + /// + /// + public static bool orderChanged; + + static UpdateContext _updateContext; + static List _targets = new List(); + + /// + /// + /// + public static bool packageListReady { get; private set; } + + /// + /// + /// + public static bool hasTarget + { + get { return _targets.Count > 0; } + } + + /// + /// + /// + /// + public static void Add(EMRenderTarget value) + { + if (!_targets.Contains(value)) + _targets.Add(value); + orderChanged = true; + } + + /// + /// + /// + /// + public static void Remove(EMRenderTarget value) + { + _targets.Remove(value); + } + + /// + /// 由StageCamera调用 + /// + public static void Update() + { + if (Application.isPlaying) + return; + + if (_updateContext == null) + _updateContext = new UpdateContext(); + + if (orderChanged) + { + _targets.Sort(CompareDepth); + orderChanged = false; + } + + int cnt = _targets.Count; + for (int i = 0; i < cnt; i++) + { + EMRenderTarget panel = _targets[i]; + panel.EM_BeforeUpdate(); + } + + if (packageListReady) + { + _updateContext.Begin(); + for (int i = 0; i < cnt; i++) + { + EMRenderTarget panel = _targets[i]; + panel.EM_Update(_updateContext); + } + _updateContext.End(); + } + } + + /// + /// 当发生二进制重载时,或用户点击刷新菜单 + /// + public static void Reload() + { + if (Application.isPlaying) + return; + + UIConfig.ClearResourceRefs(); + UIConfig[] configs = GameObject.FindObjectsOfType(); + foreach (UIConfig config in configs) + config.Load(); + + packageListReady = true; + + int cnt = _targets.Count; + for (int i = 0; i < cnt; i++) + { + EMRenderTarget panel = _targets[i]; + panel.EM_Reload(); + } + } + + static int CompareDepth(EMRenderTarget c1, EMRenderTarget c2) + { + return c1.EM_sortingOrder - c2.EM_sortingOrder; + } + } +} diff --git a/Assets/Scripts/UI/EMRenderSupport.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/EMRenderSupport.cs.meta similarity index 100% rename from Assets/Scripts/UI/EMRenderSupport.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/EMRenderSupport.cs.meta diff --git a/Assets/Scripts/UI/FieldTypes.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/FieldTypes.cs similarity index 93% rename from Assets/Scripts/UI/FieldTypes.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/FieldTypes.cs index 57f5ffe1..629a44e8 100644 --- a/Assets/Scripts/UI/FieldTypes.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/FieldTypes.cs @@ -1,304 +1,304 @@ -namespace FairyGUI -{ - public enum PackageItemType - { - Image, - MovieClip, - Sound, - Component, - Atlas, - Font, - Swf, - Misc, - Unknown, - Spine, - DragoneBones - } - - public enum ObjectType - { - Image, - MovieClip, - Swf, - Graph, - Loader, - Group, - Text, - RichText, - InputText, - Component, - List, - Label, - Button, - ComboBox, - ProgressBar, - Slider, - ScrollBar, - Tree, - Loader3D - } - - public enum AlignType - { - Left, - Center, - Right - } - - public enum VertAlignType - { - Top, - Middle, - Bottom - } - - public enum OverflowType - { - Visible, - Hidden, - Scroll - } - - public enum FillType - { - None, - Scale, - ScaleMatchHeight, - ScaleMatchWidth, - ScaleFree, - ScaleNoBorder - } - - public enum AutoSizeType - { - None, - Both, - Height, - Shrink, - Ellipsis - } - - public enum ScrollType - { - Horizontal, - Vertical, - Both - } - - public enum ScrollBarDisplayType - { - Default, - Visible, - Auto, - Hidden - } - - public enum RelationType - { - Left_Left, - Left_Center, - Left_Right, - Center_Center, - Right_Left, - Right_Center, - Right_Right, - - Top_Top, - Top_Middle, - Top_Bottom, - Middle_Middle, - Bottom_Top, - Bottom_Middle, - Bottom_Bottom, - - Width, - Height, - - LeftExt_Left, - LeftExt_Right, - RightExt_Left, - RightExt_Right, - TopExt_Top, - TopExt_Bottom, - BottomExt_Top, - BottomExt_Bottom, - - Size - } - - public enum ListLayoutType - { - SingleColumn, - SingleRow, - FlowHorizontal, - FlowVertical, - Pagination - } - - public enum ListSelectionMode - { - Single, - Multiple, - Multiple_SingleClick, - None - } - - public enum ProgressTitleType - { - Percent, - ValueAndMax, - Value, - Max - } - - public enum ButtonMode - { - Common, - Check, - Radio - } - - public enum TransitionActionType - { - XY, - Size, - Scale, - Pivot, - Alpha, - Rotation, - Color, - Animation, - Visible, - Sound, - Transition, - Shake, - ColorFilter, - Skew, - Text, - Icon, - Unknown - } - - public enum GroupLayoutType - { - None, - Horizontal, - Vertical - } - - public enum ChildrenRenderOrder - { - Ascent, - Descent, - Arch, - } - - public enum PopupDirection - { - Auto, - Up, - Down - } - - /// - /// - /// - public enum FlipType - { - None, - Horizontal, - Vertical, - Both - } - - /// - /// - /// - public enum FillMethod - { - None = 0, - - /// - /// The Image will be filled Horizontally - /// - Horizontal = 1, - - /// - /// The Image will be filled Vertically. - /// - Vertical = 2, - - /// - /// The Image will be filled Radially with the radial center in one of the corners. - /// - Radial90 = 3, - - /// - /// The Image will be filled Radially with the radial center in one of the edges. - /// - Radial180 = 4, - - /// - /// The Image will be filled Radially with the radial center at the center. - /// - Radial360 = 5, - } - - /// - /// - /// - public enum OriginHorizontal - { - Left, - Right, - } - - /// - /// - /// - public enum OriginVertical - { - Top, - Bottom - } - - /// - /// - /// - public enum Origin90 - { - TopLeft, - TopRight, - BottomLeft, - BottomRight - } - - /// - /// - /// - public enum Origin180 - { - Top, - Bottom, - Left, - Right - } - - /// - /// - /// - public enum Origin360 - { - Top, - Bottom, - Left, - Right - } - - public enum FocusRule - { - NotFocusable, - Focusable, - NavigationBase - } -} +namespace FairyGUI +{ + public enum PackageItemType + { + Image, + MovieClip, + Sound, + Component, + Atlas, + Font, + Swf, + Misc, + Unknown, + Spine, + DragoneBones + } + + public enum ObjectType + { + Image, + MovieClip, + Swf, + Graph, + Loader, + Group, + Text, + RichText, + InputText, + Component, + List, + Label, + Button, + ComboBox, + ProgressBar, + Slider, + ScrollBar, + Tree, + Loader3D + } + + public enum AlignType + { + Left, + Center, + Right + } + + public enum VertAlignType + { + Top, + Middle, + Bottom + } + + public enum OverflowType + { + Visible, + Hidden, + Scroll + } + + public enum FillType + { + None, + Scale, + ScaleMatchHeight, + ScaleMatchWidth, + ScaleFree, + ScaleNoBorder + } + + public enum AutoSizeType + { + None, + Both, + Height, + Shrink, + Ellipsis + } + + public enum ScrollType + { + Horizontal, + Vertical, + Both + } + + public enum ScrollBarDisplayType + { + Default, + Visible, + Auto, + Hidden + } + + public enum RelationType + { + Left_Left, + Left_Center, + Left_Right, + Center_Center, + Right_Left, + Right_Center, + Right_Right, + + Top_Top, + Top_Middle, + Top_Bottom, + Middle_Middle, + Bottom_Top, + Bottom_Middle, + Bottom_Bottom, + + Width, + Height, + + LeftExt_Left, + LeftExt_Right, + RightExt_Left, + RightExt_Right, + TopExt_Top, + TopExt_Bottom, + BottomExt_Top, + BottomExt_Bottom, + + Size + } + + public enum ListLayoutType + { + SingleColumn, + SingleRow, + FlowHorizontal, + FlowVertical, + Pagination + } + + public enum ListSelectionMode + { + Single, + Multiple, + Multiple_SingleClick, + None + } + + public enum ProgressTitleType + { + Percent, + ValueAndMax, + Value, + Max + } + + public enum ButtonMode + { + Common, + Check, + Radio + } + + public enum TransitionActionType + { + XY, + Size, + Scale, + Pivot, + Alpha, + Rotation, + Color, + Animation, + Visible, + Sound, + Transition, + Shake, + ColorFilter, + Skew, + Text, + Icon, + Unknown + } + + public enum GroupLayoutType + { + None, + Horizontal, + Vertical + } + + public enum ChildrenRenderOrder + { + Ascent, + Descent, + Arch, + } + + public enum PopupDirection + { + Auto, + Up, + Down + } + + /// + /// + /// + public enum FlipType + { + None, + Horizontal, + Vertical, + Both + } + + /// + /// + /// + public enum FillMethod + { + None = 0, + + /// + /// The Image will be filled Horizontally + /// + Horizontal = 1, + + /// + /// The Image will be filled Vertically. + /// + Vertical = 2, + + /// + /// The Image will be filled Radially with the radial center in one of the corners. + /// + Radial90 = 3, + + /// + /// The Image will be filled Radially with the radial center in one of the edges. + /// + Radial180 = 4, + + /// + /// The Image will be filled Radially with the radial center at the center. + /// + Radial360 = 5, + } + + /// + /// + /// + public enum OriginHorizontal + { + Left, + Right, + } + + /// + /// + /// + public enum OriginVertical + { + Top, + Bottom + } + + /// + /// + /// + public enum Origin90 + { + TopLeft, + TopRight, + BottomLeft, + BottomRight + } + + /// + /// + /// + public enum Origin180 + { + Top, + Bottom, + Left, + Right + } + + /// + /// + /// + public enum Origin360 + { + Top, + Bottom, + Left, + Right + } + + public enum FocusRule + { + NotFocusable, + Focusable, + NavigationBase + } +} diff --git a/Assets/Scripts/UI/FieldTypes.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/FieldTypes.cs.meta similarity index 100% rename from Assets/Scripts/UI/FieldTypes.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/FieldTypes.cs.meta diff --git a/Assets/Scripts/UI/GButton.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GButton.cs similarity index 96% rename from Assets/Scripts/UI/GButton.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GButton.cs index f49b9b28..1401912b 100644 --- a/Assets/Scripts/UI/GButton.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GButton.cs @@ -1,657 +1,657 @@ -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GButton class. - /// - public class GButton : GComponent, IColorGear - { - /// - /// Play sound when button is clicked. - /// - public NAudioClip sound; - - /// - /// Volume of the click sound. (0-1) - /// - public float soundVolumeScale; - - /// - /// For radio or checkbox. if false, the button will not change selected status on click. Default is true. - /// 如果为true,对于单选和多选按钮,当玩家点击时,按钮会自动切换状态。设置为false,则不会。默认为true。 - /// - public bool changeStateOnClick; - - /// - /// Show a popup on click. - /// 可以为按钮设置一个关联的组件,当按钮被点击时,此组件被自动弹出。 - /// - public GObject linkedPopup; - - protected GObject _titleObject; - protected GObject _iconObject; - protected Controller _relatedController; - protected string _relatedPageId; - - ButtonMode _mode; - bool _selected; - string _title; - string _icon; - string _selectedTitle; - string _selectedIcon; - Controller _buttonController; - int _downEffect; - float _downEffectValue; - bool _downScaled; - - bool _down; - bool _over; - - EventListener _onChanged; - - public const string UP = "up"; - public const string DOWN = "down"; - public const string OVER = "over"; - public const string SELECTED_OVER = "selectedOver"; - public const string DISABLED = "disabled"; - public const string SELECTED_DISABLED = "selectedDisabled"; - - public GButton() - { - sound = UIConfig.buttonSound; - soundVolumeScale = UIConfig.buttonSoundVolumeScale; - changeStateOnClick = true; - _downEffectValue = 0.8f; - _title = string.Empty; - } - - /// - /// Dispatched when the button status was changed. - /// 如果为单选或多选按钮,当按钮的选中状态发生改变时,此事件触发。 - /// - public EventListener onChanged - { - get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } - } - - /// - /// Icon of the button. - /// - override public string icon - { - get - { - return _icon; - } - set - { - _icon = value; - value = (_selected && _selectedIcon != null) ? _selectedIcon : _icon; - if (_iconObject != null) - _iconObject.icon = value; - UpdateGear(7); - } - } - - /// - /// Title of the button - /// - public string title - { - get - { - return _title; - } - set - { - _title = value; - if (_titleObject != null) - _titleObject.text = (_selected && _selectedTitle != null) ? _selectedTitle : _title; - UpdateGear(6); - } - } - - /// - /// Same of the title. - /// - override public string text - { - get { return this.title; } - set { this.title = value; } - } - - /// - /// Icon value on selected status. - /// - public string selectedIcon - { - get - { - return _selectedIcon; - } - set - { - _selectedIcon = value; - value = (_selected && _selectedIcon != null) ? _selectedIcon : _icon; - if (_iconObject != null) - _iconObject.icon = value; - } - } - - /// - /// Title value on selected status. - /// - public string selectedTitle - { - get - { - return _selectedTitle; - } - set - { - _selectedTitle = value; - if (_titleObject != null) - _titleObject.text = (_selected && _selectedTitle != null) ? _selectedTitle : _title; - } - } - - /// - /// Title color. - /// - public Color titleColor - { - get - { - GTextField tf = GetTextField(); - if (tf != null) - return tf.color; - else - return Color.black; - } - set - { - GTextField tf = GetTextField(); - if (tf != null) - { - tf.color = value; - UpdateGear(4); - } - } - } - - /// - /// - /// - public Color color - { - get { return this.titleColor; } - set { this.titleColor = value; } - } - - /// - /// - /// - public int titleFontSize - { - get - { - GTextField tf = GetTextField(); - if (tf != null) - return tf.textFormat.size; - else - return 0; - } - set - { - GTextField tf = GetTextField(); - if (tf != null) - { - TextFormat format = tf.textFormat; - format.size = value; - tf.textFormat = format; - } - } - } - - /// - /// If the button is in selected status. - /// - public bool selected - { - get - { - return _selected; - } - - set - { - if (_mode == ButtonMode.Common) - return; - - if (_selected != value) - { - _selected = value; - SetCurrentState(); - if (_selectedTitle != null && _titleObject != null) - _titleObject.text = _selected ? _selectedTitle : _title; - if (_selectedIcon != null) - { - string str = _selected ? _selectedIcon : _icon; - if (_iconObject != null) - _iconObject.icon = str; - } - if (_relatedController != null - && parent != null - && !parent._buildingDisplayList) - { - if (_selected) - { - _relatedController.selectedPageId = _relatedPageId; - if (_relatedController.autoRadioGroupDepth) - parent.AdjustRadioGroupDepth(this, _relatedController); - } - else if (_mode == ButtonMode.Check && _relatedController.selectedPageId == _relatedPageId) - _relatedController.oppositePageId = _relatedPageId; - } - } - - } - } - - /// - /// Button mode. - /// - /// - public ButtonMode mode - { - get - { - return _mode; - } - set - { - if (_mode != value) - { - if (value == ButtonMode.Common) - this.selected = false; - _mode = value; - } - } - } - - /// - /// A controller is connected to this button, the activate page of this controller will change while the button status changed. - /// 对应编辑器中的单选控制器。 - /// - public Controller relatedController - { - get - { - return _relatedController; - } - set - { - if (value != _relatedController) - { - _relatedController = value; - _relatedPageId = null; - } - } - } - - /// - /// - /// - public string relatedPageId - { - get - { - return _relatedPageId; - } - set - { - _relatedPageId = value; - } - } - - /// - /// Simulates a click on this button. - /// 模拟点击这个按钮。 - /// - /// If the down effect will simulate too. - public void FireClick(bool downEffect, bool clickCall = false) - { - if (downEffect && _mode == ButtonMode.Common) - { - SetState(OVER); - - Timers.inst.Add(0.1f, 1, (object param) => { SetState(DOWN); }); - Timers.inst.Add(0.2f, 1, - (object param) => - { - SetState(UP); - if (clickCall) - { - onClick.Call(); - } - } - ); - } - else - { - if (clickCall) - { - onClick.Call(); - } - } - __click(); - } - - /// - /// - /// - /// - public GTextField GetTextField() - { - if (_titleObject is GTextField) - return (GTextField)_titleObject; - else if (_titleObject is GLabel) - return ((GLabel)_titleObject).GetTextField(); - else if (_titleObject is GButton) - return ((GButton)_titleObject).GetTextField(); - else - return null; - } - - protected void SetState(string val) - { - if (_buttonController != null) - _buttonController.selectedPage = val; - - if (_downEffect == 1) - { - int cnt = this.numChildren; - if (val == DOWN || val == SELECTED_OVER || val == SELECTED_DISABLED) - { - Color color = new Color(_downEffectValue, _downEffectValue, _downEffectValue); - for (int i = 0; i < cnt; i++) - { - GObject obj = this.GetChildAt(i); - if ((obj is IColorGear) && !(obj is GTextField)) - ((IColorGear)obj).color = color; - } - } - else - { - for (int i = 0; i < cnt; i++) - { - GObject obj = this.GetChildAt(i); - if ((obj is IColorGear) && !(obj is GTextField)) - ((IColorGear)obj).color = Color.white; - } - } - } - else if (_downEffect == 2) - { - if (val == DOWN || val == SELECTED_OVER || val == SELECTED_DISABLED) - { - if (!_downScaled) - { - _downScaled = true; - SetScale(this.scaleX * _downEffectValue, this.scaleY * _downEffectValue); - } - } - else - { - if (_downScaled) - { - _downScaled = false; - SetScale(this.scaleX / _downEffectValue, this.scaleY / _downEffectValue); - } - } - } - } - - protected void SetCurrentState() - { - if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) - { - if (_selected) - SetState(SELECTED_DISABLED); - else - SetState(DISABLED); - } - else - { - if (_selected) - SetState(_over ? SELECTED_OVER : DOWN); - else - SetState(_over ? OVER : UP); - } - } - - override public void HandleControllerChanged(Controller c) - { - base.HandleControllerChanged(c); - - if (_relatedController == c) - this.selected = _relatedPageId == c.selectedPageId; - } - - override protected void HandleGrayedChanged() - { - if (_buttonController != null && _buttonController.HasPage(DISABLED)) - { - if (this.grayed) - { - if (_selected) - SetState(SELECTED_DISABLED); - else - SetState(DISABLED); - } - else - { - if (_selected) - SetState(DOWN); - else - SetState(UP); - } - } - else - base.HandleGrayedChanged(); - } - - override protected void ConstructExtension(ByteBuffer buffer) - { - buffer.Seek(0, 6); - - _mode = (ButtonMode)buffer.ReadByte(); - string str = buffer.ReadS(); - if (str != null) - sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; - soundVolumeScale = buffer.ReadFloat(); - _downEffect = buffer.ReadByte(); - _downEffectValue = buffer.ReadFloat(); - if (_downEffect == 2) - SetPivot(0.5f, 0.5f, this.pivotAsAnchor); - - _buttonController = GetController("button"); - _titleObject = GetChild("title"); - _iconObject = GetChild("icon"); - if (_titleObject != null) - _title = _titleObject.text; - if (_iconObject != null) - _icon = _iconObject.icon; - - if (_mode == ButtonMode.Common) - SetState(UP); - - displayObject.onRollOver.Add(__rollover); - displayObject.onRollOut.Add(__rollout); - displayObject.onTouchBegin.Add(__touchBegin); - displayObject.onTouchEnd.Add(__touchEnd); - displayObject.onRemovedFromStage.Add(__removedFromStage); - displayObject.onClick.Add(__click); - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - if (!buffer.Seek(beginPos, 6)) - return; - - if ((ObjectType)buffer.ReadByte() != packageItem.objectType) - return; - - string str; - - str = buffer.ReadS(); - if (str != null) - this.title = str; - str = buffer.ReadS(); - if (str != null) - this.selectedTitle = str; - str = buffer.ReadS(); - if (str != null) - this.icon = str; - str = buffer.ReadS(); - if (str != null) - this.selectedIcon = str; - if (buffer.ReadBool()) - this.titleColor = buffer.ReadColor(); - int iv = buffer.ReadInt(); - if (iv != 0) - this.titleFontSize = iv; - iv = buffer.ReadShort(); - if (iv >= 0) - _relatedController = parent.GetControllerAt(iv); - _relatedPageId = buffer.ReadS(); - - str = buffer.ReadS(); - if (str != null) - sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; - if (buffer.ReadBool()) - soundVolumeScale = buffer.ReadFloat(); - - this.selected = buffer.ReadBool(); - } - - private void __rollover() - { - if (_buttonController == null || !_buttonController.HasPage(OVER)) - return; - - _over = true; - if (_down) - return; - - if (this.grayed && _buttonController.HasPage(DISABLED)) - return; - - SetState(_selected ? SELECTED_OVER : OVER); - } - - private void __rollout() - { - if (_buttonController == null || !_buttonController.HasPage(OVER)) - return; - - _over = false; - if (_down) - return; - - if (this.grayed && _buttonController.HasPage(DISABLED)) - return; - - SetState(_selected ? DOWN : UP); - } - - private void __touchBegin(EventContext context) - { - if (context.inputEvent.button != 0) - return; - - _down = true; - context.CaptureTouch(); - - if (_mode == ButtonMode.Common) - { - if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) - SetState(SELECTED_DISABLED); - else - SetState(DOWN); - } - - if (linkedPopup != null) - { - if (linkedPopup is Window) - ((Window)linkedPopup).ToggleStatus(); - else - this.root.TogglePopup(linkedPopup, this); - } - } - - private void __touchEnd() - { - if (_down) - { - _down = false; - if (_mode == ButtonMode.Common) - { - if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) - SetState(DISABLED); - else if (_over) - SetState(OVER); - else - SetState(UP); - } - else - { - if (!_over - && _buttonController != null - && (_buttonController.selectedPage == OVER || _buttonController.selectedPage == SELECTED_OVER)) - { - SetCurrentState(); - } - } - } - } - - private void __removedFromStage() - { - if (_over) - __rollout(); - } - - private void __click() - { - if (sound != null && sound.nativeClip != null) - Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); - - if (_mode == ButtonMode.Check) - { - if (changeStateOnClick) - { - this.selected = !_selected; - DispatchEvent("onChanged", null); - } - } - else if (_mode == ButtonMode.Radio) - { - if (changeStateOnClick && !_selected) - { - this.selected = true; - DispatchEvent("onChanged", null); - } - } - else - { - if (_relatedController != null) - _relatedController.selectedPageId = _relatedPageId; - } - } - } -} +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GButton class. + /// + public class GButton : GComponent, IColorGear + { + /// + /// Play sound when button is clicked. + /// + public NAudioClip sound; + + /// + /// Volume of the click sound. (0-1) + /// + public float soundVolumeScale; + + /// + /// For radio or checkbox. if false, the button will not change selected status on click. Default is true. + /// 如果为true,对于单选和多选按钮,当玩家点击时,按钮会自动切换状态。设置为false,则不会。默认为true。 + /// + public bool changeStateOnClick; + + /// + /// Show a popup on click. + /// 可以为按钮设置一个关联的组件,当按钮被点击时,此组件被自动弹出。 + /// + public GObject linkedPopup; + + protected GObject _titleObject; + protected GObject _iconObject; + protected Controller _relatedController; + protected string _relatedPageId; + + ButtonMode _mode; + bool _selected; + string _title; + string _icon; + string _selectedTitle; + string _selectedIcon; + Controller _buttonController; + int _downEffect; + float _downEffectValue; + bool _downScaled; + + bool _down; + bool _over; + + EventListener _onChanged; + + public const string UP = "up"; + public const string DOWN = "down"; + public const string OVER = "over"; + public const string SELECTED_OVER = "selectedOver"; + public const string DISABLED = "disabled"; + public const string SELECTED_DISABLED = "selectedDisabled"; + + public GButton() + { + sound = UIConfig.buttonSound; + soundVolumeScale = UIConfig.buttonSoundVolumeScale; + changeStateOnClick = true; + _downEffectValue = 0.8f; + _title = string.Empty; + } + + /// + /// Dispatched when the button status was changed. + /// 如果为单选或多选按钮,当按钮的选中状态发生改变时,此事件触发。 + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// Icon of the button. + /// + override public string icon + { + get + { + return _icon; + } + set + { + _icon = value; + value = (_selected && _selectedIcon != null) ? _selectedIcon : _icon; + if (_iconObject != null) + _iconObject.icon = value; + UpdateGear(7); + } + } + + /// + /// Title of the button + /// + public string title + { + get + { + return _title; + } + set + { + _title = value; + if (_titleObject != null) + _titleObject.text = (_selected && _selectedTitle != null) ? _selectedTitle : _title; + UpdateGear(6); + } + } + + /// + /// Same of the title. + /// + override public string text + { + get { return this.title; } + set { this.title = value; } + } + + /// + /// Icon value on selected status. + /// + public string selectedIcon + { + get + { + return _selectedIcon; + } + set + { + _selectedIcon = value; + value = (_selected && _selectedIcon != null) ? _selectedIcon : _icon; + if (_iconObject != null) + _iconObject.icon = value; + } + } + + /// + /// Title value on selected status. + /// + public string selectedTitle + { + get + { + return _selectedTitle; + } + set + { + _selectedTitle = value; + if (_titleObject != null) + _titleObject.text = (_selected && _selectedTitle != null) ? _selectedTitle : _title; + } + } + + /// + /// Title color. + /// + public Color titleColor + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.color; + else + return Color.black; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + tf.color = value; + UpdateGear(4); + } + } + } + + /// + /// + /// + public Color color + { + get { return this.titleColor; } + set { this.titleColor = value; } + } + + /// + /// + /// + public int titleFontSize + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.textFormat.size; + else + return 0; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + TextFormat format = tf.textFormat; + format.size = value; + tf.textFormat = format; + } + } + } + + /// + /// If the button is in selected status. + /// + public bool selected + { + get + { + return _selected; + } + + set + { + if (_mode == ButtonMode.Common) + return; + + if (_selected != value) + { + _selected = value; + SetCurrentState(); + if (_selectedTitle != null && _titleObject != null) + _titleObject.text = _selected ? _selectedTitle : _title; + if (_selectedIcon != null) + { + string str = _selected ? _selectedIcon : _icon; + if (_iconObject != null) + _iconObject.icon = str; + } + if (_relatedController != null + && parent != null + && !parent._buildingDisplayList) + { + if (_selected) + { + _relatedController.selectedPageId = _relatedPageId; + if (_relatedController.autoRadioGroupDepth) + parent.AdjustRadioGroupDepth(this, _relatedController); + } + else if (_mode == ButtonMode.Check && _relatedController.selectedPageId == _relatedPageId) + _relatedController.oppositePageId = _relatedPageId; + } + } + + } + } + + /// + /// Button mode. + /// + /// + public ButtonMode mode + { + get + { + return _mode; + } + set + { + if (_mode != value) + { + if (value == ButtonMode.Common) + this.selected = false; + _mode = value; + } + } + } + + /// + /// A controller is connected to this button, the activate page of this controller will change while the button status changed. + /// 对应编辑器中的单选控制器。 + /// + public Controller relatedController + { + get + { + return _relatedController; + } + set + { + if (value != _relatedController) + { + _relatedController = value; + _relatedPageId = null; + } + } + } + + /// + /// + /// + public string relatedPageId + { + get + { + return _relatedPageId; + } + set + { + _relatedPageId = value; + } + } + + /// + /// Simulates a click on this button. + /// 模拟点击这个按钮。 + /// + /// If the down effect will simulate too. + public void FireClick(bool downEffect, bool clickCall = false) + { + if (downEffect && _mode == ButtonMode.Common) + { + SetState(OVER); + + Timers.inst.Add(0.1f, 1, (object param) => { SetState(DOWN); }); + Timers.inst.Add(0.2f, 1, + (object param) => + { + SetState(UP); + if (clickCall) + { + onClick.Call(); + } + } + ); + } + else + { + if (clickCall) + { + onClick.Call(); + } + } + __click(); + } + + /// + /// + /// + /// + public GTextField GetTextField() + { + if (_titleObject is GTextField) + return (GTextField)_titleObject; + else if (_titleObject is GLabel) + return ((GLabel)_titleObject).GetTextField(); + else if (_titleObject is GButton) + return ((GButton)_titleObject).GetTextField(); + else + return null; + } + + protected void SetState(string val) + { + if (_buttonController != null) + _buttonController.selectedPage = val; + + if (_downEffect == 1) + { + int cnt = this.numChildren; + if (val == DOWN || val == SELECTED_OVER || val == SELECTED_DISABLED) + { + Color color = new Color(_downEffectValue, _downEffectValue, _downEffectValue); + for (int i = 0; i < cnt; i++) + { + GObject obj = this.GetChildAt(i); + if ((obj is IColorGear) && !(obj is GTextField)) + ((IColorGear)obj).color = color; + } + } + else + { + for (int i = 0; i < cnt; i++) + { + GObject obj = this.GetChildAt(i); + if ((obj is IColorGear) && !(obj is GTextField)) + ((IColorGear)obj).color = Color.white; + } + } + } + else if (_downEffect == 2) + { + if (val == DOWN || val == SELECTED_OVER || val == SELECTED_DISABLED) + { + if (!_downScaled) + { + _downScaled = true; + SetScale(this.scaleX * _downEffectValue, this.scaleY * _downEffectValue); + } + } + else + { + if (_downScaled) + { + _downScaled = false; + SetScale(this.scaleX / _downEffectValue, this.scaleY / _downEffectValue); + } + } + } + } + + protected void SetCurrentState() + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) + { + if (_selected) + SetState(SELECTED_DISABLED); + else + SetState(DISABLED); + } + else + { + if (_selected) + SetState(_over ? SELECTED_OVER : DOWN); + else + SetState(_over ? OVER : UP); + } + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (_relatedController == c) + this.selected = _relatedPageId == c.selectedPageId; + } + + override protected void HandleGrayedChanged() + { + if (_buttonController != null && _buttonController.HasPage(DISABLED)) + { + if (this.grayed) + { + if (_selected) + SetState(SELECTED_DISABLED); + else + SetState(DISABLED); + } + else + { + if (_selected) + SetState(DOWN); + else + SetState(UP); + } + } + else + base.HandleGrayedChanged(); + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _mode = (ButtonMode)buffer.ReadByte(); + string str = buffer.ReadS(); + if (str != null) + sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; + soundVolumeScale = buffer.ReadFloat(); + _downEffect = buffer.ReadByte(); + _downEffectValue = buffer.ReadFloat(); + if (_downEffect == 2) + SetPivot(0.5f, 0.5f, this.pivotAsAnchor); + + _buttonController = GetController("button"); + _titleObject = GetChild("title"); + _iconObject = GetChild("icon"); + if (_titleObject != null) + _title = _titleObject.text; + if (_iconObject != null) + _icon = _iconObject.icon; + + if (_mode == ButtonMode.Common) + SetState(UP); + + displayObject.onRollOver.Add(__rollover); + displayObject.onRollOut.Add(__rollout); + displayObject.onTouchBegin.Add(__touchBegin); + displayObject.onTouchEnd.Add(__touchEnd); + displayObject.onRemovedFromStage.Add(__removedFromStage); + displayObject.onClick.Add(__click); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + return; + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + return; + + string str; + + str = buffer.ReadS(); + if (str != null) + this.title = str; + str = buffer.ReadS(); + if (str != null) + this.selectedTitle = str; + str = buffer.ReadS(); + if (str != null) + this.icon = str; + str = buffer.ReadS(); + if (str != null) + this.selectedIcon = str; + if (buffer.ReadBool()) + this.titleColor = buffer.ReadColor(); + int iv = buffer.ReadInt(); + if (iv != 0) + this.titleFontSize = iv; + iv = buffer.ReadShort(); + if (iv >= 0) + _relatedController = parent.GetControllerAt(iv); + _relatedPageId = buffer.ReadS(); + + str = buffer.ReadS(); + if (str != null) + sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; + if (buffer.ReadBool()) + soundVolumeScale = buffer.ReadFloat(); + + this.selected = buffer.ReadBool(); + } + + private void __rollover() + { + if (_buttonController == null || !_buttonController.HasPage(OVER)) + return; + + _over = true; + if (_down) + return; + + if (this.grayed && _buttonController.HasPage(DISABLED)) + return; + + SetState(_selected ? SELECTED_OVER : OVER); + } + + private void __rollout() + { + if (_buttonController == null || !_buttonController.HasPage(OVER)) + return; + + _over = false; + if (_down) + return; + + if (this.grayed && _buttonController.HasPage(DISABLED)) + return; + + SetState(_selected ? DOWN : UP); + } + + private void __touchBegin(EventContext context) + { + if (context.inputEvent.button != 0) + return; + + _down = true; + context.CaptureTouch(); + + if (_mode == ButtonMode.Common) + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) + SetState(SELECTED_DISABLED); + else + SetState(DOWN); + } + + if (linkedPopup != null) + { + if (linkedPopup is Window) + ((Window)linkedPopup).ToggleStatus(); + else + this.root.TogglePopup(linkedPopup, this); + } + } + + private void __touchEnd() + { + if (_down) + { + _down = false; + if (_mode == ButtonMode.Common) + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(DISABLED)) + SetState(DISABLED); + else if (_over) + SetState(OVER); + else + SetState(UP); + } + else + { + if (!_over + && _buttonController != null + && (_buttonController.selectedPage == OVER || _buttonController.selectedPage == SELECTED_OVER)) + { + SetCurrentState(); + } + } + } + } + + private void __removedFromStage() + { + if (_over) + __rollout(); + } + + private void __click() + { + if (sound != null && sound.nativeClip != null) + Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); + + if (_mode == ButtonMode.Check) + { + if (changeStateOnClick) + { + this.selected = !_selected; + DispatchEvent("onChanged", null); + } + } + else if (_mode == ButtonMode.Radio) + { + if (changeStateOnClick && !_selected) + { + this.selected = true; + DispatchEvent("onChanged", null); + } + } + else + { + if (_relatedController != null) + _relatedController.selectedPageId = _relatedPageId; + } + } + } +} diff --git a/Assets/Scripts/UI/GButton.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GButton.cs.meta similarity index 100% rename from Assets/Scripts/UI/GButton.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GButton.cs.meta diff --git a/Assets/Scripts/UI/GComboBox.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComboBox.cs similarity index 96% rename from Assets/Scripts/UI/GComboBox.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComboBox.cs index e7758c32..40b9fdda 100644 --- a/Assets/Scripts/UI/GComboBox.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComboBox.cs @@ -1,629 +1,629 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GComboBox class. - /// - public class GComboBox : GComponent - { - /// - /// Visible item count of the drop down list. - /// - public int visibleItemCount; - - /// - /// - /// - public GComponent dropdown; - - /// - /// Play sound when button is clicked. - /// - public NAudioClip sound; - - /// - /// Volume of the click sound. (0-1) - /// - public float soundVolumeScale; - - protected GObject _titleObject; - protected GObject _iconObject; - protected GList _list; - - protected List _items; - protected List _icons; - protected List _values; - protected PopupDirection _popupDirection; - protected Controller _selectionController; - - bool _itemsUpdated; - int _selectedIndex; - Controller _buttonController; - - bool _down; - bool _over; - - EventListener _onChanged; - - public GComboBox() - { - visibleItemCount = UIConfig.defaultComboBoxVisibleItemCount; - _itemsUpdated = true; - _selectedIndex = -1; - _items = new List(); - _values = new List(); - _popupDirection = PopupDirection.Auto; - soundVolumeScale = 1; - } - - /// - /// Dispatched when selection was changed. - /// - public EventListener onChanged - { - get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } - } - - /// - /// Icon of the combobox. - /// - override public string icon - { - get - { - if (_iconObject != null) - return _iconObject.icon; - else - return null; - } - - set - { - if (_iconObject != null) - _iconObject.icon = value; - UpdateGear(7); - } - } - - /// - /// Title of the combobox. - /// - public string title - { - get - { - if (_titleObject != null) - return _titleObject.text; - else - return null; - } - set - { - if (_titleObject != null) - _titleObject.text = value; - UpdateGear(6); - } - } - - /// - /// Same of the title. - /// - override public string text - { - get { return this.title; } - set { this.title = value; } - } - - /// - /// Text color - /// - public Color titleColor - { - get - { - GTextField tf = GetTextField(); - if (tf != null) - return tf.color; - else - return Color.black; - } - set - { - GTextField tf = GetTextField(); - if (tf != null) - tf.color = value; - } - } - - /// - /// - /// - public int titleFontSize - { - get - { - GTextField tf = GetTextField(); - if (tf != null) - return tf.textFormat.size; - else - return 0; - } - set - { - GTextField tf = GetTextField(); - if (tf != null) - { - TextFormat format = tf.textFormat; - format.size = value; - tf.textFormat = format; - } - } - } - - /// - /// Items to build up drop down list. - /// - public string[] items - { - get - { - return _items.ToArray(); - } - set - { - _items.Clear(); - if (value != null) - _items.AddRange(value); - ApplyListChange(); - } - } - - /// - /// - /// - public string[] icons - { - get { return _icons != null ? _icons.ToArray() : null; } - set - { - this.iconList.Clear(); - if (value != null) - _icons.AddRange(value); - ApplyListChange(); - } - } - - /// - /// Values, should be same size of the items. - /// - public string[] values - { - get { return _values.ToArray(); } - set - { - _values.Clear(); - if (value != null) - _values.AddRange(value); - } - } - - /// - /// - /// - public List itemList - { - get { return _items; } - } - - /// - /// - /// - public List valueList - { - get { return _values; } - } - - /// - /// - /// - public List iconList - { - get { return _icons ?? (_icons = new List()); } - } - - /// - /// Call this method after you made changes on itemList or iconList - /// - public void ApplyListChange() - { - if (_items.Count > 0) - { - if (_selectedIndex >= _items.Count) - _selectedIndex = _items.Count - 1; - else if (_selectedIndex == -1) - _selectedIndex = 0; - - this.text = _items[_selectedIndex]; - if (_icons != null && _selectedIndex < _icons.Count) - this.icon = _icons[_selectedIndex]; - } - else - { - this.text = string.Empty; - if (_icons != null) - this.icon = null; - _selectedIndex = -1; - } - - _itemsUpdated = true; - } - - /// - /// Selected index. - /// - public int selectedIndex - { - get - { - return _selectedIndex; - } - set - { - if (_selectedIndex == value) - return; - - _selectedIndex = value; - if (_selectedIndex >= 0 && _selectedIndex < _items.Count) - { - this.text = (string)_items[_selectedIndex]; - if (_icons != null && _selectedIndex < _icons.Count) - this.icon = _icons[_selectedIndex]; - } - else - { - this.text = string.Empty; - if (_icons != null) - this.icon = null; - } - - UpdateSelectionController(); - } - } - - /// - /// - /// - public Controller selectionController - { - get { return _selectionController; } - set { _selectionController = value; } - } - - /// - /// Selected value. - /// - public string value - { - get - { - if (_selectedIndex >= 0 && _selectedIndex < _values.Count) - return _values[_selectedIndex]; - else - return null; - } - set - { - int index = _values.IndexOf(value); - if (index == -1 && value == null) - index = _values.IndexOf(string.Empty); - if (index == -1) - index = 0; - this.selectedIndex = index; - } - } - - /// - /// - /// - public PopupDirection popupDirection - { - get { return _popupDirection; } - set { _popupDirection = value; } - } - - /// - /// - /// - /// - public GTextField GetTextField() - { - if (_titleObject is GTextField) - return (GTextField)_titleObject; - else if (_titleObject is GLabel) - return ((GLabel)_titleObject).GetTextField(); - else if (_titleObject is GButton) - return ((GButton)_titleObject).GetTextField(); - else - return null; - } - - protected void SetState(string value) - { - if (_buttonController != null) - _buttonController.selectedPage = value; - } - - protected void SetCurrentState() - { - if (this.grayed && _buttonController != null && _buttonController.HasPage(GButton.DISABLED)) - SetState(GButton.DISABLED); - else if (dropdown != null && dropdown.parent != null) - SetState(GButton.DOWN); - else - SetState(_over ? GButton.OVER : GButton.UP); - } - - override protected void HandleGrayedChanged() - { - if (_buttonController != null && _buttonController.HasPage(GButton.DISABLED)) - { - if (this.grayed) - SetState(GButton.DISABLED); - else - SetState(GButton.UP); - } - else - base.HandleGrayedChanged(); - } - - override public void HandleControllerChanged(Controller c) - { - base.HandleControllerChanged(c); - - if (_selectionController == c) - this.selectedIndex = c.selectedIndex; - } - - void UpdateSelectionController() - { - if (_selectionController != null && !_selectionController.changing - && _selectedIndex < _selectionController.pageCount) - { - Controller c = _selectionController; - _selectionController = null; - c.selectedIndex = _selectedIndex; - _selectionController = c; - } - } - - public override void Dispose() - { - if (dropdown != null) - { - dropdown.Dispose(); - dropdown = null; - } - _selectionController = null; - - base.Dispose(); - } - - override protected void ConstructExtension(ByteBuffer buffer) - { - buffer.Seek(0, 6); - - _buttonController = GetController("button"); - _titleObject = GetChild("title"); - _iconObject = GetChild("icon"); - - string str = buffer.ReadS(); - if (str != null) - { - dropdown = UIPackage.CreateObjectFromURL(str) as GComponent; - if (dropdown == null) - { - Debug.LogWarning("FairyGUI: " + this.resourceURL + " should be a component."); - return; - } - - _list = dropdown.GetChild("list") as GList; - if (_list == null) - { - Debug.LogWarning("FairyGUI: " + this.resourceURL + ": should container a list component named list."); - return; - } - _list.onClickItem.Add(__clickItem); - - _list.AddRelation(dropdown, RelationType.Width); - _list.RemoveRelation(dropdown, RelationType.Height); - - dropdown.AddRelation(_list, RelationType.Height); - dropdown.RemoveRelation(_list, RelationType.Width); - - dropdown.SetHome(this); - } - - displayObject.onRollOver.Add(__rollover); - displayObject.onRollOut.Add(__rollout); - displayObject.onTouchBegin.Add(__touchBegin); - displayObject.onTouchEnd.Add(__touchEnd); - displayObject.onClick.Add(__click); - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - if (!buffer.Seek(beginPos, 6)) - return; - - if ((ObjectType)buffer.ReadByte() != packageItem.objectType) - return; - - string str; - int itemCount = buffer.ReadShort(); - for (int i = 0; i < itemCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - _items.Add(buffer.ReadS()); - _values.Add(buffer.ReadS()); - str = buffer.ReadS(); - if (str != null) - { - if (_icons == null) - _icons = new List(); - _icons.Add(str); - } - - buffer.position = nextPos; - } - - str = buffer.ReadS(); - if (str != null) - { - this.text = str; - _selectedIndex = _items.IndexOf(str); - } - else if (_items.Count > 0) - { - _selectedIndex = 0; - this.text = _items[0]; - } - else - _selectedIndex = -1; - - str = buffer.ReadS(); - if (str != null) - this.icon = str; - - if (buffer.ReadBool()) - this.titleColor = buffer.ReadColor(); - int iv = buffer.ReadInt(); - if (iv > 0) - visibleItemCount = iv; - _popupDirection = (PopupDirection)buffer.ReadByte(); - - iv = buffer.ReadShort(); - if (iv >= 0) - _selectionController = parent.GetControllerAt(iv); - - if (buffer.version >= 5) - { - str = buffer.ReadS(); - if (str != null) - sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; - soundVolumeScale = buffer.ReadFloat(); - } - } - - public void UpdateDropdownList() - { - if (_itemsUpdated) - { - _itemsUpdated = false; - RenderDropdownList(); - _list.ResizeToFit(visibleItemCount); - } - } - - protected void ShowDropdown() - { - UpdateDropdownList(); - if (_list.selectionMode == ListSelectionMode.Single) - _list.selectedIndex = -1; - dropdown.width = this.width; - _list.EnsureBoundsCorrect(); //avoid flicker - - this.root.TogglePopup(dropdown, this, _popupDirection); - if (dropdown.parent != null) - { - dropdown.displayObject.onRemovedFromStage.Add(__popupWinClosed); - SetState(GButton.DOWN); - } - } - - virtual protected void RenderDropdownList() - { - _list.RemoveChildrenToPool(); - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - GObject item = _list.AddItemFromPool(); - item.text = _items[i]; - item.icon = (_icons != null && i < _icons.Count) ? _icons[i] : null; - item.name = i < _values.Count ? _values[i] : string.Empty; - } - } - - private void __popupWinClosed(object obj) - { - dropdown.displayObject.onRemovedFromStage.Remove(__popupWinClosed); - SetCurrentState(); - - RequestFocus(); - } - - private void __clickItem(EventContext context) - { - if (dropdown.parent is GRoot) - ((GRoot)dropdown.parent).HidePopup(dropdown); - _selectedIndex = int.MinValue; - this.selectedIndex = _list.GetChildIndex((GObject)context.data); - - DispatchEvent("onChanged", null); - } - - private void __rollover() - { - _over = true; - if (_down || dropdown != null && dropdown.parent != null) - return; - - SetCurrentState(); - } - - private void __rollout() - { - _over = false; - if (_down || dropdown != null && dropdown.parent != null) - return; - - SetCurrentState(); - } - - private void __touchBegin(EventContext context) - { - if (context.initiator is InputTextField) - return; - - _down = true; - - if (dropdown != null) - ShowDropdown(); - - context.CaptureTouch(); - } - - private void __touchEnd(EventContext context) - { - if (_down) - { - _down = false; - if (dropdown != null && dropdown.parent != null) - SetCurrentState(); - } - } - - private void __click() - { - if (sound != null && sound.nativeClip != null) - Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GComboBox class. + /// + public class GComboBox : GComponent + { + /// + /// Visible item count of the drop down list. + /// + public int visibleItemCount; + + /// + /// + /// + public GComponent dropdown; + + /// + /// Play sound when button is clicked. + /// + public NAudioClip sound; + + /// + /// Volume of the click sound. (0-1) + /// + public float soundVolumeScale; + + protected GObject _titleObject; + protected GObject _iconObject; + protected GList _list; + + protected List _items; + protected List _icons; + protected List _values; + protected PopupDirection _popupDirection; + protected Controller _selectionController; + + bool _itemsUpdated; + int _selectedIndex; + Controller _buttonController; + + bool _down; + bool _over; + + EventListener _onChanged; + + public GComboBox() + { + visibleItemCount = UIConfig.defaultComboBoxVisibleItemCount; + _itemsUpdated = true; + _selectedIndex = -1; + _items = new List(); + _values = new List(); + _popupDirection = PopupDirection.Auto; + soundVolumeScale = 1; + } + + /// + /// Dispatched when selection was changed. + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// Icon of the combobox. + /// + override public string icon + { + get + { + if (_iconObject != null) + return _iconObject.icon; + else + return null; + } + + set + { + if (_iconObject != null) + _iconObject.icon = value; + UpdateGear(7); + } + } + + /// + /// Title of the combobox. + /// + public string title + { + get + { + if (_titleObject != null) + return _titleObject.text; + else + return null; + } + set + { + if (_titleObject != null) + _titleObject.text = value; + UpdateGear(6); + } + } + + /// + /// Same of the title. + /// + override public string text + { + get { return this.title; } + set { this.title = value; } + } + + /// + /// Text color + /// + public Color titleColor + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.color; + else + return Color.black; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + tf.color = value; + } + } + + /// + /// + /// + public int titleFontSize + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.textFormat.size; + else + return 0; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + TextFormat format = tf.textFormat; + format.size = value; + tf.textFormat = format; + } + } + } + + /// + /// Items to build up drop down list. + /// + public string[] items + { + get + { + return _items.ToArray(); + } + set + { + _items.Clear(); + if (value != null) + _items.AddRange(value); + ApplyListChange(); + } + } + + /// + /// + /// + public string[] icons + { + get { return _icons != null ? _icons.ToArray() : null; } + set + { + this.iconList.Clear(); + if (value != null) + _icons.AddRange(value); + ApplyListChange(); + } + } + + /// + /// Values, should be same size of the items. + /// + public string[] values + { + get { return _values.ToArray(); } + set + { + _values.Clear(); + if (value != null) + _values.AddRange(value); + } + } + + /// + /// + /// + public List itemList + { + get { return _items; } + } + + /// + /// + /// + public List valueList + { + get { return _values; } + } + + /// + /// + /// + public List iconList + { + get { return _icons ?? (_icons = new List()); } + } + + /// + /// Call this method after you made changes on itemList or iconList + /// + public void ApplyListChange() + { + if (_items.Count > 0) + { + if (_selectedIndex >= _items.Count) + _selectedIndex = _items.Count - 1; + else if (_selectedIndex == -1) + _selectedIndex = 0; + + this.text = _items[_selectedIndex]; + if (_icons != null && _selectedIndex < _icons.Count) + this.icon = _icons[_selectedIndex]; + } + else + { + this.text = string.Empty; + if (_icons != null) + this.icon = null; + _selectedIndex = -1; + } + + _itemsUpdated = true; + } + + /// + /// Selected index. + /// + public int selectedIndex + { + get + { + return _selectedIndex; + } + set + { + if (_selectedIndex == value) + return; + + _selectedIndex = value; + if (_selectedIndex >= 0 && _selectedIndex < _items.Count) + { + this.text = (string)_items[_selectedIndex]; + if (_icons != null && _selectedIndex < _icons.Count) + this.icon = _icons[_selectedIndex]; + } + else + { + this.text = string.Empty; + if (_icons != null) + this.icon = null; + } + + UpdateSelectionController(); + } + } + + /// + /// + /// + public Controller selectionController + { + get { return _selectionController; } + set { _selectionController = value; } + } + + /// + /// Selected value. + /// + public string value + { + get + { + if (_selectedIndex >= 0 && _selectedIndex < _values.Count) + return _values[_selectedIndex]; + else + return null; + } + set + { + int index = _values.IndexOf(value); + if (index == -1 && value == null) + index = _values.IndexOf(string.Empty); + if (index == -1) + index = 0; + this.selectedIndex = index; + } + } + + /// + /// + /// + public PopupDirection popupDirection + { + get { return _popupDirection; } + set { _popupDirection = value; } + } + + /// + /// + /// + /// + public GTextField GetTextField() + { + if (_titleObject is GTextField) + return (GTextField)_titleObject; + else if (_titleObject is GLabel) + return ((GLabel)_titleObject).GetTextField(); + else if (_titleObject is GButton) + return ((GButton)_titleObject).GetTextField(); + else + return null; + } + + protected void SetState(string value) + { + if (_buttonController != null) + _buttonController.selectedPage = value; + } + + protected void SetCurrentState() + { + if (this.grayed && _buttonController != null && _buttonController.HasPage(GButton.DISABLED)) + SetState(GButton.DISABLED); + else if (dropdown != null && dropdown.parent != null) + SetState(GButton.DOWN); + else + SetState(_over ? GButton.OVER : GButton.UP); + } + + override protected void HandleGrayedChanged() + { + if (_buttonController != null && _buttonController.HasPage(GButton.DISABLED)) + { + if (this.grayed) + SetState(GButton.DISABLED); + else + SetState(GButton.UP); + } + else + base.HandleGrayedChanged(); + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (_selectionController == c) + this.selectedIndex = c.selectedIndex; + } + + void UpdateSelectionController() + { + if (_selectionController != null && !_selectionController.changing + && _selectedIndex < _selectionController.pageCount) + { + Controller c = _selectionController; + _selectionController = null; + c.selectedIndex = _selectedIndex; + _selectionController = c; + } + } + + public override void Dispose() + { + if (dropdown != null) + { + dropdown.Dispose(); + dropdown = null; + } + _selectionController = null; + + base.Dispose(); + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _buttonController = GetController("button"); + _titleObject = GetChild("title"); + _iconObject = GetChild("icon"); + + string str = buffer.ReadS(); + if (str != null) + { + dropdown = UIPackage.CreateObjectFromURL(str) as GComponent; + if (dropdown == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + " should be a component."); + return; + } + + _list = dropdown.GetChild("list") as GList; + if (_list == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + ": should container a list component named list."); + return; + } + _list.onClickItem.Add(__clickItem); + + _list.AddRelation(dropdown, RelationType.Width); + _list.RemoveRelation(dropdown, RelationType.Height); + + dropdown.AddRelation(_list, RelationType.Height); + dropdown.RemoveRelation(_list, RelationType.Width); + + dropdown.SetHome(this); + } + + displayObject.onRollOver.Add(__rollover); + displayObject.onRollOut.Add(__rollout); + displayObject.onTouchBegin.Add(__touchBegin); + displayObject.onTouchEnd.Add(__touchEnd); + displayObject.onClick.Add(__click); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + return; + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + return; + + string str; + int itemCount = buffer.ReadShort(); + for (int i = 0; i < itemCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + _items.Add(buffer.ReadS()); + _values.Add(buffer.ReadS()); + str = buffer.ReadS(); + if (str != null) + { + if (_icons == null) + _icons = new List(); + _icons.Add(str); + } + + buffer.position = nextPos; + } + + str = buffer.ReadS(); + if (str != null) + { + this.text = str; + _selectedIndex = _items.IndexOf(str); + } + else if (_items.Count > 0) + { + _selectedIndex = 0; + this.text = _items[0]; + } + else + _selectedIndex = -1; + + str = buffer.ReadS(); + if (str != null) + this.icon = str; + + if (buffer.ReadBool()) + this.titleColor = buffer.ReadColor(); + int iv = buffer.ReadInt(); + if (iv > 0) + visibleItemCount = iv; + _popupDirection = (PopupDirection)buffer.ReadByte(); + + iv = buffer.ReadShort(); + if (iv >= 0) + _selectionController = parent.GetControllerAt(iv); + + if (buffer.version >= 5) + { + str = buffer.ReadS(); + if (str != null) + sound = UIPackage.GetItemAssetByURL(str) as NAudioClip; + soundVolumeScale = buffer.ReadFloat(); + } + } + + public void UpdateDropdownList() + { + if (_itemsUpdated) + { + _itemsUpdated = false; + RenderDropdownList(); + _list.ResizeToFit(visibleItemCount); + } + } + + protected void ShowDropdown() + { + UpdateDropdownList(); + if (_list.selectionMode == ListSelectionMode.Single) + _list.selectedIndex = -1; + dropdown.width = this.width; + _list.EnsureBoundsCorrect(); //avoid flicker + + this.root.TogglePopup(dropdown, this, _popupDirection); + if (dropdown.parent != null) + { + dropdown.displayObject.onRemovedFromStage.Add(__popupWinClosed); + SetState(GButton.DOWN); + } + } + + virtual protected void RenderDropdownList() + { + _list.RemoveChildrenToPool(); + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + GObject item = _list.AddItemFromPool(); + item.text = _items[i]; + item.icon = (_icons != null && i < _icons.Count) ? _icons[i] : null; + item.name = i < _values.Count ? _values[i] : string.Empty; + } + } + + private void __popupWinClosed(object obj) + { + dropdown.displayObject.onRemovedFromStage.Remove(__popupWinClosed); + SetCurrentState(); + + RequestFocus(); + } + + private void __clickItem(EventContext context) + { + if (dropdown.parent is GRoot) + ((GRoot)dropdown.parent).HidePopup(dropdown); + _selectedIndex = int.MinValue; + this.selectedIndex = _list.GetChildIndex((GObject)context.data); + + DispatchEvent("onChanged", null); + } + + private void __rollover() + { + _over = true; + if (_down || dropdown != null && dropdown.parent != null) + return; + + SetCurrentState(); + } + + private void __rollout() + { + _over = false; + if (_down || dropdown != null && dropdown.parent != null) + return; + + SetCurrentState(); + } + + private void __touchBegin(EventContext context) + { + if (context.initiator is InputTextField) + return; + + _down = true; + + if (dropdown != null) + ShowDropdown(); + + context.CaptureTouch(); + } + + private void __touchEnd(EventContext context) + { + if (_down) + { + _down = false; + if (dropdown != null && dropdown.parent != null) + SetCurrentState(); + } + } + + private void __click() + { + if (sound != null && sound.nativeClip != null) + Stage.inst.PlayOneShotSound(sound.nativeClip, soundVolumeScale); + } + } +} diff --git a/Assets/Scripts/UI/GComboBox.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComboBox.cs.meta similarity index 100% rename from Assets/Scripts/UI/GComboBox.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComboBox.cs.meta diff --git a/Assets/Scripts/UI/GComponent.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComponent.cs similarity index 96% rename from Assets/Scripts/UI/GComponent.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComponent.cs index 5ce9a3be..7176e374 100644 --- a/Assets/Scripts/UI/GComponent.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComponent.cs @@ -1,1726 +1,1726 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; -#if FAIRYGUI_TOLUA -using LuaInterface; -#endif - -namespace FairyGUI -{ - /// - /// Component - /// - public class GComponent : GObject - { - /// - /// Root container. - /// - public Container rootContainer { get; private set; } - /// - /// Content container. If the component is not clipped, then container==rootContainer. - /// - public Container container { get; protected set; } - /// - /// ScrollPane of the component. If the component is not scrollable, the value is null. - /// - public ScrollPane scrollPane { get; private set; } - - internal List _children; - internal List _controllers; - internal List _transitions; - internal bool _buildingDisplayList; - - protected Margin _margin; - protected bool _trackBounds; - protected bool _boundsChanged; - protected ChildrenRenderOrder _childrenRenderOrder; - protected int _apexIndex; - internal Vector2 _alignOffset; - - Vector2 _clipSoftness; - int _sortingChildCount; - Action _buildDelegate; - Controller _applyingController; - - EventListener _onDrop; - - public GComponent() - { - _children = new List(); - _controllers = new List(); - _transitions = new List(); - _margin = new Margin(); - _buildDelegate = BuildNativeDisplayList; - } - - override protected void CreateDisplayObject() - { - rootContainer = new Container("GComponent"); - rootContainer.gOwner = this; - rootContainer.onUpdate += OnUpdate; - container = rootContainer; - - displayObject = rootContainer; - } - - override public void Dispose() - { - int cnt = _transitions.Count; - for (int i = 0; i < cnt; ++i) - { - Transition trans = _transitions[i]; - trans.Dispose(); - } - - cnt = _controllers.Count; - for (int i = 0; i < cnt; ++i) - { - Controller c = _controllers[i]; - c.Dispose(); - } - - if (scrollPane != null) - scrollPane.Dispose(); - - base.Dispose(); //Dispose native tree first, avoid DisplayObject.RemoveFromParent call - - cnt = _children.Count; - for (int i = cnt - 1; i >= 0; --i) - { - GObject obj = _children[i]; - obj.InternalSetParent(null); //Avoid GObject.RemoveParent call - obj.Dispose(); - } - -#if FAIRYGUI_TOLUA - if (_peerTable != null) - { - _peerTable.Dispose(); - _peerTable = null; - } -#endif - -#if FAIRYGUI_PUERTS - if (__onDispose != null) - __onDispose(); - __onConstruct = null; - __onDispose = null; -#endif - } - - /// - /// Dispatched when an object was dragged and dropped to this component. - /// - public EventListener onDrop - { - get { return _onDrop ?? (_onDrop = new EventListener(this, "onDrop")); } - } - - /// - /// Draw call optimization switch. - /// - public bool fairyBatching - { - get { return rootContainer.fairyBatching; } - set { rootContainer.fairyBatching = value; } - } - - /// - /// - /// - /// - public void InvalidateBatchingState(bool childChanged) - { - if (childChanged) - container.InvalidateBatchingState(childChanged); - else - rootContainer.InvalidateBatchingState(); - } - - /// - /// If true, mouse/touch events cannot pass through the empty area of the component. Default is true. - /// - public bool opaque - { - get { return rootContainer.opaque; } - set { rootContainer.opaque = value; } - } - - /// - /// - /// - /// - public Margin margin - { - get { return _margin; } - set - { - _margin = value; - if (rootContainer.clipRect != null && scrollPane == null) //如果scrollPane不为空,则HandleSizeChanged里面的处理会促使ScrollPane处理 - container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); - HandleSizeChanged(); - } - } - - /// - /// - /// - public ChildrenRenderOrder childrenRenderOrder - { - get { return _childrenRenderOrder; } - set - { - if (_childrenRenderOrder != value) - { - _childrenRenderOrder = value; - BuildNativeDisplayList(); - } - } - } - - /// - /// - /// - public int apexIndex - { - get { return _apexIndex; } - set - { - if (_apexIndex != value) - { - _apexIndex = value; - - if (_childrenRenderOrder == ChildrenRenderOrder.Arch) - BuildNativeDisplayList(); - } - } - } - - /// - /// If true, children can be navigated by TAB from first to last, and repeat - /// - public bool tabStopChildren - { - get { return rootContainer.tabStopChildren; } - set { rootContainer.tabStopChildren = value; } - } - - /// - /// Add a child to the component. It will be at the frontmost position. - /// - /// A child object - /// GObject - public GObject AddChild(GObject child) - { - AddChildAt(child, _children.Count); - return child; - } - - /// - /// Adds a child to the component at a certain index. - /// - /// A child object - /// Index - /// GObject - virtual public GObject AddChildAt(GObject child, int index) - { - if (index >= 0 && index <= _children.Count) - { - if (child.parent == this) - { - SetChildIndex(child, index); - } - else - { - child.RemoveFromParent(); - child.InternalSetParent(this); - - int cnt = _children.Count; - if (child.sortingOrder != 0) - { - _sortingChildCount++; - index = GetInsertPosForSortingChild(child); - } - else if (_sortingChildCount > 0) - { - if (index > (cnt - _sortingChildCount)) - index = cnt - _sortingChildCount; - } - - if (index == cnt) - _children.Add(child); - else - _children.Insert(index, child); - - ChildStateChanged(child); - SetBoundsChangedFlag(); - } - return child; - } - else - { - throw new Exception("Invalid child index: " + index + ">" + _children.Count); - } - } - - int GetInsertPosForSortingChild(GObject target) - { - int cnt = _children.Count; - int i; - for (i = 0; i < cnt; i++) - { - GObject child = _children[i]; - if (child == target) - continue; - - if (target.sortingOrder < child.sortingOrder) - break; - } - return i; - } - - /// - /// Removes a child from the component. If the object is not a child, nothing happens. - /// - /// A child object - /// GObject - public GObject RemoveChild(GObject child) - { - return RemoveChild(child, false); - } - - /// - /// Removes a child from the component. If the object is not a child, nothing happens. - /// - /// A child object - /// If true, the child will be disposed right away. - /// GObject - public GObject RemoveChild(GObject child, bool dispose) - { - int childIndex = _children.IndexOf(child); - if (childIndex != -1) - { - RemoveChildAt(childIndex, dispose); - } - return child; - } - - /// - /// Removes a child at a certain index. Children above the child will move down. - /// - /// Index - /// GObject - public GObject RemoveChildAt(int index) - { - return RemoveChildAt(index, false); - } - - /// - /// Removes a child at a certain index. Children above the child will move down. - /// - /// Index - /// If true, the child will be disposed right away. - /// GObject - virtual public GObject RemoveChildAt(int index, bool dispose) - { - if (index >= 0 && index < numChildren) - { - GObject child = _children[index]; - - child.InternalSetParent(null); - - if (child.sortingOrder != 0) - _sortingChildCount--; - - _children.RemoveAt(index); - child.group = null; - if (child.inContainer) - { - container.RemoveChild(child.displayObject); - if (_childrenRenderOrder == ChildrenRenderOrder.Arch) - { - UpdateContext.OnBegin -= _buildDelegate; - UpdateContext.OnBegin += _buildDelegate; - } - } - - if (dispose) - child.Dispose(); - - SetBoundsChangedFlag(); - return child; - } - else - throw new Exception("Invalid child index: " + index + ">" + numChildren); - } - - /// - /// Remove all children. - /// - public void RemoveChildren() - { - RemoveChildren(0, -1, false); - } - - /// - /// Removes a range of children from the container (endIndex included). - /// - /// Begin index. - /// End index.(Included). - /// If true, the child will be disposed right away. - public void RemoveChildren(int beginIndex, int endIndex, bool dispose) - { - if (endIndex < 0 || endIndex >= numChildren) - endIndex = numChildren - 1; - - for (int i = beginIndex; i <= endIndex; ++i) - RemoveChildAt(beginIndex, dispose); - } - - /// - /// Returns a child object at a certain index. If index out of bounds, exception raised. - /// - /// Index - /// A child object. - public GObject GetChildAt(int index) - { - if (index >= 0 && index < numChildren) - return _children[index]; - else - throw new Exception("Invalid child index: " + index + ">" + numChildren); - } - - /// - /// Returns a child object with a certain name. - /// - /// Name - /// A child object. Null if not found. - public GObject GetChild(string name) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - if (_children[i].name == name) - return _children[i]; - } - - return null; - } - - public GObject GetChildByPath(string path) - { - string[] arr = path.Split('.'); - int cnt = arr.Length; - GComponent gcom = this; - GObject obj = null; - for (int i = 0; i < cnt; ++i) - { - obj = gcom.GetChild(arr[i]); - if (obj == null) - break; - - if (i != cnt - 1) - { - if (!(obj is GComponent)) - { - obj = null; - break; - } - else - gcom = (GComponent)obj; - } - } - - return obj; - } - - /// - /// Returns a visible child object with a certain name. - /// - /// Name - /// A child object. Null if not found. - public GObject GetVisibleChild(string name) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - GObject child = _children[i]; - if (child.internalVisible && child.internalVisible2 && child.name == name) - return child; - } - - return null; - } - - /// - /// Returns a child object belong to a group with a certain name. - /// - /// A group object - /// Name - /// A child object. Null if not found. - public GObject GetChildInGroup(GGroup group, string name) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - GObject child = _children[i]; - if (child.group == group && child.name == name) - return child; - } - - return null; - } - - internal GObject GetChildById(string id) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - if (_children[i].id == id) - return _children[i]; - } - - return null; - } - - /// - /// Returns a copy of all children with an array. - /// - /// An array contains all children - public GObject[] GetChildren() - { - return _children.ToArray(); - } - - /// - /// Returns the index of a child within the container, or "-1" if it is not found. - /// - /// A child object - /// Index of the child. -1 If not found. - public int GetChildIndex(GObject child) - { - return _children.IndexOf(child); - } - - /// - /// Moves a child to a certain index. Children at and after the replaced position move up. - /// - /// A Child - /// Index - public void SetChildIndex(GObject child, int index) - { - int oldIndex = _children.IndexOf(child); - if (oldIndex == -1) - throw new ArgumentException("Not a child of this container"); - - if (child.sortingOrder != 0) //no effect - return; - - if (_sortingChildCount > 0) - { - int cnt = _children.Count; - if (index > (cnt - _sortingChildCount - 1)) - index = cnt - _sortingChildCount - 1; - } - - _SetChildIndex(child, oldIndex, index); - } - - /// - /// Moves a child to a certain position which is in front of the child previously at given index. - /// 与SetChildIndex不同的是,如果child原来在index的前面,那么child插入的位置是index-1,即保证排在原来占据index的对象的前面。 - /// - /// - /// - public int SetChildIndexBefore(GObject child, int index) - { - int oldIndex = _children.IndexOf(child); - if (oldIndex == -1) - throw new ArgumentException("Not a child of this container"); - - if (child.sortingOrder != 0) //no effect - return oldIndex; - - int cnt = _children.Count; - if (_sortingChildCount > 0) - { - if (index > (cnt - _sortingChildCount - 1)) - index = cnt - _sortingChildCount - 1; - } - - if (oldIndex < index) - return _SetChildIndex(child, oldIndex, index - 1); - else - return _SetChildIndex(child, oldIndex, index); - } - - int _SetChildIndex(GObject child, int oldIndex, int index) - { - int cnt = _children.Count; - if (index > cnt) - index = cnt; - - if (oldIndex == index) - return oldIndex; - - _children.RemoveAt(oldIndex); - if (index >= cnt) - _children.Add(child); - else - _children.Insert(index, child); - - if (child.inContainer) - { - int displayIndex = 0; - if (_childrenRenderOrder == ChildrenRenderOrder.Ascent) - { - for (int i = 0; i < index; i++) - { - GObject g = _children[i]; - if (g.inContainer) - displayIndex++; - } - container.SetChildIndex(child.displayObject, displayIndex); - } - else if (_childrenRenderOrder == ChildrenRenderOrder.Descent) - { - for (int i = cnt - 1; i > index; i--) - { - GObject g = _children[i]; - if (g.inContainer) - displayIndex++; - } - container.SetChildIndex(child.displayObject, displayIndex); - } - else - { - UpdateContext.OnBegin -= _buildDelegate; - UpdateContext.OnBegin += _buildDelegate; - } - - SetBoundsChangedFlag(); - } - - return index; - } - - /// - /// Swaps the indexes of two children. - /// - /// A child object - /// A child object - public void SwapChildren(GObject child1, GObject child2) - { - int index1 = _children.IndexOf(child1); - int index2 = _children.IndexOf(child2); - if (index1 == -1 || index2 == -1) - throw new Exception("Not a child of this container"); - SwapChildrenAt(index1, index2); - } - - /// - /// Swaps the indexes of two children. - /// - /// index of first child - /// index of second child - public void SwapChildrenAt(int index1, int index2) - { - GObject child1 = _children[index1]; - GObject child2 = _children[index2]; - - SetChildIndex(child1, index2); - SetChildIndex(child2, index1); - } - - /// - /// The number of children of this component. - /// - public int numChildren - { - get { return _children.Count; } - } - - /// - /// - /// - /// - /// - public bool IsAncestorOf(GObject obj) - { - if (obj == null) - return false; - - GComponent p = obj.parent; - while (p != null) - { - if (p == this) - return true; - - p = p.parent; - } - return false; - } - - - /// - /// - /// - /// - public void ChangeChildrenOrder(IList objs) - { - int cnt = objs.Count; - for (int i = 0; i < cnt; i++) - { - GObject obj = objs[i]; - if (obj.parent != this) - throw new Exception("Not a child of this container"); - - _children[i] = obj; - } - BuildNativeDisplayList(); - SetBoundsChangedFlag(); - } - - /// - /// Adds a controller to the container. - /// - /// Controller object - public void AddController(Controller controller) - { - _controllers.Add(controller); - controller.parent = this; - ApplyController(controller); - } - - /// - /// Returns a controller object at a certain index. - /// - /// Index - /// Controller object. - public Controller GetControllerAt(int index) - { - return _controllers[index]; - } - - /// - /// Returns a controller object with a certain name. - /// - /// Name - /// Controller object. Null if not found. - public Controller GetController(string name) - { - int cnt = _controllers.Count; - for (int i = 0; i < cnt; ++i) - { - Controller c = _controllers[i]; - if (c.name == name) - return c; - } - - return null; - } - - /// - /// Removes a controller from the container. - /// - /// Controller object. - public void RemoveController(Controller c) - { - int index = _controllers.IndexOf(c); - if (index == -1) - throw new Exception("controller not exists: " + c.name); - - c.parent = null; - _controllers.RemoveAt(index); - - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - GObject child = _children[i]; - child.HandleControllerChanged(c); - } - } - - /// - /// Returns controller list. - /// - /// Controller list - public List Controllers - { - get { return _controllers; } - } - - /// - /// Returns a transition object at a certain index. - /// - /// Index - /// transition object. - public Transition GetTransitionAt(int index) - { - return _transitions[index]; - } - - /// - /// Returns a transition object at a certain name. - /// - /// Name - /// Transition Object - public Transition GetTransition(string name) - { - int cnt = _transitions.Count; - for (int i = 0; i < cnt; ++i) - { - Transition trans = _transitions[i]; - if (trans.name == name) - return trans; - } - - return null; - } - - /// - /// Returns transition list. - /// - /// Transition list - public List Transitions - { - get { return _transitions; } - } - - internal void ChildStateChanged(GObject child) - { - if (_buildingDisplayList) - return; - - int cnt = _children.Count; - - if (child is GGroup) - { - for (int i = 0; i < cnt; ++i) - { - GObject g = _children[i]; - if (g.group == child) - ChildStateChanged(g); - } - return; - } - - if (child.displayObject == null) - return; - - if (child.internalVisible) - { - if (child.displayObject.parent == null) - { - if (_childrenRenderOrder == ChildrenRenderOrder.Ascent) - { - int index = 0; - for (int i = 0; i < cnt; i++) - { - GObject g = _children[i]; - if (g == child) - break; - - if (g.displayObject != null && g.displayObject.parent != null) - index++; - } - container.AddChildAt(child.displayObject, index); - } - else if (_childrenRenderOrder == ChildrenRenderOrder.Descent) - { - int index = 0; - for (int i = cnt - 1; i >= 0; i--) - { - GObject g = _children[i]; - if (g == child) - break; - - if (g.displayObject != null && g.displayObject.parent != null) - index++; - } - container.AddChildAt(child.displayObject, index); - } - else - { - container.AddChild(child.displayObject); - - UpdateContext.OnBegin -= _buildDelegate; - UpdateContext.OnBegin += _buildDelegate; - } - } - } - else - { - if (child.displayObject.parent != null) - { - container.RemoveChild(child.displayObject); - if (_childrenRenderOrder == ChildrenRenderOrder.Arch) - { - UpdateContext.OnBegin -= _buildDelegate; - UpdateContext.OnBegin += _buildDelegate; - } - } - } - } - - void BuildNativeDisplayList() - { - if (displayObject == null || displayObject.isDisposed) - return; - - int cnt = _children.Count; - if (cnt == 0) - return; - - switch (_childrenRenderOrder) - { - case ChildrenRenderOrder.Ascent: - { - for (int i = 0; i < cnt; i++) - { - GObject child = _children[i]; - if (child.displayObject != null && child.internalVisible) - container.AddChild(child.displayObject); - } - } - break; - case ChildrenRenderOrder.Descent: - { - for (int i = cnt - 1; i >= 0; i--) - { - GObject child = _children[i]; - if (child.displayObject != null && child.internalVisible) - container.AddChild(child.displayObject); - } - } - break; - - case ChildrenRenderOrder.Arch: - { - int apex = Mathf.Clamp(_apexIndex, 0, cnt); - for (int i = 0; i < apex; i++) - { - GObject child = _children[i]; - if (child.displayObject != null && child.internalVisible) - container.AddChild(child.displayObject); - } - for (int i = cnt - 1; i >= apex; i--) - { - GObject child = _children[i]; - if (child.displayObject != null && child.internalVisible) - container.AddChild(child.displayObject); - } - } - break; - } - } - - internal void ApplyController(Controller c) - { - _applyingController = c; - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - GObject child = _children[i]; - child.HandleControllerChanged(c); - } - _applyingController = null; - - c.RunActions(); - } - - void ApplyAllControllers() - { - int cnt = _controllers.Count; - for (int i = 0; i < cnt; ++i) - { - Controller controller = _controllers[i]; - ApplyController(controller); - } - } - - internal void AdjustRadioGroupDepth(GObject obj, Controller c) - { - int cnt = _children.Count; - int i; - GObject child; - int myIndex = -1, maxIndex = -1; - for (i = 0; i < cnt; i++) - { - child = _children[i]; - if (child == obj) - { - myIndex = i; - } - else if ((child is GButton) - && ((GButton)child).relatedController == c) - { - if (i > maxIndex) - maxIndex = i; - } - } - if (myIndex < maxIndex) - { - if (_applyingController != null) - _children[maxIndex].HandleControllerChanged(_applyingController); - this.SwapChildrenAt(myIndex, maxIndex); - } - } - - /// - /// If clipping softness is set, clipped containers will have soft border effect. - /// - public Vector2 clipSoftness - { - get { return _clipSoftness; } - set - { - _clipSoftness = value; - if (scrollPane != null) - scrollPane.UpdateClipSoft(); - else if (_clipSoftness.x > 0 || _clipSoftness.y > 0) - rootContainer.clipSoftness = new Vector4(value.x, value.y, value.x, value.y); - else - rootContainer.clipSoftness = null; - } - } - - /// - /// The mask of the component. - /// - public DisplayObject mask - { - get { return container.mask; } - set - { - container.mask = value; - if (value != null && value.parent != container) - container.AddChild(value); - } - } - - /// - /// - /// - public bool reversedMask - { - get { return container.reversedMask; } - set { container.reversedMask = value; } - } - - /// - /// - /// - public string baseUserData - { - get - { - ByteBuffer buffer = packageItem.rawData; - buffer.Seek(0, 4); - return buffer.ReadS(); - } - } - - /// - /// Test if a child is in view. - /// - /// A child object - /// True if in view - public bool IsChildInView(GObject child) - { - if (scrollPane != null) - { - return scrollPane.IsChildInView(child); - } - else if (rootContainer.clipRect != null) - { - return child.x + child.width >= 0 && child.x <= this.width - && child.y + child.height >= 0 && child.y <= this.height; - } - else - return true; - } - - virtual public int GetFirstChildInView() - { - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - GObject child = _children[i]; - if (IsChildInView(child)) - return i; - } - return -1; - } - - protected void SetupScroll(ByteBuffer buffer) - { - if (rootContainer == container) - { - container = new Container(); - rootContainer.AddChild(container); - } - - scrollPane = new ScrollPane(this); - scrollPane.Setup(buffer); - } - - protected void SetupOverflow(OverflowType overflow) - { - if (overflow == OverflowType.Hidden) - { - if (rootContainer == container) - { - container = new Container(); - rootContainer.AddChild(container); - } - - UpdateClipRect(); - container.SetXY(_margin.left, _margin.top); - } - else if (_margin.left != 0 || _margin.top != 0) - { - if (rootContainer == container) - { - container = new Container(); - rootContainer.AddChild(container); - } - - container.SetXY(_margin.left, _margin.top); - } - } - - void UpdateClipRect() - { - if (scrollPane == null) - { - float w = this.width - (_margin.left + _margin.right); - float h = this.height - (_margin.top + _margin.bottom); - rootContainer.clipRect = new Rect(_margin.left, _margin.top, w, h); - } - else - rootContainer.clipRect = new Rect(0, 0, this.width, this.height); - } - - override protected void HandleSizeChanged() - { - base.HandleSizeChanged(); - - if (scrollPane != null) - scrollPane.OnOwnerSizeChanged(); - if (rootContainer.clipRect != null) - UpdateClipRect(); - } - - override protected void HandleGrayedChanged() - { - Controller cc = GetController("grayed"); - if (cc != null) - cc.selectedIndex = this.grayed ? 1 : 0; - else - base.HandleGrayedChanged(); - } - - override public void HandleControllerChanged(Controller c) - { - base.HandleControllerChanged(c); - - if (scrollPane != null) - scrollPane.HandleControllerChanged(c); - } - - /// - /// Notify the component the bounds should recaculate. - /// - public void SetBoundsChangedFlag() - { - if (scrollPane == null && !_trackBounds) - return; - - _boundsChanged = true; - } - - /// - /// Make sure the bounds of the component is correct. - /// Bounds of the component is not updated on every changed. For example, you add a new child to the list, children in the list will be rearranged in next frame. - /// If you want to access the correct child position immediatelly, call this function first. - /// - public void EnsureBoundsCorrect() - { - if (_boundsChanged) - UpdateBounds(); - } - - virtual protected void UpdateBounds() - { - float ax, ay, aw, ah; - if (_children.Count > 0) - { - ax = int.MaxValue; - ay = int.MaxValue; - float ar = int.MinValue, ab = int.MinValue; - float tmp; - - int cnt = _children.Count; - for (int i = 0; i < cnt; ++i) - { - GObject child = _children[i]; - tmp = child.x; - if (tmp < ax) - ax = tmp; - tmp = child.y; - if (tmp < ay) - ay = tmp; - tmp = child.x + child.actualWidth; - if (tmp > ar) - ar = tmp; - tmp = child.y + child.actualHeight; - if (tmp > ab) - ab = tmp; - } - aw = ar - ax; - ah = ab - ay; - } - else - { - ax = 0; - ay = 0; - aw = 0; - ah = 0; - } - - SetBounds(ax, ay, aw, ah); - } - - protected void SetBounds(float ax, float ay, float aw, float ah) - { - _boundsChanged = false; - if (scrollPane != null) - scrollPane.SetContentSize(Mathf.RoundToInt(ax + aw), Mathf.RoundToInt(ay + ah)); - } - - /// - /// Viwe port width of the container. - /// - public float viewWidth - { - get - { - if (scrollPane != null) - return scrollPane.viewWidth; - else - return this.width - _margin.left - _margin.right; - } - - set - { - if (scrollPane != null) - scrollPane.viewWidth = value; - else - this.width = value + _margin.left + _margin.right; - } - } - - /// - /// View port height of the container. - /// - public float viewHeight - { - get - { - if (scrollPane != null) - return scrollPane.viewHeight; - else - return this.height - _margin.top - _margin.bottom; - } - - set - { - if (scrollPane != null) - scrollPane.viewHeight = value; - else - this.height = value + _margin.top + _margin.bottom; - } - } - - public void GetSnappingPosition(ref float xValue, ref float yValue) - { - GetSnappingPositionWithDir(ref xValue, ref yValue, 0, 0); - } - - protected bool ShouldSnapToNext(float dir, float delta, float size) - { - return dir < 0 && delta > UIConfig.defaultScrollSnappingThreshold * size - || dir > 0 && delta > (1 - UIConfig.defaultScrollSnappingThreshold) * size - || dir == 0 && delta > size / 2; - } - - /** - * dir正数表示右移或者下移,负数表示左移或者上移 - */ - virtual public void GetSnappingPositionWithDir(ref float xValue, ref float yValue, float xDir, float yDir) - { - int cnt = _children.Count; - if (cnt == 0) - return; - - EnsureBoundsCorrect(); - - GObject obj = null; - - int i = 0; - if (yValue != 0) - { - for (; i < cnt; i++) - { - obj = _children[i]; - if (yValue < obj.y) - { - if (i == 0) - { - yValue = 0; - break; - } - else - { - GObject prev = _children[i - 1]; - if (ShouldSnapToNext(yDir, yValue - prev.y, prev.height)) - yValue = obj.y; - else - yValue = prev.y; - break; - } - } - } - - if (i == cnt) - yValue = obj.y; - } - - if (xValue != 0) - { - if (i > 0) - i--; - for (; i < cnt; i++) - { - obj = _children[i]; - if (xValue < obj.x) - { - if (i == 0) - { - xValue = 0; - break; - } - else - { - GObject prev = _children[i - 1]; - if (ShouldSnapToNext(xDir, xValue - prev.x, prev.width)) - xValue = obj.x; - else - xValue = prev.x; - break; - } - } - } - if (i == cnt) - xValue = obj.x; - } - } - - internal void ChildSortingOrderChanged(GObject child, int oldValue, int newValue) - { - if (newValue == 0) - { - _sortingChildCount--; - SetChildIndex(child, _children.Count); - } - else - { - if (oldValue == 0) - _sortingChildCount++; - - int oldIndex = _children.IndexOf(child); - int index = GetInsertPosForSortingChild(child); - if (oldIndex < index) - _SetChildIndex(child, oldIndex, index - 1); - else - _SetChildIndex(child, oldIndex, index); - } - } - - /// - /// 每帧调用的一个回调。如果你要override,请记住以下两点: - /// 1、记得调用base.onUpdate; - /// 2、不要在方法里进行任何会更改显示列表的操作,例如AddChild、RemoveChild、visible等。 - /// - virtual protected void OnUpdate() - { - if (_boundsChanged) - UpdateBounds(); - } - - override public void ConstructFromResource() - { - ConstructFromResource(null, 0); - } - - internal void ConstructFromResource(List objectPool, int poolIndex) - { - this.gameObjectName = packageItem.name; - - PackageItem contentItem = packageItem.getBranch(); - - if (!contentItem.translated) - { - contentItem.translated = true; - TranslationHelper.TranslateComponent(contentItem); - } - - ByteBuffer buffer = contentItem.rawData; - buffer.Seek(0, 0); - - underConstruct = true; - - sourceWidth = buffer.ReadInt(); - sourceHeight = buffer.ReadInt(); - initWidth = sourceWidth; - initHeight = sourceHeight; - - SetSize(sourceWidth, sourceHeight); - - if (buffer.ReadBool()) - { - minWidth = buffer.ReadInt(); - maxWidth = buffer.ReadInt(); - minHeight = buffer.ReadInt(); - maxHeight = buffer.ReadInt(); - } - - if (buffer.ReadBool()) - { - float f1 = buffer.ReadFloat(); - float f2 = buffer.ReadFloat(); - SetPivot(f1, f2, buffer.ReadBool()); - } - - if (buffer.ReadBool()) - { - _margin.top = buffer.ReadInt(); - _margin.bottom = buffer.ReadInt(); - _margin.left = buffer.ReadInt(); - _margin.right = buffer.ReadInt(); - } - - OverflowType overflow = (OverflowType)buffer.ReadByte(); - if (overflow == OverflowType.Scroll) - { - int savedPos = buffer.position; - buffer.Seek(0, 7); - SetupScroll(buffer); - buffer.position = savedPos; - } - else - SetupOverflow(overflow); - - if (buffer.ReadBool()) - { - int i1 = buffer.ReadInt(); - int i2 = buffer.ReadInt(); - this.clipSoftness = new Vector2(i1, i2); - } - - _buildingDisplayList = true; - - buffer.Seek(0, 1); - - int controllerCount = buffer.ReadShort(); - for (int i = 0; i < controllerCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - Controller controller = new Controller(); - _controllers.Add(controller); - controller.parent = this; - controller.Setup(buffer); - - buffer.position = nextPos; - } - - buffer.Seek(0, 2); - - GObject child; - int childCount = buffer.ReadShort(); - for (int i = 0; i < childCount; i++) - { - int dataLen = buffer.ReadShort(); - int curPos = buffer.position; - - if (objectPool != null) - child = objectPool[poolIndex + i]; - else - { - buffer.Seek(curPos, 0); - - ObjectType type = (ObjectType)buffer.ReadByte(); - string src = buffer.ReadS(); - string pkgId = buffer.ReadS(); - - PackageItem pi = null; - if (src != null) - { - UIPackage pkg; - if (pkgId != null) - pkg = UIPackage.GetById(pkgId); - else - pkg = contentItem.owner; - - pi = pkg != null ? pkg.GetItem(src) : null; - } - - if (pi != null) - { - child = UIObjectFactory.NewObject(pi); - child.ConstructFromResource(); - } - else - child = UIObjectFactory.NewObject(type); - } - - child.underConstruct = true; - child.Setup_BeforeAdd(buffer, curPos); - child.InternalSetParent(this); - _children.Add(child); - - buffer.position = curPos + dataLen; - } - - buffer.Seek(0, 3); - this.relations.Setup(buffer, true); - - buffer.Seek(0, 2); - buffer.Skip(2); - - for (int i = 0; i < childCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - buffer.Seek(buffer.position, 3); - _children[i].relations.Setup(buffer, false); - - buffer.position = nextPos; - } - - buffer.Seek(0, 2); - buffer.Skip(2); - - for (int i = 0; i < childCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - child = _children[i]; - child.Setup_AfterAdd(buffer, buffer.position); - child.underConstruct = false; - if (child.displayObject != null) - child.displayObject.cachedTransform.SetParent(this.displayObject.cachedTransform, false); - - buffer.position = nextPos; - } - - buffer.Seek(0, 4); - - buffer.Skip(2); //customData - this.opaque = buffer.ReadBool(); - int maskId = buffer.ReadShort(); - if (maskId != -1) - { - container.mask = GetChildAt(maskId).displayObject; - if (buffer.ReadBool()) - container.reversedMask = true; - } - - { - string hitTestId = buffer.ReadS(); - int i1 = buffer.ReadInt(); - int i2 = buffer.ReadInt(); - if (hitTestId != null) - { - PackageItem pi = contentItem.owner.GetItem(hitTestId); - if (pi != null && pi.pixelHitTestData != null) - rootContainer.hitArea = new PixelHitTest(pi.pixelHitTestData, i1, i2, sourceWidth, sourceHeight); - } - else if (i1 != 0 && i2 != -1) - { - rootContainer.hitArea = new ShapeHitTest(this.GetChildAt(i2).displayObject); - } - } - - if (buffer.version >= 5) - { - string str = buffer.ReadS(); - if (!string.IsNullOrEmpty(str)) - this.onAddedToStage.Add(() => __playSound(str, 1)); - - string str2 = buffer.ReadS(); - if (!string.IsNullOrEmpty(str2)) - this.onRemovedFromStage.Add(() => __playSound(str2, 1)); - } - - buffer.Seek(0, 5); - - int transitionCount = buffer.ReadShort(); - for (int i = 0; i < transitionCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - Transition trans = new Transition(this); - trans.Setup(buffer); - _transitions.Add(trans); - - buffer.position = nextPos; - } - - if (_transitions.Count > 0) - { - this.onAddedToStage.Add(__addedToStage); - this.onRemovedFromStage.Add(__removedFromStage); - } - - ApplyAllControllers(); - - _buildingDisplayList = false; - underConstruct = false; - - BuildNativeDisplayList(); - SetBoundsChangedFlag(); - - if (contentItem.objectType != ObjectType.Component) - ConstructExtension(buffer); - - ConstructFromXML(null); - -#if FAIRYGUI_TOLUA - CallLua("ctor"); -#endif -#if FAIRYGUI_PUERTS - if (__onConstruct != null) - __onConstruct(); -#endif - } - - virtual protected void ConstructExtension(ByteBuffer buffer) - { - } - - /// - /// Method for extensions to override - /// - /// - virtual public void ConstructFromXML(XML xml) - { - } - - public override void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - buffer.Seek(beginPos, 4); - - int pageController = buffer.ReadShort(); - if (pageController != -1 && scrollPane != null && scrollPane.pageMode) - scrollPane.pageController = parent.GetControllerAt(pageController); - - int cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - Controller cc = GetController(buffer.ReadS()); - string pageId = buffer.ReadS(); - if (cc != null) - cc.selectedPageId = pageId; - } - - if (buffer.version >= 2) - { - cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - string target = buffer.ReadS(); - int propertyId = buffer.ReadShort(); - string value = buffer.ReadS(); - GObject obj = this.GetChildByPath(target); - if (obj != null) - { - if (propertyId == 0) - obj.text = value; - else if (propertyId == 1) - obj.icon = value; - } - } - } - } - - void __playSound(string soundRes, float volumeScale) - { - NAudioClip sound = UIPackage.GetItemAssetByURL(soundRes) as NAudioClip; - if (sound != null && sound.nativeClip != null) - Stage.inst.PlayOneShotSound(sound.nativeClip, volumeScale); - } - - void __addedToStage() - { - int cnt = _transitions.Count; - for (int i = 0; i < cnt; ++i) - _transitions[i].OnOwnerAddedToStage(); - } - - void __removedFromStage() - { - int cnt = _transitions.Count; - for (int i = 0; i < cnt; ++i) - _transitions[i].OnOwnerRemovedFromStage(); - } - -#if FAIRYGUI_TOLUA - internal LuaTable _peerTable; - - public void SetLuaPeer(LuaTable peerTable) - { - _peerTable = peerTable; - } - - [NoToLua] - public bool CallLua(string funcName) - { - if (_peerTable != null) - { - LuaFunction ctor = _peerTable.GetLuaFunction(funcName); - if (ctor != null) - { - try - { - ctor.Call(this); - } - catch (Exception err) - { - Debug.LogError(err); - } - - ctor.Dispose(); - return true; - } - } - - return false; - } -#endif - -#if FAIRYGUI_PUERTS - public Action __onConstruct; - public Action __onDispose; -#endif - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// Component + /// + public class GComponent : GObject + { + /// + /// Root container. + /// + public Container rootContainer { get; private set; } + /// + /// Content container. If the component is not clipped, then container==rootContainer. + /// + public Container container { get; protected set; } + /// + /// ScrollPane of the component. If the component is not scrollable, the value is null. + /// + public ScrollPane scrollPane { get; private set; } + + internal List _children; + internal List _controllers; + internal List _transitions; + internal bool _buildingDisplayList; + + protected Margin _margin; + protected bool _trackBounds; + protected bool _boundsChanged; + protected ChildrenRenderOrder _childrenRenderOrder; + protected int _apexIndex; + internal Vector2 _alignOffset; + + Vector2 _clipSoftness; + int _sortingChildCount; + Action _buildDelegate; + Controller _applyingController; + + EventListener _onDrop; + + public GComponent() + { + _children = new List(); + _controllers = new List(); + _transitions = new List(); + _margin = new Margin(); + _buildDelegate = BuildNativeDisplayList; + } + + override protected void CreateDisplayObject() + { + rootContainer = new Container("GComponent"); + rootContainer.gOwner = this; + rootContainer.onUpdate += OnUpdate; + container = rootContainer; + + displayObject = rootContainer; + } + + override public void Dispose() + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + { + Transition trans = _transitions[i]; + trans.Dispose(); + } + + cnt = _controllers.Count; + for (int i = 0; i < cnt; ++i) + { + Controller c = _controllers[i]; + c.Dispose(); + } + + if (scrollPane != null) + scrollPane.Dispose(); + + base.Dispose(); //Dispose native tree first, avoid DisplayObject.RemoveFromParent call + + cnt = _children.Count; + for (int i = cnt - 1; i >= 0; --i) + { + GObject obj = _children[i]; + obj.InternalSetParent(null); //Avoid GObject.RemoveParent call + obj.Dispose(); + } + +#if FAIRYGUI_TOLUA + if (_peerTable != null) + { + _peerTable.Dispose(); + _peerTable = null; + } +#endif + +#if FAIRYGUI_PUERTS + if (__onDispose != null) + __onDispose(); + __onConstruct = null; + __onDispose = null; +#endif + } + + /// + /// Dispatched when an object was dragged and dropped to this component. + /// + public EventListener onDrop + { + get { return _onDrop ?? (_onDrop = new EventListener(this, "onDrop")); } + } + + /// + /// Draw call optimization switch. + /// + public bool fairyBatching + { + get { return rootContainer.fairyBatching; } + set { rootContainer.fairyBatching = value; } + } + + /// + /// + /// + /// + public void InvalidateBatchingState(bool childChanged) + { + if (childChanged) + container.InvalidateBatchingState(childChanged); + else + rootContainer.InvalidateBatchingState(); + } + + /// + /// If true, mouse/touch events cannot pass through the empty area of the component. Default is true. + /// + public bool opaque + { + get { return rootContainer.opaque; } + set { rootContainer.opaque = value; } + } + + /// + /// + /// + /// + public Margin margin + { + get { return _margin; } + set + { + _margin = value; + if (rootContainer.clipRect != null && scrollPane == null) //如果scrollPane不为空,则HandleSizeChanged里面的处理会促使ScrollPane处理 + container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); + HandleSizeChanged(); + } + } + + /// + /// + /// + public ChildrenRenderOrder childrenRenderOrder + { + get { return _childrenRenderOrder; } + set + { + if (_childrenRenderOrder != value) + { + _childrenRenderOrder = value; + BuildNativeDisplayList(); + } + } + } + + /// + /// + /// + public int apexIndex + { + get { return _apexIndex; } + set + { + if (_apexIndex != value) + { + _apexIndex = value; + + if (_childrenRenderOrder == ChildrenRenderOrder.Arch) + BuildNativeDisplayList(); + } + } + } + + /// + /// If true, children can be navigated by TAB from first to last, and repeat + /// + public bool tabStopChildren + { + get { return rootContainer.tabStopChildren; } + set { rootContainer.tabStopChildren = value; } + } + + /// + /// Add a child to the component. It will be at the frontmost position. + /// + /// A child object + /// GObject + public GObject AddChild(GObject child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// Adds a child to the component at a certain index. + /// + /// A child object + /// Index + /// GObject + virtual public GObject AddChildAt(GObject child, int index) + { + if (index >= 0 && index <= _children.Count) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + child.RemoveFromParent(); + child.InternalSetParent(this); + + int cnt = _children.Count; + if (child.sortingOrder != 0) + { + _sortingChildCount++; + index = GetInsertPosForSortingChild(child); + } + else if (_sortingChildCount > 0) + { + if (index > (cnt - _sortingChildCount)) + index = cnt - _sortingChildCount; + } + + if (index == cnt) + _children.Add(child); + else + _children.Insert(index, child); + + ChildStateChanged(child); + SetBoundsChangedFlag(); + } + return child; + } + else + { + throw new Exception("Invalid child index: " + index + ">" + _children.Count); + } + } + + int GetInsertPosForSortingChild(GObject target) + { + int cnt = _children.Count; + int i; + for (i = 0; i < cnt; i++) + { + GObject child = _children[i]; + if (child == target) + continue; + + if (target.sortingOrder < child.sortingOrder) + break; + } + return i; + } + + /// + /// Removes a child from the component. If the object is not a child, nothing happens. + /// + /// A child object + /// GObject + public GObject RemoveChild(GObject child) + { + return RemoveChild(child, false); + } + + /// + /// Removes a child from the component. If the object is not a child, nothing happens. + /// + /// A child object + /// If true, the child will be disposed right away. + /// GObject + public GObject RemoveChild(GObject child, bool dispose) + { + int childIndex = _children.IndexOf(child); + if (childIndex != -1) + { + RemoveChildAt(childIndex, dispose); + } + return child; + } + + /// + /// Removes a child at a certain index. Children above the child will move down. + /// + /// Index + /// GObject + public GObject RemoveChildAt(int index) + { + return RemoveChildAt(index, false); + } + + /// + /// Removes a child at a certain index. Children above the child will move down. + /// + /// Index + /// If true, the child will be disposed right away. + /// GObject + virtual public GObject RemoveChildAt(int index, bool dispose) + { + if (index >= 0 && index < numChildren) + { + GObject child = _children[index]; + + child.InternalSetParent(null); + + if (child.sortingOrder != 0) + _sortingChildCount--; + + _children.RemoveAt(index); + child.group = null; + if (child.inContainer) + { + container.RemoveChild(child.displayObject); + if (_childrenRenderOrder == ChildrenRenderOrder.Arch) + { + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + } + + if (dispose) + child.Dispose(); + + SetBoundsChangedFlag(); + return child; + } + else + throw new Exception("Invalid child index: " + index + ">" + numChildren); + } + + /// + /// Remove all children. + /// + public void RemoveChildren() + { + RemoveChildren(0, -1, false); + } + + /// + /// Removes a range of children from the container (endIndex included). + /// + /// Begin index. + /// End index.(Included). + /// If true, the child will be disposed right away. + public void RemoveChildren(int beginIndex, int endIndex, bool dispose) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex, dispose); + } + + /// + /// Returns a child object at a certain index. If index out of bounds, exception raised. + /// + /// Index + /// A child object. + public GObject GetChildAt(int index) + { + if (index >= 0 && index < numChildren) + return _children[index]; + else + throw new Exception("Invalid child index: " + index + ">" + numChildren); + } + + /// + /// Returns a child object with a certain name. + /// + /// Name + /// A child object. Null if not found. + public GObject GetChild(string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + if (_children[i].name == name) + return _children[i]; + } + + return null; + } + + public GObject GetChildByPath(string path) + { + string[] arr = path.Split('.'); + int cnt = arr.Length; + GComponent gcom = this; + GObject obj = null; + for (int i = 0; i < cnt; ++i) + { + obj = gcom.GetChild(arr[i]); + if (obj == null) + break; + + if (i != cnt - 1) + { + if (!(obj is GComponent)) + { + obj = null; + break; + } + else + gcom = (GComponent)obj; + } + } + + return obj; + } + + /// + /// Returns a visible child object with a certain name. + /// + /// Name + /// A child object. Null if not found. + public GObject GetVisibleChild(string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + if (child.internalVisible && child.internalVisible2 && child.name == name) + return child; + } + + return null; + } + + /// + /// Returns a child object belong to a group with a certain name. + /// + /// A group object + /// Name + /// A child object. Null if not found. + public GObject GetChildInGroup(GGroup group, string name) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + if (child.group == group && child.name == name) + return child; + } + + return null; + } + + internal GObject GetChildById(string id) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + if (_children[i].id == id) + return _children[i]; + } + + return null; + } + + /// + /// Returns a copy of all children with an array. + /// + /// An array contains all children + public GObject[] GetChildren() + { + return _children.ToArray(); + } + + /// + /// Returns the index of a child within the container, or "-1" if it is not found. + /// + /// A child object + /// Index of the child. -1 If not found. + public int GetChildIndex(GObject child) + { + return _children.IndexOf(child); + } + + /// + /// Moves a child to a certain index. Children at and after the replaced position move up. + /// + /// A Child + /// Index + public void SetChildIndex(GObject child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new ArgumentException("Not a child of this container"); + + if (child.sortingOrder != 0) //no effect + return; + + if (_sortingChildCount > 0) + { + int cnt = _children.Count; + if (index > (cnt - _sortingChildCount - 1)) + index = cnt - _sortingChildCount - 1; + } + + _SetChildIndex(child, oldIndex, index); + } + + /// + /// Moves a child to a certain position which is in front of the child previously at given index. + /// 与SetChildIndex不同的是,如果child原来在index的前面,那么child插入的位置是index-1,即保证排在原来占据index的对象的前面。 + /// + /// + /// + public int SetChildIndexBefore(GObject child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new ArgumentException("Not a child of this container"); + + if (child.sortingOrder != 0) //no effect + return oldIndex; + + int cnt = _children.Count; + if (_sortingChildCount > 0) + { + if (index > (cnt - _sortingChildCount - 1)) + index = cnt - _sortingChildCount - 1; + } + + if (oldIndex < index) + return _SetChildIndex(child, oldIndex, index - 1); + else + return _SetChildIndex(child, oldIndex, index); + } + + int _SetChildIndex(GObject child, int oldIndex, int index) + { + int cnt = _children.Count; + if (index > cnt) + index = cnt; + + if (oldIndex == index) + return oldIndex; + + _children.RemoveAt(oldIndex); + if (index >= cnt) + _children.Add(child); + else + _children.Insert(index, child); + + if (child.inContainer) + { + int displayIndex = 0; + if (_childrenRenderOrder == ChildrenRenderOrder.Ascent) + { + for (int i = 0; i < index; i++) + { + GObject g = _children[i]; + if (g.inContainer) + displayIndex++; + } + container.SetChildIndex(child.displayObject, displayIndex); + } + else if (_childrenRenderOrder == ChildrenRenderOrder.Descent) + { + for (int i = cnt - 1; i > index; i--) + { + GObject g = _children[i]; + if (g.inContainer) + displayIndex++; + } + container.SetChildIndex(child.displayObject, displayIndex); + } + else + { + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + + SetBoundsChangedFlag(); + } + + return index; + } + + /// + /// Swaps the indexes of two children. + /// + /// A child object + /// A child object + public void SwapChildren(GObject child1, GObject child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// Swaps the indexes of two children. + /// + /// index of first child + /// index of second child + public void SwapChildrenAt(int index1, int index2) + { + GObject child1 = _children[index1]; + GObject child2 = _children[index2]; + + SetChildIndex(child1, index2); + SetChildIndex(child2, index1); + } + + /// + /// The number of children of this component. + /// + public int numChildren + { + get { return _children.Count; } + } + + /// + /// + /// + /// + /// + public bool IsAncestorOf(GObject obj) + { + if (obj == null) + return false; + + GComponent p = obj.parent; + while (p != null) + { + if (p == this) + return true; + + p = p.parent; + } + return false; + } + + + /// + /// + /// + /// + public void ChangeChildrenOrder(IList objs) + { + int cnt = objs.Count; + for (int i = 0; i < cnt; i++) + { + GObject obj = objs[i]; + if (obj.parent != this) + throw new Exception("Not a child of this container"); + + _children[i] = obj; + } + BuildNativeDisplayList(); + SetBoundsChangedFlag(); + } + + /// + /// Adds a controller to the container. + /// + /// Controller object + public void AddController(Controller controller) + { + _controllers.Add(controller); + controller.parent = this; + ApplyController(controller); + } + + /// + /// Returns a controller object at a certain index. + /// + /// Index + /// Controller object. + public Controller GetControllerAt(int index) + { + return _controllers[index]; + } + + /// + /// Returns a controller object with a certain name. + /// + /// Name + /// Controller object. Null if not found. + public Controller GetController(string name) + { + int cnt = _controllers.Count; + for (int i = 0; i < cnt; ++i) + { + Controller c = _controllers[i]; + if (c.name == name) + return c; + } + + return null; + } + + /// + /// Removes a controller from the container. + /// + /// Controller object. + public void RemoveController(Controller c) + { + int index = _controllers.IndexOf(c); + if (index == -1) + throw new Exception("controller not exists: " + c.name); + + c.parent = null; + _controllers.RemoveAt(index); + + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + child.HandleControllerChanged(c); + } + } + + /// + /// Returns controller list. + /// + /// Controller list + public List Controllers + { + get { return _controllers; } + } + + /// + /// Returns a transition object at a certain index. + /// + /// Index + /// transition object. + public Transition GetTransitionAt(int index) + { + return _transitions[index]; + } + + /// + /// Returns a transition object at a certain name. + /// + /// Name + /// Transition Object + public Transition GetTransition(string name) + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + { + Transition trans = _transitions[i]; + if (trans.name == name) + return trans; + } + + return null; + } + + /// + /// Returns transition list. + /// + /// Transition list + public List Transitions + { + get { return _transitions; } + } + + internal void ChildStateChanged(GObject child) + { + if (_buildingDisplayList) + return; + + int cnt = _children.Count; + + if (child is GGroup) + { + for (int i = 0; i < cnt; ++i) + { + GObject g = _children[i]; + if (g.group == child) + ChildStateChanged(g); + } + return; + } + + if (child.displayObject == null) + return; + + if (child.internalVisible) + { + if (child.displayObject.parent == null) + { + if (_childrenRenderOrder == ChildrenRenderOrder.Ascent) + { + int index = 0; + for (int i = 0; i < cnt; i++) + { + GObject g = _children[i]; + if (g == child) + break; + + if (g.displayObject != null && g.displayObject.parent != null) + index++; + } + container.AddChildAt(child.displayObject, index); + } + else if (_childrenRenderOrder == ChildrenRenderOrder.Descent) + { + int index = 0; + for (int i = cnt - 1; i >= 0; i--) + { + GObject g = _children[i]; + if (g == child) + break; + + if (g.displayObject != null && g.displayObject.parent != null) + index++; + } + container.AddChildAt(child.displayObject, index); + } + else + { + container.AddChild(child.displayObject); + + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + } + } + else + { + if (child.displayObject.parent != null) + { + container.RemoveChild(child.displayObject); + if (_childrenRenderOrder == ChildrenRenderOrder.Arch) + { + UpdateContext.OnBegin -= _buildDelegate; + UpdateContext.OnBegin += _buildDelegate; + } + } + } + } + + void BuildNativeDisplayList() + { + if (displayObject == null || displayObject.isDisposed) + return; + + int cnt = _children.Count; + if (cnt == 0) + return; + + switch (_childrenRenderOrder) + { + case ChildrenRenderOrder.Ascent: + { + for (int i = 0; i < cnt; i++) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + } + break; + case ChildrenRenderOrder.Descent: + { + for (int i = cnt - 1; i >= 0; i--) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + } + break; + + case ChildrenRenderOrder.Arch: + { + int apex = Mathf.Clamp(_apexIndex, 0, cnt); + for (int i = 0; i < apex; i++) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + for (int i = cnt - 1; i >= apex; i--) + { + GObject child = _children[i]; + if (child.displayObject != null && child.internalVisible) + container.AddChild(child.displayObject); + } + } + break; + } + } + + internal void ApplyController(Controller c) + { + _applyingController = c; + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + child.HandleControllerChanged(c); + } + _applyingController = null; + + c.RunActions(); + } + + void ApplyAllControllers() + { + int cnt = _controllers.Count; + for (int i = 0; i < cnt; ++i) + { + Controller controller = _controllers[i]; + ApplyController(controller); + } + } + + internal void AdjustRadioGroupDepth(GObject obj, Controller c) + { + int cnt = _children.Count; + int i; + GObject child; + int myIndex = -1, maxIndex = -1; + for (i = 0; i < cnt; i++) + { + child = _children[i]; + if (child == obj) + { + myIndex = i; + } + else if ((child is GButton) + && ((GButton)child).relatedController == c) + { + if (i > maxIndex) + maxIndex = i; + } + } + if (myIndex < maxIndex) + { + if (_applyingController != null) + _children[maxIndex].HandleControllerChanged(_applyingController); + this.SwapChildrenAt(myIndex, maxIndex); + } + } + + /// + /// If clipping softness is set, clipped containers will have soft border effect. + /// + public Vector2 clipSoftness + { + get { return _clipSoftness; } + set + { + _clipSoftness = value; + if (scrollPane != null) + scrollPane.UpdateClipSoft(); + else if (_clipSoftness.x > 0 || _clipSoftness.y > 0) + rootContainer.clipSoftness = new Vector4(value.x, value.y, value.x, value.y); + else + rootContainer.clipSoftness = null; + } + } + + /// + /// The mask of the component. + /// + public DisplayObject mask + { + get { return container.mask; } + set + { + container.mask = value; + if (value != null && value.parent != container) + container.AddChild(value); + } + } + + /// + /// + /// + public bool reversedMask + { + get { return container.reversedMask; } + set { container.reversedMask = value; } + } + + /// + /// + /// + public string baseUserData + { + get + { + ByteBuffer buffer = packageItem.rawData; + buffer.Seek(0, 4); + return buffer.ReadS(); + } + } + + /// + /// Test if a child is in view. + /// + /// A child object + /// True if in view + public bool IsChildInView(GObject child) + { + if (scrollPane != null) + { + return scrollPane.IsChildInView(child); + } + else if (rootContainer.clipRect != null) + { + return child.x + child.width >= 0 && child.x <= this.width + && child.y + child.height >= 0 && child.y <= this.height; + } + else + return true; + } + + virtual public int GetFirstChildInView() + { + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + if (IsChildInView(child)) + return i; + } + return -1; + } + + protected void SetupScroll(ByteBuffer buffer) + { + if (rootContainer == container) + { + container = new Container(); + rootContainer.AddChild(container); + } + + scrollPane = new ScrollPane(this); + scrollPane.Setup(buffer); + } + + protected void SetupOverflow(OverflowType overflow) + { + if (overflow == OverflowType.Hidden) + { + if (rootContainer == container) + { + container = new Container(); + rootContainer.AddChild(container); + } + + UpdateClipRect(); + container.SetXY(_margin.left, _margin.top); + } + else if (_margin.left != 0 || _margin.top != 0) + { + if (rootContainer == container) + { + container = new Container(); + rootContainer.AddChild(container); + } + + container.SetXY(_margin.left, _margin.top); + } + } + + void UpdateClipRect() + { + if (scrollPane == null) + { + float w = this.width - (_margin.left + _margin.right); + float h = this.height - (_margin.top + _margin.bottom); + rootContainer.clipRect = new Rect(_margin.left, _margin.top, w, h); + } + else + rootContainer.clipRect = new Rect(0, 0, this.width, this.height); + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (scrollPane != null) + scrollPane.OnOwnerSizeChanged(); + if (rootContainer.clipRect != null) + UpdateClipRect(); + } + + override protected void HandleGrayedChanged() + { + Controller cc = GetController("grayed"); + if (cc != null) + cc.selectedIndex = this.grayed ? 1 : 0; + else + base.HandleGrayedChanged(); + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (scrollPane != null) + scrollPane.HandleControllerChanged(c); + } + + /// + /// Notify the component the bounds should recaculate. + /// + public void SetBoundsChangedFlag() + { + if (scrollPane == null && !_trackBounds) + return; + + _boundsChanged = true; + } + + /// + /// Make sure the bounds of the component is correct. + /// Bounds of the component is not updated on every changed. For example, you add a new child to the list, children in the list will be rearranged in next frame. + /// If you want to access the correct child position immediatelly, call this function first. + /// + public void EnsureBoundsCorrect() + { + if (_boundsChanged) + UpdateBounds(); + } + + virtual protected void UpdateBounds() + { + float ax, ay, aw, ah; + if (_children.Count > 0) + { + ax = int.MaxValue; + ay = int.MaxValue; + float ar = int.MinValue, ab = int.MinValue; + float tmp; + + int cnt = _children.Count; + for (int i = 0; i < cnt; ++i) + { + GObject child = _children[i]; + tmp = child.x; + if (tmp < ax) + ax = tmp; + tmp = child.y; + if (tmp < ay) + ay = tmp; + tmp = child.x + child.actualWidth; + if (tmp > ar) + ar = tmp; + tmp = child.y + child.actualHeight; + if (tmp > ab) + ab = tmp; + } + aw = ar - ax; + ah = ab - ay; + } + else + { + ax = 0; + ay = 0; + aw = 0; + ah = 0; + } + + SetBounds(ax, ay, aw, ah); + } + + protected void SetBounds(float ax, float ay, float aw, float ah) + { + _boundsChanged = false; + if (scrollPane != null) + scrollPane.SetContentSize(Mathf.RoundToInt(ax + aw), Mathf.RoundToInt(ay + ah)); + } + + /// + /// Viwe port width of the container. + /// + public float viewWidth + { + get + { + if (scrollPane != null) + return scrollPane.viewWidth; + else + return this.width - _margin.left - _margin.right; + } + + set + { + if (scrollPane != null) + scrollPane.viewWidth = value; + else + this.width = value + _margin.left + _margin.right; + } + } + + /// + /// View port height of the container. + /// + public float viewHeight + { + get + { + if (scrollPane != null) + return scrollPane.viewHeight; + else + return this.height - _margin.top - _margin.bottom; + } + + set + { + if (scrollPane != null) + scrollPane.viewHeight = value; + else + this.height = value + _margin.top + _margin.bottom; + } + } + + public void GetSnappingPosition(ref float xValue, ref float yValue) + { + GetSnappingPositionWithDir(ref xValue, ref yValue, 0, 0); + } + + protected bool ShouldSnapToNext(float dir, float delta, float size) + { + return dir < 0 && delta > UIConfig.defaultScrollSnappingThreshold * size + || dir > 0 && delta > (1 - UIConfig.defaultScrollSnappingThreshold) * size + || dir == 0 && delta > size / 2; + } + + /** + * dir正数表示右移或者下移,负数表示左移或者上移 + */ + virtual public void GetSnappingPositionWithDir(ref float xValue, ref float yValue, float xDir, float yDir) + { + int cnt = _children.Count; + if (cnt == 0) + return; + + EnsureBoundsCorrect(); + + GObject obj = null; + + int i = 0; + if (yValue != 0) + { + for (; i < cnt; i++) + { + obj = _children[i]; + if (yValue < obj.y) + { + if (i == 0) + { + yValue = 0; + break; + } + else + { + GObject prev = _children[i - 1]; + if (ShouldSnapToNext(yDir, yValue - prev.y, prev.height)) + yValue = obj.y; + else + yValue = prev.y; + break; + } + } + } + + if (i == cnt) + yValue = obj.y; + } + + if (xValue != 0) + { + if (i > 0) + i--; + for (; i < cnt; i++) + { + obj = _children[i]; + if (xValue < obj.x) + { + if (i == 0) + { + xValue = 0; + break; + } + else + { + GObject prev = _children[i - 1]; + if (ShouldSnapToNext(xDir, xValue - prev.x, prev.width)) + xValue = obj.x; + else + xValue = prev.x; + break; + } + } + } + if (i == cnt) + xValue = obj.x; + } + } + + internal void ChildSortingOrderChanged(GObject child, int oldValue, int newValue) + { + if (newValue == 0) + { + _sortingChildCount--; + SetChildIndex(child, _children.Count); + } + else + { + if (oldValue == 0) + _sortingChildCount++; + + int oldIndex = _children.IndexOf(child); + int index = GetInsertPosForSortingChild(child); + if (oldIndex < index) + _SetChildIndex(child, oldIndex, index - 1); + else + _SetChildIndex(child, oldIndex, index); + } + } + + /// + /// 每帧调用的一个回调。如果你要override,请记住以下两点: + /// 1、记得调用base.onUpdate; + /// 2、不要在方法里进行任何会更改显示列表的操作,例如AddChild、RemoveChild、visible等。 + /// + virtual protected void OnUpdate() + { + if (_boundsChanged) + UpdateBounds(); + } + + override public void ConstructFromResource() + { + ConstructFromResource(null, 0); + } + + internal void ConstructFromResource(List objectPool, int poolIndex) + { + this.gameObjectName = packageItem.name; + + PackageItem contentItem = packageItem.getBranch(); + + if (!contentItem.translated) + { + contentItem.translated = true; + TranslationHelper.TranslateComponent(contentItem); + } + + ByteBuffer buffer = contentItem.rawData; + buffer.Seek(0, 0); + + underConstruct = true; + + sourceWidth = buffer.ReadInt(); + sourceHeight = buffer.ReadInt(); + initWidth = sourceWidth; + initHeight = sourceHeight; + + SetSize(sourceWidth, sourceHeight); + + if (buffer.ReadBool()) + { + minWidth = buffer.ReadInt(); + maxWidth = buffer.ReadInt(); + minHeight = buffer.ReadInt(); + maxHeight = buffer.ReadInt(); + } + + if (buffer.ReadBool()) + { + float f1 = buffer.ReadFloat(); + float f2 = buffer.ReadFloat(); + SetPivot(f1, f2, buffer.ReadBool()); + } + + if (buffer.ReadBool()) + { + _margin.top = buffer.ReadInt(); + _margin.bottom = buffer.ReadInt(); + _margin.left = buffer.ReadInt(); + _margin.right = buffer.ReadInt(); + } + + OverflowType overflow = (OverflowType)buffer.ReadByte(); + if (overflow == OverflowType.Scroll) + { + int savedPos = buffer.position; + buffer.Seek(0, 7); + SetupScroll(buffer); + buffer.position = savedPos; + } + else + SetupOverflow(overflow); + + if (buffer.ReadBool()) + { + int i1 = buffer.ReadInt(); + int i2 = buffer.ReadInt(); + this.clipSoftness = new Vector2(i1, i2); + } + + _buildingDisplayList = true; + + buffer.Seek(0, 1); + + int controllerCount = buffer.ReadShort(); + for (int i = 0; i < controllerCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + Controller controller = new Controller(); + _controllers.Add(controller); + controller.parent = this; + controller.Setup(buffer); + + buffer.position = nextPos; + } + + buffer.Seek(0, 2); + + GObject child; + int childCount = buffer.ReadShort(); + for (int i = 0; i < childCount; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + if (objectPool != null) + child = objectPool[poolIndex + i]; + else + { + buffer.Seek(curPos, 0); + + ObjectType type = (ObjectType)buffer.ReadByte(); + string src = buffer.ReadS(); + string pkgId = buffer.ReadS(); + + PackageItem pi = null; + if (src != null) + { + UIPackage pkg; + if (pkgId != null) + pkg = UIPackage.GetById(pkgId); + else + pkg = contentItem.owner; + + pi = pkg != null ? pkg.GetItem(src) : null; + } + + if (pi != null) + { + child = UIObjectFactory.NewObject(pi); + child.ConstructFromResource(); + } + else + child = UIObjectFactory.NewObject(type); + } + + child.underConstruct = true; + child.Setup_BeforeAdd(buffer, curPos); + child.InternalSetParent(this); + _children.Add(child); + + buffer.position = curPos + dataLen; + } + + buffer.Seek(0, 3); + this.relations.Setup(buffer, true); + + buffer.Seek(0, 2); + buffer.Skip(2); + + for (int i = 0; i < childCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + buffer.Seek(buffer.position, 3); + _children[i].relations.Setup(buffer, false); + + buffer.position = nextPos; + } + + buffer.Seek(0, 2); + buffer.Skip(2); + + for (int i = 0; i < childCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + child = _children[i]; + child.Setup_AfterAdd(buffer, buffer.position); + child.underConstruct = false; + if (child.displayObject != null) + child.displayObject.cachedTransform.SetParent(this.displayObject.cachedTransform, false); + + buffer.position = nextPos; + } + + buffer.Seek(0, 4); + + buffer.Skip(2); //customData + this.opaque = buffer.ReadBool(); + int maskId = buffer.ReadShort(); + if (maskId != -1) + { + container.mask = GetChildAt(maskId).displayObject; + if (buffer.ReadBool()) + container.reversedMask = true; + } + + { + string hitTestId = buffer.ReadS(); + int i1 = buffer.ReadInt(); + int i2 = buffer.ReadInt(); + if (hitTestId != null) + { + PackageItem pi = contentItem.owner.GetItem(hitTestId); + if (pi != null && pi.pixelHitTestData != null) + rootContainer.hitArea = new PixelHitTest(pi.pixelHitTestData, i1, i2, sourceWidth, sourceHeight); + } + else if (i1 != 0 && i2 != -1) + { + rootContainer.hitArea = new ShapeHitTest(this.GetChildAt(i2).displayObject); + } + } + + if (buffer.version >= 5) + { + string str = buffer.ReadS(); + if (!string.IsNullOrEmpty(str)) + this.onAddedToStage.Add(() => __playSound(str, 1)); + + string str2 = buffer.ReadS(); + if (!string.IsNullOrEmpty(str2)) + this.onRemovedFromStage.Add(() => __playSound(str2, 1)); + } + + buffer.Seek(0, 5); + + int transitionCount = buffer.ReadShort(); + for (int i = 0; i < transitionCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + Transition trans = new Transition(this); + trans.Setup(buffer); + _transitions.Add(trans); + + buffer.position = nextPos; + } + + if (_transitions.Count > 0) + { + this.onAddedToStage.Add(__addedToStage); + this.onRemovedFromStage.Add(__removedFromStage); + } + + ApplyAllControllers(); + + _buildingDisplayList = false; + underConstruct = false; + + BuildNativeDisplayList(); + SetBoundsChangedFlag(); + + if (contentItem.objectType != ObjectType.Component) + ConstructExtension(buffer); + + ConstructFromXML(null); + +#if FAIRYGUI_TOLUA + CallLua("ctor"); +#endif +#if FAIRYGUI_PUERTS + if (__onConstruct != null) + __onConstruct(); +#endif + } + + virtual protected void ConstructExtension(ByteBuffer buffer) + { + } + + /// + /// Method for extensions to override + /// + /// + virtual public void ConstructFromXML(XML xml) + { + } + + public override void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + buffer.Seek(beginPos, 4); + + int pageController = buffer.ReadShort(); + if (pageController != -1 && scrollPane != null && scrollPane.pageMode) + scrollPane.pageController = parent.GetControllerAt(pageController); + + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + Controller cc = GetController(buffer.ReadS()); + string pageId = buffer.ReadS(); + if (cc != null) + cc.selectedPageId = pageId; + } + + if (buffer.version >= 2) + { + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + string value = buffer.ReadS(); + GObject obj = this.GetChildByPath(target); + if (obj != null) + { + if (propertyId == 0) + obj.text = value; + else if (propertyId == 1) + obj.icon = value; + } + } + } + } + + void __playSound(string soundRes, float volumeScale) + { + NAudioClip sound = UIPackage.GetItemAssetByURL(soundRes) as NAudioClip; + if (sound != null && sound.nativeClip != null) + Stage.inst.PlayOneShotSound(sound.nativeClip, volumeScale); + } + + void __addedToStage() + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + _transitions[i].OnOwnerAddedToStage(); + } + + void __removedFromStage() + { + int cnt = _transitions.Count; + for (int i = 0; i < cnt; ++i) + _transitions[i].OnOwnerRemovedFromStage(); + } + +#if FAIRYGUI_TOLUA + internal LuaTable _peerTable; + + public void SetLuaPeer(LuaTable peerTable) + { + _peerTable = peerTable; + } + + [NoToLua] + public bool CallLua(string funcName) + { + if (_peerTable != null) + { + LuaFunction ctor = _peerTable.GetLuaFunction(funcName); + if (ctor != null) + { + try + { + ctor.Call(this); + } + catch (Exception err) + { + Debug.LogError(err); + } + + ctor.Dispose(); + return true; + } + } + + return false; + } +#endif + +#if FAIRYGUI_PUERTS + public Action __onConstruct; + public Action __onDispose; +#endif + } +} diff --git a/Assets/Scripts/UI/GComponent.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComponent.cs.meta similarity index 100% rename from Assets/Scripts/UI/GComponent.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GComponent.cs.meta diff --git a/Assets/Scripts/UI/GGraph.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGraph.cs similarity index 97% rename from Assets/Scripts/UI/GGraph.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGraph.cs index 2dfed8e8..62cab969 100644 --- a/Assets/Scripts/UI/GGraph.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGraph.cs @@ -1,274 +1,274 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GGraph class. - /// 对应编辑器里的图形对象。图形有两个用途,一是用来显示简单的图形,例如矩形等;二是作为一个占位的用途, - /// 可以将本对象替换为其他对象,或者在它的前后添加其他对象,相当于一个位置和深度的占位;还可以直接将内容设置 - /// 为原生对象。 - /// - public class GGraph : GObject, IColorGear - { - Shape _shape; - - public GGraph() - { - } - - override protected void CreateDisplayObject() - { - _shape = new Shape(); - _shape.gOwner = this; - displayObject = _shape; - } - - /// - /// Replace this object to another object in the display list. - /// 在显示列表中,将指定对象取代这个图形对象。这个图形对象相当于一个占位的用途。 - /// - /// Target object. - public void ReplaceMe(GObject target) - { - if (parent == null) - throw new Exception("parent not set"); - - target.name = this.name; - target.alpha = this.alpha; - target.rotation = this.rotation; - target.visible = this.visible; - target.touchable = this.touchable; - target.grayed = this.grayed; - target.SetXY(this.x, this.y); - target.SetSize(this.width, this.height); - - int index = parent.GetChildIndex(this); - parent.AddChildAt(target, index); - target.relations.CopyFrom(this.relations); - - parent.RemoveChild(this, true); - } - - /// - /// Add another object before this object. - /// 在显示列表中,将另一个对象插入到这个对象的前面。 - /// - /// Target object. - public void AddBeforeMe(GObject target) - { - if (parent == null) - throw new Exception("parent not set"); - - int index = parent.GetChildIndex(this); - parent.AddChildAt(target, index); - } - - /// - /// Add another object after this object. - /// 在显示列表中,将另一个对象插入到这个对象的后面。 - /// - /// Target object. - public void AddAfterMe(GObject target) - { - if (parent == null) - throw new Exception("parent not set"); - - int index = parent.GetChildIndex(this); - index++; - parent.AddChildAt(target, index); - } - - /// - /// 设置内容为一个原生对象。这个图形对象相当于一个占位的用途。 - /// - /// 原生对象 - public void SetNativeObject(DisplayObject obj) - { - if (displayObject == obj) - return; - - if (_shape != null) - { - if (_shape.parent != null) - _shape.parent.RemoveChild(displayObject, true); - else - _shape.Dispose(); - _shape.gOwner = null; - _shape = null; - } - - displayObject = obj; - - if (displayObject != null) - { - displayObject.alpha = this.alpha; - displayObject.rotation = this.rotation; - displayObject.visible = this.visible; - displayObject.touchable = this.touchable; - displayObject.gOwner = this; - } - - if (parent != null) - parent.ChildStateChanged(this); - HandlePositionChanged(); - } - - /// - /// - /// - public Color color - { - get - { - if (_shape != null) - return _shape.color; - else - return Color.clear; - } - set - { - if (_shape != null && _shape.color != value) - { - _shape.color = value; - UpdateGear(4); - } - } - } - - /// - /// Get the shape object. It can be used for drawing. - /// 获取图形的原生对象,可用于绘制图形。 - /// - public Shape shape - { - get { return _shape; } - } - - /// - /// Draw a rectangle. - /// 画矩形。 - /// - /// Width - /// Height - /// Line size - /// Line color - /// Fill color - public void DrawRect(float aWidth, float aHeight, int lineSize, Color lineColor, Color fillColor) - { - this.SetSize(aWidth, aHeight); - _shape.DrawRect(lineSize, lineColor, fillColor); - } - - /// - /// - /// - /// - /// - /// - /// - public void DrawRoundRect(float aWidth, float aHeight, Color fillColor, float[] corner) - { - this.SetSize(aWidth, aHeight); - this.shape.DrawRoundRect(0, Color.white, fillColor, corner[0], corner[1], corner[2], corner[3]); - } - - /// - /// - /// - /// - /// - /// - public void DrawEllipse(float aWidth, float aHeight, Color fillColor) - { - this.SetSize(aWidth, aHeight); - _shape.DrawEllipse(fillColor); - } - - /// - /// - /// - /// - /// - /// - /// - public void DrawPolygon(float aWidth, float aHeight, IList points, Color fillColor) - { - this.SetSize(aWidth, aHeight); - _shape.DrawPolygon(points, fillColor); - } - - /// - /// - /// - /// - /// - /// - /// - /// - /// - public void DrawPolygon(float aWidth, float aHeight, IList points, Color fillColor, float lineSize, Color lineColor) - { - this.SetSize(aWidth, aHeight); - _shape.DrawPolygon(points, fillColor, lineSize, lineColor); - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - int type = buffer.ReadByte(); - if (type != 0) - { - int lineSize = buffer.ReadInt(); - Color lineColor = buffer.ReadColor(); - Color fillColor = buffer.ReadColor(); - bool roundedRect = buffer.ReadBool(); - Vector4 cornerRadius = new Vector4(); - if (roundedRect) - { - for (int i = 0; i < 4; i++) - cornerRadius[i] = buffer.ReadFloat(); - } - - if (type == 1) - { - if (roundedRect) - _shape.DrawRoundRect(lineSize, lineColor, fillColor, cornerRadius.x, cornerRadius.y, cornerRadius.z, cornerRadius.w); - else - _shape.DrawRect(lineSize, lineColor, fillColor); - } - else if (type == 2) - _shape.DrawEllipse(lineSize, fillColor, lineColor, fillColor, 0, 360); - else if (type == 3) - { - int cnt = buffer.ReadShort() / 2; - Vector2[] points = new Vector2[cnt]; - for (int i = 0; i < cnt; i++) - points[i].Set(buffer.ReadFloat(), buffer.ReadFloat()); - - _shape.DrawPolygon(points, fillColor, lineSize, lineColor); - } - else if (type == 4) - { - int sides = buffer.ReadShort(); - float startAngle = buffer.ReadFloat(); - int cnt = buffer.ReadShort(); - float[] distances = null; - if (cnt > 0) - { - distances = new float[cnt]; - for (int i = 0; i < cnt; i++) - distances[i] = buffer.ReadFloat(); - } - - _shape.DrawRegularPolygon(sides, lineSize, fillColor, lineColor, fillColor, startAngle, distances); - } - } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GGraph class. + /// 对应编辑器里的图形对象。图形有两个用途,一是用来显示简单的图形,例如矩形等;二是作为一个占位的用途, + /// 可以将本对象替换为其他对象,或者在它的前后添加其他对象,相当于一个位置和深度的占位;还可以直接将内容设置 + /// 为原生对象。 + /// + public class GGraph : GObject, IColorGear + { + Shape _shape; + + public GGraph() + { + } + + override protected void CreateDisplayObject() + { + _shape = new Shape(); + _shape.gOwner = this; + displayObject = _shape; + } + + /// + /// Replace this object to another object in the display list. + /// 在显示列表中,将指定对象取代这个图形对象。这个图形对象相当于一个占位的用途。 + /// + /// Target object. + public void ReplaceMe(GObject target) + { + if (parent == null) + throw new Exception("parent not set"); + + target.name = this.name; + target.alpha = this.alpha; + target.rotation = this.rotation; + target.visible = this.visible; + target.touchable = this.touchable; + target.grayed = this.grayed; + target.SetXY(this.x, this.y); + target.SetSize(this.width, this.height); + + int index = parent.GetChildIndex(this); + parent.AddChildAt(target, index); + target.relations.CopyFrom(this.relations); + + parent.RemoveChild(this, true); + } + + /// + /// Add another object before this object. + /// 在显示列表中,将另一个对象插入到这个对象的前面。 + /// + /// Target object. + public void AddBeforeMe(GObject target) + { + if (parent == null) + throw new Exception("parent not set"); + + int index = parent.GetChildIndex(this); + parent.AddChildAt(target, index); + } + + /// + /// Add another object after this object. + /// 在显示列表中,将另一个对象插入到这个对象的后面。 + /// + /// Target object. + public void AddAfterMe(GObject target) + { + if (parent == null) + throw new Exception("parent not set"); + + int index = parent.GetChildIndex(this); + index++; + parent.AddChildAt(target, index); + } + + /// + /// 设置内容为一个原生对象。这个图形对象相当于一个占位的用途。 + /// + /// 原生对象 + public void SetNativeObject(DisplayObject obj) + { + if (displayObject == obj) + return; + + if (_shape != null) + { + if (_shape.parent != null) + _shape.parent.RemoveChild(displayObject, true); + else + _shape.Dispose(); + _shape.gOwner = null; + _shape = null; + } + + displayObject = obj; + + if (displayObject != null) + { + displayObject.alpha = this.alpha; + displayObject.rotation = this.rotation; + displayObject.visible = this.visible; + displayObject.touchable = this.touchable; + displayObject.gOwner = this; + } + + if (parent != null) + parent.ChildStateChanged(this); + HandlePositionChanged(); + } + + /// + /// + /// + public Color color + { + get + { + if (_shape != null) + return _shape.color; + else + return Color.clear; + } + set + { + if (_shape != null && _shape.color != value) + { + _shape.color = value; + UpdateGear(4); + } + } + } + + /// + /// Get the shape object. It can be used for drawing. + /// 获取图形的原生对象,可用于绘制图形。 + /// + public Shape shape + { + get { return _shape; } + } + + /// + /// Draw a rectangle. + /// 画矩形。 + /// + /// Width + /// Height + /// Line size + /// Line color + /// Fill color + public void DrawRect(float aWidth, float aHeight, int lineSize, Color lineColor, Color fillColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawRect(lineSize, lineColor, fillColor); + } + + /// + /// + /// + /// + /// + /// + /// + public void DrawRoundRect(float aWidth, float aHeight, Color fillColor, float[] corner) + { + this.SetSize(aWidth, aHeight); + this.shape.DrawRoundRect(0, Color.white, fillColor, corner[0], corner[1], corner[2], corner[3]); + } + + /// + /// + /// + /// + /// + /// + public void DrawEllipse(float aWidth, float aHeight, Color fillColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawEllipse(fillColor); + } + + /// + /// + /// + /// + /// + /// + /// + public void DrawPolygon(float aWidth, float aHeight, IList points, Color fillColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawPolygon(points, fillColor); + } + + /// + /// + /// + /// + /// + /// + /// + /// + /// + public void DrawPolygon(float aWidth, float aHeight, IList points, Color fillColor, float lineSize, Color lineColor) + { + this.SetSize(aWidth, aHeight); + _shape.DrawPolygon(points, fillColor, lineSize, lineColor); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + int type = buffer.ReadByte(); + if (type != 0) + { + int lineSize = buffer.ReadInt(); + Color lineColor = buffer.ReadColor(); + Color fillColor = buffer.ReadColor(); + bool roundedRect = buffer.ReadBool(); + Vector4 cornerRadius = new Vector4(); + if (roundedRect) + { + for (int i = 0; i < 4; i++) + cornerRadius[i] = buffer.ReadFloat(); + } + + if (type == 1) + { + if (roundedRect) + _shape.DrawRoundRect(lineSize, lineColor, fillColor, cornerRadius.x, cornerRadius.y, cornerRadius.z, cornerRadius.w); + else + _shape.DrawRect(lineSize, lineColor, fillColor); + } + else if (type == 2) + _shape.DrawEllipse(lineSize, fillColor, lineColor, fillColor, 0, 360); + else if (type == 3) + { + int cnt = buffer.ReadShort() / 2; + Vector2[] points = new Vector2[cnt]; + for (int i = 0; i < cnt; i++) + points[i].Set(buffer.ReadFloat(), buffer.ReadFloat()); + + _shape.DrawPolygon(points, fillColor, lineSize, lineColor); + } + else if (type == 4) + { + int sides = buffer.ReadShort(); + float startAngle = buffer.ReadFloat(); + int cnt = buffer.ReadShort(); + float[] distances = null; + if (cnt > 0) + { + distances = new float[cnt]; + for (int i = 0; i < cnt; i++) + distances[i] = buffer.ReadFloat(); + } + + _shape.DrawRegularPolygon(sides, lineSize, fillColor, lineColor, fillColor, startAngle, distances); + } + } + } + } +} diff --git a/Assets/Scripts/UI/GGraph.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGraph.cs.meta similarity index 100% rename from Assets/Scripts/UI/GGraph.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGraph.cs.meta diff --git a/Assets/Scripts/UI/GGroup.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGroup.cs similarity index 96% rename from Assets/Scripts/UI/GGroup.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGroup.cs index f056a220..8958c01c 100644 --- a/Assets/Scripts/UI/GGroup.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGroup.cs @@ -1,538 +1,538 @@ -using System; -using FairyGUI.Utils; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// GGroup class. - /// 组对象,对应编辑器里的高级组。 - /// - public class GGroup : GObject - { - GroupLayoutType _layout; - int _lineGap; - int _columnGap; - - bool _excludeInvisibles; - bool _autoSizeDisabled; - int _mainGridIndex; - int _mainGridMinSize; - - bool _percentReady; - bool _boundsChanged; - int _mainChildIndex; - float _totalSize; - int _numChildren; - internal int _updating; - - Action _refreshDelegate; - - public GGroup() - { - _mainGridIndex = -1; - _mainChildIndex = -1; - _mainGridMinSize = 50; - _refreshDelegate = EnsureBoundsCorrect; - } - - /// - /// Group layout type. - /// - public GroupLayoutType layout - { - get { return _layout; } - set - { - if (_layout != value) - { - _layout = value; - SetBoundsChangedFlag(); - } - } - } - - /// - /// - /// - public int lineGap - { - get { return _lineGap; } - set - { - if (_lineGap != value) - { - _lineGap = value; - SetBoundsChangedFlag(true); - } - } - } - - /// - /// - /// - public int columnGap - { - get { return _columnGap; } - set - { - if (_columnGap != value) - { - _columnGap = value; - SetBoundsChangedFlag(true); - } - } - } - - /// - /// - /// - public bool excludeInvisibles - { - get { return _excludeInvisibles; } - set - { - if (_excludeInvisibles != value) - { - _excludeInvisibles = value; - SetBoundsChangedFlag(); - } - } - } - - /// - /// - /// - public bool autoSizeDisabled - { - get { return _autoSizeDisabled; } - set - { - if (_autoSizeDisabled != value) - { - _autoSizeDisabled = value; - SetBoundsChangedFlag(); - } - } - } - - /// - /// - /// - public int mainGridMinSize - { - get { return _mainGridMinSize; } - set - { - if (_mainGridMinSize != value) - { - _mainGridMinSize = value; - SetBoundsChangedFlag(); - } - } - } - - /// - /// - /// - public int mainGridIndex - { - get { return _mainGridIndex; } - set - { - if (_mainGridIndex != value) - { - _mainGridIndex = value; - SetBoundsChangedFlag(); - } - } - } - - /// - /// Update group bounds. - /// 更新组的包围. - /// - public void SetBoundsChangedFlag(bool positionChangedOnly = false) - { - if (_updating == 0 && parent != null) - { - if (!positionChangedOnly) - _percentReady = false; - - if (!_boundsChanged) - { - _boundsChanged = true; - - if (_layout != GroupLayoutType.None) - { - UpdateContext.OnBegin -= _refreshDelegate; - UpdateContext.OnBegin += _refreshDelegate; - } - } - } - } - - public void EnsureBoundsCorrect() - { - if (parent == null || !_boundsChanged) - return; - - UpdateContext.OnBegin -= _refreshDelegate; - _boundsChanged = false; - - if (_autoSizeDisabled) - ResizeChildren(0, 0); - else - { - HandleLayout(); - UpdateBounds(); - } - } - - void UpdateBounds() - { - int cnt = parent.numChildren; - int i; - GObject child; - float ax = int.MaxValue, ay = int.MaxValue; - float ar = int.MinValue, ab = int.MinValue; - float tmp; - bool empty = true; - bool skipInvisibles = _layout != GroupLayoutType.None && _excludeInvisibles; - - for (i = 0; i < cnt; i++) - { - child = parent.GetChildAt(i); - if (child.group != this) - continue; - - if (skipInvisibles && !child.internalVisible3) - continue; - - tmp = child.xMin; - if (tmp < ax) - ax = tmp; - tmp = child.yMin; - if (tmp < ay) - ay = tmp; - tmp = child.xMin + child.width; - if (tmp > ar) - ar = tmp; - tmp = child.yMin + child.height; - if (tmp > ab) - ab = tmp; - - empty = false; - } - - float w; - float h; - if (!empty) - { - _updating |= 1; - SetXY(ax, ay); - _updating &= 2; - - w = ar - ax; - h = ab - ay; - } - else - w = h = 0; - - if ((_updating & 2) == 0) - { - _updating |= 2; - SetSize(w, h); - _updating &= 1; - } - else - { - _updating &= 1; - ResizeChildren(_width - w, _height - h); - } - } - - void HandleLayout() - { - _updating |= 1; - - if (_layout == GroupLayoutType.Horizontal) - { - float curX = this.x; - int cnt = parent.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group != this) - continue; - if (_excludeInvisibles && !child.internalVisible3) - continue; - - child.xMin = curX; - if (child.width != 0) - curX += child.width + _columnGap; - } - } - else if (_layout == GroupLayoutType.Vertical) - { - float curY = this.y; - int cnt = parent.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group != this) - continue; - if (_excludeInvisibles && !child.internalVisible3) - continue; - - child.yMin = curY; - if (child.height != 0) - curY += child.height + _lineGap; - } - } - - _updating &= 2; - } - - internal void MoveChildren(float dx, float dy) - { - if ((_updating & 1) != 0 || parent == null) - return; - - _updating |= 1; - - int cnt = parent.numChildren; - int i; - GObject child; - for (i = 0; i < cnt; i++) - { - child = parent.GetChildAt(i); - if (child.group == this) - { - child.SetXY(child.x + dx, child.y + dy); - } - } - - _updating &= 2; - } - - internal void ResizeChildren(float dw, float dh) - { - if (_layout == GroupLayoutType.None || (_updating & 2) != 0 || parent == null) - return; - - _updating |= 2; - - if (_boundsChanged) - { - _boundsChanged = false; - if (!_autoSizeDisabled) - { - UpdateBounds(); - return; - } - } - - int cnt = parent.numChildren; - - if (!_percentReady) - { - _percentReady = true; - _numChildren = 0; - _totalSize = 0; - _mainChildIndex = -1; - - int j = 0; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group != this) - continue; - - if (!_excludeInvisibles || child.internalVisible3) - { - if (j == _mainGridIndex) - _mainChildIndex = i; - - _numChildren++; - - if (_layout == GroupLayoutType.Horizontal) - _totalSize += child.width; - else - _totalSize += child.height; - } - - j++; - } - - if (_mainChildIndex != -1) - { - if (_layout == GroupLayoutType.Horizontal) - { - GObject child = parent.GetChildAt(_mainChildIndex); - _totalSize += _mainGridMinSize - child.width; - child._sizePercentInGroup = _mainGridMinSize / _totalSize; - } - else - { - GObject child = parent.GetChildAt(_mainChildIndex); - _totalSize += _mainGridMinSize - child.height; - child._sizePercentInGroup = _mainGridMinSize / _totalSize; - } - } - - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group != this) - continue; - - if (i == _mainChildIndex) - continue; - - if (_totalSize > 0) - child._sizePercentInGroup = (_layout == GroupLayoutType.Horizontal ? child.width : child.height) / _totalSize; - else - child._sizePercentInGroup = 0; - } - } - - float remainSize = 0; - float remainPercent = 1; - bool priorHandled = false; - - if (_layout == GroupLayoutType.Horizontal) - { - remainSize = this.width - (_numChildren - 1) * _columnGap; - if (_mainChildIndex != -1 && remainSize >= _totalSize) - { - GObject child = parent.GetChildAt(_mainChildIndex); - child.SetSize(remainSize - (_totalSize - _mainGridMinSize), child._rawHeight + dh, true); - remainSize -= child.width; - remainPercent -= child._sizePercentInGroup; - priorHandled = true; - } - - float curX = this.x; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group != this) - continue; - - if (_excludeInvisibles && !child.internalVisible3) - { - child.SetSize(child._rawWidth, child._rawHeight + dh, true); - continue; - } - - if (!priorHandled || i != _mainChildIndex) - { - child.SetSize(Mathf.Round(child._sizePercentInGroup / remainPercent * remainSize), child._rawHeight + dh, true); - remainPercent -= child._sizePercentInGroup; - remainSize -= child.width; - } - - child.xMin = curX; - if (child.width != 0) - curX += child.width + _columnGap; - } - } - else - { - remainSize = this.height - (_numChildren - 1) * _lineGap; - if (_mainChildIndex != -1 && remainSize >= _totalSize) - { - GObject child = parent.GetChildAt(_mainChildIndex); - child.SetSize(child._rawWidth + dw, remainSize - (_totalSize - _mainGridMinSize), true); - remainSize -= child.height; - remainPercent -= child._sizePercentInGroup; - priorHandled = true; - } - - float curY = this.y; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group != this) - continue; - - if (_excludeInvisibles && !child.internalVisible3) - { - child.SetSize(child._rawWidth + dw, child._rawHeight, true); - continue; - } - - if (!priorHandled || i != _mainChildIndex) - { - child.SetSize(child._rawWidth + dw, Mathf.Round(child._sizePercentInGroup / remainPercent * remainSize), true); - remainPercent -= child._sizePercentInGroup; - remainSize -= child.height; - } - - child.yMin = curY; - if (child.height != 0) - curY += child.height + _lineGap; - } - } - - _updating &= 1; - } - - override protected void HandleAlphaChanged() - { - base.HandleAlphaChanged(); - - if (this.underConstruct || parent == null) - return; - - int cnt = parent.numChildren; - float a = this.alpha; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group == this) - child.alpha = a; - } - } - - override internal protected void HandleVisibleChanged() - { - if (parent == null) - return; - - int cnt = parent.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject child = parent.GetChildAt(i); - if (child.group == this) - child.HandleVisibleChanged(); - } - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - _layout = (GroupLayoutType)buffer.ReadByte(); - _lineGap = buffer.ReadInt(); - _columnGap = buffer.ReadInt(); - if (buffer.version >= 2) - { - _excludeInvisibles = buffer.ReadBool(); - _autoSizeDisabled = buffer.ReadBool(); - _mainGridIndex = buffer.ReadShort(); - } - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - if (!this.visible) - HandleVisibleChanged(); - } - } -} +using System; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// GGroup class. + /// 组对象,对应编辑器里的高级组。 + /// + public class GGroup : GObject + { + GroupLayoutType _layout; + int _lineGap; + int _columnGap; + + bool _excludeInvisibles; + bool _autoSizeDisabled; + int _mainGridIndex; + int _mainGridMinSize; + + bool _percentReady; + bool _boundsChanged; + int _mainChildIndex; + float _totalSize; + int _numChildren; + internal int _updating; + + Action _refreshDelegate; + + public GGroup() + { + _mainGridIndex = -1; + _mainChildIndex = -1; + _mainGridMinSize = 50; + _refreshDelegate = EnsureBoundsCorrect; + } + + /// + /// Group layout type. + /// + public GroupLayoutType layout + { + get { return _layout; } + set + { + if (_layout != value) + { + _layout = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public int lineGap + { + get { return _lineGap; } + set + { + if (_lineGap != value) + { + _lineGap = value; + SetBoundsChangedFlag(true); + } + } + } + + /// + /// + /// + public int columnGap + { + get { return _columnGap; } + set + { + if (_columnGap != value) + { + _columnGap = value; + SetBoundsChangedFlag(true); + } + } + } + + /// + /// + /// + public bool excludeInvisibles + { + get { return _excludeInvisibles; } + set + { + if (_excludeInvisibles != value) + { + _excludeInvisibles = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public bool autoSizeDisabled + { + get { return _autoSizeDisabled; } + set + { + if (_autoSizeDisabled != value) + { + _autoSizeDisabled = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public int mainGridMinSize + { + get { return _mainGridMinSize; } + set + { + if (_mainGridMinSize != value) + { + _mainGridMinSize = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// + /// + public int mainGridIndex + { + get { return _mainGridIndex; } + set + { + if (_mainGridIndex != value) + { + _mainGridIndex = value; + SetBoundsChangedFlag(); + } + } + } + + /// + /// Update group bounds. + /// 更新组的包围. + /// + public void SetBoundsChangedFlag(bool positionChangedOnly = false) + { + if (_updating == 0 && parent != null) + { + if (!positionChangedOnly) + _percentReady = false; + + if (!_boundsChanged) + { + _boundsChanged = true; + + if (_layout != GroupLayoutType.None) + { + UpdateContext.OnBegin -= _refreshDelegate; + UpdateContext.OnBegin += _refreshDelegate; + } + } + } + } + + public void EnsureBoundsCorrect() + { + if (parent == null || !_boundsChanged) + return; + + UpdateContext.OnBegin -= _refreshDelegate; + _boundsChanged = false; + + if (_autoSizeDisabled) + ResizeChildren(0, 0); + else + { + HandleLayout(); + UpdateBounds(); + } + } + + void UpdateBounds() + { + int cnt = parent.numChildren; + int i; + GObject child; + float ax = int.MaxValue, ay = int.MaxValue; + float ar = int.MinValue, ab = int.MinValue; + float tmp; + bool empty = true; + bool skipInvisibles = _layout != GroupLayoutType.None && _excludeInvisibles; + + for (i = 0; i < cnt; i++) + { + child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (skipInvisibles && !child.internalVisible3) + continue; + + tmp = child.xMin; + if (tmp < ax) + ax = tmp; + tmp = child.yMin; + if (tmp < ay) + ay = tmp; + tmp = child.xMin + child.width; + if (tmp > ar) + ar = tmp; + tmp = child.yMin + child.height; + if (tmp > ab) + ab = tmp; + + empty = false; + } + + float w; + float h; + if (!empty) + { + _updating |= 1; + SetXY(ax, ay); + _updating &= 2; + + w = ar - ax; + h = ab - ay; + } + else + w = h = 0; + + if ((_updating & 2) == 0) + { + _updating |= 2; + SetSize(w, h); + _updating &= 1; + } + else + { + _updating &= 1; + ResizeChildren(_width - w, _height - h); + } + } + + void HandleLayout() + { + _updating |= 1; + + if (_layout == GroupLayoutType.Horizontal) + { + float curX = this.x; + int cnt = parent.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + if (_excludeInvisibles && !child.internalVisible3) + continue; + + child.xMin = curX; + if (child.width != 0) + curX += child.width + _columnGap; + } + } + else if (_layout == GroupLayoutType.Vertical) + { + float curY = this.y; + int cnt = parent.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + if (_excludeInvisibles && !child.internalVisible3) + continue; + + child.yMin = curY; + if (child.height != 0) + curY += child.height + _lineGap; + } + } + + _updating &= 2; + } + + internal void MoveChildren(float dx, float dy) + { + if ((_updating & 1) != 0 || parent == null) + return; + + _updating |= 1; + + int cnt = parent.numChildren; + int i; + GObject child; + for (i = 0; i < cnt; i++) + { + child = parent.GetChildAt(i); + if (child.group == this) + { + child.SetXY(child.x + dx, child.y + dy); + } + } + + _updating &= 2; + } + + internal void ResizeChildren(float dw, float dh) + { + if (_layout == GroupLayoutType.None || (_updating & 2) != 0 || parent == null) + return; + + _updating |= 2; + + if (_boundsChanged) + { + _boundsChanged = false; + if (!_autoSizeDisabled) + { + UpdateBounds(); + return; + } + } + + int cnt = parent.numChildren; + + if (!_percentReady) + { + _percentReady = true; + _numChildren = 0; + _totalSize = 0; + _mainChildIndex = -1; + + int j = 0; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (!_excludeInvisibles || child.internalVisible3) + { + if (j == _mainGridIndex) + _mainChildIndex = i; + + _numChildren++; + + if (_layout == GroupLayoutType.Horizontal) + _totalSize += child.width; + else + _totalSize += child.height; + } + + j++; + } + + if (_mainChildIndex != -1) + { + if (_layout == GroupLayoutType.Horizontal) + { + GObject child = parent.GetChildAt(_mainChildIndex); + _totalSize += _mainGridMinSize - child.width; + child._sizePercentInGroup = _mainGridMinSize / _totalSize; + } + else + { + GObject child = parent.GetChildAt(_mainChildIndex); + _totalSize += _mainGridMinSize - child.height; + child._sizePercentInGroup = _mainGridMinSize / _totalSize; + } + } + + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (i == _mainChildIndex) + continue; + + if (_totalSize > 0) + child._sizePercentInGroup = (_layout == GroupLayoutType.Horizontal ? child.width : child.height) / _totalSize; + else + child._sizePercentInGroup = 0; + } + } + + float remainSize = 0; + float remainPercent = 1; + bool priorHandled = false; + + if (_layout == GroupLayoutType.Horizontal) + { + remainSize = this.width - (_numChildren - 1) * _columnGap; + if (_mainChildIndex != -1 && remainSize >= _totalSize) + { + GObject child = parent.GetChildAt(_mainChildIndex); + child.SetSize(remainSize - (_totalSize - _mainGridMinSize), child._rawHeight + dh, true); + remainSize -= child.width; + remainPercent -= child._sizePercentInGroup; + priorHandled = true; + } + + float curX = this.x; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (_excludeInvisibles && !child.internalVisible3) + { + child.SetSize(child._rawWidth, child._rawHeight + dh, true); + continue; + } + + if (!priorHandled || i != _mainChildIndex) + { + child.SetSize(Mathf.Round(child._sizePercentInGroup / remainPercent * remainSize), child._rawHeight + dh, true); + remainPercent -= child._sizePercentInGroup; + remainSize -= child.width; + } + + child.xMin = curX; + if (child.width != 0) + curX += child.width + _columnGap; + } + } + else + { + remainSize = this.height - (_numChildren - 1) * _lineGap; + if (_mainChildIndex != -1 && remainSize >= _totalSize) + { + GObject child = parent.GetChildAt(_mainChildIndex); + child.SetSize(child._rawWidth + dw, remainSize - (_totalSize - _mainGridMinSize), true); + remainSize -= child.height; + remainPercent -= child._sizePercentInGroup; + priorHandled = true; + } + + float curY = this.y; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group != this) + continue; + + if (_excludeInvisibles && !child.internalVisible3) + { + child.SetSize(child._rawWidth + dw, child._rawHeight, true); + continue; + } + + if (!priorHandled || i != _mainChildIndex) + { + child.SetSize(child._rawWidth + dw, Mathf.Round(child._sizePercentInGroup / remainPercent * remainSize), true); + remainPercent -= child._sizePercentInGroup; + remainSize -= child.height; + } + + child.yMin = curY; + if (child.height != 0) + curY += child.height + _lineGap; + } + } + + _updating &= 1; + } + + override protected void HandleAlphaChanged() + { + base.HandleAlphaChanged(); + + if (this.underConstruct || parent == null) + return; + + int cnt = parent.numChildren; + float a = this.alpha; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group == this) + child.alpha = a; + } + } + + override internal protected void HandleVisibleChanged() + { + if (parent == null) + return; + + int cnt = parent.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject child = parent.GetChildAt(i); + if (child.group == this) + child.HandleVisibleChanged(); + } + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _layout = (GroupLayoutType)buffer.ReadByte(); + _lineGap = buffer.ReadInt(); + _columnGap = buffer.ReadInt(); + if (buffer.version >= 2) + { + _excludeInvisibles = buffer.ReadBool(); + _autoSizeDisabled = buffer.ReadBool(); + _mainGridIndex = buffer.ReadShort(); + } + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!this.visible) + HandleVisibleChanged(); + } + } +} diff --git a/Assets/Scripts/UI/GGroup.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGroup.cs.meta similarity index 100% rename from Assets/Scripts/UI/GGroup.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GGroup.cs.meta diff --git a/Assets/Scripts/UI/GImage.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GImage.cs similarity index 96% rename from Assets/Scripts/UI/GImage.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GImage.cs index 417fd5d8..457d71db 100644 --- a/Assets/Scripts/UI/GImage.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GImage.cs @@ -1,170 +1,170 @@ -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GImage class. - /// - public class GImage : GObject, IColorGear - { - Image _content; - - public GImage() - { - } - - override protected void CreateDisplayObject() - { - _content = new Image(); - _content.gOwner = this; - displayObject = _content; - } - - /// - /// Color of the image. - /// - public Color color - { - get { return _content.color; } - set - { - _content.color = value; - UpdateGear(4); - } - } - - /// - /// Flip type. - /// - /// - public FlipType flip - { - get { return _content.graphics.flip; } - set { _content.graphics.flip = value; } - } - - /// - /// Fill method. - /// - /// - public FillMethod fillMethod - { - get { return _content.fillMethod; } - set { _content.fillMethod = value; } - } - - /// - /// Fill origin. - /// - /// - /// - /// - /// - /// - public int fillOrigin - { - get { return _content.fillOrigin; } - set { _content.fillOrigin = value; } - } - - /// - /// Fill clockwise if true. - /// - public bool fillClockwise - { - get { return _content.fillClockwise; } - set { _content.fillClockwise = value; } - } - - /// - /// Fill amount. (0~1) - /// - public float fillAmount - { - get { return _content.fillAmount; } - set { _content.fillAmount = value; } - } - - /// - /// Set texture directly. The image wont own the texture. - /// - public NTexture texture - { - get { return _content.texture; } - set - { - if (value != null) - { - sourceWidth = value.width; - sourceHeight = value.height; - } - else - { - sourceWidth = 0; - sourceHeight = 0; - } - initWidth = sourceWidth; - initHeight = sourceHeight; - _content.texture = value; - } - } - - /// - /// Set material. - /// - public Material material - { - get { return _content.material; } - set { _content.material = value; } - } - - /// - /// Set shader. - /// - public string shader - { - get { return _content.shader; } - set { _content.shader = value; } - } - - override public void ConstructFromResource() - { - this.gameObjectName = packageItem.name; - - PackageItem contentItem = packageItem.getBranch(); - sourceWidth = contentItem.width; - sourceHeight = contentItem.height; - initWidth = sourceWidth; - initHeight = sourceHeight; - - contentItem = contentItem.getHighResolution(); - contentItem.Load(); - _content.scale9Grid = contentItem.scale9Grid; - _content.scaleByTile = contentItem.scaleByTile; - _content.tileGridIndice = contentItem.tileGridIndice; - _content.texture = contentItem.texture; - _content.textureScale = new Vector2(contentItem.width / (float)sourceWidth, contentItem.height / (float)sourceHeight); - - SetSize(sourceWidth, sourceHeight); - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - if (buffer.ReadBool()) - _content.color = buffer.ReadColor(); - _content.graphics.flip = (FlipType)buffer.ReadByte(); - _content.fillMethod = (FillMethod)buffer.ReadByte(); - if (_content.fillMethod != FillMethod.None) - { - _content.fillOrigin = buffer.ReadByte(); - _content.fillClockwise = buffer.ReadBool(); - _content.fillAmount = buffer.ReadFloat(); - } - } - } -} +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GImage class. + /// + public class GImage : GObject, IColorGear + { + Image _content; + + public GImage() + { + } + + override protected void CreateDisplayObject() + { + _content = new Image(); + _content.gOwner = this; + displayObject = _content; + } + + /// + /// Color of the image. + /// + public Color color + { + get { return _content.color; } + set + { + _content.color = value; + UpdateGear(4); + } + } + + /// + /// Flip type. + /// + /// + public FlipType flip + { + get { return _content.graphics.flip; } + set { _content.graphics.flip = value; } + } + + /// + /// Fill method. + /// + /// + public FillMethod fillMethod + { + get { return _content.fillMethod; } + set { _content.fillMethod = value; } + } + + /// + /// Fill origin. + /// + /// + /// + /// + /// + /// + public int fillOrigin + { + get { return _content.fillOrigin; } + set { _content.fillOrigin = value; } + } + + /// + /// Fill clockwise if true. + /// + public bool fillClockwise + { + get { return _content.fillClockwise; } + set { _content.fillClockwise = value; } + } + + /// + /// Fill amount. (0~1) + /// + public float fillAmount + { + get { return _content.fillAmount; } + set { _content.fillAmount = value; } + } + + /// + /// Set texture directly. The image wont own the texture. + /// + public NTexture texture + { + get { return _content.texture; } + set + { + if (value != null) + { + sourceWidth = value.width; + sourceHeight = value.height; + } + else + { + sourceWidth = 0; + sourceHeight = 0; + } + initWidth = sourceWidth; + initHeight = sourceHeight; + _content.texture = value; + } + } + + /// + /// Set material. + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// Set shader. + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + override public void ConstructFromResource() + { + this.gameObjectName = packageItem.name; + + PackageItem contentItem = packageItem.getBranch(); + sourceWidth = contentItem.width; + sourceHeight = contentItem.height; + initWidth = sourceWidth; + initHeight = sourceHeight; + + contentItem = contentItem.getHighResolution(); + contentItem.Load(); + _content.scale9Grid = contentItem.scale9Grid; + _content.scaleByTile = contentItem.scaleByTile; + _content.tileGridIndice = contentItem.tileGridIndice; + _content.texture = contentItem.texture; + _content.textureScale = new Vector2(contentItem.width / (float)sourceWidth, contentItem.height / (float)sourceHeight); + + SetSize(sourceWidth, sourceHeight); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + if (buffer.ReadBool()) + _content.color = buffer.ReadColor(); + _content.graphics.flip = (FlipType)buffer.ReadByte(); + _content.fillMethod = (FillMethod)buffer.ReadByte(); + if (_content.fillMethod != FillMethod.None) + { + _content.fillOrigin = buffer.ReadByte(); + _content.fillClockwise = buffer.ReadBool(); + _content.fillAmount = buffer.ReadFloat(); + } + } + } +} diff --git a/Assets/Scripts/UI/GImage.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GImage.cs.meta similarity index 100% rename from Assets/Scripts/UI/GImage.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GImage.cs.meta diff --git a/Assets/Scripts/UI/GLabel.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLabel.cs similarity index 96% rename from Assets/Scripts/UI/GLabel.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLabel.cs index da840c30..bc0a5b27 100644 --- a/Assets/Scripts/UI/GLabel.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLabel.cs @@ -1,235 +1,235 @@ -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GLabel class. - /// - public class GLabel : GComponent, IColorGear - { - protected GObject _titleObject; - protected GObject _iconObject; - - public GLabel() - { - } - - /// - /// Icon of the label. - /// - override public string icon - { - get - { - if (_iconObject != null) - return _iconObject.icon; - else - return null; - } - - set - { - if (_iconObject != null) - _iconObject.icon = value; - UpdateGear(7); - } - } - - /// - /// Title of the label. - /// - public string title - { - get - { - if (_titleObject != null) - return _titleObject.text; - else - return null; - } - set - { - if (_titleObject != null) - _titleObject.text = value; - UpdateGear(6); - } - } - - /// - /// Same of the title. - /// - override public string text - { - get { return this.title; } - set { this.title = value; } - } - - /// - /// If title is input text. - /// - public bool editable - { - get - { - if (_titleObject is GTextInput) - return _titleObject.asTextInput.editable; - else - return false; - } - - set - { - if (_titleObject is GTextInput) - _titleObject.asTextInput.editable = value; - } - } - - /// - /// Title color of the label - /// - public Color titleColor - { - get - { - GTextField tf = GetTextField(); - if (tf != null) - return tf.color; - else - return Color.black; - } - set - { - GTextField tf = GetTextField(); - if (tf != null) - { - tf.color = value; - UpdateGear(4); - } - } - } - - /// - /// - /// - public int titleFontSize - { - get - { - GTextField tf = GetTextField(); - if (tf != null) - return tf.textFormat.size; - else - return 0; - } - set - { - GTextField tf = GetTextField(); - if (tf != null) - { - TextFormat format = tf.textFormat; - format.size = value; - tf.textFormat = format; - } - } - } - - /// - /// - /// - public Color color - { - get { return this.titleColor; } - set { this.titleColor = value; } - } - - /// - /// - /// - /// - public GTextField GetTextField() - { - if (_titleObject is GTextField) - return (GTextField)_titleObject; - else if (_titleObject is GLabel) - return ((GLabel)_titleObject).GetTextField(); - else if (_titleObject is GButton) - return ((GButton)_titleObject).GetTextField(); - else - return null; - } - - override protected void ConstructExtension(ByteBuffer buffer) - { - _titleObject = GetChild("title"); - _iconObject = GetChild("icon"); - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - if (!buffer.Seek(beginPos, 6)) - return; - - if ((ObjectType)buffer.ReadByte() != packageItem.objectType) - return; - - string str; - str = buffer.ReadS(); - if (str != null) - this.title = str; - str = buffer.ReadS(); - if (str != null) - this.icon = str; - if (buffer.ReadBool()) - this.titleColor = buffer.ReadColor(); - int iv = buffer.ReadInt(); - if (iv != 0) - this.titleFontSize = iv; - - if (buffer.ReadBool()) - { - GTextInput input = GetTextField() as GTextInput; - if (input != null) - { - str = buffer.ReadS(); - if (str != null) - input.promptText = str; - - str = buffer.ReadS(); - if (str != null) - input.restrict = str; - - iv = buffer.ReadInt(); - if (iv != 0) - input.maxLength = iv; - iv = buffer.ReadInt(); - if (iv != 0) - input.keyboardType = iv; - if (buffer.ReadBool()) - input.displayAsPassword = true; - } - else - buffer.Skip(13); - } - - if (buffer.version >= 5) - { - string sound = buffer.ReadS(); - if (!string.IsNullOrEmpty(sound)) - { - float volumeScale = buffer.ReadFloat(); - displayObject.onClick.Add(() => - { - NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip; - if (audioClip != null && audioClip.nativeClip != null) - Stage.inst.PlayOneShotSound(audioClip.nativeClip, volumeScale); - }); - } - else - buffer.Skip(4); - } - } - } -} +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GLabel class. + /// + public class GLabel : GComponent, IColorGear + { + protected GObject _titleObject; + protected GObject _iconObject; + + public GLabel() + { + } + + /// + /// Icon of the label. + /// + override public string icon + { + get + { + if (_iconObject != null) + return _iconObject.icon; + else + return null; + } + + set + { + if (_iconObject != null) + _iconObject.icon = value; + UpdateGear(7); + } + } + + /// + /// Title of the label. + /// + public string title + { + get + { + if (_titleObject != null) + return _titleObject.text; + else + return null; + } + set + { + if (_titleObject != null) + _titleObject.text = value; + UpdateGear(6); + } + } + + /// + /// Same of the title. + /// + override public string text + { + get { return this.title; } + set { this.title = value; } + } + + /// + /// If title is input text. + /// + public bool editable + { + get + { + if (_titleObject is GTextInput) + return _titleObject.asTextInput.editable; + else + return false; + } + + set + { + if (_titleObject is GTextInput) + _titleObject.asTextInput.editable = value; + } + } + + /// + /// Title color of the label + /// + public Color titleColor + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.color; + else + return Color.black; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + tf.color = value; + UpdateGear(4); + } + } + } + + /// + /// + /// + public int titleFontSize + { + get + { + GTextField tf = GetTextField(); + if (tf != null) + return tf.textFormat.size; + else + return 0; + } + set + { + GTextField tf = GetTextField(); + if (tf != null) + { + TextFormat format = tf.textFormat; + format.size = value; + tf.textFormat = format; + } + } + } + + /// + /// + /// + public Color color + { + get { return this.titleColor; } + set { this.titleColor = value; } + } + + /// + /// + /// + /// + public GTextField GetTextField() + { + if (_titleObject is GTextField) + return (GTextField)_titleObject; + else if (_titleObject is GLabel) + return ((GLabel)_titleObject).GetTextField(); + else if (_titleObject is GButton) + return ((GButton)_titleObject).GetTextField(); + else + return null; + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + _titleObject = GetChild("title"); + _iconObject = GetChild("icon"); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + return; + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + return; + + string str; + str = buffer.ReadS(); + if (str != null) + this.title = str; + str = buffer.ReadS(); + if (str != null) + this.icon = str; + if (buffer.ReadBool()) + this.titleColor = buffer.ReadColor(); + int iv = buffer.ReadInt(); + if (iv != 0) + this.titleFontSize = iv; + + if (buffer.ReadBool()) + { + GTextInput input = GetTextField() as GTextInput; + if (input != null) + { + str = buffer.ReadS(); + if (str != null) + input.promptText = str; + + str = buffer.ReadS(); + if (str != null) + input.restrict = str; + + iv = buffer.ReadInt(); + if (iv != 0) + input.maxLength = iv; + iv = buffer.ReadInt(); + if (iv != 0) + input.keyboardType = iv; + if (buffer.ReadBool()) + input.displayAsPassword = true; + } + else + buffer.Skip(13); + } + + if (buffer.version >= 5) + { + string sound = buffer.ReadS(); + if (!string.IsNullOrEmpty(sound)) + { + float volumeScale = buffer.ReadFloat(); + displayObject.onClick.Add(() => + { + NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip; + if (audioClip != null && audioClip.nativeClip != null) + Stage.inst.PlayOneShotSound(audioClip.nativeClip, volumeScale); + }); + } + else + buffer.Skip(4); + } + } + } +} diff --git a/Assets/Scripts/UI/GLabel.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLabel.cs.meta similarity index 100% rename from Assets/Scripts/UI/GLabel.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLabel.cs.meta diff --git a/Assets/Scripts/UI/GList.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GList.cs similarity index 97% rename from Assets/Scripts/UI/GList.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GList.cs index f19ed898..37ced040 100644 --- a/Assets/Scripts/UI/GList.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GList.cs @@ -1,3067 +1,3067 @@ -using System; -using System.Collections.Generic; -using FairyGUI.Utils; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// Callback function when an item is needed to update its look. - /// - /// Item index. - /// Item object. - public delegate void ListItemRenderer(int index, GObject item); - - /// - /// - /// - /// - /// - public delegate string ListItemProvider(int index); - - /// - /// GList class. - /// - public class GList : GComponent - { - /// - /// 如果true,当item不可见时自动折叠,否则依然占位 - /// - public bool foldInvisibleItems = false; - - /// - /// List selection mode - /// - /// - public ListSelectionMode selectionMode; - - /// - /// Callback function when an item is needed to update its look. - /// - public ListItemRenderer itemRenderer; - - /// - /// Callback funtion to return item resource url. - /// - public ListItemProvider itemProvider; - - /// - /// - /// - public bool scrollItemToViewOnClick; - - string _defaultItem; - ListLayoutType _layout; - int _lineCount; - int _columnCount; - int _lineGap; - int _columnGap; - AlignType _align; - VertAlignType _verticalAlign; - bool _autoResizeItem; - Controller _selectionController; - - GObjectPool _pool; - int _lastSelectedIndex; - - EventListener _onClickItem; - EventListener _onRightClickItem; - - //Virtual List support - bool _virtual; - bool _loop; - int _numItems; - int _realNumItems; - int _firstIndex; //the top left index - int _curLineItemCount; //item count in one line - int _curLineItemCount2; //只用在页面模式,表示垂直方向的项目数 - Vector2 _itemSize; - int _virtualListChanged; //1-content changed, 2-size changed - uint itemInfoVer; //用来标志item是否在本次处理中已经被重用了 - - int _miscFlags; //1-event locked, 2-focus events registered - - class ItemInfo - { - public Vector2 size; - public GObject obj; - public uint updateFlag; - public bool selected; - } - List _virtualItems; - - EventCallback1 _itemClickDelegate; - - public GList() - : base() - { - _trackBounds = true; - this.opaque = true; - scrollItemToViewOnClick = true; - - container = new Container(); - rootContainer.AddChild(container); - rootContainer.gameObject.name = "GList"; - - _pool = new GObjectPool(container.cachedTransform); - - _itemClickDelegate = __clickItem; - } - - public override void Dispose() - { - _pool.Clear(); - if (_virtualListChanged != 0) - Timers.inst.Remove(this.RefreshVirtualList); - - _selectionController = null; - scrollItemToViewOnClick = false; - itemRenderer = null; - itemProvider = null; - - base.Dispose(); - } - - /// - /// Dispatched when a list item being clicked. - /// - public EventListener onClickItem - { - get { return _onClickItem ?? (_onClickItem = new EventListener(this, "onClickItem")); } - } - - /// - /// Dispatched when a list item being clicked with right button. - /// - public EventListener onRightClickItem - { - get { return _onRightClickItem ?? (_onRightClickItem = new EventListener(this, "onRightClickItem")); } - } - - /// - /// Resource url of the default item. - /// - public string defaultItem - { - get { return _defaultItem; } - set - { - _defaultItem = UIPackage.NormalizeURL(value); - } - } - - /// - /// List layout type. - /// - public ListLayoutType layout - { - get { return _layout; } - set - { - if (_layout != value) - { - _layout = value; - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - - /// - /// - /// - public int lineCount - { - get { return _lineCount; } - set - { - if (_lineCount != value) - { - _lineCount = value; - if (_layout == ListLayoutType.FlowVertical || _layout == ListLayoutType.Pagination) - { - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - } - - /// - /// - /// - public int columnCount - { - get { return _columnCount; } - set - { - if (_columnCount != value) - { - _columnCount = value; - if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) - { - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - } - - /// - /// - /// - public int lineGap - { - get { return _lineGap; } - set - { - if (_lineGap != value) - { - _lineGap = value; - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - - /// - /// - /// - public int columnGap - { - get { return _columnGap; } - set - { - if (_columnGap != value) - { - _columnGap = value; - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - - /// - /// - /// - public AlignType align - { - get { return _align; } - set - { - if (_align != value) - { - _align = value; - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - - /// - /// - /// - public VertAlignType verticalAlign - { - get { return _verticalAlign; } - set - { - if (_verticalAlign != value) - { - _verticalAlign = value; - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - /// - /// If the item will resize itself to fit the list width/height. - /// - public bool autoResizeItem - { - get { return _autoResizeItem; } - set - { - if (_autoResizeItem != value) - { - _autoResizeItem = value; - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - } - } - - /// - /// - /// - /// - public Vector2 defaultItemSize - { - get { return _itemSize; } - set - { - _itemSize = value; - if (_virtual) - { - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - this.scrollPane.scrollStep = _itemSize.y; - else - this.scrollPane.scrollStep = _itemSize.x; - SetVirtualListChangedFlag(true); - } - } - } - - /// - /// - /// - public GObjectPool itemPool - { - get { return _pool; } - } - - /// - /// - /// - /// - /// - public GObject GetFromPool(string url) - { - if (string.IsNullOrEmpty(url)) - url = _defaultItem; - - GObject ret = _pool.GetObject(url); - if (ret != null) - ret.visible = true; - return ret; - } - - void ReturnToPool(GObject obj) - { - _pool.ReturnObject(obj); - } - - /// - /// Add a item to list, same as GetFromPool+AddChild - /// - /// Item object - public GObject AddItemFromPool() - { - GObject obj = GetFromPool(null); - - return AddChild(obj); - } - - /// - /// Add a item to list, same as GetFromPool+AddChild - /// - /// Item resource url - /// Item object - public GObject AddItemFromPool(string url) - { - GObject obj = GetFromPool(url); - - return AddChild(obj); - } - - /// - /// - /// - /// - /// - /// - override public GObject AddChildAt(GObject child, int index) - { - base.AddChildAt(child, index); - if (child is GButton) - { - GButton button = (GButton)child; - button.selected = false; - button.changeStateOnClick = false; - } - - child.onClick.Add(_itemClickDelegate); - child.onRightClick.Add(_itemClickDelegate); - - return child; - } - - /// - /// - /// - /// - /// - /// - override public GObject RemoveChildAt(int index, bool dispose) - { - GObject child = base.RemoveChildAt(index, dispose); - child.onClick.Remove(_itemClickDelegate); - child.onRightClick.Remove(_itemClickDelegate); - - return child; - } - - /// - /// - /// - /// - public void RemoveChildToPoolAt(int index) - { - GObject child = base.RemoveChildAt(index); - ReturnToPool(child); - } - - /// - /// - /// - /// - public void RemoveChildToPool(GObject child) - { - base.RemoveChild(child); - ReturnToPool(child); - } - - /// - /// - /// - public void RemoveChildrenToPool() - { - RemoveChildrenToPool(0, -1); - } - - /// - /// - /// - /// - /// - public void RemoveChildrenToPool(int beginIndex, int endIndex) - { - if (endIndex < 0 || endIndex >= _children.Count) - endIndex = _children.Count - 1; - - for (int i = beginIndex; i <= endIndex; ++i) - RemoveChildToPoolAt(beginIndex); - } - - /// - /// - /// - public int selectedIndex - { - get - { - if (_virtual) - { - int cnt = _realNumItems; - for (int i = 0; i < cnt; i++) - { - ItemInfo ii = _virtualItems[i]; - if ((ii.obj is GButton) && ((GButton)ii.obj).selected - || ii.obj == null && ii.selected) - { - if (_loop) - return i % _numItems; - else - return i; - } - } - } - else - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null && obj.selected) - return i; - } - } - return -1; - } - - set - { - if (value >= 0 && value < this.numItems) - { - if (selectionMode != ListSelectionMode.Single) - ClearSelection(); - AddSelection(value, false); - } - else - ClearSelection(); - } - } - - /// - /// - /// - public Controller selectionController - { - get { return _selectionController; } - set { _selectionController = value; } - } - - /// - /// - /// - /// - public List GetSelection() - { - return GetSelection(null); - } - - /// - /// - /// - /// - public List GetSelection(List result) - { - if (result == null) - result = new List(); - if (_virtual) - { - int cnt = _realNumItems; - for (int i = 0; i < cnt; i++) - { - ItemInfo ii = _virtualItems[i]; - if ((ii.obj is GButton) && ((GButton)ii.obj).selected - || ii.obj == null && ii.selected) - { - int j = i; - if (_loop) - { - j = i % _numItems; - if (result.Contains(j)) - continue; - } - result.Add(j); - } - } - } - else - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null && obj.selected) - result.Add(i); - } - } - return result; - } - - /// - /// - /// - /// - /// - public void AddSelection(int index, bool scrollItToView) - { - if (selectionMode == ListSelectionMode.None) - return; - - CheckVirtualList(); - - if (selectionMode == ListSelectionMode.Single) - ClearSelection(); - - if (scrollItToView) - ScrollToView(index); - - _lastSelectedIndex = index; - GButton obj = null; - if (_virtual) - { - ItemInfo ii = _virtualItems[index]; - if (ii.obj != null) - obj = ii.obj.asButton; - ii.selected = true; - } - else - obj = GetChildAt(index).asButton; - - if (obj != null && !obj.selected) - { - obj.selected = true; - UpdateSelectionController(index); - } - } - - /// - /// - /// - /// - public void RemoveSelection(int index) - { - if (selectionMode == ListSelectionMode.None) - return; - - GButton obj = null; - if (_virtual) - { - ItemInfo ii = _virtualItems[index]; - if (ii.obj != null) - obj = ii.obj.asButton; - ii.selected = false; - } - else - obj = GetChildAt(index).asButton; - - if (obj != null) - obj.selected = false; - } - - /// - /// - /// - public void ClearSelection() - { - if (_virtual) - { - int cnt = _realNumItems; - for (int i = 0; i < cnt; i++) - { - ItemInfo ii = _virtualItems[i]; - if ((ii.obj is GButton)) - ((GButton)ii.obj).selected = false; - ii.selected = false; - } - } - else - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null) - obj.selected = false; - } - } - } - - void ClearSelectionExcept(GObject g) - { - if (_virtual) - { - int cnt = _realNumItems; - for (int i = 0; i < cnt; i++) - { - ItemInfo ii = _virtualItems[i]; - if (ii.obj != g) - { - if ((ii.obj is GButton)) - ((GButton)ii.obj).selected = false; - ii.selected = false; - } - } - } - else - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null && obj != g) - obj.selected = false; - } - } - } - - /// - /// - /// - public void SelectAll() - { - CheckVirtualList(); - - int last = -1; - if (_virtual) - { - int cnt = _realNumItems; - for (int i = 0; i < cnt; i++) - { - ItemInfo ii = _virtualItems[i]; - if ((ii.obj is GButton) && !((GButton)ii.obj).selected) - { - ((GButton)ii.obj).selected = true; - last = i; - } - ii.selected = true; - } - } - else - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null && !obj.selected) - { - obj.selected = true; - last = i; - } - } - } - - if (last != -1) - UpdateSelectionController(last); - } - - /// - /// - /// - public void SelectNone() - { - ClearSelection(); - } - - /// - /// - /// - public void SelectReverse() - { - CheckVirtualList(); - - int last = -1; - if (_virtual) - { - int cnt = _realNumItems; - for (int i = 0; i < cnt; i++) - { - ItemInfo ii = _virtualItems[i]; - if ((ii.obj is GButton)) - { - ((GButton)ii.obj).selected = !((GButton)ii.obj).selected; - if (((GButton)ii.obj).selected) - last = i; - } - ii.selected = !ii.selected; - } - } - else - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null) - { - obj.selected = !obj.selected; - if (obj.selected) - last = i; - } - } - } - - if (last != -1) - UpdateSelectionController(last); - } - - /// - /// - /// - /// - public void EnableSelectionFocusEvents(bool enabled) - { - if (((_miscFlags & 2) != 0) == enabled) - return; - - if (enabled) - { - _miscFlags |= 2; - this.tabStopChildren = true; - onFocusIn.Add(NotifySelection); - onFocusOut.Add(NotifySelection); - } - else - { - _miscFlags &= 0xFD; - onFocusIn.Remove(NotifySelection); - onFocusOut.Remove(NotifySelection); - } - } - - void NotifySelection(EventContext context) - { - string eventType = context.type == "onFocusIn" ? "onListFocusIn" : "onListFocusOut"; - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - GButton obj = _children[i].asButton; - if (obj != null && obj.selected) - obj.DispatchEvent(eventType); - } - } - - /// - /// - /// - public void EnableArrowKeyNavigation(bool enabled) - { - if (enabled) - { - this.tabStopChildren = true; - onKeyDown.Add(__keydown); - } - else - { - this.tabStopChildren = false; - onKeyDown.Remove(__keydown); - } - } - - void __keydown(EventContext context) - { - int index = -1; - switch (context.inputEvent.keyCode) - { - case KeyCode.LeftArrow: - index = HandleArrowKey(7); - break; - - case KeyCode.RightArrow: - index = HandleArrowKey(3); - break; - - case KeyCode.UpArrow: - index = HandleArrowKey(1); - break; - - case KeyCode.DownArrow: - index = HandleArrowKey(5); - break; - } - - if (index != -1) - { - index = ItemIndexToChildIndex(index); - if (index != -1) - DispatchItemEvent(GetChildAt(index), context); - - context.StopPropagation(); - } - } - - /// - /// - /// - /// - public int HandleArrowKey(int dir) - { - int curIndex = this.selectedIndex; - if (curIndex == -1) - return -1; - - int index = curIndex; - switch (dir) - { - case 1://up - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowVertical) - { - index--; - } - else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) - { - if (_virtual) - { - index -= _curLineItemCount; - } - else - { - GObject current = _children[index]; - int k = 0; - int i; - for (i = index - 1; i >= 0; i--) - { - GObject obj = _children[i]; - if (obj.y != current.y) - { - current = obj; - break; - } - k++; - } - for (; i >= 0; i--) - { - GObject obj = _children[i]; - if (obj.y != current.y) - { - index = i + k + 1; - break; - } - } - } - } - break; - - case 3://right - if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) - { - index++; - } - else if (_layout == ListLayoutType.FlowVertical) - { - if (_virtual) - { - index += _curLineItemCount; - } - else - { - GObject current = _children[index]; - int k = 0; - int cnt = _children.Count; - int i; - for (i = index + 1; i < cnt; i++) - { - GObject obj = _children[i]; - if (obj.x != current.x) - { - current = obj; - break; - } - k++; - } - for (; i < cnt; i++) - { - GObject obj = _children[i]; - if (obj.x != current.x) - { - index = i - k - 1; - break; - } - } - } - } - break; - - case 5://down - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowVertical) - { - index++; - } - else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) - { - if (_virtual) - { - index += _curLineItemCount; - } - else - { - GObject current = _children[index]; - int k = 0; - int cnt = _children.Count; - int i; - for (i = index + 1; i < cnt; i++) - { - GObject obj = _children[i]; - if (obj.y != current.y) - { - current = obj; - break; - } - k++; - } - for (; i < cnt; i++) - { - GObject obj = _children[i]; - if (obj.y != current.y) - { - index = i - k - 1; - break; - } - } - } - } - break; - - case 7://left - if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) - { - index--; - } - else if (_layout == ListLayoutType.FlowVertical) - { - if (_virtual) - { - index -= _curLineItemCount; - } - else - { - GObject current = _children[index]; - int k = 0; - int i; - for (i = index - 1; i >= 0; i--) - { - GObject obj = _children[i]; - if (obj.x != current.x) - { - current = obj; - break; - } - k++; - } - for (; i >= 0; i--) - { - GObject obj = _children[i]; - if (obj.x != current.x) - { - index = i + k + 1; - break; - } - } - } - } - break; - } - - if (index != curIndex && index >= 0 && index < this.numItems) - { - ClearSelection(); - AddSelection(index, true); - return index; - } - else - return -1; - } - - void __clickItem(EventContext context) - { - GObject item = context.sender as GObject; - if ((item is GButton) && selectionMode != ListSelectionMode.None) - SetSelectionOnEvent(item, context.inputEvent); - - if (scrollPane != null && scrollItemToViewOnClick) - scrollPane.ScrollToView(item, true); - - DispatchItemEvent(item, context); - } - - virtual protected void DispatchItemEvent(GObject item, EventContext context) - { - if (context.type == item.onRightClick.type) - DispatchEvent("onRightClickItem", item); - else - DispatchEvent("onClickItem", item); - } - - void SetSelectionOnEvent(GObject item, InputEvent evt) - { - bool dontChangeLastIndex = false; - GButton button = (GButton)item; - int index = ChildIndexToItemIndex(GetChildIndex(item)); - - if (selectionMode == ListSelectionMode.Single) - { - if (!button.selected) - { - ClearSelectionExcept(button); - button.selected = true; - } - } - else - { - if (evt.shift) - { - if (!button.selected) - { - if (_lastSelectedIndex != -1) - { - int min = Math.Min(_lastSelectedIndex, index); - int max = Math.Max(_lastSelectedIndex, index); - max = Math.Min(max, this.numItems - 1); - if (_virtual) - { - for (int i = min; i <= max; i++) - { - ItemInfo ii = _virtualItems[i]; - if (ii.obj is GButton) - ((GButton)ii.obj).selected = true; - ii.selected = true; - } - } - else - { - for (int i = min; i <= max; i++) - { - GButton obj = GetChildAt(i).asButton; - if (obj != null && !obj.selected) - obj.selected = true; - } - } - - dontChangeLastIndex = true; - } - else - { - button.selected = true; - } - } - } - else if (evt.ctrlOrCmd || selectionMode == ListSelectionMode.Multiple_SingleClick) - { - button.selected = !button.selected; - } - else - { - if (!button.selected) - { - ClearSelectionExcept(button); - button.selected = true; - } - else if (evt.button == 0) - ClearSelectionExcept(button); - } - } - - if (!dontChangeLastIndex) - _lastSelectedIndex = index; - - if (button.selected) - UpdateSelectionController(index); - } - - /// - /// Resize to list size to fit specified item count. - /// If list layout is single column or flow horizontally, the height will change to fit. - /// If list layout is single row or flow vertically, the width will change to fit. - /// - public void ResizeToFit() - { - ResizeToFit(int.MaxValue, 0); - } - - /// - /// Resize to list size to fit specified item count. - /// If list layout is single column or flow horizontally, the height will change to fit. - /// If list layout is single row or flow vertically, the width will change to fit. - /// - /// Item count - public void ResizeToFit(int itemCount) - { - ResizeToFit(itemCount, 0); - } - - /// - /// Resize to list size to fit specified item count. - /// If list layout is single column or flow horizontally, the height will change to fit. - /// If list layout is single row or flow vertically, the width will change to fit. - /// - /// >Item count - /// If the result size if smaller than minSize, then use minSize. - public void ResizeToFit(int itemCount, int minSize) - { - EnsureBoundsCorrect(); - - int curCount = this.numItems; - if (itemCount > curCount) - itemCount = curCount; - - if (_virtual) - { - int lineCount = Mathf.CeilToInt((float)itemCount / _curLineItemCount); - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - this.viewHeight = lineCount * _itemSize.y + Math.Max(0, lineCount - 1) * _lineGap; - else - this.viewWidth = lineCount * _itemSize.x + Math.Max(0, lineCount - 1) * _columnGap; - } - else if (itemCount == 0) - { - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - this.viewHeight = minSize; - else - this.viewWidth = minSize; - } - else - { - int i = itemCount - 1; - GObject obj = null; - while (i >= 0) - { - obj = this.GetChildAt(i); - if (!foldInvisibleItems || obj.visible) - break; - i--; - } - if (i < 0) - { - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - this.viewHeight = minSize; - else - this.viewWidth = minSize; - } - else - { - float size; - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - { - size = obj.y + obj.height; - if (size < minSize) - size = minSize; - this.viewHeight = size; - } - else - { - size = obj.x + obj.width; - if (size < minSize) - size = minSize; - this.viewWidth = size; - } - } - } - } - - /// - /// - /// - override protected void HandleSizeChanged() - { - base.HandleSizeChanged(); - - SetBoundsChangedFlag(); - if (_virtual) - SetVirtualListChangedFlag(true); - } - - override public void HandleControllerChanged(Controller c) - { - base.HandleControllerChanged(c); - - if (_selectionController == c) - this.selectedIndex = c.selectedIndex; - } - - void UpdateSelectionController(int index) - { - if (_selectionController != null && !_selectionController.changing - && index < _selectionController.pageCount) - { - Controller c = _selectionController; - _selectionController = null; - c.selectedIndex = index; - _selectionController = c; - } - } - - /// - /// Scroll the list to make an item with certain index visible. - /// - /// Item index - public void ScrollToView(int index) - { - ScrollToView(index, false); - } - - /// - /// Scroll the list to make an item with certain index visible. - /// - /// Item index - /// True to scroll smoothly, othewise immdediately. - public void ScrollToView(int index, bool ani) - { - ScrollToView(index, ani, false); - } - - /// - /// Scroll the list to make an item with certain index visible. - /// - /// Item index - /// True to scroll smoothly, othewise immdediately. - /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. - public void ScrollToView(int index, bool ani, bool setFirst) - { - if (_virtual) - { - if (_numItems == 0) - return; - - CheckVirtualList(); - - if (index >= _virtualItems.Count) - throw new Exception("Invalid child index: " + index + ">" + _virtualItems.Count); - - if (_loop) - index = Mathf.FloorToInt((float)_firstIndex / _numItems) * _numItems + index; - - Rect rect; - ItemInfo ii = _virtualItems[index]; - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - { - float pos = 0; - for (int i = _curLineItemCount - 1; i < index; i += _curLineItemCount) - pos += _virtualItems[i].size.y + _lineGap; - rect = new Rect(0, pos, _itemSize.x, ii.size.y); - } - else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) - { - float pos = 0; - for (int i = _curLineItemCount - 1; i < index; i += _curLineItemCount) - pos += _virtualItems[i].size.x + _columnGap; - rect = new Rect(pos, 0, ii.size.x, _itemSize.y); - } - else - { - int page = index / (_curLineItemCount * _curLineItemCount2); - rect = new Rect(page * viewWidth + (index % _curLineItemCount) * (ii.size.x + _columnGap), - (index / _curLineItemCount) % _curLineItemCount2 * (ii.size.y + _lineGap), - ii.size.x, ii.size.y); - } - - if (this.scrollPane != null) - scrollPane.ScrollToView(rect, ani, setFirst); - else if (parent != null && parent.scrollPane != null) - parent.scrollPane.ScrollToView(this.TransformRect(rect, parent), ani, setFirst); - } - else - { - GObject obj = GetChildAt(index); - if (this.scrollPane != null) - scrollPane.ScrollToView(obj, ani, setFirst); - else if (parent != null && parent.scrollPane != null) - parent.scrollPane.ScrollToView(obj, ani, setFirst); - } - } - - /// - /// 获取当前点击哪个item - /// - public GObject touchItem - { - get - { - //find out which item is under finger - //逐层往上知道查到点击了那个item - GObject obj = GRoot.inst.touchTarget; - GObject p = obj.parent; - while (p != null) - { - if (p == this) - return obj; - - obj = p; - p = p.parent; - } - - return null; - } - } - - /// - /// Get first child in view. - /// - /// - public override int GetFirstChildInView() - { - return ChildIndexToItemIndex(base.GetFirstChildInView()); - } - - public int ChildIndexToItemIndex(int index) - { - if (!_virtual) - return index; - - if (_layout == ListLayoutType.Pagination) - { - for (int i = _firstIndex; i < _realNumItems; i++) - { - if (_virtualItems[i].obj != null) - { - index--; - if (index < 0) - return i; - } - } - - return index; - } - else - { - index += _firstIndex; - if (_loop && _numItems > 0) - index = index % _numItems; - - return index; - } - } - - public int ItemIndexToChildIndex(int index) - { - if (!_virtual) - return index; - - if (_layout == ListLayoutType.Pagination) - { - return GetChildIndex(_virtualItems[index].obj); - } - else - { - if (_loop && _numItems > 0) - { - int j = _firstIndex % _numItems; - if (index >= j) - index = index - j; - else - index = _numItems - j + index; - } - else - index -= _firstIndex; - - return index; - } - } - - - /// - /// Set the list to be virtual list. - /// 设置列表为虚拟列表模式。在虚拟列表模式下,列表不会为每一条列表数据创建一个实体对象,而是根据视口大小创建最小量的显示对象,然后通过itemRenderer指定的回调函数设置列表数据。 - /// 在虚拟模式下,你不能通过AddChild、RemoveChild等方式管理列表,只能通过设置numItems设置列表数据的长度。 - /// 如果要刷新列表,可以通过重新设置numItems,或者调用RefreshVirtualList完成。 - /// ‘单行’或者‘单列’的列表布局可支持不等高的列表项目。 - /// 除了‘页面’的列表布局,其他布局均支持使用不同资源构建列表项目,你可以在itemProvider里返回。如果不提供,默认使用defaultItem。 - /// - public void SetVirtual() - { - SetVirtual(false); - } - - public bool isVirtual - { - get { return _virtual; } - } - - /// - /// Set the list to be virtual list, and has loop behavior. - /// - public void SetVirtualAndLoop() - { - SetVirtual(true); - } - - void SetVirtual(bool loop) - { - if (!_virtual) - { - if (this.scrollPane == null) - Debug.LogError("FairyGUI: Virtual list must be scrollable!"); - - if (loop) - { - if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.FlowVertical) - Debug.LogError("FairyGUI: Loop list is not supported for FlowHorizontal or FlowVertical layout!"); - - this.scrollPane.bouncebackEffect = false; - } - - _virtual = true; - _loop = loop; - _virtualItems = new List(); - RemoveChildrenToPool(); - - if (_itemSize.x == 0 || _itemSize.y == 0) - { - GObject obj = GetFromPool(null); - if (obj == null) - { - Debug.LogError("FairyGUI: Virtual List must have a default list item resource."); - _itemSize = new Vector2(100, 100); - } - else - { - _itemSize = obj.size; - _itemSize.x = Mathf.CeilToInt(_itemSize.x); - _itemSize.y = Mathf.CeilToInt(_itemSize.y); - ReturnToPool(obj); - } - } - - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - { - this.scrollPane.scrollStep = _itemSize.y; - if (_loop) - this.scrollPane._loop = 2; - } - else - { - this.scrollPane.scrollStep = _itemSize.x; - if (_loop) - this.scrollPane._loop = 1; - } - - this.scrollPane.onScroll.AddCapture(__scrolled); - SetVirtualListChangedFlag(true); - } - } - - /// - /// Set the list item count. - /// If the list is not virtual, specified number of items will be created. - /// If the list is virtual, only items in view will be created. - /// - public int numItems - { - get - { - if (_virtual) - return _numItems; - else - return _children.Count; - } - set - { - if (_virtual) - { - if (itemRenderer == null) - throw new Exception("FairyGUI: Set itemRenderer first!"); - - _numItems = value; - if (_loop) - _realNumItems = _numItems * 6;//设置6倍数量,用于循环滚动 - else - _realNumItems = _numItems; - - //_virtualItems的设计是只增不减的 - int oldCount = _virtualItems.Count; - if (_realNumItems > oldCount) - { - for (int i = oldCount; i < _realNumItems; i++) - { - ItemInfo ii = new ItemInfo(); - ii.size = _itemSize; - - _virtualItems.Add(ii); - } - } - else - { - for (int i = _realNumItems; i < oldCount; i++) - _virtualItems[i].selected = false; - } - - if (_virtualListChanged != 0) - Timers.inst.Remove(this.RefreshVirtualList); - //立即刷新 - this.RefreshVirtualList(null); - } - else - { - int cnt = _children.Count; - if (value > cnt) - { - for (int i = cnt; i < value; i++) - { - if (itemProvider == null) - AddItemFromPool(); - else - AddItemFromPool(itemProvider(i)); - } - } - else - { - RemoveChildrenToPool(value, cnt); - } - - if (itemRenderer != null) - { - for (int i = 0; i < value; i++) - itemRenderer(i, GetChildAt(i)); - } - } - } - } - - public void RefreshVirtualList() - { - if (!_virtual) - throw new Exception("FairyGUI: not virtual list"); - - SetVirtualListChangedFlag(false); - } - - void CheckVirtualList() - { - if (_virtualListChanged != 0) - { - this.RefreshVirtualList(null); - Timers.inst.Remove(this.RefreshVirtualList); - } - } - - void SetVirtualListChangedFlag(bool layoutChanged) - { - if (layoutChanged) - _virtualListChanged = 2; - else if (_virtualListChanged == 0) - _virtualListChanged = 1; - - Timers.inst.CallLater(RefreshVirtualList); - } - - void RefreshVirtualList(object param) - { - bool layoutChanged = _virtualListChanged == 2; - _virtualListChanged = 0; - _miscFlags |= 1; - - if (layoutChanged) - { - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.SingleRow) - _curLineItemCount = 1; - else if (_layout == ListLayoutType.FlowHorizontal) - { - if (_columnCount > 0) - _curLineItemCount = _columnCount; - else - { - _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); - if (_curLineItemCount <= 0) - _curLineItemCount = 1; - } - } - else if (_layout == ListLayoutType.FlowVertical) - { - if (_lineCount > 0) - _curLineItemCount = _lineCount; - else - { - _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); - if (_curLineItemCount <= 0) - _curLineItemCount = 1; - } - } - else //pagination - { - if (_columnCount > 0) - _curLineItemCount = _columnCount; - else - { - _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); - if (_curLineItemCount <= 0) - _curLineItemCount = 1; - } - - if (_lineCount > 0) - _curLineItemCount2 = _lineCount; - else - { - _curLineItemCount2 = Mathf.FloorToInt((this.scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); - if (_curLineItemCount2 <= 0) - _curLineItemCount2 = 1; - } - } - } - - float ch = 0, cw = 0; - if (_realNumItems > 0) - { - int len = Mathf.CeilToInt((float)_realNumItems / _curLineItemCount) * _curLineItemCount; - int len2 = Math.Min(_curLineItemCount, _realNumItems); - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - { - for (int i = 0; i < len; i += _curLineItemCount) - ch += _virtualItems[i].size.y + _lineGap; - if (ch > 0) - ch -= _lineGap; - - if (_autoResizeItem) - cw = scrollPane.viewWidth; - else - { - for (int i = 0; i < len2; i++) - cw += _virtualItems[i].size.x + _columnGap; - if (cw > 0) - cw -= _columnGap; - } - } - else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) - { - for (int i = 0; i < len; i += _curLineItemCount) - cw += _virtualItems[i].size.x + _columnGap; - if (cw > 0) - cw -= _columnGap; - - if (_autoResizeItem) - ch = this.scrollPane.viewHeight; - else - { - for (int i = 0; i < len2; i++) - ch += _virtualItems[i].size.y + _lineGap; - if (ch > 0) - ch -= _lineGap; - } - } - else - { - int pageCount = Mathf.CeilToInt((float)len / (_curLineItemCount * _curLineItemCount2)); - cw = pageCount * viewWidth; - ch = viewHeight; - } - } - - HandleAlign(cw, ch); - this.scrollPane.SetContentSize(cw, ch); - - _miscFlags &= 0xFE; - - HandleScroll(true); - } - - void __scrolled(EventContext context) - { - HandleScroll(false); - } - - int GetIndexOnPos1(ref float pos, bool forceUpdate) - { - if (_realNumItems < _curLineItemCount) - { - pos = 0; - return 0; - } - - if (numChildren > 0 && !forceUpdate) - { - float pos2 = this.GetChildAt(0).y; - if (pos2 + (_lineGap > 0 ? 0 : -_lineGap) > pos) - { - for (int i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) - { - pos2 -= (_virtualItems[i].size.y + _lineGap); - if (pos2 <= pos) - { - pos = pos2; - return i; - } - } - - pos = 0; - return 0; - } - else - { - float testGap = _lineGap > 0 ? _lineGap : 0; - for (int i = _firstIndex; i < _realNumItems; i += _curLineItemCount) - { - float pos3 = pos2 + _virtualItems[i].size.y; - if (pos3 + testGap > pos) - { - pos = pos2; - return i; - } - pos2 = pos3 + _lineGap; - } - - pos = pos2; - return _realNumItems - _curLineItemCount; - } - } - else - { - float pos2 = 0; - float testGap = _lineGap > 0 ? _lineGap : 0; - for (int i = 0; i < _realNumItems; i += _curLineItemCount) - { - float pos3 = pos2 + _virtualItems[i].size.y; - if (pos3 + testGap > pos) - { - pos = pos2; - return i; - } - pos2 = pos3 + _lineGap; - } - - pos = pos2; - return _realNumItems - _curLineItemCount; - } - } - - int GetIndexOnPos2(ref float pos, bool forceUpdate) - { - if (_realNumItems < _curLineItemCount) - { - pos = 0; - return 0; - } - - if (numChildren > 0 && !forceUpdate) - { - float pos2 = this.GetChildAt(0).x; - if (pos2 + (_columnGap > 0 ? 0 : -_columnGap) > pos) - { - for (int i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) - { - pos2 -= (_virtualItems[i].size.x + _columnGap); - if (pos2 <= pos) - { - pos = pos2; - return i; - } - } - - pos = 0; - return 0; - } - else - { - float testGap = _columnGap > 0 ? _columnGap : 0; - for (int i = _firstIndex; i < _realNumItems; i += _curLineItemCount) - { - float pos3 = pos2 + _virtualItems[i].size.x; - if (pos3 + testGap > pos) - { - pos = pos2; - return i; - } - pos2 = pos3 + _columnGap; - } - - pos = pos2; - return _realNumItems - _curLineItemCount; - } - } - else - { - float pos2 = 0; - float testGap = _columnGap > 0 ? _columnGap : 0; - for (int i = 0; i < _realNumItems; i += _curLineItemCount) - { - float pos3 = pos2 + _virtualItems[i].size.x; - if (pos3 + testGap > pos) - { - pos = pos2; - return i; - } - pos2 = pos3 + _columnGap; - } - - pos = pos2; - return _realNumItems - _curLineItemCount; - } - } - - int GetIndexOnPos3(ref float pos, bool forceUpdate) - { - if (_realNumItems < _curLineItemCount) - { - pos = 0; - return 0; - } - - float viewWidth = this.viewWidth; - int page = Mathf.FloorToInt(pos / viewWidth); - int startIndex = page * (_curLineItemCount * _curLineItemCount2); - float pos2 = page * viewWidth; - float testGap = _columnGap > 0 ? _columnGap : 0; - for (int i = 0; i < _curLineItemCount; i++) - { - float pos3 = pos2 + _virtualItems[startIndex + i].size.x; - if (pos3 + testGap > pos) - { - pos = pos2; - return startIndex + i; - } - pos2 = pos3 + _columnGap; - } - - pos = pos2; - return startIndex + _curLineItemCount - 1; - } - - void HandleScroll(bool forceUpdate) - { - if ((_miscFlags & 1) != 0) - return; - - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - { - int enterCounter = 0; - while (HandleScroll1(forceUpdate)) - { - //可能会因为ITEM资源改变导致ITEM大小发生改变,所有出现最后一页填不满的情况,这时要反复尝试填满。 - enterCounter++; - forceUpdate = false; - if (enterCounter > 20) - { - Debug.Log("FairyGUI: list will never be filled as the item renderer function always returns a different size."); - break; - } - } - - HandleArchOrder1(); - } - else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) - { - int enterCounter = 0; - while (HandleScroll2(forceUpdate)) - { - enterCounter++; - forceUpdate = false; - if (enterCounter > 20) - { - Debug.Log("FairyGUI: list will never be filled as the item renderer function always returns a different size."); - break; - } - } - - HandleArchOrder2(); - } - else - { - HandleScroll3(forceUpdate); - } - - _boundsChanged = false; - } - - bool HandleScroll1(bool forceUpdate) - { - float pos = scrollPane.scrollingPosY; - float max = pos + scrollPane.viewHeight; - bool end = max == scrollPane.contentHeight;//这个标志表示当前需要滚动到最末,无论内容变化大小 - - //寻找当前位置的第一条项目 - int newFirstIndex = GetIndexOnPos1(ref pos, forceUpdate); - if (newFirstIndex == _firstIndex && !forceUpdate) - return false; - - int oldFirstIndex = _firstIndex; - _firstIndex = newFirstIndex; - int curIndex = newFirstIndex; - bool forward = oldFirstIndex > newFirstIndex; - int childCount = this.numChildren; - int lastIndex = oldFirstIndex + childCount - 1; - int reuseIndex = forward ? lastIndex : oldFirstIndex; - float curX = 0, curY = pos; - bool needRender; - float deltaSize = 0; - float firstItemDeltaSize = 0; - string url = _defaultItem; - int partSize = (int)((scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount); - - itemInfoVer++; - while (curIndex < _realNumItems && (end || curY < max)) - { - ItemInfo ii = _virtualItems[curIndex]; - - if (ii.obj == null || forceUpdate) - { - if (itemProvider != null) - { - url = itemProvider(curIndex % _numItems); - if (url == null) - url = _defaultItem; - url = UIPackage.NormalizeURL(url); - } - - if (ii.obj != null && ii.obj.resourceURL != url) - { - if (ii.obj is GButton) - ii.selected = ((GButton)ii.obj).selected; - RemoveChildToPool(ii.obj); - ii.obj = null; - } - } - - if (ii.obj == null) - { - //搜索最适合的重用item,保证每次刷新需要新建或者重新render的item最少 - if (forward) - { - for (int j = reuseIndex; j >= oldFirstIndex; j--) - { - ItemInfo ii2 = _virtualItems[j]; - if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) - { - if (ii2.obj is GButton) - ii2.selected = ((GButton)ii2.obj).selected; - ii.obj = ii2.obj; - ii2.obj = null; - if (j == reuseIndex) - reuseIndex--; - break; - } - } - } - else - { - for (int j = reuseIndex; j <= lastIndex; j++) - { - ItemInfo ii2 = _virtualItems[j]; - if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) - { - if (ii2.obj is GButton) - ii2.selected = ((GButton)ii2.obj).selected; - ii.obj = ii2.obj; - ii2.obj = null; - if (j == reuseIndex) - reuseIndex++; - break; - } - } - } - - if (ii.obj != null) - { - SetChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); - } - else - { - ii.obj = _pool.GetObject(url); - if (forward) - this.AddChildAt(ii.obj, curIndex - newFirstIndex); - else - this.AddChild(ii.obj); - } - if (ii.obj is GButton) - ((GButton)ii.obj).selected = ii.selected; - - needRender = true; - } - else - needRender = forceUpdate; - - if (needRender) - { - if (_autoResizeItem && (_layout == ListLayoutType.SingleColumn || _columnCount > 0)) - ii.obj.SetSize(partSize, ii.obj.height, true); - - itemRenderer(curIndex % _numItems, ii.obj); - if (curIndex % _curLineItemCount == 0) - { - deltaSize += Mathf.CeilToInt(ii.obj.size.y) - ii.size.y; - if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) - { - //当内容向下滚动时,如果新出现的项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 - firstItemDeltaSize = Mathf.CeilToInt(ii.obj.size.y) - ii.size.y; - } - } - ii.size.x = Mathf.CeilToInt(ii.obj.size.x); - ii.size.y = Mathf.CeilToInt(ii.obj.size.y); - } - - ii.updateFlag = itemInfoVer; - ii.obj.SetXY(curX, curY); - if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 - max += ii.size.y; - - curX += ii.size.x + _columnGap; - - if (curIndex % _curLineItemCount == _curLineItemCount - 1) - { - curX = 0; - curY += ii.size.y + _lineGap; - } - curIndex++; - } - - for (int i = 0; i < childCount; i++) - { - ItemInfo ii = _virtualItems[oldFirstIndex + i]; - if (ii.updateFlag != itemInfoVer && ii.obj != null) - { - if (ii.obj is GButton) - ii.selected = ((GButton)ii.obj).selected; - RemoveChildToPool(ii.obj); - ii.obj = null; - } - } - - childCount = _children.Count; - for (int i = 0; i < childCount; i++) - { - GObject obj = _virtualItems[newFirstIndex + i].obj; - if (_children[i] != obj) - SetChildIndex(obj, i); - } - - if (deltaSize != 0 || firstItemDeltaSize != 0) - this.scrollPane.ChangeContentSizeOnScrolling(0, deltaSize, 0, firstItemDeltaSize); - - if (curIndex > 0 && this.numChildren > 0 && this.container.y <= 0 && GetChildAt(0).y > -this.container.y)//最后一页没填满! - return true; - else - return false; - } - - bool HandleScroll2(bool forceUpdate) - { - float pos = scrollPane.scrollingPosX; - float max = pos + scrollPane.viewWidth; - bool end = pos == scrollPane.contentWidth;//这个标志表示当前需要滚动到最末,无论内容变化大小 - - //寻找当前位置的第一条项目 - int newFirstIndex = GetIndexOnPos2(ref pos, forceUpdate); - if (newFirstIndex == _firstIndex && !forceUpdate) - return false; - - int oldFirstIndex = _firstIndex; - _firstIndex = newFirstIndex; - int curIndex = newFirstIndex; - bool forward = oldFirstIndex > newFirstIndex; - int childCount = this.numChildren; - int lastIndex = oldFirstIndex + childCount - 1; - int reuseIndex = forward ? lastIndex : oldFirstIndex; - float curX = pos, curY = 0; - bool needRender; - float deltaSize = 0; - float firstItemDeltaSize = 0; - string url = _defaultItem; - int partSize = (int)((scrollPane.viewHeight - _lineGap * (_curLineItemCount - 1)) / _curLineItemCount); - - itemInfoVer++; - while (curIndex < _realNumItems && (end || curX < max)) - { - ItemInfo ii = _virtualItems[curIndex]; - - if (ii.obj == null || forceUpdate) - { - if (itemProvider != null) - { - url = itemProvider(curIndex % _numItems); - if (url == null) - url = _defaultItem; - url = UIPackage.NormalizeURL(url); - } - - if (ii.obj != null && ii.obj.resourceURL != url) - { - if (ii.obj is GButton) - ii.selected = ((GButton)ii.obj).selected; - RemoveChildToPool(ii.obj); - ii.obj = null; - } - } - - if (ii.obj == null) - { - if (forward) - { - for (int j = reuseIndex; j >= oldFirstIndex; j--) - { - ItemInfo ii2 = _virtualItems[j]; - if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) - { - if (ii2.obj is GButton) - ii2.selected = ((GButton)ii2.obj).selected; - ii.obj = ii2.obj; - ii2.obj = null; - if (j == reuseIndex) - reuseIndex--; - break; - } - } - } - else - { - for (int j = reuseIndex; j <= lastIndex; j++) - { - ItemInfo ii2 = _virtualItems[j]; - if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) - { - if (ii2.obj is GButton) - ii2.selected = ((GButton)ii2.obj).selected; - ii.obj = ii2.obj; - ii2.obj = null; - if (j == reuseIndex) - reuseIndex++; - break; - } - } - } - - if (ii.obj != null) - { - SetChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); - } - else - { - ii.obj = _pool.GetObject(url); - if (forward) - this.AddChildAt(ii.obj, curIndex - newFirstIndex); - else - this.AddChild(ii.obj); - } - if (ii.obj is GButton) - ((GButton)ii.obj).selected = ii.selected; - - needRender = true; - } - else - needRender = forceUpdate; - - if (needRender) - { - if (_autoResizeItem && (_layout == ListLayoutType.SingleRow || _lineCount > 0)) - ii.obj.SetSize(ii.obj.width, partSize, true); - - itemRenderer(curIndex % _numItems, ii.obj); - if (curIndex % _curLineItemCount == 0) - { - deltaSize += Mathf.CeilToInt(ii.obj.size.x) - ii.size.x; - if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) - { - //当内容向下滚动时,如果新出现的一个项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 - firstItemDeltaSize = Mathf.CeilToInt(ii.obj.size.x) - ii.size.x; - } - } - ii.size.x = Mathf.CeilToInt(ii.obj.size.x); - ii.size.y = Mathf.CeilToInt(ii.obj.size.y); - } - - ii.updateFlag = itemInfoVer; - ii.obj.SetXY(curX, curY); - if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 - max += ii.size.x; - - curY += ii.size.y + _lineGap; - - if (curIndex % _curLineItemCount == _curLineItemCount - 1) - { - curY = 0; - curX += ii.size.x + _columnGap; - } - curIndex++; - } - - for (int i = 0; i < childCount; i++) - { - ItemInfo ii = _virtualItems[oldFirstIndex + i]; - if (ii.updateFlag != itemInfoVer && ii.obj != null) - { - if (ii.obj is GButton) - ii.selected = ((GButton)ii.obj).selected; - RemoveChildToPool(ii.obj); - ii.obj = null; - } - } - - childCount = _children.Count; - for (int i = 0; i < childCount; i++) - { - GObject obj = _virtualItems[newFirstIndex + i].obj; - if (_children[i] != obj) - SetChildIndex(obj, i); - } - - if (deltaSize != 0 || firstItemDeltaSize != 0) - this.scrollPane.ChangeContentSizeOnScrolling(deltaSize, 0, firstItemDeltaSize, 0); - - if (curIndex > 0 && this.numChildren > 0 && this.container.x <= 0 && GetChildAt(0).x > -this.container.x)//最后一页没填满! - return true; - else - return false; - } - - void HandleScroll3(bool forceUpdate) - { - float pos = scrollPane.scrollingPosX; - - //寻找当前位置的第一条项目 - int newFirstIndex = GetIndexOnPos3(ref pos, forceUpdate); - if (newFirstIndex == _firstIndex && !forceUpdate) - return; - - int oldFirstIndex = _firstIndex; - _firstIndex = newFirstIndex; - - //分页模式不支持不等高,所以渲染满一页就好了 - - int reuseIndex = oldFirstIndex; - int virtualItemCount = _virtualItems.Count; - int pageSize = _curLineItemCount * _curLineItemCount2; - int startCol = newFirstIndex % _curLineItemCount; - float viewWidth = this.viewWidth; - int page = (int)(newFirstIndex / pageSize); - int startIndex = page * pageSize; - int lastIndex = startIndex + pageSize * 2; //测试两页 - bool needRender; - string url = _defaultItem; - int partWidth = (int)((scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount); - int partHeight = (int)((scrollPane.viewHeight - _lineGap * (_curLineItemCount2 - 1)) / _curLineItemCount2); - itemInfoVer++; - - //先标记这次要用到的项目 - for (int i = startIndex; i < lastIndex; i++) - { - if (i >= _realNumItems) - continue; - - int col = i % _curLineItemCount; - if (i - startIndex < pageSize) - { - if (col < startCol) - continue; - } - else - { - if (col > startCol) - continue; - } - - ItemInfo ii = _virtualItems[i]; - ii.updateFlag = itemInfoVer; - } - - GObject lastObj = null; - int insertIndex = 0; - for (int i = startIndex; i < lastIndex; i++) - { - if (i >= _realNumItems) - continue; - - ItemInfo ii = _virtualItems[i]; - if (ii.updateFlag != itemInfoVer) - continue; - - if (ii.obj == null) - { - //寻找看有没有可重用的 - while (reuseIndex < virtualItemCount) - { - ItemInfo ii2 = _virtualItems[reuseIndex]; - if (ii2.obj != null && ii2.updateFlag != itemInfoVer) - { - if (ii2.obj is GButton) - ii2.selected = ((GButton)ii2.obj).selected; - ii.obj = ii2.obj; - ii2.obj = null; - break; - } - reuseIndex++; - } - - if (insertIndex == -1) - insertIndex = GetChildIndex(lastObj) + 1; - - if (ii.obj == null) - { - if (itemProvider != null) - { - url = itemProvider(i % _numItems); - if (url == null) - url = _defaultItem; - url = UIPackage.NormalizeURL(url); - } - - ii.obj = _pool.GetObject(url); - this.AddChildAt(ii.obj, insertIndex); - } - else - { - insertIndex = SetChildIndexBefore(ii.obj, insertIndex); - } - insertIndex++; - - if (ii.obj is GButton) - ((GButton)ii.obj).selected = ii.selected; - - needRender = true; - } - else - { - needRender = forceUpdate; - insertIndex = -1; - lastObj = ii.obj; - } - - if (needRender) - { - if (_autoResizeItem) - { - if (_curLineItemCount == _columnCount && _curLineItemCount2 == _lineCount) - ii.obj.SetSize(partWidth, partHeight, true); - else if (_curLineItemCount == _columnCount) - ii.obj.SetSize(partWidth, ii.obj.height, true); - else if (_curLineItemCount2 == _lineCount) - ii.obj.SetSize(ii.obj.width, partHeight, true); - } - - itemRenderer(i % _numItems, ii.obj); - ii.size.x = Mathf.CeilToInt(ii.obj.size.x); - ii.size.y = Mathf.CeilToInt(ii.obj.size.y); - } - } - - //排列item - float borderX = (startIndex / pageSize) * viewWidth; - float xx = borderX; - float yy = 0; - float lineHeight = 0; - for (int i = startIndex; i < lastIndex; i++) - { - if (i >= _realNumItems) - continue; - - ItemInfo ii = _virtualItems[i]; - if (ii.updateFlag == itemInfoVer) - ii.obj.SetXY(xx, yy); - - if (ii.size.y > lineHeight) - lineHeight = ii.size.y; - if (i % _curLineItemCount == _curLineItemCount - 1) - { - xx = borderX; - yy += lineHeight + _lineGap; - lineHeight = 0; - - if (i == startIndex + pageSize - 1) - { - borderX += viewWidth; - xx = borderX; - yy = 0; - } - } - else - xx += ii.size.x + _columnGap; - } - - //释放未使用的 - for (int i = reuseIndex; i < virtualItemCount; i++) - { - ItemInfo ii = _virtualItems[i]; - if (ii.updateFlag != itemInfoVer && ii.obj != null) - { - if (ii.obj is GButton) - ii.selected = ((GButton)ii.obj).selected; - RemoveChildToPool(ii.obj); - ii.obj = null; - } - } - } - - void HandleArchOrder1() - { - if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) - { - float mid = this.scrollPane.posY + this.viewHeight / 2; - float minDist = int.MaxValue, dist; - int apexIndex = 0; - int cnt = this.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = GetChildAt(i); - if (!foldInvisibleItems || obj.visible) - { - dist = Mathf.Abs(mid - obj.y - obj.height / 2); - if (dist < minDist) - { - minDist = dist; - apexIndex = i; - } - } - } - this.apexIndex = apexIndex; - } - } - - void HandleArchOrder2() - { - if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) - { - float mid = this.scrollPane.posX + this.viewWidth / 2; - float minDist = int.MaxValue, dist; - int apexIndex = 0; - int cnt = this.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = GetChildAt(i); - if (!foldInvisibleItems || obj.visible) - { - dist = Mathf.Abs(mid - obj.x - obj.width / 2); - if (dist < minDist) - { - minDist = dist; - apexIndex = i; - } - } - } - this.apexIndex = apexIndex; - } - } - - override public void GetSnappingPositionWithDir(ref float xValue, ref float yValue, float xDir, float yDir) - { - if (_virtual) - { - if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) - { - float saved = yValue; - int index = GetIndexOnPos1(ref yValue, false); - if (index < _virtualItems.Count && index < _realNumItems) - { - float size = _virtualItems[index].size.y; - if (ShouldSnapToNext(yDir, saved - yValue, size)) - yValue += size + _lineGap; - } - } - else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) - { - float saved = xValue; - int index = GetIndexOnPos2(ref xValue, false); - if (index < _virtualItems.Count && index < _realNumItems) - { - float size = _virtualItems[index].size.x; - if (ShouldSnapToNext(xDir, saved - xValue, size)) - xValue += size + _columnGap; - } - } - else - { - float saved = xValue; - int index = GetIndexOnPos3(ref xValue, false); - if (index < _virtualItems.Count && index < _realNumItems) - { - float size = _virtualItems[index].size.x; - if (ShouldSnapToNext(xDir, saved - xValue, size)) - xValue += size + _columnGap; - } - } - } - else - base.GetSnappingPositionWithDir(ref xValue, ref yValue, xDir, yDir); - } - - private void HandleAlign(float contentWidth, float contentHeight) - { - Vector2 newOffset = Vector2.zero; - - if (contentHeight < viewHeight) - { - if (_verticalAlign == VertAlignType.Middle) - newOffset.y = (int)((viewHeight - contentHeight) / 2); - else if (_verticalAlign == VertAlignType.Bottom) - newOffset.y = viewHeight - contentHeight; - } - - if (contentWidth < this.viewWidth) - { - if (_align == AlignType.Center) - newOffset.x = (int)((viewWidth - contentWidth) / 2); - else if (_align == AlignType.Right) - newOffset.x = viewWidth - contentWidth; - } - - if (newOffset != _alignOffset) - { - _alignOffset = newOffset; - if (scrollPane != null) - scrollPane.AdjustMaskContainer(); - else - container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); - } - } - - override protected void UpdateBounds() - { - if (_virtual) - return; - - int cnt = _children.Count; - int i; - int j = 0; - GObject child; - float curX = 0; - float curY = 0; - float cw, ch; - float maxWidth = 0; - float maxHeight = 0; - float viewWidth = this.viewWidth; - float viewHeight = this.viewHeight; - - if (_layout == ListLayoutType.SingleColumn) - { - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - if (curY != 0) - curY += _lineGap; - child.y = curY; - if (_autoResizeItem) - child.SetSize(viewWidth, child.height, true); - curY += Mathf.CeilToInt(child.height); - if (child.width > maxWidth) - maxWidth = child.width; - } - - ch = curY; - if (ch <= viewHeight && _autoResizeItem && scrollPane != null && scrollPane._displayInDemand && scrollPane.vtScrollBar != null) - { - viewWidth += scrollPane.vtScrollBar.width; - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - child.SetSize(viewWidth, child.height, true); - } - } - cw = Mathf.CeilToInt(maxWidth); - } - else if (_layout == ListLayoutType.SingleRow) - { - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - if (curX != 0) - curX += _columnGap; - child.x = curX; - if (_autoResizeItem) - child.SetSize(child.width, viewHeight, true); - curX += Mathf.CeilToInt(child.width); - if (child.height > maxHeight) - maxHeight = child.height; - } - - cw = curX; - if (cw <= viewWidth && _autoResizeItem && scrollPane != null && scrollPane._displayInDemand && scrollPane.hzScrollBar != null) - { - viewHeight += scrollPane.hzScrollBar.height; - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - child.SetSize(child.width, viewHeight, true); - } - } - ch = Mathf.CeilToInt(maxHeight); - } - else if (_layout == ListLayoutType.FlowHorizontal) - { - if (_autoResizeItem && _columnCount > 0) - { - float lineSize = 0; - int lineStart = 0; - float remainSize; - float remainPercent; - - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - lineSize += child.sourceWidth; - j++; - if (j == _columnCount || i == cnt - 1) - { - remainSize = viewWidth - (j - 1) * _columnGap; - remainPercent = 1; - curX = 0; - for (j = lineStart; j <= i; j++) - { - child = GetChildAt(j); - if (foldInvisibleItems && !child.visible) - continue; - - child.SetXY(curX, curY); - float perc = child.sourceWidth / lineSize; - child.SetSize(Mathf.Round(perc / remainPercent * remainSize), child.height, true); - remainSize -= child.width; - remainPercent -= perc; - curX += child.width + _columnGap; - - if (child.height > maxHeight) - maxHeight = child.height; - } - //new line - curY += Mathf.CeilToInt(maxHeight) + _lineGap; - maxHeight = 0; - j = 0; - lineStart = i + 1; - lineSize = 0; - } - } - ch = curY + Mathf.CeilToInt(maxHeight); - cw = viewWidth; - } - else - { - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - if (curX != 0) - curX += _columnGap; - - if (_columnCount != 0 && j >= _columnCount - || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) - { - //new line - curX = 0; - curY += Mathf.CeilToInt(maxHeight) + _lineGap; - maxHeight = 0; - j = 0; - } - child.SetXY(curX, curY); - curX += Mathf.CeilToInt(child.width); - if (curX > maxWidth) - maxWidth = curX; - if (child.height > maxHeight) - maxHeight = child.height; - j++; - } - ch = curY + Mathf.CeilToInt(maxHeight); - cw = Mathf.CeilToInt(maxWidth); - } - } - else if (_layout == ListLayoutType.FlowVertical) - { - if (_autoResizeItem && _lineCount > 0) - { - float lineSize = 0; - int lineStart = 0; - float remainSize; - float remainPercent; - - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - lineSize += child.sourceHeight; - j++; - if (j == _lineCount || i == cnt - 1) - { - remainSize = viewHeight - (j - 1) * _lineGap; - remainPercent = 1; - curY = 0; - for (j = lineStart; j <= i; j++) - { - child = GetChildAt(j); - if (foldInvisibleItems && !child.visible) - continue; - - child.SetXY(curX, curY); - float perc = child.sourceHeight / lineSize; - child.SetSize(child.width, Mathf.Round(perc / remainPercent * remainSize), true); - remainSize -= child.height; - remainPercent -= perc; - curY += child.height + _lineGap; - - if (child.width > maxWidth) - maxWidth = child.width; - } - //new line - curX += Mathf.CeilToInt(maxWidth) + _columnGap; - maxWidth = 0; - j = 0; - lineStart = i + 1; - lineSize = 0; - } - } - cw = curX + Mathf.CeilToInt(maxWidth); - ch = viewHeight; - } - else - { - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - if (curY != 0) - curY += _lineGap; - - if (_lineCount != 0 && j >= _lineCount - || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0) - { - curY = 0; - curX += Mathf.CeilToInt(maxWidth) + _columnGap; - maxWidth = 0; - j = 0; - } - child.SetXY(curX, curY); - curY += child.height; - if (curY > maxHeight) - maxHeight = curY; - if (child.width > maxWidth) - maxWidth = child.width; - j++; - } - cw = curX + Mathf.CeilToInt(maxWidth); - ch = Mathf.CeilToInt(maxHeight); - } - } - else //pagination - { - int page = 0; - int k = 0; - float eachHeight = 0; - if (_autoResizeItem && _lineCount > 0) - eachHeight = Mathf.Floor((viewHeight - (_lineCount - 1) * _lineGap) / _lineCount); - - if (_autoResizeItem && _columnCount > 0) - { - float lineSize = 0; - int lineStart = 0; - float remainSize; - float remainPercent; - - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - if (j == 0 && (_lineCount != 0 && k >= _lineCount - || _lineCount == 0 && curY + (_lineCount > 0 ? eachHeight : child.height) > viewHeight)) - { - //new page - page++; - curY = 0; - k = 0; - } - - lineSize += child.sourceWidth; - j++; - if (j == _columnCount || i == cnt - 1) - { - remainSize = viewWidth - (j - 1) * _columnGap; - remainPercent = 1; - curX = 0; - for (j = lineStart; j <= i; j++) - { - child = GetChildAt(j); - if (foldInvisibleItems && !child.visible) - continue; - - child.SetXY(page * viewWidth + curX, curY); - float perc = child.sourceWidth / lineSize; - child.SetSize(Mathf.Round(perc / remainPercent * remainSize), _lineCount > 0 ? eachHeight : child.height, true); - remainSize -= child.width; - remainPercent -= perc; - curX += child.width + _columnGap; - - if (child.height > maxHeight) - maxHeight = child.height; - } - //new line - curY += Mathf.CeilToInt(maxHeight) + _lineGap; - maxHeight = 0; - j = 0; - lineStart = i + 1; - lineSize = 0; - - k++; - } - } - } - else - { - for (i = 0; i < cnt; i++) - { - child = GetChildAt(i); - if (foldInvisibleItems && !child.visible) - continue; - - if (curX != 0) - curX += _columnGap; - - if (_autoResizeItem && _lineCount > 0) - child.SetSize(child.width, eachHeight, true); - - if (_columnCount != 0 && j >= _columnCount - || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) - { - curX = 0; - curY += maxHeight + _lineGap; - maxHeight = 0; - j = 0; - k++; - - if (_lineCount != 0 && k >= _lineCount - || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0)//new page - { - page++; - curY = 0; - k = 0; - } - } - child.SetXY(page * viewWidth + curX, curY); - curX += Mathf.CeilToInt(child.width); - if (curX > maxWidth) - maxWidth = curX; - if (child.height > maxHeight) - maxHeight = child.height; - j++; - } - } - ch = page > 0 ? viewHeight : (curY + Mathf.CeilToInt(maxHeight)); - cw = (page + 1) * viewWidth; - } - - HandleAlign(cw, ch); - SetBounds(0, 0, cw, ch); - - InvalidateBatchingState(true); - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - _layout = (ListLayoutType)buffer.ReadByte(); - selectionMode = (ListSelectionMode)buffer.ReadByte(); - _align = (AlignType)buffer.ReadByte(); - _verticalAlign = (VertAlignType)buffer.ReadByte(); - _lineGap = buffer.ReadShort(); - _columnGap = buffer.ReadShort(); - _lineCount = buffer.ReadShort(); - _columnCount = buffer.ReadShort(); - _autoResizeItem = buffer.ReadBool(); - _childrenRenderOrder = (ChildrenRenderOrder)buffer.ReadByte(); - _apexIndex = buffer.ReadShort(); - - if (buffer.ReadBool()) - { - _margin.top = buffer.ReadInt(); - _margin.bottom = buffer.ReadInt(); - _margin.left = buffer.ReadInt(); - _margin.right = buffer.ReadInt(); - } - - OverflowType overflow = (OverflowType)buffer.ReadByte(); - if (overflow == OverflowType.Scroll) - { - int savedPos = buffer.position; - buffer.Seek(beginPos, 7); - SetupScroll(buffer); - buffer.position = savedPos; - } - else - SetupOverflow(overflow); - - if (buffer.ReadBool()) - { - int i1 = buffer.ReadInt(); - int i2 = buffer.ReadInt(); - this.clipSoftness = new Vector2(i1, i2); - } - - if (buffer.version >= 2) - { - scrollItemToViewOnClick = buffer.ReadBool(); - foldInvisibleItems = buffer.ReadBool(); - } - - buffer.Seek(beginPos, 8); - - _defaultItem = buffer.ReadS(); - ReadItems(buffer); - } - - virtual protected void ReadItems(ByteBuffer buffer) - { - int itemCount = buffer.ReadShort(); - for (int i = 0; i < itemCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - string str = buffer.ReadS(); - if (str == null) - { - str = _defaultItem; - if (string.IsNullOrEmpty(str)) - { - buffer.position = nextPos; - continue; - } - } - - GObject obj = GetFromPool(str); - if (obj != null) - { - AddChild(obj); - SetupItem(buffer, obj); - } - - buffer.position = nextPos; - } - } - - protected void SetupItem(ByteBuffer buffer, GObject obj) - { - string str; - str = buffer.ReadS(); - if (str != null) - obj.text = str; - str = buffer.ReadS(); - if (str != null && (obj is GButton)) - (obj as GButton).selectedTitle = str; - str = buffer.ReadS(); - if (str != null) - obj.icon = str; - str = buffer.ReadS(); - if (str != null && (obj is GButton)) - (obj as GButton).selectedIcon = str; - str = buffer.ReadS(); - if (str != null) - obj.name = str; - - if (obj is GComponent) - { - int cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - Controller cc = ((GComponent)obj).GetController(buffer.ReadS()); - str = buffer.ReadS(); - if (cc != null) - cc.selectedPageId = str; - } - - if (buffer.version >= 2) - { - cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - string target = buffer.ReadS(); - int propertyId = buffer.ReadShort(); - string value = buffer.ReadS(); - GObject obj2 = ((GComponent)obj).GetChildByPath(target); - if (obj2 != null) - { - if (propertyId == 0) - obj2.text = value; - else if (propertyId == 1) - obj2.icon = value; - } - } - } - } - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - buffer.Seek(beginPos, 6); - - int i = buffer.ReadShort(); - if (i != -1) - _selectionController = parent.GetControllerAt(i); - } - } -} +using System; +using System.Collections.Generic; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Callback function when an item is needed to update its look. + /// + /// Item index. + /// Item object. + public delegate void ListItemRenderer(int index, GObject item); + + /// + /// + /// + /// + /// + public delegate string ListItemProvider(int index); + + /// + /// GList class. + /// + public class GList : GComponent + { + /// + /// 如果true,当item不可见时自动折叠,否则依然占位 + /// + public bool foldInvisibleItems = false; + + /// + /// List selection mode + /// + /// + public ListSelectionMode selectionMode; + + /// + /// Callback function when an item is needed to update its look. + /// + public ListItemRenderer itemRenderer; + + /// + /// Callback funtion to return item resource url. + /// + public ListItemProvider itemProvider; + + /// + /// + /// + public bool scrollItemToViewOnClick; + + string _defaultItem; + ListLayoutType _layout; + int _lineCount; + int _columnCount; + int _lineGap; + int _columnGap; + AlignType _align; + VertAlignType _verticalAlign; + bool _autoResizeItem; + Controller _selectionController; + + GObjectPool _pool; + int _lastSelectedIndex; + + EventListener _onClickItem; + EventListener _onRightClickItem; + + //Virtual List support + bool _virtual; + bool _loop; + int _numItems; + int _realNumItems; + int _firstIndex; //the top left index + int _curLineItemCount; //item count in one line + int _curLineItemCount2; //只用在页面模式,表示垂直方向的项目数 + Vector2 _itemSize; + int _virtualListChanged; //1-content changed, 2-size changed + uint itemInfoVer; //用来标志item是否在本次处理中已经被重用了 + + int _miscFlags; //1-event locked, 2-focus events registered + + class ItemInfo + { + public Vector2 size; + public GObject obj; + public uint updateFlag; + public bool selected; + } + List _virtualItems; + + EventCallback1 _itemClickDelegate; + + public GList() + : base() + { + _trackBounds = true; + this.opaque = true; + scrollItemToViewOnClick = true; + + container = new Container(); + rootContainer.AddChild(container); + rootContainer.gameObject.name = "GList"; + + _pool = new GObjectPool(container.cachedTransform); + + _itemClickDelegate = __clickItem; + } + + public override void Dispose() + { + _pool.Clear(); + if (_virtualListChanged != 0) + Timers.inst.Remove(this.RefreshVirtualList); + + _selectionController = null; + scrollItemToViewOnClick = false; + itemRenderer = null; + itemProvider = null; + + base.Dispose(); + } + + /// + /// Dispatched when a list item being clicked. + /// + public EventListener onClickItem + { + get { return _onClickItem ?? (_onClickItem = new EventListener(this, "onClickItem")); } + } + + /// + /// Dispatched when a list item being clicked with right button. + /// + public EventListener onRightClickItem + { + get { return _onRightClickItem ?? (_onRightClickItem = new EventListener(this, "onRightClickItem")); } + } + + /// + /// Resource url of the default item. + /// + public string defaultItem + { + get { return _defaultItem; } + set + { + _defaultItem = UIPackage.NormalizeURL(value); + } + } + + /// + /// List layout type. + /// + public ListLayoutType layout + { + get { return _layout; } + set + { + if (_layout != value) + { + _layout = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public int lineCount + { + get { return _lineCount; } + set + { + if (_lineCount != value) + { + _lineCount = value; + if (_layout == ListLayoutType.FlowVertical || _layout == ListLayoutType.Pagination) + { + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + } + + /// + /// + /// + public int columnCount + { + get { return _columnCount; } + set + { + if (_columnCount != value) + { + _columnCount = value; + if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + } + + /// + /// + /// + public int lineGap + { + get { return _lineGap; } + set + { + if (_lineGap != value) + { + _lineGap = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public int columnGap + { + get { return _columnGap; } + set + { + if (_columnGap != value) + { + _columnGap = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public AlignType align + { + get { return _align; } + set + { + if (_align != value) + { + _align = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _verticalAlign; } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + /// + /// If the item will resize itself to fit the list width/height. + /// + public bool autoResizeItem + { + get { return _autoResizeItem; } + set + { + if (_autoResizeItem != value) + { + _autoResizeItem = value; + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + /// + public Vector2 defaultItemSize + { + get { return _itemSize; } + set + { + _itemSize = value; + if (_virtual) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.scrollPane.scrollStep = _itemSize.y; + else + this.scrollPane.scrollStep = _itemSize.x; + SetVirtualListChangedFlag(true); + } + } + } + + /// + /// + /// + public GObjectPool itemPool + { + get { return _pool; } + } + + /// + /// + /// + /// + /// + public GObject GetFromPool(string url) + { + if (string.IsNullOrEmpty(url)) + url = _defaultItem; + + GObject ret = _pool.GetObject(url); + if (ret != null) + ret.visible = true; + return ret; + } + + void ReturnToPool(GObject obj) + { + _pool.ReturnObject(obj); + } + + /// + /// Add a item to list, same as GetFromPool+AddChild + /// + /// Item object + public GObject AddItemFromPool() + { + GObject obj = GetFromPool(null); + + return AddChild(obj); + } + + /// + /// Add a item to list, same as GetFromPool+AddChild + /// + /// Item resource url + /// Item object + public GObject AddItemFromPool(string url) + { + GObject obj = GetFromPool(url); + + return AddChild(obj); + } + + /// + /// + /// + /// + /// + /// + override public GObject AddChildAt(GObject child, int index) + { + base.AddChildAt(child, index); + if (child is GButton) + { + GButton button = (GButton)child; + button.selected = false; + button.changeStateOnClick = false; + } + + child.onClick.Add(_itemClickDelegate); + child.onRightClick.Add(_itemClickDelegate); + + return child; + } + + /// + /// + /// + /// + /// + /// + override public GObject RemoveChildAt(int index, bool dispose) + { + GObject child = base.RemoveChildAt(index, dispose); + child.onClick.Remove(_itemClickDelegate); + child.onRightClick.Remove(_itemClickDelegate); + + return child; + } + + /// + /// + /// + /// + public void RemoveChildToPoolAt(int index) + { + GObject child = base.RemoveChildAt(index); + ReturnToPool(child); + } + + /// + /// + /// + /// + public void RemoveChildToPool(GObject child) + { + base.RemoveChild(child); + ReturnToPool(child); + } + + /// + /// + /// + public void RemoveChildrenToPool() + { + RemoveChildrenToPool(0, -1); + } + + /// + /// + /// + /// + /// + public void RemoveChildrenToPool(int beginIndex, int endIndex) + { + if (endIndex < 0 || endIndex >= _children.Count) + endIndex = _children.Count - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildToPoolAt(beginIndex); + } + + /// + /// + /// + public int selectedIndex + { + get + { + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton) && ((GButton)ii.obj).selected + || ii.obj == null && ii.selected) + { + if (_loop) + return i % _numItems; + else + return i; + } + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj.selected) + return i; + } + } + return -1; + } + + set + { + if (value >= 0 && value < this.numItems) + { + if (selectionMode != ListSelectionMode.Single) + ClearSelection(); + AddSelection(value, false); + } + else + ClearSelection(); + } + } + + /// + /// + /// + public Controller selectionController + { + get { return _selectionController; } + set { _selectionController = value; } + } + + /// + /// + /// + /// + public List GetSelection() + { + return GetSelection(null); + } + + /// + /// + /// + /// + public List GetSelection(List result) + { + if (result == null) + result = new List(); + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton) && ((GButton)ii.obj).selected + || ii.obj == null && ii.selected) + { + int j = i; + if (_loop) + { + j = i % _numItems; + if (result.Contains(j)) + continue; + } + result.Add(j); + } + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj.selected) + result.Add(i); + } + } + return result; + } + + /// + /// + /// + /// + /// + public void AddSelection(int index, bool scrollItToView) + { + if (selectionMode == ListSelectionMode.None) + return; + + CheckVirtualList(); + + if (selectionMode == ListSelectionMode.Single) + ClearSelection(); + + if (scrollItToView) + ScrollToView(index); + + _lastSelectedIndex = index; + GButton obj = null; + if (_virtual) + { + ItemInfo ii = _virtualItems[index]; + if (ii.obj != null) + obj = ii.obj.asButton; + ii.selected = true; + } + else + obj = GetChildAt(index).asButton; + + if (obj != null && !obj.selected) + { + obj.selected = true; + UpdateSelectionController(index); + } + } + + /// + /// + /// + /// + public void RemoveSelection(int index) + { + if (selectionMode == ListSelectionMode.None) + return; + + GButton obj = null; + if (_virtual) + { + ItemInfo ii = _virtualItems[index]; + if (ii.obj != null) + obj = ii.obj.asButton; + ii.selected = false; + } + else + obj = GetChildAt(index).asButton; + + if (obj != null) + obj.selected = false; + } + + /// + /// + /// + public void ClearSelection() + { + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton)) + ((GButton)ii.obj).selected = false; + ii.selected = false; + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null) + obj.selected = false; + } + } + } + + void ClearSelectionExcept(GObject g) + { + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if (ii.obj != g) + { + if ((ii.obj is GButton)) + ((GButton)ii.obj).selected = false; + ii.selected = false; + } + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj != g) + obj.selected = false; + } + } + } + + /// + /// + /// + public void SelectAll() + { + CheckVirtualList(); + + int last = -1; + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton) && !((GButton)ii.obj).selected) + { + ((GButton)ii.obj).selected = true; + last = i; + } + ii.selected = true; + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && !obj.selected) + { + obj.selected = true; + last = i; + } + } + } + + if (last != -1) + UpdateSelectionController(last); + } + + /// + /// + /// + public void SelectNone() + { + ClearSelection(); + } + + /// + /// + /// + public void SelectReverse() + { + CheckVirtualList(); + + int last = -1; + if (_virtual) + { + int cnt = _realNumItems; + for (int i = 0; i < cnt; i++) + { + ItemInfo ii = _virtualItems[i]; + if ((ii.obj is GButton)) + { + ((GButton)ii.obj).selected = !((GButton)ii.obj).selected; + if (((GButton)ii.obj).selected) + last = i; + } + ii.selected = !ii.selected; + } + } + else + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null) + { + obj.selected = !obj.selected; + if (obj.selected) + last = i; + } + } + } + + if (last != -1) + UpdateSelectionController(last); + } + + /// + /// + /// + /// + public void EnableSelectionFocusEvents(bool enabled) + { + if (((_miscFlags & 2) != 0) == enabled) + return; + + if (enabled) + { + _miscFlags |= 2; + this.tabStopChildren = true; + onFocusIn.Add(NotifySelection); + onFocusOut.Add(NotifySelection); + } + else + { + _miscFlags &= 0xFD; + onFocusIn.Remove(NotifySelection); + onFocusOut.Remove(NotifySelection); + } + } + + void NotifySelection(EventContext context) + { + string eventType = context.type == "onFocusIn" ? "onListFocusIn" : "onListFocusOut"; + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + GButton obj = _children[i].asButton; + if (obj != null && obj.selected) + obj.DispatchEvent(eventType); + } + } + + /// + /// + /// + public void EnableArrowKeyNavigation(bool enabled) + { + if (enabled) + { + this.tabStopChildren = true; + onKeyDown.Add(__keydown); + } + else + { + this.tabStopChildren = false; + onKeyDown.Remove(__keydown); + } + } + + void __keydown(EventContext context) + { + int index = -1; + switch (context.inputEvent.keyCode) + { + case KeyCode.LeftArrow: + index = HandleArrowKey(7); + break; + + case KeyCode.RightArrow: + index = HandleArrowKey(3); + break; + + case KeyCode.UpArrow: + index = HandleArrowKey(1); + break; + + case KeyCode.DownArrow: + index = HandleArrowKey(5); + break; + } + + if (index != -1) + { + index = ItemIndexToChildIndex(index); + if (index != -1) + DispatchItemEvent(GetChildAt(index), context); + + context.StopPropagation(); + } + } + + /// + /// + /// + /// + public int HandleArrowKey(int dir) + { + int curIndex = this.selectedIndex; + if (curIndex == -1) + return -1; + + int index = curIndex; + switch (dir) + { + case 1://up + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowVertical) + { + index--; + } + else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + if (_virtual) + { + index -= _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int i; + for (i = index - 1; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + current = obj; + break; + } + k++; + } + for (; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + index = i + k + 1; + break; + } + } + } + } + break; + + case 3://right + if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + index++; + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_virtual) + { + index += _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int cnt = _children.Count; + int i; + for (i = index + 1; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + current = obj; + break; + } + k++; + } + for (; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + index = i - k - 1; + break; + } + } + } + } + break; + + case 5://down + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowVertical) + { + index++; + } + else if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + if (_virtual) + { + index += _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int cnt = _children.Count; + int i; + for (i = index + 1; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + current = obj; + break; + } + k++; + } + for (; i < cnt; i++) + { + GObject obj = _children[i]; + if (obj.y != current.y) + { + index = i - k - 1; + break; + } + } + } + } + break; + + case 7://left + if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.Pagination) + { + index--; + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_virtual) + { + index -= _curLineItemCount; + } + else + { + GObject current = _children[index]; + int k = 0; + int i; + for (i = index - 1; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + current = obj; + break; + } + k++; + } + for (; i >= 0; i--) + { + GObject obj = _children[i]; + if (obj.x != current.x) + { + index = i + k + 1; + break; + } + } + } + } + break; + } + + if (index != curIndex && index >= 0 && index < this.numItems) + { + ClearSelection(); + AddSelection(index, true); + return index; + } + else + return -1; + } + + void __clickItem(EventContext context) + { + GObject item = context.sender as GObject; + if ((item is GButton) && selectionMode != ListSelectionMode.None) + SetSelectionOnEvent(item, context.inputEvent); + + if (scrollPane != null && scrollItemToViewOnClick) + scrollPane.ScrollToView(item, true); + + DispatchItemEvent(item, context); + } + + virtual protected void DispatchItemEvent(GObject item, EventContext context) + { + if (context.type == item.onRightClick.type) + DispatchEvent("onRightClickItem", item); + else + DispatchEvent("onClickItem", item); + } + + void SetSelectionOnEvent(GObject item, InputEvent evt) + { + bool dontChangeLastIndex = false; + GButton button = (GButton)item; + int index = ChildIndexToItemIndex(GetChildIndex(item)); + + if (selectionMode == ListSelectionMode.Single) + { + if (!button.selected) + { + ClearSelectionExcept(button); + button.selected = true; + } + } + else + { + if (evt.shift) + { + if (!button.selected) + { + if (_lastSelectedIndex != -1) + { + int min = Math.Min(_lastSelectedIndex, index); + int max = Math.Max(_lastSelectedIndex, index); + max = Math.Min(max, this.numItems - 1); + if (_virtual) + { + for (int i = min; i <= max; i++) + { + ItemInfo ii = _virtualItems[i]; + if (ii.obj is GButton) + ((GButton)ii.obj).selected = true; + ii.selected = true; + } + } + else + { + for (int i = min; i <= max; i++) + { + GButton obj = GetChildAt(i).asButton; + if (obj != null && !obj.selected) + obj.selected = true; + } + } + + dontChangeLastIndex = true; + } + else + { + button.selected = true; + } + } + } + else if (evt.ctrlOrCmd || selectionMode == ListSelectionMode.Multiple_SingleClick) + { + button.selected = !button.selected; + } + else + { + if (!button.selected) + { + ClearSelectionExcept(button); + button.selected = true; + } + else if (evt.button == 0) + ClearSelectionExcept(button); + } + } + + if (!dontChangeLastIndex) + _lastSelectedIndex = index; + + if (button.selected) + UpdateSelectionController(index); + } + + /// + /// Resize to list size to fit specified item count. + /// If list layout is single column or flow horizontally, the height will change to fit. + /// If list layout is single row or flow vertically, the width will change to fit. + /// + public void ResizeToFit() + { + ResizeToFit(int.MaxValue, 0); + } + + /// + /// Resize to list size to fit specified item count. + /// If list layout is single column or flow horizontally, the height will change to fit. + /// If list layout is single row or flow vertically, the width will change to fit. + /// + /// Item count + public void ResizeToFit(int itemCount) + { + ResizeToFit(itemCount, 0); + } + + /// + /// Resize to list size to fit specified item count. + /// If list layout is single column or flow horizontally, the height will change to fit. + /// If list layout is single row or flow vertically, the width will change to fit. + /// + /// >Item count + /// If the result size if smaller than minSize, then use minSize. + public void ResizeToFit(int itemCount, int minSize) + { + EnsureBoundsCorrect(); + + int curCount = this.numItems; + if (itemCount > curCount) + itemCount = curCount; + + if (_virtual) + { + int lineCount = Mathf.CeilToInt((float)itemCount / _curLineItemCount); + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.viewHeight = lineCount * _itemSize.y + Math.Max(0, lineCount - 1) * _lineGap; + else + this.viewWidth = lineCount * _itemSize.x + Math.Max(0, lineCount - 1) * _columnGap; + } + else if (itemCount == 0) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.viewHeight = minSize; + else + this.viewWidth = minSize; + } + else + { + int i = itemCount - 1; + GObject obj = null; + while (i >= 0) + { + obj = this.GetChildAt(i); + if (!foldInvisibleItems || obj.visible) + break; + i--; + } + if (i < 0) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + this.viewHeight = minSize; + else + this.viewWidth = minSize; + } + else + { + float size; + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + size = obj.y + obj.height; + if (size < minSize) + size = minSize; + this.viewHeight = size; + } + else + { + size = obj.x + obj.width; + if (size < minSize) + size = minSize; + this.viewWidth = size; + } + } + } + } + + /// + /// + /// + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + SetBoundsChangedFlag(); + if (_virtual) + SetVirtualListChangedFlag(true); + } + + override public void HandleControllerChanged(Controller c) + { + base.HandleControllerChanged(c); + + if (_selectionController == c) + this.selectedIndex = c.selectedIndex; + } + + void UpdateSelectionController(int index) + { + if (_selectionController != null && !_selectionController.changing + && index < _selectionController.pageCount) + { + Controller c = _selectionController; + _selectionController = null; + c.selectedIndex = index; + _selectionController = c; + } + } + + /// + /// Scroll the list to make an item with certain index visible. + /// + /// Item index + public void ScrollToView(int index) + { + ScrollToView(index, false); + } + + /// + /// Scroll the list to make an item with certain index visible. + /// + /// Item index + /// True to scroll smoothly, othewise immdediately. + public void ScrollToView(int index, bool ani) + { + ScrollToView(index, ani, false); + } + + /// + /// Scroll the list to make an item with certain index visible. + /// + /// Item index + /// True to scroll smoothly, othewise immdediately. + /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. + public void ScrollToView(int index, bool ani, bool setFirst) + { + if (_virtual) + { + if (_numItems == 0) + return; + + CheckVirtualList(); + + if (index >= _virtualItems.Count) + throw new Exception("Invalid child index: " + index + ">" + _virtualItems.Count); + + if (_loop) + index = Mathf.FloorToInt((float)_firstIndex / _numItems) * _numItems + index; + + Rect rect; + ItemInfo ii = _virtualItems[index]; + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + float pos = 0; + for (int i = _curLineItemCount - 1; i < index; i += _curLineItemCount) + pos += _virtualItems[i].size.y + _lineGap; + rect = new Rect(0, pos, _itemSize.x, ii.size.y); + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + float pos = 0; + for (int i = _curLineItemCount - 1; i < index; i += _curLineItemCount) + pos += _virtualItems[i].size.x + _columnGap; + rect = new Rect(pos, 0, ii.size.x, _itemSize.y); + } + else + { + int page = index / (_curLineItemCount * _curLineItemCount2); + rect = new Rect(page * viewWidth + (index % _curLineItemCount) * (ii.size.x + _columnGap), + (index / _curLineItemCount) % _curLineItemCount2 * (ii.size.y + _lineGap), + ii.size.x, ii.size.y); + } + + if (this.scrollPane != null) + scrollPane.ScrollToView(rect, ani, setFirst); + else if (parent != null && parent.scrollPane != null) + parent.scrollPane.ScrollToView(this.TransformRect(rect, parent), ani, setFirst); + } + else + { + GObject obj = GetChildAt(index); + if (this.scrollPane != null) + scrollPane.ScrollToView(obj, ani, setFirst); + else if (parent != null && parent.scrollPane != null) + parent.scrollPane.ScrollToView(obj, ani, setFirst); + } + } + + /// + /// 获取当前点击哪个item + /// + public GObject touchItem + { + get + { + //find out which item is under finger + //逐层往上知道查到点击了那个item + GObject obj = GRoot.inst.touchTarget; + GObject p = obj.parent; + while (p != null) + { + if (p == this) + return obj; + + obj = p; + p = p.parent; + } + + return null; + } + } + + /// + /// Get first child in view. + /// + /// + public override int GetFirstChildInView() + { + return ChildIndexToItemIndex(base.GetFirstChildInView()); + } + + public int ChildIndexToItemIndex(int index) + { + if (!_virtual) + return index; + + if (_layout == ListLayoutType.Pagination) + { + for (int i = _firstIndex; i < _realNumItems; i++) + { + if (_virtualItems[i].obj != null) + { + index--; + if (index < 0) + return i; + } + } + + return index; + } + else + { + index += _firstIndex; + if (_loop && _numItems > 0) + index = index % _numItems; + + return index; + } + } + + public int ItemIndexToChildIndex(int index) + { + if (!_virtual) + return index; + + if (_layout == ListLayoutType.Pagination) + { + return GetChildIndex(_virtualItems[index].obj); + } + else + { + if (_loop && _numItems > 0) + { + int j = _firstIndex % _numItems; + if (index >= j) + index = index - j; + else + index = _numItems - j + index; + } + else + index -= _firstIndex; + + return index; + } + } + + + /// + /// Set the list to be virtual list. + /// 设置列表为虚拟列表模式。在虚拟列表模式下,列表不会为每一条列表数据创建一个实体对象,而是根据视口大小创建最小量的显示对象,然后通过itemRenderer指定的回调函数设置列表数据。 + /// 在虚拟模式下,你不能通过AddChild、RemoveChild等方式管理列表,只能通过设置numItems设置列表数据的长度。 + /// 如果要刷新列表,可以通过重新设置numItems,或者调用RefreshVirtualList完成。 + /// ‘单行’或者‘单列’的列表布局可支持不等高的列表项目。 + /// 除了‘页面’的列表布局,其他布局均支持使用不同资源构建列表项目,你可以在itemProvider里返回。如果不提供,默认使用defaultItem。 + /// + public void SetVirtual() + { + SetVirtual(false); + } + + public bool isVirtual + { + get { return _virtual; } + } + + /// + /// Set the list to be virtual list, and has loop behavior. + /// + public void SetVirtualAndLoop() + { + SetVirtual(true); + } + + void SetVirtual(bool loop) + { + if (!_virtual) + { + if (this.scrollPane == null) + Debug.LogError("FairyGUI: Virtual list must be scrollable!"); + + if (loop) + { + if (_layout == ListLayoutType.FlowHorizontal || _layout == ListLayoutType.FlowVertical) + Debug.LogError("FairyGUI: Loop list is not supported for FlowHorizontal or FlowVertical layout!"); + + this.scrollPane.bouncebackEffect = false; + } + + _virtual = true; + _loop = loop; + _virtualItems = new List(); + RemoveChildrenToPool(); + + if (_itemSize.x == 0 || _itemSize.y == 0) + { + GObject obj = GetFromPool(null); + if (obj == null) + { + Debug.LogError("FairyGUI: Virtual List must have a default list item resource."); + _itemSize = new Vector2(100, 100); + } + else + { + _itemSize = obj.size; + _itemSize.x = Mathf.CeilToInt(_itemSize.x); + _itemSize.y = Mathf.CeilToInt(_itemSize.y); + ReturnToPool(obj); + } + } + + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + this.scrollPane.scrollStep = _itemSize.y; + if (_loop) + this.scrollPane._loop = 2; + } + else + { + this.scrollPane.scrollStep = _itemSize.x; + if (_loop) + this.scrollPane._loop = 1; + } + + this.scrollPane.onScroll.AddCapture(__scrolled); + SetVirtualListChangedFlag(true); + } + } + + /// + /// Set the list item count. + /// If the list is not virtual, specified number of items will be created. + /// If the list is virtual, only items in view will be created. + /// + public int numItems + { + get + { + if (_virtual) + return _numItems; + else + return _children.Count; + } + set + { + if (_virtual) + { + if (itemRenderer == null) + throw new Exception("FairyGUI: Set itemRenderer first!"); + + _numItems = value; + if (_loop) + _realNumItems = _numItems * 6;//设置6倍数量,用于循环滚动 + else + _realNumItems = _numItems; + + //_virtualItems的设计是只增不减的 + int oldCount = _virtualItems.Count; + if (_realNumItems > oldCount) + { + for (int i = oldCount; i < _realNumItems; i++) + { + ItemInfo ii = new ItemInfo(); + ii.size = _itemSize; + + _virtualItems.Add(ii); + } + } + else + { + for (int i = _realNumItems; i < oldCount; i++) + _virtualItems[i].selected = false; + } + + if (_virtualListChanged != 0) + Timers.inst.Remove(this.RefreshVirtualList); + //立即刷新 + this.RefreshVirtualList(null); + } + else + { + int cnt = _children.Count; + if (value > cnt) + { + for (int i = cnt; i < value; i++) + { + if (itemProvider == null) + AddItemFromPool(); + else + AddItemFromPool(itemProvider(i)); + } + } + else + { + RemoveChildrenToPool(value, cnt); + } + + if (itemRenderer != null) + { + for (int i = 0; i < value; i++) + itemRenderer(i, GetChildAt(i)); + } + } + } + } + + public void RefreshVirtualList() + { + if (!_virtual) + throw new Exception("FairyGUI: not virtual list"); + + SetVirtualListChangedFlag(false); + } + + void CheckVirtualList() + { + if (_virtualListChanged != 0) + { + this.RefreshVirtualList(null); + Timers.inst.Remove(this.RefreshVirtualList); + } + } + + void SetVirtualListChangedFlag(bool layoutChanged) + { + if (layoutChanged) + _virtualListChanged = 2; + else if (_virtualListChanged == 0) + _virtualListChanged = 1; + + Timers.inst.CallLater(RefreshVirtualList); + } + + void RefreshVirtualList(object param) + { + bool layoutChanged = _virtualListChanged == 2; + _virtualListChanged = 0; + _miscFlags |= 1; + + if (layoutChanged) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.SingleRow) + _curLineItemCount = 1; + else if (_layout == ListLayoutType.FlowHorizontal) + { + if (_columnCount > 0) + _curLineItemCount = _columnCount; + else + { + _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); + if (_curLineItemCount <= 0) + _curLineItemCount = 1; + } + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_lineCount > 0) + _curLineItemCount = _lineCount; + else + { + _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); + if (_curLineItemCount <= 0) + _curLineItemCount = 1; + } + } + else //pagination + { + if (_columnCount > 0) + _curLineItemCount = _columnCount; + else + { + _curLineItemCount = Mathf.FloorToInt((this.scrollPane.viewWidth + _columnGap) / (_itemSize.x + _columnGap)); + if (_curLineItemCount <= 0) + _curLineItemCount = 1; + } + + if (_lineCount > 0) + _curLineItemCount2 = _lineCount; + else + { + _curLineItemCount2 = Mathf.FloorToInt((this.scrollPane.viewHeight + _lineGap) / (_itemSize.y + _lineGap)); + if (_curLineItemCount2 <= 0) + _curLineItemCount2 = 1; + } + } + } + + float ch = 0, cw = 0; + if (_realNumItems > 0) + { + int len = Mathf.CeilToInt((float)_realNumItems / _curLineItemCount) * _curLineItemCount; + int len2 = Math.Min(_curLineItemCount, _realNumItems); + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + for (int i = 0; i < len; i += _curLineItemCount) + ch += _virtualItems[i].size.y + _lineGap; + if (ch > 0) + ch -= _lineGap; + + if (_autoResizeItem) + cw = scrollPane.viewWidth; + else + { + for (int i = 0; i < len2; i++) + cw += _virtualItems[i].size.x + _columnGap; + if (cw > 0) + cw -= _columnGap; + } + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + for (int i = 0; i < len; i += _curLineItemCount) + cw += _virtualItems[i].size.x + _columnGap; + if (cw > 0) + cw -= _columnGap; + + if (_autoResizeItem) + ch = this.scrollPane.viewHeight; + else + { + for (int i = 0; i < len2; i++) + ch += _virtualItems[i].size.y + _lineGap; + if (ch > 0) + ch -= _lineGap; + } + } + else + { + int pageCount = Mathf.CeilToInt((float)len / (_curLineItemCount * _curLineItemCount2)); + cw = pageCount * viewWidth; + ch = viewHeight; + } + } + + HandleAlign(cw, ch); + this.scrollPane.SetContentSize(cw, ch); + + _miscFlags &= 0xFE; + + HandleScroll(true); + } + + void __scrolled(EventContext context) + { + HandleScroll(false); + } + + int GetIndexOnPos1(ref float pos, bool forceUpdate) + { + if (_realNumItems < _curLineItemCount) + { + pos = 0; + return 0; + } + + if (numChildren > 0 && !forceUpdate) + { + float pos2 = this.GetChildAt(0).y; + if (pos2 + (_lineGap > 0 ? 0 : -_lineGap) > pos) + { + for (int i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) + { + pos2 -= (_virtualItems[i].size.y + _lineGap); + if (pos2 <= pos) + { + pos = pos2; + return i; + } + } + + pos = 0; + return 0; + } + else + { + float testGap = _lineGap > 0 ? _lineGap : 0; + for (int i = _firstIndex; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.y; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _lineGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + else + { + float pos2 = 0; + float testGap = _lineGap > 0 ? _lineGap : 0; + for (int i = 0; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.y; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _lineGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + + int GetIndexOnPos2(ref float pos, bool forceUpdate) + { + if (_realNumItems < _curLineItemCount) + { + pos = 0; + return 0; + } + + if (numChildren > 0 && !forceUpdate) + { + float pos2 = this.GetChildAt(0).x; + if (pos2 + (_columnGap > 0 ? 0 : -_columnGap) > pos) + { + for (int i = _firstIndex - _curLineItemCount; i >= 0; i -= _curLineItemCount) + { + pos2 -= (_virtualItems[i].size.x + _columnGap); + if (pos2 <= pos) + { + pos = pos2; + return i; + } + } + + pos = 0; + return 0; + } + else + { + float testGap = _columnGap > 0 ? _columnGap : 0; + for (int i = _firstIndex; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.x; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _columnGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + else + { + float pos2 = 0; + float testGap = _columnGap > 0 ? _columnGap : 0; + for (int i = 0; i < _realNumItems; i += _curLineItemCount) + { + float pos3 = pos2 + _virtualItems[i].size.x; + if (pos3 + testGap > pos) + { + pos = pos2; + return i; + } + pos2 = pos3 + _columnGap; + } + + pos = pos2; + return _realNumItems - _curLineItemCount; + } + } + + int GetIndexOnPos3(ref float pos, bool forceUpdate) + { + if (_realNumItems < _curLineItemCount) + { + pos = 0; + return 0; + } + + float viewWidth = this.viewWidth; + int page = Mathf.FloorToInt(pos / viewWidth); + int startIndex = page * (_curLineItemCount * _curLineItemCount2); + float pos2 = page * viewWidth; + float testGap = _columnGap > 0 ? _columnGap : 0; + for (int i = 0; i < _curLineItemCount; i++) + { + float pos3 = pos2 + _virtualItems[startIndex + i].size.x; + if (pos3 + testGap > pos) + { + pos = pos2; + return startIndex + i; + } + pos2 = pos3 + _columnGap; + } + + pos = pos2; + return startIndex + _curLineItemCount - 1; + } + + void HandleScroll(bool forceUpdate) + { + if ((_miscFlags & 1) != 0) + return; + + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + int enterCounter = 0; + while (HandleScroll1(forceUpdate)) + { + //可能会因为ITEM资源改变导致ITEM大小发生改变,所有出现最后一页填不满的情况,这时要反复尝试填满。 + enterCounter++; + forceUpdate = false; + if (enterCounter > 20) + { + Debug.Log("FairyGUI: list will never be filled as the item renderer function always returns a different size."); + break; + } + } + + HandleArchOrder1(); + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + int enterCounter = 0; + while (HandleScroll2(forceUpdate)) + { + enterCounter++; + forceUpdate = false; + if (enterCounter > 20) + { + Debug.Log("FairyGUI: list will never be filled as the item renderer function always returns a different size."); + break; + } + } + + HandleArchOrder2(); + } + else + { + HandleScroll3(forceUpdate); + } + + _boundsChanged = false; + } + + bool HandleScroll1(bool forceUpdate) + { + float pos = scrollPane.scrollingPosY; + float max = pos + scrollPane.viewHeight; + bool end = max == scrollPane.contentHeight;//这个标志表示当前需要滚动到最末,无论内容变化大小 + + //寻找当前位置的第一条项目 + int newFirstIndex = GetIndexOnPos1(ref pos, forceUpdate); + if (newFirstIndex == _firstIndex && !forceUpdate) + return false; + + int oldFirstIndex = _firstIndex; + _firstIndex = newFirstIndex; + int curIndex = newFirstIndex; + bool forward = oldFirstIndex > newFirstIndex; + int childCount = this.numChildren; + int lastIndex = oldFirstIndex + childCount - 1; + int reuseIndex = forward ? lastIndex : oldFirstIndex; + float curX = 0, curY = pos; + bool needRender; + float deltaSize = 0; + float firstItemDeltaSize = 0; + string url = _defaultItem; + int partSize = (int)((scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount); + + itemInfoVer++; + while (curIndex < _realNumItems && (end || curY < max)) + { + ItemInfo ii = _virtualItems[curIndex]; + + if (ii.obj == null || forceUpdate) + { + if (itemProvider != null) + { + url = itemProvider(curIndex % _numItems); + if (url == null) + url = _defaultItem; + url = UIPackage.NormalizeURL(url); + } + + if (ii.obj != null && ii.obj.resourceURL != url) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + if (ii.obj == null) + { + //搜索最适合的重用item,保证每次刷新需要新建或者重新render的item最少 + if (forward) + { + for (int j = reuseIndex; j >= oldFirstIndex; j--) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex--; + break; + } + } + } + else + { + for (int j = reuseIndex; j <= lastIndex; j++) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex++; + break; + } + } + } + + if (ii.obj != null) + { + SetChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); + } + else + { + ii.obj = _pool.GetObject(url); + if (forward) + this.AddChildAt(ii.obj, curIndex - newFirstIndex); + else + this.AddChild(ii.obj); + } + if (ii.obj is GButton) + ((GButton)ii.obj).selected = ii.selected; + + needRender = true; + } + else + needRender = forceUpdate; + + if (needRender) + { + if (_autoResizeItem && (_layout == ListLayoutType.SingleColumn || _columnCount > 0)) + ii.obj.SetSize(partSize, ii.obj.height, true); + + itemRenderer(curIndex % _numItems, ii.obj); + if (curIndex % _curLineItemCount == 0) + { + deltaSize += Mathf.CeilToInt(ii.obj.size.y) - ii.size.y; + if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) + { + //当内容向下滚动时,如果新出现的项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 + firstItemDeltaSize = Mathf.CeilToInt(ii.obj.size.y) - ii.size.y; + } + } + ii.size.x = Mathf.CeilToInt(ii.obj.size.x); + ii.size.y = Mathf.CeilToInt(ii.obj.size.y); + } + + ii.updateFlag = itemInfoVer; + ii.obj.SetXY(curX, curY); + if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 + max += ii.size.y; + + curX += ii.size.x + _columnGap; + + if (curIndex % _curLineItemCount == _curLineItemCount - 1) + { + curX = 0; + curY += ii.size.y + _lineGap; + } + curIndex++; + } + + for (int i = 0; i < childCount; i++) + { + ItemInfo ii = _virtualItems[oldFirstIndex + i]; + if (ii.updateFlag != itemInfoVer && ii.obj != null) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + childCount = _children.Count; + for (int i = 0; i < childCount; i++) + { + GObject obj = _virtualItems[newFirstIndex + i].obj; + if (_children[i] != obj) + SetChildIndex(obj, i); + } + + if (deltaSize != 0 || firstItemDeltaSize != 0) + this.scrollPane.ChangeContentSizeOnScrolling(0, deltaSize, 0, firstItemDeltaSize); + + if (curIndex > 0 && this.numChildren > 0 && this.container.y <= 0 && GetChildAt(0).y > -this.container.y)//最后一页没填满! + return true; + else + return false; + } + + bool HandleScroll2(bool forceUpdate) + { + float pos = scrollPane.scrollingPosX; + float max = pos + scrollPane.viewWidth; + bool end = pos == scrollPane.contentWidth;//这个标志表示当前需要滚动到最末,无论内容变化大小 + + //寻找当前位置的第一条项目 + int newFirstIndex = GetIndexOnPos2(ref pos, forceUpdate); + if (newFirstIndex == _firstIndex && !forceUpdate) + return false; + + int oldFirstIndex = _firstIndex; + _firstIndex = newFirstIndex; + int curIndex = newFirstIndex; + bool forward = oldFirstIndex > newFirstIndex; + int childCount = this.numChildren; + int lastIndex = oldFirstIndex + childCount - 1; + int reuseIndex = forward ? lastIndex : oldFirstIndex; + float curX = pos, curY = 0; + bool needRender; + float deltaSize = 0; + float firstItemDeltaSize = 0; + string url = _defaultItem; + int partSize = (int)((scrollPane.viewHeight - _lineGap * (_curLineItemCount - 1)) / _curLineItemCount); + + itemInfoVer++; + while (curIndex < _realNumItems && (end || curX < max)) + { + ItemInfo ii = _virtualItems[curIndex]; + + if (ii.obj == null || forceUpdate) + { + if (itemProvider != null) + { + url = itemProvider(curIndex % _numItems); + if (url == null) + url = _defaultItem; + url = UIPackage.NormalizeURL(url); + } + + if (ii.obj != null && ii.obj.resourceURL != url) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + if (ii.obj == null) + { + if (forward) + { + for (int j = reuseIndex; j >= oldFirstIndex; j--) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex--; + break; + } + } + } + else + { + for (int j = reuseIndex; j <= lastIndex; j++) + { + ItemInfo ii2 = _virtualItems[j]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer && ii2.obj.resourceURL == url) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + if (j == reuseIndex) + reuseIndex++; + break; + } + } + } + + if (ii.obj != null) + { + SetChildIndex(ii.obj, forward ? curIndex - newFirstIndex : numChildren); + } + else + { + ii.obj = _pool.GetObject(url); + if (forward) + this.AddChildAt(ii.obj, curIndex - newFirstIndex); + else + this.AddChild(ii.obj); + } + if (ii.obj is GButton) + ((GButton)ii.obj).selected = ii.selected; + + needRender = true; + } + else + needRender = forceUpdate; + + if (needRender) + { + if (_autoResizeItem && (_layout == ListLayoutType.SingleRow || _lineCount > 0)) + ii.obj.SetSize(ii.obj.width, partSize, true); + + itemRenderer(curIndex % _numItems, ii.obj); + if (curIndex % _curLineItemCount == 0) + { + deltaSize += Mathf.CeilToInt(ii.obj.size.x) - ii.size.x; + if (curIndex == newFirstIndex && oldFirstIndex > newFirstIndex) + { + //当内容向下滚动时,如果新出现的一个项目大小发生变化,需要做一个位置补偿,才不会导致滚动跳动 + firstItemDeltaSize = Mathf.CeilToInt(ii.obj.size.x) - ii.size.x; + } + } + ii.size.x = Mathf.CeilToInt(ii.obj.size.x); + ii.size.y = Mathf.CeilToInt(ii.obj.size.y); + } + + ii.updateFlag = itemInfoVer; + ii.obj.SetXY(curX, curY); + if (curIndex == newFirstIndex) //要显示多一条才不会穿帮 + max += ii.size.x; + + curY += ii.size.y + _lineGap; + + if (curIndex % _curLineItemCount == _curLineItemCount - 1) + { + curY = 0; + curX += ii.size.x + _columnGap; + } + curIndex++; + } + + for (int i = 0; i < childCount; i++) + { + ItemInfo ii = _virtualItems[oldFirstIndex + i]; + if (ii.updateFlag != itemInfoVer && ii.obj != null) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + + childCount = _children.Count; + for (int i = 0; i < childCount; i++) + { + GObject obj = _virtualItems[newFirstIndex + i].obj; + if (_children[i] != obj) + SetChildIndex(obj, i); + } + + if (deltaSize != 0 || firstItemDeltaSize != 0) + this.scrollPane.ChangeContentSizeOnScrolling(deltaSize, 0, firstItemDeltaSize, 0); + + if (curIndex > 0 && this.numChildren > 0 && this.container.x <= 0 && GetChildAt(0).x > -this.container.x)//最后一页没填满! + return true; + else + return false; + } + + void HandleScroll3(bool forceUpdate) + { + float pos = scrollPane.scrollingPosX; + + //寻找当前位置的第一条项目 + int newFirstIndex = GetIndexOnPos3(ref pos, forceUpdate); + if (newFirstIndex == _firstIndex && !forceUpdate) + return; + + int oldFirstIndex = _firstIndex; + _firstIndex = newFirstIndex; + + //分页模式不支持不等高,所以渲染满一页就好了 + + int reuseIndex = oldFirstIndex; + int virtualItemCount = _virtualItems.Count; + int pageSize = _curLineItemCount * _curLineItemCount2; + int startCol = newFirstIndex % _curLineItemCount; + float viewWidth = this.viewWidth; + int page = (int)(newFirstIndex / pageSize); + int startIndex = page * pageSize; + int lastIndex = startIndex + pageSize * 2; //测试两页 + bool needRender; + string url = _defaultItem; + int partWidth = (int)((scrollPane.viewWidth - _columnGap * (_curLineItemCount - 1)) / _curLineItemCount); + int partHeight = (int)((scrollPane.viewHeight - _lineGap * (_curLineItemCount2 - 1)) / _curLineItemCount2); + itemInfoVer++; + + //先标记这次要用到的项目 + for (int i = startIndex; i < lastIndex; i++) + { + if (i >= _realNumItems) + continue; + + int col = i % _curLineItemCount; + if (i - startIndex < pageSize) + { + if (col < startCol) + continue; + } + else + { + if (col > startCol) + continue; + } + + ItemInfo ii = _virtualItems[i]; + ii.updateFlag = itemInfoVer; + } + + GObject lastObj = null; + int insertIndex = 0; + for (int i = startIndex; i < lastIndex; i++) + { + if (i >= _realNumItems) + continue; + + ItemInfo ii = _virtualItems[i]; + if (ii.updateFlag != itemInfoVer) + continue; + + if (ii.obj == null) + { + //寻找看有没有可重用的 + while (reuseIndex < virtualItemCount) + { + ItemInfo ii2 = _virtualItems[reuseIndex]; + if (ii2.obj != null && ii2.updateFlag != itemInfoVer) + { + if (ii2.obj is GButton) + ii2.selected = ((GButton)ii2.obj).selected; + ii.obj = ii2.obj; + ii2.obj = null; + break; + } + reuseIndex++; + } + + if (insertIndex == -1) + insertIndex = GetChildIndex(lastObj) + 1; + + if (ii.obj == null) + { + if (itemProvider != null) + { + url = itemProvider(i % _numItems); + if (url == null) + url = _defaultItem; + url = UIPackage.NormalizeURL(url); + } + + ii.obj = _pool.GetObject(url); + this.AddChildAt(ii.obj, insertIndex); + } + else + { + insertIndex = SetChildIndexBefore(ii.obj, insertIndex); + } + insertIndex++; + + if (ii.obj is GButton) + ((GButton)ii.obj).selected = ii.selected; + + needRender = true; + } + else + { + needRender = forceUpdate; + insertIndex = -1; + lastObj = ii.obj; + } + + if (needRender) + { + if (_autoResizeItem) + { + if (_curLineItemCount == _columnCount && _curLineItemCount2 == _lineCount) + ii.obj.SetSize(partWidth, partHeight, true); + else if (_curLineItemCount == _columnCount) + ii.obj.SetSize(partWidth, ii.obj.height, true); + else if (_curLineItemCount2 == _lineCount) + ii.obj.SetSize(ii.obj.width, partHeight, true); + } + + itemRenderer(i % _numItems, ii.obj); + ii.size.x = Mathf.CeilToInt(ii.obj.size.x); + ii.size.y = Mathf.CeilToInt(ii.obj.size.y); + } + } + + //排列item + float borderX = (startIndex / pageSize) * viewWidth; + float xx = borderX; + float yy = 0; + float lineHeight = 0; + for (int i = startIndex; i < lastIndex; i++) + { + if (i >= _realNumItems) + continue; + + ItemInfo ii = _virtualItems[i]; + if (ii.updateFlag == itemInfoVer) + ii.obj.SetXY(xx, yy); + + if (ii.size.y > lineHeight) + lineHeight = ii.size.y; + if (i % _curLineItemCount == _curLineItemCount - 1) + { + xx = borderX; + yy += lineHeight + _lineGap; + lineHeight = 0; + + if (i == startIndex + pageSize - 1) + { + borderX += viewWidth; + xx = borderX; + yy = 0; + } + } + else + xx += ii.size.x + _columnGap; + } + + //释放未使用的 + for (int i = reuseIndex; i < virtualItemCount; i++) + { + ItemInfo ii = _virtualItems[i]; + if (ii.updateFlag != itemInfoVer && ii.obj != null) + { + if (ii.obj is GButton) + ii.selected = ((GButton)ii.obj).selected; + RemoveChildToPool(ii.obj); + ii.obj = null; + } + } + } + + void HandleArchOrder1() + { + if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) + { + float mid = this.scrollPane.posY + this.viewHeight / 2; + float minDist = int.MaxValue, dist; + int apexIndex = 0; + int cnt = this.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = GetChildAt(i); + if (!foldInvisibleItems || obj.visible) + { + dist = Mathf.Abs(mid - obj.y - obj.height / 2); + if (dist < minDist) + { + minDist = dist; + apexIndex = i; + } + } + } + this.apexIndex = apexIndex; + } + } + + void HandleArchOrder2() + { + if (this.childrenRenderOrder == ChildrenRenderOrder.Arch) + { + float mid = this.scrollPane.posX + this.viewWidth / 2; + float minDist = int.MaxValue, dist; + int apexIndex = 0; + int cnt = this.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = GetChildAt(i); + if (!foldInvisibleItems || obj.visible) + { + dist = Mathf.Abs(mid - obj.x - obj.width / 2); + if (dist < minDist) + { + minDist = dist; + apexIndex = i; + } + } + } + this.apexIndex = apexIndex; + } + } + + override public void GetSnappingPositionWithDir(ref float xValue, ref float yValue, float xDir, float yDir) + { + if (_virtual) + { + if (_layout == ListLayoutType.SingleColumn || _layout == ListLayoutType.FlowHorizontal) + { + float saved = yValue; + int index = GetIndexOnPos1(ref yValue, false); + if (index < _virtualItems.Count && index < _realNumItems) + { + float size = _virtualItems[index].size.y; + if (ShouldSnapToNext(yDir, saved - yValue, size)) + yValue += size + _lineGap; + } + } + else if (_layout == ListLayoutType.SingleRow || _layout == ListLayoutType.FlowVertical) + { + float saved = xValue; + int index = GetIndexOnPos2(ref xValue, false); + if (index < _virtualItems.Count && index < _realNumItems) + { + float size = _virtualItems[index].size.x; + if (ShouldSnapToNext(xDir, saved - xValue, size)) + xValue += size + _columnGap; + } + } + else + { + float saved = xValue; + int index = GetIndexOnPos3(ref xValue, false); + if (index < _virtualItems.Count && index < _realNumItems) + { + float size = _virtualItems[index].size.x; + if (ShouldSnapToNext(xDir, saved - xValue, size)) + xValue += size + _columnGap; + } + } + } + else + base.GetSnappingPositionWithDir(ref xValue, ref yValue, xDir, yDir); + } + + private void HandleAlign(float contentWidth, float contentHeight) + { + Vector2 newOffset = Vector2.zero; + + if (contentHeight < viewHeight) + { + if (_verticalAlign == VertAlignType.Middle) + newOffset.y = (int)((viewHeight - contentHeight) / 2); + else if (_verticalAlign == VertAlignType.Bottom) + newOffset.y = viewHeight - contentHeight; + } + + if (contentWidth < this.viewWidth) + { + if (_align == AlignType.Center) + newOffset.x = (int)((viewWidth - contentWidth) / 2); + else if (_align == AlignType.Right) + newOffset.x = viewWidth - contentWidth; + } + + if (newOffset != _alignOffset) + { + _alignOffset = newOffset; + if (scrollPane != null) + scrollPane.AdjustMaskContainer(); + else + container.SetXY(_margin.left + _alignOffset.x, _margin.top + _alignOffset.y); + } + } + + override protected void UpdateBounds() + { + if (_virtual) + return; + + int cnt = _children.Count; + int i; + int j = 0; + GObject child; + float curX = 0; + float curY = 0; + float cw, ch; + float maxWidth = 0; + float maxHeight = 0; + float viewWidth = this.viewWidth; + float viewHeight = this.viewHeight; + + if (_layout == ListLayoutType.SingleColumn) + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curY != 0) + curY += _lineGap; + child.y = curY; + if (_autoResizeItem) + child.SetSize(viewWidth, child.height, true); + curY += Mathf.CeilToInt(child.height); + if (child.width > maxWidth) + maxWidth = child.width; + } + + ch = curY; + if (ch <= viewHeight && _autoResizeItem && scrollPane != null && scrollPane._displayInDemand && scrollPane.vtScrollBar != null) + { + viewWidth += scrollPane.vtScrollBar.width; + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetSize(viewWidth, child.height, true); + } + } + cw = Mathf.CeilToInt(maxWidth); + } + else if (_layout == ListLayoutType.SingleRow) + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curX != 0) + curX += _columnGap; + child.x = curX; + if (_autoResizeItem) + child.SetSize(child.width, viewHeight, true); + curX += Mathf.CeilToInt(child.width); + if (child.height > maxHeight) + maxHeight = child.height; + } + + cw = curX; + if (cw <= viewWidth && _autoResizeItem && scrollPane != null && scrollPane._displayInDemand && scrollPane.hzScrollBar != null) + { + viewHeight += scrollPane.hzScrollBar.height; + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetSize(child.width, viewHeight, true); + } + } + ch = Mathf.CeilToInt(maxHeight); + } + else if (_layout == ListLayoutType.FlowHorizontal) + { + if (_autoResizeItem && _columnCount > 0) + { + float lineSize = 0; + int lineStart = 0; + float remainSize; + float remainPercent; + + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + lineSize += child.sourceWidth; + j++; + if (j == _columnCount || i == cnt - 1) + { + remainSize = viewWidth - (j - 1) * _columnGap; + remainPercent = 1; + curX = 0; + for (j = lineStart; j <= i; j++) + { + child = GetChildAt(j); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetXY(curX, curY); + float perc = child.sourceWidth / lineSize; + child.SetSize(Mathf.Round(perc / remainPercent * remainSize), child.height, true); + remainSize -= child.width; + remainPercent -= perc; + curX += child.width + _columnGap; + + if (child.height > maxHeight) + maxHeight = child.height; + } + //new line + curY += Mathf.CeilToInt(maxHeight) + _lineGap; + maxHeight = 0; + j = 0; + lineStart = i + 1; + lineSize = 0; + } + } + ch = curY + Mathf.CeilToInt(maxHeight); + cw = viewWidth; + } + else + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curX != 0) + curX += _columnGap; + + if (_columnCount != 0 && j >= _columnCount + || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) + { + //new line + curX = 0; + curY += Mathf.CeilToInt(maxHeight) + _lineGap; + maxHeight = 0; + j = 0; + } + child.SetXY(curX, curY); + curX += Mathf.CeilToInt(child.width); + if (curX > maxWidth) + maxWidth = curX; + if (child.height > maxHeight) + maxHeight = child.height; + j++; + } + ch = curY + Mathf.CeilToInt(maxHeight); + cw = Mathf.CeilToInt(maxWidth); + } + } + else if (_layout == ListLayoutType.FlowVertical) + { + if (_autoResizeItem && _lineCount > 0) + { + float lineSize = 0; + int lineStart = 0; + float remainSize; + float remainPercent; + + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + lineSize += child.sourceHeight; + j++; + if (j == _lineCount || i == cnt - 1) + { + remainSize = viewHeight - (j - 1) * _lineGap; + remainPercent = 1; + curY = 0; + for (j = lineStart; j <= i; j++) + { + child = GetChildAt(j); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetXY(curX, curY); + float perc = child.sourceHeight / lineSize; + child.SetSize(child.width, Mathf.Round(perc / remainPercent * remainSize), true); + remainSize -= child.height; + remainPercent -= perc; + curY += child.height + _lineGap; + + if (child.width > maxWidth) + maxWidth = child.width; + } + //new line + curX += Mathf.CeilToInt(maxWidth) + _columnGap; + maxWidth = 0; + j = 0; + lineStart = i + 1; + lineSize = 0; + } + } + cw = curX + Mathf.CeilToInt(maxWidth); + ch = viewHeight; + } + else + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curY != 0) + curY += _lineGap; + + if (_lineCount != 0 && j >= _lineCount + || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0) + { + curY = 0; + curX += Mathf.CeilToInt(maxWidth) + _columnGap; + maxWidth = 0; + j = 0; + } + child.SetXY(curX, curY); + curY += child.height; + if (curY > maxHeight) + maxHeight = curY; + if (child.width > maxWidth) + maxWidth = child.width; + j++; + } + cw = curX + Mathf.CeilToInt(maxWidth); + ch = Mathf.CeilToInt(maxHeight); + } + } + else //pagination + { + int page = 0; + int k = 0; + float eachHeight = 0; + if (_autoResizeItem && _lineCount > 0) + eachHeight = Mathf.Floor((viewHeight - (_lineCount - 1) * _lineGap) / _lineCount); + + if (_autoResizeItem && _columnCount > 0) + { + float lineSize = 0; + int lineStart = 0; + float remainSize; + float remainPercent; + + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (j == 0 && (_lineCount != 0 && k >= _lineCount + || _lineCount == 0 && curY + (_lineCount > 0 ? eachHeight : child.height) > viewHeight)) + { + //new page + page++; + curY = 0; + k = 0; + } + + lineSize += child.sourceWidth; + j++; + if (j == _columnCount || i == cnt - 1) + { + remainSize = viewWidth - (j - 1) * _columnGap; + remainPercent = 1; + curX = 0; + for (j = lineStart; j <= i; j++) + { + child = GetChildAt(j); + if (foldInvisibleItems && !child.visible) + continue; + + child.SetXY(page * viewWidth + curX, curY); + float perc = child.sourceWidth / lineSize; + child.SetSize(Mathf.Round(perc / remainPercent * remainSize), _lineCount > 0 ? eachHeight : child.height, true); + remainSize -= child.width; + remainPercent -= perc; + curX += child.width + _columnGap; + + if (child.height > maxHeight) + maxHeight = child.height; + } + //new line + curY += Mathf.CeilToInt(maxHeight) + _lineGap; + maxHeight = 0; + j = 0; + lineStart = i + 1; + lineSize = 0; + + k++; + } + } + } + else + { + for (i = 0; i < cnt; i++) + { + child = GetChildAt(i); + if (foldInvisibleItems && !child.visible) + continue; + + if (curX != 0) + curX += _columnGap; + + if (_autoResizeItem && _lineCount > 0) + child.SetSize(child.width, eachHeight, true); + + if (_columnCount != 0 && j >= _columnCount + || _columnCount == 0 && curX + child.width > viewWidth && maxHeight != 0) + { + curX = 0; + curY += maxHeight + _lineGap; + maxHeight = 0; + j = 0; + k++; + + if (_lineCount != 0 && k >= _lineCount + || _lineCount == 0 && curY + child.height > viewHeight && maxWidth != 0)//new page + { + page++; + curY = 0; + k = 0; + } + } + child.SetXY(page * viewWidth + curX, curY); + curX += Mathf.CeilToInt(child.width); + if (curX > maxWidth) + maxWidth = curX; + if (child.height > maxHeight) + maxHeight = child.height; + j++; + } + } + ch = page > 0 ? viewHeight : (curY + Mathf.CeilToInt(maxHeight)); + cw = (page + 1) * viewWidth; + } + + HandleAlign(cw, ch); + SetBounds(0, 0, cw, ch); + + InvalidateBatchingState(true); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _layout = (ListLayoutType)buffer.ReadByte(); + selectionMode = (ListSelectionMode)buffer.ReadByte(); + _align = (AlignType)buffer.ReadByte(); + _verticalAlign = (VertAlignType)buffer.ReadByte(); + _lineGap = buffer.ReadShort(); + _columnGap = buffer.ReadShort(); + _lineCount = buffer.ReadShort(); + _columnCount = buffer.ReadShort(); + _autoResizeItem = buffer.ReadBool(); + _childrenRenderOrder = (ChildrenRenderOrder)buffer.ReadByte(); + _apexIndex = buffer.ReadShort(); + + if (buffer.ReadBool()) + { + _margin.top = buffer.ReadInt(); + _margin.bottom = buffer.ReadInt(); + _margin.left = buffer.ReadInt(); + _margin.right = buffer.ReadInt(); + } + + OverflowType overflow = (OverflowType)buffer.ReadByte(); + if (overflow == OverflowType.Scroll) + { + int savedPos = buffer.position; + buffer.Seek(beginPos, 7); + SetupScroll(buffer); + buffer.position = savedPos; + } + else + SetupOverflow(overflow); + + if (buffer.ReadBool()) + { + int i1 = buffer.ReadInt(); + int i2 = buffer.ReadInt(); + this.clipSoftness = new Vector2(i1, i2); + } + + if (buffer.version >= 2) + { + scrollItemToViewOnClick = buffer.ReadBool(); + foldInvisibleItems = buffer.ReadBool(); + } + + buffer.Seek(beginPos, 8); + + _defaultItem = buffer.ReadS(); + ReadItems(buffer); + } + + virtual protected void ReadItems(ByteBuffer buffer) + { + int itemCount = buffer.ReadShort(); + for (int i = 0; i < itemCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + string str = buffer.ReadS(); + if (str == null) + { + str = _defaultItem; + if (string.IsNullOrEmpty(str)) + { + buffer.position = nextPos; + continue; + } + } + + GObject obj = GetFromPool(str); + if (obj != null) + { + AddChild(obj); + SetupItem(buffer, obj); + } + + buffer.position = nextPos; + } + } + + protected void SetupItem(ByteBuffer buffer, GObject obj) + { + string str; + str = buffer.ReadS(); + if (str != null) + obj.text = str; + str = buffer.ReadS(); + if (str != null && (obj is GButton)) + (obj as GButton).selectedTitle = str; + str = buffer.ReadS(); + if (str != null) + obj.icon = str; + str = buffer.ReadS(); + if (str != null && (obj is GButton)) + (obj as GButton).selectedIcon = str; + str = buffer.ReadS(); + if (str != null) + obj.name = str; + + if (obj is GComponent) + { + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + Controller cc = ((GComponent)obj).GetController(buffer.ReadS()); + str = buffer.ReadS(); + if (cc != null) + cc.selectedPageId = str; + } + + if (buffer.version >= 2) + { + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + string value = buffer.ReadS(); + GObject obj2 = ((GComponent)obj).GetChildByPath(target); + if (obj2 != null) + { + if (propertyId == 0) + obj2.text = value; + else if (propertyId == 1) + obj2.icon = value; + } + } + } + } + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + buffer.Seek(beginPos, 6); + + int i = buffer.ReadShort(); + if (i != -1) + _selectionController = parent.GetControllerAt(i); + } + } +} diff --git a/Assets/Scripts/UI/GList.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GList.cs.meta similarity index 100% rename from Assets/Scripts/UI/GList.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GList.cs.meta diff --git a/Assets/Scripts/UI/GLoader.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader.cs similarity index 96% rename from Assets/Scripts/UI/GLoader.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader.cs index 1cfd2dc6..bd604c11 100644 --- a/Assets/Scripts/UI/GLoader.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader.cs @@ -1,701 +1,701 @@ -using System; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GLoader class - /// - public class GLoader : GObject, IAnimationGear, IColorGear - { - /// - /// Display an error sign if the loader fails to load the content. - /// UIConfig.loaderErrorSign muse be set. - /// - public bool showErrorSign; - - string _url; - AlignType _align; - VertAlignType _verticalAlign; - bool _autoSize; - FillType _fill; - bool _shrinkOnly; - bool _updatingLayout; - PackageItem _contentItem; - Action _reloadDelegate; - - MovieClip _content; - GObject _errorSign; - GComponent _content2; - -#if FAIRYGUI_PUERTS - public Action __loadExternal; - public Action __freeExternal; -#endif - - public GLoader() - { - _url = string.Empty; - _align = AlignType.Left; - _verticalAlign = VertAlignType.Top; - showErrorSign = true; - _reloadDelegate = OnExternalReload; - } - - override protected void CreateDisplayObject() - { - displayObject = new Container("GLoader"); - displayObject.gOwner = this; - _content = new MovieClip(); - ((Container)displayObject).AddChild(_content); - ((Container)displayObject).opaque = true; - } - - override public void Dispose() - { - if (_disposed) return; - - if (_content.texture != null) - { - if (_contentItem == null) - { - _content.texture.onSizeChanged -= _reloadDelegate; - try - { - FreeExternal(_content.texture); - } - catch (Exception err) - { - Debug.LogWarning(err); - } - } - } - if (_errorSign != null) - _errorSign.Dispose(); - if (_content2 != null) - _content2.Dispose(); - _content.Dispose(); - - base.Dispose(); - } - - /// - /// - /// - public string url - { - get { return _url; } - set - { - if (_url == value) - return; - - ClearContent(); - _url = value; - LoadContent(); - UpdateGear(7); - } - } - - override public string icon - { - get { return _url; } - set { this.url = value; } - } - - /// - /// - /// - public AlignType align - { - get { return _align; } - set - { - if (_align != value) - { - _align = value; - UpdateLayout(); - } - } - } - - /// - /// - /// - public VertAlignType verticalAlign - { - get { return _verticalAlign; } - set - { - if (_verticalAlign != value) - { - _verticalAlign = value; - UpdateLayout(); - } - } - } - - /// - /// - /// - public FillType fill - { - get { return _fill; } - set - { - if (_fill != value) - { - _fill = value; - UpdateLayout(); - } - } - } - - /// - /// - /// - public bool shrinkOnly - { - get { return _shrinkOnly; } - set - { - if (_shrinkOnly != value) - { - _shrinkOnly = value; - UpdateLayout(); - } - } - } - - /// - /// - /// - public bool autoSize - { - get { return _autoSize; } - set - { - if (_autoSize != value) - { - _autoSize = value; - UpdateLayout(); - } - } - } - - /// - /// - /// - public bool playing - { - get { return _content.playing; } - set - { - _content.playing = value; - UpdateGear(5); - } - } - - /// - /// - /// - public int frame - { - get { return _content.frame; } - set - { - _content.frame = value; - UpdateGear(5); - } - } - - /// - /// - /// - public float timeScale - { - get { return _content.timeScale; } - set { _content.timeScale = value; } - } - - /// - /// - /// - public bool ignoreEngineTimeScale - { - get { return _content.ignoreEngineTimeScale; } - set { _content.ignoreEngineTimeScale = value; } - } - - /// - /// - /// - /// - public void Advance(float time) - { - _content.Advance(time); - } - - /// - /// - /// - public Material material - { - get { return _content.material; } - set { _content.material = value; } - } - - /// - /// - /// - public string shader - { - get { return _content.shader; } - set { _content.shader = value; } - } - - /// - /// - /// - public Color color - { - get { return _content.color; } - set - { - if (_content.color != value) - { - _content.color = value; - UpdateGear(4); - } - } - } - - /// - /// - /// - public FillMethod fillMethod - { - get { return _content.fillMethod; } - set { _content.fillMethod = value; } - } - - /// - /// - /// - public int fillOrigin - { - get { return _content.fillOrigin; } - set { _content.fillOrigin = value; } - } - - /// - /// - /// - public bool fillClockwise - { - get { return _content.fillClockwise; } - set { _content.fillClockwise = value; } - } - - /// - /// - /// - public float fillAmount - { - get { return _content.fillAmount; } - set { _content.fillAmount = value; } - } - - /// - /// - /// - public Image image - { - get { return _content; } - } - - /// - /// - /// - public MovieClip movieClip - { - get { return _content; } - } - - /// - /// - /// - public GComponent component - { - get { return _content2; } - } - - /// - /// - /// - public NTexture texture - { - get - { - return _content.texture; - } - - set - { - this.url = null; - - _content.texture = value; - if (value != null) - { - sourceWidth = value.width; - sourceHeight = value.height; - } - else - { - sourceWidth = sourceHeight = 0; - } - - UpdateLayout(); - } - } - - override public IFilter filter - { - get { return _content.filter; } - set { _content.filter = value; } - } - - override public BlendMode blendMode - { - get { return _content.blendMode; } - set { _content.blendMode = value; } - } - - /// - /// - /// - protected void LoadContent() - { - ClearContent(); - - if (string.IsNullOrEmpty(_url)) - return; - - if (_url.StartsWith(UIPackage.URL_PREFIX)) - LoadFromPackage(_url); - else - LoadExternal(); - } - - protected void LoadFromPackage(string itemURL) - { - _contentItem = UIPackage.GetItemByURL(itemURL); - - if (_contentItem != null) - { - _contentItem = _contentItem.getBranch(); - sourceWidth = _contentItem.width; - sourceHeight = _contentItem.height; - _contentItem = _contentItem.getHighResolution(); - _contentItem.Load(); - - if (_contentItem.type == PackageItemType.Image) - { - _content.texture = _contentItem.texture; - _content.textureScale = new Vector2(_contentItem.width / (float)sourceWidth, _contentItem.height / (float)sourceHeight); - _content.scale9Grid = _contentItem.scale9Grid; - _content.scaleByTile = _contentItem.scaleByTile; - _content.tileGridIndice = _contentItem.tileGridIndice; - - UpdateLayout(); - } - else if (_contentItem.type == PackageItemType.MovieClip) - { - _content.interval = _contentItem.interval; - _content.swing = _contentItem.swing; - _content.repeatDelay = _contentItem.repeatDelay; - _content.frames = _contentItem.frames; - - UpdateLayout(); - } - else if (_contentItem.type == PackageItemType.Component) - { - GObject obj = UIPackage.CreateObjectFromURL(itemURL); - if (obj == null) - SetErrorState(); - else if (!(obj is GComponent)) - { - obj.Dispose(); - SetErrorState(); - } - else - { - _content2 = (GComponent)obj; - ((Container)displayObject).AddChild(_content2.displayObject); - UpdateLayout(); - } - } - else - { - if (_autoSize) - this.SetSize(_contentItem.width, _contentItem.height); - - SetErrorState(); - - Debug.LogWarning("Unsupported type of GLoader: " + _contentItem.type); - } - } - else - SetErrorState(); - } - - virtual protected void LoadExternal() - { -#if FAIRYGUI_PUERTS - if (__loadExternal != null) { - __loadExternal(); - return; - } -#endif - Texture2D tex = (Texture2D)Resources.Load(_url, typeof(Texture2D)); - if (tex != null) - onExternalLoadSuccess(new NTexture(tex)); - else - onExternalLoadFailed(); - } - - virtual protected void FreeExternal(NTexture texture) - { -#if FAIRYGUI_PUERTS - if (__freeExternal != null) { - __freeExternal(texture); - return; - } -#endif - } - - public void onExternalLoadSuccess(NTexture texture) - { - _content.texture = texture; - sourceWidth = texture.width; - sourceHeight = texture.height; - _content.scale9Grid = null; - _content.scaleByTile = false; - texture.onSizeChanged += _reloadDelegate; - UpdateLayout(); - } - - public void onExternalLoadFailed() - { - SetErrorState(); - } - - void OnExternalReload(NTexture texture) - { - sourceWidth = texture.width; - sourceHeight = texture.height; - UpdateLayout(); - } - - private void SetErrorState() - { - if (!showErrorSign || !Application.isPlaying) - return; - - if (_errorSign == null) - { - if (UIConfig.loaderErrorSign != null) - _errorSign = UIPackage.CreateObjectFromURL(UIConfig.loaderErrorSign); - else - return; - } - - if (_errorSign != null) - { - _errorSign.SetSize(this.width, this.height); - ((Container)displayObject).AddChild(_errorSign.displayObject); - } - } - - protected void ClearErrorState() - { - if (_errorSign != null && _errorSign.displayObject.parent != null) - ((Container)displayObject).RemoveChild(_errorSign.displayObject); - } - - protected void UpdateLayout() - { - if (_content2 == null && _content.texture == null && _content.frames == null) - { - if (_autoSize) - { - _updatingLayout = true; - SetSize(50, 30); - _updatingLayout = false; - } - return; - } - - float contentWidth = sourceWidth; - float contentHeight = sourceHeight; - - if (_autoSize) - { - _updatingLayout = true; - if (contentWidth == 0) - contentWidth = 50; - if (contentHeight == 0) - contentHeight = 30; - SetSize(contentWidth, contentHeight); - - _updatingLayout = false; - - if (_width == contentWidth && _height == contentHeight) - { - if (_content2 != null) - { - _content2.SetXY(0, 0); - _content2.SetScale(1, 1); - } - else - { - _content.SetXY(0, 0); - _content.SetSize(contentWidth, contentHeight); - } - - InvalidateBatchingState(); - return; - } - //如果不相等,可能是由于大小限制造成的,要后续处理 - } - - float sx = 1, sy = 1; - if (_fill != FillType.None) - { - sx = this.width / sourceWidth; - sy = this.height / sourceHeight; - - if (sx != 1 || sy != 1) - { - if (_fill == FillType.ScaleMatchHeight) - sx = sy; - else if (_fill == FillType.ScaleMatchWidth) - sy = sx; - else if (_fill == FillType.Scale) - { - if (sx > sy) - sx = sy; - else - sy = sx; - } - else if (_fill == FillType.ScaleNoBorder) - { - if (sx > sy) - sy = sx; - else - sx = sy; - } - - if (_shrinkOnly) - { - if (sx > 1) - sx = 1; - if (sy > 1) - sy = 1; - } - - contentWidth = sourceWidth * sx; - contentHeight = sourceHeight * sy; - } - } - - if (_content2 != null) - _content2.SetScale(sx, sy); - else - _content.size = new Vector2(contentWidth, contentHeight); - - float nx; - float ny; - if (_align == AlignType.Center) - nx = (this.width - contentWidth) / 2; - else if (_align == AlignType.Right) - nx = this.width - contentWidth; - else - nx = 0; - if (_verticalAlign == VertAlignType.Middle) - ny = (this.height - contentHeight) / 2; - else if (_verticalAlign == VertAlignType.Bottom) - ny = this.height - contentHeight; - else - ny = 0; - if (_content2 != null) - _content2.SetXY(nx, ny); - else - _content.SetXY(nx, ny); - - InvalidateBatchingState(); - } - - private void ClearContent() - { - ClearErrorState(); - - if (_content.texture != null) - { - if (_contentItem == null) - { - _content.texture.onSizeChanged -= _reloadDelegate; - FreeExternal(_content.texture); - } - _content.texture = null; - } - _content.frames = null; - - if (_content2 != null) - { - _content2.Dispose(); - _content2 = null; - } - _contentItem = null; - } - - override protected void HandleSizeChanged() - { - base.HandleSizeChanged(); - - if (!_updatingLayout) - UpdateLayout(); - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - _url = buffer.ReadS(); - _align = (AlignType)buffer.ReadByte(); - _verticalAlign = (VertAlignType)buffer.ReadByte(); - _fill = (FillType)buffer.ReadByte(); - _shrinkOnly = buffer.ReadBool(); - _autoSize = buffer.ReadBool(); - showErrorSign = buffer.ReadBool(); - _content.playing = buffer.ReadBool(); - _content.frame = buffer.ReadInt(); - - if (buffer.ReadBool()) - _content.color = buffer.ReadColor(); - _content.fillMethod = (FillMethod)buffer.ReadByte(); - if (_content.fillMethod != FillMethod.None) - { - _content.fillOrigin = buffer.ReadByte(); - _content.fillClockwise = buffer.ReadBool(); - _content.fillAmount = buffer.ReadFloat(); - } - - if (!string.IsNullOrEmpty(_url)) - LoadContent(); - } - } -} +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GLoader class + /// + public class GLoader : GObject, IAnimationGear, IColorGear + { + /// + /// Display an error sign if the loader fails to load the content. + /// UIConfig.loaderErrorSign muse be set. + /// + public bool showErrorSign; + + string _url; + AlignType _align; + VertAlignType _verticalAlign; + bool _autoSize; + FillType _fill; + bool _shrinkOnly; + bool _updatingLayout; + PackageItem _contentItem; + Action _reloadDelegate; + + MovieClip _content; + GObject _errorSign; + GComponent _content2; + +#if FAIRYGUI_PUERTS + public Action __loadExternal; + public Action __freeExternal; +#endif + + public GLoader() + { + _url = string.Empty; + _align = AlignType.Left; + _verticalAlign = VertAlignType.Top; + showErrorSign = true; + _reloadDelegate = OnExternalReload; + } + + override protected void CreateDisplayObject() + { + displayObject = new Container("GLoader"); + displayObject.gOwner = this; + _content = new MovieClip(); + ((Container)displayObject).AddChild(_content); + ((Container)displayObject).opaque = true; + } + + override public void Dispose() + { + if (_disposed) return; + + if (_content.texture != null) + { + if (_contentItem == null) + { + _content.texture.onSizeChanged -= _reloadDelegate; + try + { + FreeExternal(_content.texture); + } + catch (Exception err) + { + Debug.LogWarning(err); + } + } + } + if (_errorSign != null) + _errorSign.Dispose(); + if (_content2 != null) + _content2.Dispose(); + _content.Dispose(); + + base.Dispose(); + } + + /// + /// + /// + public string url + { + get { return _url; } + set + { + if (_url == value) + return; + + ClearContent(); + _url = value; + LoadContent(); + UpdateGear(7); + } + } + + override public string icon + { + get { return _url; } + set { this.url = value; } + } + + /// + /// + /// + public AlignType align + { + get { return _align; } + set + { + if (_align != value) + { + _align = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _verticalAlign; } + set + { + if (_verticalAlign != value) + { + _verticalAlign = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public FillType fill + { + get { return _fill; } + set + { + if (_fill != value) + { + _fill = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool shrinkOnly + { + get { return _shrinkOnly; } + set + { + if (_shrinkOnly != value) + { + _shrinkOnly = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool autoSize + { + get { return _autoSize; } + set + { + if (_autoSize != value) + { + _autoSize = value; + UpdateLayout(); + } + } + } + + /// + /// + /// + public bool playing + { + get { return _content.playing; } + set + { + _content.playing = value; + UpdateGear(5); + } + } + + /// + /// + /// + public int frame + { + get { return _content.frame; } + set + { + _content.frame = value; + UpdateGear(5); + } + } + + /// + /// + /// + public float timeScale + { + get { return _content.timeScale; } + set { _content.timeScale = value; } + } + + /// + /// + /// + public bool ignoreEngineTimeScale + { + get { return _content.ignoreEngineTimeScale; } + set { _content.ignoreEngineTimeScale = value; } + } + + /// + /// + /// + /// + public void Advance(float time) + { + _content.Advance(time); + } + + /// + /// + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + /// + /// + /// + public Color color + { + get { return _content.color; } + set + { + if (_content.color != value) + { + _content.color = value; + UpdateGear(4); + } + } + } + + /// + /// + /// + public FillMethod fillMethod + { + get { return _content.fillMethod; } + set { _content.fillMethod = value; } + } + + /// + /// + /// + public int fillOrigin + { + get { return _content.fillOrigin; } + set { _content.fillOrigin = value; } + } + + /// + /// + /// + public bool fillClockwise + { + get { return _content.fillClockwise; } + set { _content.fillClockwise = value; } + } + + /// + /// + /// + public float fillAmount + { + get { return _content.fillAmount; } + set { _content.fillAmount = value; } + } + + /// + /// + /// + public Image image + { + get { return _content; } + } + + /// + /// + /// + public MovieClip movieClip + { + get { return _content; } + } + + /// + /// + /// + public GComponent component + { + get { return _content2; } + } + + /// + /// + /// + public NTexture texture + { + get + { + return _content.texture; + } + + set + { + this.url = null; + + _content.texture = value; + if (value != null) + { + sourceWidth = value.width; + sourceHeight = value.height; + } + else + { + sourceWidth = sourceHeight = 0; + } + + UpdateLayout(); + } + } + + override public IFilter filter + { + get { return _content.filter; } + set { _content.filter = value; } + } + + override public BlendMode blendMode + { + get { return _content.blendMode; } + set { _content.blendMode = value; } + } + + /// + /// + /// + protected void LoadContent() + { + ClearContent(); + + if (string.IsNullOrEmpty(_url)) + return; + + if (_url.StartsWith(UIPackage.URL_PREFIX)) + LoadFromPackage(_url); + else + LoadExternal(); + } + + protected void LoadFromPackage(string itemURL) + { + _contentItem = UIPackage.GetItemByURL(itemURL); + + if (_contentItem != null) + { + _contentItem = _contentItem.getBranch(); + sourceWidth = _contentItem.width; + sourceHeight = _contentItem.height; + _contentItem = _contentItem.getHighResolution(); + _contentItem.Load(); + + if (_contentItem.type == PackageItemType.Image) + { + _content.texture = _contentItem.texture; + _content.textureScale = new Vector2(_contentItem.width / (float)sourceWidth, _contentItem.height / (float)sourceHeight); + _content.scale9Grid = _contentItem.scale9Grid; + _content.scaleByTile = _contentItem.scaleByTile; + _content.tileGridIndice = _contentItem.tileGridIndice; + + UpdateLayout(); + } + else if (_contentItem.type == PackageItemType.MovieClip) + { + _content.interval = _contentItem.interval; + _content.swing = _contentItem.swing; + _content.repeatDelay = _contentItem.repeatDelay; + _content.frames = _contentItem.frames; + + UpdateLayout(); + } + else if (_contentItem.type == PackageItemType.Component) + { + GObject obj = UIPackage.CreateObjectFromURL(itemURL); + if (obj == null) + SetErrorState(); + else if (!(obj is GComponent)) + { + obj.Dispose(); + SetErrorState(); + } + else + { + _content2 = (GComponent)obj; + ((Container)displayObject).AddChild(_content2.displayObject); + UpdateLayout(); + } + } + else + { + if (_autoSize) + this.SetSize(_contentItem.width, _contentItem.height); + + SetErrorState(); + + Debug.LogWarning("Unsupported type of GLoader: " + _contentItem.type); + } + } + else + SetErrorState(); + } + + virtual protected void LoadExternal() + { +#if FAIRYGUI_PUERTS + if (__loadExternal != null) { + __loadExternal(); + return; + } +#endif + Texture2D tex = (Texture2D)Resources.Load(_url, typeof(Texture2D)); + if (tex != null) + onExternalLoadSuccess(new NTexture(tex)); + else + onExternalLoadFailed(); + } + + virtual protected void FreeExternal(NTexture texture) + { +#if FAIRYGUI_PUERTS + if (__freeExternal != null) { + __freeExternal(texture); + return; + } +#endif + } + + public void onExternalLoadSuccess(NTexture texture) + { + _content.texture = texture; + sourceWidth = texture.width; + sourceHeight = texture.height; + _content.scale9Grid = null; + _content.scaleByTile = false; + texture.onSizeChanged += _reloadDelegate; + UpdateLayout(); + } + + public void onExternalLoadFailed() + { + SetErrorState(); + } + + void OnExternalReload(NTexture texture) + { + sourceWidth = texture.width; + sourceHeight = texture.height; + UpdateLayout(); + } + + private void SetErrorState() + { + if (!showErrorSign || !Application.isPlaying) + return; + + if (_errorSign == null) + { + if (UIConfig.loaderErrorSign != null) + _errorSign = UIPackage.CreateObjectFromURL(UIConfig.loaderErrorSign); + else + return; + } + + if (_errorSign != null) + { + _errorSign.SetSize(this.width, this.height); + ((Container)displayObject).AddChild(_errorSign.displayObject); + } + } + + protected void ClearErrorState() + { + if (_errorSign != null && _errorSign.displayObject.parent != null) + ((Container)displayObject).RemoveChild(_errorSign.displayObject); + } + + protected void UpdateLayout() + { + if (_content2 == null && _content.texture == null && _content.frames == null) + { + if (_autoSize) + { + _updatingLayout = true; + SetSize(50, 30); + _updatingLayout = false; + } + return; + } + + float contentWidth = sourceWidth; + float contentHeight = sourceHeight; + + if (_autoSize) + { + _updatingLayout = true; + if (contentWidth == 0) + contentWidth = 50; + if (contentHeight == 0) + contentHeight = 30; + SetSize(contentWidth, contentHeight); + + _updatingLayout = false; + + if (_width == contentWidth && _height == contentHeight) + { + if (_content2 != null) + { + _content2.SetXY(0, 0); + _content2.SetScale(1, 1); + } + else + { + _content.SetXY(0, 0); + _content.SetSize(contentWidth, contentHeight); + } + + InvalidateBatchingState(); + return; + } + //如果不相等,可能是由于大小限制造成的,要后续处理 + } + + float sx = 1, sy = 1; + if (_fill != FillType.None) + { + sx = this.width / sourceWidth; + sy = this.height / sourceHeight; + + if (sx != 1 || sy != 1) + { + if (_fill == FillType.ScaleMatchHeight) + sx = sy; + else if (_fill == FillType.ScaleMatchWidth) + sy = sx; + else if (_fill == FillType.Scale) + { + if (sx > sy) + sx = sy; + else + sy = sx; + } + else if (_fill == FillType.ScaleNoBorder) + { + if (sx > sy) + sy = sx; + else + sx = sy; + } + + if (_shrinkOnly) + { + if (sx > 1) + sx = 1; + if (sy > 1) + sy = 1; + } + + contentWidth = sourceWidth * sx; + contentHeight = sourceHeight * sy; + } + } + + if (_content2 != null) + _content2.SetScale(sx, sy); + else + _content.size = new Vector2(contentWidth, contentHeight); + + float nx; + float ny; + if (_align == AlignType.Center) + nx = (this.width - contentWidth) / 2; + else if (_align == AlignType.Right) + nx = this.width - contentWidth; + else + nx = 0; + if (_verticalAlign == VertAlignType.Middle) + ny = (this.height - contentHeight) / 2; + else if (_verticalAlign == VertAlignType.Bottom) + ny = this.height - contentHeight; + else + ny = 0; + if (_content2 != null) + _content2.SetXY(nx, ny); + else + _content.SetXY(nx, ny); + + InvalidateBatchingState(); + } + + private void ClearContent() + { + ClearErrorState(); + + if (_content.texture != null) + { + if (_contentItem == null) + { + _content.texture.onSizeChanged -= _reloadDelegate; + FreeExternal(_content.texture); + } + _content.texture = null; + } + _content.frames = null; + + if (_content2 != null) + { + _content2.Dispose(); + _content2 = null; + } + _contentItem = null; + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (!_updatingLayout) + UpdateLayout(); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + _url = buffer.ReadS(); + _align = (AlignType)buffer.ReadByte(); + _verticalAlign = (VertAlignType)buffer.ReadByte(); + _fill = (FillType)buffer.ReadByte(); + _shrinkOnly = buffer.ReadBool(); + _autoSize = buffer.ReadBool(); + showErrorSign = buffer.ReadBool(); + _content.playing = buffer.ReadBool(); + _content.frame = buffer.ReadInt(); + + if (buffer.ReadBool()) + _content.color = buffer.ReadColor(); + _content.fillMethod = (FillMethod)buffer.ReadByte(); + if (_content.fillMethod != FillMethod.None) + { + _content.fillOrigin = buffer.ReadByte(); + _content.fillClockwise = buffer.ReadBool(); + _content.fillAmount = buffer.ReadFloat(); + } + + if (!string.IsNullOrEmpty(_url)) + LoadContent(); + } + } +} diff --git a/Assets/Scripts/UI/GLoader.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader.cs.meta similarity index 100% rename from Assets/Scripts/UI/GLoader.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader.cs.meta diff --git a/Assets/Scripts/UI/GLoader3D.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader3D.cs similarity index 100% rename from Assets/Scripts/UI/GLoader3D.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader3D.cs diff --git a/Assets/Scripts/UI/GLoader3D.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader3D.cs.meta similarity index 100% rename from Assets/Scripts/UI/GLoader3D.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GLoader3D.cs.meta diff --git a/Assets/Scripts/UI/GMovieClip.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GMovieClip.cs similarity index 96% rename from Assets/Scripts/UI/GMovieClip.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GMovieClip.cs index f4fdd986..1697a935 100644 --- a/Assets/Scripts/UI/GMovieClip.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GMovieClip.cs @@ -1,190 +1,190 @@ -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GMovieClip class. - /// - public class GMovieClip : GObject, IAnimationGear, IColorGear - { - MovieClip _content; - EventListener _onPlayEnd; - - public GMovieClip() - { - } - - override protected void CreateDisplayObject() - { - _content = new MovieClip(); - _content.gOwner = this; - _content.ignoreEngineTimeScale = true; - displayObject = _content; - } - - /// - /// - /// - public EventListener onPlayEnd - { - get { return _onPlayEnd ?? (_onPlayEnd = new EventListener(this, "onPlayEnd")); } - } - - /// - /// - /// - public bool playing - { - get { return _content.playing; } - set - { - _content.playing = value; - UpdateGear(5); - } - } - - /// - /// - /// - public int frame - { - get { return _content.frame; } - set - { - _content.frame = value; - UpdateGear(5); - } - } - - /// - /// - /// - public Color color - { - get { return _content.color; } - set - { - _content.color = value; - UpdateGear(4); - } - } - - /// - /// - /// - public FlipType flip - { - get { return _content.graphics.flip; } - set { _content.graphics.flip = value; } - } - - /// - /// - /// - public Material material - { - get { return _content.material; } - set { _content.material = value; } - } - - /// - /// - /// - public string shader - { - get { return _content.shader; } - set { _content.shader = value; } - } - - /// - /// - /// - public float timeScale - { - get { return _content.timeScale; } - set { _content.timeScale = value; } - } - - /// - /// - /// - public bool ignoreEngineTimeScale - { - get { return _content.ignoreEngineTimeScale; } - set { _content.ignoreEngineTimeScale = value; } - } - - /// - /// - /// - public void Rewind() - { - _content.Rewind(); - } - - /// - /// - /// - /// - public void SyncStatus(GMovieClip anotherMc) - { - _content.SyncStatus(anotherMc._content); - } - - /// - /// - /// - /// - public void Advance(float time) - { - _content.Advance(time); - } - - /// - /// Play from the start to end, repeat times, set to endAt on complete. - /// 从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) - /// - /// Start frame - /// End frame. -1 indicates the last frame. - /// Repeat times. 0 indicates infinite loop. - /// Stop frame. -1 indicates to equal to the end parameter. - public void SetPlaySettings(int start, int end, int times, int endAt) - { - ((MovieClip)displayObject).SetPlaySettings(start, end, times, endAt); - } - - override public void ConstructFromResource() - { - this.gameObjectName = packageItem.name; - - PackageItem contentItem = packageItem.getBranch(); - sourceWidth = contentItem.width; - sourceHeight = contentItem.height; - initWidth = sourceWidth; - initHeight = sourceHeight; - contentItem = contentItem.getHighResolution(); - contentItem.Load(); - - _content.interval = contentItem.interval; - _content.swing = contentItem.swing; - _content.repeatDelay = contentItem.repeatDelay; - _content.frames = contentItem.frames; - - SetSize(sourceWidth, sourceHeight); - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - if (buffer.ReadBool()) - _content.color = buffer.ReadColor(); - _content.graphics.flip = (FlipType)buffer.ReadByte(); - _content.frame = buffer.ReadInt(); - _content.playing = buffer.ReadBool(); - } - } -} +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GMovieClip class. + /// + public class GMovieClip : GObject, IAnimationGear, IColorGear + { + MovieClip _content; + EventListener _onPlayEnd; + + public GMovieClip() + { + } + + override protected void CreateDisplayObject() + { + _content = new MovieClip(); + _content.gOwner = this; + _content.ignoreEngineTimeScale = true; + displayObject = _content; + } + + /// + /// + /// + public EventListener onPlayEnd + { + get { return _onPlayEnd ?? (_onPlayEnd = new EventListener(this, "onPlayEnd")); } + } + + /// + /// + /// + public bool playing + { + get { return _content.playing; } + set + { + _content.playing = value; + UpdateGear(5); + } + } + + /// + /// + /// + public int frame + { + get { return _content.frame; } + set + { + _content.frame = value; + UpdateGear(5); + } + } + + /// + /// + /// + public Color color + { + get { return _content.color; } + set + { + _content.color = value; + UpdateGear(4); + } + } + + /// + /// + /// + public FlipType flip + { + get { return _content.graphics.flip; } + set { _content.graphics.flip = value; } + } + + /// + /// + /// + public Material material + { + get { return _content.material; } + set { _content.material = value; } + } + + /// + /// + /// + public string shader + { + get { return _content.shader; } + set { _content.shader = value; } + } + + /// + /// + /// + public float timeScale + { + get { return _content.timeScale; } + set { _content.timeScale = value; } + } + + /// + /// + /// + public bool ignoreEngineTimeScale + { + get { return _content.ignoreEngineTimeScale; } + set { _content.ignoreEngineTimeScale = value; } + } + + /// + /// + /// + public void Rewind() + { + _content.Rewind(); + } + + /// + /// + /// + /// + public void SyncStatus(GMovieClip anotherMc) + { + _content.SyncStatus(anotherMc._content); + } + + /// + /// + /// + /// + public void Advance(float time) + { + _content.Advance(time); + } + + /// + /// Play from the start to end, repeat times, set to endAt on complete. + /// 从start帧开始,播放到end帧(-1表示结尾),重复times次(0表示无限循环),循环结束后,停止在endAt帧(-1表示参数end) + /// + /// Start frame + /// End frame. -1 indicates the last frame. + /// Repeat times. 0 indicates infinite loop. + /// Stop frame. -1 indicates to equal to the end parameter. + public void SetPlaySettings(int start, int end, int times, int endAt) + { + ((MovieClip)displayObject).SetPlaySettings(start, end, times, endAt); + } + + override public void ConstructFromResource() + { + this.gameObjectName = packageItem.name; + + PackageItem contentItem = packageItem.getBranch(); + sourceWidth = contentItem.width; + sourceHeight = contentItem.height; + initWidth = sourceWidth; + initHeight = sourceHeight; + contentItem = contentItem.getHighResolution(); + contentItem.Load(); + + _content.interval = contentItem.interval; + _content.swing = contentItem.swing; + _content.repeatDelay = contentItem.repeatDelay; + _content.frames = contentItem.frames; + + SetSize(sourceWidth, sourceHeight); + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + if (buffer.ReadBool()) + _content.color = buffer.ReadColor(); + _content.graphics.flip = (FlipType)buffer.ReadByte(); + _content.frame = buffer.ReadInt(); + _content.playing = buffer.ReadBool(); + } + } +} diff --git a/Assets/Scripts/UI/GMovieClip.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GMovieClip.cs.meta similarity index 100% rename from Assets/Scripts/UI/GMovieClip.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GMovieClip.cs.meta diff --git a/Assets/Scripts/UI/GObject.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObject.cs similarity index 96% rename from Assets/Scripts/UI/GObject.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObject.cs index 55431701..941b3f58 100644 --- a/Assets/Scripts/UI/GObject.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObject.cs @@ -1,2179 +1,2179 @@ -using System; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - public class GObject : EventDispatcher - { - /// - /// GObject的id,仅作为内部使用。与name不同,id值是不会相同的。 - /// id is for internal use only. - /// - public string id { get; private set; } - - /// - /// Name of the object. - /// - public string name; - - /// - /// User defined data. - /// - public object data; - - /// - /// The source width of the object. - /// - public int sourceWidth; - - /// - /// The source height of the object. - /// - public int sourceHeight; - - /// - /// The initial width of the object. - /// - public int initWidth; - - /// - /// The initial height of the object. - /// - public int initHeight; - - /// - /// - /// - public int minWidth; - - /// - /// - /// - public int maxWidth; - - /// - /// - /// - public int minHeight; - - /// - /// - /// - public int maxHeight; - - /// - /// Relations Object. - /// - public Relations relations { get; private set; } - - /// - /// Restricted range of dragging. - /// - public Rect? dragBounds; - - /// - /// Parent object. - /// - public GComponent parent { get; private set; } - - /// - /// Lowlevel display object. - /// - public DisplayObject displayObject { get; protected set; } - - /// - /// 当前全局正在被拖动的对象 - /// - public static GObject draggingObject { get; private set; } - - /// - /// - /// - public PackageItem packageItem; - - float _x; - float _y; - float _z; - float _pivotX; - float _pivotY; - bool _pivotAsAnchor; - float _alpha; - float _rotation; - float _rotationX; - float _rotationY; - bool _visible; - bool _internalVisible; - bool _handlingController; - bool _touchable; - bool _grayed; - bool _draggable; - float _scaleX; - float _scaleY; - int _sortingOrder; - string _tooltips; - GGroup _group; - - GearBase[] _gears; - - EventListener _onClick; - EventListener _onRightClick; - EventListener _onTouchBegin; - EventListener _onTouchMove; - EventListener _onTouchEnd; - EventListener _onRollOver; - EventListener _onRollOut; - EventListener _onAddedToStage; - EventListener _onRemovedFromStage; - EventListener _onKeyDown; - EventListener _onClickLink; - EventListener _onPositionChanged; - EventListener _onSizeChanged; - EventListener _onDragStart; - EventListener _onDragMove; - EventListener _onDragEnd; - EventListener _onGearStop; - EventListener _onFocusIn; - EventListener _onFocusOut; - - internal protected bool underConstruct; - internal float _width; - internal float _height; - internal float _rawWidth; - internal float _rawHeight; - internal bool _gearLocked; - internal float _sizePercentInGroup; - internal bool _disposed; - internal GTreeNode _treeNode; - - internal static uint _gInstanceCounter; - - public GObject() - { - _width = 0; - _height = 0; - _alpha = 1; - _visible = true; - _touchable = true; - _scaleX = 1; - _scaleY = 1; - _internalVisible = true; - id = "_n" + _gInstanceCounter++; - name = string.Empty; - - CreateDisplayObject(); - - relations = new Relations(this); - _gears = new GearBase[10]; - } - - /// - /// Dispatched when the object or its child was clicked. - /// - public EventListener onClick - { - get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } - } - - /// - /// Dispatched when the object or its child was clicked by right mouse button. Web only. - /// - public EventListener onRightClick - { - get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } - } - - /// - /// Dispatched when the finger touched the object or its child just now. - /// - public EventListener onTouchBegin - { - get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } - } - - /// - /// - /// - public EventListener onTouchMove - { - get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } - } - - /// - /// Dispatched when the finger was lifted from the screen or from the mouse button. - /// - public EventListener onTouchEnd - { - get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } - } - - /// - /// The cursor or finger hovers over an object. - /// - public EventListener onRollOver - { - get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } - } - - /// - /// The cursor or finger leave an object. - /// - public EventListener onRollOut - { - get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } - } - - /// - /// Dispatched when the object was added to the stage. - /// - public EventListener onAddedToStage - { - get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } - } - - /// - /// Dispatched when the object was removed from the stage. - /// - public EventListener onRemovedFromStage - { - get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } - } - - /// - /// Dispatched on key pressed when the object is in focus. - /// - public EventListener onKeyDown - { - get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } - } - - /// - /// Dispatched when links in the object or its child was clicked. - /// - public EventListener onClickLink - { - get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } - } - - /// - /// Dispatched when the object was moved. - /// - public EventListener onPositionChanged - { - get { return _onPositionChanged ?? (_onPositionChanged = new EventListener(this, "onPositionChanged")); } - } - - /// - /// Dispatched when the object was resized. - /// - public EventListener onSizeChanged - { - get { return _onSizeChanged ?? (_onSizeChanged = new EventListener(this, "onSizeChanged")); } - } - - /// - /// Dispatched when drag start. - /// - public EventListener onDragStart - { - get { return _onDragStart ?? (_onDragStart = new EventListener(this, "onDragStart")); } - } - - /// - /// Dispatched when dragging. - /// - public EventListener onDragMove - { - get { return _onDragMove ?? (_onDragMove = new EventListener(this, "onDragMove")); } - } - - /// - /// Dispatched when drag end. - /// - public EventListener onDragEnd - { - get { return _onDragEnd ?? (_onDragEnd = new EventListener(this, "onDragEnd")); } - } - - /// - /// - /// - public EventListener onGearStop - { - get { return _onGearStop ?? (_onGearStop = new EventListener(this, "onGearStop")); } - } - - /// - /// - /// - public EventListener onFocusIn - { - get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } - } - - /// - /// - /// - public EventListener onFocusOut - { - get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } - } - - /// - /// The x coordinate of the object relative to the local coordinates of the parent. - /// - public float x - { - get { return _x; } - set - { - SetPosition(value, _y, _z); - } - } - - /// - /// The y coordinate of the object relative to the local coordinates of the parent. - /// - public float y - { - get { return _y; } - set - { - SetPosition(_x, value, _z); - } - } - - /// - /// The z coordinate of the object relative to the local coordinates of the parent. - /// - public float z - { - get { return _z; } - set - { - SetPosition(_x, _y, value); - } - } - - /// - /// The x and y coordinates of the object relative to the local coordinates of the parent. - /// - public Vector2 xy - { - get { return new Vector2(_x, _y); } - set { SetPosition(value.x, value.y, _z); } - } - - /// - /// The x,y,z coordinates of the object relative to the local coordinates of the parent. - /// - public Vector3 position - { - get { return new Vector3(_x, _y, _z); } - set { SetPosition(value.x, value.y, value.z); } - } - - /// - /// change the x and y coordinates of the object relative to the local coordinates of the parent. - /// - /// x value. - /// y value. - public void SetXY(float xv, float yv) - { - SetPosition(xv, yv, _z); - } - - /// - /// - /// - /// - /// - /// - public void SetXY(float xv, float yv, bool topLeftValue) - { - if (_pivotAsAnchor) - SetPosition(xv + _pivotX * _width, yv + _pivotY * _height, _z); - else - SetPosition(xv, yv, _z); - } - - /// - /// change the x,y,z coordinates of the object relative to the local coordinates of the parent. - /// - /// x value. - /// y value. - /// z value. - public void SetPosition(float xv, float yv, float zv) - { - if (_x != xv || _y != yv || _z != zv) - { - float dx = xv - _x; - float dy = yv - _y; - _x = xv; - _y = yv; - _z = zv; - - HandlePositionChanged(); - - if (this is GGroup) - ((GGroup)this).MoveChildren(dx, dy); - - UpdateGear(1); - - if (parent != null && !(parent is GList)) - { - parent.SetBoundsChangedFlag(); - if (_group != null) - _group.SetBoundsChangedFlag(true); - DispatchEvent("onPositionChanged", null); - } - - if (draggingObject == this && !sUpdateInDragging) - sGlobalRect = this.LocalToGlobal(new Rect(0, 0, this.width, this.height)); - } - } - - [Obsolete("Use UIConfig.makePixelPerfect or DisplayObject.pixelPerfect")] - public bool pixelSnapping - { - get { return false; } - set { } - } - - /// - /// Set the object in middle of the parent or GRoot if the parent is not set. - /// - public void Center() - { - Center(false); - } - - /// - /// Set the object in middle of the parent or GRoot if the parent is not set. - /// - /// Add relations to maintain the center state. - public void Center(bool restraint) - { - GComponent r; - if (parent != null) - r = parent; - else - r = this.root; - - this.SetXY((int)((r.width - this.width) / 2), (int)((r.height - this.height) / 2), true); - if (restraint) - { - this.AddRelation(r, RelationType.Center_Center); - this.AddRelation(r, RelationType.Middle_Middle); - } - } - - /// - /// 设置对象为全屏大小(逻辑屏幕)。 - /// - public void MakeFullScreen() - { - this.SetSize(GRoot.inst.width, GRoot.inst.height); - } - - /// - /// The width of the object in pixels. - /// - public float width - { - get - { - return _width; - } - set - { - SetSize(value, _rawHeight); - } - } - - /// - /// The height of the object in pixels. - /// - public float height - { - get - { - return _height; - } - set - { - SetSize(_rawWidth, value); - } - } - - /// - /// The size of the object in pixels. - /// - public Vector2 size - { - get { return new Vector2(width, height); } - set { SetSize(value.x, value.y); } - } - - /// - /// actualWidth = width * scalex - /// - public float actualWidth - { - get { return this.width * _scaleX; } - } - - /// - /// actualHeight = height * scaleY - /// - public float actualHeight - { - get { return this.height * _scaleY; } - } - - /// - /// Change size. - /// - /// Width value. - /// Height value. - public void SetSize(float wv, float hv) - { - SetSize(wv, hv, false); - } - - /// - /// Change size. - /// - /// Width value. - /// Height value. - /// If pivot is set, the object's positon will change when its size change. Set ignorePivot=true to keep the position. - public void SetSize(float wv, float hv, bool ignorePivot) - { - if (_rawWidth != wv || _rawHeight != hv) - { - _rawWidth = wv; - _rawHeight = hv; - if (wv < minWidth) - wv = minWidth; - else if (maxWidth > 0 && wv > maxWidth) - wv = maxWidth; - if (hv < minHeight) - hv = minHeight; - else if (maxHeight > 0 && hv > maxHeight) - hv = maxHeight; - float dWidth = wv - _width; - float dHeight = hv - _height; - _width = wv; - _height = hv; - - HandleSizeChanged(); - - if (_pivotX != 0 || _pivotY != 0) - { - if (!_pivotAsAnchor) - { - if (!ignorePivot) - SetXY(_x - _pivotX * dWidth, _y - _pivotY * dHeight); - else - HandlePositionChanged(); - } - else - HandlePositionChanged(); - } - - if (this is GGroup) - ((GGroup)this).ResizeChildren(dWidth, dHeight); - - UpdateGear(2); - - if (parent != null) - { - relations.OnOwnerSizeChanged(dWidth, dHeight, _pivotAsAnchor || !ignorePivot); - parent.SetBoundsChangedFlag(); - if (_group != null) - _group.SetBoundsChangedFlag(); - } - - DispatchEvent("onSizeChanged", null); - } - } - - protected void SetSizeDirectly(float wv, float hv) - { - _rawWidth = wv; - _rawHeight = hv; - if (wv < 0) - wv = 0; - if (hv < 0) - hv = 0; - _width = wv; - _height = hv; - } - - /// - /// - /// - public float xMin - { - get - { - return _pivotAsAnchor ? (_x - _width * _pivotX) : _x; - } - set - { - if (_pivotAsAnchor) - SetPosition(value + _width * _pivotX, _y, _z); - else - SetPosition(value, _y, _z); - } - } - - /// - /// - /// - public float yMin - { - get - { - return _pivotAsAnchor ? (_y - _height * _pivotY) : _y; - } - set - { - if (_pivotAsAnchor) - SetPosition(_x, value + _height * _pivotY, _z); - else - SetPosition(_x, value, _z); - } - } - - /// - /// The horizontal scale factor. '1' means no scale, cannt be negative. - /// - public float scaleX - { - get { return _scaleX; } - set - { - SetScale(value, _scaleY); - } - } - - /// - /// The vertical scale factor. '1' means no scale, cannt be negative. - /// - public float scaleY - { - get { return _scaleY; } - set - { - SetScale(_scaleX, value); - } - } - - /// - /// The scale factor. - /// - public Vector2 scale - { - get { return new Vector2(_scaleX, _scaleY); } - set { SetScale(value.x, value.y); } - } - - /// - /// Change the scale factor. - /// - /// The horizontal scale factor. - /// The vertical scale factor - public void SetScale(float wv, float hv) - { - if (_scaleX != wv || _scaleY != hv) - { - _scaleX = wv; - _scaleY = hv; - HandleScaleChanged(); - - UpdateGear(2); - } - } - - /// - /// - /// - public Vector2 skew - { - get - { - if (displayObject != null) - return displayObject.skew; - else - return Vector2.zero; - } - - set - { - if (displayObject != null) - displayObject.skew = value; - } - } - - /// - /// The x coordinate of the object's origin in its own coordinate space. - /// - public float pivotX - { - get { return _pivotX; } - set - { - SetPivot(value, _pivotY, _pivotAsAnchor); - } - } - - /// - /// The y coordinate of the object's origin in its own coordinate space. - /// - public float pivotY - { - get { return _pivotY; } - set - { - SetPivot(_pivotX, value, _pivotAsAnchor); - } - } - - /// - /// The x and y coordinates of the object's origin in its own coordinate space. - /// - public Vector2 pivot - { - get { return new Vector2(_pivotX, _pivotY); } - set { SetPivot(value.x, value.y, _pivotAsAnchor); } - } - - public bool pivotAsAnchor - { - get { return _pivotAsAnchor; } - set - { - SetPivot(_pivotX, _pivotY, value); - } - } - - /// - /// Change the x and y coordinates of the object's origin in its own coordinate space. - /// - /// x value in ratio - /// y value in ratio - public void SetPivot(float xv, float yv) - { - SetPivot(xv, yv, false); - } - - /// - /// Change the x and y coordinates of the object's origin in its own coordinate space. - /// - /// x value in ratio - /// y value in ratio - /// If use the pivot as the anchor position - public void SetPivot(float xv, float yv, bool asAnchor) - { - if (_pivotX != xv || _pivotY != yv || _pivotAsAnchor != asAnchor) - { - _pivotX = xv; - _pivotY = yv; - _pivotAsAnchor = asAnchor; - if (displayObject != null) - displayObject.pivot = new Vector2(_pivotX, _pivotY); - HandlePositionChanged(); - } - } - - /// - /// If the object can touch or click. GImage/GTextField is not touchable even it is true. - /// - public bool touchable - { - get - { - return _touchable; - } - set - { - if (_touchable != value) - { - _touchable = value; - UpdateGear(3); - - if (displayObject != null) - displayObject.touchable = _touchable; - } - } - } - - /// - /// If true, apply a grayed effect on this object. - /// - public bool grayed - { - get - { - return _grayed; - } - set - { - if (_grayed != value) - { - _grayed = value; - HandleGrayedChanged(); - UpdateGear(3); - } - } - } - - /// - /// Enabled is shortcut for grayed and !touchable combination. - /// - public bool enabled - { - get - { - return !_grayed && _touchable; - } - set - { - this.grayed = !value; - this.touchable = value; - } - } - - /// - /// The rotation around the z axis of the object in degrees. - /// - public float rotation - { - get - { - return _rotation; - } - set - { - _rotation = value; - if (displayObject != null) - displayObject.rotation = _rotation; - UpdateGear(3); - } - } - - /// - /// The rotation around the x axis of the object in degrees. - /// - public float rotationX - { - get - { - return _rotationX; - } - set - { - _rotationX = value; - if (displayObject != null) - displayObject.rotationX = _rotationX; - } - } - - /// - /// The rotation around the y axis of the object in degrees. - /// - public float rotationY - { - get - { - return _rotationY; - } - set - { - _rotationY = value; - if (displayObject != null) - displayObject.rotationY = _rotationY; - } - } - - /// - /// The opacity of the object. 0 = transparent, 1 = opaque. - /// - public float alpha - { - - get - { - return _alpha; - } - - set - { - _alpha = value; - HandleAlphaChanged(); - UpdateGear(3); - } - } - - /// - /// The visibility of the object. An invisible object will be untouchable. - /// - public bool visible - { - get - { - return _visible; - } - - set - { - if (_visible != value) - { - _visible = value; - HandleVisibleChanged(); - if (parent != null) - parent.SetBoundsChangedFlag(); - if (_group != null && _group.excludeInvisibles) - _group.SetBoundsChangedFlag(); - } - } - } - - internal bool internalVisible - { - get - { - return _internalVisible && (group == null || group.internalVisible); - } - } - - internal bool internalVisible2 - { - get - { - return _visible && (group == null || group.internalVisible2); - } - } - - internal bool internalVisible3 - { - get - { - return _visible && _internalVisible; - } - } - - /// - /// By default(when sortingOrder==0), object added to component is arrange by the added roder. - /// The bigger is the sorting order, the object is more in front. - /// - public int sortingOrder - { - get { return _sortingOrder; } - set - { - if (value < 0) - value = 0; - if (_sortingOrder != value) - { - int old = _sortingOrder; - _sortingOrder = value; - if (parent != null) - parent.ChildSortingOrderChanged(this, old, _sortingOrder); - } - } - } - - /// - /// If the object can be focused? - /// - public bool focusable - { - get { return displayObject != null && displayObject.focusable; } - set { if (displayObject != null) displayObject.focusable = value; } - } - - /// - /// If the object can be navigated by TAB? - /// - public bool tabStop - { - get { return displayObject != null && displayObject.tabStop; } - set { if (displayObject != null) displayObject.tabStop = value; } - } - - /// - /// If the object is focused. - /// - public bool focused - { - get { return displayObject != null && displayObject.focused; } - } - - /// - /// Request focus on this object. - /// - public void RequestFocus() - { - if (displayObject != null) - Stage.inst.SetFocus(displayObject, false); - } - - /// - /// Request focus on this object. - /// - public void RequestFocus(bool byKey) - { - if (displayObject != null) - Stage.inst.SetFocus(displayObject, byKey); - } - - /// - /// Tooltips of this object. UIConfig.tooltipsWin must be set first. - /// - public string tooltips - { - get { return _tooltips; } - set - { - if (!string.IsNullOrEmpty(_tooltips)) - { - this.onRollOver.Remove(__rollOver); - this.onRollOut.Remove(__rollOut); - } - - _tooltips = value; - if (!string.IsNullOrEmpty(_tooltips)) - { - this.onRollOver.Add(__rollOver); - this.onRollOut.Add(__rollOut); - } - } - } - - - /// - /// - /// - /// - public string cursor - { - get { return displayObject != null ? displayObject.cursor : null; } - set - { - if (displayObject != null) - displayObject.cursor = value; - } - } - - private void __rollOver() - { - this.root.ShowTooltips(tooltips); - } - - private void __rollOut() - { - this.root.HideTooltips(); - } - - /// - /// - /// - virtual public IFilter filter - { - get { return displayObject != null ? displayObject.filter : null; } - set { if (displayObject != null) displayObject.filter = value; } - } - - /// - /// - /// - virtual public BlendMode blendMode - { - get { return displayObject != null ? displayObject.blendMode : BlendMode.None; } - set { if (displayObject != null) displayObject.blendMode = value; } - } - - /// - /// 设定GameObject的名称 - /// - public string gameObjectName - { - get - { - if (displayObject != null) - return displayObject.gameObject.name; - else - return null; - } - - set - { - if (displayObject != null) - displayObject.gameObject.name = value; - } - } - - /// - /// - /// - /// - public void SetHome(GObject obj) - { - if (obj != null && displayObject != null && obj.displayObject != null) - displayObject.home = obj.displayObject.cachedTransform; - } - - /// - /// If the object has lowlevel displayobject and the displayobject has a container parent? - /// - public bool inContainer - { - get - { - return displayObject != null && displayObject.parent != null; - } - } - - /// - /// If the object is on stage. - /// - public bool onStage - { - get - { - return displayObject != null && displayObject.stage != null; - } - } - - /// - /// Resource url of this object. - /// - public string resourceURL - { - get - { - if (packageItem != null) - return UIPackage.URL_PREFIX + packageItem.owner.id + packageItem.id; - else - return null; - } - } - - /// - /// Gear to xy controller. - /// - public GearXY gearXY - { - get - { - return (GearXY)GetGear(1); - } - } - - /// - /// Gear to size controller. - /// - public GearSize gearSize - { - get - { - return (GearSize)GetGear(2); - } - } - - /// - /// Gear to look controller. - /// - public GearLook gearLook - { - get - { - return (GearLook)GetGear(3); - } - } - - public GearBase GetGear(int index) - { - GearBase gear = _gears[index]; - if (gear == null) - { - switch (index) - { - case 0: - gear = new GearDisplay(this); - break; - case 1: - gear = new GearXY(this); - break; - case 2: - gear = new GearSize(this); - break; - case 3: - gear = new GearLook(this); - break; - case 4: - gear = new GearColor(this); - break; - case 5: - gear = new GearAnimation(this); - break; - case 6: - gear = new GearText(this); - break; - case 7: - gear = new GearIcon(this); - break; - case 8: - gear = new GearDisplay2(this); - break; - case 9: - gear = new GearFontSize(this); - break; - default: - throw new System.Exception("FairyGUI: invalid gear index!"); - } - _gears[index] = gear; - } - return gear; - } - - protected void UpdateGear(int index) - { - if (underConstruct || _gearLocked) - return; - - GearBase gear = _gears[index]; - if (gear != null && gear.controller != null) - gear.UpdateState(); - } - - internal bool CheckGearController(int index, Controller c) - { - return _gears[index] != null && _gears[index].controller == c; - } - - internal void UpdateGearFromRelations(int index, float dx, float dy) - { - if (_gears[index] != null) - _gears[index].UpdateFromRelations(dx, dy); - } - - internal uint AddDisplayLock() - { - GearDisplay gearDisplay = (GearDisplay)_gears[0]; - if (gearDisplay != null && gearDisplay.controller != null) - { - uint ret = gearDisplay.AddLock(); - CheckGearDisplay(); - - return ret; - } - else - return 0; - } - - internal void ReleaseDisplayLock(uint token) - { - GearDisplay gearDisplay = (GearDisplay)_gears[0]; - if (gearDisplay != null && gearDisplay.controller != null) - { - gearDisplay.ReleaseLock(token); - CheckGearDisplay(); - } - } - - void CheckGearDisplay() - { - if (_handlingController) - return; - - bool connected = _gears[0] == null || ((GearDisplay)_gears[0]).connected; - if (_gears[8] != null) - connected = ((GearDisplay2)_gears[8]).Evaluate(connected); - - if (connected != _internalVisible) - { - _internalVisible = connected; - if (parent != null) - parent.ChildStateChanged(this); - if (_group != null && _group.excludeInvisibles) - _group.SetBoundsChangedFlag(); - } - } - - /// - /// Mark the fairy batching state is invalid. - /// - public void InvalidateBatchingState() - { - if (displayObject != null) - displayObject.InvalidateBatchingState(); - else if ((this is GGroup) && parent != null) - parent.container.InvalidateBatchingState(true); - } - - virtual public void HandleControllerChanged(Controller c) - { - _handlingController = true; - for (int i = 0; i < 10; i++) - { - GearBase gear = _gears[i]; - if (gear != null && gear.controller == c) - gear.Apply(); - } - _handlingController = false; - - CheckGearDisplay(); - } - - /// - /// - /// - /// - /// - public void AddRelation(GObject target, RelationType relationType) - { - AddRelation(target, relationType, false); - } - - /// - /// - /// - /// - /// - /// - public void AddRelation(GObject target, RelationType relationType, bool usePercent) - { - relations.Add(target, relationType, usePercent); - } - - /// - /// - /// - /// - /// - public void RemoveRelation(GObject target, RelationType relationType) - { - relations.Remove(target, relationType); - } - - /// - /// - /// - public void RemoveFromParent() - { - if (parent != null) - parent.RemoveChild(this); - } - - /// - /// Group belonging to. - /// - public GGroup group - { - get { return _group; } - set - { - if (_group != value) - { - if (_group != null) - _group.SetBoundsChangedFlag(); - _group = value; - if (_group != null) - _group.SetBoundsChangedFlag(); - HandleVisibleChanged(); - if (parent != null) - parent.ChildStateChanged(this); - } - } - } - - /// - /// - /// - public GRoot root - { - get - { - GObject p = this; - while (p.parent != null) - p = p.parent; - - if (p is GRoot) - return (GRoot)p; - - if (p.displayObject != null && p.displayObject.parent != null) - { - DisplayObject d = p.displayObject.parent.GetChild("GRoot"); - if (d != null && (d.gOwner is GRoot)) - return (GRoot)d.gOwner; - } - - return GRoot.inst; - } - } - - /// - /// - /// - virtual public string text - { - get { return null; } - set { /*override in child*/} - } - - /// - /// - /// - virtual public string icon - { - get { return null; } - set { /*override in child*/} - } - - /// - /// - /// - public bool draggable - { - get { return _draggable; } - set - { - if (_draggable != value) - { - _draggable = value; - InitDrag(); - } - } - } - - /// - /// - /// - public void StartDrag() - { - StartDrag(-1); - } - - /// - /// - /// - /// - public void StartDrag(int touchId) - { - if (displayObject.stage == null) - return; - - DragBegin(touchId); - } - - /// - /// - /// - public void StopDrag() - { - DragEnd(); - } - - /// - /// - /// - public bool dragging - { - get { return draggingObject == this; } - } - - /// - /// Transforms a point from the local coordinate system to global (Stage) coordinates. - /// - /// - /// - public Vector2 LocalToGlobal(Vector2 pt) - { - if (_pivotAsAnchor) - { - pt.x += _width * _pivotX; - pt.y += _height * _pivotY; - } - return displayObject.LocalToGlobal(pt); - } - - /// - /// Transforms a point from global (Stage) coordinates to the local coordinate system. - /// - /// - /// - public Vector2 GlobalToLocal(Vector2 pt) - { - pt = displayObject.GlobalToLocal(pt); - if (_pivotAsAnchor) - { - pt.x -= _width * _pivotX; - pt.y -= _height * _pivotY; - } - return pt; - } - - /// - /// - /// - /// - /// - public Rect LocalToGlobal(Rect rect) - { - Rect ret = new Rect(); - Vector2 v = this.LocalToGlobal(new Vector2(rect.xMin, rect.yMin)); - ret.xMin = v.x; - ret.yMin = v.y; - v = this.LocalToGlobal(new Vector2(rect.xMax, rect.yMax)); - ret.xMax = v.x; - ret.yMax = v.y; - return ret; - } - - /// - /// - /// - /// - /// - public Rect GlobalToLocal(Rect rect) - { - Rect ret = new Rect(); - Vector2 v = this.GlobalToLocal(new Vector2(rect.xMin, rect.yMin)); - ret.xMin = v.x; - ret.yMin = v.y; - v = this.GlobalToLocal(new Vector2(rect.xMax, rect.yMax)); - ret.xMax = v.x; - ret.yMax = v.y; - return ret; - } - - /// - /// Transforms a point from the local coordinate system to GRoot coordinates. - /// - /// - /// - /// - public Vector2 LocalToRoot(Vector2 pt, GRoot r) - { - pt = LocalToGlobal(pt); - if (r == null || r == GRoot.inst) - { - //fast - pt.x /= UIContentScaler.scaleFactor; - pt.y /= UIContentScaler.scaleFactor; - return pt; - } - else - return r.GlobalToLocal(pt); - } - - /// - /// Transforms a point from the GRoot coordinate to local coordinates system. - /// - /// - /// - /// - public Vector2 RootToLocal(Vector2 pt, GRoot r) - { - if (r == null || r == GRoot.inst) - { - //fast - pt.x *= UIContentScaler.scaleFactor; - pt.y *= UIContentScaler.scaleFactor; - } - else - pt = r.LocalToGlobal(pt); - return GlobalToLocal(pt); - } - - /// - /// - /// - /// - /// - public Vector2 WorldToLocal(Vector3 pt) - { - return WorldToLocal(pt, HitTestContext.cachedMainCamera); - } - - /// - /// - /// - /// - /// - /// - public Vector2 WorldToLocal(Vector3 pt, Camera camera) - { - Vector3 v = camera.WorldToScreenPoint(pt); - v.y = Screen.height - v.y; - v.z = 0; - return GlobalToLocal(v); - } - - /// - /// - /// - /// - /// - /// - public Vector2 TransformPoint(Vector2 pt, GObject targetSpace) - { - if (_pivotAsAnchor) - { - pt.x += _width * _pivotX; - pt.y += _height * _pivotY; - } - return this.displayObject.TransformPoint(pt, targetSpace != null ? targetSpace.displayObject : Stage.inst); - } - - /// - /// - /// - /// - /// - /// - public Rect TransformRect(Rect rect, GObject targetSpace) - { - if (_pivotAsAnchor) - { - rect.x += _width * _pivotX; - rect.y += _height * _pivotY; - } - return this.displayObject.TransformRect(rect, targetSpace != null ? targetSpace.displayObject : Stage.inst); - } - - /// - /// - /// - public bool isDisposed - { - get { return _disposed; } - } - - /// - /// - /// - virtual public void Dispose() - { - if (_disposed) - return; - - _disposed = true; - - RemoveFromParent(); - RemoveEventListeners(); - relations.Dispose(); - relations = null; - for (int i = 0; i < 10; i++) - { - GearBase gear = _gears[i]; - if (gear != null) - gear.Dispose(); - } - if (displayObject != null) - { - displayObject.gOwner = null; - displayObject.Dispose(); - } - data = null; - } - - /// - /// - /// - public GImage asImage - { - get { return this as GImage; } - } - - /// - /// - /// - public GComponent asCom - { - get { return this as GComponent; } - } - - /// - /// - /// - public GButton asButton - { - get { return this as GButton; } - } - - /// - /// - /// - public GLabel asLabel - { - get { return this as GLabel; } - } - - /// - /// - /// - public GProgressBar asProgress - { - get { return this as GProgressBar; } - } - - /// - /// - /// - public GSlider asSlider - { - get { return this as GSlider; } - } - - /// - /// - /// - public GComboBox asComboBox - { - get { return this as GComboBox; } - } - - /// - /// - /// - public GTextField asTextField - { - get { return this as GTextField; } - } - - /// - /// - /// - public GRichTextField asRichTextField - { - get { return this as GRichTextField; } - } - - /// - /// - /// - public GTextInput asTextInput - { - get { return this as GTextInput; } - } - - /// - /// - /// - public GLoader asLoader - { - get { return this as GLoader; } - } - - /// - /// - /// - public GLoader3D asLoader3D - { - get { return this as GLoader3D; } - } - - /// - /// - /// - public GList asList - { - get { return this as GList; } - } - - /// - /// - /// - public GGraph asGraph - { - get { return this as GGraph; } - } - - /// - /// - /// - public GGroup asGroup - { - get { return this as GGroup; } - } - - /// - /// - /// - public GMovieClip asMovieClip - { - get { return this as GMovieClip; } - } - - /// - /// - /// - public GTree asTree - { - get { return this as GTree; } - } - - /// - /// - /// - public GTreeNode treeNode - { - get { return _treeNode; } - } - - virtual protected void CreateDisplayObject() - { - } - - internal void InternalSetParent(GComponent value) - { - parent = value; - } - - virtual protected void HandlePositionChanged() - { - if (displayObject != null) - { - float xv = _x; - float yv = _y; - if (!_pivotAsAnchor) - { - xv += _width * _pivotX; - yv += _height * _pivotY; - } - displayObject.location = new Vector3(xv, yv, _z); - } - } - - virtual protected void HandleSizeChanged() - { - if (displayObject != null) - displayObject.SetSize(_width, _height); - } - - virtual protected void HandleScaleChanged() - { - if (displayObject != null) - displayObject.SetScale(_scaleX, _scaleY); - } - - virtual protected void HandleGrayedChanged() - { - if (displayObject != null) - displayObject.grayed = _grayed; - } - - virtual protected void HandleAlphaChanged() - { - if (displayObject != null) - displayObject.alpha = _alpha; - } - - virtual internal protected void HandleVisibleChanged() - { - if (displayObject != null) - displayObject.visible = internalVisible2; - } - - virtual public void ConstructFromResource() - { - } - - virtual public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - buffer.Seek(beginPos, 0); - buffer.Skip(5); - - id = buffer.ReadS(); - name = buffer.ReadS(); - float f1 = buffer.ReadInt(); - float f2 = buffer.ReadInt(); - SetXY(f1, f2); - - if (buffer.ReadBool()) - { - initWidth = buffer.ReadInt(); - initHeight = buffer.ReadInt(); - SetSize(initWidth, initHeight, true); - } - - if (buffer.ReadBool()) - { - minWidth = buffer.ReadInt(); - maxWidth = buffer.ReadInt(); - minHeight = buffer.ReadInt(); - maxHeight = buffer.ReadInt(); - } - - if (buffer.ReadBool()) - { - f1 = buffer.ReadFloat(); - f2 = buffer.ReadFloat(); - SetScale(f1, f2); - } - - if (buffer.ReadBool()) - { - f1 = buffer.ReadFloat(); - f2 = buffer.ReadFloat(); - this.skew = new Vector2(f1, f2); - } - - if (buffer.ReadBool()) - { - f1 = buffer.ReadFloat(); - f2 = buffer.ReadFloat(); - SetPivot(f1, f2, buffer.ReadBool()); - } - - f1 = buffer.ReadFloat(); - if (f1 != 1) - this.alpha = f1; - - f1 = buffer.ReadFloat(); - if (f1 != 0) - this.rotation = f1; - - if (!buffer.ReadBool()) - this.visible = false; - if (!buffer.ReadBool()) - this.touchable = false; - if (buffer.ReadBool()) - this.grayed = true; - this.blendMode = (BlendMode)buffer.ReadByte(); - - int filter = buffer.ReadByte(); - if (filter == 1) - { - ColorFilter cf = new ColorFilter(); - this.filter = cf; - - cf.AdjustBrightness(buffer.ReadFloat()); - cf.AdjustContrast(buffer.ReadFloat()); - cf.AdjustSaturation(buffer.ReadFloat()); - cf.AdjustHue(buffer.ReadFloat()); - } - - string str = buffer.ReadS(); - if (str != null) - this.data = str; - } - - virtual public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - buffer.Seek(beginPos, 1); - - string str = buffer.ReadS(); - if (str != null) - this.tooltips = str; - - int groupId = buffer.ReadShort(); - if (groupId >= 0) - group = parent.GetChildAt(groupId) as GGroup; - - buffer.Seek(beginPos, 2); - - int cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - GearBase gear = GetGear(buffer.ReadByte()); - gear.Setup(buffer); - - buffer.position = nextPos; - } - } - - #region Drag support - Vector2 _dragTouchStartPos; - bool _dragTesting; - - static Vector2 sGlobalDragStart = new Vector2(); - static Rect sGlobalRect = new Rect(); - static bool sUpdateInDragging = false; - - private void InitDrag() - { - if (_draggable) - { - onTouchBegin.Add(__touchBegin); - onTouchMove.Add(__touchMove); - onTouchEnd.Add(__touchEnd); - } - else - { - onTouchBegin.Remove(__touchBegin); - onTouchMove.Remove(__touchMove); - onTouchEnd.Remove(__touchEnd); - } - } - - private void DragBegin(int touchId) - { - if (DispatchEvent("onDragStart", touchId)) - return; - - if (draggingObject != null) - { - GObject tmp = draggingObject; - draggingObject.StopDrag(); - draggingObject = null; - tmp.DispatchEvent("onDragEnd", null); - } - - onTouchMove.Add(__touchMove); - onTouchEnd.Add(__touchEnd); - - sGlobalDragStart = Stage.inst.GetTouchPosition(touchId); - sGlobalRect = this.LocalToGlobal(new Rect(0, 0, this.width, this.height)); - _dragTesting = false; - - draggingObject = this; - Stage.inst.AddTouchMonitor(touchId, this); - } - - private void DragEnd() - { - if (draggingObject == this) - { - _dragTesting = false; - draggingObject = null; - } - } - - private void __touchBegin(EventContext context) - { - if ((Stage.inst.focus is InputTextField) && ((InputTextField)Stage.inst.focus).editable) - { - _dragTesting = false; - return; - } - - InputEvent evt = context.inputEvent; - _dragTouchStartPos = evt.position; - _dragTesting = true; - context.CaptureTouch(); - } - - private void __touchMove(EventContext context) - { - InputEvent evt = context.inputEvent; - - if (_dragTesting && draggingObject != this) - { - int sensitivity; - if (Stage.touchScreen) - sensitivity = UIConfig.touchDragSensitivity; - else - sensitivity = UIConfig.clickDragSensitivity; - if (Mathf.Abs(_dragTouchStartPos.x - evt.x) < sensitivity - && Mathf.Abs(_dragTouchStartPos.y - evt.y) < sensitivity) - return; - - _dragTesting = false; - DragBegin(evt.touchId); - } - - if (draggingObject == this) - { - float xx = evt.x - sGlobalDragStart.x + sGlobalRect.x; - float yy = evt.y - sGlobalDragStart.y + sGlobalRect.y; - - if (dragBounds != null) - { - Rect rect = GRoot.inst.LocalToGlobal((Rect)dragBounds); - if (xx < rect.x) - xx = rect.x; - else if (xx + sGlobalRect.width > rect.xMax) - { - xx = rect.xMax - sGlobalRect.width; - if (xx < rect.x) - xx = rect.x; - } - - if (yy < rect.y) - yy = rect.y; - else if (yy + sGlobalRect.height > rect.yMax) - { - yy = rect.yMax - sGlobalRect.height; - if (yy < rect.y) - yy = rect.y; - } - } - - Vector2 pt = this.parent.GlobalToLocal(new Vector2(xx, yy)); - if (float.IsNaN(pt.x)) - return; - - sUpdateInDragging = true; - this.SetXY(Mathf.RoundToInt(pt.x), Mathf.RoundToInt(pt.y)); - sUpdateInDragging = false; - - DispatchEvent("onDragMove", null); - } - } - - private void __touchEnd(EventContext context) - { - if (draggingObject == this) - { - draggingObject = null; - DispatchEvent("onDragEnd", null); - } - } - #endregion - - #region Tween Helpers - public GTweener TweenMove(Vector2 endValue, float duration) - { - return GTween.To(this.xy, endValue, duration).SetTarget(this, TweenPropType.XY); - } - - public GTweener TweenMoveX(float endValue, float duration) - { - return GTween.To(_x, endValue, duration).SetTarget(this, TweenPropType.X); - } - - public GTweener TweenMoveY(float endValue, float duration) - { - return GTween.To(_y, endValue, duration).SetTarget(this, TweenPropType.Y); - } - - public GTweener TweenScale(Vector2 endValue, float duration) - { - return GTween.To(this.scale, endValue, duration).SetTarget(this, TweenPropType.Scale); - } - - public GTweener TweenScaleX(float endValue, float duration) - { - return GTween.To(_scaleX, endValue, duration).SetTarget(this, TweenPropType.ScaleX); - } - - public GTweener TweenScaleY(float endValue, float duration) - { - return GTween.To(_scaleY, endValue, duration).SetTarget(this, TweenPropType.ScaleY); - } - - public GTweener TweenResize(Vector2 endValue, float duration) - { - return GTween.To(this.size, endValue, duration).SetTarget(this, TweenPropType.Size); - } - - public GTweener TweenFade(float endValue, float duration) - { - return GTween.To(_alpha, endValue, duration).SetTarget(this, TweenPropType.Alpha); - } - - public GTweener TweenRotate(float endValue, float duration) - { - return GTween.To(_rotation, endValue, duration).SetTarget(this, TweenPropType.Rotation); - } - #endregion - } -} +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class GObject : EventDispatcher + { + /// + /// GObject的id,仅作为内部使用。与name不同,id值是不会相同的。 + /// id is for internal use only. + /// + public string id { get; private set; } + + /// + /// Name of the object. + /// + public string name; + + /// + /// User defined data. + /// + public object data; + + /// + /// The source width of the object. + /// + public int sourceWidth; + + /// + /// The source height of the object. + /// + public int sourceHeight; + + /// + /// The initial width of the object. + /// + public int initWidth; + + /// + /// The initial height of the object. + /// + public int initHeight; + + /// + /// + /// + public int minWidth; + + /// + /// + /// + public int maxWidth; + + /// + /// + /// + public int minHeight; + + /// + /// + /// + public int maxHeight; + + /// + /// Relations Object. + /// + public Relations relations { get; private set; } + + /// + /// Restricted range of dragging. + /// + public Rect? dragBounds; + + /// + /// Parent object. + /// + public GComponent parent { get; private set; } + + /// + /// Lowlevel display object. + /// + public DisplayObject displayObject { get; protected set; } + + /// + /// 当前全局正在被拖动的对象 + /// + public static GObject draggingObject { get; private set; } + + /// + /// + /// + public PackageItem packageItem; + + float _x; + float _y; + float _z; + float _pivotX; + float _pivotY; + bool _pivotAsAnchor; + float _alpha; + float _rotation; + float _rotationX; + float _rotationY; + bool _visible; + bool _internalVisible; + bool _handlingController; + bool _touchable; + bool _grayed; + bool _draggable; + float _scaleX; + float _scaleY; + int _sortingOrder; + string _tooltips; + GGroup _group; + + GearBase[] _gears; + + EventListener _onClick; + EventListener _onRightClick; + EventListener _onTouchBegin; + EventListener _onTouchMove; + EventListener _onTouchEnd; + EventListener _onRollOver; + EventListener _onRollOut; + EventListener _onAddedToStage; + EventListener _onRemovedFromStage; + EventListener _onKeyDown; + EventListener _onClickLink; + EventListener _onPositionChanged; + EventListener _onSizeChanged; + EventListener _onDragStart; + EventListener _onDragMove; + EventListener _onDragEnd; + EventListener _onGearStop; + EventListener _onFocusIn; + EventListener _onFocusOut; + + internal protected bool underConstruct; + internal float _width; + internal float _height; + internal float _rawWidth; + internal float _rawHeight; + internal bool _gearLocked; + internal float _sizePercentInGroup; + internal bool _disposed; + internal GTreeNode _treeNode; + + internal static uint _gInstanceCounter; + + public GObject() + { + _width = 0; + _height = 0; + _alpha = 1; + _visible = true; + _touchable = true; + _scaleX = 1; + _scaleY = 1; + _internalVisible = true; + id = "_n" + _gInstanceCounter++; + name = string.Empty; + + CreateDisplayObject(); + + relations = new Relations(this); + _gears = new GearBase[10]; + } + + /// + /// Dispatched when the object or its child was clicked. + /// + public EventListener onClick + { + get { return _onClick ?? (_onClick = new EventListener(this, "onClick")); } + } + + /// + /// Dispatched when the object or its child was clicked by right mouse button. Web only. + /// + public EventListener onRightClick + { + get { return _onRightClick ?? (_onRightClick = new EventListener(this, "onRightClick")); } + } + + /// + /// Dispatched when the finger touched the object or its child just now. + /// + public EventListener onTouchBegin + { + get { return _onTouchBegin ?? (_onTouchBegin = new EventListener(this, "onTouchBegin")); } + } + + /// + /// + /// + public EventListener onTouchMove + { + get { return _onTouchMove ?? (_onTouchMove = new EventListener(this, "onTouchMove")); } + } + + /// + /// Dispatched when the finger was lifted from the screen or from the mouse button. + /// + public EventListener onTouchEnd + { + get { return _onTouchEnd ?? (_onTouchEnd = new EventListener(this, "onTouchEnd")); } + } + + /// + /// The cursor or finger hovers over an object. + /// + public EventListener onRollOver + { + get { return _onRollOver ?? (_onRollOver = new EventListener(this, "onRollOver")); } + } + + /// + /// The cursor or finger leave an object. + /// + public EventListener onRollOut + { + get { return _onRollOut ?? (_onRollOut = new EventListener(this, "onRollOut")); } + } + + /// + /// Dispatched when the object was added to the stage. + /// + public EventListener onAddedToStage + { + get { return _onAddedToStage ?? (_onAddedToStage = new EventListener(this, "onAddedToStage")); } + } + + /// + /// Dispatched when the object was removed from the stage. + /// + public EventListener onRemovedFromStage + { + get { return _onRemovedFromStage ?? (_onRemovedFromStage = new EventListener(this, "onRemovedFromStage")); } + } + + /// + /// Dispatched on key pressed when the object is in focus. + /// + public EventListener onKeyDown + { + get { return _onKeyDown ?? (_onKeyDown = new EventListener(this, "onKeyDown")); } + } + + /// + /// Dispatched when links in the object or its child was clicked. + /// + public EventListener onClickLink + { + get { return _onClickLink ?? (_onClickLink = new EventListener(this, "onClickLink")); } + } + + /// + /// Dispatched when the object was moved. + /// + public EventListener onPositionChanged + { + get { return _onPositionChanged ?? (_onPositionChanged = new EventListener(this, "onPositionChanged")); } + } + + /// + /// Dispatched when the object was resized. + /// + public EventListener onSizeChanged + { + get { return _onSizeChanged ?? (_onSizeChanged = new EventListener(this, "onSizeChanged")); } + } + + /// + /// Dispatched when drag start. + /// + public EventListener onDragStart + { + get { return _onDragStart ?? (_onDragStart = new EventListener(this, "onDragStart")); } + } + + /// + /// Dispatched when dragging. + /// + public EventListener onDragMove + { + get { return _onDragMove ?? (_onDragMove = new EventListener(this, "onDragMove")); } + } + + /// + /// Dispatched when drag end. + /// + public EventListener onDragEnd + { + get { return _onDragEnd ?? (_onDragEnd = new EventListener(this, "onDragEnd")); } + } + + /// + /// + /// + public EventListener onGearStop + { + get { return _onGearStop ?? (_onGearStop = new EventListener(this, "onGearStop")); } + } + + /// + /// + /// + public EventListener onFocusIn + { + get { return _onFocusIn ?? (_onFocusIn = new EventListener(this, "onFocusIn")); } + } + + /// + /// + /// + public EventListener onFocusOut + { + get { return _onFocusOut ?? (_onFocusOut = new EventListener(this, "onFocusOut")); } + } + + /// + /// The x coordinate of the object relative to the local coordinates of the parent. + /// + public float x + { + get { return _x; } + set + { + SetPosition(value, _y, _z); + } + } + + /// + /// The y coordinate of the object relative to the local coordinates of the parent. + /// + public float y + { + get { return _y; } + set + { + SetPosition(_x, value, _z); + } + } + + /// + /// The z coordinate of the object relative to the local coordinates of the parent. + /// + public float z + { + get { return _z; } + set + { + SetPosition(_x, _y, value); + } + } + + /// + /// The x and y coordinates of the object relative to the local coordinates of the parent. + /// + public Vector2 xy + { + get { return new Vector2(_x, _y); } + set { SetPosition(value.x, value.y, _z); } + } + + /// + /// The x,y,z coordinates of the object relative to the local coordinates of the parent. + /// + public Vector3 position + { + get { return new Vector3(_x, _y, _z); } + set { SetPosition(value.x, value.y, value.z); } + } + + /// + /// change the x and y coordinates of the object relative to the local coordinates of the parent. + /// + /// x value. + /// y value. + public void SetXY(float xv, float yv) + { + SetPosition(xv, yv, _z); + } + + /// + /// + /// + /// + /// + /// + public void SetXY(float xv, float yv, bool topLeftValue) + { + if (_pivotAsAnchor) + SetPosition(xv + _pivotX * _width, yv + _pivotY * _height, _z); + else + SetPosition(xv, yv, _z); + } + + /// + /// change the x,y,z coordinates of the object relative to the local coordinates of the parent. + /// + /// x value. + /// y value. + /// z value. + public void SetPosition(float xv, float yv, float zv) + { + if (_x != xv || _y != yv || _z != zv) + { + float dx = xv - _x; + float dy = yv - _y; + _x = xv; + _y = yv; + _z = zv; + + HandlePositionChanged(); + + if (this is GGroup) + ((GGroup)this).MoveChildren(dx, dy); + + UpdateGear(1); + + if (parent != null && !(parent is GList)) + { + parent.SetBoundsChangedFlag(); + if (_group != null) + _group.SetBoundsChangedFlag(true); + DispatchEvent("onPositionChanged", null); + } + + if (draggingObject == this && !sUpdateInDragging) + sGlobalRect = this.LocalToGlobal(new Rect(0, 0, this.width, this.height)); + } + } + + [Obsolete("Use UIConfig.makePixelPerfect or DisplayObject.pixelPerfect")] + public bool pixelSnapping + { + get { return false; } + set { } + } + + /// + /// Set the object in middle of the parent or GRoot if the parent is not set. + /// + public void Center() + { + Center(false); + } + + /// + /// Set the object in middle of the parent or GRoot if the parent is not set. + /// + /// Add relations to maintain the center state. + public void Center(bool restraint) + { + GComponent r; + if (parent != null) + r = parent; + else + r = this.root; + + this.SetXY((int)((r.width - this.width) / 2), (int)((r.height - this.height) / 2), true); + if (restraint) + { + this.AddRelation(r, RelationType.Center_Center); + this.AddRelation(r, RelationType.Middle_Middle); + } + } + + /// + /// 设置对象为全屏大小(逻辑屏幕)。 + /// + public void MakeFullScreen() + { + this.SetSize(GRoot.inst.width, GRoot.inst.height); + } + + /// + /// The width of the object in pixels. + /// + public float width + { + get + { + return _width; + } + set + { + SetSize(value, _rawHeight); + } + } + + /// + /// The height of the object in pixels. + /// + public float height + { + get + { + return _height; + } + set + { + SetSize(_rawWidth, value); + } + } + + /// + /// The size of the object in pixels. + /// + public Vector2 size + { + get { return new Vector2(width, height); } + set { SetSize(value.x, value.y); } + } + + /// + /// actualWidth = width * scalex + /// + public float actualWidth + { + get { return this.width * _scaleX; } + } + + /// + /// actualHeight = height * scaleY + /// + public float actualHeight + { + get { return this.height * _scaleY; } + } + + /// + /// Change size. + /// + /// Width value. + /// Height value. + public void SetSize(float wv, float hv) + { + SetSize(wv, hv, false); + } + + /// + /// Change size. + /// + /// Width value. + /// Height value. + /// If pivot is set, the object's positon will change when its size change. Set ignorePivot=true to keep the position. + public void SetSize(float wv, float hv, bool ignorePivot) + { + if (_rawWidth != wv || _rawHeight != hv) + { + _rawWidth = wv; + _rawHeight = hv; + if (wv < minWidth) + wv = minWidth; + else if (maxWidth > 0 && wv > maxWidth) + wv = maxWidth; + if (hv < minHeight) + hv = minHeight; + else if (maxHeight > 0 && hv > maxHeight) + hv = maxHeight; + float dWidth = wv - _width; + float dHeight = hv - _height; + _width = wv; + _height = hv; + + HandleSizeChanged(); + + if (_pivotX != 0 || _pivotY != 0) + { + if (!_pivotAsAnchor) + { + if (!ignorePivot) + SetXY(_x - _pivotX * dWidth, _y - _pivotY * dHeight); + else + HandlePositionChanged(); + } + else + HandlePositionChanged(); + } + + if (this is GGroup) + ((GGroup)this).ResizeChildren(dWidth, dHeight); + + UpdateGear(2); + + if (parent != null) + { + relations.OnOwnerSizeChanged(dWidth, dHeight, _pivotAsAnchor || !ignorePivot); + parent.SetBoundsChangedFlag(); + if (_group != null) + _group.SetBoundsChangedFlag(); + } + + DispatchEvent("onSizeChanged", null); + } + } + + protected void SetSizeDirectly(float wv, float hv) + { + _rawWidth = wv; + _rawHeight = hv; + if (wv < 0) + wv = 0; + if (hv < 0) + hv = 0; + _width = wv; + _height = hv; + } + + /// + /// + /// + public float xMin + { + get + { + return _pivotAsAnchor ? (_x - _width * _pivotX) : _x; + } + set + { + if (_pivotAsAnchor) + SetPosition(value + _width * _pivotX, _y, _z); + else + SetPosition(value, _y, _z); + } + } + + /// + /// + /// + public float yMin + { + get + { + return _pivotAsAnchor ? (_y - _height * _pivotY) : _y; + } + set + { + if (_pivotAsAnchor) + SetPosition(_x, value + _height * _pivotY, _z); + else + SetPosition(_x, value, _z); + } + } + + /// + /// The horizontal scale factor. '1' means no scale, cannt be negative. + /// + public float scaleX + { + get { return _scaleX; } + set + { + SetScale(value, _scaleY); + } + } + + /// + /// The vertical scale factor. '1' means no scale, cannt be negative. + /// + public float scaleY + { + get { return _scaleY; } + set + { + SetScale(_scaleX, value); + } + } + + /// + /// The scale factor. + /// + public Vector2 scale + { + get { return new Vector2(_scaleX, _scaleY); } + set { SetScale(value.x, value.y); } + } + + /// + /// Change the scale factor. + /// + /// The horizontal scale factor. + /// The vertical scale factor + public void SetScale(float wv, float hv) + { + if (_scaleX != wv || _scaleY != hv) + { + _scaleX = wv; + _scaleY = hv; + HandleScaleChanged(); + + UpdateGear(2); + } + } + + /// + /// + /// + public Vector2 skew + { + get + { + if (displayObject != null) + return displayObject.skew; + else + return Vector2.zero; + } + + set + { + if (displayObject != null) + displayObject.skew = value; + } + } + + /// + /// The x coordinate of the object's origin in its own coordinate space. + /// + public float pivotX + { + get { return _pivotX; } + set + { + SetPivot(value, _pivotY, _pivotAsAnchor); + } + } + + /// + /// The y coordinate of the object's origin in its own coordinate space. + /// + public float pivotY + { + get { return _pivotY; } + set + { + SetPivot(_pivotX, value, _pivotAsAnchor); + } + } + + /// + /// The x and y coordinates of the object's origin in its own coordinate space. + /// + public Vector2 pivot + { + get { return new Vector2(_pivotX, _pivotY); } + set { SetPivot(value.x, value.y, _pivotAsAnchor); } + } + + public bool pivotAsAnchor + { + get { return _pivotAsAnchor; } + set + { + SetPivot(_pivotX, _pivotY, value); + } + } + + /// + /// Change the x and y coordinates of the object's origin in its own coordinate space. + /// + /// x value in ratio + /// y value in ratio + public void SetPivot(float xv, float yv) + { + SetPivot(xv, yv, false); + } + + /// + /// Change the x and y coordinates of the object's origin in its own coordinate space. + /// + /// x value in ratio + /// y value in ratio + /// If use the pivot as the anchor position + public void SetPivot(float xv, float yv, bool asAnchor) + { + if (_pivotX != xv || _pivotY != yv || _pivotAsAnchor != asAnchor) + { + _pivotX = xv; + _pivotY = yv; + _pivotAsAnchor = asAnchor; + if (displayObject != null) + displayObject.pivot = new Vector2(_pivotX, _pivotY); + HandlePositionChanged(); + } + } + + /// + /// If the object can touch or click. GImage/GTextField is not touchable even it is true. + /// + public bool touchable + { + get + { + return _touchable; + } + set + { + if (_touchable != value) + { + _touchable = value; + UpdateGear(3); + + if (displayObject != null) + displayObject.touchable = _touchable; + } + } + } + + /// + /// If true, apply a grayed effect on this object. + /// + public bool grayed + { + get + { + return _grayed; + } + set + { + if (_grayed != value) + { + _grayed = value; + HandleGrayedChanged(); + UpdateGear(3); + } + } + } + + /// + /// Enabled is shortcut for grayed and !touchable combination. + /// + public bool enabled + { + get + { + return !_grayed && _touchable; + } + set + { + this.grayed = !value; + this.touchable = value; + } + } + + /// + /// The rotation around the z axis of the object in degrees. + /// + public float rotation + { + get + { + return _rotation; + } + set + { + _rotation = value; + if (displayObject != null) + displayObject.rotation = _rotation; + UpdateGear(3); + } + } + + /// + /// The rotation around the x axis of the object in degrees. + /// + public float rotationX + { + get + { + return _rotationX; + } + set + { + _rotationX = value; + if (displayObject != null) + displayObject.rotationX = _rotationX; + } + } + + /// + /// The rotation around the y axis of the object in degrees. + /// + public float rotationY + { + get + { + return _rotationY; + } + set + { + _rotationY = value; + if (displayObject != null) + displayObject.rotationY = _rotationY; + } + } + + /// + /// The opacity of the object. 0 = transparent, 1 = opaque. + /// + public float alpha + { + + get + { + return _alpha; + } + + set + { + _alpha = value; + HandleAlphaChanged(); + UpdateGear(3); + } + } + + /// + /// The visibility of the object. An invisible object will be untouchable. + /// + public bool visible + { + get + { + return _visible; + } + + set + { + if (_visible != value) + { + _visible = value; + HandleVisibleChanged(); + if (parent != null) + parent.SetBoundsChangedFlag(); + if (_group != null && _group.excludeInvisibles) + _group.SetBoundsChangedFlag(); + } + } + } + + internal bool internalVisible + { + get + { + return _internalVisible && (group == null || group.internalVisible); + } + } + + internal bool internalVisible2 + { + get + { + return _visible && (group == null || group.internalVisible2); + } + } + + internal bool internalVisible3 + { + get + { + return _visible && _internalVisible; + } + } + + /// + /// By default(when sortingOrder==0), object added to component is arrange by the added roder. + /// The bigger is the sorting order, the object is more in front. + /// + public int sortingOrder + { + get { return _sortingOrder; } + set + { + if (value < 0) + value = 0; + if (_sortingOrder != value) + { + int old = _sortingOrder; + _sortingOrder = value; + if (parent != null) + parent.ChildSortingOrderChanged(this, old, _sortingOrder); + } + } + } + + /// + /// If the object can be focused? + /// + public bool focusable + { + get { return displayObject != null && displayObject.focusable; } + set { if (displayObject != null) displayObject.focusable = value; } + } + + /// + /// If the object can be navigated by TAB? + /// + public bool tabStop + { + get { return displayObject != null && displayObject.tabStop; } + set { if (displayObject != null) displayObject.tabStop = value; } + } + + /// + /// If the object is focused. + /// + public bool focused + { + get { return displayObject != null && displayObject.focused; } + } + + /// + /// Request focus on this object. + /// + public void RequestFocus() + { + if (displayObject != null) + Stage.inst.SetFocus(displayObject, false); + } + + /// + /// Request focus on this object. + /// + public void RequestFocus(bool byKey) + { + if (displayObject != null) + Stage.inst.SetFocus(displayObject, byKey); + } + + /// + /// Tooltips of this object. UIConfig.tooltipsWin must be set first. + /// + public string tooltips + { + get { return _tooltips; } + set + { + if (!string.IsNullOrEmpty(_tooltips)) + { + this.onRollOver.Remove(__rollOver); + this.onRollOut.Remove(__rollOut); + } + + _tooltips = value; + if (!string.IsNullOrEmpty(_tooltips)) + { + this.onRollOver.Add(__rollOver); + this.onRollOut.Add(__rollOut); + } + } + } + + + /// + /// + /// + /// + public string cursor + { + get { return displayObject != null ? displayObject.cursor : null; } + set + { + if (displayObject != null) + displayObject.cursor = value; + } + } + + private void __rollOver() + { + this.root.ShowTooltips(tooltips); + } + + private void __rollOut() + { + this.root.HideTooltips(); + } + + /// + /// + /// + virtual public IFilter filter + { + get { return displayObject != null ? displayObject.filter : null; } + set { if (displayObject != null) displayObject.filter = value; } + } + + /// + /// + /// + virtual public BlendMode blendMode + { + get { return displayObject != null ? displayObject.blendMode : BlendMode.None; } + set { if (displayObject != null) displayObject.blendMode = value; } + } + + /// + /// 设定GameObject的名称 + /// + public string gameObjectName + { + get + { + if (displayObject != null) + return displayObject.gameObject.name; + else + return null; + } + + set + { + if (displayObject != null) + displayObject.gameObject.name = value; + } + } + + /// + /// + /// + /// + public void SetHome(GObject obj) + { + if (obj != null && displayObject != null && obj.displayObject != null) + displayObject.home = obj.displayObject.cachedTransform; + } + + /// + /// If the object has lowlevel displayobject and the displayobject has a container parent? + /// + public bool inContainer + { + get + { + return displayObject != null && displayObject.parent != null; + } + } + + /// + /// If the object is on stage. + /// + public bool onStage + { + get + { + return displayObject != null && displayObject.stage != null; + } + } + + /// + /// Resource url of this object. + /// + public string resourceURL + { + get + { + if (packageItem != null) + return UIPackage.URL_PREFIX + packageItem.owner.id + packageItem.id; + else + return null; + } + } + + /// + /// Gear to xy controller. + /// + public GearXY gearXY + { + get + { + return (GearXY)GetGear(1); + } + } + + /// + /// Gear to size controller. + /// + public GearSize gearSize + { + get + { + return (GearSize)GetGear(2); + } + } + + /// + /// Gear to look controller. + /// + public GearLook gearLook + { + get + { + return (GearLook)GetGear(3); + } + } + + public GearBase GetGear(int index) + { + GearBase gear = _gears[index]; + if (gear == null) + { + switch (index) + { + case 0: + gear = new GearDisplay(this); + break; + case 1: + gear = new GearXY(this); + break; + case 2: + gear = new GearSize(this); + break; + case 3: + gear = new GearLook(this); + break; + case 4: + gear = new GearColor(this); + break; + case 5: + gear = new GearAnimation(this); + break; + case 6: + gear = new GearText(this); + break; + case 7: + gear = new GearIcon(this); + break; + case 8: + gear = new GearDisplay2(this); + break; + case 9: + gear = new GearFontSize(this); + break; + default: + throw new System.Exception("FairyGUI: invalid gear index!"); + } + _gears[index] = gear; + } + return gear; + } + + protected void UpdateGear(int index) + { + if (underConstruct || _gearLocked) + return; + + GearBase gear = _gears[index]; + if (gear != null && gear.controller != null) + gear.UpdateState(); + } + + internal bool CheckGearController(int index, Controller c) + { + return _gears[index] != null && _gears[index].controller == c; + } + + internal void UpdateGearFromRelations(int index, float dx, float dy) + { + if (_gears[index] != null) + _gears[index].UpdateFromRelations(dx, dy); + } + + internal uint AddDisplayLock() + { + GearDisplay gearDisplay = (GearDisplay)_gears[0]; + if (gearDisplay != null && gearDisplay.controller != null) + { + uint ret = gearDisplay.AddLock(); + CheckGearDisplay(); + + return ret; + } + else + return 0; + } + + internal void ReleaseDisplayLock(uint token) + { + GearDisplay gearDisplay = (GearDisplay)_gears[0]; + if (gearDisplay != null && gearDisplay.controller != null) + { + gearDisplay.ReleaseLock(token); + CheckGearDisplay(); + } + } + + void CheckGearDisplay() + { + if (_handlingController) + return; + + bool connected = _gears[0] == null || ((GearDisplay)_gears[0]).connected; + if (_gears[8] != null) + connected = ((GearDisplay2)_gears[8]).Evaluate(connected); + + if (connected != _internalVisible) + { + _internalVisible = connected; + if (parent != null) + parent.ChildStateChanged(this); + if (_group != null && _group.excludeInvisibles) + _group.SetBoundsChangedFlag(); + } + } + + /// + /// Mark the fairy batching state is invalid. + /// + public void InvalidateBatchingState() + { + if (displayObject != null) + displayObject.InvalidateBatchingState(); + else if ((this is GGroup) && parent != null) + parent.container.InvalidateBatchingState(true); + } + + virtual public void HandleControllerChanged(Controller c) + { + _handlingController = true; + for (int i = 0; i < 10; i++) + { + GearBase gear = _gears[i]; + if (gear != null && gear.controller == c) + gear.Apply(); + } + _handlingController = false; + + CheckGearDisplay(); + } + + /// + /// + /// + /// + /// + public void AddRelation(GObject target, RelationType relationType) + { + AddRelation(target, relationType, false); + } + + /// + /// + /// + /// + /// + /// + public void AddRelation(GObject target, RelationType relationType, bool usePercent) + { + relations.Add(target, relationType, usePercent); + } + + /// + /// + /// + /// + /// + public void RemoveRelation(GObject target, RelationType relationType) + { + relations.Remove(target, relationType); + } + + /// + /// + /// + public void RemoveFromParent() + { + if (parent != null) + parent.RemoveChild(this); + } + + /// + /// Group belonging to. + /// + public GGroup group + { + get { return _group; } + set + { + if (_group != value) + { + if (_group != null) + _group.SetBoundsChangedFlag(); + _group = value; + if (_group != null) + _group.SetBoundsChangedFlag(); + HandleVisibleChanged(); + if (parent != null) + parent.ChildStateChanged(this); + } + } + } + + /// + /// + /// + public GRoot root + { + get + { + GObject p = this; + while (p.parent != null) + p = p.parent; + + if (p is GRoot) + return (GRoot)p; + + if (p.displayObject != null && p.displayObject.parent != null) + { + DisplayObject d = p.displayObject.parent.GetChild("GRoot"); + if (d != null && (d.gOwner is GRoot)) + return (GRoot)d.gOwner; + } + + return GRoot.inst; + } + } + + /// + /// + /// + virtual public string text + { + get { return null; } + set { /*override in child*/} + } + + /// + /// + /// + virtual public string icon + { + get { return null; } + set { /*override in child*/} + } + + /// + /// + /// + public bool draggable + { + get { return _draggable; } + set + { + if (_draggable != value) + { + _draggable = value; + InitDrag(); + } + } + } + + /// + /// + /// + public void StartDrag() + { + StartDrag(-1); + } + + /// + /// + /// + /// + public void StartDrag(int touchId) + { + if (displayObject.stage == null) + return; + + DragBegin(touchId); + } + + /// + /// + /// + public void StopDrag() + { + DragEnd(); + } + + /// + /// + /// + public bool dragging + { + get { return draggingObject == this; } + } + + /// + /// Transforms a point from the local coordinate system to global (Stage) coordinates. + /// + /// + /// + public Vector2 LocalToGlobal(Vector2 pt) + { + if (_pivotAsAnchor) + { + pt.x += _width * _pivotX; + pt.y += _height * _pivotY; + } + return displayObject.LocalToGlobal(pt); + } + + /// + /// Transforms a point from global (Stage) coordinates to the local coordinate system. + /// + /// + /// + public Vector2 GlobalToLocal(Vector2 pt) + { + pt = displayObject.GlobalToLocal(pt); + if (_pivotAsAnchor) + { + pt.x -= _width * _pivotX; + pt.y -= _height * _pivotY; + } + return pt; + } + + /// + /// + /// + /// + /// + public Rect LocalToGlobal(Rect rect) + { + Rect ret = new Rect(); + Vector2 v = this.LocalToGlobal(new Vector2(rect.xMin, rect.yMin)); + ret.xMin = v.x; + ret.yMin = v.y; + v = this.LocalToGlobal(new Vector2(rect.xMax, rect.yMax)); + ret.xMax = v.x; + ret.yMax = v.y; + return ret; + } + + /// + /// + /// + /// + /// + public Rect GlobalToLocal(Rect rect) + { + Rect ret = new Rect(); + Vector2 v = this.GlobalToLocal(new Vector2(rect.xMin, rect.yMin)); + ret.xMin = v.x; + ret.yMin = v.y; + v = this.GlobalToLocal(new Vector2(rect.xMax, rect.yMax)); + ret.xMax = v.x; + ret.yMax = v.y; + return ret; + } + + /// + /// Transforms a point from the local coordinate system to GRoot coordinates. + /// + /// + /// + /// + public Vector2 LocalToRoot(Vector2 pt, GRoot r) + { + pt = LocalToGlobal(pt); + if (r == null || r == GRoot.inst) + { + //fast + pt.x /= UIContentScaler.scaleFactor; + pt.y /= UIContentScaler.scaleFactor; + return pt; + } + else + return r.GlobalToLocal(pt); + } + + /// + /// Transforms a point from the GRoot coordinate to local coordinates system. + /// + /// + /// + /// + public Vector2 RootToLocal(Vector2 pt, GRoot r) + { + if (r == null || r == GRoot.inst) + { + //fast + pt.x *= UIContentScaler.scaleFactor; + pt.y *= UIContentScaler.scaleFactor; + } + else + pt = r.LocalToGlobal(pt); + return GlobalToLocal(pt); + } + + /// + /// + /// + /// + /// + public Vector2 WorldToLocal(Vector3 pt) + { + return WorldToLocal(pt, HitTestContext.cachedMainCamera); + } + + /// + /// + /// + /// + /// + /// + public Vector2 WorldToLocal(Vector3 pt, Camera camera) + { + Vector3 v = camera.WorldToScreenPoint(pt); + v.y = Screen.height - v.y; + v.z = 0; + return GlobalToLocal(v); + } + + /// + /// + /// + /// + /// + /// + public Vector2 TransformPoint(Vector2 pt, GObject targetSpace) + { + if (_pivotAsAnchor) + { + pt.x += _width * _pivotX; + pt.y += _height * _pivotY; + } + return this.displayObject.TransformPoint(pt, targetSpace != null ? targetSpace.displayObject : Stage.inst); + } + + /// + /// + /// + /// + /// + /// + public Rect TransformRect(Rect rect, GObject targetSpace) + { + if (_pivotAsAnchor) + { + rect.x += _width * _pivotX; + rect.y += _height * _pivotY; + } + return this.displayObject.TransformRect(rect, targetSpace != null ? targetSpace.displayObject : Stage.inst); + } + + /// + /// + /// + public bool isDisposed + { + get { return _disposed; } + } + + /// + /// + /// + virtual public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + + RemoveFromParent(); + RemoveEventListeners(); + relations.Dispose(); + relations = null; + for (int i = 0; i < 10; i++) + { + GearBase gear = _gears[i]; + if (gear != null) + gear.Dispose(); + } + if (displayObject != null) + { + displayObject.gOwner = null; + displayObject.Dispose(); + } + data = null; + } + + /// + /// + /// + public GImage asImage + { + get { return this as GImage; } + } + + /// + /// + /// + public GComponent asCom + { + get { return this as GComponent; } + } + + /// + /// + /// + public GButton asButton + { + get { return this as GButton; } + } + + /// + /// + /// + public GLabel asLabel + { + get { return this as GLabel; } + } + + /// + /// + /// + public GProgressBar asProgress + { + get { return this as GProgressBar; } + } + + /// + /// + /// + public GSlider asSlider + { + get { return this as GSlider; } + } + + /// + /// + /// + public GComboBox asComboBox + { + get { return this as GComboBox; } + } + + /// + /// + /// + public GTextField asTextField + { + get { return this as GTextField; } + } + + /// + /// + /// + public GRichTextField asRichTextField + { + get { return this as GRichTextField; } + } + + /// + /// + /// + public GTextInput asTextInput + { + get { return this as GTextInput; } + } + + /// + /// + /// + public GLoader asLoader + { + get { return this as GLoader; } + } + + /// + /// + /// + public GLoader3D asLoader3D + { + get { return this as GLoader3D; } + } + + /// + /// + /// + public GList asList + { + get { return this as GList; } + } + + /// + /// + /// + public GGraph asGraph + { + get { return this as GGraph; } + } + + /// + /// + /// + public GGroup asGroup + { + get { return this as GGroup; } + } + + /// + /// + /// + public GMovieClip asMovieClip + { + get { return this as GMovieClip; } + } + + /// + /// + /// + public GTree asTree + { + get { return this as GTree; } + } + + /// + /// + /// + public GTreeNode treeNode + { + get { return _treeNode; } + } + + virtual protected void CreateDisplayObject() + { + } + + internal void InternalSetParent(GComponent value) + { + parent = value; + } + + virtual protected void HandlePositionChanged() + { + if (displayObject != null) + { + float xv = _x; + float yv = _y; + if (!_pivotAsAnchor) + { + xv += _width * _pivotX; + yv += _height * _pivotY; + } + displayObject.location = new Vector3(xv, yv, _z); + } + } + + virtual protected void HandleSizeChanged() + { + if (displayObject != null) + displayObject.SetSize(_width, _height); + } + + virtual protected void HandleScaleChanged() + { + if (displayObject != null) + displayObject.SetScale(_scaleX, _scaleY); + } + + virtual protected void HandleGrayedChanged() + { + if (displayObject != null) + displayObject.grayed = _grayed; + } + + virtual protected void HandleAlphaChanged() + { + if (displayObject != null) + displayObject.alpha = _alpha; + } + + virtual internal protected void HandleVisibleChanged() + { + if (displayObject != null) + displayObject.visible = internalVisible2; + } + + virtual public void ConstructFromResource() + { + } + + virtual public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + buffer.Seek(beginPos, 0); + buffer.Skip(5); + + id = buffer.ReadS(); + name = buffer.ReadS(); + float f1 = buffer.ReadInt(); + float f2 = buffer.ReadInt(); + SetXY(f1, f2); + + if (buffer.ReadBool()) + { + initWidth = buffer.ReadInt(); + initHeight = buffer.ReadInt(); + SetSize(initWidth, initHeight, true); + } + + if (buffer.ReadBool()) + { + minWidth = buffer.ReadInt(); + maxWidth = buffer.ReadInt(); + minHeight = buffer.ReadInt(); + maxHeight = buffer.ReadInt(); + } + + if (buffer.ReadBool()) + { + f1 = buffer.ReadFloat(); + f2 = buffer.ReadFloat(); + SetScale(f1, f2); + } + + if (buffer.ReadBool()) + { + f1 = buffer.ReadFloat(); + f2 = buffer.ReadFloat(); + this.skew = new Vector2(f1, f2); + } + + if (buffer.ReadBool()) + { + f1 = buffer.ReadFloat(); + f2 = buffer.ReadFloat(); + SetPivot(f1, f2, buffer.ReadBool()); + } + + f1 = buffer.ReadFloat(); + if (f1 != 1) + this.alpha = f1; + + f1 = buffer.ReadFloat(); + if (f1 != 0) + this.rotation = f1; + + if (!buffer.ReadBool()) + this.visible = false; + if (!buffer.ReadBool()) + this.touchable = false; + if (buffer.ReadBool()) + this.grayed = true; + this.blendMode = (BlendMode)buffer.ReadByte(); + + int filter = buffer.ReadByte(); + if (filter == 1) + { + ColorFilter cf = new ColorFilter(); + this.filter = cf; + + cf.AdjustBrightness(buffer.ReadFloat()); + cf.AdjustContrast(buffer.ReadFloat()); + cf.AdjustSaturation(buffer.ReadFloat()); + cf.AdjustHue(buffer.ReadFloat()); + } + + string str = buffer.ReadS(); + if (str != null) + this.data = str; + } + + virtual public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + buffer.Seek(beginPos, 1); + + string str = buffer.ReadS(); + if (str != null) + this.tooltips = str; + + int groupId = buffer.ReadShort(); + if (groupId >= 0) + group = parent.GetChildAt(groupId) as GGroup; + + buffer.Seek(beginPos, 2); + + int cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + GearBase gear = GetGear(buffer.ReadByte()); + gear.Setup(buffer); + + buffer.position = nextPos; + } + } + + #region Drag support + Vector2 _dragTouchStartPos; + bool _dragTesting; + + static Vector2 sGlobalDragStart = new Vector2(); + static Rect sGlobalRect = new Rect(); + static bool sUpdateInDragging = false; + + private void InitDrag() + { + if (_draggable) + { + onTouchBegin.Add(__touchBegin); + onTouchMove.Add(__touchMove); + onTouchEnd.Add(__touchEnd); + } + else + { + onTouchBegin.Remove(__touchBegin); + onTouchMove.Remove(__touchMove); + onTouchEnd.Remove(__touchEnd); + } + } + + private void DragBegin(int touchId) + { + if (DispatchEvent("onDragStart", touchId)) + return; + + if (draggingObject != null) + { + GObject tmp = draggingObject; + draggingObject.StopDrag(); + draggingObject = null; + tmp.DispatchEvent("onDragEnd", null); + } + + onTouchMove.Add(__touchMove); + onTouchEnd.Add(__touchEnd); + + sGlobalDragStart = Stage.inst.GetTouchPosition(touchId); + sGlobalRect = this.LocalToGlobal(new Rect(0, 0, this.width, this.height)); + _dragTesting = false; + + draggingObject = this; + Stage.inst.AddTouchMonitor(touchId, this); + } + + private void DragEnd() + { + if (draggingObject == this) + { + _dragTesting = false; + draggingObject = null; + } + } + + private void __touchBegin(EventContext context) + { + if ((Stage.inst.focus is InputTextField) && ((InputTextField)Stage.inst.focus).editable) + { + _dragTesting = false; + return; + } + + InputEvent evt = context.inputEvent; + _dragTouchStartPos = evt.position; + _dragTesting = true; + context.CaptureTouch(); + } + + private void __touchMove(EventContext context) + { + InputEvent evt = context.inputEvent; + + if (_dragTesting && draggingObject != this) + { + int sensitivity; + if (Stage.touchScreen) + sensitivity = UIConfig.touchDragSensitivity; + else + sensitivity = UIConfig.clickDragSensitivity; + if (Mathf.Abs(_dragTouchStartPos.x - evt.x) < sensitivity + && Mathf.Abs(_dragTouchStartPos.y - evt.y) < sensitivity) + return; + + _dragTesting = false; + DragBegin(evt.touchId); + } + + if (draggingObject == this) + { + float xx = evt.x - sGlobalDragStart.x + sGlobalRect.x; + float yy = evt.y - sGlobalDragStart.y + sGlobalRect.y; + + if (dragBounds != null) + { + Rect rect = GRoot.inst.LocalToGlobal((Rect)dragBounds); + if (xx < rect.x) + xx = rect.x; + else if (xx + sGlobalRect.width > rect.xMax) + { + xx = rect.xMax - sGlobalRect.width; + if (xx < rect.x) + xx = rect.x; + } + + if (yy < rect.y) + yy = rect.y; + else if (yy + sGlobalRect.height > rect.yMax) + { + yy = rect.yMax - sGlobalRect.height; + if (yy < rect.y) + yy = rect.y; + } + } + + Vector2 pt = this.parent.GlobalToLocal(new Vector2(xx, yy)); + if (float.IsNaN(pt.x)) + return; + + sUpdateInDragging = true; + this.SetXY(Mathf.RoundToInt(pt.x), Mathf.RoundToInt(pt.y)); + sUpdateInDragging = false; + + DispatchEvent("onDragMove", null); + } + } + + private void __touchEnd(EventContext context) + { + if (draggingObject == this) + { + draggingObject = null; + DispatchEvent("onDragEnd", null); + } + } + #endregion + + #region Tween Helpers + public GTweener TweenMove(Vector2 endValue, float duration) + { + return GTween.To(this.xy, endValue, duration).SetTarget(this, TweenPropType.XY); + } + + public GTweener TweenMoveX(float endValue, float duration) + { + return GTween.To(_x, endValue, duration).SetTarget(this, TweenPropType.X); + } + + public GTweener TweenMoveY(float endValue, float duration) + { + return GTween.To(_y, endValue, duration).SetTarget(this, TweenPropType.Y); + } + + public GTweener TweenScale(Vector2 endValue, float duration) + { + return GTween.To(this.scale, endValue, duration).SetTarget(this, TweenPropType.Scale); + } + + public GTweener TweenScaleX(float endValue, float duration) + { + return GTween.To(_scaleX, endValue, duration).SetTarget(this, TweenPropType.ScaleX); + } + + public GTweener TweenScaleY(float endValue, float duration) + { + return GTween.To(_scaleY, endValue, duration).SetTarget(this, TweenPropType.ScaleY); + } + + public GTweener TweenResize(Vector2 endValue, float duration) + { + return GTween.To(this.size, endValue, duration).SetTarget(this, TweenPropType.Size); + } + + public GTweener TweenFade(float endValue, float duration) + { + return GTween.To(_alpha, endValue, duration).SetTarget(this, TweenPropType.Alpha); + } + + public GTweener TweenRotate(float endValue, float duration) + { + return GTween.To(_rotation, endValue, duration).SetTarget(this, TweenPropType.Rotation); + } + #endregion + } +} diff --git a/Assets/Scripts/UI/GObject.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObject.cs.meta similarity index 100% rename from Assets/Scripts/UI/GObject.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObject.cs.meta diff --git a/Assets/Scripts/UI/GObjectPool.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObjectPool.cs similarity index 96% rename from Assets/Scripts/UI/GObjectPool.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObjectPool.cs index 08dea2c8..baafadd9 100644 --- a/Assets/Scripts/UI/GObjectPool.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObjectPool.cs @@ -1,106 +1,106 @@ -using UnityEngine; -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GObjectPool is use for GObject pooling. - /// - public class GObjectPool - { - /// - /// Callback function when a new object is creating. - /// - /// - public delegate void InitCallbackDelegate(GObject obj); - - /// - /// Callback function when a new object is creating. - /// - public InitCallbackDelegate initCallback; - - Dictionary> _pool; - Transform _manager; - - /// - /// 需要设置一个manager,加入池里的对象都成为这个manager的孩子 - /// - /// - public GObjectPool(Transform manager) - { - _manager = manager; - _pool = new Dictionary>(); - } - - /// - /// Dispose all objects in the pool. - /// - public void Clear() - { - foreach (KeyValuePair> kv in _pool) - { - Queue list = kv.Value; - foreach (GObject obj in list) - obj.Dispose(); - } - _pool.Clear(); - } - - /// - /// - /// - public int count - { - get { return _pool.Count; } - } - - /// - /// - /// - /// - /// - public GObject GetObject(string url) - { - url = UIPackage.NormalizeURL(url); - if (url == null) - return null; - - Queue arr; - if (_pool.TryGetValue(url, out arr) - && arr.Count > 0) - return arr.Dequeue(); - - GObject obj = UIPackage.CreateObjectFromURL(url); - if (obj != null) - { - if (initCallback != null) - initCallback(obj); - } - - return obj; - } - - /// - /// - /// - /// - public void ReturnObject(GObject obj) - { - if (obj.displayObject.isDisposed) - return; - - string url = obj.resourceURL; - Queue arr; - if (!_pool.TryGetValue(url, out arr)) - { - arr = new Queue(); - _pool.Add(url, arr); - } - - if (_manager != null) - obj.displayObject.cachedTransform.SetParent(_manager, false); - arr.Enqueue(obj); - } - } -} +using UnityEngine; +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GObjectPool is use for GObject pooling. + /// + public class GObjectPool + { + /// + /// Callback function when a new object is creating. + /// + /// + public delegate void InitCallbackDelegate(GObject obj); + + /// + /// Callback function when a new object is creating. + /// + public InitCallbackDelegate initCallback; + + Dictionary> _pool; + Transform _manager; + + /// + /// 需要设置一个manager,加入池里的对象都成为这个manager的孩子 + /// + /// + public GObjectPool(Transform manager) + { + _manager = manager; + _pool = new Dictionary>(); + } + + /// + /// Dispose all objects in the pool. + /// + public void Clear() + { + foreach (KeyValuePair> kv in _pool) + { + Queue list = kv.Value; + foreach (GObject obj in list) + obj.Dispose(); + } + _pool.Clear(); + } + + /// + /// + /// + public int count + { + get { return _pool.Count; } + } + + /// + /// + /// + /// + /// + public GObject GetObject(string url) + { + url = UIPackage.NormalizeURL(url); + if (url == null) + return null; + + Queue arr; + if (_pool.TryGetValue(url, out arr) + && arr.Count > 0) + return arr.Dequeue(); + + GObject obj = UIPackage.CreateObjectFromURL(url); + if (obj != null) + { + if (initCallback != null) + initCallback(obj); + } + + return obj; + } + + /// + /// + /// + /// + public void ReturnObject(GObject obj) + { + if (obj.displayObject.isDisposed) + return; + + string url = obj.resourceURL; + Queue arr; + if (!_pool.TryGetValue(url, out arr)) + { + arr = new Queue(); + _pool.Add(url, arr); + } + + if (_manager != null) + obj.displayObject.cachedTransform.SetParent(_manager, false); + arr.Enqueue(obj); + } + } +} diff --git a/Assets/Scripts/UI/GObjectPool.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObjectPool.cs.meta similarity index 100% rename from Assets/Scripts/UI/GObjectPool.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GObjectPool.cs.meta diff --git a/Assets/Scripts/UI/GProgressBar.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GProgressBar.cs similarity index 96% rename from Assets/Scripts/UI/GProgressBar.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GProgressBar.cs index 862a08bc..50d37488 100644 --- a/Assets/Scripts/UI/GProgressBar.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GProgressBar.cs @@ -1,311 +1,311 @@ -using System; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GProgressBar class. - /// - public class GProgressBar : GComponent - { - double _min; - double _max; - double _value; - ProgressTitleType _titleType; - bool _reverse; - - GObject _titleObject; - GMovieClip _aniObject; - GObject _barObjectH; - GObject _barObjectV; - float _barMaxWidth; - float _barMaxHeight; - float _barMaxWidthDelta; - float _barMaxHeightDelta; - float _barStartX; - float _barStartY; - - public GProgressBar() - { - _value = 50; - _max = 100; - } - - /// - /// - /// - public ProgressTitleType titleType - { - - get - { - return _titleType; - } - set - { - if (_titleType != value) - { - _titleType = value; - Update(_value); - } - } - } - - /// - /// - /// - public double min - { - get - { - return _min; - } - set - { - if (_min != value) - { - _min = value; - Update(_value); - } - } - } - - /// - /// - /// - public double max - { - get - { - return _max; - } - set - { - if (_max != value) - { - _max = value; - Update(_value); - } - } - } - - /// - /// - /// - public double value - { - get - { - return _value; - } - set - { - if (_value != value) - { - GTween.Kill(this, TweenPropType.Progress, false); - - _value = value; - Update(_value); - } - } - } - - public bool reverse - { - get { return _reverse; } - set { _reverse = value; } - } - - /// - /// 动态改变进度值。 - /// - /// - /// - public GTweener TweenValue(double value, float duration) - { - double oldValule; - - GTweener twener = GTween.GetTween(this, TweenPropType.Progress); - if (twener != null) - { - oldValule = twener.value.d; - twener.Kill(false); - } - else - oldValule = _value; - - _value = value; - return GTween.ToDouble(oldValule, _value, duration) - .SetEase(EaseType.Linear) - .SetTarget(this, TweenPropType.Progress); - } - - /// - /// - /// - /// - public void Update(double newValue) - { - float percent = Mathf.Clamp01((float)((newValue - _min) / (_max - _min))); - if (_titleObject != null) - { - switch (_titleType) - { - case ProgressTitleType.Percent: - if (RTLSupport.BaseDirection == RTLSupport.DirectionType.RTL) - _titleObject.text = "%" + Mathf.FloorToInt(percent * 100); - else - _titleObject.text = Mathf.FloorToInt(percent * 100) + "%"; - break; - - case ProgressTitleType.ValueAndMax: - if (RTLSupport.BaseDirection == RTLSupport.DirectionType.RTL) - _titleObject.text = Math.Round(max) + "/" + Math.Round(newValue); - else - _titleObject.text = Math.Round(newValue) + "/" + Math.Round(max); - break; - - case ProgressTitleType.Value: - _titleObject.text = "" + Math.Round(newValue); - break; - - case ProgressTitleType.Max: - _titleObject.text = "" + Math.Round(_max); - break; - } - } - - float fullWidth = this.width - _barMaxWidthDelta; - float fullHeight = this.height - _barMaxHeightDelta; - if (!_reverse) - { - if (_barObjectH != null) - { - if (!SetFillAmount(_barObjectH, percent)) - _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); - } - if (_barObjectV != null) - { - if (!SetFillAmount(_barObjectV, percent)) - _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); - } - } - else - { - if (_barObjectH != null) - { - if (!SetFillAmount(_barObjectH, 1 - percent)) - { - _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); - _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); - } - } - if (_barObjectV != null) - { - if (!SetFillAmount(_barObjectV, 1 - percent)) - { - _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); - _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); - } - } - } - if (_aniObject != null) - _aniObject.frame = Mathf.RoundToInt(percent * 100); - - InvalidateBatchingState(true); - } - - bool SetFillAmount(GObject bar, float amount) - { - if ((bar is GImage) && ((GImage)bar).fillMethod != FillMethod.None) - ((GImage)bar).fillAmount = amount; - else if ((bar is GLoader) && ((GLoader)bar).fillMethod != FillMethod.None) - ((GLoader)bar).fillAmount = amount; - else - return false; - - return true; - } - - override protected void ConstructExtension(ByteBuffer buffer) - { - buffer.Seek(0, 6); - - _titleType = (ProgressTitleType)buffer.ReadByte(); - _reverse = buffer.ReadBool(); - - _titleObject = GetChild("title"); - _barObjectH = GetChild("bar"); - _barObjectV = GetChild("bar_v"); - _aniObject = GetChild("ani") as GMovieClip; - - if (_barObjectH != null) - { - _barMaxWidth = _barObjectH.width; - _barMaxWidthDelta = this.width - _barMaxWidth; - _barStartX = _barObjectH.x; - } - if (_barObjectV != null) - { - _barMaxHeight = _barObjectV.height; - _barMaxHeightDelta = this.height - _barMaxHeight; - _barStartY = _barObjectV.y; - } - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - if (!buffer.Seek(beginPos, 6)) - { - Update(_value); - return; - } - - if ((ObjectType)buffer.ReadByte() != packageItem.objectType) - { - Update(_value); - return; - } - - _value = buffer.ReadInt(); - _max = buffer.ReadInt(); - if (buffer.version >= 2) - _min = buffer.ReadInt(); - - if (buffer.version >= 5) - { - string sound = buffer.ReadS(); - if (!string.IsNullOrEmpty(sound)) - { - float volumeScale = buffer.ReadFloat(); - displayObject.onClick.Add(() => - { - NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip; - if (audioClip != null && audioClip.nativeClip != null) - Stage.inst.PlayOneShotSound(audioClip.nativeClip, volumeScale); - }); - } - else - buffer.Skip(4); - } - - Update(_value); - } - - override protected void HandleSizeChanged() - { - base.HandleSizeChanged(); - - if (_barObjectH != null) - _barMaxWidth = this.width - _barMaxWidthDelta; - if (_barObjectV != null) - _barMaxHeight = this.height - _barMaxHeightDelta; - - if (!this.underConstruct) - Update(_value); - } - } -} +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GProgressBar class. + /// + public class GProgressBar : GComponent + { + double _min; + double _max; + double _value; + ProgressTitleType _titleType; + bool _reverse; + + GObject _titleObject; + GMovieClip _aniObject; + GObject _barObjectH; + GObject _barObjectV; + float _barMaxWidth; + float _barMaxHeight; + float _barMaxWidthDelta; + float _barMaxHeightDelta; + float _barStartX; + float _barStartY; + + public GProgressBar() + { + _value = 50; + _max = 100; + } + + /// + /// + /// + public ProgressTitleType titleType + { + + get + { + return _titleType; + } + set + { + if (_titleType != value) + { + _titleType = value; + Update(_value); + } + } + } + + /// + /// + /// + public double min + { + get + { + return _min; + } + set + { + if (_min != value) + { + _min = value; + Update(_value); + } + } + } + + /// + /// + /// + public double max + { + get + { + return _max; + } + set + { + if (_max != value) + { + _max = value; + Update(_value); + } + } + } + + /// + /// + /// + public double value + { + get + { + return _value; + } + set + { + if (_value != value) + { + GTween.Kill(this, TweenPropType.Progress, false); + + _value = value; + Update(_value); + } + } + } + + public bool reverse + { + get { return _reverse; } + set { _reverse = value; } + } + + /// + /// 动态改变进度值。 + /// + /// + /// + public GTweener TweenValue(double value, float duration) + { + double oldValule; + + GTweener twener = GTween.GetTween(this, TweenPropType.Progress); + if (twener != null) + { + oldValule = twener.value.d; + twener.Kill(false); + } + else + oldValule = _value; + + _value = value; + return GTween.ToDouble(oldValule, _value, duration) + .SetEase(EaseType.Linear) + .SetTarget(this, TweenPropType.Progress); + } + + /// + /// + /// + /// + public void Update(double newValue) + { + float percent = Mathf.Clamp01((float)((newValue - _min) / (_max - _min))); + if (_titleObject != null) + { + switch (_titleType) + { + case ProgressTitleType.Percent: + if (RTLSupport.BaseDirection == RTLSupport.DirectionType.RTL) + _titleObject.text = "%" + Mathf.FloorToInt(percent * 100); + else + _titleObject.text = Mathf.FloorToInt(percent * 100) + "%"; + break; + + case ProgressTitleType.ValueAndMax: + if (RTLSupport.BaseDirection == RTLSupport.DirectionType.RTL) + _titleObject.text = Math.Round(max) + "/" + Math.Round(newValue); + else + _titleObject.text = Math.Round(newValue) + "/" + Math.Round(max); + break; + + case ProgressTitleType.Value: + _titleObject.text = "" + Math.Round(newValue); + break; + + case ProgressTitleType.Max: + _titleObject.text = "" + Math.Round(_max); + break; + } + } + + float fullWidth = this.width - _barMaxWidthDelta; + float fullHeight = this.height - _barMaxHeightDelta; + if (!_reverse) + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, percent)) + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, percent)) + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + } + } + else + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, 1 - percent)) + { + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); + } + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, 1 - percent)) + { + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); + } + } + } + if (_aniObject != null) + _aniObject.frame = Mathf.RoundToInt(percent * 100); + + InvalidateBatchingState(true); + } + + bool SetFillAmount(GObject bar, float amount) + { + if ((bar is GImage) && ((GImage)bar).fillMethod != FillMethod.None) + ((GImage)bar).fillAmount = amount; + else if ((bar is GLoader) && ((GLoader)bar).fillMethod != FillMethod.None) + ((GLoader)bar).fillAmount = amount; + else + return false; + + return true; + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _titleType = (ProgressTitleType)buffer.ReadByte(); + _reverse = buffer.ReadBool(); + + _titleObject = GetChild("title"); + _barObjectH = GetChild("bar"); + _barObjectV = GetChild("bar_v"); + _aniObject = GetChild("ani") as GMovieClip; + + if (_barObjectH != null) + { + _barMaxWidth = _barObjectH.width; + _barMaxWidthDelta = this.width - _barMaxWidth; + _barStartX = _barObjectH.x; + } + if (_barObjectV != null) + { + _barMaxHeight = _barObjectV.height; + _barMaxHeightDelta = this.height - _barMaxHeight; + _barStartY = _barObjectV.y; + } + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + { + Update(_value); + return; + } + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + { + Update(_value); + return; + } + + _value = buffer.ReadInt(); + _max = buffer.ReadInt(); + if (buffer.version >= 2) + _min = buffer.ReadInt(); + + if (buffer.version >= 5) + { + string sound = buffer.ReadS(); + if (!string.IsNullOrEmpty(sound)) + { + float volumeScale = buffer.ReadFloat(); + displayObject.onClick.Add(() => + { + NAudioClip audioClip = UIPackage.GetItemAssetByURL(sound) as NAudioClip; + if (audioClip != null && audioClip.nativeClip != null) + Stage.inst.PlayOneShotSound(audioClip.nativeClip, volumeScale); + }); + } + else + buffer.Skip(4); + } + + Update(_value); + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (_barObjectH != null) + _barMaxWidth = this.width - _barMaxWidthDelta; + if (_barObjectV != null) + _barMaxHeight = this.height - _barMaxHeightDelta; + + if (!this.underConstruct) + Update(_value); + } + } +} diff --git a/Assets/Scripts/UI/GProgressBar.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GProgressBar.cs.meta similarity index 100% rename from Assets/Scripts/UI/GProgressBar.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GProgressBar.cs.meta diff --git a/Assets/Scripts/UI/GRichTextField.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRichTextField.cs similarity index 96% rename from Assets/Scripts/UI/GRichTextField.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRichTextField.cs index d6a974cf..7df005e5 100644 --- a/Assets/Scripts/UI/GRichTextField.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRichTextField.cs @@ -1,53 +1,53 @@ -using System.Collections.Generic; -using FairyGUI.Utils; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// GRichTextField class. - /// - public class GRichTextField : GTextField - { - /// - /// - /// - public RichTextField richTextField { get; private set; } - - public GRichTextField() - : base() - { - } - - override protected void CreateDisplayObject() - { - richTextField = new RichTextField(); - richTextField.gOwner = this; - displayObject = richTextField; - - _textField = richTextField.textField; - } - - override protected void SetTextFieldText() - { - string str = _text; - if (_templateVars != null) - str = ParseTemplate(str); - - _textField.maxWidth = maxWidth; - if (_ubbEnabled) - richTextField.htmlText = UBBParser.inst.Parse(str); - else - richTextField.htmlText = str; - } - - /// - /// - /// - public Dictionary emojies - { - get { return richTextField.emojies; } - set { richTextField.emojies = value; } - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// GRichTextField class. + /// + public class GRichTextField : GTextField + { + /// + /// + /// + public RichTextField richTextField { get; private set; } + + public GRichTextField() + : base() + { + } + + override protected void CreateDisplayObject() + { + richTextField = new RichTextField(); + richTextField.gOwner = this; + displayObject = richTextField; + + _textField = richTextField.textField; + } + + override protected void SetTextFieldText() + { + string str = _text; + if (_templateVars != null) + str = ParseTemplate(str); + + _textField.maxWidth = maxWidth; + if (_ubbEnabled) + richTextField.htmlText = UBBParser.inst.Parse(str); + else + richTextField.htmlText = str; + } + + /// + /// + /// + public Dictionary emojies + { + get { return richTextField.emojies; } + set { richTextField.emojies = value; } + } + } +} diff --git a/Assets/Scripts/UI/GRichTextField.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRichTextField.cs.meta similarity index 100% rename from Assets/Scripts/UI/GRichTextField.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRichTextField.cs.meta diff --git a/Assets/Scripts/UI/GRoot.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRoot.cs similarity index 96% rename from Assets/Scripts/UI/GRoot.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRoot.cs index 42fff247..83735b42 100644 --- a/Assets/Scripts/UI/GRoot.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRoot.cs @@ -1,847 +1,847 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// GRoot is a topmost component of UI display list.You dont need to create GRoot. It is created automatically. - /// - public class GRoot : GComponent - { - /// - /// - /// - public static float contentScaleFactor - { - get { return UIContentScaler.scaleFactor; } - } - - /// - /// - /// - public static int contentScaleLevel - { - get { return UIContentScaler.scaleLevel; } - } - - GGraph _modalLayer; - GObject _modalWaitPane; - List _popupStack; - List _justClosedPopups; - HashSet _specialPopups; - GObject _tooltipWin; - GObject _defaultTooltipWin; - - internal static GRoot _inst; - public static GRoot inst - { - get - { - if (_inst == null) - Stage.Instantiate(); - - return _inst; - } - } - - public GRoot() - { - this.name = this.rootContainer.name = this.rootContainer.gameObject.name = "GRoot"; - this.opaque = false; - - _popupStack = new List(); - _justClosedPopups = new List(); - _specialPopups = new HashSet(); - - Stage.inst.onTouchBegin.AddCapture(__stageTouchBegin); - Stage.inst.onTouchEnd.AddCapture(__stageTouchEnd); - } - - override public void Dispose() - { - base.Dispose(); - - Stage.inst.onTouchBegin.RemoveCapture(__stageTouchBegin); - Stage.inst.onTouchEnd.RemoveCapture(__stageTouchEnd); - } - - /// - /// Set content scale factor. - /// - /// Design resolution of x axis. - /// Design resolution of y axis. - public void SetContentScaleFactor(int designResolutionX, int designResolutionY) - { - SetContentScaleFactor(designResolutionX, designResolutionY, UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); - } - - /// - /// Set content scale factor. - /// - /// Design resolution of x axis. - /// Design resolution of y axis. - /// Match mode. - public void SetContentScaleFactor(int designResolutionX, int designResolutionY, UIContentScaler.ScreenMatchMode screenMatchMode) - { - UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); - scaler.designResolutionX = designResolutionX; - scaler.designResolutionY = designResolutionY; - scaler.scaleMode = UIContentScaler.ScaleMode.ScaleWithScreenSize; - scaler.screenMatchMode = screenMatchMode; - scaler.ApplyChange(); - ApplyContentScaleFactor(); - } - - /// - /// - /// - /// - public void SetContentScaleFactor(float constantScaleFactor) - { - UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); - scaler.scaleMode = UIContentScaler.ScaleMode.ConstantPixelSize; - scaler.constantScaleFactor = constantScaleFactor; - scaler.ApplyChange(); - ApplyContentScaleFactor(); - } - - /// - /// This is called after screen size changed. - /// - public void ApplyContentScaleFactor() - { - this.SetSize(Mathf.CeilToInt(Stage.inst.width / UIContentScaler.scaleFactor), Mathf.CeilToInt(Stage.inst.height / UIContentScaler.scaleFactor)); - this.SetScale(UIContentScaler.scaleFactor, UIContentScaler.scaleFactor); - } - - /// - /// Display a window. - /// - /// - public void ShowWindow(Window win) - { - AddChild(win); - AdjustModalLayer(); - } - - /// - /// Call window.Hide - /// 关闭一个窗口。将调用Window.Hide方法。 - /// - /// - public void HideWindow(Window win) - { - win.Hide(); - } - - /// - /// Remove a window from stage immediatelly. window.Hide/window.OnHide will never be called. - ///立刻关闭一个窗口。不会调用Window.Hide方法,Window.OnHide也不会被调用。 - /// - /// - public void HideWindowImmediately(Window win) - { - HideWindowImmediately(win, false); - } - - /// - /// Remove a window from stage immediatelly. window.Hide/window.OnHide will never be called. - /// 立刻关闭一个窗口。不会调用Window.Hide方法,Window.OnHide也不会被调用。 - /// - /// - /// True to dispose the window. - public void HideWindowImmediately(Window win, bool dispose) - { - if (win.parent == this) - RemoveChild(win, dispose); - else if (dispose) - win.Dispose(); - - AdjustModalLayer(); - } - - /// - /// 将一个窗口提到所有窗口的最前面 - /// - /// - public void BringToFront(Window win) - { - int cnt = this.numChildren; - int i; - if (_modalLayer != null && _modalLayer.parent != null && !win.modal) - i = GetChildIndex(_modalLayer) - 1; - else - i = cnt - 1; - - for (; i >= 0; i--) - { - GObject g = GetChildAt(i); - if (g == win) - return; - if (g is Window) - break; - } - - if (i >= 0) - SetChildIndex(win, i); - } - - /// - /// Display a modal layer and a waiting sign in the front. - /// 显示一个半透明层和一个等待标志在最前面。半透明层的颜色可以通过UIConfig.modalLayerColor设定。 - /// 等待标志的资源可以通过UIConfig.globalModalWaiting。等待标志组件会设置为屏幕大小,请内部做好关联。 - /// - public void ShowModalWait() - { - if (UIConfig.globalModalWaiting != null) - { - if (_modalWaitPane == null || _modalWaitPane.isDisposed) - { - _modalWaitPane = UIPackage.CreateObjectFromURL(UIConfig.globalModalWaiting); - _modalWaitPane.SetHome(this); - } - _modalWaitPane.SetSize(this.width, this.height); - _modalWaitPane.AddRelation(this, RelationType.Size); - - AddChild(_modalWaitPane); - } - } - - /// - /// Hide modal layer and waiting sign. - /// - public void CloseModalWait() - { - if (_modalWaitPane != null && _modalWaitPane.parent != null) - RemoveChild(_modalWaitPane); - } - - /// - /// Close all windows except modal windows. - /// - public void CloseAllExceptModals() - { - GObject[] arr = _children.ToArray(); - foreach (GObject g in arr) - { - if ((g is Window) && !(g as Window).modal) - HideWindowImmediately(g as Window); - } - } - - /// - /// Close all windows. - /// - public void CloseAllWindows() - { - GObject[] arr = _children.ToArray(); - foreach (GObject g in arr) - { - if (g is Window) - HideWindowImmediately(g as Window); - } - } - - /// - /// Get window on top. - /// - /// - public Window GetTopWindow() - { - int cnt = this.numChildren; - for (int i = cnt - 1; i >= 0; i--) - { - GObject g = this.GetChildAt(i); - if (g is Window) - { - return (Window)(g); - } - } - - return null; - } - - /// - /// - /// - public GGraph modalLayer - { - get - { - if (_modalLayer == null || _modalLayer.isDisposed) - CreateModalLayer(); - - return _modalLayer; - } - } - - void CreateModalLayer() - { - _modalLayer = new GGraph(); - _modalLayer.DrawRect(this.width, this.height, 0, Color.white, UIConfig.modalLayerColor); - _modalLayer.AddRelation(this, RelationType.Size); - _modalLayer.name = _modalLayer.gameObjectName = "ModalLayer"; - _modalLayer.SetHome(this); - } - - /// - /// Return true if a modal window is on stage. - /// - public bool hasModalWindow - { - get { return _modalLayer != null && _modalLayer.parent != null; } - } - - /// - /// Return true if modal waiting layer is on stage. - /// - public bool modalWaiting - { - get - { - return (_modalWaitPane != null) && _modalWaitPane.onStage; - } - } - - /// - /// Get current touch target. (including hover) - /// - public GObject touchTarget - { - get - { - return DisplayObjectToGObject(Stage.inst.touchTarget); - } - } - - /// - /// - /// - /// - /// - public GObject DisplayObjectToGObject(DisplayObject obj) - { - while (obj != null) - { - if (obj.gOwner != null) - return obj.gOwner; - - obj = obj.parent; - } - return null; - } - - private void AdjustModalLayer() - { - if (_modalLayer == null || _modalLayer.isDisposed) - CreateModalLayer(); - - int cnt = this.numChildren; - - if (_modalWaitPane != null && _modalWaitPane.parent != null) - SetChildIndex(_modalWaitPane, cnt - 1); - - for (int i = cnt - 1; i >= 0; i--) - { - GObject g = this.GetChildAt(i); - if ((g is Window) && (g as Window).modal) - { - if (_modalLayer.parent == null) - AddChildAt(_modalLayer, i); - else - SetChildIndexBefore(_modalLayer, i); - return; - } - } - - if (_modalLayer.parent != null) - RemoveChild(_modalLayer); - } - - /// - /// Show a popup object. - /// 显示一个popup。 - /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 - /// - /// - public void ShowPopup(GObject popup) - { - ShowPopup(popup, null, PopupDirection.Auto, false); - } - - /// - /// Show a popup object along with the specific target object. - /// 显示一个popup。将popup显示在指定对象的上边或者下边。 - /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 - /// - /// - /// - public void ShowPopup(GObject popup, GObject target) - { - ShowPopup(popup, target, PopupDirection.Auto, false); - } - - [Obsolete] - public void ShowPopup(GObject popup, GObject target, object downward) - { - ShowPopup(popup, target, - downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), - false); - } - - /// - /// Show a popup object along with the specific target object. - /// 显示一个popup。将popup显示在指定对象的上方或者下方。 - /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 - /// - /// - /// - /// - public void ShowPopup(GObject popup, GObject target, PopupDirection dir) - { - ShowPopup(popup, target, dir, false); - } - - /// - /// Show a popup object along with the specific target object. - /// 显示一个popup。将popup显示在指定对象的上方或者下方。 - /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 - /// 默认情况下,popup在touchEnd事件中关闭;特别设置closeUntilUpEvent=true则可使该popup在touchEnd中才关闭。 - /// - /// - /// - /// - /// - public void ShowPopup(GObject popup, GObject target, PopupDirection dir, bool closeUntilUpEvent) - { - if (_popupStack.Count > 0) - { - int k = _popupStack.IndexOf(popup); - if (k != -1) - { - for (int i = _popupStack.Count - 1; i >= k; i--) - { - int last = _popupStack.Count - 1; - GObject obj = _popupStack[last]; - ClosePopup(obj); - _popupStack.RemoveAt(last); - _specialPopups.Remove(obj); - } - } - } - _popupStack.Add(popup); - if (closeUntilUpEvent) - _specialPopups.Add(popup); - - if (target != null) - { - GObject p = target; - while (p != null) - { - if (p.parent == this) - { - if (popup.sortingOrder < p.sortingOrder) - { - popup.sortingOrder = p.sortingOrder; - } - break; - } - p = p.parent; - } - } - - AddChild(popup); - AdjustModalLayer(); - - if ((popup is Window) && target == null && dir == PopupDirection.Auto) - return; - - Vector2 pos = GetPoupPosition(popup, target, dir); - popup.xy = pos; - } - - [Obsolete] - public Vector2 GetPoupPosition(GObject popup, GObject target, object downward) - { - return GetPoupPosition(popup, target, - downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up)); - } - - /// - /// - /// - /// - /// - /// - /// - public Vector2 GetPoupPosition(GObject popup, GObject target, PopupDirection dir) - { - Vector2 pos; - Vector2 size = Vector2.zero; - if (target != null) - { - pos = target.LocalToRoot(Vector2.zero, this); - size = target.LocalToRoot(target.size, this) - pos; - } - else - { - pos = this.GlobalToLocal(Stage.inst.touchPosition); - } - float xx, yy; - xx = pos.x; - if (xx + popup.width > this.width) - xx = xx + size.x - popup.width; - yy = pos.y + size.y; - if ((dir == PopupDirection.Auto && yy + popup.height > this.height) - || dir == PopupDirection.Up) - { - yy = pos.y - popup.height - 1; - if (yy < 0) - { - yy = 0; - xx += size.x / 2; - } - } - - return new Vector2(Mathf.RoundToInt(xx), Mathf.RoundToInt(yy)); - } - - /// - /// If a popup is showing, then close it; otherwise, open it. - /// - /// - public void TogglePopup(GObject popup) - { - TogglePopup(popup, null, PopupDirection.Auto, false); - } - - /// - /// - /// - /// - /// - public void TogglePopup(GObject popup, GObject target) - { - TogglePopup(popup, target, PopupDirection.Auto, false); - } - - [Obsolete] - public void TogglePopup(GObject popup, GObject target, object downward) - { - TogglePopup(popup, target, - downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), - false); - } - - /// - /// - /// - /// - /// - /// - public void TogglePopup(GObject popup, GObject target, PopupDirection dir) - { - TogglePopup(popup, target, dir, false); - } - - /// - /// - /// - /// - /// - /// - /// - public void TogglePopup(GObject popup, GObject target, PopupDirection dir, bool closeUntilUpEvent) - { - if (_justClosedPopups.IndexOf(popup) != -1) - return; - - ShowPopup(popup, target, dir, closeUntilUpEvent); - } - - /// - /// Close all popups. - /// - public void HidePopup() - { - HidePopup(null); - } - - /// - /// Close a popup. - /// - /// - public void HidePopup(GObject popup) - { - if (popup != null) - { - int k = _popupStack.IndexOf(popup); - if (k != -1) - { - for (int i = _popupStack.Count - 1; i >= k; i--) - { - int last = _popupStack.Count - 1; - GObject obj = _popupStack[last]; - ClosePopup(obj); - _popupStack.RemoveAt(last); - _specialPopups.Remove(obj); - } - } - } - else - { - foreach (GObject obj in _popupStack) - ClosePopup(obj); - _popupStack.Clear(); - _specialPopups.Clear(); - } - } - - /// - /// - /// - public bool hasAnyPopup - { - get { return _popupStack.Count > 0; } - } - - void ClosePopup(GObject target) - { - if (target.parent != null) - { - if (target is Window) - ((Window)target).Hide(); - else - RemoveChild(target); - } - } - - /// - /// - /// - /// - public void ShowTooltips(string msg) - { - ShowTooltips(msg, 0.1f); - } - - /// - /// - /// - /// - /// - public void ShowTooltips(string msg, float delay) - { - if (_defaultTooltipWin == null || _defaultTooltipWin.isDisposed) - { - string resourceURL = UIConfig.tooltipsWin; - if (string.IsNullOrEmpty(resourceURL)) - { - Debug.LogWarning("FairyGUI: UIConfig.tooltipsWin not defined"); - return; - } - - _defaultTooltipWin = UIPackage.CreateObjectFromURL(resourceURL); - _defaultTooltipWin.SetHome(this); - _defaultTooltipWin.touchable = false; - } - - _defaultTooltipWin.text = msg; - ShowTooltipsWin(_defaultTooltipWin, delay); - } - - /// - /// - /// - /// - public void ShowTooltipsWin(GObject tooltipWin) - { - ShowTooltipsWin(tooltipWin, 0.1f); - } - - /// - /// - /// - /// - /// - public void ShowTooltipsWin(GObject tooltipWin, float delay) - { - HideTooltips(); - - _tooltipWin = tooltipWin; - Timers.inst.Add(delay, 1, __showTooltipsWin); - } - - void __showTooltipsWin(object param) - { - if (_tooltipWin == null) - return; - - float xx = Stage.inst.touchPosition.x + 10; - float yy = Stage.inst.touchPosition.y + 20; - - Vector2 pt = this.GlobalToLocal(new Vector2(xx, yy)); - xx = pt.x; - yy = pt.y; - - if (xx + _tooltipWin.width > this.width) - xx = xx - _tooltipWin.width; - if (yy + _tooltipWin.height > this.height) - { - yy = yy - _tooltipWin.height - 1; - if (yy < 0) - yy = 0; - } - - _tooltipWin.x = Mathf.RoundToInt(xx); - _tooltipWin.y = Mathf.RoundToInt(yy); - AddChild(_tooltipWin); - } - - /// - /// - /// - public void HideTooltips() - { - if (_tooltipWin != null) - { - if (_tooltipWin.parent != null) - RemoveChild(_tooltipWin); - _tooltipWin = null; - } - } - - /// - /// - /// - public GObject focus - { - get - { - GObject obj = DisplayObjectToGObject(Stage.inst.focus); - if (obj != null && !IsAncestorOf(obj)) - return null; - else - return obj; - } - - set - { - if (value == null) - Stage.inst.focus = null; - else - Stage.inst.focus = value.displayObject; - } - } - - void __stageTouchBegin(EventContext context) - { - if (_tooltipWin != null) - HideTooltips(); - - CheckPopups(true); - } - - void __stageTouchEnd(EventContext context) - { - CheckPopups(false); - } - - void CheckPopups(bool touchBegin) - { - if (touchBegin) - _justClosedPopups.Clear(); - - if (_popupStack.Count > 0) - { - DisplayObject mc = Stage.inst.touchTarget as DisplayObject; - bool handled = false; - while (mc != Stage.inst && mc != null) - { - if (mc.gOwner != null) - { - int k = _popupStack.IndexOf(mc.gOwner); - if (k != -1) - { - for (int i = _popupStack.Count - 1; i > k; i--) - { - int last = _popupStack.Count - 1; - GObject popup = _popupStack[last]; - if (touchBegin == _specialPopups.Contains(popup)) - continue; - - ClosePopup(popup); - _justClosedPopups.Add(popup); - _popupStack.RemoveAt(last); - _specialPopups.Remove(popup); - } - handled = true; - break; - } - } - mc = mc.parent; - } - - if (!handled) - { - for (int i = _popupStack.Count - 1; i >= 0; i--) - { - GObject popup = _popupStack[i]; - if (touchBegin == _specialPopups.Contains(popup)) - continue; - - ClosePopup(popup); - _justClosedPopups.Add(popup); - _popupStack.RemoveAt(i); - _specialPopups.Remove(popup); - } - } - } - } - - /// - /// - /// - public void EnableSound() - { - Stage.inst.EnableSound(); - } - - /// - /// - /// - public void DisableSound() - { - Stage.inst.DisableSound(); - } - - /// - /// - /// - /// - /// - public void PlayOneShotSound(AudioClip clip, float volumeScale) - { - Stage.inst.PlayOneShotSound(clip, volumeScale); - } - - /// - /// - /// - /// - public void PlayOneShotSound(AudioClip clip) - { - Stage.inst.PlayOneShotSound(clip); - } - - /// - /// - /// - public float soundVolume - { - get { return Stage.inst.soundVolume; } - set { Stage.inst.soundVolume = value; } - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// GRoot is a topmost component of UI display list.You dont need to create GRoot. It is created automatically. + /// + public class GRoot : GComponent + { + /// + /// + /// + public static float contentScaleFactor + { + get { return UIContentScaler.scaleFactor; } + } + + /// + /// + /// + public static int contentScaleLevel + { + get { return UIContentScaler.scaleLevel; } + } + + GGraph _modalLayer; + GObject _modalWaitPane; + List _popupStack; + List _justClosedPopups; + HashSet _specialPopups; + GObject _tooltipWin; + GObject _defaultTooltipWin; + + internal static GRoot _inst; + public static GRoot inst + { + get + { + if (_inst == null) + Stage.Instantiate(); + + return _inst; + } + } + + public GRoot() + { + this.name = this.rootContainer.name = this.rootContainer.gameObject.name = "GRoot"; + this.opaque = false; + + _popupStack = new List(); + _justClosedPopups = new List(); + _specialPopups = new HashSet(); + + Stage.inst.onTouchBegin.AddCapture(__stageTouchBegin); + Stage.inst.onTouchEnd.AddCapture(__stageTouchEnd); + } + + override public void Dispose() + { + base.Dispose(); + + Stage.inst.onTouchBegin.RemoveCapture(__stageTouchBegin); + Stage.inst.onTouchEnd.RemoveCapture(__stageTouchEnd); + } + + /// + /// Set content scale factor. + /// + /// Design resolution of x axis. + /// Design resolution of y axis. + public void SetContentScaleFactor(int designResolutionX, int designResolutionY) + { + SetContentScaleFactor(designResolutionX, designResolutionY, UIContentScaler.ScreenMatchMode.MatchWidthOrHeight); + } + + /// + /// Set content scale factor. + /// + /// Design resolution of x axis. + /// Design resolution of y axis. + /// Match mode. + public void SetContentScaleFactor(int designResolutionX, int designResolutionY, UIContentScaler.ScreenMatchMode screenMatchMode) + { + UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); + scaler.designResolutionX = designResolutionX; + scaler.designResolutionY = designResolutionY; + scaler.scaleMode = UIContentScaler.ScaleMode.ScaleWithScreenSize; + scaler.screenMatchMode = screenMatchMode; + scaler.ApplyChange(); + ApplyContentScaleFactor(); + } + + /// + /// + /// + /// + public void SetContentScaleFactor(float constantScaleFactor) + { + UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); + scaler.scaleMode = UIContentScaler.ScaleMode.ConstantPixelSize; + scaler.constantScaleFactor = constantScaleFactor; + scaler.ApplyChange(); + ApplyContentScaleFactor(); + } + + /// + /// This is called after screen size changed. + /// + public void ApplyContentScaleFactor() + { + this.SetSize(Mathf.CeilToInt(Stage.inst.width / UIContentScaler.scaleFactor), Mathf.CeilToInt(Stage.inst.height / UIContentScaler.scaleFactor)); + this.SetScale(UIContentScaler.scaleFactor, UIContentScaler.scaleFactor); + } + + /// + /// Display a window. + /// + /// + public void ShowWindow(Window win) + { + AddChild(win); + AdjustModalLayer(); + } + + /// + /// Call window.Hide + /// 关闭一个窗口。将调用Window.Hide方法。 + /// + /// + public void HideWindow(Window win) + { + win.Hide(); + } + + /// + /// Remove a window from stage immediatelly. window.Hide/window.OnHide will never be called. + ///立刻关闭一个窗口。不会调用Window.Hide方法,Window.OnHide也不会被调用。 + /// + /// + public void HideWindowImmediately(Window win) + { + HideWindowImmediately(win, false); + } + + /// + /// Remove a window from stage immediatelly. window.Hide/window.OnHide will never be called. + /// 立刻关闭一个窗口。不会调用Window.Hide方法,Window.OnHide也不会被调用。 + /// + /// + /// True to dispose the window. + public void HideWindowImmediately(Window win, bool dispose) + { + if (win.parent == this) + RemoveChild(win, dispose); + else if (dispose) + win.Dispose(); + + AdjustModalLayer(); + } + + /// + /// 将一个窗口提到所有窗口的最前面 + /// + /// + public void BringToFront(Window win) + { + int cnt = this.numChildren; + int i; + if (_modalLayer != null && _modalLayer.parent != null && !win.modal) + i = GetChildIndex(_modalLayer) - 1; + else + i = cnt - 1; + + for (; i >= 0; i--) + { + GObject g = GetChildAt(i); + if (g == win) + return; + if (g is Window) + break; + } + + if (i >= 0) + SetChildIndex(win, i); + } + + /// + /// Display a modal layer and a waiting sign in the front. + /// 显示一个半透明层和一个等待标志在最前面。半透明层的颜色可以通过UIConfig.modalLayerColor设定。 + /// 等待标志的资源可以通过UIConfig.globalModalWaiting。等待标志组件会设置为屏幕大小,请内部做好关联。 + /// + public void ShowModalWait() + { + if (UIConfig.globalModalWaiting != null) + { + if (_modalWaitPane == null || _modalWaitPane.isDisposed) + { + _modalWaitPane = UIPackage.CreateObjectFromURL(UIConfig.globalModalWaiting); + _modalWaitPane.SetHome(this); + } + _modalWaitPane.SetSize(this.width, this.height); + _modalWaitPane.AddRelation(this, RelationType.Size); + + AddChild(_modalWaitPane); + } + } + + /// + /// Hide modal layer and waiting sign. + /// + public void CloseModalWait() + { + if (_modalWaitPane != null && _modalWaitPane.parent != null) + RemoveChild(_modalWaitPane); + } + + /// + /// Close all windows except modal windows. + /// + public void CloseAllExceptModals() + { + GObject[] arr = _children.ToArray(); + foreach (GObject g in arr) + { + if ((g is Window) && !(g as Window).modal) + HideWindowImmediately(g as Window); + } + } + + /// + /// Close all windows. + /// + public void CloseAllWindows() + { + GObject[] arr = _children.ToArray(); + foreach (GObject g in arr) + { + if (g is Window) + HideWindowImmediately(g as Window); + } + } + + /// + /// Get window on top. + /// + /// + public Window GetTopWindow() + { + int cnt = this.numChildren; + for (int i = cnt - 1; i >= 0; i--) + { + GObject g = this.GetChildAt(i); + if (g is Window) + { + return (Window)(g); + } + } + + return null; + } + + /// + /// + /// + public GGraph modalLayer + { + get + { + if (_modalLayer == null || _modalLayer.isDisposed) + CreateModalLayer(); + + return _modalLayer; + } + } + + void CreateModalLayer() + { + _modalLayer = new GGraph(); + _modalLayer.DrawRect(this.width, this.height, 0, Color.white, UIConfig.modalLayerColor); + _modalLayer.AddRelation(this, RelationType.Size); + _modalLayer.name = _modalLayer.gameObjectName = "ModalLayer"; + _modalLayer.SetHome(this); + } + + /// + /// Return true if a modal window is on stage. + /// + public bool hasModalWindow + { + get { return _modalLayer != null && _modalLayer.parent != null; } + } + + /// + /// Return true if modal waiting layer is on stage. + /// + public bool modalWaiting + { + get + { + return (_modalWaitPane != null) && _modalWaitPane.onStage; + } + } + + /// + /// Get current touch target. (including hover) + /// + public GObject touchTarget + { + get + { + return DisplayObjectToGObject(Stage.inst.touchTarget); + } + } + + /// + /// + /// + /// + /// + public GObject DisplayObjectToGObject(DisplayObject obj) + { + while (obj != null) + { + if (obj.gOwner != null) + return obj.gOwner; + + obj = obj.parent; + } + return null; + } + + private void AdjustModalLayer() + { + if (_modalLayer == null || _modalLayer.isDisposed) + CreateModalLayer(); + + int cnt = this.numChildren; + + if (_modalWaitPane != null && _modalWaitPane.parent != null) + SetChildIndex(_modalWaitPane, cnt - 1); + + for (int i = cnt - 1; i >= 0; i--) + { + GObject g = this.GetChildAt(i); + if ((g is Window) && (g as Window).modal) + { + if (_modalLayer.parent == null) + AddChildAt(_modalLayer, i); + else + SetChildIndexBefore(_modalLayer, i); + return; + } + } + + if (_modalLayer.parent != null) + RemoveChild(_modalLayer); + } + + /// + /// Show a popup object. + /// 显示一个popup。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// + /// + public void ShowPopup(GObject popup) + { + ShowPopup(popup, null, PopupDirection.Auto, false); + } + + /// + /// Show a popup object along with the specific target object. + /// 显示一个popup。将popup显示在指定对象的上边或者下边。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// + /// + /// + public void ShowPopup(GObject popup, GObject target) + { + ShowPopup(popup, target, PopupDirection.Auto, false); + } + + [Obsolete] + public void ShowPopup(GObject popup, GObject target, object downward) + { + ShowPopup(popup, target, + downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), + false); + } + + /// + /// Show a popup object along with the specific target object. + /// 显示一个popup。将popup显示在指定对象的上方或者下方。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// + /// + /// + /// + public void ShowPopup(GObject popup, GObject target, PopupDirection dir) + { + ShowPopup(popup, target, dir, false); + } + + /// + /// Show a popup object along with the specific target object. + /// 显示一个popup。将popup显示在指定对象的上方或者下方。 + /// popup的特点是点击popup对象外的区域,popup对象将自动消失。 + /// 默认情况下,popup在touchEnd事件中关闭;特别设置closeUntilUpEvent=true则可使该popup在touchEnd中才关闭。 + /// + /// + /// + /// + /// + public void ShowPopup(GObject popup, GObject target, PopupDirection dir, bool closeUntilUpEvent) + { + if (_popupStack.Count > 0) + { + int k = _popupStack.IndexOf(popup); + if (k != -1) + { + for (int i = _popupStack.Count - 1; i >= k; i--) + { + int last = _popupStack.Count - 1; + GObject obj = _popupStack[last]; + ClosePopup(obj); + _popupStack.RemoveAt(last); + _specialPopups.Remove(obj); + } + } + } + _popupStack.Add(popup); + if (closeUntilUpEvent) + _specialPopups.Add(popup); + + if (target != null) + { + GObject p = target; + while (p != null) + { + if (p.parent == this) + { + if (popup.sortingOrder < p.sortingOrder) + { + popup.sortingOrder = p.sortingOrder; + } + break; + } + p = p.parent; + } + } + + AddChild(popup); + AdjustModalLayer(); + + if ((popup is Window) && target == null && dir == PopupDirection.Auto) + return; + + Vector2 pos = GetPoupPosition(popup, target, dir); + popup.xy = pos; + } + + [Obsolete] + public Vector2 GetPoupPosition(GObject popup, GObject target, object downward) + { + return GetPoupPosition(popup, target, + downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up)); + } + + /// + /// + /// + /// + /// + /// + /// + public Vector2 GetPoupPosition(GObject popup, GObject target, PopupDirection dir) + { + Vector2 pos; + Vector2 size = Vector2.zero; + if (target != null) + { + pos = target.LocalToRoot(Vector2.zero, this); + size = target.LocalToRoot(target.size, this) - pos; + } + else + { + pos = this.GlobalToLocal(Stage.inst.touchPosition); + } + float xx, yy; + xx = pos.x; + if (xx + popup.width > this.width) + xx = xx + size.x - popup.width; + yy = pos.y + size.y; + if ((dir == PopupDirection.Auto && yy + popup.height > this.height) + || dir == PopupDirection.Up) + { + yy = pos.y - popup.height - 1; + if (yy < 0) + { + yy = 0; + xx += size.x / 2; + } + } + + return new Vector2(Mathf.RoundToInt(xx), Mathf.RoundToInt(yy)); + } + + /// + /// If a popup is showing, then close it; otherwise, open it. + /// + /// + public void TogglePopup(GObject popup) + { + TogglePopup(popup, null, PopupDirection.Auto, false); + } + + /// + /// + /// + /// + /// + public void TogglePopup(GObject popup, GObject target) + { + TogglePopup(popup, target, PopupDirection.Auto, false); + } + + [Obsolete] + public void TogglePopup(GObject popup, GObject target, object downward) + { + TogglePopup(popup, target, + downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), + false); + } + + /// + /// + /// + /// + /// + /// + public void TogglePopup(GObject popup, GObject target, PopupDirection dir) + { + TogglePopup(popup, target, dir, false); + } + + /// + /// + /// + /// + /// + /// + /// + public void TogglePopup(GObject popup, GObject target, PopupDirection dir, bool closeUntilUpEvent) + { + if (_justClosedPopups.IndexOf(popup) != -1) + return; + + ShowPopup(popup, target, dir, closeUntilUpEvent); + } + + /// + /// Close all popups. + /// + public void HidePopup() + { + HidePopup(null); + } + + /// + /// Close a popup. + /// + /// + public void HidePopup(GObject popup) + { + if (popup != null) + { + int k = _popupStack.IndexOf(popup); + if (k != -1) + { + for (int i = _popupStack.Count - 1; i >= k; i--) + { + int last = _popupStack.Count - 1; + GObject obj = _popupStack[last]; + ClosePopup(obj); + _popupStack.RemoveAt(last); + _specialPopups.Remove(obj); + } + } + } + else + { + foreach (GObject obj in _popupStack) + ClosePopup(obj); + _popupStack.Clear(); + _specialPopups.Clear(); + } + } + + /// + /// + /// + public bool hasAnyPopup + { + get { return _popupStack.Count > 0; } + } + + void ClosePopup(GObject target) + { + if (target.parent != null) + { + if (target is Window) + ((Window)target).Hide(); + else + RemoveChild(target); + } + } + + /// + /// + /// + /// + public void ShowTooltips(string msg) + { + ShowTooltips(msg, 0.1f); + } + + /// + /// + /// + /// + /// + public void ShowTooltips(string msg, float delay) + { + if (_defaultTooltipWin == null || _defaultTooltipWin.isDisposed) + { + string resourceURL = UIConfig.tooltipsWin; + if (string.IsNullOrEmpty(resourceURL)) + { + Debug.LogWarning("FairyGUI: UIConfig.tooltipsWin not defined"); + return; + } + + _defaultTooltipWin = UIPackage.CreateObjectFromURL(resourceURL); + _defaultTooltipWin.SetHome(this); + _defaultTooltipWin.touchable = false; + } + + _defaultTooltipWin.text = msg; + ShowTooltipsWin(_defaultTooltipWin, delay); + } + + /// + /// + /// + /// + public void ShowTooltipsWin(GObject tooltipWin) + { + ShowTooltipsWin(tooltipWin, 0.1f); + } + + /// + /// + /// + /// + /// + public void ShowTooltipsWin(GObject tooltipWin, float delay) + { + HideTooltips(); + + _tooltipWin = tooltipWin; + Timers.inst.Add(delay, 1, __showTooltipsWin); + } + + void __showTooltipsWin(object param) + { + if (_tooltipWin == null) + return; + + float xx = Stage.inst.touchPosition.x + 10; + float yy = Stage.inst.touchPosition.y + 20; + + Vector2 pt = this.GlobalToLocal(new Vector2(xx, yy)); + xx = pt.x; + yy = pt.y; + + if (xx + _tooltipWin.width > this.width) + xx = xx - _tooltipWin.width; + if (yy + _tooltipWin.height > this.height) + { + yy = yy - _tooltipWin.height - 1; + if (yy < 0) + yy = 0; + } + + _tooltipWin.x = Mathf.RoundToInt(xx); + _tooltipWin.y = Mathf.RoundToInt(yy); + AddChild(_tooltipWin); + } + + /// + /// + /// + public void HideTooltips() + { + if (_tooltipWin != null) + { + if (_tooltipWin.parent != null) + RemoveChild(_tooltipWin); + _tooltipWin = null; + } + } + + /// + /// + /// + public GObject focus + { + get + { + GObject obj = DisplayObjectToGObject(Stage.inst.focus); + if (obj != null && !IsAncestorOf(obj)) + return null; + else + return obj; + } + + set + { + if (value == null) + Stage.inst.focus = null; + else + Stage.inst.focus = value.displayObject; + } + } + + void __stageTouchBegin(EventContext context) + { + if (_tooltipWin != null) + HideTooltips(); + + CheckPopups(true); + } + + void __stageTouchEnd(EventContext context) + { + CheckPopups(false); + } + + void CheckPopups(bool touchBegin) + { + if (touchBegin) + _justClosedPopups.Clear(); + + if (_popupStack.Count > 0) + { + DisplayObject mc = Stage.inst.touchTarget as DisplayObject; + bool handled = false; + while (mc != Stage.inst && mc != null) + { + if (mc.gOwner != null) + { + int k = _popupStack.IndexOf(mc.gOwner); + if (k != -1) + { + for (int i = _popupStack.Count - 1; i > k; i--) + { + int last = _popupStack.Count - 1; + GObject popup = _popupStack[last]; + if (touchBegin == _specialPopups.Contains(popup)) + continue; + + ClosePopup(popup); + _justClosedPopups.Add(popup); + _popupStack.RemoveAt(last); + _specialPopups.Remove(popup); + } + handled = true; + break; + } + } + mc = mc.parent; + } + + if (!handled) + { + for (int i = _popupStack.Count - 1; i >= 0; i--) + { + GObject popup = _popupStack[i]; + if (touchBegin == _specialPopups.Contains(popup)) + continue; + + ClosePopup(popup); + _justClosedPopups.Add(popup); + _popupStack.RemoveAt(i); + _specialPopups.Remove(popup); + } + } + } + } + + /// + /// + /// + public void EnableSound() + { + Stage.inst.EnableSound(); + } + + /// + /// + /// + public void DisableSound() + { + Stage.inst.DisableSound(); + } + + /// + /// + /// + /// + /// + public void PlayOneShotSound(AudioClip clip, float volumeScale) + { + Stage.inst.PlayOneShotSound(clip, volumeScale); + } + + /// + /// + /// + /// + public void PlayOneShotSound(AudioClip clip) + { + Stage.inst.PlayOneShotSound(clip); + } + + /// + /// + /// + public float soundVolume + { + get { return Stage.inst.soundVolume; } + set { Stage.inst.soundVolume = value; } + } + } +} diff --git a/Assets/Scripts/UI/GRoot.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRoot.cs.meta similarity index 100% rename from Assets/Scripts/UI/GRoot.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GRoot.cs.meta diff --git a/Assets/Scripts/UI/GScrollBar.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GScrollBar.cs similarity index 96% rename from Assets/Scripts/UI/GScrollBar.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GScrollBar.cs index a00f2d65..c490ce10 100644 --- a/Assets/Scripts/UI/GScrollBar.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GScrollBar.cs @@ -1,226 +1,226 @@ -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// GScrollBar class. - /// - public class GScrollBar : GComponent - { - GObject _grip; - GObject _arrowButton1; - GObject _arrowButton2; - GObject _bar; - ScrollPane _target; - - bool _vertical; - float _scrollPerc; - bool _fixedGripSize; - bool _gripDragging; - - Vector2 _dragOffset; - - public GScrollBar() - { - _scrollPerc = 0; - } - - /// - /// - /// - /// - /// - public void SetScrollPane(ScrollPane target, bool vertical) - { - _target = target; - _vertical = vertical; - } - - /// - /// - /// - public void SetDisplayPerc(float value) - { - if (_vertical) - { - if (!_fixedGripSize) - _grip.height = Mathf.FloorToInt(value * _bar.height); - _grip.y = Mathf.RoundToInt(_bar.y + (_bar.height - _grip.height) * _scrollPerc); - } - else - { - if (!_fixedGripSize) - _grip.width = Mathf.FloorToInt(value * _bar.width); - _grip.x = Mathf.RoundToInt(_bar.x + (_bar.width - _grip.width) * _scrollPerc); - } - - _grip.visible = value != 0 && value != 1; - } - - /// - /// - /// - public void setScrollPerc(float value) - { - _scrollPerc = value; - if (_vertical) - _grip.y = Mathf.RoundToInt(_bar.y + (_bar.height - _grip.height) * _scrollPerc); - else - _grip.x = Mathf.RoundToInt(_bar.x + (_bar.width - _grip.width) * _scrollPerc); - } - - /// - /// - /// - public float minSize - { - get - { - if (_vertical) - return (_arrowButton1 != null ? _arrowButton1.height : 0) + (_arrowButton2 != null ? _arrowButton2.height : 0); - else - return (_arrowButton1 != null ? _arrowButton1.width : 0) + (_arrowButton2 != null ? _arrowButton2.width : 0); - } - } - - /// - /// - /// - public bool gripDragging - { - get - { - return _gripDragging; - } - } - - override protected void ConstructExtension(ByteBuffer buffer) - { - buffer.Seek(0, 6); - - _fixedGripSize = buffer.ReadBool(); - - _grip = GetChild("grip"); - if (_grip == null) - { - Debug.LogWarning("FairyGUI: " + this.resourceURL + " should define grip"); - return; - } - - _bar = GetChild("bar"); - if (_bar == null) - { - Debug.LogWarning("FairyGUI: " + this.resourceURL + " should define bar"); - return; - } - - _arrowButton1 = GetChild("arrow1"); - _arrowButton2 = GetChild("arrow2"); - - _grip.onTouchBegin.Add(__gripTouchBegin); - _grip.onTouchMove.Add(__gripTouchMove); - _grip.onTouchEnd.Add(__gripTouchEnd); - - this.onTouchBegin.Add(__touchBegin); - if (_arrowButton1 != null) - _arrowButton1.onTouchBegin.Add(__arrowButton1Click); - if (_arrowButton2 != null) - _arrowButton2.onTouchBegin.Add(__arrowButton2Click); - } - - void __gripTouchBegin(EventContext context) - { - if (_bar == null) - return; - - context.StopPropagation(); - - InputEvent evt = context.inputEvent; - if (evt.button != 0) - return; - - context.CaptureTouch(); - - _gripDragging = true; - _target.UpdateScrollBarVisible(); - - _dragOffset = this.GlobalToLocal(new Vector2(evt.x, evt.y)) - _grip.xy; - } - - void __gripTouchMove(EventContext context) - { - InputEvent evt = context.inputEvent; - Vector2 pt = this.GlobalToLocal(new Vector2(evt.x, evt.y)); - if (float.IsNaN(pt.x)) - return; - - if (_vertical) - { - float curY = pt.y - _dragOffset.y; - float diff = _bar.height - _grip.height; - if (diff == 0) - _target.percY = 0; - else - _target.percY = (curY - _bar.y) / diff; - } - else - { - float curX = pt.x - _dragOffset.x; - float diff = _bar.width - _grip.width; - if (diff == 0) - _target.percX = 0; - else - _target.percX = (curX - _bar.x) / diff; - } - } - - void __gripTouchEnd(EventContext context) - { - _gripDragging = false; - _target.UpdateScrollBarVisible(); - } - - void __arrowButton1Click(EventContext context) - { - context.StopPropagation(); - - if (_vertical) - _target.ScrollUp(); - else - _target.ScrollLeft(); - } - - void __arrowButton2Click(EventContext context) - { - context.StopPropagation(); - - if (_vertical) - _target.ScrollDown(); - else - _target.ScrollRight(); - } - - void __touchBegin(EventContext context) - { - context.StopPropagation(); - - InputEvent evt = context.inputEvent; - Vector2 pt = _grip.GlobalToLocal(new Vector2(evt.x, evt.y)); - if (_vertical) - { - if (pt.y < 0) - _target.ScrollUp(4, false); - else - _target.ScrollDown(4, false); - } - else - { - if (pt.x < 0) - _target.ScrollLeft(4, false); - else - _target.ScrollRight(4, false); - } - } - } -} +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// GScrollBar class. + /// + public class GScrollBar : GComponent + { + GObject _grip; + GObject _arrowButton1; + GObject _arrowButton2; + GObject _bar; + ScrollPane _target; + + bool _vertical; + float _scrollPerc; + bool _fixedGripSize; + bool _gripDragging; + + Vector2 _dragOffset; + + public GScrollBar() + { + _scrollPerc = 0; + } + + /// + /// + /// + /// + /// + public void SetScrollPane(ScrollPane target, bool vertical) + { + _target = target; + _vertical = vertical; + } + + /// + /// + /// + public void SetDisplayPerc(float value) + { + if (_vertical) + { + if (!_fixedGripSize) + _grip.height = Mathf.FloorToInt(value * _bar.height); + _grip.y = Mathf.RoundToInt(_bar.y + (_bar.height - _grip.height) * _scrollPerc); + } + else + { + if (!_fixedGripSize) + _grip.width = Mathf.FloorToInt(value * _bar.width); + _grip.x = Mathf.RoundToInt(_bar.x + (_bar.width - _grip.width) * _scrollPerc); + } + + _grip.visible = value != 0 && value != 1; + } + + /// + /// + /// + public void setScrollPerc(float value) + { + _scrollPerc = value; + if (_vertical) + _grip.y = Mathf.RoundToInt(_bar.y + (_bar.height - _grip.height) * _scrollPerc); + else + _grip.x = Mathf.RoundToInt(_bar.x + (_bar.width - _grip.width) * _scrollPerc); + } + + /// + /// + /// + public float minSize + { + get + { + if (_vertical) + return (_arrowButton1 != null ? _arrowButton1.height : 0) + (_arrowButton2 != null ? _arrowButton2.height : 0); + else + return (_arrowButton1 != null ? _arrowButton1.width : 0) + (_arrowButton2 != null ? _arrowButton2.width : 0); + } + } + + /// + /// + /// + public bool gripDragging + { + get + { + return _gripDragging; + } + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _fixedGripSize = buffer.ReadBool(); + + _grip = GetChild("grip"); + if (_grip == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + " should define grip"); + return; + } + + _bar = GetChild("bar"); + if (_bar == null) + { + Debug.LogWarning("FairyGUI: " + this.resourceURL + " should define bar"); + return; + } + + _arrowButton1 = GetChild("arrow1"); + _arrowButton2 = GetChild("arrow2"); + + _grip.onTouchBegin.Add(__gripTouchBegin); + _grip.onTouchMove.Add(__gripTouchMove); + _grip.onTouchEnd.Add(__gripTouchEnd); + + this.onTouchBegin.Add(__touchBegin); + if (_arrowButton1 != null) + _arrowButton1.onTouchBegin.Add(__arrowButton1Click); + if (_arrowButton2 != null) + _arrowButton2.onTouchBegin.Add(__arrowButton2Click); + } + + void __gripTouchBegin(EventContext context) + { + if (_bar == null) + return; + + context.StopPropagation(); + + InputEvent evt = context.inputEvent; + if (evt.button != 0) + return; + + context.CaptureTouch(); + + _gripDragging = true; + _target.UpdateScrollBarVisible(); + + _dragOffset = this.GlobalToLocal(new Vector2(evt.x, evt.y)) - _grip.xy; + } + + void __gripTouchMove(EventContext context) + { + InputEvent evt = context.inputEvent; + Vector2 pt = this.GlobalToLocal(new Vector2(evt.x, evt.y)); + if (float.IsNaN(pt.x)) + return; + + if (_vertical) + { + float curY = pt.y - _dragOffset.y; + float diff = _bar.height - _grip.height; + if (diff == 0) + _target.percY = 0; + else + _target.percY = (curY - _bar.y) / diff; + } + else + { + float curX = pt.x - _dragOffset.x; + float diff = _bar.width - _grip.width; + if (diff == 0) + _target.percX = 0; + else + _target.percX = (curX - _bar.x) / diff; + } + } + + void __gripTouchEnd(EventContext context) + { + _gripDragging = false; + _target.UpdateScrollBarVisible(); + } + + void __arrowButton1Click(EventContext context) + { + context.StopPropagation(); + + if (_vertical) + _target.ScrollUp(); + else + _target.ScrollLeft(); + } + + void __arrowButton2Click(EventContext context) + { + context.StopPropagation(); + + if (_vertical) + _target.ScrollDown(); + else + _target.ScrollRight(); + } + + void __touchBegin(EventContext context) + { + context.StopPropagation(); + + InputEvent evt = context.inputEvent; + Vector2 pt = _grip.GlobalToLocal(new Vector2(evt.x, evt.y)); + if (_vertical) + { + if (pt.y < 0) + _target.ScrollUp(4, false); + else + _target.ScrollDown(4, false); + } + else + { + if (pt.x < 0) + _target.ScrollLeft(4, false); + else + _target.ScrollRight(4, false); + } + } + } +} diff --git a/Assets/Scripts/UI/GScrollBar.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GScrollBar.cs.meta similarity index 100% rename from Assets/Scripts/UI/GScrollBar.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GScrollBar.cs.meta diff --git a/Assets/Scripts/UI/GSlider.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GSlider.cs similarity index 96% rename from Assets/Scripts/UI/GSlider.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GSlider.cs index 14747eb9..86642640 100644 --- a/Assets/Scripts/UI/GSlider.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GSlider.cs @@ -1,405 +1,405 @@ -using System; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class GSlider : GComponent - { - double _min; - double _max; - double _value; - ProgressTitleType _titleType; - bool _reverse; - bool _wholeNumbers; - - GObject _titleObject; - GObject _barObjectH; - GObject _barObjectV; - float _barMaxWidth; - float _barMaxHeight; - float _barMaxWidthDelta; - float _barMaxHeightDelta; - GObject _gripObject; - Vector2 _clickPos; - float _clickPercent; - float _barStartX; - float _barStartY; - - EventListener _onChanged; - EventListener _onGripTouchEnd; - - public bool changeOnClick; - public bool canDrag; - - public GSlider() - { - _value = 50; - _max = 100; - changeOnClick = true; - canDrag = true; - } - - /// - /// - /// - public EventListener onChanged - { - get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } - } - - /// - /// - /// - public EventListener onGripTouchEnd - { - get { return _onGripTouchEnd ?? (_onGripTouchEnd = new EventListener(this, "onGripTouchEnd")); } - } - - /// - /// - /// - public ProgressTitleType titleType - { - get - { - return _titleType; - } - set - { - if (_titleType != value) - { - _titleType = value; - Update(); - } - } - } - - /// - /// - /// - public double min - { - get - { - return _min; - } - set - { - if (_min != value) - { - _min = value; - Update(); - } - } - } - - /// - /// - /// - public double max - { - get - { - return _max; - } - set - { - if (_max != value) - { - _max = value; - Update(); - } - } - } - - /// - /// - /// - public double value - { - get - { - return _value; - } - set - { - if (_value != value) - { - _value = value; - Update(); - } - } - } - - /// - /// - /// - public bool wholeNumbers - { - get - { - return _wholeNumbers; - } - set - { - if (_wholeNumbers != value) - { - _wholeNumbers = value; - Update(); - } - } - } - - private void Update() - { - UpdateWithPercent((float)((_value - _min) / (_max - _min)), false); - } - - private void UpdateWithPercent(float percent, bool manual) - { - percent = Mathf.Clamp01(percent); - if (manual) - { - double newValue = _min + (_max - _min) * percent; - if (newValue < _min) - newValue = _min; - if (newValue > _max) - newValue = _max; - if (_wholeNumbers) - { - newValue = Math.Round(newValue); - percent = Mathf.Clamp01((float)((newValue - _min) / (_max - _min))); - } - - if (newValue != _value) - { - _value = newValue; - if (DispatchEvent("onChanged", null)) - return; - } - } - - if (_titleObject != null) - { - switch (_titleType) - { - case ProgressTitleType.Percent: - _titleObject.text = Mathf.FloorToInt(percent * 100) + "%"; - break; - - case ProgressTitleType.ValueAndMax: - _titleObject.text = Math.Round(_value) + "/" + Math.Round(max); - break; - - case ProgressTitleType.Value: - _titleObject.text = "" + Math.Round(_value); - break; - - case ProgressTitleType.Max: - _titleObject.text = "" + Math.Round(_max); - break; - } - } - - float fullWidth = this.width - _barMaxWidthDelta; - float fullHeight = this.height - _barMaxHeightDelta; - if (!_reverse) - { - if (_barObjectH != null) - { - if (!SetFillAmount(_barObjectH, percent)) - _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); - } - if (_barObjectV != null) - { - if (!SetFillAmount(_barObjectV, percent)) - _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); - } - } - else - { - if (_barObjectH != null) - { - if (!SetFillAmount(_barObjectH, 1 - percent)) - { - _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); - _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); - } - } - if (_barObjectV != null) - { - if (!SetFillAmount(_barObjectV, 1 - percent)) - { - _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); - _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); - } - } - } - - InvalidateBatchingState(true); - } - - bool SetFillAmount(GObject bar, float amount) - { - if ((bar is GImage) && ((GImage)bar).fillMethod != FillMethod.None) - ((GImage)bar).fillAmount = amount; - else if ((bar is GLoader) && ((GLoader)bar).fillMethod != FillMethod.None) - ((GLoader)bar).fillAmount = amount; - else - return false; - - return true; - } - - override protected void ConstructExtension(ByteBuffer buffer) - { - buffer.Seek(0, 6); - - _titleType = (ProgressTitleType)buffer.ReadByte(); - _reverse = buffer.ReadBool(); - if (buffer.version >= 2) - { - _wholeNumbers = buffer.ReadBool(); - this.changeOnClick = buffer.ReadBool(); - } - - _titleObject = GetChild("title"); - _barObjectH = GetChild("bar"); - _barObjectV = GetChild("bar_v"); - _gripObject = GetChild("grip"); - - if (_barObjectH != null) - { - _barMaxWidth = _barObjectH.width; - _barMaxWidthDelta = this.width - _barMaxWidth; - _barStartX = _barObjectH.x; - } - if (_barObjectV != null) - { - _barMaxHeight = _barObjectV.height; - _barMaxHeightDelta = this.height - _barMaxHeight; - _barStartY = _barObjectV.y; - } - - if (_gripObject != null) - { - _gripObject.onTouchBegin.Add(__gripTouchBegin); - _gripObject.onTouchMove.Add(__gripTouchMove); - _gripObject.onTouchEnd.Add(__gripTouchEnd); - } - - onTouchBegin.Add(__barTouchBegin); - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - if (!buffer.Seek(beginPos, 6)) - { - Update(); - return; - } - - if ((ObjectType)buffer.ReadByte() != packageItem.objectType) - { - Update(); - return; - } - - _value = buffer.ReadInt(); - _max = buffer.ReadInt(); - if (buffer.version >= 2) - _min = buffer.ReadInt(); - - - Update(); - } - - override protected void HandleSizeChanged() - { - base.HandleSizeChanged(); - - if (_barObjectH != null) - _barMaxWidth = this.width - _barMaxWidthDelta; - if (_barObjectV != null) - _barMaxHeight = this.height - _barMaxHeightDelta; - - if (!this.underConstruct) - Update(); - } - - private void __gripTouchBegin(EventContext context) - { - this.canDrag = true; - - context.StopPropagation(); - - InputEvent evt = context.inputEvent; - if (evt.button != 0) - return; - - context.CaptureTouch(); - - _clickPos = this.GlobalToLocal(new Vector2(evt.x, evt.y)); - _clickPercent = Mathf.Clamp01((float)((_value - _min) / (_max - _min))); - } - - private void __gripTouchMove(EventContext context) - { - if (!this.canDrag) - return; - - InputEvent evt = context.inputEvent; - Vector2 pt = this.GlobalToLocal(new Vector2(evt.x, evt.y)); - if (float.IsNaN(pt.x)) - return; - - float deltaX = pt.x - _clickPos.x; - float deltaY = pt.y - _clickPos.y; - if (_reverse) - { - deltaX = -deltaX; - deltaY = -deltaY; - } - - float percent; - if (_barObjectH != null) - percent = _clickPercent + deltaX / _barMaxWidth; - else - percent = _clickPercent + deltaY / _barMaxHeight; - - UpdateWithPercent(percent, true); - } - - private void __gripTouchEnd(EventContext context) - { - DispatchEvent("onGripTouchEnd", null); - } - - private void __barTouchBegin(EventContext context) - { - if (!changeOnClick) - return; - - InputEvent evt = context.inputEvent; - Vector2 pt = _gripObject.GlobalToLocal(new Vector2(evt.x, evt.y)); - float percent = Mathf.Clamp01((float)((_value - _min) / (_max - _min))); - float delta = 0; - if (_barObjectH != null) - delta = (pt.x - _gripObject.width / 2) / _barMaxWidth; - if (_barObjectV != null) - delta = (pt.y - _gripObject.height / 2) / _barMaxHeight; - if (_reverse) - percent -= delta; - else - percent += delta; - - UpdateWithPercent(percent, true); - } - } -} +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class GSlider : GComponent + { + double _min; + double _max; + double _value; + ProgressTitleType _titleType; + bool _reverse; + bool _wholeNumbers; + + GObject _titleObject; + GObject _barObjectH; + GObject _barObjectV; + float _barMaxWidth; + float _barMaxHeight; + float _barMaxWidthDelta; + float _barMaxHeightDelta; + GObject _gripObject; + Vector2 _clickPos; + float _clickPercent; + float _barStartX; + float _barStartY; + + EventListener _onChanged; + EventListener _onGripTouchEnd; + + public bool changeOnClick; + public bool canDrag; + + public GSlider() + { + _value = 50; + _max = 100; + changeOnClick = true; + canDrag = true; + } + + /// + /// + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// + /// + public EventListener onGripTouchEnd + { + get { return _onGripTouchEnd ?? (_onGripTouchEnd = new EventListener(this, "onGripTouchEnd")); } + } + + /// + /// + /// + public ProgressTitleType titleType + { + get + { + return _titleType; + } + set + { + if (_titleType != value) + { + _titleType = value; + Update(); + } + } + } + + /// + /// + /// + public double min + { + get + { + return _min; + } + set + { + if (_min != value) + { + _min = value; + Update(); + } + } + } + + /// + /// + /// + public double max + { + get + { + return _max; + } + set + { + if (_max != value) + { + _max = value; + Update(); + } + } + } + + /// + /// + /// + public double value + { + get + { + return _value; + } + set + { + if (_value != value) + { + _value = value; + Update(); + } + } + } + + /// + /// + /// + public bool wholeNumbers + { + get + { + return _wholeNumbers; + } + set + { + if (_wholeNumbers != value) + { + _wholeNumbers = value; + Update(); + } + } + } + + private void Update() + { + UpdateWithPercent((float)((_value - _min) / (_max - _min)), false); + } + + private void UpdateWithPercent(float percent, bool manual) + { + percent = Mathf.Clamp01(percent); + if (manual) + { + double newValue = _min + (_max - _min) * percent; + if (newValue < _min) + newValue = _min; + if (newValue > _max) + newValue = _max; + if (_wholeNumbers) + { + newValue = Math.Round(newValue); + percent = Mathf.Clamp01((float)((newValue - _min) / (_max - _min))); + } + + if (newValue != _value) + { + _value = newValue; + if (DispatchEvent("onChanged", null)) + return; + } + } + + if (_titleObject != null) + { + switch (_titleType) + { + case ProgressTitleType.Percent: + _titleObject.text = Mathf.FloorToInt(percent * 100) + "%"; + break; + + case ProgressTitleType.ValueAndMax: + _titleObject.text = Math.Round(_value) + "/" + Math.Round(max); + break; + + case ProgressTitleType.Value: + _titleObject.text = "" + Math.Round(_value); + break; + + case ProgressTitleType.Max: + _titleObject.text = "" + Math.Round(_max); + break; + } + } + + float fullWidth = this.width - _barMaxWidthDelta; + float fullHeight = this.height - _barMaxHeightDelta; + if (!_reverse) + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, percent)) + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, percent)) + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + } + } + else + { + if (_barObjectH != null) + { + if (!SetFillAmount(_barObjectH, 1 - percent)) + { + _barObjectH.width = Mathf.RoundToInt(fullWidth * percent); + _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); + } + } + if (_barObjectV != null) + { + if (!SetFillAmount(_barObjectV, 1 - percent)) + { + _barObjectV.height = Mathf.RoundToInt(fullHeight * percent); + _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); + } + } + } + + InvalidateBatchingState(true); + } + + bool SetFillAmount(GObject bar, float amount) + { + if ((bar is GImage) && ((GImage)bar).fillMethod != FillMethod.None) + ((GImage)bar).fillAmount = amount; + else if ((bar is GLoader) && ((GLoader)bar).fillMethod != FillMethod.None) + ((GLoader)bar).fillAmount = amount; + else + return false; + + return true; + } + + override protected void ConstructExtension(ByteBuffer buffer) + { + buffer.Seek(0, 6); + + _titleType = (ProgressTitleType)buffer.ReadByte(); + _reverse = buffer.ReadBool(); + if (buffer.version >= 2) + { + _wholeNumbers = buffer.ReadBool(); + this.changeOnClick = buffer.ReadBool(); + } + + _titleObject = GetChild("title"); + _barObjectH = GetChild("bar"); + _barObjectV = GetChild("bar_v"); + _gripObject = GetChild("grip"); + + if (_barObjectH != null) + { + _barMaxWidth = _barObjectH.width; + _barMaxWidthDelta = this.width - _barMaxWidth; + _barStartX = _barObjectH.x; + } + if (_barObjectV != null) + { + _barMaxHeight = _barObjectV.height; + _barMaxHeightDelta = this.height - _barMaxHeight; + _barStartY = _barObjectV.y; + } + + if (_gripObject != null) + { + _gripObject.onTouchBegin.Add(__gripTouchBegin); + _gripObject.onTouchMove.Add(__gripTouchMove); + _gripObject.onTouchEnd.Add(__gripTouchEnd); + } + + onTouchBegin.Add(__barTouchBegin); + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + if (!buffer.Seek(beginPos, 6)) + { + Update(); + return; + } + + if ((ObjectType)buffer.ReadByte() != packageItem.objectType) + { + Update(); + return; + } + + _value = buffer.ReadInt(); + _max = buffer.ReadInt(); + if (buffer.version >= 2) + _min = buffer.ReadInt(); + + + Update(); + } + + override protected void HandleSizeChanged() + { + base.HandleSizeChanged(); + + if (_barObjectH != null) + _barMaxWidth = this.width - _barMaxWidthDelta; + if (_barObjectV != null) + _barMaxHeight = this.height - _barMaxHeightDelta; + + if (!this.underConstruct) + Update(); + } + + private void __gripTouchBegin(EventContext context) + { + this.canDrag = true; + + context.StopPropagation(); + + InputEvent evt = context.inputEvent; + if (evt.button != 0) + return; + + context.CaptureTouch(); + + _clickPos = this.GlobalToLocal(new Vector2(evt.x, evt.y)); + _clickPercent = Mathf.Clamp01((float)((_value - _min) / (_max - _min))); + } + + private void __gripTouchMove(EventContext context) + { + if (!this.canDrag) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = this.GlobalToLocal(new Vector2(evt.x, evt.y)); + if (float.IsNaN(pt.x)) + return; + + float deltaX = pt.x - _clickPos.x; + float deltaY = pt.y - _clickPos.y; + if (_reverse) + { + deltaX = -deltaX; + deltaY = -deltaY; + } + + float percent; + if (_barObjectH != null) + percent = _clickPercent + deltaX / _barMaxWidth; + else + percent = _clickPercent + deltaY / _barMaxHeight; + + UpdateWithPercent(percent, true); + } + + private void __gripTouchEnd(EventContext context) + { + DispatchEvent("onGripTouchEnd", null); + } + + private void __barTouchBegin(EventContext context) + { + if (!changeOnClick) + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = _gripObject.GlobalToLocal(new Vector2(evt.x, evt.y)); + float percent = Mathf.Clamp01((float)((_value - _min) / (_max - _min))); + float delta = 0; + if (_barObjectH != null) + delta = (pt.x - _gripObject.width / 2) / _barMaxWidth; + if (_barObjectV != null) + delta = (pt.y - _gripObject.height / 2) / _barMaxHeight; + if (_reverse) + percent -= delta; + else + percent += delta; + + UpdateWithPercent(percent, true); + } + } +} diff --git a/Assets/Scripts/UI/GSlider.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GSlider.cs.meta similarity index 100% rename from Assets/Scripts/UI/GSlider.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GSlider.cs.meta diff --git a/Assets/Scripts/UI/GTextField.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextField.cs similarity index 96% rename from Assets/Scripts/UI/GTextField.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextField.cs index c804a1ab..25d9fec7 100644 --- a/Assets/Scripts/UI/GTextField.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextField.cs @@ -1,438 +1,438 @@ -using System.Collections.Generic; -using System.Text; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class GTextField : GObject, ITextColorGear - { - protected TextField _textField; - protected string _text; - protected bool _ubbEnabled; - protected bool _updatingSize; - protected Dictionary _templateVars; - - public GTextField() - : base() - { - TextFormat tf = _textField.textFormat; - tf.font = UIConfig.defaultFont; - tf.size = 12; - tf.color = Color.black; - tf.lineSpacing = 3; - tf.letterSpacing = 0; - _textField.textFormat = tf; - - _text = string.Empty; - _textField.autoSize = AutoSizeType.Both; - _textField.wordWrap = false; - } - - override protected void CreateDisplayObject() - { - _textField = new TextField(); - _textField.gOwner = this; - displayObject = _textField; - } - - /// - /// - /// - override public string text - { - get - { - if (this is GTextInput) - _text = ((GTextInput)this).inputTextField.text; - return _text; - } - set - { - if (value == null) - value = string.Empty; - _text = value; - SetTextFieldText(); - UpdateSize(); - UpdateGear(6); - } - } - - virtual protected void SetTextFieldText() - { - string str = _text; - if (_templateVars != null) - str = ParseTemplate(str); - - _textField.maxWidth = maxWidth; - if (_ubbEnabled) - _textField.htmlText = UBBParser.inst.Parse(XMLUtils.EncodeString(str)); - else - _textField.text = str; - } - - /// - /// - /// - public Dictionary templateVars - { - get { return _templateVars; } - set - { - if (_templateVars == null && value == null) - return; - - _templateVars = value; - - FlushVars(); - } - } - - /// - /// - /// - /// - /// - /// - public GTextField SetVar(string name, string value) - { - if (_templateVars == null) - _templateVars = new Dictionary(); - _templateVars[name] = value; - - return this; - } - - /// - /// - /// - public void FlushVars() - { - SetTextFieldText(); - UpdateSize(); - } - - /// - /// - /// - public bool HasCharacter(char ch) - { - return _textField.HasCharacter(ch); - } - - protected string ParseTemplate(string template) - { - int pos1 = 0, pos2 = 0; - int pos3; - string tag; - string value; - StringBuilder buffer = new StringBuilder(); - - while ((pos2 = template.IndexOf('{', pos1)) != -1) - { - if (pos2 > 0 && template[pos2 - 1] == '\\') - { - buffer.Append(template, pos1, pos2 - pos1 - 1); - buffer.Append('{'); - pos1 = pos2 + 1; - continue; - } - - buffer.Append(template, pos1, pos2 - pos1); - pos1 = pos2; - pos2 = template.IndexOf('}', pos1); - if (pos2 == -1) - break; - - if (pos2 == pos1 + 1) - { - buffer.Append(template, pos1, 2); - pos1 = pos2 + 1; - continue; - } - - tag = template.Substring(pos1 + 1, pos2 - pos1 - 1); - pos3 = tag.IndexOf('='); - if (pos3 != -1) - { - if (!_templateVars.TryGetValue(tag.Substring(0, pos3), out value)) - value = tag.Substring(pos3 + 1); - } - else - { - if (!_templateVars.TryGetValue(tag, out value)) - value = ""; - } - buffer.Append(value); - pos1 = pos2 + 1; - } - if (pos1 < template.Length) - buffer.Append(template, pos1, template.Length - pos1); - - return buffer.ToString(); - } - - /// - /// - /// - public TextFormat textFormat - { - get - { - return _textField.textFormat; - } - set - { - _textField.textFormat = value; - if (!underConstruct) - UpdateSize(); - } - } - - /// - /// - /// - public Color color - { - get - { - return _textField.textFormat.color; - } - set - { - if (_textField.textFormat.color != value) - { - TextFormat tf = _textField.textFormat; - tf.color = value; - _textField.textFormat = tf; - UpdateGear(4); - } - } - } - - /// - /// - /// - public AlignType align - { - get { return _textField.align; } - set { _textField.align = value; } - } - - /// - /// - /// - public VertAlignType verticalAlign - { - get { return _textField.verticalAlign; } - set { _textField.verticalAlign = value; } - } - - /// - /// - /// - public bool singleLine - { - get { return _textField.singleLine; } - set { _textField.singleLine = value; } - } - - /// - /// - /// - public float stroke - { - get { return _textField.stroke; } - set { _textField.stroke = value; } - } - - /// - /// - /// - public Color strokeColor - { - get { return _textField.strokeColor; } - set - { - _textField.strokeColor = value; - UpdateGear(4); - } - } - - /// - /// - /// - public Vector2 shadowOffset - { - get { return _textField.shadowOffset; } - set { _textField.shadowOffset = value; } - } - - /// - /// - /// - public bool UBBEnabled - { - get { return _ubbEnabled; } - set { _ubbEnabled = value; } - } - - /// - /// - /// - public AutoSizeType autoSize - { - get { return _textField.autoSize; } - set - { - _textField.autoSize = value; - if (value == AutoSizeType.Both) - { - _textField.wordWrap = false; - - if (!underConstruct) - this.SetSize(_textField.textWidth, _textField.textHeight); - } - else - { - _textField.wordWrap = true; - - if (value == AutoSizeType.Height) - { - if (!underConstruct) - { - displayObject.width = this.width; - this.height = _textField.textHeight; - } - } - else - displayObject.SetSize(this.width, this.height); - } - } - } - - /// - /// - /// - public float textWidth - { - get { return _textField.textWidth; } - } - - /// - /// - /// - public float textHeight - { - get { return _textField.textHeight; } - } - - protected void UpdateSize() - { - if (_updatingSize) - return; - - _updatingSize = true; - - if (_textField.autoSize == AutoSizeType.Both) - { - this.size = displayObject.size; - InvalidateBatchingState(); - } - else if (_textField.autoSize == AutoSizeType.Height) - { - this.height = displayObject.height; - InvalidateBatchingState(); - } - - _updatingSize = false; - } - - override protected void HandleSizeChanged() - { - if (_updatingSize) - return; - - if (underConstruct) - displayObject.SetSize(this.width, this.height); - else if (_textField.autoSize != AutoSizeType.Both) - { - if (_textField.autoSize == AutoSizeType.Height) - { - displayObject.width = this.width;//先调整宽度,让文本重排 - if (_text != string.Empty) //文本为空时,1是本来就不需要调整, 2是为了防止改掉文本为空时的默认高度,造成关联错误 - SetSizeDirectly(this.width, displayObject.height); - } - else - displayObject.SetSize(this.width, this.height); - } - } - - override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 5); - - TextFormat tf = _textField.textFormat; - - tf.font = buffer.ReadS(); - tf.size = buffer.ReadShort(); - tf.color = buffer.ReadColor(); - this.align = (AlignType)buffer.ReadByte(); - this.verticalAlign = (VertAlignType)buffer.ReadByte(); - tf.lineSpacing = buffer.ReadShort(); - tf.letterSpacing = buffer.ReadShort(); - _ubbEnabled = buffer.ReadBool(); - this.autoSize = (AutoSizeType)buffer.ReadByte(); - tf.underline = buffer.ReadBool(); - tf.italic = buffer.ReadBool(); - tf.bold = buffer.ReadBool(); - this.singleLine = buffer.ReadBool(); - if (buffer.ReadBool()) - { - tf.outlineColor = buffer.ReadColor(); - tf.outline = buffer.ReadFloat(); - } - - if (buffer.ReadBool()) - { - tf.shadowColor = buffer.ReadColor(); - float f1 = buffer.ReadFloat(); - float f2 = buffer.ReadFloat(); - tf.shadowOffset = new Vector2(f1, f2); - } - - if (buffer.ReadBool()) - _templateVars = new Dictionary(); - - if (buffer.version >= 3) - { - tf.strikethrough = buffer.ReadBool(); -#if FAIRYGUI_TMPRO - tf.faceDilate = buffer.ReadFloat(); - tf.outlineSoftness = buffer.ReadFloat(); - tf.underlaySoftness = buffer.ReadFloat(); -#else - buffer.Skip(12); -#endif - } - - _textField.textFormat = tf; - } - - override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_AfterAdd(buffer, beginPos); - - buffer.Seek(beginPos, 6); - - string str = buffer.ReadS(); - if (str != null) - this.text = str; - } - } -} +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class GTextField : GObject, ITextColorGear + { + protected TextField _textField; + protected string _text; + protected bool _ubbEnabled; + protected bool _updatingSize; + protected Dictionary _templateVars; + + public GTextField() + : base() + { + TextFormat tf = _textField.textFormat; + tf.font = UIConfig.defaultFont; + tf.size = 12; + tf.color = Color.black; + tf.lineSpacing = 3; + tf.letterSpacing = 0; + _textField.textFormat = tf; + + _text = string.Empty; + _textField.autoSize = AutoSizeType.Both; + _textField.wordWrap = false; + } + + override protected void CreateDisplayObject() + { + _textField = new TextField(); + _textField.gOwner = this; + displayObject = _textField; + } + + /// + /// + /// + override public string text + { + get + { + if (this is GTextInput) + _text = ((GTextInput)this).inputTextField.text; + return _text; + } + set + { + if (value == null) + value = string.Empty; + _text = value; + SetTextFieldText(); + UpdateSize(); + UpdateGear(6); + } + } + + virtual protected void SetTextFieldText() + { + string str = _text; + if (_templateVars != null) + str = ParseTemplate(str); + + _textField.maxWidth = maxWidth; + if (_ubbEnabled) + _textField.htmlText = UBBParser.inst.Parse(XMLUtils.EncodeString(str)); + else + _textField.text = str; + } + + /// + /// + /// + public Dictionary templateVars + { + get { return _templateVars; } + set + { + if (_templateVars == null && value == null) + return; + + _templateVars = value; + + FlushVars(); + } + } + + /// + /// + /// + /// + /// + /// + public GTextField SetVar(string name, string value) + { + if (_templateVars == null) + _templateVars = new Dictionary(); + _templateVars[name] = value; + + return this; + } + + /// + /// + /// + public void FlushVars() + { + SetTextFieldText(); + UpdateSize(); + } + + /// + /// + /// + public bool HasCharacter(char ch) + { + return _textField.HasCharacter(ch); + } + + protected string ParseTemplate(string template) + { + int pos1 = 0, pos2 = 0; + int pos3; + string tag; + string value; + StringBuilder buffer = new StringBuilder(); + + while ((pos2 = template.IndexOf('{', pos1)) != -1) + { + if (pos2 > 0 && template[pos2 - 1] == '\\') + { + buffer.Append(template, pos1, pos2 - pos1 - 1); + buffer.Append('{'); + pos1 = pos2 + 1; + continue; + } + + buffer.Append(template, pos1, pos2 - pos1); + pos1 = pos2; + pos2 = template.IndexOf('}', pos1); + if (pos2 == -1) + break; + + if (pos2 == pos1 + 1) + { + buffer.Append(template, pos1, 2); + pos1 = pos2 + 1; + continue; + } + + tag = template.Substring(pos1 + 1, pos2 - pos1 - 1); + pos3 = tag.IndexOf('='); + if (pos3 != -1) + { + if (!_templateVars.TryGetValue(tag.Substring(0, pos3), out value)) + value = tag.Substring(pos3 + 1); + } + else + { + if (!_templateVars.TryGetValue(tag, out value)) + value = ""; + } + buffer.Append(value); + pos1 = pos2 + 1; + } + if (pos1 < template.Length) + buffer.Append(template, pos1, template.Length - pos1); + + return buffer.ToString(); + } + + /// + /// + /// + public TextFormat textFormat + { + get + { + return _textField.textFormat; + } + set + { + _textField.textFormat = value; + if (!underConstruct) + UpdateSize(); + } + } + + /// + /// + /// + public Color color + { + get + { + return _textField.textFormat.color; + } + set + { + if (_textField.textFormat.color != value) + { + TextFormat tf = _textField.textFormat; + tf.color = value; + _textField.textFormat = tf; + UpdateGear(4); + } + } + } + + /// + /// + /// + public AlignType align + { + get { return _textField.align; } + set { _textField.align = value; } + } + + /// + /// + /// + public VertAlignType verticalAlign + { + get { return _textField.verticalAlign; } + set { _textField.verticalAlign = value; } + } + + /// + /// + /// + public bool singleLine + { + get { return _textField.singleLine; } + set { _textField.singleLine = value; } + } + + /// + /// + /// + public float stroke + { + get { return _textField.stroke; } + set { _textField.stroke = value; } + } + + /// + /// + /// + public Color strokeColor + { + get { return _textField.strokeColor; } + set + { + _textField.strokeColor = value; + UpdateGear(4); + } + } + + /// + /// + /// + public Vector2 shadowOffset + { + get { return _textField.shadowOffset; } + set { _textField.shadowOffset = value; } + } + + /// + /// + /// + public bool UBBEnabled + { + get { return _ubbEnabled; } + set { _ubbEnabled = value; } + } + + /// + /// + /// + public AutoSizeType autoSize + { + get { return _textField.autoSize; } + set + { + _textField.autoSize = value; + if (value == AutoSizeType.Both) + { + _textField.wordWrap = false; + + if (!underConstruct) + this.SetSize(_textField.textWidth, _textField.textHeight); + } + else + { + _textField.wordWrap = true; + + if (value == AutoSizeType.Height) + { + if (!underConstruct) + { + displayObject.width = this.width; + this.height = _textField.textHeight; + } + } + else + displayObject.SetSize(this.width, this.height); + } + } + } + + /// + /// + /// + public float textWidth + { + get { return _textField.textWidth; } + } + + /// + /// + /// + public float textHeight + { + get { return _textField.textHeight; } + } + + protected void UpdateSize() + { + if (_updatingSize) + return; + + _updatingSize = true; + + if (_textField.autoSize == AutoSizeType.Both) + { + this.size = displayObject.size; + InvalidateBatchingState(); + } + else if (_textField.autoSize == AutoSizeType.Height) + { + this.height = displayObject.height; + InvalidateBatchingState(); + } + + _updatingSize = false; + } + + override protected void HandleSizeChanged() + { + if (_updatingSize) + return; + + if (underConstruct) + displayObject.SetSize(this.width, this.height); + else if (_textField.autoSize != AutoSizeType.Both) + { + if (_textField.autoSize == AutoSizeType.Height) + { + displayObject.width = this.width;//先调整宽度,让文本重排 + if (_text != string.Empty) //文本为空时,1是本来就不需要调整, 2是为了防止改掉文本为空时的默认高度,造成关联错误 + SetSizeDirectly(this.width, displayObject.height); + } + else + displayObject.SetSize(this.width, this.height); + } + } + + override public void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 5); + + TextFormat tf = _textField.textFormat; + + tf.font = buffer.ReadS(); + tf.size = buffer.ReadShort(); + tf.color = buffer.ReadColor(); + this.align = (AlignType)buffer.ReadByte(); + this.verticalAlign = (VertAlignType)buffer.ReadByte(); + tf.lineSpacing = buffer.ReadShort(); + tf.letterSpacing = buffer.ReadShort(); + _ubbEnabled = buffer.ReadBool(); + this.autoSize = (AutoSizeType)buffer.ReadByte(); + tf.underline = buffer.ReadBool(); + tf.italic = buffer.ReadBool(); + tf.bold = buffer.ReadBool(); + this.singleLine = buffer.ReadBool(); + if (buffer.ReadBool()) + { + tf.outlineColor = buffer.ReadColor(); + tf.outline = buffer.ReadFloat(); + } + + if (buffer.ReadBool()) + { + tf.shadowColor = buffer.ReadColor(); + float f1 = buffer.ReadFloat(); + float f2 = buffer.ReadFloat(); + tf.shadowOffset = new Vector2(f1, f2); + } + + if (buffer.ReadBool()) + _templateVars = new Dictionary(); + + if (buffer.version >= 3) + { + tf.strikethrough = buffer.ReadBool(); +#if FAIRYGUI_TMPRO + tf.faceDilate = buffer.ReadFloat(); + tf.outlineSoftness = buffer.ReadFloat(); + tf.underlaySoftness = buffer.ReadFloat(); +#else + buffer.Skip(12); +#endif + } + + _textField.textFormat = tf; + } + + override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_AfterAdd(buffer, beginPos); + + buffer.Seek(beginPos, 6); + + string str = buffer.ReadS(); + if (str != null) + this.text = str; + } + } +} diff --git a/Assets/Scripts/UI/GTextField.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextField.cs.meta similarity index 100% rename from Assets/Scripts/UI/GTextField.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextField.cs.meta diff --git a/Assets/Scripts/UI/GTextInput.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextInput.cs similarity index 96% rename from Assets/Scripts/UI/GTextInput.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextInput.cs index 8fbd19f9..d0b76b66 100644 --- a/Assets/Scripts/UI/GTextInput.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextInput.cs @@ -1,243 +1,243 @@ -using System.Collections.Generic; -using FairyGUI.Utils; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class GTextInput : GTextField - { - /// - /// - /// - public InputTextField inputTextField { get; private set; } - - EventListener _onChanged; - EventListener _onSubmit; - - public GTextInput() - { - _textField.autoSize = AutoSizeType.None; - _textField.wordWrap = false; - } - - /// - /// - /// - public EventListener onChanged - { - get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } - } - - /// - /// - /// - public EventListener onSubmit - { - get { return _onSubmit ?? (_onSubmit = new EventListener(this, "onSubmit")); } - } - - /// - /// - /// - public bool editable - { - get { return inputTextField.editable; } - set { inputTextField.editable = value; } - } - - /// - /// - /// - public bool hideInput - { - get { return inputTextField.hideInput; } - set { inputTextField.hideInput = value; } - } - - /// - /// - /// - public int maxLength - { - get { return inputTextField.maxLength; } - set { inputTextField.maxLength = value; } - } - - /// - /// - /// - public string restrict - { - get { return inputTextField.restrict; } - set { inputTextField.restrict = value; } - } - - /// - /// - /// - public bool displayAsPassword - { - get { return inputTextField.displayAsPassword; } - set { inputTextField.displayAsPassword = value; } - } - - /// - /// - /// - public int caretPosition - { - get { return inputTextField.caretPosition; } - set { inputTextField.caretPosition = value; } - } - - /// - /// - /// - public string promptText - { - get { return inputTextField.promptText; } - set { inputTextField.promptText = value; } - } - - /// - /// 在移动设备上是否使用键盘输入。如果false,则文本在获得焦点后不会弹出键盘。 - /// - public bool keyboardInput - { - get { return inputTextField.keyboardInput; } - set { inputTextField.keyboardInput = value; } - } - - /// - /// - /// - public int keyboardType - { - get { return inputTextField.keyboardType; } - set { inputTextField.keyboardType = value; } - } - - /// - /// - /// - public bool disableIME - { - get { return inputTextField.disableIME; } - set { inputTextField.disableIME = value; } - } - - /// - /// - /// - public Dictionary emojies - { - get { return inputTextField.emojies; } - set { inputTextField.emojies = value; } - } - - /// - /// - /// - public int border - { - get { return inputTextField.border; } - set { inputTextField.border = value; } - } - - /// - /// - /// - public int corner - { - get { return inputTextField.corner; } - set { inputTextField.corner = value; } - } - - /// - /// - /// - public Color borderColor - { - get { return inputTextField.borderColor; } - set { inputTextField.borderColor = value; } - } - - /// - /// - /// - public Color backgroundColor - { - get { return inputTextField.backgroundColor; } - set { inputTextField.backgroundColor = value; } - } - - /// - /// - /// - public bool mouseWheelEnabled - { - get { return inputTextField.mouseWheelEnabled; } - set { inputTextField.mouseWheelEnabled = value; } - } - - /// - /// - /// - /// - /// - public void SetSelection(int start, int length) - { - inputTextField.SetSelection(start, length); - } - - /// - /// - /// - /// - public void ReplaceSelection(string value) - { - inputTextField.ReplaceSelection(value); - } - - override protected void SetTextFieldText() - { - inputTextField.text = _text; - } - - override protected void CreateDisplayObject() - { - inputTextField = new InputTextField(); - inputTextField.gOwner = this; - displayObject = inputTextField; - - _textField = inputTextField.textField; - } - - public override void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) - { - base.Setup_BeforeAdd(buffer, beginPos); - - buffer.Seek(beginPos, 4); - - string str = buffer.ReadS(); - if (str != null) - inputTextField.promptText = str; - - str = buffer.ReadS(); - if (str != null) - inputTextField.restrict = str; - - int iv = buffer.ReadInt(); - if (iv != 0) - inputTextField.maxLength = iv; - iv = buffer.ReadInt(); - if (iv != 0) - inputTextField.keyboardType = iv; - if (buffer.ReadBool()) - inputTextField.displayAsPassword = true; - } - } +using System.Collections.Generic; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class GTextInput : GTextField + { + /// + /// + /// + public InputTextField inputTextField { get; private set; } + + EventListener _onChanged; + EventListener _onSubmit; + + public GTextInput() + { + _textField.autoSize = AutoSizeType.None; + _textField.wordWrap = false; + } + + /// + /// + /// + public EventListener onChanged + { + get { return _onChanged ?? (_onChanged = new EventListener(this, "onChanged")); } + } + + /// + /// + /// + public EventListener onSubmit + { + get { return _onSubmit ?? (_onSubmit = new EventListener(this, "onSubmit")); } + } + + /// + /// + /// + public bool editable + { + get { return inputTextField.editable; } + set { inputTextField.editable = value; } + } + + /// + /// + /// + public bool hideInput + { + get { return inputTextField.hideInput; } + set { inputTextField.hideInput = value; } + } + + /// + /// + /// + public int maxLength + { + get { return inputTextField.maxLength; } + set { inputTextField.maxLength = value; } + } + + /// + /// + /// + public string restrict + { + get { return inputTextField.restrict; } + set { inputTextField.restrict = value; } + } + + /// + /// + /// + public bool displayAsPassword + { + get { return inputTextField.displayAsPassword; } + set { inputTextField.displayAsPassword = value; } + } + + /// + /// + /// + public int caretPosition + { + get { return inputTextField.caretPosition; } + set { inputTextField.caretPosition = value; } + } + + /// + /// + /// + public string promptText + { + get { return inputTextField.promptText; } + set { inputTextField.promptText = value; } + } + + /// + /// 在移动设备上是否使用键盘输入。如果false,则文本在获得焦点后不会弹出键盘。 + /// + public bool keyboardInput + { + get { return inputTextField.keyboardInput; } + set { inputTextField.keyboardInput = value; } + } + + /// + /// + /// + public int keyboardType + { + get { return inputTextField.keyboardType; } + set { inputTextField.keyboardType = value; } + } + + /// + /// + /// + public bool disableIME + { + get { return inputTextField.disableIME; } + set { inputTextField.disableIME = value; } + } + + /// + /// + /// + public Dictionary emojies + { + get { return inputTextField.emojies; } + set { inputTextField.emojies = value; } + } + + /// + /// + /// + public int border + { + get { return inputTextField.border; } + set { inputTextField.border = value; } + } + + /// + /// + /// + public int corner + { + get { return inputTextField.corner; } + set { inputTextField.corner = value; } + } + + /// + /// + /// + public Color borderColor + { + get { return inputTextField.borderColor; } + set { inputTextField.borderColor = value; } + } + + /// + /// + /// + public Color backgroundColor + { + get { return inputTextField.backgroundColor; } + set { inputTextField.backgroundColor = value; } + } + + /// + /// + /// + public bool mouseWheelEnabled + { + get { return inputTextField.mouseWheelEnabled; } + set { inputTextField.mouseWheelEnabled = value; } + } + + /// + /// + /// + /// + /// + public void SetSelection(int start, int length) + { + inputTextField.SetSelection(start, length); + } + + /// + /// + /// + /// + public void ReplaceSelection(string value) + { + inputTextField.ReplaceSelection(value); + } + + override protected void SetTextFieldText() + { + inputTextField.text = _text; + } + + override protected void CreateDisplayObject() + { + inputTextField = new InputTextField(); + inputTextField.gOwner = this; + displayObject = inputTextField; + + _textField = inputTextField.textField; + } + + public override void Setup_BeforeAdd(ByteBuffer buffer, int beginPos) + { + base.Setup_BeforeAdd(buffer, beginPos); + + buffer.Seek(beginPos, 4); + + string str = buffer.ReadS(); + if (str != null) + inputTextField.promptText = str; + + str = buffer.ReadS(); + if (str != null) + inputTextField.restrict = str; + + int iv = buffer.ReadInt(); + if (iv != 0) + inputTextField.maxLength = iv; + iv = buffer.ReadInt(); + if (iv != 0) + inputTextField.keyboardType = iv; + if (buffer.ReadBool()) + inputTextField.displayAsPassword = true; + } + } } \ No newline at end of file diff --git a/Assets/Scripts/UI/GTextInput.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextInput.cs.meta similarity index 100% rename from Assets/Scripts/UI/GTextInput.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTextInput.cs.meta diff --git a/Assets/Scripts/UI/GTree.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTree.cs similarity index 100% rename from Assets/Scripts/UI/GTree.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTree.cs diff --git a/Assets/Scripts/UI/GTree.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTree.cs.meta similarity index 100% rename from Assets/Scripts/UI/GTree.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTree.cs.meta diff --git a/Assets/Scripts/UI/GTreeNode.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTreeNode.cs similarity index 100% rename from Assets/Scripts/UI/GTreeNode.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTreeNode.cs diff --git a/Assets/Scripts/UI/GTreeNode.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTreeNode.cs.meta similarity index 100% rename from Assets/Scripts/UI/GTreeNode.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/GTreeNode.cs.meta diff --git a/Assets/Scripts/UI/Gears.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears.meta similarity index 100% rename from Assets/Scripts/UI/Gears.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears.meta diff --git a/Assets/Scripts/UI/Gears/GearAnimation.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearAnimation.cs similarity index 96% rename from Assets/Scripts/UI/Gears/GearAnimation.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearAnimation.cs index fe47927a..3638afcc 100644 --- a/Assets/Scripts/UI/Gears/GearAnimation.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearAnimation.cs @@ -1,109 +1,109 @@ -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - class GearAnimationValue - { - public bool playing; - public int frame; - public string animationName; - public string skinName; - - public GearAnimationValue(bool playing, int frame) - { - this.playing = playing; - this.frame = frame; - } - } - - /// - /// Gear is a connection between object and controller. - /// - public class GearAnimation : GearBase - { - Dictionary _storage; - GearAnimationValue _default; - - public GearAnimation(GObject owner) - : base(owner) - { - } - - protected override void Init() - { - _default = new GearAnimationValue(((IAnimationGear)_owner).playing, ((IAnimationGear)_owner).frame); - if (_owner is GLoader3D) - { - _default.animationName = ((GLoader3D)_owner).animationName; - _default.skinName = ((GLoader3D)_owner).skinName; - } - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - GearAnimationValue gv; - if (pageId == null) - gv = _default; - else - { - gv = new GearAnimationValue(false, 0); - _storage[pageId] = gv; - } - - gv.playing = buffer.ReadBool(); - gv.frame = buffer.ReadInt(); - } - - public void AddExtStatus(string pageId, ByteBuffer buffer) - { - GearAnimationValue gv; - if (pageId == null) - gv = _default; - else - gv = _storage[pageId]; - gv.animationName = buffer.ReadS(); - gv.skinName = buffer.ReadS(); - } - - override public void Apply() - { - _owner._gearLocked = true; - - GearAnimationValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - gv = _default; - - IAnimationGear mc = (IAnimationGear)_owner; - mc.frame = gv.frame; - mc.playing = gv.playing; - if (_owner is GLoader3D) - { - ((GLoader3D)_owner).animationName = gv.animationName; - ((GLoader3D)_owner).skinName = gv.skinName; - } - - _owner._gearLocked = false; - } - - override public void UpdateState() - { - IAnimationGear mc = (IAnimationGear)_owner; - GearAnimationValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - _storage[_controller.selectedPageId] = gv = new GearAnimationValue(mc.playing, mc.frame); - else - { - gv.playing = mc.playing; - gv.frame = mc.frame; - } - - if (_owner is GLoader3D) - { - gv.animationName = ((GLoader3D)_owner).animationName; - gv.skinName = ((GLoader3D)_owner).skinName; - } - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearAnimationValue + { + public bool playing; + public int frame; + public string animationName; + public string skinName; + + public GearAnimationValue(bool playing, int frame) + { + this.playing = playing; + this.frame = frame; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearAnimation : GearBase + { + Dictionary _storage; + GearAnimationValue _default; + + public GearAnimation(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearAnimationValue(((IAnimationGear)_owner).playing, ((IAnimationGear)_owner).frame); + if (_owner is GLoader3D) + { + _default.animationName = ((GLoader3D)_owner).animationName; + _default.skinName = ((GLoader3D)_owner).skinName; + } + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearAnimationValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearAnimationValue(false, 0); + _storage[pageId] = gv; + } + + gv.playing = buffer.ReadBool(); + gv.frame = buffer.ReadInt(); + } + + public void AddExtStatus(string pageId, ByteBuffer buffer) + { + GearAnimationValue gv; + if (pageId == null) + gv = _default; + else + gv = _storage[pageId]; + gv.animationName = buffer.ReadS(); + gv.skinName = buffer.ReadS(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + GearAnimationValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + IAnimationGear mc = (IAnimationGear)_owner; + mc.frame = gv.frame; + mc.playing = gv.playing; + if (_owner is GLoader3D) + { + ((GLoader3D)_owner).animationName = gv.animationName; + ((GLoader3D)_owner).skinName = gv.skinName; + } + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + IAnimationGear mc = (IAnimationGear)_owner; + GearAnimationValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = gv = new GearAnimationValue(mc.playing, mc.frame); + else + { + gv.playing = mc.playing; + gv.frame = mc.frame; + } + + if (_owner is GLoader3D) + { + gv.animationName = ((GLoader3D)_owner).animationName; + gv.skinName = ((GLoader3D)_owner).skinName; + } + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearAnimation.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearAnimation.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearAnimation.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearAnimation.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearBase.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearBase.cs similarity index 96% rename from Assets/Scripts/UI/Gears/GearBase.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearBase.cs index ea6b7df8..6d05ef7d 100644 --- a/Assets/Scripts/UI/Gears/GearBase.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearBase.cs @@ -1,203 +1,203 @@ -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// Gear is a connection between object and controller. - /// - abstract public class GearBase - { - public static bool disableAllTweenEffect = false; - - protected GObject _owner; - protected Controller _controller; - protected GearTweenConfig _tweenConfig; - - public GearBase(GObject owner) - { - _owner = owner; - } - - public void Dispose() - { - if (_tweenConfig != null && _tweenConfig._tweener != null) - { - _tweenConfig._tweener.Kill(); - _tweenConfig._tweener = null; - } - } - - /// - /// Controller object. - /// - public Controller controller - { - get - { - return _controller; - } - - set - { - if (value != _controller) - { - _controller = value; - if (_controller != null) - Init(); - } - } - } - - public GearTweenConfig tweenConfig - { - get - { - if (_tweenConfig == null) - _tweenConfig = new GearTweenConfig(); - return _tweenConfig; - } - } - - public void Setup(ByteBuffer buffer) - { - _controller = _owner.parent.GetControllerAt(buffer.ReadShort()); - Init(); - - int cnt = buffer.ReadShort(); - if (this is GearDisplay) - { - ((GearDisplay)this).pages = buffer.ReadSArray(cnt); - } - else if (this is GearDisplay2) - { - ((GearDisplay2)this).pages = buffer.ReadSArray(cnt); - } - else - { - for (int i = 0; i < cnt; i++) - { - string page = buffer.ReadS(); - if (page == null) - continue; - - AddStatus(page, buffer); - } - - if (buffer.ReadBool()) - AddStatus(null, buffer); - } - - if (buffer.ReadBool()) - { - _tweenConfig = new GearTweenConfig(); - _tweenConfig.easeType = (EaseType)buffer.ReadByte(); - _tweenConfig.duration = buffer.ReadFloat(); - _tweenConfig.delay = buffer.ReadFloat(); - } - - if (buffer.version >= 2) - { - if (this is GearXY) - { - if (buffer.ReadBool()) - { - ((GearXY)this).positionsInPercent = true; - for (int i = 0; i < cnt; i++) - { - string page = buffer.ReadS(); - if (page == null) - continue; - - ((GearXY)this).AddExtStatus(page, buffer); - } - - if (buffer.ReadBool()) - ((GearXY)this).AddExtStatus(null, buffer); - } - } - else if (this is GearDisplay2) - ((GearDisplay2)this).condition = buffer.ReadByte(); - } - - if (buffer.version >= 4 && _tweenConfig != null && _tweenConfig.easeType == EaseType.Custom) - { - _tweenConfig.customEase = new CustomEase(); - _tweenConfig.customEase.Create(buffer.ReadPath()); - } - - if (buffer.version >= 6) - { - if (this is GearAnimation) - { - for (int i = 0; i < cnt; i++) - { - string page = buffer.ReadS(); - if (page == null) - continue; - - ((GearAnimation)this).AddExtStatus(page, buffer); - } - - if (buffer.ReadBool()) - ((GearAnimation)this).AddExtStatus(null, buffer); - } - } - } - - virtual public void UpdateFromRelations(float dx, float dy) - { - } - - abstract protected void AddStatus(string pageId, ByteBuffer buffer); - abstract protected void Init(); - - /// - /// Call when controller active page changed. - /// - abstract public void Apply(); - - /// - /// Call when object's properties changed. - /// - abstract public void UpdateState(); - } - - public class GearTweenConfig - { - /// - /// Use tween to apply change. - /// - public bool tween; - - /// - /// Ease type. - /// - public EaseType easeType; - - /// - /// - /// - public CustomEase customEase; - - /// - /// Tween duration in seconds. - /// - public float duration; - - /// - /// Tween delay in seconds. - /// - public float delay; - - internal uint _displayLockToken; - internal GTweener _tweener; - - public GearTweenConfig() - { - tween = true; - easeType = EaseType.QuadOut; - duration = 0.3f; - delay = 0; - } - } -} +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + abstract public class GearBase + { + public static bool disableAllTweenEffect = false; + + protected GObject _owner; + protected Controller _controller; + protected GearTweenConfig _tweenConfig; + + public GearBase(GObject owner) + { + _owner = owner; + } + + public void Dispose() + { + if (_tweenConfig != null && _tweenConfig._tweener != null) + { + _tweenConfig._tweener.Kill(); + _tweenConfig._tweener = null; + } + } + + /// + /// Controller object. + /// + public Controller controller + { + get + { + return _controller; + } + + set + { + if (value != _controller) + { + _controller = value; + if (_controller != null) + Init(); + } + } + } + + public GearTweenConfig tweenConfig + { + get + { + if (_tweenConfig == null) + _tweenConfig = new GearTweenConfig(); + return _tweenConfig; + } + } + + public void Setup(ByteBuffer buffer) + { + _controller = _owner.parent.GetControllerAt(buffer.ReadShort()); + Init(); + + int cnt = buffer.ReadShort(); + if (this is GearDisplay) + { + ((GearDisplay)this).pages = buffer.ReadSArray(cnt); + } + else if (this is GearDisplay2) + { + ((GearDisplay2)this).pages = buffer.ReadSArray(cnt); + } + else + { + for (int i = 0; i < cnt; i++) + { + string page = buffer.ReadS(); + if (page == null) + continue; + + AddStatus(page, buffer); + } + + if (buffer.ReadBool()) + AddStatus(null, buffer); + } + + if (buffer.ReadBool()) + { + _tweenConfig = new GearTweenConfig(); + _tweenConfig.easeType = (EaseType)buffer.ReadByte(); + _tweenConfig.duration = buffer.ReadFloat(); + _tweenConfig.delay = buffer.ReadFloat(); + } + + if (buffer.version >= 2) + { + if (this is GearXY) + { + if (buffer.ReadBool()) + { + ((GearXY)this).positionsInPercent = true; + for (int i = 0; i < cnt; i++) + { + string page = buffer.ReadS(); + if (page == null) + continue; + + ((GearXY)this).AddExtStatus(page, buffer); + } + + if (buffer.ReadBool()) + ((GearXY)this).AddExtStatus(null, buffer); + } + } + else if (this is GearDisplay2) + ((GearDisplay2)this).condition = buffer.ReadByte(); + } + + if (buffer.version >= 4 && _tweenConfig != null && _tweenConfig.easeType == EaseType.Custom) + { + _tweenConfig.customEase = new CustomEase(); + _tweenConfig.customEase.Create(buffer.ReadPath()); + } + + if (buffer.version >= 6) + { + if (this is GearAnimation) + { + for (int i = 0; i < cnt; i++) + { + string page = buffer.ReadS(); + if (page == null) + continue; + + ((GearAnimation)this).AddExtStatus(page, buffer); + } + + if (buffer.ReadBool()) + ((GearAnimation)this).AddExtStatus(null, buffer); + } + } + } + + virtual public void UpdateFromRelations(float dx, float dy) + { + } + + abstract protected void AddStatus(string pageId, ByteBuffer buffer); + abstract protected void Init(); + + /// + /// Call when controller active page changed. + /// + abstract public void Apply(); + + /// + /// Call when object's properties changed. + /// + abstract public void UpdateState(); + } + + public class GearTweenConfig + { + /// + /// Use tween to apply change. + /// + public bool tween; + + /// + /// Ease type. + /// + public EaseType easeType; + + /// + /// + /// + public CustomEase customEase; + + /// + /// Tween duration in seconds. + /// + public float duration; + + /// + /// Tween delay in seconds. + /// + public float delay; + + internal uint _displayLockToken; + internal GTweener _tweener; + + public GearTweenConfig() + { + tween = true; + easeType = EaseType.QuadOut; + duration = 0.3f; + delay = 0; + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearBase.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearBase.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearBase.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearBase.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearColor.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearColor.cs similarity index 96% rename from Assets/Scripts/UI/Gears/GearColor.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearColor.cs index 4083327e..0e07b854 100644 --- a/Assets/Scripts/UI/Gears/GearColor.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearColor.cs @@ -1,142 +1,142 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - class GearColorValue - { - public Color color; - public Color strokeColor; - - public GearColorValue() - { - } - - public GearColorValue(Color color, Color strokeColor) - { - this.color = color; - this.strokeColor = strokeColor; - } - } - - /// - /// Gear is a connection between object and controller. - /// - public class GearColor : GearBase, ITweenListener - { - Dictionary _storage; - GearColorValue _default; - - public GearColor(GObject owner) - : base(owner) - { - } - - protected override void Init() - { - _default = new GearColorValue(); - _default.color = ((IColorGear)_owner).color; - if (_owner is ITextColorGear) - _default.strokeColor = ((ITextColorGear)_owner).strokeColor; - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - GearColorValue gv; - if (pageId == null) - gv = _default; - else - { - gv = new GearColorValue(Color.black, Color.black); - _storage[pageId] = gv; - } - - gv.color = buffer.ReadColor(); - gv.strokeColor = buffer.ReadColor(); - } - - override public void Apply() - { - GearColorValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - gv = _default; - - if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) - { - if ((_owner is ITextColorGear) && gv.strokeColor.a > 0) - { - _owner._gearLocked = true; - ((ITextColorGear)_owner).strokeColor = gv.strokeColor; - _owner._gearLocked = false; - } - - if (_tweenConfig._tweener != null) - { - if (_tweenConfig._tweener.endValue.color != gv.color) - { - _tweenConfig._tweener.Kill(true); - _tweenConfig._tweener = null; - } - else - return; - } - - if (((IColorGear)_owner).color != gv.color) - { - if (_owner.CheckGearController(0, _controller)) - _tweenConfig._displayLockToken = _owner.AddDisplayLock(); - - _tweenConfig._tweener = GTween.To(((IColorGear)_owner).color, gv.color, _tweenConfig.duration) - .SetDelay(_tweenConfig.delay) - .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) - .SetTarget(this) - .SetListener(this); - } - } - else - { - _owner._gearLocked = true; - ((IColorGear)_owner).color = gv.color; - if ((_owner is ITextColorGear) && gv.strokeColor.a > 0) - ((ITextColorGear)_owner).strokeColor = gv.strokeColor; - _owner._gearLocked = false; - } - } - - public void OnTweenStart(GTweener tweener) - { - } - - public void OnTweenUpdate(GTweener tweener) - { - _owner._gearLocked = true; - ((IColorGear)_owner).color = tweener.value.color; - _owner._gearLocked = false; - - _owner.InvalidateBatchingState(); - } - - public void OnTweenComplete(GTweener tweener) - { - _tweenConfig._tweener = null; - if (_tweenConfig._displayLockToken != 0) - { - _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); - _tweenConfig._displayLockToken = 0; - } - _owner.DispatchEvent("onGearStop", this); - } - - override public void UpdateState() - { - GearColorValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - _storage[_controller.selectedPageId] = gv = new GearColorValue(); - gv.color = ((IColorGear)_owner).color; - if (_owner is ITextColorGear) - gv.strokeColor = ((ITextColorGear)_owner).strokeColor; - } - } -} +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearColorValue + { + public Color color; + public Color strokeColor; + + public GearColorValue() + { + } + + public GearColorValue(Color color, Color strokeColor) + { + this.color = color; + this.strokeColor = strokeColor; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearColor : GearBase, ITweenListener + { + Dictionary _storage; + GearColorValue _default; + + public GearColor(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearColorValue(); + _default.color = ((IColorGear)_owner).color; + if (_owner is ITextColorGear) + _default.strokeColor = ((ITextColorGear)_owner).strokeColor; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearColorValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearColorValue(Color.black, Color.black); + _storage[pageId] = gv; + } + + gv.color = buffer.ReadColor(); + gv.strokeColor = buffer.ReadColor(); + } + + override public void Apply() + { + GearColorValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + if ((_owner is ITextColorGear) && gv.strokeColor.a > 0) + { + _owner._gearLocked = true; + ((ITextColorGear)_owner).strokeColor = gv.strokeColor; + _owner._gearLocked = false; + } + + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.color != gv.color) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + + if (((IColorGear)_owner).color != gv.color) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(((IColorGear)_owner).color, gv.color, _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + ((IColorGear)_owner).color = gv.color; + if ((_owner is ITextColorGear) && gv.strokeColor.a > 0) + ((ITextColorGear)_owner).strokeColor = gv.strokeColor; + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + { + } + + public void OnTweenUpdate(GTweener tweener) + { + _owner._gearLocked = true; + ((IColorGear)_owner).color = tweener.value.color; + _owner._gearLocked = false; + + _owner.InvalidateBatchingState(); + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearColorValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = gv = new GearColorValue(); + gv.color = ((IColorGear)_owner).color; + if (_owner is ITextColorGear) + gv.strokeColor = ((ITextColorGear)_owner).strokeColor; + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearColor.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearColor.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearColor.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearColor.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearDisplay.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay.cs similarity index 95% rename from Assets/Scripts/UI/Gears/GearDisplay.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay.cs index f8dfa3a8..c8c2e8ae 100644 --- a/Assets/Scripts/UI/Gears/GearDisplay.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay.cs @@ -1,68 +1,68 @@ -using System; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// Gear is a connection between object and controller. - /// - public class GearDisplay : GearBase - { - /// - /// Pages involed in this gear. - /// - public string[] pages { get; set; } - - int _visible; - uint _displayLockToken; - - public GearDisplay(GObject owner) - : base(owner) - { - _displayLockToken = 1; - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - } - - override protected void Init() - { - pages = null; - } - - override public void Apply() - { - _displayLockToken++; - if (_displayLockToken == 0) - _displayLockToken = 1; - - if (pages == null || pages.Length == 0 - || Array.IndexOf(pages, _controller.selectedPageId) != -1) - _visible = 1; - else - _visible = 0; - } - - override public void UpdateState() - { - } - - public uint AddLock() - { - _visible++; - return _displayLockToken; - } - - public void ReleaseLock(uint token) - { - if (token == _displayLockToken) - _visible--; - } - - public bool connected - { - get { return _controller == null || _visible > 0; } - } - } -} +using System; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearDisplay : GearBase + { + /// + /// Pages involed in this gear. + /// + public string[] pages { get; set; } + + int _visible; + uint _displayLockToken; + + public GearDisplay(GObject owner) + : base(owner) + { + _displayLockToken = 1; + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + } + + override protected void Init() + { + pages = null; + } + + override public void Apply() + { + _displayLockToken++; + if (_displayLockToken == 0) + _displayLockToken = 1; + + if (pages == null || pages.Length == 0 + || Array.IndexOf(pages, _controller.selectedPageId) != -1) + _visible = 1; + else + _visible = 0; + } + + override public void UpdateState() + { + } + + public uint AddLock() + { + _visible++; + return _displayLockToken; + } + + public void ReleaseLock(uint token) + { + if (token == _displayLockToken) + _visible--; + } + + public bool connected + { + get { return _controller == null || _visible > 0; } + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearDisplay.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearDisplay.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearDisplay2.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay2.cs similarity index 100% rename from Assets/Scripts/UI/Gears/GearDisplay2.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay2.cs diff --git a/Assets/Scripts/UI/Gears/GearDisplay2.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay2.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearDisplay2.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearDisplay2.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearFontSize.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearFontSize.cs similarity index 100% rename from Assets/Scripts/UI/Gears/GearFontSize.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearFontSize.cs diff --git a/Assets/Scripts/UI/Gears/GearFontSize.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearFontSize.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearFontSize.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearFontSize.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearIcon.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearIcon.cs similarity index 95% rename from Assets/Scripts/UI/Gears/GearIcon.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearIcon.cs index e92a0314..be04750e 100644 --- a/Assets/Scripts/UI/Gears/GearIcon.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearIcon.cs @@ -1,51 +1,51 @@ -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// Gear is a connection between object and controller. - /// - public class GearIcon : GearBase - { - Dictionary _storage; - string _default; - - public GearIcon(GObject owner) - : base(owner) - { - } - - protected override void Init() - { - _default = _owner.icon; - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - if (pageId == null) - _default = buffer.ReadS(); - else - _storage[pageId] = buffer.ReadS(); - } - - override public void Apply() - { - _owner._gearLocked = true; - - string cv; - if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) - cv = _default; - - _owner.icon = cv; - - _owner._gearLocked = false; - } - - override public void UpdateState() - { - _storage[_controller.selectedPageId] = _owner.icon; - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearIcon : GearBase + { + Dictionary _storage; + string _default; + + public GearIcon(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = _owner.icon; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + if (pageId == null) + _default = buffer.ReadS(); + else + _storage[pageId] = buffer.ReadS(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + string cv; + if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) + cv = _default; + + _owner.icon = cv; + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + _storage[_controller.selectedPageId] = _owner.icon; + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearIcon.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearIcon.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearIcon.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearIcon.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearLook.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearLook.cs similarity index 97% rename from Assets/Scripts/UI/Gears/GearLook.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearLook.cs index 49fa68ef..20c7520e 100644 --- a/Assets/Scripts/UI/Gears/GearLook.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearLook.cs @@ -1,152 +1,152 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - class GearLookValue - { - public float alpha; - public float rotation; - public bool grayed; - public bool touchable; - - public GearLookValue(float alpha, float rotation, bool grayed, bool touchable) - { - this.alpha = alpha; - this.rotation = rotation; - this.grayed = grayed; - this.touchable = touchable; - } - } - - /// - /// Gear is a connection between object and controller. - /// - public class GearLook : GearBase, ITweenListener - { - Dictionary _storage; - GearLookValue _default; - - public GearLook(GObject owner) - : base(owner) - { - } - - protected override void Init() - { - _default = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable); - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - GearLookValue gv; - if (pageId == null) - gv = _default; - else - { - gv = new GearLookValue(0, 0, false, false); - _storage[pageId] = gv; - } - - gv.alpha = buffer.ReadFloat(); - gv.rotation = buffer.ReadFloat(); - gv.grayed = buffer.ReadBool(); - gv.touchable = buffer.ReadBool(); - } - - override public void Apply() - { - GearLookValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - gv = _default; - - if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) - { - _owner._gearLocked = true; - _owner.grayed = gv.grayed; - _owner.touchable = gv.touchable; - _owner._gearLocked = false; - - if (_tweenConfig._tweener != null) - { - if (_tweenConfig._tweener.endValue.x != gv.alpha || _tweenConfig._tweener.endValue.y != gv.rotation) - { - _tweenConfig._tweener.Kill(true); - _tweenConfig._tweener = null; - } - else - return; - } - - bool a = gv.alpha != _owner.alpha; - bool b = gv.rotation != _owner.rotation; - if (a || b) - { - if (_owner.CheckGearController(0, _controller)) - _tweenConfig._displayLockToken = _owner.AddDisplayLock(); - - _tweenConfig._tweener = GTween.To(new Vector2(_owner.alpha, _owner.rotation), new Vector2(gv.alpha, gv.rotation), _tweenConfig.duration) - .SetDelay(_tweenConfig.delay) - .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) - .SetUserData((a ? 1 : 0) + (b ? 2 : 0)) - .SetTarget(this) - .SetListener(this); - } - } - else - { - _owner._gearLocked = true; - _owner.alpha = gv.alpha; - _owner.rotation = gv.rotation; - _owner.grayed = gv.grayed; - _owner.touchable = gv.touchable; - _owner._gearLocked = false; - } - } - - public void OnTweenStart(GTweener tweener) - { - } - - public void OnTweenUpdate(GTweener tweener) - { - int flag = (int)tweener.userData; - _owner._gearLocked = true; - if ((flag & 1) != 0) - _owner.alpha = tweener.value.x; - if ((flag & 2) != 0) - { - _owner.rotation = tweener.value.y; - _owner.InvalidateBatchingState(); - } - _owner._gearLocked = false; - } - - public void OnTweenComplete(GTweener tweener) - { - _tweenConfig._tweener = null; - if (_tweenConfig._displayLockToken != 0) - { - _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); - _tweenConfig._displayLockToken = 0; - } - _owner.DispatchEvent("onGearStop", this); - } - - override public void UpdateState() - { - GearLookValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - _storage[_controller.selectedPageId] = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable); - else - { - gv.alpha = _owner.alpha; - gv.rotation = _owner.rotation; - gv.grayed = _owner.grayed; - gv.touchable = _owner.touchable; - } - } - } -} +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearLookValue + { + public float alpha; + public float rotation; + public bool grayed; + public bool touchable; + + public GearLookValue(float alpha, float rotation, bool grayed, bool touchable) + { + this.alpha = alpha; + this.rotation = rotation; + this.grayed = grayed; + this.touchable = touchable; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearLook : GearBase, ITweenListener + { + Dictionary _storage; + GearLookValue _default; + + public GearLook(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable); + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearLookValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearLookValue(0, 0, false, false); + _storage[pageId] = gv; + } + + gv.alpha = buffer.ReadFloat(); + gv.rotation = buffer.ReadFloat(); + gv.grayed = buffer.ReadBool(); + gv.touchable = buffer.ReadBool(); + } + + override public void Apply() + { + GearLookValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + _owner._gearLocked = true; + _owner.grayed = gv.grayed; + _owner.touchable = gv.touchable; + _owner._gearLocked = false; + + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.x != gv.alpha || _tweenConfig._tweener.endValue.y != gv.rotation) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + + bool a = gv.alpha != _owner.alpha; + bool b = gv.rotation != _owner.rotation; + if (a || b) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(new Vector2(_owner.alpha, _owner.rotation), new Vector2(gv.alpha, gv.rotation), _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetUserData((a ? 1 : 0) + (b ? 2 : 0)) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + _owner.alpha = gv.alpha; + _owner.rotation = gv.rotation; + _owner.grayed = gv.grayed; + _owner.touchable = gv.touchable; + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + { + } + + public void OnTweenUpdate(GTweener tweener) + { + int flag = (int)tweener.userData; + _owner._gearLocked = true; + if ((flag & 1) != 0) + _owner.alpha = tweener.value.x; + if ((flag & 2) != 0) + { + _owner.rotation = tweener.value.y; + _owner.InvalidateBatchingState(); + } + _owner._gearLocked = false; + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearLookValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable); + else + { + gv.alpha = _owner.alpha; + gv.rotation = _owner.rotation; + gv.grayed = _owner.grayed; + gv.touchable = _owner.touchable; + } + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearLook.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearLook.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearLook.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearLook.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearSize.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearSize.cs similarity index 97% rename from Assets/Scripts/UI/Gears/GearSize.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearSize.cs index 0a37ae67..e949097e 100644 --- a/Assets/Scripts/UI/Gears/GearSize.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearSize.cs @@ -1,163 +1,163 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - class GearSizeValue - { - public float width; - public float height; - public float scaleX; - public float scaleY; - - public GearSizeValue(float width, float height, float scaleX, float scaleY) - { - this.width = width; - this.height = height; - this.scaleX = scaleX; - this.scaleY = scaleY; - } - } - - /// - /// Gear is a connection between object and controller. - /// - public class GearSize : GearBase, ITweenListener - { - Dictionary _storage; - GearSizeValue _default; - - public GearSize(GObject owner) - : base(owner) - { - - } - - protected override void Init() - { - _default = new GearSizeValue(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY); - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - GearSizeValue gv; - if (pageId == null) - gv = _default; - else - { - gv = new GearSizeValue(0, 0, 1, 1); - _storage[pageId] = gv; - } - - gv.width = buffer.ReadInt(); - gv.height = buffer.ReadInt(); - gv.scaleX = buffer.ReadFloat(); - gv.scaleY = buffer.ReadFloat(); - } - - override public void Apply() - { - GearSizeValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - gv = _default; - - if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) - { - if (_tweenConfig._tweener != null) - { - if (_tweenConfig._tweener.endValue.x != gv.width || _tweenConfig._tweener.endValue.y != gv.height - || _tweenConfig._tweener.endValue.z != gv.scaleX || _tweenConfig._tweener.endValue.w != gv.scaleY) - { - _tweenConfig._tweener.Kill(true); - _tweenConfig._tweener = null; - } - else - return; - } - - bool a = gv.width != _owner.width || gv.height != _owner.height; - bool b = gv.scaleX != _owner.scaleX || gv.scaleY != _owner.scaleY; - if (a || b) - { - if (_owner.CheckGearController(0, _controller)) - _tweenConfig._displayLockToken = _owner.AddDisplayLock(); - - _tweenConfig._tweener = GTween.To(new Vector4(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY), - new Vector4(gv.width, gv.height, gv.scaleX, gv.scaleY), _tweenConfig.duration) - .SetDelay(_tweenConfig.delay) - .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) - .SetUserData((a ? 1 : 0) + (b ? 2 : 0)) - .SetTarget(this) - .SetListener(this); - } - } - else - { - _owner._gearLocked = true; - _owner.SetSize(gv.width, gv.height, _owner.CheckGearController(1, _controller)); - _owner.SetScale(gv.scaleX, gv.scaleY); - _owner._gearLocked = false; - } - } - - public void OnTweenStart(GTweener tweener) - { - } - - public void OnTweenUpdate(GTweener tweener) - { - _owner._gearLocked = true; - int flag = (int)tweener.userData; - if ((flag & 1) != 0) - _owner.SetSize(tweener.value.x, tweener.value.y, _owner.CheckGearController(1, _controller)); - if ((flag & 2) != 0) - _owner.SetScale(tweener.value.z, tweener.value.w); - _owner._gearLocked = false; - - _owner.InvalidateBatchingState(); - } - - public void OnTweenComplete(GTweener tweener) - { - _tweenConfig._tweener = null; - if (_tweenConfig._displayLockToken != 0) - { - _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); - _tweenConfig._displayLockToken = 0; - } - _owner.DispatchEvent("onGearStop", this); - } - - override public void UpdateState() - { - GearSizeValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - _storage[_controller.selectedPageId] = new GearSizeValue(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY); - else - { - gv.width = _owner.width; - gv.height = _owner.height; - gv.scaleX = _owner.scaleX; - gv.scaleY = _owner.scaleY; - } - } - - override public void UpdateFromRelations(float dx, float dy) - { - if (_controller != null && _storage != null) - { - foreach (GearSizeValue gv in _storage.Values) - { - gv.width += dx; - gv.height += dy; - } - _default.width += dx; - _default.height += dy; - - UpdateState(); - } - } - } -} +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearSizeValue + { + public float width; + public float height; + public float scaleX; + public float scaleY; + + public GearSizeValue(float width, float height, float scaleX, float scaleY) + { + this.width = width; + this.height = height; + this.scaleX = scaleX; + this.scaleY = scaleY; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearSize : GearBase, ITweenListener + { + Dictionary _storage; + GearSizeValue _default; + + public GearSize(GObject owner) + : base(owner) + { + + } + + protected override void Init() + { + _default = new GearSizeValue(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY); + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearSizeValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearSizeValue(0, 0, 1, 1); + _storage[pageId] = gv; + } + + gv.width = buffer.ReadInt(); + gv.height = buffer.ReadInt(); + gv.scaleX = buffer.ReadFloat(); + gv.scaleY = buffer.ReadFloat(); + } + + override public void Apply() + { + GearSizeValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.x != gv.width || _tweenConfig._tweener.endValue.y != gv.height + || _tweenConfig._tweener.endValue.z != gv.scaleX || _tweenConfig._tweener.endValue.w != gv.scaleY) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + + bool a = gv.width != _owner.width || gv.height != _owner.height; + bool b = gv.scaleX != _owner.scaleX || gv.scaleY != _owner.scaleY; + if (a || b) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(new Vector4(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY), + new Vector4(gv.width, gv.height, gv.scaleX, gv.scaleY), _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetUserData((a ? 1 : 0) + (b ? 2 : 0)) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + _owner.SetSize(gv.width, gv.height, _owner.CheckGearController(1, _controller)); + _owner.SetScale(gv.scaleX, gv.scaleY); + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + { + } + + public void OnTweenUpdate(GTweener tweener) + { + _owner._gearLocked = true; + int flag = (int)tweener.userData; + if ((flag & 1) != 0) + _owner.SetSize(tweener.value.x, tweener.value.y, _owner.CheckGearController(1, _controller)); + if ((flag & 2) != 0) + _owner.SetScale(tweener.value.z, tweener.value.w); + _owner._gearLocked = false; + + _owner.InvalidateBatchingState(); + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearSizeValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = new GearSizeValue(_owner.width, _owner.height, _owner.scaleX, _owner.scaleY); + else + { + gv.width = _owner.width; + gv.height = _owner.height; + gv.scaleX = _owner.scaleX; + gv.scaleY = _owner.scaleY; + } + } + + override public void UpdateFromRelations(float dx, float dy) + { + if (_controller != null && _storage != null) + { + foreach (GearSizeValue gv in _storage.Values) + { + gv.width += dx; + gv.height += dy; + } + _default.width += dx; + _default.height += dy; + + UpdateState(); + } + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearSize.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearSize.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearSize.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearSize.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearText.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearText.cs similarity index 95% rename from Assets/Scripts/UI/Gears/GearText.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearText.cs index ff188978..7cef4408 100644 --- a/Assets/Scripts/UI/Gears/GearText.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearText.cs @@ -1,51 +1,51 @@ -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// Gear is a connection between object and controller. - /// - public class GearText : GearBase - { - Dictionary _storage; - string _default; - - public GearText(GObject owner) - : base(owner) - { - } - - protected override void Init() - { - _default = _owner.text; - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - if (pageId == null) - _default = buffer.ReadS(); - else - _storage[pageId] = buffer.ReadS(); - } - - override public void Apply() - { - _owner._gearLocked = true; - - string cv; - if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) - cv = _default; - - _owner.text = cv; - - _owner._gearLocked = false; - } - - override public void UpdateState() - { - _storage[_controller.selectedPageId] = _owner.text; - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// Gear is a connection between object and controller. + /// + public class GearText : GearBase + { + Dictionary _storage; + string _default; + + public GearText(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = _owner.text; + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + if (pageId == null) + _default = buffer.ReadS(); + else + _storage[pageId] = buffer.ReadS(); + } + + override public void Apply() + { + _owner._gearLocked = true; + + string cv; + if (!_storage.TryGetValue(_controller.selectedPageId, out cv)) + cv = _default; + + _owner.text = cv; + + _owner._gearLocked = false; + } + + override public void UpdateState() + { + _storage[_controller.selectedPageId] = _owner.text; + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearText.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearText.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearText.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearText.cs.meta diff --git a/Assets/Scripts/UI/Gears/GearXY.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearXY.cs similarity index 96% rename from Assets/Scripts/UI/Gears/GearXY.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearXY.cs index acaead1a..ed48c788 100644 --- a/Assets/Scripts/UI/Gears/GearXY.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearXY.cs @@ -1,177 +1,177 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - class GearXYValue - { - public float x; - public float y; - public float px; - public float py; - - public GearXYValue(float x = 0, float y = 0, float px = 0, float py = 0) - { - this.x = x; - this.y = y; - this.px = px; - this.py = py; - } - } - - /// - /// Gear is a connection between object and controller. - /// - public class GearXY : GearBase, ITweenListener - { - public bool positionsInPercent; - - Dictionary _storage; - GearXYValue _default; - - public GearXY(GObject owner) - : base(owner) - { - } - - protected override void Init() - { - _default = new GearXYValue(_owner.x, _owner.y, _owner.x / _owner.parent.width, _owner.y / _owner.parent.height); - _storage = new Dictionary(); - } - - override protected void AddStatus(string pageId, ByteBuffer buffer) - { - GearXYValue gv; - if (pageId == null) - gv = _default; - else - { - gv = new GearXYValue(); - _storage[pageId] = gv; - } - - gv.x = buffer.ReadInt(); - gv.y = buffer.ReadInt(); - } - - public void AddExtStatus(string pageId, ByteBuffer buffer) - { - GearXYValue gv; - if (pageId == null) - gv = _default; - else - gv = _storage[pageId]; - gv.px = buffer.ReadFloat(); - gv.py = buffer.ReadFloat(); - } - - override public void Apply() - { - GearXYValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - gv = _default; - - Vector2 endPos = new Vector2(); - - if (positionsInPercent && _owner.parent != null) - { - endPos.x = gv.px * _owner.parent.width; - endPos.y = gv.py * _owner.parent.height; - } - else - { - endPos.x = gv.x; - endPos.y = gv.y; - } - - if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) - { - if (_tweenConfig._tweener != null) - { - if (_tweenConfig._tweener.endValue.x != endPos.x || _tweenConfig._tweener.endValue.y != endPos.y) - { - _tweenConfig._tweener.Kill(true); - _tweenConfig._tweener = null; - } - else - return; - } - Vector2 origin = _owner.xy; - - if (endPos != origin) - { - if (_owner.CheckGearController(0, _controller)) - _tweenConfig._displayLockToken = _owner.AddDisplayLock(); - - _tweenConfig._tweener = GTween.To(origin, endPos, _tweenConfig.duration) - .SetDelay(_tweenConfig.delay) - .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) - .SetTarget(this) - .SetListener(this); - } - } - else - { - _owner._gearLocked = true; - _owner.SetXY(endPos.x, endPos.y); - _owner._gearLocked = false; - } - } - - public void OnTweenStart(GTweener tweener) - {//nothing - } - - public void OnTweenUpdate(GTweener tweener) - { - _owner._gearLocked = true; - _owner.SetXY(tweener.value.x, tweener.value.y); - _owner._gearLocked = false; - - _owner.InvalidateBatchingState(); - } - - public void OnTweenComplete(GTweener tweener) - { - _tweenConfig._tweener = null; - if (_tweenConfig._displayLockToken != 0) - { - _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); - _tweenConfig._displayLockToken = 0; - } - _owner.DispatchEvent("onGearStop", this); - } - - override public void UpdateState() - { - GearXYValue gv; - if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) - _storage[_controller.selectedPageId] = gv = new GearXYValue(); - - gv.x = _owner.x; - gv.y = _owner.y; - - gv.px = _owner.x / _owner.parent.width; - gv.py = _owner.y / _owner.parent.height; - - } - - override public void UpdateFromRelations(float dx, float dy) - { - if (_controller != null && _storage != null && !positionsInPercent) - { - foreach (GearXYValue gv in _storage.Values) - { - gv.x += dx; - gv.y += dy; - } - _default.x += dx; - _default.y += dy; - - UpdateState(); - } - } - } -} +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class GearXYValue + { + public float x; + public float y; + public float px; + public float py; + + public GearXYValue(float x = 0, float y = 0, float px = 0, float py = 0) + { + this.x = x; + this.y = y; + this.px = px; + this.py = py; + } + } + + /// + /// Gear is a connection between object and controller. + /// + public class GearXY : GearBase, ITweenListener + { + public bool positionsInPercent; + + Dictionary _storage; + GearXYValue _default; + + public GearXY(GObject owner) + : base(owner) + { + } + + protected override void Init() + { + _default = new GearXYValue(_owner.x, _owner.y, _owner.x / _owner.parent.width, _owner.y / _owner.parent.height); + _storage = new Dictionary(); + } + + override protected void AddStatus(string pageId, ByteBuffer buffer) + { + GearXYValue gv; + if (pageId == null) + gv = _default; + else + { + gv = new GearXYValue(); + _storage[pageId] = gv; + } + + gv.x = buffer.ReadInt(); + gv.y = buffer.ReadInt(); + } + + public void AddExtStatus(string pageId, ByteBuffer buffer) + { + GearXYValue gv; + if (pageId == null) + gv = _default; + else + gv = _storage[pageId]; + gv.px = buffer.ReadFloat(); + gv.py = buffer.ReadFloat(); + } + + override public void Apply() + { + GearXYValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + gv = _default; + + Vector2 endPos = new Vector2(); + + if (positionsInPercent && _owner.parent != null) + { + endPos.x = gv.px * _owner.parent.width; + endPos.y = gv.py * _owner.parent.height; + } + else + { + endPos.x = gv.x; + endPos.y = gv.y; + } + + if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect) + { + if (_tweenConfig._tweener != null) + { + if (_tweenConfig._tweener.endValue.x != endPos.x || _tweenConfig._tweener.endValue.y != endPos.y) + { + _tweenConfig._tweener.Kill(true); + _tweenConfig._tweener = null; + } + else + return; + } + Vector2 origin = _owner.xy; + + if (endPos != origin) + { + if (_owner.CheckGearController(0, _controller)) + _tweenConfig._displayLockToken = _owner.AddDisplayLock(); + + _tweenConfig._tweener = GTween.To(origin, endPos, _tweenConfig.duration) + .SetDelay(_tweenConfig.delay) + .SetEase(_tweenConfig.easeType, _tweenConfig.customEase) + .SetTarget(this) + .SetListener(this); + } + } + else + { + _owner._gearLocked = true; + _owner.SetXY(endPos.x, endPos.y); + _owner._gearLocked = false; + } + } + + public void OnTweenStart(GTweener tweener) + {//nothing + } + + public void OnTweenUpdate(GTweener tweener) + { + _owner._gearLocked = true; + _owner.SetXY(tweener.value.x, tweener.value.y); + _owner._gearLocked = false; + + _owner.InvalidateBatchingState(); + } + + public void OnTweenComplete(GTweener tweener) + { + _tweenConfig._tweener = null; + if (_tweenConfig._displayLockToken != 0) + { + _owner.ReleaseDisplayLock(_tweenConfig._displayLockToken); + _tweenConfig._displayLockToken = 0; + } + _owner.DispatchEvent("onGearStop", this); + } + + override public void UpdateState() + { + GearXYValue gv; + if (!_storage.TryGetValue(_controller.selectedPageId, out gv)) + _storage[_controller.selectedPageId] = gv = new GearXYValue(); + + gv.x = _owner.x; + gv.y = _owner.y; + + gv.px = _owner.x / _owner.parent.width; + gv.py = _owner.y / _owner.parent.height; + + } + + override public void UpdateFromRelations(float dx, float dy) + { + if (_controller != null && _storage != null && !positionsInPercent) + { + foreach (GearXYValue gv in _storage.Values) + { + gv.x += dx; + gv.y += dy; + } + _default.x += dx; + _default.y += dy; + + UpdateState(); + } + } + } +} diff --git a/Assets/Scripts/UI/Gears/GearXY.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearXY.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/GearXY.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/GearXY.cs.meta diff --git a/Assets/Scripts/UI/Gears/IAnimationGear.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IAnimationGear.cs similarity index 94% rename from Assets/Scripts/UI/Gears/IAnimationGear.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IAnimationGear.cs index 7c68a014..7c7900fa 100644 --- a/Assets/Scripts/UI/Gears/IAnimationGear.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IAnimationGear.cs @@ -1,35 +1,35 @@ - -namespace FairyGUI -{ - /// - /// - /// - public interface IAnimationGear - { - /// - /// - /// - bool playing { get; set; } - - /// - /// - /// - int frame { get; set; } - - /// - /// - /// - float timeScale { get; set; } - - /// - /// - /// - bool ignoreEngineTimeScale { get; set; } - - /// - /// - /// - /// - void Advance(float time); - } -} + +namespace FairyGUI +{ + /// + /// + /// + public interface IAnimationGear + { + /// + /// + /// + bool playing { get; set; } + + /// + /// + /// + int frame { get; set; } + + /// + /// + /// + float timeScale { get; set; } + + /// + /// + /// + bool ignoreEngineTimeScale { get; set; } + + /// + /// + /// + /// + void Advance(float time); + } +} diff --git a/Assets/Scripts/UI/Gears/IAnimationGear.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IAnimationGear.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/IAnimationGear.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IAnimationGear.cs.meta diff --git a/Assets/Scripts/UI/Gears/IColorGear.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IColorGear.cs similarity index 94% rename from Assets/Scripts/UI/Gears/IColorGear.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IColorGear.cs index 7dce8a82..a3b9f238 100644 --- a/Assets/Scripts/UI/Gears/IColorGear.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IColorGear.cs @@ -1,26 +1,26 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public interface IColorGear - { - /// - /// - /// - Color color { get; set; } - } - - /// - /// - /// - public interface ITextColorGear : IColorGear - { - /// - /// - /// - Color strokeColor { get; set; } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public interface IColorGear + { + /// + /// + /// + Color color { get; set; } + } + + /// + /// + /// + public interface ITextColorGear : IColorGear + { + /// + /// + /// + Color strokeColor { get; set; } + } +} diff --git a/Assets/Scripts/UI/Gears/IColorGear.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IColorGear.cs.meta similarity index 100% rename from Assets/Scripts/UI/Gears/IColorGear.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Gears/IColorGear.cs.meta diff --git a/Assets/Scripts/UI/IUISource.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/IUISource.cs similarity index 94% rename from Assets/Scripts/UI/IUISource.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/IUISource.cs index 0f3f4ff7..e6623b28 100644 --- a/Assets/Scripts/UI/IUISource.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/IUISource.cs @@ -1,36 +1,36 @@ - -namespace FairyGUI -{ - /// - /// - /// - public delegate void UILoadCallback(); - - /// - /// - /// - public interface IUISource - { - /// - /// - /// - string fileName { get; set; } - - /// - /// - /// - bool loaded { get; } - - /// - /// - /// - /// - void Load(UILoadCallback callback); - - /// - /// 取消加载 - /// - void Cancel(); - - } -} + +namespace FairyGUI +{ + /// + /// + /// + public delegate void UILoadCallback(); + + /// + /// + /// + public interface IUISource + { + /// + /// + /// + string fileName { get; set; } + + /// + /// + /// + bool loaded { get; } + + /// + /// + /// + /// + void Load(UILoadCallback callback); + + /// + /// 取消加载 + /// + void Cancel(); + + } +} diff --git a/Assets/Scripts/UI/IUISource.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/IUISource.cs.meta similarity index 100% rename from Assets/Scripts/UI/IUISource.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/IUISource.cs.meta diff --git a/Assets/Scripts/UI/Margin.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Margin.cs similarity index 94% rename from Assets/Scripts/UI/Margin.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Margin.cs index 84f987d2..5955172b 100644 --- a/Assets/Scripts/UI/Margin.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Margin.cs @@ -1,29 +1,29 @@ - -namespace FairyGUI -{ - /// - /// - /// - public struct Margin - { - /// - /// - /// - public int left; - - /// - /// - /// - public int right; - - /// - /// - /// - public int top; - - /// - /// - /// - public int bottom; - } -} + +namespace FairyGUI +{ + /// + /// + /// + public struct Margin + { + /// + /// + /// + public int left; + + /// + /// + /// + public int right; + + /// + /// + /// + public int top; + + /// + /// + /// + public int bottom; + } +} diff --git a/Assets/Scripts/UI/Margin.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Margin.cs.meta similarity index 100% rename from Assets/Scripts/UI/Margin.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Margin.cs.meta diff --git a/Assets/Scripts/UI/PackageItem.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PackageItem.cs similarity index 96% rename from Assets/Scripts/UI/PackageItem.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PackageItem.cs index 6a570217..434816d3 100644 --- a/Assets/Scripts/UI/PackageItem.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PackageItem.cs @@ -1,85 +1,85 @@ -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class PackageItem - { - public UIPackage owner; - - public PackageItemType type; - public ObjectType objectType; - - public string id; - public string name; - public int width; - public int height; - public string file; - public bool exported; - public NTexture texture; - public ByteBuffer rawData; - public string[] branches; - public string[] highResolution; - - //image - public Rect? scale9Grid; - public bool scaleByTile; - public int tileGridIndice; - public PixelHitTestData pixelHitTestData; - - //movieclip - public float interval; - public float repeatDelay; - public bool swing; - public MovieClip.Frame[] frames; - - //component - public bool translated; - public UIObjectFactory.GComponentCreator extensionCreator; - - //font - public BitmapFont bitmapFont; - - //sound - public NAudioClip audioClip; - - //spine/dragonbones - public Vector2 skeletonAnchor; - public object skeletonAsset; - - public object Load() - { - return owner.GetItemAsset(this); - } - - public PackageItem getBranch() - { - if (branches != null && owner._branchIndex != -1) - { - string itemId = branches[owner._branchIndex]; - if (itemId != null) - return owner.GetItem(itemId); - } - - return this; - } - - public PackageItem getHighResolution() - { - if (highResolution != null && GRoot.contentScaleLevel > 0) - { - int i = GRoot.contentScaleLevel - 1; - if (i >= highResolution.Length) - i = highResolution.Length - 1; - string itemId = highResolution[i]; - if (itemId != null) - return owner.GetItem(itemId); - } - - return this; - } - } -} +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class PackageItem + { + public UIPackage owner; + + public PackageItemType type; + public ObjectType objectType; + + public string id; + public string name; + public int width; + public int height; + public string file; + public bool exported; + public NTexture texture; + public ByteBuffer rawData; + public string[] branches; + public string[] highResolution; + + //image + public Rect? scale9Grid; + public bool scaleByTile; + public int tileGridIndice; + public PixelHitTestData pixelHitTestData; + + //movieclip + public float interval; + public float repeatDelay; + public bool swing; + public MovieClip.Frame[] frames; + + //component + public bool translated; + public UIObjectFactory.GComponentCreator extensionCreator; + + //font + public BitmapFont bitmapFont; + + //sound + public NAudioClip audioClip; + + //spine/dragonbones + public Vector2 skeletonAnchor; + public object skeletonAsset; + + public object Load() + { + return owner.GetItemAsset(this); + } + + public PackageItem getBranch() + { + if (branches != null && owner._branchIndex != -1) + { + string itemId = branches[owner._branchIndex]; + if (itemId != null) + return owner.GetItem(itemId); + } + + return this; + } + + public PackageItem getHighResolution() + { + if (highResolution != null && GRoot.contentScaleLevel > 0) + { + int i = GRoot.contentScaleLevel - 1; + if (i >= highResolution.Length) + i = highResolution.Length - 1; + string itemId = highResolution[i]; + if (itemId != null) + return owner.GetItem(itemId); + } + + return this; + } + } +} diff --git a/Assets/Scripts/UI/PackageItem.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PackageItem.cs.meta similarity index 100% rename from Assets/Scripts/UI/PackageItem.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PackageItem.cs.meta diff --git a/Assets/Scripts/UI/PopupMenu.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PopupMenu.cs similarity index 96% rename from Assets/Scripts/UI/PopupMenu.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PopupMenu.cs index 62a95824..f349860b 100644 --- a/Assets/Scripts/UI/PopupMenu.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PopupMenu.cs @@ -1,565 +1,565 @@ -using System; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public class PopupMenu : EventDispatcher - { - protected GComponent _contentPane; - protected GList _list; - protected GObject _expandingItem; - - PopupMenu _parentMenu; - TimerCallback _showSubMenu; - TimerCallback _closeSubMenu; - EventListener _onPopup; - EventListener _onClose; - - public int visibleItemCount; - public bool hideOnClickItem; - public bool autoSize; - - const string EVENT_TYPE = "PopupMenuItemClick"; - - public PopupMenu() - { - Create(null); - } - - /// - /// - /// - /// - public PopupMenu(string resourceURL) - { - Create(resourceURL); - } - - public EventListener onPopup - { - get { return _onPopup ?? (_onPopup = new EventListener(this, "onPopup")); } - } - - public EventListener onClose - { - get { return _onClose ?? (_onClose = new EventListener(this, "onClose")); } - } - - void Create(string resourceURL) - { - if (resourceURL == null) - { - resourceURL = UIConfig.popupMenu; - if (resourceURL == null) - { - Debug.LogError("FairyGUI: UIConfig.popupMenu not defined"); - return; - } - } - - _contentPane = UIPackage.CreateObjectFromURL(resourceURL).asCom; - _contentPane.onAddedToStage.Add(__addedToStage); - _contentPane.onRemovedFromStage.Add(__removeFromStage); - _contentPane.focusable = false; - - _list = _contentPane.GetChild("list").asList; - _list.RemoveChildrenToPool(); - - _list.AddRelation(_contentPane, RelationType.Width); - _list.RemoveRelation(_contentPane, RelationType.Height); - _contentPane.AddRelation(_list, RelationType.Height); - - _list.onClickItem.Add(__clickItem); - - hideOnClickItem = true; - _showSubMenu = __showSubMenu; - _closeSubMenu = CloseSubMenu; - } - - /// - /// - /// - /// - /// - /// - public GButton AddItem(string caption, EventCallback0 callback) - { - GButton item = CreateItem(caption, callback); - _list.AddChild(item); - - return item; - } - - /// - /// - /// - /// - /// - /// - public GButton AddItem(string caption, EventCallback1 callback) - { - GButton item = CreateItem(caption, callback); - _list.AddChild(item); - - return item; - } - - /// - /// - /// - /// - /// - /// - /// - public GButton AddItemAt(string caption, int index, EventCallback1 callback) - { - GButton item = CreateItem(caption, callback); - _list.AddChildAt(item, index); - - return item; - } - - /// - /// - /// - /// - /// - /// - /// - public GButton AddItemAt(string caption, int index, EventCallback0 callback) - { - GButton item = CreateItem(caption, callback); - _list.AddChildAt(item, index); - - return item; - } - - GButton CreateItem(string caption, Delegate callback) - { - GButton item = _list.GetFromPool(_list.defaultItem).asButton; - item.title = caption; - item.grayed = false; - Controller c = item.GetController("checked"); - if (c != null) - c.selectedIndex = 0; - item.RemoveEventListeners(EVENT_TYPE); - if (callback is EventCallback0) - item.AddEventListener(EVENT_TYPE, (EventCallback0)callback); - else - item.AddEventListener(EVENT_TYPE, (EventCallback1)callback); - - item.onRollOver.Add(__rollOver); - item.onRollOut.Add(__rollOut); - - return item; - } - - /// - /// - /// - public void AddSeperator() - { - AddSeperator(-1); - } - - /// - /// - /// - public void AddSeperator(int index) - { - if (UIConfig.popupMenu_seperator == null) - { - Debug.LogError("FairyGUI: UIConfig.popupMenu_seperator not defined"); - return; - } - - if (index == -1) - _list.AddItemFromPool(UIConfig.popupMenu_seperator); - else - { - GObject item = _list.GetFromPool(UIConfig.popupMenu_seperator); - _list.AddChildAt(item, index); - } - } - - /// - /// - /// - /// - /// - public string GetItemName(int index) - { - GButton item = _list.GetChildAt(index).asButton; - return item.name; - } - - /// - /// - /// - /// - /// - public void SetItemText(string name, string caption) - { - GButton item = _list.GetChild(name).asButton; - item.title = caption; - } - - /// - /// - /// - /// - /// - public void SetItemVisible(string name, bool visible) - { - GButton item = _list.GetChild(name).asButton; - if (item.visible != visible) - { - item.visible = visible; - _list.SetBoundsChangedFlag(); - } - } - - /// - /// - /// - /// - /// - public void SetItemGrayed(string name, bool grayed) - { - GButton item = _list.GetChild(name).asButton; - item.grayed = grayed; - } - - /// - /// - /// - /// - /// - public void SetItemCheckable(string name, bool checkable) - { - GButton item = _list.GetChild(name).asButton; - Controller c = item.GetController("checked"); - if (c != null) - { - if (checkable) - { - if (c.selectedIndex == 0) - c.selectedIndex = 1; - } - else - c.selectedIndex = 0; - } - } - - /// - /// - /// - /// - /// - public void SetItemChecked(string name, bool check) - { - GButton item = _list.GetChild(name).asButton; - Controller c = item.GetController("checked"); - if (c != null) - c.selectedIndex = check ? 2 : 1; - } - - [Obsolete("Use IsItemChecked instead")] - public bool isItemChecked(string name) - { - return IsItemChecked(name); - } - - /// - /// - /// - /// - /// - public bool IsItemChecked(string name) - { - GButton item = _list.GetChild(name).asButton; - Controller c = item.GetController("checked"); - if (c != null) - return c.selectedIndex == 2; - else - return false; - } - - /// - /// - /// - /// - public void RemoveItem(string name) - { - GComponent item = _list.GetChild(name).asCom; - if (item != null) - { - item.RemoveEventListeners(EVENT_TYPE); - if (item.data is PopupMenu) - { - ((PopupMenu)item.data).Dispose(); - item.data = null; - } - int index = _list.GetChildIndex(item); - _list.RemoveChildToPoolAt(index); - } - } - - /// - /// - /// - public void ClearItems() - { - _list.RemoveChildrenToPool(); - } - - /// - /// - /// - public int itemCount - { - get { return _list.numChildren; } - } - - /// - /// - /// - public GComponent contentPane - { - get { return _contentPane; } - } - - /// - /// - /// - public GList list - { - get { return _list; } - } - - public void Dispose() - { - int cnt = _list.numChildren; - for (int i = 0; i < cnt; i++) - { - GObject obj = _list.GetChildAt(i); - if (obj.data is PopupMenu) - ((PopupMenu)obj.data).Dispose(); - } - _contentPane.Dispose(); - } - - /// - /// - /// - public void Show() - { - Show(null, PopupDirection.Auto); - } - - /// - /// - /// - /// - public void Show(GObject target) - { - Show(target, PopupDirection.Auto, null); - } - - [Obsolete] - public void Show(GObject target, object downward) - { - Show(target, downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), null); - } - - /// - /// - /// - /// - /// - public void Show(GObject target, PopupDirection dir) - { - Show(target, PopupDirection.Auto, null); - } - - /// - /// - /// - /// - /// - /// - public void Show(GObject target, PopupDirection dir, PopupMenu parentMenu) - { - GRoot r = target != null ? target.root : GRoot.inst; - r.ShowPopup(this.contentPane, (target is GRoot) ? null : target, dir); - _parentMenu = parentMenu; - } - - public void Hide() - { - if (contentPane.parent != null) - ((GRoot)contentPane.parent).HidePopup(contentPane); - } - - void ShowSubMenu(GObject item) - { - _expandingItem = item; - - PopupMenu popup = item.data as PopupMenu; - if (item is GButton) - ((GButton)item).selected = true; - popup.Show(item, PopupDirection.Auto, this); - - Vector2 pt = contentPane.LocalToRoot(new Vector2(item.x + item.width - 5, item.y - 5), item.root); - popup.contentPane.position = pt; - } - - void CloseSubMenu(object param) - { - if (contentPane.isDisposed) - return; - - if (_expandingItem == null) - return; - - if (_expandingItem is GButton) - ((GButton)_expandingItem).selected = false; - PopupMenu popup = (PopupMenu)_expandingItem.data; - if (popup == null) - return; - - _expandingItem = null; - popup.Hide(); - } - - private void __clickItem(EventContext context) - { - GButton item = ((GObject)context.data).asButton; - if (item == null) - return; - - if (item.grayed) - { - _list.selectedIndex = -1; - return; - } - - Controller c = item.GetController("checked"); - if (c != null && c.selectedIndex != 0) - { - if (c.selectedIndex == 1) - c.selectedIndex = 2; - else - c.selectedIndex = 1; - } - - if (hideOnClickItem) - { - if (_parentMenu != null) - _parentMenu.Hide(); - Hide(); - } - - item.DispatchEvent(EVENT_TYPE, item); //event data is for backward compatibility - } - - void __addedToStage() - { - DispatchEvent("onPopup", null); - - if (autoSize) - { - _list.EnsureBoundsCorrect(); - int cnt = _list.numChildren; - float maxDelta = -1000; - for (int i = 0; i < cnt; i++) - { - GButton obj = _list.GetChildAt(i).asButton; - if (obj == null) - continue; - GTextField tf = obj.GetTextField(); - if (tf != null) - { - float v = tf.textWidth - tf.width; - if (v > maxDelta) - maxDelta = v; - } - } - - if (contentPane.width + maxDelta > contentPane.initWidth) - contentPane.width += maxDelta; - else - contentPane.width = contentPane.initWidth; - } - - _list.selectedIndex = -1; - _list.ResizeToFit(visibleItemCount > 0 ? visibleItemCount : int.MaxValue, 10); - } - - void __removeFromStage() - { - _parentMenu = null; - - if (_expandingItem != null) - Timers.inst.Add(0, 1, _closeSubMenu); - - DispatchEvent("onClose", null); - } - - void __rollOver(EventContext context) - { - GObject item = (GObject)context.sender; - if ((item.data is PopupMenu) || _expandingItem != null) - { - Timers.inst.Add(0.1f, 1, _showSubMenu, item); - } - } - - void __showSubMenu(object param) - { - if (contentPane.isDisposed) - return; - - GObject item = (GObject)param; - GRoot r = contentPane.root; - if (r == null) - return; - - if (_expandingItem != null) - { - if (_expandingItem == item) - return; - - CloseSubMenu(null); - } - - PopupMenu popup = item.data as PopupMenu; - if (popup == null) - return; - - ShowSubMenu(item); - } - - void __rollOut(EventContext context) - { - if (_expandingItem == null) - return; - - Timers.inst.Remove(_showSubMenu); - - GRoot r = contentPane.root; - if (r != null) - { - PopupMenu popup = (PopupMenu)_expandingItem.data; - Vector2 pt = popup.contentPane.GlobalToLocal(context.inputEvent.position); - if (pt.x >= 0 && pt.y >= 0 && pt.x < popup.contentPane.width && pt.y < popup.contentPane.height) - return; - } - - CloseSubMenu(null); - } - } -} +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public class PopupMenu : EventDispatcher + { + protected GComponent _contentPane; + protected GList _list; + protected GObject _expandingItem; + + PopupMenu _parentMenu; + TimerCallback _showSubMenu; + TimerCallback _closeSubMenu; + EventListener _onPopup; + EventListener _onClose; + + public int visibleItemCount; + public bool hideOnClickItem; + public bool autoSize; + + const string EVENT_TYPE = "PopupMenuItemClick"; + + public PopupMenu() + { + Create(null); + } + + /// + /// + /// + /// + public PopupMenu(string resourceURL) + { + Create(resourceURL); + } + + public EventListener onPopup + { + get { return _onPopup ?? (_onPopup = new EventListener(this, "onPopup")); } + } + + public EventListener onClose + { + get { return _onClose ?? (_onClose = new EventListener(this, "onClose")); } + } + + void Create(string resourceURL) + { + if (resourceURL == null) + { + resourceURL = UIConfig.popupMenu; + if (resourceURL == null) + { + Debug.LogError("FairyGUI: UIConfig.popupMenu not defined"); + return; + } + } + + _contentPane = UIPackage.CreateObjectFromURL(resourceURL).asCom; + _contentPane.onAddedToStage.Add(__addedToStage); + _contentPane.onRemovedFromStage.Add(__removeFromStage); + _contentPane.focusable = false; + + _list = _contentPane.GetChild("list").asList; + _list.RemoveChildrenToPool(); + + _list.AddRelation(_contentPane, RelationType.Width); + _list.RemoveRelation(_contentPane, RelationType.Height); + _contentPane.AddRelation(_list, RelationType.Height); + + _list.onClickItem.Add(__clickItem); + + hideOnClickItem = true; + _showSubMenu = __showSubMenu; + _closeSubMenu = CloseSubMenu; + } + + /// + /// + /// + /// + /// + /// + public GButton AddItem(string caption, EventCallback0 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChild(item); + + return item; + } + + /// + /// + /// + /// + /// + /// + public GButton AddItem(string caption, EventCallback1 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChild(item); + + return item; + } + + /// + /// + /// + /// + /// + /// + /// + public GButton AddItemAt(string caption, int index, EventCallback1 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChildAt(item, index); + + return item; + } + + /// + /// + /// + /// + /// + /// + /// + public GButton AddItemAt(string caption, int index, EventCallback0 callback) + { + GButton item = CreateItem(caption, callback); + _list.AddChildAt(item, index); + + return item; + } + + GButton CreateItem(string caption, Delegate callback) + { + GButton item = _list.GetFromPool(_list.defaultItem).asButton; + item.title = caption; + item.grayed = false; + Controller c = item.GetController("checked"); + if (c != null) + c.selectedIndex = 0; + item.RemoveEventListeners(EVENT_TYPE); + if (callback is EventCallback0) + item.AddEventListener(EVENT_TYPE, (EventCallback0)callback); + else + item.AddEventListener(EVENT_TYPE, (EventCallback1)callback); + + item.onRollOver.Add(__rollOver); + item.onRollOut.Add(__rollOut); + + return item; + } + + /// + /// + /// + public void AddSeperator() + { + AddSeperator(-1); + } + + /// + /// + /// + public void AddSeperator(int index) + { + if (UIConfig.popupMenu_seperator == null) + { + Debug.LogError("FairyGUI: UIConfig.popupMenu_seperator not defined"); + return; + } + + if (index == -1) + _list.AddItemFromPool(UIConfig.popupMenu_seperator); + else + { + GObject item = _list.GetFromPool(UIConfig.popupMenu_seperator); + _list.AddChildAt(item, index); + } + } + + /// + /// + /// + /// + /// + public string GetItemName(int index) + { + GButton item = _list.GetChildAt(index).asButton; + return item.name; + } + + /// + /// + /// + /// + /// + public void SetItemText(string name, string caption) + { + GButton item = _list.GetChild(name).asButton; + item.title = caption; + } + + /// + /// + /// + /// + /// + public void SetItemVisible(string name, bool visible) + { + GButton item = _list.GetChild(name).asButton; + if (item.visible != visible) + { + item.visible = visible; + _list.SetBoundsChangedFlag(); + } + } + + /// + /// + /// + /// + /// + public void SetItemGrayed(string name, bool grayed) + { + GButton item = _list.GetChild(name).asButton; + item.grayed = grayed; + } + + /// + /// + /// + /// + /// + public void SetItemCheckable(string name, bool checkable) + { + GButton item = _list.GetChild(name).asButton; + Controller c = item.GetController("checked"); + if (c != null) + { + if (checkable) + { + if (c.selectedIndex == 0) + c.selectedIndex = 1; + } + else + c.selectedIndex = 0; + } + } + + /// + /// + /// + /// + /// + public void SetItemChecked(string name, bool check) + { + GButton item = _list.GetChild(name).asButton; + Controller c = item.GetController("checked"); + if (c != null) + c.selectedIndex = check ? 2 : 1; + } + + [Obsolete("Use IsItemChecked instead")] + public bool isItemChecked(string name) + { + return IsItemChecked(name); + } + + /// + /// + /// + /// + /// + public bool IsItemChecked(string name) + { + GButton item = _list.GetChild(name).asButton; + Controller c = item.GetController("checked"); + if (c != null) + return c.selectedIndex == 2; + else + return false; + } + + /// + /// + /// + /// + public void RemoveItem(string name) + { + GComponent item = _list.GetChild(name).asCom; + if (item != null) + { + item.RemoveEventListeners(EVENT_TYPE); + if (item.data is PopupMenu) + { + ((PopupMenu)item.data).Dispose(); + item.data = null; + } + int index = _list.GetChildIndex(item); + _list.RemoveChildToPoolAt(index); + } + } + + /// + /// + /// + public void ClearItems() + { + _list.RemoveChildrenToPool(); + } + + /// + /// + /// + public int itemCount + { + get { return _list.numChildren; } + } + + /// + /// + /// + public GComponent contentPane + { + get { return _contentPane; } + } + + /// + /// + /// + public GList list + { + get { return _list; } + } + + public void Dispose() + { + int cnt = _list.numChildren; + for (int i = 0; i < cnt; i++) + { + GObject obj = _list.GetChildAt(i); + if (obj.data is PopupMenu) + ((PopupMenu)obj.data).Dispose(); + } + _contentPane.Dispose(); + } + + /// + /// + /// + public void Show() + { + Show(null, PopupDirection.Auto); + } + + /// + /// + /// + /// + public void Show(GObject target) + { + Show(target, PopupDirection.Auto, null); + } + + [Obsolete] + public void Show(GObject target, object downward) + { + Show(target, downward == null ? PopupDirection.Auto : ((bool)downward == true ? PopupDirection.Down : PopupDirection.Up), null); + } + + /// + /// + /// + /// + /// + public void Show(GObject target, PopupDirection dir) + { + Show(target, PopupDirection.Auto, null); + } + + /// + /// + /// + /// + /// + /// + public void Show(GObject target, PopupDirection dir, PopupMenu parentMenu) + { + GRoot r = target != null ? target.root : GRoot.inst; + r.ShowPopup(this.contentPane, (target is GRoot) ? null : target, dir); + _parentMenu = parentMenu; + } + + public void Hide() + { + if (contentPane.parent != null) + ((GRoot)contentPane.parent).HidePopup(contentPane); + } + + void ShowSubMenu(GObject item) + { + _expandingItem = item; + + PopupMenu popup = item.data as PopupMenu; + if (item is GButton) + ((GButton)item).selected = true; + popup.Show(item, PopupDirection.Auto, this); + + Vector2 pt = contentPane.LocalToRoot(new Vector2(item.x + item.width - 5, item.y - 5), item.root); + popup.contentPane.position = pt; + } + + void CloseSubMenu(object param) + { + if (contentPane.isDisposed) + return; + + if (_expandingItem == null) + return; + + if (_expandingItem is GButton) + ((GButton)_expandingItem).selected = false; + PopupMenu popup = (PopupMenu)_expandingItem.data; + if (popup == null) + return; + + _expandingItem = null; + popup.Hide(); + } + + private void __clickItem(EventContext context) + { + GButton item = ((GObject)context.data).asButton; + if (item == null) + return; + + if (item.grayed) + { + _list.selectedIndex = -1; + return; + } + + Controller c = item.GetController("checked"); + if (c != null && c.selectedIndex != 0) + { + if (c.selectedIndex == 1) + c.selectedIndex = 2; + else + c.selectedIndex = 1; + } + + if (hideOnClickItem) + { + if (_parentMenu != null) + _parentMenu.Hide(); + Hide(); + } + + item.DispatchEvent(EVENT_TYPE, item); //event data is for backward compatibility + } + + void __addedToStage() + { + DispatchEvent("onPopup", null); + + if (autoSize) + { + _list.EnsureBoundsCorrect(); + int cnt = _list.numChildren; + float maxDelta = -1000; + for (int i = 0; i < cnt; i++) + { + GButton obj = _list.GetChildAt(i).asButton; + if (obj == null) + continue; + GTextField tf = obj.GetTextField(); + if (tf != null) + { + float v = tf.textWidth - tf.width; + if (v > maxDelta) + maxDelta = v; + } + } + + if (contentPane.width + maxDelta > contentPane.initWidth) + contentPane.width += maxDelta; + else + contentPane.width = contentPane.initWidth; + } + + _list.selectedIndex = -1; + _list.ResizeToFit(visibleItemCount > 0 ? visibleItemCount : int.MaxValue, 10); + } + + void __removeFromStage() + { + _parentMenu = null; + + if (_expandingItem != null) + Timers.inst.Add(0, 1, _closeSubMenu); + + DispatchEvent("onClose", null); + } + + void __rollOver(EventContext context) + { + GObject item = (GObject)context.sender; + if ((item.data is PopupMenu) || _expandingItem != null) + { + Timers.inst.Add(0.1f, 1, _showSubMenu, item); + } + } + + void __showSubMenu(object param) + { + if (contentPane.isDisposed) + return; + + GObject item = (GObject)param; + GRoot r = contentPane.root; + if (r == null) + return; + + if (_expandingItem != null) + { + if (_expandingItem == item) + return; + + CloseSubMenu(null); + } + + PopupMenu popup = item.data as PopupMenu; + if (popup == null) + return; + + ShowSubMenu(item); + } + + void __rollOut(EventContext context) + { + if (_expandingItem == null) + return; + + Timers.inst.Remove(_showSubMenu); + + GRoot r = contentPane.root; + if (r != null) + { + PopupMenu popup = (PopupMenu)_expandingItem.data; + Vector2 pt = popup.contentPane.GlobalToLocal(context.inputEvent.position); + if (pt.x >= 0 && pt.y >= 0 && pt.x < popup.contentPane.width && pt.y < popup.contentPane.height) + return; + } + + CloseSubMenu(null); + } + } +} diff --git a/Assets/Scripts/UI/PopupMenu.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PopupMenu.cs.meta similarity index 100% rename from Assets/Scripts/UI/PopupMenu.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/PopupMenu.cs.meta diff --git a/Assets/Scripts/UI/RelationItem.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/RelationItem.cs similarity index 97% rename from Assets/Scripts/UI/RelationItem.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/RelationItem.cs index 40f03194..62133ad6 100644 --- a/Assets/Scripts/UI/RelationItem.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/RelationItem.cs @@ -1,672 +1,672 @@ -using System.Collections.Generic; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - class RelationDef - { - public bool percent; - public RelationType type; - public int axis; - - public void copyFrom(RelationDef source) - { - this.percent = source.percent; - this.type = source.type; - this.axis = source.axis; - } - } - - class RelationItem - { - GObject _owner; - GObject _target; - List _defs; - Vector4 _targetData; - - public RelationItem(GObject owner) - { - _owner = owner; - _defs = new List(); - } - - public GObject target - { - get { return _target; } - set - { - if (_target != value) - { - if (_target != null) - ReleaseRefTarget(_target); - _target = value; - if (_target != null) - AddRefTarget(_target); - } - } - } - - public void Add(RelationType relationType, bool usePercent) - { - if (relationType == RelationType.Size) - { - Add(RelationType.Width, usePercent); - Add(RelationType.Height, usePercent); - return; - } - - int dc = _defs.Count; - for (int k = 0; k < dc; k++) - { - if (_defs[k].type == relationType) - return; - } - - InternalAdd(relationType, usePercent); - } - - public void InternalAdd(RelationType relationType, bool usePercent) - { - if (relationType == RelationType.Size) - { - InternalAdd(RelationType.Width, usePercent); - InternalAdd(RelationType.Height, usePercent); - return; - } - - RelationDef info = new RelationDef(); - info.percent = usePercent; - info.type = relationType; - info.axis = (relationType <= RelationType.Right_Right || relationType == RelationType.Width || relationType >= RelationType.LeftExt_Left && relationType <= RelationType.RightExt_Right) ? 0 : 1; - _defs.Add(info); - } - - public void Remove(RelationType relationType) - { - if (relationType == RelationType.Size) - { - Remove(RelationType.Width); - Remove(RelationType.Height); - return; - } - - int dc = _defs.Count; - for (int k = 0; k < dc; k++) - { - if (_defs[k].type == relationType) - { - _defs.RemoveAt(k); - break; - } - } - } - - public void CopyFrom(RelationItem source) - { - this.target = source.target; - - _defs.Clear(); - foreach (RelationDef info in source._defs) - { - RelationDef info2 = new RelationDef(); - info2.copyFrom(info); - _defs.Add(info2); - } - } - - public void Dispose() - { - if (_target != null) - { - ReleaseRefTarget(_target); - _target = null; - } - } - - public bool isEmpty - { - get { return _defs.Count == 0; } - } - - public void ApplyOnSelfSizeChanged(float dWidth, float dHeight, bool applyPivot) - { - int cnt = _defs.Count; - if (cnt == 0) - return; - - float ox = _owner.x; - float oy = _owner.y; - - for (int i = 0; i < cnt; i++) - { - RelationDef info = _defs[i]; - switch (info.type) - { - case RelationType.Center_Center: - _owner.x -= (0.5f - (applyPivot ? _owner.pivotX : 0)) * dWidth; - break; - - case RelationType.Right_Center: - case RelationType.Right_Left: - case RelationType.Right_Right: - _owner.x -= (1 - (applyPivot ? _owner.pivotX : 0)) * dWidth; - break; - - case RelationType.Middle_Middle: - _owner.y -= (0.5f - (applyPivot ? _owner.pivotY : 0)) * dHeight; - break; - - case RelationType.Bottom_Middle: - case RelationType.Bottom_Top: - case RelationType.Bottom_Bottom: - _owner.y -= (1 - (applyPivot ? _owner.pivotY : 0)) * dHeight; - break; - } - } - - if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) - { - ox = _owner.x - ox; - oy = _owner.y - oy; - - _owner.UpdateGearFromRelations(1, ox, oy); - - if (_owner.parent != null) - { - int transCount = _owner.parent._transitions.Count; - for (int i = 0; i < transCount; i++) - _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); - } - } - } - - void ApplyOnXYChanged(RelationDef info, float dx, float dy) - { - float tmp; - switch (info.type) - { - case RelationType.Left_Left: - case RelationType.Left_Center: - case RelationType.Left_Right: - case RelationType.Center_Center: - case RelationType.Right_Left: - case RelationType.Right_Center: - case RelationType.Right_Right: - _owner.x += dx; - break; - - case RelationType.Top_Top: - case RelationType.Top_Middle: - case RelationType.Top_Bottom: - case RelationType.Middle_Middle: - case RelationType.Bottom_Top: - case RelationType.Bottom_Middle: - case RelationType.Bottom_Bottom: - _owner.y += dy; - break; - - case RelationType.Width: - case RelationType.Height: - break; - - case RelationType.LeftExt_Left: - case RelationType.LeftExt_Right: - if (_owner != _target.parent) - { - tmp = _owner.xMin; - _owner.width = _owner._rawWidth - dx; - _owner.xMin = tmp + dx; - } - else - _owner.width = _owner._rawWidth - dx; - break; - - case RelationType.RightExt_Left: - case RelationType.RightExt_Right: - if (_owner != _target.parent) - { - tmp = _owner.xMin; - _owner.width = _owner._rawWidth + dx; - _owner.xMin = tmp; - } - else - _owner.width = _owner._rawWidth + dx; - break; - - case RelationType.TopExt_Top: - case RelationType.TopExt_Bottom: - if (_owner != _target.parent) - { - tmp = _owner.yMin; - _owner.height = _owner._rawHeight - dy; - _owner.yMin = tmp + dy; - } - else - _owner.height = _owner._rawHeight - dy; - break; - - case RelationType.BottomExt_Top: - case RelationType.BottomExt_Bottom: - if (_owner != _target.parent) - { - tmp = _owner.yMin; - _owner.height = _owner._rawHeight + dy; - _owner.yMin = tmp; - } - else - _owner.height = _owner._rawHeight + dy; - break; - } - } - - void ApplyOnSizeChanged(RelationDef info) - { - float pos = 0, pivot = 0, delta = 0; - if (info.axis == 0) - { - if (_target != _owner.parent) - { - pos = _target.x; - if (_target.pivotAsAnchor) - pivot = _target.pivotX; - } - - if (info.percent) - { - if (_targetData.z != 0) - delta = _target._width / _targetData.z; - } - else - delta = _target._width - _targetData.z; - } - else - { - if (_target != _owner.parent) - { - pos = _target.y; - if (_target.pivotAsAnchor) - pivot = _target.pivotY; - } - - if (info.percent) - { - if (_targetData.w != 0) - delta = _target._height / _targetData.w; - } - else - delta = _target._height - _targetData.w; - } - - float v, tmp; - - switch (info.type) - { - case RelationType.Left_Left: - if (info.percent) - _owner.xMin = pos + (_owner.xMin - pos) * delta; - else if (pivot != 0) - _owner.x += delta * (-pivot); - break; - case RelationType.Left_Center: - if (info.percent) - _owner.xMin = pos + (_owner.xMin - pos) * delta; - else - _owner.x += delta * (0.5f - pivot); - break; - case RelationType.Left_Right: - if (info.percent) - _owner.xMin = pos + (_owner.xMin - pos) * delta; - else - _owner.x += delta * (1 - pivot); - break; - case RelationType.Center_Center: - if (info.percent) - _owner.xMin = pos + (_owner.xMin + _owner._rawWidth * 0.5f - pos) * delta - _owner._rawWidth * 0.5f; - else - _owner.x += delta * (0.5f - pivot); - break; - case RelationType.Right_Left: - if (info.percent) - _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; - else if (pivot != 0) - _owner.x += delta * (-pivot); - break; - case RelationType.Right_Center: - if (info.percent) - _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; - else - _owner.x += delta * (0.5f - pivot); - break; - case RelationType.Right_Right: - if (info.percent) - _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; - else - _owner.x += delta * (1 - pivot); - break; - - case RelationType.Top_Top: - if (info.percent) - _owner.yMin = pos + (_owner.yMin - pos) * delta; - else if (pivot != 0) - _owner.y += delta * (-pivot); - break; - case RelationType.Top_Middle: - if (info.percent) - _owner.yMin = pos + (_owner.yMin - pos) * delta; - else - _owner.y += delta * (0.5f - pivot); - break; - case RelationType.Top_Bottom: - if (info.percent) - _owner.yMin = pos + (_owner.yMin - pos) * delta; - else - _owner.y += delta * (1 - pivot); - break; - case RelationType.Middle_Middle: - if (info.percent) - _owner.yMin = pos + (_owner.yMin + _owner._rawHeight * 0.5f - pos) * delta - _owner._rawHeight * 0.5f; - else - _owner.y += delta * (0.5f - pivot); - break; - case RelationType.Bottom_Top: - if (info.percent) - _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; - else if (pivot != 0) - _owner.y += delta * (-pivot); - break; - case RelationType.Bottom_Middle: - if (info.percent) - _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; - else - _owner.y += delta * (0.5f - pivot); - break; - case RelationType.Bottom_Bottom: - if (info.percent) - _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; - else - _owner.y += delta * (1 - pivot); - break; - - case RelationType.Width: - if (_owner.underConstruct && _owner == _target.parent) - v = _owner.sourceWidth - _target.initWidth; - else - v = _owner._rawWidth - _targetData.z; - if (info.percent) - v = v * delta; - if (_target == _owner.parent) - { - if (_owner.pivotAsAnchor) - { - tmp = _owner.xMin; - _owner.SetSize(_target._width + v, _owner._rawHeight, true); - _owner.xMin = tmp; - } - else - _owner.SetSize(_target._width + v, _owner._rawHeight, true); - } - else - _owner.width = _target._width + v; - break; - case RelationType.Height: - if (_owner.underConstruct && _owner == _target.parent) - v = _owner.sourceHeight - _target.initHeight; - else - v = _owner._rawHeight - _targetData.w; - if (info.percent) - v = v * delta; - if (_target == _owner.parent) - { - if (_owner.pivotAsAnchor) - { - tmp = _owner.yMin; - _owner.SetSize(_owner._rawWidth, _target._height + v, true); - _owner.yMin = tmp; - } - else - _owner.SetSize(_owner._rawWidth, _target._height + v, true); - } - else - _owner.height = _target._height + v; - break; - - case RelationType.LeftExt_Left: - tmp = _owner.xMin; - if (info.percent) - v = pos + (tmp - pos) * delta - tmp; - else - v = delta * (-pivot); - _owner.width = _owner._rawWidth - v; - _owner.xMin = tmp + v; - break; - case RelationType.LeftExt_Right: - tmp = _owner.xMin; - if (info.percent) - v = pos + (tmp - pos) * delta - tmp; - else - v = delta * (1 - pivot); - _owner.width = _owner._rawWidth - v; - _owner.xMin = tmp + v; - break; - case RelationType.RightExt_Left: - tmp = _owner.xMin; - if (info.percent) - v = pos + (tmp + _owner._rawWidth - pos) * delta - (tmp + _owner._rawWidth); - else - v = delta * (-pivot); - _owner.width = _owner._rawWidth + v; - _owner.xMin = tmp; - break; - case RelationType.RightExt_Right: - tmp = _owner.xMin; - if (info.percent) - { - if (_owner == _target.parent) - { - if (_owner.underConstruct) - _owner.width = pos + _target._width - _target._width * pivot + - (_owner.sourceWidth - pos - _target.initWidth + _target.initWidth * pivot) * delta; - else - _owner.width = pos + (_owner._rawWidth - pos) * delta; - } - else - { - v = pos + (tmp + _owner._rawWidth - pos) * delta - (tmp + _owner._rawWidth); - _owner.width = _owner._rawWidth + v; - _owner.xMin = tmp; - } - } - else - { - if (_owner == _target.parent) - { - if (_owner.underConstruct) - _owner.width = _owner.sourceWidth + (_target._width - _target.initWidth) * (1 - pivot); - else - _owner.width = _owner._rawWidth + delta * (1 - pivot); - } - else - { - v = delta * (1 - pivot); - _owner.width = _owner._rawWidth + v; - _owner.xMin = tmp; - } - } - break; - case RelationType.TopExt_Top: - tmp = _owner.yMin; - if (info.percent) - v = pos + (tmp - pos) * delta - tmp; - else - v = delta * (-pivot); - _owner.height = _owner._rawHeight - v; - _owner.yMin = tmp + v; - break; - case RelationType.TopExt_Bottom: - tmp = _owner.yMin; - if (info.percent) - v = pos + (tmp - pos) * delta - tmp; - else - v = delta * (1 - pivot); - _owner.height = _owner._rawHeight - v; - _owner.yMin = tmp + v; - break; - case RelationType.BottomExt_Top: - tmp = _owner.yMin; - if (info.percent) - v = pos + (tmp + _owner._rawHeight - pos) * delta - (tmp + _owner._rawHeight); - else - v = delta * (-pivot); - _owner.height = _owner._rawHeight + v; - _owner.yMin = tmp; - break; - case RelationType.BottomExt_Bottom: - tmp = _owner.yMin; - if (info.percent) - { - if (_owner == _target.parent) - { - if (_owner.underConstruct) - _owner.height = pos + _target._height - _target._height * pivot + - (_owner.sourceHeight - pos - _target.initHeight + _target.initHeight * pivot) * delta; - else - _owner.height = pos + (_owner._rawHeight - pos) * delta; - } - else - { - v = pos + (tmp + _owner._rawHeight - pos) * delta - (tmp + _owner._rawHeight); - _owner.height = _owner._rawHeight + v; - _owner.yMin = tmp; - } - } - else - { - if (_owner == _target.parent) - { - if (_owner.underConstruct) - _owner.height = _owner.sourceHeight + (_target._height - _target.initHeight) * (1 - pivot); - else - _owner.height = _owner._rawHeight + delta * (1 - pivot); - } - else - { - v = delta * (1 - pivot); - _owner.height = _owner._rawHeight + v; - _owner.yMin = tmp; - } - } - break; - } - } - - void AddRefTarget(GObject target) - { - if (target != _owner.parent) - target.onPositionChanged.Add(__targetXYChanged); - target.onSizeChanged.Add(__targetSizeChanged); - _targetData.x = _target.x; - _targetData.y = _target.y; - _targetData.z = _target._width; - _targetData.w = _target._height; - } - - void ReleaseRefTarget(GObject target) - { - target.onPositionChanged.Remove(__targetXYChanged); - target.onSizeChanged.Remove(__targetSizeChanged); - } - - void __targetXYChanged(EventContext context) - { - if (_owner.relations.handling != null - || _owner.group != null && _owner.group._updating != 0) - { - _targetData.x = _target.x; - _targetData.y = _target.y; - return; - } - - _owner.relations.handling = (GObject)context.sender; - - float ox = _owner.x; - float oy = _owner.y; - float dx = _target.x - _targetData.x; - float dy = _target.y - _targetData.y; - - int cnt = _defs.Count; - for (int i = 0; i < cnt; i++) - ApplyOnXYChanged(_defs[i], dx, dy); - - _targetData.x = _target.x; - _targetData.y = _target.y; - - if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) - { - ox = _owner.x - ox; - oy = _owner.y - oy; - - _owner.UpdateGearFromRelations(1, ox, oy); - - if (_owner.parent != null) - { - int transCount = _owner.parent._transitions.Count; - for (int i = 0; i < transCount; i++) - _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); - } - } - - _owner.relations.handling = null; - } - - void __targetSizeChanged(EventContext context) - { - if (_owner.relations.handling != null - || _owner.group != null && _owner.group._updating != 0) - { - _targetData.z = _target._width; - _targetData.w = _target._height; - return; - } - - _owner.relations.handling = (GObject)context.sender; - - float ox = _owner.x; - float oy = _owner.y; - float ow = _owner._rawWidth; - float oh = _owner._rawHeight; - - int cnt = _defs.Count; - for (int i = 0; i < cnt; i++) - ApplyOnSizeChanged(_defs[i]); - - _targetData.z = _target._width; - _targetData.w = _target._height; - - if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) - { - ox = _owner.x - ox; - oy = _owner.y - oy; - - _owner.UpdateGearFromRelations(1, ox, oy); - - if (_owner.parent != null) - { - int transCount = _owner.parent._transitions.Count; - for (int i = 0; i < transCount; i++) - _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); - } - } - - if (!Mathf.Approximately(ow, _owner._rawWidth) || !Mathf.Approximately(oh, _owner._rawHeight)) - { - ow = _owner._rawWidth - ow; - oh = _owner._rawHeight - oh; - - _owner.UpdateGearFromRelations(2, ow, oh); - } - - _owner.relations.handling = null; - } - } -} +using System.Collections.Generic; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + class RelationDef + { + public bool percent; + public RelationType type; + public int axis; + + public void copyFrom(RelationDef source) + { + this.percent = source.percent; + this.type = source.type; + this.axis = source.axis; + } + } + + class RelationItem + { + GObject _owner; + GObject _target; + List _defs; + Vector4 _targetData; + + public RelationItem(GObject owner) + { + _owner = owner; + _defs = new List(); + } + + public GObject target + { + get { return _target; } + set + { + if (_target != value) + { + if (_target != null) + ReleaseRefTarget(_target); + _target = value; + if (_target != null) + AddRefTarget(_target); + } + } + } + + public void Add(RelationType relationType, bool usePercent) + { + if (relationType == RelationType.Size) + { + Add(RelationType.Width, usePercent); + Add(RelationType.Height, usePercent); + return; + } + + int dc = _defs.Count; + for (int k = 0; k < dc; k++) + { + if (_defs[k].type == relationType) + return; + } + + InternalAdd(relationType, usePercent); + } + + public void InternalAdd(RelationType relationType, bool usePercent) + { + if (relationType == RelationType.Size) + { + InternalAdd(RelationType.Width, usePercent); + InternalAdd(RelationType.Height, usePercent); + return; + } + + RelationDef info = new RelationDef(); + info.percent = usePercent; + info.type = relationType; + info.axis = (relationType <= RelationType.Right_Right || relationType == RelationType.Width || relationType >= RelationType.LeftExt_Left && relationType <= RelationType.RightExt_Right) ? 0 : 1; + _defs.Add(info); + } + + public void Remove(RelationType relationType) + { + if (relationType == RelationType.Size) + { + Remove(RelationType.Width); + Remove(RelationType.Height); + return; + } + + int dc = _defs.Count; + for (int k = 0; k < dc; k++) + { + if (_defs[k].type == relationType) + { + _defs.RemoveAt(k); + break; + } + } + } + + public void CopyFrom(RelationItem source) + { + this.target = source.target; + + _defs.Clear(); + foreach (RelationDef info in source._defs) + { + RelationDef info2 = new RelationDef(); + info2.copyFrom(info); + _defs.Add(info2); + } + } + + public void Dispose() + { + if (_target != null) + { + ReleaseRefTarget(_target); + _target = null; + } + } + + public bool isEmpty + { + get { return _defs.Count == 0; } + } + + public void ApplyOnSelfSizeChanged(float dWidth, float dHeight, bool applyPivot) + { + int cnt = _defs.Count; + if (cnt == 0) + return; + + float ox = _owner.x; + float oy = _owner.y; + + for (int i = 0; i < cnt; i++) + { + RelationDef info = _defs[i]; + switch (info.type) + { + case RelationType.Center_Center: + _owner.x -= (0.5f - (applyPivot ? _owner.pivotX : 0)) * dWidth; + break; + + case RelationType.Right_Center: + case RelationType.Right_Left: + case RelationType.Right_Right: + _owner.x -= (1 - (applyPivot ? _owner.pivotX : 0)) * dWidth; + break; + + case RelationType.Middle_Middle: + _owner.y -= (0.5f - (applyPivot ? _owner.pivotY : 0)) * dHeight; + break; + + case RelationType.Bottom_Middle: + case RelationType.Bottom_Top: + case RelationType.Bottom_Bottom: + _owner.y -= (1 - (applyPivot ? _owner.pivotY : 0)) * dHeight; + break; + } + } + + if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) + { + ox = _owner.x - ox; + oy = _owner.y - oy; + + _owner.UpdateGearFromRelations(1, ox, oy); + + if (_owner.parent != null) + { + int transCount = _owner.parent._transitions.Count; + for (int i = 0; i < transCount; i++) + _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); + } + } + } + + void ApplyOnXYChanged(RelationDef info, float dx, float dy) + { + float tmp; + switch (info.type) + { + case RelationType.Left_Left: + case RelationType.Left_Center: + case RelationType.Left_Right: + case RelationType.Center_Center: + case RelationType.Right_Left: + case RelationType.Right_Center: + case RelationType.Right_Right: + _owner.x += dx; + break; + + case RelationType.Top_Top: + case RelationType.Top_Middle: + case RelationType.Top_Bottom: + case RelationType.Middle_Middle: + case RelationType.Bottom_Top: + case RelationType.Bottom_Middle: + case RelationType.Bottom_Bottom: + _owner.y += dy; + break; + + case RelationType.Width: + case RelationType.Height: + break; + + case RelationType.LeftExt_Left: + case RelationType.LeftExt_Right: + if (_owner != _target.parent) + { + tmp = _owner.xMin; + _owner.width = _owner._rawWidth - dx; + _owner.xMin = tmp + dx; + } + else + _owner.width = _owner._rawWidth - dx; + break; + + case RelationType.RightExt_Left: + case RelationType.RightExt_Right: + if (_owner != _target.parent) + { + tmp = _owner.xMin; + _owner.width = _owner._rawWidth + dx; + _owner.xMin = tmp; + } + else + _owner.width = _owner._rawWidth + dx; + break; + + case RelationType.TopExt_Top: + case RelationType.TopExt_Bottom: + if (_owner != _target.parent) + { + tmp = _owner.yMin; + _owner.height = _owner._rawHeight - dy; + _owner.yMin = tmp + dy; + } + else + _owner.height = _owner._rawHeight - dy; + break; + + case RelationType.BottomExt_Top: + case RelationType.BottomExt_Bottom: + if (_owner != _target.parent) + { + tmp = _owner.yMin; + _owner.height = _owner._rawHeight + dy; + _owner.yMin = tmp; + } + else + _owner.height = _owner._rawHeight + dy; + break; + } + } + + void ApplyOnSizeChanged(RelationDef info) + { + float pos = 0, pivot = 0, delta = 0; + if (info.axis == 0) + { + if (_target != _owner.parent) + { + pos = _target.x; + if (_target.pivotAsAnchor) + pivot = _target.pivotX; + } + + if (info.percent) + { + if (_targetData.z != 0) + delta = _target._width / _targetData.z; + } + else + delta = _target._width - _targetData.z; + } + else + { + if (_target != _owner.parent) + { + pos = _target.y; + if (_target.pivotAsAnchor) + pivot = _target.pivotY; + } + + if (info.percent) + { + if (_targetData.w != 0) + delta = _target._height / _targetData.w; + } + else + delta = _target._height - _targetData.w; + } + + float v, tmp; + + switch (info.type) + { + case RelationType.Left_Left: + if (info.percent) + _owner.xMin = pos + (_owner.xMin - pos) * delta; + else if (pivot != 0) + _owner.x += delta * (-pivot); + break; + case RelationType.Left_Center: + if (info.percent) + _owner.xMin = pos + (_owner.xMin - pos) * delta; + else + _owner.x += delta * (0.5f - pivot); + break; + case RelationType.Left_Right: + if (info.percent) + _owner.xMin = pos + (_owner.xMin - pos) * delta; + else + _owner.x += delta * (1 - pivot); + break; + case RelationType.Center_Center: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth * 0.5f - pos) * delta - _owner._rawWidth * 0.5f; + else + _owner.x += delta * (0.5f - pivot); + break; + case RelationType.Right_Left: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; + else if (pivot != 0) + _owner.x += delta * (-pivot); + break; + case RelationType.Right_Center: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; + else + _owner.x += delta * (0.5f - pivot); + break; + case RelationType.Right_Right: + if (info.percent) + _owner.xMin = pos + (_owner.xMin + _owner._rawWidth - pos) * delta - _owner._rawWidth; + else + _owner.x += delta * (1 - pivot); + break; + + case RelationType.Top_Top: + if (info.percent) + _owner.yMin = pos + (_owner.yMin - pos) * delta; + else if (pivot != 0) + _owner.y += delta * (-pivot); + break; + case RelationType.Top_Middle: + if (info.percent) + _owner.yMin = pos + (_owner.yMin - pos) * delta; + else + _owner.y += delta * (0.5f - pivot); + break; + case RelationType.Top_Bottom: + if (info.percent) + _owner.yMin = pos + (_owner.yMin - pos) * delta; + else + _owner.y += delta * (1 - pivot); + break; + case RelationType.Middle_Middle: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight * 0.5f - pos) * delta - _owner._rawHeight * 0.5f; + else + _owner.y += delta * (0.5f - pivot); + break; + case RelationType.Bottom_Top: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; + else if (pivot != 0) + _owner.y += delta * (-pivot); + break; + case RelationType.Bottom_Middle: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; + else + _owner.y += delta * (0.5f - pivot); + break; + case RelationType.Bottom_Bottom: + if (info.percent) + _owner.yMin = pos + (_owner.yMin + _owner._rawHeight - pos) * delta - _owner._rawHeight; + else + _owner.y += delta * (1 - pivot); + break; + + case RelationType.Width: + if (_owner.underConstruct && _owner == _target.parent) + v = _owner.sourceWidth - _target.initWidth; + else + v = _owner._rawWidth - _targetData.z; + if (info.percent) + v = v * delta; + if (_target == _owner.parent) + { + if (_owner.pivotAsAnchor) + { + tmp = _owner.xMin; + _owner.SetSize(_target._width + v, _owner._rawHeight, true); + _owner.xMin = tmp; + } + else + _owner.SetSize(_target._width + v, _owner._rawHeight, true); + } + else + _owner.width = _target._width + v; + break; + case RelationType.Height: + if (_owner.underConstruct && _owner == _target.parent) + v = _owner.sourceHeight - _target.initHeight; + else + v = _owner._rawHeight - _targetData.w; + if (info.percent) + v = v * delta; + if (_target == _owner.parent) + { + if (_owner.pivotAsAnchor) + { + tmp = _owner.yMin; + _owner.SetSize(_owner._rawWidth, _target._height + v, true); + _owner.yMin = tmp; + } + else + _owner.SetSize(_owner._rawWidth, _target._height + v, true); + } + else + _owner.height = _target._height + v; + break; + + case RelationType.LeftExt_Left: + tmp = _owner.xMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (-pivot); + _owner.width = _owner._rawWidth - v; + _owner.xMin = tmp + v; + break; + case RelationType.LeftExt_Right: + tmp = _owner.xMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (1 - pivot); + _owner.width = _owner._rawWidth - v; + _owner.xMin = tmp + v; + break; + case RelationType.RightExt_Left: + tmp = _owner.xMin; + if (info.percent) + v = pos + (tmp + _owner._rawWidth - pos) * delta - (tmp + _owner._rawWidth); + else + v = delta * (-pivot); + _owner.width = _owner._rawWidth + v; + _owner.xMin = tmp; + break; + case RelationType.RightExt_Right: + tmp = _owner.xMin; + if (info.percent) + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.width = pos + _target._width - _target._width * pivot + + (_owner.sourceWidth - pos - _target.initWidth + _target.initWidth * pivot) * delta; + else + _owner.width = pos + (_owner._rawWidth - pos) * delta; + } + else + { + v = pos + (tmp + _owner._rawWidth - pos) * delta - (tmp + _owner._rawWidth); + _owner.width = _owner._rawWidth + v; + _owner.xMin = tmp; + } + } + else + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.width = _owner.sourceWidth + (_target._width - _target.initWidth) * (1 - pivot); + else + _owner.width = _owner._rawWidth + delta * (1 - pivot); + } + else + { + v = delta * (1 - pivot); + _owner.width = _owner._rawWidth + v; + _owner.xMin = tmp; + } + } + break; + case RelationType.TopExt_Top: + tmp = _owner.yMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (-pivot); + _owner.height = _owner._rawHeight - v; + _owner.yMin = tmp + v; + break; + case RelationType.TopExt_Bottom: + tmp = _owner.yMin; + if (info.percent) + v = pos + (tmp - pos) * delta - tmp; + else + v = delta * (1 - pivot); + _owner.height = _owner._rawHeight - v; + _owner.yMin = tmp + v; + break; + case RelationType.BottomExt_Top: + tmp = _owner.yMin; + if (info.percent) + v = pos + (tmp + _owner._rawHeight - pos) * delta - (tmp + _owner._rawHeight); + else + v = delta * (-pivot); + _owner.height = _owner._rawHeight + v; + _owner.yMin = tmp; + break; + case RelationType.BottomExt_Bottom: + tmp = _owner.yMin; + if (info.percent) + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.height = pos + _target._height - _target._height * pivot + + (_owner.sourceHeight - pos - _target.initHeight + _target.initHeight * pivot) * delta; + else + _owner.height = pos + (_owner._rawHeight - pos) * delta; + } + else + { + v = pos + (tmp + _owner._rawHeight - pos) * delta - (tmp + _owner._rawHeight); + _owner.height = _owner._rawHeight + v; + _owner.yMin = tmp; + } + } + else + { + if (_owner == _target.parent) + { + if (_owner.underConstruct) + _owner.height = _owner.sourceHeight + (_target._height - _target.initHeight) * (1 - pivot); + else + _owner.height = _owner._rawHeight + delta * (1 - pivot); + } + else + { + v = delta * (1 - pivot); + _owner.height = _owner._rawHeight + v; + _owner.yMin = tmp; + } + } + break; + } + } + + void AddRefTarget(GObject target) + { + if (target != _owner.parent) + target.onPositionChanged.Add(__targetXYChanged); + target.onSizeChanged.Add(__targetSizeChanged); + _targetData.x = _target.x; + _targetData.y = _target.y; + _targetData.z = _target._width; + _targetData.w = _target._height; + } + + void ReleaseRefTarget(GObject target) + { + target.onPositionChanged.Remove(__targetXYChanged); + target.onSizeChanged.Remove(__targetSizeChanged); + } + + void __targetXYChanged(EventContext context) + { + if (_owner.relations.handling != null + || _owner.group != null && _owner.group._updating != 0) + { + _targetData.x = _target.x; + _targetData.y = _target.y; + return; + } + + _owner.relations.handling = (GObject)context.sender; + + float ox = _owner.x; + float oy = _owner.y; + float dx = _target.x - _targetData.x; + float dy = _target.y - _targetData.y; + + int cnt = _defs.Count; + for (int i = 0; i < cnt; i++) + ApplyOnXYChanged(_defs[i], dx, dy); + + _targetData.x = _target.x; + _targetData.y = _target.y; + + if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) + { + ox = _owner.x - ox; + oy = _owner.y - oy; + + _owner.UpdateGearFromRelations(1, ox, oy); + + if (_owner.parent != null) + { + int transCount = _owner.parent._transitions.Count; + for (int i = 0; i < transCount; i++) + _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); + } + } + + _owner.relations.handling = null; + } + + void __targetSizeChanged(EventContext context) + { + if (_owner.relations.handling != null + || _owner.group != null && _owner.group._updating != 0) + { + _targetData.z = _target._width; + _targetData.w = _target._height; + return; + } + + _owner.relations.handling = (GObject)context.sender; + + float ox = _owner.x; + float oy = _owner.y; + float ow = _owner._rawWidth; + float oh = _owner._rawHeight; + + int cnt = _defs.Count; + for (int i = 0; i < cnt; i++) + ApplyOnSizeChanged(_defs[i]); + + _targetData.z = _target._width; + _targetData.w = _target._height; + + if (!Mathf.Approximately(ox, _owner.x) || !Mathf.Approximately(oy, _owner.y)) + { + ox = _owner.x - ox; + oy = _owner.y - oy; + + _owner.UpdateGearFromRelations(1, ox, oy); + + if (_owner.parent != null) + { + int transCount = _owner.parent._transitions.Count; + for (int i = 0; i < transCount; i++) + _owner.parent._transitions[i].UpdateFromRelations(_owner.id, ox, oy); + } + } + + if (!Mathf.Approximately(ow, _owner._rawWidth) || !Mathf.Approximately(oh, _owner._rawHeight)) + { + ow = _owner._rawWidth - ow; + oh = _owner._rawHeight - oh; + + _owner.UpdateGearFromRelations(2, ow, oh); + } + + _owner.relations.handling = null; + } + } +} diff --git a/Assets/Scripts/UI/RelationItem.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/RelationItem.cs.meta similarity index 100% rename from Assets/Scripts/UI/RelationItem.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/RelationItem.cs.meta diff --git a/Assets/Scripts/UI/Relations.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Relations.cs similarity index 96% rename from Assets/Scripts/UI/Relations.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Relations.cs index 5d7650a2..14ef2ba3 100644 --- a/Assets/Scripts/UI/Relations.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Relations.cs @@ -1,220 +1,220 @@ -using System; -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class Relations - { - GObject _owner; - List _items; - - public GObject handling; - - public Relations(GObject owner) - { - _owner = owner; - _items = new List(); - } - - /// - /// - /// - /// - /// - public void Add(GObject target, RelationType relationType) - { - Add(target, relationType, false); - } - - /// - /// - /// - /// - /// - /// - public void Add(GObject target, RelationType relationType, bool usePercent) - { - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - RelationItem item = _items[i]; - if (item.target == target) - { - item.Add(relationType, usePercent); - return; - } - } - RelationItem newItem = new RelationItem(_owner); - newItem.target = target; - newItem.Add(relationType, usePercent); - _items.Add(newItem); - } - - /// - /// - /// - /// - /// - public void Remove(GObject target, RelationType relationType) - { - int cnt = _items.Count; - int i = 0; - while (i < cnt) - { - RelationItem item = _items[i]; - if (item.target == target) - { - item.Remove(relationType); - if (item.isEmpty) - { - item.Dispose(); - _items.RemoveAt(i); - cnt--; - continue; - } - else - i++; - } - i++; - } - } - - /// - /// - /// - /// - /// - public bool Contains(GObject target) - { - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - RelationItem item = _items[i]; - if (item.target == target) - return true; - } - return false; - } - - /// - /// - /// - /// - public void ClearFor(GObject target) - { - int cnt = _items.Count; - int i = 0; - while (i < cnt) - { - RelationItem item = _items[i]; - if (item.target == target) - { - item.Dispose(); - _items.RemoveAt(i); - cnt--; - } - else - i++; - } - } - - /// - /// - /// - public void ClearAll() - { - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - RelationItem item = _items[i]; - item.Dispose(); - } - _items.Clear(); - } - - /// - /// - /// - /// - public void CopyFrom(Relations source) - { - ClearAll(); - - List arr = source._items; - foreach (RelationItem ri in arr) - { - RelationItem item = new RelationItem(_owner); - item.CopyFrom(ri); - _items.Add(item); - } - } - - /// - /// - /// - public void Dispose() - { - ClearAll(); - handling = null; - } - - /// - /// - /// - /// - /// - /// - public void OnOwnerSizeChanged(float dWidth, float dHeight, bool applyPivot) - { - int cnt = _items.Count; - if (cnt == 0) - return; - - for (int i = 0; i < cnt; i++) - _items[i].ApplyOnSelfSizeChanged(dWidth, dHeight, applyPivot); - } - - /// - /// - /// - public bool isEmpty - { - get - { - return _items.Count == 0; - } - } - - public void Setup(ByteBuffer buffer, bool parentToChild) - { - int cnt = buffer.ReadByte(); - GObject target; - for (int i = 0; i < cnt; i++) - { - int targetIndex = buffer.ReadShort(); - if (targetIndex == -1) - target = _owner.parent; - else if (parentToChild) - target = ((GComponent)_owner).GetChildAt(targetIndex); - else - target = _owner.parent.GetChildAt(targetIndex); - - RelationItem newItem = new RelationItem(_owner); - newItem.target = target; - _items.Add(newItem); - - int cnt2 = buffer.ReadByte(); - for (int j = 0; j < cnt2; j++) - { - RelationType rt = (RelationType)buffer.ReadByte(); - bool usePercent = buffer.ReadBool(); - newItem.InternalAdd(rt, usePercent); - } - } - } - } -} +using System; +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class Relations + { + GObject _owner; + List _items; + + public GObject handling; + + public Relations(GObject owner) + { + _owner = owner; + _items = new List(); + } + + /// + /// + /// + /// + /// + public void Add(GObject target, RelationType relationType) + { + Add(target, relationType, false); + } + + /// + /// + /// + /// + /// + /// + public void Add(GObject target, RelationType relationType, bool usePercent) + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + RelationItem item = _items[i]; + if (item.target == target) + { + item.Add(relationType, usePercent); + return; + } + } + RelationItem newItem = new RelationItem(_owner); + newItem.target = target; + newItem.Add(relationType, usePercent); + _items.Add(newItem); + } + + /// + /// + /// + /// + /// + public void Remove(GObject target, RelationType relationType) + { + int cnt = _items.Count; + int i = 0; + while (i < cnt) + { + RelationItem item = _items[i]; + if (item.target == target) + { + item.Remove(relationType); + if (item.isEmpty) + { + item.Dispose(); + _items.RemoveAt(i); + cnt--; + continue; + } + else + i++; + } + i++; + } + } + + /// + /// + /// + /// + /// + public bool Contains(GObject target) + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + RelationItem item = _items[i]; + if (item.target == target) + return true; + } + return false; + } + + /// + /// + /// + /// + public void ClearFor(GObject target) + { + int cnt = _items.Count; + int i = 0; + while (i < cnt) + { + RelationItem item = _items[i]; + if (item.target == target) + { + item.Dispose(); + _items.RemoveAt(i); + cnt--; + } + else + i++; + } + } + + /// + /// + /// + public void ClearAll() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + RelationItem item = _items[i]; + item.Dispose(); + } + _items.Clear(); + } + + /// + /// + /// + /// + public void CopyFrom(Relations source) + { + ClearAll(); + + List arr = source._items; + foreach (RelationItem ri in arr) + { + RelationItem item = new RelationItem(_owner); + item.CopyFrom(ri); + _items.Add(item); + } + } + + /// + /// + /// + public void Dispose() + { + ClearAll(); + handling = null; + } + + /// + /// + /// + /// + /// + /// + public void OnOwnerSizeChanged(float dWidth, float dHeight, bool applyPivot) + { + int cnt = _items.Count; + if (cnt == 0) + return; + + for (int i = 0; i < cnt; i++) + _items[i].ApplyOnSelfSizeChanged(dWidth, dHeight, applyPivot); + } + + /// + /// + /// + public bool isEmpty + { + get + { + return _items.Count == 0; + } + } + + public void Setup(ByteBuffer buffer, bool parentToChild) + { + int cnt = buffer.ReadByte(); + GObject target; + for (int i = 0; i < cnt; i++) + { + int targetIndex = buffer.ReadShort(); + if (targetIndex == -1) + target = _owner.parent; + else if (parentToChild) + target = ((GComponent)_owner).GetChildAt(targetIndex); + else + target = _owner.parent.GetChildAt(targetIndex); + + RelationItem newItem = new RelationItem(_owner); + newItem.target = target; + _items.Add(newItem); + + int cnt2 = buffer.ReadByte(); + for (int j = 0; j < cnt2; j++) + { + RelationType rt = (RelationType)buffer.ReadByte(); + bool usePercent = buffer.ReadBool(); + newItem.InternalAdd(rt, usePercent); + } + } + } + } +} diff --git a/Assets/Scripts/UI/Relations.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Relations.cs.meta similarity index 100% rename from Assets/Scripts/UI/Relations.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Relations.cs.meta diff --git a/Assets/Scripts/UI/ScrollPane.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/ScrollPane.cs similarity index 97% rename from Assets/Scripts/UI/ScrollPane.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/ScrollPane.cs index 5f21caaa..5082420e 100644 --- a/Assets/Scripts/UI/ScrollPane.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/ScrollPane.cs @@ -1,2320 +1,2320 @@ -using System; -using UnityEngine; -using FairyGUI.Utils; - -namespace FairyGUI -{ - /// - /// - /// - public class ScrollPane : EventDispatcher - { - /// - /// 当前被拖拽的滚动面板。同一时间只能有一个在进行此操作。 - /// - public static ScrollPane draggingPane { get; private set; } - - ScrollType _scrollType; - float _scrollStep; - float _decelerationRate; - Margin _scrollBarMargin; - bool _bouncebackEffect; - bool _touchEffect; - bool _scrollBarDisplayAuto; - bool _vScrollNone; - bool _hScrollNone; - bool _needRefresh; - int _refreshBarAxis; - - bool _displayOnLeft; - bool _snapToItem; - internal bool _displayInDemand; - bool _mouseWheelEnabled; - bool _softnessOnTopOrLeftSide; - bool _pageMode; - Vector2 _pageSize; - bool _inertiaDisabled; - bool _maskDisabled; - bool _floating; - bool _dontClipMargin; - - float _xPos; - float _yPos; - - Vector2 _viewSize; - Vector2 _contentSize; - Vector2 _overlapSize; - Vector2 _containerPos; - Vector2 _beginTouchPos; - Vector2 _lastTouchPos; - Vector2 _lastTouchGlobalPos; - Vector2 _velocity; - float _velocityScale; - float _lastMoveTime; - bool _dragged; - bool _isHoldAreaDone; - int _aniFlag; - internal int _loop; - int _headerLockedSize; - int _footerLockedSize; - bool _hover; - - int _tweening; - Vector2 _tweenStart; - Vector2 _tweenChange; - Vector2 _tweenTime; - Vector2 _tweenDuration; - - Action _refreshDelegate; - TimerCallback _tweenUpdateDelegate; - GTweenCallback1 _hideScrollBarDelegate; - - GComponent _owner; - Container _maskContainer; - Container _container; - GScrollBar _hzScrollBar; - GScrollBar _vtScrollBar; - GComponent _header; - GComponent _footer; - Controller _pageController; - - EventListener _onScroll; - EventListener _onScrollEnd; - EventListener _onPullDownRelease; - EventListener _onPullUpRelease; - - static int _gestureFlag; - - public static float TWEEN_TIME_GO = 0.3f; //调用SetPos(ani)时使用的缓动时间 - public static float TWEEN_TIME_DEFAULT = 0.3f; //惯性滚动的最小缓动时间 - public static float PULL_RATIO = 0.5f; //下拉过顶或者上拉过底时允许超过的距离占显示区域的比例 - - public ScrollPane(GComponent owner) - { - _onScroll = new EventListener(this, "onScroll"); - _onScrollEnd = new EventListener(this, "onScrollEnd"); - - _scrollStep = UIConfig.defaultScrollStep; - _softnessOnTopOrLeftSide = UIConfig.allowSoftnessOnTopOrLeftSide; - _decelerationRate = UIConfig.defaultScrollDecelerationRate; - _touchEffect = UIConfig.defaultScrollTouchEffect; - _bouncebackEffect = UIConfig.defaultScrollBounceEffect; - _mouseWheelEnabled = true; - _pageSize = Vector2.one; - - _refreshDelegate = Refresh; - _tweenUpdateDelegate = TweenUpdate; - _hideScrollBarDelegate = __barTweenComplete; - - _owner = owner; - - _maskContainer = new Container(); - _owner.rootContainer.AddChild(_maskContainer); - - _container = _owner.container; - _container.SetXY(0, 0); - _maskContainer.AddChild(_container); - - _owner.rootContainer.onMouseWheel.Add(__mouseWheel); - _owner.rootContainer.onTouchBegin.Add(__touchBegin); - _owner.rootContainer.onTouchMove.Add(__touchMove); - _owner.rootContainer.onTouchEnd.Add(__touchEnd); - } - - public void Setup(ByteBuffer buffer) - { - _scrollType = (ScrollType)buffer.ReadByte(); - ScrollBarDisplayType scrollBarDisplay = (ScrollBarDisplayType)buffer.ReadByte(); - int flags = buffer.ReadInt(); - - if (buffer.ReadBool()) - { - _scrollBarMargin.top = buffer.ReadInt(); - _scrollBarMargin.bottom = buffer.ReadInt(); - _scrollBarMargin.left = buffer.ReadInt(); - _scrollBarMargin.right = buffer.ReadInt(); - } - - string vtScrollBarRes = buffer.ReadS(); - string hzScrollBarRes = buffer.ReadS(); - string headerRes = buffer.ReadS(); - string footerRes = buffer.ReadS(); - - _displayOnLeft = (flags & 1) != 0; - _snapToItem = (flags & 2) != 0; - _displayInDemand = (flags & 4) != 0; - _pageMode = (flags & 8) != 0; - if ((flags & 16) != 0) - _touchEffect = true; - else if ((flags & 32) != 0) - _touchEffect = false; - if ((flags & 64) != 0) - _bouncebackEffect = true; - else if ((flags & 128) != 0) - _bouncebackEffect = false; - _inertiaDisabled = (flags & 256) != 0; - _maskDisabled = (flags & 512) != 0; - _floating = (flags & 1024) != 0; - _dontClipMargin = (flags & 2048) != 0; - - if (scrollBarDisplay == ScrollBarDisplayType.Default) - { - if (Application.isMobilePlatform) - scrollBarDisplay = ScrollBarDisplayType.Auto; - else - scrollBarDisplay = UIConfig.defaultScrollBarDisplay; - } - - if (scrollBarDisplay != ScrollBarDisplayType.Hidden) - { - if (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) - { - string res = vtScrollBarRes != null ? vtScrollBarRes : UIConfig.verticalScrollBar; - if (!string.IsNullOrEmpty(res)) - { - _vtScrollBar = UIPackage.CreateObjectFromURL(res) as GScrollBar; - if (_vtScrollBar == null) - Debug.LogWarning("FairyGUI: cannot create scrollbar from " + res); - else - { - _vtScrollBar.SetScrollPane(this, true); - _owner.rootContainer.AddChild(_vtScrollBar.displayObject); - } - } - } - if (_scrollType == ScrollType.Both || _scrollType == ScrollType.Horizontal) - { - string res = hzScrollBarRes != null ? hzScrollBarRes : UIConfig.horizontalScrollBar; - if (!string.IsNullOrEmpty(res)) - { - _hzScrollBar = UIPackage.CreateObjectFromURL(res) as GScrollBar; - if (_hzScrollBar == null) - Debug.LogWarning("FairyGUI: cannot create scrollbar from " + res); - else - { - _hzScrollBar.SetScrollPane(this, false); - _owner.rootContainer.AddChild(_hzScrollBar.displayObject); - } - } - } - - _scrollBarDisplayAuto = scrollBarDisplay == ScrollBarDisplayType.Auto; - if (_scrollBarDisplayAuto) - { - if (_vtScrollBar != null) - _vtScrollBar.displayObject.visible = false; - if (_hzScrollBar != null) - _hzScrollBar.displayObject.visible = false; - - _owner.rootContainer.onRollOver.Add(__rollOver); - _owner.rootContainer.onRollOut.Add(__rollOut); - } - } - else - _mouseWheelEnabled = false; - - if (Application.isPlaying) - { - if (headerRes != null) - { - _header = (GComponent)UIPackage.CreateObjectFromURL(headerRes); - if (_header == null) - Debug.LogWarning("FairyGUI: cannot create scrollPane header from " + headerRes); - } - - if (footerRes != null) - { - _footer = (GComponent)UIPackage.CreateObjectFromURL(footerRes); - if (_footer == null) - Debug.LogWarning("FairyGUI: cannot create scrollPane footer from " + footerRes); - } - - if (_header != null || _footer != null) - _refreshBarAxis = (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) ? 1 : 0; - } - - SetSize(owner.width, owner.height); - } - - /// - /// - /// - public void Dispose() - { - RemoveEventListeners(); - - if (_tweening != 0) - Timers.inst.Remove(_tweenUpdateDelegate); - - if (draggingPane == this) - draggingPane = null; - - _pageController = null; - - if (_hzScrollBar != null) - _hzScrollBar.Dispose(); - if (_vtScrollBar != null) - _vtScrollBar.Dispose(); - if (_header != null) - _header.Dispose(); - if (_footer != null) - _footer.Dispose(); - } - - /// - /// Dispatched when scrolling. - /// 在滚动时派发该事件。 - /// - public EventListener onScroll - { - get { return _onScroll ?? (_onScroll = new EventListener(this, "onScroll")); } - } - - /// - /// 在滚动结束时派发该事件。 - /// - public EventListener onScrollEnd - { - get { return _onScrollEnd ?? (_onScrollEnd = new EventListener(this, "onScrollEnd")); } - } - - /// - /// 向下拉过上边缘后释放则派发该事件。 - /// - public EventListener onPullDownRelease - { - get { return _onPullDownRelease ?? (_onPullDownRelease = new EventListener(this, "onPullDownRelease")); } - } - - /// - /// 向上拉过下边缘后释放则派发该事件。 - /// - public EventListener onPullUpRelease - { - get { return _onPullUpRelease ?? (_onPullUpRelease = new EventListener(this, "onPullUpRelease")); } - } - - /// - /// - /// - public GComponent owner - { - get { return _owner; } - } - - /// - /// - /// - public GScrollBar hzScrollBar - { - get { return _hzScrollBar; } - } - - /// - /// - /// - public GScrollBar vtScrollBar - { - get { return _vtScrollBar; } - } - - /// - /// - /// - public GComponent header - { - get { return _header; } - } - - /// - /// - /// - public GComponent footer - { - get { return _footer; } - } - - /// - /// 滚动到达边缘时是否允许回弹效果。 - /// - public bool bouncebackEffect - { - get { return _bouncebackEffect; } - set { _bouncebackEffect = value; } - } - - /// - /// 是否允许拖拽内容区域进行滚动。 - /// - public bool touchEffect - { - get { return _touchEffect; } - set { _touchEffect = value; } - } - - /// - /// 是否允许惯性滚动。 - /// - public bool inertiaDisabled - { - get { return _inertiaDisabled; } - set { _inertiaDisabled = value; } - } - - /// - /// 是否允许在左/上边缘显示虚化效果。 - /// - public bool softnessOnTopOrLeftSide - { - get { return _softnessOnTopOrLeftSide; } - set { _softnessOnTopOrLeftSide = value; } - } - - /// - /// 当调用ScrollPane.scrollUp/Down/Left/Right时,或者点击滚动条的上下箭头时,滑动的距离。 - /// - public float scrollStep - { - get { return _scrollStep; } - set - { - _scrollStep = value; - if (_scrollStep == 0) - _scrollStep = UIConfig.defaultScrollStep; - } - } - - /// - /// 滚动位置是否保持贴近在某个元件的边缘。 - /// - public bool snapToItem - { - get { return _snapToItem; } - set { _snapToItem = value; } - } - - /// - /// 是否页面滚动模式。 - /// - public bool pageMode - { - get { return _pageMode; } - set { _pageMode = value; } - } - - /// - /// - /// - public Controller pageController - { - get { return _pageController; } - set { _pageController = value; } - } - - /// - /// 是否允许使用鼠标滚轮进行滚动。 - /// - public bool mouseWheelEnabled - { - get { return _mouseWheelEnabled; } - set { _mouseWheelEnabled = value; } - } - - /// - /// 当处于惯性滚动时减速的速率。默认值是UIConfig.defaultScrollDecelerationRate。 - /// 越接近1,减速越慢,意味着滑动的时间和距离更长。 - /// - public float decelerationRate - { - get { return _decelerationRate; } - set { _decelerationRate = value; } - } - - /// - /// - public bool isDragged - { - get { return _dragged; } - } - - /// - /// 当前X轴滚动位置百分比,0~1(包含)。 - /// - public float percX - { - get { return _overlapSize.x == 0 ? 0 : _xPos / _overlapSize.x; } - set { SetPercX(value, false); } - } - - /// - /// 设置当前X轴滚动位置百分比,0~1(包含)。 - /// - /// - /// 是否使用缓动到达目标。 - public void SetPercX(float value, bool ani) - { - _owner.EnsureBoundsCorrect(); - SetPosX(_overlapSize.x * Mathf.Clamp01(value), ani); - } - - /// - /// 当前Y轴滚动位置百分比,0~1(包含)。 - /// - public float percY - { - get { return _overlapSize.y == 0 ? 0 : _yPos / _overlapSize.y; } - set { SetPercY(value, false); } - } - - /// - /// 设置当前Y轴滚动位置百分比,0~1(包含)。 - /// - /// - /// 是否使用缓动到达目标。 - public void SetPercY(float value, bool ani) - { - _owner.EnsureBoundsCorrect(); - SetPosY(_overlapSize.y * Mathf.Clamp01(value), ani); - } - - /// - /// 当前X轴滚动位置,值范围是viewWidth与contentWidth之差。 - /// - public float posX - { - get { return _xPos; } - set { SetPosX(value, false); } - } - - /// - /// 设置当前X轴滚动位置。 - /// - /// - /// 是否使用缓动到达目标。 - public void SetPosX(float value, bool ani) - { - _owner.EnsureBoundsCorrect(); - - if (_loop == 1) - LoopCheckingNewPos(ref value, 0); - - value = Mathf.Clamp(value, 0, _overlapSize.x); - if (value != _xPos) - { - _xPos = value; - PosChanged(ani); - } - } - - /// - /// 当前Y轴滚动位置,值范围是viewHeight与contentHeight之差。 - /// - public float posY - { - get { return _yPos; } - set { SetPosY(value, false); } - } - - /// - /// 设置当前Y轴滚动位置。 - /// - /// - /// 是否使用缓动到达目标。 - public void SetPosY(float value, bool ani) - { - _owner.EnsureBoundsCorrect(); - - if (_loop == 2) - LoopCheckingNewPos(ref value, 1); - - value = Mathf.Clamp(value, 0, _overlapSize.y); - if (value != _yPos) - { - _yPos = value; - PosChanged(ani); - } - } - - /// - /// 返回当前滚动位置是否在最下边。 - /// - public bool isBottomMost - { - get { return _yPos == _overlapSize.y || _overlapSize.y == 0; } - } - - /// - /// 返回当前滚动位置是否在最右边。 - /// - public bool isRightMost - { - get { return _xPos == _overlapSize.x || _overlapSize.x == 0; } - } - - /// - /// 如果处于分页模式,返回当前在X轴的页码。 - /// - public int currentPageX - { - get - { - if (!_pageMode) - return 0; - - int page = Mathf.FloorToInt(_xPos / _pageSize.x); - if (_xPos - page * _pageSize.x > _pageSize.x * 0.5f) - page++; - - return page; - } - set - { - if (!_pageMode) - return; - - _owner.EnsureBoundsCorrect(); - - if (_overlapSize.x > 0) - this.SetPosX(value * _pageSize.x, false); - } - } - - /// - /// 如果处于分页模式,可设置X轴的页码。 - /// - /// - /// 是否使用缓动到达目标。 - public void SetCurrentPageX(int value, bool ani) - { - if (!_pageMode) - return; - - _owner.EnsureBoundsCorrect(); - - if (_overlapSize.x > 0) - this.SetPosX(value * _pageSize.x, ani); - } - - /// - /// 如果处于分页模式,返回当前在Y轴的页码。 - /// - public int currentPageY - { - get - { - if (!_pageMode) - return 0; - - int page = Mathf.FloorToInt(_yPos / _pageSize.y); - if (_yPos - page * _pageSize.y > _pageSize.y * 0.5f) - page++; - - return page; - } - set - { - if (!_pageMode) - return; - - _owner.EnsureBoundsCorrect(); - - if (_overlapSize.y > 0) - this.SetPosY(value * _pageSize.y, false); - } - } - - /// - /// 如果处于分页模式,可设置Y轴的页码。 - /// - /// - /// 是否使用缓动到达目标。 - public void SetCurrentPageY(int value, bool ani) - { - if (!_pageMode) - return; - - _owner.EnsureBoundsCorrect(); - - if (_overlapSize.y > 0) - this.SetPosY(value * _pageSize.y, ani); - } - - /// - /// 这个值与PosX不同在于,他反映的是实时位置,而PosX在有缓动过程的情况下只是终值。 - /// - public float scrollingPosX - { - get - { - return Mathf.Clamp(-_container.x, 0, _overlapSize.x); - } - } - - /// - /// 这个值与PosY不同在于,他反映的是实时位置,而PosY在有缓动过程的情况下只是终值。 - /// - public float scrollingPosY - { - get - { - return Mathf.Clamp(-_container.y, 0, _overlapSize.y); - } - } - - /// - /// 显示内容宽度。 - /// - public float contentWidth - { - get - { - return _contentSize.x; - } - } - - /// - /// 显示内容高度。 - /// - public float contentHeight - { - get - { - return _contentSize.y; - } - } - - /// - /// 显示区域宽度。 - /// - public float viewWidth - { - get { return _viewSize.x; } - set - { - value = value + _owner.margin.left + _owner.margin.right; - if (_vtScrollBar != null && !_floating) - value += _vtScrollBar.width; - _owner.width = value; - } - } - - /// - /// 显示区域高度。 - /// - public float viewHeight - { - get { return _viewSize.y; } - set - { - value = value + _owner.margin.top + _owner.margin.bottom; - if (_hzScrollBar != null && !_floating) - value += _hzScrollBar.height; - _owner.height = value; - } - } - - /// - /// - /// - public void ScrollTop() - { - ScrollTop(false); - } - - /// - /// - /// - /// - public void ScrollTop(bool ani) - { - this.SetPercY(0, ani); - } - - /// - /// - /// - public void ScrollBottom() - { - ScrollBottom(false); - } - - /// - /// - /// - /// - public void ScrollBottom(bool ani) - { - this.SetPercY(1, ani); - } - - /// - /// - /// - public void ScrollUp() - { - ScrollUp(1, false); - } - - /// - /// - /// - /// - /// - public void ScrollUp(float ratio, bool ani) - { - if (_pageMode) - SetPosY(_yPos - _pageSize.y * ratio, ani); - else - SetPosY(_yPos - _scrollStep * ratio, ani); - } - - /// - /// - /// - public void ScrollDown() - { - ScrollDown(1, false); - } - - /// - /// - /// - /// - /// - public void ScrollDown(float ratio, bool ani) - { - if (_pageMode) - SetPosY(_yPos + _pageSize.y * ratio, ani); - else - SetPosY(_yPos + _scrollStep * ratio, ani); - } - - /// - /// - /// - public void ScrollLeft() - { - ScrollLeft(1, false); - } - - /// - /// - /// - /// - /// - public void ScrollLeft(float ratio, bool ani) - { - if (_pageMode) - SetPosX(_xPos - _pageSize.x * ratio, ani); - else - SetPosX(_xPos - _scrollStep * ratio, ani); - } - - /// - /// - /// - public void ScrollRight() - { - ScrollRight(1, false); - } - - /// - /// - /// - /// - /// - public void ScrollRight(float ratio, bool ani) - { - if (_pageMode) - SetPosX(_xPos + _pageSize.x * ratio, ani); - else - SetPosX(_xPos + _scrollStep * ratio, ani); - } - - /// - /// - /// - /// obj can be any object on stage, not limited to the direct child of this container. - public void ScrollToView(GObject obj) - { - ScrollToView(obj, false); - } - - /// - /// - /// - /// obj can be any object on stage, not limited to the direct child of this container. - /// If moving to target position with animation - public void ScrollToView(GObject obj, bool ani) - { - ScrollToView(obj, ani, false); - } - - /// - /// - /// - /// obj can be any object on stage, not limited to the direct child of this container. - /// If moving to target position with animation - /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. - public void ScrollToView(GObject obj, bool ani, bool setFirst) - { - _owner.EnsureBoundsCorrect(); - if (_needRefresh) - Refresh(); - - Rect rect = new Rect(obj.x, obj.y, obj.width, obj.height); - if (obj.parent != _owner) - rect = obj.parent.TransformRect(rect, _owner); - ScrollToView(rect, ani, setFirst); - } - - /// - /// - /// - /// Rect in local coordinates - /// If moving to target position with animation - /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. - public void ScrollToView(Rect rect, bool ani, bool setFirst) - { - _owner.EnsureBoundsCorrect(); - if (_needRefresh) - Refresh(); - - if (_overlapSize.y > 0) - { - float bottom = _yPos + _viewSize.y; - if (setFirst || rect.y <= _yPos || rect.height >= _viewSize.y) - { - if (rect.yMax >= bottom) //if an item size is large than viewSize, dont scroll - return; - - if (_pageMode) - this.SetPosY(Mathf.Floor(rect.y / _pageSize.y) * _pageSize.y, ani); - else - SetPosY(rect.y, ani); - } - else if (rect.yMax > bottom) - { - if (_pageMode) - this.SetPosY(Mathf.Floor(rect.y / _pageSize.y) * _pageSize.y, ani); - else if (rect.height <= _viewSize.y / 2) - SetPosY(rect.y + rect.height * 2 - _viewSize.y, ani); - else - SetPosY(rect.y + Mathf.Min(rect.height - _viewSize.y, 0), ani); - } - } - if (_overlapSize.x > 0) - { - float right = _xPos + _viewSize.x; - if (setFirst || rect.x <= _xPos || rect.width >= _viewSize.x) - { - if (rect.xMax >= right) //if an item size is large than viewSize, dont scroll - return; - - if (_pageMode) - this.SetPosX(Mathf.Floor(rect.x / _pageSize.x) * _pageSize.x, ani); - SetPosX(rect.x, ani); - } - else if (rect.xMax > right) - { - if (_pageMode) - this.SetPosX(Mathf.Floor(rect.x / _pageSize.x) * _pageSize.x, ani); - else if (rect.width <= _viewSize.x / 2) - SetPosX(rect.x + rect.width * 2 - _viewSize.x, ani); - else - SetPosX(rect.x + Mathf.Min(rect.width - _viewSize.x, 0), ani); - } - } - - if (!ani && _needRefresh) - Refresh(); - } - - /// - /// - /// - /// obj must be the direct child of this container - /// - public bool IsChildInView(GObject obj) - { - if (_overlapSize.y > 0) - { - float dist = obj.y + _container.y; - if (dist <= -obj.height || dist >= _viewSize.y) - return false; - } - if (_overlapSize.x > 0) - { - float dist = obj.x + _container.x; - if (dist <= -obj.width || dist >= _viewSize.x) - return false; - } - - return true; - } - - /// - /// 当滚动面板处于拖拽滚动状态或即将进入拖拽状态时,可以调用此方法停止或禁止本次拖拽。 - /// - public void CancelDragging() - { - Stage.inst.RemoveTouchMonitor(_owner.rootContainer); - - if (draggingPane == this) - draggingPane = null; - - _gestureFlag = 0; - _dragged = false; - } - - /// - /// 设置Header固定显示。如果size为0,则取消固定显示。 - /// - /// Header显示的大小 - public void LockHeader(int size) - { - if (_headerLockedSize == size) - return; - - _headerLockedSize = size; - if (!isDispatching("onPullDownRelease") && _container.xy[_refreshBarAxis] >= 0) - { - _tweenStart = _container.xy; - _tweenChange = Vector2.zero; - _tweenChange[_refreshBarAxis] = _headerLockedSize - _tweenStart[_refreshBarAxis]; - _tweenDuration = new Vector2(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); - StartTween(2); - } - } - - /// - /// 设置Footer固定显示。如果size为0,则取消固定显示。 - /// - /// - public void LockFooter(int size) - { - if (_footerLockedSize == size) - return; - - _footerLockedSize = size; - if (!isDispatching("onPullUpRelease") && _container.xy[_refreshBarAxis] <= -_overlapSize[_refreshBarAxis]) - { - _tweenStart = _container.xy; - _tweenChange = Vector2.zero; - float max = _overlapSize[_refreshBarAxis]; - if (max == 0) - max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); - else - max += _footerLockedSize; - _tweenChange[_refreshBarAxis] = -max - _tweenStart[_refreshBarAxis]; - _tweenDuration = new Vector2(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); - StartTween(2); - } - } - - internal void OnOwnerSizeChanged() - { - SetSize(_owner.width, _owner.height); - PosChanged(false); - } - - internal void HandleControllerChanged(Controller c) - { - if (_pageController == c) - { - if (_scrollType == ScrollType.Horizontal) - this.SetCurrentPageX(c.selectedIndex, true); - else - this.SetCurrentPageY(c.selectedIndex, true); - } - } - - void UpdatePageController() - { - if (_pageController != null && !_pageController.changing) - { - int index; - if (_scrollType == ScrollType.Horizontal) - index = this.currentPageX; - else - index = this.currentPageY; - if (index < _pageController.pageCount) - { - Controller c = _pageController; - _pageController = null; //防止HandleControllerChanged的调用 - c.selectedIndex = index; - _pageController = c; - } - } - } - - internal void AdjustMaskContainer() - { - float mx, my; - if (_displayOnLeft && _vtScrollBar != null && !_floating) - mx = Mathf.FloorToInt(_owner.margin.left + _vtScrollBar.width); - else - mx = _owner.margin.left; - my = _owner.margin.top; - mx += _owner._alignOffset.x; - my += _owner._alignOffset.y; - - _maskContainer.SetXY(mx, my); - } - - void SetSize(float aWidth, float aHeight) - { - AdjustMaskContainer(); - - if (_hzScrollBar != null) - { - _hzScrollBar.y = aHeight - _hzScrollBar.height; - if (_vtScrollBar != null) - { - _hzScrollBar.width = aWidth - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; - if (_displayOnLeft) - _hzScrollBar.x = _scrollBarMargin.left + _vtScrollBar.width; - else - _hzScrollBar.x = _scrollBarMargin.left; - } - else - { - _hzScrollBar.width = aWidth - _scrollBarMargin.left - _scrollBarMargin.right; - _hzScrollBar.x = _scrollBarMargin.left; - } - } - if (_vtScrollBar != null) - { - if (!_displayOnLeft) - _vtScrollBar.x = aWidth - _vtScrollBar.width; - if (_hzScrollBar != null) - _vtScrollBar.height = aHeight - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; - else - _vtScrollBar.height = aHeight - _scrollBarMargin.top - _scrollBarMargin.bottom; - _vtScrollBar.y = _scrollBarMargin.top; - } - - _viewSize.x = aWidth; - _viewSize.y = aHeight; - if (_hzScrollBar != null && !_floating) - _viewSize.y -= _hzScrollBar.height; - if (_vtScrollBar != null && !_floating) - _viewSize.x -= _vtScrollBar.width; - _viewSize.x -= (_owner.margin.left + _owner.margin.right); - _viewSize.y -= (_owner.margin.top + _owner.margin.bottom); - - _viewSize.x = Mathf.Max(1, _viewSize.x); - _viewSize.y = Mathf.Max(1, _viewSize.y); - _pageSize.x = _viewSize.x; - _pageSize.y = _viewSize.y; - - HandleSizeChanged(); - } - - internal void SetContentSize(float aWidth, float aHeight) - { - if (Mathf.Approximately(_contentSize.x, aWidth) && Mathf.Approximately(_contentSize.y, aHeight)) - return; - - _contentSize.x = aWidth; - _contentSize.y = aHeight; - HandleSizeChanged(); - } - - /// - /// 内部使用。由虚拟列表调用。在滚动时修改显示内容的大小,需要进行修正,避免滚动跳跃。 - /// - /// - /// - /// - /// - internal void ChangeContentSizeOnScrolling(float deltaWidth, float deltaHeight, float deltaPosX, float deltaPosY) - { - bool isRightmost = _xPos == _overlapSize.x; - bool isBottom = _yPos == _overlapSize.y; - - _contentSize.x += deltaWidth; - _contentSize.y += deltaHeight; - HandleSizeChanged(); - - if (_tweening == 1) - { - //如果原来滚动位置是贴边,加入处理继续贴边。 - if (deltaWidth != 0 && isRightmost && _tweenChange.x < 0) - { - _xPos = _overlapSize.x; - _tweenChange.x = -_xPos - _tweenStart.x; - } - - if (deltaHeight != 0 && isBottom && _tweenChange.y < 0) - { - _yPos = _overlapSize.y; - _tweenChange.y = -_yPos - _tweenStart.y; - } - } - else if (_tweening == 2) - { - //重新调整起始位置,确保能够顺滑滚下去 - if (deltaPosX != 0) - { - _container.x -= deltaPosX; - _tweenStart.x -= deltaPosX; - _xPos = -_container.x; - } - if (deltaPosY != 0) - { - _container.y -= deltaPosY; - _tweenStart.y -= deltaPosY; - _yPos = -_container.y; - } - } - else if (_dragged) - { - if (deltaPosX != 0) - { - _container.x -= deltaPosX; - _containerPos.x -= deltaPosX; - _xPos = -_container.x; - } - if (deltaPosY != 0) - { - _container.y -= deltaPosY; - _containerPos.y -= deltaPosY; - _yPos = -_container.y; - } - } - else - { - //如果原来滚动位置是贴边,加入处理继续贴边。 - if (deltaWidth != 0 && isRightmost) - { - _xPos = _overlapSize.x; - _container.x = -_xPos; - } - - if (deltaHeight != 0 && isBottom) - { - _yPos = _overlapSize.y; - _container.y = -_yPos; - } - } - - if (_pageMode) - UpdatePageController(); - } - - void HandleSizeChanged() - { - if (_displayInDemand) - { - _vScrollNone = _contentSize.y <= _viewSize.y; - _hScrollNone = _contentSize.x <= _viewSize.x; - - if (_vtScrollBar != null && _hzScrollBar != null) - { - if (!_hScrollNone) - _vtScrollBar.height = _owner.height - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; - else - _vtScrollBar.height = _owner.height - _scrollBarMargin.top - _scrollBarMargin.bottom; - - if (!_vScrollNone) - _hzScrollBar.width = _owner.width - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; - else - _hzScrollBar.width = _owner.width - _scrollBarMargin.left - _scrollBarMargin.right; - } - } - - if (_vtScrollBar != null) - { - if (_contentSize.y == 0) - _vtScrollBar.SetDisplayPerc(0); - else - _vtScrollBar.SetDisplayPerc(Mathf.Min(1, _viewSize.y / _contentSize.y)); - } - if (_hzScrollBar != null) - { - if (_contentSize.x == 0) - _hzScrollBar.SetDisplayPerc(0); - else - _hzScrollBar.SetDisplayPerc(Mathf.Min(1, _viewSize.x / _contentSize.x)); - } - - UpdateScrollBarVisible(); - - if (!_maskDisabled) - { - Rect rect = new Rect(-_owner._alignOffset.x, -_owner._alignOffset.y, _viewSize.x, _viewSize.y); - if (_vScrollNone && _vtScrollBar != null) - rect.width += _vtScrollBar.width; - if (_hScrollNone && _hzScrollBar != null) - rect.height += _hzScrollBar.height; - if (_dontClipMargin) - { - rect.x -= _owner.margin.left; - rect.width += (_owner.margin.left + _owner.margin.right); - rect.y -= _owner.margin.top; - rect.height += (_owner.margin.top + _owner.margin.bottom); - } - - _maskContainer.clipRect = rect; - } - - if (_scrollType == ScrollType.Horizontal || _scrollType == ScrollType.Both) - _overlapSize.x = Mathf.CeilToInt(Math.Max(0, _contentSize.x - _viewSize.x)); - else - _overlapSize.x = 0; - if (_scrollType == ScrollType.Vertical || _scrollType == ScrollType.Both) - _overlapSize.y = Mathf.CeilToInt(Math.Max(0, _contentSize.y - _viewSize.y)); - else - _overlapSize.y = 0; - - //边界检查 - _xPos = Mathf.Clamp(_xPos, 0, _overlapSize.x); - _yPos = Mathf.Clamp(_yPos, 0, _overlapSize.y); - float max = _overlapSize[_refreshBarAxis]; - if (max == 0) - max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); - else - max += _footerLockedSize; - if (_refreshBarAxis == 0) - _container.SetXY(Mathf.Clamp(_container.x, -max, _headerLockedSize), Mathf.Clamp(_container.y, -_overlapSize.y, 0)); - else - _container.SetXY(Mathf.Clamp(_container.x, -_overlapSize.x, 0), Mathf.Clamp(_container.y, -max, _headerLockedSize)); - - if (_header != null) - { - if (_refreshBarAxis == 0) - _header.height = _viewSize.y; - else - _header.width = _viewSize.x; - } - - if (_footer != null) - { - if (_refreshBarAxis == 0) - _footer.height = _viewSize.y; - else - _footer.width = _viewSize.x; - } - - UpdateScrollBarPos(); - if (_pageMode) - UpdatePageController(); - } - - private void PosChanged(bool ani) - { - //只要有1处要求不要缓动,那就不缓动 - if (_aniFlag == 0) - _aniFlag = ani ? 1 : -1; - else if (_aniFlag == 1 && !ani) - _aniFlag = -1; - - _needRefresh = true; - - UpdateContext.OnBegin -= _refreshDelegate; - UpdateContext.OnBegin += _refreshDelegate; - } - - private void Refresh() - { - _needRefresh = false; - UpdateContext.OnBegin -= _refreshDelegate; - - if (_owner.displayObject == null || _owner.displayObject.isDisposed) - return; - - if (_pageMode || _snapToItem) - { - Vector2 pos = new Vector2(-_xPos, -_yPos); - AlignPosition(ref pos, false); - _xPos = -pos.x; - _yPos = -pos.y; - } - - Refresh2(); - - _onScroll.Call(); - if (_needRefresh) //在onScroll事件里开发者可能修改位置,这里再刷新一次,避免闪烁 - { - _needRefresh = false; - UpdateContext.OnBegin -= _refreshDelegate; - - Refresh2(); - } - - UpdateScrollBarPos(); - _aniFlag = 0; - } - - void Refresh2() - { - if (_aniFlag == 1 && !_dragged) - { - Vector2 pos = new Vector2(); - - if (_overlapSize.x > 0) - pos.x = -(int)_xPos; - else - { - if (_container.x != 0) - _container.x = 0; - pos.x = 0; - } - if (_overlapSize.y > 0) - pos.y = -(int)_yPos; - else - { - if (_container.y != 0) - _container.y = 0; - pos.y = 0; - } - - if (pos.x != _container.x || pos.y != _container.y) - { - _tweenDuration = new Vector2(TWEEN_TIME_GO, TWEEN_TIME_GO); - _tweenStart = _container.xy; - _tweenChange = pos - _tweenStart; - StartTween(1); - } - else if (_tweening != 0) - KillTween(); - } - else - { - if (_tweening != 0) - KillTween(); - - _container.SetXY((int)-_xPos, (int)-_yPos); - - LoopCheckingCurrent(); - } - - if (_pageMode) - UpdatePageController(); - } - - private void __touchBegin(EventContext context) - { - if (!_touchEffect) - return; - - InputEvent evt = context.inputEvent; - if (evt.button != 0) - return; - - context.CaptureTouch(); - - Vector2 pt = _owner.GlobalToLocal(evt.position); - - if (_tweening != 0) - { - KillTween(); - Stage.inst.CancelClick(evt.touchId); - - //立刻停止惯性滚动,可能位置不对齐,设定这个标志,使touchEnd时归位 - _dragged = true; - } - else - _dragged = false; - - _containerPos = _container.xy; - _beginTouchPos = _lastTouchPos = pt; - _lastTouchGlobalPos = evt.position; - _isHoldAreaDone = false; - _velocity = Vector2.zero; - _velocityScale = 1; - _lastMoveTime = Time.unscaledTime; - } - - private void __touchMove(EventContext context) - { - if (!_touchEffect || draggingPane != null && draggingPane != this || GObject.draggingObject != null) //已经有其他拖动 - return; - - InputEvent evt = context.inputEvent; - Vector2 pt = _owner.GlobalToLocal(evt.position); - if (float.IsNaN(pt.x)) - return; - - int sensitivity; - if (Stage.touchScreen) - sensitivity = UIConfig.touchScrollSensitivity; - else - sensitivity = 8; - - float diff; - bool sv = false, sh = false; - - if (_scrollType == ScrollType.Vertical) - { - if (!_isHoldAreaDone) - { - //表示正在监测垂直方向的手势 - _gestureFlag |= 1; - - diff = Mathf.Abs(_beginTouchPos.y - pt.y); - if (diff < sensitivity) - return; - - if ((_gestureFlag & 2) != 0) //已经有水平方向的手势在监测,那么我们用严格的方式检查是不是按垂直方向移动,避免冲突 - { - float diff2 = Mathf.Abs(_beginTouchPos.x - pt.x); - if (diff < diff2) //不通过则不允许滚动了 - return; - } - } - - sv = true; - } - else if (_scrollType == ScrollType.Horizontal) - { - if (!_isHoldAreaDone) - { - _gestureFlag |= 2; - - diff = Mathf.Abs(_beginTouchPos.x - pt.x); - if (diff < sensitivity) - return; - - if ((_gestureFlag & 1) != 0) - { - float diff2 = Mathf.Abs(_beginTouchPos.y - pt.y); - if (diff < diff2) - return; - } - } - - sh = true; - } - else - { - _gestureFlag = 3; - - if (!_isHoldAreaDone) - { - diff = Mathf.Abs(_beginTouchPos.y - pt.y); - if (diff < sensitivity) - { - diff = Mathf.Abs(_beginTouchPos.x - pt.x); - if (diff < sensitivity) - return; - } - } - - sv = sh = true; - } - - Vector2 newPos = _containerPos + pt - _beginTouchPos; - newPos.x = (int)newPos.x; - newPos.y = (int)newPos.y; - - if (sv) - { - if (newPos.y > 0) - { - if (!_bouncebackEffect) - _container.y = 0; - else if (_header != null && _header.maxHeight != 0) - _container.y = (int)Mathf.Min(newPos.y * 0.5f, _header.maxHeight); - else - _container.y = (int)Mathf.Min(newPos.y * 0.5f, _viewSize.y * PULL_RATIO); - } - else if (newPos.y < -_overlapSize.y) - { - if (!_bouncebackEffect) - _container.y = -_overlapSize.y; - else if (_footer != null && _footer.maxHeight > 0) - _container.y = (int)Mathf.Max((newPos.y + _overlapSize.y) * 0.5f, -_footer.maxHeight) - _overlapSize.y; - else - _container.y = (int)Mathf.Max((newPos.y + _overlapSize.y) * 0.5f, -_viewSize.y * PULL_RATIO) - _overlapSize.y; - } - else - _container.y = newPos.y; - } - - if (sh) - { - if (newPos.x > 0) - { - if (!_bouncebackEffect) - _container.x = 0; - else if (_header != null && _header.maxWidth != 0) - _container.x = (int)Mathf.Min(newPos.x * 0.5f, _header.maxWidth); - else - _container.x = (int)Mathf.Min(newPos.x * 0.5f, _viewSize.x * PULL_RATIO); - } - else if (newPos.x < 0 - _overlapSize.x) - { - if (!_bouncebackEffect) - _container.x = -_overlapSize.x; - else if (_footer != null && _footer.maxWidth > 0) - _container.x = (int)Mathf.Max((newPos.x + _overlapSize.x) * 0.5f, -_footer.maxWidth) - _overlapSize.x; - else - _container.x = (int)Mathf.Max((newPos.x + _overlapSize.x) * 0.5f, -_viewSize.x * PULL_RATIO) - _overlapSize.x; - } - else - _container.x = newPos.x; - } - - //更新速度 - float deltaTime = Time.unscaledDeltaTime; - float elapsed = (Time.unscaledTime - _lastMoveTime) * 60 - 1; - if (elapsed > 1) //速度衰减 - _velocity = _velocity * Mathf.Pow(0.833f, elapsed); - Vector2 deltaPosition = pt - _lastTouchPos; - if (!sh) - deltaPosition.x = 0; - if (!sv) - deltaPosition.y = 0; - _velocity = Vector2.Lerp(_velocity, deltaPosition / deltaTime, deltaTime * 10); - - /*速度计算使用的是本地位移,但在后续的惯性滚动判断中需要用到屏幕位移,所以这里要记录一个位移的比例。 - *后续的处理要使用这个比例但不使用坐标转换的方法的原因是,在曲面UI等异形UI中,还无法简单地进行屏幕坐标和本地坐标的转换。 - */ - Vector2 deltaGlobalPosition = _lastTouchGlobalPos - evt.position; - if (deltaPosition.x != 0) - _velocityScale = Mathf.Abs(deltaGlobalPosition.x / deltaPosition.x); - else if (deltaPosition.y != 0) - _velocityScale = Mathf.Abs(deltaGlobalPosition.y / deltaPosition.y); - - _lastTouchPos = pt; - _lastTouchGlobalPos = evt.position; - _lastMoveTime = Time.unscaledTime; - - //同步更新pos值 - if (_overlapSize.x > 0) - _xPos = Mathf.Clamp(-_container.x, 0, _overlapSize.x); - if (_overlapSize.y > 0) - _yPos = Mathf.Clamp(-_container.y, 0, _overlapSize.y); - - //循环滚动特别检查 - if (_loop != 0) - { - newPos = _container.xy; - if (LoopCheckingCurrent()) - _containerPos += _container.xy - newPos; - } - - draggingPane = this; - _isHoldAreaDone = true; - _dragged = true; - - UpdateScrollBarPos(); - UpdateScrollBarVisible(); - if (_pageMode) - UpdatePageController(); - _onScroll.Call(); - } - - private void __touchEnd(EventContext context) - { - if (draggingPane == this) - draggingPane = null; - - _gestureFlag = 0; - - if (!_dragged || !_touchEffect) - { - _dragged = false; - return; - } - - _dragged = false; - _tweenStart = _container.xy; - - Vector2 endPos = _tweenStart; - bool flag = false; - if (_container.x > 0) - { - endPos.x = 0; - flag = true; - } - else if (_container.x < -_overlapSize.x) - { - endPos.x = -_overlapSize.x; - flag = true; - } - if (_container.y > 0) - { - endPos.y = 0; - flag = true; - } - else if (_container.y < -_overlapSize.y) - { - endPos.y = -_overlapSize.y; - flag = true; - } - - if (flag) - { - _tweenChange = endPos - _tweenStart; - if (_tweenChange.x < -UIConfig.touchDragSensitivity || _tweenChange.y < -UIConfig.touchDragSensitivity) - DispatchEvent("onPullDownRelease", null); - else if (_tweenChange.x > UIConfig.touchDragSensitivity || _tweenChange.y > UIConfig.touchDragSensitivity) - DispatchEvent("onPullUpRelease", null); - - if (_headerLockedSize > 0 && endPos[_refreshBarAxis] == 0) - { - endPos[_refreshBarAxis] = _headerLockedSize; - _tweenChange = endPos - _tweenStart; - } - else if (_footerLockedSize > 0 && endPos[_refreshBarAxis] == -_overlapSize[_refreshBarAxis]) - { - float max = _overlapSize[_refreshBarAxis]; - if (max == 0) - max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); - else - max += _footerLockedSize; - endPos[_refreshBarAxis] = -max; - _tweenChange = endPos - _tweenStart; - } - - _tweenDuration.Set(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); - } - else - { - //更新速度 - if (!_inertiaDisabled) - { - float elapsed = (Time.unscaledTime - _lastMoveTime) * 60 - 1; - if (elapsed > 1) - _velocity = _velocity * Mathf.Pow(0.833f, elapsed); - - //根据速度计算目标位置和需要时间 - endPos = UpdateTargetAndDuration(_tweenStart); - } - else - _tweenDuration.Set(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); - Vector2 oldChange = endPos - _tweenStart; - - //调整目标位置 - LoopCheckingTarget(ref endPos); - if (_pageMode || _snapToItem) - AlignPosition(ref endPos, true); - - _tweenChange = endPos - _tweenStart; - if (_tweenChange.x == 0 && _tweenChange.y == 0) - { - UpdateScrollBarVisible(); - return; - } - - //如果目标位置已调整,随之调整需要时间 - if (_pageMode || _snapToItem) - { - FixDuration(0, oldChange.x); - FixDuration(1, oldChange.y); - } - } - - StartTween(2); - } - - private void __mouseWheel(EventContext context) - { - if (!_mouseWheelEnabled) - return; - - InputEvent evt = context.inputEvent; - float delta = evt.mouseWheelDelta / Stage.devicePixelRatio; - if (_snapToItem && Mathf.Abs(delta) < 1) - delta = Mathf.Sign(delta); - - if (_overlapSize.x > 0 && _overlapSize.y == 0) - { - float step = _pageMode ? _pageSize.x : _scrollStep; - SetPosX(_xPos + step * delta, false); - } - else - { - float step = _pageMode ? _pageSize.y : _scrollStep; - SetPosY(_yPos + step * delta, false); - } - } - - private void __rollOver() - { - _hover = true; - UpdateScrollBarVisible(); - } - - private void __rollOut() - { - _hover = false; - UpdateScrollBarVisible(); - } - - internal void UpdateClipSoft() - { - Vector2 softness = _owner.clipSoftness; - if (softness.x != 0 || softness.y != 0) - { - _maskContainer.clipSoftness = new Vector4( - (_container.x >= 0 || !_softnessOnTopOrLeftSide) ? 0 : softness.x, - (_container.y >= 0 || !_softnessOnTopOrLeftSide) ? 0 : softness.y, - (-_container.x - _overlapSize.x >= 0) ? 0 : softness.x, - (-_container.y - _overlapSize.y >= 0) ? 0 : softness.y); - } - else - _maskContainer.clipSoftness = null; - } - - private void UpdateScrollBarPos() - { - if (_vtScrollBar != null) - _vtScrollBar.setScrollPerc(_overlapSize.y == 0 ? 0 : Mathf.Clamp(-_container.y, 0, _overlapSize.y) / _overlapSize.y); - - if (_hzScrollBar != null) - _hzScrollBar.setScrollPerc(_overlapSize.x == 0 ? 0 : Mathf.Clamp(-_container.x, 0, _overlapSize.x) / _overlapSize.x); - - UpdateClipSoft(); - CheckRefreshBar(); - } - - public void UpdateScrollBarVisible() - { - if (_vtScrollBar != null) - { - if (_viewSize.y <= _vtScrollBar.minSize || _vScrollNone) - _vtScrollBar.displayObject.visible = false; - else - UpdateScrollBarVisible2(_vtScrollBar); - } - - if (_hzScrollBar != null) - { - if (_viewSize.x <= _hzScrollBar.minSize || _hScrollNone) - _hzScrollBar.displayObject.visible = false; - else - UpdateScrollBarVisible2(_hzScrollBar); - } - } - - private void UpdateScrollBarVisible2(GScrollBar bar) - { - if (_scrollBarDisplayAuto) - GTween.Kill(bar, TweenPropType.Alpha, false); - - if (_scrollBarDisplayAuto && !_hover && _tweening == 0 && !_dragged && !bar.gripDragging) - { - if (bar.displayObject.visible) - GTween.To(1, 0, 0.5f).SetDelay(0.5f).OnComplete(_hideScrollBarDelegate).SetTarget(bar, TweenPropType.Alpha); - } - else - { - bar.alpha = 1; - bar.displayObject.visible = true; - } - } - - private void __barTweenComplete(GTweener tweener) - { - GObject bar = (GObject)tweener.target; - bar.alpha = 1; - bar.displayObject.visible = false; - } - - float GetLoopPartSize(float division, int axis) - { - return (_contentSize[axis] + (axis == 0 ? ((GList)_owner).columnGap : ((GList)_owner).lineGap)) / division; - } - - /// - /// 对当前的滚动位置进行循环滚动边界检查。当到达边界时,回退一半内容区域(循环滚动内容大小通常是真实内容大小的偶数倍)。 - /// - /// - bool LoopCheckingCurrent() - { - bool changed = false; - if (_loop == 1 && _overlapSize.x > 0) - { - if (_xPos < 0.001f) - { - _xPos += GetLoopPartSize(2, 0); - changed = true; - } - else if (_xPos >= _overlapSize.x) - { - _xPos -= GetLoopPartSize(2, 0); - changed = true; - } - } - else if (_loop == 2 && _overlapSize.y > 0) - { - if (_yPos < 0.001f) - { - _yPos += GetLoopPartSize(2, 1); - changed = true; - } - else if (_yPos >= _overlapSize.y) - { - _yPos -= GetLoopPartSize(2, 1); - changed = true; - } - } - - if (changed) - _container.SetXY((int)-_xPos, (int)-_yPos); - - return changed; - } - - /// - /// 对目标位置进行循环滚动边界检查。当到达边界时,回退一半内容区域(循环滚动内容大小通常是真实内容大小的偶数倍)。 - /// - /// - void LoopCheckingTarget(ref Vector2 endPos) - { - if (_loop == 1) - LoopCheckingTarget(ref endPos, 0); - - if (_loop == 2) - LoopCheckingTarget(ref endPos, 1); - } - - void LoopCheckingTarget(ref Vector2 endPos, int axis) - { - if (endPos[axis] > 0) - { - float halfSize = GetLoopPartSize(2, axis); - float tmp = _tweenStart[axis] - halfSize; - if (tmp <= 0 && tmp >= -_overlapSize[axis]) - { - endPos[axis] -= halfSize; - _tweenStart[axis] = tmp; - } - } - else if (endPos[axis] < -_overlapSize[axis]) - { - float halfSize = GetLoopPartSize(2, axis); - float tmp = _tweenStart[axis] + halfSize; - if (tmp <= 0 && tmp >= -_overlapSize[axis]) - { - endPos[axis] += halfSize; - _tweenStart[axis] = tmp; - } - } - } - - void LoopCheckingNewPos(ref float value, int axis) - { - if (_overlapSize[axis] == 0) - return; - - float pos = axis == 0 ? _xPos : _yPos; - bool changed = false; - if (value < 0.001f) - { - value += GetLoopPartSize(2, axis); - if (value > pos) - { - float v = GetLoopPartSize(6, axis); - v = Mathf.CeilToInt((value - pos) / v) * v; - pos = Mathf.Clamp(pos + v, 0, _overlapSize[axis]); - changed = true; - } - } - else if (value >= _overlapSize[axis]) - { - value -= GetLoopPartSize(2, axis); - if (value < pos) - { - float v = GetLoopPartSize(6, axis); - v = Mathf.CeilToInt((pos - value) / v) * v; - pos = Mathf.Clamp(pos - v, 0, _overlapSize[axis]); - changed = true; - } - } - - if (changed) - { - if (axis == 0) - _container.x = -(int)pos; - else - _container.y = -(int)pos; - } - } - - /// - /// 从oldPos滚动至pos,调整pos位置对齐页面、对齐item等(如果需要)。 - /// - /// - /// - void AlignPosition(ref Vector2 pos, bool inertialScrolling) - { - if (_pageMode) - { - pos.x = AlignByPage(pos.x, 0, inertialScrolling); - pos.y = AlignByPage(pos.y, 1, inertialScrolling); - } - else if (_snapToItem) - { - float tmpX = -pos.x; - float tmpY = -pos.y; - float xDir = 0; - float yDir = 0; - if (inertialScrolling) - { - xDir = pos.x - _containerPos.x; - yDir = pos.y - _containerPos.y; - } - _owner.GetSnappingPositionWithDir(ref tmpX, ref tmpY, xDir, yDir); - if (pos.x < 0 && pos.x > -_overlapSize.x) - pos.x = -tmpX; - if (pos.y < 0 && pos.y > -_overlapSize.y) - pos.y = -tmpY; - } - } - - /// - /// 从oldPos滚动至pos,调整目标位置到对齐页面。 - /// - /// - /// - /// - /// - float AlignByPage(float pos, int axis, bool inertialScrolling) - { - int page; - - if (pos > 0) - page = 0; - else if (pos < -_overlapSize[axis]) - page = Mathf.CeilToInt(_contentSize[axis] / _pageSize[axis]) - 1; - else - { - page = Mathf.FloorToInt(-pos / _pageSize[axis]); - float change = inertialScrolling ? (pos - _containerPos[axis]) : (pos - _container.xy[axis]); - float testPageSize = Mathf.Min(_pageSize[axis], _contentSize[axis] - (page + 1) * _pageSize[axis]); - float delta = -pos - page * _pageSize[axis]; - - //页面吸附策略 - if (Mathf.Abs(change) > _pageSize[axis])//如果滚动距离超过1页,则需要超过页面的一半,才能到更下一页 - { - if (delta > testPageSize * 0.5f) - page++; - } - else //否则只需要页面的1/3,当然,需要考虑到左移和右移的情况 - { - if (delta > testPageSize * (change < 0 ? UIConfig.defaultScrollPagingThreshold : (1 - UIConfig.defaultScrollPagingThreshold))) - page++; - } - - //重新计算终点 - pos = -page * _pageSize[axis]; - if (pos < -_overlapSize[axis]) //最后一页未必有pageSize那么大 - pos = -_overlapSize[axis]; - } - - //惯性滚动模式下,会增加判断尽量不要滚动超过一页 - if (inertialScrolling) - { - float oldPos = _tweenStart[axis]; - int oldPage; - if (oldPos > 0) - oldPage = 0; - else if (oldPos < -_overlapSize[axis]) - oldPage = Mathf.CeilToInt(_contentSize[axis] / _pageSize[axis]) - 1; - else - oldPage = Mathf.FloorToInt(-oldPos / _pageSize[axis]); - int startPage = Mathf.FloorToInt(-_containerPos[axis] / _pageSize[axis]); - if (Mathf.Abs(page - startPage) > 1 && Mathf.Abs(oldPage - startPage) <= 1) - { - if (page > startPage) - page = startPage + 1; - else - page = startPage - 1; - pos = -page * _pageSize[axis]; - } - } - - return pos; - } - - /// - /// 根据当前速度,计算滚动的目标位置,以及到达时间。 - /// - /// - /// - Vector2 UpdateTargetAndDuration(Vector2 orignPos) - { - Vector2 ret = Vector2.zero; - ret.x = UpdateTargetAndDuration(orignPos.x, 0); - ret.y = UpdateTargetAndDuration(orignPos.y, 1); - return ret; - } - - float UpdateTargetAndDuration(float pos, int axis) - { - float v = _velocity[axis]; - float duration = 0; - - if (pos > 0) - pos = 0; - else if (pos < -_overlapSize[axis]) - pos = -_overlapSize[axis]; - else - { - //以屏幕像素为基准 - float v2 = Mathf.Abs(v) * _velocityScale; - //在移动设备上,需要对不同分辨率做一个适配,我们的速度判断以1136分辨率为基准 - if (Stage.touchScreen) - v2 *= 1136f / Mathf.Max(Screen.width, Screen.height); - //这里有一些阈值的处理,因为在低速内,不希望产生较大的滚动(甚至不滚动) - float ratio = 0; - if (_pageMode || !Stage.touchScreen) - { - if (v2 > 500) - ratio = Mathf.Pow((v2 - 500) / 500, 2); - } - else - { - if (v2 > 1000) - ratio = Mathf.Pow((v2 - 1000) / 1000, 2); - } - - if (ratio != 0) - { - if (ratio > 1) - ratio = 1; - - v2 *= ratio; - v *= ratio; - _velocity[axis] = v; - - //算法:v*(_decelerationRate的n次幂)= 60,即在n帧后速度降为60(假设每秒60帧)。 - duration = Mathf.Log(60 / v2, _decelerationRate) / 60; - - //计算距离要使用本地速度 - //理论公式貌似滚动的距离不够,改为经验公式 - //float change = (int)((v/ 60 - 1) / (1 - _decelerationRate)); - float change = (int)(v * duration * 0.4f); - pos += change; - } - } - - if (duration < TWEEN_TIME_DEFAULT) - duration = TWEEN_TIME_DEFAULT; - _tweenDuration[axis] = duration; - - return pos; - } - - /// - /// 根据修改后的tweenChange重新计算减速时间。 - /// - void FixDuration(int axis, float oldChange) - { - if (_tweenChange[axis] == 0 || Mathf.Abs(_tweenChange[axis]) >= Mathf.Abs(oldChange)) - return; - - float newDuration = Mathf.Abs(_tweenChange[axis] / oldChange) * _tweenDuration[axis]; - if (newDuration < TWEEN_TIME_DEFAULT) - newDuration = TWEEN_TIME_DEFAULT; - - _tweenDuration[axis] = newDuration; - } - - void StartTween(int type) - { - _tweenTime.Set(0, 0); - _tweening = type; - Timers.inst.AddUpdate(_tweenUpdateDelegate); - - UpdateScrollBarVisible(); - } - - void KillTween() - { - if (_tweening == 1) //取消类型为1的tween需立刻设置到终点 - { - _container.xy = _tweenStart + _tweenChange; - _onScroll.Call(); - } - - _tweening = 0; - Timers.inst.Remove(_tweenUpdateDelegate); - - UpdateScrollBarVisible(); - - _onScrollEnd.Call(); - } - - void CheckRefreshBar() - { - if (_header == null && _footer == null) - return; - - float pos = _container.xy[_refreshBarAxis]; - if (_header != null) - { - if (pos > 0) - { - if (_header.displayObject.parent == null) - _maskContainer.AddChildAt(_header.displayObject, 0); - Vector2 vec; - - vec = _header.size; - vec[_refreshBarAxis] = pos; - _header.size = vec; - } - else - { - if (_header.displayObject.parent != null) - _maskContainer.RemoveChild(_header.displayObject); - } - } - - if (_footer != null) - { - float max = _overlapSize[_refreshBarAxis]; - if (pos < -max || max == 0 && _footerLockedSize > 0) - { - if (_footer.displayObject.parent == null) - _maskContainer.AddChildAt(_footer.displayObject, 0); - - Vector2 vec; - - vec = _footer.xy; - if (max > 0) - vec[_refreshBarAxis] = pos + _contentSize[_refreshBarAxis]; - else - vec[_refreshBarAxis] = Mathf.Max(Mathf.Min(pos + _viewSize[_refreshBarAxis], _viewSize[_refreshBarAxis] - _footerLockedSize), _viewSize[_refreshBarAxis] - _contentSize[_refreshBarAxis]); - _footer.xy = vec; - - vec = _footer.size; - if (max > 0) - vec[_refreshBarAxis] = -max - pos; - else - vec[_refreshBarAxis] = _viewSize[_refreshBarAxis] - _footer.xy[_refreshBarAxis]; - _footer.size = vec; - } - else - { - if (_footer.displayObject.parent != null) - _maskContainer.RemoveChild(_footer.displayObject); - } - } - } - - void TweenUpdate(object param) - { - if (_owner.displayObject == null || _owner.displayObject.isDisposed) - { - Timers.inst.Remove(_tweenUpdateDelegate); - return; - } - - float nx = RunTween(0); - float ny = RunTween(1); - - _container.SetXY(nx, ny); - - if (_tweening == 2) - { - if (_overlapSize.x > 0) - _xPos = Mathf.Clamp(-nx, 0, _overlapSize.x); - if (_overlapSize.y > 0) - _yPos = Mathf.Clamp(-ny, 0, _overlapSize.y); - - if (_pageMode) - UpdatePageController(); - } - - if (_tweenChange.x == 0 && _tweenChange.y == 0) - { - _tweening = 0; - Timers.inst.Remove(_tweenUpdateDelegate); - - LoopCheckingCurrent(); - - UpdateScrollBarPos(); - UpdateScrollBarVisible(); - - _onScroll.Call(); - _onScrollEnd.Call(); - } - else - { - UpdateScrollBarPos(); - _onScroll.Call(); - } - } - - float RunTween(int axis) - { - float newValue; - if (_tweenChange[axis] != 0) - { - _tweenTime[axis] += Time.unscaledDeltaTime; - if (_tweenTime[axis] >= _tweenDuration[axis]) - { - newValue = _tweenStart[axis] + _tweenChange[axis]; - _tweenChange[axis] = 0; - } - else - { - float ratio = EaseFunc(_tweenTime[axis], _tweenDuration[axis]); - newValue = _tweenStart[axis] + (int)(_tweenChange[axis] * ratio); - } - - float threshold1 = 0; - float threshold2 = -_overlapSize[axis]; - if (_headerLockedSize > 0 && _refreshBarAxis == axis) - threshold1 = _headerLockedSize; - if (_footerLockedSize > 0 && _refreshBarAxis == axis) - { - float max = _overlapSize[_refreshBarAxis]; - if (max == 0) - max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); - else - max += _footerLockedSize; - threshold2 = -max; - } - - if (_tweening == 2 && _bouncebackEffect) - { - if (newValue > 20 + threshold1 && _tweenChange[axis] > 0 - || newValue > threshold1 && _tweenChange[axis] == 0)//开始回弹 - { - _tweenTime[axis] = 0; - _tweenDuration[axis] = TWEEN_TIME_DEFAULT; - _tweenChange[axis] = -newValue + threshold1; - _tweenStart[axis] = newValue; - } - else if (newValue < threshold2 - 20 && _tweenChange[axis] < 0 - || newValue < threshold2 && _tweenChange[axis] == 0)//开始回弹 - { - _tweenTime[axis] = 0; - _tweenDuration[axis] = TWEEN_TIME_DEFAULT; - _tweenChange[axis] = threshold2 - newValue; - _tweenStart[axis] = newValue; - } - } - else - { - if (newValue > threshold1) - { - newValue = threshold1; - _tweenChange[axis] = 0; - } - else if (newValue < threshold2) - { - newValue = threshold2; - _tweenChange[axis] = 0; - } - } - } - else - newValue = _container.xy[axis]; - - return newValue; - } - - static float EaseFunc(float t, float d) - { - return (t = t / d - 1) * t * t + 1;//cubicOut - } - } -} +using System; +using UnityEngine; +using FairyGUI.Utils; + +namespace FairyGUI +{ + /// + /// + /// + public class ScrollPane : EventDispatcher + { + /// + /// 当前被拖拽的滚动面板。同一时间只能有一个在进行此操作。 + /// + public static ScrollPane draggingPane { get; private set; } + + ScrollType _scrollType; + float _scrollStep; + float _decelerationRate; + Margin _scrollBarMargin; + bool _bouncebackEffect; + bool _touchEffect; + bool _scrollBarDisplayAuto; + bool _vScrollNone; + bool _hScrollNone; + bool _needRefresh; + int _refreshBarAxis; + + bool _displayOnLeft; + bool _snapToItem; + internal bool _displayInDemand; + bool _mouseWheelEnabled; + bool _softnessOnTopOrLeftSide; + bool _pageMode; + Vector2 _pageSize; + bool _inertiaDisabled; + bool _maskDisabled; + bool _floating; + bool _dontClipMargin; + + float _xPos; + float _yPos; + + Vector2 _viewSize; + Vector2 _contentSize; + Vector2 _overlapSize; + Vector2 _containerPos; + Vector2 _beginTouchPos; + Vector2 _lastTouchPos; + Vector2 _lastTouchGlobalPos; + Vector2 _velocity; + float _velocityScale; + float _lastMoveTime; + bool _dragged; + bool _isHoldAreaDone; + int _aniFlag; + internal int _loop; + int _headerLockedSize; + int _footerLockedSize; + bool _hover; + + int _tweening; + Vector2 _tweenStart; + Vector2 _tweenChange; + Vector2 _tweenTime; + Vector2 _tweenDuration; + + Action _refreshDelegate; + TimerCallback _tweenUpdateDelegate; + GTweenCallback1 _hideScrollBarDelegate; + + GComponent _owner; + Container _maskContainer; + Container _container; + GScrollBar _hzScrollBar; + GScrollBar _vtScrollBar; + GComponent _header; + GComponent _footer; + Controller _pageController; + + EventListener _onScroll; + EventListener _onScrollEnd; + EventListener _onPullDownRelease; + EventListener _onPullUpRelease; + + static int _gestureFlag; + + public static float TWEEN_TIME_GO = 0.3f; //调用SetPos(ani)时使用的缓动时间 + public static float TWEEN_TIME_DEFAULT = 0.3f; //惯性滚动的最小缓动时间 + public static float PULL_RATIO = 0.5f; //下拉过顶或者上拉过底时允许超过的距离占显示区域的比例 + + public ScrollPane(GComponent owner) + { + _onScroll = new EventListener(this, "onScroll"); + _onScrollEnd = new EventListener(this, "onScrollEnd"); + + _scrollStep = UIConfig.defaultScrollStep; + _softnessOnTopOrLeftSide = UIConfig.allowSoftnessOnTopOrLeftSide; + _decelerationRate = UIConfig.defaultScrollDecelerationRate; + _touchEffect = UIConfig.defaultScrollTouchEffect; + _bouncebackEffect = UIConfig.defaultScrollBounceEffect; + _mouseWheelEnabled = true; + _pageSize = Vector2.one; + + _refreshDelegate = Refresh; + _tweenUpdateDelegate = TweenUpdate; + _hideScrollBarDelegate = __barTweenComplete; + + _owner = owner; + + _maskContainer = new Container(); + _owner.rootContainer.AddChild(_maskContainer); + + _container = _owner.container; + _container.SetXY(0, 0); + _maskContainer.AddChild(_container); + + _owner.rootContainer.onMouseWheel.Add(__mouseWheel); + _owner.rootContainer.onTouchBegin.Add(__touchBegin); + _owner.rootContainer.onTouchMove.Add(__touchMove); + _owner.rootContainer.onTouchEnd.Add(__touchEnd); + } + + public void Setup(ByteBuffer buffer) + { + _scrollType = (ScrollType)buffer.ReadByte(); + ScrollBarDisplayType scrollBarDisplay = (ScrollBarDisplayType)buffer.ReadByte(); + int flags = buffer.ReadInt(); + + if (buffer.ReadBool()) + { + _scrollBarMargin.top = buffer.ReadInt(); + _scrollBarMargin.bottom = buffer.ReadInt(); + _scrollBarMargin.left = buffer.ReadInt(); + _scrollBarMargin.right = buffer.ReadInt(); + } + + string vtScrollBarRes = buffer.ReadS(); + string hzScrollBarRes = buffer.ReadS(); + string headerRes = buffer.ReadS(); + string footerRes = buffer.ReadS(); + + _displayOnLeft = (flags & 1) != 0; + _snapToItem = (flags & 2) != 0; + _displayInDemand = (flags & 4) != 0; + _pageMode = (flags & 8) != 0; + if ((flags & 16) != 0) + _touchEffect = true; + else if ((flags & 32) != 0) + _touchEffect = false; + if ((flags & 64) != 0) + _bouncebackEffect = true; + else if ((flags & 128) != 0) + _bouncebackEffect = false; + _inertiaDisabled = (flags & 256) != 0; + _maskDisabled = (flags & 512) != 0; + _floating = (flags & 1024) != 0; + _dontClipMargin = (flags & 2048) != 0; + + if (scrollBarDisplay == ScrollBarDisplayType.Default) + { + if (Application.isMobilePlatform) + scrollBarDisplay = ScrollBarDisplayType.Auto; + else + scrollBarDisplay = UIConfig.defaultScrollBarDisplay; + } + + if (scrollBarDisplay != ScrollBarDisplayType.Hidden) + { + if (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) + { + string res = vtScrollBarRes != null ? vtScrollBarRes : UIConfig.verticalScrollBar; + if (!string.IsNullOrEmpty(res)) + { + _vtScrollBar = UIPackage.CreateObjectFromURL(res) as GScrollBar; + if (_vtScrollBar == null) + Debug.LogWarning("FairyGUI: cannot create scrollbar from " + res); + else + { + _vtScrollBar.SetScrollPane(this, true); + _owner.rootContainer.AddChild(_vtScrollBar.displayObject); + } + } + } + if (_scrollType == ScrollType.Both || _scrollType == ScrollType.Horizontal) + { + string res = hzScrollBarRes != null ? hzScrollBarRes : UIConfig.horizontalScrollBar; + if (!string.IsNullOrEmpty(res)) + { + _hzScrollBar = UIPackage.CreateObjectFromURL(res) as GScrollBar; + if (_hzScrollBar == null) + Debug.LogWarning("FairyGUI: cannot create scrollbar from " + res); + else + { + _hzScrollBar.SetScrollPane(this, false); + _owner.rootContainer.AddChild(_hzScrollBar.displayObject); + } + } + } + + _scrollBarDisplayAuto = scrollBarDisplay == ScrollBarDisplayType.Auto; + if (_scrollBarDisplayAuto) + { + if (_vtScrollBar != null) + _vtScrollBar.displayObject.visible = false; + if (_hzScrollBar != null) + _hzScrollBar.displayObject.visible = false; + + _owner.rootContainer.onRollOver.Add(__rollOver); + _owner.rootContainer.onRollOut.Add(__rollOut); + } + } + else + _mouseWheelEnabled = false; + + if (Application.isPlaying) + { + if (headerRes != null) + { + _header = (GComponent)UIPackage.CreateObjectFromURL(headerRes); + if (_header == null) + Debug.LogWarning("FairyGUI: cannot create scrollPane header from " + headerRes); + } + + if (footerRes != null) + { + _footer = (GComponent)UIPackage.CreateObjectFromURL(footerRes); + if (_footer == null) + Debug.LogWarning("FairyGUI: cannot create scrollPane footer from " + footerRes); + } + + if (_header != null || _footer != null) + _refreshBarAxis = (_scrollType == ScrollType.Both || _scrollType == ScrollType.Vertical) ? 1 : 0; + } + + SetSize(owner.width, owner.height); + } + + /// + /// + /// + public void Dispose() + { + RemoveEventListeners(); + + if (_tweening != 0) + Timers.inst.Remove(_tweenUpdateDelegate); + + if (draggingPane == this) + draggingPane = null; + + _pageController = null; + + if (_hzScrollBar != null) + _hzScrollBar.Dispose(); + if (_vtScrollBar != null) + _vtScrollBar.Dispose(); + if (_header != null) + _header.Dispose(); + if (_footer != null) + _footer.Dispose(); + } + + /// + /// Dispatched when scrolling. + /// 在滚动时派发该事件。 + /// + public EventListener onScroll + { + get { return _onScroll ?? (_onScroll = new EventListener(this, "onScroll")); } + } + + /// + /// 在滚动结束时派发该事件。 + /// + public EventListener onScrollEnd + { + get { return _onScrollEnd ?? (_onScrollEnd = new EventListener(this, "onScrollEnd")); } + } + + /// + /// 向下拉过上边缘后释放则派发该事件。 + /// + public EventListener onPullDownRelease + { + get { return _onPullDownRelease ?? (_onPullDownRelease = new EventListener(this, "onPullDownRelease")); } + } + + /// + /// 向上拉过下边缘后释放则派发该事件。 + /// + public EventListener onPullUpRelease + { + get { return _onPullUpRelease ?? (_onPullUpRelease = new EventListener(this, "onPullUpRelease")); } + } + + /// + /// + /// + public GComponent owner + { + get { return _owner; } + } + + /// + /// + /// + public GScrollBar hzScrollBar + { + get { return _hzScrollBar; } + } + + /// + /// + /// + public GScrollBar vtScrollBar + { + get { return _vtScrollBar; } + } + + /// + /// + /// + public GComponent header + { + get { return _header; } + } + + /// + /// + /// + public GComponent footer + { + get { return _footer; } + } + + /// + /// 滚动到达边缘时是否允许回弹效果。 + /// + public bool bouncebackEffect + { + get { return _bouncebackEffect; } + set { _bouncebackEffect = value; } + } + + /// + /// 是否允许拖拽内容区域进行滚动。 + /// + public bool touchEffect + { + get { return _touchEffect; } + set { _touchEffect = value; } + } + + /// + /// 是否允许惯性滚动。 + /// + public bool inertiaDisabled + { + get { return _inertiaDisabled; } + set { _inertiaDisabled = value; } + } + + /// + /// 是否允许在左/上边缘显示虚化效果。 + /// + public bool softnessOnTopOrLeftSide + { + get { return _softnessOnTopOrLeftSide; } + set { _softnessOnTopOrLeftSide = value; } + } + + /// + /// 当调用ScrollPane.scrollUp/Down/Left/Right时,或者点击滚动条的上下箭头时,滑动的距离。 + /// + public float scrollStep + { + get { return _scrollStep; } + set + { + _scrollStep = value; + if (_scrollStep == 0) + _scrollStep = UIConfig.defaultScrollStep; + } + } + + /// + /// 滚动位置是否保持贴近在某个元件的边缘。 + /// + public bool snapToItem + { + get { return _snapToItem; } + set { _snapToItem = value; } + } + + /// + /// 是否页面滚动模式。 + /// + public bool pageMode + { + get { return _pageMode; } + set { _pageMode = value; } + } + + /// + /// + /// + public Controller pageController + { + get { return _pageController; } + set { _pageController = value; } + } + + /// + /// 是否允许使用鼠标滚轮进行滚动。 + /// + public bool mouseWheelEnabled + { + get { return _mouseWheelEnabled; } + set { _mouseWheelEnabled = value; } + } + + /// + /// 当处于惯性滚动时减速的速率。默认值是UIConfig.defaultScrollDecelerationRate。 + /// 越接近1,减速越慢,意味着滑动的时间和距离更长。 + /// + public float decelerationRate + { + get { return _decelerationRate; } + set { _decelerationRate = value; } + } + + /// + /// + public bool isDragged + { + get { return _dragged; } + } + + /// + /// 当前X轴滚动位置百分比,0~1(包含)。 + /// + public float percX + { + get { return _overlapSize.x == 0 ? 0 : _xPos / _overlapSize.x; } + set { SetPercX(value, false); } + } + + /// + /// 设置当前X轴滚动位置百分比,0~1(包含)。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPercX(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + SetPosX(_overlapSize.x * Mathf.Clamp01(value), ani); + } + + /// + /// 当前Y轴滚动位置百分比,0~1(包含)。 + /// + public float percY + { + get { return _overlapSize.y == 0 ? 0 : _yPos / _overlapSize.y; } + set { SetPercY(value, false); } + } + + /// + /// 设置当前Y轴滚动位置百分比,0~1(包含)。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPercY(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + SetPosY(_overlapSize.y * Mathf.Clamp01(value), ani); + } + + /// + /// 当前X轴滚动位置,值范围是viewWidth与contentWidth之差。 + /// + public float posX + { + get { return _xPos; } + set { SetPosX(value, false); } + } + + /// + /// 设置当前X轴滚动位置。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPosX(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + + if (_loop == 1) + LoopCheckingNewPos(ref value, 0); + + value = Mathf.Clamp(value, 0, _overlapSize.x); + if (value != _xPos) + { + _xPos = value; + PosChanged(ani); + } + } + + /// + /// 当前Y轴滚动位置,值范围是viewHeight与contentHeight之差。 + /// + public float posY + { + get { return _yPos; } + set { SetPosY(value, false); } + } + + /// + /// 设置当前Y轴滚动位置。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetPosY(float value, bool ani) + { + _owner.EnsureBoundsCorrect(); + + if (_loop == 2) + LoopCheckingNewPos(ref value, 1); + + value = Mathf.Clamp(value, 0, _overlapSize.y); + if (value != _yPos) + { + _yPos = value; + PosChanged(ani); + } + } + + /// + /// 返回当前滚动位置是否在最下边。 + /// + public bool isBottomMost + { + get { return _yPos == _overlapSize.y || _overlapSize.y == 0; } + } + + /// + /// 返回当前滚动位置是否在最右边。 + /// + public bool isRightMost + { + get { return _xPos == _overlapSize.x || _overlapSize.x == 0; } + } + + /// + /// 如果处于分页模式,返回当前在X轴的页码。 + /// + public int currentPageX + { + get + { + if (!_pageMode) + return 0; + + int page = Mathf.FloorToInt(_xPos / _pageSize.x); + if (_xPos - page * _pageSize.x > _pageSize.x * 0.5f) + page++; + + return page; + } + set + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.x > 0) + this.SetPosX(value * _pageSize.x, false); + } + } + + /// + /// 如果处于分页模式,可设置X轴的页码。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetCurrentPageX(int value, bool ani) + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.x > 0) + this.SetPosX(value * _pageSize.x, ani); + } + + /// + /// 如果处于分页模式,返回当前在Y轴的页码。 + /// + public int currentPageY + { + get + { + if (!_pageMode) + return 0; + + int page = Mathf.FloorToInt(_yPos / _pageSize.y); + if (_yPos - page * _pageSize.y > _pageSize.y * 0.5f) + page++; + + return page; + } + set + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.y > 0) + this.SetPosY(value * _pageSize.y, false); + } + } + + /// + /// 如果处于分页模式,可设置Y轴的页码。 + /// + /// + /// 是否使用缓动到达目标。 + public void SetCurrentPageY(int value, bool ani) + { + if (!_pageMode) + return; + + _owner.EnsureBoundsCorrect(); + + if (_overlapSize.y > 0) + this.SetPosY(value * _pageSize.y, ani); + } + + /// + /// 这个值与PosX不同在于,他反映的是实时位置,而PosX在有缓动过程的情况下只是终值。 + /// + public float scrollingPosX + { + get + { + return Mathf.Clamp(-_container.x, 0, _overlapSize.x); + } + } + + /// + /// 这个值与PosY不同在于,他反映的是实时位置,而PosY在有缓动过程的情况下只是终值。 + /// + public float scrollingPosY + { + get + { + return Mathf.Clamp(-_container.y, 0, _overlapSize.y); + } + } + + /// + /// 显示内容宽度。 + /// + public float contentWidth + { + get + { + return _contentSize.x; + } + } + + /// + /// 显示内容高度。 + /// + public float contentHeight + { + get + { + return _contentSize.y; + } + } + + /// + /// 显示区域宽度。 + /// + public float viewWidth + { + get { return _viewSize.x; } + set + { + value = value + _owner.margin.left + _owner.margin.right; + if (_vtScrollBar != null && !_floating) + value += _vtScrollBar.width; + _owner.width = value; + } + } + + /// + /// 显示区域高度。 + /// + public float viewHeight + { + get { return _viewSize.y; } + set + { + value = value + _owner.margin.top + _owner.margin.bottom; + if (_hzScrollBar != null && !_floating) + value += _hzScrollBar.height; + _owner.height = value; + } + } + + /// + /// + /// + public void ScrollTop() + { + ScrollTop(false); + } + + /// + /// + /// + /// + public void ScrollTop(bool ani) + { + this.SetPercY(0, ani); + } + + /// + /// + /// + public void ScrollBottom() + { + ScrollBottom(false); + } + + /// + /// + /// + /// + public void ScrollBottom(bool ani) + { + this.SetPercY(1, ani); + } + + /// + /// + /// + public void ScrollUp() + { + ScrollUp(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollUp(float ratio, bool ani) + { + if (_pageMode) + SetPosY(_yPos - _pageSize.y * ratio, ani); + else + SetPosY(_yPos - _scrollStep * ratio, ani); + } + + /// + /// + /// + public void ScrollDown() + { + ScrollDown(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollDown(float ratio, bool ani) + { + if (_pageMode) + SetPosY(_yPos + _pageSize.y * ratio, ani); + else + SetPosY(_yPos + _scrollStep * ratio, ani); + } + + /// + /// + /// + public void ScrollLeft() + { + ScrollLeft(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollLeft(float ratio, bool ani) + { + if (_pageMode) + SetPosX(_xPos - _pageSize.x * ratio, ani); + else + SetPosX(_xPos - _scrollStep * ratio, ani); + } + + /// + /// + /// + public void ScrollRight() + { + ScrollRight(1, false); + } + + /// + /// + /// + /// + /// + public void ScrollRight(float ratio, bool ani) + { + if (_pageMode) + SetPosX(_xPos + _pageSize.x * ratio, ani); + else + SetPosX(_xPos + _scrollStep * ratio, ani); + } + + /// + /// + /// + /// obj can be any object on stage, not limited to the direct child of this container. + public void ScrollToView(GObject obj) + { + ScrollToView(obj, false); + } + + /// + /// + /// + /// obj can be any object on stage, not limited to the direct child of this container. + /// If moving to target position with animation + public void ScrollToView(GObject obj, bool ani) + { + ScrollToView(obj, ani, false); + } + + /// + /// + /// + /// obj can be any object on stage, not limited to the direct child of this container. + /// If moving to target position with animation + /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. + public void ScrollToView(GObject obj, bool ani, bool setFirst) + { + _owner.EnsureBoundsCorrect(); + if (_needRefresh) + Refresh(); + + Rect rect = new Rect(obj.x, obj.y, obj.width, obj.height); + if (obj.parent != _owner) + rect = obj.parent.TransformRect(rect, _owner); + ScrollToView(rect, ani, setFirst); + } + + /// + /// + /// + /// Rect in local coordinates + /// If moving to target position with animation + /// If true, scroll to make the target on the top/left; If false, scroll to make the target any position in view. + public void ScrollToView(Rect rect, bool ani, bool setFirst) + { + _owner.EnsureBoundsCorrect(); + if (_needRefresh) + Refresh(); + + if (_overlapSize.y > 0) + { + float bottom = _yPos + _viewSize.y; + if (setFirst || rect.y <= _yPos || rect.height >= _viewSize.y) + { + if (rect.yMax >= bottom) //if an item size is large than viewSize, dont scroll + return; + + if (_pageMode) + this.SetPosY(Mathf.Floor(rect.y / _pageSize.y) * _pageSize.y, ani); + else + SetPosY(rect.y, ani); + } + else if (rect.yMax > bottom) + { + if (_pageMode) + this.SetPosY(Mathf.Floor(rect.y / _pageSize.y) * _pageSize.y, ani); + else if (rect.height <= _viewSize.y / 2) + SetPosY(rect.y + rect.height * 2 - _viewSize.y, ani); + else + SetPosY(rect.y + Mathf.Min(rect.height - _viewSize.y, 0), ani); + } + } + if (_overlapSize.x > 0) + { + float right = _xPos + _viewSize.x; + if (setFirst || rect.x <= _xPos || rect.width >= _viewSize.x) + { + if (rect.xMax >= right) //if an item size is large than viewSize, dont scroll + return; + + if (_pageMode) + this.SetPosX(Mathf.Floor(rect.x / _pageSize.x) * _pageSize.x, ani); + SetPosX(rect.x, ani); + } + else if (rect.xMax > right) + { + if (_pageMode) + this.SetPosX(Mathf.Floor(rect.x / _pageSize.x) * _pageSize.x, ani); + else if (rect.width <= _viewSize.x / 2) + SetPosX(rect.x + rect.width * 2 - _viewSize.x, ani); + else + SetPosX(rect.x + Mathf.Min(rect.width - _viewSize.x, 0), ani); + } + } + + if (!ani && _needRefresh) + Refresh(); + } + + /// + /// + /// + /// obj must be the direct child of this container + /// + public bool IsChildInView(GObject obj) + { + if (_overlapSize.y > 0) + { + float dist = obj.y + _container.y; + if (dist <= -obj.height || dist >= _viewSize.y) + return false; + } + if (_overlapSize.x > 0) + { + float dist = obj.x + _container.x; + if (dist <= -obj.width || dist >= _viewSize.x) + return false; + } + + return true; + } + + /// + /// 当滚动面板处于拖拽滚动状态或即将进入拖拽状态时,可以调用此方法停止或禁止本次拖拽。 + /// + public void CancelDragging() + { + Stage.inst.RemoveTouchMonitor(_owner.rootContainer); + + if (draggingPane == this) + draggingPane = null; + + _gestureFlag = 0; + _dragged = false; + } + + /// + /// 设置Header固定显示。如果size为0,则取消固定显示。 + /// + /// Header显示的大小 + public void LockHeader(int size) + { + if (_headerLockedSize == size) + return; + + _headerLockedSize = size; + if (!isDispatching("onPullDownRelease") && _container.xy[_refreshBarAxis] >= 0) + { + _tweenStart = _container.xy; + _tweenChange = Vector2.zero; + _tweenChange[_refreshBarAxis] = _headerLockedSize - _tweenStart[_refreshBarAxis]; + _tweenDuration = new Vector2(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + StartTween(2); + } + } + + /// + /// 设置Footer固定显示。如果size为0,则取消固定显示。 + /// + /// + public void LockFooter(int size) + { + if (_footerLockedSize == size) + return; + + _footerLockedSize = size; + if (!isDispatching("onPullUpRelease") && _container.xy[_refreshBarAxis] <= -_overlapSize[_refreshBarAxis]) + { + _tweenStart = _container.xy; + _tweenChange = Vector2.zero; + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + _tweenChange[_refreshBarAxis] = -max - _tweenStart[_refreshBarAxis]; + _tweenDuration = new Vector2(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + StartTween(2); + } + } + + internal void OnOwnerSizeChanged() + { + SetSize(_owner.width, _owner.height); + PosChanged(false); + } + + internal void HandleControllerChanged(Controller c) + { + if (_pageController == c) + { + if (_scrollType == ScrollType.Horizontal) + this.SetCurrentPageX(c.selectedIndex, true); + else + this.SetCurrentPageY(c.selectedIndex, true); + } + } + + void UpdatePageController() + { + if (_pageController != null && !_pageController.changing) + { + int index; + if (_scrollType == ScrollType.Horizontal) + index = this.currentPageX; + else + index = this.currentPageY; + if (index < _pageController.pageCount) + { + Controller c = _pageController; + _pageController = null; //防止HandleControllerChanged的调用 + c.selectedIndex = index; + _pageController = c; + } + } + } + + internal void AdjustMaskContainer() + { + float mx, my; + if (_displayOnLeft && _vtScrollBar != null && !_floating) + mx = Mathf.FloorToInt(_owner.margin.left + _vtScrollBar.width); + else + mx = _owner.margin.left; + my = _owner.margin.top; + mx += _owner._alignOffset.x; + my += _owner._alignOffset.y; + + _maskContainer.SetXY(mx, my); + } + + void SetSize(float aWidth, float aHeight) + { + AdjustMaskContainer(); + + if (_hzScrollBar != null) + { + _hzScrollBar.y = aHeight - _hzScrollBar.height; + if (_vtScrollBar != null) + { + _hzScrollBar.width = aWidth - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; + if (_displayOnLeft) + _hzScrollBar.x = _scrollBarMargin.left + _vtScrollBar.width; + else + _hzScrollBar.x = _scrollBarMargin.left; + } + else + { + _hzScrollBar.width = aWidth - _scrollBarMargin.left - _scrollBarMargin.right; + _hzScrollBar.x = _scrollBarMargin.left; + } + } + if (_vtScrollBar != null) + { + if (!_displayOnLeft) + _vtScrollBar.x = aWidth - _vtScrollBar.width; + if (_hzScrollBar != null) + _vtScrollBar.height = aHeight - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; + else + _vtScrollBar.height = aHeight - _scrollBarMargin.top - _scrollBarMargin.bottom; + _vtScrollBar.y = _scrollBarMargin.top; + } + + _viewSize.x = aWidth; + _viewSize.y = aHeight; + if (_hzScrollBar != null && !_floating) + _viewSize.y -= _hzScrollBar.height; + if (_vtScrollBar != null && !_floating) + _viewSize.x -= _vtScrollBar.width; + _viewSize.x -= (_owner.margin.left + _owner.margin.right); + _viewSize.y -= (_owner.margin.top + _owner.margin.bottom); + + _viewSize.x = Mathf.Max(1, _viewSize.x); + _viewSize.y = Mathf.Max(1, _viewSize.y); + _pageSize.x = _viewSize.x; + _pageSize.y = _viewSize.y; + + HandleSizeChanged(); + } + + internal void SetContentSize(float aWidth, float aHeight) + { + if (Mathf.Approximately(_contentSize.x, aWidth) && Mathf.Approximately(_contentSize.y, aHeight)) + return; + + _contentSize.x = aWidth; + _contentSize.y = aHeight; + HandleSizeChanged(); + } + + /// + /// 内部使用。由虚拟列表调用。在滚动时修改显示内容的大小,需要进行修正,避免滚动跳跃。 + /// + /// + /// + /// + /// + internal void ChangeContentSizeOnScrolling(float deltaWidth, float deltaHeight, float deltaPosX, float deltaPosY) + { + bool isRightmost = _xPos == _overlapSize.x; + bool isBottom = _yPos == _overlapSize.y; + + _contentSize.x += deltaWidth; + _contentSize.y += deltaHeight; + HandleSizeChanged(); + + if (_tweening == 1) + { + //如果原来滚动位置是贴边,加入处理继续贴边。 + if (deltaWidth != 0 && isRightmost && _tweenChange.x < 0) + { + _xPos = _overlapSize.x; + _tweenChange.x = -_xPos - _tweenStart.x; + } + + if (deltaHeight != 0 && isBottom && _tweenChange.y < 0) + { + _yPos = _overlapSize.y; + _tweenChange.y = -_yPos - _tweenStart.y; + } + } + else if (_tweening == 2) + { + //重新调整起始位置,确保能够顺滑滚下去 + if (deltaPosX != 0) + { + _container.x -= deltaPosX; + _tweenStart.x -= deltaPosX; + _xPos = -_container.x; + } + if (deltaPosY != 0) + { + _container.y -= deltaPosY; + _tweenStart.y -= deltaPosY; + _yPos = -_container.y; + } + } + else if (_dragged) + { + if (deltaPosX != 0) + { + _container.x -= deltaPosX; + _containerPos.x -= deltaPosX; + _xPos = -_container.x; + } + if (deltaPosY != 0) + { + _container.y -= deltaPosY; + _containerPos.y -= deltaPosY; + _yPos = -_container.y; + } + } + else + { + //如果原来滚动位置是贴边,加入处理继续贴边。 + if (deltaWidth != 0 && isRightmost) + { + _xPos = _overlapSize.x; + _container.x = -_xPos; + } + + if (deltaHeight != 0 && isBottom) + { + _yPos = _overlapSize.y; + _container.y = -_yPos; + } + } + + if (_pageMode) + UpdatePageController(); + } + + void HandleSizeChanged() + { + if (_displayInDemand) + { + _vScrollNone = _contentSize.y <= _viewSize.y; + _hScrollNone = _contentSize.x <= _viewSize.x; + + if (_vtScrollBar != null && _hzScrollBar != null) + { + if (!_hScrollNone) + _vtScrollBar.height = _owner.height - _hzScrollBar.height - _scrollBarMargin.top - _scrollBarMargin.bottom; + else + _vtScrollBar.height = _owner.height - _scrollBarMargin.top - _scrollBarMargin.bottom; + + if (!_vScrollNone) + _hzScrollBar.width = _owner.width - _vtScrollBar.width - _scrollBarMargin.left - _scrollBarMargin.right; + else + _hzScrollBar.width = _owner.width - _scrollBarMargin.left - _scrollBarMargin.right; + } + } + + if (_vtScrollBar != null) + { + if (_contentSize.y == 0) + _vtScrollBar.SetDisplayPerc(0); + else + _vtScrollBar.SetDisplayPerc(Mathf.Min(1, _viewSize.y / _contentSize.y)); + } + if (_hzScrollBar != null) + { + if (_contentSize.x == 0) + _hzScrollBar.SetDisplayPerc(0); + else + _hzScrollBar.SetDisplayPerc(Mathf.Min(1, _viewSize.x / _contentSize.x)); + } + + UpdateScrollBarVisible(); + + if (!_maskDisabled) + { + Rect rect = new Rect(-_owner._alignOffset.x, -_owner._alignOffset.y, _viewSize.x, _viewSize.y); + if (_vScrollNone && _vtScrollBar != null) + rect.width += _vtScrollBar.width; + if (_hScrollNone && _hzScrollBar != null) + rect.height += _hzScrollBar.height; + if (_dontClipMargin) + { + rect.x -= _owner.margin.left; + rect.width += (_owner.margin.left + _owner.margin.right); + rect.y -= _owner.margin.top; + rect.height += (_owner.margin.top + _owner.margin.bottom); + } + + _maskContainer.clipRect = rect; + } + + if (_scrollType == ScrollType.Horizontal || _scrollType == ScrollType.Both) + _overlapSize.x = Mathf.CeilToInt(Math.Max(0, _contentSize.x - _viewSize.x)); + else + _overlapSize.x = 0; + if (_scrollType == ScrollType.Vertical || _scrollType == ScrollType.Both) + _overlapSize.y = Mathf.CeilToInt(Math.Max(0, _contentSize.y - _viewSize.y)); + else + _overlapSize.y = 0; + + //边界检查 + _xPos = Mathf.Clamp(_xPos, 0, _overlapSize.x); + _yPos = Mathf.Clamp(_yPos, 0, _overlapSize.y); + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + if (_refreshBarAxis == 0) + _container.SetXY(Mathf.Clamp(_container.x, -max, _headerLockedSize), Mathf.Clamp(_container.y, -_overlapSize.y, 0)); + else + _container.SetXY(Mathf.Clamp(_container.x, -_overlapSize.x, 0), Mathf.Clamp(_container.y, -max, _headerLockedSize)); + + if (_header != null) + { + if (_refreshBarAxis == 0) + _header.height = _viewSize.y; + else + _header.width = _viewSize.x; + } + + if (_footer != null) + { + if (_refreshBarAxis == 0) + _footer.height = _viewSize.y; + else + _footer.width = _viewSize.x; + } + + UpdateScrollBarPos(); + if (_pageMode) + UpdatePageController(); + } + + private void PosChanged(bool ani) + { + //只要有1处要求不要缓动,那就不缓动 + if (_aniFlag == 0) + _aniFlag = ani ? 1 : -1; + else if (_aniFlag == 1 && !ani) + _aniFlag = -1; + + _needRefresh = true; + + UpdateContext.OnBegin -= _refreshDelegate; + UpdateContext.OnBegin += _refreshDelegate; + } + + private void Refresh() + { + _needRefresh = false; + UpdateContext.OnBegin -= _refreshDelegate; + + if (_owner.displayObject == null || _owner.displayObject.isDisposed) + return; + + if (_pageMode || _snapToItem) + { + Vector2 pos = new Vector2(-_xPos, -_yPos); + AlignPosition(ref pos, false); + _xPos = -pos.x; + _yPos = -pos.y; + } + + Refresh2(); + + _onScroll.Call(); + if (_needRefresh) //在onScroll事件里开发者可能修改位置,这里再刷新一次,避免闪烁 + { + _needRefresh = false; + UpdateContext.OnBegin -= _refreshDelegate; + + Refresh2(); + } + + UpdateScrollBarPos(); + _aniFlag = 0; + } + + void Refresh2() + { + if (_aniFlag == 1 && !_dragged) + { + Vector2 pos = new Vector2(); + + if (_overlapSize.x > 0) + pos.x = -(int)_xPos; + else + { + if (_container.x != 0) + _container.x = 0; + pos.x = 0; + } + if (_overlapSize.y > 0) + pos.y = -(int)_yPos; + else + { + if (_container.y != 0) + _container.y = 0; + pos.y = 0; + } + + if (pos.x != _container.x || pos.y != _container.y) + { + _tweenDuration = new Vector2(TWEEN_TIME_GO, TWEEN_TIME_GO); + _tweenStart = _container.xy; + _tweenChange = pos - _tweenStart; + StartTween(1); + } + else if (_tweening != 0) + KillTween(); + } + else + { + if (_tweening != 0) + KillTween(); + + _container.SetXY((int)-_xPos, (int)-_yPos); + + LoopCheckingCurrent(); + } + + if (_pageMode) + UpdatePageController(); + } + + private void __touchBegin(EventContext context) + { + if (!_touchEffect) + return; + + InputEvent evt = context.inputEvent; + if (evt.button != 0) + return; + + context.CaptureTouch(); + + Vector2 pt = _owner.GlobalToLocal(evt.position); + + if (_tweening != 0) + { + KillTween(); + Stage.inst.CancelClick(evt.touchId); + + //立刻停止惯性滚动,可能位置不对齐,设定这个标志,使touchEnd时归位 + _dragged = true; + } + else + _dragged = false; + + _containerPos = _container.xy; + _beginTouchPos = _lastTouchPos = pt; + _lastTouchGlobalPos = evt.position; + _isHoldAreaDone = false; + _velocity = Vector2.zero; + _velocityScale = 1; + _lastMoveTime = Time.unscaledTime; + } + + private void __touchMove(EventContext context) + { + if (!_touchEffect || draggingPane != null && draggingPane != this || GObject.draggingObject != null) //已经有其他拖动 + return; + + InputEvent evt = context.inputEvent; + Vector2 pt = _owner.GlobalToLocal(evt.position); + if (float.IsNaN(pt.x)) + return; + + int sensitivity; + if (Stage.touchScreen) + sensitivity = UIConfig.touchScrollSensitivity; + else + sensitivity = 8; + + float diff; + bool sv = false, sh = false; + + if (_scrollType == ScrollType.Vertical) + { + if (!_isHoldAreaDone) + { + //表示正在监测垂直方向的手势 + _gestureFlag |= 1; + + diff = Mathf.Abs(_beginTouchPos.y - pt.y); + if (diff < sensitivity) + return; + + if ((_gestureFlag & 2) != 0) //已经有水平方向的手势在监测,那么我们用严格的方式检查是不是按垂直方向移动,避免冲突 + { + float diff2 = Mathf.Abs(_beginTouchPos.x - pt.x); + if (diff < diff2) //不通过则不允许滚动了 + return; + } + } + + sv = true; + } + else if (_scrollType == ScrollType.Horizontal) + { + if (!_isHoldAreaDone) + { + _gestureFlag |= 2; + + diff = Mathf.Abs(_beginTouchPos.x - pt.x); + if (diff < sensitivity) + return; + + if ((_gestureFlag & 1) != 0) + { + float diff2 = Mathf.Abs(_beginTouchPos.y - pt.y); + if (diff < diff2) + return; + } + } + + sh = true; + } + else + { + _gestureFlag = 3; + + if (!_isHoldAreaDone) + { + diff = Mathf.Abs(_beginTouchPos.y - pt.y); + if (diff < sensitivity) + { + diff = Mathf.Abs(_beginTouchPos.x - pt.x); + if (diff < sensitivity) + return; + } + } + + sv = sh = true; + } + + Vector2 newPos = _containerPos + pt - _beginTouchPos; + newPos.x = (int)newPos.x; + newPos.y = (int)newPos.y; + + if (sv) + { + if (newPos.y > 0) + { + if (!_bouncebackEffect) + _container.y = 0; + else if (_header != null && _header.maxHeight != 0) + _container.y = (int)Mathf.Min(newPos.y * 0.5f, _header.maxHeight); + else + _container.y = (int)Mathf.Min(newPos.y * 0.5f, _viewSize.y * PULL_RATIO); + } + else if (newPos.y < -_overlapSize.y) + { + if (!_bouncebackEffect) + _container.y = -_overlapSize.y; + else if (_footer != null && _footer.maxHeight > 0) + _container.y = (int)Mathf.Max((newPos.y + _overlapSize.y) * 0.5f, -_footer.maxHeight) - _overlapSize.y; + else + _container.y = (int)Mathf.Max((newPos.y + _overlapSize.y) * 0.5f, -_viewSize.y * PULL_RATIO) - _overlapSize.y; + } + else + _container.y = newPos.y; + } + + if (sh) + { + if (newPos.x > 0) + { + if (!_bouncebackEffect) + _container.x = 0; + else if (_header != null && _header.maxWidth != 0) + _container.x = (int)Mathf.Min(newPos.x * 0.5f, _header.maxWidth); + else + _container.x = (int)Mathf.Min(newPos.x * 0.5f, _viewSize.x * PULL_RATIO); + } + else if (newPos.x < 0 - _overlapSize.x) + { + if (!_bouncebackEffect) + _container.x = -_overlapSize.x; + else if (_footer != null && _footer.maxWidth > 0) + _container.x = (int)Mathf.Max((newPos.x + _overlapSize.x) * 0.5f, -_footer.maxWidth) - _overlapSize.x; + else + _container.x = (int)Mathf.Max((newPos.x + _overlapSize.x) * 0.5f, -_viewSize.x * PULL_RATIO) - _overlapSize.x; + } + else + _container.x = newPos.x; + } + + //更新速度 + float deltaTime = Time.unscaledDeltaTime; + float elapsed = (Time.unscaledTime - _lastMoveTime) * 60 - 1; + if (elapsed > 1) //速度衰减 + _velocity = _velocity * Mathf.Pow(0.833f, elapsed); + Vector2 deltaPosition = pt - _lastTouchPos; + if (!sh) + deltaPosition.x = 0; + if (!sv) + deltaPosition.y = 0; + _velocity = Vector2.Lerp(_velocity, deltaPosition / deltaTime, deltaTime * 10); + + /*速度计算使用的是本地位移,但在后续的惯性滚动判断中需要用到屏幕位移,所以这里要记录一个位移的比例。 + *后续的处理要使用这个比例但不使用坐标转换的方法的原因是,在曲面UI等异形UI中,还无法简单地进行屏幕坐标和本地坐标的转换。 + */ + Vector2 deltaGlobalPosition = _lastTouchGlobalPos - evt.position; + if (deltaPosition.x != 0) + _velocityScale = Mathf.Abs(deltaGlobalPosition.x / deltaPosition.x); + else if (deltaPosition.y != 0) + _velocityScale = Mathf.Abs(deltaGlobalPosition.y / deltaPosition.y); + + _lastTouchPos = pt; + _lastTouchGlobalPos = evt.position; + _lastMoveTime = Time.unscaledTime; + + //同步更新pos值 + if (_overlapSize.x > 0) + _xPos = Mathf.Clamp(-_container.x, 0, _overlapSize.x); + if (_overlapSize.y > 0) + _yPos = Mathf.Clamp(-_container.y, 0, _overlapSize.y); + + //循环滚动特别检查 + if (_loop != 0) + { + newPos = _container.xy; + if (LoopCheckingCurrent()) + _containerPos += _container.xy - newPos; + } + + draggingPane = this; + _isHoldAreaDone = true; + _dragged = true; + + UpdateScrollBarPos(); + UpdateScrollBarVisible(); + if (_pageMode) + UpdatePageController(); + _onScroll.Call(); + } + + private void __touchEnd(EventContext context) + { + if (draggingPane == this) + draggingPane = null; + + _gestureFlag = 0; + + if (!_dragged || !_touchEffect) + { + _dragged = false; + return; + } + + _dragged = false; + _tweenStart = _container.xy; + + Vector2 endPos = _tweenStart; + bool flag = false; + if (_container.x > 0) + { + endPos.x = 0; + flag = true; + } + else if (_container.x < -_overlapSize.x) + { + endPos.x = -_overlapSize.x; + flag = true; + } + if (_container.y > 0) + { + endPos.y = 0; + flag = true; + } + else if (_container.y < -_overlapSize.y) + { + endPos.y = -_overlapSize.y; + flag = true; + } + + if (flag) + { + _tweenChange = endPos - _tweenStart; + if (_tweenChange.x < -UIConfig.touchDragSensitivity || _tweenChange.y < -UIConfig.touchDragSensitivity) + DispatchEvent("onPullDownRelease", null); + else if (_tweenChange.x > UIConfig.touchDragSensitivity || _tweenChange.y > UIConfig.touchDragSensitivity) + DispatchEvent("onPullUpRelease", null); + + if (_headerLockedSize > 0 && endPos[_refreshBarAxis] == 0) + { + endPos[_refreshBarAxis] = _headerLockedSize; + _tweenChange = endPos - _tweenStart; + } + else if (_footerLockedSize > 0 && endPos[_refreshBarAxis] == -_overlapSize[_refreshBarAxis]) + { + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + endPos[_refreshBarAxis] = -max; + _tweenChange = endPos - _tweenStart; + } + + _tweenDuration.Set(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + } + else + { + //更新速度 + if (!_inertiaDisabled) + { + float elapsed = (Time.unscaledTime - _lastMoveTime) * 60 - 1; + if (elapsed > 1) + _velocity = _velocity * Mathf.Pow(0.833f, elapsed); + + //根据速度计算目标位置和需要时间 + endPos = UpdateTargetAndDuration(_tweenStart); + } + else + _tweenDuration.Set(TWEEN_TIME_DEFAULT, TWEEN_TIME_DEFAULT); + Vector2 oldChange = endPos - _tweenStart; + + //调整目标位置 + LoopCheckingTarget(ref endPos); + if (_pageMode || _snapToItem) + AlignPosition(ref endPos, true); + + _tweenChange = endPos - _tweenStart; + if (_tweenChange.x == 0 && _tweenChange.y == 0) + { + UpdateScrollBarVisible(); + return; + } + + //如果目标位置已调整,随之调整需要时间 + if (_pageMode || _snapToItem) + { + FixDuration(0, oldChange.x); + FixDuration(1, oldChange.y); + } + } + + StartTween(2); + } + + private void __mouseWheel(EventContext context) + { + if (!_mouseWheelEnabled) + return; + + InputEvent evt = context.inputEvent; + float delta = evt.mouseWheelDelta / Stage.devicePixelRatio; + if (_snapToItem && Mathf.Abs(delta) < 1) + delta = Mathf.Sign(delta); + + if (_overlapSize.x > 0 && _overlapSize.y == 0) + { + float step = _pageMode ? _pageSize.x : _scrollStep; + SetPosX(_xPos + step * delta, false); + } + else + { + float step = _pageMode ? _pageSize.y : _scrollStep; + SetPosY(_yPos + step * delta, false); + } + } + + private void __rollOver() + { + _hover = true; + UpdateScrollBarVisible(); + } + + private void __rollOut() + { + _hover = false; + UpdateScrollBarVisible(); + } + + internal void UpdateClipSoft() + { + Vector2 softness = _owner.clipSoftness; + if (softness.x != 0 || softness.y != 0) + { + _maskContainer.clipSoftness = new Vector4( + (_container.x >= 0 || !_softnessOnTopOrLeftSide) ? 0 : softness.x, + (_container.y >= 0 || !_softnessOnTopOrLeftSide) ? 0 : softness.y, + (-_container.x - _overlapSize.x >= 0) ? 0 : softness.x, + (-_container.y - _overlapSize.y >= 0) ? 0 : softness.y); + } + else + _maskContainer.clipSoftness = null; + } + + private void UpdateScrollBarPos() + { + if (_vtScrollBar != null) + _vtScrollBar.setScrollPerc(_overlapSize.y == 0 ? 0 : Mathf.Clamp(-_container.y, 0, _overlapSize.y) / _overlapSize.y); + + if (_hzScrollBar != null) + _hzScrollBar.setScrollPerc(_overlapSize.x == 0 ? 0 : Mathf.Clamp(-_container.x, 0, _overlapSize.x) / _overlapSize.x); + + UpdateClipSoft(); + CheckRefreshBar(); + } + + public void UpdateScrollBarVisible() + { + if (_vtScrollBar != null) + { + if (_viewSize.y <= _vtScrollBar.minSize || _vScrollNone) + _vtScrollBar.displayObject.visible = false; + else + UpdateScrollBarVisible2(_vtScrollBar); + } + + if (_hzScrollBar != null) + { + if (_viewSize.x <= _hzScrollBar.minSize || _hScrollNone) + _hzScrollBar.displayObject.visible = false; + else + UpdateScrollBarVisible2(_hzScrollBar); + } + } + + private void UpdateScrollBarVisible2(GScrollBar bar) + { + if (_scrollBarDisplayAuto) + GTween.Kill(bar, TweenPropType.Alpha, false); + + if (_scrollBarDisplayAuto && !_hover && _tweening == 0 && !_dragged && !bar.gripDragging) + { + if (bar.displayObject.visible) + GTween.To(1, 0, 0.5f).SetDelay(0.5f).OnComplete(_hideScrollBarDelegate).SetTarget(bar, TweenPropType.Alpha); + } + else + { + bar.alpha = 1; + bar.displayObject.visible = true; + } + } + + private void __barTweenComplete(GTweener tweener) + { + GObject bar = (GObject)tweener.target; + bar.alpha = 1; + bar.displayObject.visible = false; + } + + float GetLoopPartSize(float division, int axis) + { + return (_contentSize[axis] + (axis == 0 ? ((GList)_owner).columnGap : ((GList)_owner).lineGap)) / division; + } + + /// + /// 对当前的滚动位置进行循环滚动边界检查。当到达边界时,回退一半内容区域(循环滚动内容大小通常是真实内容大小的偶数倍)。 + /// + /// + bool LoopCheckingCurrent() + { + bool changed = false; + if (_loop == 1 && _overlapSize.x > 0) + { + if (_xPos < 0.001f) + { + _xPos += GetLoopPartSize(2, 0); + changed = true; + } + else if (_xPos >= _overlapSize.x) + { + _xPos -= GetLoopPartSize(2, 0); + changed = true; + } + } + else if (_loop == 2 && _overlapSize.y > 0) + { + if (_yPos < 0.001f) + { + _yPos += GetLoopPartSize(2, 1); + changed = true; + } + else if (_yPos >= _overlapSize.y) + { + _yPos -= GetLoopPartSize(2, 1); + changed = true; + } + } + + if (changed) + _container.SetXY((int)-_xPos, (int)-_yPos); + + return changed; + } + + /// + /// 对目标位置进行循环滚动边界检查。当到达边界时,回退一半内容区域(循环滚动内容大小通常是真实内容大小的偶数倍)。 + /// + /// + void LoopCheckingTarget(ref Vector2 endPos) + { + if (_loop == 1) + LoopCheckingTarget(ref endPos, 0); + + if (_loop == 2) + LoopCheckingTarget(ref endPos, 1); + } + + void LoopCheckingTarget(ref Vector2 endPos, int axis) + { + if (endPos[axis] > 0) + { + float halfSize = GetLoopPartSize(2, axis); + float tmp = _tweenStart[axis] - halfSize; + if (tmp <= 0 && tmp >= -_overlapSize[axis]) + { + endPos[axis] -= halfSize; + _tweenStart[axis] = tmp; + } + } + else if (endPos[axis] < -_overlapSize[axis]) + { + float halfSize = GetLoopPartSize(2, axis); + float tmp = _tweenStart[axis] + halfSize; + if (tmp <= 0 && tmp >= -_overlapSize[axis]) + { + endPos[axis] += halfSize; + _tweenStart[axis] = tmp; + } + } + } + + void LoopCheckingNewPos(ref float value, int axis) + { + if (_overlapSize[axis] == 0) + return; + + float pos = axis == 0 ? _xPos : _yPos; + bool changed = false; + if (value < 0.001f) + { + value += GetLoopPartSize(2, axis); + if (value > pos) + { + float v = GetLoopPartSize(6, axis); + v = Mathf.CeilToInt((value - pos) / v) * v; + pos = Mathf.Clamp(pos + v, 0, _overlapSize[axis]); + changed = true; + } + } + else if (value >= _overlapSize[axis]) + { + value -= GetLoopPartSize(2, axis); + if (value < pos) + { + float v = GetLoopPartSize(6, axis); + v = Mathf.CeilToInt((pos - value) / v) * v; + pos = Mathf.Clamp(pos - v, 0, _overlapSize[axis]); + changed = true; + } + } + + if (changed) + { + if (axis == 0) + _container.x = -(int)pos; + else + _container.y = -(int)pos; + } + } + + /// + /// 从oldPos滚动至pos,调整pos位置对齐页面、对齐item等(如果需要)。 + /// + /// + /// + void AlignPosition(ref Vector2 pos, bool inertialScrolling) + { + if (_pageMode) + { + pos.x = AlignByPage(pos.x, 0, inertialScrolling); + pos.y = AlignByPage(pos.y, 1, inertialScrolling); + } + else if (_snapToItem) + { + float tmpX = -pos.x; + float tmpY = -pos.y; + float xDir = 0; + float yDir = 0; + if (inertialScrolling) + { + xDir = pos.x - _containerPos.x; + yDir = pos.y - _containerPos.y; + } + _owner.GetSnappingPositionWithDir(ref tmpX, ref tmpY, xDir, yDir); + if (pos.x < 0 && pos.x > -_overlapSize.x) + pos.x = -tmpX; + if (pos.y < 0 && pos.y > -_overlapSize.y) + pos.y = -tmpY; + } + } + + /// + /// 从oldPos滚动至pos,调整目标位置到对齐页面。 + /// + /// + /// + /// + /// + float AlignByPage(float pos, int axis, bool inertialScrolling) + { + int page; + + if (pos > 0) + page = 0; + else if (pos < -_overlapSize[axis]) + page = Mathf.CeilToInt(_contentSize[axis] / _pageSize[axis]) - 1; + else + { + page = Mathf.FloorToInt(-pos / _pageSize[axis]); + float change = inertialScrolling ? (pos - _containerPos[axis]) : (pos - _container.xy[axis]); + float testPageSize = Mathf.Min(_pageSize[axis], _contentSize[axis] - (page + 1) * _pageSize[axis]); + float delta = -pos - page * _pageSize[axis]; + + //页面吸附策略 + if (Mathf.Abs(change) > _pageSize[axis])//如果滚动距离超过1页,则需要超过页面的一半,才能到更下一页 + { + if (delta > testPageSize * 0.5f) + page++; + } + else //否则只需要页面的1/3,当然,需要考虑到左移和右移的情况 + { + if (delta > testPageSize * (change < 0 ? UIConfig.defaultScrollPagingThreshold : (1 - UIConfig.defaultScrollPagingThreshold))) + page++; + } + + //重新计算终点 + pos = -page * _pageSize[axis]; + if (pos < -_overlapSize[axis]) //最后一页未必有pageSize那么大 + pos = -_overlapSize[axis]; + } + + //惯性滚动模式下,会增加判断尽量不要滚动超过一页 + if (inertialScrolling) + { + float oldPos = _tweenStart[axis]; + int oldPage; + if (oldPos > 0) + oldPage = 0; + else if (oldPos < -_overlapSize[axis]) + oldPage = Mathf.CeilToInt(_contentSize[axis] / _pageSize[axis]) - 1; + else + oldPage = Mathf.FloorToInt(-oldPos / _pageSize[axis]); + int startPage = Mathf.FloorToInt(-_containerPos[axis] / _pageSize[axis]); + if (Mathf.Abs(page - startPage) > 1 && Mathf.Abs(oldPage - startPage) <= 1) + { + if (page > startPage) + page = startPage + 1; + else + page = startPage - 1; + pos = -page * _pageSize[axis]; + } + } + + return pos; + } + + /// + /// 根据当前速度,计算滚动的目标位置,以及到达时间。 + /// + /// + /// + Vector2 UpdateTargetAndDuration(Vector2 orignPos) + { + Vector2 ret = Vector2.zero; + ret.x = UpdateTargetAndDuration(orignPos.x, 0); + ret.y = UpdateTargetAndDuration(orignPos.y, 1); + return ret; + } + + float UpdateTargetAndDuration(float pos, int axis) + { + float v = _velocity[axis]; + float duration = 0; + + if (pos > 0) + pos = 0; + else if (pos < -_overlapSize[axis]) + pos = -_overlapSize[axis]; + else + { + //以屏幕像素为基准 + float v2 = Mathf.Abs(v) * _velocityScale; + //在移动设备上,需要对不同分辨率做一个适配,我们的速度判断以1136分辨率为基准 + if (Stage.touchScreen) + v2 *= 1136f / Mathf.Max(Screen.width, Screen.height); + //这里有一些阈值的处理,因为在低速内,不希望产生较大的滚动(甚至不滚动) + float ratio = 0; + if (_pageMode || !Stage.touchScreen) + { + if (v2 > 500) + ratio = Mathf.Pow((v2 - 500) / 500, 2); + } + else + { + if (v2 > 1000) + ratio = Mathf.Pow((v2 - 1000) / 1000, 2); + } + + if (ratio != 0) + { + if (ratio > 1) + ratio = 1; + + v2 *= ratio; + v *= ratio; + _velocity[axis] = v; + + //算法:v*(_decelerationRate的n次幂)= 60,即在n帧后速度降为60(假设每秒60帧)。 + duration = Mathf.Log(60 / v2, _decelerationRate) / 60; + + //计算距离要使用本地速度 + //理论公式貌似滚动的距离不够,改为经验公式 + //float change = (int)((v/ 60 - 1) / (1 - _decelerationRate)); + float change = (int)(v * duration * 0.4f); + pos += change; + } + } + + if (duration < TWEEN_TIME_DEFAULT) + duration = TWEEN_TIME_DEFAULT; + _tweenDuration[axis] = duration; + + return pos; + } + + /// + /// 根据修改后的tweenChange重新计算减速时间。 + /// + void FixDuration(int axis, float oldChange) + { + if (_tweenChange[axis] == 0 || Mathf.Abs(_tweenChange[axis]) >= Mathf.Abs(oldChange)) + return; + + float newDuration = Mathf.Abs(_tweenChange[axis] / oldChange) * _tweenDuration[axis]; + if (newDuration < TWEEN_TIME_DEFAULT) + newDuration = TWEEN_TIME_DEFAULT; + + _tweenDuration[axis] = newDuration; + } + + void StartTween(int type) + { + _tweenTime.Set(0, 0); + _tweening = type; + Timers.inst.AddUpdate(_tweenUpdateDelegate); + + UpdateScrollBarVisible(); + } + + void KillTween() + { + if (_tweening == 1) //取消类型为1的tween需立刻设置到终点 + { + _container.xy = _tweenStart + _tweenChange; + _onScroll.Call(); + } + + _tweening = 0; + Timers.inst.Remove(_tweenUpdateDelegate); + + UpdateScrollBarVisible(); + + _onScrollEnd.Call(); + } + + void CheckRefreshBar() + { + if (_header == null && _footer == null) + return; + + float pos = _container.xy[_refreshBarAxis]; + if (_header != null) + { + if (pos > 0) + { + if (_header.displayObject.parent == null) + _maskContainer.AddChildAt(_header.displayObject, 0); + Vector2 vec; + + vec = _header.size; + vec[_refreshBarAxis] = pos; + _header.size = vec; + } + else + { + if (_header.displayObject.parent != null) + _maskContainer.RemoveChild(_header.displayObject); + } + } + + if (_footer != null) + { + float max = _overlapSize[_refreshBarAxis]; + if (pos < -max || max == 0 && _footerLockedSize > 0) + { + if (_footer.displayObject.parent == null) + _maskContainer.AddChildAt(_footer.displayObject, 0); + + Vector2 vec; + + vec = _footer.xy; + if (max > 0) + vec[_refreshBarAxis] = pos + _contentSize[_refreshBarAxis]; + else + vec[_refreshBarAxis] = Mathf.Max(Mathf.Min(pos + _viewSize[_refreshBarAxis], _viewSize[_refreshBarAxis] - _footerLockedSize), _viewSize[_refreshBarAxis] - _contentSize[_refreshBarAxis]); + _footer.xy = vec; + + vec = _footer.size; + if (max > 0) + vec[_refreshBarAxis] = -max - pos; + else + vec[_refreshBarAxis] = _viewSize[_refreshBarAxis] - _footer.xy[_refreshBarAxis]; + _footer.size = vec; + } + else + { + if (_footer.displayObject.parent != null) + _maskContainer.RemoveChild(_footer.displayObject); + } + } + } + + void TweenUpdate(object param) + { + if (_owner.displayObject == null || _owner.displayObject.isDisposed) + { + Timers.inst.Remove(_tweenUpdateDelegate); + return; + } + + float nx = RunTween(0); + float ny = RunTween(1); + + _container.SetXY(nx, ny); + + if (_tweening == 2) + { + if (_overlapSize.x > 0) + _xPos = Mathf.Clamp(-nx, 0, _overlapSize.x); + if (_overlapSize.y > 0) + _yPos = Mathf.Clamp(-ny, 0, _overlapSize.y); + + if (_pageMode) + UpdatePageController(); + } + + if (_tweenChange.x == 0 && _tweenChange.y == 0) + { + _tweening = 0; + Timers.inst.Remove(_tweenUpdateDelegate); + + LoopCheckingCurrent(); + + UpdateScrollBarPos(); + UpdateScrollBarVisible(); + + _onScroll.Call(); + _onScrollEnd.Call(); + } + else + { + UpdateScrollBarPos(); + _onScroll.Call(); + } + } + + float RunTween(int axis) + { + float newValue; + if (_tweenChange[axis] != 0) + { + _tweenTime[axis] += Time.unscaledDeltaTime; + if (_tweenTime[axis] >= _tweenDuration[axis]) + { + newValue = _tweenStart[axis] + _tweenChange[axis]; + _tweenChange[axis] = 0; + } + else + { + float ratio = EaseFunc(_tweenTime[axis], _tweenDuration[axis]); + newValue = _tweenStart[axis] + (int)(_tweenChange[axis] * ratio); + } + + float threshold1 = 0; + float threshold2 = -_overlapSize[axis]; + if (_headerLockedSize > 0 && _refreshBarAxis == axis) + threshold1 = _headerLockedSize; + if (_footerLockedSize > 0 && _refreshBarAxis == axis) + { + float max = _overlapSize[_refreshBarAxis]; + if (max == 0) + max = Mathf.Max(_contentSize[_refreshBarAxis] + _footerLockedSize - _viewSize[_refreshBarAxis], 0); + else + max += _footerLockedSize; + threshold2 = -max; + } + + if (_tweening == 2 && _bouncebackEffect) + { + if (newValue > 20 + threshold1 && _tweenChange[axis] > 0 + || newValue > threshold1 && _tweenChange[axis] == 0)//开始回弹 + { + _tweenTime[axis] = 0; + _tweenDuration[axis] = TWEEN_TIME_DEFAULT; + _tweenChange[axis] = -newValue + threshold1; + _tweenStart[axis] = newValue; + } + else if (newValue < threshold2 - 20 && _tweenChange[axis] < 0 + || newValue < threshold2 && _tweenChange[axis] == 0)//开始回弹 + { + _tweenTime[axis] = 0; + _tweenDuration[axis] = TWEEN_TIME_DEFAULT; + _tweenChange[axis] = threshold2 - newValue; + _tweenStart[axis] = newValue; + } + } + else + { + if (newValue > threshold1) + { + newValue = threshold1; + _tweenChange[axis] = 0; + } + else if (newValue < threshold2) + { + newValue = threshold2; + _tweenChange[axis] = 0; + } + } + } + else + newValue = _container.xy[axis]; + + return newValue; + } + + static float EaseFunc(float t, float d) + { + return (t = t / d - 1) * t * t + 1;//cubicOut + } + } +} diff --git a/Assets/Scripts/UI/ScrollPane.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/ScrollPane.cs.meta similarity index 100% rename from Assets/Scripts/UI/ScrollPane.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/ScrollPane.cs.meta diff --git a/Assets/Scripts/UI/Transition.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Transition.cs similarity index 97% rename from Assets/Scripts/UI/Transition.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Transition.cs index 5a206d37..faa957b5 100644 --- a/Assets/Scripts/UI/Transition.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Transition.cs @@ -1,1771 +1,1771 @@ -using System; -using System.Collections.Generic; -using FairyGUI.Utils; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - public delegate void PlayCompleteCallback(); - - /// - /// - /// - public delegate void TransitionHook(); - - /// - /// - /// - public class Transition : ITweenListener - { - /// - /// 动效的名称。在编辑器里设定。 - /// - public string name { get; private set; } - - /// - /// 当你启动了自动合批,动效里有涉及到XY、大小、旋转等的改变,如果你观察到元件的显示深度在播放过程中有错误,可以开启这个选项。 - /// - public bool invalidateBatchingEveryFrame; - - GComponent _owner; - TransitionItem[] _items; - int _totalTimes; - int _totalTasks; - bool _playing; - bool _paused; - float _ownerBaseX; - float _ownerBaseY; - PlayCompleteCallback _onComplete; - int _options; - bool _reversed; - float _totalDuration; - bool _autoPlay; - int _autoPlayTimes; - float _autoPlayDelay; - float _timeScale; - bool _ignoreEngineTimeScale; - float _startTime; - float _endTime; - GTweenCallback _delayedCallDelegate; - GTweenCallback _checkAllDelegate; - GTweenCallback1 _delayedCallDelegate2; - - const int OPTION_IGNORE_DISPLAY_CONTROLLER = 1; - const int OPTION_AUTO_STOP_DISABLED = 2; - const int OPTION_AUTO_STOP_AT_END = 4; - - public Transition(GComponent owner) - { - _owner = owner; - _timeScale = 1; - _ignoreEngineTimeScale = true; - - _delayedCallDelegate = OnDelayedPlay; - _delayedCallDelegate2 = OnDelayedPlayItem; - _checkAllDelegate = CheckAllComplete; - } - - /// - /// - /// - public void Play() - { - _Play(1, 0, 0, -1, null, false); - } - - /// - /// - /// - /// - public void Play(PlayCompleteCallback onComplete) - { - _Play(1, 0, 0, -1, onComplete, false); - } - - /// - /// - /// - /// - /// - /// - public void Play(int times, float delay, PlayCompleteCallback onComplete) - { - _Play(times, delay, 0, -1, onComplete, false); - } - - /// - /// - /// - /// - /// - /// - /// - /// - public void Play(int times, float delay, float startTime, float endTime, PlayCompleteCallback onComplete) - { - _Play(times, delay, startTime, endTime, onComplete, false); - } - - /// - /// - /// - public void PlayReverse() - { - _Play(1, 0, 0, -1, null, true); - } - - /// - /// - /// - /// - public void PlayReverse(PlayCompleteCallback onComplete) - { - _Play(1, 0, 0, -1, onComplete, true); - } - - /// - /// - /// - /// - /// - /// - public void PlayReverse(int times, float delay, PlayCompleteCallback onComplete) - { - _Play(times, delay, 0, -1, onComplete, true); - } - - /// - /// - /// - /// - public void ChangePlayTimes(int value) - { - _totalTimes = value; - } - - /// - /// 设置动效是否自动播放。 - /// - /// - /// - /// - public void SetAutoPlay(bool autoPlay, int times, float delay) - { - if (_autoPlay != autoPlay) - { - _autoPlay = autoPlay; - _autoPlayTimes = times; - _autoPlayDelay = delay; - if (_autoPlay) - { - if (_owner.onStage) - Play(times, delay, null); - } - else - { - if (!_owner.onStage) - Stop(false, true); - } - } - } - - void _Play(int times, float delay, float startTime, float endTime, PlayCompleteCallback onComplete, bool reverse) - { - Stop(true, true); - - _totalTimes = times; - _reversed = reverse; - _startTime = startTime; - _endTime = endTime; - _playing = true; - _paused = false; - _onComplete = onComplete; - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.target == null) - { - if (item.targetId.Length > 0) - item.target = _owner.GetChildById(item.targetId); - else - item.target = _owner; - } - else if (item.target != _owner && item.target.parent != _owner) //maybe removed - item.target = null; - - if (item.target != null && item.type == TransitionActionType.Transition) - { - TValue_Transition value = (TValue_Transition)item.value; - Transition trans = ((GComponent)item.target).GetTransition(value.transName); - if (trans == this) - trans = null; - if (trans != null) - { - if (value.playTimes == 0) //stop - { - int j; - for (j = i - 1; j >= 0; j--) - { - TransitionItem item2 = _items[j]; - if (item2.type == TransitionActionType.Transition) - { - TValue_Transition value2 = (TValue_Transition)item2.value; - if (value2.trans == trans) - { - value2.stopTime = item.time - item2.time; - break; - } - } - } - if (j < 0) - value.stopTime = 0; - else - trans = null; //no need to handle stop anymore - } - else - value.stopTime = -1; - } - value.trans = trans; - } - } - - if (delay == 0) - OnDelayedPlay(); - else - GTween.DelayedCall(delay).SetTarget(this).OnComplete(_delayedCallDelegate); - } - - /// - /// - /// - public void Stop() - { - Stop(true, false); - } - - /// - /// - /// - /// - /// - public void Stop(bool setToComplete, bool processCallback) - { - if (!_playing) - return; - - _playing = false; - _totalTasks = 0; - _totalTimes = 0; - PlayCompleteCallback func = _onComplete; - _onComplete = null; - - GTween.Kill(this);//delay start - - int cnt = _items.Length; - if (_reversed) - { - for (int i = cnt - 1; i >= 0; i--) - { - TransitionItem item = _items[i]; - if (item.target == null) - continue; - - StopItem(item, setToComplete); - } - } - else - { - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.target == null) - continue; - - StopItem(item, setToComplete); - } - } - - if (processCallback && func != null) - func(); - - } - - void StopItem(TransitionItem item, bool setToComplete) - { - if (item.displayLockToken != 0) - { - item.target.ReleaseDisplayLock(item.displayLockToken); - item.displayLockToken = 0; - } - - if (item.tweener != null) - { - item.tweener.Kill(setToComplete); - item.tweener = null; - - if (item.type == TransitionActionType.Shake && !setToComplete) //震动必须归位,否则下次就越震越远了。 - { - item.target._gearLocked = true; - item.target.SetXY(item.target.x - ((TValue_Shake)item.value).lastOffset.x, item.target.y - ((TValue_Shake)item.value).lastOffset.y); - item.target._gearLocked = false; - - _owner.InvalidateBatchingState(true); - } - } - - if (item.type == TransitionActionType.Transition) - { - TValue_Transition value = (TValue_Transition)item.value; - if (value.trans != null) - value.trans.Stop(setToComplete, false); - } - } - - /// - /// - /// - /// - public void SetPaused(bool paused) - { - if (!_playing || _paused == paused) - return; - - _paused = paused; - GTweener tweener = GTween.GetTween(this); - if (tweener != null) - tweener.SetPaused(paused); - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.target == null) - continue; - - if (item.type == TransitionActionType.Transition) - { - if (((TValue_Transition)item.value).trans != null) - ((TValue_Transition)item.value).trans.SetPaused(paused); - } - else if (item.type == TransitionActionType.Animation) - { - if (paused) - { - ((TValue_Animation)item.value).flag = ((IAnimationGear)item.target).playing; - ((IAnimationGear)item.target).playing = false; - } - else - ((IAnimationGear)item.target).playing = ((TValue_Animation)item.value).flag; - } - - if (item.tweener != null) - item.tweener.SetPaused(paused); - } - } - - public void Dispose() - { - if (_playing) - GTween.Kill(this);//delay start - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.tweener != null) - { - item.tweener.Kill(); - item.tweener = null; - } - - item.target = null; - item.hook = null; - if (item.tweenConfig != null) - item.tweenConfig.endHook = null; - } - - _playing = false; - _onComplete = null; - } - - /// - /// - /// - public bool playing - { - get { return _playing; } - } - - /// - /// transition's total duration, maybe zero when the transition only has one frame - /// - public float totalDuration - { - get { return _totalDuration; } - } - - /// - /// - /// - /// - /// - public void SetValue(string label, params object[] aParams) - { - int cnt = _items.Length; - object value; - bool found = false; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.label == label) - { - if (item.tweenConfig != null) - value = item.tweenConfig.startValue; - else - value = item.value; - found = true; - } - else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) - { - value = item.tweenConfig.endValue; - found = true; - } - else - continue; - - switch (item.type) - { - case TransitionActionType.XY: - case TransitionActionType.Size: - case TransitionActionType.Pivot: - case TransitionActionType.Scale: - case TransitionActionType.Skew: - { - TValue tvalue = (TValue)value; - tvalue.b1 = true; - tvalue.b2 = true; - tvalue.f1 = Convert.ToSingle(aParams[0]); - tvalue.f2 = Convert.ToSingle(aParams[1]); - } - break; - - case TransitionActionType.Alpha: - ((TValue)value).f1 = Convert.ToSingle(aParams[0]); - break; - - case TransitionActionType.Rotation: - ((TValue)value).f1 = Convert.ToSingle(aParams[0]); - break; - - case TransitionActionType.Color: - ((TValue)value).color = (Color)aParams[0]; - break; - - case TransitionActionType.Animation: - { - TValue_Animation tvalue = (TValue_Animation)value; - tvalue.frame = Convert.ToInt32(aParams[0]); - if (aParams.Length > 1) - tvalue.playing = Convert.ToBoolean(aParams[1]); - if (aParams.Length > 2) - tvalue.animationName = (string)aParams[2]; - if (aParams.Length > 3) - tvalue.skinName = (string)aParams[3]; - } - break; - - case TransitionActionType.Visible: - ((TValue_Visible)value).visible = Convert.ToBoolean(aParams[0]); - break; - - case TransitionActionType.Sound: - { - TValue_Sound tvalue = (TValue_Sound)value; - tvalue.sound = (string)aParams[0]; - if (aParams.Length > 1) - tvalue.volume = Convert.ToSingle(aParams[1]); - } - break; - - case TransitionActionType.Transition: - { - TValue_Transition tvalue = (TValue_Transition)value; - tvalue.transName = (string)aParams[0]; - if (aParams.Length > 1) - tvalue.playTimes = Convert.ToInt32(aParams[1]); - } - break; - - case TransitionActionType.Shake: - { - ((TValue_Shake)value).amplitude = Convert.ToSingle(aParams[0]); - if (aParams.Length > 1) - ((TValue_Shake)value).duration = Convert.ToSingle(aParams[1]); - } - break; - - case TransitionActionType.ColorFilter: - { - TValue tvalue = (TValue)value; - tvalue.f1 = Convert.ToSingle(aParams[0]); - tvalue.f2 = Convert.ToSingle(aParams[1]); - tvalue.f3 = Convert.ToSingle(aParams[2]); - tvalue.f4 = Convert.ToSingle(aParams[3]); - } - break; - - case TransitionActionType.Text: - case TransitionActionType.Icon: - ((TValue_Text)value).text = (string)aParams[0]; - break; - } - } - - if (!found) - throw new Exception("label not exists"); - } - - /// - /// - /// - /// - /// - public void SetHook(string label, TransitionHook callback) - { - int cnt = _items.Length; - bool found = false; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.label == label) - { - item.hook = callback; - found = true; - break; - } - else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) - { - item.tweenConfig.endHook = callback; - found = true; - break; - } - } - if (!found) - throw new Exception("label not exists"); - } - - /// - /// - /// - public void ClearHooks() - { - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - item.hook = null; - if (item.tweenConfig != null) - item.tweenConfig.endHook = null; - } - } - - /// - /// - /// - /// - /// - public void SetTarget(string label, GObject newTarget) - { - int cnt = _items.Length; - bool found = false; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.label == label) - { - item.targetId = (newTarget == _owner || newTarget == null) ? string.Empty : newTarget.id; - if (_playing) - { - if (item.targetId.Length > 0) - item.target = _owner.GetChildById(item.targetId); - else - item.target = _owner; - } - else - item.target = null; - found = true; - } - } - if (!found) - throw new Exception("label not exists"); - } - - /// - /// - /// - /// - /// - public void SetDuration(string label, float value) - { - int cnt = _items.Length; - bool found = false; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.tweenConfig != null && item.label == label) - { - item.tweenConfig.duration = value; - found = true; - } - } - - if (!found) - throw new Exception("label not exists or not a tween label"); - } - - /// - /// - /// - /// - /// - public float GetLabelTime(string label) - { - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.label == label) - return item.time; - else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) - return item.time + item.tweenConfig.duration; - } - - return float.NaN; - } - - /// - /// - /// - public float timeScale - { - get { return _timeScale; } - set - { - if (_timeScale != value) - { - _timeScale = value; - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.tweener != null) - item.tweener.SetTimeScale(value); - else if (item.type == TransitionActionType.Transition) - { - if (((TValue_Transition)item.value).trans != null) - ((TValue_Transition)item.value).trans.timeScale = value; - } - else if (item.type == TransitionActionType.Animation) - { - if (item.target != null) - ((IAnimationGear)item.target).timeScale = value; - } - } - } - } - } - - /// - /// - /// - public bool ignoreEngineTimeScale - { - get { return _ignoreEngineTimeScale; } - set - { - if (_ignoreEngineTimeScale != value) - { - _ignoreEngineTimeScale = value; - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.tweener != null) - item.tweener.SetIgnoreEngineTimeScale(value); - else if (item.type == TransitionActionType.Transition) - { - if (((TValue_Transition)item.value).trans != null) - ((TValue_Transition)item.value).trans.ignoreEngineTimeScale = value; - } - else if (item.type == TransitionActionType.Animation) - { - if (item.target != null) - ((IAnimationGear)item.target).ignoreEngineTimeScale = value; - } - } - } - } - } - - internal void UpdateFromRelations(string targetId, float dx, float dy) - { - int cnt = _items.Length; - if (cnt == 0) - return; - - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.type == TransitionActionType.XY && item.targetId == targetId) - { - if (item.tweenConfig != null) - { - if (!item.tweenConfig.startValue.b3) - { - item.tweenConfig.startValue.f1 += dx; - item.tweenConfig.startValue.f2 += dy; - } - if (!item.tweenConfig.endValue.b3) - { - item.tweenConfig.endValue.f1 += dx; - item.tweenConfig.endValue.f2 += dy; - } - } - else - { - if (!((TValue)item.value).b3) - { - ((TValue)item.value).f1 += dx; - ((TValue)item.value).f2 += dy; - } - } - } - } - } - - internal void OnOwnerAddedToStage() - { - if (_autoPlay && !_playing) - Play(_autoPlayTimes, _autoPlayDelay, null); - } - - internal void OnOwnerRemovedFromStage() - { - if ((_options & OPTION_AUTO_STOP_DISABLED) == 0) - Stop((_options & OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false); - } - - void OnDelayedPlay() - { - InternalPlay(); - - _playing = _totalTasks > 0; - if (_playing) - { - if ((_options & OPTION_IGNORE_DISPLAY_CONTROLLER) != 0) - { - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.target != null && item.target != _owner) - item.displayLockToken = item.target.AddDisplayLock(); - } - } - } - else if (_onComplete != null) - { - PlayCompleteCallback func = _onComplete; - _onComplete = null; - func(); - } - } - - void InternalPlay() - { - _ownerBaseX = _owner.x; - _ownerBaseY = _owner.y; - - _totalTasks = 1; //prevent to complete inside the loop - - bool needSkipAnimations = false; - int cnt = _items.Length; - if (!_reversed) - { - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.target == null) - continue; - - if (item.type == TransitionActionType.Animation && _startTime != 0 && item.time <= _startTime) - { - needSkipAnimations = true; - ((TValue_Animation)item.value).flag = false; - } - else - PlayItem(item); - } - } - else - { - for (int i = cnt - 1; i >= 0; i--) - { - TransitionItem item = _items[i]; - if (item.target == null) - continue; - - PlayItem(item); - } - } - - if (needSkipAnimations) - SkipAnimations(); - - _totalTasks--; - } - - void PlayItem(TransitionItem item) - { - float time; - if (item.tweenConfig != null) - { - if (_reversed) - time = (_totalDuration - item.time - item.tweenConfig.duration); - else - time = item.time; - - if (_endTime == -1 || time <= _endTime) - { - TValue startValue; - TValue endValue; - - if (_reversed) - { - startValue = item.tweenConfig.endValue; - endValue = item.tweenConfig.startValue; - } - else - { - startValue = item.tweenConfig.startValue; - endValue = item.tweenConfig.endValue; - } - - ((TValue)item.value).b1 = startValue.b1 || endValue.b1; - ((TValue)item.value).b2 = startValue.b2 || endValue.b2; - - switch (item.type) - { - case TransitionActionType.XY: - case TransitionActionType.Size: - case TransitionActionType.Scale: - case TransitionActionType.Skew: - item.tweener = GTween.To(startValue.vec2, endValue.vec2, item.tweenConfig.duration); - break; - - case TransitionActionType.Alpha: - case TransitionActionType.Rotation: - item.tweener = GTween.To(startValue.f1, endValue.f1, item.tweenConfig.duration); - break; - - case TransitionActionType.Color: - item.tweener = GTween.To(startValue.color, endValue.color, item.tweenConfig.duration); - break; - - case TransitionActionType.ColorFilter: - item.tweener = GTween.To(startValue.vec4, endValue.vec4, item.tweenConfig.duration); - break; - } - - item.tweener.SetDelay(time) - .SetEase(item.tweenConfig.easeType, item.tweenConfig.customEase) - .SetRepeat(item.tweenConfig.repeat, item.tweenConfig.yoyo) - .SetTimeScale(_timeScale) - .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) - .SetTarget(item) - .SetListener(this); - - if (_endTime >= 0) - item.tweener.SetBreakpoint(_endTime - time); - - _totalTasks++; - } - } - else if (item.type == TransitionActionType.Shake) - { - TValue_Shake value = (TValue_Shake)item.value; - - if (_reversed) - time = (_totalDuration - item.time - value.duration); - else - time = item.time; - - if (_endTime == -1 || time <= _endTime) - { - value.lastOffset.Set(0, 0); - value.offset.Set(0, 0); - item.tweener = GTween.Shake(Vector3.zero, value.amplitude, value.duration) - .SetDelay(time) - .SetTimeScale(_timeScale) - .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) - .SetTarget(item) - .SetListener(this); - - if (_endTime >= 0) - item.tweener.SetBreakpoint(_endTime - item.time); - - _totalTasks++; - } - } - else - { - if (_reversed) - time = (_totalDuration - item.time); - else - time = item.time; - - if (time <= _startTime) - { - ApplyValue(item); - CallHook(item, false); - } - else if (_endTime == -1 || time <= _endTime) - { - _totalTasks++; - item.tweener = GTween.DelayedCall(time) - .SetTimeScale(_timeScale) - .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) - .SetTarget(item) - .OnComplete(_delayedCallDelegate2); - } - } - - if (item.tweener != null) - item.tweener.Seek(_startTime); - } - - void SkipAnimations() - { - int frame; - float playStartTime; - float playTotalTime; - TValue_Animation value; - IAnimationGear target; - TransitionItem item; - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - item = _items[i]; - if (item.type != TransitionActionType.Animation || item.time > _startTime) - continue; - - value = (TValue_Animation)item.value; - if (value.flag) - continue; - - target = (IAnimationGear)item.target; - frame = target.frame; - playStartTime = target.playing ? 0 : -1; - playTotalTime = 0; - - for (int j = i; j < cnt; j++) - { - item = _items[j]; - if (item.type != TransitionActionType.Animation || item.target != target || item.time > _startTime) - continue; - - value = (TValue_Animation)item.value; - value.flag = true; - - if (value.frame != -1) - { - frame = value.frame; - if (value.playing) - playStartTime = item.time; - else - playStartTime = -1; - playTotalTime = 0; - } - else - { - if (value.playing) - { - if (playStartTime < 0) - playStartTime = item.time; - } - else - { - if (playStartTime >= 0) - playTotalTime += (item.time - playStartTime); - playStartTime = -1; - } - } - - CallHook(item, false); - } - - if (playStartTime >= 0) - playTotalTime += (_startTime - playStartTime); - - target.playing = playStartTime >= 0; - target.frame = frame; - if (playTotalTime > 0) - target.Advance(playTotalTime); - } - } - - void OnDelayedPlayItem(GTweener tweener) - { - TransitionItem item = (TransitionItem)tweener.target; - item.tweener = null; - _totalTasks--; - - ApplyValue(item); - CallHook(item, false); - - CheckAllComplete(); - } - - public void OnTweenStart(GTweener tweener) - { - TransitionItem item = (TransitionItem)tweener.target; - - if (item.type == TransitionActionType.XY || item.type == TransitionActionType.Size) //位置和大小要到start才最终确认起始值 - { - TValue startValue; - TValue endValue; - - if (_reversed) - { - startValue = item.tweenConfig.endValue; - endValue = item.tweenConfig.startValue; - } - else - { - startValue = item.tweenConfig.startValue; - endValue = item.tweenConfig.endValue; - } - - if (item.type == TransitionActionType.XY) - { - if (item.target != _owner) - { - if (!startValue.b1) - tweener.startValue.x = item.target.x; - else if (startValue.b3) //percent - tweener.startValue.x = startValue.f1 * _owner.width; - - if (!startValue.b2) - tweener.startValue.y = item.target.y; - else if (startValue.b3) //percent - tweener.startValue.y = startValue.f2 * _owner.height; - - if (!endValue.b1) - tweener.endValue.x = tweener.startValue.x; - else if (endValue.b3) - tweener.endValue.x = endValue.f1 * _owner.width; - - if (!endValue.b2) - tweener.endValue.y = tweener.startValue.y; - else if (endValue.b3) - tweener.endValue.y = endValue.f2 * _owner.height; - } - else - { - if (!startValue.b1) - tweener.startValue.x = item.target.x - _ownerBaseX; - if (!startValue.b2) - tweener.startValue.y = item.target.y - _ownerBaseY; - - if (!endValue.b1) - tweener.endValue.x = tweener.startValue.x; - if (!endValue.b2) - tweener.endValue.y = tweener.startValue.y; - } - } - else - { - if (!startValue.b1) - tweener.startValue.x = item.target.width; - if (!startValue.b2) - tweener.startValue.y = item.target.height; - - if (!endValue.b1) - tweener.endValue.x = tweener.startValue.x; - if (!endValue.b2) - tweener.endValue.y = tweener.startValue.y; - } - - if (item.tweenConfig.path != null) - { - ((TValue)item.value).b1 = ((TValue)item.value).b2 = true; - tweener.SetPath(item.tweenConfig.path); - } - } - - CallHook(item, false); - } - - public void OnTweenUpdate(GTweener tweener) - { - TransitionItem item = (TransitionItem)tweener.target; - switch (item.type) - { - case TransitionActionType.XY: - case TransitionActionType.Size: - case TransitionActionType.Scale: - case TransitionActionType.Skew: - ((TValue)item.value).vec2 = tweener.value.vec2; - if (item.tweenConfig.path != null) - { - ((TValue)item.value).f1 += tweener.startValue.x; - ((TValue)item.value).f2 += tweener.startValue.y; - } - break; - - case TransitionActionType.Alpha: - case TransitionActionType.Rotation: - ((TValue)item.value).f1 = tweener.value.x; - break; - - case TransitionActionType.Color: - ((TValue)item.value).color = tweener.value.color; - break; - - case TransitionActionType.ColorFilter: - ((TValue)item.value).vec4 = tweener.value.vec4; - break; - - case TransitionActionType.Shake: - ((TValue_Shake)item.value).offset = tweener.deltaValue.vec2; - break; - } - ApplyValue(item); - } - - public void OnTweenComplete(GTweener tweener) - { - TransitionItem item = (TransitionItem)tweener.target; - item.tweener = null; - _totalTasks--; - - if (tweener.allCompleted) //当整体播放结束时间在这个tween的中间时不应该调用结尾钩子 - CallHook(item, true); - - CheckAllComplete(); - } - - void OnPlayTransCompleted(TransitionItem item) - { - _totalTasks--; - - CheckAllComplete(); - } - - void CallHook(TransitionItem item, bool tweenEnd) - { - if (tweenEnd) - { - if (item.tweenConfig != null && item.tweenConfig.endHook != null) - item.tweenConfig.endHook(); - } - else - { - if (item.time >= _startTime && item.hook != null) - item.hook(); - } - } - - void CheckAllComplete() - { - if (_playing && _totalTasks == 0) - { - if (_totalTimes < 0) - { - InternalPlay(); - if (_totalTasks == 0) - GTween.DelayedCall(0).SetTarget(this).OnComplete(_checkAllDelegate); - } - else - { - _totalTimes--; - if (_totalTimes > 0) - { - InternalPlay(); - if (_totalTasks == 0) - GTween.DelayedCall(0).SetTarget(this).OnComplete(_checkAllDelegate); - } - else - { - _playing = false; - - int cnt = _items.Length; - for (int i = 0; i < cnt; i++) - { - TransitionItem item = _items[i]; - if (item.target != null && item.displayLockToken != 0) - { - item.target.ReleaseDisplayLock(item.displayLockToken); - item.displayLockToken = 0; - } - } - - if (_onComplete != null) - { - PlayCompleteCallback func = _onComplete; - _onComplete = null; - func(); - } - } - } - } - } - - void ApplyValue(TransitionItem item) - { - item.target._gearLocked = true; - - switch (item.type) - { - case TransitionActionType.XY: - { - TValue value = (TValue)item.value; - if (item.target == _owner) - { - if (value.b1 && value.b2) - item.target.SetXY(value.f1 + _ownerBaseX, value.f2 + _ownerBaseY); - else if (value.b1) - item.target.x = value.f1 + _ownerBaseX; - else - item.target.y = value.f2 + _ownerBaseY; - } - else - { - if (value.b3) //position in percent - { - if (value.b1 && value.b2) - item.target.SetXY(value.f1 * _owner.width, value.f2 * _owner.height); - else if (value.b1) - item.target.x = value.f1 * _owner.width; - else if (value.b2) - item.target.y = value.f2 * _owner.height; - } - else - { - if (value.b1 && value.b2) - item.target.SetXY(value.f1, value.f2); - else if (value.b1) - item.target.x = value.f1; - else if (value.b2) - item.target.y = value.f2; - } - } - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - } - break; - - case TransitionActionType.Size: - { - TValue value = (TValue)item.value; - if (!value.b1) - value.f1 = item.target.width; - if (!value.b2) - value.f2 = item.target.height; - item.target.SetSize(value.f1, value.f2); - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - } - break; - - case TransitionActionType.Pivot: - item.target.SetPivot(((TValue)item.value).f1, ((TValue)item.value).f2, item.target.pivotAsAnchor); - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - break; - - case TransitionActionType.Alpha: - item.target.alpha = ((TValue)item.value).f1; - break; - - case TransitionActionType.Rotation: - item.target.rotation = ((TValue)item.value).f1; - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - break; - - case TransitionActionType.Scale: - item.target.SetScale(((TValue)item.value).f1, ((TValue)item.value).f2); - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - break; - - case TransitionActionType.Skew: - item.target.skew = ((TValue)item.value).vec2; - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - break; - - case TransitionActionType.Color: - ((IColorGear)item.target).color = ((TValue)item.value).color; - break; - - case TransitionActionType.Animation: - { - TValue_Animation value = (TValue_Animation)item.value; - if (value.frame >= 0) - ((IAnimationGear)item.target).frame = value.frame; - ((IAnimationGear)item.target).playing = value.playing; - ((IAnimationGear)item.target).timeScale = _timeScale; - ((IAnimationGear)item.target).ignoreEngineTimeScale = _ignoreEngineTimeScale; - if (value.animationName != null) - ((GLoader3D)item.target).animationName = value.animationName; - if (value.skinName != null) - ((GLoader3D)item.target).skinName = value.skinName; - } - break; - - case TransitionActionType.Visible: - item.target.visible = ((TValue_Visible)item.value).visible; - break; - - case TransitionActionType.Shake: - { - TValue_Shake value = (TValue_Shake)item.value; - item.target.SetXY(item.target.x - value.lastOffset.x + value.offset.x, item.target.y - value.lastOffset.y + value.offset.y); - value.lastOffset = value.offset; - - if (invalidateBatchingEveryFrame) - _owner.InvalidateBatchingState(true); - } - break; - - case TransitionActionType.Transition: - if (_playing) - { - TValue_Transition value = (TValue_Transition)item.value; - if (value.trans != null) - { - _totalTasks++; - - float startTime = _startTime > item.time ? (_startTime - item.time) : 0; - float endTime = _endTime >= 0 ? (_endTime - item.time) : -1; - if (value.stopTime >= 0 && (endTime < 0 || endTime > value.stopTime)) - endTime = value.stopTime; - value.trans.timeScale = _timeScale; - value.trans.ignoreEngineTimeScale = _ignoreEngineTimeScale; - value.trans._Play(value.playTimes, 0, startTime, endTime, value.playCompleteDelegate, _reversed); - } - } - break; - - case TransitionActionType.Sound: - if (_playing && item.time >= _startTime) - { - TValue_Sound value = (TValue_Sound)item.value; - if (value.audioClip == null) - { - if (UIConfig.soundLoader == null || value.sound.StartsWith(UIPackage.URL_PREFIX)) - value.audioClip = UIPackage.GetItemAssetByURL(value.sound) as NAudioClip; - else - value.audioClip = UIConfig.soundLoader(value.sound); - } - - if (value.audioClip != null && value.audioClip.nativeClip != null) - Stage.inst.PlayOneShotSound(value.audioClip.nativeClip, value.volume); - } - break; - - case TransitionActionType.ColorFilter: - { - TValue value = (TValue)item.value; - ColorFilter cf = item.target.filter as ColorFilter; - if (cf == null) - { - cf = new ColorFilter(); - item.target.filter = cf; - } - else - cf.Reset(); - - cf.AdjustBrightness(value.f1); - cf.AdjustContrast(value.f2); - cf.AdjustSaturation(value.f3); - cf.AdjustHue(value.f4); - } - break; - - case TransitionActionType.Text: - item.target.text = ((TValue_Text)item.value).text; - break; - - case TransitionActionType.Icon: - item.target.icon = ((TValue_Text)item.value).text; - break; - } - - item.target._gearLocked = false; - } - - public void Setup(ByteBuffer buffer) - { - this.name = buffer.ReadS(); - _options = buffer.ReadInt(); - _autoPlay = buffer.ReadBool(); - _autoPlayTimes = buffer.ReadInt(); - _autoPlayDelay = buffer.ReadFloat(); - - int cnt = buffer.ReadShort(); - _items = new TransitionItem[cnt]; - for (int i = 0; i < cnt; i++) - { - int dataLen = buffer.ReadShort(); - int curPos = buffer.position; - - buffer.Seek(curPos, 0); - - TransitionItem item = new TransitionItem((TransitionActionType)buffer.ReadByte()); - _items[i] = item; - - item.time = buffer.ReadFloat(); - int targetId = buffer.ReadShort(); - if (targetId < 0) - item.targetId = string.Empty; - else - item.targetId = _owner.GetChildAt(targetId).id; - item.label = buffer.ReadS(); - - if (buffer.ReadBool()) - { - buffer.Seek(curPos, 1); - - item.tweenConfig = new TweenConfig(); - item.tweenConfig.duration = buffer.ReadFloat(); - if (item.time + item.tweenConfig.duration > _totalDuration) - _totalDuration = item.time + item.tweenConfig.duration; - item.tweenConfig.easeType = (EaseType)buffer.ReadByte(); - item.tweenConfig.repeat = buffer.ReadInt(); - item.tweenConfig.yoyo = buffer.ReadBool(); - item.tweenConfig.endLabel = buffer.ReadS(); - - buffer.Seek(curPos, 2); - - DecodeValue(item, buffer, item.tweenConfig.startValue); - - buffer.Seek(curPos, 3); - - DecodeValue(item, buffer, item.tweenConfig.endValue); - - if (buffer.version >= 2) - { - var pts = buffer.ReadPath(); - if (pts.Count > 0) - { - item.tweenConfig.path = new GPath(); - item.tweenConfig.path.Create(pts); - } - } - - if (buffer.version >= 4 && item.tweenConfig.easeType == EaseType.Custom) - { - var pts = buffer.ReadPath(); - if (pts.Count > 0) - { - item.tweenConfig.customEase = new CustomEase(); - item.tweenConfig.customEase.Create(pts); - } - } - } - else - { - if (item.time > _totalDuration) - _totalDuration = item.time; - - buffer.Seek(curPos, 2); - - DecodeValue(item, buffer, item.value); - } - - buffer.position = curPos + dataLen; - } - } - - void DecodeValue(TransitionItem item, ByteBuffer buffer, object value) - { - switch (item.type) - { - case TransitionActionType.XY: - case TransitionActionType.Size: - case TransitionActionType.Pivot: - case TransitionActionType.Skew: - { - TValue tvalue = (TValue)value; - tvalue.b1 = buffer.ReadBool(); - tvalue.b2 = buffer.ReadBool(); - tvalue.f1 = buffer.ReadFloat(); - tvalue.f2 = buffer.ReadFloat(); - - if (buffer.version >= 2 && item.type == TransitionActionType.XY) - tvalue.b3 = buffer.ReadBool(); //percent - } - break; - - case TransitionActionType.Alpha: - case TransitionActionType.Rotation: - ((TValue)value).f1 = buffer.ReadFloat(); - break; - - case TransitionActionType.Scale: - ((TValue)value).f1 = buffer.ReadFloat(); - ((TValue)value).f2 = buffer.ReadFloat(); - break; - - case TransitionActionType.Color: - ((TValue)value).color = buffer.ReadColor(); - break; - - case TransitionActionType.Animation: - ((TValue_Animation)value).playing = buffer.ReadBool(); - ((TValue_Animation)value).frame = buffer.ReadInt(); - if (buffer.version >= 6) - { - ((TValue_Animation)value).animationName = buffer.ReadS(); - ((TValue_Animation)value).skinName = buffer.ReadS(); - } - break; - - case TransitionActionType.Visible: - ((TValue_Visible)value).visible = buffer.ReadBool(); - break; - - case TransitionActionType.Sound: - ((TValue_Sound)value).sound = buffer.ReadS(); - ((TValue_Sound)value).volume = buffer.ReadFloat(); - break; - - case TransitionActionType.Transition: - ((TValue_Transition)value).transName = buffer.ReadS(); - ((TValue_Transition)value).playTimes = buffer.ReadInt(); - ((TValue_Transition)value).playCompleteDelegate = () => { OnPlayTransCompleted(item); }; - break; - - case TransitionActionType.Shake: - ((TValue_Shake)value).amplitude = buffer.ReadFloat(); - ((TValue_Shake)value).duration = buffer.ReadFloat(); - break; - - case TransitionActionType.ColorFilter: - { - TValue tvalue = (TValue)value; - tvalue.f1 = buffer.ReadFloat(); - tvalue.f2 = buffer.ReadFloat(); - tvalue.f3 = buffer.ReadFloat(); - tvalue.f4 = buffer.ReadFloat(); - } - break; - - case TransitionActionType.Text: - case TransitionActionType.Icon: - ((TValue_Text)value).text = buffer.ReadS(); - break; - } - } - } - - class TransitionItem - { - public float time; - public string targetId; - public TransitionActionType type; - public TweenConfig tweenConfig; - public string label; - public object value; - public TransitionHook hook; - - //running properties - public GTweener tweener; - public GObject target; - public uint displayLockToken; - - public TransitionItem(TransitionActionType type) - { - this.type = type; - - switch (type) - { - case TransitionActionType.XY: - case TransitionActionType.Size: - case TransitionActionType.Scale: - case TransitionActionType.Pivot: - case TransitionActionType.Skew: - case TransitionActionType.Alpha: - case TransitionActionType.Rotation: - case TransitionActionType.Color: - case TransitionActionType.ColorFilter: - value = new TValue(); - break; - - case TransitionActionType.Animation: - value = new TValue_Animation(); - break; - - case TransitionActionType.Shake: - value = new TValue_Shake(); - break; - - case TransitionActionType.Sound: - value = new TValue_Sound(); - break; - - case TransitionActionType.Transition: - value = new TValue_Transition(); - break; - - case TransitionActionType.Visible: - value = new TValue_Visible(); - break; - - case TransitionActionType.Text: - case TransitionActionType.Icon: - value = new TValue_Text(); - break; - } - } - } - - class TweenConfig - { - public float duration; - public EaseType easeType; - public CustomEase customEase; - public int repeat; - public bool yoyo; - - public TValue startValue; - public TValue endValue; - - public string endLabel; - public TransitionHook endHook; - - public GPath path; - - public TweenConfig() - { - easeType = EaseType.QuadOut; - startValue = new TValue(); - endValue = new TValue(); - } - } - - class TValue_Visible - { - public bool visible; - } - - class TValue_Animation - { - public int frame; - public bool playing; - public bool flag; - public string animationName; - public string skinName; - } - - class TValue_Sound - { - public string sound; - public float volume; - public NAudioClip audioClip; - } - - class TValue_Transition - { - public string transName; - public int playTimes; - public Transition trans; - public PlayCompleteCallback playCompleteDelegate; - public float stopTime; - } - - class TValue_Shake - { - public float amplitude; - public float duration; - public Vector2 lastOffset; - public Vector2 offset; - } - - class TValue_Text - { - public string text; - } - - class TValue - { - public float f1; - public float f2; - public float f3; - public float f4; - public bool b1; - public bool b2; - public bool b3; - - public TValue() - { - b1 = true; - b2 = true; - } - - public void Copy(TValue source) - { - this.f1 = source.f1; - this.f2 = source.f2; - this.f3 = source.f3; - this.f4 = source.f4; - this.b1 = source.b1; - this.b2 = source.b2; - } - - public Vector2 vec2 - { - get { return new Vector2(f1, f2); } - set - { - f1 = value.x; - f2 = value.y; - } - } - - public Vector4 vec4 - { - get { return new Vector4(f1, f2, f3, f4); } - set - { - f1 = value.x; - f2 = value.y; - f3 = value.z; - f4 = value.w; - } - } - - public Color color - { - get { return new Color(f1, f2, f3, f4); } - set - { - f1 = value.r; - f2 = value.g; - f3 = value.b; - f4 = value.a; - } - } - } -} +using System; +using System.Collections.Generic; +using FairyGUI.Utils; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + public delegate void PlayCompleteCallback(); + + /// + /// + /// + public delegate void TransitionHook(); + + /// + /// + /// + public class Transition : ITweenListener + { + /// + /// 动效的名称。在编辑器里设定。 + /// + public string name { get; private set; } + + /// + /// 当你启动了自动合批,动效里有涉及到XY、大小、旋转等的改变,如果你观察到元件的显示深度在播放过程中有错误,可以开启这个选项。 + /// + public bool invalidateBatchingEveryFrame; + + GComponent _owner; + TransitionItem[] _items; + int _totalTimes; + int _totalTasks; + bool _playing; + bool _paused; + float _ownerBaseX; + float _ownerBaseY; + PlayCompleteCallback _onComplete; + int _options; + bool _reversed; + float _totalDuration; + bool _autoPlay; + int _autoPlayTimes; + float _autoPlayDelay; + float _timeScale; + bool _ignoreEngineTimeScale; + float _startTime; + float _endTime; + GTweenCallback _delayedCallDelegate; + GTweenCallback _checkAllDelegate; + GTweenCallback1 _delayedCallDelegate2; + + const int OPTION_IGNORE_DISPLAY_CONTROLLER = 1; + const int OPTION_AUTO_STOP_DISABLED = 2; + const int OPTION_AUTO_STOP_AT_END = 4; + + public Transition(GComponent owner) + { + _owner = owner; + _timeScale = 1; + _ignoreEngineTimeScale = true; + + _delayedCallDelegate = OnDelayedPlay; + _delayedCallDelegate2 = OnDelayedPlayItem; + _checkAllDelegate = CheckAllComplete; + } + + /// + /// + /// + public void Play() + { + _Play(1, 0, 0, -1, null, false); + } + + /// + /// + /// + /// + public void Play(PlayCompleteCallback onComplete) + { + _Play(1, 0, 0, -1, onComplete, false); + } + + /// + /// + /// + /// + /// + /// + public void Play(int times, float delay, PlayCompleteCallback onComplete) + { + _Play(times, delay, 0, -1, onComplete, false); + } + + /// + /// + /// + /// + /// + /// + /// + /// + public void Play(int times, float delay, float startTime, float endTime, PlayCompleteCallback onComplete) + { + _Play(times, delay, startTime, endTime, onComplete, false); + } + + /// + /// + /// + public void PlayReverse() + { + _Play(1, 0, 0, -1, null, true); + } + + /// + /// + /// + /// + public void PlayReverse(PlayCompleteCallback onComplete) + { + _Play(1, 0, 0, -1, onComplete, true); + } + + /// + /// + /// + /// + /// + /// + public void PlayReverse(int times, float delay, PlayCompleteCallback onComplete) + { + _Play(times, delay, 0, -1, onComplete, true); + } + + /// + /// + /// + /// + public void ChangePlayTimes(int value) + { + _totalTimes = value; + } + + /// + /// 设置动效是否自动播放。 + /// + /// + /// + /// + public void SetAutoPlay(bool autoPlay, int times, float delay) + { + if (_autoPlay != autoPlay) + { + _autoPlay = autoPlay; + _autoPlayTimes = times; + _autoPlayDelay = delay; + if (_autoPlay) + { + if (_owner.onStage) + Play(times, delay, null); + } + else + { + if (!_owner.onStage) + Stop(false, true); + } + } + } + + void _Play(int times, float delay, float startTime, float endTime, PlayCompleteCallback onComplete, bool reverse) + { + Stop(true, true); + + _totalTimes = times; + _reversed = reverse; + _startTime = startTime; + _endTime = endTime; + _playing = true; + _paused = false; + _onComplete = onComplete; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + { + if (item.targetId.Length > 0) + item.target = _owner.GetChildById(item.targetId); + else + item.target = _owner; + } + else if (item.target != _owner && item.target.parent != _owner) //maybe removed + item.target = null; + + if (item.target != null && item.type == TransitionActionType.Transition) + { + TValue_Transition value = (TValue_Transition)item.value; + Transition trans = ((GComponent)item.target).GetTransition(value.transName); + if (trans == this) + trans = null; + if (trans != null) + { + if (value.playTimes == 0) //stop + { + int j; + for (j = i - 1; j >= 0; j--) + { + TransitionItem item2 = _items[j]; + if (item2.type == TransitionActionType.Transition) + { + TValue_Transition value2 = (TValue_Transition)item2.value; + if (value2.trans == trans) + { + value2.stopTime = item.time - item2.time; + break; + } + } + } + if (j < 0) + value.stopTime = 0; + else + trans = null; //no need to handle stop anymore + } + else + value.stopTime = -1; + } + value.trans = trans; + } + } + + if (delay == 0) + OnDelayedPlay(); + else + GTween.DelayedCall(delay).SetTarget(this).OnComplete(_delayedCallDelegate); + } + + /// + /// + /// + public void Stop() + { + Stop(true, false); + } + + /// + /// + /// + /// + /// + public void Stop(bool setToComplete, bool processCallback) + { + if (!_playing) + return; + + _playing = false; + _totalTasks = 0; + _totalTimes = 0; + PlayCompleteCallback func = _onComplete; + _onComplete = null; + + GTween.Kill(this);//delay start + + int cnt = _items.Length; + if (_reversed) + { + for (int i = cnt - 1; i >= 0; i--) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + StopItem(item, setToComplete); + } + } + else + { + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + StopItem(item, setToComplete); + } + } + + if (processCallback && func != null) + func(); + + } + + void StopItem(TransitionItem item, bool setToComplete) + { + if (item.displayLockToken != 0) + { + item.target.ReleaseDisplayLock(item.displayLockToken); + item.displayLockToken = 0; + } + + if (item.tweener != null) + { + item.tweener.Kill(setToComplete); + item.tweener = null; + + if (item.type == TransitionActionType.Shake && !setToComplete) //震动必须归位,否则下次就越震越远了。 + { + item.target._gearLocked = true; + item.target.SetXY(item.target.x - ((TValue_Shake)item.value).lastOffset.x, item.target.y - ((TValue_Shake)item.value).lastOffset.y); + item.target._gearLocked = false; + + _owner.InvalidateBatchingState(true); + } + } + + if (item.type == TransitionActionType.Transition) + { + TValue_Transition value = (TValue_Transition)item.value; + if (value.trans != null) + value.trans.Stop(setToComplete, false); + } + } + + /// + /// + /// + /// + public void SetPaused(bool paused) + { + if (!_playing || _paused == paused) + return; + + _paused = paused; + GTweener tweener = GTween.GetTween(this); + if (tweener != null) + tweener.SetPaused(paused); + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + if (item.type == TransitionActionType.Transition) + { + if (((TValue_Transition)item.value).trans != null) + ((TValue_Transition)item.value).trans.SetPaused(paused); + } + else if (item.type == TransitionActionType.Animation) + { + if (paused) + { + ((TValue_Animation)item.value).flag = ((IAnimationGear)item.target).playing; + ((IAnimationGear)item.target).playing = false; + } + else + ((IAnimationGear)item.target).playing = ((TValue_Animation)item.value).flag; + } + + if (item.tweener != null) + item.tweener.SetPaused(paused); + } + } + + public void Dispose() + { + if (_playing) + GTween.Kill(this);//delay start + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweener != null) + { + item.tweener.Kill(); + item.tweener = null; + } + + item.target = null; + item.hook = null; + if (item.tweenConfig != null) + item.tweenConfig.endHook = null; + } + + _playing = false; + _onComplete = null; + } + + /// + /// + /// + public bool playing + { + get { return _playing; } + } + + /// + /// transition's total duration, maybe zero when the transition only has one frame + /// + public float totalDuration + { + get { return _totalDuration; } + } + + /// + /// + /// + /// + /// + public void SetValue(string label, params object[] aParams) + { + int cnt = _items.Length; + object value; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + { + if (item.tweenConfig != null) + value = item.tweenConfig.startValue; + else + value = item.value; + found = true; + } + else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) + { + value = item.tweenConfig.endValue; + found = true; + } + else + continue; + + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Pivot: + case TransitionActionType.Scale: + case TransitionActionType.Skew: + { + TValue tvalue = (TValue)value; + tvalue.b1 = true; + tvalue.b2 = true; + tvalue.f1 = Convert.ToSingle(aParams[0]); + tvalue.f2 = Convert.ToSingle(aParams[1]); + } + break; + + case TransitionActionType.Alpha: + ((TValue)value).f1 = Convert.ToSingle(aParams[0]); + break; + + case TransitionActionType.Rotation: + ((TValue)value).f1 = Convert.ToSingle(aParams[0]); + break; + + case TransitionActionType.Color: + ((TValue)value).color = (Color)aParams[0]; + break; + + case TransitionActionType.Animation: + { + TValue_Animation tvalue = (TValue_Animation)value; + tvalue.frame = Convert.ToInt32(aParams[0]); + if (aParams.Length > 1) + tvalue.playing = Convert.ToBoolean(aParams[1]); + if (aParams.Length > 2) + tvalue.animationName = (string)aParams[2]; + if (aParams.Length > 3) + tvalue.skinName = (string)aParams[3]; + } + break; + + case TransitionActionType.Visible: + ((TValue_Visible)value).visible = Convert.ToBoolean(aParams[0]); + break; + + case TransitionActionType.Sound: + { + TValue_Sound tvalue = (TValue_Sound)value; + tvalue.sound = (string)aParams[0]; + if (aParams.Length > 1) + tvalue.volume = Convert.ToSingle(aParams[1]); + } + break; + + case TransitionActionType.Transition: + { + TValue_Transition tvalue = (TValue_Transition)value; + tvalue.transName = (string)aParams[0]; + if (aParams.Length > 1) + tvalue.playTimes = Convert.ToInt32(aParams[1]); + } + break; + + case TransitionActionType.Shake: + { + ((TValue_Shake)value).amplitude = Convert.ToSingle(aParams[0]); + if (aParams.Length > 1) + ((TValue_Shake)value).duration = Convert.ToSingle(aParams[1]); + } + break; + + case TransitionActionType.ColorFilter: + { + TValue tvalue = (TValue)value; + tvalue.f1 = Convert.ToSingle(aParams[0]); + tvalue.f2 = Convert.ToSingle(aParams[1]); + tvalue.f3 = Convert.ToSingle(aParams[2]); + tvalue.f4 = Convert.ToSingle(aParams[3]); + } + break; + + case TransitionActionType.Text: + case TransitionActionType.Icon: + ((TValue_Text)value).text = (string)aParams[0]; + break; + } + } + + if (!found) + throw new Exception("label not exists"); + } + + /// + /// + /// + /// + /// + public void SetHook(string label, TransitionHook callback) + { + int cnt = _items.Length; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + { + item.hook = callback; + found = true; + break; + } + else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) + { + item.tweenConfig.endHook = callback; + found = true; + break; + } + } + if (!found) + throw new Exception("label not exists"); + } + + /// + /// + /// + public void ClearHooks() + { + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + item.hook = null; + if (item.tweenConfig != null) + item.tweenConfig.endHook = null; + } + } + + /// + /// + /// + /// + /// + public void SetTarget(string label, GObject newTarget) + { + int cnt = _items.Length; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + { + item.targetId = (newTarget == _owner || newTarget == null) ? string.Empty : newTarget.id; + if (_playing) + { + if (item.targetId.Length > 0) + item.target = _owner.GetChildById(item.targetId); + else + item.target = _owner; + } + else + item.target = null; + found = true; + } + } + if (!found) + throw new Exception("label not exists"); + } + + /// + /// + /// + /// + /// + public void SetDuration(string label, float value) + { + int cnt = _items.Length; + bool found = false; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweenConfig != null && item.label == label) + { + item.tweenConfig.duration = value; + found = true; + } + } + + if (!found) + throw new Exception("label not exists or not a tween label"); + } + + /// + /// + /// + /// + /// + public float GetLabelTime(string label) + { + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.label == label) + return item.time; + else if (item.tweenConfig != null && item.tweenConfig.endLabel == label) + return item.time + item.tweenConfig.duration; + } + + return float.NaN; + } + + /// + /// + /// + public float timeScale + { + get { return _timeScale; } + set + { + if (_timeScale != value) + { + _timeScale = value; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweener != null) + item.tweener.SetTimeScale(value); + else if (item.type == TransitionActionType.Transition) + { + if (((TValue_Transition)item.value).trans != null) + ((TValue_Transition)item.value).trans.timeScale = value; + } + else if (item.type == TransitionActionType.Animation) + { + if (item.target != null) + ((IAnimationGear)item.target).timeScale = value; + } + } + } + } + } + + /// + /// + /// + public bool ignoreEngineTimeScale + { + get { return _ignoreEngineTimeScale; } + set + { + if (_ignoreEngineTimeScale != value) + { + _ignoreEngineTimeScale = value; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.tweener != null) + item.tweener.SetIgnoreEngineTimeScale(value); + else if (item.type == TransitionActionType.Transition) + { + if (((TValue_Transition)item.value).trans != null) + ((TValue_Transition)item.value).trans.ignoreEngineTimeScale = value; + } + else if (item.type == TransitionActionType.Animation) + { + if (item.target != null) + ((IAnimationGear)item.target).ignoreEngineTimeScale = value; + } + } + } + } + } + + internal void UpdateFromRelations(string targetId, float dx, float dy) + { + int cnt = _items.Length; + if (cnt == 0) + return; + + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.type == TransitionActionType.XY && item.targetId == targetId) + { + if (item.tweenConfig != null) + { + if (!item.tweenConfig.startValue.b3) + { + item.tweenConfig.startValue.f1 += dx; + item.tweenConfig.startValue.f2 += dy; + } + if (!item.tweenConfig.endValue.b3) + { + item.tweenConfig.endValue.f1 += dx; + item.tweenConfig.endValue.f2 += dy; + } + } + else + { + if (!((TValue)item.value).b3) + { + ((TValue)item.value).f1 += dx; + ((TValue)item.value).f2 += dy; + } + } + } + } + } + + internal void OnOwnerAddedToStage() + { + if (_autoPlay && !_playing) + Play(_autoPlayTimes, _autoPlayDelay, null); + } + + internal void OnOwnerRemovedFromStage() + { + if ((_options & OPTION_AUTO_STOP_DISABLED) == 0) + Stop((_options & OPTION_AUTO_STOP_AT_END) != 0 ? true : false, false); + } + + void OnDelayedPlay() + { + InternalPlay(); + + _playing = _totalTasks > 0; + if (_playing) + { + if ((_options & OPTION_IGNORE_DISPLAY_CONTROLLER) != 0) + { + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target != null && item.target != _owner) + item.displayLockToken = item.target.AddDisplayLock(); + } + } + } + else if (_onComplete != null) + { + PlayCompleteCallback func = _onComplete; + _onComplete = null; + func(); + } + } + + void InternalPlay() + { + _ownerBaseX = _owner.x; + _ownerBaseY = _owner.y; + + _totalTasks = 1; //prevent to complete inside the loop + + bool needSkipAnimations = false; + int cnt = _items.Length; + if (!_reversed) + { + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + if (item.type == TransitionActionType.Animation && _startTime != 0 && item.time <= _startTime) + { + needSkipAnimations = true; + ((TValue_Animation)item.value).flag = false; + } + else + PlayItem(item); + } + } + else + { + for (int i = cnt - 1; i >= 0; i--) + { + TransitionItem item = _items[i]; + if (item.target == null) + continue; + + PlayItem(item); + } + } + + if (needSkipAnimations) + SkipAnimations(); + + _totalTasks--; + } + + void PlayItem(TransitionItem item) + { + float time; + if (item.tweenConfig != null) + { + if (_reversed) + time = (_totalDuration - item.time - item.tweenConfig.duration); + else + time = item.time; + + if (_endTime == -1 || time <= _endTime) + { + TValue startValue; + TValue endValue; + + if (_reversed) + { + startValue = item.tweenConfig.endValue; + endValue = item.tweenConfig.startValue; + } + else + { + startValue = item.tweenConfig.startValue; + endValue = item.tweenConfig.endValue; + } + + ((TValue)item.value).b1 = startValue.b1 || endValue.b1; + ((TValue)item.value).b2 = startValue.b2 || endValue.b2; + + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Scale: + case TransitionActionType.Skew: + item.tweener = GTween.To(startValue.vec2, endValue.vec2, item.tweenConfig.duration); + break; + + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + item.tweener = GTween.To(startValue.f1, endValue.f1, item.tweenConfig.duration); + break; + + case TransitionActionType.Color: + item.tweener = GTween.To(startValue.color, endValue.color, item.tweenConfig.duration); + break; + + case TransitionActionType.ColorFilter: + item.tweener = GTween.To(startValue.vec4, endValue.vec4, item.tweenConfig.duration); + break; + } + + item.tweener.SetDelay(time) + .SetEase(item.tweenConfig.easeType, item.tweenConfig.customEase) + .SetRepeat(item.tweenConfig.repeat, item.tweenConfig.yoyo) + .SetTimeScale(_timeScale) + .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) + .SetTarget(item) + .SetListener(this); + + if (_endTime >= 0) + item.tweener.SetBreakpoint(_endTime - time); + + _totalTasks++; + } + } + else if (item.type == TransitionActionType.Shake) + { + TValue_Shake value = (TValue_Shake)item.value; + + if (_reversed) + time = (_totalDuration - item.time - value.duration); + else + time = item.time; + + if (_endTime == -1 || time <= _endTime) + { + value.lastOffset.Set(0, 0); + value.offset.Set(0, 0); + item.tweener = GTween.Shake(Vector3.zero, value.amplitude, value.duration) + .SetDelay(time) + .SetTimeScale(_timeScale) + .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) + .SetTarget(item) + .SetListener(this); + + if (_endTime >= 0) + item.tweener.SetBreakpoint(_endTime - item.time); + + _totalTasks++; + } + } + else + { + if (_reversed) + time = (_totalDuration - item.time); + else + time = item.time; + + if (time <= _startTime) + { + ApplyValue(item); + CallHook(item, false); + } + else if (_endTime == -1 || time <= _endTime) + { + _totalTasks++; + item.tweener = GTween.DelayedCall(time) + .SetTimeScale(_timeScale) + .SetIgnoreEngineTimeScale(_ignoreEngineTimeScale) + .SetTarget(item) + .OnComplete(_delayedCallDelegate2); + } + } + + if (item.tweener != null) + item.tweener.Seek(_startTime); + } + + void SkipAnimations() + { + int frame; + float playStartTime; + float playTotalTime; + TValue_Animation value; + IAnimationGear target; + TransitionItem item; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + item = _items[i]; + if (item.type != TransitionActionType.Animation || item.time > _startTime) + continue; + + value = (TValue_Animation)item.value; + if (value.flag) + continue; + + target = (IAnimationGear)item.target; + frame = target.frame; + playStartTime = target.playing ? 0 : -1; + playTotalTime = 0; + + for (int j = i; j < cnt; j++) + { + item = _items[j]; + if (item.type != TransitionActionType.Animation || item.target != target || item.time > _startTime) + continue; + + value = (TValue_Animation)item.value; + value.flag = true; + + if (value.frame != -1) + { + frame = value.frame; + if (value.playing) + playStartTime = item.time; + else + playStartTime = -1; + playTotalTime = 0; + } + else + { + if (value.playing) + { + if (playStartTime < 0) + playStartTime = item.time; + } + else + { + if (playStartTime >= 0) + playTotalTime += (item.time - playStartTime); + playStartTime = -1; + } + } + + CallHook(item, false); + } + + if (playStartTime >= 0) + playTotalTime += (_startTime - playStartTime); + + target.playing = playStartTime >= 0; + target.frame = frame; + if (playTotalTime > 0) + target.Advance(playTotalTime); + } + } + + void OnDelayedPlayItem(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + item.tweener = null; + _totalTasks--; + + ApplyValue(item); + CallHook(item, false); + + CheckAllComplete(); + } + + public void OnTweenStart(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + + if (item.type == TransitionActionType.XY || item.type == TransitionActionType.Size) //位置和大小要到start才最终确认起始值 + { + TValue startValue; + TValue endValue; + + if (_reversed) + { + startValue = item.tweenConfig.endValue; + endValue = item.tweenConfig.startValue; + } + else + { + startValue = item.tweenConfig.startValue; + endValue = item.tweenConfig.endValue; + } + + if (item.type == TransitionActionType.XY) + { + if (item.target != _owner) + { + if (!startValue.b1) + tweener.startValue.x = item.target.x; + else if (startValue.b3) //percent + tweener.startValue.x = startValue.f1 * _owner.width; + + if (!startValue.b2) + tweener.startValue.y = item.target.y; + else if (startValue.b3) //percent + tweener.startValue.y = startValue.f2 * _owner.height; + + if (!endValue.b1) + tweener.endValue.x = tweener.startValue.x; + else if (endValue.b3) + tweener.endValue.x = endValue.f1 * _owner.width; + + if (!endValue.b2) + tweener.endValue.y = tweener.startValue.y; + else if (endValue.b3) + tweener.endValue.y = endValue.f2 * _owner.height; + } + else + { + if (!startValue.b1) + tweener.startValue.x = item.target.x - _ownerBaseX; + if (!startValue.b2) + tweener.startValue.y = item.target.y - _ownerBaseY; + + if (!endValue.b1) + tweener.endValue.x = tweener.startValue.x; + if (!endValue.b2) + tweener.endValue.y = tweener.startValue.y; + } + } + else + { + if (!startValue.b1) + tweener.startValue.x = item.target.width; + if (!startValue.b2) + tweener.startValue.y = item.target.height; + + if (!endValue.b1) + tweener.endValue.x = tweener.startValue.x; + if (!endValue.b2) + tweener.endValue.y = tweener.startValue.y; + } + + if (item.tweenConfig.path != null) + { + ((TValue)item.value).b1 = ((TValue)item.value).b2 = true; + tweener.SetPath(item.tweenConfig.path); + } + } + + CallHook(item, false); + } + + public void OnTweenUpdate(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Scale: + case TransitionActionType.Skew: + ((TValue)item.value).vec2 = tweener.value.vec2; + if (item.tweenConfig.path != null) + { + ((TValue)item.value).f1 += tweener.startValue.x; + ((TValue)item.value).f2 += tweener.startValue.y; + } + break; + + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + ((TValue)item.value).f1 = tweener.value.x; + break; + + case TransitionActionType.Color: + ((TValue)item.value).color = tweener.value.color; + break; + + case TransitionActionType.ColorFilter: + ((TValue)item.value).vec4 = tweener.value.vec4; + break; + + case TransitionActionType.Shake: + ((TValue_Shake)item.value).offset = tweener.deltaValue.vec2; + break; + } + ApplyValue(item); + } + + public void OnTweenComplete(GTweener tweener) + { + TransitionItem item = (TransitionItem)tweener.target; + item.tweener = null; + _totalTasks--; + + if (tweener.allCompleted) //当整体播放结束时间在这个tween的中间时不应该调用结尾钩子 + CallHook(item, true); + + CheckAllComplete(); + } + + void OnPlayTransCompleted(TransitionItem item) + { + _totalTasks--; + + CheckAllComplete(); + } + + void CallHook(TransitionItem item, bool tweenEnd) + { + if (tweenEnd) + { + if (item.tweenConfig != null && item.tweenConfig.endHook != null) + item.tweenConfig.endHook(); + } + else + { + if (item.time >= _startTime && item.hook != null) + item.hook(); + } + } + + void CheckAllComplete() + { + if (_playing && _totalTasks == 0) + { + if (_totalTimes < 0) + { + InternalPlay(); + if (_totalTasks == 0) + GTween.DelayedCall(0).SetTarget(this).OnComplete(_checkAllDelegate); + } + else + { + _totalTimes--; + if (_totalTimes > 0) + { + InternalPlay(); + if (_totalTasks == 0) + GTween.DelayedCall(0).SetTarget(this).OnComplete(_checkAllDelegate); + } + else + { + _playing = false; + + int cnt = _items.Length; + for (int i = 0; i < cnt; i++) + { + TransitionItem item = _items[i]; + if (item.target != null && item.displayLockToken != 0) + { + item.target.ReleaseDisplayLock(item.displayLockToken); + item.displayLockToken = 0; + } + } + + if (_onComplete != null) + { + PlayCompleteCallback func = _onComplete; + _onComplete = null; + func(); + } + } + } + } + } + + void ApplyValue(TransitionItem item) + { + item.target._gearLocked = true; + + switch (item.type) + { + case TransitionActionType.XY: + { + TValue value = (TValue)item.value; + if (item.target == _owner) + { + if (value.b1 && value.b2) + item.target.SetXY(value.f1 + _ownerBaseX, value.f2 + _ownerBaseY); + else if (value.b1) + item.target.x = value.f1 + _ownerBaseX; + else + item.target.y = value.f2 + _ownerBaseY; + } + else + { + if (value.b3) //position in percent + { + if (value.b1 && value.b2) + item.target.SetXY(value.f1 * _owner.width, value.f2 * _owner.height); + else if (value.b1) + item.target.x = value.f1 * _owner.width; + else if (value.b2) + item.target.y = value.f2 * _owner.height; + } + else + { + if (value.b1 && value.b2) + item.target.SetXY(value.f1, value.f2); + else if (value.b1) + item.target.x = value.f1; + else if (value.b2) + item.target.y = value.f2; + } + } + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + } + break; + + case TransitionActionType.Size: + { + TValue value = (TValue)item.value; + if (!value.b1) + value.f1 = item.target.width; + if (!value.b2) + value.f2 = item.target.height; + item.target.SetSize(value.f1, value.f2); + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + } + break; + + case TransitionActionType.Pivot: + item.target.SetPivot(((TValue)item.value).f1, ((TValue)item.value).f2, item.target.pivotAsAnchor); + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Alpha: + item.target.alpha = ((TValue)item.value).f1; + break; + + case TransitionActionType.Rotation: + item.target.rotation = ((TValue)item.value).f1; + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Scale: + item.target.SetScale(((TValue)item.value).f1, ((TValue)item.value).f2); + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Skew: + item.target.skew = ((TValue)item.value).vec2; + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + break; + + case TransitionActionType.Color: + ((IColorGear)item.target).color = ((TValue)item.value).color; + break; + + case TransitionActionType.Animation: + { + TValue_Animation value = (TValue_Animation)item.value; + if (value.frame >= 0) + ((IAnimationGear)item.target).frame = value.frame; + ((IAnimationGear)item.target).playing = value.playing; + ((IAnimationGear)item.target).timeScale = _timeScale; + ((IAnimationGear)item.target).ignoreEngineTimeScale = _ignoreEngineTimeScale; + if (value.animationName != null) + ((GLoader3D)item.target).animationName = value.animationName; + if (value.skinName != null) + ((GLoader3D)item.target).skinName = value.skinName; + } + break; + + case TransitionActionType.Visible: + item.target.visible = ((TValue_Visible)item.value).visible; + break; + + case TransitionActionType.Shake: + { + TValue_Shake value = (TValue_Shake)item.value; + item.target.SetXY(item.target.x - value.lastOffset.x + value.offset.x, item.target.y - value.lastOffset.y + value.offset.y); + value.lastOffset = value.offset; + + if (invalidateBatchingEveryFrame) + _owner.InvalidateBatchingState(true); + } + break; + + case TransitionActionType.Transition: + if (_playing) + { + TValue_Transition value = (TValue_Transition)item.value; + if (value.trans != null) + { + _totalTasks++; + + float startTime = _startTime > item.time ? (_startTime - item.time) : 0; + float endTime = _endTime >= 0 ? (_endTime - item.time) : -1; + if (value.stopTime >= 0 && (endTime < 0 || endTime > value.stopTime)) + endTime = value.stopTime; + value.trans.timeScale = _timeScale; + value.trans.ignoreEngineTimeScale = _ignoreEngineTimeScale; + value.trans._Play(value.playTimes, 0, startTime, endTime, value.playCompleteDelegate, _reversed); + } + } + break; + + case TransitionActionType.Sound: + if (_playing && item.time >= _startTime) + { + TValue_Sound value = (TValue_Sound)item.value; + if (value.audioClip == null) + { + if (UIConfig.soundLoader == null || value.sound.StartsWith(UIPackage.URL_PREFIX)) + value.audioClip = UIPackage.GetItemAssetByURL(value.sound) as NAudioClip; + else + value.audioClip = UIConfig.soundLoader(value.sound); + } + + if (value.audioClip != null && value.audioClip.nativeClip != null) + Stage.inst.PlayOneShotSound(value.audioClip.nativeClip, value.volume); + } + break; + + case TransitionActionType.ColorFilter: + { + TValue value = (TValue)item.value; + ColorFilter cf = item.target.filter as ColorFilter; + if (cf == null) + { + cf = new ColorFilter(); + item.target.filter = cf; + } + else + cf.Reset(); + + cf.AdjustBrightness(value.f1); + cf.AdjustContrast(value.f2); + cf.AdjustSaturation(value.f3); + cf.AdjustHue(value.f4); + } + break; + + case TransitionActionType.Text: + item.target.text = ((TValue_Text)item.value).text; + break; + + case TransitionActionType.Icon: + item.target.icon = ((TValue_Text)item.value).text; + break; + } + + item.target._gearLocked = false; + } + + public void Setup(ByteBuffer buffer) + { + this.name = buffer.ReadS(); + _options = buffer.ReadInt(); + _autoPlay = buffer.ReadBool(); + _autoPlayTimes = buffer.ReadInt(); + _autoPlayDelay = buffer.ReadFloat(); + + int cnt = buffer.ReadShort(); + _items = new TransitionItem[cnt]; + for (int i = 0; i < cnt; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + buffer.Seek(curPos, 0); + + TransitionItem item = new TransitionItem((TransitionActionType)buffer.ReadByte()); + _items[i] = item; + + item.time = buffer.ReadFloat(); + int targetId = buffer.ReadShort(); + if (targetId < 0) + item.targetId = string.Empty; + else + item.targetId = _owner.GetChildAt(targetId).id; + item.label = buffer.ReadS(); + + if (buffer.ReadBool()) + { + buffer.Seek(curPos, 1); + + item.tweenConfig = new TweenConfig(); + item.tweenConfig.duration = buffer.ReadFloat(); + if (item.time + item.tweenConfig.duration > _totalDuration) + _totalDuration = item.time + item.tweenConfig.duration; + item.tweenConfig.easeType = (EaseType)buffer.ReadByte(); + item.tweenConfig.repeat = buffer.ReadInt(); + item.tweenConfig.yoyo = buffer.ReadBool(); + item.tweenConfig.endLabel = buffer.ReadS(); + + buffer.Seek(curPos, 2); + + DecodeValue(item, buffer, item.tweenConfig.startValue); + + buffer.Seek(curPos, 3); + + DecodeValue(item, buffer, item.tweenConfig.endValue); + + if (buffer.version >= 2) + { + var pts = buffer.ReadPath(); + if (pts.Count > 0) + { + item.tweenConfig.path = new GPath(); + item.tweenConfig.path.Create(pts); + } + } + + if (buffer.version >= 4 && item.tweenConfig.easeType == EaseType.Custom) + { + var pts = buffer.ReadPath(); + if (pts.Count > 0) + { + item.tweenConfig.customEase = new CustomEase(); + item.tweenConfig.customEase.Create(pts); + } + } + } + else + { + if (item.time > _totalDuration) + _totalDuration = item.time; + + buffer.Seek(curPos, 2); + + DecodeValue(item, buffer, item.value); + } + + buffer.position = curPos + dataLen; + } + } + + void DecodeValue(TransitionItem item, ByteBuffer buffer, object value) + { + switch (item.type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Pivot: + case TransitionActionType.Skew: + { + TValue tvalue = (TValue)value; + tvalue.b1 = buffer.ReadBool(); + tvalue.b2 = buffer.ReadBool(); + tvalue.f1 = buffer.ReadFloat(); + tvalue.f2 = buffer.ReadFloat(); + + if (buffer.version >= 2 && item.type == TransitionActionType.XY) + tvalue.b3 = buffer.ReadBool(); //percent + } + break; + + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + ((TValue)value).f1 = buffer.ReadFloat(); + break; + + case TransitionActionType.Scale: + ((TValue)value).f1 = buffer.ReadFloat(); + ((TValue)value).f2 = buffer.ReadFloat(); + break; + + case TransitionActionType.Color: + ((TValue)value).color = buffer.ReadColor(); + break; + + case TransitionActionType.Animation: + ((TValue_Animation)value).playing = buffer.ReadBool(); + ((TValue_Animation)value).frame = buffer.ReadInt(); + if (buffer.version >= 6) + { + ((TValue_Animation)value).animationName = buffer.ReadS(); + ((TValue_Animation)value).skinName = buffer.ReadS(); + } + break; + + case TransitionActionType.Visible: + ((TValue_Visible)value).visible = buffer.ReadBool(); + break; + + case TransitionActionType.Sound: + ((TValue_Sound)value).sound = buffer.ReadS(); + ((TValue_Sound)value).volume = buffer.ReadFloat(); + break; + + case TransitionActionType.Transition: + ((TValue_Transition)value).transName = buffer.ReadS(); + ((TValue_Transition)value).playTimes = buffer.ReadInt(); + ((TValue_Transition)value).playCompleteDelegate = () => { OnPlayTransCompleted(item); }; + break; + + case TransitionActionType.Shake: + ((TValue_Shake)value).amplitude = buffer.ReadFloat(); + ((TValue_Shake)value).duration = buffer.ReadFloat(); + break; + + case TransitionActionType.ColorFilter: + { + TValue tvalue = (TValue)value; + tvalue.f1 = buffer.ReadFloat(); + tvalue.f2 = buffer.ReadFloat(); + tvalue.f3 = buffer.ReadFloat(); + tvalue.f4 = buffer.ReadFloat(); + } + break; + + case TransitionActionType.Text: + case TransitionActionType.Icon: + ((TValue_Text)value).text = buffer.ReadS(); + break; + } + } + } + + class TransitionItem + { + public float time; + public string targetId; + public TransitionActionType type; + public TweenConfig tweenConfig; + public string label; + public object value; + public TransitionHook hook; + + //running properties + public GTweener tweener; + public GObject target; + public uint displayLockToken; + + public TransitionItem(TransitionActionType type) + { + this.type = type; + + switch (type) + { + case TransitionActionType.XY: + case TransitionActionType.Size: + case TransitionActionType.Scale: + case TransitionActionType.Pivot: + case TransitionActionType.Skew: + case TransitionActionType.Alpha: + case TransitionActionType.Rotation: + case TransitionActionType.Color: + case TransitionActionType.ColorFilter: + value = new TValue(); + break; + + case TransitionActionType.Animation: + value = new TValue_Animation(); + break; + + case TransitionActionType.Shake: + value = new TValue_Shake(); + break; + + case TransitionActionType.Sound: + value = new TValue_Sound(); + break; + + case TransitionActionType.Transition: + value = new TValue_Transition(); + break; + + case TransitionActionType.Visible: + value = new TValue_Visible(); + break; + + case TransitionActionType.Text: + case TransitionActionType.Icon: + value = new TValue_Text(); + break; + } + } + } + + class TweenConfig + { + public float duration; + public EaseType easeType; + public CustomEase customEase; + public int repeat; + public bool yoyo; + + public TValue startValue; + public TValue endValue; + + public string endLabel; + public TransitionHook endHook; + + public GPath path; + + public TweenConfig() + { + easeType = EaseType.QuadOut; + startValue = new TValue(); + endValue = new TValue(); + } + } + + class TValue_Visible + { + public bool visible; + } + + class TValue_Animation + { + public int frame; + public bool playing; + public bool flag; + public string animationName; + public string skinName; + } + + class TValue_Sound + { + public string sound; + public float volume; + public NAudioClip audioClip; + } + + class TValue_Transition + { + public string transName; + public int playTimes; + public Transition trans; + public PlayCompleteCallback playCompleteDelegate; + public float stopTime; + } + + class TValue_Shake + { + public float amplitude; + public float duration; + public Vector2 lastOffset; + public Vector2 offset; + } + + class TValue_Text + { + public string text; + } + + class TValue + { + public float f1; + public float f2; + public float f3; + public float f4; + public bool b1; + public bool b2; + public bool b3; + + public TValue() + { + b1 = true; + b2 = true; + } + + public void Copy(TValue source) + { + this.f1 = source.f1; + this.f2 = source.f2; + this.f3 = source.f3; + this.f4 = source.f4; + this.b1 = source.b1; + this.b2 = source.b2; + } + + public Vector2 vec2 + { + get { return new Vector2(f1, f2); } + set + { + f1 = value.x; + f2 = value.y; + } + } + + public Vector4 vec4 + { + get { return new Vector4(f1, f2, f3, f4); } + set + { + f1 = value.x; + f2 = value.y; + f3 = value.z; + f4 = value.w; + } + } + + public Color color + { + get { return new Color(f1, f2, f3, f4); } + set + { + f1 = value.r; + f2 = value.g; + f3 = value.b; + f4 = value.a; + } + } + } +} diff --git a/Assets/Scripts/UI/Transition.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Transition.cs.meta similarity index 100% rename from Assets/Scripts/UI/Transition.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Transition.cs.meta diff --git a/Assets/Scripts/UI/TranslationHelper.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/TranslationHelper.cs similarity index 97% rename from Assets/Scripts/UI/TranslationHelper.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/TranslationHelper.cs index 47faec6c..1b441fe7 100644 --- a/Assets/Scripts/UI/TranslationHelper.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/TranslationHelper.cs @@ -1,253 +1,253 @@ -using System.Collections.Generic; -using FairyGUI.Utils; - -namespace FairyGUI -{ - public class TranslationHelper - { - public static Dictionary> strings; - - public static void LoadFromXML(XML source) - { - strings = new Dictionary>(); - XMLList.Enumerator et = source.GetEnumerator("string"); - while (et.MoveNext()) - { - XML cxml = et.Current; - string key = cxml.GetAttribute("name"); - string text = cxml.text; - int i = key.IndexOf("-"); - if (i == -1) - continue; - - string key2 = key.Substring(0, i); - string key3 = key.Substring(i + 1); - Dictionary col; - if (!strings.TryGetValue(key2, out col)) - { - col = new Dictionary(); - strings[key2] = col; - } - col[key3] = text; - } - } - - public static void TranslateComponent(PackageItem item) - { - if (TranslationHelper.strings == null) - return; - - Dictionary strings; - if (!TranslationHelper.strings.TryGetValue(item.owner.id + item.id, out strings)) - return; - - string elementId, value; - ByteBuffer buffer = item.rawData; - - buffer.Seek(0, 2); - - int childCount = buffer.ReadShort(); - for (int i = 0; i < childCount; i++) - { - int dataLen = buffer.ReadShort(); - int curPos = buffer.position; - - buffer.Seek(curPos, 0); - - ObjectType baseType = (ObjectType)buffer.ReadByte(); - ObjectType type = baseType; - buffer.Skip(4); - elementId = buffer.ReadS(); - - if (type == ObjectType.Component) - { - if (buffer.Seek(curPos, 6)) - type = (ObjectType)buffer.ReadByte(); - } - - buffer.Seek(curPos, 1); - - if (strings.TryGetValue(elementId + "-tips", out value)) - buffer.WriteS(value); - - buffer.Seek(curPos, 2); - - int gearCnt = buffer.ReadShort(); - for (int j = 0; j < gearCnt; j++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - if (buffer.ReadByte() == 6) //gearText - { - buffer.Skip(2);//controller - int valueCnt = buffer.ReadShort(); - for (int k = 0; k < valueCnt; k++) - { - string page = buffer.ReadS(); - if (page != null) - { - if (strings.TryGetValue(elementId + "-texts_" + k, out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - } - } - - if (buffer.ReadBool() && strings.TryGetValue(elementId + "-texts_def", out value)) - buffer.WriteS(value); - } - - buffer.position = nextPos; - } - - if (baseType == ObjectType.Component && buffer.version >= 2) - { - buffer.Seek(curPos, 4); - - buffer.Skip(2); //pageController - - buffer.Skip(4 * buffer.ReadShort()); - - int cpCount = buffer.ReadShort(); - for (int k = 0; k < cpCount; k++) - { - string target = buffer.ReadS(); - int propertyId = buffer.ReadShort(); - if (propertyId == 0 && strings.TryGetValue(elementId + "-cp-" + target, out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - } - } - - switch (type) - { - case ObjectType.Text: - case ObjectType.RichText: - case ObjectType.InputText: - { - if (strings.TryGetValue(elementId, out value)) - { - buffer.Seek(curPos, 6); - buffer.WriteS(value); - } - if (strings.TryGetValue(elementId + "-prompt", out value)) - { - buffer.Seek(curPos, 4); - buffer.WriteS(value); - } - break; - } - - case ObjectType.List: - case ObjectType.Tree: - { - buffer.Seek(curPos, 8); - buffer.Skip(2); - int itemCount = buffer.ReadShort(); - for (int j = 0; j < itemCount; j++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - buffer.Skip(2); //url - if (type == ObjectType.Tree) - buffer.Skip(2); - - //title - if (strings.TryGetValue(elementId + "-" + j, out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - - //selected title - if (strings.TryGetValue(elementId + "-" + j + "-0", out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - - if (buffer.version >= 2) - { - buffer.Skip(6); - buffer.Skip(buffer.ReadShort() * 4);//controllers - - int cpCount = buffer.ReadShort(); - for (int k = 0; k < cpCount; k++) - { - string target = buffer.ReadS(); - int propertyId = buffer.ReadShort(); - if (propertyId == 0 && strings.TryGetValue(elementId + "-" + j + "-" + target, out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - } - } - - buffer.position = nextPos; - } - break; - } - - case ObjectType.Label: - { - if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) - { - if (strings.TryGetValue(elementId, out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - - buffer.Skip(2); - if (buffer.ReadBool()) - buffer.Skip(4); - buffer.Skip(4); - if (buffer.ReadBool() && strings.TryGetValue(elementId + "-prompt", out value)) - buffer.WriteS(value); - } - break; - } - - case ObjectType.Button: - { - if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) - { - if (strings.TryGetValue(elementId, out value)) - buffer.WriteS(value); - else - buffer.Skip(2); - if (strings.TryGetValue(elementId + "-0", out value)) - buffer.WriteS(value); - } - break; - } - - case ObjectType.ComboBox: - { - if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) - { - int itemCount = buffer.ReadShort(); - for (int j = 0; j < itemCount; j++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - if (strings.TryGetValue(elementId + "-" + j, out value)) - buffer.WriteS(value); - - buffer.position = nextPos; - } - - if (strings.TryGetValue(elementId, out value)) - buffer.WriteS(value); - } - - break; - } - } - - buffer.position = curPos + dataLen; - } - } - } -} +using System.Collections.Generic; +using FairyGUI.Utils; + +namespace FairyGUI +{ + public class TranslationHelper + { + public static Dictionary> strings; + + public static void LoadFromXML(XML source) + { + strings = new Dictionary>(); + XMLList.Enumerator et = source.GetEnumerator("string"); + while (et.MoveNext()) + { + XML cxml = et.Current; + string key = cxml.GetAttribute("name"); + string text = cxml.text; + int i = key.IndexOf("-"); + if (i == -1) + continue; + + string key2 = key.Substring(0, i); + string key3 = key.Substring(i + 1); + Dictionary col; + if (!strings.TryGetValue(key2, out col)) + { + col = new Dictionary(); + strings[key2] = col; + } + col[key3] = text; + } + } + + public static void TranslateComponent(PackageItem item) + { + if (TranslationHelper.strings == null) + return; + + Dictionary strings; + if (!TranslationHelper.strings.TryGetValue(item.owner.id + item.id, out strings)) + return; + + string elementId, value; + ByteBuffer buffer = item.rawData; + + buffer.Seek(0, 2); + + int childCount = buffer.ReadShort(); + for (int i = 0; i < childCount; i++) + { + int dataLen = buffer.ReadShort(); + int curPos = buffer.position; + + buffer.Seek(curPos, 0); + + ObjectType baseType = (ObjectType)buffer.ReadByte(); + ObjectType type = baseType; + buffer.Skip(4); + elementId = buffer.ReadS(); + + if (type == ObjectType.Component) + { + if (buffer.Seek(curPos, 6)) + type = (ObjectType)buffer.ReadByte(); + } + + buffer.Seek(curPos, 1); + + if (strings.TryGetValue(elementId + "-tips", out value)) + buffer.WriteS(value); + + buffer.Seek(curPos, 2); + + int gearCnt = buffer.ReadShort(); + for (int j = 0; j < gearCnt; j++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + if (buffer.ReadByte() == 6) //gearText + { + buffer.Skip(2);//controller + int valueCnt = buffer.ReadShort(); + for (int k = 0; k < valueCnt; k++) + { + string page = buffer.ReadS(); + if (page != null) + { + if (strings.TryGetValue(elementId + "-texts_" + k, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + } + } + + if (buffer.ReadBool() && strings.TryGetValue(elementId + "-texts_def", out value)) + buffer.WriteS(value); + } + + buffer.position = nextPos; + } + + if (baseType == ObjectType.Component && buffer.version >= 2) + { + buffer.Seek(curPos, 4); + + buffer.Skip(2); //pageController + + buffer.Skip(4 * buffer.ReadShort()); + + int cpCount = buffer.ReadShort(); + for (int k = 0; k < cpCount; k++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + if (propertyId == 0 && strings.TryGetValue(elementId + "-cp-" + target, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + } + } + + switch (type) + { + case ObjectType.Text: + case ObjectType.RichText: + case ObjectType.InputText: + { + if (strings.TryGetValue(elementId, out value)) + { + buffer.Seek(curPos, 6); + buffer.WriteS(value); + } + if (strings.TryGetValue(elementId + "-prompt", out value)) + { + buffer.Seek(curPos, 4); + buffer.WriteS(value); + } + break; + } + + case ObjectType.List: + case ObjectType.Tree: + { + buffer.Seek(curPos, 8); + buffer.Skip(2); + int itemCount = buffer.ReadShort(); + for (int j = 0; j < itemCount; j++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + buffer.Skip(2); //url + if (type == ObjectType.Tree) + buffer.Skip(2); + + //title + if (strings.TryGetValue(elementId + "-" + j, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + + //selected title + if (strings.TryGetValue(elementId + "-" + j + "-0", out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + + if (buffer.version >= 2) + { + buffer.Skip(6); + buffer.Skip(buffer.ReadShort() * 4);//controllers + + int cpCount = buffer.ReadShort(); + for (int k = 0; k < cpCount; k++) + { + string target = buffer.ReadS(); + int propertyId = buffer.ReadShort(); + if (propertyId == 0 && strings.TryGetValue(elementId + "-" + j + "-" + target, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + } + } + + buffer.position = nextPos; + } + break; + } + + case ObjectType.Label: + { + if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) + { + if (strings.TryGetValue(elementId, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + + buffer.Skip(2); + if (buffer.ReadBool()) + buffer.Skip(4); + buffer.Skip(4); + if (buffer.ReadBool() && strings.TryGetValue(elementId + "-prompt", out value)) + buffer.WriteS(value); + } + break; + } + + case ObjectType.Button: + { + if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) + { + if (strings.TryGetValue(elementId, out value)) + buffer.WriteS(value); + else + buffer.Skip(2); + if (strings.TryGetValue(elementId + "-0", out value)) + buffer.WriteS(value); + } + break; + } + + case ObjectType.ComboBox: + { + if (buffer.Seek(curPos, 6) && (ObjectType)buffer.ReadByte() == type) + { + int itemCount = buffer.ReadShort(); + for (int j = 0; j < itemCount; j++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + if (strings.TryGetValue(elementId + "-" + j, out value)) + buffer.WriteS(value); + + buffer.position = nextPos; + } + + if (strings.TryGetValue(elementId, out value)) + buffer.WriteS(value); + } + + break; + } + } + + buffer.position = curPos + dataLen; + } + } + } +} diff --git a/Assets/Scripts/UI/TranslationHelper.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/TranslationHelper.cs.meta similarity index 100% rename from Assets/Scripts/UI/TranslationHelper.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/TranslationHelper.cs.meta diff --git a/Assets/Scripts/UI/Tree.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree.meta similarity index 100% rename from Assets/Scripts/UI/Tree.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree.meta diff --git a/Assets/Scripts/UI/Tree/TreeNode.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeNode.cs similarity index 96% rename from Assets/Scripts/UI/Tree/TreeNode.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeNode.cs index 7a4a0322..686ddfd7 100644 --- a/Assets/Scripts/UI/Tree/TreeNode.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeNode.cs @@ -1,348 +1,348 @@ -using System; -using System.Collections.Generic; - -namespace FairyGUI -{ - /// - /// - /// - [Obsolete("Use GTree and GTreeNode instead")] - public class TreeNode - { - /// - /// - /// - public object data; - - /// - /// - /// - public TreeNode parent { get; private set; } - - /// - /// - /// - public TreeView tree { get; private set; } - - /// - /// - /// - public GComponent cell { get; internal set; } - - /// - /// - /// - public int level { get; private set; } - - private List _children; - private bool _expanded; - - /// - /// - /// - /// - public TreeNode(bool hasChild) - { - if (hasChild) - _children = new List(); - } - - /// - /// - /// - public bool expanded - { - get - { - return _expanded; - } - - set - { - if (_children == null) - return; - - if (_expanded != value) - { - _expanded = value; - if (tree != null) - { - if (_expanded) - tree.AfterExpanded(this); - else - tree.AfterCollapsed(this); - } - } - } - } - - /// - /// - /// - public bool isFolder - { - get { return _children != null; } - } - - /// - /// - /// - public string text - { - get - { - if (cell != null) - return cell.text; - else - return null; - } - } - - /// - /// - /// - /// - /// - public TreeNode AddChild(TreeNode child) - { - AddChildAt(child, _children.Count); - return child; - } - - /// - /// - /// - /// - /// - /// - public TreeNode AddChildAt(TreeNode child, int index) - { - if (child == null) - throw new Exception("child is null"); - - int numChildren = _children.Count; - - if (index >= 0 && index <= numChildren) - { - if (child.parent == this) - { - SetChildIndex(child, index); - } - else - { - if (child.parent != null) - child.parent.RemoveChild(child); - - int cnt = _children.Count; - if (index == cnt) - _children.Add(child); - else - _children.Insert(index, child); - - child.parent = this; - child.level = this.level + 1; - child.SetTree(this.tree); - if (this.cell != null && this.cell.parent != null && _expanded) - tree.AfterInserted(child); - } - - return child; - } - else - { - throw new Exception("Invalid child index"); - } - } - - /// - /// - /// - /// - /// - public TreeNode RemoveChild(TreeNode child) - { - int childIndex = _children.IndexOf(child); - if (childIndex != -1) - { - RemoveChildAt(childIndex); - } - return child; - } - - /// - /// - /// - /// - /// - public TreeNode RemoveChildAt(int index) - { - if (index >= 0 && index < numChildren) - { - TreeNode child = _children[index]; - _children.RemoveAt(index); - - child.parent = null; - if (tree != null) - { - child.SetTree(null); - tree.AfterRemoved(child); - } - - return child; - } - else - { - throw new Exception("Invalid child index"); - } - } - - /// - /// - /// - /// - /// - public void RemoveChildren(int beginIndex = 0, int endIndex = -1) - { - if (endIndex < 0 || endIndex >= numChildren) - endIndex = numChildren - 1; - - for (int i = beginIndex; i <= endIndex; ++i) - RemoveChildAt(beginIndex); - } - - /// - /// - /// - /// - /// - public TreeNode GetChildAt(int index) - { - if (index >= 0 && index < numChildren) - return _children[index]; - else - throw new Exception("Invalid child index"); - } - - /// - /// - /// - /// - /// - public int GetChildIndex(TreeNode child) - { - return _children.IndexOf(child); - } - - /// - /// - /// - /// - public TreeNode GetPrevSibling() - { - if (parent == null) - return null; - - int i = parent._children.IndexOf(this); - if (i <= 0) - return null; - - return parent._children[i - 1]; - } - - /// - /// - /// - /// - public TreeNode GetNextSibling() - { - if (parent == null) - return null; - - int i = parent._children.IndexOf(this); - if (i < 0 || i >= parent._children.Count - 1) - return null; - - return parent._children[i + 1]; - } - - /// - /// - /// - /// - /// - public void SetChildIndex(TreeNode child, int index) - { - int oldIndex = _children.IndexOf(child); - if (oldIndex == -1) - throw new Exception("Not a child of this container"); - - int cnt = _children.Count; - if (index < 0) - index = 0; - else if (index > cnt) - index = cnt; - - if (oldIndex == index) - return; - - _children.RemoveAt(oldIndex); - _children.Insert(index, child); - if (this.cell != null && this.cell.parent != null && _expanded) - tree.AfterMoved(child); - } - - /// - /// - /// - /// - /// - public void SwapChildren(TreeNode child1, TreeNode child2) - { - int index1 = _children.IndexOf(child1); - int index2 = _children.IndexOf(child2); - if (index1 == -1 || index2 == -1) - throw new Exception("Not a child of this container"); - SwapChildrenAt(index1, index2); - } - - /// - /// - /// - /// - /// - public void SwapChildrenAt(int index1, int index2) - { - TreeNode child1 = _children[index1]; - TreeNode child2 = _children[index2]; - - SetChildIndex(child1, index2); - SetChildIndex(child2, index1); - } - - /// - /// - /// - public int numChildren - { - get { return (null == _children) ? 0 : _children.Count; } - } - - internal void SetTree(TreeView value) - { - tree = value; - if (tree != null && tree.treeNodeWillExpand != null && _expanded) - tree.treeNodeWillExpand(this, true); - - if (_children != null) - { - int cnt = _children.Count; - for (int i = 0; i < cnt; i++) - { - TreeNode node = _children[i]; - node.level = level + 1; - node.SetTree(value); - } - } - } - } -} +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + [Obsolete("Use GTree and GTreeNode instead")] + public class TreeNode + { + /// + /// + /// + public object data; + + /// + /// + /// + public TreeNode parent { get; private set; } + + /// + /// + /// + public TreeView tree { get; private set; } + + /// + /// + /// + public GComponent cell { get; internal set; } + + /// + /// + /// + public int level { get; private set; } + + private List _children; + private bool _expanded; + + /// + /// + /// + /// + public TreeNode(bool hasChild) + { + if (hasChild) + _children = new List(); + } + + /// + /// + /// + public bool expanded + { + get + { + return _expanded; + } + + set + { + if (_children == null) + return; + + if (_expanded != value) + { + _expanded = value; + if (tree != null) + { + if (_expanded) + tree.AfterExpanded(this); + else + tree.AfterCollapsed(this); + } + } + } + } + + /// + /// + /// + public bool isFolder + { + get { return _children != null; } + } + + /// + /// + /// + public string text + { + get + { + if (cell != null) + return cell.text; + else + return null; + } + } + + /// + /// + /// + /// + /// + public TreeNode AddChild(TreeNode child) + { + AddChildAt(child, _children.Count); + return child; + } + + /// + /// + /// + /// + /// + /// + public TreeNode AddChildAt(TreeNode child, int index) + { + if (child == null) + throw new Exception("child is null"); + + int numChildren = _children.Count; + + if (index >= 0 && index <= numChildren) + { + if (child.parent == this) + { + SetChildIndex(child, index); + } + else + { + if (child.parent != null) + child.parent.RemoveChild(child); + + int cnt = _children.Count; + if (index == cnt) + _children.Add(child); + else + _children.Insert(index, child); + + child.parent = this; + child.level = this.level + 1; + child.SetTree(this.tree); + if (this.cell != null && this.cell.parent != null && _expanded) + tree.AfterInserted(child); + } + + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public TreeNode RemoveChild(TreeNode child) + { + int childIndex = _children.IndexOf(child); + if (childIndex != -1) + { + RemoveChildAt(childIndex); + } + return child; + } + + /// + /// + /// + /// + /// + public TreeNode RemoveChildAt(int index) + { + if (index >= 0 && index < numChildren) + { + TreeNode child = _children[index]; + _children.RemoveAt(index); + + child.parent = null; + if (tree != null) + { + child.SetTree(null); + tree.AfterRemoved(child); + } + + return child; + } + else + { + throw new Exception("Invalid child index"); + } + } + + /// + /// + /// + /// + /// + public void RemoveChildren(int beginIndex = 0, int endIndex = -1) + { + if (endIndex < 0 || endIndex >= numChildren) + endIndex = numChildren - 1; + + for (int i = beginIndex; i <= endIndex; ++i) + RemoveChildAt(beginIndex); + } + + /// + /// + /// + /// + /// + public TreeNode GetChildAt(int index) + { + if (index >= 0 && index < numChildren) + return _children[index]; + else + throw new Exception("Invalid child index"); + } + + /// + /// + /// + /// + /// + public int GetChildIndex(TreeNode child) + { + return _children.IndexOf(child); + } + + /// + /// + /// + /// + public TreeNode GetPrevSibling() + { + if (parent == null) + return null; + + int i = parent._children.IndexOf(this); + if (i <= 0) + return null; + + return parent._children[i - 1]; + } + + /// + /// + /// + /// + public TreeNode GetNextSibling() + { + if (parent == null) + return null; + + int i = parent._children.IndexOf(this); + if (i < 0 || i >= parent._children.Count - 1) + return null; + + return parent._children[i + 1]; + } + + /// + /// + /// + /// + /// + public void SetChildIndex(TreeNode child, int index) + { + int oldIndex = _children.IndexOf(child); + if (oldIndex == -1) + throw new Exception("Not a child of this container"); + + int cnt = _children.Count; + if (index < 0) + index = 0; + else if (index > cnt) + index = cnt; + + if (oldIndex == index) + return; + + _children.RemoveAt(oldIndex); + _children.Insert(index, child); + if (this.cell != null && this.cell.parent != null && _expanded) + tree.AfterMoved(child); + } + + /// + /// + /// + /// + /// + public void SwapChildren(TreeNode child1, TreeNode child2) + { + int index1 = _children.IndexOf(child1); + int index2 = _children.IndexOf(child2); + if (index1 == -1 || index2 == -1) + throw new Exception("Not a child of this container"); + SwapChildrenAt(index1, index2); + } + + /// + /// + /// + /// + /// + public void SwapChildrenAt(int index1, int index2) + { + TreeNode child1 = _children[index1]; + TreeNode child2 = _children[index2]; + + SetChildIndex(child1, index2); + SetChildIndex(child2, index1); + } + + /// + /// + /// + public int numChildren + { + get { return (null == _children) ? 0 : _children.Count; } + } + + internal void SetTree(TreeView value) + { + tree = value; + if (tree != null && tree.treeNodeWillExpand != null && _expanded) + tree.treeNodeWillExpand(this, true); + + if (_children != null) + { + int cnt = _children.Count; + for (int i = 0; i < cnt; i++) + { + TreeNode node = _children[i]; + node.level = level + 1; + node.SetTree(value); + } + } + } + } +} diff --git a/Assets/Scripts/UI/Tree/TreeNode.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeNode.cs.meta similarity index 100% rename from Assets/Scripts/UI/Tree/TreeNode.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeNode.cs.meta diff --git a/Assets/Scripts/UI/Tree/TreeView.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeView.cs similarity index 96% rename from Assets/Scripts/UI/Tree/TreeView.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeView.cs index 9cb8cd77..17bdc0db 100644 --- a/Assets/Scripts/UI/Tree/TreeView.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeView.cs @@ -1,490 +1,490 @@ -using System; -using System.Collections.Generic; - -namespace FairyGUI -{ - /// - /// - /// - [Obsolete("Use GTree and GTreeNode instead")] - public class TreeView : EventDispatcher - { - /// - /// TreeView使用的List对象 - /// - public GList list { get; private set; } - - /// - /// TreeView的顶层节点,这是个虚拟节点,也就是他不会显示出来。 - /// - public TreeNode root { get; private set; } - - /// - /// TreeView每级的缩进,单位像素。 - /// - public int indent; - - public delegate GComponent TreeNodeCreateCellDelegate(TreeNode node); - public delegate void TreeNodeRenderDelegate(TreeNode node); - public delegate void TreeNodeWillExpandDelegate(TreeNode node, bool expand); - - /// - /// 当TreeNode需要创建对象的显示对象时回调 - /// - public TreeNodeCreateCellDelegate treeNodeCreateCell; - - /// - /// 当TreeNode需要更新时回调 - /// - public TreeNodeRenderDelegate treeNodeRender; - - /// - /// 当TreeNode即将展开或者收缩时回调。可以在回调中动态增加子节点。 - /// - public TreeNodeWillExpandDelegate treeNodeWillExpand; - - /// - /// 点击任意TreeNode时触发 - /// - public EventListener onClickNode { get; private set; } - - /// - /// 右键点击任意TreeNode时触发 - /// - public EventListener onRightClickNode { get; private set; } - - /// - /// - /// - /// - public TreeView(GList list) - { - this.list = list; - list.onClickItem.Add(__clickItem); - list.onRightClickItem.Add(__clickItem); - list.RemoveChildrenToPool(); - - root = new TreeNode(true); - root.SetTree(this); - root.cell = list; - root.expanded = true; - - indent = 30; - - onClickNode = new EventListener(this, "onClickNode"); - onRightClickNode = new EventListener(this, "onRightClickNode"); - } - - /// - /// - /// - /// - public TreeNode GetSelectedNode() - { - if (list.selectedIndex != -1) - return (TreeNode)list.GetChildAt(list.selectedIndex).data; - else - return null; - } - - /// - /// - /// - /// - public List GetSelection() - { - List sels = list.GetSelection(); - int cnt = sels.Count; - List ret = new List(); - for (int i = 0; i < cnt; i++) - { - TreeNode node = (TreeNode)list.GetChildAt(sels[i]).data; - ret.Add(node); - } - return ret; - } - - /// - /// - /// - /// - /// - public void AddSelection(TreeNode node, bool scrollItToView = false) - { - TreeNode parentNode = node.parent; - while (parentNode != null && parentNode != root) - { - parentNode.expanded = true; - parentNode = parentNode.parent; - } - list.AddSelection(list.GetChildIndex(node.cell), scrollItToView); - } - - /// - /// - /// - /// - public void RemoveSelection(TreeNode node) - { - list.RemoveSelection(list.GetChildIndex(node.cell)); - } - - /// - /// - /// - public void ClearSelection() - { - list.ClearSelection(); - } - - /// - /// - /// - /// - /// - public int GetNodeIndex(TreeNode node) - { - return list.GetChildIndex(node.cell); - } - - /// - /// - /// - /// - public void UpdateNode(TreeNode node) - { - if (node.cell == null) - return; - - if (treeNodeRender != null) - treeNodeRender(node); - } - - /// - /// - /// - /// - public void UpdateNodes(List nodes) - { - int cnt = nodes.Count; - for (int i = 0; i < cnt; i++) - { - TreeNode node = nodes[i]; - if (node.cell == null) - return; - - if (treeNodeRender != null) - treeNodeRender(node); - } - } - - /// - /// - /// - /// - public void ExpandAll(TreeNode folderNode) - { - folderNode.expanded = true; - int cnt = folderNode.numChildren; - for (int i = 0; i < cnt; i++) - { - TreeNode node = folderNode.GetChildAt(i); - if (node.isFolder) - ExpandAll(node); - } - } - - /// - /// - /// - /// - public void CollapseAll(TreeNode folderNode) - { - if (folderNode != root) - folderNode.expanded = false; - int cnt = folderNode.numChildren; - for (int i = 0; i < cnt; i++) - { - TreeNode node = folderNode.GetChildAt(i); - if (node.isFolder) - CollapseAll(node); - } - } - - /// - /// - /// - /// - void CreateCell(TreeNode node) - { - if (treeNodeCreateCell != null) - node.cell = treeNodeCreateCell(node); - else - node.cell = list.itemPool.GetObject(list.defaultItem) as GComponent; - if (node.cell == null) - throw new Exception("Unable to create tree cell"); - node.cell.data = node; - - GObject indentObj = node.cell.GetChild("indent"); - if (indentObj != null) - indentObj.width = (node.level - 1) * indent; - - GButton expandButton = (GButton)node.cell.GetChild("expandButton"); - if (expandButton != null) - { - if (node.isFolder) - { - expandButton.visible = true; - expandButton.onClick.Add(__clickExpandButton); - expandButton.data = node; - expandButton.selected = node.expanded; - } - else - expandButton.visible = false; - } - - if (treeNodeRender != null) - treeNodeRender(node); - } - - /// - /// - /// - /// - internal void AfterInserted(TreeNode node) - { - CreateCell(node); - - int index = GetInsertIndexForNode(node); - list.AddChildAt(node.cell, index); - if (treeNodeRender != null) - treeNodeRender(node); - - if (node.isFolder && node.expanded) - CheckChildren(node, index); - } - - /// - /// - /// - /// - /// - int GetInsertIndexForNode(TreeNode node) - { - TreeNode prevNode = node.GetPrevSibling(); - if (prevNode == null) - prevNode = node.parent; - int insertIndex = list.GetChildIndex(prevNode.cell) + 1; - int myLevel = node.level; - int cnt = list.numChildren; - for (int i = insertIndex; i < cnt; i++) - { - TreeNode testNode = (TreeNode)list.GetChildAt(i).data; - if (testNode.level <= myLevel) - break; - - insertIndex++; - } - - return insertIndex; - } - - /// - /// - /// - /// - internal void AfterRemoved(TreeNode node) - { - RemoveNode(node); - } - - /// - /// - /// - /// - internal void AfterExpanded(TreeNode node) - { - if (node != root && treeNodeWillExpand != null) - treeNodeWillExpand(node, true); - - if (node.cell == null) - return; - - if (node != root) - { - if (treeNodeRender != null) - treeNodeRender(node); - - GButton expandButton = (GButton)node.cell.GetChild("expandButton"); - if (expandButton != null) - expandButton.selected = true; - } - - if (node.cell.parent != null) - CheckChildren(node, list.GetChildIndex(node.cell)); - } - - /// - /// - /// - /// - internal void AfterCollapsed(TreeNode node) - { - if (node != root && treeNodeWillExpand != null) - treeNodeWillExpand(node, false); - - if (node.cell == null) - return; - - if (node != root) - { - if (treeNodeRender != null) - treeNodeRender(node); - - GButton expandButton = (GButton)node.cell.GetChild("expandButton"); - if (expandButton != null) - expandButton.selected = false; - } - - if (node.cell.parent != null) - HideFolderNode(node); - } - - /// - /// - /// - /// - internal void AfterMoved(TreeNode node) - { - if (!node.isFolder) - list.RemoveChild(node.cell); - else - HideFolderNode(node); - - int index = GetInsertIndexForNode(node); - list.AddChildAt(node.cell, index); - - if (node.isFolder && node.expanded) - CheckChildren(node, index); - } - - /// - /// - /// - /// - /// - /// - int CheckChildren(TreeNode folderNode, int index) - { - int cnt = folderNode.numChildren; - for (int i = 0; i < cnt; i++) - { - index++; - TreeNode node = folderNode.GetChildAt(i); - if (node.cell == null) - CreateCell(node); - - if (node.cell.parent == null) - list.AddChildAt(node.cell, index); - - if (node.isFolder && node.expanded) - index = CheckChildren(node, index); - } - - return index; - } - - /// - /// - /// - /// - void HideFolderNode(TreeNode folderNode) - { - int cnt = folderNode.numChildren; - for (int i = 0; i < cnt; i++) - { - TreeNode node = folderNode.GetChildAt(i); - if (node.cell != null) - { - if (node.cell.parent != null) - list.RemoveChild(node.cell); - list.itemPool.ReturnObject(node.cell); - node.cell.data = null; - node.cell = null; - } - if (node.isFolder && node.expanded) - HideFolderNode(node); - } - } - - /// - /// - /// - /// - void RemoveNode(TreeNode node) - { - if (node.cell != null) - { - if (node.cell.parent != null) - list.RemoveChild(node.cell); - list.itemPool.ReturnObject(node.cell); - node.cell.data = null; - node.cell = null; - } - - if (node.isFolder) - { - int cnt = node.numChildren; - for (int i = 0; i < cnt; i++) - { - TreeNode node2 = node.GetChildAt(i); - RemoveNode(node2); - } - } - } - - void __clickExpandButton(EventContext context) - { - context.StopPropagation(); - - GButton expandButton = (GButton)context.sender; - TreeNode node = (TreeNode)expandButton.parent.data; - if (list.scrollPane != null) - { - float posY = list.scrollPane.posY; - if (expandButton.selected) - node.expanded = true; - else - node.expanded = false; - list.scrollPane.posY = posY; - list.scrollPane.ScrollToView(node.cell); - } - else - { - if (expandButton.selected) - node.expanded = true; - else - node.expanded = false; - } - } - - void __clickItem(EventContext context) - { - float posY = 0; - if (list.scrollPane != null) - posY = list.scrollPane.posY; - - TreeNode node = (TreeNode)((GObject)context.data).data; - if (context.type == list.onRightClickItem.type) - onRightClickNode.Call(node); - else - onClickNode.Call(node); - - if (list.scrollPane != null) - { - list.scrollPane.posY = posY; - list.scrollPane.ScrollToView(node.cell); - } - } - } -} +using System; +using System.Collections.Generic; + +namespace FairyGUI +{ + /// + /// + /// + [Obsolete("Use GTree and GTreeNode instead")] + public class TreeView : EventDispatcher + { + /// + /// TreeView使用的List对象 + /// + public GList list { get; private set; } + + /// + /// TreeView的顶层节点,这是个虚拟节点,也就是他不会显示出来。 + /// + public TreeNode root { get; private set; } + + /// + /// TreeView每级的缩进,单位像素。 + /// + public int indent; + + public delegate GComponent TreeNodeCreateCellDelegate(TreeNode node); + public delegate void TreeNodeRenderDelegate(TreeNode node); + public delegate void TreeNodeWillExpandDelegate(TreeNode node, bool expand); + + /// + /// 当TreeNode需要创建对象的显示对象时回调 + /// + public TreeNodeCreateCellDelegate treeNodeCreateCell; + + /// + /// 当TreeNode需要更新时回调 + /// + public TreeNodeRenderDelegate treeNodeRender; + + /// + /// 当TreeNode即将展开或者收缩时回调。可以在回调中动态增加子节点。 + /// + public TreeNodeWillExpandDelegate treeNodeWillExpand; + + /// + /// 点击任意TreeNode时触发 + /// + public EventListener onClickNode { get; private set; } + + /// + /// 右键点击任意TreeNode时触发 + /// + public EventListener onRightClickNode { get; private set; } + + /// + /// + /// + /// + public TreeView(GList list) + { + this.list = list; + list.onClickItem.Add(__clickItem); + list.onRightClickItem.Add(__clickItem); + list.RemoveChildrenToPool(); + + root = new TreeNode(true); + root.SetTree(this); + root.cell = list; + root.expanded = true; + + indent = 30; + + onClickNode = new EventListener(this, "onClickNode"); + onRightClickNode = new EventListener(this, "onRightClickNode"); + } + + /// + /// + /// + /// + public TreeNode GetSelectedNode() + { + if (list.selectedIndex != -1) + return (TreeNode)list.GetChildAt(list.selectedIndex).data; + else + return null; + } + + /// + /// + /// + /// + public List GetSelection() + { + List sels = list.GetSelection(); + int cnt = sels.Count; + List ret = new List(); + for (int i = 0; i < cnt; i++) + { + TreeNode node = (TreeNode)list.GetChildAt(sels[i]).data; + ret.Add(node); + } + return ret; + } + + /// + /// + /// + /// + /// + public void AddSelection(TreeNode node, bool scrollItToView = false) + { + TreeNode parentNode = node.parent; + while (parentNode != null && parentNode != root) + { + parentNode.expanded = true; + parentNode = parentNode.parent; + } + list.AddSelection(list.GetChildIndex(node.cell), scrollItToView); + } + + /// + /// + /// + /// + public void RemoveSelection(TreeNode node) + { + list.RemoveSelection(list.GetChildIndex(node.cell)); + } + + /// + /// + /// + public void ClearSelection() + { + list.ClearSelection(); + } + + /// + /// + /// + /// + /// + public int GetNodeIndex(TreeNode node) + { + return list.GetChildIndex(node.cell); + } + + /// + /// + /// + /// + public void UpdateNode(TreeNode node) + { + if (node.cell == null) + return; + + if (treeNodeRender != null) + treeNodeRender(node); + } + + /// + /// + /// + /// + public void UpdateNodes(List nodes) + { + int cnt = nodes.Count; + for (int i = 0; i < cnt; i++) + { + TreeNode node = nodes[i]; + if (node.cell == null) + return; + + if (treeNodeRender != null) + treeNodeRender(node); + } + } + + /// + /// + /// + /// + public void ExpandAll(TreeNode folderNode) + { + folderNode.expanded = true; + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node = folderNode.GetChildAt(i); + if (node.isFolder) + ExpandAll(node); + } + } + + /// + /// + /// + /// + public void CollapseAll(TreeNode folderNode) + { + if (folderNode != root) + folderNode.expanded = false; + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node = folderNode.GetChildAt(i); + if (node.isFolder) + CollapseAll(node); + } + } + + /// + /// + /// + /// + void CreateCell(TreeNode node) + { + if (treeNodeCreateCell != null) + node.cell = treeNodeCreateCell(node); + else + node.cell = list.itemPool.GetObject(list.defaultItem) as GComponent; + if (node.cell == null) + throw new Exception("Unable to create tree cell"); + node.cell.data = node; + + GObject indentObj = node.cell.GetChild("indent"); + if (indentObj != null) + indentObj.width = (node.level - 1) * indent; + + GButton expandButton = (GButton)node.cell.GetChild("expandButton"); + if (expandButton != null) + { + if (node.isFolder) + { + expandButton.visible = true; + expandButton.onClick.Add(__clickExpandButton); + expandButton.data = node; + expandButton.selected = node.expanded; + } + else + expandButton.visible = false; + } + + if (treeNodeRender != null) + treeNodeRender(node); + } + + /// + /// + /// + /// + internal void AfterInserted(TreeNode node) + { + CreateCell(node); + + int index = GetInsertIndexForNode(node); + list.AddChildAt(node.cell, index); + if (treeNodeRender != null) + treeNodeRender(node); + + if (node.isFolder && node.expanded) + CheckChildren(node, index); + } + + /// + /// + /// + /// + /// + int GetInsertIndexForNode(TreeNode node) + { + TreeNode prevNode = node.GetPrevSibling(); + if (prevNode == null) + prevNode = node.parent; + int insertIndex = list.GetChildIndex(prevNode.cell) + 1; + int myLevel = node.level; + int cnt = list.numChildren; + for (int i = insertIndex; i < cnt; i++) + { + TreeNode testNode = (TreeNode)list.GetChildAt(i).data; + if (testNode.level <= myLevel) + break; + + insertIndex++; + } + + return insertIndex; + } + + /// + /// + /// + /// + internal void AfterRemoved(TreeNode node) + { + RemoveNode(node); + } + + /// + /// + /// + /// + internal void AfterExpanded(TreeNode node) + { + if (node != root && treeNodeWillExpand != null) + treeNodeWillExpand(node, true); + + if (node.cell == null) + return; + + if (node != root) + { + if (treeNodeRender != null) + treeNodeRender(node); + + GButton expandButton = (GButton)node.cell.GetChild("expandButton"); + if (expandButton != null) + expandButton.selected = true; + } + + if (node.cell.parent != null) + CheckChildren(node, list.GetChildIndex(node.cell)); + } + + /// + /// + /// + /// + internal void AfterCollapsed(TreeNode node) + { + if (node != root && treeNodeWillExpand != null) + treeNodeWillExpand(node, false); + + if (node.cell == null) + return; + + if (node != root) + { + if (treeNodeRender != null) + treeNodeRender(node); + + GButton expandButton = (GButton)node.cell.GetChild("expandButton"); + if (expandButton != null) + expandButton.selected = false; + } + + if (node.cell.parent != null) + HideFolderNode(node); + } + + /// + /// + /// + /// + internal void AfterMoved(TreeNode node) + { + if (!node.isFolder) + list.RemoveChild(node.cell); + else + HideFolderNode(node); + + int index = GetInsertIndexForNode(node); + list.AddChildAt(node.cell, index); + + if (node.isFolder && node.expanded) + CheckChildren(node, index); + } + + /// + /// + /// + /// + /// + /// + int CheckChildren(TreeNode folderNode, int index) + { + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + index++; + TreeNode node = folderNode.GetChildAt(i); + if (node.cell == null) + CreateCell(node); + + if (node.cell.parent == null) + list.AddChildAt(node.cell, index); + + if (node.isFolder && node.expanded) + index = CheckChildren(node, index); + } + + return index; + } + + /// + /// + /// + /// + void HideFolderNode(TreeNode folderNode) + { + int cnt = folderNode.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node = folderNode.GetChildAt(i); + if (node.cell != null) + { + if (node.cell.parent != null) + list.RemoveChild(node.cell); + list.itemPool.ReturnObject(node.cell); + node.cell.data = null; + node.cell = null; + } + if (node.isFolder && node.expanded) + HideFolderNode(node); + } + } + + /// + /// + /// + /// + void RemoveNode(TreeNode node) + { + if (node.cell != null) + { + if (node.cell.parent != null) + list.RemoveChild(node.cell); + list.itemPool.ReturnObject(node.cell); + node.cell.data = null; + node.cell = null; + } + + if (node.isFolder) + { + int cnt = node.numChildren; + for (int i = 0; i < cnt; i++) + { + TreeNode node2 = node.GetChildAt(i); + RemoveNode(node2); + } + } + } + + void __clickExpandButton(EventContext context) + { + context.StopPropagation(); + + GButton expandButton = (GButton)context.sender; + TreeNode node = (TreeNode)expandButton.parent.data; + if (list.scrollPane != null) + { + float posY = list.scrollPane.posY; + if (expandButton.selected) + node.expanded = true; + else + node.expanded = false; + list.scrollPane.posY = posY; + list.scrollPane.ScrollToView(node.cell); + } + else + { + if (expandButton.selected) + node.expanded = true; + else + node.expanded = false; + } + } + + void __clickItem(EventContext context) + { + float posY = 0; + if (list.scrollPane != null) + posY = list.scrollPane.posY; + + TreeNode node = (TreeNode)((GObject)context.data).data; + if (context.type == list.onRightClickItem.type) + onRightClickNode.Call(node); + else + onClickNode.Call(node); + + if (list.scrollPane != null) + { + list.scrollPane.posY = posY; + list.scrollPane.ScrollToView(node.cell); + } + } + } +} diff --git a/Assets/Scripts/UI/Tree/TreeView.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeView.cs.meta similarity index 100% rename from Assets/Scripts/UI/Tree/TreeView.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Tree/TreeView.cs.meta diff --git a/Assets/Scripts/UI/UIConfig.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIConfig.cs similarity index 97% rename from Assets/Scripts/UI/UIConfig.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIConfig.cs index a253e659..a10131ea 100644 --- a/Assets/Scripts/UI/UIConfig.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIConfig.cs @@ -1,462 +1,462 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// Global configs. These options should be set before any UI construction. - /// - [AddComponentMenu("FairyGUI/UI Config")] - public class UIConfig : MonoBehaviour - { - /// - /// Dynamic Font Support. - /// 4.x: Put the xxx.ttf into /Resources or /Resources/Fonts, and set defaultFont="xxx". - /// 5.x: set defaultFont to system font name(or names joint with comma). e.g. defaultFont="Microsoft YaHei, SimHei" - /// - public static string defaultFont = ""; - - [Obsolete("No use anymore")] - public static bool renderingTextBrighterOnDesktop = true; - - /// - /// Resource using in Window.ShowModalWait for locking the window. - /// - public static string windowModalWaiting; - - /// - /// Resource using in GRoot.ShowModalWait for locking the screen. - /// - public static string globalModalWaiting; - - /// - /// When a modal window is in front, the background becomes dark. - /// - public static Color modalLayerColor = new Color(0f, 0f, 0f, 0.4f); - - /// - /// Default button click sound. - /// - public static NAudioClip buttonSound; - - /// - /// Default button click sound volume. - /// - public static float buttonSoundVolumeScale = 1f; - - /// - /// Resource url of horizontal scrollbar - /// - public static string horizontalScrollBar; - - /// - /// Resource url of vertical scrollbar - /// - public static string verticalScrollBar; - - /// - /// Scrolling step in pixels - /// 当调用ScrollPane.scrollUp/Down/Left/Right时,或者点击滚动条的上下箭头时,滑动的距离。 - /// 鼠标滚轮触发一次滚动的距离设定为defaultScrollStep*2 - /// - public static float defaultScrollStep = 25; - - /// - /// Deceleration ratio of scrollpane when its in touch dragging. - /// 当手指拖动并释放滚动区域后,内容会滑动一定距离后停下,这个速率就是减速的速率。 - /// 越接近1,减速越慢,意味着滑动的时间和距离更长。 - /// 这个是全局设置,也可以通过ScrollPane.decelerationRate进行个性设置。 - /// - public static float defaultScrollDecelerationRate = 0.967f; - - /// - /// Scrollbar display mode. Recommended 'Auto' for mobile and 'Visible' for web. - /// - public static ScrollBarDisplayType defaultScrollBarDisplay = ScrollBarDisplayType.Default; - - /// - /// Allow dragging anywhere in container to scroll. - /// - public static bool defaultScrollTouchEffect = true; - - /// - /// The "rebound" effect in the scolling container. - /// - public static bool defaultScrollBounceEffect = true; - - /// - /// When the scrolling container is set to "snap to the item", the rolling distance threshold of which item is close to is determined. - /// - public static float defaultScrollSnappingThreshold = 0.5f; - - /// - /// When the scrolling container is set to "page mode", it determines the scrolling distance threshold to which page to turn. - /// - public static float defaultScrollPagingThreshold = 0.3f; - - /// - /// Resources url of PopupMenu. - /// - public static string popupMenu; - - /// - /// Resource url of menu seperator. - /// - public static string popupMenu_seperator; - - /// - /// In case of failure of loading content for GLoader, use this sign to indicate an error. - /// - public static string loaderErrorSign; - - /// - /// Resource url of tooltips. - /// - public static string tooltipsWin; - - /// - /// The number of visible items in ComboBox. - /// - public static int defaultComboBoxVisibleItemCount = 10; - - /// - /// Pixel offsets of finger to trigger scrolling - /// - public static int touchScrollSensitivity = 20; - - /// - /// Pixel offsets of finger to trigger dragging - /// - public static int touchDragSensitivity = 10; - - /// - /// Pixel offsets of mouse pointer to trigger dragging. - /// - public static int clickDragSensitivity = 2; - - /// - /// Allow softness on top or left side for scrollpane. - /// - public static bool allowSoftnessOnTopOrLeftSide = true; - - /// - /// When click the window, brings to front automatically. - /// - public static bool bringWindowToFrontOnClick = true; - - /// - /// - /// - public static float inputCaretSize = 1; - - /// - /// - /// - public static Color inputHighlightColor = new Color32(255, 223, 141, 128); - - /// - /// - /// - public static float frameTimeForAsyncUIConstruction = 0.002f; - - /// - /// if RenderTexture using in painting mode has depth support. - /// - public static bool depthSupportForPaintingMode = true; - - /// - /// Indicates whether to draw extra 4 or 8 times to achieve stroke effect for textfield. - /// If it is true, that is the 8 times, otherwise it is the 4 times. - /// - public static bool enhancedTextOutlineEffect = false; - - [Obsolete("No use anymore.")] - public static VertAlignType richTextRowVerticalAlign = VertAlignType.Bottom; - - /// - /// Suggest to enable it on low dpi (e.g. 96dpi) screens. - /// - public static bool makePixelPerfect = false; - - public enum ConfigKey - { - DefaultFont, - ButtonSound, - ButtonSoundVolumeScale, - HorizontalScrollBar, - VerticalScrollBar, - DefaultScrollStep, - DefaultScrollBarDisplay, - DefaultScrollTouchEffect, - DefaultScrollBounceEffect, - TouchScrollSensitivity, - WindowModalWaiting, - GlobalModalWaiting, - PopupMenu, - PopupMenu_seperator, - LoaderErrorSign, - TooltipsWin, - DefaultComboBoxVisibleItemCount, - TouchDragSensitivity, - ClickDragSensitivity, - ModalLayerColor, - RenderingTextBrighterOnDesktop, - AllowSoftnessOnTopOrLeftSide, - InputCaretSize, - InputHighlightColor, - EnhancedTextOutlineEffect, - DepthSupportForPaintingMode, - RichTextRowVerticalAlign, - Branch, - - PleaseSelect = 100 - } - - [Serializable] - public class ConfigValue - { - public bool valid; - public string s; - public int i; - public float f; - public bool b; - public Color c; - - public void Reset() - { - valid = false; - s = null; - i = 0; - f = 0; - b = false; - c = Color.black; - } - } - - public List Items = new List(); - public List PreloadPackages = new List(); - - void Awake() - { - if (Application.isPlaying) - { - foreach (string packagePath in PreloadPackages) - { - UIPackage.AddPackage(packagePath); - } - - Load(); - } - } - - public void Load() - { - int cnt = Items.Count; - for (int i = 0; i < cnt; i++) - { - ConfigValue value = Items[i]; - if (!value.valid) - continue; - - switch ((UIConfig.ConfigKey)i) - { - case ConfigKey.ButtonSound: - if (Application.isPlaying) - UIConfig.buttonSound = UIPackage.GetItemAssetByURL(value.s) as NAudioClip; - break; - - case ConfigKey.ButtonSoundVolumeScale: - UIConfig.buttonSoundVolumeScale = value.f; - break; - - case ConfigKey.ClickDragSensitivity: - UIConfig.clickDragSensitivity = value.i; - break; - - case ConfigKey.DefaultComboBoxVisibleItemCount: - UIConfig.defaultComboBoxVisibleItemCount = value.i; - break; - - case ConfigKey.DefaultFont: - UIConfig.defaultFont = value.s; - break; - - case ConfigKey.DefaultScrollBarDisplay: - UIConfig.defaultScrollBarDisplay = (ScrollBarDisplayType)value.i; - break; - - case ConfigKey.DefaultScrollBounceEffect: - UIConfig.defaultScrollBounceEffect = value.b; - break; - - case ConfigKey.DefaultScrollStep: - UIConfig.defaultScrollStep = value.i; - break; - - case ConfigKey.DefaultScrollTouchEffect: - UIConfig.defaultScrollTouchEffect = value.b; - break; - - case ConfigKey.GlobalModalWaiting: - UIConfig.globalModalWaiting = value.s; - break; - - case ConfigKey.HorizontalScrollBar: - UIConfig.horizontalScrollBar = value.s; - break; - - case ConfigKey.LoaderErrorSign: - UIConfig.loaderErrorSign = value.s; - break; - - case ConfigKey.ModalLayerColor: - UIConfig.modalLayerColor = value.c; - break; - - case ConfigKey.PopupMenu: - UIConfig.popupMenu = value.s; - break; - - case ConfigKey.PopupMenu_seperator: - UIConfig.popupMenu_seperator = value.s; - break; - - case ConfigKey.TooltipsWin: - UIConfig.tooltipsWin = value.s; - break; - - case ConfigKey.TouchDragSensitivity: - UIConfig.touchDragSensitivity = value.i; - break; - - case ConfigKey.TouchScrollSensitivity: - UIConfig.touchScrollSensitivity = value.i; - break; - - case ConfigKey.VerticalScrollBar: - UIConfig.verticalScrollBar = value.s; - break; - - case ConfigKey.WindowModalWaiting: - UIConfig.windowModalWaiting = value.s; - break; - - case ConfigKey.AllowSoftnessOnTopOrLeftSide: - UIConfig.allowSoftnessOnTopOrLeftSide = value.b; - break; - - case ConfigKey.InputCaretSize: - UIConfig.inputCaretSize = value.i; - break; - - case ConfigKey.InputHighlightColor: - UIConfig.inputHighlightColor = value.c; - break; - - case ConfigKey.DepthSupportForPaintingMode: - UIConfig.depthSupportForPaintingMode = value.b; - break; - - case ConfigKey.EnhancedTextOutlineEffect: - UIConfig.enhancedTextOutlineEffect = value.b; - break; - - case ConfigKey.Branch: - UIPackage.branch = value.s; - break; - } - } - } - - public static void SetDefaultValue(ConfigKey key, ConfigValue value) - { - switch (key) - { - case ConfigKey.ButtonSoundVolumeScale: - value.f = 1; - break; - - case ConfigKey.ClickDragSensitivity: - value.i = 2; - break; - - case ConfigKey.DefaultComboBoxVisibleItemCount: - value.i = 10; - break; - - case ConfigKey.DefaultScrollBarDisplay: - value.i = (int)ScrollBarDisplayType.Default; - break; - - case ConfigKey.DefaultScrollBounceEffect: - case ConfigKey.DefaultScrollTouchEffect: - value.b = true; - break; - - case ConfigKey.DefaultScrollStep: - value.i = 25; - break; - - case ConfigKey.ModalLayerColor: - value.c = new Color(0f, 0f, 0f, 0.4f); - break; - - case ConfigKey.RenderingTextBrighterOnDesktop: - value.b = true; - break; - - case ConfigKey.TouchDragSensitivity: - value.i = 10; - break; - - case ConfigKey.TouchScrollSensitivity: - value.i = 20; - break; - - case ConfigKey.InputCaretSize: - value.i = 1; - break; - - case ConfigKey.InputHighlightColor: - value.c = new Color32(255, 223, 141, 128); - break; - - case ConfigKey.DepthSupportForPaintingMode: - value.b = false; - break; - - case ConfigKey.Branch: - value.s = ""; - break; - } - } - - public static void ClearResourceRefs() - { - UIConfig.defaultFont = ""; - UIConfig.buttonSound = null; - UIConfig.globalModalWaiting = null; - UIConfig.horizontalScrollBar = null; - UIConfig.loaderErrorSign = null; - UIConfig.popupMenu = null; - UIConfig.popupMenu_seperator = null; - UIConfig.tooltipsWin = null; - UIConfig.verticalScrollBar = null; - UIConfig.windowModalWaiting = null; - UIPackage.branch = null; - } - - public void ApplyModifiedProperties() - { - EMRenderSupport.Reload(); - } - - public delegate NAudioClip SoundLoader(string url); - - /// - /// - /// - public static SoundLoader soundLoader = null; - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Global configs. These options should be set before any UI construction. + /// + [AddComponentMenu("FairyGUI/UI Config")] + public class UIConfig : MonoBehaviour + { + /// + /// Dynamic Font Support. + /// 4.x: Put the xxx.ttf into /Resources or /Resources/Fonts, and set defaultFont="xxx". + /// 5.x: set defaultFont to system font name(or names joint with comma). e.g. defaultFont="Microsoft YaHei, SimHei" + /// + public static string defaultFont = ""; + + [Obsolete("No use anymore")] + public static bool renderingTextBrighterOnDesktop = true; + + /// + /// Resource using in Window.ShowModalWait for locking the window. + /// + public static string windowModalWaiting; + + /// + /// Resource using in GRoot.ShowModalWait for locking the screen. + /// + public static string globalModalWaiting; + + /// + /// When a modal window is in front, the background becomes dark. + /// + public static Color modalLayerColor = new Color(0f, 0f, 0f, 0.4f); + + /// + /// Default button click sound. + /// + public static NAudioClip buttonSound; + + /// + /// Default button click sound volume. + /// + public static float buttonSoundVolumeScale = 1f; + + /// + /// Resource url of horizontal scrollbar + /// + public static string horizontalScrollBar; + + /// + /// Resource url of vertical scrollbar + /// + public static string verticalScrollBar; + + /// + /// Scrolling step in pixels + /// 当调用ScrollPane.scrollUp/Down/Left/Right时,或者点击滚动条的上下箭头时,滑动的距离。 + /// 鼠标滚轮触发一次滚动的距离设定为defaultScrollStep*2 + /// + public static float defaultScrollStep = 25; + + /// + /// Deceleration ratio of scrollpane when its in touch dragging. + /// 当手指拖动并释放滚动区域后,内容会滑动一定距离后停下,这个速率就是减速的速率。 + /// 越接近1,减速越慢,意味着滑动的时间和距离更长。 + /// 这个是全局设置,也可以通过ScrollPane.decelerationRate进行个性设置。 + /// + public static float defaultScrollDecelerationRate = 0.967f; + + /// + /// Scrollbar display mode. Recommended 'Auto' for mobile and 'Visible' for web. + /// + public static ScrollBarDisplayType defaultScrollBarDisplay = ScrollBarDisplayType.Default; + + /// + /// Allow dragging anywhere in container to scroll. + /// + public static bool defaultScrollTouchEffect = true; + + /// + /// The "rebound" effect in the scolling container. + /// + public static bool defaultScrollBounceEffect = true; + + /// + /// When the scrolling container is set to "snap to the item", the rolling distance threshold of which item is close to is determined. + /// + public static float defaultScrollSnappingThreshold = 0.5f; + + /// + /// When the scrolling container is set to "page mode", it determines the scrolling distance threshold to which page to turn. + /// + public static float defaultScrollPagingThreshold = 0.3f; + + /// + /// Resources url of PopupMenu. + /// + public static string popupMenu; + + /// + /// Resource url of menu seperator. + /// + public static string popupMenu_seperator; + + /// + /// In case of failure of loading content for GLoader, use this sign to indicate an error. + /// + public static string loaderErrorSign; + + /// + /// Resource url of tooltips. + /// + public static string tooltipsWin; + + /// + /// The number of visible items in ComboBox. + /// + public static int defaultComboBoxVisibleItemCount = 10; + + /// + /// Pixel offsets of finger to trigger scrolling + /// + public static int touchScrollSensitivity = 20; + + /// + /// Pixel offsets of finger to trigger dragging + /// + public static int touchDragSensitivity = 10; + + /// + /// Pixel offsets of mouse pointer to trigger dragging. + /// + public static int clickDragSensitivity = 2; + + /// + /// Allow softness on top or left side for scrollpane. + /// + public static bool allowSoftnessOnTopOrLeftSide = true; + + /// + /// When click the window, brings to front automatically. + /// + public static bool bringWindowToFrontOnClick = true; + + /// + /// + /// + public static float inputCaretSize = 1; + + /// + /// + /// + public static Color inputHighlightColor = new Color32(255, 223, 141, 128); + + /// + /// + /// + public static float frameTimeForAsyncUIConstruction = 0.002f; + + /// + /// if RenderTexture using in painting mode has depth support. + /// + public static bool depthSupportForPaintingMode = true; + + /// + /// Indicates whether to draw extra 4 or 8 times to achieve stroke effect for textfield. + /// If it is true, that is the 8 times, otherwise it is the 4 times. + /// + public static bool enhancedTextOutlineEffect = false; + + [Obsolete("No use anymore.")] + public static VertAlignType richTextRowVerticalAlign = VertAlignType.Bottom; + + /// + /// Suggest to enable it on low dpi (e.g. 96dpi) screens. + /// + public static bool makePixelPerfect = false; + + public enum ConfigKey + { + DefaultFont, + ButtonSound, + ButtonSoundVolumeScale, + HorizontalScrollBar, + VerticalScrollBar, + DefaultScrollStep, + DefaultScrollBarDisplay, + DefaultScrollTouchEffect, + DefaultScrollBounceEffect, + TouchScrollSensitivity, + WindowModalWaiting, + GlobalModalWaiting, + PopupMenu, + PopupMenu_seperator, + LoaderErrorSign, + TooltipsWin, + DefaultComboBoxVisibleItemCount, + TouchDragSensitivity, + ClickDragSensitivity, + ModalLayerColor, + RenderingTextBrighterOnDesktop, + AllowSoftnessOnTopOrLeftSide, + InputCaretSize, + InputHighlightColor, + EnhancedTextOutlineEffect, + DepthSupportForPaintingMode, + RichTextRowVerticalAlign, + Branch, + + PleaseSelect = 100 + } + + [Serializable] + public class ConfigValue + { + public bool valid; + public string s; + public int i; + public float f; + public bool b; + public Color c; + + public void Reset() + { + valid = false; + s = null; + i = 0; + f = 0; + b = false; + c = Color.black; + } + } + + public List Items = new List(); + public List PreloadPackages = new List(); + + void Awake() + { + if (Application.isPlaying) + { + foreach (string packagePath in PreloadPackages) + { + UIPackage.AddPackage(packagePath); + } + + Load(); + } + } + + public void Load() + { + int cnt = Items.Count; + for (int i = 0; i < cnt; i++) + { + ConfigValue value = Items[i]; + if (!value.valid) + continue; + + switch ((UIConfig.ConfigKey)i) + { + case ConfigKey.ButtonSound: + if (Application.isPlaying) + UIConfig.buttonSound = UIPackage.GetItemAssetByURL(value.s) as NAudioClip; + break; + + case ConfigKey.ButtonSoundVolumeScale: + UIConfig.buttonSoundVolumeScale = value.f; + break; + + case ConfigKey.ClickDragSensitivity: + UIConfig.clickDragSensitivity = value.i; + break; + + case ConfigKey.DefaultComboBoxVisibleItemCount: + UIConfig.defaultComboBoxVisibleItemCount = value.i; + break; + + case ConfigKey.DefaultFont: + UIConfig.defaultFont = value.s; + break; + + case ConfigKey.DefaultScrollBarDisplay: + UIConfig.defaultScrollBarDisplay = (ScrollBarDisplayType)value.i; + break; + + case ConfigKey.DefaultScrollBounceEffect: + UIConfig.defaultScrollBounceEffect = value.b; + break; + + case ConfigKey.DefaultScrollStep: + UIConfig.defaultScrollStep = value.i; + break; + + case ConfigKey.DefaultScrollTouchEffect: + UIConfig.defaultScrollTouchEffect = value.b; + break; + + case ConfigKey.GlobalModalWaiting: + UIConfig.globalModalWaiting = value.s; + break; + + case ConfigKey.HorizontalScrollBar: + UIConfig.horizontalScrollBar = value.s; + break; + + case ConfigKey.LoaderErrorSign: + UIConfig.loaderErrorSign = value.s; + break; + + case ConfigKey.ModalLayerColor: + UIConfig.modalLayerColor = value.c; + break; + + case ConfigKey.PopupMenu: + UIConfig.popupMenu = value.s; + break; + + case ConfigKey.PopupMenu_seperator: + UIConfig.popupMenu_seperator = value.s; + break; + + case ConfigKey.TooltipsWin: + UIConfig.tooltipsWin = value.s; + break; + + case ConfigKey.TouchDragSensitivity: + UIConfig.touchDragSensitivity = value.i; + break; + + case ConfigKey.TouchScrollSensitivity: + UIConfig.touchScrollSensitivity = value.i; + break; + + case ConfigKey.VerticalScrollBar: + UIConfig.verticalScrollBar = value.s; + break; + + case ConfigKey.WindowModalWaiting: + UIConfig.windowModalWaiting = value.s; + break; + + case ConfigKey.AllowSoftnessOnTopOrLeftSide: + UIConfig.allowSoftnessOnTopOrLeftSide = value.b; + break; + + case ConfigKey.InputCaretSize: + UIConfig.inputCaretSize = value.i; + break; + + case ConfigKey.InputHighlightColor: + UIConfig.inputHighlightColor = value.c; + break; + + case ConfigKey.DepthSupportForPaintingMode: + UIConfig.depthSupportForPaintingMode = value.b; + break; + + case ConfigKey.EnhancedTextOutlineEffect: + UIConfig.enhancedTextOutlineEffect = value.b; + break; + + case ConfigKey.Branch: + UIPackage.branch = value.s; + break; + } + } + } + + public static void SetDefaultValue(ConfigKey key, ConfigValue value) + { + switch (key) + { + case ConfigKey.ButtonSoundVolumeScale: + value.f = 1; + break; + + case ConfigKey.ClickDragSensitivity: + value.i = 2; + break; + + case ConfigKey.DefaultComboBoxVisibleItemCount: + value.i = 10; + break; + + case ConfigKey.DefaultScrollBarDisplay: + value.i = (int)ScrollBarDisplayType.Default; + break; + + case ConfigKey.DefaultScrollBounceEffect: + case ConfigKey.DefaultScrollTouchEffect: + value.b = true; + break; + + case ConfigKey.DefaultScrollStep: + value.i = 25; + break; + + case ConfigKey.ModalLayerColor: + value.c = new Color(0f, 0f, 0f, 0.4f); + break; + + case ConfigKey.RenderingTextBrighterOnDesktop: + value.b = true; + break; + + case ConfigKey.TouchDragSensitivity: + value.i = 10; + break; + + case ConfigKey.TouchScrollSensitivity: + value.i = 20; + break; + + case ConfigKey.InputCaretSize: + value.i = 1; + break; + + case ConfigKey.InputHighlightColor: + value.c = new Color32(255, 223, 141, 128); + break; + + case ConfigKey.DepthSupportForPaintingMode: + value.b = false; + break; + + case ConfigKey.Branch: + value.s = ""; + break; + } + } + + public static void ClearResourceRefs() + { + UIConfig.defaultFont = ""; + UIConfig.buttonSound = null; + UIConfig.globalModalWaiting = null; + UIConfig.horizontalScrollBar = null; + UIConfig.loaderErrorSign = null; + UIConfig.popupMenu = null; + UIConfig.popupMenu_seperator = null; + UIConfig.tooltipsWin = null; + UIConfig.verticalScrollBar = null; + UIConfig.windowModalWaiting = null; + UIPackage.branch = null; + } + + public void ApplyModifiedProperties() + { + EMRenderSupport.Reload(); + } + + public delegate NAudioClip SoundLoader(string url); + + /// + /// + /// + public static SoundLoader soundLoader = null; + } +} diff --git a/Assets/Scripts/UI/UIConfig.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIConfig.cs.meta similarity index 100% rename from Assets/Scripts/UI/UIConfig.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIConfig.cs.meta diff --git a/Assets/Scripts/UI/UIContentScaler.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIContentScaler.cs similarity index 96% rename from Assets/Scripts/UI/UIContentScaler.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIContentScaler.cs index 843a9e76..1daebb1e 100644 --- a/Assets/Scripts/UI/UIContentScaler.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIContentScaler.cs @@ -1,217 +1,217 @@ -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - [ExecuteInEditMode] - [AddComponentMenu("FairyGUI/UI Content Scaler")] - public class UIContentScaler : MonoBehaviour - { - /// - /// - /// - public enum ScaleMode - { - ConstantPixelSize, - ScaleWithScreenSize, - ConstantPhysicalSize - } - - /// - /// - /// - public enum ScreenMatchMode - { - MatchWidthOrHeight, - MatchWidth, - MatchHeight - } - - /// - /// - /// - public ScaleMode scaleMode; - - /// - /// - /// - public ScreenMatchMode screenMatchMode; - - /// - /// - /// - public int designResolutionX; - - /// - /// - /// - public int designResolutionY; - - /// - /// - /// - public int fallbackScreenDPI = 96; - - /// - /// - /// - public int defaultSpriteDPI = 96; - - /// - /// - /// - public float constantScaleFactor = 1; - - /// - /// 当false时,计算比例时会考虑designResolutionX/Y的设置是针对横屏还是竖屏。否则不考虑。 - /// - public bool ignoreOrientation = false; - - [System.NonSerialized] - public static float scaleFactor = 1; - - [System.NonSerialized] - public static int scaleLevel = 0; - - [System.NonSerialized] - bool _changed; - - void OnEnable() - { - if (Application.isPlaying) - { - //播放模式下都是通过Stage自带的UIContentScaler实现调整的,所以这里只是把参数传过去 - UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); - if (scaler != this) - { - scaler.scaleMode = scaleMode; - if (scaleMode == ScaleMode.ScaleWithScreenSize) - { - scaler.designResolutionX = designResolutionX; - scaler.designResolutionY = designResolutionY; - scaler.screenMatchMode = screenMatchMode; - scaler.ignoreOrientation = ignoreOrientation; - } - else if (scaleMode == ScaleMode.ConstantPhysicalSize) - { - scaler.fallbackScreenDPI = fallbackScreenDPI; - scaler.defaultSpriteDPI = defaultSpriteDPI; - } - else - { - scaler.constantScaleFactor = constantScaleFactor; - } - scaler.ApplyChange(); - GRoot.inst.ApplyContentScaleFactor(); - } - } - else //Screen width/height is not reliable in OnEnable in editmode - _changed = true; - } - - void Update() - { - if (_changed) - { - _changed = false; - ApplyChange(); - } - } - - void OnDestroy() - { - if (!Application.isPlaying) - { - scaleFactor = 1; - scaleLevel = 0; - } - } - - //For UIContentScalerEditor Only, as the Screen.width/height is not correct in OnInspectorGUI - /// - /// - /// - public void ApplyModifiedProperties() - { - _changed = true; - } - - /// - /// - /// - public void ApplyChange() - { - float screenWidth; - float screenHeight; - - if (Application.isPlaying) //In case of multi display, we keep using the display which Stage object resides. - { - screenWidth = Stage.inst.width; - screenHeight = Stage.inst.height; - } - else - { - screenWidth = Screen.width; - screenHeight = Screen.height; - } - if (scaleMode == ScaleMode.ScaleWithScreenSize) - { - if (designResolutionX == 0 || designResolutionY == 0) - return; - - int dx = designResolutionX; - int dy = designResolutionY; - if (!ignoreOrientation && (screenWidth > screenHeight && dx < dy || screenWidth < screenHeight && dx > dy)) - { - //scale should not change when orientation change - int tmp = dx; - dx = dy; - dy = tmp; - } - - if (screenMatchMode == ScreenMatchMode.MatchWidthOrHeight) - { - float s1 = (float)screenWidth / dx; - float s2 = (float)screenHeight / dy; - scaleFactor = Mathf.Min(s1, s2); - } - else if (screenMatchMode == ScreenMatchMode.MatchWidth) - scaleFactor = (float)screenWidth / dx; - else - scaleFactor = (float)screenHeight / dy; - } - else if (scaleMode == ScaleMode.ConstantPhysicalSize) - { - float dpi = Screen.dpi; - if (dpi == 0) - dpi = fallbackScreenDPI; - if (dpi == 0) - dpi = 96; - scaleFactor = dpi / (defaultSpriteDPI == 0 ? 96 : defaultSpriteDPI); - } - else - scaleFactor = constantScaleFactor; - - if (scaleFactor > 10) - scaleFactor = 10; - - UpdateScaleLevel(); - - StageCamera.screenSizeVer++; - } - - void UpdateScaleLevel() - { - if (scaleFactor > 3) - scaleLevel = 3; //x4 - else if (scaleFactor > 2) - scaleLevel = 2; //x3 - else if (scaleFactor > 1) - scaleLevel = 1; //x2 - else - scaleLevel = 0; - } - } -} +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Content Scaler")] + public class UIContentScaler : MonoBehaviour + { + /// + /// + /// + public enum ScaleMode + { + ConstantPixelSize, + ScaleWithScreenSize, + ConstantPhysicalSize + } + + /// + /// + /// + public enum ScreenMatchMode + { + MatchWidthOrHeight, + MatchWidth, + MatchHeight + } + + /// + /// + /// + public ScaleMode scaleMode; + + /// + /// + /// + public ScreenMatchMode screenMatchMode; + + /// + /// + /// + public int designResolutionX; + + /// + /// + /// + public int designResolutionY; + + /// + /// + /// + public int fallbackScreenDPI = 96; + + /// + /// + /// + public int defaultSpriteDPI = 96; + + /// + /// + /// + public float constantScaleFactor = 1; + + /// + /// 当false时,计算比例时会考虑designResolutionX/Y的设置是针对横屏还是竖屏。否则不考虑。 + /// + public bool ignoreOrientation = false; + + [System.NonSerialized] + public static float scaleFactor = 1; + + [System.NonSerialized] + public static int scaleLevel = 0; + + [System.NonSerialized] + bool _changed; + + void OnEnable() + { + if (Application.isPlaying) + { + //播放模式下都是通过Stage自带的UIContentScaler实现调整的,所以这里只是把参数传过去 + UIContentScaler scaler = Stage.inst.gameObject.GetComponent(); + if (scaler != this) + { + scaler.scaleMode = scaleMode; + if (scaleMode == ScaleMode.ScaleWithScreenSize) + { + scaler.designResolutionX = designResolutionX; + scaler.designResolutionY = designResolutionY; + scaler.screenMatchMode = screenMatchMode; + scaler.ignoreOrientation = ignoreOrientation; + } + else if (scaleMode == ScaleMode.ConstantPhysicalSize) + { + scaler.fallbackScreenDPI = fallbackScreenDPI; + scaler.defaultSpriteDPI = defaultSpriteDPI; + } + else + { + scaler.constantScaleFactor = constantScaleFactor; + } + scaler.ApplyChange(); + GRoot.inst.ApplyContentScaleFactor(); + } + } + else //Screen width/height is not reliable in OnEnable in editmode + _changed = true; + } + + void Update() + { + if (_changed) + { + _changed = false; + ApplyChange(); + } + } + + void OnDestroy() + { + if (!Application.isPlaying) + { + scaleFactor = 1; + scaleLevel = 0; + } + } + + //For UIContentScalerEditor Only, as the Screen.width/height is not correct in OnInspectorGUI + /// + /// + /// + public void ApplyModifiedProperties() + { + _changed = true; + } + + /// + /// + /// + public void ApplyChange() + { + float screenWidth; + float screenHeight; + + if (Application.isPlaying) //In case of multi display, we keep using the display which Stage object resides. + { + screenWidth = Stage.inst.width; + screenHeight = Stage.inst.height; + } + else + { + screenWidth = Screen.width; + screenHeight = Screen.height; + } + if (scaleMode == ScaleMode.ScaleWithScreenSize) + { + if (designResolutionX == 0 || designResolutionY == 0) + return; + + int dx = designResolutionX; + int dy = designResolutionY; + if (!ignoreOrientation && (screenWidth > screenHeight && dx < dy || screenWidth < screenHeight && dx > dy)) + { + //scale should not change when orientation change + int tmp = dx; + dx = dy; + dy = tmp; + } + + if (screenMatchMode == ScreenMatchMode.MatchWidthOrHeight) + { + float s1 = (float)screenWidth / dx; + float s2 = (float)screenHeight / dy; + scaleFactor = Mathf.Min(s1, s2); + } + else if (screenMatchMode == ScreenMatchMode.MatchWidth) + scaleFactor = (float)screenWidth / dx; + else + scaleFactor = (float)screenHeight / dy; + } + else if (scaleMode == ScaleMode.ConstantPhysicalSize) + { + float dpi = Screen.dpi; + if (dpi == 0) + dpi = fallbackScreenDPI; + if (dpi == 0) + dpi = 96; + scaleFactor = dpi / (defaultSpriteDPI == 0 ? 96 : defaultSpriteDPI); + } + else + scaleFactor = constantScaleFactor; + + if (scaleFactor > 10) + scaleFactor = 10; + + UpdateScaleLevel(); + + StageCamera.screenSizeVer++; + } + + void UpdateScaleLevel() + { + if (scaleFactor > 3) + scaleLevel = 3; //x4 + else if (scaleFactor > 2) + scaleLevel = 2; //x3 + else if (scaleFactor > 1) + scaleLevel = 1; //x2 + else + scaleLevel = 0; + } + } +} diff --git a/Assets/Scripts/UI/UIContentScaler.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIContentScaler.cs.meta similarity index 100% rename from Assets/Scripts/UI/UIContentScaler.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIContentScaler.cs.meta diff --git a/Assets/Scripts/UI/UIObjectFactory.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIObjectFactory.cs similarity index 96% rename from Assets/Scripts/UI/UIObjectFactory.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIObjectFactory.cs index dba16109..51ff2b19 100644 --- a/Assets/Scripts/UI/UIObjectFactory.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIObjectFactory.cs @@ -1,202 +1,202 @@ -using System; -using System.Collections.Generic; -#if FAIRYGUI_TOLUA -using LuaInterface; -#endif - -namespace FairyGUI -{ - /// - /// - /// - public class UIObjectFactory - { - public delegate GComponent GComponentCreator(); - public delegate GLoader GLoaderCreator(); - - static Dictionary packageItemExtensions = new Dictionary(); - static GLoaderCreator loaderCreator; - - /// - /// - /// - /// - /// - public static void SetPackageItemExtension(string url, System.Type type) - { - SetPackageItemExtension(url, () => { return (GComponent)Activator.CreateInstance(type); }); - } - - /// - /// - /// - /// - /// - public static void SetPackageItemExtension(string url, GComponentCreator creator) - { - if (url == null) - throw new Exception("Invaild url: " + url); - - PackageItem pi = UIPackage.GetItemByURL(url); - if (pi != null) - pi.extensionCreator = creator; - - packageItemExtensions[url] = creator; - } - -#if FAIRYGUI_TOLUA - public static void SetExtension(string url, System.Type baseType, LuaFunction extendFunction) - { - SetPackageItemExtension(url, () => - { - GComponent gcom = (GComponent)Activator.CreateInstance(baseType); - - extendFunction.BeginPCall(); - extendFunction.Push(gcom); - extendFunction.PCall(); - gcom.SetLuaPeer(extendFunction.CheckLuaTable()); - extendFunction.EndPCall(); - - return gcom; - }); - } -#endif - - /// - /// - /// - /// - public static void SetLoaderExtension(System.Type type) - { - loaderCreator = () => { return (GLoader)Activator.CreateInstance(type); }; - } - - /// - /// - /// - /// - public static void SetLoaderExtension(GLoaderCreator creator) - { - loaderCreator = creator; - } - - internal static void ResolvePackageItemExtension(PackageItem pi) - { - if (!packageItemExtensions.TryGetValue(UIPackage.URL_PREFIX + pi.owner.id + pi.id, out pi.extensionCreator) - && !packageItemExtensions.TryGetValue(UIPackage.URL_PREFIX + pi.owner.name + "/" + pi.name, out pi.extensionCreator)) - pi.extensionCreator = null; - } - - public static void Clear() - { - packageItemExtensions.Clear(); - loaderCreator = null; - } - - /// - /// - /// - /// - /// - /// - public static GObject NewObject(PackageItem pi, System.Type userClass = null) - { - GObject obj; - if (pi.type == PackageItemType.Component) - { - if (userClass != null) - { - Stats.LatestObjectCreation++; - obj = (GComponent)Activator.CreateInstance(userClass); - } - else if (pi.extensionCreator != null) - { - Stats.LatestObjectCreation++; - obj = pi.extensionCreator(); - } - else - obj = NewObject(pi.objectType); - } - else - obj = NewObject(pi.objectType); - - if (obj != null) - obj.packageItem = pi; - - return obj; - } - - /// - /// - /// - /// - /// - public static GObject NewObject(ObjectType type) - { - Stats.LatestObjectCreation++; - - switch (type) - { - case ObjectType.Image: - return new GImage(); - - case ObjectType.MovieClip: - return new GMovieClip(); - - case ObjectType.Component: - return new GComponent(); - - case ObjectType.Text: - return new GTextField(); - - case ObjectType.RichText: - return new GRichTextField(); - - case ObjectType.InputText: - return new GTextInput(); - - case ObjectType.Group: - return new GGroup(); - - case ObjectType.List: - return new GList(); - - case ObjectType.Graph: - return new GGraph(); - - case ObjectType.Loader: - if (loaderCreator != null) - return loaderCreator(); - else - return new GLoader(); - - case ObjectType.Button: - return new GButton(); - - case ObjectType.Label: - return new GLabel(); - - case ObjectType.ProgressBar: - return new GProgressBar(); - - case ObjectType.Slider: - return new GSlider(); - - case ObjectType.ScrollBar: - return new GScrollBar(); - - case ObjectType.ComboBox: - return new GComboBox(); - - case ObjectType.Tree: - return new GTree(); - - case ObjectType.Loader3D: - return new GLoader3D(); - - default: - return null; - } - } - } -} +using System; +using System.Collections.Generic; +#if FAIRYGUI_TOLUA +using LuaInterface; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public class UIObjectFactory + { + public delegate GComponent GComponentCreator(); + public delegate GLoader GLoaderCreator(); + + static Dictionary packageItemExtensions = new Dictionary(); + static GLoaderCreator loaderCreator; + + /// + /// + /// + /// + /// + public static void SetPackageItemExtension(string url, System.Type type) + { + SetPackageItemExtension(url, () => { return (GComponent)Activator.CreateInstance(type); }); + } + + /// + /// + /// + /// + /// + public static void SetPackageItemExtension(string url, GComponentCreator creator) + { + if (url == null) + throw new Exception("Invaild url: " + url); + + PackageItem pi = UIPackage.GetItemByURL(url); + if (pi != null) + pi.extensionCreator = creator; + + packageItemExtensions[url] = creator; + } + +#if FAIRYGUI_TOLUA + public static void SetExtension(string url, System.Type baseType, LuaFunction extendFunction) + { + SetPackageItemExtension(url, () => + { + GComponent gcom = (GComponent)Activator.CreateInstance(baseType); + + extendFunction.BeginPCall(); + extendFunction.Push(gcom); + extendFunction.PCall(); + gcom.SetLuaPeer(extendFunction.CheckLuaTable()); + extendFunction.EndPCall(); + + return gcom; + }); + } +#endif + + /// + /// + /// + /// + public static void SetLoaderExtension(System.Type type) + { + loaderCreator = () => { return (GLoader)Activator.CreateInstance(type); }; + } + + /// + /// + /// + /// + public static void SetLoaderExtension(GLoaderCreator creator) + { + loaderCreator = creator; + } + + internal static void ResolvePackageItemExtension(PackageItem pi) + { + if (!packageItemExtensions.TryGetValue(UIPackage.URL_PREFIX + pi.owner.id + pi.id, out pi.extensionCreator) + && !packageItemExtensions.TryGetValue(UIPackage.URL_PREFIX + pi.owner.name + "/" + pi.name, out pi.extensionCreator)) + pi.extensionCreator = null; + } + + public static void Clear() + { + packageItemExtensions.Clear(); + loaderCreator = null; + } + + /// + /// + /// + /// + /// + /// + public static GObject NewObject(PackageItem pi, System.Type userClass = null) + { + GObject obj; + if (pi.type == PackageItemType.Component) + { + if (userClass != null) + { + Stats.LatestObjectCreation++; + obj = (GComponent)Activator.CreateInstance(userClass); + } + else if (pi.extensionCreator != null) + { + Stats.LatestObjectCreation++; + obj = pi.extensionCreator(); + } + else + obj = NewObject(pi.objectType); + } + else + obj = NewObject(pi.objectType); + + if (obj != null) + obj.packageItem = pi; + + return obj; + } + + /// + /// + /// + /// + /// + public static GObject NewObject(ObjectType type) + { + Stats.LatestObjectCreation++; + + switch (type) + { + case ObjectType.Image: + return new GImage(); + + case ObjectType.MovieClip: + return new GMovieClip(); + + case ObjectType.Component: + return new GComponent(); + + case ObjectType.Text: + return new GTextField(); + + case ObjectType.RichText: + return new GRichTextField(); + + case ObjectType.InputText: + return new GTextInput(); + + case ObjectType.Group: + return new GGroup(); + + case ObjectType.List: + return new GList(); + + case ObjectType.Graph: + return new GGraph(); + + case ObjectType.Loader: + if (loaderCreator != null) + return loaderCreator(); + else + return new GLoader(); + + case ObjectType.Button: + return new GButton(); + + case ObjectType.Label: + return new GLabel(); + + case ObjectType.ProgressBar: + return new GProgressBar(); + + case ObjectType.Slider: + return new GSlider(); + + case ObjectType.ScrollBar: + return new GScrollBar(); + + case ObjectType.ComboBox: + return new GComboBox(); + + case ObjectType.Tree: + return new GTree(); + + case ObjectType.Loader3D: + return new GLoader3D(); + + default: + return null; + } + } + } +} diff --git a/Assets/Scripts/UI/UIObjectFactory.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIObjectFactory.cs.meta similarity index 100% rename from Assets/Scripts/UI/UIObjectFactory.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIObjectFactory.cs.meta diff --git a/Assets/Scripts/UI/UIPackage.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPackage.cs similarity index 97% rename from Assets/Scripts/UI/UIPackage.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPackage.cs index 42918cef..2e5d5e2d 100644 --- a/Assets/Scripts/UI/UIPackage.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPackage.cs @@ -1,1666 +1,1666 @@ -using System; -using System.Collections.Generic; -using System.IO; -using UnityEngine; -using FairyGUI.Utils; -#if UNITY_EDITOR -using UnityEditor; -#endif - -namespace FairyGUI -{ - /// - /// A UI Package contains a description file and some texture, sound assets. - /// - public class UIPackage - { - /// - /// Unload UIAssetBundle by FairyGUI system. - /// if use AssetBundlesManager set value to false - /// then unload UIAssetBundle by AssetBundlesManager - /// - public static bool unloadBundleByFGUI = true; - - /// - /// The event is triggered when all reference to this package item dropped. - /// - public static event Action onReleaseResource; - - /// - /// Package id. It is generated by the Editor. - /// - public string id { get; private set; } - - /// - /// Package name. - /// - public string name { get; private set; } - - /// - /// Use this callback to provide resources to the package. - /// - /// Resource name without extension. - /// Resource extension. e.g. '.png' '.wav' - /// Resource type. e.g. 'Texture' 'AudioClip' - /// How to destroy this resource. - /// - public delegate object LoadResource(string name, string extension, System.Type type, out DestroyMethod destroyMethod); - - /// - /// A async load resource callback. After loaded, you should call item.owner.SetItemAsset. - /// - /// Resource name without extension. - /// Resource extension. e.g. '.png' '.wav' - /// Resource type. e.g. 'Texture' 'AudioClip' - /// Resource item object. - /// - public delegate void LoadResourceAsync(string name, string extension, System.Type type, PackageItem item); - - /// - /// - /// - /// - public delegate void CreateObjectCallback(GObject result); - - List _items; - Dictionary _itemsById; - Dictionary _itemsByName; - Dictionary[] _dependencies; - string _assetPath; - string[] _branches; - internal int _branchIndex; - AssetBundle _resBundle; - string _customId; - bool _fromBundle; - LoadResource _loadFunc; - LoadResourceAsync _loadAsyncFunc; - - class AtlasSprite - { - public PackageItem atlas; - public Rect rect = new Rect(); - public Vector2 offset = new Vector2(); - public Vector2 originalSize = new Vector2(); - public bool rotated; - } - Dictionary _sprites; - - static Dictionary _packageInstById = new Dictionary(); - static Dictionary _packageInstByName = new Dictionary(); - static List _packageList = new List(); - static string _branch; - static Dictionary _vars = new Dictionary(); - - internal static int _constructing; - - public const string URL_PREFIX = "ui://"; - -#if UNITY_EDITOR - static LoadResource _loadFromAssetsPath = (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => - { - destroyMethod = DestroyMethod.Unload; - return AssetDatabase.LoadAssetAtPath(name + extension, type); - }; -#endif - - static LoadResource _loadFromResourcesPath = (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => - { - destroyMethod = DestroyMethod.Unload; - return Resources.Load(name, type); - }; - - public UIPackage() - { - _items = new List(); - _itemsById = new Dictionary(); - _itemsByName = new Dictionary(); - _sprites = new Dictionary(); - - _branchIndex = -1; - } - - /// - /// - /// - public static string branch - { - get { return _branch; } - set - { - _branch = value; - bool empty = string.IsNullOrEmpty(_branch); - var iter = _packageInstById.GetEnumerator(); - while (iter.MoveNext()) - { - UIPackage pkg = iter.Current.Value; - if (empty) - pkg._branchIndex = -1; - else if (pkg._branches != null) - pkg._branchIndex = Array.IndexOf(pkg._branches, value); - } - iter.Dispose(); - } - } - - /// - /// - /// - public static string GetVar(string key) - { - string value; - if (_vars.TryGetValue(key, out value)) - return value; - else - return null; - } - - /// - /// - /// - public static void SetVar(string key, string value) - { - if (value == null) - _vars.Remove(key); - else - _vars[key] = value; - } - - /// - /// Return a UIPackage with a certain id. - /// - /// ID of the package. - /// UIPackage - public static UIPackage GetById(string id) - { - UIPackage pkg; - if (_packageInstById.TryGetValue(id, out pkg)) - return pkg; - else - return null; - } - - /// - /// Return a UIPackage with a certain name. - /// - /// Name of the package. - /// UIPackage - public static UIPackage GetByName(string name) - { - UIPackage pkg; - if (_packageInstByName.TryGetValue(name, out pkg)) - return pkg; - else - return null; - } - - /// - /// Add a UI package from assetbundle. - /// - /// A assetbundle. - /// UIPackage - public static UIPackage AddPackage(AssetBundle bundle) - { - return AddPackage(bundle, bundle, null); - } - - /// - /// Add a UI package from two assetbundles. desc and res can be same. - /// - /// A assetbunble contains description file. - /// A assetbundle contains resources. - /// UIPackage - public static UIPackage AddPackage(AssetBundle desc, AssetBundle res) - { - return AddPackage(desc, res, null); - } - - /// - /// Add a UI package from two assetbundles with a optional main asset name. - /// - /// A assetbunble contains description file. - /// A assetbundle contains resources. - /// Main asset name. e.g. Basics_fui - /// UIPackage - public static UIPackage AddPackage(AssetBundle desc, AssetBundle res, string mainAssetName) - { - byte[] source = null; - if (!string.IsNullOrEmpty(mainAssetName)) - { - TextAsset ta = desc.LoadAsset(mainAssetName); - if (ta != null) - source = ta.bytes; - } - else - { - string[] names = desc.GetAllAssetNames(); - string searchPattern = "_fui"; - foreach (string n in names) - { - if (n.IndexOf(searchPattern) != -1) - { - TextAsset ta = desc.LoadAsset(n); - if (ta != null) - { - source = ta.bytes; - mainAssetName = Path.GetFileNameWithoutExtension(n); - break; - } - } - } - } - - if (source == null) - throw new Exception("FairyGUI: no package found in this bundle."); - - if (unloadBundleByFGUI && desc != res) - desc.Unload(true); - - ByteBuffer buffer = new ByteBuffer(source); - - UIPackage pkg = new UIPackage(); - pkg._resBundle = res; - pkg._fromBundle = true; - int pos = mainAssetName.IndexOf("_fui"); - if (pos != -1) - mainAssetName = mainAssetName.Substring(0, pos); - if (!pkg.LoadPackage(buffer, mainAssetName)) - return null; - - _packageInstById[pkg.id] = pkg; - _packageInstByName[pkg.name] = pkg; - _packageList.Add(pkg); - - return pkg; - } - - /// - /// Add a UI package from a path relative to Unity Resources path. - /// - /// Path relative to Unity Resources path. - /// UIPackage - public static UIPackage AddPackage(string descFilePath) - { - if (descFilePath.StartsWith("Assets/")) - { -#if UNITY_EDITOR - return AddPackage(descFilePath, _loadFromAssetsPath); -#else - - Debug.LogWarning("FairyGUI: failed to load package in '" + descFilePath + "'"); - return null; -#endif - } - else - return AddPackage(descFilePath, _loadFromResourcesPath); - } - - /// - /// 使用自定义的加载方式载入一个包。 - /// - /// 包资源路径。 - /// 载入函数 - /// - public static UIPackage AddPackage(string assetPath, LoadResource loadFunc) - { - if (_packageInstById.ContainsKey(assetPath)) - return _packageInstById[assetPath]; - - DestroyMethod dm; - TextAsset asset = (TextAsset)loadFunc(assetPath + "_fui", ".bytes", typeof(TextAsset), out dm); - if (asset == null) - { - if (Application.isPlaying) - throw new Exception("FairyGUI: Cannot load ui package in '" + assetPath + "'"); - else - Debug.LogWarning("FairyGUI: Cannot load ui package in '" + assetPath + "'"); - } - - ByteBuffer buffer = new ByteBuffer(asset.bytes); - - UIPackage pkg = new UIPackage(); - pkg._loadFunc = loadFunc; - pkg._assetPath = assetPath; - if (!pkg.LoadPackage(buffer, assetPath)) - return null; - - _packageInstById[pkg.id] = pkg; - _packageInstByName[pkg.name] = pkg; - _packageInstById[assetPath] = pkg; - _packageList.Add(pkg); - return pkg; - } - - /// - /// Load Package by custom load method. - /// - /// Description file data - /// Prefix of the resource file name. The file name would be in format of 'assetNamePrefix_resFileName'. It can be empty. - /// Load method - /// - public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResource loadFunc) - { - ByteBuffer buffer = new ByteBuffer(descData); - - UIPackage pkg = new UIPackage(); - pkg._loadFunc = loadFunc; - if (!pkg.LoadPackage(buffer, assetNamePrefix)) - return null; - - _packageInstById[pkg.id] = pkg; - _packageInstByName[pkg.name] = pkg; - _packageList.Add(pkg); - - return pkg; - } - - /// - /// Load Package async by custom load method. - /// - /// Description file data - /// refix of the resource file name. The file name would be in format of 'assetNamePrefix_resFileName'. It can be empty. - /// Load method - /// - public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResourceAsync loadFunc) - { - ByteBuffer buffer = new ByteBuffer(descData); - - UIPackage pkg = new UIPackage(); - pkg._loadAsyncFunc = loadFunc; - if (!pkg.LoadPackage(buffer, assetNamePrefix)) - return null; - - _packageInstById[pkg.id] = pkg; - _packageInstByName[pkg.name] = pkg; - _packageList.Add(pkg); - - return pkg; - } - - /// - /// Remove a package. All resources in this package will be disposed. - /// - /// - public static void RemovePackage(string packageIdOrName) - { - UIPackage pkg = null; - if (!_packageInstById.TryGetValue(packageIdOrName, out pkg)) - { - if (!_packageInstByName.TryGetValue(packageIdOrName, out pkg)) - throw new Exception("FairyGUI: '" + packageIdOrName + "' is not a valid package id or name."); - } - pkg.Dispose(); - _packageInstById.Remove(pkg.id); - if (pkg._customId != null) - _packageInstById.Remove(pkg._customId); - if (pkg._assetPath != null) - _packageInstById.Remove(pkg._assetPath); - _packageInstByName.Remove(pkg.name); - _packageList.Remove(pkg); - } - - /// - /// - /// - public static void RemoveAllPackages() - { - if (_packageInstById.Count > 0) - { - UIPackage[] pkgs = _packageList.ToArray(); - - foreach (UIPackage pkg in pkgs) - { - pkg.Dispose(); - } - } - _packageList.Clear(); - _packageInstById.Clear(); - _packageInstByName.Clear(); - } - - /// - /// - /// - /// - public static List GetPackages() - { - return _packageList; - } - - /// - /// Create a UI object. - /// - /// Package name. - /// Resource name. - /// A UI object. - public static GObject CreateObject(string pkgName, string resName) - { - UIPackage pkg = GetByName(pkgName); - if (pkg != null) - return pkg.CreateObject(resName); - else - return null; - } - - /// - /// Create a UI object. - /// - /// Package name. - /// Resource name. - /// Custom implementation of this object. - /// A UI object. - public static GObject CreateObject(string pkgName, string resName, System.Type userClass) - { - UIPackage pkg = GetByName(pkgName); - if (pkg != null) - return pkg.CreateObject(resName, userClass); - else - return null; - } - - /// - /// Create a UI object. - /// - /// Resource url. - /// A UI object. - public static GObject CreateObjectFromURL(string url) - { - PackageItem pi = GetItemByURL(url); - if (pi != null) - return pi.owner.CreateObject(pi, null); - else - return null; - } - - /// - /// Create a UI object. - /// - /// Resource url. - /// Custom implementation of this object. - /// A UI object. - public static GObject CreateObjectFromURL(string url, System.Type userClass) - { - PackageItem pi = GetItemByURL(url); - if (pi != null) - return pi.owner.CreateObject(pi, userClass); - else - return null; - } - - public static void CreateObjectAsync(string pkgName, string resName, CreateObjectCallback callback) - { - UIPackage pkg = GetByName(pkgName); - if (pkg != null) - pkg.CreateObjectAsync(resName, callback); - else - Debug.LogError("FairyGUI: package not found - " + pkgName); - } - - public static void CreateObjectFromURL(string url, CreateObjectCallback callback) - { - PackageItem pi = GetItemByURL(url); - if (pi != null) - AsyncCreationHelper.CreateObject(pi, callback); - else - Debug.LogError("FairyGUI: resource not found - " + url); - } - - /// - /// Get a asset with a certain name. - /// - /// Package name. - /// Resource name. - /// If resource is atlas, returns NTexture; If resource is sound, returns AudioClip. - public static object GetItemAsset(string pkgName, string resName) - { - UIPackage pkg = GetByName(pkgName); - if (pkg != null) - return pkg.GetItemAsset(resName); - else - return null; - } - - /// - /// Get a asset with a certain name. - /// - /// Resource url. - /// If resource is atlas, returns NTexture; If resource is sound, returns AudioClip. - public static object GetItemAssetByURL(string url) - { - PackageItem item = GetItemByURL(url); - if (item == null) - return null; - - return item.owner.GetItemAsset(item); - } - - /// - /// Get url of an item in package. - /// - /// Package name. - /// Resource name. - /// Url. - public static string GetItemURL(string pkgName, string resName) - { - UIPackage pkg = GetByName(pkgName); - if (pkg == null) - return null; - - PackageItem pi; - if (!pkg._itemsByName.TryGetValue(resName, out pi)) - return null; - - return URL_PREFIX + pkg.id + pi.id; - } - - public static PackageItem GetItemByURL(string url) - { - if (url == null) - return null; - - int pos1 = url.IndexOf("//"); - if (pos1 == -1) - return null; - - int pos2 = url.IndexOf('/', pos1 + 2); - if (pos2 == -1) - { - if (url.Length > 13) - { - string pkgId = url.Substring(5, 8); - UIPackage pkg = GetById(pkgId); - if (pkg != null) - { - string srcId = url.Substring(13); - return pkg.GetItem(srcId); - } - } - } - else - { - string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2); - UIPackage pkg = GetByName(pkgName); - if (pkg != null) - { - string srcName = url.Substring(pos2 + 1); - return pkg.GetItemByName(srcName); - } - } - - return null; - } - - /// - /// 将'ui://包名/组件名'转换为以内部id表达的url格式。如果传入的url本身就是内部id格式,则直接返回。 - /// 同时这个方法还带格式检测,如果传入不正确的url,会返回null。 - /// - /// - /// - public static string NormalizeURL(string url) - { - if (url == null) - return null; - - int pos1 = url.IndexOf("//"); - if (pos1 == -1) - return null; - - int pos2 = url.IndexOf('/', pos1 + 2); - if (pos2 == -1) - return url; - else - { - string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2); - string srcName = url.Substring(pos2 + 1); - return GetItemURL(pkgName, srcName); - } - } - - /// - /// Set strings source. - /// - /// - public static void SetStringsSource(XML source) - { - TranslationHelper.LoadFromXML(source); - } - - /// - /// - /// - public string assetPath - { - get { return _assetPath; } - } - - /// - /// Set a custom id for package, then you can use it in GetById. - /// - public string customId - { - get { return _customId; } - set - { - if (_customId != null) - _packageInstById.Remove(_customId); - _customId = value; - if (_customId != null) - _packageInstById[_customId] = this; - } - } - - /// - /// - /// - public AssetBundle resBundle - { - get { return _resBundle; } - } - - /// - /// 获得本包依赖的包的id列表 - /// - public Dictionary[] dependencies - { - get { return _dependencies; } - } - - bool LoadPackage(ByteBuffer buffer, string assetNamePrefix) - { - if (buffer.ReadUint() != 0x46475549) - { - if (Application.isPlaying) - throw new Exception("FairyGUI: old package format found in '" + assetNamePrefix + "'"); - else - { - Debug.LogWarning("FairyGUI: old package format found in '" + assetNamePrefix + "'"); - return false; - } - } - - buffer.version = buffer.ReadInt(); - bool ver2 = buffer.version >= 2; - buffer.ReadBool(); //compressed - id = buffer.ReadString(); - name = buffer.ReadString(); - - UIPackage existingPkg; - if (_packageInstById.TryGetValue(id, out existingPkg)) - { - if (name != existingPkg.name) - Debug.LogWarning("FairyGUI: Package conflicts, '" + name + "' and '" + existingPkg.name + "'"); - -#if UNITY_EDITOR - //maybe multiple pkgs in different folder, pefer the one in resources - if (Application.isEditor) - { - if (existingPkg._loadFunc == _loadFromAssetsPath) //old one is outside resources path - existingPkg.Dispose(); //replace the existing - else if (existingPkg._loadFunc == _loadFromResourcesPath && _loadFunc == _loadFromResourcesPath - && _assetPath.Length < existingPkg._assetPath.Length) //both in resources path, pefer short path - existingPkg.Dispose(); //replace the existing - else //keep the existing - return false; - } -#endif - } - - buffer.Skip(20); - int indexTablePos = buffer.position; - int cnt; - - buffer.Seek(indexTablePos, 4); - - cnt = buffer.ReadInt(); - string[] stringTable = new string[cnt]; - for (int i = 0; i < cnt; i++) - stringTable[i] = buffer.ReadString(); - buffer.stringTable = stringTable; - - if (buffer.Seek(indexTablePos, 5)) - { - cnt = buffer.ReadInt(); - for (int i = 0; i < cnt; i++) - { - int index = buffer.ReadUshort(); - int len = buffer.ReadInt(); - stringTable[index] = buffer.ReadString(len); - } - } - - buffer.Seek(indexTablePos, 0); - - cnt = buffer.ReadShort(); - _dependencies = new Dictionary[cnt]; - for (int i = 0; i < cnt; i++) - { - Dictionary kv = new Dictionary(); - kv.Add("id", buffer.ReadS()); - kv.Add("name", buffer.ReadS()); - _dependencies[i] = kv; - } - - bool branchIncluded = false; - if (ver2) - { - cnt = buffer.ReadShort(); - if (cnt > 0) - { - _branches = buffer.ReadSArray(cnt); - if (!string.IsNullOrEmpty(_branch)) - _branchIndex = Array.IndexOf(_branches, _branch); - } - - branchIncluded = cnt > 0; - } - - buffer.Seek(indexTablePos, 1); - - PackageItem pi; - string assetPath; - if (assetNamePrefix.Length > 0) - { - assetPath = Path.GetDirectoryName(assetNamePrefix); - if (assetPath.Length > 0) - assetPath += "/"; - assetNamePrefix = assetNamePrefix + "_"; - } - else - assetPath = string.Empty; - - cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - int nextPos = buffer.ReadInt(); - nextPos += buffer.position; - - pi = new PackageItem(); - pi.owner = this; - pi.type = (PackageItemType)buffer.ReadByte(); - pi.id = buffer.ReadS(); - pi.name = buffer.ReadS(); - buffer.ReadS(); //path - pi.file = buffer.ReadS(); - pi.exported = buffer.ReadBool(); - pi.width = buffer.ReadInt(); - pi.height = buffer.ReadInt(); - - switch (pi.type) - { - case PackageItemType.Image: - { - pi.objectType = ObjectType.Image; - int scaleOption = buffer.ReadByte(); - if (scaleOption == 1) - { - Rect rect = new Rect(); - rect.x = buffer.ReadInt(); - rect.y = buffer.ReadInt(); - rect.width = buffer.ReadInt(); - rect.height = buffer.ReadInt(); - pi.scale9Grid = rect; - - pi.tileGridIndice = buffer.ReadInt(); - } - else if (scaleOption == 2) - pi.scaleByTile = true; - - buffer.ReadBool(); //smoothing - break; - } - - case PackageItemType.MovieClip: - { - buffer.ReadBool(); //smoothing - pi.objectType = ObjectType.MovieClip; - pi.rawData = buffer.ReadBuffer(); - break; - } - - case PackageItemType.Font: - { - pi.rawData = buffer.ReadBuffer(); - break; - } - - case PackageItemType.Component: - { - int extension = buffer.ReadByte(); - if (extension > 0) - pi.objectType = (ObjectType)extension; - else - pi.objectType = ObjectType.Component; - pi.rawData = buffer.ReadBuffer(); - - UIObjectFactory.ResolvePackageItemExtension(pi); - break; - } - - case PackageItemType.Atlas: - case PackageItemType.Sound: - case PackageItemType.Misc: - { - pi.file = assetNamePrefix + pi.file; - break; - } - - case PackageItemType.Spine: - case PackageItemType.DragoneBones: - { - pi.file = assetPath + pi.file; - pi.skeletonAnchor.x = buffer.ReadFloat(); - pi.skeletonAnchor.y = buffer.ReadFloat(); - break; - } - } - - if (ver2) - { - string str = buffer.ReadS();//branch - if (str != null) - pi.name = str + "/" + pi.name; - - int branchCnt = buffer.ReadByte(); - if (branchCnt > 0) - { - if (branchIncluded) - pi.branches = buffer.ReadSArray(branchCnt); - else - _itemsById[buffer.ReadS()] = pi; - } - - int highResCnt = buffer.ReadByte(); - if (highResCnt > 0) - pi.highResolution = buffer.ReadSArray(highResCnt); - } - - _items.Add(pi); - _itemsById[pi.id] = pi; - if (pi.name != null) - _itemsByName[pi.name] = pi; - - buffer.position = nextPos; - } - - buffer.Seek(indexTablePos, 2); - - cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - string itemId = buffer.ReadS(); - pi = _itemsById[buffer.ReadS()]; - - AtlasSprite sprite = new AtlasSprite(); - sprite.atlas = pi; - sprite.rect.x = buffer.ReadInt(); - sprite.rect.y = buffer.ReadInt(); - sprite.rect.width = buffer.ReadInt(); - sprite.rect.height = buffer.ReadInt(); - sprite.rotated = buffer.ReadBool(); - if (ver2 && buffer.ReadBool()) - { - sprite.offset.x = buffer.ReadInt(); - sprite.offset.y = buffer.ReadInt(); - sprite.originalSize.x = buffer.ReadInt(); - sprite.originalSize.y = buffer.ReadInt(); - } - else if (sprite.rotated) - { - sprite.originalSize.x = sprite.rect.height; - sprite.originalSize.y = sprite.rect.width; - } - else - { - sprite.originalSize.x = sprite.rect.width; - sprite.originalSize.y = sprite.rect.height; - } - - _sprites[itemId] = sprite; - - buffer.position = nextPos; - } - - if (buffer.Seek(indexTablePos, 3)) - { - cnt = buffer.ReadShort(); - for (int i = 0; i < cnt; i++) - { - int nextPos = buffer.ReadInt(); - nextPos += buffer.position; - - if (_itemsById.TryGetValue(buffer.ReadS(), out pi)) - { - if (pi.type == PackageItemType.Image) - { - pi.pixelHitTestData = new PixelHitTestData(); - pi.pixelHitTestData.Load(buffer); - } - } - - buffer.position = nextPos; - } - } - - if (!Application.isPlaying) - _items.Sort(ComparePackageItem); - - return true; - } - - static int ComparePackageItem(PackageItem p1, PackageItem p2) - { - if (p1.name != null && p2.name != null) - return p1.name.CompareTo(p2.name); - else - return 0; - } - - /// - /// - /// - public void LoadAllAssets() - { - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - GetItemAsset(_items[i]); - } - - /// - /// - /// - public void UnloadAssets() - { - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - PackageItem pi = _items[i]; - if (pi.type == PackageItemType.Atlas) - { - if (pi.texture != null) - pi.texture.Unload(); - } - else if (pi.type == PackageItemType.Sound) - { - if (pi.audioClip != null) - pi.audioClip.Unload(); - } - } - - if (unloadBundleByFGUI && - _resBundle != null) - { - _resBundle.Unload(true); - _resBundle = null; - } - } - - /// - /// - /// - public void ReloadAssets() - { - if (_fromBundle) - throw new Exception("FairyGUI: new bundle must be passed to this function"); - - ReloadAssets(null); - } - - /// - /// - /// - public void ReloadAssets(AssetBundle resBundle) - { - _resBundle = resBundle; - _fromBundle = _resBundle != null; - - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - PackageItem pi = _items[i]; - if (pi.type == PackageItemType.Atlas) - { - if (pi.texture != null && pi.texture.nativeTexture == null) - LoadAtlas(pi); - } - else if (pi.type == PackageItemType.Sound) - { - if (pi.audioClip != null && pi.audioClip.nativeClip == null) - LoadSound(pi); - } - } - } - - void Dispose() - { - int cnt = _items.Count; - for (int i = 0; i < cnt; i++) - { - PackageItem pi = _items[i]; - if (pi.type == PackageItemType.Atlas) - { - if (pi.texture != null) - { - pi.texture.Dispose(); - pi.texture = null; - } - } - else if (pi.type == PackageItemType.Sound) - { - if (pi.audioClip != null) - { - pi.audioClip.Unload(); - pi.audioClip = null; - } - } - } - _items.Clear(); - - if (unloadBundleByFGUI && - _resBundle != null) - { - _resBundle.Unload(true); - _resBundle = null; - } - } - - /// - /// - /// - /// - /// - public GObject CreateObject(string resName) - { - PackageItem pi; - if (!_itemsByName.TryGetValue(resName, out pi)) - { - Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); - return null; - } - - return CreateObject(pi, null); - } - - /// - /// - /// - /// - /// - /// - public GObject CreateObject(string resName, System.Type userClass) - { - PackageItem pi; - if (!_itemsByName.TryGetValue(resName, out pi)) - { - Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); - return null; - } - - return CreateObject(pi, userClass); - } - - public void CreateObjectAsync(string resName, CreateObjectCallback callback) - { - PackageItem pi; - if (!_itemsByName.TryGetValue(resName, out pi)) - { - Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); - return; - } - - AsyncCreationHelper.CreateObject(pi, callback); - } - - GObject CreateObject(PackageItem item, System.Type userClass) - { - Stats.LatestObjectCreation = 0; - Stats.LatestGraphicsCreation = 0; - - GetItemAsset(item); - - GObject g = UIObjectFactory.NewObject(item, userClass); - if (g == null) - return null; - - _constructing++; - g.ConstructFromResource(); - _constructing--; - - return g; - } - - - /// - /// - /// - /// - /// - public object GetItemAsset(string resName) - { - PackageItem pi; - if (!_itemsByName.TryGetValue(resName, out pi)) - { - Debug.LogError("FairyGUI: Resource not found - " + resName + " in " + this.name); - return null; - } - - return GetItemAsset(pi); - } - - public List GetItems() - { - return _items; - } - - public PackageItem GetItem(string itemId) - { - PackageItem pi; - if (_itemsById.TryGetValue(itemId, out pi)) - return pi; - else - return null; - } - - public PackageItem GetItemByName(string itemName) - { - PackageItem pi; - if (_itemsByName.TryGetValue(itemName, out pi)) - return pi; - else - return null; - } - - public object GetItemAsset(PackageItem item) - { - switch (item.type) - { - case PackageItemType.Image: - if (item.texture == null) - LoadImage(item); - return item.texture; - - case PackageItemType.Atlas: - if (item.texture == null) - LoadAtlas(item); - return item.texture; - - case PackageItemType.Sound: - if (item.audioClip == null) - LoadSound(item); - return item.audioClip; - - case PackageItemType.Font: - if (item.bitmapFont == null) - LoadFont(item); - - return item.bitmapFont; - - case PackageItemType.MovieClip: - if (item.frames == null) - LoadMovieClip(item); - - return item.frames; - - case PackageItemType.Component: - return item.rawData; - - case PackageItemType.Misc: - return LoadBinary(item); - - case PackageItemType.Spine: - if (item.skeletonAsset == null) - LoadSpine(item); - return item.skeletonAsset; - - case PackageItemType.DragoneBones: - if (item.skeletonAsset == null) - LoadDragonBones(item); - return item.skeletonAsset; - - default: - return null; - } - } - - /// - /// - /// - /// - /// - /// - public void SetItemAsset(PackageItem item, object asset, DestroyMethod destroyMethod) - { - switch (item.type) - { - case PackageItemType.Atlas: - if (item.texture == null) - item.texture = new NTexture(null, new Rect(0, 0, item.width, item.height)); - item.texture.Reload((Texture)asset, null); - item.texture.destroyMethod = destroyMethod; - break; - - case PackageItemType.Sound: - if (item.audioClip == null) - item.audioClip = new NAudioClip(null); - item.audioClip.Reload((AudioClip)asset); - item.audioClip.destroyMethod = destroyMethod; - break; - - case PackageItemType.Spine: -#if FAIRYGUI_SPINE - item.skeletonAsset = (Spine.Unity.SkeletonDataAsset)asset; -#endif - break; - - case PackageItemType.DragoneBones: -#if FAIRYGUI_DRAGONBONES - item.skeletonAsset = (DragonBones.UnityDragonBonesData)asset; -#endif - break; - } - } - - void LoadAtlas(PackageItem item) - { - string ext = Path.GetExtension(item.file); - string fileName = item.file.Substring(0, item.file.Length - ext.Length); - - if (_loadAsyncFunc != null) - { - _loadAsyncFunc(fileName, ext, typeof(Texture), item); - if (item.texture == null) - item.texture = new NTexture(null, new Rect(0, 0, item.width, item.height)); - item.texture.destroyMethod = DestroyMethod.None; - } - else - { - Texture tex = null; - Texture alphaTex = null; - DestroyMethod dm; - - if (_fromBundle) - { - if (_resBundle != null) - tex = _resBundle.LoadAsset(fileName); - else - Debug.LogWarning("FairyGUI: bundle already unloaded."); - - dm = DestroyMethod.None; - } - else - tex = (Texture)_loadFunc(fileName, ext, typeof(Texture), out dm); - - if (tex == null) - Debug.LogWarning("FairyGUI: texture '" + item.file + "' not found in " + this.name); - - else if (!(tex is Texture2D)) - { - Debug.LogWarning("FairyGUI: settings for '" + item.file + "' is wrong! Correct values are: (Texture Type=Default, Texture Shape=2D)"); - tex = null; - } - else - { - if (((Texture2D)tex).mipmapCount > 1) - Debug.LogWarning("FairyGUI: settings for '" + item.file + "' is wrong! Correct values are: (Generate Mip Maps=unchecked)"); - } - - if (tex != null) - { - fileName = fileName + "!a"; - if (_fromBundle) - { - if (_resBundle != null) - alphaTex = _resBundle.LoadAsset(fileName); - } - else - alphaTex = (Texture2D)_loadFunc(fileName, ext, typeof(Texture2D), out dm); - } - - if (tex == null) - { - tex = NTexture.CreateEmptyTexture(); - dm = DestroyMethod.Destroy; - } - - if (item.texture == null) - { - item.texture = new NTexture(tex, alphaTex, (float)tex.width / item.width, (float)tex.height / item.height); - item.texture.onRelease += (NTexture t) => - { - if (onReleaseResource != null) - onReleaseResource(item); - }; - } - else - item.texture.Reload(tex, alphaTex); - item.texture.destroyMethod = dm; - } - } - - void LoadImage(PackageItem item) - { - AtlasSprite sprite; - if (_sprites.TryGetValue(item.id, out sprite)) - { - NTexture atlas = (NTexture)GetItemAsset(sprite.atlas); - if (atlas.width == sprite.rect.width && atlas.height == sprite.rect.height) - item.texture = atlas; - else - item.texture = new NTexture(atlas, sprite.rect, sprite.rotated, sprite.originalSize, sprite.offset); - } - else - item.texture = NTexture.Empty; - } - - void LoadSound(PackageItem item) - { - string ext = Path.GetExtension(item.file); - string fileName = item.file.Substring(0, item.file.Length - ext.Length); - - if (_loadAsyncFunc != null) - { - _loadAsyncFunc(fileName, ext, typeof(AudioClip), item); - if (item.audioClip == null) - item.audioClip = new NAudioClip(null); - item.audioClip.destroyMethod = DestroyMethod.None; - } - else - { - AudioClip audioClip = null; - DestroyMethod dm; - - if (_fromBundle) - { - if (_resBundle != null) - audioClip = _resBundle.LoadAsset(fileName); - dm = DestroyMethod.None; - } - else - { - audioClip = (AudioClip)_loadFunc(fileName, ext, typeof(AudioClip), out dm); - } - - if (item.audioClip == null) - item.audioClip = new NAudioClip(audioClip); - else - item.audioClip.Reload(audioClip); - item.audioClip.destroyMethod = dm; - } - } - - byte[] LoadBinary(PackageItem item) - { - string ext = Path.GetExtension(item.file); - string fileName = item.file.Substring(0, item.file.Length - ext.Length); - - TextAsset ta; - if (_resBundle != null) - { - ta = _resBundle.LoadAsset(fileName); - if (ta != null) - return ta.bytes; - else - return null; - } - else - { - DestroyMethod dm; - object ret = _loadFunc(fileName, ext, typeof(TextAsset), out dm); - if (ret == null) - return null; - if (ret is byte[]) - return (byte[])ret; - else - return ((TextAsset)ret).bytes; - } - } - - void LoadMovieClip(PackageItem item) - { - ByteBuffer buffer = item.rawData; - - buffer.Seek(0, 0); - - item.interval = buffer.ReadInt() / 1000f; - item.swing = buffer.ReadBool(); - item.repeatDelay = buffer.ReadInt() / 1000f; - - buffer.Seek(0, 1); - - int frameCount = buffer.ReadShort(); - item.frames = new MovieClip.Frame[frameCount]; - - string spriteId; - MovieClip.Frame frame; - AtlasSprite sprite; - Rect frameRect = new Rect(); - - for (int i = 0; i < frameCount; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - frame = new MovieClip.Frame(); - frameRect.x = buffer.ReadInt(); - frameRect.y = buffer.ReadInt(); - frameRect.width = buffer.ReadInt(); - frameRect.height = buffer.ReadInt(); - frame.addDelay = buffer.ReadInt() / 1000f; - spriteId = buffer.ReadS(); - - if (spriteId != null && _sprites.TryGetValue(spriteId, out sprite)) - { - frame.texture = new NTexture((NTexture)GetItemAsset(sprite.atlas), sprite.rect, sprite.rotated, - new Vector2(item.width, item.height), frameRect.position); - } - item.frames[i] = frame; - - buffer.position = nextPos; - } - } - - void LoadFont(PackageItem item) - { - BitmapFont font = new BitmapFont(); - font.name = URL_PREFIX + this.id + item.id; - item.bitmapFont = font; - ByteBuffer buffer = item.rawData; - - buffer.Seek(0, 0); - - bool ttf = buffer.ReadBool(); - font.canTint = buffer.ReadBool(); - font.resizable = buffer.ReadBool(); - font.hasChannel = buffer.ReadBool(); - int fontSize = buffer.ReadInt(); - int xadvance = buffer.ReadInt(); - int lineHeight = buffer.ReadInt(); - - float texScaleX = 1; - float texScaleY = 1; - int bgX; - int bgY; - int bgWidth; - int bgHeight; - - NTexture mainTexture = null; - AtlasSprite mainSprite = null; - if (ttf && _sprites.TryGetValue(item.id, out mainSprite)) - { - mainTexture = (NTexture)GetItemAsset(mainSprite.atlas); - texScaleX = mainTexture.root.uvRect.width / mainTexture.width; - texScaleY = mainTexture.root.uvRect.height / mainTexture.height; - } - - buffer.Seek(0, 1); - - BitmapFont.BMGlyph bg; - int cnt = buffer.ReadInt(); - for (int i = 0; i < cnt; i++) - { - int nextPos = buffer.ReadUshort(); - nextPos += buffer.position; - - bg = new BitmapFont.BMGlyph(); - char ch = buffer.ReadChar(); - font.AddChar(ch, bg); - - string img = buffer.ReadS(); - int bx = buffer.ReadInt(); - int by = buffer.ReadInt(); - bgX = buffer.ReadInt(); - bgY = buffer.ReadInt(); - bgWidth = buffer.ReadInt(); - bgHeight = buffer.ReadInt(); - bg.advance = buffer.ReadInt(); - bg.channel = buffer.ReadByte(); - //The texture channel where the character image is found (1 = blue, 2 = green, 4 = red, 8 = alpha, 15-all). - if (bg.channel == 1) - bg.channel = 2; - else if (bg.channel == 2) - bg.channel = 1; - else if (bg.channel == 4) - bg.channel = 0; - else if (bg.channel == 8) - bg.channel = 3; - - if (ttf) - { - if (mainSprite.rotated) - { - bg.uv[0] = new Vector2((float)(by + bgHeight + mainSprite.rect.x) * texScaleX, - 1 - (float)(mainSprite.rect.yMax - bx) * texScaleY); - bg.uv[1] = new Vector2(bg.uv[0].x - (float)bgHeight * texScaleX, bg.uv[0].y); - bg.uv[2] = new Vector2(bg.uv[1].x, bg.uv[0].y + (float)bgWidth * texScaleY); - bg.uv[3] = new Vector2(bg.uv[0].x, bg.uv[2].y); - } - else - { - bg.uv[0] = new Vector2((float)(bx + mainSprite.rect.x) * texScaleX, - 1 - (float)(by + bgHeight + mainSprite.rect.y) * texScaleY); - bg.uv[1] = new Vector2(bg.uv[0].x, bg.uv[0].y + (float)bgHeight * texScaleY); - bg.uv[2] = new Vector2(bg.uv[0].x + (float)bgWidth * texScaleX, bg.uv[1].y); - bg.uv[3] = new Vector2(bg.uv[2].x, bg.uv[0].y); - } - - bg.lineHeight = lineHeight; - bg.x = bgX; - bg.y = bgY; - bg.width = bgWidth; - bg.height = bgHeight; - } - else - { - PackageItem charImg; - if (_itemsById.TryGetValue(img, out charImg)) - { - charImg = charImg.getBranch(); - bgWidth = charImg.width; - bgHeight = charImg.height; - charImg = charImg.getHighResolution(); - GetItemAsset(charImg); - charImg.texture.GetUV(bg.uv); - - texScaleX = (float)bgWidth / charImg.width; - texScaleY = (float)bgHeight / charImg.height; - - bg.x = bgX + charImg.texture.offset.x * texScaleX; - bg.y = bgY + charImg.texture.offset.y * texScaleY; - bg.width = charImg.texture.width * texScaleX; - bg.height = charImg.texture.height * texScaleY; - - if (mainTexture == null) - mainTexture = charImg.texture.root; - } - - if (fontSize == 0) - fontSize = bgHeight; - - if (bg.advance == 0) - { - if (xadvance == 0) - bg.advance = bgX + bgWidth; - else - bg.advance = xadvance; - } - - bg.lineHeight = bgY < 0 ? bgHeight : (bgY + bgHeight); - if (bg.lineHeight < fontSize) - bg.lineHeight = fontSize; - } - - buffer.position = nextPos; - } - - font.size = fontSize; - font.mainTexture = mainTexture; - if (!font.hasChannel) - font.shader = ShaderConfig.imageShader; - } - - void LoadSpine(PackageItem item) - { -#if FAIRYGUI_SPINE - string ext = Path.GetExtension(item.file); - string fileName = item.file.Substring(0, item.file.Length - ext.Length); - int index = fileName.LastIndexOf(".skel"); - if (index > 0) - fileName = fileName.Substring(0, index); - - Spine.Unity.SkeletonDataAsset asset; - if (_resBundle != null) - asset = _resBundle.LoadAsset(fileName + "_SkeletonData"); - else - { - DestroyMethod dm; - asset = (Spine.Unity.SkeletonDataAsset)_loadFunc(fileName + "_SkeletonData", ".asset", typeof(Spine.Unity.SkeletonDataAsset), out dm); - } - if (asset == null) - Debug.LogWarning("FairyGUI: Failed to load " + fileName); - item.skeletonAsset = asset; -#else - Debug.LogWarning("To enable Spine support, add script define symbol: FAIRYGUI_SPINE"); -#endif - } - - void LoadDragonBones(PackageItem item) - { -#if FAIRYGUI_DRAGONBONES - string ext = Path.GetExtension(item.file); - string fileName = item.file.Substring(0, item.file.Length - ext.Length); - int index = fileName.LastIndexOf("_ske"); - if (index > 0) - fileName = fileName.Substring(0, index); - index = fileName.LastIndexOf(".dbbin"); - if (index > 0) - fileName = fileName.Substring(0, index); - - DragonBones.UnityDragonBonesData asset; - if (_resBundle != null) - asset = _resBundle.LoadAsset(fileName + "_Data"); - else - { - DestroyMethod dm; - asset = (DragonBones.UnityDragonBonesData)_loadFunc(fileName + "_Data", ".asset", typeof(DragonBones.UnityDragonBonesData), out dm); - } - if (asset != null) - { - foreach (var atlas in asset.textureAtlas) - { - if (atlas.material == null) - { - atlas.material = new Material(ShaderConfig.GetShader(ShaderConfig.imageShader)); - atlas.material.mainTexture = atlas.texture; - } - } - item.skeletonAsset = DragonBones.UnityFactory.factory.LoadData(asset); - } - else - Debug.LogWarning("FairyGUI: Failed to load " + fileName); -#else - Debug.LogWarning("To enable DragonBones support, add script define symbol: FAIRYGUI_DRAGONBONES"); -#endif - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using FairyGUI.Utils; +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace FairyGUI +{ + /// + /// A UI Package contains a description file and some texture, sound assets. + /// + public class UIPackage + { + /// + /// Unload UIAssetBundle by FairyGUI system. + /// if use AssetBundlesManager set value to false + /// then unload UIAssetBundle by AssetBundlesManager + /// + public static bool unloadBundleByFGUI = true; + + /// + /// The event is triggered when all reference to this package item dropped. + /// + public static event Action onReleaseResource; + + /// + /// Package id. It is generated by the Editor. + /// + public string id { get; private set; } + + /// + /// Package name. + /// + public string name { get; private set; } + + /// + /// Use this callback to provide resources to the package. + /// + /// Resource name without extension. + /// Resource extension. e.g. '.png' '.wav' + /// Resource type. e.g. 'Texture' 'AudioClip' + /// How to destroy this resource. + /// + public delegate object LoadResource(string name, string extension, System.Type type, out DestroyMethod destroyMethod); + + /// + /// A async load resource callback. After loaded, you should call item.owner.SetItemAsset. + /// + /// Resource name without extension. + /// Resource extension. e.g. '.png' '.wav' + /// Resource type. e.g. 'Texture' 'AudioClip' + /// Resource item object. + /// + public delegate void LoadResourceAsync(string name, string extension, System.Type type, PackageItem item); + + /// + /// + /// + /// + public delegate void CreateObjectCallback(GObject result); + + List _items; + Dictionary _itemsById; + Dictionary _itemsByName; + Dictionary[] _dependencies; + string _assetPath; + string[] _branches; + internal int _branchIndex; + AssetBundle _resBundle; + string _customId; + bool _fromBundle; + LoadResource _loadFunc; + LoadResourceAsync _loadAsyncFunc; + + class AtlasSprite + { + public PackageItem atlas; + public Rect rect = new Rect(); + public Vector2 offset = new Vector2(); + public Vector2 originalSize = new Vector2(); + public bool rotated; + } + Dictionary _sprites; + + static Dictionary _packageInstById = new Dictionary(); + static Dictionary _packageInstByName = new Dictionary(); + static List _packageList = new List(); + static string _branch; + static Dictionary _vars = new Dictionary(); + + internal static int _constructing; + + public const string URL_PREFIX = "ui://"; + +#if UNITY_EDITOR + static LoadResource _loadFromAssetsPath = (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => + { + destroyMethod = DestroyMethod.Unload; + return AssetDatabase.LoadAssetAtPath(name + extension, type); + }; +#endif + + static LoadResource _loadFromResourcesPath = (string name, string extension, System.Type type, out DestroyMethod destroyMethod) => + { + destroyMethod = DestroyMethod.Unload; + return Resources.Load(name, type); + }; + + public UIPackage() + { + _items = new List(); + _itemsById = new Dictionary(); + _itemsByName = new Dictionary(); + _sprites = new Dictionary(); + + _branchIndex = -1; + } + + /// + /// + /// + public static string branch + { + get { return _branch; } + set + { + _branch = value; + bool empty = string.IsNullOrEmpty(_branch); + var iter = _packageInstById.GetEnumerator(); + while (iter.MoveNext()) + { + UIPackage pkg = iter.Current.Value; + if (empty) + pkg._branchIndex = -1; + else if (pkg._branches != null) + pkg._branchIndex = Array.IndexOf(pkg._branches, value); + } + iter.Dispose(); + } + } + + /// + /// + /// + public static string GetVar(string key) + { + string value; + if (_vars.TryGetValue(key, out value)) + return value; + else + return null; + } + + /// + /// + /// + public static void SetVar(string key, string value) + { + if (value == null) + _vars.Remove(key); + else + _vars[key] = value; + } + + /// + /// Return a UIPackage with a certain id. + /// + /// ID of the package. + /// UIPackage + public static UIPackage GetById(string id) + { + UIPackage pkg; + if (_packageInstById.TryGetValue(id, out pkg)) + return pkg; + else + return null; + } + + /// + /// Return a UIPackage with a certain name. + /// + /// Name of the package. + /// UIPackage + public static UIPackage GetByName(string name) + { + UIPackage pkg; + if (_packageInstByName.TryGetValue(name, out pkg)) + return pkg; + else + return null; + } + + /// + /// Add a UI package from assetbundle. + /// + /// A assetbundle. + /// UIPackage + public static UIPackage AddPackage(AssetBundle bundle) + { + return AddPackage(bundle, bundle, null); + } + + /// + /// Add a UI package from two assetbundles. desc and res can be same. + /// + /// A assetbunble contains description file. + /// A assetbundle contains resources. + /// UIPackage + public static UIPackage AddPackage(AssetBundle desc, AssetBundle res) + { + return AddPackage(desc, res, null); + } + + /// + /// Add a UI package from two assetbundles with a optional main asset name. + /// + /// A assetbunble contains description file. + /// A assetbundle contains resources. + /// Main asset name. e.g. Basics_fui + /// UIPackage + public static UIPackage AddPackage(AssetBundle desc, AssetBundle res, string mainAssetName) + { + byte[] source = null; + if (!string.IsNullOrEmpty(mainAssetName)) + { + TextAsset ta = desc.LoadAsset(mainAssetName); + if (ta != null) + source = ta.bytes; + } + else + { + string[] names = desc.GetAllAssetNames(); + string searchPattern = "_fui"; + foreach (string n in names) + { + if (n.IndexOf(searchPattern) != -1) + { + TextAsset ta = desc.LoadAsset(n); + if (ta != null) + { + source = ta.bytes; + mainAssetName = Path.GetFileNameWithoutExtension(n); + break; + } + } + } + } + + if (source == null) + throw new Exception("FairyGUI: no package found in this bundle."); + + if (unloadBundleByFGUI && desc != res) + desc.Unload(true); + + ByteBuffer buffer = new ByteBuffer(source); + + UIPackage pkg = new UIPackage(); + pkg._resBundle = res; + pkg._fromBundle = true; + int pos = mainAssetName.IndexOf("_fui"); + if (pos != -1) + mainAssetName = mainAssetName.Substring(0, pos); + if (!pkg.LoadPackage(buffer, mainAssetName)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + + return pkg; + } + + /// + /// Add a UI package from a path relative to Unity Resources path. + /// + /// Path relative to Unity Resources path. + /// UIPackage + public static UIPackage AddPackage(string descFilePath) + { + if (descFilePath.StartsWith("Assets/")) + { +#if UNITY_EDITOR + return AddPackage(descFilePath, _loadFromAssetsPath); +#else + + Debug.LogWarning("FairyGUI: failed to load package in '" + descFilePath + "'"); + return null; +#endif + } + else + return AddPackage(descFilePath, _loadFromResourcesPath); + } + + /// + /// 使用自定义的加载方式载入一个包。 + /// + /// 包资源路径。 + /// 载入函数 + /// + public static UIPackage AddPackage(string assetPath, LoadResource loadFunc) + { + if (_packageInstById.ContainsKey(assetPath)) + return _packageInstById[assetPath]; + + DestroyMethod dm; + TextAsset asset = (TextAsset)loadFunc(assetPath + "_fui", ".bytes", typeof(TextAsset), out dm); + if (asset == null) + { + if (Application.isPlaying) + throw new Exception("FairyGUI: Cannot load ui package in '" + assetPath + "'"); + else + Debug.LogWarning("FairyGUI: Cannot load ui package in '" + assetPath + "'"); + } + + ByteBuffer buffer = new ByteBuffer(asset.bytes); + + UIPackage pkg = new UIPackage(); + pkg._loadFunc = loadFunc; + pkg._assetPath = assetPath; + if (!pkg.LoadPackage(buffer, assetPath)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageInstById[assetPath] = pkg; + _packageList.Add(pkg); + return pkg; + } + + /// + /// Load Package by custom load method. + /// + /// Description file data + /// Prefix of the resource file name. The file name would be in format of 'assetNamePrefix_resFileName'. It can be empty. + /// Load method + /// + public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResource loadFunc) + { + ByteBuffer buffer = new ByteBuffer(descData); + + UIPackage pkg = new UIPackage(); + pkg._loadFunc = loadFunc; + if (!pkg.LoadPackage(buffer, assetNamePrefix)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + + return pkg; + } + + /// + /// Load Package async by custom load method. + /// + /// Description file data + /// refix of the resource file name. The file name would be in format of 'assetNamePrefix_resFileName'. It can be empty. + /// Load method + /// + public static UIPackage AddPackage(byte[] descData, string assetNamePrefix, LoadResourceAsync loadFunc) + { + ByteBuffer buffer = new ByteBuffer(descData); + + UIPackage pkg = new UIPackage(); + pkg._loadAsyncFunc = loadFunc; + if (!pkg.LoadPackage(buffer, assetNamePrefix)) + return null; + + _packageInstById[pkg.id] = pkg; + _packageInstByName[pkg.name] = pkg; + _packageList.Add(pkg); + + return pkg; + } + + /// + /// Remove a package. All resources in this package will be disposed. + /// + /// + public static void RemovePackage(string packageIdOrName) + { + UIPackage pkg = null; + if (!_packageInstById.TryGetValue(packageIdOrName, out pkg)) + { + if (!_packageInstByName.TryGetValue(packageIdOrName, out pkg)) + throw new Exception("FairyGUI: '" + packageIdOrName + "' is not a valid package id or name."); + } + pkg.Dispose(); + _packageInstById.Remove(pkg.id); + if (pkg._customId != null) + _packageInstById.Remove(pkg._customId); + if (pkg._assetPath != null) + _packageInstById.Remove(pkg._assetPath); + _packageInstByName.Remove(pkg.name); + _packageList.Remove(pkg); + } + + /// + /// + /// + public static void RemoveAllPackages() + { + if (_packageInstById.Count > 0) + { + UIPackage[] pkgs = _packageList.ToArray(); + + foreach (UIPackage pkg in pkgs) + { + pkg.Dispose(); + } + } + _packageList.Clear(); + _packageInstById.Clear(); + _packageInstByName.Clear(); + } + + /// + /// + /// + /// + public static List GetPackages() + { + return _packageList; + } + + /// + /// Create a UI object. + /// + /// Package name. + /// Resource name. + /// A UI object. + public static GObject CreateObject(string pkgName, string resName) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + return pkg.CreateObject(resName); + else + return null; + } + + /// + /// Create a UI object. + /// + /// Package name. + /// Resource name. + /// Custom implementation of this object. + /// A UI object. + public static GObject CreateObject(string pkgName, string resName, System.Type userClass) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + return pkg.CreateObject(resName, userClass); + else + return null; + } + + /// + /// Create a UI object. + /// + /// Resource url. + /// A UI object. + public static GObject CreateObjectFromURL(string url) + { + PackageItem pi = GetItemByURL(url); + if (pi != null) + return pi.owner.CreateObject(pi, null); + else + return null; + } + + /// + /// Create a UI object. + /// + /// Resource url. + /// Custom implementation of this object. + /// A UI object. + public static GObject CreateObjectFromURL(string url, System.Type userClass) + { + PackageItem pi = GetItemByURL(url); + if (pi != null) + return pi.owner.CreateObject(pi, userClass); + else + return null; + } + + public static void CreateObjectAsync(string pkgName, string resName, CreateObjectCallback callback) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + pkg.CreateObjectAsync(resName, callback); + else + Debug.LogError("FairyGUI: package not found - " + pkgName); + } + + public static void CreateObjectFromURL(string url, CreateObjectCallback callback) + { + PackageItem pi = GetItemByURL(url); + if (pi != null) + AsyncCreationHelper.CreateObject(pi, callback); + else + Debug.LogError("FairyGUI: resource not found - " + url); + } + + /// + /// Get a asset with a certain name. + /// + /// Package name. + /// Resource name. + /// If resource is atlas, returns NTexture; If resource is sound, returns AudioClip. + public static object GetItemAsset(string pkgName, string resName) + { + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + return pkg.GetItemAsset(resName); + else + return null; + } + + /// + /// Get a asset with a certain name. + /// + /// Resource url. + /// If resource is atlas, returns NTexture; If resource is sound, returns AudioClip. + public static object GetItemAssetByURL(string url) + { + PackageItem item = GetItemByURL(url); + if (item == null) + return null; + + return item.owner.GetItemAsset(item); + } + + /// + /// Get url of an item in package. + /// + /// Package name. + /// Resource name. + /// Url. + public static string GetItemURL(string pkgName, string resName) + { + UIPackage pkg = GetByName(pkgName); + if (pkg == null) + return null; + + PackageItem pi; + if (!pkg._itemsByName.TryGetValue(resName, out pi)) + return null; + + return URL_PREFIX + pkg.id + pi.id; + } + + public static PackageItem GetItemByURL(string url) + { + if (url == null) + return null; + + int pos1 = url.IndexOf("//"); + if (pos1 == -1) + return null; + + int pos2 = url.IndexOf('/', pos1 + 2); + if (pos2 == -1) + { + if (url.Length > 13) + { + string pkgId = url.Substring(5, 8); + UIPackage pkg = GetById(pkgId); + if (pkg != null) + { + string srcId = url.Substring(13); + return pkg.GetItem(srcId); + } + } + } + else + { + string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2); + UIPackage pkg = GetByName(pkgName); + if (pkg != null) + { + string srcName = url.Substring(pos2 + 1); + return pkg.GetItemByName(srcName); + } + } + + return null; + } + + /// + /// 将'ui://包名/组件名'转换为以内部id表达的url格式。如果传入的url本身就是内部id格式,则直接返回。 + /// 同时这个方法还带格式检测,如果传入不正确的url,会返回null。 + /// + /// + /// + public static string NormalizeURL(string url) + { + if (url == null) + return null; + + int pos1 = url.IndexOf("//"); + if (pos1 == -1) + return null; + + int pos2 = url.IndexOf('/', pos1 + 2); + if (pos2 == -1) + return url; + else + { + string pkgName = url.Substring(pos1 + 2, pos2 - pos1 - 2); + string srcName = url.Substring(pos2 + 1); + return GetItemURL(pkgName, srcName); + } + } + + /// + /// Set strings source. + /// + /// + public static void SetStringsSource(XML source) + { + TranslationHelper.LoadFromXML(source); + } + + /// + /// + /// + public string assetPath + { + get { return _assetPath; } + } + + /// + /// Set a custom id for package, then you can use it in GetById. + /// + public string customId + { + get { return _customId; } + set + { + if (_customId != null) + _packageInstById.Remove(_customId); + _customId = value; + if (_customId != null) + _packageInstById[_customId] = this; + } + } + + /// + /// + /// + public AssetBundle resBundle + { + get { return _resBundle; } + } + + /// + /// 获得本包依赖的包的id列表 + /// + public Dictionary[] dependencies + { + get { return _dependencies; } + } + + bool LoadPackage(ByteBuffer buffer, string assetNamePrefix) + { + if (buffer.ReadUint() != 0x46475549) + { + if (Application.isPlaying) + throw new Exception("FairyGUI: old package format found in '" + assetNamePrefix + "'"); + else + { + Debug.LogWarning("FairyGUI: old package format found in '" + assetNamePrefix + "'"); + return false; + } + } + + buffer.version = buffer.ReadInt(); + bool ver2 = buffer.version >= 2; + buffer.ReadBool(); //compressed + id = buffer.ReadString(); + name = buffer.ReadString(); + + UIPackage existingPkg; + if (_packageInstById.TryGetValue(id, out existingPkg)) + { + if (name != existingPkg.name) + Debug.LogWarning("FairyGUI: Package conflicts, '" + name + "' and '" + existingPkg.name + "'"); + +#if UNITY_EDITOR + //maybe multiple pkgs in different folder, pefer the one in resources + if (Application.isEditor) + { + if (existingPkg._loadFunc == _loadFromAssetsPath) //old one is outside resources path + existingPkg.Dispose(); //replace the existing + else if (existingPkg._loadFunc == _loadFromResourcesPath && _loadFunc == _loadFromResourcesPath + && _assetPath.Length < existingPkg._assetPath.Length) //both in resources path, pefer short path + existingPkg.Dispose(); //replace the existing + else //keep the existing + return false; + } +#endif + } + + buffer.Skip(20); + int indexTablePos = buffer.position; + int cnt; + + buffer.Seek(indexTablePos, 4); + + cnt = buffer.ReadInt(); + string[] stringTable = new string[cnt]; + for (int i = 0; i < cnt; i++) + stringTable[i] = buffer.ReadString(); + buffer.stringTable = stringTable; + + if (buffer.Seek(indexTablePos, 5)) + { + cnt = buffer.ReadInt(); + for (int i = 0; i < cnt; i++) + { + int index = buffer.ReadUshort(); + int len = buffer.ReadInt(); + stringTable[index] = buffer.ReadString(len); + } + } + + buffer.Seek(indexTablePos, 0); + + cnt = buffer.ReadShort(); + _dependencies = new Dictionary[cnt]; + for (int i = 0; i < cnt; i++) + { + Dictionary kv = new Dictionary(); + kv.Add("id", buffer.ReadS()); + kv.Add("name", buffer.ReadS()); + _dependencies[i] = kv; + } + + bool branchIncluded = false; + if (ver2) + { + cnt = buffer.ReadShort(); + if (cnt > 0) + { + _branches = buffer.ReadSArray(cnt); + if (!string.IsNullOrEmpty(_branch)) + _branchIndex = Array.IndexOf(_branches, _branch); + } + + branchIncluded = cnt > 0; + } + + buffer.Seek(indexTablePos, 1); + + PackageItem pi; + string assetPath; + if (assetNamePrefix.Length > 0) + { + assetPath = Path.GetDirectoryName(assetNamePrefix); + if (assetPath.Length > 0) + assetPath += "/"; + assetNamePrefix = assetNamePrefix + "_"; + } + else + assetPath = string.Empty; + + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadInt(); + nextPos += buffer.position; + + pi = new PackageItem(); + pi.owner = this; + pi.type = (PackageItemType)buffer.ReadByte(); + pi.id = buffer.ReadS(); + pi.name = buffer.ReadS(); + buffer.ReadS(); //path + pi.file = buffer.ReadS(); + pi.exported = buffer.ReadBool(); + pi.width = buffer.ReadInt(); + pi.height = buffer.ReadInt(); + + switch (pi.type) + { + case PackageItemType.Image: + { + pi.objectType = ObjectType.Image; + int scaleOption = buffer.ReadByte(); + if (scaleOption == 1) + { + Rect rect = new Rect(); + rect.x = buffer.ReadInt(); + rect.y = buffer.ReadInt(); + rect.width = buffer.ReadInt(); + rect.height = buffer.ReadInt(); + pi.scale9Grid = rect; + + pi.tileGridIndice = buffer.ReadInt(); + } + else if (scaleOption == 2) + pi.scaleByTile = true; + + buffer.ReadBool(); //smoothing + break; + } + + case PackageItemType.MovieClip: + { + buffer.ReadBool(); //smoothing + pi.objectType = ObjectType.MovieClip; + pi.rawData = buffer.ReadBuffer(); + break; + } + + case PackageItemType.Font: + { + pi.rawData = buffer.ReadBuffer(); + break; + } + + case PackageItemType.Component: + { + int extension = buffer.ReadByte(); + if (extension > 0) + pi.objectType = (ObjectType)extension; + else + pi.objectType = ObjectType.Component; + pi.rawData = buffer.ReadBuffer(); + + UIObjectFactory.ResolvePackageItemExtension(pi); + break; + } + + case PackageItemType.Atlas: + case PackageItemType.Sound: + case PackageItemType.Misc: + { + pi.file = assetNamePrefix + pi.file; + break; + } + + case PackageItemType.Spine: + case PackageItemType.DragoneBones: + { + pi.file = assetPath + pi.file; + pi.skeletonAnchor.x = buffer.ReadFloat(); + pi.skeletonAnchor.y = buffer.ReadFloat(); + break; + } + } + + if (ver2) + { + string str = buffer.ReadS();//branch + if (str != null) + pi.name = str + "/" + pi.name; + + int branchCnt = buffer.ReadByte(); + if (branchCnt > 0) + { + if (branchIncluded) + pi.branches = buffer.ReadSArray(branchCnt); + else + _itemsById[buffer.ReadS()] = pi; + } + + int highResCnt = buffer.ReadByte(); + if (highResCnt > 0) + pi.highResolution = buffer.ReadSArray(highResCnt); + } + + _items.Add(pi); + _itemsById[pi.id] = pi; + if (pi.name != null) + _itemsByName[pi.name] = pi; + + buffer.position = nextPos; + } + + buffer.Seek(indexTablePos, 2); + + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + string itemId = buffer.ReadS(); + pi = _itemsById[buffer.ReadS()]; + + AtlasSprite sprite = new AtlasSprite(); + sprite.atlas = pi; + sprite.rect.x = buffer.ReadInt(); + sprite.rect.y = buffer.ReadInt(); + sprite.rect.width = buffer.ReadInt(); + sprite.rect.height = buffer.ReadInt(); + sprite.rotated = buffer.ReadBool(); + if (ver2 && buffer.ReadBool()) + { + sprite.offset.x = buffer.ReadInt(); + sprite.offset.y = buffer.ReadInt(); + sprite.originalSize.x = buffer.ReadInt(); + sprite.originalSize.y = buffer.ReadInt(); + } + else if (sprite.rotated) + { + sprite.originalSize.x = sprite.rect.height; + sprite.originalSize.y = sprite.rect.width; + } + else + { + sprite.originalSize.x = sprite.rect.width; + sprite.originalSize.y = sprite.rect.height; + } + + _sprites[itemId] = sprite; + + buffer.position = nextPos; + } + + if (buffer.Seek(indexTablePos, 3)) + { + cnt = buffer.ReadShort(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadInt(); + nextPos += buffer.position; + + if (_itemsById.TryGetValue(buffer.ReadS(), out pi)) + { + if (pi.type == PackageItemType.Image) + { + pi.pixelHitTestData = new PixelHitTestData(); + pi.pixelHitTestData.Load(buffer); + } + } + + buffer.position = nextPos; + } + } + + if (!Application.isPlaying) + _items.Sort(ComparePackageItem); + + return true; + } + + static int ComparePackageItem(PackageItem p1, PackageItem p2) + { + if (p1.name != null && p2.name != null) + return p1.name.CompareTo(p2.name); + else + return 0; + } + + /// + /// + /// + public void LoadAllAssets() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + GetItemAsset(_items[i]); + } + + /// + /// + /// + public void UnloadAssets() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + PackageItem pi = _items[i]; + if (pi.type == PackageItemType.Atlas) + { + if (pi.texture != null) + pi.texture.Unload(); + } + else if (pi.type == PackageItemType.Sound) + { + if (pi.audioClip != null) + pi.audioClip.Unload(); + } + } + + if (unloadBundleByFGUI && + _resBundle != null) + { + _resBundle.Unload(true); + _resBundle = null; + } + } + + /// + /// + /// + public void ReloadAssets() + { + if (_fromBundle) + throw new Exception("FairyGUI: new bundle must be passed to this function"); + + ReloadAssets(null); + } + + /// + /// + /// + public void ReloadAssets(AssetBundle resBundle) + { + _resBundle = resBundle; + _fromBundle = _resBundle != null; + + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + PackageItem pi = _items[i]; + if (pi.type == PackageItemType.Atlas) + { + if (pi.texture != null && pi.texture.nativeTexture == null) + LoadAtlas(pi); + } + else if (pi.type == PackageItemType.Sound) + { + if (pi.audioClip != null && pi.audioClip.nativeClip == null) + LoadSound(pi); + } + } + } + + void Dispose() + { + int cnt = _items.Count; + for (int i = 0; i < cnt; i++) + { + PackageItem pi = _items[i]; + if (pi.type == PackageItemType.Atlas) + { + if (pi.texture != null) + { + pi.texture.Dispose(); + pi.texture = null; + } + } + else if (pi.type == PackageItemType.Sound) + { + if (pi.audioClip != null) + { + pi.audioClip.Unload(); + pi.audioClip = null; + } + } + } + _items.Clear(); + + if (unloadBundleByFGUI && + _resBundle != null) + { + _resBundle.Unload(true); + _resBundle = null; + } + } + + /// + /// + /// + /// + /// + public GObject CreateObject(string resName) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); + return null; + } + + return CreateObject(pi, null); + } + + /// + /// + /// + /// + /// + /// + public GObject CreateObject(string resName, System.Type userClass) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); + return null; + } + + return CreateObject(pi, userClass); + } + + public void CreateObjectAsync(string resName, CreateObjectCallback callback) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: resource not found - " + resName + " in " + this.name); + return; + } + + AsyncCreationHelper.CreateObject(pi, callback); + } + + GObject CreateObject(PackageItem item, System.Type userClass) + { + Stats.LatestObjectCreation = 0; + Stats.LatestGraphicsCreation = 0; + + GetItemAsset(item); + + GObject g = UIObjectFactory.NewObject(item, userClass); + if (g == null) + return null; + + _constructing++; + g.ConstructFromResource(); + _constructing--; + + return g; + } + + + /// + /// + /// + /// + /// + public object GetItemAsset(string resName) + { + PackageItem pi; + if (!_itemsByName.TryGetValue(resName, out pi)) + { + Debug.LogError("FairyGUI: Resource not found - " + resName + " in " + this.name); + return null; + } + + return GetItemAsset(pi); + } + + public List GetItems() + { + return _items; + } + + public PackageItem GetItem(string itemId) + { + PackageItem pi; + if (_itemsById.TryGetValue(itemId, out pi)) + return pi; + else + return null; + } + + public PackageItem GetItemByName(string itemName) + { + PackageItem pi; + if (_itemsByName.TryGetValue(itemName, out pi)) + return pi; + else + return null; + } + + public object GetItemAsset(PackageItem item) + { + switch (item.type) + { + case PackageItemType.Image: + if (item.texture == null) + LoadImage(item); + return item.texture; + + case PackageItemType.Atlas: + if (item.texture == null) + LoadAtlas(item); + return item.texture; + + case PackageItemType.Sound: + if (item.audioClip == null) + LoadSound(item); + return item.audioClip; + + case PackageItemType.Font: + if (item.bitmapFont == null) + LoadFont(item); + + return item.bitmapFont; + + case PackageItemType.MovieClip: + if (item.frames == null) + LoadMovieClip(item); + + return item.frames; + + case PackageItemType.Component: + return item.rawData; + + case PackageItemType.Misc: + return LoadBinary(item); + + case PackageItemType.Spine: + if (item.skeletonAsset == null) + LoadSpine(item); + return item.skeletonAsset; + + case PackageItemType.DragoneBones: + if (item.skeletonAsset == null) + LoadDragonBones(item); + return item.skeletonAsset; + + default: + return null; + } + } + + /// + /// + /// + /// + /// + /// + public void SetItemAsset(PackageItem item, object asset, DestroyMethod destroyMethod) + { + switch (item.type) + { + case PackageItemType.Atlas: + if (item.texture == null) + item.texture = new NTexture(null, new Rect(0, 0, item.width, item.height)); + item.texture.Reload((Texture)asset, null); + item.texture.destroyMethod = destroyMethod; + break; + + case PackageItemType.Sound: + if (item.audioClip == null) + item.audioClip = new NAudioClip(null); + item.audioClip.Reload((AudioClip)asset); + item.audioClip.destroyMethod = destroyMethod; + break; + + case PackageItemType.Spine: +#if FAIRYGUI_SPINE + item.skeletonAsset = (Spine.Unity.SkeletonDataAsset)asset; +#endif + break; + + case PackageItemType.DragoneBones: +#if FAIRYGUI_DRAGONBONES + item.skeletonAsset = (DragonBones.UnityDragonBonesData)asset; +#endif + break; + } + } + + void LoadAtlas(PackageItem item) + { + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + + if (_loadAsyncFunc != null) + { + _loadAsyncFunc(fileName, ext, typeof(Texture), item); + if (item.texture == null) + item.texture = new NTexture(null, new Rect(0, 0, item.width, item.height)); + item.texture.destroyMethod = DestroyMethod.None; + } + else + { + Texture tex = null; + Texture alphaTex = null; + DestroyMethod dm; + + if (_fromBundle) + { + if (_resBundle != null) + tex = _resBundle.LoadAsset(fileName); + else + Debug.LogWarning("FairyGUI: bundle already unloaded."); + + dm = DestroyMethod.None; + } + else + tex = (Texture)_loadFunc(fileName, ext, typeof(Texture), out dm); + + if (tex == null) + Debug.LogWarning("FairyGUI: texture '" + item.file + "' not found in " + this.name); + + else if (!(tex is Texture2D)) + { + Debug.LogWarning("FairyGUI: settings for '" + item.file + "' is wrong! Correct values are: (Texture Type=Default, Texture Shape=2D)"); + tex = null; + } + else + { + if (((Texture2D)tex).mipmapCount > 1) + Debug.LogWarning("FairyGUI: settings for '" + item.file + "' is wrong! Correct values are: (Generate Mip Maps=unchecked)"); + } + + if (tex != null) + { + fileName = fileName + "!a"; + if (_fromBundle) + { + if (_resBundle != null) + alphaTex = _resBundle.LoadAsset(fileName); + } + else + alphaTex = (Texture2D)_loadFunc(fileName, ext, typeof(Texture2D), out dm); + } + + if (tex == null) + { + tex = NTexture.CreateEmptyTexture(); + dm = DestroyMethod.Destroy; + } + + if (item.texture == null) + { + item.texture = new NTexture(tex, alphaTex, (float)tex.width / item.width, (float)tex.height / item.height); + item.texture.onRelease += (NTexture t) => + { + if (onReleaseResource != null) + onReleaseResource(item); + }; + } + else + item.texture.Reload(tex, alphaTex); + item.texture.destroyMethod = dm; + } + } + + void LoadImage(PackageItem item) + { + AtlasSprite sprite; + if (_sprites.TryGetValue(item.id, out sprite)) + { + NTexture atlas = (NTexture)GetItemAsset(sprite.atlas); + if (atlas.width == sprite.rect.width && atlas.height == sprite.rect.height) + item.texture = atlas; + else + item.texture = new NTexture(atlas, sprite.rect, sprite.rotated, sprite.originalSize, sprite.offset); + } + else + item.texture = NTexture.Empty; + } + + void LoadSound(PackageItem item) + { + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + + if (_loadAsyncFunc != null) + { + _loadAsyncFunc(fileName, ext, typeof(AudioClip), item); + if (item.audioClip == null) + item.audioClip = new NAudioClip(null); + item.audioClip.destroyMethod = DestroyMethod.None; + } + else + { + AudioClip audioClip = null; + DestroyMethod dm; + + if (_fromBundle) + { + if (_resBundle != null) + audioClip = _resBundle.LoadAsset(fileName); + dm = DestroyMethod.None; + } + else + { + audioClip = (AudioClip)_loadFunc(fileName, ext, typeof(AudioClip), out dm); + } + + if (item.audioClip == null) + item.audioClip = new NAudioClip(audioClip); + else + item.audioClip.Reload(audioClip); + item.audioClip.destroyMethod = dm; + } + } + + byte[] LoadBinary(PackageItem item) + { + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + + TextAsset ta; + if (_resBundle != null) + { + ta = _resBundle.LoadAsset(fileName); + if (ta != null) + return ta.bytes; + else + return null; + } + else + { + DestroyMethod dm; + object ret = _loadFunc(fileName, ext, typeof(TextAsset), out dm); + if (ret == null) + return null; + if (ret is byte[]) + return (byte[])ret; + else + return ((TextAsset)ret).bytes; + } + } + + void LoadMovieClip(PackageItem item) + { + ByteBuffer buffer = item.rawData; + + buffer.Seek(0, 0); + + item.interval = buffer.ReadInt() / 1000f; + item.swing = buffer.ReadBool(); + item.repeatDelay = buffer.ReadInt() / 1000f; + + buffer.Seek(0, 1); + + int frameCount = buffer.ReadShort(); + item.frames = new MovieClip.Frame[frameCount]; + + string spriteId; + MovieClip.Frame frame; + AtlasSprite sprite; + Rect frameRect = new Rect(); + + for (int i = 0; i < frameCount; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + frame = new MovieClip.Frame(); + frameRect.x = buffer.ReadInt(); + frameRect.y = buffer.ReadInt(); + frameRect.width = buffer.ReadInt(); + frameRect.height = buffer.ReadInt(); + frame.addDelay = buffer.ReadInt() / 1000f; + spriteId = buffer.ReadS(); + + if (spriteId != null && _sprites.TryGetValue(spriteId, out sprite)) + { + frame.texture = new NTexture((NTexture)GetItemAsset(sprite.atlas), sprite.rect, sprite.rotated, + new Vector2(item.width, item.height), frameRect.position); + } + item.frames[i] = frame; + + buffer.position = nextPos; + } + } + + void LoadFont(PackageItem item) + { + BitmapFont font = new BitmapFont(); + font.name = URL_PREFIX + this.id + item.id; + item.bitmapFont = font; + ByteBuffer buffer = item.rawData; + + buffer.Seek(0, 0); + + bool ttf = buffer.ReadBool(); + font.canTint = buffer.ReadBool(); + font.resizable = buffer.ReadBool(); + font.hasChannel = buffer.ReadBool(); + int fontSize = buffer.ReadInt(); + int xadvance = buffer.ReadInt(); + int lineHeight = buffer.ReadInt(); + + float texScaleX = 1; + float texScaleY = 1; + int bgX; + int bgY; + int bgWidth; + int bgHeight; + + NTexture mainTexture = null; + AtlasSprite mainSprite = null; + if (ttf && _sprites.TryGetValue(item.id, out mainSprite)) + { + mainTexture = (NTexture)GetItemAsset(mainSprite.atlas); + texScaleX = mainTexture.root.uvRect.width / mainTexture.width; + texScaleY = mainTexture.root.uvRect.height / mainTexture.height; + } + + buffer.Seek(0, 1); + + BitmapFont.BMGlyph bg; + int cnt = buffer.ReadInt(); + for (int i = 0; i < cnt; i++) + { + int nextPos = buffer.ReadUshort(); + nextPos += buffer.position; + + bg = new BitmapFont.BMGlyph(); + char ch = buffer.ReadChar(); + font.AddChar(ch, bg); + + string img = buffer.ReadS(); + int bx = buffer.ReadInt(); + int by = buffer.ReadInt(); + bgX = buffer.ReadInt(); + bgY = buffer.ReadInt(); + bgWidth = buffer.ReadInt(); + bgHeight = buffer.ReadInt(); + bg.advance = buffer.ReadInt(); + bg.channel = buffer.ReadByte(); + //The texture channel where the character image is found (1 = blue, 2 = green, 4 = red, 8 = alpha, 15-all). + if (bg.channel == 1) + bg.channel = 2; + else if (bg.channel == 2) + bg.channel = 1; + else if (bg.channel == 4) + bg.channel = 0; + else if (bg.channel == 8) + bg.channel = 3; + + if (ttf) + { + if (mainSprite.rotated) + { + bg.uv[0] = new Vector2((float)(by + bgHeight + mainSprite.rect.x) * texScaleX, + 1 - (float)(mainSprite.rect.yMax - bx) * texScaleY); + bg.uv[1] = new Vector2(bg.uv[0].x - (float)bgHeight * texScaleX, bg.uv[0].y); + bg.uv[2] = new Vector2(bg.uv[1].x, bg.uv[0].y + (float)bgWidth * texScaleY); + bg.uv[3] = new Vector2(bg.uv[0].x, bg.uv[2].y); + } + else + { + bg.uv[0] = new Vector2((float)(bx + mainSprite.rect.x) * texScaleX, + 1 - (float)(by + bgHeight + mainSprite.rect.y) * texScaleY); + bg.uv[1] = new Vector2(bg.uv[0].x, bg.uv[0].y + (float)bgHeight * texScaleY); + bg.uv[2] = new Vector2(bg.uv[0].x + (float)bgWidth * texScaleX, bg.uv[1].y); + bg.uv[3] = new Vector2(bg.uv[2].x, bg.uv[0].y); + } + + bg.lineHeight = lineHeight; + bg.x = bgX; + bg.y = bgY; + bg.width = bgWidth; + bg.height = bgHeight; + } + else + { + PackageItem charImg; + if (_itemsById.TryGetValue(img, out charImg)) + { + charImg = charImg.getBranch(); + bgWidth = charImg.width; + bgHeight = charImg.height; + charImg = charImg.getHighResolution(); + GetItemAsset(charImg); + charImg.texture.GetUV(bg.uv); + + texScaleX = (float)bgWidth / charImg.width; + texScaleY = (float)bgHeight / charImg.height; + + bg.x = bgX + charImg.texture.offset.x * texScaleX; + bg.y = bgY + charImg.texture.offset.y * texScaleY; + bg.width = charImg.texture.width * texScaleX; + bg.height = charImg.texture.height * texScaleY; + + if (mainTexture == null) + mainTexture = charImg.texture.root; + } + + if (fontSize == 0) + fontSize = bgHeight; + + if (bg.advance == 0) + { + if (xadvance == 0) + bg.advance = bgX + bgWidth; + else + bg.advance = xadvance; + } + + bg.lineHeight = bgY < 0 ? bgHeight : (bgY + bgHeight); + if (bg.lineHeight < fontSize) + bg.lineHeight = fontSize; + } + + buffer.position = nextPos; + } + + font.size = fontSize; + font.mainTexture = mainTexture; + if (!font.hasChannel) + font.shader = ShaderConfig.imageShader; + } + + void LoadSpine(PackageItem item) + { +#if FAIRYGUI_SPINE + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + int index = fileName.LastIndexOf(".skel"); + if (index > 0) + fileName = fileName.Substring(0, index); + + Spine.Unity.SkeletonDataAsset asset; + if (_resBundle != null) + asset = _resBundle.LoadAsset(fileName + "_SkeletonData"); + else + { + DestroyMethod dm; + asset = (Spine.Unity.SkeletonDataAsset)_loadFunc(fileName + "_SkeletonData", ".asset", typeof(Spine.Unity.SkeletonDataAsset), out dm); + } + if (asset == null) + Debug.LogWarning("FairyGUI: Failed to load " + fileName); + item.skeletonAsset = asset; +#else + Debug.LogWarning("To enable Spine support, add script define symbol: FAIRYGUI_SPINE"); +#endif + } + + void LoadDragonBones(PackageItem item) + { +#if FAIRYGUI_DRAGONBONES + string ext = Path.GetExtension(item.file); + string fileName = item.file.Substring(0, item.file.Length - ext.Length); + int index = fileName.LastIndexOf("_ske"); + if (index > 0) + fileName = fileName.Substring(0, index); + index = fileName.LastIndexOf(".dbbin"); + if (index > 0) + fileName = fileName.Substring(0, index); + + DragonBones.UnityDragonBonesData asset; + if (_resBundle != null) + asset = _resBundle.LoadAsset(fileName + "_Data"); + else + { + DestroyMethod dm; + asset = (DragonBones.UnityDragonBonesData)_loadFunc(fileName + "_Data", ".asset", typeof(DragonBones.UnityDragonBonesData), out dm); + } + if (asset != null) + { + foreach (var atlas in asset.textureAtlas) + { + if (atlas.material == null) + { + atlas.material = new Material(ShaderConfig.GetShader(ShaderConfig.imageShader)); + atlas.material.mainTexture = atlas.texture; + } + } + item.skeletonAsset = DragonBones.UnityFactory.factory.LoadData(asset); + } + else + Debug.LogWarning("FairyGUI: Failed to load " + fileName); +#else + Debug.LogWarning("To enable DragonBones support, add script define symbol: FAIRYGUI_DRAGONBONES"); +#endif + } + } +} diff --git a/Assets/Scripts/UI/UIPackage.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPackage.cs.meta similarity index 100% rename from Assets/Scripts/UI/UIPackage.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPackage.cs.meta diff --git a/Assets/Scripts/UI/UIPainter.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPainter.cs similarity index 96% rename from Assets/Scripts/UI/UIPainter.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPainter.cs index 42d2661f..d7e9130e 100644 --- a/Assets/Scripts/UI/UIPainter.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPainter.cs @@ -1,335 +1,335 @@ -using System; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// - /// - [ExecuteInEditMode] - [AddComponentMenu("FairyGUI/UI Painter")] - [RequireComponent(typeof(MeshCollider), typeof(MeshRenderer))] - public class UIPainter : MonoBehaviour, EMRenderTarget - { - /// - /// - /// - public Container container { get; private set; } - - /// - /// - /// - public string packageName; - - /// - /// - /// - public string componentName; - - /// - /// - /// - public int sortingOrder; - - [SerializeField] - string packagePath; - [SerializeField] - Camera renderCamera = null; - [SerializeField] - bool fairyBatching = false; - [SerializeField] - bool touchDisabled = false; - - GComponent _ui; - [NonSerialized] - bool _created; - [NonSerialized] - bool _captured; - [NonSerialized] - Renderer _renderer; - - [NonSerialized] - RenderTexture _texture; - - Action _captureDelegate; - - void OnEnable() - { - if (Application.isPlaying) - { - if (this.container == null) - { - CreateContainer(); - - if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) - UIPackage.AddPackage(packagePath); - } - } - else - { - EMRenderSupport.Add(this); - } - } - - void OnDisable() - { - if (!Application.isPlaying) - EMRenderSupport.Remove(this); - } - - void OnGUI() - { - if (!Application.isPlaying) - EM_BeforeUpdate(); - } - - void Start() - { - useGUILayout = false; - - if (!_created && Application.isPlaying) - CreateUI(); - } - - void OnDestroy() - { - if (Application.isPlaying) - { - if (_ui != null) - { - _ui.Dispose(); - _ui = null; - } - - container.Dispose(); - container = null; - } - else - { - EMRenderSupport.Remove(this); - } - - DestroyTexture(); - } - - void CreateContainer() - { - this.container = new Container("UIPainter"); - this.container.renderMode = RenderMode.WorldSpace; - this.container.renderCamera = renderCamera; - this.container.touchable = !touchDisabled; - this.container.fairyBatching = fairyBatching; - this.container._panelOrder = sortingOrder; - this.container.hitArea = new MeshColliderHitTest(this.gameObject.GetComponent()); - SetSortingOrder(this.sortingOrder, true); - this.container.layer = CaptureCamera.hiddenLayer; - } - - /// - /// Change the sorting order of the panel in runtime. - /// - /// sorting order value - /// false if you dont want the default sorting behavior. - public void SetSortingOrder(int value, bool apply) - { - this.sortingOrder = value; - container._panelOrder = value; - - if (apply) - Stage.inst.ApplyPanelOrder(container); - } - - /// - /// - /// - public GComponent ui - { - get - { - if (!_created && Application.isPlaying) - CreateUI(); - - return _ui; - } - } - - /// - /// - /// - public void CreateUI() - { - if (_ui != null) - { - _ui.Dispose(); - _ui = null; - DestroyTexture(); - } - - _created = true; - - if (string.IsNullOrEmpty(packageName) || string.IsNullOrEmpty(componentName)) - return; - - _ui = (GComponent)UIPackage.CreateObject(packageName, componentName); - if (_ui != null) - { - this.container.AddChild(_ui.displayObject); - this.container.size = _ui.size; - _texture = CaptureCamera.CreateRenderTexture(Mathf.RoundToInt(_ui.width), Mathf.RoundToInt(_ui.height), UIConfig.depthSupportForPaintingMode); - _renderer = this.GetComponent(); - if (_renderer != null) - { - _renderer.sharedMaterial.mainTexture = _texture; - _captureDelegate = Capture; - if (_renderer.sharedMaterial.renderQueue == 3000) //Set in transpare queue only - { - this.container.onUpdate += () => - { - UpdateContext.OnEnd += _captureDelegate; - }; - } - } - } - else - Debug.LogError("Create " + componentName + "@" + packageName + " failed!"); - } - - void Capture() - { - CaptureCamera.Capture(this.container, _texture, this.container.size.y, Vector2.zero); - if (_renderer != null) - _renderer.sortingOrder = container.renderingOrder; - } - - void DestroyTexture() - { - if (_texture != null) - { - if (Application.isPlaying) - RenderTexture.Destroy(_texture); - else - RenderTexture.DestroyImmediate(_texture); - _texture = null; - - if (_renderer != null) - _renderer.sharedMaterial.mainTexture = null; - } - } - - #region edit mode functions - - void CaptureInEditMode() - { - if (!EMRenderSupport.packageListReady || UIPackage.GetByName(packageName) == null) - return; - - _captured = true; - - DisplayObject.hideFlags = HideFlags.DontSaveInEditor; - GComponent view = (GComponent)UIPackage.CreateObject(packageName, componentName); - - if (view != null) - { - DestroyTexture(); - - _texture = CaptureCamera.CreateRenderTexture(Mathf.RoundToInt(view.width), Mathf.RoundToInt(view.height), false); - - Container root = (Container)view.displayObject; - root.layer = CaptureCamera.layer; - root.gameObject.hideFlags = HideFlags.None; - root.gameObject.SetActive(true); - - GameObject cameraObject = new GameObject("Temp Capture Camera"); - Camera camera = cameraObject.AddComponent(); - camera.depth = 0; - camera.cullingMask = 1 << CaptureCamera.layer; - camera.clearFlags = CameraClearFlags.Depth; - camera.orthographic = true; - camera.nearClipPlane = -30; - camera.farClipPlane = 30; - camera.enabled = false; - camera.targetTexture = _texture; - - float halfHeight = (float)_texture.height / 2; - camera.orthographicSize = halfHeight; - cameraObject.transform.localPosition = root.cachedTransform.TransformPoint(halfHeight * camera.aspect, -halfHeight, 0); - - UpdateContext context = new UpdateContext(); - //run two times - context.Begin(); - view.displayObject.Update(context); - context.End(); - - context.Begin(); - view.displayObject.Update(context); - context.End(); - - RenderTexture old = RenderTexture.active; - RenderTexture.active = _texture; - GL.Clear(true, true, Color.clear); - camera.Render(); - RenderTexture.active = old; - - camera.targetTexture = null; - view.Dispose(); - GameObject.DestroyImmediate(cameraObject); - - if (_renderer != null) - _renderer.sharedMaterial.mainTexture = _texture; - } - } - - public void ApplyModifiedProperties(bool sortingOrderChanged) - { - if (sortingOrderChanged) - { - if (Application.isPlaying) - SetSortingOrder(sortingOrder, true); - else - EMRenderSupport.orderChanged = true; - } - } - - public void OnUpdateSource(object[] data) - { - if (Application.isPlaying) - return; - - this.packageName = (string)data[0]; - this.packagePath = (string)data[1]; - this.componentName = (string)data[2]; - - if ((bool)data[3]) - _captured = false; - } - - public int EM_sortingOrder - { - get { return sortingOrder; } - } - - public void EM_BeforeUpdate() - { - if (_renderer == null) - _renderer = this.GetComponent(); - if (_renderer != null && _renderer.sharedMaterial.mainTexture != _texture) - _renderer.sharedMaterial.mainTexture = _texture; - - if (packageName != null && componentName != null && !_captured) - CaptureInEditMode(); - } - - public void EM_Update(UpdateContext context) - { - if (_renderer != null) - _renderer.sortingOrder = context.renderingOrder++; - } - - public void EM_Reload() - { - _captured = false; - } - - #endregion - } -} +using System; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Painter")] + [RequireComponent(typeof(MeshCollider), typeof(MeshRenderer))] + public class UIPainter : MonoBehaviour, EMRenderTarget + { + /// + /// + /// + public Container container { get; private set; } + + /// + /// + /// + public string packageName; + + /// + /// + /// + public string componentName; + + /// + /// + /// + public int sortingOrder; + + [SerializeField] + string packagePath; + [SerializeField] + Camera renderCamera = null; + [SerializeField] + bool fairyBatching = false; + [SerializeField] + bool touchDisabled = false; + + GComponent _ui; + [NonSerialized] + bool _created; + [NonSerialized] + bool _captured; + [NonSerialized] + Renderer _renderer; + + [NonSerialized] + RenderTexture _texture; + + Action _captureDelegate; + + void OnEnable() + { + if (Application.isPlaying) + { + if (this.container == null) + { + CreateContainer(); + + if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) + UIPackage.AddPackage(packagePath); + } + } + else + { + EMRenderSupport.Add(this); + } + } + + void OnDisable() + { + if (!Application.isPlaying) + EMRenderSupport.Remove(this); + } + + void OnGUI() + { + if (!Application.isPlaying) + EM_BeforeUpdate(); + } + + void Start() + { + useGUILayout = false; + + if (!_created && Application.isPlaying) + CreateUI(); + } + + void OnDestroy() + { + if (Application.isPlaying) + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + + container.Dispose(); + container = null; + } + else + { + EMRenderSupport.Remove(this); + } + + DestroyTexture(); + } + + void CreateContainer() + { + this.container = new Container("UIPainter"); + this.container.renderMode = RenderMode.WorldSpace; + this.container.renderCamera = renderCamera; + this.container.touchable = !touchDisabled; + this.container.fairyBatching = fairyBatching; + this.container._panelOrder = sortingOrder; + this.container.hitArea = new MeshColliderHitTest(this.gameObject.GetComponent()); + SetSortingOrder(this.sortingOrder, true); + this.container.layer = CaptureCamera.hiddenLayer; + } + + /// + /// Change the sorting order of the panel in runtime. + /// + /// sorting order value + /// false if you dont want the default sorting behavior. + public void SetSortingOrder(int value, bool apply) + { + this.sortingOrder = value; + container._panelOrder = value; + + if (apply) + Stage.inst.ApplyPanelOrder(container); + } + + /// + /// + /// + public GComponent ui + { + get + { + if (!_created && Application.isPlaying) + CreateUI(); + + return _ui; + } + } + + /// + /// + /// + public void CreateUI() + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + DestroyTexture(); + } + + _created = true; + + if (string.IsNullOrEmpty(packageName) || string.IsNullOrEmpty(componentName)) + return; + + _ui = (GComponent)UIPackage.CreateObject(packageName, componentName); + if (_ui != null) + { + this.container.AddChild(_ui.displayObject); + this.container.size = _ui.size; + _texture = CaptureCamera.CreateRenderTexture(Mathf.RoundToInt(_ui.width), Mathf.RoundToInt(_ui.height), UIConfig.depthSupportForPaintingMode); + _renderer = this.GetComponent(); + if (_renderer != null) + { + _renderer.sharedMaterial.mainTexture = _texture; + _captureDelegate = Capture; + if (_renderer.sharedMaterial.renderQueue == 3000) //Set in transpare queue only + { + this.container.onUpdate += () => + { + UpdateContext.OnEnd += _captureDelegate; + }; + } + } + } + else + Debug.LogError("Create " + componentName + "@" + packageName + " failed!"); + } + + void Capture() + { + CaptureCamera.Capture(this.container, _texture, this.container.size.y, Vector2.zero); + if (_renderer != null) + _renderer.sortingOrder = container.renderingOrder; + } + + void DestroyTexture() + { + if (_texture != null) + { + if (Application.isPlaying) + RenderTexture.Destroy(_texture); + else + RenderTexture.DestroyImmediate(_texture); + _texture = null; + + if (_renderer != null) + _renderer.sharedMaterial.mainTexture = null; + } + } + + #region edit mode functions + + void CaptureInEditMode() + { + if (!EMRenderSupport.packageListReady || UIPackage.GetByName(packageName) == null) + return; + + _captured = true; + + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + GComponent view = (GComponent)UIPackage.CreateObject(packageName, componentName); + + if (view != null) + { + DestroyTexture(); + + _texture = CaptureCamera.CreateRenderTexture(Mathf.RoundToInt(view.width), Mathf.RoundToInt(view.height), false); + + Container root = (Container)view.displayObject; + root.layer = CaptureCamera.layer; + root.gameObject.hideFlags = HideFlags.None; + root.gameObject.SetActive(true); + + GameObject cameraObject = new GameObject("Temp Capture Camera"); + Camera camera = cameraObject.AddComponent(); + camera.depth = 0; + camera.cullingMask = 1 << CaptureCamera.layer; + camera.clearFlags = CameraClearFlags.Depth; + camera.orthographic = true; + camera.nearClipPlane = -30; + camera.farClipPlane = 30; + camera.enabled = false; + camera.targetTexture = _texture; + + float halfHeight = (float)_texture.height / 2; + camera.orthographicSize = halfHeight; + cameraObject.transform.localPosition = root.cachedTransform.TransformPoint(halfHeight * camera.aspect, -halfHeight, 0); + + UpdateContext context = new UpdateContext(); + //run two times + context.Begin(); + view.displayObject.Update(context); + context.End(); + + context.Begin(); + view.displayObject.Update(context); + context.End(); + + RenderTexture old = RenderTexture.active; + RenderTexture.active = _texture; + GL.Clear(true, true, Color.clear); + camera.Render(); + RenderTexture.active = old; + + camera.targetTexture = null; + view.Dispose(); + GameObject.DestroyImmediate(cameraObject); + + if (_renderer != null) + _renderer.sharedMaterial.mainTexture = _texture; + } + } + + public void ApplyModifiedProperties(bool sortingOrderChanged) + { + if (sortingOrderChanged) + { + if (Application.isPlaying) + SetSortingOrder(sortingOrder, true); + else + EMRenderSupport.orderChanged = true; + } + } + + public void OnUpdateSource(object[] data) + { + if (Application.isPlaying) + return; + + this.packageName = (string)data[0]; + this.packagePath = (string)data[1]; + this.componentName = (string)data[2]; + + if ((bool)data[3]) + _captured = false; + } + + public int EM_sortingOrder + { + get { return sortingOrder; } + } + + public void EM_BeforeUpdate() + { + if (_renderer == null) + _renderer = this.GetComponent(); + if (_renderer != null && _renderer.sharedMaterial.mainTexture != _texture) + _renderer.sharedMaterial.mainTexture = _texture; + + if (packageName != null && componentName != null && !_captured) + CaptureInEditMode(); + } + + public void EM_Update(UpdateContext context) + { + if (_renderer != null) + _renderer.sortingOrder = context.renderingOrder++; + } + + public void EM_Reload() + { + _captured = false; + } + + #endregion + } +} diff --git a/Assets/Scripts/UI/UIPainter.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPainter.cs.meta similarity index 100% rename from Assets/Scripts/UI/UIPainter.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPainter.cs.meta diff --git a/Assets/Scripts/UI/UIPanel.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPanel.cs similarity index 96% rename from Assets/Scripts/UI/UIPanel.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPanel.cs index 3241d6bc..ce29190a 100644 --- a/Assets/Scripts/UI/UIPanel.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPanel.cs @@ -1,622 +1,622 @@ -using System; -using System.Collections.Generic; -using UnityEngine; -#if UNITY_EDITOR -using UnityEditor; -#endif - -namespace FairyGUI -{ - /// - /// - /// - public enum FitScreen - { - None, - FitSize, - FitWidthAndSetMiddle, - FitHeightAndSetCenter - } - - /// - /// - /// - [ExecuteInEditMode] - [AddComponentMenu("FairyGUI/UI Panel")] - public class UIPanel : MonoBehaviour, EMRenderTarget - { - /// - /// - /// - public Container container { get; private set; } - - /// - /// - /// - public string packageName; - - /// - /// - /// - public string componentName; - - /// - /// - /// - public FitScreen fitScreen; - - /// - /// - /// - public int sortingOrder; - - [SerializeField] - string packagePath; - [SerializeField] - RenderMode renderMode = RenderMode.ScreenSpaceOverlay; - [SerializeField] - Camera renderCamera = null; - [SerializeField] - Vector3 position; - [SerializeField] - Vector3 scale = new Vector3(1, 1, 1); - [SerializeField] - Vector3 rotation = new Vector3(0, 0, 0); - [SerializeField] - bool fairyBatching = false; - [SerializeField] - bool touchDisabled = false; - [SerializeField] - Vector2 cachedUISize; - [SerializeField] - HitTestMode hitTestMode = HitTestMode.Default; - [SerializeField] - bool setNativeChildrenOrder = false; - - [System.NonSerialized] - int screenSizeVer; - [System.NonSerialized] - Rect uiBounds; //Track bounds even when UI is not created, edit mode - - GComponent _ui; - [NonSerialized] - bool _created; - - List _renders; - - void OnEnable() - { - if (Application.isPlaying) - { - if (this.container == null) - { - CreateContainer(); - - if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) - UIPackage.AddPackage(packagePath); - } - } - else - { - //不在播放状态时我们不在OnEnable创建,因为Prefab也会调用OnEnable,延迟到Update里创建(Prefab不调用Update) - //每次播放前都会disable/enable一次。。。 - if (container != null)//如果不为null,可能是因为Prefab revert, 而不是因为Assembly reload, - OnDestroy(); - - EMRenderSupport.Add(this); - screenSizeVer = 0; - uiBounds.position = position; - uiBounds.size = cachedUISize; - if (uiBounds.size == Vector2.zero) - uiBounds.size = new Vector2(30, 30); - } - } - - void OnDisable() - { - if (!Application.isPlaying) - EMRenderSupport.Remove(this); - } - - void Start() - { - if (!_created && Application.isPlaying) - CreateUI_PlayMode(); - } - - void Update() - { - if (screenSizeVer != StageCamera.screenSizeVer) - HandleScreenSizeChanged(); - } - - void OnDestroy() - { - if (container != null) - { - if (!Application.isPlaying) - EMRenderSupport.Remove(this); - - if (_ui != null) - { - _ui.Dispose(); - _ui = null; - } - - container.Dispose(); - container = null; - } - - _renders = null; - } - - void CreateContainer() - { - if (!Application.isPlaying) - { - Transform t = this.transform; - int cnt = t.childCount; - while (cnt > 0) - { - GameObject go = t.GetChild(cnt - 1).gameObject; - if (go.name == "UI(AutoGenerated)") - { -#if (UNITY_2018_3_OR_NEWER && UNITY_EDITOR) - if (PrefabUtility.IsPartOfPrefabInstance(go)) - PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetOutermostPrefabInstanceRoot(gameObject), PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); -#endif - UnityEngine.Object.DestroyImmediate(go); - } - cnt--; - } - } - - this.container = new Container(this.gameObject); - this.container.renderMode = renderMode; - this.container.renderCamera = renderCamera; - this.container.touchable = !touchDisabled; - this.container._panelOrder = sortingOrder; - this.container.fairyBatching = fairyBatching; - if (Application.isPlaying) - { - SetSortingOrder(this.sortingOrder, true); - if (this.hitTestMode == HitTestMode.Raycast) - { - ColliderHitTest hitArea = new ColliderHitTest(); - hitArea.collider = this.gameObject.AddComponent(); - this.container.hitArea = hitArea; - } - - if (setNativeChildrenOrder) - { - CacheNativeChildrenRenderers(); - - this.container.onUpdate += () => - { - int cnt = _renders.Count; - int sv = UpdateContext.current.renderingOrder++; - for (int i = 0; i < cnt; i++) - { - Renderer r = _renders[i]; - if (r != null) - _renders[i].sortingOrder = sv; - } - }; - } - } - } - - /// - /// - /// - public GComponent ui - { - get - { - if (!_created && Application.isPlaying) - { - if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) - UIPackage.AddPackage(packagePath); - - CreateUI_PlayMode(); - } - - return _ui; - } - } - - /// - /// - /// - public void CreateUI() - { - if (_ui != null) - { - _ui.Dispose(); - _ui = null; - } - - CreateUI_PlayMode(); - } - - /// - /// Change the sorting order of the panel in runtime. - /// - /// sorting order value - /// false if you dont want the default sorting behavior. e.g. call Stage.SortWorldSpacePanelsByZOrder later. - public void SetSortingOrder(int value, bool apply) - { - this.sortingOrder = value; - container._panelOrder = value; - - if (apply) - Stage.inst.ApplyPanelOrder(container); - } - - /// - /// - /// - /// - public void SetHitTestMode(HitTestMode value) - { - if (this.hitTestMode != value) - { - this.hitTestMode = value; - BoxCollider collider = this.gameObject.GetComponent(); - if (this.hitTestMode == HitTestMode.Raycast) - { - if (collider == null) - collider = this.gameObject.AddComponent(); - ColliderHitTest hitArea = new ColliderHitTest(); - hitArea.collider = collider; - this.container.hitArea = hitArea; - if (_ui != null) - UpdateHitArea(); - } - else - { - this.container.hitArea = null; - if (collider != null) - Component.Destroy(collider); - } - } - } - - /// - /// - /// - public void CacheNativeChildrenRenderers() - { - if (_renders == null) - _renders = new List(); - else - _renders.Clear(); - - Transform t = this.container.cachedTransform; - int cnt = t.childCount; - for (int i = 0; i < cnt; i++) - { - GameObject go = t.GetChild(i).gameObject; - if (go.name != "GComponent") - _renders.AddRange(go.GetComponentsInChildren(true)); - } - - cnt = _renders.Count; - for (int i = 0; i < cnt; i++) - { - Renderer r = _renders[i]; - if ((r is SkinnedMeshRenderer) || (r is MeshRenderer)) - { - //Set the object rendering in Transparent Queue as UI objects - if (r.sharedMaterial != null) - r.sharedMaterial.renderQueue = 3000; - } - } - } - - void CreateUI_PlayMode() - { - _created = true; - - if (string.IsNullOrEmpty(packageName) || string.IsNullOrEmpty(componentName)) - return; - - _ui = (GComponent)UIPackage.CreateObject(packageName, componentName); - if (_ui != null) - { - _ui.position = position; - if (scale.x != 0 && scale.y != 0) - _ui.scale = scale; - _ui.rotationX = rotation.x; - _ui.rotationY = rotation.y; - _ui.rotation = rotation.z; - if (this.container.hitArea != null) - { - UpdateHitArea(); - _ui.onSizeChanged.Add(UpdateHitArea); - _ui.onPositionChanged.Add(UpdateHitArea); - } - this.container.AddChildAt(_ui.displayObject, 0); - - HandleScreenSizeChanged(); - } - else - Debug.LogError("Create " + packageName + "/" + componentName + " failed!"); - } - - void UpdateHitArea() - { - ColliderHitTest hitArea = this.container.hitArea as ColliderHitTest; - if (hitArea != null) - { - ((BoxCollider)hitArea.collider).center = new Vector3(_ui.xMin + _ui.width / 2, -_ui.yMin - _ui.height / 2); - ((BoxCollider)hitArea.collider).size = _ui.size; - } - } - - void CreateUI_EditMode() - { - if (!EMRenderSupport.packageListReady || UIPackage.GetByName(packageName) == null) - return; - - - DisplayObject.hideFlags = HideFlags.DontSaveInEditor; - GObject obj = UIPackage.CreateObject(packageName, componentName); - if (obj != null && !(obj is GComponent)) - { - obj.Dispose(); - Debug.LogWarning("Not a GComponnet: " + packageName + "/" + componentName); - return; - } - _ui = (GComponent)obj; - - if (_ui != null) - { - _ui.displayObject.gameObject.hideFlags |= HideFlags.HideInHierarchy; - _ui.gameObjectName = "UI(AutoGenerated)"; - - _ui.position = position; - if (scale.x != 0 && scale.y != 0) - _ui.scale = scale; - _ui.rotationX = rotation.x; - _ui.rotationY = rotation.y; - _ui.rotation = rotation.z; - this.container.AddChildAt(_ui.displayObject, 0); - - cachedUISize = _ui.size; - uiBounds.size = cachedUISize; - HandleScreenSizeChanged(); - } - } - - void HandleScreenSizeChanged() - { - if (!Application.isPlaying) - DisplayObject.hideFlags = HideFlags.DontSaveInEditor; - - screenSizeVer = StageCamera.screenSizeVer; - - int width = Screen.width; - int height = Screen.height; - if (this.container != null) - { - Camera cam = container.GetRenderCamera(); - if (cam.targetDisplay != 0 && cam.targetDisplay < Display.displays.Length) - { - width = Display.displays[cam.targetDisplay].renderingWidth; - height = Display.displays[cam.targetDisplay].renderingHeight; - } - - if (this.container.renderMode != RenderMode.WorldSpace) - { - StageCamera sc = cam.GetComponent(); - if (sc == null) - sc = StageCamera.main.GetComponent(); - this.container.scale = new Vector2(sc.unitsPerPixel * UIContentScaler.scaleFactor, sc.unitsPerPixel * UIContentScaler.scaleFactor); - } - } - - width = Mathf.CeilToInt(width / UIContentScaler.scaleFactor); - height = Mathf.CeilToInt(height / UIContentScaler.scaleFactor); - if (_ui != null) - { - switch (fitScreen) - { - case FitScreen.FitSize: - _ui.SetSize(width, height); - _ui.SetXY(0, 0, true); - break; - - case FitScreen.FitWidthAndSetMiddle: - _ui.SetSize(width, _ui.sourceHeight); - _ui.SetXY(0, (int)((height - _ui.sourceHeight) / 2), true); - break; - - case FitScreen.FitHeightAndSetCenter: - _ui.SetSize(_ui.sourceWidth, height); - _ui.SetXY((int)((width - _ui.sourceWidth) / 2), 0, true); - break; - } - - UpdateHitArea(); - } - else - { - switch (fitScreen) - { - case FitScreen.FitSize: - uiBounds.position = new Vector2(0, 0); - uiBounds.size = new Vector2(width, height); - break; - - case FitScreen.FitWidthAndSetMiddle: - uiBounds.position = new Vector2(0, (int)((height - cachedUISize.y) / 2)); - uiBounds.size = new Vector2(width, cachedUISize.y); - break; - - case FitScreen.FitHeightAndSetCenter: - uiBounds.position = new Vector2((int)((width - cachedUISize.x) / 2), 0); - uiBounds.size = new Vector2(cachedUISize.x, height); - break; - } - } - } - - #region edit mode functions - - void OnUpdateSource(object[] data) - { - if (Application.isPlaying) - return; - - this.packageName = (string)data[0]; - this.packagePath = (string)data[1]; - this.componentName = (string)data[2]; - - if ((bool)data[3]) - { - if (container == null) - return; - - if (_ui != null) - { - _ui.Dispose(); - _ui = null; - } - } - } - - public void ApplyModifiedProperties(bool sortingOrderChanged, bool fitScreenChanged) - { - if (container != null) - { - container.renderMode = renderMode; - container.renderCamera = renderCamera; - if (sortingOrderChanged) - { - container._panelOrder = sortingOrder; - if (Application.isPlaying) - SetSortingOrder(sortingOrder, true); - else - EMRenderSupport.orderChanged = true; - } - container.fairyBatching = fairyBatching; - } - - if (_ui != null) - { - if (fitScreen == FitScreen.None) - _ui.position = position; - if (scale.x != 0 && scale.y != 0) - _ui.scale = scale; - _ui.rotationX = rotation.x; - _ui.rotationY = rotation.y; - _ui.rotation = rotation.z; - } - if (fitScreen == FitScreen.None) - uiBounds.position = position; - screenSizeVer = 0;//force HandleScreenSizeChanged be called - - if (fitScreenChanged && this.fitScreen == FitScreen.None) - { - if (_ui != null) - _ui.SetSize(_ui.sourceWidth, _ui.sourceHeight); - uiBounds.size = cachedUISize; - } - } - - public void MoveUI(Vector3 delta) - { - if (fitScreen != FitScreen.None) - return; - - this.position += delta; - if (_ui != null) - _ui.position = position; - uiBounds.position = position; - } - - public Vector3 GetUIWorldPosition() - { - if (_ui != null) - return _ui.displayObject.cachedTransform.position; - else - return this.container.cachedTransform.TransformPoint(uiBounds.position); - } - - void OnDrawGizmos() - { - if (Application.isPlaying || this.container == null) - return; - - Vector3 pos, size; - if (_ui != null) - { - Gizmos.matrix = _ui.displayObject.cachedTransform.localToWorldMatrix; - pos = new Vector3(_ui.width / 2, -_ui.height / 2, 0); - size = new Vector3(_ui.width, _ui.height, 0); - } - else - { - Gizmos.matrix = this.container.cachedTransform.localToWorldMatrix; - pos = new Vector3(uiBounds.x + uiBounds.width / 2, -uiBounds.y - uiBounds.height / 2, 0); - size = new Vector3(uiBounds.width, uiBounds.height, 0); - } - - Gizmos.color = new Color(0, 0, 0, 0); - Gizmos.DrawCube(pos, size); - - Gizmos.color = Color.white; - Gizmos.DrawWireCube(pos, size); - } - - public int EM_sortingOrder - { - get { return sortingOrder; } - } - - public void EM_BeforeUpdate() - { - if (container == null) - CreateContainer(); - - if (packageName != null && componentName != null && _ui == null) - CreateUI_EditMode(); - - if (screenSizeVer != StageCamera.screenSizeVer) - HandleScreenSizeChanged(); - } - - public void EM_Update(UpdateContext context) - { - DisplayObject.hideFlags = HideFlags.DontSaveInEditor; - - container.Update(context); - - if (setNativeChildrenOrder) - { - CacheNativeChildrenRenderers(); - - int cnt = _renders.Count; - int sv = context.renderingOrder++; - for (int i = 0; i < cnt; i++) - { - Renderer r = _renders[i]; - if (r != null) - r.sortingOrder = sv; - } - } - } - - public void EM_Reload() - { - if (_ui != null) - { - _ui.Dispose(); - _ui = null; - } - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using UnityEngine; +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace FairyGUI +{ + /// + /// + /// + public enum FitScreen + { + None, + FitSize, + FitWidthAndSetMiddle, + FitHeightAndSetCenter + } + + /// + /// + /// + [ExecuteInEditMode] + [AddComponentMenu("FairyGUI/UI Panel")] + public class UIPanel : MonoBehaviour, EMRenderTarget + { + /// + /// + /// + public Container container { get; private set; } + + /// + /// + /// + public string packageName; + + /// + /// + /// + public string componentName; + + /// + /// + /// + public FitScreen fitScreen; + + /// + /// + /// + public int sortingOrder; + + [SerializeField] + string packagePath; + [SerializeField] + RenderMode renderMode = RenderMode.ScreenSpaceOverlay; + [SerializeField] + Camera renderCamera = null; + [SerializeField] + Vector3 position; + [SerializeField] + Vector3 scale = new Vector3(1, 1, 1); + [SerializeField] + Vector3 rotation = new Vector3(0, 0, 0); + [SerializeField] + bool fairyBatching = false; + [SerializeField] + bool touchDisabled = false; + [SerializeField] + Vector2 cachedUISize; + [SerializeField] + HitTestMode hitTestMode = HitTestMode.Default; + [SerializeField] + bool setNativeChildrenOrder = false; + + [System.NonSerialized] + int screenSizeVer; + [System.NonSerialized] + Rect uiBounds; //Track bounds even when UI is not created, edit mode + + GComponent _ui; + [NonSerialized] + bool _created; + + List _renders; + + void OnEnable() + { + if (Application.isPlaying) + { + if (this.container == null) + { + CreateContainer(); + + if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) + UIPackage.AddPackage(packagePath); + } + } + else + { + //不在播放状态时我们不在OnEnable创建,因为Prefab也会调用OnEnable,延迟到Update里创建(Prefab不调用Update) + //每次播放前都会disable/enable一次。。。 + if (container != null)//如果不为null,可能是因为Prefab revert, 而不是因为Assembly reload, + OnDestroy(); + + EMRenderSupport.Add(this); + screenSizeVer = 0; + uiBounds.position = position; + uiBounds.size = cachedUISize; + if (uiBounds.size == Vector2.zero) + uiBounds.size = new Vector2(30, 30); + } + } + + void OnDisable() + { + if (!Application.isPlaying) + EMRenderSupport.Remove(this); + } + + void Start() + { + if (!_created && Application.isPlaying) + CreateUI_PlayMode(); + } + + void Update() + { + if (screenSizeVer != StageCamera.screenSizeVer) + HandleScreenSizeChanged(); + } + + void OnDestroy() + { + if (container != null) + { + if (!Application.isPlaying) + EMRenderSupport.Remove(this); + + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + + container.Dispose(); + container = null; + } + + _renders = null; + } + + void CreateContainer() + { + if (!Application.isPlaying) + { + Transform t = this.transform; + int cnt = t.childCount; + while (cnt > 0) + { + GameObject go = t.GetChild(cnt - 1).gameObject; + if (go.name == "UI(AutoGenerated)") + { +#if (UNITY_2018_3_OR_NEWER && UNITY_EDITOR) + if (PrefabUtility.IsPartOfPrefabInstance(go)) + PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetOutermostPrefabInstanceRoot(gameObject), PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); +#endif + UnityEngine.Object.DestroyImmediate(go); + } + cnt--; + } + } + + this.container = new Container(this.gameObject); + this.container.renderMode = renderMode; + this.container.renderCamera = renderCamera; + this.container.touchable = !touchDisabled; + this.container._panelOrder = sortingOrder; + this.container.fairyBatching = fairyBatching; + if (Application.isPlaying) + { + SetSortingOrder(this.sortingOrder, true); + if (this.hitTestMode == HitTestMode.Raycast) + { + ColliderHitTest hitArea = new ColliderHitTest(); + hitArea.collider = this.gameObject.AddComponent(); + this.container.hitArea = hitArea; + } + + if (setNativeChildrenOrder) + { + CacheNativeChildrenRenderers(); + + this.container.onUpdate += () => + { + int cnt = _renders.Count; + int sv = UpdateContext.current.renderingOrder++; + for (int i = 0; i < cnt; i++) + { + Renderer r = _renders[i]; + if (r != null) + _renders[i].sortingOrder = sv; + } + }; + } + } + } + + /// + /// + /// + public GComponent ui + { + get + { + if (!_created && Application.isPlaying) + { + if (!string.IsNullOrEmpty(packagePath) && UIPackage.GetByName(packageName) == null) + UIPackage.AddPackage(packagePath); + + CreateUI_PlayMode(); + } + + return _ui; + } + } + + /// + /// + /// + public void CreateUI() + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + + CreateUI_PlayMode(); + } + + /// + /// Change the sorting order of the panel in runtime. + /// + /// sorting order value + /// false if you dont want the default sorting behavior. e.g. call Stage.SortWorldSpacePanelsByZOrder later. + public void SetSortingOrder(int value, bool apply) + { + this.sortingOrder = value; + container._panelOrder = value; + + if (apply) + Stage.inst.ApplyPanelOrder(container); + } + + /// + /// + /// + /// + public void SetHitTestMode(HitTestMode value) + { + if (this.hitTestMode != value) + { + this.hitTestMode = value; + BoxCollider collider = this.gameObject.GetComponent(); + if (this.hitTestMode == HitTestMode.Raycast) + { + if (collider == null) + collider = this.gameObject.AddComponent(); + ColliderHitTest hitArea = new ColliderHitTest(); + hitArea.collider = collider; + this.container.hitArea = hitArea; + if (_ui != null) + UpdateHitArea(); + } + else + { + this.container.hitArea = null; + if (collider != null) + Component.Destroy(collider); + } + } + } + + /// + /// + /// + public void CacheNativeChildrenRenderers() + { + if (_renders == null) + _renders = new List(); + else + _renders.Clear(); + + Transform t = this.container.cachedTransform; + int cnt = t.childCount; + for (int i = 0; i < cnt; i++) + { + GameObject go = t.GetChild(i).gameObject; + if (go.name != "GComponent") + _renders.AddRange(go.GetComponentsInChildren(true)); + } + + cnt = _renders.Count; + for (int i = 0; i < cnt; i++) + { + Renderer r = _renders[i]; + if ((r is SkinnedMeshRenderer) || (r is MeshRenderer)) + { + //Set the object rendering in Transparent Queue as UI objects + if (r.sharedMaterial != null) + r.sharedMaterial.renderQueue = 3000; + } + } + } + + void CreateUI_PlayMode() + { + _created = true; + + if (string.IsNullOrEmpty(packageName) || string.IsNullOrEmpty(componentName)) + return; + + _ui = (GComponent)UIPackage.CreateObject(packageName, componentName); + if (_ui != null) + { + _ui.position = position; + if (scale.x != 0 && scale.y != 0) + _ui.scale = scale; + _ui.rotationX = rotation.x; + _ui.rotationY = rotation.y; + _ui.rotation = rotation.z; + if (this.container.hitArea != null) + { + UpdateHitArea(); + _ui.onSizeChanged.Add(UpdateHitArea); + _ui.onPositionChanged.Add(UpdateHitArea); + } + this.container.AddChildAt(_ui.displayObject, 0); + + HandleScreenSizeChanged(); + } + else + Debug.LogError("Create " + packageName + "/" + componentName + " failed!"); + } + + void UpdateHitArea() + { + ColliderHitTest hitArea = this.container.hitArea as ColliderHitTest; + if (hitArea != null) + { + ((BoxCollider)hitArea.collider).center = new Vector3(_ui.xMin + _ui.width / 2, -_ui.yMin - _ui.height / 2); + ((BoxCollider)hitArea.collider).size = _ui.size; + } + } + + void CreateUI_EditMode() + { + if (!EMRenderSupport.packageListReady || UIPackage.GetByName(packageName) == null) + return; + + + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + GObject obj = UIPackage.CreateObject(packageName, componentName); + if (obj != null && !(obj is GComponent)) + { + obj.Dispose(); + Debug.LogWarning("Not a GComponnet: " + packageName + "/" + componentName); + return; + } + _ui = (GComponent)obj; + + if (_ui != null) + { + _ui.displayObject.gameObject.hideFlags |= HideFlags.HideInHierarchy; + _ui.gameObjectName = "UI(AutoGenerated)"; + + _ui.position = position; + if (scale.x != 0 && scale.y != 0) + _ui.scale = scale; + _ui.rotationX = rotation.x; + _ui.rotationY = rotation.y; + _ui.rotation = rotation.z; + this.container.AddChildAt(_ui.displayObject, 0); + + cachedUISize = _ui.size; + uiBounds.size = cachedUISize; + HandleScreenSizeChanged(); + } + } + + void HandleScreenSizeChanged() + { + if (!Application.isPlaying) + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + + screenSizeVer = StageCamera.screenSizeVer; + + int width = Screen.width; + int height = Screen.height; + if (this.container != null) + { + Camera cam = container.GetRenderCamera(); + if (cam.targetDisplay != 0 && cam.targetDisplay < Display.displays.Length) + { + width = Display.displays[cam.targetDisplay].renderingWidth; + height = Display.displays[cam.targetDisplay].renderingHeight; + } + + if (this.container.renderMode != RenderMode.WorldSpace) + { + StageCamera sc = cam.GetComponent(); + if (sc == null) + sc = StageCamera.main.GetComponent(); + this.container.scale = new Vector2(sc.unitsPerPixel * UIContentScaler.scaleFactor, sc.unitsPerPixel * UIContentScaler.scaleFactor); + } + } + + width = Mathf.CeilToInt(width / UIContentScaler.scaleFactor); + height = Mathf.CeilToInt(height / UIContentScaler.scaleFactor); + if (_ui != null) + { + switch (fitScreen) + { + case FitScreen.FitSize: + _ui.SetSize(width, height); + _ui.SetXY(0, 0, true); + break; + + case FitScreen.FitWidthAndSetMiddle: + _ui.SetSize(width, _ui.sourceHeight); + _ui.SetXY(0, (int)((height - _ui.sourceHeight) / 2), true); + break; + + case FitScreen.FitHeightAndSetCenter: + _ui.SetSize(_ui.sourceWidth, height); + _ui.SetXY((int)((width - _ui.sourceWidth) / 2), 0, true); + break; + } + + UpdateHitArea(); + } + else + { + switch (fitScreen) + { + case FitScreen.FitSize: + uiBounds.position = new Vector2(0, 0); + uiBounds.size = new Vector2(width, height); + break; + + case FitScreen.FitWidthAndSetMiddle: + uiBounds.position = new Vector2(0, (int)((height - cachedUISize.y) / 2)); + uiBounds.size = new Vector2(width, cachedUISize.y); + break; + + case FitScreen.FitHeightAndSetCenter: + uiBounds.position = new Vector2((int)((width - cachedUISize.x) / 2), 0); + uiBounds.size = new Vector2(cachedUISize.x, height); + break; + } + } + } + + #region edit mode functions + + void OnUpdateSource(object[] data) + { + if (Application.isPlaying) + return; + + this.packageName = (string)data[0]; + this.packagePath = (string)data[1]; + this.componentName = (string)data[2]; + + if ((bool)data[3]) + { + if (container == null) + return; + + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + } + } + + public void ApplyModifiedProperties(bool sortingOrderChanged, bool fitScreenChanged) + { + if (container != null) + { + container.renderMode = renderMode; + container.renderCamera = renderCamera; + if (sortingOrderChanged) + { + container._panelOrder = sortingOrder; + if (Application.isPlaying) + SetSortingOrder(sortingOrder, true); + else + EMRenderSupport.orderChanged = true; + } + container.fairyBatching = fairyBatching; + } + + if (_ui != null) + { + if (fitScreen == FitScreen.None) + _ui.position = position; + if (scale.x != 0 && scale.y != 0) + _ui.scale = scale; + _ui.rotationX = rotation.x; + _ui.rotationY = rotation.y; + _ui.rotation = rotation.z; + } + if (fitScreen == FitScreen.None) + uiBounds.position = position; + screenSizeVer = 0;//force HandleScreenSizeChanged be called + + if (fitScreenChanged && this.fitScreen == FitScreen.None) + { + if (_ui != null) + _ui.SetSize(_ui.sourceWidth, _ui.sourceHeight); + uiBounds.size = cachedUISize; + } + } + + public void MoveUI(Vector3 delta) + { + if (fitScreen != FitScreen.None) + return; + + this.position += delta; + if (_ui != null) + _ui.position = position; + uiBounds.position = position; + } + + public Vector3 GetUIWorldPosition() + { + if (_ui != null) + return _ui.displayObject.cachedTransform.position; + else + return this.container.cachedTransform.TransformPoint(uiBounds.position); + } + + void OnDrawGizmos() + { + if (Application.isPlaying || this.container == null) + return; + + Vector3 pos, size; + if (_ui != null) + { + Gizmos.matrix = _ui.displayObject.cachedTransform.localToWorldMatrix; + pos = new Vector3(_ui.width / 2, -_ui.height / 2, 0); + size = new Vector3(_ui.width, _ui.height, 0); + } + else + { + Gizmos.matrix = this.container.cachedTransform.localToWorldMatrix; + pos = new Vector3(uiBounds.x + uiBounds.width / 2, -uiBounds.y - uiBounds.height / 2, 0); + size = new Vector3(uiBounds.width, uiBounds.height, 0); + } + + Gizmos.color = new Color(0, 0, 0, 0); + Gizmos.DrawCube(pos, size); + + Gizmos.color = Color.white; + Gizmos.DrawWireCube(pos, size); + } + + public int EM_sortingOrder + { + get { return sortingOrder; } + } + + public void EM_BeforeUpdate() + { + if (container == null) + CreateContainer(); + + if (packageName != null && componentName != null && _ui == null) + CreateUI_EditMode(); + + if (screenSizeVer != StageCamera.screenSizeVer) + HandleScreenSizeChanged(); + } + + public void EM_Update(UpdateContext context) + { + DisplayObject.hideFlags = HideFlags.DontSaveInEditor; + + container.Update(context); + + if (setNativeChildrenOrder) + { + CacheNativeChildrenRenderers(); + + int cnt = _renders.Count; + int sv = context.renderingOrder++; + for (int i = 0; i < cnt; i++) + { + Renderer r = _renders[i]; + if (r != null) + r.sortingOrder = sv; + } + } + } + + public void EM_Reload() + { + if (_ui != null) + { + _ui.Dispose(); + _ui = null; + } + } + + #endregion + } +} diff --git a/Assets/Scripts/UI/UIPanel.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPanel.cs.meta similarity index 100% rename from Assets/Scripts/UI/UIPanel.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/UIPanel.cs.meta diff --git a/Assets/Scripts/UI/Window.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Window.cs similarity index 96% rename from Assets/Scripts/UI/Window.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Window.cs index 997846f8..8a4b6e65 100644 --- a/Assets/Scripts/UI/Window.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Window.cs @@ -1,555 +1,555 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI -{ - /// - /// Window class. - /// 窗口使用前首先要设置窗口中需要显示的内容,这通常是在编辑器里制作好的,可以直接使用Window.contentPane进行设置。 - /// 建议把设置contentPane等初始化操作放置到Window.onInit方法中。 - /// 另外,FairyGUI还提供了一套机制用于窗口动态创建。动态创建是指初始时仅指定窗口需要使用的资源,等窗口需要显示时才实际开始构建窗口的内容。 - /// 首先需要在窗口的构造函数中调用Window.addUISource。这个方法需要一个IUISource类型的参数,而IUISource是一个接口, - /// 用户需要自行实现载入相关UI包的逻辑。当窗口第一次显示之前,IUISource的加载方法将会被调用,并等待载入完成后才返回执行Window.OnInit,然后窗口才会显示。 - /// - /// 如果你需要窗口显示时播放动画效果,那么覆盖doShowAnimation编写你的动画代码,并且在动画结束后调用onShown。覆盖onShown编写其他需要在窗口显示时处理的业务逻辑。 - /// 如果你需要窗口隐藏时播放动画效果,那么覆盖doHideAnimation编写你的动画代码,并且在动画结束时调用Window.hideImmediately(注意不是直接调用onHide!)。覆盖onHide编写其他需要在窗口隐藏时处理的业务逻辑。 - /// - public class Window : GComponent - { - /// - /// - /// - public bool bringToFontOnClick; - - GComponent _frame; - GComponent _contentPane; - GObject _modalWaitPane; - GObject _closeButton; - GObject _dragArea; - GObject _contentArea; - bool _modal; - - List _uiSources; - bool _inited; - bool _loading; - - protected int _requestingCmd; - -#if FAIRYGUI_PUERTS - public Action __onInit; - public Action __onShown; - public Action __onHide; - public Action __doShowAnimation; - public Action __doHideAnimation; -#endif - - public Window() - : base() - { - _uiSources = new List(); - this.tabStopChildren = true; - bringToFontOnClick = UIConfig.bringWindowToFrontOnClick; - - displayObject.onAddedToStage.Add(__addedToStage); - displayObject.onRemovedFromStage.Add(__removeFromStage); - displayObject.onTouchBegin.AddCapture(__touchBegin); - - this.gameObjectName = "Window"; - SetHome(GRoot.inst); - } - - /// - /// Set a UISource to this window. It must call before the window is shown. When the window is first time to show, - /// UISource.Load is called. Only after all UISource is loaded, the window will continue to init. - /// 为窗口添加一个源。这个方法建议在构造函数调用。当窗口第一次显示前,UISource的Load方法将被调用,然后只有所有的UISource - /// 都ready后,窗口才会继续初始化和显示。 - /// - /// - public void AddUISource(IUISource source) - { - _uiSources.Add(source); - } - - /// - /// - /// - public GComponent contentPane - { - set - { - if (_contentPane != value) - { - if (_contentPane != null) - RemoveChild(_contentPane); - _contentPane = value; - if (_contentPane != null) - { - this.gameObjectName = "Window - " + _contentPane.gameObjectName; - _contentPane.gameObjectName = "ContentPane"; - - AddChild(_contentPane); - this.SetSize(_contentPane.width, _contentPane.height); - _contentPane.AddRelation(this, RelationType.Size); - _contentPane.fairyBatching = true; - _frame = _contentPane.GetChild("frame") as GComponent; - if (_frame != null) - { - this.closeButton = _frame.GetChild("closeButton"); - this.dragArea = _frame.GetChild("dragArea"); - this.contentArea = _frame.GetChild("contentArea"); - } - } - else - { - _frame = null; - this.gameObjectName = "Window"; - } - } - } - get - { - return _contentPane; - } - } - - /// - /// - /// - public GComponent frame - { - get { return _frame; } - } - - /// - /// - /// - public GObject closeButton - { - get { return _closeButton; } - set - { - if (_closeButton != null) - _closeButton.onClick.Remove(closeEventHandler); - _closeButton = value; - if (_closeButton != null) - _closeButton.onClick.Add(closeEventHandler); - } - } - - /// - /// - /// - public GObject dragArea - { - get { return _dragArea; } - set - { - if (_dragArea != value) - { - if (_dragArea != null) - { - _dragArea.draggable = false; - _dragArea.onDragStart.Remove(__dragStart); - } - - _dragArea = value; - if (_dragArea != null) - { - GGraph graph = _dragArea as GGraph; - if (graph != null && graph.shape.isEmpty) - graph.DrawRect(_dragArea.width, _dragArea.height, 0, Color.clear, Color.clear); - _dragArea.draggable = true; - _dragArea.onDragStart.Add(__dragStart); - } - } - } - } - - /// - /// - /// - public GObject contentArea - { - get { return _contentArea; } - set { _contentArea = value; } - } - - /// - /// - /// - public GObject modalWaitingPane - { - get { return _modalWaitPane; } - } - - /// - /// - /// - public void Show() - { - GRoot.inst.ShowWindow(this); - } - - /// - /// - /// - /// - public void ShowOn(GRoot r) - { - r.ShowWindow(this); - } - - /// - /// - /// - public void Hide() - { - if (this.isShowing) - DoHideAnimation(); - } - - /// - /// Hide window immediately, no OnHide will be called. - /// - public void HideImmediately() - { - this.root.HideWindowImmediately(this); - } - - /// - /// Make the window be center of the screen. - /// - /// - /// Add relations to ensure keeping center on screen size changed. - public void CenterOn(GRoot r, bool restraint) - { - this.SetXY((int)((r.width - this.width) / 2), (int)((r.height - this.height) / 2)); - if (restraint) - { - this.AddRelation(r, RelationType.Center_Center); - this.AddRelation(r, RelationType.Middle_Middle); - } - } - - /// - /// Switch show and hide status. - /// - public void ToggleStatus() - { - if (isTop) - Hide(); - else - Show(); - } - - /// - /// - /// - public bool isShowing - { - get { return parent != null; } - } - - /// - /// - /// - public bool isTop - { - get { return parent != null && parent.GetChildIndex(this) == parent.numChildren - 1; } - } - - /// - /// - /// - public bool modal - { - get { return _modal; } - set { _modal = value; } - } - - /// - /// - /// - public void BringToFront() - { - this.root.BringToFront(this); - } - - /// - /// - /// - public void ShowModalWait() - { - ShowModalWait(0); - } - - /// - /// Display a modal waiting sign in the front. - /// 显示一个等待标志在最前面。等待标志的资源可以通过UIConfig.windowModalWaiting。等待标志组件会设置为屏幕大小,请内部做好关联。 - /// 还可以设定一个requestingCmd作为等待的命令字,在CloseModalWait里传入相同的命令字ModalWait将结束,否则CloseModalWait无效。 - /// - /// - public void ShowModalWait(int requestingCmd) - { - if (requestingCmd != 0) - _requestingCmd = requestingCmd; - - if (UIConfig.windowModalWaiting != null) - { - if (_modalWaitPane == null) - { - _modalWaitPane = UIPackage.CreateObjectFromURL(UIConfig.windowModalWaiting); - _modalWaitPane.SetHome(this); - } - - LayoutModalWaitPane(); - - AddChild(_modalWaitPane); - } - } - - virtual protected void LayoutModalWaitPane() - { - if (_contentArea != null) - { - Vector2 pt = _frame.LocalToGlobal(Vector2.zero); - pt = this.GlobalToLocal(pt); - _modalWaitPane.SetXY((int)pt.x + _contentArea.x, (int)pt.y + _contentArea.y); - _modalWaitPane.SetSize(_contentArea.width, _contentArea.height); - } - else - _modalWaitPane.SetSize(this.width, this.height); - } - - /// - /// - /// - /// - public bool CloseModalWait() - { - return CloseModalWait(0); - } - - /// - /// Close modal waiting. If rquestingCmd is equal to the value you transfer in ShowModalWait, mowal wait will be closed. - /// Otherwise, this function has no effect. - /// 关闭模式等待。如果requestingCmd和ShowModalWait传入的不相同,则这个函数没有任何动作,立即返回。 - /// - /// - /// - public bool CloseModalWait(int requestingCmd) - { - if (requestingCmd != 0) - { - if (_requestingCmd != requestingCmd) - return false; - } - _requestingCmd = 0; - - if (_modalWaitPane != null && _modalWaitPane.parent != null) - RemoveChild(_modalWaitPane); - - return true; - } - - /// - /// - /// - public bool modalWaiting - { - get { return (_modalWaitPane != null) && _modalWaitPane.inContainer; } - } - - /// - /// - /// - public void Init() - { - if (_inited || _loading) - return; - - if (_uiSources.Count > 0) - { - _loading = false; - int cnt = _uiSources.Count; - for (int i = 0; i < cnt; i++) - { - IUISource lib = _uiSources[i]; - if (!lib.loaded) - { - lib.Load(__uiLoadComplete); - _loading = true; - } - } - - if (!_loading) - _init(); - } - else - _init(); - } - - /// - /// - /// - virtual protected void OnInit() - { -#if FAIRYGUI_TOLUA - CallLua("OnInit"); -#endif -#if FAIRYGUI_PUERTS - if (__onInit != null) - __onInit(); -#endif - } - - /// - /// - /// - virtual protected void OnShown() - { -#if FAIRYGUI_TOLUA - CallLua("OnShown"); -#endif -#if FAIRYGUI_PUERTS - if (__onShown != null) - __onShown(); -#endif - } - - /// - /// - /// - virtual protected void OnHide() - { -#if FAIRYGUI_TOLUA - CallLua("OnHide"); -#endif -#if FAIRYGUI_PUERTS - if (__onHide != null) - __onHide(); -#endif - } - - /// - /// - /// - virtual protected void DoShowAnimation() - { -#if FAIRYGUI_TOLUA - if (!CallLua("DoShowAnimation")) - OnShown(); -#elif FAIRYGUI_PUERTS - if (__doShowAnimation != null) - __doShowAnimation(); - else - OnShown(); -#else - OnShown(); -#endif - } - - /// - /// - /// - virtual protected void DoHideAnimation() - { -#if FAIRYGUI_TOLUA - if (!CallLua("DoHideAnimation")) - HideImmediately(); -#elif FAIRYGUI_PUERTS - if (__doHideAnimation != null) - __doHideAnimation(); - else - HideImmediately(); -#else - HideImmediately(); -#endif - } - - void __uiLoadComplete() - { - int cnt = _uiSources.Count; - for (int i = 0; i < cnt; i++) - { - IUISource lib = _uiSources[i]; - if (!lib.loaded) - return; - } - - _loading = false; - _init(); - } - - void _init() - { - _inited = true; - OnInit(); - - if (this.isShowing) - DoShowAnimation(); - } - - override public void Dispose() - { - if (_modalWaitPane != null && _modalWaitPane.parent == null) - _modalWaitPane.Dispose(); - - - //正在加载资源的异步过程中发生意外关闭 应该取消正在加载的load - if (_loading) - { - for (int i = 0; i < _uiSources.Count; ++i) - { - _uiSources[i].Cancel(); - } - } - - -#if FAIRYGUI_PUERTS - __onInit = null; - __onShown = null; - __onHide = null; - __doShowAnimation = null; - __doHideAnimation = null; -#endif - - base.Dispose(); - } - - virtual protected void closeEventHandler(EventContext context) - { - Hide(); - } - - void __addedToStage() - { - if (!_inited) - Init(); - else - DoShowAnimation(); - } - - void __removeFromStage() - { - CloseModalWait(); - OnHide(); - } - - private void __touchBegin(EventContext context) - { - if (this.isShowing && bringToFontOnClick) - { - BringToFront(); - } - } - - private void __dragStart(EventContext context) - { - context.PreventDefault(); - - this.StartDrag((int)context.data); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI +{ + /// + /// Window class. + /// 窗口使用前首先要设置窗口中需要显示的内容,这通常是在编辑器里制作好的,可以直接使用Window.contentPane进行设置。 + /// 建议把设置contentPane等初始化操作放置到Window.onInit方法中。 + /// 另外,FairyGUI还提供了一套机制用于窗口动态创建。动态创建是指初始时仅指定窗口需要使用的资源,等窗口需要显示时才实际开始构建窗口的内容。 + /// 首先需要在窗口的构造函数中调用Window.addUISource。这个方法需要一个IUISource类型的参数,而IUISource是一个接口, + /// 用户需要自行实现载入相关UI包的逻辑。当窗口第一次显示之前,IUISource的加载方法将会被调用,并等待载入完成后才返回执行Window.OnInit,然后窗口才会显示。 + /// + /// 如果你需要窗口显示时播放动画效果,那么覆盖doShowAnimation编写你的动画代码,并且在动画结束后调用onShown。覆盖onShown编写其他需要在窗口显示时处理的业务逻辑。 + /// 如果你需要窗口隐藏时播放动画效果,那么覆盖doHideAnimation编写你的动画代码,并且在动画结束时调用Window.hideImmediately(注意不是直接调用onHide!)。覆盖onHide编写其他需要在窗口隐藏时处理的业务逻辑。 + /// + public class Window : GComponent + { + /// + /// + /// + public bool bringToFontOnClick; + + GComponent _frame; + GComponent _contentPane; + GObject _modalWaitPane; + GObject _closeButton; + GObject _dragArea; + GObject _contentArea; + bool _modal; + + List _uiSources; + bool _inited; + bool _loading; + + protected int _requestingCmd; + +#if FAIRYGUI_PUERTS + public Action __onInit; + public Action __onShown; + public Action __onHide; + public Action __doShowAnimation; + public Action __doHideAnimation; +#endif + + public Window() + : base() + { + _uiSources = new List(); + this.tabStopChildren = true; + bringToFontOnClick = UIConfig.bringWindowToFrontOnClick; + + displayObject.onAddedToStage.Add(__addedToStage); + displayObject.onRemovedFromStage.Add(__removeFromStage); + displayObject.onTouchBegin.AddCapture(__touchBegin); + + this.gameObjectName = "Window"; + SetHome(GRoot.inst); + } + + /// + /// Set a UISource to this window. It must call before the window is shown. When the window is first time to show, + /// UISource.Load is called. Only after all UISource is loaded, the window will continue to init. + /// 为窗口添加一个源。这个方法建议在构造函数调用。当窗口第一次显示前,UISource的Load方法将被调用,然后只有所有的UISource + /// 都ready后,窗口才会继续初始化和显示。 + /// + /// + public void AddUISource(IUISource source) + { + _uiSources.Add(source); + } + + /// + /// + /// + public GComponent contentPane + { + set + { + if (_contentPane != value) + { + if (_contentPane != null) + RemoveChild(_contentPane); + _contentPane = value; + if (_contentPane != null) + { + this.gameObjectName = "Window - " + _contentPane.gameObjectName; + _contentPane.gameObjectName = "ContentPane"; + + AddChild(_contentPane); + this.SetSize(_contentPane.width, _contentPane.height); + _contentPane.AddRelation(this, RelationType.Size); + _contentPane.fairyBatching = true; + _frame = _contentPane.GetChild("frame") as GComponent; + if (_frame != null) + { + this.closeButton = _frame.GetChild("closeButton"); + this.dragArea = _frame.GetChild("dragArea"); + this.contentArea = _frame.GetChild("contentArea"); + } + } + else + { + _frame = null; + this.gameObjectName = "Window"; + } + } + } + get + { + return _contentPane; + } + } + + /// + /// + /// + public GComponent frame + { + get { return _frame; } + } + + /// + /// + /// + public GObject closeButton + { + get { return _closeButton; } + set + { + if (_closeButton != null) + _closeButton.onClick.Remove(closeEventHandler); + _closeButton = value; + if (_closeButton != null) + _closeButton.onClick.Add(closeEventHandler); + } + } + + /// + /// + /// + public GObject dragArea + { + get { return _dragArea; } + set + { + if (_dragArea != value) + { + if (_dragArea != null) + { + _dragArea.draggable = false; + _dragArea.onDragStart.Remove(__dragStart); + } + + _dragArea = value; + if (_dragArea != null) + { + GGraph graph = _dragArea as GGraph; + if (graph != null && graph.shape.isEmpty) + graph.DrawRect(_dragArea.width, _dragArea.height, 0, Color.clear, Color.clear); + _dragArea.draggable = true; + _dragArea.onDragStart.Add(__dragStart); + } + } + } + } + + /// + /// + /// + public GObject contentArea + { + get { return _contentArea; } + set { _contentArea = value; } + } + + /// + /// + /// + public GObject modalWaitingPane + { + get { return _modalWaitPane; } + } + + /// + /// + /// + public void Show() + { + GRoot.inst.ShowWindow(this); + } + + /// + /// + /// + /// + public void ShowOn(GRoot r) + { + r.ShowWindow(this); + } + + /// + /// + /// + public void Hide() + { + if (this.isShowing) + DoHideAnimation(); + } + + /// + /// Hide window immediately, no OnHide will be called. + /// + public void HideImmediately() + { + this.root.HideWindowImmediately(this); + } + + /// + /// Make the window be center of the screen. + /// + /// + /// Add relations to ensure keeping center on screen size changed. + public void CenterOn(GRoot r, bool restraint) + { + this.SetXY((int)((r.width - this.width) / 2), (int)((r.height - this.height) / 2)); + if (restraint) + { + this.AddRelation(r, RelationType.Center_Center); + this.AddRelation(r, RelationType.Middle_Middle); + } + } + + /// + /// Switch show and hide status. + /// + public void ToggleStatus() + { + if (isTop) + Hide(); + else + Show(); + } + + /// + /// + /// + public bool isShowing + { + get { return parent != null; } + } + + /// + /// + /// + public bool isTop + { + get { return parent != null && parent.GetChildIndex(this) == parent.numChildren - 1; } + } + + /// + /// + /// + public bool modal + { + get { return _modal; } + set { _modal = value; } + } + + /// + /// + /// + public void BringToFront() + { + this.root.BringToFront(this); + } + + /// + /// + /// + public void ShowModalWait() + { + ShowModalWait(0); + } + + /// + /// Display a modal waiting sign in the front. + /// 显示一个等待标志在最前面。等待标志的资源可以通过UIConfig.windowModalWaiting。等待标志组件会设置为屏幕大小,请内部做好关联。 + /// 还可以设定一个requestingCmd作为等待的命令字,在CloseModalWait里传入相同的命令字ModalWait将结束,否则CloseModalWait无效。 + /// + /// + public void ShowModalWait(int requestingCmd) + { + if (requestingCmd != 0) + _requestingCmd = requestingCmd; + + if (UIConfig.windowModalWaiting != null) + { + if (_modalWaitPane == null) + { + _modalWaitPane = UIPackage.CreateObjectFromURL(UIConfig.windowModalWaiting); + _modalWaitPane.SetHome(this); + } + + LayoutModalWaitPane(); + + AddChild(_modalWaitPane); + } + } + + virtual protected void LayoutModalWaitPane() + { + if (_contentArea != null) + { + Vector2 pt = _frame.LocalToGlobal(Vector2.zero); + pt = this.GlobalToLocal(pt); + _modalWaitPane.SetXY((int)pt.x + _contentArea.x, (int)pt.y + _contentArea.y); + _modalWaitPane.SetSize(_contentArea.width, _contentArea.height); + } + else + _modalWaitPane.SetSize(this.width, this.height); + } + + /// + /// + /// + /// + public bool CloseModalWait() + { + return CloseModalWait(0); + } + + /// + /// Close modal waiting. If rquestingCmd is equal to the value you transfer in ShowModalWait, mowal wait will be closed. + /// Otherwise, this function has no effect. + /// 关闭模式等待。如果requestingCmd和ShowModalWait传入的不相同,则这个函数没有任何动作,立即返回。 + /// + /// + /// + public bool CloseModalWait(int requestingCmd) + { + if (requestingCmd != 0) + { + if (_requestingCmd != requestingCmd) + return false; + } + _requestingCmd = 0; + + if (_modalWaitPane != null && _modalWaitPane.parent != null) + RemoveChild(_modalWaitPane); + + return true; + } + + /// + /// + /// + public bool modalWaiting + { + get { return (_modalWaitPane != null) && _modalWaitPane.inContainer; } + } + + /// + /// + /// + public void Init() + { + if (_inited || _loading) + return; + + if (_uiSources.Count > 0) + { + _loading = false; + int cnt = _uiSources.Count; + for (int i = 0; i < cnt; i++) + { + IUISource lib = _uiSources[i]; + if (!lib.loaded) + { + lib.Load(__uiLoadComplete); + _loading = true; + } + } + + if (!_loading) + _init(); + } + else + _init(); + } + + /// + /// + /// + virtual protected void OnInit() + { +#if FAIRYGUI_TOLUA + CallLua("OnInit"); +#endif +#if FAIRYGUI_PUERTS + if (__onInit != null) + __onInit(); +#endif + } + + /// + /// + /// + virtual protected void OnShown() + { +#if FAIRYGUI_TOLUA + CallLua("OnShown"); +#endif +#if FAIRYGUI_PUERTS + if (__onShown != null) + __onShown(); +#endif + } + + /// + /// + /// + virtual protected void OnHide() + { +#if FAIRYGUI_TOLUA + CallLua("OnHide"); +#endif +#if FAIRYGUI_PUERTS + if (__onHide != null) + __onHide(); +#endif + } + + /// + /// + /// + virtual protected void DoShowAnimation() + { +#if FAIRYGUI_TOLUA + if (!CallLua("DoShowAnimation")) + OnShown(); +#elif FAIRYGUI_PUERTS + if (__doShowAnimation != null) + __doShowAnimation(); + else + OnShown(); +#else + OnShown(); +#endif + } + + /// + /// + /// + virtual protected void DoHideAnimation() + { +#if FAIRYGUI_TOLUA + if (!CallLua("DoHideAnimation")) + HideImmediately(); +#elif FAIRYGUI_PUERTS + if (__doHideAnimation != null) + __doHideAnimation(); + else + HideImmediately(); +#else + HideImmediately(); +#endif + } + + void __uiLoadComplete() + { + int cnt = _uiSources.Count; + for (int i = 0; i < cnt; i++) + { + IUISource lib = _uiSources[i]; + if (!lib.loaded) + return; + } + + _loading = false; + _init(); + } + + void _init() + { + _inited = true; + OnInit(); + + if (this.isShowing) + DoShowAnimation(); + } + + override public void Dispose() + { + if (_modalWaitPane != null && _modalWaitPane.parent == null) + _modalWaitPane.Dispose(); + + + //正在加载资源的异步过程中发生意外关闭 应该取消正在加载的load + if (_loading) + { + for (int i = 0; i < _uiSources.Count; ++i) + { + _uiSources[i].Cancel(); + } + } + + +#if FAIRYGUI_PUERTS + __onInit = null; + __onShown = null; + __onHide = null; + __doShowAnimation = null; + __doHideAnimation = null; +#endif + + base.Dispose(); + } + + virtual protected void closeEventHandler(EventContext context) + { + Hide(); + } + + void __addedToStage() + { + if (!_inited) + Init(); + else + DoShowAnimation(); + } + + void __removeFromStage() + { + CloseModalWait(); + OnHide(); + } + + private void __touchBegin(EventContext context) + { + if (this.isShowing && bringToFontOnClick) + { + BringToFront(); + } + } + + private void __dragStart(EventContext context) + { + context.PreventDefault(); + + this.StartDrag((int)context.data); + } + } +} diff --git a/Assets/Scripts/UI/Window.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Window.cs.meta similarity index 100% rename from Assets/Scripts/UI/Window.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/UI/Window.cs.meta diff --git a/Assets/Scripts/Utils.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils.meta similarity index 100% rename from Assets/Scripts/Utils.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils.meta diff --git a/Assets/Scripts/Utils/ByteBuffer.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ByteBuffer.cs similarity index 96% rename from Assets/Scripts/Utils/ByteBuffer.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ByteBuffer.cs index abf95589..878be226 100644 --- a/Assets/Scripts/Utils/ByteBuffer.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ByteBuffer.cs @@ -1,455 +1,455 @@ -using System; -using System.Text; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class ByteBuffer - { - /// - /// - /// - public bool littleEndian; - - /// - /// - /// - public string[] stringTable; - - /// - /// - /// - public int version; - - int _pointer; - int _offset; - int _length; - byte[] _data; - - static byte[] temp = new byte[8]; - - /// - /// - /// - /// - /// - /// - public ByteBuffer(byte[] data, int offset = 0, int length = -1) - { - _data = data; - _pointer = 0; - _offset = offset; - if (length < 0) - _length = data.Length - offset; - else - _length = length; - littleEndian = false; - } - - /// - /// - /// - public int position - { - get { return _pointer; } - set { _pointer = value; } - } - - /// - /// - /// - public int length - { - get { return _length; } - } - - /// - /// - /// - public bool bytesAvailable - { - get { return _pointer < _length; } - } - - /// - /// - /// - public byte[] buffer - { - get { return _data; } - set - { - _data = value; - _pointer = 0; - _offset = 0; - _length = _data.Length; - } - } - - /// - /// - /// - /// - /// - public int Skip(int count) - { - _pointer += count; - return _pointer; - } - - /// - /// - /// - /// - public byte ReadByte() - { - return _data[_offset + _pointer++]; - } - - /// - /// - /// - /// - /// - /// - /// - public byte[] ReadBytes(byte[] output, int destIndex, int count) - { - if (count > _length - _pointer) - throw new ArgumentOutOfRangeException(); - - Array.Copy(_data, _offset + _pointer, output, destIndex, count); - _pointer += count; - return output; - } - - /// - /// - /// - /// - /// - public byte[] ReadBytes(int count) - { - if (count > _length - _pointer) - throw new ArgumentOutOfRangeException(); - - byte[] result = new byte[count]; - Array.Copy(_data, _offset + _pointer, result, 0, count); - _pointer += count; - return result; - } - - /// - /// - /// - /// - public ByteBuffer ReadBuffer() - { - int count = ReadInt(); - ByteBuffer ba = new ByteBuffer(_data, _pointer, count); - ba.stringTable = stringTable; - ba.version = version; - _pointer += count; - return ba; - } - - /// - /// - /// - /// - public char ReadChar() - { - return (char)ReadShort(); - } - - /// - /// - /// - /// - public bool ReadBool() - { - bool result = _data[_offset + _pointer] == 1; - _pointer++; - return result; - } - - /// - /// - /// - /// - public short ReadShort() - { - int startIndex = _offset + _pointer; - _pointer += 2; - if (littleEndian) - return (short)(_data[startIndex] | (_data[startIndex + 1] << 8)); - else - return (short)((_data[startIndex] << 8) | _data[startIndex + 1]); - } - - /// - /// - /// - /// - public ushort ReadUshort() - { - return (ushort)ReadShort(); - } - - /// - /// - /// - /// - public int ReadInt() - { - int startIndex = _offset + _pointer; - _pointer += 4; - if (littleEndian) - return (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24); - else - return (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]); - } - - /// - /// - /// - /// - public uint ReadUint() - { - return (uint)ReadInt(); - } - - /// - /// - /// - /// - public float ReadFloat() - { - int startIndex = _offset + _pointer; - _pointer += 4; - if (littleEndian == BitConverter.IsLittleEndian) - return BitConverter.ToSingle(_data, startIndex); - else - { - temp[3] = _data[startIndex]; - temp[2] = _data[startIndex + 1]; - temp[1] = _data[startIndex + 2]; - temp[0] = _data[startIndex + 3]; - return BitConverter.ToSingle(temp, 0); - } - } - - /// - /// - /// - /// - public long ReadLong() - { - int startIndex = _offset + _pointer; - _pointer += 8; - if (littleEndian) - { - int i1 = (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24); - int i2 = (_data[startIndex + 4]) | (_data[startIndex + 5] << 8) | (_data[startIndex + 6] << 16) | (_data[startIndex + 7] << 24); - return (uint)i1 | ((long)i2 << 32); - } - else - { - int i1 = (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]); - int i2 = (_data[startIndex + 4] << 24) | (_data[startIndex + 5] << 16) | (_data[startIndex + 6] << 8) | (_data[startIndex + 7]); - return (uint)i2 | ((long)i1 << 32); - } - } - - /// - /// - /// - /// - public double ReadDouble() - { - int startIndex = _offset + _pointer; - _pointer += 8; - if (littleEndian == BitConverter.IsLittleEndian) - return BitConverter.ToDouble(_data, startIndex); - else - { - temp[7] = _data[startIndex]; - temp[6] = _data[startIndex + 1]; - temp[5] = _data[startIndex + 2]; - temp[4] = _data[startIndex + 3]; - temp[3] = _data[startIndex + 4]; - temp[2] = _data[startIndex + 5]; - temp[1] = _data[startIndex + 6]; - temp[0] = _data[startIndex + 7]; - return BitConverter.ToSingle(temp, 0); - } - } - - /// - /// - /// - /// - public string ReadString() - { - ushort len = ReadUshort(); - string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len); - _pointer += len; - return result; - } - - /// - /// - /// - /// - /// - public string ReadString(int len) - { - string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len); - _pointer += len; - return result; - } - - /// - /// - /// - /// - public string ReadS() - { - int index = ReadUshort(); - if (index == 65534) //null - return null; - else if (index == 65533) - return string.Empty; - else - return stringTable[index]; - } - - /// - /// - /// - /// - /// - public string[] ReadSArray(int cnt) - { - string[] ret = new string[cnt]; - for (int i = 0; i < cnt; i++) - ret[i] = ReadS(); - - return ret; - } - - private static List helperPoints = new List(); - - /// - /// - /// - /// - public List ReadPath() - { - helperPoints.Clear(); - - int len = ReadInt(); - if (len == 0) - return helperPoints; - - for (int i = 0; i < len; i++) - { - GPathPoint.CurveType curveType = (GPathPoint.CurveType)ReadByte(); - switch (curveType) - { - case GPathPoint.CurveType.Bezier: - helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), - new Vector3(ReadFloat(), ReadFloat(), 0))); - break; - - case GPathPoint.CurveType.CubicBezier: - helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), - new Vector3(ReadFloat(), ReadFloat(), 0), - new Vector3(ReadFloat(), ReadFloat(), 0))); - break; - - default: - helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), curveType)); - break; - } - } - - return helperPoints; - } - - /// - /// - /// - /// - public void WriteS(string value) - { - int index = ReadUshort(); - if (index != 65534 && index != 65533) - stringTable[index] = value; - } - - /// - /// - /// - /// - public Color ReadColor() - { - int startIndex = _offset + _pointer; - byte r = _data[startIndex]; - byte g = _data[startIndex + 1]; - byte b = _data[startIndex + 2]; - byte a = _data[startIndex + 3]; - _pointer += 4; - - return new Color32(r, g, b, a); - } - - /// - /// - /// - /// - /// - /// - public bool Seek(int indexTablePos, int blockIndex) - { - int tmp = _pointer; - _pointer = indexTablePos; - int segCount = _data[_offset + _pointer++]; - if (blockIndex < segCount) - { - bool useShort = _data[_offset + _pointer++] == 1; - int newPos; - if (useShort) - { - _pointer += 2 * blockIndex; - newPos = ReadShort(); - } - else - { - _pointer += 4 * blockIndex; - newPos = ReadInt(); - } - - if (newPos > 0) - { - _pointer = indexTablePos + newPos; - return true; - } - else - { - _pointer = tmp; - return false; - } - } - else - { - _pointer = tmp; - return false; - } - } - } -} +using System; +using System.Text; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class ByteBuffer + { + /// + /// + /// + public bool littleEndian; + + /// + /// + /// + public string[] stringTable; + + /// + /// + /// + public int version; + + int _pointer; + int _offset; + int _length; + byte[] _data; + + static byte[] temp = new byte[8]; + + /// + /// + /// + /// + /// + /// + public ByteBuffer(byte[] data, int offset = 0, int length = -1) + { + _data = data; + _pointer = 0; + _offset = offset; + if (length < 0) + _length = data.Length - offset; + else + _length = length; + littleEndian = false; + } + + /// + /// + /// + public int position + { + get { return _pointer; } + set { _pointer = value; } + } + + /// + /// + /// + public int length + { + get { return _length; } + } + + /// + /// + /// + public bool bytesAvailable + { + get { return _pointer < _length; } + } + + /// + /// + /// + public byte[] buffer + { + get { return _data; } + set + { + _data = value; + _pointer = 0; + _offset = 0; + _length = _data.Length; + } + } + + /// + /// + /// + /// + /// + public int Skip(int count) + { + _pointer += count; + return _pointer; + } + + /// + /// + /// + /// + public byte ReadByte() + { + return _data[_offset + _pointer++]; + } + + /// + /// + /// + /// + /// + /// + /// + public byte[] ReadBytes(byte[] output, int destIndex, int count) + { + if (count > _length - _pointer) + throw new ArgumentOutOfRangeException(); + + Array.Copy(_data, _offset + _pointer, output, destIndex, count); + _pointer += count; + return output; + } + + /// + /// + /// + /// + /// + public byte[] ReadBytes(int count) + { + if (count > _length - _pointer) + throw new ArgumentOutOfRangeException(); + + byte[] result = new byte[count]; + Array.Copy(_data, _offset + _pointer, result, 0, count); + _pointer += count; + return result; + } + + /// + /// + /// + /// + public ByteBuffer ReadBuffer() + { + int count = ReadInt(); + ByteBuffer ba = new ByteBuffer(_data, _pointer, count); + ba.stringTable = stringTable; + ba.version = version; + _pointer += count; + return ba; + } + + /// + /// + /// + /// + public char ReadChar() + { + return (char)ReadShort(); + } + + /// + /// + /// + /// + public bool ReadBool() + { + bool result = _data[_offset + _pointer] == 1; + _pointer++; + return result; + } + + /// + /// + /// + /// + public short ReadShort() + { + int startIndex = _offset + _pointer; + _pointer += 2; + if (littleEndian) + return (short)(_data[startIndex] | (_data[startIndex + 1] << 8)); + else + return (short)((_data[startIndex] << 8) | _data[startIndex + 1]); + } + + /// + /// + /// + /// + public ushort ReadUshort() + { + return (ushort)ReadShort(); + } + + /// + /// + /// + /// + public int ReadInt() + { + int startIndex = _offset + _pointer; + _pointer += 4; + if (littleEndian) + return (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24); + else + return (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]); + } + + /// + /// + /// + /// + public uint ReadUint() + { + return (uint)ReadInt(); + } + + /// + /// + /// + /// + public float ReadFloat() + { + int startIndex = _offset + _pointer; + _pointer += 4; + if (littleEndian == BitConverter.IsLittleEndian) + return BitConverter.ToSingle(_data, startIndex); + else + { + temp[3] = _data[startIndex]; + temp[2] = _data[startIndex + 1]; + temp[1] = _data[startIndex + 2]; + temp[0] = _data[startIndex + 3]; + return BitConverter.ToSingle(temp, 0); + } + } + + /// + /// + /// + /// + public long ReadLong() + { + int startIndex = _offset + _pointer; + _pointer += 8; + if (littleEndian) + { + int i1 = (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24); + int i2 = (_data[startIndex + 4]) | (_data[startIndex + 5] << 8) | (_data[startIndex + 6] << 16) | (_data[startIndex + 7] << 24); + return (uint)i1 | ((long)i2 << 32); + } + else + { + int i1 = (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]); + int i2 = (_data[startIndex + 4] << 24) | (_data[startIndex + 5] << 16) | (_data[startIndex + 6] << 8) | (_data[startIndex + 7]); + return (uint)i2 | ((long)i1 << 32); + } + } + + /// + /// + /// + /// + public double ReadDouble() + { + int startIndex = _offset + _pointer; + _pointer += 8; + if (littleEndian == BitConverter.IsLittleEndian) + return BitConverter.ToDouble(_data, startIndex); + else + { + temp[7] = _data[startIndex]; + temp[6] = _data[startIndex + 1]; + temp[5] = _data[startIndex + 2]; + temp[4] = _data[startIndex + 3]; + temp[3] = _data[startIndex + 4]; + temp[2] = _data[startIndex + 5]; + temp[1] = _data[startIndex + 6]; + temp[0] = _data[startIndex + 7]; + return BitConverter.ToSingle(temp, 0); + } + } + + /// + /// + /// + /// + public string ReadString() + { + ushort len = ReadUshort(); + string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len); + _pointer += len; + return result; + } + + /// + /// + /// + /// + /// + public string ReadString(int len) + { + string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len); + _pointer += len; + return result; + } + + /// + /// + /// + /// + public string ReadS() + { + int index = ReadUshort(); + if (index == 65534) //null + return null; + else if (index == 65533) + return string.Empty; + else + return stringTable[index]; + } + + /// + /// + /// + /// + /// + public string[] ReadSArray(int cnt) + { + string[] ret = new string[cnt]; + for (int i = 0; i < cnt; i++) + ret[i] = ReadS(); + + return ret; + } + + private static List helperPoints = new List(); + + /// + /// + /// + /// + public List ReadPath() + { + helperPoints.Clear(); + + int len = ReadInt(); + if (len == 0) + return helperPoints; + + for (int i = 0; i < len; i++) + { + GPathPoint.CurveType curveType = (GPathPoint.CurveType)ReadByte(); + switch (curveType) + { + case GPathPoint.CurveType.Bezier: + helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), + new Vector3(ReadFloat(), ReadFloat(), 0))); + break; + + case GPathPoint.CurveType.CubicBezier: + helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), + new Vector3(ReadFloat(), ReadFloat(), 0), + new Vector3(ReadFloat(), ReadFloat(), 0))); + break; + + default: + helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), curveType)); + break; + } + } + + return helperPoints; + } + + /// + /// + /// + /// + public void WriteS(string value) + { + int index = ReadUshort(); + if (index != 65534 && index != 65533) + stringTable[index] = value; + } + + /// + /// + /// + /// + public Color ReadColor() + { + int startIndex = _offset + _pointer; + byte r = _data[startIndex]; + byte g = _data[startIndex + 1]; + byte b = _data[startIndex + 2]; + byte a = _data[startIndex + 3]; + _pointer += 4; + + return new Color32(r, g, b, a); + } + + /// + /// + /// + /// + /// + /// + public bool Seek(int indexTablePos, int blockIndex) + { + int tmp = _pointer; + _pointer = indexTablePos; + int segCount = _data[_offset + _pointer++]; + if (blockIndex < segCount) + { + bool useShort = _data[_offset + _pointer++] == 1; + int newPos; + if (useShort) + { + _pointer += 2 * blockIndex; + newPos = ReadShort(); + } + else + { + _pointer += 4 * blockIndex; + newPos = ReadInt(); + } + + if (newPos > 0) + { + _pointer = indexTablePos + newPos; + return true; + } + else + { + _pointer = tmp; + return false; + } + } + else + { + _pointer = tmp; + return false; + } + } + } +} diff --git a/Assets/Scripts/Utils/ByteBuffer.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ByteBuffer.cs.meta similarity index 100% rename from Assets/Scripts/Utils/ByteBuffer.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ByteBuffer.cs.meta diff --git a/Assets/Scripts/Utils/Html.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html.meta similarity index 100% rename from Assets/Scripts/Utils/Html.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html.meta diff --git a/Assets/Scripts/Utils/Html/HtmlButton.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlButton.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlButton.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlButton.cs index 740c5bd1..ab9a3292 100644 --- a/Assets/Scripts/Utils/Html/HtmlButton.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlButton.cs @@ -1,104 +1,104 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlButton : IHtmlObject - { - public GComponent button { get; private set; } - - public const string CLICK_EVENT = "OnHtmlButtonClick"; - - public static string resource; - - RichTextField _owner; - HtmlElement _element; - EventCallback1 _clickHandler; - - public HtmlButton() - { - if (resource != null) - { - button = UIPackage.CreateObjectFromURL(resource).asCom; - _clickHandler = (EventContext context) => - { - _owner.DispatchEvent(CLICK_EVENT, context.data, this); - }; - } - else - Debug.LogWarning("FairyGUI: Set HtmlButton.resource first"); - } - - public DisplayObject displayObject - { - get { return button != null ? button.displayObject : null; } - } - - public HtmlElement element - { - get { return _element; } - } - - public float width - { - get { return button != null ? button.width : 0; } - } - - public float height - { - get { return button != null ? button.height : 0; } - } - - public void Create(RichTextField owner, HtmlElement element) - { - _owner = owner; - _element = element; - - if (button == null) - return; - - button.onClick.Add(_clickHandler); - int width = element.GetInt("width", button.sourceWidth); - int height = element.GetInt("height", button.sourceHeight); - button.SetSize(width, height); - button.text = element.GetString("value"); - } - - public void SetPosition(float x, float y) - { - if (button != null) - button.SetXY(x, y); - } - - public void Add() - { - if (button != null) - _owner.AddChild(button.displayObject); - } - - public void Remove() - { - if (button != null && button.displayObject.parent != null) - _owner.RemoveChild(button.displayObject); - } - - public void Release() - { - if (button != null) - button.RemoveEventListeners(); - - _owner = null; - _element = null; - } - - public void Dispose() - { - if (button != null) - button.Dispose(); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlButton : IHtmlObject + { + public GComponent button { get; private set; } + + public const string CLICK_EVENT = "OnHtmlButtonClick"; + + public static string resource; + + RichTextField _owner; + HtmlElement _element; + EventCallback1 _clickHandler; + + public HtmlButton() + { + if (resource != null) + { + button = UIPackage.CreateObjectFromURL(resource).asCom; + _clickHandler = (EventContext context) => + { + _owner.DispatchEvent(CLICK_EVENT, context.data, this); + }; + } + else + Debug.LogWarning("FairyGUI: Set HtmlButton.resource first"); + } + + public DisplayObject displayObject + { + get { return button != null ? button.displayObject : null; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return button != null ? button.width : 0; } + } + + public float height + { + get { return button != null ? button.height : 0; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + if (button == null) + return; + + button.onClick.Add(_clickHandler); + int width = element.GetInt("width", button.sourceWidth); + int height = element.GetInt("height", button.sourceHeight); + button.SetSize(width, height); + button.text = element.GetString("value"); + } + + public void SetPosition(float x, float y) + { + if (button != null) + button.SetXY(x, y); + } + + public void Add() + { + if (button != null) + _owner.AddChild(button.displayObject); + } + + public void Remove() + { + if (button != null && button.displayObject.parent != null) + _owner.RemoveChild(button.displayObject); + } + + public void Release() + { + if (button != null) + button.RemoveEventListeners(); + + _owner = null; + _element = null; + } + + public void Dispose() + { + if (button != null) + button.Dispose(); + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlButton.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlButton.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlButton.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlButton.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlElement.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlElement.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlElement.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlElement.cs index 4cdbc47d..4ec38ff1 100644 --- a/Assets/Scripts/Utils/Html/HtmlElement.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlElement.cs @@ -1,207 +1,207 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public enum HtmlElementType - { - Text, - Link, - Image, - Input, - Select, - Object, - - //internal - LinkEnd, - } - - /// - /// - /// - public class HtmlElement - { - public HtmlElementType type; - public string name; - public string text; - public TextFormat format; - public int charIndex; - - public IHtmlObject htmlObject; - public int status; //1 hidden 2 clipped 4 added - public int space; - public Vector2 position; - - Hashtable attributes; - - public HtmlElement() - { - format = new TextFormat(); - } - - public object Get(string attrName) - { - if (attributes == null) - return null; - - return attributes[attrName]; - } - - public void Set(string attrName, object attrValue) - { - if (attributes == null) - attributes = new Hashtable(); - - attributes[attrName] = attrValue; - } - - public string GetString(string attrName) - { - return GetString(attrName, null); - } - - public string GetString(string attrName, string defValue) - { - if (attributes == null) - return defValue; - - object ret = attributes[attrName]; - if (ret != null) - return ret.ToString(); - else - return defValue; - } - - public int GetInt(string attrName) - { - return GetInt(attrName, 0); - } - - public int GetInt(string attrName, int defValue) - { - string value = GetString(attrName); - if (value == null || value.Length == 0) - return defValue; - - if (value[value.Length - 1] == '%') - { - int ret; - if (int.TryParse(value.Substring(0, value.Length - 1), out ret)) - return Mathf.CeilToInt(ret / 100.0f * defValue); - else - return defValue; - } - else - { - int ret; - if (int.TryParse(value, out ret)) - return ret; - else - return defValue; - } - } - - public float GetFloat(string attrName) - { - return GetFloat(attrName, 0); - } - - public float GetFloat(string attrName, float defValue) - { - string value = GetString(attrName); - if (value == null || value.Length == 0) - return defValue; - - float ret; - if (float.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public bool GetBool(string attrName) - { - return GetBool(attrName, false); - } - - public bool GetBool(string attrName, bool defValue) - { - string value = GetString(attrName); - if (value == null || value.Length == 0) - return defValue; - - bool ret; - if (bool.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public Color GetColor(string attrName, Color defValue) - { - string value = GetString(attrName); - if (value == null || value.Length == 0) - return defValue; - - return ToolSet.ConvertFromHtmlColor(value); - } - - public void FetchAttributes() - { - attributes = XMLIterator.GetAttributes(attributes); - } - - - public bool isEntity - { - get { return type == HtmlElementType.Image || type == HtmlElementType.Select || type == HtmlElementType.Input || type == HtmlElementType.Object; } - } - - #region Pool Support - - static Stack elementPool = new Stack(); - - public static HtmlElement GetElement(HtmlElementType type) - { - HtmlElement ret; - if (elementPool.Count > 0) - ret = elementPool.Pop(); - else - ret = new HtmlElement(); - ret.type = type; - - if (type != HtmlElementType.Text && ret.attributes == null) - ret.attributes = new Hashtable(); - - return ret; - } - - public static void ReturnElement(HtmlElement element) - { - element.name = null; - element.text = null; - element.htmlObject = null; - element.status = 0; - if (element.attributes != null) - element.attributes.Clear(); - elementPool.Push(element); - } - - public static void ReturnElements(List elements) - { - int count = elements.Count; - for (int i = 0; i < count; i++) - { - HtmlElement element = elements[i]; - ReturnElement(element); - } - elements.Clear(); - } - - #endregion - } -} +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public enum HtmlElementType + { + Text, + Link, + Image, + Input, + Select, + Object, + + //internal + LinkEnd, + } + + /// + /// + /// + public class HtmlElement + { + public HtmlElementType type; + public string name; + public string text; + public TextFormat format; + public int charIndex; + + public IHtmlObject htmlObject; + public int status; //1 hidden 2 clipped 4 added + public int space; + public Vector2 position; + + Hashtable attributes; + + public HtmlElement() + { + format = new TextFormat(); + } + + public object Get(string attrName) + { + if (attributes == null) + return null; + + return attributes[attrName]; + } + + public void Set(string attrName, object attrValue) + { + if (attributes == null) + attributes = new Hashtable(); + + attributes[attrName] = attrValue; + } + + public string GetString(string attrName) + { + return GetString(attrName, null); + } + + public string GetString(string attrName, string defValue) + { + if (attributes == null) + return defValue; + + object ret = attributes[attrName]; + if (ret != null) + return ret.ToString(); + else + return defValue; + } + + public int GetInt(string attrName) + { + return GetInt(attrName, 0); + } + + public int GetInt(string attrName, int defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + if (value[value.Length - 1] == '%') + { + int ret; + if (int.TryParse(value.Substring(0, value.Length - 1), out ret)) + return Mathf.CeilToInt(ret / 100.0f * defValue); + else + return defValue; + } + else + { + int ret; + if (int.TryParse(value, out ret)) + return ret; + else + return defValue; + } + } + + public float GetFloat(string attrName) + { + return GetFloat(attrName, 0); + } + + public float GetFloat(string attrName, float defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + float ret; + if (float.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public bool GetBool(string attrName) + { + return GetBool(attrName, false); + } + + public bool GetBool(string attrName, bool defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + bool ret; + if (bool.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public Color GetColor(string attrName, Color defValue) + { + string value = GetString(attrName); + if (value == null || value.Length == 0) + return defValue; + + return ToolSet.ConvertFromHtmlColor(value); + } + + public void FetchAttributes() + { + attributes = XMLIterator.GetAttributes(attributes); + } + + + public bool isEntity + { + get { return type == HtmlElementType.Image || type == HtmlElementType.Select || type == HtmlElementType.Input || type == HtmlElementType.Object; } + } + + #region Pool Support + + static Stack elementPool = new Stack(); + + public static HtmlElement GetElement(HtmlElementType type) + { + HtmlElement ret; + if (elementPool.Count > 0) + ret = elementPool.Pop(); + else + ret = new HtmlElement(); + ret.type = type; + + if (type != HtmlElementType.Text && ret.attributes == null) + ret.attributes = new Hashtable(); + + return ret; + } + + public static void ReturnElement(HtmlElement element) + { + element.name = null; + element.text = null; + element.htmlObject = null; + element.status = 0; + if (element.attributes != null) + element.attributes.Clear(); + elementPool.Push(element); + } + + public static void ReturnElements(List elements) + { + int count = elements.Count; + for (int i = 0; i < count; i++) + { + HtmlElement element = elements[i]; + ReturnElement(element); + } + elements.Clear(); + } + + #endregion + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlElement.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlElement.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlElement.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlElement.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlImage.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlImage.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlImage.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlImage.cs index 1ebc3320..1882480f 100644 --- a/Assets/Scripts/Utils/Html/HtmlImage.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlImage.cs @@ -1,126 +1,126 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlImage : IHtmlObject - { - public GLoader loader { get; private set; } - - RichTextField _owner; - HtmlElement _element; - bool _externalTexture; - - public HtmlImage() - { - loader = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader); - loader.gameObjectName = "HtmlImage"; - loader.fill = FillType.ScaleFree; - loader.touchable = false; - } - - public DisplayObject displayObject - { - get { return loader.displayObject; } - } - - public HtmlElement element - { - get { return _element; } - } - - public float width - { - get { return loader.width; } - } - - public float height - { - get { return loader.height; } - } - - public void Create(RichTextField owner, HtmlElement element) - { - _owner = owner; - _element = element; - - int sourceWidth = 0; - int sourceHeight = 0; - NTexture texture = owner.htmlPageContext.GetImageTexture(this); - if (texture != null) - { - sourceWidth = texture.width; - sourceHeight = texture.height; - - loader.texture = texture; - _externalTexture = true; - } - else - { - string src = element.GetString("src"); - if (src != null) - { - PackageItem pi = UIPackage.GetItemByURL(src); - if (pi != null) - { - sourceWidth = pi.width; - sourceHeight = pi.height; - } - } - - loader.url = src; - _externalTexture = false; - } - - int width = element.GetInt("width", sourceWidth); - int height = element.GetInt("height", sourceHeight); - - if (width == 0) - width = 5; - if (height == 0) - height = 10; - loader.SetSize(width, height); - } - - public void SetPosition(float x, float y) - { - loader.SetXY(x, y); - } - - public void Add() - { - _owner.AddChild(loader.displayObject); - } - - public void Remove() - { - if (loader.displayObject.parent != null) - _owner.RemoveChild(loader.displayObject); - } - - public void Release() - { - loader.RemoveEventListeners(); - if (_externalTexture) - { - _owner.htmlPageContext.FreeImageTexture(this, loader.texture); - _externalTexture = false; - } - - loader.url = null; - _owner = null; - _element = null; - } - - public void Dispose() - { - if (_externalTexture) - _owner.htmlPageContext.FreeImageTexture(this, loader.texture); - loader.Dispose(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlImage : IHtmlObject + { + public GLoader loader { get; private set; } + + RichTextField _owner; + HtmlElement _element; + bool _externalTexture; + + public HtmlImage() + { + loader = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader); + loader.gameObjectName = "HtmlImage"; + loader.fill = FillType.ScaleFree; + loader.touchable = false; + } + + public DisplayObject displayObject + { + get { return loader.displayObject; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return loader.width; } + } + + public float height + { + get { return loader.height; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + int sourceWidth = 0; + int sourceHeight = 0; + NTexture texture = owner.htmlPageContext.GetImageTexture(this); + if (texture != null) + { + sourceWidth = texture.width; + sourceHeight = texture.height; + + loader.texture = texture; + _externalTexture = true; + } + else + { + string src = element.GetString("src"); + if (src != null) + { + PackageItem pi = UIPackage.GetItemByURL(src); + if (pi != null) + { + sourceWidth = pi.width; + sourceHeight = pi.height; + } + } + + loader.url = src; + _externalTexture = false; + } + + int width = element.GetInt("width", sourceWidth); + int height = element.GetInt("height", sourceHeight); + + if (width == 0) + width = 5; + if (height == 0) + height = 10; + loader.SetSize(width, height); + } + + public void SetPosition(float x, float y) + { + loader.SetXY(x, y); + } + + public void Add() + { + _owner.AddChild(loader.displayObject); + } + + public void Remove() + { + if (loader.displayObject.parent != null) + _owner.RemoveChild(loader.displayObject); + } + + public void Release() + { + loader.RemoveEventListeners(); + if (_externalTexture) + { + _owner.htmlPageContext.FreeImageTexture(this, loader.texture); + _externalTexture = false; + } + + loader.url = null; + _owner = null; + _element = null; + } + + public void Dispose() + { + if (_externalTexture) + _owner.htmlPageContext.FreeImageTexture(this, loader.texture); + loader.Dispose(); + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlImage.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlImage.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlImage.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlImage.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlInput.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlInput.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlInput.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlInput.cs index a197e2f5..dcd6b784 100644 --- a/Assets/Scripts/Utils/Html/HtmlInput.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlInput.cs @@ -1,117 +1,117 @@ -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlInput : IHtmlObject - { - public GTextInput textInput { get; private set; } - - RichTextField _owner; - HtmlElement _element; - bool _hidden; - - public static int defaultBorderSize = 2; - public static Color defaultBorderColor = ToolSet.ColorFromRGB(0xA9A9A9); - public static Color defaultBackgroundColor = Color.clear; - - public HtmlInput() - { - textInput = (GTextInput)UIObjectFactory.NewObject(ObjectType.InputText); - textInput.gameObjectName = "HtmlInput"; - textInput.verticalAlign = VertAlignType.Middle; - } - - public DisplayObject displayObject - { - get { return textInput.displayObject; } - } - - public HtmlElement element - { - get { return _element; } - } - - public float width - { - get { return _hidden ? 0 : textInput.width; } - } - - public float height - { - get { return _hidden ? 0 : textInput.height; } - } - - public void Create(RichTextField owner, HtmlElement element) - { - _owner = owner; - _element = element; - - string type = element.GetString("type"); - if (type != null) - type = type.ToLower(); - - _hidden = type == "hidden"; - if (!_hidden) - { - int width = element.GetInt("width", 0); - int height = element.GetInt("height", 0); - int borderSize = element.GetInt("border", defaultBorderSize); - Color borderColor = element.GetColor("border-color", defaultBorderColor); - Color backgroundColor = element.GetColor("background-color", defaultBackgroundColor); - - if (width == 0) - { - width = element.space; - if (width > _owner.width / 2 || width < 100) - width = (int)_owner.width / 2; - } - if (height == 0) - height = element.format.size + 10; - - textInput.textFormat = element.format; - textInput.displayAsPassword = type == "password"; - textInput.maxLength = element.GetInt("maxlength", int.MaxValue); - textInput.border = borderSize; - textInput.borderColor = borderColor; - textInput.backgroundColor = backgroundColor; - textInput.SetSize(width, height); - } - textInput.text = element.GetString("value"); - } - - public void SetPosition(float x, float y) - { - if (!_hidden) - textInput.SetXY(x, y); - } - - public void Add() - { - if (!_hidden) - _owner.AddChild(textInput.displayObject); - } - - public void Remove() - { - if (!_hidden && textInput.displayObject.parent != null) - _owner.RemoveChild(textInput.displayObject); - } - - public void Release() - { - textInput.RemoveEventListeners(); - textInput.text = null; - - _owner = null; - _element = null; - } - - public void Dispose() - { - textInput.Dispose(); - } - } -} +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlInput : IHtmlObject + { + public GTextInput textInput { get; private set; } + + RichTextField _owner; + HtmlElement _element; + bool _hidden; + + public static int defaultBorderSize = 2; + public static Color defaultBorderColor = ToolSet.ColorFromRGB(0xA9A9A9); + public static Color defaultBackgroundColor = Color.clear; + + public HtmlInput() + { + textInput = (GTextInput)UIObjectFactory.NewObject(ObjectType.InputText); + textInput.gameObjectName = "HtmlInput"; + textInput.verticalAlign = VertAlignType.Middle; + } + + public DisplayObject displayObject + { + get { return textInput.displayObject; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return _hidden ? 0 : textInput.width; } + } + + public float height + { + get { return _hidden ? 0 : textInput.height; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + string type = element.GetString("type"); + if (type != null) + type = type.ToLower(); + + _hidden = type == "hidden"; + if (!_hidden) + { + int width = element.GetInt("width", 0); + int height = element.GetInt("height", 0); + int borderSize = element.GetInt("border", defaultBorderSize); + Color borderColor = element.GetColor("border-color", defaultBorderColor); + Color backgroundColor = element.GetColor("background-color", defaultBackgroundColor); + + if (width == 0) + { + width = element.space; + if (width > _owner.width / 2 || width < 100) + width = (int)_owner.width / 2; + } + if (height == 0) + height = element.format.size + 10; + + textInput.textFormat = element.format; + textInput.displayAsPassword = type == "password"; + textInput.maxLength = element.GetInt("maxlength", int.MaxValue); + textInput.border = borderSize; + textInput.borderColor = borderColor; + textInput.backgroundColor = backgroundColor; + textInput.SetSize(width, height); + } + textInput.text = element.GetString("value"); + } + + public void SetPosition(float x, float y) + { + if (!_hidden) + textInput.SetXY(x, y); + } + + public void Add() + { + if (!_hidden) + _owner.AddChild(textInput.displayObject); + } + + public void Remove() + { + if (!_hidden && textInput.displayObject.parent != null) + _owner.RemoveChild(textInput.displayObject); + } + + public void Release() + { + textInput.RemoveEventListeners(); + textInput.text = null; + + _owner = null; + _element = null; + } + + public void Dispose() + { + textInput.Dispose(); + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlInput.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlInput.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlInput.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlInput.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlLink.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlLink.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlLink.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlLink.cs index 61c4d3ef..6875fab5 100644 --- a/Assets/Scripts/Utils/Html/HtmlLink.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlLink.cs @@ -1,113 +1,113 @@ - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlLink : IHtmlObject - { - RichTextField _owner; - HtmlElement _element; - SelectionShape _shape; - - EventCallback1 _clickHandler; - EventCallback1 _rolloverHandler; - EventCallback0 _rolloutHandler; - - public HtmlLink() - { - _shape = new SelectionShape(); - _shape.gameObject.name = "HtmlLink"; - _shape.cursor = "text-link"; - - _clickHandler = (EventContext context) => - { - _owner.BubbleEvent("onClickLink", _element.GetString("href")); - }; - _rolloverHandler = (EventContext context) => - { - if (_owner.htmlParseOptions.linkHoverBgColor.a > 0) - _shape.color = _owner.htmlParseOptions.linkHoverBgColor; - }; - _rolloutHandler = () => - { - if (_owner.htmlParseOptions.linkHoverBgColor.a > 0) - _shape.color = _owner.htmlParseOptions.linkBgColor; - }; - } - - public DisplayObject displayObject - { - get { return _shape; } - } - - public HtmlElement element - { - get { return _element; } - } - - public float width - { - get { return 0; } - } - - public float height - { - get { return 0; } - } - - public void Create(RichTextField owner, HtmlElement element) - { - _owner = owner; - _element = element; - _shape.onClick.Add(_clickHandler); - _shape.onRollOver.Add(_rolloverHandler); - _shape.onRollOut.Add(_rolloutHandler); - _shape.color = _owner.htmlParseOptions.linkBgColor; - } - - public void SetArea(int startLine, float startCharX, int endLine, float endCharX) - { - if (startLine == endLine && startCharX > endCharX) - { - float tmp = startCharX; - startCharX = endCharX; - endCharX = tmp; - } - _shape.rects.Clear(); - _owner.textField.GetLinesShape(startLine, startCharX, endLine, endCharX, true, _shape.rects); - _shape.Refresh(); - } - - public void SetPosition(float x, float y) - { - _shape.SetXY(x, y); - } - - public void Add() - { - //add below _shape - _owner.AddChildAt(_shape, 0); - } - - public void Remove() - { - if (_shape.parent != null) - _owner.RemoveChild(_shape); - } - - public void Release() - { - _shape.RemoveEventListeners(); - - _owner = null; - _element = null; - } - - public void Dispose() - { - _shape.Dispose(); - _shape = null; - } - } -} + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlLink : IHtmlObject + { + RichTextField _owner; + HtmlElement _element; + SelectionShape _shape; + + EventCallback1 _clickHandler; + EventCallback1 _rolloverHandler; + EventCallback0 _rolloutHandler; + + public HtmlLink() + { + _shape = new SelectionShape(); + _shape.gameObject.name = "HtmlLink"; + _shape.cursor = "text-link"; + + _clickHandler = (EventContext context) => + { + _owner.BubbleEvent("onClickLink", _element.GetString("href")); + }; + _rolloverHandler = (EventContext context) => + { + if (_owner.htmlParseOptions.linkHoverBgColor.a > 0) + _shape.color = _owner.htmlParseOptions.linkHoverBgColor; + }; + _rolloutHandler = () => + { + if (_owner.htmlParseOptions.linkHoverBgColor.a > 0) + _shape.color = _owner.htmlParseOptions.linkBgColor; + }; + } + + public DisplayObject displayObject + { + get { return _shape; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return 0; } + } + + public float height + { + get { return 0; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + _shape.onClick.Add(_clickHandler); + _shape.onRollOver.Add(_rolloverHandler); + _shape.onRollOut.Add(_rolloutHandler); + _shape.color = _owner.htmlParseOptions.linkBgColor; + } + + public void SetArea(int startLine, float startCharX, int endLine, float endCharX) + { + if (startLine == endLine && startCharX > endCharX) + { + float tmp = startCharX; + startCharX = endCharX; + endCharX = tmp; + } + _shape.rects.Clear(); + _owner.textField.GetLinesShape(startLine, startCharX, endLine, endCharX, true, _shape.rects); + _shape.Refresh(); + } + + public void SetPosition(float x, float y) + { + _shape.SetXY(x, y); + } + + public void Add() + { + //add below _shape + _owner.AddChildAt(_shape, 0); + } + + public void Remove() + { + if (_shape.parent != null) + _owner.RemoveChild(_shape); + } + + public void Release() + { + _shape.RemoveEventListeners(); + + _owner = null; + _element = null; + } + + public void Dispose() + { + _shape.Dispose(); + _shape = null; + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlLink.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlLink.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlLink.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlLink.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlPageContext.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlPageContext.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlPageContext.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlPageContext.cs index f1a46972..483fa4c2 100644 --- a/Assets/Scripts/Utils/Html/HtmlPageContext.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlPageContext.cs @@ -1,150 +1,150 @@ -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlPageContext : IHtmlPageContext - { - Stack _imagePool; - Stack _inputPool; - Stack _buttonPool; - Stack _selectPool; - Stack _linkPool; - - public static HtmlPageContext inst = new HtmlPageContext(); - - static Transform _poolManager; - - public HtmlPageContext() - { - _imagePool = new Stack(); - _inputPool = new Stack(); - _buttonPool = new Stack(); - _selectPool = new Stack(); - _linkPool = new Stack(); - - if (Application.isPlaying && _poolManager == null) - _poolManager = Stage.inst.CreatePoolManager("HtmlObjectPool"); - } - - virtual public IHtmlObject CreateObject(RichTextField owner, HtmlElement element) - { - IHtmlObject ret = null; - bool fromPool = false; - if (element.type == HtmlElementType.Image) - { - if (_imagePool.Count > 0 && _poolManager != null) - { - ret = _imagePool.Pop(); - fromPool = true; - } - else - ret = new HtmlImage(); - } - else if (element.type == HtmlElementType.Link) - { - if (_linkPool.Count > 0 && _poolManager != null) - { - ret = _linkPool.Pop(); - fromPool = true; - } - else - ret = new HtmlLink(); - } - else if (element.type == HtmlElementType.Input) - { - string type = element.GetString("type"); - if (type != null) - type = type.ToLower(); - if (type == "button" || type == "submit") - { - if (_buttonPool.Count > 0 && _poolManager != null) - { - ret = _buttonPool.Pop(); - fromPool = true; - } - else - ret = new HtmlButton(); - } - else - { - if (_inputPool.Count > 0 && _poolManager != null) - { - ret = _inputPool.Pop(); - fromPool = true; - } - else - ret = new HtmlInput(); - } - } - else if (element.type == HtmlElementType.Select) - { - if (_selectPool.Count > 0 && _poolManager != null) - { - ret = _selectPool.Pop(); - fromPool = true; - } - else - ret = new HtmlSelect(); - } - - //Debug.Log("from=" + fromPool); - if (ret != null) - { - //可能已经被GameObject tree deleted了,不再使用 - if (fromPool && ret.displayObject != null && ret.displayObject.isDisposed) - { - ret.Dispose(); - return CreateObject(owner, element); - - } - ret.Create(owner, element); - if (ret.displayObject != null) - ret.displayObject.home = owner.cachedTransform; - } - - return ret; - } - - virtual public void FreeObject(IHtmlObject obj) - { - if (_poolManager == null) - { - obj.Dispose(); - return; - } - - //可能已经被GameObject tree deleted了,不再回收 - if (obj.displayObject != null && obj.displayObject.isDisposed) - { - obj.Dispose(); - return; - } - - obj.Release(); - if (obj is HtmlImage) - _imagePool.Push(obj); - else if (obj is HtmlInput) - _inputPool.Push(obj); - else if (obj is HtmlButton) - _buttonPool.Push(obj); - else if (obj is HtmlLink) - _linkPool.Push(obj); - - if (obj.displayObject != null) - obj.displayObject.cachedTransform.SetParent(_poolManager, false); - } - - virtual public NTexture GetImageTexture(HtmlImage image) - { - return null; - } - - virtual public void FreeImageTexture(HtmlImage image, NTexture texture) - { - } - } -} +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlPageContext : IHtmlPageContext + { + Stack _imagePool; + Stack _inputPool; + Stack _buttonPool; + Stack _selectPool; + Stack _linkPool; + + public static HtmlPageContext inst = new HtmlPageContext(); + + static Transform _poolManager; + + public HtmlPageContext() + { + _imagePool = new Stack(); + _inputPool = new Stack(); + _buttonPool = new Stack(); + _selectPool = new Stack(); + _linkPool = new Stack(); + + if (Application.isPlaying && _poolManager == null) + _poolManager = Stage.inst.CreatePoolManager("HtmlObjectPool"); + } + + virtual public IHtmlObject CreateObject(RichTextField owner, HtmlElement element) + { + IHtmlObject ret = null; + bool fromPool = false; + if (element.type == HtmlElementType.Image) + { + if (_imagePool.Count > 0 && _poolManager != null) + { + ret = _imagePool.Pop(); + fromPool = true; + } + else + ret = new HtmlImage(); + } + else if (element.type == HtmlElementType.Link) + { + if (_linkPool.Count > 0 && _poolManager != null) + { + ret = _linkPool.Pop(); + fromPool = true; + } + else + ret = new HtmlLink(); + } + else if (element.type == HtmlElementType.Input) + { + string type = element.GetString("type"); + if (type != null) + type = type.ToLower(); + if (type == "button" || type == "submit") + { + if (_buttonPool.Count > 0 && _poolManager != null) + { + ret = _buttonPool.Pop(); + fromPool = true; + } + else + ret = new HtmlButton(); + } + else + { + if (_inputPool.Count > 0 && _poolManager != null) + { + ret = _inputPool.Pop(); + fromPool = true; + } + else + ret = new HtmlInput(); + } + } + else if (element.type == HtmlElementType.Select) + { + if (_selectPool.Count > 0 && _poolManager != null) + { + ret = _selectPool.Pop(); + fromPool = true; + } + else + ret = new HtmlSelect(); + } + + //Debug.Log("from=" + fromPool); + if (ret != null) + { + //可能已经被GameObject tree deleted了,不再使用 + if (fromPool && ret.displayObject != null && ret.displayObject.isDisposed) + { + ret.Dispose(); + return CreateObject(owner, element); + + } + ret.Create(owner, element); + if (ret.displayObject != null) + ret.displayObject.home = owner.cachedTransform; + } + + return ret; + } + + virtual public void FreeObject(IHtmlObject obj) + { + if (_poolManager == null) + { + obj.Dispose(); + return; + } + + //可能已经被GameObject tree deleted了,不再回收 + if (obj.displayObject != null && obj.displayObject.isDisposed) + { + obj.Dispose(); + return; + } + + obj.Release(); + if (obj is HtmlImage) + _imagePool.Push(obj); + else if (obj is HtmlInput) + _inputPool.Push(obj); + else if (obj is HtmlButton) + _buttonPool.Push(obj); + else if (obj is HtmlLink) + _linkPool.Push(obj); + + if (obj.displayObject != null) + obj.displayObject.cachedTransform.SetParent(_poolManager, false); + } + + virtual public NTexture GetImageTexture(HtmlImage image) + { + return null; + } + + virtual public void FreeImageTexture(HtmlImage image, NTexture texture) + { + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlPageContext.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlPageContext.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlPageContext.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlPageContext.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlParseOptions.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParseOptions.cs similarity index 95% rename from Assets/Scripts/Utils/Html/HtmlParseOptions.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParseOptions.cs index ae87cabb..3c378a33 100644 --- a/Assets/Scripts/Utils/Html/HtmlParseOptions.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParseOptions.cs @@ -1,65 +1,65 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlParseOptions - { - /// - /// - /// - public bool linkUnderline; - - /// - /// - /// - public Color linkColor; - - /// - /// - /// - public Color linkBgColor; - - /// - /// - /// - public Color linkHoverBgColor; - - /// - /// - /// - public bool ignoreWhiteSpace; - - /// - /// - /// - public static bool DefaultLinkUnderline = true; - - /// - /// - /// - public static Color DefaultLinkColor = new Color32(0x3A, 0x67, 0xCC, 0xFF); - - /// - /// - /// - public static Color DefaultLinkBgColor = Color.clear; - - /// - /// - /// - public static Color DefaultLinkHoverBgColor = Color.clear; - - public HtmlParseOptions() - { - linkUnderline = DefaultLinkUnderline; - linkColor = DefaultLinkColor; - linkBgColor = DefaultLinkBgColor; - linkHoverBgColor = DefaultLinkHoverBgColor; - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlParseOptions + { + /// + /// + /// + public bool linkUnderline; + + /// + /// + /// + public Color linkColor; + + /// + /// + /// + public Color linkBgColor; + + /// + /// + /// + public Color linkHoverBgColor; + + /// + /// + /// + public bool ignoreWhiteSpace; + + /// + /// + /// + public static bool DefaultLinkUnderline = true; + + /// + /// + /// + public static Color DefaultLinkColor = new Color32(0x3A, 0x67, 0xCC, 0xFF); + + /// + /// + /// + public static Color DefaultLinkBgColor = Color.clear; + + /// + /// + /// + public static Color DefaultLinkHoverBgColor = Color.clear; + + public HtmlParseOptions() + { + linkUnderline = DefaultLinkUnderline; + linkColor = DefaultLinkColor; + linkBgColor = DefaultLinkBgColor; + linkHoverBgColor = DefaultLinkHoverBgColor; + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlParseOptions.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParseOptions.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlParseOptions.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParseOptions.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlParser.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParser.cs similarity index 97% rename from Assets/Scripts/Utils/Html/HtmlParser.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParser.cs index 706f03ea..3a550130 100644 --- a/Assets/Scripts/Utils/Html/HtmlParser.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParser.cs @@ -1,387 +1,387 @@ -using System; -using System.Collections.Generic; -using System.Text; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlParser - { - public static HtmlParser inst = new HtmlParser(); - - protected class TextFormat2 : TextFormat - { - public bool colorChanged; - } - - protected List _textFormatStack; - protected int _textFormatStackTop; - protected TextFormat2 _format; - protected List _elements; - protected HtmlParseOptions _defaultOptions; - - static List sHelperList1 = new List(); - static List sHelperList2 = new List(); - - public HtmlParser() - { - _textFormatStack = new List(); - _format = new TextFormat2(); - _defaultOptions = new HtmlParseOptions(); - } - - virtual public void Parse(string aSource, TextFormat defaultFormat, List elements, HtmlParseOptions parseOptions) - { - if (parseOptions == null) - parseOptions = _defaultOptions; - - _elements = elements; - _textFormatStackTop = 0; - _format.CopyFrom(defaultFormat); - _format.colorChanged = false; - int skipText = 0; - bool ignoreWhiteSpace = parseOptions.ignoreWhiteSpace; - bool skipNextCR = false; - string text; - - XMLIterator.Begin(aSource, true); - while (XMLIterator.NextTag()) - { - if (skipText == 0) - { - text = XMLIterator.GetText(ignoreWhiteSpace); - if (text.Length > 0) - { - if (skipNextCR && text[0] == '\n') - text = text.Substring(1); - AppendText(text); - } - } - - skipNextCR = false; - switch (XMLIterator.tagName) - { - case "b": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - _format.bold = true; - } - else - PopTextFormat(); - break; - - case "i": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - _format.italic = true; - } - else - PopTextFormat(); - break; - - case "u": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - _format.underline = true; - } - else - PopTextFormat(); - break; - - case "strike": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - _format.strikethrough = true; - } - else - PopTextFormat(); - break; - - case "sub": - { - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - _format.specialStyle = TextFormat.SpecialStyle.Subscript; - } - else - PopTextFormat(); - } - break; - - case "sup": - { - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - _format.specialStyle = TextFormat.SpecialStyle.Superscript; - } - else - PopTextFormat(); - } - break; - - case "font": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - - _format.size = XMLIterator.GetAttributeInt("size", _format.size); - string color = XMLIterator.GetAttribute("color"); - if (color != null) - { - string[] parts = color.Split(','); - if (parts.Length == 1) - { - _format.color = ToolSet.ConvertFromHtmlColor(color); - _format.gradientColor = null; - _format.colorChanged = true; - } - else - { - if (_format.gradientColor == null) - _format.gradientColor = new Color32[4]; - _format.gradientColor[0] = ToolSet.ConvertFromHtmlColor(parts[0]); - _format.gradientColor[1] = ToolSet.ConvertFromHtmlColor(parts[1]); - if (parts.Length > 2) - { - _format.gradientColor[2] = ToolSet.ConvertFromHtmlColor(parts[2]); - if (parts.Length > 3) - _format.gradientColor[3] = ToolSet.ConvertFromHtmlColor(parts[3]); - else - _format.gradientColor[3] = _format.gradientColor[2]; - } - else - { - _format.gradientColor[2] = _format.gradientColor[0]; - _format.gradientColor[3] = _format.gradientColor[1]; - } - } - } - } - else if (XMLIterator.tagType == XMLTagType.End) - PopTextFormat(); - break; - - case "br": - AppendText("\n"); - break; - - case "img": - if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) - { - HtmlElement element = HtmlElement.GetElement(HtmlElementType.Image); - element.FetchAttributes(); - element.name = element.GetString("name"); - element.format.align = _format.align; - _elements.Add(element); - } - break; - - case "a": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - - _format.underline = _format.underline || parseOptions.linkUnderline; - if (!_format.colorChanged && parseOptions.linkColor.a != 0) - _format.color = parseOptions.linkColor; - - HtmlElement element = HtmlElement.GetElement(HtmlElementType.Link); - element.FetchAttributes(); - element.name = element.GetString("name"); - element.format.align = _format.align; - _elements.Add(element); - } - else if (XMLIterator.tagType == XMLTagType.End) - { - PopTextFormat(); - - HtmlElement element = HtmlElement.GetElement(HtmlElementType.LinkEnd); - _elements.Add(element); - } - break; - - case "input": - { - HtmlElement element = HtmlElement.GetElement(HtmlElementType.Input); - element.FetchAttributes(); - element.name = element.GetString("name"); - element.format.CopyFrom(_format); - _elements.Add(element); - } - break; - - case "select": - { - if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) - { - HtmlElement element = HtmlElement.GetElement(HtmlElementType.Select); - element.FetchAttributes(); - if (XMLIterator.tagType == XMLTagType.Start) - { - sHelperList1.Clear(); - sHelperList2.Clear(); - while (XMLIterator.NextTag()) - { - if (XMLIterator.tagName == "select") - break; - - if (XMLIterator.tagName == "option") - { - if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) - sHelperList2.Add(XMLIterator.GetAttribute("value", string.Empty)); - else - sHelperList1.Add(XMLIterator.GetText()); - } - } - element.Set("items", sHelperList1.ToArray()); - element.Set("values", sHelperList2.ToArray()); - } - element.name = element.GetString("name"); - element.format.CopyFrom(_format); - _elements.Add(element); - } - } - break; - - case "p": - if (XMLIterator.tagType == XMLTagType.Start) - { - PushTextFormat(); - string align = XMLIterator.GetAttribute("align"); - switch (align) - { - case "center": - _format.align = AlignType.Center; - break; - case "right": - _format.align = AlignType.Right; - break; - } - if (!IsNewLine()) - AppendText("\n"); - } - else if (XMLIterator.tagType == XMLTagType.End) - { - AppendText("\n"); - skipNextCR = true; - - PopTextFormat(); - } - break; - - case "ui": - case "div": - case "li": - if (XMLIterator.tagType == XMLTagType.Start) - { - if (!IsNewLine()) - AppendText("\n"); - } - else - { - AppendText("\n"); - skipNextCR = true; - } - break; - - case "html": - case "body": - //full html - ignoreWhiteSpace = true; - break; - - case "head": - case "style": - case "script": - case "form": - if (XMLIterator.tagType == XMLTagType.Start) - skipText++; - else if (XMLIterator.tagType == XMLTagType.End) - skipText--; - break; - } - } - - if (skipText == 0) - { - text = XMLIterator.GetText(ignoreWhiteSpace); - if (text.Length > 0) - { - if (skipNextCR && text[0] == '\n') - text = text.Substring(1); - AppendText(text); - } - } - - _elements = null; - } - - protected void PushTextFormat() - { - TextFormat2 tf; - if (_textFormatStack.Count <= _textFormatStackTop) - { - tf = new TextFormat2(); - _textFormatStack.Add(tf); - } - else - tf = _textFormatStack[_textFormatStackTop]; - tf.CopyFrom(_format); - tf.colorChanged = _format.colorChanged; - _textFormatStackTop++; - } - - protected void PopTextFormat() - { - if (_textFormatStackTop > 0) - { - TextFormat2 tf = _textFormatStack[_textFormatStackTop - 1]; - _format.CopyFrom(tf); - _format.colorChanged = tf.colorChanged; - _textFormatStackTop--; - } - } - - protected bool IsNewLine() - { - if (_elements.Count > 0) - { - HtmlElement element = _elements[_elements.Count - 1]; - if (element != null && element.type == HtmlElementType.Text) - return element.text.EndsWith("\n"); - else - return false; - } - - return true; - } - - protected void AppendText(string text) - { - HtmlElement element; - if (_elements.Count > 0) - { - element = _elements[_elements.Count - 1]; - if (element.type == HtmlElementType.Text && element.format.EqualStyle(_format)) - { - element.text += text; - return; - } - } - - element = HtmlElement.GetElement(HtmlElementType.Text); - element.text = text; - element.format.CopyFrom(_format); - _elements.Add(element); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlParser + { + public static HtmlParser inst = new HtmlParser(); + + protected class TextFormat2 : TextFormat + { + public bool colorChanged; + } + + protected List _textFormatStack; + protected int _textFormatStackTop; + protected TextFormat2 _format; + protected List _elements; + protected HtmlParseOptions _defaultOptions; + + static List sHelperList1 = new List(); + static List sHelperList2 = new List(); + + public HtmlParser() + { + _textFormatStack = new List(); + _format = new TextFormat2(); + _defaultOptions = new HtmlParseOptions(); + } + + virtual public void Parse(string aSource, TextFormat defaultFormat, List elements, HtmlParseOptions parseOptions) + { + if (parseOptions == null) + parseOptions = _defaultOptions; + + _elements = elements; + _textFormatStackTop = 0; + _format.CopyFrom(defaultFormat); + _format.colorChanged = false; + int skipText = 0; + bool ignoreWhiteSpace = parseOptions.ignoreWhiteSpace; + bool skipNextCR = false; + string text; + + XMLIterator.Begin(aSource, true); + while (XMLIterator.NextTag()) + { + if (skipText == 0) + { + text = XMLIterator.GetText(ignoreWhiteSpace); + if (text.Length > 0) + { + if (skipNextCR && text[0] == '\n') + text = text.Substring(1); + AppendText(text); + } + } + + skipNextCR = false; + switch (XMLIterator.tagName) + { + case "b": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.bold = true; + } + else + PopTextFormat(); + break; + + case "i": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.italic = true; + } + else + PopTextFormat(); + break; + + case "u": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.underline = true; + } + else + PopTextFormat(); + break; + + case "strike": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.strikethrough = true; + } + else + PopTextFormat(); + break; + + case "sub": + { + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.specialStyle = TextFormat.SpecialStyle.Subscript; + } + else + PopTextFormat(); + } + break; + + case "sup": + { + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + _format.specialStyle = TextFormat.SpecialStyle.Superscript; + } + else + PopTextFormat(); + } + break; + + case "font": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + + _format.size = XMLIterator.GetAttributeInt("size", _format.size); + string color = XMLIterator.GetAttribute("color"); + if (color != null) + { + string[] parts = color.Split(','); + if (parts.Length == 1) + { + _format.color = ToolSet.ConvertFromHtmlColor(color); + _format.gradientColor = null; + _format.colorChanged = true; + } + else + { + if (_format.gradientColor == null) + _format.gradientColor = new Color32[4]; + _format.gradientColor[0] = ToolSet.ConvertFromHtmlColor(parts[0]); + _format.gradientColor[1] = ToolSet.ConvertFromHtmlColor(parts[1]); + if (parts.Length > 2) + { + _format.gradientColor[2] = ToolSet.ConvertFromHtmlColor(parts[2]); + if (parts.Length > 3) + _format.gradientColor[3] = ToolSet.ConvertFromHtmlColor(parts[3]); + else + _format.gradientColor[3] = _format.gradientColor[2]; + } + else + { + _format.gradientColor[2] = _format.gradientColor[0]; + _format.gradientColor[3] = _format.gradientColor[1]; + } + } + } + } + else if (XMLIterator.tagType == XMLTagType.End) + PopTextFormat(); + break; + + case "br": + AppendText("\n"); + break; + + case "img": + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + { + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Image); + element.FetchAttributes(); + element.name = element.GetString("name"); + element.format.align = _format.align; + _elements.Add(element); + } + break; + + case "a": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + + _format.underline = _format.underline || parseOptions.linkUnderline; + if (!_format.colorChanged && parseOptions.linkColor.a != 0) + _format.color = parseOptions.linkColor; + + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Link); + element.FetchAttributes(); + element.name = element.GetString("name"); + element.format.align = _format.align; + _elements.Add(element); + } + else if (XMLIterator.tagType == XMLTagType.End) + { + PopTextFormat(); + + HtmlElement element = HtmlElement.GetElement(HtmlElementType.LinkEnd); + _elements.Add(element); + } + break; + + case "input": + { + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Input); + element.FetchAttributes(); + element.name = element.GetString("name"); + element.format.CopyFrom(_format); + _elements.Add(element); + } + break; + + case "select": + { + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + { + HtmlElement element = HtmlElement.GetElement(HtmlElementType.Select); + element.FetchAttributes(); + if (XMLIterator.tagType == XMLTagType.Start) + { + sHelperList1.Clear(); + sHelperList2.Clear(); + while (XMLIterator.NextTag()) + { + if (XMLIterator.tagName == "select") + break; + + if (XMLIterator.tagName == "option") + { + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + sHelperList2.Add(XMLIterator.GetAttribute("value", string.Empty)); + else + sHelperList1.Add(XMLIterator.GetText()); + } + } + element.Set("items", sHelperList1.ToArray()); + element.Set("values", sHelperList2.ToArray()); + } + element.name = element.GetString("name"); + element.format.CopyFrom(_format); + _elements.Add(element); + } + } + break; + + case "p": + if (XMLIterator.tagType == XMLTagType.Start) + { + PushTextFormat(); + string align = XMLIterator.GetAttribute("align"); + switch (align) + { + case "center": + _format.align = AlignType.Center; + break; + case "right": + _format.align = AlignType.Right; + break; + } + if (!IsNewLine()) + AppendText("\n"); + } + else if (XMLIterator.tagType == XMLTagType.End) + { + AppendText("\n"); + skipNextCR = true; + + PopTextFormat(); + } + break; + + case "ui": + case "div": + case "li": + if (XMLIterator.tagType == XMLTagType.Start) + { + if (!IsNewLine()) + AppendText("\n"); + } + else + { + AppendText("\n"); + skipNextCR = true; + } + break; + + case "html": + case "body": + //full html + ignoreWhiteSpace = true; + break; + + case "head": + case "style": + case "script": + case "form": + if (XMLIterator.tagType == XMLTagType.Start) + skipText++; + else if (XMLIterator.tagType == XMLTagType.End) + skipText--; + break; + } + } + + if (skipText == 0) + { + text = XMLIterator.GetText(ignoreWhiteSpace); + if (text.Length > 0) + { + if (skipNextCR && text[0] == '\n') + text = text.Substring(1); + AppendText(text); + } + } + + _elements = null; + } + + protected void PushTextFormat() + { + TextFormat2 tf; + if (_textFormatStack.Count <= _textFormatStackTop) + { + tf = new TextFormat2(); + _textFormatStack.Add(tf); + } + else + tf = _textFormatStack[_textFormatStackTop]; + tf.CopyFrom(_format); + tf.colorChanged = _format.colorChanged; + _textFormatStackTop++; + } + + protected void PopTextFormat() + { + if (_textFormatStackTop > 0) + { + TextFormat2 tf = _textFormatStack[_textFormatStackTop - 1]; + _format.CopyFrom(tf); + _format.colorChanged = tf.colorChanged; + _textFormatStackTop--; + } + } + + protected bool IsNewLine() + { + if (_elements.Count > 0) + { + HtmlElement element = _elements[_elements.Count - 1]; + if (element != null && element.type == HtmlElementType.Text) + return element.text.EndsWith("\n"); + else + return false; + } + + return true; + } + + protected void AppendText(string text) + { + HtmlElement element; + if (_elements.Count > 0) + { + element = _elements[_elements.Count - 1]; + if (element.type == HtmlElementType.Text && element.format.EqualStyle(_format)) + { + element.text += text; + return; + } + } + + element = HtmlElement.GetElement(HtmlElementType.Text); + element.text = text; + element.format.CopyFrom(_format); + _elements.Add(element); + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlParser.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParser.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlParser.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlParser.cs.meta diff --git a/Assets/Scripts/Utils/Html/HtmlSelect.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlSelect.cs similarity index 96% rename from Assets/Scripts/Utils/Html/HtmlSelect.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlSelect.cs index 577a2f65..dcbcccb7 100644 --- a/Assets/Scripts/Utils/Html/HtmlSelect.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlSelect.cs @@ -1,107 +1,107 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class HtmlSelect : IHtmlObject - { - public GComboBox comboBox { get; private set; } - - public const string CHANGED_EVENT = "OnHtmlSelectChanged"; - - public static string resource; - - RichTextField _owner; - HtmlElement _element; - EventCallback0 _changeHandler; - - public HtmlSelect() - { - if (resource != null) - { - comboBox = UIPackage.CreateObjectFromURL(resource).asComboBox; - _changeHandler = () => - { - _owner.DispatchEvent(CHANGED_EVENT, null, this); - }; - } - else - Debug.LogWarning("FairyGUI: Set HtmlSelect.resource first"); - } - - public DisplayObject displayObject - { - get { return comboBox.displayObject; } - } - - public HtmlElement element - { - get { return _element; } - } - - public float width - { - get { return comboBox != null ? comboBox.width : 0; } - } - - public float height - { - get { return comboBox != null ? comboBox.height : 0; } - } - - public void Create(RichTextField owner, HtmlElement element) - { - _owner = owner; - _element = element; - - if (comboBox == null) - return; - - comboBox.onChanged.Add(_changeHandler); - - int width = element.GetInt("width", comboBox.sourceWidth); - int height = element.GetInt("height", comboBox.sourceHeight); - comboBox.SetSize(width, height); - comboBox.items = (string[])element.Get("items"); - comboBox.values = (string[])element.Get("values"); - comboBox.value = element.GetString("value"); - } - - public void SetPosition(float x, float y) - { - if (comboBox != null) - comboBox.SetXY(x, y); - } - - public void Add() - { - if (comboBox != null) - _owner.AddChild(comboBox.displayObject); - } - - public void Remove() - { - if (comboBox != null && comboBox.displayObject.parent != null) - _owner.RemoveChild(comboBox.displayObject); - } - - public void Release() - { - if (comboBox != null) - comboBox.RemoveEventListeners(); - - _owner = null; - _element = null; - } - - public void Dispose() - { - if (comboBox != null) - comboBox.Dispose(); - } - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class HtmlSelect : IHtmlObject + { + public GComboBox comboBox { get; private set; } + + public const string CHANGED_EVENT = "OnHtmlSelectChanged"; + + public static string resource; + + RichTextField _owner; + HtmlElement _element; + EventCallback0 _changeHandler; + + public HtmlSelect() + { + if (resource != null) + { + comboBox = UIPackage.CreateObjectFromURL(resource).asComboBox; + _changeHandler = () => + { + _owner.DispatchEvent(CHANGED_EVENT, null, this); + }; + } + else + Debug.LogWarning("FairyGUI: Set HtmlSelect.resource first"); + } + + public DisplayObject displayObject + { + get { return comboBox.displayObject; } + } + + public HtmlElement element + { + get { return _element; } + } + + public float width + { + get { return comboBox != null ? comboBox.width : 0; } + } + + public float height + { + get { return comboBox != null ? comboBox.height : 0; } + } + + public void Create(RichTextField owner, HtmlElement element) + { + _owner = owner; + _element = element; + + if (comboBox == null) + return; + + comboBox.onChanged.Add(_changeHandler); + + int width = element.GetInt("width", comboBox.sourceWidth); + int height = element.GetInt("height", comboBox.sourceHeight); + comboBox.SetSize(width, height); + comboBox.items = (string[])element.Get("items"); + comboBox.values = (string[])element.Get("values"); + comboBox.value = element.GetString("value"); + } + + public void SetPosition(float x, float y) + { + if (comboBox != null) + comboBox.SetXY(x, y); + } + + public void Add() + { + if (comboBox != null) + _owner.AddChild(comboBox.displayObject); + } + + public void Remove() + { + if (comboBox != null && comboBox.displayObject.parent != null) + _owner.RemoveChild(comboBox.displayObject); + } + + public void Release() + { + if (comboBox != null) + comboBox.RemoveEventListeners(); + + _owner = null; + _element = null; + } + + public void Dispose() + { + if (comboBox != null) + comboBox.Dispose(); + } + } +} diff --git a/Assets/Scripts/Utils/Html/HtmlSelect.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlSelect.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/HtmlSelect.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/HtmlSelect.cs.meta diff --git a/Assets/Scripts/Utils/Html/IHtmlObject.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlObject.cs similarity index 96% rename from Assets/Scripts/Utils/Html/IHtmlObject.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlObject.cs index 56e44b60..cfe2d9ab 100644 --- a/Assets/Scripts/Utils/Html/IHtmlObject.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlObject.cs @@ -1,24 +1,24 @@ -using System; -using System.Collections.Generic; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// Create->SetPosition->(Add<->Remove)->Release->Dispose - /// - public interface IHtmlObject - { - float width { get; } - float height { get; } - DisplayObject displayObject { get; } - HtmlElement element { get; } - - void Create(RichTextField owner, HtmlElement element); - void SetPosition(float x, float y); - void Add(); - void Remove(); - void Release(); - void Dispose(); - } -} +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// Create->SetPosition->(Add<->Remove)->Release->Dispose + /// + public interface IHtmlObject + { + float width { get; } + float height { get; } + DisplayObject displayObject { get; } + HtmlElement element { get; } + + void Create(RichTextField owner, HtmlElement element); + void SetPosition(float x, float y); + void Add(); + void Remove(); + void Release(); + void Dispose(); + } +} diff --git a/Assets/Scripts/Utils/Html/IHtmlObject.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlObject.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/IHtmlObject.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlObject.cs.meta diff --git a/Assets/Scripts/Utils/Html/IHtmlPageContext.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlPageContext.cs similarity index 96% rename from Assets/Scripts/Utils/Html/IHtmlPageContext.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlPageContext.cs index c1ada53f..8073e751 100644 --- a/Assets/Scripts/Utils/Html/IHtmlPageContext.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlPageContext.cs @@ -1,15 +1,15 @@ - -namespace FairyGUI.Utils -{ - /// - /// - /// - public interface IHtmlPageContext - { - IHtmlObject CreateObject(RichTextField owner, HtmlElement element); - void FreeObject(IHtmlObject obj); - - NTexture GetImageTexture(HtmlImage image); - void FreeImageTexture(HtmlImage image, NTexture texture); - } -} + +namespace FairyGUI.Utils +{ + /// + /// + /// + public interface IHtmlPageContext + { + IHtmlObject CreateObject(RichTextField owner, HtmlElement element); + void FreeObject(IHtmlObject obj); + + NTexture GetImageTexture(HtmlImage image); + void FreeImageTexture(HtmlImage image, NTexture texture); + } +} diff --git a/Assets/Scripts/Utils/Html/IHtmlPageContext.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlPageContext.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Html/IHtmlPageContext.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Html/IHtmlPageContext.cs.meta diff --git a/Assets/Scripts/Utils/Timers.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Timers.cs similarity index 100% rename from Assets/Scripts/Utils/Timers.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Timers.cs diff --git a/Assets/Scripts/Utils/Timers.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Timers.cs.meta similarity index 100% rename from Assets/Scripts/Utils/Timers.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/Timers.cs.meta diff --git a/Assets/Scripts/Utils/ToolSet.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ToolSet.cs similarity index 97% rename from Assets/Scripts/Utils/ToolSet.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ToolSet.cs index 83ffe05e..ca06b666 100644 --- a/Assets/Scripts/Utils/ToolSet.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ToolSet.cs @@ -1,136 +1,136 @@ -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public static class ToolSet - { - public static Color ConvertFromHtmlColor(string str) - { - if (str.Length < 7 || str[0] != '#') - return Color.black; - - if (str.Length == 9) - { - //optimize:avoid using Convert.ToByte and Substring - //return new Color32(Convert.ToByte(str.Substring(3, 2), 16), Convert.ToByte(str.Substring(5, 2), 16), - // Convert.ToByte(str.Substring(7, 2), 16), Convert.ToByte(str.Substring(1, 2), 16)); - - return new Color32((byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])), - (byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])), - (byte)(CharToHex(str[7]) * 16 + CharToHex(str[8])), - (byte)(CharToHex(str[1]) * 16 + CharToHex(str[2]))); - } - else - { - //return new Color32(Convert.ToByte(str.Substring(1, 2), 16), Convert.ToByte(str.Substring(3, 2), 16), - //Convert.ToByte(str.Substring(5, 2), 16), 255); - - return new Color32((byte)(CharToHex(str[1]) * 16 + CharToHex(str[2])), - (byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])), - (byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])), - 255); - } - } - - public static Color ColorFromRGB(int value) - { - return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, 1); - } - - public static Color ColorFromRGBA(uint value) - { - return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, ((value >> 24) & 0xFF) / 255f); - } - - public static int CharToHex(char c) - { - if (c >= '0' && c <= '9') - return (int)c - 48; - if (c >= 'A' && c <= 'F') - return 10 + (int)c - 65; - else if (c >= 'a' && c <= 'f') - return 10 + (int)c - 97; - else - return 0; - } - - public static Rect Intersection(ref Rect rect1, ref Rect rect2) - { - if (rect1.width == 0 || rect1.height == 0 || rect2.width == 0 || rect2.height == 0) - return new Rect(0, 0, 0, 0); - - float left = rect1.xMin > rect2.xMin ? rect1.xMin : rect2.xMin; - float right = rect1.xMax < rect2.xMax ? rect1.xMax : rect2.xMax; - float top = rect1.yMin > rect2.yMin ? rect1.yMin : rect2.yMin; - float bottom = rect1.yMax < rect2.yMax ? rect1.yMax : rect2.yMax; - - if (left > right || top > bottom) - return new Rect(0, 0, 0, 0); - else - return Rect.MinMaxRect(left, top, right, bottom); - } - - public static Rect Union(ref Rect rect1, ref Rect rect2) - { - if (rect2.width == 0 || rect2.height == 0) - return rect1; - - if (rect1.width == 0 || rect1.height == 0) - return rect2; - - float x = Mathf.Min(rect1.x, rect2.x); - float y = Mathf.Min(rect1.y, rect2.y); - return new Rect(x, y, Mathf.Max(rect1.xMax, rect2.xMax) - x, Mathf.Max(rect1.yMax, rect2.yMax) - y); - } - - public static void SkewMatrix(ref Matrix4x4 matrix, float skewX, float skewY) - { - skewX = -skewX * Mathf.Deg2Rad; - skewY = -skewY * Mathf.Deg2Rad; - float sinX = Mathf.Sin(skewX); - float cosX = Mathf.Cos(skewX); - float sinY = Mathf.Sin(skewY); - float cosY = Mathf.Cos(skewY); - - float m00 = matrix.m00 * cosY - matrix.m10 * sinX; - float m10 = matrix.m00 * sinY + matrix.m10 * cosX; - float m01 = matrix.m01 * cosY - matrix.m11 * sinX; - float m11 = matrix.m01 * sinY + matrix.m11 * cosX; - float m02 = matrix.m02 * cosY - matrix.m12 * sinX; - float m12 = matrix.m02 * sinY + matrix.m12 * cosX; - - matrix.m00 = m00; - matrix.m10 = m10; - matrix.m01 = m01; - matrix.m11 = m11; - matrix.m02 = m02; - matrix.m12 = m12; - } - - public static void RotateUV(Vector2[] uv, ref Rect baseUVRect) - { - int vertCount = uv.Length; - float xMin = Mathf.Min(baseUVRect.xMin, baseUVRect.xMax); - float yMin = baseUVRect.yMin; - float yMax = baseUVRect.yMax; - if (yMin > yMax) - { - yMin = yMax; - yMax = baseUVRect.yMin; - } - - float tmp; - for (int i = 0; i < vertCount; i++) - { - Vector2 m = uv[i]; - tmp = m.y; - m.y = yMin + m.x - xMin; - m.x = xMin + yMax - tmp; - uv[i] = m; - } - } - } -} +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public static class ToolSet + { + public static Color ConvertFromHtmlColor(string str) + { + if (str.Length < 7 || str[0] != '#') + return Color.black; + + if (str.Length == 9) + { + //optimize:avoid using Convert.ToByte and Substring + //return new Color32(Convert.ToByte(str.Substring(3, 2), 16), Convert.ToByte(str.Substring(5, 2), 16), + // Convert.ToByte(str.Substring(7, 2), 16), Convert.ToByte(str.Substring(1, 2), 16)); + + return new Color32((byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])), + (byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])), + (byte)(CharToHex(str[7]) * 16 + CharToHex(str[8])), + (byte)(CharToHex(str[1]) * 16 + CharToHex(str[2]))); + } + else + { + //return new Color32(Convert.ToByte(str.Substring(1, 2), 16), Convert.ToByte(str.Substring(3, 2), 16), + //Convert.ToByte(str.Substring(5, 2), 16), 255); + + return new Color32((byte)(CharToHex(str[1]) * 16 + CharToHex(str[2])), + (byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])), + (byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])), + 255); + } + } + + public static Color ColorFromRGB(int value) + { + return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, 1); + } + + public static Color ColorFromRGBA(uint value) + { + return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, ((value >> 24) & 0xFF) / 255f); + } + + public static int CharToHex(char c) + { + if (c >= '0' && c <= '9') + return (int)c - 48; + if (c >= 'A' && c <= 'F') + return 10 + (int)c - 65; + else if (c >= 'a' && c <= 'f') + return 10 + (int)c - 97; + else + return 0; + } + + public static Rect Intersection(ref Rect rect1, ref Rect rect2) + { + if (rect1.width == 0 || rect1.height == 0 || rect2.width == 0 || rect2.height == 0) + return new Rect(0, 0, 0, 0); + + float left = rect1.xMin > rect2.xMin ? rect1.xMin : rect2.xMin; + float right = rect1.xMax < rect2.xMax ? rect1.xMax : rect2.xMax; + float top = rect1.yMin > rect2.yMin ? rect1.yMin : rect2.yMin; + float bottom = rect1.yMax < rect2.yMax ? rect1.yMax : rect2.yMax; + + if (left > right || top > bottom) + return new Rect(0, 0, 0, 0); + else + return Rect.MinMaxRect(left, top, right, bottom); + } + + public static Rect Union(ref Rect rect1, ref Rect rect2) + { + if (rect2.width == 0 || rect2.height == 0) + return rect1; + + if (rect1.width == 0 || rect1.height == 0) + return rect2; + + float x = Mathf.Min(rect1.x, rect2.x); + float y = Mathf.Min(rect1.y, rect2.y); + return new Rect(x, y, Mathf.Max(rect1.xMax, rect2.xMax) - x, Mathf.Max(rect1.yMax, rect2.yMax) - y); + } + + public static void SkewMatrix(ref Matrix4x4 matrix, float skewX, float skewY) + { + skewX = -skewX * Mathf.Deg2Rad; + skewY = -skewY * Mathf.Deg2Rad; + float sinX = Mathf.Sin(skewX); + float cosX = Mathf.Cos(skewX); + float sinY = Mathf.Sin(skewY); + float cosY = Mathf.Cos(skewY); + + float m00 = matrix.m00 * cosY - matrix.m10 * sinX; + float m10 = matrix.m00 * sinY + matrix.m10 * cosX; + float m01 = matrix.m01 * cosY - matrix.m11 * sinX; + float m11 = matrix.m01 * sinY + matrix.m11 * cosX; + float m02 = matrix.m02 * cosY - matrix.m12 * sinX; + float m12 = matrix.m02 * sinY + matrix.m12 * cosX; + + matrix.m00 = m00; + matrix.m10 = m10; + matrix.m01 = m01; + matrix.m11 = m11; + matrix.m02 = m02; + matrix.m12 = m12; + } + + public static void RotateUV(Vector2[] uv, ref Rect baseUVRect) + { + int vertCount = uv.Length; + float xMin = Mathf.Min(baseUVRect.xMin, baseUVRect.xMax); + float yMin = baseUVRect.yMin; + float yMax = baseUVRect.yMax; + if (yMin > yMax) + { + yMin = yMax; + yMax = baseUVRect.yMin; + } + + float tmp; + for (int i = 0; i < vertCount; i++) + { + Vector2 m = uv[i]; + tmp = m.y; + m.y = yMin + m.x - xMin; + m.x = xMin + yMax - tmp; + uv[i] = m; + } + } + } +} diff --git a/Assets/Scripts/Utils/ToolSet.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ToolSet.cs.meta similarity index 100% rename from Assets/Scripts/Utils/ToolSet.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ToolSet.cs.meta diff --git a/Assets/Scripts/Utils/UBBParser.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/UBBParser.cs similarity index 96% rename from Assets/Scripts/Utils/UBBParser.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/UBBParser.cs index b2d6d380..dcbbff23 100644 --- a/Assets/Scripts/Utils/UBBParser.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/UBBParser.cs @@ -1,226 +1,226 @@ -using System.Collections.Generic; -using System.Text; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class UBBParser - { - public static UBBParser inst = new UBBParser(); - - string _text; - int _readPos; - - public TagHandler defaultTagHandler; - public Dictionary handlers; - - public int defaultImgWidth = 0; - public int defaultImgHeight = 0; - - public delegate string TagHandler(string tagName, bool end, string attr); - - public UBBParser() - { - handlers = new Dictionary(); - handlers["url"] = onTag_URL; - handlers["img"] = onTag_IMG; - handlers["b"] = onTag_Simple; - handlers["i"] = onTag_Simple; - handlers["u"] = onTag_Simple; - handlers["sup"] = onTag_Simple; - handlers["sub"] = onTag_Simple; - handlers["color"] = onTag_COLOR; - handlers["font"] = onTag_FONT; - handlers["size"] = onTag_SIZE; - handlers["align"] = onTag_ALIGN; - handlers["strike"] = onTag_Simple; - } - - protected string onTag_URL(string tagName, bool end, string attr) - { - if (!end) - { - if (attr != null) - return ""; - else - { - string href = GetTagText(false); - return ""; - } - } - else - return ""; - } - - protected string onTag_IMG(string tagName, bool end, string attr) - { - if (!end) - { - string src = GetTagText(true); - if (src == null || src.Length == 0) - return null; - - if (defaultImgWidth != 0) - return ""; - else - return ""; - } - else - return null; - } - - protected string onTag_Simple(string tagName, bool end, string attr) - { - return end ? ("") : ("<" + tagName + ">"); - } - - protected string onTag_COLOR(string tagName, bool end, string attr) - { - if (!end) - return ""; - else - return ""; - } - - protected string onTag_FONT(string tagName, bool end, string attr) - { - if (!end) - return ""; - else - return ""; - } - - protected string onTag_SIZE(string tagName, bool end, string attr) - { - if (!end) - return ""; - else - return ""; - } - - protected string onTag_ALIGN(string tagName, bool end, string attr) - { - if (!end) - return "

"; - else - return "

"; - } - - public string GetTagText(bool remove) - { - int pos1 = _readPos; - int pos2; - StringBuilder buffer = null; - while ((pos2 = _text.IndexOf('[', pos1)) != -1) - { - if (buffer == null) - buffer = new StringBuilder(); - - if (_text[pos2 - 1] == '\\') - { - buffer.Append(_text, pos1, pos2 - pos1 - 1); - buffer.Append('['); - pos1 = pos2 + 1; - } - else - { - buffer.Append(_text, pos1, pos2 - pos1); - break; - } - } - if (pos2 == -1) - return null; - - if (remove) - _readPos = pos2; - - return buffer.ToString(); - } - - public string Parse(string text) - { - _text = text; - int pos1 = 0, pos2, pos3; - bool end; - string tag, attr; - string repl; - StringBuilder buffer = null; - TagHandler func; - while ((pos2 = _text.IndexOf('[', pos1)) != -1) - { - if (buffer == null) - buffer = new StringBuilder(); - - if (pos2 > 0 && _text[pos2 - 1] == '\\') - { - buffer.Append(_text, pos1, pos2 - pos1 - 1); - buffer.Append('['); - pos1 = pos2 + 1; - continue; - } - - buffer.Append(_text, pos1, pos2 - pos1); - pos1 = pos2; - pos2 = _text.IndexOf(']', pos1); - if (pos2 == -1) - break; - - if (pos2 == pos1 + 1) - { - buffer.Append(_text, pos1, 2); - pos1 = pos2 + 1; - continue; - } - - end = _text[pos1 + 1] == '/'; - pos3 = end ? pos1 + 2 : pos1 + 1; - tag = _text.Substring(pos3, pos2 - pos3); - _readPos = pos2 + 1; - attr = null; - repl = null; - pos3 = tag.IndexOf('='); - if (pos3 != -1) - { - attr = tag.Substring(pos3 + 1); - tag = tag.Substring(0, pos3); - } - tag = tag.ToLower(); - if (handlers.TryGetValue(tag, out func)) - { - repl = func(tag, end, attr); - if (repl != null) - buffer.Append(repl); - } - else if (defaultTagHandler != null) - { - repl = defaultTagHandler(tag, end, attr); - if (repl != null) - buffer.Append(repl); - else - buffer.Append(_text, pos1, pos2 - pos1 + 1); - } - else - { - buffer.Append(_text, pos1, pos2 - pos1 + 1); - } - pos1 = _readPos; - } - - if (buffer == null) - { - _text = null; - return text; - } - else - { - if (pos1 < _text.Length) - buffer.Append(_text, pos1, _text.Length - pos1); - - _text = null; - return buffer.ToString(); - } - } - } -} +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class UBBParser + { + public static UBBParser inst = new UBBParser(); + + string _text; + int _readPos; + + public TagHandler defaultTagHandler; + public Dictionary handlers; + + public int defaultImgWidth = 0; + public int defaultImgHeight = 0; + + public delegate string TagHandler(string tagName, bool end, string attr); + + public UBBParser() + { + handlers = new Dictionary(); + handlers["url"] = onTag_URL; + handlers["img"] = onTag_IMG; + handlers["b"] = onTag_Simple; + handlers["i"] = onTag_Simple; + handlers["u"] = onTag_Simple; + handlers["sup"] = onTag_Simple; + handlers["sub"] = onTag_Simple; + handlers["color"] = onTag_COLOR; + handlers["font"] = onTag_FONT; + handlers["size"] = onTag_SIZE; + handlers["align"] = onTag_ALIGN; + handlers["strike"] = onTag_Simple; + } + + protected string onTag_URL(string tagName, bool end, string attr) + { + if (!end) + { + if (attr != null) + return ""; + else + { + string href = GetTagText(false); + return ""; + } + } + else + return ""; + } + + protected string onTag_IMG(string tagName, bool end, string attr) + { + if (!end) + { + string src = GetTagText(true); + if (src == null || src.Length == 0) + return null; + + if (defaultImgWidth != 0) + return ""; + else + return ""; + } + else + return null; + } + + protected string onTag_Simple(string tagName, bool end, string attr) + { + return end ? ("") : ("<" + tagName + ">"); + } + + protected string onTag_COLOR(string tagName, bool end, string attr) + { + if (!end) + return ""; + else + return ""; + } + + protected string onTag_FONT(string tagName, bool end, string attr) + { + if (!end) + return ""; + else + return ""; + } + + protected string onTag_SIZE(string tagName, bool end, string attr) + { + if (!end) + return ""; + else + return ""; + } + + protected string onTag_ALIGN(string tagName, bool end, string attr) + { + if (!end) + return "

"; + else + return "

"; + } + + public string GetTagText(bool remove) + { + int pos1 = _readPos; + int pos2; + StringBuilder buffer = null; + while ((pos2 = _text.IndexOf('[', pos1)) != -1) + { + if (buffer == null) + buffer = new StringBuilder(); + + if (_text[pos2 - 1] == '\\') + { + buffer.Append(_text, pos1, pos2 - pos1 - 1); + buffer.Append('['); + pos1 = pos2 + 1; + } + else + { + buffer.Append(_text, pos1, pos2 - pos1); + break; + } + } + if (pos2 == -1) + return null; + + if (remove) + _readPos = pos2; + + return buffer.ToString(); + } + + public string Parse(string text) + { + _text = text; + int pos1 = 0, pos2, pos3; + bool end; + string tag, attr; + string repl; + StringBuilder buffer = null; + TagHandler func; + while ((pos2 = _text.IndexOf('[', pos1)) != -1) + { + if (buffer == null) + buffer = new StringBuilder(); + + if (pos2 > 0 && _text[pos2 - 1] == '\\') + { + buffer.Append(_text, pos1, pos2 - pos1 - 1); + buffer.Append('['); + pos1 = pos2 + 1; + continue; + } + + buffer.Append(_text, pos1, pos2 - pos1); + pos1 = pos2; + pos2 = _text.IndexOf(']', pos1); + if (pos2 == -1) + break; + + if (pos2 == pos1 + 1) + { + buffer.Append(_text, pos1, 2); + pos1 = pos2 + 1; + continue; + } + + end = _text[pos1 + 1] == '/'; + pos3 = end ? pos1 + 2 : pos1 + 1; + tag = _text.Substring(pos3, pos2 - pos3); + _readPos = pos2 + 1; + attr = null; + repl = null; + pos3 = tag.IndexOf('='); + if (pos3 != -1) + { + attr = tag.Substring(pos3 + 1); + tag = tag.Substring(0, pos3); + } + tag = tag.ToLower(); + if (handlers.TryGetValue(tag, out func)) + { + repl = func(tag, end, attr); + if (repl != null) + buffer.Append(repl); + } + else if (defaultTagHandler != null) + { + repl = defaultTagHandler(tag, end, attr); + if (repl != null) + buffer.Append(repl); + else + buffer.Append(_text, pos1, pos2 - pos1 + 1); + } + else + { + buffer.Append(_text, pos1, pos2 - pos1 + 1); + } + pos1 = _readPos; + } + + if (buffer == null) + { + _text = null; + return text; + } + else + { + if (pos1 < _text.Length) + buffer.Append(_text, pos1, _text.Length - pos1); + + _text = null; + return buffer.ToString(); + } + } + } +} diff --git a/Assets/Scripts/Utils/UBBParser.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/UBBParser.cs.meta similarity index 100% rename from Assets/Scripts/Utils/UBBParser.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/UBBParser.cs.meta diff --git a/Assets/Scripts/Utils/XML.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XML.cs similarity index 96% rename from Assets/Scripts/Utils/XML.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XML.cs index 6a5538f4..788b7c6d 100644 --- a/Assets/Scripts/Utils/XML.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XML.cs @@ -1,427 +1,427 @@ -using System; -using System.Collections.Generic; -using System.Text; -using UnityEngine; - -namespace FairyGUI.Utils -{ - /// - /// A simplest and readonly XML class - /// - public class XML - { - public string name; - public string text; - - Dictionary _attributes; - XMLList _children; - - public static XML Create(string tag) - { - XML xml = new XML(); - xml.name = tag; - return xml; - } - - public XML(string XmlString) - { - Parse(XmlString); - } - - private XML() - { - } - - public Dictionary attributes - { - get - { - if (_attributes == null) - _attributes = new Dictionary(); - return _attributes; - } - } - - public bool HasAttribute(string attrName) - { - if (_attributes == null) - return false; - - return _attributes.ContainsKey(attrName); - } - - public string GetAttribute(string attrName) - { - return GetAttribute(attrName, null); - } - - public string GetAttribute(string attrName, string defValue) - { - if (_attributes == null) - return defValue; - - string ret; - if (_attributes.TryGetValue(attrName, out ret)) - return ret; - else - return defValue; - } - - public int GetAttributeInt(string attrName) - { - return GetAttributeInt(attrName, 0); - } - - public int GetAttributeInt(string attrName, int defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - int ret; - if (int.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public float GetAttributeFloat(string attrName) - { - return GetAttributeFloat(attrName, 0); - } - - public float GetAttributeFloat(string attrName, float defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - float ret; - if (float.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public bool GetAttributeBool(string attrName) - { - return GetAttributeBool(attrName, false); - } - - public bool GetAttributeBool(string attrName, bool defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - bool ret; - if (bool.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public string[] GetAttributeArray(string attrName) - { - string value = GetAttribute(attrName); - if (value != null) - { - if (value.Length == 0) - return new string[] { }; - else - return value.Split(','); - } - else - return null; - } - - public string[] GetAttributeArray(string attrName, char seperator) - { - string value = GetAttribute(attrName); - if (value != null) - { - if (value.Length == 0) - return new string[] { }; - else - return value.Split(seperator); - } - else - return null; - } - - public Color GetAttributeColor(string attrName, Color defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - return ToolSet.ConvertFromHtmlColor(value); - } - - public Vector2 GetAttributeVector(string attrName) - { - string value = GetAttribute(attrName); - if (value != null) - { - string[] arr = value.Split(','); - return new Vector2(float.Parse(arr[0]), float.Parse(arr[1])); - } - else - return Vector2.zero; - } - - public void SetAttribute(string attrName, string attrValue) - { - if (_attributes == null) - _attributes = new Dictionary(); - - _attributes[attrName] = attrValue; - } - - public void SetAttribute(string attrName, bool attrValue) - { - if (_attributes == null) - _attributes = new Dictionary(); - - _attributes[attrName] = attrValue ? "true" : "false"; - } - - public void SetAttribute(string attrName, int attrValue) - { - if (_attributes == null) - _attributes = new Dictionary(); - - _attributes[attrName] = attrValue.ToString(); - } - - public void SetAttribute(string attrName, float attrValue) - { - if (_attributes == null) - _attributes = new Dictionary(); - - _attributes[attrName] = string.Format("{0:#.####}", attrValue); - } - - public void RemoveAttribute(string attrName) - { - if (_attributes != null) - _attributes.Remove(attrName); - } - - public XML GetNode(string selector) - { - if (_children == null) - return null; - else - return _children.Find(selector); - } - - public XMLList elements - { - get - { - if (_children == null) - _children = new XMLList(); - return _children; - } - } - - public XMLList Elements() - { - if (_children == null) - _children = new XMLList(); - return _children; - } - - public XMLList Elements(string selector) - { - if (_children == null) - _children = new XMLList(); - return _children.Filter(selector); - } - - public XMLList.Enumerator GetEnumerator() - { - if (_children == null) - return new XMLList.Enumerator(null, null); - else - return new XMLList.Enumerator(_children.rawList, null); - } - - public XMLList.Enumerator GetEnumerator(string selector) - { - if (_children == null) - return new XMLList.Enumerator(null, selector); - else - return new XMLList.Enumerator(_children.rawList, selector); - } - - public void AppendChild(XML child) - { - this.elements.Add(child); - } - - public void RemoveChild(XML child) - { - if (_children == null) - return; - - this._children.rawList.Remove(child); - } - - public void RemoveChildren(string selector) - { - if (_children == null) - return; - - if (string.IsNullOrEmpty(selector)) - _children.Clear(); - else - _children.RemoveAll(selector); - } - - static Stack sNodeStack = new Stack(); - public void Parse(string aSource) - { - Reset(); - - XML lastOpenNode = null; - sNodeStack.Clear(); - - XMLIterator.Begin(aSource); - while (XMLIterator.NextTag()) - { - if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) - { - XML childNode; - if (lastOpenNode != null) - childNode = new XML(); - else - { - if (this.name != null) - { - Reset(); - throw new Exception("Invalid xml format - no root node."); - } - childNode = this; - } - - childNode.name = XMLIterator.tagName; - childNode._attributes = XMLIterator.GetAttributes(childNode._attributes); - - if (lastOpenNode != null) - { - if (XMLIterator.tagType != XMLTagType.Void) - sNodeStack.Push(lastOpenNode); - if (lastOpenNode._children == null) - lastOpenNode._children = new XMLList(); - lastOpenNode._children.Add(childNode); - } - if (XMLIterator.tagType != XMLTagType.Void) - lastOpenNode = childNode; - } - else if (XMLIterator.tagType == XMLTagType.End) - { - if (lastOpenNode == null || lastOpenNode.name != XMLIterator.tagName) - { - Reset(); - throw new Exception("Invalid xml format - <" + XMLIterator.tagName + "> dismatched."); - } - - if (lastOpenNode._children == null || lastOpenNode._children.Count == 0) - { - lastOpenNode.text = XMLIterator.GetText(); - } - - if (sNodeStack.Count > 0) - lastOpenNode = sNodeStack.Pop(); - else - lastOpenNode = null; - } - } - } - - public void Reset() - { - if (_attributes != null) - _attributes.Clear(); - if (_children != null) - _children.Clear(); - this.text = null; - } - - public string ToXMLString(bool includeHeader) - { - StringBuilder sb = new StringBuilder(); - if (includeHeader) - sb.Append("\n"); - ToXMLString(sb, 0); - return sb.ToString(); - } - - void ToXMLString(StringBuilder sb, int tabs) - { - if (tabs > 0) - sb.Append(' ', tabs * 2); - - if (name == "!") - { - sb.Append(""); - return; - } - - sb.Append('<').Append(name); - if (_attributes != null) - { - foreach (KeyValuePair kv in _attributes) - { - sb.Append(' '); - sb.Append(kv.Key).Append('=').Append('\"'); - int c = sb.Length; - sb.Append(kv.Value); - XMLUtils.EncodeString(sb, c, true); - sb.Append("\""); - } - } - - int numChildren = _children != null ? _children.Count : 0; - - if (string.IsNullOrEmpty(text) && numChildren == 0) - sb.Append("/>"); - else - { - sb.Append('>'); - - if (!string.IsNullOrEmpty(text)) - { - int c = sb.Length; - sb.Append(text); - XMLUtils.EncodeString(sb, c); - } - - if (numChildren > 0) - { - sb.Append('\n'); - int ctabs = tabs + 1; - for (int i = 0; i < numChildren; i++) - { - _children[i].ToXMLString(sb, ctabs); - sb.Append('\n'); - } - - if (tabs > 0) - sb.Append(' ', tabs * 2); - } - - sb.Append(""); - } - } - } +using System; +using System.Collections.Generic; +using System.Text; +using UnityEngine; + +namespace FairyGUI.Utils +{ + /// + /// A simplest and readonly XML class + /// + public class XML + { + public string name; + public string text; + + Dictionary _attributes; + XMLList _children; + + public static XML Create(string tag) + { + XML xml = new XML(); + xml.name = tag; + return xml; + } + + public XML(string XmlString) + { + Parse(XmlString); + } + + private XML() + { + } + + public Dictionary attributes + { + get + { + if (_attributes == null) + _attributes = new Dictionary(); + return _attributes; + } + } + + public bool HasAttribute(string attrName) + { + if (_attributes == null) + return false; + + return _attributes.ContainsKey(attrName); + } + + public string GetAttribute(string attrName) + { + return GetAttribute(attrName, null); + } + + public string GetAttribute(string attrName, string defValue) + { + if (_attributes == null) + return defValue; + + string ret; + if (_attributes.TryGetValue(attrName, out ret)) + return ret; + else + return defValue; + } + + public int GetAttributeInt(string attrName) + { + return GetAttributeInt(attrName, 0); + } + + public int GetAttributeInt(string attrName, int defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + int ret; + if (int.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public float GetAttributeFloat(string attrName) + { + return GetAttributeFloat(attrName, 0); + } + + public float GetAttributeFloat(string attrName, float defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + float ret; + if (float.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public bool GetAttributeBool(string attrName) + { + return GetAttributeBool(attrName, false); + } + + public bool GetAttributeBool(string attrName, bool defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + bool ret; + if (bool.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public string[] GetAttributeArray(string attrName) + { + string value = GetAttribute(attrName); + if (value != null) + { + if (value.Length == 0) + return new string[] { }; + else + return value.Split(','); + } + else + return null; + } + + public string[] GetAttributeArray(string attrName, char seperator) + { + string value = GetAttribute(attrName); + if (value != null) + { + if (value.Length == 0) + return new string[] { }; + else + return value.Split(seperator); + } + else + return null; + } + + public Color GetAttributeColor(string attrName, Color defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + return ToolSet.ConvertFromHtmlColor(value); + } + + public Vector2 GetAttributeVector(string attrName) + { + string value = GetAttribute(attrName); + if (value != null) + { + string[] arr = value.Split(','); + return new Vector2(float.Parse(arr[0]), float.Parse(arr[1])); + } + else + return Vector2.zero; + } + + public void SetAttribute(string attrName, string attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = attrValue; + } + + public void SetAttribute(string attrName, bool attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = attrValue ? "true" : "false"; + } + + public void SetAttribute(string attrName, int attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = attrValue.ToString(); + } + + public void SetAttribute(string attrName, float attrValue) + { + if (_attributes == null) + _attributes = new Dictionary(); + + _attributes[attrName] = string.Format("{0:#.####}", attrValue); + } + + public void RemoveAttribute(string attrName) + { + if (_attributes != null) + _attributes.Remove(attrName); + } + + public XML GetNode(string selector) + { + if (_children == null) + return null; + else + return _children.Find(selector); + } + + public XMLList elements + { + get + { + if (_children == null) + _children = new XMLList(); + return _children; + } + } + + public XMLList Elements() + { + if (_children == null) + _children = new XMLList(); + return _children; + } + + public XMLList Elements(string selector) + { + if (_children == null) + _children = new XMLList(); + return _children.Filter(selector); + } + + public XMLList.Enumerator GetEnumerator() + { + if (_children == null) + return new XMLList.Enumerator(null, null); + else + return new XMLList.Enumerator(_children.rawList, null); + } + + public XMLList.Enumerator GetEnumerator(string selector) + { + if (_children == null) + return new XMLList.Enumerator(null, selector); + else + return new XMLList.Enumerator(_children.rawList, selector); + } + + public void AppendChild(XML child) + { + this.elements.Add(child); + } + + public void RemoveChild(XML child) + { + if (_children == null) + return; + + this._children.rawList.Remove(child); + } + + public void RemoveChildren(string selector) + { + if (_children == null) + return; + + if (string.IsNullOrEmpty(selector)) + _children.Clear(); + else + _children.RemoveAll(selector); + } + + static Stack sNodeStack = new Stack(); + public void Parse(string aSource) + { + Reset(); + + XML lastOpenNode = null; + sNodeStack.Clear(); + + XMLIterator.Begin(aSource); + while (XMLIterator.NextTag()) + { + if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) + { + XML childNode; + if (lastOpenNode != null) + childNode = new XML(); + else + { + if (this.name != null) + { + Reset(); + throw new Exception("Invalid xml format - no root node."); + } + childNode = this; + } + + childNode.name = XMLIterator.tagName; + childNode._attributes = XMLIterator.GetAttributes(childNode._attributes); + + if (lastOpenNode != null) + { + if (XMLIterator.tagType != XMLTagType.Void) + sNodeStack.Push(lastOpenNode); + if (lastOpenNode._children == null) + lastOpenNode._children = new XMLList(); + lastOpenNode._children.Add(childNode); + } + if (XMLIterator.tagType != XMLTagType.Void) + lastOpenNode = childNode; + } + else if (XMLIterator.tagType == XMLTagType.End) + { + if (lastOpenNode == null || lastOpenNode.name != XMLIterator.tagName) + { + Reset(); + throw new Exception("Invalid xml format - <" + XMLIterator.tagName + "> dismatched."); + } + + if (lastOpenNode._children == null || lastOpenNode._children.Count == 0) + { + lastOpenNode.text = XMLIterator.GetText(); + } + + if (sNodeStack.Count > 0) + lastOpenNode = sNodeStack.Pop(); + else + lastOpenNode = null; + } + } + } + + public void Reset() + { + if (_attributes != null) + _attributes.Clear(); + if (_children != null) + _children.Clear(); + this.text = null; + } + + public string ToXMLString(bool includeHeader) + { + StringBuilder sb = new StringBuilder(); + if (includeHeader) + sb.Append("\n"); + ToXMLString(sb, 0); + return sb.ToString(); + } + + void ToXMLString(StringBuilder sb, int tabs) + { + if (tabs > 0) + sb.Append(' ', tabs * 2); + + if (name == "!") + { + sb.Append(""); + return; + } + + sb.Append('<').Append(name); + if (_attributes != null) + { + foreach (KeyValuePair kv in _attributes) + { + sb.Append(' '); + sb.Append(kv.Key).Append('=').Append('\"'); + int c = sb.Length; + sb.Append(kv.Value); + XMLUtils.EncodeString(sb, c, true); + sb.Append("\""); + } + } + + int numChildren = _children != null ? _children.Count : 0; + + if (string.IsNullOrEmpty(text) && numChildren == 0) + sb.Append("/>"); + else + { + sb.Append('>'); + + if (!string.IsNullOrEmpty(text)) + { + int c = sb.Length; + sb.Append(text); + XMLUtils.EncodeString(sb, c); + } + + if (numChildren > 0) + { + sb.Append('\n'); + int ctabs = tabs + 1; + for (int i = 0; i < numChildren; i++) + { + _children[i].ToXMLString(sb, ctabs); + sb.Append('\n'); + } + + if (tabs > 0) + sb.Append(' ', tabs * 2); + } + + sb.Append(""); + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/Utils/XML.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XML.cs.meta similarity index 100% rename from Assets/Scripts/Utils/XML.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XML.cs.meta diff --git a/Assets/Scripts/Utils/XMLIterator.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLIterator.cs similarity index 96% rename from Assets/Scripts/Utils/XMLIterator.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLIterator.cs index 27953762..34151703 100644 --- a/Assets/Scripts/Utils/XMLIterator.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLIterator.cs @@ -1,485 +1,485 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; - -namespace FairyGUI.Utils -{ - public enum XMLTagType - { - Start, - End, - Void, - CDATA, - Comment, - Instruction - } - - /// - /// - /// - public class XMLIterator - { - public static string tagName; - public static XMLTagType tagType; - public static string lastTagName; - - static string source; - static int sourceLen; - static int parsePos; - static int tagPos; - static int tagLength; - static int lastTagEnd; - static bool attrParsed; - static bool lowerCaseName; - static StringBuilder buffer = new StringBuilder(); - static Dictionary attributes = new Dictionary(); - - const string CDATA_START = ""; - const string COMMENT_START = ""; - - public static void Begin(string source, bool lowerCaseName = false) - { - XMLIterator.source = source; - XMLIterator.lowerCaseName = lowerCaseName; - sourceLen = source.Length; - parsePos = 0; - lastTagEnd = 0; - tagPos = 0; - tagLength = 0; - tagName = null; - } - - public static bool NextTag() - { - int pos; - char c; - tagType = XMLTagType.Start; - buffer.Length = 0; - lastTagEnd = parsePos; - attrParsed = false; - lastTagName = tagName; - - while ((pos = source.IndexOf('<', parsePos)) != -1) - { - parsePos = pos; - pos++; - - if (pos == sourceLen) - break; - - c = source[pos]; - if (c == '!') - { - if (sourceLen > pos + 7 && source.Substring(pos - 1, 9) == CDATA_START) - { - pos = source.IndexOf(CDATA_END, pos); - tagType = XMLTagType.CDATA; - tagName = string.Empty; - tagPos = parsePos; - if (pos == -1) - tagLength = sourceLen - parsePos; - else - tagLength = pos + 3 - parsePos; - parsePos += tagLength; - return true; - } - else if (sourceLen > pos + 2 && source.Substring(pos - 1, 4) == COMMENT_START) - { - pos = source.IndexOf(COMMENT_END, pos); - tagType = XMLTagType.Comment; - tagName = string.Empty; - tagPos = parsePos; - if (pos == -1) - tagLength = sourceLen - parsePos; - else - tagLength = pos + 3 - parsePos; - parsePos += tagLength; - return true; - } - else - { - pos++; - tagType = XMLTagType.Instruction; - } - } - else if (c == '/') - { - pos++; - tagType = XMLTagType.End; - } - else if (c == '?') - { - pos++; - tagType = XMLTagType.Instruction; - } - - for (; pos < sourceLen; pos++) - { - c = source[pos]; - if (Char.IsWhiteSpace(c) || c == '>' || c == '/') - break; - } - if (pos == sourceLen) - break; - - buffer.Append(source, parsePos + 1, pos - parsePos - 1); - if (buffer.Length > 0 && buffer[0] == '/') - buffer.Remove(0, 1); - - bool singleQuoted = false, doubleQuoted = false; - int possibleEnd = -1; - for (; pos < sourceLen; pos++) - { - c = source[pos]; - if (c == '"') - { - if (!singleQuoted) - doubleQuoted = !doubleQuoted; - } - else if (c == '\'') - { - if (!doubleQuoted) - singleQuoted = !singleQuoted; - } - - if (c == '>') - { - if (!(singleQuoted || doubleQuoted)) - { - possibleEnd = -1; - break; - } - - possibleEnd = pos; - } - else if (c == '<') - break; - } - if (possibleEnd != -1) - pos = possibleEnd; - - if (pos == sourceLen) - break; - - if (source[pos - 1] == '/') - tagType = XMLTagType.Void; - - tagName = buffer.ToString(); - if (lowerCaseName) - tagName = tagName.ToLower(); - tagPos = parsePos; - tagLength = pos + 1 - parsePos; - parsePos += tagLength; - - return true; - } - - tagPos = sourceLen; - tagLength = 0; - tagName = null; - return false; - } - - public static string GetTagSource() - { - return source.Substring(tagPos, tagLength); - } - - public static string GetRawText(bool trim = false) - { - if (lastTagEnd == tagPos) - return string.Empty; - else if (trim) - { - int i = lastTagEnd; - for (; i < tagPos; i++) - { - char c = source[i]; - if (!char.IsWhiteSpace(c)) - break; - } - - if (i == tagPos) - return string.Empty; - else - return source.Substring(i, tagPos - i).TrimEnd(); - } - else - return source.Substring(lastTagEnd, tagPos - lastTagEnd); - } - - public static string GetText(bool trim = false) - { - if (lastTagEnd == tagPos) - return string.Empty; - else if (trim) - { - int i = lastTagEnd; - for (; i < tagPos; i++) - { - char c = source[i]; - if (!char.IsWhiteSpace(c)) - break; - } - - if (i == tagPos) - return string.Empty; - else - return XMLUtils.DecodeString(source.Substring(i, tagPos - i).TrimEnd()); - } - else - return XMLUtils.DecodeString(source.Substring(lastTagEnd, tagPos - lastTagEnd)); - } - - public static bool HasAttribute(string attrName) - { - if (!attrParsed) - { - attributes.Clear(); - ParseAttributes(attributes); - attrParsed = true; - } - - return attributes.ContainsKey(attrName); - } - - public static string GetAttribute(string attrName) - { - if (!attrParsed) - { - attributes.Clear(); - ParseAttributes(attributes); - attrParsed = true; - } - - string value; - if (attributes.TryGetValue(attrName, out value)) - return value; - else - return null; - } - - public static string GetAttribute(string attrName, string defValue) - { - string ret = GetAttribute(attrName); - if (ret != null) - return ret; - else - return defValue; - } - - public static int GetAttributeInt(string attrName) - { - return GetAttributeInt(attrName, 0); - } - - public static int GetAttributeInt(string attrName, int defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - int ret; - if (int.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public static float GetAttributeFloat(string attrName) - { - return GetAttributeFloat(attrName, 0); - } - - public static float GetAttributeFloat(string attrName, float defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - float ret; - if (float.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public static bool GetAttributeBool(string attrName) - { - return GetAttributeBool(attrName, false); - } - - public static bool GetAttributeBool(string attrName, bool defValue) - { - string value = GetAttribute(attrName); - if (value == null || value.Length == 0) - return defValue; - - bool ret; - if (bool.TryParse(value, out ret)) - return ret; - else - return defValue; - } - - public static Dictionary GetAttributes(Dictionary result) - { - if (result == null) - result = new Dictionary(); - - if (attrParsed) - { - foreach (KeyValuePair kv in attributes) - result[kv.Key] = kv.Value; - } - else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作 - ParseAttributes(result); - - return result; - } - - public static Hashtable GetAttributes(Hashtable result) - { - if (result == null) - result = new Hashtable(); - - if (attrParsed) - { - foreach (KeyValuePair kv in attributes) - result[kv.Key] = kv.Value; - } - else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作 - ParseAttributes(result); - - return result; - } - - static void ParseAttributes(IDictionary attrs) - { - string attrName; - int valueStart; - int valueEnd; - bool waitValue = false; - int quoted; - buffer.Length = 0; - int i = tagPos; - int attrEnd = tagPos + tagLength; - - if (i < attrEnd && source[i] == '<') - { - for (; i < attrEnd; i++) - { - char c = source[i]; - if (Char.IsWhiteSpace(c) || c == '>' || c == '/') - break; - } - } - - for (; i < attrEnd; i++) - { - char c = source[i]; - if (c == '=') - { - valueStart = -1; - valueEnd = -1; - quoted = 0; - for (int j = i + 1; j < attrEnd; j++) - { - char c2 = source[j]; - if (Char.IsWhiteSpace(c2)) - { - if (valueStart != -1 && quoted == 0) - { - valueEnd = j - 1; - break; - } - } - else if (c2 == '>') - { - if (quoted == 0) - { - valueEnd = j - 1; - break; - } - } - else if (c2 == '"') - { - if (valueStart != -1) - { - if (quoted != 1) - { - valueEnd = j - 1; - break; - } - } - else - { - quoted = 2; - valueStart = j + 1; - } - } - else if (c2 == '\'') - { - if (valueStart != -1) - { - if (quoted != 2) - { - valueEnd = j - 1; - break; - } - } - else - { - quoted = 1; - valueStart = j + 1; - } - } - else if (valueStart == -1) - { - valueStart = j; - } - } - - if (valueStart != -1 && valueEnd != -1) - { - attrName = buffer.ToString(); - if (lowerCaseName) - attrName = attrName.ToLower(); - buffer.Length = 0; - attrs[attrName] = XMLUtils.DecodeString(source.Substring(valueStart, valueEnd - valueStart + 1)); - i = valueEnd + 1; - } - else - break; - } - else if (!Char.IsWhiteSpace(c)) - { - if (waitValue || c == '/' || c == '>') - { - if (buffer.Length > 0) - { - attrName = buffer.ToString(); - if (lowerCaseName) - attrName = attrName.ToLower(); - attrs[attrName] = string.Empty; - buffer.Length = 0; - } - - waitValue = false; - } - - if (c != '/' && c != '>') - buffer.Append(c); - } - else - { - if (buffer.Length > 0) - waitValue = true; - } - } - } - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; + +namespace FairyGUI.Utils +{ + public enum XMLTagType + { + Start, + End, + Void, + CDATA, + Comment, + Instruction + } + + /// + /// + /// + public class XMLIterator + { + public static string tagName; + public static XMLTagType tagType; + public static string lastTagName; + + static string source; + static int sourceLen; + static int parsePos; + static int tagPos; + static int tagLength; + static int lastTagEnd; + static bool attrParsed; + static bool lowerCaseName; + static StringBuilder buffer = new StringBuilder(); + static Dictionary attributes = new Dictionary(); + + const string CDATA_START = ""; + const string COMMENT_START = ""; + + public static void Begin(string source, bool lowerCaseName = false) + { + XMLIterator.source = source; + XMLIterator.lowerCaseName = lowerCaseName; + sourceLen = source.Length; + parsePos = 0; + lastTagEnd = 0; + tagPos = 0; + tagLength = 0; + tagName = null; + } + + public static bool NextTag() + { + int pos; + char c; + tagType = XMLTagType.Start; + buffer.Length = 0; + lastTagEnd = parsePos; + attrParsed = false; + lastTagName = tagName; + + while ((pos = source.IndexOf('<', parsePos)) != -1) + { + parsePos = pos; + pos++; + + if (pos == sourceLen) + break; + + c = source[pos]; + if (c == '!') + { + if (sourceLen > pos + 7 && source.Substring(pos - 1, 9) == CDATA_START) + { + pos = source.IndexOf(CDATA_END, pos); + tagType = XMLTagType.CDATA; + tagName = string.Empty; + tagPos = parsePos; + if (pos == -1) + tagLength = sourceLen - parsePos; + else + tagLength = pos + 3 - parsePos; + parsePos += tagLength; + return true; + } + else if (sourceLen > pos + 2 && source.Substring(pos - 1, 4) == COMMENT_START) + { + pos = source.IndexOf(COMMENT_END, pos); + tagType = XMLTagType.Comment; + tagName = string.Empty; + tagPos = parsePos; + if (pos == -1) + tagLength = sourceLen - parsePos; + else + tagLength = pos + 3 - parsePos; + parsePos += tagLength; + return true; + } + else + { + pos++; + tagType = XMLTagType.Instruction; + } + } + else if (c == '/') + { + pos++; + tagType = XMLTagType.End; + } + else if (c == '?') + { + pos++; + tagType = XMLTagType.Instruction; + } + + for (; pos < sourceLen; pos++) + { + c = source[pos]; + if (Char.IsWhiteSpace(c) || c == '>' || c == '/') + break; + } + if (pos == sourceLen) + break; + + buffer.Append(source, parsePos + 1, pos - parsePos - 1); + if (buffer.Length > 0 && buffer[0] == '/') + buffer.Remove(0, 1); + + bool singleQuoted = false, doubleQuoted = false; + int possibleEnd = -1; + for (; pos < sourceLen; pos++) + { + c = source[pos]; + if (c == '"') + { + if (!singleQuoted) + doubleQuoted = !doubleQuoted; + } + else if (c == '\'') + { + if (!doubleQuoted) + singleQuoted = !singleQuoted; + } + + if (c == '>') + { + if (!(singleQuoted || doubleQuoted)) + { + possibleEnd = -1; + break; + } + + possibleEnd = pos; + } + else if (c == '<') + break; + } + if (possibleEnd != -1) + pos = possibleEnd; + + if (pos == sourceLen) + break; + + if (source[pos - 1] == '/') + tagType = XMLTagType.Void; + + tagName = buffer.ToString(); + if (lowerCaseName) + tagName = tagName.ToLower(); + tagPos = parsePos; + tagLength = pos + 1 - parsePos; + parsePos += tagLength; + + return true; + } + + tagPos = sourceLen; + tagLength = 0; + tagName = null; + return false; + } + + public static string GetTagSource() + { + return source.Substring(tagPos, tagLength); + } + + public static string GetRawText(bool trim = false) + { + if (lastTagEnd == tagPos) + return string.Empty; + else if (trim) + { + int i = lastTagEnd; + for (; i < tagPos; i++) + { + char c = source[i]; + if (!char.IsWhiteSpace(c)) + break; + } + + if (i == tagPos) + return string.Empty; + else + return source.Substring(i, tagPos - i).TrimEnd(); + } + else + return source.Substring(lastTagEnd, tagPos - lastTagEnd); + } + + public static string GetText(bool trim = false) + { + if (lastTagEnd == tagPos) + return string.Empty; + else if (trim) + { + int i = lastTagEnd; + for (; i < tagPos; i++) + { + char c = source[i]; + if (!char.IsWhiteSpace(c)) + break; + } + + if (i == tagPos) + return string.Empty; + else + return XMLUtils.DecodeString(source.Substring(i, tagPos - i).TrimEnd()); + } + else + return XMLUtils.DecodeString(source.Substring(lastTagEnd, tagPos - lastTagEnd)); + } + + public static bool HasAttribute(string attrName) + { + if (!attrParsed) + { + attributes.Clear(); + ParseAttributes(attributes); + attrParsed = true; + } + + return attributes.ContainsKey(attrName); + } + + public static string GetAttribute(string attrName) + { + if (!attrParsed) + { + attributes.Clear(); + ParseAttributes(attributes); + attrParsed = true; + } + + string value; + if (attributes.TryGetValue(attrName, out value)) + return value; + else + return null; + } + + public static string GetAttribute(string attrName, string defValue) + { + string ret = GetAttribute(attrName); + if (ret != null) + return ret; + else + return defValue; + } + + public static int GetAttributeInt(string attrName) + { + return GetAttributeInt(attrName, 0); + } + + public static int GetAttributeInt(string attrName, int defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + int ret; + if (int.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public static float GetAttributeFloat(string attrName) + { + return GetAttributeFloat(attrName, 0); + } + + public static float GetAttributeFloat(string attrName, float defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + float ret; + if (float.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public static bool GetAttributeBool(string attrName) + { + return GetAttributeBool(attrName, false); + } + + public static bool GetAttributeBool(string attrName, bool defValue) + { + string value = GetAttribute(attrName); + if (value == null || value.Length == 0) + return defValue; + + bool ret; + if (bool.TryParse(value, out ret)) + return ret; + else + return defValue; + } + + public static Dictionary GetAttributes(Dictionary result) + { + if (result == null) + result = new Dictionary(); + + if (attrParsed) + { + foreach (KeyValuePair kv in attributes) + result[kv.Key] = kv.Value; + } + else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作 + ParseAttributes(result); + + return result; + } + + public static Hashtable GetAttributes(Hashtable result) + { + if (result == null) + result = new Hashtable(); + + if (attrParsed) + { + foreach (KeyValuePair kv in attributes) + result[kv.Key] = kv.Value; + } + else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作 + ParseAttributes(result); + + return result; + } + + static void ParseAttributes(IDictionary attrs) + { + string attrName; + int valueStart; + int valueEnd; + bool waitValue = false; + int quoted; + buffer.Length = 0; + int i = tagPos; + int attrEnd = tagPos + tagLength; + + if (i < attrEnd && source[i] == '<') + { + for (; i < attrEnd; i++) + { + char c = source[i]; + if (Char.IsWhiteSpace(c) || c == '>' || c == '/') + break; + } + } + + for (; i < attrEnd; i++) + { + char c = source[i]; + if (c == '=') + { + valueStart = -1; + valueEnd = -1; + quoted = 0; + for (int j = i + 1; j < attrEnd; j++) + { + char c2 = source[j]; + if (Char.IsWhiteSpace(c2)) + { + if (valueStart != -1 && quoted == 0) + { + valueEnd = j - 1; + break; + } + } + else if (c2 == '>') + { + if (quoted == 0) + { + valueEnd = j - 1; + break; + } + } + else if (c2 == '"') + { + if (valueStart != -1) + { + if (quoted != 1) + { + valueEnd = j - 1; + break; + } + } + else + { + quoted = 2; + valueStart = j + 1; + } + } + else if (c2 == '\'') + { + if (valueStart != -1) + { + if (quoted != 2) + { + valueEnd = j - 1; + break; + } + } + else + { + quoted = 1; + valueStart = j + 1; + } + } + else if (valueStart == -1) + { + valueStart = j; + } + } + + if (valueStart != -1 && valueEnd != -1) + { + attrName = buffer.ToString(); + if (lowerCaseName) + attrName = attrName.ToLower(); + buffer.Length = 0; + attrs[attrName] = XMLUtils.DecodeString(source.Substring(valueStart, valueEnd - valueStart + 1)); + i = valueEnd + 1; + } + else + break; + } + else if (!Char.IsWhiteSpace(c)) + { + if (waitValue || c == '/' || c == '>') + { + if (buffer.Length > 0) + { + attrName = buffer.ToString(); + if (lowerCaseName) + attrName = attrName.ToLower(); + attrs[attrName] = string.Empty; + buffer.Length = 0; + } + + waitValue = false; + } + + if (c != '/' && c != '>') + buffer.Append(c); + } + else + { + if (buffer.Length > 0) + waitValue = true; + } + } + } + } +} diff --git a/Assets/Scripts/Utils/XMLIterator.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLIterator.cs.meta similarity index 100% rename from Assets/Scripts/Utils/XMLIterator.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLIterator.cs.meta diff --git a/Assets/Scripts/Utils/XMLList.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLList.cs similarity index 95% rename from Assets/Scripts/Utils/XMLList.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLList.cs index 960b3de7..c4710ee5 100644 --- a/Assets/Scripts/Utils/XMLList.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLList.cs @@ -1,144 +1,144 @@ -using System; -using System.Collections.Generic; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class XMLList - { - public List rawList; - - public XMLList() - { - rawList = new List(); - } - - public XMLList(List list) - { - rawList = list; - } - - public void Add(XML xml) - { - rawList.Add(xml); - } - - public void Clear() - { - rawList.Clear(); - } - - public int Count - { - get { return rawList.Count; } - } - - public XML this[int index] - { - get { return rawList[index]; } - } - - public Enumerator GetEnumerator() - { - return new Enumerator(rawList, null); - } - - public Enumerator GetEnumerator(string selector) - { - return new Enumerator(rawList, selector); - } - - static List _tmpList = new List(); - public XMLList Filter(string selector) - { - bool allFit = true; - _tmpList.Clear(); - int cnt = rawList.Count; - for (int i = 0; i < cnt; i++) - { - XML xml = rawList[i]; - if (xml.name == selector) - _tmpList.Add(xml); - else - allFit = false; - } - - if (allFit) - return this; - else - { - XMLList ret = new XMLList(_tmpList); - _tmpList = new List(); - return ret; - } - } - - public XML Find(string selector) - { - int cnt = rawList.Count; - for (int i = 0; i < cnt; i++) - { - XML xml = rawList[i]; - if (xml.name == selector) - return xml; - } - return null; - } - - public void RemoveAll(string selector) - { - rawList.RemoveAll(xml => xml.name == selector); - } - - public struct Enumerator - { - List _source; - string _selector; - int _index; - int _total; - XML _current; - - public Enumerator(List source, string selector) - { - _source = source; - _selector = selector; - _index = -1; - if (_source != null) - _total = _source.Count; - else - _total = 0; - _current = null; - } - - public XML Current - { - get { return _current; } - } - - public bool MoveNext() - { - while (++_index < _total) - { - _current = _source[_index]; - if (_selector == null || _current.name == _selector) - return true; - } - - return false; - } - - public void Erase() - { - _source.RemoveAt(_index); - _total--; - } - - public void Reset() - { - _index = -1; - } - } - } -} +using System; +using System.Collections.Generic; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class XMLList + { + public List rawList; + + public XMLList() + { + rawList = new List(); + } + + public XMLList(List list) + { + rawList = list; + } + + public void Add(XML xml) + { + rawList.Add(xml); + } + + public void Clear() + { + rawList.Clear(); + } + + public int Count + { + get { return rawList.Count; } + } + + public XML this[int index] + { + get { return rawList[index]; } + } + + public Enumerator GetEnumerator() + { + return new Enumerator(rawList, null); + } + + public Enumerator GetEnumerator(string selector) + { + return new Enumerator(rawList, selector); + } + + static List _tmpList = new List(); + public XMLList Filter(string selector) + { + bool allFit = true; + _tmpList.Clear(); + int cnt = rawList.Count; + for (int i = 0; i < cnt; i++) + { + XML xml = rawList[i]; + if (xml.name == selector) + _tmpList.Add(xml); + else + allFit = false; + } + + if (allFit) + return this; + else + { + XMLList ret = new XMLList(_tmpList); + _tmpList = new List(); + return ret; + } + } + + public XML Find(string selector) + { + int cnt = rawList.Count; + for (int i = 0; i < cnt; i++) + { + XML xml = rawList[i]; + if (xml.name == selector) + return xml; + } + return null; + } + + public void RemoveAll(string selector) + { + rawList.RemoveAll(xml => xml.name == selector); + } + + public struct Enumerator + { + List _source; + string _selector; + int _index; + int _total; + XML _current; + + public Enumerator(List source, string selector) + { + _source = source; + _selector = selector; + _index = -1; + if (_source != null) + _total = _source.Count; + else + _total = 0; + _current = null; + } + + public XML Current + { + get { return _current; } + } + + public bool MoveNext() + { + while (++_index < _total) + { + _current = _source[_index]; + if (_selector == null || _current.name == _selector) + return true; + } + + return false; + } + + public void Erase() + { + _source.RemoveAt(_index); + _total--; + } + + public void Reset() + { + _index = -1; + } + } + } +} diff --git a/Assets/Scripts/Utils/XMLList.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLList.cs.meta similarity index 100% rename from Assets/Scripts/Utils/XMLList.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLList.cs.meta diff --git a/Assets/Scripts/Utils/XMLUtils.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLUtils.cs similarity index 96% rename from Assets/Scripts/Utils/XMLUtils.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLUtils.cs index 4481fcc3..ce00722f 100644 --- a/Assets/Scripts/Utils/XMLUtils.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLUtils.cs @@ -1,133 +1,133 @@ -using System; -using System.Text; - -namespace FairyGUI.Utils -{ - /// - /// - /// - public class XMLUtils - { - public static string DecodeString(string aSource) - { - int len = aSource.Length; - StringBuilder sb = new StringBuilder(); - int pos1 = 0, pos2 = 0; - - while (true) - { - pos2 = aSource.IndexOf('&', pos1); - if (pos2 == -1) - { - sb.Append(aSource.Substring(pos1)); - break; - } - sb.Append(aSource.Substring(pos1, pos2 - pos1)); - - pos1 = pos2 + 1; - pos2 = pos1; - int end = Math.Min(len, pos2 + 10); - for (; pos2 < end; pos2++) - { - if (aSource[pos2] == ';') - break; - } - if (pos2 < end && pos2 > pos1) - { - string entity = aSource.Substring(pos1, pos2 - pos1); - int u = 0; - if (entity[0] == '#') - { - if (entity.Length > 1) - { - if (entity[1] == 'x') - u = Convert.ToInt16(entity.Substring(2), 16); - else - u = Convert.ToInt16(entity.Substring(1)); - sb.Append((char)u); - pos1 = pos2 + 1; - } - else - sb.Append('&'); - } - else - { - switch (entity) - { - case "amp": - u = 38; - break; - - case "apos": - u = 39; - break; - - case "gt": - u = 62; - break; - - case "lt": - u = 60; - break; - - case "nbsp": - u = 32; - break; - - case "quot": - u = 34; - break; - } - if (u > 0) - { - sb.Append((char)u); - pos1 = pos2 + 1; - } - else - sb.Append('&'); - } - } - else - { - sb.Append('&'); - } - } - - return sb.ToString(); - } - - private static string[] ESCAPES = new string[] { - "&", "&", - "<", "<", - ">", ">", - - "'", "'", - "\"", """, - "\t", " ", - "\n", " ", - "\r", " " - }; - public static void EncodeString(StringBuilder sb, int start, bool isAttribute = false) - { - int count; - int len = isAttribute ? ESCAPES.Length : 6; - for (int i = 0; i < len; i += 2) - { - count = sb.Length - start; - sb.Replace(ESCAPES[i], ESCAPES[i + 1], start, count); - } - } - - public static string EncodeString(string str, bool isAttribute = false) - { - if (string.IsNullOrEmpty(str)) - return ""; - else - { - StringBuilder sb = new StringBuilder(str); - EncodeString(sb, 0); - return sb.ToString(); - } - } - } -} +using System; +using System.Text; + +namespace FairyGUI.Utils +{ + /// + /// + /// + public class XMLUtils + { + public static string DecodeString(string aSource) + { + int len = aSource.Length; + StringBuilder sb = new StringBuilder(); + int pos1 = 0, pos2 = 0; + + while (true) + { + pos2 = aSource.IndexOf('&', pos1); + if (pos2 == -1) + { + sb.Append(aSource.Substring(pos1)); + break; + } + sb.Append(aSource.Substring(pos1, pos2 - pos1)); + + pos1 = pos2 + 1; + pos2 = pos1; + int end = Math.Min(len, pos2 + 10); + for (; pos2 < end; pos2++) + { + if (aSource[pos2] == ';') + break; + } + if (pos2 < end && pos2 > pos1) + { + string entity = aSource.Substring(pos1, pos2 - pos1); + int u = 0; + if (entity[0] == '#') + { + if (entity.Length > 1) + { + if (entity[1] == 'x') + u = Convert.ToInt16(entity.Substring(2), 16); + else + u = Convert.ToInt16(entity.Substring(1)); + sb.Append((char)u); + pos1 = pos2 + 1; + } + else + sb.Append('&'); + } + else + { + switch (entity) + { + case "amp": + u = 38; + break; + + case "apos": + u = 39; + break; + + case "gt": + u = 62; + break; + + case "lt": + u = 60; + break; + + case "nbsp": + u = 32; + break; + + case "quot": + u = 34; + break; + } + if (u > 0) + { + sb.Append((char)u); + pos1 = pos2 + 1; + } + else + sb.Append('&'); + } + } + else + { + sb.Append('&'); + } + } + + return sb.ToString(); + } + + private static string[] ESCAPES = new string[] { + "&", "&", + "<", "<", + ">", ">", + + "'", "'", + "\"", """, + "\t", " ", + "\n", " ", + "\r", " " + }; + public static void EncodeString(StringBuilder sb, int start, bool isAttribute = false) + { + int count; + int len = isAttribute ? ESCAPES.Length : 6; + for (int i = 0; i < len; i += 2) + { + count = sb.Length - start; + sb.Replace(ESCAPES[i], ESCAPES[i + 1], start, count); + } + } + + public static string EncodeString(string str, bool isAttribute = false) + { + if (string.IsNullOrEmpty(str)) + return ""; + else + { + StringBuilder sb = new StringBuilder(str); + EncodeString(sb, 0); + return sb.ToString(); + } + } + } +} diff --git a/Assets/Scripts/Utils/XMLUtils.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLUtils.cs.meta similarity index 100% rename from Assets/Scripts/Utils/XMLUtils.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/XMLUtils.cs.meta diff --git a/Assets/Scripts/Utils/ZipReader.cs b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ZipReader.cs similarity index 96% rename from Assets/Scripts/Utils/ZipReader.cs rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ZipReader.cs index 470d5a83..014eaa21 100644 --- a/Assets/Scripts/Utils/ZipReader.cs +++ b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ZipReader.cs @@ -1,114 +1,114 @@ -namespace FairyGUI.Utils -{ - /// - /// 一个简单的Zip文件处理类。不处理解压。 - /// - public class ZipReader - { - /// - /// - /// - public class ZipEntry - { - public string name; - public int compress; - public uint crc; - public int size; - public int sourceSize; - public int offset; - public bool isDirectory; - } - - ByteBuffer _stream; - int _entryCount; - int _pos; - int _index; - - /// - /// - /// - /// - public ZipReader(byte[] data) - { - _stream = new ByteBuffer(data); - _stream.littleEndian = true; - - int pos = _stream.length - 22; - _stream.position = pos + 10; - _entryCount = _stream.ReadShort(); - _stream.position = pos + 16; - _pos = _stream.ReadInt(); - } - - /// - /// - /// - public int entryCount - { - get { return _entryCount; } - } - - /// - /// - /// - /// - public bool GetNextEntry(ZipEntry entry) - { - if (_index >= _entryCount) - return false; - - _stream.position = _pos + 28; - int len = _stream.ReadUshort(); - int len2 = _stream.ReadUshort() + _stream.ReadUshort(); - - _stream.position = _pos + 46; - string name = _stream.ReadString(len); - name = name.Replace("\\", "/"); - - entry.name = name; - if (name[name.Length - 1] == '/') //directory - { - entry.isDirectory = true; - entry.compress = 0; - entry.crc = 0; - entry.size = entry.sourceSize = 0; - entry.offset = 0; - } - else - { - entry.isDirectory = false; - _stream.position = _pos + 10; - entry.compress = _stream.ReadUshort(); - _stream.position = _pos + 16; - entry.crc = _stream.ReadUint(); - entry.size = _stream.ReadInt(); - entry.sourceSize = _stream.ReadInt(); - _stream.position = _pos + 42; - entry.offset = _stream.ReadInt() + 30 + len; - } - - _pos += 46 + len + len2; - _index++; - - return true; - } - - - /// - /// - /// - /// - /// - public byte[] GetEntryData(ZipEntry entry) - { - byte[] data = new byte[entry.size]; - if (entry.size > 0) - { - _stream.position = entry.offset; - _stream.ReadBytes(data, 0, entry.size); - } - - return data; - } - } -} +namespace FairyGUI.Utils +{ + /// + /// 一个简单的Zip文件处理类。不处理解压。 + /// + public class ZipReader + { + /// + /// + /// + public class ZipEntry + { + public string name; + public int compress; + public uint crc; + public int size; + public int sourceSize; + public int offset; + public bool isDirectory; + } + + ByteBuffer _stream; + int _entryCount; + int _pos; + int _index; + + /// + /// + /// + /// + public ZipReader(byte[] data) + { + _stream = new ByteBuffer(data); + _stream.littleEndian = true; + + int pos = _stream.length - 22; + _stream.position = pos + 10; + _entryCount = _stream.ReadShort(); + _stream.position = pos + 16; + _pos = _stream.ReadInt(); + } + + /// + /// + /// + public int entryCount + { + get { return _entryCount; } + } + + /// + /// + /// + /// + public bool GetNextEntry(ZipEntry entry) + { + if (_index >= _entryCount) + return false; + + _stream.position = _pos + 28; + int len = _stream.ReadUshort(); + int len2 = _stream.ReadUshort() + _stream.ReadUshort(); + + _stream.position = _pos + 46; + string name = _stream.ReadString(len); + name = name.Replace("\\", "/"); + + entry.name = name; + if (name[name.Length - 1] == '/') //directory + { + entry.isDirectory = true; + entry.compress = 0; + entry.crc = 0; + entry.size = entry.sourceSize = 0; + entry.offset = 0; + } + else + { + entry.isDirectory = false; + _stream.position = _pos + 10; + entry.compress = _stream.ReadUshort(); + _stream.position = _pos + 16; + entry.crc = _stream.ReadUint(); + entry.size = _stream.ReadInt(); + entry.sourceSize = _stream.ReadInt(); + _stream.position = _pos + 42; + entry.offset = _stream.ReadInt() + 30 + len; + } + + _pos += 46 + len + len2; + _index++; + + return true; + } + + + /// + /// + /// + /// + /// + public byte[] GetEntryData(ZipEntry entry) + { + byte[] data = new byte[entry.size]; + if (entry.size > 0) + { + _stream.position = entry.offset; + _stream.ReadBytes(data, 0, entry.size); + } + + return data; + } + } +} diff --git a/Assets/Scripts/Utils/ZipReader.cs.meta b/Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ZipReader.cs.meta similarity index 100% rename from Assets/Scripts/Utils/ZipReader.cs.meta rename to Assets/Plugins/FairyGUI/Runtime/Scripts/Utils/ZipReader.cs.meta diff --git a/Assets/Plugins/FairyGUI/package.json b/Assets/Plugins/FairyGUI/package.json new file mode 100644 index 00000000..c45955b7 --- /dev/null +++ b/Assets/Plugins/FairyGUI/package.json @@ -0,0 +1,8 @@ +{ + "name": "fairygui", + "displayName": "FairyGUI", + "version": "1.0.1", + "description": "FairyGUI is a Cross Platform UI Editor & UI framework.[https://github.com/fairygui/FairyGUI-unity]", + "keywords": ["ui","fui","fairygui"], + "dependencies": {} +} \ No newline at end of file diff --git a/Assets/Plugins/FairyGUI/package.json.meta b/Assets/Plugins/FairyGUI/package.json.meta new file mode 100644 index 00000000..0a7a8a13 --- /dev/null +++ b/Assets/Plugins/FairyGUI/package.json.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5480f333619646cfba269a8166586c5b +timeCreated: 1667314258 \ No newline at end of file diff --git a/Assets/Resources.meta b/Assets/Resources.meta index 6e4dc8c9..76867712 100644 --- a/Assets/Resources.meta +++ b/Assets/Resources.meta @@ -1,9 +1,8 @@ fileFormatVersion: 2 -guid: 66d9312cafc49bf4cad1ccdbb5b6668b +guid: 0c7274bbf6950754cb735b526a1525ca folderAsset: yes -timeCreated: 1446459912 -licenseType: Pro DefaultImporter: + externalObjects: {} userData: assetBundleName: assetBundleVariant: diff --git a/Assets/Resources/BillingMode.json b/Assets/Resources/BillingMode.json new file mode 100644 index 00000000..6f4bfb71 --- /dev/null +++ b/Assets/Resources/BillingMode.json @@ -0,0 +1 @@ +{"androidStore":"GooglePlay"} \ No newline at end of file diff --git a/Assets/Resources/BillingMode.json.meta b/Assets/Resources/BillingMode.json.meta new file mode 100644 index 00000000..d3f22b73 --- /dev/null +++ b/Assets/Resources/BillingMode.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: db8cd7212c77d264596fde22745ce103 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/LICENSE b/LICENSE index 32bc7979..48605477 100644 --- a/LICENSE +++ b/LICENSE @@ -1,20 +1,20 @@ -The MIT License (MIT) - -Copyright (c) 2015 fairygui.com - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +The MIT License (MIT) + +Copyright (c) 2015 fairygui.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Logs/Packages-Update.log b/Logs/Packages-Update.log deleted file mode 100644 index 44f1fbbc..00000000 --- a/Logs/Packages-Update.log +++ /dev/null @@ -1,9 +0,0 @@ - -=== Tue Apr 13 10:43:49 2021 - -Packages were changed. -Update Mode: updateDependencies - -The following packages were updated: - com.unity.package-manager-ui from version 2.0.8 to 2.0.13 - com.unity.purchasing from version 2.0.3 to 2.1.1 diff --git a/LuaSupport/README.md b/LuaSupport/README.md index 6c347d3c..d790c052 100644 --- a/LuaSupport/README.md +++ b/LuaSupport/README.md @@ -1,194 +1,194 @@ -Lua支持 -==== - -## 准备工作 - -1. **如果你使用的是ToLua,在Scripting Define Symbols里加上** `FAIRYGUI_TOLUA`。XLUA则不需要。 -2. 如果是ToLua,将以下语句添加到CustomSettings.cs适当的位置,然后重新生成绑定文件。 - - ```csharp - - _GT(typeof(EventContext)), - _GT(typeof(EventDispatcher)), - _GT(typeof(EventListener)), - _GT(typeof(InputEvent)), - _GT(typeof(DisplayObject)), - _GT(typeof(Container)), - _GT(typeof(Stage)), - _GT(typeof(FairyGUI.Controller)), - _GT(typeof(GObject)), - _GT(typeof(GGraph)), - _GT(typeof(GGroup)), - _GT(typeof(GImage)), - _GT(typeof(GLoader)), - _GT(typeof(GMovieClip)), - _GT(typeof(TextFormat)), - _GT(typeof(GTextField)), - _GT(typeof(GRichTextField)), - _GT(typeof(GTextInput)), - _GT(typeof(GComponent)), - _GT(typeof(GList)), - _GT(typeof(GRoot)), - _GT(typeof(GLabel)), - _GT(typeof(GButton)), - _GT(typeof(GComboBox)), - _GT(typeof(GProgressBar)), - _GT(typeof(GSlider)), - _GT(typeof(PopupMenu)), - _GT(typeof(ScrollPane)), - _GT(typeof(Transition)), - _GT(typeof(UIPackage)), - _GT(typeof(Window)), - _GT(typeof(GObjectPool)), - _GT(typeof(Relations)), - _GT(typeof(RelationType)), - _GT(typeof(Timers)), - _GT(typeof(GTween)), - _GT(typeof(GTweener)), - _GT(typeof(EaseType)), - _GT(typeof(TweenValue)), - _GT(typeof(UIObjectFactory)), - ``` - -3. 将FairyGUI.lua放入你的lua文件存放目录。 - -## 监听事件 - -1. 普通方法的侦听和删除侦听 - - ```csharp - - require 'FairyGUI' - - function OnClick() - print('you click') - end - - --也可以带上事件参数 - function OnClick(context) - print('you click'..context.sender) - end - - UIPackage.AddPackage('Demo') - local view = UIPackage.CreateObject('Demo', 'DemoMain') - GRoot.inst:AddChild(view) - - view.onClick:Add(OnClick) - --view.onClick:Remove(OnClick) - --view.onClick:Set(OnClick) - - ``` - -2. **ToLua支持带self的回调** - - ```csharp - - function TestClass:OnClick() - print('you click') - end - - function TestClass:OnClick(context) - print('you click'..context.sender) - end - - self.view.onClick:Add(TestClass.OnClick, self) - self.view.onClick:Remove(TestClass.OnClick, self) - - ``` - -## 使用Window类 - -FairyGUI提供的Window类,一般需要开发者自己扩展,例如覆盖OnShown,OnHide等。在Lua里,编写Window扩展的方法是: - -```csharp - WindowBase = fgui.window_class() - - --构建函数 - function WindowBase:ctor() - end - - --可覆盖的函数(可选,不是说必须) - function WindowBase:OnInit() - self.contentPane = UIPackage.CreateObject("Basics", "WindowA"); - end - - function WindowBase:OnShown() - end - - function WindowBase:OnHide() - end - - function WindowBase:DoShowAnimation() - self:OnShown(); - end - - function WindowBase:DoHideAnimation() - self:HideImmediately(); - end - - --创建并显示窗口 - local win = WindowBase.New(); - win:Show(); - - 也可以继续继承以上得到的Window类,例如: - MyWindow = fgui.window_class(WindowBase) - - 在继承类里调用父类方法的: - function MyWindow:OnInit() - WindowBase.OnInit(self) - end -``` - -## 自定义扩展 - -FairyGUI在C#里可以使用`UIObjectFactory.SetPackageItemExtension`进行自定义扩展。在Lua里,同样可以这样做。方法如下: - -1. 定义扩展类。注意基础类型,不要搞错。例如按钮是GButton,一般的组件则是GComponent。 - - ```csharp - - MyButton = fgui.extension_class(GButton) - - --注意这里不是构造函数,是当组件已经构建完毕后调用的 - - function MyButton:ctor() - print(self:GetChild('n1')) - end - - --添加自定义的方法和字段 - function MyButton:Test() - print('test') - end - - local get = tolua.initget(MyButton) - local set = tolua.initset(MyButton) - get.myProp = function(self) - return self._myProp - end - - set.myProp = function(self, value) - self._myProp = value - self:GetChild('n1').text = value - end - - ``` - -2. 注册扩展类。要在创建任何对象前注册好。 - - ```csharp - fgui.register_extension("ui://包名/我的按钮", MyButton) - ``` - -3. 完成以上两步后,任何“我的按钮”这个资源创建出来的对象都可以使用MyButton访问了。例如: - - ```csharp - - local myButton = someComponent:GetChild("myButton") --这个myButton的资源是“我的按钮” - myButton:Test() - myButton.myProp = 'hello' - - local myButton2 = UIPackage.CreateObject("包名","我的按钮") - myButton2:Test() - myButton2.myProp = 'world' - +Lua支持 +==== + +## 准备工作 + +1. **如果你使用的是ToLua,在Scripting Define Symbols里加上** `FAIRYGUI_TOLUA`。XLUA则不需要。 +2. 如果是ToLua,将以下语句添加到CustomSettings.cs适当的位置,然后重新生成绑定文件。 + + ```csharp + + _GT(typeof(EventContext)), + _GT(typeof(EventDispatcher)), + _GT(typeof(EventListener)), + _GT(typeof(InputEvent)), + _GT(typeof(DisplayObject)), + _GT(typeof(Container)), + _GT(typeof(Stage)), + _GT(typeof(FairyGUI.Controller)), + _GT(typeof(GObject)), + _GT(typeof(GGraph)), + _GT(typeof(GGroup)), + _GT(typeof(GImage)), + _GT(typeof(GLoader)), + _GT(typeof(GMovieClip)), + _GT(typeof(TextFormat)), + _GT(typeof(GTextField)), + _GT(typeof(GRichTextField)), + _GT(typeof(GTextInput)), + _GT(typeof(GComponent)), + _GT(typeof(GList)), + _GT(typeof(GRoot)), + _GT(typeof(GLabel)), + _GT(typeof(GButton)), + _GT(typeof(GComboBox)), + _GT(typeof(GProgressBar)), + _GT(typeof(GSlider)), + _GT(typeof(PopupMenu)), + _GT(typeof(ScrollPane)), + _GT(typeof(Transition)), + _GT(typeof(UIPackage)), + _GT(typeof(Window)), + _GT(typeof(GObjectPool)), + _GT(typeof(Relations)), + _GT(typeof(RelationType)), + _GT(typeof(Timers)), + _GT(typeof(GTween)), + _GT(typeof(GTweener)), + _GT(typeof(EaseType)), + _GT(typeof(TweenValue)), + _GT(typeof(UIObjectFactory)), + ``` + +3. 将FairyGUI.lua放入你的lua文件存放目录。 + +## 监听事件 + +1. 普通方法的侦听和删除侦听 + + ```csharp + + require 'FairyGUI' + + function OnClick() + print('you click') + end + + --也可以带上事件参数 + function OnClick(context) + print('you click'..context.sender) + end + + UIPackage.AddPackage('Demo') + local view = UIPackage.CreateObject('Demo', 'DemoMain') + GRoot.inst:AddChild(view) + + view.onClick:Add(OnClick) + --view.onClick:Remove(OnClick) + --view.onClick:Set(OnClick) + + ``` + +2. **ToLua支持带self的回调** + + ```csharp + + function TestClass:OnClick() + print('you click') + end + + function TestClass:OnClick(context) + print('you click'..context.sender) + end + + self.view.onClick:Add(TestClass.OnClick, self) + self.view.onClick:Remove(TestClass.OnClick, self) + + ``` + +## 使用Window类 + +FairyGUI提供的Window类,一般需要开发者自己扩展,例如覆盖OnShown,OnHide等。在Lua里,编写Window扩展的方法是: + +```csharp + WindowBase = fgui.window_class() + + --构建函数 + function WindowBase:ctor() + end + + --可覆盖的函数(可选,不是说必须) + function WindowBase:OnInit() + self.contentPane = UIPackage.CreateObject("Basics", "WindowA"); + end + + function WindowBase:OnShown() + end + + function WindowBase:OnHide() + end + + function WindowBase:DoShowAnimation() + self:OnShown(); + end + + function WindowBase:DoHideAnimation() + self:HideImmediately(); + end + + --创建并显示窗口 + local win = WindowBase.New(); + win:Show(); + + 也可以继续继承以上得到的Window类,例如: + MyWindow = fgui.window_class(WindowBase) + + 在继承类里调用父类方法的: + function MyWindow:OnInit() + WindowBase.OnInit(self) + end +``` + +## 自定义扩展 + +FairyGUI在C#里可以使用`UIObjectFactory.SetPackageItemExtension`进行自定义扩展。在Lua里,同样可以这样做。方法如下: + +1. 定义扩展类。注意基础类型,不要搞错。例如按钮是GButton,一般的组件则是GComponent。 + + ```csharp + + MyButton = fgui.extension_class(GButton) + + --注意这里不是构造函数,是当组件已经构建完毕后调用的 + + function MyButton:ctor() + print(self:GetChild('n1')) + end + + --添加自定义的方法和字段 + function MyButton:Test() + print('test') + end + + local get = tolua.initget(MyButton) + local set = tolua.initset(MyButton) + get.myProp = function(self) + return self._myProp + end + + set.myProp = function(self, value) + self._myProp = value + self:GetChild('n1').text = value + end + + ``` + +2. 注册扩展类。要在创建任何对象前注册好。 + + ```csharp + fgui.register_extension("ui://包名/我的按钮", MyButton) + ``` + +3. 完成以上两步后,任何“我的按钮”这个资源创建出来的对象都可以使用MyButton访问了。例如: + + ```csharp + + local myButton = someComponent:GetChild("myButton") --这个myButton的资源是“我的按钮” + myButton:Test() + myButton.myProp = 'hello' + + local myButton2 = UIPackage.CreateObject("包名","我的按钮") + myButton2:Test() + myButton2.myProp = 'world' + ``` \ No newline at end of file diff --git a/LuaSupport/ToLua/FairyGUI.lua b/LuaSupport/ToLua/FairyGUI.lua index 0b497df6..2323d799 100644 --- a/LuaSupport/ToLua/FairyGUI.lua +++ b/LuaSupport/ToLua/FairyGUI.lua @@ -1,145 +1,145 @@ -EventContext = FairyGUI.EventContext -EventListener = FairyGUI.EventListener -EventDispatcher = FairyGUI.EventDispatcher -InputEvent = FairyGUI.InputEvent -NTexture = FairyGUI.NTexture -Container = FairyGUI.Container -Image = FairyGUI.Image -Stage = FairyGUI.Stage -Controller = FairyGUI.Controller -GObject = FairyGUI.GObject -GGraph = FairyGUI.GGraph -GGroup = FairyGUI.GGroup -GImage = FairyGUI.GImage -GLoader = FairyGUI.GLoader -GMovieClip = FairyGUI.GMovieClip -TextFormat = FairyGUI.TextFormat -GTextField = FairyGUI.GTextField -GRichTextField = FairyGUI.GRichTextField -GTextInput = FairyGUI.GTextInput -GComponent = FairyGUI.GComponent -GList = FairyGUI.GList -GRoot = FairyGUI.GRoot -GLabel = FairyGUI.GLabel -GButton = FairyGUI.GButton -GComboBox = FairyGUI.GComboBox -GProgressBar = FairyGUI.GProgressBar -GSlider = FairyGUI.GSlider -PopupMenu = FairyGUI.PopupMenu -ScrollPane = FairyGUI.ScrollPane -Transition = FairyGUI.Transition -UIPackage = FairyGUI.UIPackage -Window = FairyGUI.Window -GObjectPool = FairyGUI.GObjectPool -Relations = FairyGUI.Relations -RelationType = FairyGUI.RelationType -UIPanel = FairyGUI.UIPanel -UIPainter = FairyGUI.UIPainter -TypingEffect = FairyGUI.TypingEffect -GTween = FairyGUI.GTween -GTweener = FairyGUI.GTweener -EaseType = FairyGUI.EaseType - -fgui = {} - ---[[ -用于继承FairyGUI的Window类,同时派生的Window类可以继续被继承。可以重写的方法有(与Window类里的同名方法含义完全相同) -OnInit、DoHideAnimation、DoShowAnimation、OnShown、OnHide。 - -例子: -MyWinClass = fgui.window_class() - -function MyWinClass:ctor() - print('MyWinClass-ctor') - self.contentPane = UIPackage.CreateObject("Basics", "WindowA") -end - -function MyWinClass:OnShown() - print('MyWinClass-onShown') -end - -local win = MyWinClass.New() -win:Show() - -]] -function fgui.window_class(base) - local o = {} - - local base = base or FairyGUI.Window - setmetatable(o, base) - - o.__index = o - o.base = base - - o.New = function(...) - local t = {} - setmetatable(t, o) - - local ins = FairyGUI.Window.New() - tolua.setpeer(ins, t) - ins:SetLuaPeer(t) - if t.ctor then t.ctor(ins, ...) end - - return ins - end - - return o -end - ---[[ -注册组件扩展,用于继承FairyGUI原来的组件类。 - -例子: - -MyButton = fgui.extension_class(GButton) -fgui.register_extension("ui://包名/我的按钮", MyButton) - -function MyButton:ctor() --当组件构建完成时此方法被调用 - print(self:GetChild("n1")) -end - ---添加自定义的方法和字段 -function MyButton:Test() - print('test') -end - -local get = tolua.initget(MyButton) -local set = tolua.initset(MyButton) -get.myProp = function(self) - return self._myProp -end - -set.myProp = function(self, value) - self._myProp = value - self:GetChild('n1').text = value -end - -local myButton = someComponent:GetChild("myButton") --这个myButton的资源是“我的按钮” -myButton:Test() -myButton.myProp = 'hello' - -local myButton2 = UIPackage.CreateObject("包名","我的按钮") -myButton2:Test() -myButton2.myProp = 'world' -]] - -function fgui.register_extension(url, extension) - FairyGUI.UIObjectFactory.SetExtension(url, typeof(extension.base), - extension.Extend) -end - -function fgui.extension_class(base) - local o = {} - o.__index = o - - o.base = base or GComponent - - o.Extend = function(ins) - local t = {} - setmetatable(t, o) - tolua.setpeer(ins, t) - return t - end - - return o -end +EventContext = FairyGUI.EventContext +EventListener = FairyGUI.EventListener +EventDispatcher = FairyGUI.EventDispatcher +InputEvent = FairyGUI.InputEvent +NTexture = FairyGUI.NTexture +Container = FairyGUI.Container +Image = FairyGUI.Image +Stage = FairyGUI.Stage +Controller = FairyGUI.Controller +GObject = FairyGUI.GObject +GGraph = FairyGUI.GGraph +GGroup = FairyGUI.GGroup +GImage = FairyGUI.GImage +GLoader = FairyGUI.GLoader +GMovieClip = FairyGUI.GMovieClip +TextFormat = FairyGUI.TextFormat +GTextField = FairyGUI.GTextField +GRichTextField = FairyGUI.GRichTextField +GTextInput = FairyGUI.GTextInput +GComponent = FairyGUI.GComponent +GList = FairyGUI.GList +GRoot = FairyGUI.GRoot +GLabel = FairyGUI.GLabel +GButton = FairyGUI.GButton +GComboBox = FairyGUI.GComboBox +GProgressBar = FairyGUI.GProgressBar +GSlider = FairyGUI.GSlider +PopupMenu = FairyGUI.PopupMenu +ScrollPane = FairyGUI.ScrollPane +Transition = FairyGUI.Transition +UIPackage = FairyGUI.UIPackage +Window = FairyGUI.Window +GObjectPool = FairyGUI.GObjectPool +Relations = FairyGUI.Relations +RelationType = FairyGUI.RelationType +UIPanel = FairyGUI.UIPanel +UIPainter = FairyGUI.UIPainter +TypingEffect = FairyGUI.TypingEffect +GTween = FairyGUI.GTween +GTweener = FairyGUI.GTweener +EaseType = FairyGUI.EaseType + +fgui = {} + +--[[ +用于继承FairyGUI的Window类,同时派生的Window类可以继续被继承。可以重写的方法有(与Window类里的同名方法含义完全相同) +OnInit、DoHideAnimation、DoShowAnimation、OnShown、OnHide。 + +例子: +MyWinClass = fgui.window_class() + +function MyWinClass:ctor() + print('MyWinClass-ctor') + self.contentPane = UIPackage.CreateObject("Basics", "WindowA") +end + +function MyWinClass:OnShown() + print('MyWinClass-onShown') +end + +local win = MyWinClass.New() +win:Show() + +]] +function fgui.window_class(base) + local o = {} + + local base = base or FairyGUI.Window + setmetatable(o, base) + + o.__index = o + o.base = base + + o.New = function(...) + local t = {} + setmetatable(t, o) + + local ins = FairyGUI.Window.New() + tolua.setpeer(ins, t) + ins:SetLuaPeer(t) + if t.ctor then t.ctor(ins, ...) end + + return ins + end + + return o +end + +--[[ +注册组件扩展,用于继承FairyGUI原来的组件类。 + +例子: + +MyButton = fgui.extension_class(GButton) +fgui.register_extension("ui://包名/我的按钮", MyButton) + +function MyButton:ctor() --当组件构建完成时此方法被调用 + print(self:GetChild("n1")) +end + +--添加自定义的方法和字段 +function MyButton:Test() + print('test') +end + +local get = tolua.initget(MyButton) +local set = tolua.initset(MyButton) +get.myProp = function(self) + return self._myProp +end + +set.myProp = function(self, value) + self._myProp = value + self:GetChild('n1').text = value +end + +local myButton = someComponent:GetChild("myButton") --这个myButton的资源是“我的按钮” +myButton:Test() +myButton.myProp = 'hello' + +local myButton2 = UIPackage.CreateObject("包名","我的按钮") +myButton2:Test() +myButton2.myProp = 'world' +]] + +function fgui.register_extension(url, extension) + FairyGUI.UIObjectFactory.SetExtension(url, typeof(extension.base), + extension.Extend) +end + +function fgui.extension_class(base) + local o = {} + o.__index = o + + o.base = base or GComponent + + o.Extend = function(ins) + local t = {} + setmetatable(t, o) + tolua.setpeer(ins, t) + return t + end + + return o +end diff --git a/LuaSupport/xLua/FairyGUI.lua b/LuaSupport/xLua/FairyGUI.lua index a0d0dc0d..76ea0feb 100644 --- a/LuaSupport/xLua/FairyGUI.lua +++ b/LuaSupport/xLua/FairyGUI.lua @@ -1,38 +1,38 @@ -EventContext = CS.FairyGUI.EventContext -EventListener = CS.FairyGUI.EventListener -EventDispatcher = CS.FairyGUI.EventDispatcher -InputEvent = CS.FairyGUI.InputEvent -NTexture = CS.FairyGUI.NTexture -Container = CS.FairyGUI.Container -Image = CS.FairyGUI.Image -Stage = CS.FairyGUI.Stage -Controller = CS.FairyGUI.Controller -GObject = CS.FairyGUI.GObject -GGraph = CS.FairyGUI.GGraph -GGroup = CS.FairyGUI.GGroup -GImage = CS.FairyGUI.GImage -GLoader = CS.FairyGUI.GLoader -GMovieClip = CS.FairyGUI.GMovieClip -TextFormat = CS.FairyGUI.TextFormat -GTextField = CS.FairyGUI.GTextField -GRichTextField = CS.FairyGUI.GRichTextField -GTextInput = CS.FairyGUI.GTextInput -GComponent = CS.FairyGUI.GComponent -GList = CS.FairyGUI.GList -GRoot = CS.FairyGUI.GRoot -GLabel = CS.FairyGUI.GLabel -GButton = CS.FairyGUI.GButton -GComboBox = CS.FairyGUI.GComboBox -GProgressBar = CS.FairyGUI.GProgressBar -GSlider = CS.FairyGUI.GSlider -PopupMenu = CS.FairyGUI.PopupMenu -ScrollPane = CS.FairyGUI.ScrollPane -Transition = CS.FairyGUI.Transition -UIPackage = CS.FairyGUI.UIPackage -Window = CS.FairyGUI.Window -GObjectPool = CS.FairyGUI.GObjectPool -Relations = CS.FairyGUI.Relations -RelationType = CS.FairyGUI.RelationType -UIPanel = CS.FairyGUI.UIPanel -UIPainter = CS.FairyGUI.UIPainter -TypingEffect = CS.FairyGUI.TypingEffect +EventContext = CS.FairyGUI.EventContext +EventListener = CS.FairyGUI.EventListener +EventDispatcher = CS.FairyGUI.EventDispatcher +InputEvent = CS.FairyGUI.InputEvent +NTexture = CS.FairyGUI.NTexture +Container = CS.FairyGUI.Container +Image = CS.FairyGUI.Image +Stage = CS.FairyGUI.Stage +Controller = CS.FairyGUI.Controller +GObject = CS.FairyGUI.GObject +GGraph = CS.FairyGUI.GGraph +GGroup = CS.FairyGUI.GGroup +GImage = CS.FairyGUI.GImage +GLoader = CS.FairyGUI.GLoader +GMovieClip = CS.FairyGUI.GMovieClip +TextFormat = CS.FairyGUI.TextFormat +GTextField = CS.FairyGUI.GTextField +GRichTextField = CS.FairyGUI.GRichTextField +GTextInput = CS.FairyGUI.GTextInput +GComponent = CS.FairyGUI.GComponent +GList = CS.FairyGUI.GList +GRoot = CS.FairyGUI.GRoot +GLabel = CS.FairyGUI.GLabel +GButton = CS.FairyGUI.GButton +GComboBox = CS.FairyGUI.GComboBox +GProgressBar = CS.FairyGUI.GProgressBar +GSlider = CS.FairyGUI.GSlider +PopupMenu = CS.FairyGUI.PopupMenu +ScrollPane = CS.FairyGUI.ScrollPane +Transition = CS.FairyGUI.Transition +UIPackage = CS.FairyGUI.UIPackage +Window = CS.FairyGUI.Window +GObjectPool = CS.FairyGUI.GObjectPool +Relations = CS.FairyGUI.Relations +RelationType = CS.FairyGUI.RelationType +UIPanel = CS.FairyGUI.UIPanel +UIPainter = CS.FairyGUI.UIPainter +TypingEffect = CS.FairyGUI.TypingEffect diff --git a/Packages/manifest.json b/Packages/manifest.json index 21e25a54..f9bd0476 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -1,11 +1,17 @@ { "dependencies": { - "com.unity.ads": "2.0.8", - "com.unity.analytics": "3.2.2", - "com.unity.collab-proxy": "1.2.15", - "com.unity.package-manager-ui": "2.0.13", - "com.unity.purchasing": "2.1.1", + "com.unity.2d.sprite": "1.0.0", + "com.unity.2d.tilemap": "1.0.0", + "com.unity.ide.rider": "3.0.16", + "com.unity.ide.visualstudio": "2.0.16", + "com.unity.ide.vscode": "1.2.5", + "com.unity.purchasing": "4.4.1", + "com.unity.test-framework": "1.1.33", + "com.unity.timeline": "1.7.2", + "com.unity.ugui": "1.0.0", + "com.unity.xr.legacyinputhelpers": "2.1.10", "com.unity.modules.ai": "1.0.0", + "com.unity.modules.androidjni": "1.0.0", "com.unity.modules.animation": "1.0.0", "com.unity.modules.assetbundle": "1.0.0", "com.unity.modules.audio": "1.0.0", diff --git a/Packages/packages-lock.json b/Packages/packages-lock.json new file mode 100644 index 00000000..2f2532e9 --- /dev/null +++ b/Packages/packages-lock.json @@ -0,0 +1,406 @@ +{ + "dependencies": { + "com.unity.2d.sprite": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.2d.tilemap": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.ads": { + "version": "4.3.0", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.ugui": "1.0.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.analytics": { + "version": "3.7.1", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.services.analytics": "1.0.4", + "com.unity.ugui": "1.0.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.ext.nunit": { + "version": "1.0.6", + "depth": 1, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.cn" + }, + "com.unity.ide.rider": { + "version": "3.0.16", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.ext.nunit": "1.0.6" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.ide.visualstudio": { + "version": "2.0.16", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.test-framework": "1.1.9" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.ide.vscode": { + "version": "1.2.5", + "depth": 0, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.cn" + }, + "com.unity.nuget.newtonsoft-json": { + "version": "3.0.2", + "depth": 2, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.cn" + }, + "com.unity.purchasing": { + "version": "4.4.1", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.ugui": "1.0.0", + "com.unity.modules.unityanalytics": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.androidjni": "1.0.0", + "com.unity.services.core": "1.3.1", + "com.unity.services.analytics": "4.0.1" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.services.analytics": { + "version": "4.2.0", + "depth": 1, + "source": "registry", + "dependencies": { + "com.unity.ugui": "1.0.0", + "com.unity.services.core": "1.4.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.services.core": { + "version": "1.4.3", + "depth": 1, + "source": "registry", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.nuget.newtonsoft-json": "3.0.2", + "com.unity.modules.androidjni": "1.0.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.test-framework": { + "version": "1.1.33", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.ext.nunit": "1.0.6", + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.timeline": { + "version": "1.7.1", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.modules.director": "1.0.0", + "com.unity.modules.animation": "1.0.0", + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.particlesystem": "1.0.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.ugui": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.imgui": "1.0.0" + } + }, + "com.unity.xr.legacyinputhelpers": { + "version": "2.1.10", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.modules.vr": "1.0.0", + "com.unity.modules.xr": "1.0.0" + }, + "url": "https://packages.unity.cn" + }, + "com.unity.modules.ai": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.androidjni": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.animation": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.assetbundle": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.audio": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.cloth": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0" + } + }, + "com.unity.modules.director": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.animation": "1.0.0" + } + }, + "com.unity.modules.imageconversion": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.imgui": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.jsonserialize": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.particlesystem": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.physics": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.physics2d": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.screencapture": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.imageconversion": "1.0.0" + } + }, + "com.unity.modules.subsystems": { + "version": "1.0.0", + "depth": 1, + "source": "builtin", + "dependencies": { + "com.unity.modules.jsonserialize": "1.0.0" + } + }, + "com.unity.modules.terrain": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.terrainphysics": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.terrain": "1.0.0" + } + }, + "com.unity.modules.tilemap": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics2d": "1.0.0" + } + }, + "com.unity.modules.ui": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.uielements": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.uielementsnative": "1.0.0" + } + }, + "com.unity.modules.uielementsnative": { + "version": "1.0.0", + "depth": 1, + "source": "builtin", + "dependencies": { + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + } + }, + "com.unity.modules.umbra": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.unityanalytics": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + } + }, + "com.unity.modules.unitywebrequest": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.unitywebrequestassetbundle": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0" + } + }, + "com.unity.modules.unitywebrequestaudio": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.audio": "1.0.0" + } + }, + "com.unity.modules.unitywebrequesttexture": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0" + } + }, + "com.unity.modules.unitywebrequestwww": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.unitywebrequestassetbundle": "1.0.0", + "com.unity.modules.unitywebrequestaudio": "1.0.0", + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0" + } + }, + "com.unity.modules.vehicles": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0" + } + }, + "com.unity.modules.video": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0" + } + }, + "com.unity.modules.vr": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.xr": "1.0.0" + } + }, + "com.unity.modules.wind": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.xr": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.subsystems": "1.0.0" + } + } + } +} diff --git a/ProjectSettings/AutoStreamingSettings.asset b/ProjectSettings/AutoStreamingSettings.asset new file mode 100644 index 00000000..d3e071e2 --- /dev/null +++ b/ProjectSettings/AutoStreamingSettings.asset @@ -0,0 +1,21 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1200 &1 +AutoStreamingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + mSearchMode: 15 + mCustomSearchFile: + mTextureSearchString: + mMeshSearchString: + mTextures: [] + mAudios: [] + mMeshes: [] + mScenes: [] + mConfigCCD: + useCCD: 0 + cosKey: + projectGuid: + bucketUuid: + bucketName: + badgeName: diff --git a/ProjectSettings/EditorBuildSettings.asset b/ProjectSettings/EditorBuildSettings.asset index 47055bd4..30569f0d 100644 --- a/ProjectSettings/EditorBuildSettings.asset +++ b/ProjectSettings/EditorBuildSettings.asset @@ -11,3 +11,4 @@ EditorBuildSettings: - enabled: 1 path: Assets/Examples/Scenes/scene2.unity guid: 44b386c5d0d35be45b1a3f0e55977f62 + m_configObjects: {} diff --git a/ProjectSettings/EditorSettings.asset b/ProjectSettings/EditorSettings.asset index fb9225f1..c85c533b 100644 --- a/ProjectSettings/EditorSettings.asset +++ b/ProjectSettings/EditorSettings.asset @@ -3,18 +3,43 @@ --- !u!159 &1 EditorSettings: m_ObjectHideFlags: 0 - serializedVersion: 5 - m_ExternalVersionControlSupport: Hidden Meta Files + serializedVersion: 12 m_SerializationMode: 2 + m_LineEndingsForNewScripts: 1 m_DefaultBehaviorMode: 0 + m_PrefabRegularEnvironment: {fileID: 0} + m_PrefabUIEnvironment: {fileID: 0} m_SpritePackerMode: 0 + m_SpritePackerCacheSize: 10 m_SpritePackerPaddingPower: 1 + m_Bc7TextureCompressor: 0 m_EtcTextureCompressorBehavior: 1 m_EtcTextureFastCompressor: 1 m_EtcTextureNormalCompressor: 2 m_EtcTextureBestCompressor: 4 - m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd + m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmref m_ProjectGenerationRootNamespace: - m_UserGeneratedProjectSuffix: - m_CollabEditorSettings: - inProgressEnabled: 1 + m_EnableTextureStreamingInEditMode: 1 + m_EnableTextureStreamingInPlayMode: 1 + m_EnableEditorAsyncCPUTextureLoading: 0 + m_AsyncShaderCompilation: 1 + m_PrefabModeAllowAutoSave: 1 + m_EnterPlayModeOptionsEnabled: 1 + m_EnterPlayModeOptions: 3 + m_GameObjectNamingDigits: 1 + m_GameObjectNamingScheme: 0 + m_AssetNamingUsesSpace: 1 + m_UseLegacyProbeSampleCount: 1 + m_SerializeInlineMappingsOnOneLine: 0 + m_DisableCookiesInLightmapper: 1 + m_AssetPipelineMode: 1 + m_RefreshImportMode: 0 + m_CacheServerMode: 0 + m_CacheServerEndpoint: + m_CacheServerNamespacePrefix: default + m_CacheServerEnableDownload: 1 + m_CacheServerEnableUpload: 1 + m_CacheServerEnableAuth: 0 + m_CacheServerEnableTls: 0 + m_CacheServerValidationMode: 2 + m_CacheServerDownloadBatchSize: 128 diff --git a/ProjectSettings/MemorySettings.asset b/ProjectSettings/MemorySettings.asset new file mode 100644 index 00000000..5b5facec --- /dev/null +++ b/ProjectSettings/MemorySettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!387306366 &1 +MemorySettings: + m_ObjectHideFlags: 0 + m_EditorMemorySettings: + m_MainAllocatorBlockSize: -1 + m_ThreadAllocatorBlockSize: -1 + m_MainGfxBlockSize: -1 + m_ThreadGfxBlockSize: -1 + m_CacheBlockSize: -1 + m_TypetreeBlockSize: -1 + m_ProfilerBlockSize: -1 + m_ProfilerEditorBlockSize: -1 + m_BucketAllocatorGranularity: -1 + m_BucketAllocatorBucketsCount: -1 + m_BucketAllocatorBlockSize: -1 + m_BucketAllocatorBlockCount: -1 + m_ProfilerBucketAllocatorGranularity: -1 + m_ProfilerBucketAllocatorBucketsCount: -1 + m_ProfilerBucketAllocatorBlockSize: -1 + m_ProfilerBucketAllocatorBlockCount: -1 + m_TempAllocatorSizeMain: -1 + m_JobTempAllocatorBlockSize: -1 + m_BackgroundJobTempAllocatorBlockSize: -1 + m_JobTempAllocatorReducedBlockSize: -1 + m_TempAllocatorSizeGIBakingWorker: -1 + m_TempAllocatorSizeNavMeshWorker: -1 + m_TempAllocatorSizeAudioWorker: -1 + m_TempAllocatorSizeCloudWorker: -1 + m_TempAllocatorSizeGfx: -1 + m_TempAllocatorSizeJobWorker: -1 + m_TempAllocatorSizeBackgroundWorker: -1 + m_TempAllocatorSizePreloadManager: -1 + m_PlatformMemorySettings: {} diff --git a/ProjectSettings/PackageManagerSettings.asset b/ProjectSettings/PackageManagerSettings.asset new file mode 100644 index 00000000..cdafc5c0 --- /dev/null +++ b/ProjectSettings/PackageManagerSettings.asset @@ -0,0 +1,35 @@ +%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_EnablePreReleasePackages: 0 + m_EnablePackageDependencies: 0 + m_AdvancedSettingsExpanded: 1 + m_ScopedRegistriesSettingsExpanded: 1 + m_SeeAllPackageVersions: 0 + oneTimeWarningShown: 0 + m_Registries: + - m_Id: main + m_Name: + m_Url: https://packages.unity.cn + m_Scopes: [] + m_IsDefault: 1 + m_Capabilities: 7 + m_UserSelectedRegistryName: + m_UserAddingNewScopedRegistry: 0 + m_RegistryInfoDraft: + m_Modified: 0 + m_ErrorMessage: + m_UserModificationsInstanceId: -848 + m_OriginalInstanceId: -850 + m_LoadAssets: 0 diff --git a/ProjectSettings/PresetManager.asset b/ProjectSettings/PresetManager.asset index b33fa2b9..67a94dae 100644 Binary files a/ProjectSettings/PresetManager.asset and b/ProjectSettings/PresetManager.asset differ diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index ad70ae78..be1aaeb0 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -3,7 +3,7 @@ --- !u!129 &1 PlayerSettings: m_ObjectHideFlags: 0 - serializedVersion: 18 + serializedVersion: 24 productGUID: 96718396fbde0c042854fd226add78f5 AndroidProfiler: 0 AndroidFilterTouchesWhenObscured: 0 @@ -41,12 +41,6 @@ PlayerSettings: height: 1 m_SplashScreenLogos: [] m_VirtualRealitySplashScreen: {fileID: 0} - m_ShowUnitySplashAds: 0 - m_AdsAndroidGameId: - m_AdsIosGameId: - m_ShowSplashAdsSlogan: 0 - m_SloganImage: {fileID: 0} - m_SloganHeight: 150 m_HolographicTrackingLossScreen: {fileID: 0} defaultScreenWidth: 1024 defaultScreenHeight: 768 @@ -54,13 +48,14 @@ PlayerSettings: defaultScreenHeightWeb: 600 m_StereoRenderingPath: 0 m_ActiveColorSpace: 0 + m_SpriteBatchVertexThreshold: 300 m_MTRendering: 1 + mipStripping: 0 + numberOfMipsStripped: 0 m_StackTraceTypes: 010000000100000001000000010000000100000001000000 iosShowActivityIndicatorOnLoading: -1 androidShowActivityIndicatorOnLoading: -1 - displayResolutionDialog: 1 iosUseCustomAppBackgroundBehavior: 0 - iosAllowHTTPDownload: 1 allowedAutorotateToPortrait: 1 allowedAutorotateToPortraitUpsideDown: 1 allowedAutorotateToLandscapeRight: 1 @@ -71,7 +66,14 @@ PlayerSettings: disableDepthAndStencilBuffers: 0 androidStartInFullscreen: 1 androidRenderOutsideSafeArea: 0 + androidUseSwappy: 0 androidBlitType: 0 + androidResizableWindow: 0 + androidDefaultWindowWidth: 1920 + androidDefaultWindowHeight: 1080 + androidMinimumWindowWidth: 400 + androidMinimumWindowHeight: 300 + androidFullscreenMode: 1 defaultIsNativeResolution: 1 macRetinaSupport: 1 runInBackground: 0 @@ -85,11 +87,11 @@ PlayerSettings: usePlayerLog: 1 bakeCollisionMeshes: 0 forceSingleInstance: 0 + useFlipModelSwapchain: 1 resizableWindow: 0 useMacAppStoreValidation: 0 macAppStoreCategory: public.app-category.games gpuSkinning: 0 - graphicsJobs: 0 xboxPIXTextureCapture: 0 xboxEnableAvatar: 0 xboxEnableKinect: 0 @@ -97,7 +99,6 @@ PlayerSettings: xboxEnableFitness: 0 visibleInBackground: 1 allowFullscreenSwitch: 1 - graphicsJobMode: 0 fullscreenMode: 1 xboxSpeechDB: 0 xboxEnableHeadOrientation: 0 @@ -118,8 +119,18 @@ PlayerSettings: switchNVNShaderPoolsGranularity: 33554432 switchNVNDefaultPoolsGranularity: 16777216 switchNVNOtherPoolsGranularity: 16777216 + switchGpuScratchPoolGranularity: 2097152 + switchAllowGpuScratchShrinking: 0 + switchNVNMaxPublicTextureIDCount: 0 + switchNVNMaxPublicSamplerIDCount: 0 + switchNVNGraphicsFirmwareMemory: 32 + stadiaPresentMode: 0 + stadiaTargetFramerate: 0 + vulkanNumSwapchainBuffers: 3 vulkanEnableSetSRGBWrite: 0 - useSecurityBuild: 0 + vulkanEnablePreTransform: 0 + vulkanEnableLateAcquireNextImage: 0 + vulkanEnableCommandBufferRecycling: 1 m_SupportedAspectRatios: 4:3: 1 5:4: 1 @@ -133,40 +144,26 @@ PlayerSettings: m_HolographicPauseOnTrackingLoss: 1 xboxOneDisableKinectGpuReservation: 0 xboxOneEnable7thCore: 0 - isWsaHolographicRemotingEnabled: 0 vrSettings: - cardboard: - depthFormat: 0 - enableTransitionView: 0 - daydream: - depthFormat: 0 - useSustainedPerformanceMode: 0 - enableVideoLayer: 0 - useProtectedVideoMemory: 0 - minimumSupportedHeadTracking: 0 - maximumSupportedHeadTracking: 1 - hololens: - depthFormat: 1 - depthBufferSharingEnabled: 1 - oculus: - sharedDepthBuffer: 1 - dashSupport: 1 - lowOverheadMode: 0 - protectedContext: 0 - v2Signing: 0 enable360StereoCapture: 0 - protectGraphicsMemory: 0 + isWsaHolographicRemotingEnabled: 0 enableFrameTimingStats: 0 useHDRDisplay: 0 + D3DHDRBitDepth: 0 m_ColorGamuts: 00000000 targetPixelDensity: 30 resolutionScalingMode: 0 + resetResolutionOnWindowResize: 0 androidSupportedAspectRatio: 1 androidMaxAspectRatio: 2.1 applicationIdentifier: {} - buildNumber: {} + buildNumber: + Standalone: 0 + iPhone: 0 + tvOS: 0 + overrideDefaultApplicationIdentifier: 0 AndroidBundleVersionCode: 1 - AndroidMinSdkVersion: 16 + AndroidMinSdkVersion: 22 AndroidTargetSdkVersion: 0 AndroidPreferredInstallLocation: 1 aotOptions: @@ -179,30 +176,19 @@ PlayerSettings: APKExpansionFiles: 0 keepLoadedShadersAlive: 0 StripUnusedMeshComponents: 0 + strictShaderVariantMatching: 0 VertexChannelCompressionMask: 214 iPhoneSdkVersion: 988 - iOSTargetOSVersionString: 9.0 + iOSTargetOSVersionString: 12.0 tvOSSdkVersion: 0 tvOSRequireExtendedGameController: 0 - tvOSTargetOSVersionString: 9.0 + tvOSTargetOSVersionString: 12.0 uIPrerenderedIcon: 0 uIRequiresPersistentWiFi: 0 uIRequiresFullScreen: 1 uIStatusBarHidden: 1 uIExitOnSuspend: 0 uIStatusBarStyle: 0 - iPhoneSplashScreen: {fileID: 0} - iPhoneHighResSplashScreen: {fileID: 0} - iPhoneTallHighResSplashScreen: {fileID: 0} - iPhone47inSplashScreen: {fileID: 0} - iPhone55inPortraitSplashScreen: {fileID: 0} - iPhone55inLandscapeSplashScreen: {fileID: 0} - iPhone58inPortraitSplashScreen: {fileID: 0} - iPhone58inLandscapeSplashScreen: {fileID: 0} - iPadPortraitSplashScreen: {fileID: 0} - iPadHighResPortraitSplashScreen: {fileID: 0} - iPadLandscapeSplashScreen: {fileID: 0} - iPadHighResLandscapeSplashScreen: {fileID: 0} appleTVSplashScreen: {fileID: 0} appleTVSplashScreen2x: {fileID: 0} tvOSSmallIconLayers: [] @@ -230,15 +216,17 @@ PlayerSettings: iOSLaunchScreeniPadFillPct: 100 iOSLaunchScreeniPadSize: 100 iOSLaunchScreeniPadCustomXibPath: - iOSUseLaunchScreenStoryboard: 0 iOSLaunchScreenCustomStoryboardPath: + iOSLaunchScreeniPadCustomStoryboardPath: iOSDeviceRequirements: [] iOSURLSchemes: [] + macOSURLSchemes: [] iOSBackgroundModes: 0 iOSMetalForceHardShadows: 0 metalEditorSupport: 1 metalAPIValidation: 1 iOSRenderExtraFrameOnPause: 0 + iosCopyPluginsCodeInsteadOfSymlink: 0 appleDeveloperTeamID: iOSManualSigningProvisioningProfileID: tvOSManualSigningProvisioningProfileID: @@ -248,10 +236,19 @@ PlayerSettings: iOSRequireARKit: 0 iOSAutomaticallyDetectAndAddCapabilities: 1 appleEnableProMotion: 0 + shaderPrecisionModel: 0 clonedFromGUID: 00000000000000000000000000000000 templatePackageId: templateDefaultScene: + useCustomMainManifest: 0 + useCustomLauncherManifest: 0 + useCustomMainGradleTemplate: 0 + useCustomLauncherGradleManifest: 0 + useCustomBaseGradleTemplate: 0 + useCustomGradlePropertiesTemplate: 0 + useCustomProguardFile: 0 AndroidTargetArchitectures: 5 + AndroidTargetDevices: 0 AndroidSplashScreenScale: 0 androidSplashScreen: {fileID: 0} AndroidKeystoreName: @@ -262,21 +259,265 @@ PlayerSettings: AndroidEnableTango: 0 androidEnableBanner: 1 androidUseLowAccuracyLocation: 0 + androidUseCustomKeystore: 0 m_AndroidBanners: - width: 320 height: 180 banner: {fileID: 0} androidGamepadSupportLevel: 0 - resolutionDialogBanner: {fileID: 0} + chromeosInputEmulation: 1 + AndroidMinifyWithR8: 0 + AndroidMinifyRelease: 0 + AndroidMinifyDebug: 0 + AndroidValidateAppBundleSize: 1 + AndroidAppBundleSizeToValidate: 150 m_BuildTargetIcons: [] - m_BuildTargetPlatformIcons: [] + m_BuildTargetPlatformIcons: + - m_BuildTarget: iPhone + m_Icons: + - m_Textures: [] + m_Width: 180 + m_Height: 180 + m_Kind: 0 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 120 + m_Height: 120 + m_Kind: 0 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 167 + m_Height: 167 + m_Kind: 0 + m_SubKind: iPad + - m_Textures: [] + m_Width: 152 + m_Height: 152 + m_Kind: 0 + m_SubKind: iPad + - m_Textures: [] + m_Width: 76 + m_Height: 76 + m_Kind: 0 + m_SubKind: iPad + - m_Textures: [] + m_Width: 120 + m_Height: 120 + m_Kind: 3 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 80 + m_Height: 80 + m_Kind: 3 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 80 + m_Height: 80 + m_Kind: 3 + m_SubKind: iPad + - m_Textures: [] + m_Width: 40 + m_Height: 40 + m_Kind: 3 + m_SubKind: iPad + - m_Textures: [] + m_Width: 87 + m_Height: 87 + m_Kind: 1 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 58 + m_Height: 58 + m_Kind: 1 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 29 + m_Height: 29 + m_Kind: 1 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 58 + m_Height: 58 + m_Kind: 1 + m_SubKind: iPad + - m_Textures: [] + m_Width: 29 + m_Height: 29 + m_Kind: 1 + m_SubKind: iPad + - m_Textures: [] + m_Width: 60 + m_Height: 60 + m_Kind: 2 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 40 + m_Height: 40 + m_Kind: 2 + m_SubKind: iPhone + - m_Textures: [] + m_Width: 40 + m_Height: 40 + m_Kind: 2 + m_SubKind: iPad + - m_Textures: [] + m_Width: 20 + m_Height: 20 + m_Kind: 2 + m_SubKind: iPad + - m_Textures: [] + m_Width: 1024 + m_Height: 1024 + m_Kind: 4 + m_SubKind: App Store + - m_BuildTarget: Android + m_Icons: + - m_Textures: [] + m_Width: 432 + m_Height: 432 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 324 + m_Height: 324 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 216 + m_Height: 216 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 162 + m_Height: 162 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 108 + m_Height: 108 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 81 + m_Height: 81 + m_Kind: 2 + m_SubKind: + - m_Textures: [] + m_Width: 192 + m_Height: 192 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 144 + m_Height: 144 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 96 + m_Height: 96 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 72 + m_Height: 72 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 48 + m_Height: 48 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 36 + m_Height: 36 + m_Kind: 1 + m_SubKind: + - m_Textures: [] + m_Width: 192 + m_Height: 192 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 144 + m_Height: 144 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 96 + m_Height: 96 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 72 + m_Height: 72 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 48 + m_Height: 48 + m_Kind: 0 + m_SubKind: + - m_Textures: [] + m_Width: 36 + m_Height: 36 + m_Kind: 0 + m_SubKind: m_BuildTargetBatching: [] - m_BuildTargetEncrypting: [] - m_BuildTargetGraphicsAPIs: [] + m_BuildTargetGraphicsJobs: + - m_BuildTarget: WindowsStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: MacStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: LinuxStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: AndroidPlayer + m_GraphicsJobs: 0 + - m_BuildTarget: iOSSupport + m_GraphicsJobs: 0 + - m_BuildTarget: PS4Player + m_GraphicsJobs: 0 + - m_BuildTarget: PS5Player + m_GraphicsJobs: 0 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobs: 0 + - m_BuildTarget: GameCoreXboxOneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: GameCoreScarlettSupport + m_GraphicsJobs: 0 + - m_BuildTarget: Switch + m_GraphicsJobs: 0 + - m_BuildTarget: WebGLSupport + m_GraphicsJobs: 0 + - m_BuildTarget: MetroSupport + m_GraphicsJobs: 0 + - m_BuildTarget: AppleTVSupport + m_GraphicsJobs: 0 + - m_BuildTarget: BJMSupport + m_GraphicsJobs: 0 + - m_BuildTarget: LuminSupport + m_GraphicsJobs: 0 + - m_BuildTarget: CloudRendering + m_GraphicsJobs: 0 + - m_BuildTarget: EmbeddedLinux + m_GraphicsJobs: 0 + - m_BuildTarget: QNX + m_GraphicsJobs: 0 + m_BuildTargetGraphicsJobMode: + - m_BuildTarget: PS4Player + m_GraphicsJobMode: 0 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobMode: 0 + m_BuildTargetGraphicsAPIs: + - m_BuildTarget: iOSSupport + m_APIs: 10000000 + m_Automatic: 1 + - m_BuildTarget: AndroidPlayer + m_APIs: 0b00000008000000 + m_Automatic: 0 m_BuildTargetVRSettings: [] - m_BuildTargetEnableVuforiaSettings: [] openGLRequireES31: 0 openGLRequireES31AEP: 0 + openGLRequireES32: 0 m_TemplateCustomTags: {} mobileMTRendering: Android: 1 @@ -289,7 +530,16 @@ PlayerSettings: m_EncodingQuality: 1 - m_BuildTarget: PS4 m_EncodingQuality: 1 + m_BuildTargetGroupHDRCubemapEncodingQuality: + - m_BuildTarget: Standalone + m_EncodingQuality: 2 + - m_BuildTarget: XboxOne + m_EncodingQuality: 2 + - m_BuildTarget: PS4 + m_EncodingQuality: 2 m_BuildTargetGroupLightmapSettings: [] + m_BuildTargetNormalMapEncoding: [] + m_BuildTargetDefaultTextureCompressionFormat: [] playModeTestRunnerEnabled: 0 runPlayModeTestAsEditModeTest: 0 actionOnDotNetUnhandledException: 1 @@ -299,14 +549,20 @@ PlayerSettings: cameraUsageDescription: locationUsageDescription: microphoneUsageDescription: + bluetoothUsageDescription: + macOSTargetOSVersion: 10.13.0 + switchNMETAOverride: switchNetLibKey: switchSocketMemoryPoolSize: 6144 switchSocketAllocatorPoolSize: 128 switchSocketConcurrencyLimit: 14 switchScreenResolutionBehavior: 2 switchUseCPUProfiler: 0 + switchUseGOLDLinker: 0 + switchLTOSetting: 0 switchApplicationID: 0x01004b9000490000 switchNSODependencies: + switchCompilerFlags: switchTitleNames_0: switchTitleNames_1: switchTitleNames_2: @@ -322,6 +578,7 @@ PlayerSettings: switchTitleNames_12: switchTitleNames_13: switchTitleNames_14: + switchTitleNames_15: switchPublisherNames_0: switchPublisherNames_1: switchPublisherNames_2: @@ -337,6 +594,7 @@ PlayerSettings: switchPublisherNames_12: switchPublisherNames_13: switchPublisherNames_14: + switchPublisherNames_15: switchIcons_0: {fileID: 0} switchIcons_1: {fileID: 0} switchIcons_2: {fileID: 0} @@ -352,6 +610,7 @@ PlayerSettings: switchIcons_12: {fileID: 0} switchIcons_13: {fileID: 0} switchIcons_14: {fileID: 0} + switchIcons_15: {fileID: 0} switchSmallIcons_0: {fileID: 0} switchSmallIcons_1: {fileID: 0} switchSmallIcons_2: {fileID: 0} @@ -367,6 +626,7 @@ PlayerSettings: switchSmallIcons_12: {fileID: 0} switchSmallIcons_13: {fileID: 0} switchSmallIcons_14: {fileID: 0} + switchSmallIcons_15: {fileID: 0} switchManualHTML: switchAccessibleURLs: switchLegalInformation: @@ -429,6 +689,11 @@ PlayerSettings: switchSocketInitializeEnabled: 1 switchNetworkInterfaceManagerInitializeEnabled: 1 switchPlayerConnectionEnabled: 1 + switchUseNewStyleFilepaths: 1 + switchUseMicroSleepForYield: 1 + switchEnableRamDiskSupport: 0 + switchMicroSleepForYieldTime: 25 + switchRamDiskSpaceSize: 12 ps4NPAgeRating: 12 ps4NPTitleSecret: ps4NPTrophyPackPath: @@ -455,6 +720,7 @@ PlayerSettings: ps4ShareFilePath: ps4ShareOverlayImagePath: ps4PrivacyGuardImagePath: + ps4ExtraSceSysFile: ps4NPtitleDatPath: ps4RemotePlayKeyAssignment: -1 ps4RemotePlayKeyMappingDir: @@ -467,6 +733,7 @@ PlayerSettings: ps4DownloadDataSize: 0 ps4GarlicHeapSize: 2048 ps4ProGarlicHeapSize: 2560 + playerPrefsMaxSize: 32768 ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ ps4pnSessions: 1 ps4pnPresence: 1 @@ -479,6 +746,7 @@ PlayerSettings: ps4UseResolutionFallback: 0 ps4ReprojectionSupport: 0 ps4UseAudio3dBackend: 0 + ps4UseLowGarlicFragmentationMode: 1 ps4SocialScreenEnabled: 0 ps4ScriptOptimizationLevel: 0 ps4Audio3dVirtualSpeakerCount: 14 @@ -495,11 +763,16 @@ PlayerSettings: ps4disableAutoHideSplash: 0 ps4videoRecordingFeaturesUsed: 0 ps4contentSearchFeaturesUsed: 0 + ps4CompatibilityPS5: 0 + ps4AllowPS5Detection: 0 + ps4GPU800MHz: 1 ps4attribEyeToEyeDistanceSettingVR: 0 ps4IncludedModules: [] + ps4attribVROutputEnabled: 0 monoEnv: splashScreenBackgroundSourceLandscape: {fileID: 0} splashScreenBackgroundSourcePortrait: {fileID: 0} + blurSplashScreenBackground: 1 spritePackerPolicy: webGLMemorySize: 256 webGLExceptionSupport: 1 @@ -512,17 +785,35 @@ PlayerSettings: webGLAnalyzeBuildSize: 0 webGLUseEmbeddedResources: 0 webGLCompressionFormat: 1 + webGLWasmArithmeticExceptions: 0 webGLLinkerTarget: 1 webGLThreadsSupport: 0 + webGLDecompressionFallback: 0 + webGLInitialMemorySize: 32 + webGLMaximumMemorySize: 2048 + webGLMemoryGrowthMode: 2 + webGLMemoryLinearGrowthStep: 16 + webGLMemoryGeometricGrowthStep: 0.2 + webGLMemoryGeometricGrowthCap: 96 + webGLPowerPreference: 2 scriptingDefineSymbols: {} + additionalCompilerArguments: {} platformArchitecture: {} scriptingBackend: {} il2cppCompilerConfiguration: {} + il2cppCodeGeneration: {} managedStrippingLevel: {} incrementalIl2cppBuild: {} + suppressCommonWarnings: 1 allowUnsafeCode: 0 + useDeterministicCompilation: 1 + enableRoslynAnalyzers: 1 + selectedPlatform: 0 additionalIl2CppArgs: scriptingRuntimeVersion: 1 + gcIncremental: 1 + assemblyVersionValidation: 1 + gcWBarrierValidation: 0 apiCompatibilityLevelPerPlatform: {} m_RenderingPath: 1 m_MobileRenderingPath: 1 @@ -553,7 +844,7 @@ PlayerSettings: metroFTAName: metroFTAFileTypes: [] metroProtocolName: - metroCompilationOverrides: 1 + vcxProjDefaultLanguage: XboxOneProductId: XboxOneUpdateKey: XboxOneSandboxId: @@ -572,18 +863,16 @@ PlayerSettings: XboxOneCapability: [] XboxOneGameRating: {} XboxOneIsContentPackage: 0 + XboxOneEnhancedXboxCompatibilityMode: 0 XboxOneEnableGPUVariability: 0 XboxOneSockets: {} XboxOneSplashScreen: {fileID: 0} XboxOneAllowedProductIds: [] XboxOnePersistentLocalStorageSize: 0 XboxOneXTitleMemory: 8 - xboxOneScriptCompiler: 0 XboxOneOverrideIdentityName: - vrEditorSettings: - daydream: - daydreamIconForeground: {fileID: 0} - daydreamIconBackground: {fileID: 0} + XboxOneOverrideIdentityPublisher: + vrEditorSettings: {} cloudServicesEnabled: {} luminIcon: m_Name: @@ -591,24 +880,21 @@ PlayerSettings: m_PortalFolderPath: luminCert: m_CertPath: - m_PrivateKeyPath: + m_SignPackage: 1 luminIsChannelApp: 0 luminVersion: m_VersionCode: 1 m_VersionName: - facebookSdkVersion: 7.9.4 - facebookAppId: - facebookCookies: 1 - facebookLogging: 1 - facebookStatus: 1 - facebookXfbml: 0 - facebookFrictionlessRequests: 1 apiCompatibilityLevel: 6 + activeInputHandler: 0 cloudProjectId: framebufferDepthMemorylessMode: 0 + qualitySettingsNames: [] projectName: organizationId: cloudEnabled: 0 - enableNativePlatformBackendsForNewInputSystem: 0 - disableOldInputManagerSupport: 0 legacyClampBlendShapeWeights: 1 + playerDataPath: + forceSRGBBlit: 1 + virtualTexturingSupportEnabled: 0 + insecureHttpOption: 0 diff --git a/ProjectSettings/ProjectVersion.txt b/ProjectSettings/ProjectVersion.txt index 7dbf3ee7..22ff47c5 100644 --- a/ProjectSettings/ProjectVersion.txt +++ b/ProjectSettings/ProjectVersion.txt @@ -1 +1,2 @@ -m_EditorVersion: 2018.4.29f1 +m_EditorVersion: 2021.3.12f1c1 +m_EditorVersionWithRevision: 2021.3.12f1c1 (867ad2d602fd) diff --git a/ProjectSettings/VFXManager.asset b/ProjectSettings/VFXManager.asset index 243dbac9..2efb2701 100644 Binary files a/ProjectSettings/VFXManager.asset and b/ProjectSettings/VFXManager.asset differ diff --git a/ProjectSettings/VersionControlSettings.asset b/ProjectSettings/VersionControlSettings.asset new file mode 100644 index 00000000..dca28814 --- /dev/null +++ b/ProjectSettings/VersionControlSettings.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!890905787 &1 +VersionControlSettings: + m_ObjectHideFlags: 0 + m_Mode: Visible Meta Files + m_CollabEditorSettings: + inProgressEnabled: 1 diff --git a/ProjectSettings/boot.config b/ProjectSettings/boot.config new file mode 100644 index 00000000..e69de29b diff --git a/README_zh-CN.md b/README_zh-CN.md index fac9c59a..787f87c7 100644 --- a/README_zh-CN.md +++ b/README_zh-CN.md @@ -1,31 +1,31 @@ - FairyGUI for Unity -==== - -FairyGUI是一个适用于许多游戏引擎的UI中间件。
-[下载编辑器](https://www.fairygui.com/product.html) - -在运行效率方面,FairyGUI对DrawCall优化使用了特有的`FairyBatching`技术,相比NGUI、UGUI的传统优化技术更加高效而且容易控制,特别是对动静耦合越来越复杂的UI设计更是应付自如。
- -在功能方面,FairyGUI对传统UI制作痛点都有很好的内置支持,例如`图文混排`(包括文字和动画混排),`表情输入`(直接支持键盘上的表情),`虚拟列表`、`循环列表`,`像素级点击检测`,`曲面 UI`, `手势`,`粒子和模型穿插UI`,`打字效果`等。
- -FairyGUI还对所有输入方式进行了完整的封装,无论是鼠标、单点触摸、多点触摸还是VR手柄输入,开发者都可以使用相同的代码处理交互。
- -![](images/2015-11-10_000547.png) - -![](images/2015-11-10_001320.png) - -![](images/2015-11-10_001445.png) - -![](images/2015-11-10_001516.png) - -![](images/2016-06-15_010207.png) - - -学习 -==== - -[教程](https://www.fairygui.com/docs/guide/index.html) - -License -==== + FairyGUI for Unity +==== + +FairyGUI是一个适用于许多游戏引擎的UI中间件。
+[下载编辑器](https://www.fairygui.com/product.html) + +在运行效率方面,FairyGUI对DrawCall优化使用了特有的`FairyBatching`技术,相比NGUI、UGUI的传统优化技术更加高效而且容易控制,特别是对动静耦合越来越复杂的UI设计更是应付自如。
+ +在功能方面,FairyGUI对传统UI制作痛点都有很好的内置支持,例如`图文混排`(包括文字和动画混排),`表情输入`(直接支持键盘上的表情),`虚拟列表`、`循环列表`,`像素级点击检测`,`曲面 UI`, `手势`,`粒子和模型穿插UI`,`打字效果`等。
+ +FairyGUI还对所有输入方式进行了完整的封装,无论是鼠标、单点触摸、多点触摸还是VR手柄输入,开发者都可以使用相同的代码处理交互。
+ +![](images/2015-11-10_000547.png) + +![](images/2015-11-10_001320.png) + +![](images/2015-11-10_001445.png) + +![](images/2015-11-10_001516.png) + +![](images/2016-06-15_010207.png) + + +学习 +==== + +[教程](https://www.fairygui.com/docs/guide/index.html) + +License +==== MIT \ No newline at end of file diff --git a/README.md b/Readme.md similarity index 87% rename from README.md rename to Readme.md index fdab8519..dcd0abda 100644 --- a/README.md +++ b/Readme.md @@ -1,36 +1,46 @@ - FairyGUI for Unity -==== - -FairyGUI is a Cross Platform UI Editor & UI framework. -[Get FairyGUI-Editor](https://en.fairygui.com/product.html) - -Compared with traditional Unity UI engines such as NGUI and UGUI, FairyGUI uses a way of thinking closer to the designer to redefine the production process of the UI, which greatly reduces the time the programmer needs to invest in making the UI.
- -In terms of running efficiency, FairyGUI uses the unique `FairyBatching` technology for DrawCall optimization, which is more efficient and easier to control than the traditional optimization techniques of NGUI and UGUI.
- -In terms of functionality, FairyGUI has good built-in support for traditional UI production pain points, such as `rich text` (including image and animation), `emoji input` (direct support for keyboard), `virtual list`, `loop list`, `pixel-level hit test`, `curved UI`, `gesture`, `particles and model interspersed UI`, `typing effect`, etc.
- -FairyGUI also fully encapsulates all input methods. Whether mouse, single touch, multi-touch, or VR handle input, developers can use the same code to handle interaction.
- -The library was designed to work with Unity 5.6 and above, but is currently only tested with Unity 2018 and above. - -![](images/2015-11-10_000547.png) - -![](images/2015-11-10_001320.png) - -![](images/2015-11-10_001445.png) - -![](images/2015-11-10_001516.png) - -![](images/2016-06-15_010207.png) - -![](images/turn_page.gif) - -Learn -==== - -[Guide](https://en.fairygui.com/docs/guide/index.html) - -License -==== -MIT + FairyGUI for Unity +==== + +FairyGUI is a Cross Platform UI Editor & UI framework. +[Get FairyGUI-Editor](https://en.fairygui.com/product.html) + +- [Getting started](#getting-started) + +Compared with traditional Unity UI engines such as NGUI and UGUI, FairyGUI uses a way of thinking closer to the designer to redefine the production process of the UI, which greatly reduces the time the programmer needs to invest in making the UI.
+ +In terms of running efficiency, FairyGUI uses the unique `FairyBatching` technology for DrawCall optimization, which is more efficient and easier to control than the traditional optimization techniques of NGUI and UGUI.
+ +In terms of functionality, FairyGUI has good built-in support for traditional UI production pain points, such as `rich text` (including image and animation), `emoji input` (direct support for keyboard), `virtual list`, `loop list`, `pixel-level hit test`, `curved UI`, `gesture`, `particles and model interspersed UI`, `typing effect`, etc.
+ +FairyGUI also fully encapsulates all input methods. Whether mouse, single touch, multi-touch, or VR handle input, developers can use the same code to handle interaction.
+ +The library was designed to work with Unity 5.6 and above, but is currently only tested with Unity 2018 and above. + +![](images/2015-11-10_000547.png) + +![](images/2015-11-10_001320.png) + +![](images/2015-11-10_001445.png) + +![](images/2015-11-10_001516.png) + +![](images/2016-06-15_010207.png) + +![](images/turn_page.gif) + +Learn +==== + +[Guide](https://en.fairygui.com/docs/guide/index.html) + +Getting started +--- +Install the URL `add package from git url` under `Package Manager` window +``` +https://github.com/fairygui/FairyGUI-unity.git?path=Assets/Plugins/FairyGUI +``` + + +License +==== +MIT diff --git a/UIProject/FairyGUI-Unity-Examples.fairy b/UIProject/FairyGUI-Unity-Examples.fairy old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/BagButton.xml b/UIProject/assets/Bag/BagButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/BagGridSub.xml b/UIProject/assets/Bag/BagGridSub.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/BagWin.xml b/UIProject/assets/Bag/BagWin.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/CloseButton.xml b/UIProject/assets/Bag/CloseButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/Main.xml b/UIProject/assets/Bag/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/WindowFrame.xml b/UIProject/assets/Bag/WindowFrame.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/dot.xml b/UIProject/assets/Bag/dot.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/0.png b/UIProject/assets/Bag/images/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/1.png b/UIProject/assets/Bag/images/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/2.png b/UIProject/assets/Bag/images/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/3.png b/UIProject/assets/Bag/images/3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/4.png b/UIProject/assets/Bag/images/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/5.png b/UIProject/assets/Bag/images/5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/7.png b/UIProject/assets/Bag/images/7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/8.png b/UIProject/assets/Bag/images/8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/btnimage.png b/UIProject/assets/Bag/images/btnimage.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/images/quan.jta b/UIProject/assets/Bag/images/quan.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Bag/package.xml b/UIProject/assets/Bag/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/CircleProgress.xml b/UIProject/assets/Basics/CircleProgress.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Button.xml b/UIProject/assets/Basics/Demo_Button.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Clip&Scroll.xml b/UIProject/assets/Basics/Demo_Clip&Scroll.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_ComboBox.xml b/UIProject/assets/Basics/Demo_ComboBox.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Component.xml b/UIProject/assets/Basics/Demo_Component.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Controller.xml b/UIProject/assets/Basics/Demo_Controller.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Depth.xml b/UIProject/assets/Basics/Demo_Depth.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Drag&Drop.xml b/UIProject/assets/Basics/Demo_Drag&Drop.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Graph.xml b/UIProject/assets/Basics/Demo_Graph.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Grid.xml b/UIProject/assets/Basics/Demo_Grid.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Image.xml b/UIProject/assets/Basics/Demo_Image.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Label.xml b/UIProject/assets/Basics/Demo_Label.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_List.xml b/UIProject/assets/Basics/Demo_List.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Loader.xml b/UIProject/assets/Basics/Demo_Loader.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_MovieClip.xml b/UIProject/assets/Basics/Demo_MovieClip.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Popup.xml b/UIProject/assets/Basics/Demo_Popup.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_ProgressBar.xml b/UIProject/assets/Basics/Demo_ProgressBar.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Relation.xml b/UIProject/assets/Basics/Demo_Relation.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Slider.xml b/UIProject/assets/Basics/Demo_Slider.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Text.xml b/UIProject/assets/Basics/Demo_Text.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Demo_Window.xml b/UIProject/assets/Basics/Demo_Window.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/Main.xml b/UIProject/assets/Basics/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/WindowA.xml b/UIProject/assets/Basics/WindowA.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/WindowB.xml b/UIProject/assets/Basics/WindowB.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/BagGridSub.xml b/UIProject/assets/Basics/components/BagGridSub.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/BagGridSub2.xml b/UIProject/assets/Basics/components/BagGridSub2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button.xml b/UIProject/assets/Basics/components/Button.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button1.xml b/UIProject/assets/Basics/components/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button10.xml b/UIProject/assets/Basics/components/Button10.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button13.xml b/UIProject/assets/Basics/components/Button13.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button14.xml b/UIProject/assets/Basics/components/Button14.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button15.xml b/UIProject/assets/Basics/components/Button15.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button16.xml b/UIProject/assets/Basics/components/Button16.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button2.xml b/UIProject/assets/Basics/components/Button2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button3.xml b/UIProject/assets/Basics/components/Button3.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button4.xml b/UIProject/assets/Basics/components/Button4.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button5.xml b/UIProject/assets/Basics/components/Button5.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button52.xml b/UIProject/assets/Basics/components/Button52.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button6.xml b/UIProject/assets/Basics/components/Button6.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button7.xml b/UIProject/assets/Basics/components/Button7.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button8.xml b/UIProject/assets/Basics/components/Button8.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button82.xml b/UIProject/assets/Basics/components/Button82.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Button9.xml b/UIProject/assets/Basics/components/Button9.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Checkbox.xml b/UIProject/assets/Basics/components/Checkbox.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/CloseButton.xml b/UIProject/assets/Basics/components/CloseButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ComboBox.xml b/UIProject/assets/Basics/components/ComboBox.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ComboBoxItem.xml b/UIProject/assets/Basics/components/ComboBoxItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ComboBoxPopup.xml b/UIProject/assets/Basics/components/ComboBoxPopup.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component1.xml b/UIProject/assets/Basics/components/Component1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component10.xml b/UIProject/assets/Basics/components/Component10.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component11.xml b/UIProject/assets/Basics/components/Component11.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component12.xml b/UIProject/assets/Basics/components/Component12.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component13.xml b/UIProject/assets/Basics/components/Component13.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component14.xml b/UIProject/assets/Basics/components/Component14.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component2.xml b/UIProject/assets/Basics/components/Component2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component3.xml b/UIProject/assets/Basics/components/Component3.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component4.xml b/UIProject/assets/Basics/components/Component4.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component5.xml b/UIProject/assets/Basics/components/Component5.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component6.xml b/UIProject/assets/Basics/components/Component6.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component7.xml b/UIProject/assets/Basics/components/Component7.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component8.xml b/UIProject/assets/Basics/components/Component8.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Component9.xml b/UIProject/assets/Basics/components/Component9.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Dropdown.xml b/UIProject/assets/Basics/components/Dropdown.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Dropdown2.xml b/UIProject/assets/Basics/components/Dropdown2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/GridItem.xml b/UIProject/assets/Basics/components/GridItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/GridItem2.xml b/UIProject/assets/Basics/components/GridItem2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/OnOffButton.xml b/UIProject/assets/Basics/components/OnOffButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar.xml b/UIProject/assets/Basics/components/ProgressBar.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar1.xml b/UIProject/assets/Basics/components/ProgressBar1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar2.xml b/UIProject/assets/Basics/components/ProgressBar2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar3.xml b/UIProject/assets/Basics/components/ProgressBar3.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar4.xml b/UIProject/assets/Basics/components/ProgressBar4.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar5.xml b/UIProject/assets/Basics/components/ProgressBar5.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/ProgressBar6.xml b/UIProject/assets/Basics/components/ProgressBar6.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/RadioButton.xml b/UIProject/assets/Basics/components/RadioButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Slider1.xml b/UIProject/assets/Basics/components/Slider1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Slider2.xml b/UIProject/assets/Basics/components/Slider2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Slider2_grip.xml b/UIProject/assets/Basics/components/Slider2_grip.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/SliderArrow_HZ.xml b/UIProject/assets/Basics/components/SliderArrow_HZ.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/SliderArrow_VT.xml b/UIProject/assets/Basics/components/SliderArrow_VT.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Slider_HZ.xml b/UIProject/assets/Basics/components/Slider_HZ.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/Slider_VT.xml b/UIProject/assets/Basics/components/Slider_VT.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/WindowCloseButton.xml b/UIProject/assets/Basics/components/WindowCloseButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/WindowFrame.xml b/UIProject/assets/Basics/components/WindowFrame.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/components/WindowFrameB.xml b/UIProject/assets/Basics/components/WindowFrameB.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/font/BMFontTest.fnt b/UIProject/assets/Basics/font/BMFontTest.fnt old mode 100755 new mode 100644 index 1c577578..21b12d2f --- a/UIProject/assets/Basics/font/BMFontTest.fnt +++ b/UIProject/assets/Basics/font/BMFontTest.fnt @@ -1,19 +1,19 @@ -info face="ÃÔÄã¼ò¿¨ͨ" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 outline=0 -common lineHeight=32 base=26 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=1 redChnl=0 greenChnl=0 blueChnl=0 -page id=0 file="11_0.png" -chars count=15 -char id=0 x=0 y=0 width=22 height=36 xoffset=0 yoffset=0 xadvance=22 page=0 chnl=15 -char id=35 x=22 y=37 width=15 height=20 xoffset=0 yoffset=6 xadvance=14 page=0 chnl=15 -char id=73 x=59 y=25 width=5 height=17 xoffset=0 yoffset=9 xadvance=5 page=0 chnl=15 -char id=85 x=38 y=25 width=20 height=19 xoffset=0 yoffset=7 xadvance=20 page=0 chnl=15 -char id=20307 x=23 y=0 width=24 height=24 xoffset=2 yoffset=4 xadvance=28 page=0 chnl=15 -char id=20309 x=166 y=0 width=24 height=22 xoffset=1 yoffset=6 xadvance=28 page=0 chnl=15 -char id=20351 x=48 y=0 width=23 height=24 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 -char id=20837 x=0 y=37 width=21 height=20 xoffset=3 yoffset=7 xadvance=28 page=0 chnl=15 -char id=22120 x=191 y=0 width=21 height=22 xoffset=3 yoffset=6 xadvance=28 page=0 chnl=15 -char id=22914 x=213 y=0 width=21 height=22 xoffset=3 yoffset=6 xadvance=28 page=0 chnl=15 -char id=23383 x=96 y=0 width=21 height=24 xoffset=3 yoffset=4 xadvance=28 page=0 chnl=15 -char id=23884 x=72 y=0 width=23 height=24 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 -char id=29992 x=235 y=0 width=19 height=21 xoffset=4 yoffset=6 xadvance=28 page=0 chnl=15 -char id=32534 x=118 y=0 width=23 height=23 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 -char id=36753 x=142 y=0 width=23 height=23 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 +info face="ÃÔÄã¼ò¿¨ͨ" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 outline=0 +common lineHeight=32 base=26 scaleW=256 scaleH=256 pages=1 packed=0 alphaChnl=1 redChnl=0 greenChnl=0 blueChnl=0 +page id=0 file="11_0.png" +chars count=15 +char id=0 x=0 y=0 width=22 height=36 xoffset=0 yoffset=0 xadvance=22 page=0 chnl=15 +char id=35 x=22 y=37 width=15 height=20 xoffset=0 yoffset=6 xadvance=14 page=0 chnl=15 +char id=73 x=59 y=25 width=5 height=17 xoffset=0 yoffset=9 xadvance=5 page=0 chnl=15 +char id=85 x=38 y=25 width=20 height=19 xoffset=0 yoffset=7 xadvance=20 page=0 chnl=15 +char id=20307 x=23 y=0 width=24 height=24 xoffset=2 yoffset=4 xadvance=28 page=0 chnl=15 +char id=20309 x=166 y=0 width=24 height=22 xoffset=1 yoffset=6 xadvance=28 page=0 chnl=15 +char id=20351 x=48 y=0 width=23 height=24 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 +char id=20837 x=0 y=37 width=21 height=20 xoffset=3 yoffset=7 xadvance=28 page=0 chnl=15 +char id=22120 x=191 y=0 width=21 height=22 xoffset=3 yoffset=6 xadvance=28 page=0 chnl=15 +char id=22914 x=213 y=0 width=21 height=22 xoffset=3 yoffset=6 xadvance=28 page=0 chnl=15 +char id=23383 x=96 y=0 width=21 height=24 xoffset=3 yoffset=4 xadvance=28 page=0 chnl=15 +char id=23884 x=72 y=0 width=23 height=24 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 +char id=29992 x=235 y=0 width=19 height=21 xoffset=4 yoffset=6 xadvance=28 page=0 chnl=15 +char id=32534 x=118 y=0 width=23 height=23 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 +char id=36753 x=142 y=0 width=23 height=23 xoffset=2 yoffset=5 xadvance=28 page=0 chnl=15 diff --git a/UIProject/assets/Basics/font/BMFontTest_atlas.png b/UIProject/assets/Basics/font/BMFontTest_atlas.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/font/HitNumber.fnt b/UIProject/assets/Basics/font/HitNumber.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/10_png.png b/UIProject/assets/Basics/images/10_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/22.png b/UIProject/assets/Basics/images/22.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/6_png.png b/UIProject/assets/Basics/images/6_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/8_png.png b/UIProject/assets/Basics/images/8_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/9_png.png b/UIProject/assets/Basics/images/9_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/Shape 1 copy 4.png b/UIProject/assets/Basics/images/Shape 1 copy 4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/VIP_png.png b/UIProject/assets/Basics/images/VIP_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/VtSeperator.jpg b/UIProject/assets/Basics/images/VtSeperator.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/a18_png.png b/UIProject/assets/Basics/images/a18_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/a1_png.png b/UIProject/assets/Basics/images/a1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/a2_png.png b/UIProject/assets/Basics/images/a2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/a3_png.png b/UIProject/assets/Basics/images/a3_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/a4_png.png b/UIProject/assets/Basics/images/a4_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/a8_png.png b/UIProject/assets/Basics/images/a8_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/angry_smile_png.png b/UIProject/assets/Basics/images/angry_smile_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b1.png b/UIProject/assets/Basics/images/b1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b1.png.jpg b/UIProject/assets/Basics/images/b1.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b12_png.png b/UIProject/assets/Basics/images/b12_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b13_png.png b/UIProject/assets/Basics/images/b13_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b2.png b/UIProject/assets/Basics/images/b2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b2.png.jpg b/UIProject/assets/Basics/images/b2.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b3.png b/UIProject/assets/Basics/images/b3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b3.png.jpg b/UIProject/assets/Basics/images/b3.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b4.png b/UIProject/assets/Basics/images/b4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b4.png.jpg b/UIProject/assets/Basics/images/b4.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b5.png b/UIProject/assets/Basics/images/b5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b5_png.png b/UIProject/assets/Basics/images/b5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b6_png.png b/UIProject/assets/Basics/images/b6_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b7(2)_png.png b/UIProject/assets/Basics/images/b7(2)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/b7_png.png b/UIProject/assets/Basics/images/b7_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/back btn.png b/UIProject/assets/Basics/images/back btn.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/background.png b/UIProject/assets/Basics/images/background.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/c1_png.png b/UIProject/assets/Basics/images/c1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/c2_png.png b/UIProject/assets/Basics/images/c2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/c3_png.png b/UIProject/assets/Basics/images/c3_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/caiji.png b/UIProject/assets/Basics/images/caiji.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/caiji2.png b/UIProject/assets/Basics/images/caiji2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/change.png b/UIProject/assets/Basics/images/change.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/close_png.png b/UIProject/assets/Basics/images/close_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/full bar.png b/UIProject/assets/Basics/images/full bar.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/grid_header_png.png b/UIProject/assets/Basics/images/grid_header_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/gz.jta b/UIProject/assets/Basics/images/gz.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h0.png b/UIProject/assets/Basics/images/h0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h1.png b/UIProject/assets/Basics/images/h1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h2.png b/UIProject/assets/Basics/images/h2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h3.png b/UIProject/assets/Basics/images/h3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h4.png b/UIProject/assets/Basics/images/h4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h5.png b/UIProject/assets/Basics/images/h5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h6.png b/UIProject/assets/Basics/images/h6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h7.png b/UIProject/assets/Basics/images/h7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h8.png b/UIProject/assets/Basics/images/h8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/h9.png b/UIProject/assets/Basics/images/h9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/huawen1_png.png b/UIProject/assets/Basics/images/huawen1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/huawen2_png.png b/UIProject/assets/Basics/images/huawen2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/i256.png b/UIProject/assets/Basics/images/i256.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k0.png b/UIProject/assets/Basics/images/k0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k1.png b/UIProject/assets/Basics/images/k1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k10.png b/UIProject/assets/Basics/images/k10.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k11.png b/UIProject/assets/Basics/images/k11.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k12.png b/UIProject/assets/Basics/images/k12.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k13.png b/UIProject/assets/Basics/images/k13.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k14.png b/UIProject/assets/Basics/images/k14.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k16.jpg b/UIProject/assets/Basics/images/k16.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k17.png b/UIProject/assets/Basics/images/k17.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k18.png b/UIProject/assets/Basics/images/k18.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k19.png b/UIProject/assets/Basics/images/k19.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k2.png b/UIProject/assets/Basics/images/k2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k20.png b/UIProject/assets/Basics/images/k20.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k21.png b/UIProject/assets/Basics/images/k21.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k22.png b/UIProject/assets/Basics/images/k22.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k23.png b/UIProject/assets/Basics/images/k23.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k24.png b/UIProject/assets/Basics/images/k24.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k25.png b/UIProject/assets/Basics/images/k25.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k26.png b/UIProject/assets/Basics/images/k26.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k27.png b/UIProject/assets/Basics/images/k27.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k28.png b/UIProject/assets/Basics/images/k28.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k29.png b/UIProject/assets/Basics/images/k29.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k3.png b/UIProject/assets/Basics/images/k3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k30.png b/UIProject/assets/Basics/images/k30.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k31.png b/UIProject/assets/Basics/images/k31.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k32.png b/UIProject/assets/Basics/images/k32.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k33.png b/UIProject/assets/Basics/images/k33.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k34.png b/UIProject/assets/Basics/images/k34.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k35.png b/UIProject/assets/Basics/images/k35.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k36.png b/UIProject/assets/Basics/images/k36.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k4.png b/UIProject/assets/Basics/images/k4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k5.png b/UIProject/assets/Basics/images/k5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k6.png b/UIProject/assets/Basics/images/k6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k7.png b/UIProject/assets/Basics/images/k7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k8.png b/UIProject/assets/Basics/images/k8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/k9.png b/UIProject/assets/Basics/images/k9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/loading.png.jpg b/UIProject/assets/Basics/images/loading.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/long_dead2_png.png b/UIProject/assets/Basics/images/long_dead2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/long_dead_png.png b/UIProject/assets/Basics/images/long_dead_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/nlge1k.jta b/UIProject/assets/Basics/images/nlge1k.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p10_png.png b/UIProject/assets/Basics/images/p10_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p11_png.png b/UIProject/assets/Basics/images/p11_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p12_png.png b/UIProject/assets/Basics/images/p12_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p13_png.png b/UIProject/assets/Basics/images/p13_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p14_png.png b/UIProject/assets/Basics/images/p14_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p15_png.png b/UIProject/assets/Basics/images/p15_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p16_png.png b/UIProject/assets/Basics/images/p16_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p1_png.png b/UIProject/assets/Basics/images/p1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p2_png.png b/UIProject/assets/Basics/images/p2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p3_png.png b/UIProject/assets/Basics/images/p3_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p8_png.png b/UIProject/assets/Basics/images/p8_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/p9_png.png b/UIProject/assets/Basics/images/p9_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/pet.jta b/UIProject/assets/Basics/images/pet.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/pic.png b/UIProject/assets/Basics/images/pic.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/plus_smile_png.png b/UIProject/assets/Basics/images/plus_smile_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/qtm01d.swf b/UIProject/assets/Basics/images/qtm01d.swf old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/r3.png b/UIProject/assets/Basics/images/r3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/r4.png b/UIProject/assets/Basics/images/r4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/radial.png b/UIProject/assets/Basics/images/radial.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s1.png.jpg b/UIProject/assets/Basics/images/s1.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s10.png.jpg b/UIProject/assets/Basics/images/s10.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s2.png.jpg b/UIProject/assets/Basics/images/s2.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s3.png.jpg b/UIProject/assets/Basics/images/s3.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s4.png.jpg b/UIProject/assets/Basics/images/s4.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s5.png.jpg b/UIProject/assets/Basics/images/s5.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s6.png.jpg b/UIProject/assets/Basics/images/s6.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s7.png.jpg b/UIProject/assets/Basics/images/s7.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s8.png.jpg b/UIProject/assets/Basics/images/s8.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/s9.png.jpg b/UIProject/assets/Basics/images/s9.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/images/start.png b/UIProject/assets/Basics/images/start.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/package.xml b/UIProject/assets/Basics/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/popupmenu/PopupMenu.xml b/UIProject/assets/Basics/popupmenu/PopupMenu.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/popupmenu/PopupMenuItem.xml b/UIProject/assets/Basics/popupmenu/PopupMenuItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/scrollbars/GripButton_HZ.xml b/UIProject/assets/Basics/scrollbars/GripButton_HZ.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/scrollbars/GripButton_VT.xml b/UIProject/assets/Basics/scrollbars/GripButton_VT.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/scrollbars/ScrollBar_HZ.xml b/UIProject/assets/Basics/scrollbars/ScrollBar_HZ.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/scrollbars/ScrollBar_VT.xml b/UIProject/assets/Basics/scrollbars/ScrollBar_VT.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/scrollbars/ScrollDownButton.xml b/UIProject/assets/Basics/scrollbars/ScrollDownButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/scrollbars/ScrollUpButton.xml b/UIProject/assets/Basics/scrollbars/ScrollUpButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/sound/click.wav b/UIProject/assets/Basics/sound/click.wav old mode 100755 new mode 100644 diff --git a/UIProject/assets/Basics/sound/tabswitch.wav b/UIProject/assets/Basics/sound/tabswitch.wav old mode 100755 new mode 100644 diff --git a/UIProject/assets/BundleUsage/Main.xml b/UIProject/assets/BundleUsage/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/BundleUsage/package.xml b/UIProject/assets/BundleUsage/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/BundleUsage/sword.png b/UIProject/assets/BundleUsage/sword.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/Button1.xml b/UIProject/assets/Cooldown/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/Button2.xml b/UIProject/assets/Cooldown/Button2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/Main.xml b/UIProject/assets/Cooldown/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/cdtime.fnt b/UIProject/assets/Cooldown/cdtime.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/0(4)_png.png b/UIProject/assets/Cooldown/images/0(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/1(4)_png.png b/UIProject/assets/Cooldown/images/1(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/11.png b/UIProject/assets/Cooldown/images/11.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/12.png b/UIProject/assets/Cooldown/images/12.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/13.png b/UIProject/assets/Cooldown/images/13.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/14.png b/UIProject/assets/Cooldown/images/14.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/15.png b/UIProject/assets/Cooldown/images/15.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/2(4)_png.png b/UIProject/assets/Cooldown/images/2(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/3(4)_png.png b/UIProject/assets/Cooldown/images/3(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/4(4)_png.png b/UIProject/assets/Cooldown/images/4(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/5(4)_png.png b/UIProject/assets/Cooldown/images/5(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/6(4)_png.png b/UIProject/assets/Cooldown/images/6(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/7(4)_png.png b/UIProject/assets/Cooldown/images/7(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/8(4)_png.png b/UIProject/assets/Cooldown/images/8(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/9(4)_png.png b/UIProject/assets/Cooldown/images/9(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/mask0.png b/UIProject/assets/Cooldown/images/mask0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/images/mask1.png b/UIProject/assets/Cooldown/images/mask1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Cooldown/package.xml b/UIProject/assets/Cooldown/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/Main.xml b/UIProject/assets/Curve/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/item.xml b/UIProject/assets/Curve/item.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/n1.png b/UIProject/assets/Curve/n1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/n2.png b/UIProject/assets/Curve/n2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/n3.png b/UIProject/assets/Curve/n3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/n4.png b/UIProject/assets/Curve/n4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/n5.png b/UIProject/assets/Curve/n5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Curve/package.xml b/UIProject/assets/Curve/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/Button1.xml b/UIProject/assets/CutScene/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/CutScene.xml b/UIProject/assets/CutScene/CutScene.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/Main.xml b/UIProject/assets/CutScene/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/ProgressBar5.xml b/UIProject/assets/CutScene/ProgressBar5.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/huawen1_png.png b/UIProject/assets/CutScene/huawen1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/huawen2_png.png b/UIProject/assets/CutScene/huawen2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/loading.png.jpg b/UIProject/assets/CutScene/loading.png.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/package.xml b/UIProject/assets/CutScene/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/CutScene/pet.jta b/UIProject/assets/CutScene/pet.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/0(2)5_png.png b/UIProject/assets/EmitNumbers/0(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/0(4)_png.png b/UIProject/assets/EmitNumbers/0(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/1(2)5_png.png b/UIProject/assets/EmitNumbers/1(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/1(4)_png.png b/UIProject/assets/EmitNumbers/1(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/2(2)5_png.png b/UIProject/assets/EmitNumbers/2(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/2(4)_png.png b/UIProject/assets/EmitNumbers/2(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/3(2)5_png.png b/UIProject/assets/EmitNumbers/3(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/3(4)_png.png b/UIProject/assets/EmitNumbers/3(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/4(2)5_png.png b/UIProject/assets/EmitNumbers/4(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/4(4)_png.png b/UIProject/assets/EmitNumbers/4(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/5(2)5_png.png b/UIProject/assets/EmitNumbers/5(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/5(4)_png.png b/UIProject/assets/EmitNumbers/5(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/6(2)5_png.png b/UIProject/assets/EmitNumbers/6(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/6(4)_png.png b/UIProject/assets/EmitNumbers/6(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/7(2)5_png.png b/UIProject/assets/EmitNumbers/7(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/7(4)_png.png b/UIProject/assets/EmitNumbers/7(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/8(2)5_png.png b/UIProject/assets/EmitNumbers/8(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/8(4)_png.png b/UIProject/assets/EmitNumbers/8(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/9(2)5_png.png b/UIProject/assets/EmitNumbers/9(2)5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/9(4)_png.png b/UIProject/assets/EmitNumbers/9(4)_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/Main.xml b/UIProject/assets/EmitNumbers/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/critical.png b/UIProject/assets/EmitNumbers/critical.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/m1_png.png b/UIProject/assets/EmitNumbers/m1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/m2_png.png b/UIProject/assets/EmitNumbers/m2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/number1.fnt b/UIProject/assets/EmitNumbers/number1.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/number2.fnt b/UIProject/assets/EmitNumbers/number2.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/EmitNumbers/package.xml b/UIProject/assets/EmitNumbers/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/Button.xml b/UIProject/assets/Emoji/Button.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/Button2.xml b/UIProject/assets/Emoji/Button2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/EmojiSelectUI.xml b/UIProject/assets/Emoji/EmojiSelectUI.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/EmojiSelectUI_ios.xml b/UIProject/assets/Emoji/EmojiSelectUI_ios.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/Main.xml b/UIProject/assets/Emoji/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/ScrollBar_VT.xml b/UIProject/assets/Emoji/ScrollBar_VT.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/chatLeft.xml b/UIProject/assets/Emoji/chatLeft.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/chatRight.xml b/UIProject/assets/Emoji/chatRight.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/88.jta b/UIProject/assets/Emoji/emoji/88.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/am.jta b/UIProject/assets/Emoji/emoji/am.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/bs.jta b/UIProject/assets/Emoji/emoji/bs.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/bz.jta b/UIProject/assets/Emoji/emoji/bz.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/ch.jta b/UIProject/assets/Emoji/emoji/ch.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/cool.jta b/UIProject/assets/Emoji/emoji/cool.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/dhq.jta b/UIProject/assets/Emoji/emoji/dhq.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/dn.jta b/UIProject/assets/Emoji/emoji/dn.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/fd.jta b/UIProject/assets/Emoji/emoji/fd.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/gz.jta b/UIProject/assets/Emoji/emoji/gz.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/han.jta b/UIProject/assets/Emoji/emoji/han.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/hx.jta b/UIProject/assets/Emoji/emoji/hx.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/hxiao.jta b/UIProject/assets/Emoji/emoji/hxiao.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji/hxiu.jta b/UIProject/assets/Emoji/emoji/hxiu.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f600.png b/UIProject/assets/Emoji/emoji_ios/1f600.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f601.png b/UIProject/assets/Emoji/emoji_ios/1f601.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f602.png b/UIProject/assets/Emoji/emoji_ios/1f602.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f603.png b/UIProject/assets/Emoji/emoji_ios/1f603.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f604.png b/UIProject/assets/Emoji/emoji_ios/1f604.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f605.png b/UIProject/assets/Emoji/emoji_ios/1f605.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f606.png b/UIProject/assets/Emoji/emoji_ios/1f606.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f607.png b/UIProject/assets/Emoji/emoji_ios/1f607.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f608.png b/UIProject/assets/Emoji/emoji_ios/1f608.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f609.png b/UIProject/assets/Emoji/emoji_ios/1f609.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f610.png b/UIProject/assets/Emoji/emoji_ios/1f610.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f611.png b/UIProject/assets/Emoji/emoji_ios/1f611.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f612.png b/UIProject/assets/Emoji/emoji_ios/1f612.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f613.png b/UIProject/assets/Emoji/emoji_ios/1f613.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f614.png b/UIProject/assets/Emoji/emoji_ios/1f614.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f615.png b/UIProject/assets/Emoji/emoji_ios/1f615.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f616.png b/UIProject/assets/Emoji/emoji_ios/1f616.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f617.png b/UIProject/assets/Emoji/emoji_ios/1f617.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f618.png b/UIProject/assets/Emoji/emoji_ios/1f618.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f619.png b/UIProject/assets/Emoji/emoji_ios/1f619.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f620.png b/UIProject/assets/Emoji/emoji_ios/1f620.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f621.png b/UIProject/assets/Emoji/emoji_ios/1f621.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f622.png b/UIProject/assets/Emoji/emoji_ios/1f622.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f623.png b/UIProject/assets/Emoji/emoji_ios/1f623.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f624.png b/UIProject/assets/Emoji/emoji_ios/1f624.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f625.png b/UIProject/assets/Emoji/emoji_ios/1f625.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f626.png b/UIProject/assets/Emoji/emoji_ios/1f626.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f627.png b/UIProject/assets/Emoji/emoji_ios/1f627.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f628.png b/UIProject/assets/Emoji/emoji_ios/1f628.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f629.png b/UIProject/assets/Emoji/emoji_ios/1f629.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f630.png b/UIProject/assets/Emoji/emoji_ios/1f630.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f631.png b/UIProject/assets/Emoji/emoji_ios/1f631.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f632.png b/UIProject/assets/Emoji/emoji_ios/1f632.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f633.png b/UIProject/assets/Emoji/emoji_ios/1f633.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f634.png b/UIProject/assets/Emoji/emoji_ios/1f634.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f635.png b/UIProject/assets/Emoji/emoji_ios/1f635.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f636.png b/UIProject/assets/Emoji/emoji_ios/1f636.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/emoji_ios/1f637.png b/UIProject/assets/Emoji/emoji_ios/1f637.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/faceSub.xml b/UIProject/assets/Emoji/faceSub.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/0.png b/UIProject/assets/Emoji/images/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/1.png b/UIProject/assets/Emoji/images/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/2.png b/UIProject/assets/Emoji/images/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/3.png b/UIProject/assets/Emoji/images/3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/4.png b/UIProject/assets/Emoji/images/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/5.png b/UIProject/assets/Emoji/images/5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/6.png b/UIProject/assets/Emoji/images/6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/7.png b/UIProject/assets/Emoji/images/7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/8.png b/UIProject/assets/Emoji/images/8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/9.png b/UIProject/assets/Emoji/images/9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/r0.png b/UIProject/assets/Emoji/images/r0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/images/r1.png b/UIProject/assets/Emoji/images/r1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Emoji/package.xml b/UIProject/assets/Emoji/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/Main.xml b/UIProject/assets/Extension/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/0.png b/UIProject/assets/Extension/images/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/1.png b/UIProject/assets/Extension/images/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/2.png b/UIProject/assets/Extension/images/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/3.png b/UIProject/assets/Extension/images/3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/4.png b/UIProject/assets/Extension/images/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/6.png b/UIProject/assets/Extension/images/6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/7.png b/UIProject/assets/Extension/images/7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/8.png b/UIProject/assets/Extension/images/8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/images/9.png b/UIProject/assets/Extension/images/9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/mailItem.xml b/UIProject/assets/Extension/mailItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Extension/package.xml b/UIProject/assets/Extension/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/Button5.xml b/UIProject/assets/Filter/Button5.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/Main.xml b/UIProject/assets/Filter/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/Slider2.xml b/UIProject/assets/Filter/Slider2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/Slider2_grip.xml b/UIProject/assets/Filter/Slider2_grip.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/VIP_png.png b/UIProject/assets/Filter/VIP_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/back btn.png b/UIProject/assets/Filter/back btn.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/background.png b/UIProject/assets/Filter/background.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/full bar.png b/UIProject/assets/Filter/full bar.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/k18.png b/UIProject/assets/Filter/k18.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/package.xml b/UIProject/assets/Filter/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/pet.jta b/UIProject/assets/Filter/pet.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Filter/pic.png b/UIProject/assets/Filter/pic.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Gesture/Main.xml b/UIProject/assets/Gesture/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Gesture/package.xml b/UIProject/assets/Gesture/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/BagButton.xml b/UIProject/assets/Guide/BagButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/Button1.xml b/UIProject/assets/Guide/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/GuideLayer.xml b/UIProject/assets/Guide/GuideLayer.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/Main.xml b/UIProject/assets/Guide/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/btnimage.png b/UIProject/assets/Guide/btnimage.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/package.xml b/UIProject/assets/Guide/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/quan.jta b/UIProject/assets/Guide/quan.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Guide/rswcfhd.jta b/UIProject/assets/Guide/rswcfhd.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/0.png b/UIProject/assets/HeadBar/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/1.png b/UIProject/assets/HeadBar/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/HeadBar.xml b/UIProject/assets/HeadBar/HeadBar.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/Main.xml b/UIProject/assets/HeadBar/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/bloodbar.xml b/UIProject/assets/HeadBar/bloodbar.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/cool.jta b/UIProject/assets/HeadBar/cool.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/fighting.jta b/UIProject/assets/HeadBar/fighting.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/package.xml b/UIProject/assets/HeadBar/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HeadBar/task.png b/UIProject/assets/HeadBar/task.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/0.png b/UIProject/assets/HitTest/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/1.png b/UIProject/assets/HitTest/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/2.png b/UIProject/assets/HitTest/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/Main.xml b/UIProject/assets/HitTest/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/button1.xml b/UIProject/assets/HitTest/button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/button2.xml b/UIProject/assets/HitTest/button2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/button3.xml b/UIProject/assets/HitTest/button3.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/component1.xml b/UIProject/assets/HitTest/component1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/HitTest/package.xml b/UIProject/assets/HitTest/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Joystick/Main.xml b/UIProject/assets/Joystick/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Joystick/circle.xml b/UIProject/assets/Joystick/circle.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Joystick/images/0.png b/UIProject/assets/Joystick/images/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Joystick/images/1.png b/UIProject/assets/Joystick/images/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Joystick/package.xml b/UIProject/assets/Joystick/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/Main.xml b/UIProject/assets/LoopList/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/item.xml b/UIProject/assets/LoopList/item.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/n1.png b/UIProject/assets/LoopList/n1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/n2.png b/UIProject/assets/LoopList/n2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/n3.png b/UIProject/assets/LoopList/n3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/n4.png b/UIProject/assets/LoopList/n4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/n5.png b/UIProject/assets/LoopList/n5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/LoopList/package.xml b/UIProject/assets/LoopList/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/0.png b/UIProject/assets/ModalWaiting/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/02.png b/UIProject/assets/ModalWaiting/02.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/1.png b/UIProject/assets/ModalWaiting/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/2.png b/UIProject/assets/ModalWaiting/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/4.png b/UIProject/assets/ModalWaiting/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/5.png b/UIProject/assets/ModalWaiting/5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/Button1.xml b/UIProject/assets/ModalWaiting/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/CloseButton.xml b/UIProject/assets/ModalWaiting/CloseButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/GlobalModalWaiting.xml b/UIProject/assets/ModalWaiting/GlobalModalWaiting.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/Main.xml b/UIProject/assets/ModalWaiting/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/TestWin.xml b/UIProject/assets/ModalWaiting/TestWin.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/WindowFrame.xml b/UIProject/assets/ModalWaiting/WindowFrame.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/WindowModalWaiting.xml b/UIProject/assets/ModalWaiting/WindowModalWaiting.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/icon_zzz.png b/UIProject/assets/ModalWaiting/icon_zzz.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/package.xml b/UIProject/assets/ModalWaiting/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ModalWaiting/qtm011.jta b/UIProject/assets/ModalWaiting/qtm011.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Model/Main.xml b/UIProject/assets/Model/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Model/package.xml b/UIProject/assets/Model/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Model/pet.jta b/UIProject/assets/Model/pet.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Particles/CoolComponent.xml b/UIProject/assets/Particles/CoolComponent.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Particles/Main.xml b/UIProject/assets/Particles/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Particles/package.xml b/UIProject/assets/Particles/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Particles/pet.jta b/UIProject/assets/Particles/pet.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/0.png b/UIProject/assets/Perspective/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/1.png b/UIProject/assets/Perspective/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/12.png b/UIProject/assets/Perspective/12.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/2.png b/UIProject/assets/Perspective/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/22.png b/UIProject/assets/Perspective/22.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/3.png b/UIProject/assets/Perspective/3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/32.png b/UIProject/assets/Perspective/32.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/4.png b/UIProject/assets/Perspective/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/42.png b/UIProject/assets/Perspective/42.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/5.png b/UIProject/assets/Perspective/5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/6.png b/UIProject/assets/Perspective/6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/7.png b/UIProject/assets/Perspective/7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/8.png b/UIProject/assets/Perspective/8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/9.png b/UIProject/assets/Perspective/9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/Main.xml b/UIProject/assets/Perspective/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/Panel.xml b/UIProject/assets/Perspective/Panel.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/Panel2.xml b/UIProject/assets/Perspective/Panel2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/button1.xml b/UIProject/assets/Perspective/button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/mailItem.xml b/UIProject/assets/Perspective/mailItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/package.xml b/UIProject/assets/Perspective/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Perspective/pet.jta b/UIProject/assets/Perspective/pet.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/Button1.xml b/UIProject/assets/PullToRefresh/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/Button2.xml b/UIProject/assets/PullToRefresh/Button2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/Footer.xml b/UIProject/assets/PullToRefresh/Footer.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/Header.xml b/UIProject/assets/PullToRefresh/Header.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/Main.xml b/UIProject/assets/PullToRefresh/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/Seperator1.png b/UIProject/assets/PullToRefresh/Seperator1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/arrow.png b/UIProject/assets/PullToRefresh/arrow.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/item.xml b/UIProject/assets/PullToRefresh/item.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/logo.jpg b/UIProject/assets/PullToRefresh/logo.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/package.xml b/UIProject/assets/PullToRefresh/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/PullToRefresh/refresh.png b/UIProject/assets/PullToRefresh/refresh.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/Button1.xml b/UIProject/assets/RenderTexture/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/ButtonLeft.xml b/UIProject/assets/RenderTexture/ButtonLeft.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/ButtonRight.xml b/UIProject/assets/RenderTexture/ButtonRight.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/CloseButton.xml b/UIProject/assets/RenderTexture/CloseButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/Main.xml b/UIProject/assets/RenderTexture/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/TestWin.xml b/UIProject/assets/RenderTexture/TestWin.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/WindowFrame.xml b/UIProject/assets/RenderTexture/WindowFrame.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/0.png b/UIProject/assets/RenderTexture/images/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/10.png b/UIProject/assets/RenderTexture/images/10.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/11.png b/UIProject/assets/RenderTexture/images/11.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/12.png b/UIProject/assets/RenderTexture/images/12.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/13.png b/UIProject/assets/RenderTexture/images/13.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/4.png b/UIProject/assets/RenderTexture/images/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/5.png b/UIProject/assets/RenderTexture/images/5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/8.png b/UIProject/assets/RenderTexture/images/8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/images/9.png b/UIProject/assets/RenderTexture/images/9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/RenderTexture/package.xml b/UIProject/assets/RenderTexture/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/Box.xml b/UIProject/assets/ScrollPane/Box.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/Button1.xml b/UIProject/assets/ScrollPane/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/Button2.xml b/UIProject/assets/ScrollPane/Button2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/Main.xml b/UIProject/assets/ScrollPane/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/Seperator1.png b/UIProject/assets/ScrollPane/Seperator1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/item.xml b/UIProject/assets/ScrollPane/item.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/logo.jpg b/UIProject/assets/ScrollPane/logo.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/ScrollPane/package.xml b/UIProject/assets/ScrollPane/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/BOSS.xml b/UIProject/assets/Transition/BOSS.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/BOSS_SKILL.xml b/UIProject/assets/Transition/BOSS_SKILL.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/Button1.xml b/UIProject/assets/Transition/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/GoodHit.xml b/UIProject/assets/Transition/GoodHit.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/Main.xml b/UIProject/assets/Transition/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/PowerUp.xml b/UIProject/assets/Transition/PowerUp.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/TRAP.xml b/UIProject/assets/Transition/TRAP.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h0.png b/UIProject/assets/Transition/h0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h1.png b/UIProject/assets/Transition/h1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h2.png b/UIProject/assets/Transition/h2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h3.png b/UIProject/assets/Transition/h3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h4.png b/UIProject/assets/Transition/h4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h5.png b/UIProject/assets/Transition/h5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h6.png b/UIProject/assets/Transition/h6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h7.png b/UIProject/assets/Transition/h7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h8.png b/UIProject/assets/Transition/h8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/h9.png b/UIProject/assets/Transition/h9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0.png b/UIProject/assets/Transition/images/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0000_+.png b/UIProject/assets/Transition/images/0000_+.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0000_9_png.png b/UIProject/assets/Transition/images/0000_9_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0001_8_png.png b/UIProject/assets/Transition/images/0001_8_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0001_9.png b/UIProject/assets/Transition/images/0001_9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0002_7_png.png b/UIProject/assets/Transition/images/0002_7_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0002_8.png b/UIProject/assets/Transition/images/0002_8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0003_6_png.png b/UIProject/assets/Transition/images/0003_6_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0003_7.png b/UIProject/assets/Transition/images/0003_7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0004_5_png.png b/UIProject/assets/Transition/images/0004_5_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0004_6.png b/UIProject/assets/Transition/images/0004_6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0005_4_png.png b/UIProject/assets/Transition/images/0005_4_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0005_5.png b/UIProject/assets/Transition/images/0005_5.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0006_3_png.png b/UIProject/assets/Transition/images/0006_3_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0006_4.png b/UIProject/assets/Transition/images/0006_4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0007_2_png.png b/UIProject/assets/Transition/images/0007_2_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0007_3.png b/UIProject/assets/Transition/images/0007_3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0008_1_png.png b/UIProject/assets/Transition/images/0008_1_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0008_2.png b/UIProject/assets/Transition/images/0008_2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0009_0-_png.png b/UIProject/assets/Transition/images/0009_0-_png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0009_1.png b/UIProject/assets/Transition/images/0009_1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/0010_0.png b/UIProject/assets/Transition/images/0010_0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/1.png b/UIProject/assets/Transition/images/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/2.png b/UIProject/assets/Transition/images/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/3.png b/UIProject/assets/Transition/images/3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/4.png b/UIProject/assets/Transition/images/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/BUZZ4.wav b/UIProject/assets/Transition/images/BUZZ4.wav old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/U1UIT17.jta b/UIProject/assets/Transition/images/U1UIT17.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/bangjile.png b/UIProject/assets/Transition/images/bangjile.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/blood.png b/UIProject/assets/Transition/images/blood.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/power.png b/UIProject/assets/Transition/images/power.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/images/red.png b/UIProject/assets/Transition/images/red.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/number1.fnt b/UIProject/assets/Transition/number1.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/number2.fnt b/UIProject/assets/Transition/number2.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/number3.fnt b/UIProject/assets/Transition/number3.fnt old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/package.xml b/UIProject/assets/Transition/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/Transition/r1.png b/UIProject/assets/Transition/r1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Icons/file.png b/UIProject/assets/TreeView/Icons/file.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Icons/folder_closed.png b/UIProject/assets/TreeView/Icons/folder_closed.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Icons/folder_opened.png b/UIProject/assets/TreeView/Icons/folder_opened.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Icons/heart.jta b/UIProject/assets/TreeView/Icons/heart.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Images/i3.png.png b/UIProject/assets/TreeView/Images/i3.png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Images/i4.png.png b/UIProject/assets/TreeView/Images/i4.png.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/Main.xml b/UIProject/assets/TreeView/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/TreeExpandButton.xml b/UIProject/assets/TreeView/TreeExpandButton.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/TreeItem.xml b/UIProject/assets/TreeView/TreeItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TreeView/package.xml b/UIProject/assets/TreeView/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnCard/CardComponent.xml b/UIProject/assets/TurnCard/CardComponent.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnCard/Main.xml b/UIProject/assets/TurnCard/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnCard/card_a.png b/UIProject/assets/TurnCard/card_a.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnCard/card_back.png b/UIProject/assets/TurnCard/card_back.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnCard/card_k.png b/UIProject/assets/TurnCard/card_k.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnCard/package.xml b/UIProject/assets/TurnCard/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/BackCover.xml b/UIProject/assets/TurnPage/BackCover.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Book.xml b/UIProject/assets/TurnPage/Book.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Button1.xml b/UIProject/assets/TurnPage/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Button3.xml b/UIProject/assets/TurnPage/Button3.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/CoverImage.png b/UIProject/assets/TurnPage/CoverImage.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/FrontCover.xml b/UIProject/assets/TurnPage/FrontCover.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Main.xml b/UIProject/assets/TurnPage/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Page.xml b/UIProject/assets/TurnPage/Page.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Pages.xml b/UIProject/assets/TurnPage/Pages.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/Paper.jpg b/UIProject/assets/TurnPage/Paper.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/haibian.jpg b/UIProject/assets/TurnPage/haibian.jpg old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/p3.png b/UIProject/assets/TurnPage/p3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/package.xml b/UIProject/assets/TurnPage/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/shadow_center.png b/UIProject/assets/TurnPage/shadow_center.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/shadow_soft.png b/UIProject/assets/TurnPage/shadow_soft.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/slide/Slider2.xml b/UIProject/assets/TurnPage/slide/Slider2.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/slide/Slider2_grip.xml b/UIProject/assets/TurnPage/slide/Slider2_grip.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/slide/back btn.png b/UIProject/assets/TurnPage/slide/back btn.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/slide/background.png b/UIProject/assets/TurnPage/slide/background.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TurnPage/slide/full bar.png b/UIProject/assets/TurnPage/slide/full bar.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/1f608.png b/UIProject/assets/TypingEffect/1f608.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/1f609.png b/UIProject/assets/TypingEffect/1f609.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/Main.xml b/UIProject/assets/TypingEffect/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/bz.jta b/UIProject/assets/TypingEffect/bz.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/ch.jta b/UIProject/assets/TypingEffect/ch.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/cool.jta b/UIProject/assets/TypingEffect/cool.jta old mode 100755 new mode 100644 diff --git a/UIProject/assets/TypingEffect/package.xml b/UIProject/assets/TypingEffect/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/0.png b/UIProject/assets/VirtualList/0.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/1.png b/UIProject/assets/VirtualList/1.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/2.png b/UIProject/assets/VirtualList/2.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/3.png b/UIProject/assets/VirtualList/3.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/4.png b/UIProject/assets/VirtualList/4.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/6.png b/UIProject/assets/VirtualList/6.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/7.png b/UIProject/assets/VirtualList/7.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/8.png b/UIProject/assets/VirtualList/8.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/9.png b/UIProject/assets/VirtualList/9.png old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/Button1.xml b/UIProject/assets/VirtualList/Button1.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/Main.xml b/UIProject/assets/VirtualList/Main.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/mailItem.xml b/UIProject/assets/VirtualList/mailItem.xml old mode 100755 new mode 100644 diff --git a/UIProject/assets/VirtualList/package.xml b/UIProject/assets/VirtualList/package.xml old mode 100755 new mode 100644 diff --git a/UIProject/settings/Adaptation.json b/UIProject/settings/Adaptation.json old mode 100755 new mode 100644 diff --git a/UIProject/settings/Common.json b/UIProject/settings/Common.json old mode 100755 new mode 100644 diff --git a/UIProject/settings/CustomProperties.json b/UIProject/settings/CustomProperties.json old mode 100755 new mode 100644 diff --git a/UIProject/settings/Publish.json b/UIProject/settings/Publish.json old mode 100755 new mode 100644 diff --git a/UserSettings/EditorUserSettings.asset b/UserSettings/EditorUserSettings.asset new file mode 100644 index 00000000..015740be --- /dev/null +++ b/UserSettings/EditorUserSettings.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!162 &1 +EditorUserSettings: + m_ObjectHideFlags: 0 + serializedVersion: 4 + m_ConfigSettings: + RecentlyUsedSceneGuid-0: + value: 55080056000c0a5a085e0e7241710e444e154c72787020612e7e4f30b1b16039 + flags: 0 + RecentlyUsedSceneGuid-1: + value: 570556555d030a0e095e087145215a444315492b7f2e7635787c4464b5e6626a + flags: 0 + RecentlyUsedSceneGuid-2: + value: 5a06520253075a0b5e58547714260b444f1641737d2d273178711c6ab0e3306d + flags: 0 + vcSharedLogLevel: + value: 0d5e400f0650 + flags: 0 + m_VCAutomaticAdd: 1 + m_VCDebugCom: 0 + m_VCDebugCmd: 0 + m_VCDebugOut: 0 + m_SemanticMergeMode: 2 + m_DesiredImportWorkerCount: 5 + m_StandbyImportWorkerCount: 2 + m_IdleImportWorkerShutdownDelay: 60000 + m_VCShowFailedCheckout: 1 + m_VCOverwriteFailedCheckoutAssets: 1 + m_VCProjectOverlayIcons: 1 + m_VCHierarchyOverlayIcons: 1 + m_VCOtherOverlayIcons: 1 + m_VCAllowAsyncUpdate: 1 + m_ArtifactGarbageCollection: 1 diff --git a/UserSettings/Layouts/default-2021.dwlt b/UserSettings/Layouts/default-2021.dwlt new file mode 100644 index 00000000..3106d774 --- /dev/null +++ b/UserSettings/Layouts/default-2021.dwlt @@ -0,0 +1,1315 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &1 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12004, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_PixelRect: + serializedVersion: 2 + x: 116 + y: 72 + width: 2428 + height: 1391 + m_ShowMode: 4 + m_Title: Console + m_RootView: {fileID: 8} + m_MinSize: {x: 875, y: 300} + m_MaxSize: {x: 10000, y: 10000} + m_Maximized: 0 +--- !u!114 &2 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: ConsoleWindow + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 954 + y: 0 + width: 901 + height: 671 + m_MinSize: {x: 102, y: 121} + m_MaxSize: {x: 4002, y: 4021} + m_ActualView: {fileID: 14} + m_Panes: + - {fileID: 14} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &3 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 7} + - {fileID: 2} + m_Position: + serializedVersion: 2 + x: 0 + y: 670 + width: 1855 + height: 671 + m_MinSize: {x: 200, y: 100} + m_MaxSize: {x: 16192, y: 8096} + vertical: 0 + controlID: 166 +--- !u!114 &4 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 11} + - {fileID: 5} + m_Position: + serializedVersion: 2 + x: 0 + y: 30 + width: 2428 + height: 1341 + m_MinSize: {x: 300, y: 200} + m_MaxSize: {x: 24288, y: 16192} + vertical: 0 + controlID: 164 +--- !u!114 &5 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: InspectorWindow + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 1855 + y: 0 + width: 573 + height: 1341 + m_MinSize: {x: 275, y: 50} + m_MaxSize: {x: 4000, y: 4000} + m_ActualView: {fileID: 21} + m_Panes: + - {fileID: 21} + - {fileID: 19} + - {fileID: 18} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &6 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 458 + height: 670 + m_MinSize: {x: 201, y: 221} + m_MaxSize: {x: 4001, y: 4021} + m_ActualView: {fileID: 22} + m_Panes: + - {fileID: 22} + m_Selected: 0 + m_LastSelected: 0 +--- !u!114 &7 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: ProjectBrowser + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 954 + height: 671 + m_MinSize: {x: 231, y: 271} + m_MaxSize: {x: 10001, y: 10021} + m_ActualView: {fileID: 20} + m_Panes: + - {fileID: 20} + m_Selected: 0 + m_LastSelected: 0 +--- !u!114 &8 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12008, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 9} + - {fileID: 4} + - {fileID: 10} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2428 + height: 1391 + m_MinSize: {x: 875, y: 300} + m_MaxSize: {x: 10000, y: 10000} + m_UseTopView: 1 + m_TopViewHeight: 30 + m_UseBottomView: 1 + m_BottomViewHeight: 20 +--- !u!114 &9 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12011, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2428 + height: 30 + m_MinSize: {x: 0, y: 0} + m_MaxSize: {x: 0, y: 0} + m_LastLoadedLayoutName: cc +--- !u!114 &10 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12042, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 1371 + width: 2428 + height: 20 + m_MinSize: {x: 0, y: 0} + m_MaxSize: {x: 0, y: 0} +--- !u!114 &11 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 12} + - {fileID: 3} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 1855 + height: 1341 + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 16192, y: 16192} + vertical: 1 + controlID: 165 +--- !u!114 &12 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 6} + - {fileID: 13} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 1855 + height: 670 + m_MinSize: {x: 200, y: 100} + m_MaxSize: {x: 16192, y: 8096} + vertical: 0 + controlID: 261 +--- !u!114 &13 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: GameView + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 458 + y: 0 + width: 1397 + height: 670 + m_MinSize: {x: 202, y: 221} + m_MaxSize: {x: 4002, y: 4021} + m_ActualView: {fileID: 24} + m_Panes: + - {fileID: 23} + - {fileID: 24} + - {fileID: 17} + - {fileID: 16} + - {fileID: 15} + m_Selected: 1 + m_LastSelected: 0 +--- !u!114 &14 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12003, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 100, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Console + m_Image: {fileID: -4327648978806127646, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 1070 + y: 772 + width: 899 + height: 650 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] +--- !u!114 &15 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 13854, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 310, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Project Settings + m_Image: {fileID: -5712115415447495865, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 656 + y: 83 + width: 1348.5 + height: 667.5 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_PosLeft: {x: 0, y: 0} + m_PosRight: {x: 0, y: 678} + m_Scope: 1 + m_SplitterFlex: 0.2 + m_SearchText: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: a73eced7 + m_LastClickedID: -674349401 + m_ExpandedIDs: 97ae729ea01a5fa6213269b253336be200000000067ab929c53aba5a + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 0} + m_SearchString: +--- !u!114 &16 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 13855, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 310, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Preferences + m_Image: {fileID: -5712115415447495865, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 656 + y: 83 + width: 1348.5 + height: 667.5 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_PosLeft: {x: 0, y: 0} + m_PosRight: {x: 0, y: 0} + m_Scope: 0 + m_SplitterFlex: 0.2 + m_SearchText: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: ce3102cc + m_LastClickedID: -872271410 + m_ExpandedIDs: 2956c29689577ec10000000001fecd11 + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 0} + m_SearchString: +--- !u!114 &17 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 13953, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 800, y: 250} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Package Manager + m_Image: {fileID: -2824328813065806953, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 482.6667 + y: 72.66667 + width: 1471.3334 + height: 749 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] +--- !u!114 &18 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -2667387946076563598, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 2006.5 + y: 83 + width: 552.5 + height: 1271 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_PreviewResizer: + m_CachedPref: -326 + m_ControlHash: 1412526313 + m_PrefName: Preview_InspectorPreview + m_LastInspectedObjectInstanceID: 29288 + m_LastVerticalScrollValue: 0 + m_GlobalObjectId: + m_InspectorMode: 0 + m_LockTracker: + m_IsLocked: 0 + m_PreviewWindow: {fileID: 0} +--- !u!114 &19 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -2667387946076563598, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 2006.5 + y: 83 + width: 552.5 + height: 1271 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_PreviewResizer: + m_CachedPref: -326 + m_ControlHash: 1412526313 + m_PrefName: Preview_InspectorPreview + m_LastInspectedObjectInstanceID: 29288 + m_LastVerticalScrollValue: 0 + m_GlobalObjectId: + m_InspectorMode: 0 + m_LockTracker: + m_IsLocked: 0 + m_PreviewWindow: {fileID: 0} +--- !u!114 &20 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12014, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 230, y: 250} + m_MaxSize: {x: 10000, y: 10000} + m_TitleContent: + m_Text: Project + m_Image: {fileID: -5467254957812901981, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 116 + y: 772 + width: 953 + height: 650 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_SearchFilter: + m_NameFilter: + m_ClassNames: [] + m_AssetLabels: [] + m_AssetBundleNames: [] + m_VersionControlStates: [] + m_SoftLockControlStates: [] + m_ReferencingInstanceIDs: + m_SceneHandles: + m_ShowAllHits: 0 + m_SkipHidden: 0 + m_SearchArea: 1 + m_Folders: + - Assets + m_Globs: [] + m_OriginalText: + m_ViewMode: 1 + m_StartGridSize: 16 + m_LastFolders: + - Assets/_TerrainAutoUpgrade + m_LastFoldersGridSize: 16 + m_LastProjectPath: /Users/chiuan/git/FairyGUI-unity + m_LockTracker: + m_IsLocked: 0 + m_FolderTreeState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: ca710000 + m_LastClickedID: 29130 + m_ExpandedIDs: 00000000ca710000d0710000ffffff7f + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 7} + m_SearchString: + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_AssetTreeState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: + m_LastClickedID: 0 + m_ExpandedIDs: 00000000ca710000ffffff7f + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 0} + m_SearchString: + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_ListAreaState: + m_SelectedInstanceIDs: + m_LastClickedInstanceID: 0 + m_HadKeyboardFocusLastEvent: 1 + m_ExpandedInstanceIDs: c6230000 + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 7} + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_NewAssetIndexInList: -1 + m_ScrollPosition: {x: 0, y: 0} + m_GridSize: 16 + m_SkipHiddenPackages: 0 + m_DirectoriesAreaWidth: 207 +--- !u!114 &21 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 50} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -2667387946076563598, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 1971 + y: 102 + width: 572 + height: 1320 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_PreviewResizer: + m_CachedPref: 160 + m_ControlHash: -371814159 + m_PrefName: Preview_InspectorPreview + m_LastInspectedObjectInstanceID: -1 + m_LastVerticalScrollValue: 0 + m_GlobalObjectId: + m_InspectorMode: 0 + m_LockTracker: + m_IsLocked: 0 + m_PreviewWindow: {fileID: 0} +--- !u!114 &22 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12061, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Hierarchy + m_Image: {fileID: 7966133145522015247, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 116 + y: 102 + width: 457 + height: 649 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_SceneHierarchy: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: + m_LastClickedID: 0 + m_ExpandedIDs: a8daffff14dbffff80dbffff76ddffff16fbffff + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 0} + m_SearchString: + m_ExpandedScenes: [] + m_CurrenRootInstanceID: 0 + m_LockTracker: + m_IsLocked: 0 + m_CurrentSortingName: TransformSorting + m_WindowGUID: 4c969a2b90040154d917609493e03593 +--- !u!114 &23 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12013, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Scene + m_Image: {fileID: 2593428753322112591, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 656 + y: 83 + width: 1348.5 + height: 667.5 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: + - dockPosition: 0 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: -176, y: -26} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 3 + id: Tool Settings + index: 0 + layout: 1 + - dockPosition: 0 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: -141, y: 149} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 1 + id: unity-grid-and-snap-toolbar + index: 1 + layout: 1 + - dockPosition: 1 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: unity-scene-view-toolbar + index: 0 + layout: 1 + - dockPosition: 1 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 1 + id: unity-search-toolbar + index: 1 + layout: 1 + - dockPosition: 0 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 0, y: 25.999998} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: unity-transform-toolbar + index: 2 + layout: 2 + - dockPosition: 0 + containerId: overlay-container--left + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 0, y: 197} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: unity-component-tools + index: 1 + layout: 2 + - dockPosition: 0 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 67.5, y: 86} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Orientation + index: 0 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Light Settings + index: 0 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Camera + index: 1 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Cloth Constraints + index: 2 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Cloth Collisions + index: 3 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Navmesh Display + index: 4 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Agent Display + index: 5 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Obstacle Display + index: 6 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Occlusion Culling + index: 7 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Physics Debugger + index: 8 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Scene Visibility + index: 9 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Particles + index: 10 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Tilemap + index: 11 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Tilemap Palette Helper + index: 12 + layout: 4 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Path + index: 0 + layout: 0 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Game Creator + index: 1 + layout: 0 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Open Tile Palette + index: 0 + layout: 0 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Tilemap Focus + index: 1 + layout: 0 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Animation Rigging + index: 4 + layout: 0 + m_WindowGUID: cc27987af1a868c49b0894db9c0f5429 + m_Gizmos: 0 + m_OverrideSceneCullingMask: 6917529027641081856 + m_SceneIsLit: 1 + m_SceneLighting: 1 + m_2DMode: 1 + m_isRotationLocked: 0 + m_PlayAudio: 0 + m_AudioPlay: 0 + m_Position: + m_Target: {x: 0.03499727, y: 0.06395378, z: -160.75026} + speed: 2 + m_Value: {x: 0.03499727, y: 0.06395378, z: -160.75026} + m_RenderMode: 0 + m_CameraMode: + drawMode: 0 + name: Shaded + section: Shading Mode + m_ValidateTrueMetals: 0 + m_DoValidateTrueMetals: 0 + m_ExposureSliderValue: 0 + m_SceneViewState: + m_AlwaysRefresh: 0 + showFog: 1 + showSkybox: 1 + showFlares: 1 + showImageEffects: 1 + showParticleSystems: 1 + showVisualEffectGraphs: 1 + m_FxEnabled: 1 + m_Grid: + xGrid: + m_Fade: + m_Target: 0 + speed: 2 + m_Value: 0 + m_Color: {r: 0.5, g: 0.5, b: 0.5, a: 0.4} + m_Pivot: {x: 0, y: 0, z: 0} + m_Size: {x: 0, y: 0} + yGrid: + m_Fade: + m_Target: 0 + speed: 2 + m_Value: 0 + m_Color: {r: 0.5, g: 0.5, b: 0.5, a: 0.4} + m_Pivot: {x: 0, y: 0, z: 0} + m_Size: {x: 1, y: 1} + zGrid: + m_Fade: + m_Target: 1 + speed: 2 + m_Value: 1 + m_Color: {r: 0.5, g: 0.5, b: 0.5, a: 0.4} + m_Pivot: {x: 0, y: 0, z: 0} + m_Size: {x: 1, y: 1} + m_ShowGrid: 1 + m_GridAxis: 1 + m_gridOpacity: 0.5 + m_Rotation: + m_Target: {x: 0, y: 0, z: 0, w: 1} + speed: 2 + m_Value: {x: 0, y: 0, z: 0, w: 1} + m_Size: + m_Target: 5.1368027 + speed: 2 + m_Value: 5.1368027 + m_Ortho: + m_Target: 1 + speed: 2 + m_Value: 1 + m_CameraSettings: + m_Speed: 1 + m_SpeedNormalized: 0.5 + m_SpeedMin: 0.001 + m_SpeedMax: 2 + m_EasingEnabled: 1 + m_EasingDuration: 0.4 + m_AccelerationEnabled: 1 + m_FieldOfViewHorizontalOrVertical: 60 + m_NearClip: 0.03 + m_FarClip: 10000 + m_DynamicClip: 1 + m_OcclusionCulling: 0 + m_LastSceneViewRotation: {x: -0.08717229, y: 0.89959055, z: -0.21045254, w: -0.3726226} + m_LastSceneViewOrtho: 0 + m_ReplacementShader: {fileID: 0} + m_ReplacementString: + m_SceneVisActive: 1 + m_LastLockedObject: {fileID: 0} + m_ViewIsLockedToObject: 0 +--- !u!114 &24 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12015, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Game + m_Image: {fileID: -6423792434712278376, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 574 + y: 102 + width: 1395 + height: 649 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_SerializedViewNames: [] + m_SerializedViewValues: [] + m_PlayModeViewName: GameView + m_ShowGizmos: 0 + m_TargetDisplay: 0 + m_ClearColor: {r: 0, g: 0, b: 0, a: 0} + m_TargetSize: {x: 1920, y: 1080} + m_TextureFilterMode: 0 + m_TextureHideFlags: 61 + m_RenderIMGUI: 1 + m_EnterPlayModeBehavior: 0 + m_UseMipMap: 0 + m_VSyncEnabled: 0 + m_Gizmos: 0 + m_Stats: 0 + m_SelectedSizes: 0b000000000000000000000000000000000000000000000000000000000000000000000000000000 + m_ZoomArea: + m_HRangeLocked: 0 + m_VRangeLocked: 0 + hZoomLockedByDefault: 0 + vZoomLockedByDefault: 0 + m_HBaseRangeMin: -960 + m_HBaseRangeMax: 960 + m_VBaseRangeMin: -540 + m_VBaseRangeMax: 540 + m_HAllowExceedBaseRangeMin: 1 + m_HAllowExceedBaseRangeMax: 1 + m_VAllowExceedBaseRangeMin: 1 + m_VAllowExceedBaseRangeMax: 1 + m_ScaleWithWindow: 0 + m_HSlider: 0 + m_VSlider: 0 + m_IgnoreScrollWheelUntilClicked: 0 + m_EnableMouseInput: 1 + m_EnableSliderZoomHorizontal: 0 + m_EnableSliderZoomVertical: 0 + m_UniformScale: 1 + m_UpDirection: 1 + m_DrawArea: + serializedVersion: 2 + x: 0 + y: 21 + width: 1395 + height: 628 + m_Scale: {x: 0.58148146, y: 0.58148146} + m_Translation: {x: 697.5, y: 314} + m_MarginLeft: 0 + m_MarginRight: 0 + m_MarginTop: 0 + m_MarginBottom: 0 + m_LastShownAreaInsideMargins: + serializedVersion: 2 + x: -1199.5223 + y: -540 + width: 2399.0447 + height: 1080 + m_MinimalGUI: 1 + m_defaultScale: 0.58148146 + m_LastWindowPixelSize: {x: 1395, y: 649} + m_ClearInEditMode: 1 + m_NoCameraWarning: 1 + m_LowResolutionForAspectRatios: 01000000000000000000 + m_XRRenderMode: 0 + m_RenderTexture: {fileID: 0} diff --git a/UserSettings/Layouts/default-2022.dwlt b/UserSettings/Layouts/default-2022.dwlt new file mode 100644 index 00000000..8ea7ac0f --- /dev/null +++ b/UserSettings/Layouts/default-2022.dwlt @@ -0,0 +1,1288 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &1 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12004, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_PixelRect: + serializedVersion: 2 + x: 0 + y: 42.666668 + width: 2560 + height: 1349.3334 + m_ShowMode: 4 + m_Title: Game + m_RootView: {fileID: 2} + m_MinSize: {x: 875, y: 300} + m_MaxSize: {x: 10000, y: 10000} + m_Maximized: 1 +--- !u!114 &2 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12008, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 3} + - {fileID: 5} + - {fileID: 4} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2560 + height: 1349.3334 + m_MinSize: {x: 875, y: 300} + m_MaxSize: {x: 10000, y: 10000} + m_UseTopView: 1 + m_TopViewHeight: 30 + m_UseBottomView: 1 + m_BottomViewHeight: 20 +--- !u!114 &3 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12011, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2560 + height: 30 + m_MinSize: {x: 0, y: 0} + m_MaxSize: {x: 0, y: 0} + m_LastLoadedLayoutName: cc-nor +--- !u!114 &4 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12042, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 1329.3334 + width: 2560 + height: 20 + m_MinSize: {x: 0, y: 0} + m_MaxSize: {x: 0, y: 0} +--- !u!114 &5 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 6} + m_Position: + serializedVersion: 2 + x: 0 + y: 30 + width: 2560 + height: 1299.3334 + m_MinSize: {x: 400, y: 200} + m_MaxSize: {x: 32384, y: 16192} + vertical: 1 + controlID: 359 +--- !u!114 &6 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 7} + - {fileID: 8} + - {fileID: 13} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 2560 + height: 1299.3334 + m_MinSize: {x: 400, y: 200} + m_MaxSize: {x: 32384, y: 16192} + vertical: 0 + controlID: 360 +--- !u!114 &7 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: ProjectBrowser + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 626.6667 + height: 1299.3334 + m_MinSize: {x: 231, y: 271} + m_MaxSize: {x: 10001, y: 10021} + m_ActualView: {fileID: 15} + m_Panes: + - {fileID: 15} + - {fileID: 16} + - {fileID: 17} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &8 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 9} + - {fileID: 12} + m_Position: + serializedVersion: 2 + x: 626.6667 + y: 0 + width: 1366.6667 + height: 1299.3334 + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 16192, y: 16192} + vertical: 1 + controlID: 329 +--- !u!114 &9 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12010, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: + - {fileID: 10} + - {fileID: 11} + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 1366.6667 + height: 568 + m_MinSize: {x: 200, y: 100} + m_MaxSize: {x: 16192, y: 8096} + vertical: 0 + controlID: 307 +--- !u!114 &10 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 0 + width: 368.66666 + height: 568 + m_MinSize: {x: 202, y: 221} + m_MaxSize: {x: 4002, y: 4021} + m_ActualView: {fileID: 18} + m_Panes: + - {fileID: 18} + m_Selected: 0 + m_LastSelected: 0 +--- !u!114 &11 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: GameView + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 368.66666 + y: 0 + width: 998.0001 + height: 568 + m_MinSize: {x: 202, y: 221} + m_MaxSize: {x: 4002, y: 4021} + m_ActualView: {fileID: 14} + m_Panes: + - {fileID: 14} + - {fileID: 19} + - {fileID: 20} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &12 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: SceneView + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 0 + y: 568 + width: 1366.6667 + height: 731.3334 + m_MinSize: {x: 202, y: 221} + m_MaxSize: {x: 4002, y: 4021} + m_ActualView: {fileID: 21} + m_Panes: + - {fileID: 21} + - {fileID: 22} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &13 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12006, guid: 0000000000000000e000000000000000, type: 0} + m_Name: InspectorWindow + m_EditorClassIdentifier: + m_Children: [] + m_Position: + serializedVersion: 2 + x: 1993.3334 + y: 0 + width: 566.6666 + height: 1299.3334 + m_MinSize: {x: 276, y: 71} + m_MaxSize: {x: 4001, y: 4021} + m_ActualView: {fileID: 23} + m_Panes: + - {fileID: 23} + - {fileID: 24} + m_Selected: 0 + m_LastSelected: 1 +--- !u!114 &14 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12015, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Game + m_Image: {fileID: 4621777727084837110, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 995.3334 + y: 72.66667 + width: 996.0001 + height: 547 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_SerializedViewNames: [] + m_SerializedViewValues: [] + m_PlayModeViewName: GameView + m_ShowGizmos: 0 + m_TargetDisplay: 0 + m_ClearColor: {r: 0, g: 0, b: 0, a: 0} + m_TargetSize: {x: 1920, y: 1080} + m_TextureFilterMode: 0 + m_TextureHideFlags: 61 + m_RenderIMGUI: 1 + m_EnterPlayModeBehavior: 0 + m_fullscreenMonitorIdx: 0 + m_playModeBehaviorIdx: 0 + m_UseMipMap: 0 + m_isFullscreen: 0 + m_suppressRenderingForFullscreen: 0 + m_VSyncEnabled: 0 + m_PlayFocused: 0 + m_Gizmos: 0 + m_Stats: 0 + m_SelectedSizes: 03000000000000000000000000000000000000000000000000000000000000000000000000000000 + m_ZoomArea: + m_HRangeLocked: 0 + m_VRangeLocked: 0 + hZoomLockedByDefault: 0 + vZoomLockedByDefault: 0 + m_HBaseRangeMin: -640 + m_HBaseRangeMax: 640 + m_VBaseRangeMin: -360 + m_VBaseRangeMax: 360 + m_HAllowExceedBaseRangeMin: 1 + m_HAllowExceedBaseRangeMax: 1 + m_VAllowExceedBaseRangeMin: 1 + m_VAllowExceedBaseRangeMax: 1 + m_ScaleWithWindow: 0 + m_HSlider: 0 + m_VSlider: 0 + m_IgnoreScrollWheelUntilClicked: 0 + m_EnableMouseInput: 1 + m_EnableSliderZoomHorizontal: 0 + m_EnableSliderZoomVertical: 0 + m_UniformScale: 1 + m_UpDirection: 1 + m_DrawArea: + serializedVersion: 2 + x: 0 + y: 21 + width: 996.0001 + height: 526 + m_Scale: {x: 0.73055553, y: 0.73055553} + m_Translation: {x: 498.00006, y: 263} + m_MarginLeft: 0 + m_MarginRight: 0 + m_MarginTop: 0 + m_MarginBottom: 0 + m_LastShownAreaInsideMargins: + serializedVersion: 2 + x: -681.6731 + y: -360 + width: 1363.3462 + height: 720 + m_MinimalGUI: 1 + m_defaultScale: 0.73055553 + m_LastWindowPixelSize: {x: 1494.0002, y: 820.5} + m_ClearInEditMode: 1 + m_NoCameraWarning: 1 + m_LowResolutionForAspectRatios: 01000000000000000000 + m_XRRenderMode: 0 + m_RenderTexture: {fileID: 0} + m_showToolbar: 1 + m_showToolbarOnFullscreen: 0 +--- !u!114 &15 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12014, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 230, y: 250} + m_MaxSize: {x: 10000, y: 10000} + m_TitleContent: + m_Text: Project + m_Image: {fileID: -5179483145760003458, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 0 + y: 72.66667 + width: 625.6667 + height: 1278.3334 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_SearchFilter: + m_NameFilter: + m_ClassNames: [] + m_AssetLabels: [] + m_AssetBundleNames: [] + m_VersionControlStates: [] + m_SoftLockControlStates: [] + m_ReferencingInstanceIDs: + m_SceneHandles: + m_ShowAllHits: 0 + m_SkipHidden: 1 + m_SearchArea: 1 + m_Folders: + - Assets + m_Globs: [] + m_OriginalText: + m_ViewMode: 1 + m_StartGridSize: 16 + m_LastFolders: + - Assets + m_LastFoldersGridSize: 16 + m_LastProjectPath: D:\git\FairyGUI-unity-chiuan + m_LockTracker: + m_IsLocked: 0 + m_FolderTreeState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: 9e4d0000 + m_LastClickedID: 19870 + m_ExpandedIDs: 000000009e4d0000a04d0000a24d0000a44d0000a64d000000ca9a3b + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 7} + m_SearchString: + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_AssetTreeState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: + m_LastClickedID: 0 + m_ExpandedIDs: 000000009e4d0000a04d0000a24d0000a44d0000a64d000000ca9a3b + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 0} + m_SearchString: + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_ListAreaState: + m_SelectedInstanceIDs: + m_LastClickedInstanceID: 0 + m_HadKeyboardFocusLastEvent: 1 + m_ExpandedInstanceIDs: c6230000d6cb0000f6780000fc780000fa780000f878000036d30000027b00000c7900006a7f0100f61b010016370000e6ef000074e20000000000003eca0000 + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 1 + m_ClientGUIView: {fileID: 12} + m_CreateAssetUtility: + m_EndAction: {fileID: 0} + m_InstanceID: 0 + m_Path: + m_Icon: {fileID: 0} + m_ResourceFile: + m_NewAssetIndexInList: -1 + m_ScrollPosition: {x: 0, y: 0} + m_GridSize: 16 + m_SkipHiddenPackages: 1 + m_DirectoriesAreaWidth: 254.66669 +--- !u!114 &16 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12003, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 100, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Console + m_Image: {fileID: -4950941429401207979, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 0 + y: 72.66667 + width: 625.6667 + height: 1278.3334 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] +--- !u!114 &17 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -440750813802333266, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 0 + y: 73.6 + width: 580.6 + height: 989.80005 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_PreviewResizer: + m_CachedPref: -306 + m_ControlHash: 1412526313 + m_PrefName: Preview_InspectorPreview + m_LastInspectedObjectInstanceID: -1 + m_LastVerticalScrollValue: 0 + m_GlobalObjectId: + m_InspectorMode: 0 + m_LockTracker: + m_IsLocked: 0 + m_PreviewWindow: {fileID: 0} +--- !u!114 &18 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12061, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Hierarchy + m_Image: {fileID: -3734745235275155857, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 626.6667 + y: 72.66667 + width: 366.66666 + height: 547 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_SceneHierarchy: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: + m_LastClickedID: 0 + m_ExpandedIDs: a887ffff7e91ffff8491ffff9491ffffb491ffff1aa7ffff20a7ffff30a7ffff50a7ffffb2d3ffffe8d3ffff90dbffffe8dcfffffcf7fffffcf8ffff0cf9ffff2cf9ffff9afaffff0efbffff + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 10} + m_SearchString: + m_ExpandedScenes: [] + m_CurrenRootInstanceID: 0 + m_LockTracker: + m_IsLocked: 0 + m_CurrentSortingName: TransformSorting + m_WindowGUID: 4c969a2b90040154d917609493e03593 +--- !u!114 &19 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 13854, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 310, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Project Settings + m_Image: {fileID: 866346219090771560, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 995.3334 + y: 72.66667 + width: 996.0001 + height: 547 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_PosLeft: {x: 0, y: 0} + m_PosRight: {x: 0, y: 783.6666} + m_Scope: 1 + m_SplitterFlex: 0.2 + m_SearchText: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: a73eced7 + m_LastClickedID: -674349401 + m_ExpandedIDs: 97ae729ea01a5fa6213269b253336be200000000067ab929c53aba5a + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 0} + m_SearchString: +--- !u!114 &20 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 13855, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 310, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Preferences + m_Image: {fileID: 866346219090771560, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 1389.9131 + y: 369.80872 + width: 976.36523 + height: 568.35657 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_PosLeft: {x: 0, y: 0} + m_PosRight: {x: 0, y: 0} + m_Scope: 0 + m_SplitterFlex: 0.2 + m_SearchText: + m_TreeViewState: + scrollPos: {x: 0, y: 0} + m_SelectedIDs: 71137e95 + m_LastClickedID: -1786899599 + m_ExpandedIDs: 2956c29689577ec10000000001fecd11 + m_RenameOverlay: + m_UserAcceptedRename: 0 + m_Name: + m_OriginalName: + m_EditFieldRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 0 + height: 0 + m_UserData: 0 + m_IsWaitingForDelay: 0 + m_IsRenaming: 0 + m_OriginalEventType: 11 + m_IsRenamingFilename: 0 + m_ClientGUIView: {fileID: 0} + m_SearchString: +--- !u!114 &21 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12013, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 200, y: 200} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Scene + m_Image: {fileID: 8634526014445323508, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 626.6667 + y: 640.6667 + width: 1364.6667 + height: 710.3334 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: + - dockPosition: 0 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: -174.66663, y: -26} + snapCorner: 3 + id: Tool Settings + index: 0 + layout: 1 + - dockPosition: 0 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: -141, y: 149} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 1 + id: unity-grid-and-snap-toolbar + index: 1 + layout: 1 + - dockPosition: 0 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 0, y: 25.599998} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: unity-transform-toolbar + index: 2 + layout: 2 + - dockPosition: 1 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: unity-scene-view-toolbar + index: 0 + layout: 1 + - dockPosition: 1 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 1 + id: unity-search-toolbar + index: 1 + layout: 1 + - dockPosition: 1 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Open Tile Palette + index: 2 + layout: 4 + - dockPosition: 1 + containerId: overlay-toolbar__top + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Tilemap Focus + index: 3 + layout: 4 + - dockPosition: 0 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 1 + snapOffset: {x: 67.5, y: 86} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Orientation + index: 0 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Light Settings + index: 0 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Camera + index: 1 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Cloth Constraints + index: 2 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Cloth Collisions + index: 3 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Navmesh Display + index: 4 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Agent Display + index: 5 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Obstacle Display + index: 6 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Occlusion Culling + index: 7 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Physics Debugger + index: 8 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Scene Visibility + index: 9 + layout: 4 + - dockPosition: 1 + containerId: overlay-container--right + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Particles + index: 10 + layout: 4 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Path + index: 0 + layout: 0 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Game Creator + index: 1 + layout: 0 + - dockPosition: 0 + containerId: overlay-toolbar__left + floating: 0 + collapsed: 0 + displayed: 0 + snapOffset: {x: 0, y: 0} + snapOffsetDelta: {x: 0, y: 0} + snapCorner: 0 + id: Scene View/Animation Rigging + index: 2 + layout: 0 + m_WindowGUID: cc27987af1a868c49b0894db9c0f5429 + m_Gizmos: 0 + m_OverrideSceneCullingMask: 6917529027641081856 + m_SceneIsLit: 1 + m_SceneLighting: 1 + m_2DMode: 1 + m_isRotationLocked: 0 + m_PlayAudio: 0 + m_AudioPlay: 0 + m_Position: + m_Target: {x: 17.176764, y: -8.333132, z: 0.24320231} + speed: 2 + m_Value: {x: 0, y: 0, z: 0} + m_RenderMode: 0 + m_CameraMode: + drawMode: 0 + name: Shaded + section: Shading Mode + m_ValidateTrueMetals: 0 + m_DoValidateTrueMetals: 0 + m_SceneViewState: + m_AlwaysRefresh: 0 + showFog: 1 + showSkybox: 1 + showFlares: 1 + showImageEffects: 1 + showParticleSystems: 1 + showVisualEffectGraphs: 1 + m_FxEnabled: 1 + m_Grid: + xGrid: + m_Fade: + m_Target: 0 + speed: 2 + m_Value: 0 + m_Color: {r: 0.5, g: 0.5, b: 0.5, a: 0.4} + m_Pivot: {x: 0, y: 0, z: 0} + m_Size: {x: 0, y: 0} + yGrid: + m_Fade: + m_Target: 0 + speed: 2 + m_Value: 0 + m_Color: {r: 0.5, g: 0.5, b: 0.5, a: 0.4} + m_Pivot: {x: 0, y: 0, z: 0} + m_Size: {x: 1, y: 1} + zGrid: + m_Fade: + m_Target: 0 + speed: 2 + m_Value: 0 + m_Color: {r: 0.5, g: 0.5, b: 0.5, a: 0.4} + m_Pivot: {x: 0, y: 0, z: 0} + m_Size: {x: 1, y: 1} + m_ShowGrid: 0 + m_GridAxis: 1 + m_gridOpacity: 0.5 + m_Rotation: + m_Target: {x: 0, y: 0, z: 0, w: 1} + speed: 2 + m_Value: {x: 0, y: 0, z: 0, w: 1} + m_Size: + m_Target: 15.577667 + speed: 2 + m_Value: 10 + m_Ortho: + m_Target: 1 + speed: 2 + m_Value: 1 + m_CameraSettings: + m_Speed: 1 + m_SpeedNormalized: 0.5 + m_SpeedMin: 0.001 + m_SpeedMax: 2 + m_EasingEnabled: 1 + m_EasingDuration: 0.4 + m_AccelerationEnabled: 1 + m_FieldOfViewHorizontalOrVertical: 60 + m_NearClip: 0.03 + m_FarClip: 10000 + m_DynamicClip: 1 + m_OcclusionCulling: 0 + m_LastSceneViewRotation: {x: -0.08717229, y: 0.89959055, z: -0.21045254, w: -0.3726226} + m_LastSceneViewOrtho: 0 + m_ReplacementShader: {fileID: 0} + m_ReplacementString: + m_SceneVisActive: 1 + m_LastLockedObject: {fileID: 0} + m_ViewIsLockedToObject: 0 +--- !u!114 &22 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 13953, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 800, y: 250} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Package Manager + m_Image: {fileID: 5076950121296946556, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 783.3334 + y: 642.6667 + width: 971.3333 + height: 655 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] +--- !u!114 &23 +MonoBehaviour: + m_ObjectHideFlags: 52 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 1 + m_Script: {fileID: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 50} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -440750813802333266, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 1993.3334 + y: 72.66667 + width: 565.6666 + height: 1278.3334 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_PreviewResizer: + m_CachedPref: -326 + m_ControlHash: -371814159 + m_PrefName: Preview_InspectorPreview + m_LastInspectedObjectInstanceID: -1 + m_LastVerticalScrollValue: 0 + m_GlobalObjectId: + m_InspectorMode: 0 + m_LockTracker: + m_IsLocked: 0 + m_PreviewWindow: {fileID: 0} +--- !u!114 &24 +MonoBehaviour: + m_ObjectHideFlags: 52 + 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: 12019, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_MinSize: {x: 275, y: 100} + m_MaxSize: {x: 4000, y: 4000} + m_TitleContent: + m_Text: Inspector + m_Image: {fileID: -440750813802333266, guid: 0000000000000000d000000000000000, + type: 0} + m_Tooltip: + m_Pos: + serializedVersion: 2 + x: 2143.722 + y: 369.80872 + width: 407.87827 + height: 1337.2783 + m_ViewDataDictionary: {fileID: 0} + m_OverlayCanvas: + m_LastAppliedPresetName: Default + m_SaveData: [] + m_ObjectsLockedBeforeSerialization: [] + m_InstanceIDsLockedBeforeSerialization: + m_PreviewResizer: + m_CachedPref: 326 + m_ControlHash: 1412526313 + m_PrefName: Preview_InspectorPreview + m_LastInspectedObjectInstanceID: -1 + m_LastVerticalScrollValue: 0 + m_GlobalObjectId: + m_InspectorMode: 0 + m_LockTracker: + m_IsLocked: 0 + m_PreviewWindow: {fileID: 0} diff --git a/UserSettings/Search.settings b/UserSettings/Search.settings new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/UserSettings/Search.settings @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 00000000..1d69a3e3 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "FairyGUI", + "displayName": "FairyGUI的代码库", + "version": "1.0.0", + "unity": "2022.1", + "author": "谷主", + "description": "ui工具", + "dependencies": {}, + "repository": { + "type": "git", + "url": "https://github.com/chiuan/FairyGUI-unity.git" + } +} \ No newline at end of file