Skip to content

Commit

Permalink
fix: fix the sorting algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
mob-sakai committed Oct 28, 2020
1 parent f7eac0a commit 7acbf22
Showing 1 changed file with 44 additions and 22 deletions.
66 changes: 44 additions & 22 deletions Scripts/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,30 +190,52 @@ public static void SortForRendering(this List<ParticleSystem> self, Transform tr
self.Sort((a, b) =>
{
var tr = transform;
var ra = a.GetComponent<ParticleSystemRenderer>();
var rb = b.GetComponent<ParticleSystemRenderer>();

if (!Mathf.Approximately(ra.sortingFudge, rb.sortingFudge))
return ra.sortingFudge < rb.sortingFudge ? 1 : -1;

var pa = tr.InverseTransformPoint(a.transform.position).z;
var pb = tr.InverseTransformPoint(b.transform.position).z;

if (!Mathf.Approximately(pa, pb))
return pa < pb ? 1 : -1;

var aQueue = ra.sharedMaterial.renderQueue;
var bQueue = rb.sharedMaterial.renderQueue;
if (aQueue != bQueue)
return aQueue < bQueue ? 1 : -1;
var aRenderer = a.GetComponent<ParticleSystemRenderer>();
var bRenderer = b.GetComponent<ParticleSystemRenderer>();

// Render queue: ascending
var aMat = aRenderer.sharedMaterial;
var bMat = bRenderer.sharedMaterial;
if (aMat.renderQueue != bMat.renderQueue)
return aMat.renderQueue - bMat.renderQueue;

// Sorting layer: ascending
if (aRenderer.sortingLayerID != bRenderer.sortingLayerID)
return aRenderer.sortingLayerID - bRenderer.sortingLayerID;

// Sorting order: ascending
if (aRenderer.sortingOrder != bRenderer.sortingOrder)
return aRenderer.sortingOrder - bRenderer.sortingOrder;

// Z position & sortingFudge: descending
var aTransform = a.transform;
var bTransform = b.transform;
var aPos = tr.InverseTransformPoint(aTransform.position).z+ aRenderer.sortingFudge;
var bPos = tr.InverseTransformPoint(bTransform.position).z+ bRenderer.sortingFudge;
if (!Mathf.Approximately(aPos, bPos))
return (int)Mathf.Sign(bPos - aPos);

// Material instance ID: match
if (aMat.GetInstanceID() == bMat.GetInstanceID())
return 0;

// Transform: ascending
return TransformCompare(aTransform, bTransform);
});
}

var aHash = ra.sharedMaterial.GetHashCode();
var bHash = rb.sharedMaterial.GetHashCode();
if (aHash != bHash)
return aHash < bHash ? 1 : -1;
private static int TransformCompare(Transform a, Transform b)
{
while (true)
{
if (!a && !b) return 0;
if (!a) return -1;
if (!b) return 1;
if (a.parent == b.parent) return a.GetSiblingIndex() - b.GetSiblingIndex();

return 0;
});
a = a.parent;
b = b.parent;
}
}

public static long GetMaterialHash(this ParticleSystem self, bool trail)
Expand Down

0 comments on commit 7acbf22

Please sign in to comment.