Source code for simvx.core.nodes_2d.ysort
"""YSortContainer -- Sorts children by Y for top-down games."""
from .node2d import Node2D
def _local_y(c) -> float:
"""Child local Y for YSort ordering (non-spatial children rank 0)."""
return c.position.y if isinstance(c, Node2D) and hasattr(c.position, "y") else 0.0
[docs]
class YSortContainer(Node2D):
"""Sorts children by Y position each frame for top-down perspective.
Children are drawn in Y-ascending order (lower Y = drawn first = behind),
which creates a natural depth effect for top-down 2D games. The sort
only affects draw order; the children list itself is not mutated.
Uses dirty-flag optimization: O(n) comparison instead of O(n log n) sort
when no child Y values have changed.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._last_y_values: list[float] = []
self._sorted_cache: list = []
def _ordered_children(self):
"""Ordering KEY = child local ``position.y`` (self draws first).
All children (CanvasLayers included, matching today) draw after self in
Y-ascending order: lower Y = behind. The Y-value cache re-sorts only when
a child's Y or the child count changes (O(n) compare vs O(n log n) sort).
"""
children = list(self.children.safe_iter())
y_values = [_local_y(c) for c in children]
if y_values != self._last_y_values or len(children) != len(self._sorted_cache):
self._sorted_cache = sorted(children, key=_local_y)
self._last_y_values = y_values
return [], list(self._sorted_cache)