Author Topic: UI2DSpriteTight (community script)  (Read 11396 times)

Wisteso

  • Full Member
  • ***
  • Thank You
  • -Given: 21
  • -Receive: 3
  • Posts: 103
    • View Profile
UI2DSpriteTight (community script)
« on: September 02, 2016, 03:43:01 PM »
See http://www.tasharen.com/forum/index.php?topic=14818.0 for background

Our game has been needing to use tightly packed sprites as much as possible to reduce fill rate and texture usage (Unity is very efficient if you let it use 'tight' packing).

The only downside was that NGUI did not support tight sprites due to most of the internals being based around quads. However, NGUI did not seem to care if the quads were rectangular; nor did it care if they were continuous quads or not. Just that the amount of vertices was a multiple of 4. Unity tightly packed sprites are more like traditional meshes. They are based on being multiples of 3 since they're based on triangles, not quads.

During the process of trying to convert NGUI to work with "multiple of three" meshes, I realized that I could instead just add an extra vertex to each triangle to make it technically a quad- even though the second triangle of the quad would be perceptually invisible. ArenMook confirmed my suspicion, that the few extra vertices shouldn't really cause any noticeable performance hit.

ArenMook, if you want to adopt this into NGUI, feel free to do so. If anyone finds concrete ways to improve the code, please reply to this thread. There may be a few minor bugs.

Note to users: Currently, "Type" is forced to "Simple" since the OnFill math for doing fancier types (Filled, etc) would be pretty complex and outside of my purview.

UI2DSpriteTight.cs (rev 5)
  1. using UnityEngine;
  2.  
  3. [ExecuteInEditMode]
  4. [AddComponentMenu("NGUI/UI/NGUI Unity2D Sprite (Tight)")]
  5. public class UI2DSpriteTight : UI2DSprite
  6. {
  7.     protected override void Awake()
  8.     {
  9.         base.Awake();
  10.  
  11.         if (sprite2D != null && (!sprite2D.packed || sprite2D.packingMode != SpritePackingMode.Tight))
  12.         {
  13.             Debug.LogWarning(GetType() + " should generally only be used on tightly packed sprites!");
  14.         }
  15.  
  16.         if (type != Type.Simple)
  17.         {
  18.             type = Type.Simple;
  19.  
  20.             Debug.LogWarning(GetType() + " does not support complex sprite types! Forcing simple type.");
  21.         }
  22.     }
  23.  
  24.     public override void OnFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color> cols)
  25.     {
  26.         var spr = sprite2D;
  27.         if (spr == null) return;
  28.  
  29.         var colFlat = drawingColor;
  30.         var sprUVs = spr.uv;
  31.         var sprVerts = spr.vertices;
  32.         var tris = spr.triangles;
  33.         var texRect = spr.rect;
  34.  
  35.         var flip = FlipScalar;
  36.         var size = new Vector2(mWidth, mHeight);
  37.         var scale = new Vector2(size.x / texRect.width * flip.x, size.y / texRect.height * flip.y) * spr.pixelsPerUnit;
  38.         var pivotOff = -size / 2F + Vector2.Scale(size, pivotOffset);
  39.  
  40.         if (FixedAspect) scale.x = scale.y = Mathf.Min(scale.x, scale.y);
  41.  
  42.         for (int i = 0; i < tris.Length; ++i)
  43.         {
  44.             var index = tris[i];
  45.             var vertBase = Vector2.Scale(sprVerts[index], scale);
  46.             var vert = vertBase - pivotOff;
  47.             var uv = sprUVs[index];
  48.             var col = mApplyGradient ? (Color.Lerp(mGradientBottom, mGradientTop, (vertBase.y + size.y * 0.5F) / size.y) * color).GammaToLinearSpace() : colFlat;
  49.  
  50.             verts.Add(vert);
  51.             uvs.Add(uv);
  52.             cols.Add(col);
  53.  
  54.             if (i % 3 == 0)
  55.             {
  56.                 verts.Add(vert);
  57.                 uvs.Add(uv);
  58.                 cols.Add(col);
  59.             }
  60.         }
  61.  
  62.         if (onPostFill != null)
  63.             onPostFill(this, verts.size, verts, uvs, cols);
  64.     }
  65.  
  66.     private Vector2 FlipScalar
  67.     {
  68.         get
  69.         {
  70.             switch (mFlip)
  71.             {
  72.                 case Flip.Horizontally: return new Vector2(-1F, 1F);
  73.                 case Flip.Vertically: return new Vector2(1F, -1F);
  74.                 case Flip.Both: return new Vector2(-1F, -1F);
  75.                 default: return Vector2.one;
  76.             }
  77.         }
  78.     }
  79.  
  80.     public override Type type
  81.     {
  82.         get
  83.         {
  84.             return Type.Simple;
  85.         }
  86.  
  87.         set
  88.         {
  89.             if (base.type != Type.Simple) base.type = Type.Simple;
  90.         }
  91.     }
  92.  
  93.     private bool? fixedAspect = null;
  94.     protected bool FixedAspect
  95.     {
  96.         get
  97.         {
  98.             if (fixedAspect == null)
  99.             {
  100.                 var valueField = GetType().BaseType.GetField("mFixedAspect", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  101.                 var value = valueField.GetValue(this) as bool?;
  102.                 fixedAspect = (value == null) ? false : value;
  103.             }
  104.  
  105.             return fixedAspect.Value;
  106.         }
  107.     }
  108.  
  109. #if UNITY_EDITOR
  110.     private Sprite lastSprite;
  111.     protected override void OnUpdate()
  112.     {
  113.         base.OnUpdate();
  114.  
  115.         if (mType != Type.Simple) mType = Type.Simple;
  116.  
  117.         if (Application.isPlaying && sprite2D != lastSprite)
  118.         {
  119.             lastSprite = sprite2D;
  120.  
  121.             OnInit();
  122.         }
  123.     }
  124. #endif
  125. }
  126.  

