Search Unity

Question Sorting problem in custom SpriteRenderSystem

Discussion in 'Entity Component System' started by Tony_Max, Dec 9, 2021.

  1. Tony_Max

    Tony_Max

    Joined:
    Feb 7, 2017
    Posts:
    353
    I use Graphics.DrawMeshInstancedProcedural and ComputeBuffers to draw sprites in my system with sets of properties. Each sprite is entity and belogns to some renderer (material + instanced properties set) as it is with MeshRenderer component.
    Render process goes in this steps:
    1. Gather sorting data
    2. Sorting
    3. Find batching groups
    4. Prepare shader properties data, reorder it with resulting sprites order, write to compute buffer
    5. Render all groups
    The problem:
    Unity's mono SpriteRenderer can work with SortingGroup component, which will force unity to render you sprites together depending on sorting order and position of parent sprite. For example it used to render 2D character with clothes or hairstyle.
    I want to replicate this feature, but i see no performant way to do this. Using DynamicBuffer which will link children sprite entities incompatible with my current approach. So i need to get parents and childrens as entities through same query.

    After sorting all nested sprites should go after parent no mater what position it has, so i need some smart way to do this.

    Naive approach is:
    1. Sort by parent
    2. Detect groups (parent + N children)
    3. Sort groups
    4. Restore source array in result order
    The problem of this approach is i can end up with tones of groups and only few of them will actually have children. + with N elements i'll have to sorts, one with N elements and one with N - ChildrenCount elements, which in some cases can be 2 * N. The best would be to have universal sorting algorithm.

    May be i've overthought this and it can be done with more simple way, or you just have idea/advice, or maybe i'am trying to find not existing silver bullet, please welcome to write any of your opinion :)
     
    Last edited: Jan 10, 2022