override order of items drawn within the same z index

Godot Version

4.2

Question

An extension of this question,

I tried creating the custom property called depth similar to y sort where the higher the depth value the more “in front” the image is drawn.

So far I’ve used GDExtension and followed how y sort collects children nodes & sorts the nodes as such:

void GDExample::sort_children_by_depth()
{
	// get top most node (sort_node) whose children are to be sorted
	GDExample *sort_node = this;
	GDExample *parent_node = (GDExample *)sort_node->get_parent();

	while (parent_node && parent_node->get_class() == this->get_class())
	{
		sort_node = parent_node;
		parent_node = (GDExample *)parent_node->get_parent();
	}


	// get children of `sort_node` from every level
	int children_count = 1; // 1 since including `sort_node`
	_collect_depth_children(sort_node, nullptr, children_count);
	GDExample **child_items = (GDExample **)alloca((children_count) * sizeof(GDExample *));
	child_items[0]=sort_node;


	// to store all children into child_items
	children_count = 1;
	_collect_depth_children(sort_node, child_items, children_count);


	// sort all nodes based on their depth
	SortArray<GDExample *, DepthSort> sorter;
	sorter.sort(child_items, children_count);


	// get the index of `sort_node`
	int sort_node_index=-1;
	for(int i=0; i<children_count;i++){
		if(child_items[i]==sort_node){
			sort_node_index=i;
			break;
		}
	}

    // >how do I replace the below segment by flattening the items into a single z index?
    //
	for(int i=0; i<children_count;i++) // assigning z index relative to `sort_node`
		child_items[i]->set_z_index(i - sort_node_index);
}

and this works by setting the z index as needed but I’m trying to “flatten” all the images into a single z index like in y sort, I’ve traced the “flattening” process to _attach_canvas_item_for_draw where I guess r_z_list and r_z_last_list handle the order of drawing items
within the same z index but I have no idea how to implement this in my own code.

so ultimately, how do I handle the order of items drawn within the same index? (or any other approach with similar effect?)


Update:
I tried using canvas_item_set_draw_index & set_as_top_level and seems to give the desired effect for sorting but now the children don’t follow the parent transform nor do visual properties such as modulate propagate down

for (int i = 0; i < children_count; i++){
	child_items[i]->set_as_top_level(true);
	RenderingServer::get_singleton()->canvas_item_set_draw_index(child_items[i]->get_canvas_item(), i - sort_node_index);
}