Tanoda
SpriteUtil.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using UnityEngine;
10#if UNITY_EDITOR
11using UnityEditor;
12using UnityEditor.Sprites;
13#endif
14using System;
15using System.Collections.Generic;
16
18
19 public static class SpriteAtlasUtil {
20
21#if UNITY_EDITOR
22 public static void ShowInvalidSpriteWarning(IList<LeapGraphicFeatureBase> features) {
23 bool anyRectsInvalid = false;
24 foreach (var feature in features) {
25 var spriteFeature = feature as LeapSpriteFeature;
26 if (spriteFeature == null) continue;
27
28 foreach (var spriteData in spriteFeature.featureData) {
29 var sprite = spriteData.sprite;
30 if (sprite == null) continue;
31
32 Rect rect;
33 if (TryGetAtlasedRect(sprite, out rect)) {
34 if (rect.Area() == 0) {
35 anyRectsInvalid = true;
36 }
37 }
38 }
39 }
40
41 if (anyRectsInvalid) {
42 EditorGUILayout.HelpBox("Due to a Unity bug, packed sprites may be invalid until " +
43 "PlayMode has been entered at least once.", MessageType.Warning);
44 }
45 }
46#endif
47
48 public static bool TryGetAtlasedRect(Sprite sprite, out Rect rect) {
49 Vector2[] uvs;
50 if (!TryGetAtlasedUvs(sprite, out uvs)) {
51 rect = default(Rect);
52 return false;
53 }
54
55 float minX, minY, maxX, maxY;
56 minX = maxX = uvs[0].x;
57 minY = maxY = uvs[0].y;
58
59 for (int j = 1; j < uvs.Length; j++) {
60 minX = Mathf.Min(minX, uvs[j].x);
61 minY = Mathf.Min(minY, uvs[j].y);
62 maxX = Mathf.Max(maxX, uvs[j].x);
63 maxY = Mathf.Max(maxY, uvs[j].y);
64 }
65
66 rect = Rect.MinMaxRect(minX, minY, maxX, maxY);
67 return true;
68 }
69
70 public static bool TryGetAtlasedUvs(Sprite sprite, out Vector2[] uvs) {
71#if UNITY_EDITOR
72 if (!Application.isPlaying)
73 return tryGetAtlasedUvsEditor(sprite, out uvs);
74 else
75#endif
76 return tryGetAtlasedUvs(sprite, out uvs);
77 }
78
79 private static bool tryGetAtlasedUvs(Sprite sprite, out Vector2[] uvs) {
80 if (sprite.packed) {
81 uvs = sprite.uv;
82 return true;
83 } else {
84 uvs = null;
85 return false;
86 }
87 }
88
89#if UNITY_EDITOR
90 private static bool tryGetAtlasedUvsEditor(Sprite sprite, out Vector2[] uvs) {
91 try {
92 uvs = SpriteUtility.GetSpriteUVs(sprite, getAtlasData: true);
93 return true;
94 } catch (Exception) {
95 uvs = null;
96 return false;
97 }
98 }
99#endif
100 }
101}