Code archives/3D Graphics - Misc/NextChild(entity) function

This code has been declared by its author to be Public Domain code.

Download source code

NextChild(entity) function by Beaker
(Posted 23 years ago)
Deceptively simple and very useful non-recursive function that allows you to access all sub-entities of a model as though they were all on the same level of the hierarchy. Very useful for applying an effect to a model in its entirety.

[EDIT: This was a hard one to name, I did consider calling it NextEntity(). It basically returns the next entity - either the next sibling, first child or whatever until you have "seen" all entities in the model tree structure. ]

Example of use - show names of all entities
alien = LoadAnimMesh("alien.b3d")

ent = alien
While ent
	DebugLog EntityName(ent)
	ent = NextChild(ent)
Wend


Example 2 - change alpha of all entites
alien = LoadAnimMesh("alien.b3d")

ent = alien
While ent
	EntityAlpha ent,0.3
	ent = NextChild(ent)
Wend


Example 3 - count all tris in entity
alien = LoadAnimMesh("alien.b3d")

tris=0
ent = alien
While ent
	For i = 1 To CountSurfaces(ent)
		tris = tris + CountTriangles(GetSurface(ent, i))
	Next
	ent = NextChild(ent)
Wend
Debuglog tris


Function:
Function NextChild(ent)
	Local siblingcnt
	If CountChildren(ent)>0
		Return GetChild(ent,1)
	EndIf

	Local foundunused=False
	Local foundent = 0, parent,sibling
	While foundunused=False And ent<>0
		parent = GetParent(ent)
		If parent<>0
			If CountChildren(parent)>1
				If GetChild(parent,CountChildren(parent))<>ent
					For siblingcnt = 1 To CountChildren(parent)
						sibling = GetChild(parent,siblingcnt)
						If sibling=ent
							foundunused = True
							foundent = GetChild(parent,siblingcnt+1)
						EndIf
					Next
				EndIf
			EndIf
		EndIf
		ent = parent
	Wend
	Return foundent
End Function