< Summary

Class:DCL.Helpers.Utils
Assembly:Utils
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/Helpers/Utils/Utils.cs
Covered lines:122
Uncovered lines:68
Coverable lines:190
Total lines:534
Line coverage:64.2% (122 of 190)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
EnsureResourcesMaterial(...)0%440100%
CleanMaterials(...)0%440100%
FloatArrayToV2List(...)0%220100%
ResetLocalTRS(...)0%110100%
SetToMaxStretch(...)0%110100%
SetToCentered(...)0%2100%
SetToBottomLeft(...)0%2100%
ForceUpdateLayout(...)0%440100%
ForceRebuildLayoutImmediate(...)0%660100%
ForceUpdateLayoutRoutine()0%440100%
InverseTransformChildTraversal[TComponent](...)0%550100%
ForwardTransformChildTraversal[TComponent](...)0%30500%
GetOrCreateComponent[T](...)0%220100%
FetchTexture(...)0%110100%
SafeFromJsonOverwrite(...)0%2100%
FromJsonWithNulls[T](...)0%110100%
SafeFromJson[T](...)0%4.434070%
AttachPlaceholderRendererGameObject(...)0%110100%
SafeDestroy(...)0%2.52050%
GridToWorldPosition(...)0%110100%
WorldToGridPosition(...)0%110100%
WorldToGridPositionUnclamped(...)0%110100%
AproxComparison(...)0%440100%
ParseJsonArray[T](...)0%110100%
Utils()0%110100%
LockedThisFrame()0%2100%
LockCursor()0%220100%
UnlockCursor()0%220100%
BrowserSetCursorState(...)0%12300%
DestroyAllChild(...)0%330100%
GetBottomLeftZoneArray(...)0%12300%
GetCenteredZoneArray(...)0%12300%
DrawRectGizmo(...)0%2100%
ToUpperFirst(...)0%6200%
Sanitize(...)0%770100%
CompareFloats(...)0%2100%
Deconstruct[T1, T2](...)0%110100%
SetLayerRecursively(...)0%330100%
ToVolumeCurve(...)0%2100%
ToAudioMixerGroupVolume(...)0%2100%

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        {
 89825            if (staticMaterials == null)
 26            {
 127                staticMaterials = new Dictionary<string, Material>();
 28            }
 29
 89830            if (!staticMaterials.ContainsKey(path))
 31            {
 432                Material material = Resources.Load(path) as Material;
 33
 434                if (material != null)
 35                {
 436                    staticMaterials.Add(path, material);
 37                }
 38
 439                return material;
 40            }
 41
 89442            return staticMaterials[path];
 43        }
 44
 45        public static void CleanMaterials(Renderer r)
 46        {
 12847            if (r != null)
 48            {
 51249                foreach (Material m in r.materials)
 50                {
 12851                    if (m != null)
 52                    {
 12853                        Material.Destroy(m);
 54                    }
 55                }
 56            }
 12857        }
 58
 59        public static Vector2[] FloatArrayToV2List(float[] uvs)
 60        {
 461            Vector2[] uvsResult = new Vector2[uvs.Length / 2];
 462            int uvsResultIndex = 0;
 63
 7264            for (int i = 0; i < uvs.Length;)
 65            {
 6466                Vector2 tmpUv = Vector2.zero;
 6467                tmpUv.x = uvs[i++];
 6468                tmpUv.y = uvs[i++];
 69
 6470                uvsResult[uvsResultIndex++] = tmpUv;
 71            }
 72
 473            return uvsResult;
 74        }
 75
 76        public static void ResetLocalTRS(this Transform t)
 77        {
 153278            t.localPosition = Vector3.zero;
 153279            t.localRotation = Quaternion.identity;
 153280            t.localScale = Vector3.one;
 153281        }
 82
 83        public static void SetToMaxStretch(this RectTransform t)
 84        {
 20085            t.anchorMin = Vector2.zero;
 20086            t.offsetMin = Vector2.zero;
 20087            t.anchorMax = Vector2.one;
 20088            t.offsetMax = Vector2.one;
 20089            t.sizeDelta = Vector2.zero;
 20090            t.anchoredPosition = Vector2.zero;
 20091        }
 92
 93        public static void SetToCentered(this RectTransform t)
 94        {
 095            t.anchorMin = Vector2.one * 0.5f;
 096            t.offsetMin = Vector2.one * 0.5f;
 097            t.anchorMax = Vector2.one * 0.5f;
 098            t.offsetMax = Vector2.one * 0.5f;
 099            t.sizeDelta = Vector2.one * 100;
 0100        }
 101
 102        public static void SetToBottomLeft(this RectTransform t)
 103        {
 0104            t.anchorMin = Vector2.zero;
 0105            t.offsetMin = Vector2.zero;
 0106            t.anchorMax = Vector2.zero;
 0107            t.offsetMax = Vector2.zero;
 0108            t.sizeDelta = Vector2.one * 100;
 0109        }
 110
 111        public static void ForceUpdateLayout(this RectTransform rt, bool delayed = true)
 112        {
 207113            if (!rt.gameObject.activeInHierarchy)
 12114                return;
 115
 195116            if (delayed)
 123117                CoroutineStarter.Start(ForceUpdateLayoutRoutine(rt));
 118            else
 119            {
 72120                Utils.InverseTransformChildTraversal<RectTransform>(
 1732121                    (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 122                    rt);
 123            }
 72124        }
 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        {
 4584132            if (rectTransformRoot == null)
 3133                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
 4581137            var layoutElements = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutElement), true).ToList();
 31621138            layoutElements.RemoveAll(e => (e is Behaviour && !((Behaviour) e).isActiveAndEnabled) || e is TextMeshProUGU
 21390139            foreach (var layoutElem in layoutElements)
 140            {
 6114141                (layoutElem as ILayoutElement).CalculateLayoutInputHorizontal();
 6114142                (layoutElem as ILayoutElement).CalculateLayoutInputVertical();
 143            }
 144
 4581145            var layoutControllers = rectTransformRoot.GetComponentsInChildren(typeof(ILayoutController), true).ToList();
 10097146            layoutControllers.RemoveAll(e => e is Behaviour && !((Behaviour) e).isActiveAndEnabled);
 14298147            foreach (var layoutCtrl in layoutControllers)
 148            {
 2568149                (layoutCtrl as ILayoutController).SetLayoutHorizontal();
 2568150                (layoutCtrl as ILayoutController).SetLayoutVertical();
 151            }
 4581152        }
 153
 154        private static IEnumerator ForceUpdateLayoutRoutine(RectTransform rt)
 155        {
 123156            yield return null;
 157
 123158            Utils.InverseTransformChildTraversal<RectTransform>(
 5866159                (x) => { Utils.ForceRebuildLayoutImmediate(x); },
 160                rt);
 123161        }
 162
 163        public static void InverseTransformChildTraversal<TComponent>(Action<TComponent> action, Transform startTransfor
 164            where TComponent : Component
 165        {
 7885166            if (startTransform == null)
 75167                return;
 168
 30362169            foreach (Transform t in startTransform)
 170            {
 7371171                InverseTransformChildTraversal(action, t);
 172            }
 173
 7810174            var component = startTransform.GetComponent<TComponent>();
 175
 7810176            if (component != null)
 177            {
 4695178                action.Invoke(component);
 179            }
 7810180        }
 181
 182        public static void ForwardTransformChildTraversal<TComponent>(Func<TComponent, bool> action, Transform startTran
 183            where TComponent : Component
 184        {
 0185            Assert.IsTrue(startTransform != null, "startTransform must not be null");
 186
 0187            var component = startTransform.GetComponent<TComponent>();
 188
 0189            if (component != null)
 190            {
 0191                if (!action.Invoke(component))
 0192                    return;
 193            }
 194
 0195            foreach (Transform t in startTransform)
 196            {
 0197                ForwardTransformChildTraversal(action, t);
 198            }
 0199        }
 200
 201        public static T GetOrCreateComponent<T>(this GameObject gameObject) where T : UnityEngine.Component
 202        {
 75203            T component = gameObject.GetComponent<T>();
 204
 75205            if (!component)
 206            {
 64207                return gameObject.AddComponent<T>();
 208            }
 209
 11210            return component;
 211        }
 212
 213        public static WebRequestAsyncOperation FetchTexture(string textureURL, bool isReadable, Action<Texture2D> OnSucc
 214        {
 215            //NOTE(Brian): This closure is called when the download is a success.
 216            void SuccessInternal(UnityWebRequest request)
 217            {
 0218                OnSuccess?.Invoke(DownloadHandlerTexture.GetContent(request));
 0219            }
 220
 49221            var asyncOp = DCL.Environment.i.platform.webRequest.GetTexture(
 222                url: textureURL,
 223                OnSuccess: SuccessInternal,
 224                OnFail: OnFail,
 225                isReadable: isReadable);
 226
 49227            return asyncOp;
 228        }
 229
 230        public static bool SafeFromJsonOverwrite(string json, object objectToOverwrite)
 231        {
 232            try
 233            {
 0234                JsonUtility.FromJsonOverwrite(json, objectToOverwrite);
 0235            }
 0236            catch (System.ArgumentException e)
 237            {
 0238                Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 0239                return false;
 240            }
 241
 0242            return true;
 0243        }
 244
 68245        public static T FromJsonWithNulls<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json
 246
 247        public static T SafeFromJson<T>(string json)
 248        {
 729249            ProfilingEvents.OnMessageDecodeStart?.Invoke("Misc");
 250
 729251            T returningValue = default(T);
 252
 729253            if (!string.IsNullOrEmpty(json))
 254            {
 255                try
 256                {
 728257                    returningValue = JsonUtility.FromJson<T>(json);
 728258                }
 0259                catch (System.ArgumentException e)
 260                {
 0261                    Debug.LogError("ArgumentException Fail!... Json = " + json + " " + e.ToString());
 0262                }
 263            }
 264
 729265            ProfilingEvents.OnMessageDecodeEnds?.Invoke("Misc");
 266
 729267            return returningValue;
 268        }
 269
 270        public static GameObject AttachPlaceholderRendererGameObject(UnityEngine.Transform targetTransform)
 271        {
 1272            var placeholderRenderer = GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<MeshRenderer>();
 273
 1274            placeholderRenderer.material = Resources.Load<Material>("Materials/AssetLoading");
 1275            placeholderRenderer.transform.SetParent(targetTransform);
 1276            placeholderRenderer.transform.localPosition = Vector3.zero;
 1277            placeholderRenderer.name = "PlaceholderRenderer";
 278
 1279            return placeholderRenderer.gameObject;
 280        }
 281
 282        public static void SafeDestroy(UnityEngine.Object obj)
 283        {
 284#if UNITY_EDITOR
 633285            if (Application.isPlaying)
 633286                UnityEngine.Object.Destroy(obj);
 287            else
 0288                UnityEngine.Object.DestroyImmediate(obj, false);
 289#else
 290                UnityEngine.Object.Destroy(obj);
 291#endif
 0292        }
 293
 294        /**
 295         * Transforms a grid position into a world-relative 3d position
 296         */
 297        public static Vector3 GridToWorldPosition(float xGridPosition, float yGridPosition)
 298        {
 1690299            return new Vector3(
 300                x: xGridPosition * ParcelSettings.PARCEL_SIZE,
 301                y: 0f,
 302                z: yGridPosition * ParcelSettings.PARCEL_SIZE
 303            );
 304        }
 305
 306        /**
 307         * Transforms a world position into a grid position
 308         */
 309        public static Vector2Int WorldToGridPosition(Vector3 worldPosition)
 310        {
 21531311            return new Vector2Int(
 312                (int) Mathf.Floor(worldPosition.x / ParcelSettings.PARCEL_SIZE),
 313                (int) Mathf.Floor(worldPosition.z / ParcelSettings.PARCEL_SIZE)
 314            );
 315        }
 316
 317        public static Vector2 WorldToGridPositionUnclamped(Vector3 worldPosition)
 318        {
 792319            return new Vector2(
 320                worldPosition.x / ParcelSettings.PARCEL_SIZE,
 321                worldPosition.z / ParcelSettings.PARCEL_SIZE
 322            );
 323        }
 324
 325        public static bool AproxComparison(this Color color1, Color color2, float tolerance = 0.01f) // tolerance of rou
 326        {
 3351327            if (Mathf.Abs(color1.r - color2.r) < tolerance
 328                && Mathf.Abs(color1.g - color2.g) < tolerance
 329                && Mathf.Abs(color1.b - color2.b) < tolerance)
 330            {
 328331                return true;
 332            }
 333
 3023334            return false;
 335        }
 336
 5337        public static T ParseJsonArray<T>(string jsonArray) where T : IEnumerable => DummyJsonUtilityFromArray<T>.GetFro
 338
 339        [Serializable]
 340        private class DummyJsonUtilityFromArray<T> where T : IEnumerable //UnityEngine.JsonUtility is really fast but ca
 341        {
 342            [SerializeField]
 343            private T value;
 344
 345            public static T GetFromJsonArray(string jsonArray)
 346            {
 347                string newJson = $"{{ \"value\": {jsonArray}}}";
 348                return JsonUtility.FromJson<Utils.DummyJsonUtilityFromArray<T>>(newJson).value;
 349            }
 350        }
 351
 1352        private static int lockedInFrame = -1;
 0353        public static bool LockedThisFrame() => lockedInFrame == Time.frameCount;
 354
 355        //NOTE(Brian): Made as an independent flag because the CI doesn't work well with the Cursor.lockState check.
 1356        public static bool isCursorLocked { get; private set; } = false;
 357
 358        public static void LockCursor()
 359        {
 360#if WEB_PLATFORM
 361            //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 362            //             behaviour using strategy pattern instead of this.
 363            if (isCursorLocked)
 364            {
 365                return;
 366            }
 367            if (requestedUnlock || requestedLock)
 368            {
 369                return;
 370            }
 371            requestedLock = true;
 372#else
 20373            isCursorLocked = true;
 20374            Cursor.visible = false;
 375#endif
 20376            Cursor.lockState = CursorLockMode.Locked;
 20377            lockedInFrame = Time.frameCount;
 378
 20379            EventSystem.current?.SetSelectedGameObject(null);
 20380        }
 381
 382        public static void UnlockCursor()
 383        {
 384#if WEB_PLATFORM
 385            //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 386            //             behaviour using strategy pattern instead of this.
 387            if (!isCursorLocked)
 388            {
 389                return;
 390            }
 391            if (requestedUnlock || requestedLock)
 392            {
 393                return;
 394            }
 395            requestedUnlock = true;
 396#else
 144397            isCursorLocked = false;
 144398            Cursor.visible = true;
 399#endif
 144400            Cursor.lockState = CursorLockMode.None;
 401
 144402            EventSystem.current?.SetSelectedGameObject(null);
 144403        }
 404
 405        #region BROWSER_ONLY
 406
 407        //TODO(Brian): Encapsulate all this mechanism to a new MouseLockController and branch
 408        //             behaviour using strategy pattern instead of this.
 1409        private static bool requestedUnlock = false;
 1410        private static bool requestedLock = false;
 411
 412        // NOTE: This should come from browser's pointerlockchange callback
 413        public static void BrowserSetCursorState(bool locked)
 414        {
 0415            if (!locked && !requestedUnlock)
 416            {
 0417                Cursor.lockState = CursorLockMode.None;
 418            }
 419
 0420            isCursorLocked = locked;
 0421            Cursor.visible = !locked;
 0422            requestedUnlock = false;
 0423            requestedLock = false;
 0424        }
 425
 426        #endregion
 427
 428        public static void DestroyAllChild(this Transform transform)
 429        {
 82430            foreach (Transform child in transform)
 431            {
 3432                UnityEngine.Object.Destroy(child.gameObject);
 433            }
 38434        }
 435
 436        public static List<Vector2Int> GetBottomLeftZoneArray(Vector2Int bottomLeftAnchor, Vector2Int size)
 437        {
 0438            List<Vector2Int> coords = new List<Vector2Int>();
 439
 0440            for (int x = bottomLeftAnchor.x; x < bottomLeftAnchor.x + size.x; x++)
 441            {
 0442                for (int y = bottomLeftAnchor.y; y < bottomLeftAnchor.y + size.y; y++)
 443                {
 0444                    coords.Add(new Vector2Int(x, y));
 445                }
 446            }
 447
 0448            return coords;
 449        }
 450
 451        public static List<Vector2Int> GetCenteredZoneArray(Vector2Int center, Vector2Int size)
 452        {
 0453            List<Vector2Int> coords = new List<Vector2Int>();
 454
 0455            for (int x = center.x - size.x; x < center.x + size.x; x++)
 456            {
 0457                for (int y = center.y - size.y; y < center.y + size.y; y++)
 458                {
 0459                    coords.Add(new Vector2Int(x, y));
 460                }
 461            }
 462
 0463            return coords;
 464        }
 465
 466        public static void DrawRectGizmo(Rect rect, Color color, float duration)
 467        {
 0468            Vector3 tl2 = new Vector3(rect.xMin, rect.yMax, 0);
 0469            Vector3 bl2 = new Vector3(rect.xMin, rect.yMin, 0);
 0470            Vector3 tr2 = new Vector3(rect.xMax, rect.yMax, 0);
 0471            Vector3 br2 = new Vector3(rect.xMax, rect.yMin, 0);
 472
 0473            Debug.DrawLine(tl2, bl2, color, duration);
 0474            Debug.DrawLine(tl2, tr2, color, duration);
 0475            Debug.DrawLine(bl2, br2, color, duration);
 0476            Debug.DrawLine(tr2, br2, color, duration);
 0477        }
 478
 479        public static string ToUpperFirst(this string value)
 480        {
 0481            if (!string.IsNullOrEmpty(value))
 482            {
 0483                var capital = char.ToUpper(value[0]);
 0484                value = capital + value.Substring(1);
 485            }
 486
 0487            return value;
 488        }
 489
 490        public static Vector3 Sanitize(Vector3 value)
 491        {
 268492            float x = float.IsInfinity(value.x) ? 0 : value.x;
 268493            float y = float.IsInfinity(value.y) ? 0 : value.y;
 268494            float z = float.IsInfinity(value.z) ? 0 : value.z;
 495
 268496            return new Vector3(x, y, z);
 497        }
 498
 0499        public static bool CompareFloats( float a, float b, float precision = 0.1f ) { return Mathf.Abs(a - b) < precisi
 500
 501        public static void Deconstruct<T1, T2>(this KeyValuePair<T1, T2> tuple, out T1 key, out T2 value)
 502        {
 15503            key = tuple.Key;
 15504            value = tuple.Value;
 15505        }
 506
 507        /// <summary>
 508        /// Set a layer to the given transform and its child
 509        /// </summary>
 510        /// <param name="transform"></param>
 511        public static void SetLayerRecursively(Transform transform, int layer)
 512        {
 882513            transform.gameObject.layer = layer;
 3476514            foreach (Transform child in transform)
 515            {
 856516                SetLayerRecursively(child, layer);
 517            }
 882518        }
 519
 520        /// <summary>
 521        /// Converts a linear float (between 0 and 1) into an exponential curve fitting for audio volume.
 522        /// </summary>
 523        /// <param name="volume">Linear volume float</param>
 524        /// <returns>Exponential volume curve float</returns>
 0525        public static float ToVolumeCurve(float volume) { return volume * (2f - volume); }
 526
 527        /// <summary>
 528        /// Takes a linear volume value between 0 and 1, converts to exponential curve and maps to a value fitting for a
 529        /// </summary>
 530        /// <param name="volume">Linear volume (0 to 1)</param>
 531        /// <returns>Value for audio mixer group volume</returns>
 0532        public static float ToAudioMixerGroupVolume(float volume) { return (ToVolumeCurve(volume) * 80f) - 80f; }
 533    }
 534}

Methods/Properties

EnsureResourcesMaterial(System.String)
CleanMaterials(UnityEngine.Renderer)
FloatArrayToV2List(System.Single[])
ResetLocalTRS(UnityEngine.Transform)
SetToMaxStretch(UnityEngine.RectTransform)
SetToCentered(UnityEngine.RectTransform)
SetToBottomLeft(UnityEngine.RectTransform)
ForceUpdateLayout(UnityEngine.RectTransform, System.Boolean)
ForceRebuildLayoutImmediate(UnityEngine.RectTransform)
ForceUpdateLayoutRoutine()
InverseTransformChildTraversal[TComponent](System.Action[TComponent], UnityEngine.Transform)
ForwardTransformChildTraversal[TComponent](System.Func[TComponent,Boolean], UnityEngine.Transform)
GetOrCreateComponent[T](UnityEngine.GameObject)
FetchTexture(System.String, System.Boolean, System.Action[Texture2D], System.Action[UnityWebRequest])
SafeFromJsonOverwrite(System.String, System.Object)
FromJsonWithNulls[T](System.String)
SafeFromJson[T](System.String)
AttachPlaceholderRendererGameObject(UnityEngine.Transform)
SafeDestroy(UnityEngine.Object)
GridToWorldPosition(System.Single, System.Single)
WorldToGridPosition(UnityEngine.Vector3)
WorldToGridPositionUnclamped(UnityEngine.Vector3)
AproxComparison(UnityEngine.Color, UnityEngine.Color, System.Single)
ParseJsonArray[T](System.String)
Utils()
LockedThisFrame()
isCursorLocked()
isCursorLocked(System.Boolean)
LockCursor()
UnlockCursor()
BrowserSetCursorState(System.Boolean)
DestroyAllChild(UnityEngine.Transform)
GetBottomLeftZoneArray(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
GetCenteredZoneArray(UnityEngine.Vector2Int, UnityEngine.Vector2Int)
DrawRectGizmo(UnityEngine.Rect, UnityEngine.Color, System.Single)
ToUpperFirst(System.String)
Sanitize(UnityEngine.Vector3)
CompareFloats(System.Single, System.Single, System.Single)
Deconstruct[T1, T2](System.Collections.Generic.KeyValuePair[T1,T2], , )
SetLayerRecursively(UnityEngine.Transform, System.Int32)
ToVolumeCurve(System.Single)
ToAudioMixerGroupVolume(System.Single)