Skip to content

Commit

Permalink
Add complete hierarchy and basics example
Browse files Browse the repository at this point in the history
  • Loading branch information
BeanCheeseBurrito committed Aug 31, 2023
1 parent b30cb60 commit e742532
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/Flecs.NET.Examples/Cpp/Entities/Basics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,16 @@
alice.Remove<Walking>();

// Iterate all entities with Position
// ecs.each([](flecs::entity e, Position& p) {
// std::cout << e.name() << ": {" << p.x << ", " << p.y << "}" << "\n";
// });
using Filter filter = world.Filter(
filter: world.FilterBuilder().Term<Position>()
);

filter.Iter(it =>
{
Column<Position> p = it.Field<Position>(1);
foreach (int i in it)
Console.WriteLine($"{it.Entity(i).Name()}: ({p[i].X}, {p[i].Y})");
});

public struct Position
{
Expand All @@ -49,4 +56,10 @@ public struct Walking
{
}

// Output
// (10, 20)
// [Position, Walking, (Identifier,Name)]
// Alice: (10, 20)
// Bob: (20, 30)

#endif
68 changes: 68 additions & 0 deletions src/Flecs.NET.Examples/Cpp/Entities/Hierarchy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#if Cpp_Entities_Hierarchy

using Flecs.NET.Core;
using static Flecs.NET.Bindings.Native;

void IterateTree(Entity e, Position pParent = default)
{
// Print hierarchical name of entity & the entity type
Console.WriteLine($"{e.Path()} [{e.Types().Str()}]");

// Get entity position
ref readonly Position p = ref e.Get<Position>();

// Calculate actual position
Position pActual = new() { X = p.X + pParent.X, Y = p.Y + pParent.Y };
Console.WriteLine($"({pActual.X}, {pActual.Y})\n");

// Iterate children recursively
e.Children(child => IterateTree(child, pActual));
}

using World world = World.Create();

// Create a simple hierarchy.
// Hierarchies use ECS relationships and the builtin flecs::ChildOf relationship to
// create entities as children of other entities.

Entity sun = world.Entity("Sun")
.Add<Star>()
.Set(new Position { X = 1, Y = 1 });

world.Entity("Mercury")
.ChildOf(sun) // Shortcut for add(flecs::ChildOf, sun)
.Add<Planet>()
.Set(new Position { X = 1, Y = 1 });

world.Entity("Venus")
.ChildOf(sun)
.Add<Planet>()
.Set(new Position { X = 2, Y = 2 });

Entity earth = world.Entity("Earth")
.ChildOf(sun)
.Add<Planet>()
.Set(new Position { X = 3, Y = 3 });

Entity moon = world.Entity("Moon")
.ChildOf(earth)
.Add<Moon>()
.Set(new Position { X = 0.1, Y = 0.1 });

// Is the Moon a child of Earth?
Console.WriteLine($"Child of Earth? {moon.Has(EcsChildOf, earth)}\n");

// Do a depth-first walk of the tree
IterateTree(sun);

public struct Position
{
public double X { get; set; }
public double Y { get; set; }
}

public struct Star { }
public struct Planet { }
public struct Moon { }

#endif

0 comments on commit e742532

Please sign in to comment.