[OOP] Mother-of-all-objects with children (TList)

BlitzMax Forums/BlitzMax Programming/[OOP] Mother-of-all-objects with children (TList)

Im using the same in my current OpenGL project.

Each Entity has a Parent and a Tlist of Children. That way you can find any entity through a child/parent relationship.

Keep in mind though that TList does not allow Indexing like an array. so doing World.Stuffs[1].Name. will not work.
You will have to create a GetChild() method that loops through the children and searches for the child you want by index or name.

Type World
  global Origin:Entity '// Pointer to the very topmost Entity

  Method New()
   if( Origin = null ) then  Origin = new Entity;
  End Method
End type


type Entity
  Field Parent:Entity;
  Field Children:TList;
  Field Name:String;

  Method New()
    Parent = null;
    Children = new TList;
    Name = "";
  End Method

  Function Create:Entity( parent:Entity = null, name:string = "" )
   Local e:Entity = new Entity

   if( parent <> null ) then
     e.SetParent( parent );
   end if
   e.Name = name;
   return e;
  End Function

  Method AddChild( child:Entity )
     If( Not Children.Contains( child ) ) Then
       child.Parent = Self;
       Children.AddFirst( child );
     End If
  End Method
  Method RemoveChild( child:Entity )
    If( Children.Contains( child ) ) Then
        child.Parent = null;
        Children.Remove( child );
    End If
  End Method
  Method IsChild( e:Entity )
    return Children.Contains( e );
  End Method
  Method SetParent( p:entity )
    '// we allready have a parent?
    if( Parent <> null) then
      Parent.RemoveChild( Self );
    end if

    Parent = p;
    Parent.AddChild( Self );
  End Method
  Method GetChild:Entity( index:int )
   if( index < 0 Or index >= Children.Count() ) then
     '// Index is out of Bounds.
     return null;
   end if
   return Entity( Children.ValueAtIndex( index ) );
  end method
  
end type

local world:World = new World;
local A:Entity = Entity.Create( world.Origin, "A" );
local B:Entity = Entity.Create( A, "B" );
Local C:Entity = Entity.Create( B, "C" );

'// print Enity C's name using parent/child relationship
Print( world.Origin.GetChild(0).GetChild(0).GetChild(0).Name );



That should give you an idea of how it works with TLists.
You can make it easier on yourself by using static Array's instead of TLists. It will make the Indexing easier, but extending the Array's when a new Child is added is a pain.
The above should suit you fine.

It is important that you dont assign a parent to an entity by simply doing :myEntity.Parent = OtherEntity;
If you do this, you will not have updated the parent's child lists. So make sure you use myEntity.SetParent( .. ) method to do so.

Note: there may be some small bugs, as I didnt test this code in Bmx. But the idea should work.