< Summary

Class:DCL.Helpers.UtilsDummyJsonUtilityFromArray[T]
Assembly:Utils
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/Utils/Utils.cs
Covered lines:2
Uncovered lines:0
Coverable lines:2
Total lines:578
Line coverage:100% (2 of 2)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
GetFromJsonArray(...)0%110100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/Utils/Utils.cs

#LineLine coverage
 1#if UNITY_WEBGL && !UNITY_EDITOR
 2#define WEB_PLATFORM
 3#endif
 4
 5using System;
 6using System.Collections;
 7using System.Collections.Generic;
 8using System.Linq;
 9using DCL.Configuration;
 10using TMPro;
 11using UnityEngine;
 12using UnityEngine.Assertions;
 13using UnityEngine.EventSystems;
 14using UnityEngine.Networking;
 15using UnityEngine.UI;
 16
 17namespace DCL.Helpers
 18{
 19    public static class Utils
 20    {
 21        public static Dictionary<string, Material> staticMaterials;
 22
 23        public static Material EnsureResourcesMaterial(string path)
 24        {
 25            if (staticMaterials == null)
 26            {
 27                staticMaterials = new Dictionary<string, Material>();
 28            }
 29
 30            if (!staticMaterials.ContainsKey(path))
 31            {
 32                Material material = Resources.Load(path) as Material;
 33
 34                if (material != null)
 35                {
 36                    staticMaterials.Add(path, material);
 37                }
 38
 39                return material;
 40            }
 41
 42            return staticMaterials[path];
 43        }
 44
 45        public static void CleanMaterials(Renderer r)
 46        {
 47            if (r != null)
 48            {
 49                foreach (Material m in r.materials)
 50                {
 51                    if (m != null)
 52                    {
 53                        Material.Destroy(m);
 54                    }
 55                }
 56            }
 57        }
 58
 59        public static Vector2[] FloatArrayToV2List(float[] uvs)
 60        {
 61            Vector2[] uvsResult = new Vector2[uvs.Length / 2];
 62            int uvsResultIndex = 0;
 63
 64            for (int i = 0; i < uvs.Length;)
 65            {
 66                Vector2 tmpUv = Vector2.zero;
 67                tmpUv.x = uvs[i++];
 68                tmpUv.y = uvs[i++];
 69
 70                uvsResult[uvsResultIndex++] = tmpUv;
 71            }
 72
 73            return uvsResult;
 74        }
 75
 76        public static void ResetLocalTRS(this Transform t)
 77        {
 78            t.localPosition = Vector3.zero;
 79            t.localRotation = Quaternion.identity;
 80            t.localScale = Vector3.one;
 81        }
 82
 83        public static void SetToMaxStretch(this RectTransform t)
 84        {
 85            t.anchorMin = Vector2.zero;
 86            t.offsetMin = Vector2.zero;
 87            t.anchorMax = Vector2.one;
 88            t.offsetMax = Vector2.one;
 89            t.sizeDelta = Vector2.zero;
 90            t.anchoredPosition = Vector2.zero;
 91        }
 92
 93        public static void SetToCentered(this RectTransform t)
 94        {
 95            t.anchorMin = Vector2.one * 0.5f;
 96            t.offsetMin = Vector2.one * 0.5f;
 97            t.anchorMax = Vector2.one * 0.5f;
 98            t.offsetMax = Vector2.one * 0.5f;
 99            t.sizeDelta = Vector2.one * 100;
 100        }
 101
 102        public static void SetToBottomLeft(this RectTransform t)
 103        {
 104            t.anchorMin = Vector2.zero;
 105            t.offsetMin = Vector2.zero;
 106            t.anchorMax = Vector2.zero;
 107            t.offsetMax = Vector2.zero;
 108            t.sizeDelta = Vector2.one * 100;
 109        }
 110
 111        public static void ForceUpdateLayout(this RectTransform rt, bool delayed = true)
 112        {
 113            if (!rt.gameObject.activeInHierarchy)
 114                return;
 115
 116            if (delayed)
 117                CoroutineStarter.Start(ForceUpdateLayoutRoutine(rt));
 118            else
 119            {
 120                Utils.InverseTransformChildTraversal<RectTransform>(
 121                    (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 122                    rt);
 123            }
 124        }
 125
 126        /// <summary>
 127        /// Reimplementation of the LayoutRebuilder.ForceRebuildLayoutImmediate() function (Unity UI API) for make it mo
 128        /// </summary>
 129        /// <param name="rectTransformRoot">Root from which to rebuild.</param>
 130        public static void ForceRebuildLayoutImmediate(RectTransform rectTransformRoot)
 131        {
 132            if (rectTransformRoot == null)
 133                return;
 134
 135            // NOTE(Santi): It seems to be very much cheaper to execute the next instructions manually than execute dire
 136            //              'LayoutRebuilder.ForceRebuildLayoutImmediate()', that theorically already contains these ins
 137            var layoutElements = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutElement), true).ToList();
 138            layoutElements.RemoveAll(e => (e is Behaviour && !((Behaviour) e).isActiveAndEnabled) || e is TextMeshProUGU
 139            foreach (var layoutElem in layoutElements)
 140            {
 141                (layoutElem as ILayoutElement).CalculateLayoutInputHorizontal();
 142                (layoutElem as ILayoutElement).CalculateLayoutInputVertical();
 143            }
 144
 145            var layoutControllers = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutController), true).ToList();
 146            layoutControllers.RemoveAll(e => e is Behaviour && !((Behaviour) e).isActiveAndEnabled);
 147            foreach (var layoutCtrl in layoutControllers)
 148            {
 149                (layoutCtrl as ILayoutController).SetLayoutHorizontal();
 150                (layoutCtrl as ILayoutController).SetLayoutVertical();
 151            }
 152        }
 153
 154        private static IEnumerator ForceUpdateLayoutRoutine(RectTransform rt)
 155        {
 156            yield return null;
 157
 158            Utils.InverseTransformChildTraversal<RectTransform>(
 159                (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 160                rt);
 161        }
 162
 163        public static void InverseTransformChildTraversal<TComponent>(Action<TComponent> action, Transform startTransfor
 164            where TComponent : Component
 165        {
 166            if (startTransform == null)
 167                return;
 168
 169            foreach (Transform t in startTransform)
 170            {
 171                InverseTransformChildTraversal(action, t);
 172            }
 173
 174            var component = startTransform.GetComponent<TComponent>();
 175
 176            if (component != null)
 177            {
 178                action.Invoke(component);
 179            }
 180        }
 181
 182        public static void ForwardTransformChildTraversal<TComponent>(Func<TComponent, bool> action, Transform startTran
 183            where TComponent : Component
 184        {
 185            Assert.IsTrue(startTransform != null, "startTransform must not be null");
 186
 187            var component = startTransform.GetComponent<TComponent>();
 188
 189            if (component != null)
 190            {
 191                if (!action.Invoke(component))
 192                    return;
 193            }
 194
 195            foreach (Transform t in startTransform)
 196            {
 197                ForwardTransformChildTraversal(action, t);
 198            }
 199        }
 200
 201        public static T GetOrCreateComponent<T>(this GameObject gameObject) where T : UnityEngine.Component
 202        {
 203            T component = gameObject.GetComponent<T>();
 204
 205            if (!component)
 206            {
 207                return gameObject.AddComponent<T>();
 208            }
 209
 210            return component;
 211        }
 212
 213        public static WebRequestAsyncOperation FetchAudioClip(string url, AudioType audioType, Action<AudioClip> OnSucce
 214        {
 215            //NOTE(Brian): This closure is called when the download is a success.
 216            Action<UnityWebRequest> OnSuccessInternal =
 217                (request) =>
 218                {
 219                    if (OnSuccess != null)
 220                    {
 221                        bool supported = true;
 222#if UNITY_EDITOR
 223                        supported = audioType != AudioType.MPEG;
 224#endif
 225                        AudioClip ac = null;
 226
 227                        if (supported)
 228                            ac = DownloadHandlerAudioClip.GetContent(request);
 229
 230                        OnSuccess.Invoke(ac);
 231                    }
 232                };
 233
 234            Action<UnityWebRequest> OnFailInternal =
 235                (request) =>
 236                {
 237                    if (OnFail != null)
 238                    {
 239                        OnFail.Invoke(request.error);
 240                    }
 241                };
 242
 243            return DCL.Environment.i.platform.webRequest.GetAudioClip(
 244                url: url,
 245                audioType: audioType,
 246                OnSuccess: OnSuccessInternal,
 247                OnFail: OnFailInternal);
 248        }
 249
 250        public static WebRequestAsyncOperation FetchTexture(string textureURL, Action<Texture2D> OnSuccess, Action<Unity
 251        {
 252            //NOTE(Brian): This closure is called when the download is a success.
 253            void SuccessInternal(UnityWebRequest request)
 254            {
 255                var texture = DownloadHandlerTexture.GetContent(request);
 256                OnSuccess?.Invoke(texture);
 257            }
 258
 259            return DCL.Environment.i.platform.webRequest.GetTexture(
 260                url: textureURL,
 261                OnSuccess: SuccessInternal,
 262                OnFail: OnFail);
 263        }
 264
 265        public static AudioType GetAudioTypeFromUrlName(string url)
 266        {
 267            if (string.IsNullOrEmpty(url))
 268            {
 269                Debug.LogError("GetAudioTypeFromUrlName >>> Null url!");
 270                return AudioType.UNKNOWN;
 271            }
 272
 273            string ext = url.Substring(url.Length - 3).ToLower();
 274
 275            switch (ext)
 276            {
 277                case "mp3":
 278                    return AudioType.MPEG;
 279                case "wav":
 280                    return AudioType.WAV;
 281                case "ogg":
 282                    return AudioType.OGGVORBIS;
 283                default:
 284                    return AudioType.UNKNOWN;
 285            }
 286        }
 287
 288        public static bool SafeFromJsonOverwrite(string json, object objectToOverwrite)
 289        {
 290            try
 291            {
 292                JsonUtility.FromJsonOverwrite(json, objectToOverwrite);
 293            }
 294            catch (System.ArgumentException e)
 295            {
 296                Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 297                return false;
 298            }
 299
 300            return true;
 301        }
 302
 303        public static T FromJsonWithNulls<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json
 304
 305        public static T SafeFromJson<T>(string json)
 306        {
 307            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 308
 309            T returningValue = default(T);
 310
 311            if (!string.IsNullOrEmpty(json))
 312            {
 313                try
 314                {
 315                    returningValue = JsonUtility.FromJson<T>(json);
 316                }
 317                catch (System.ArgumentException e)
 318                {
 319                    Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 320                }
 321            }
 322
 323            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 324
 325            return returningValue;
 326        }
 327
 328        public static GameObject AttachPlaceholderRendererGameObject(UnityEngine.Transform targetTransform)
 329        {
 330            var placeholderRenderer = GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<MeshRenderer>();
 331
 332            placeholderRenderer.material = Resources.Load<Material>("Materials/AssetLoading");
 333            placeholderRenderer.transform.SetParent(targetTransform);
 334            placeholderRenderer.transform.localPosition = Vector3.zero;
 335            placeholderRenderer.name = "PlaceholderRenderer";
 336
 337            return placeholderRenderer.gameObject;
 338        }
 339
 340        public static void SafeDestroy(UnityEngine.Object obj)
 341        {
 342#if UNITY_EDITOR
 343            if (Application.isPlaying)
 344                UnityEngine.Object.Destroy(obj);
 345            else
 346                UnityEngine.Object.DestroyImmediate(obj, false);
 347#else
 348                UnityEngine.Object.Destroy(obj);
 349#endif
 350        }
 351
 352        /**
 353         * Transforms a grid position into a world-relative 3d position
 354         */
 355        public static Vector3 GridToWorldPosition(float xGridPosition, float yGridPosition)
 356        {
 357            return new Vector3(
 358                x: xGridPosition * ParcelSettings.PARCEL_SIZE,
 359                y: 0f,
 360                z: yGridPosition * ParcelSettings.PARCEL_SIZE
 361            );
 362        }
 363
 364        /**
 365         * Transforms a world position into a grid position
 366         */
 367        public static Vector2Int WorldToGridPosition(Vector3 worldPosition)
 368        {
 369            return new Vector2Int(
 370                (int) Mathf.Floor(worldPosition.x / ParcelSettings.PARCEL_SIZE),
 371                (int) Mathf.Floor(worldPosition.z / ParcelSettings.PARCEL_SIZE)
 372            );
 373        }
 374
 375        public static Vector2 WorldToGridPositionUnclamped(Vector3 worldPosition)
 376        {
 377            return new Vector2(
 378                worldPosition.x / ParcelSettings.PARCEL_SIZE,
 379                worldPosition.z / ParcelSettings.PARCEL_SIZE
 380            );
 381        }
 382
 383        public static bool AproxComparison(this Color color1, Color color2, float tolerance = 0.01f) // tolerance of rou
 384        {
 385            if (Mathf.Abs(color1.r - color2.r) < tolerance
 386                && Mathf.Abs(color1.g - color2.g) < tolerance
 387                && Mathf.Abs(color1.b - color2.b) < tolerance)
 388            {
 389                return true;
 390            }
 391
 392            return false;
 393        }
 394
 395        public static T ParseJsonArray<T>(string jsonArray) where T : IEnumerable => DummyJsonUtilityFromArray<T>.GetFro
 396
 397        [Serializable]
 398        private class DummyJsonUtilityFromArray<T> where T : IEnumerable //UnityEngine.JsonUtility is really fast but ca
 399        {
 400            [SerializeField]
 401            private T value;
 402
 403            public static T GetFromJsonArray(string jsonArray)
 404            {
 4405                string newJson = $"{{ \"value\": {jsonArray}}}";
 4406                return JsonUtility.FromJson<Utils.DummyJsonUtilityFromArray<T>>(newJson).value;
 407            }
 408        }
 409
 410        private static int lockedInFrame = -1;
 411        public static bool LockedThisFrame() => lockedInFrame == Time.frameCount;
 412
 413        //NOTE(Brian): Made as an independent flag because the CI doesn't work well with the Cursor.lockState check.
 414        public static bool isCursorLocked { get; private set; } = false;
 415
 416        public static void LockCursor()
 417        {
 418#if WEB_PLATFORM
 419            //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 420            //             behaviour using strategy pattern instead of this.
 421            if (isCursorLocked)
 422            {
 423                return;
 424            }
 425            if (requestedUnlock || requestedLock)
 426            {
 427                return;
 428            }
 429            requestedLock = true;
 430#else
 431            isCursorLocked = true;
 432            Cursor.visible = false;
 433#endif
 434            Cursor.lockState = CursorLockMode.Locked;
 435            lockedInFrame = Time.frameCount;
 436
 437            EventSystem.current?.SetSelectedGameObject(null);
 438        }
 439
 440        public static void UnlockCursor()
 441        {
 442#if WEB_PLATFORM
 443            //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 444            //             behaviour using strategy pattern instead of this.
 445            if (!isCursorLocked)
 446            {
 447                return;
 448            }
 449            if (requestedUnlock || requestedLock)
 450            {
 451                return;
 452            }
 453            requestedUnlock = true;
 454#else
 455            isCursorLocked = false;
 456            Cursor.visible = true;
 457#endif
 458            Cursor.lockState = CursorLockMode.None;
 459
 460            EventSystem.current?.SetSelectedGameObject(null);
 461        }
 462
 463        #region BROWSER_ONLY
 464
 465        //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 466        //             behaviour using strategy pattern instead of this.
 467        private static bool requestedUnlock = false;
 468        private static bool requestedLock = false;
 469
 470        // NOTE: This should come from browser's pointerlockchange callback
 471        public static void BrowserSetCursorState(bool locked)
 472        {
 473            if (!locked && !requestedUnlock)
 474            {
 475                Cursor.lockState = CursorLockMode.None;
 476            }
 477
 478            isCursorLocked = locked;
 479            Cursor.visible = !locked;
 480            requestedUnlock = false;
 481            requestedLock = false;
 482        }
 483
 484        #endregion
 485
 486        public static void DestroyAllChild(this Transform transform)
 487        {
 488            foreach (Transform child in transform)
 489            {
 490                UnityEngine.Object.Destroy(child.gameObject);
 491            }
 492        }
 493
 494        public static List<Vector2Int> GetBottomLeftZoneArray(Vector2Int bottomLeftAnchor, Vector2Int size)
 495        {
 496            List<Vector2Int> coords = new List<Vector2Int>();
 497
 498            for (int x = bottomLeftAnchor.x; x < bottomLeftAnchor.x + size.x; x++)
 499            {
 500                for (int y = bottomLeftAnchor.y; y < bottomLeftAnchor.y + size.y; y++)
 501                {
 502                    coords.Add(new Vector2Int(x, y));
 503                }
 504            }
 505
 506            return coords;
 507        }
 508
 509        public static List<Vector2Int> GetCenteredZoneArray(Vector2Int center, Vector2Int size)
 510        {
 511            List<Vector2Int> coords = new List<Vector2Int>();
 512
 513            for (int x = center.x - size.x; x < center.x + size.x; x++)
 514            {
 515                for (int y = center.y - size.y; y < center.y + size.y; y++)
 516                {
 517                    coords.Add(new Vector2Int(x, y));
 518                }
 519            }
 520
 521            return coords;
 522        }
 523
 524        public static void DrawRectGizmo(Rect rect, Color color, float duration)
 525        {
 526            Vector3 tl2 = new Vector3(rect.xMin, rect.yMax, 0);
 527            Vector3 bl2 = new Vector3(rect.xMin, rect.yMin, 0);
 528            Vector3 tr2 = new Vector3(rect.xMax, rect.yMax, 0);
 529            Vector3 br2 = new Vector3(rect.xMax, rect.yMin, 0);
 530
 531            Debug.DrawLine(tl2, bl2, color, duration);
 532            Debug.DrawLine(tl2, tr2, color, duration);
 533            Debug.DrawLine(bl2, br2, color, duration);
 534            Debug.DrawLine(tr2, br2, color, duration);
 535        }
 536
 537        public static string ToUpperFirst(this string value)
 538        {
 539            if (!string.IsNullOrEmpty(value))
 540            {
 541                var capital = char.ToUpper(value[0]);
 542                value = capital + value.Substring(1);
 543            }
 544
 545            return value;
 546        }
 547
 548        public static Vector3 Sanitize(Vector3 value)
 549        {
 550            float x = float.IsInfinity(value.x) ? 0 : value.x;
 551            float y = float.IsInfinity(value.y) ? 0 : value.y;
 552            float z = float.IsInfinity(value.z) ? 0 : value.z;
 553
 554            return new Vector3(x, y, z);
 555        }
 556
 557        public static bool CompareFloats( float a, float b, float precision = 0.1f ) { return Mathf.Abs(a - b) < precisi
 558
 559        public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
 560        {
 561            key = tuple.Key;
 562            value = tuple.Value;
 563        }
 564
 565        /// <summary>
 566        /// Set a layer to the given transform and its child
 567        /// </summary>
 568        /// <param name="transform"></param>
 569        public static void SetLayerRecursively(Transform transform, int layer)
 570        {
 571            transform.gameObject.layer = layer;
 572            foreach (Transform child in transform)
 573            {
 574                SetLayerRecursively(child, layer);
 575            }
 576        }
 577    }
 578}

Methods/Properties

GetFromJsonArray(System.String)