UI2DSpriteTightEditor.cs (rev 2)
  1. using UnityEditor;
  2. using UnityEngine;
  3. using UnityEngine.Sprites;
  4.  
  5. [CanEditMultipleObjects]
  6. [CustomEditor(typeof(UI2DSpriteTight), true)]
  7. public class UI2DSpriteTightEditor : UI2DSpriteEditor
  8. {
  9.     UI2DSpriteTight mySprite;
  10.  
  11.     protected override void OnEnable()
  12.     {
  13.         base.OnEnable();
  14.  
  15.         mySprite = target as UI2DSpriteTight;
  16.     }
  17.  
  18.     public override void OnPreviewGUI(Rect rect, GUIStyle background)
  19.     {
  20.         if (mySprite != null && mySprite.sprite2D != null)
  21.         {
  22.             Texture2D tex = mySprite.mainTexture as Texture2D;
  23.  
  24.             NGUIEditorTools.DrawSprite(tex, rect, mySprite.color, CalculateTextureRect(mySprite.sprite2D), mySprite.border);
  25.         }
  26.     }
  27.  
  28.     private static Rect CalculateTextureRect(Sprite spr)
  29.     {
  30.         int w = spr.texture.width, h = spr.texture.height;
  31.         var padding = DataUtility.GetPadding(spr); // (x=left, y=bottom, z=right, w=top)
  32.         var uv = DataUtility.GetOuterUV(spr);
  33.  
  34.         return new Rect(
  35.             new Vector2(w * uv.x - padding.x, h * uv.y - padding.y),
  36.             new Vector2(w * (uv.z - uv.x) + padding.x + padding.z, h * (uv.w - uv.y) + padding.y + padding.w)
  37.         );
  38.     }
  39. }
  40.  

Note to ArenMook: My call to OnInit() in OnUpdate() fixes a bug that affects the parent class (UI2DSprite) as well, so you may want to adopt it. It happens when changing mSprite directly (via inspector serialization) when the game is running. It manifests as totally wrong UV values but correct vertex geometry.
« Last Edit: September 07, 2016, 04:33:37 AM by Wisteso »

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: UI2DSpriteTight (community script)
« Reply #1 on: September 03, 2016, 02:22:55 AM »
The mSprite thing is intentional, it's not supposed to be visible to Unity, but Unity sees it anyway and exposes it even though it shouldn't. NGUI sets its values via properties, not fields -- so when animating, it's important to go through an intermediary script that would do just that. That's why there are scripts like AnimatedAlpha and AnimatedColor.

Anyway, thanks for sharing!

Wisteso

  • Full Member
  • ***
  • Thank You
  • -Given: 21
  • -Receive: 3
  • Posts: 103
    • View Profile
Re: UI2DSpriteTight (community script)
« Reply #2 on: September 03, 2016, 05:09:31 AM »
ArenMook, I created a quick demonstration video of the issue. I do think this is something you might want to address. When I said it affected mSprite, I meant via use of NGUI's provided UI2DSpriteEditor inspector script.

https://dl.dropboxusercontent.com/u/48790176/UI2DSprite_mSprite_bug.mp4