Giter VIP home page Giter VIP logo

morpeh's Introduction

Morpeh

Morpeh License Unity Version

🎲 ECS Framework for Unity Game Engine and .Net Platform

  • Simple Syntax.
  • Plug & Play Installation.
  • No code generation.
  • Structure-Based and Cache-Friendly.

📖 Table of Contents

🛸 Migration To New Version

English version: Migration Guide
Russian version: Гайд по миграции

📖 How To Install

Unity Engine

Minimal Unity Version is 2020.3.*
Require Git for installing package.
Require Tri Inspector for drawing in inspector.

Open Unity Package Manager and add Morpeh URL.

installation_step1.png
installation_step2.png

    ⭐ Master: https://github.com/scellecs/morpeh.git
    🚧 Stage: https://github.com/scellecs/morpeh.git#stage-2023.1
    🏷️ Tag: https://github.com/scellecs/morpeh.git#2023.1.0

.Net Platform

NuGet package URL: https://www.nuget.org/packages/Scellecs.Morpeh

📖 Introduction

📘 Base concept of ECS pattern

🔖 Entity

Container of components.
Has a set of methods for add, get, set, remove components.
It is reference type. Each entity is unique and not pooled. Only entity IDs are reused.

var entity = this.World.CreateEntity();

ref var addedHealthComponent  = ref entity.AddComponent<HealthComponent>();
ref var gottenHealthComponent = ref entity.GetComponent<HealthComponent>();

//if you remove last component on entity it will be destroyd on next world.Commit()
bool removed = entity.RemoveComponent<HealthComponent>();
entity.SetComponent(new HealthComponent {healthPoints = 100});

bool hasHealthComponent = entity.Has<HealthComponent>();

var newEntity = this.World.CreateEntity();
//after migration entity has no components, so it will be destroyd on next world.Commit()
entity.MigrateTo(newEntity);
//get string with entity ID
var debugString = entity.ToString();

🔖 Component

Components are types which include only data.
In Morpeh components are value types for performance purposes.

public struct HealthComponent : IComponent {
    public int healthPoints;
}

🔖 System

Types that process entities with a specific set of components.
Entities are selected using a filter.

All systems are represented by interfaces, but for convenience, there are ScriptableObject classes that make it easier to work with the inspector and Installer.
Such classes are the default tool, but you can write pure classes that implement the interface, but then you need to use the SystemsGroup API instead of the Installer.

public class HealthSystem : ISystem {
    public World World { get; set; }

    private Filter filter;

    public void OnAwake() {
        this.filter = this.World.Filter.With<HealthComponent>().Build();
    }

    public void OnUpdate(float deltaTime) {
        foreach (var entity in this.filter) {
            ref var healthComponent = ref entity.GetComponent<HealthComponent>();
            healthComponent.healthPoints += 1;
        }
    }

    public void Dispose() {
    }
}

All systems types:

  • IInitializer & Initializer - have only OnAwake and Dispose methods, convenient for executing startup logic
  • ISystem & UpdateSystem
  • IFixedSystem & FixedUpdateSystem
  • ILateSystem & LateUpdateSystem
  • ICleanupSystem & CleanupSystem

🔖 SystemsGroup

The type that contains the systems.
There is an Installer wrapper to work in the inspector, but if you want to control everything from code, you can use the systems group directly.

var newWorld = World.Create();

var newSystem = new HealthSystem();
var newInitializer = new HealthInitializer();

var systemsGroup = newWorld.CreateSystemsGroup();
systemsGroup.AddSystem(newSystem);
systemsGroup.AddInitializer(newInitializer);

//it is bad practice to turn systems off and on, but sometimes it is very necessary for debugging
systemsGroup.DisableSystem(newSystem);
systemsGroup.EnableSystem(newSystem);

systemsGroup.RemoveSystem(newSystem);
systemsGroup.RemoveInitializer(newInitializer);

newWorld.AddSystemsGroup(order: 0, systemsGroup);
newWorld.RemoveSystemsGroup(systemsGroup);

🔖 World

A type that contains entities, components stashes, systems and root filter.

var newWorld = World.Create();
//a variable that specifies whether the world should be updated automatically by the game engine.
//if set to false, then you can update the world manually.
//and can also be used for game pauses by changing the value of this variable.
newWorld.UpdateByUnity = true;

var newEntity = newWorld.CreateEntity();
newWorld.RemoveEntity(newEntity);

var systemsGroup = newWorld.CreateSystemsGroup();
systemsGroup.AddSystem(new HealthSystem());

newWorld.AddSystemsGroup(order: 0, systemsGroup);
newWorld.RemoveSystemsGroup(systemsGroup);

var filter = newWorld.Filter.With<HealthComponent>();

var healthCache = newWorld.GetStash<HealthComponent>();
var reflectionHealthCache = newWorld.GetReflectionStash(typeof(HealthComponent));

//manually world updates
newWorld.Update(Time.deltaTime);
newWorld.FixedUpdate(Time.fixedDeltaTime);
newWorld.LateUpdate(Time.deltaTime);
newWorld.CleanupUpdate(Time.deltaTime);

//apply all entity changes, filters will be updated.
//automatically invoked between systems
newWorld.Commit();

🔖 Filter

A type that contains entities constrained by conditions With and/or Without.
You can chain them in any order and quantity.
After compose all constrains you should call Build() method.

var filter = this.World.Filter.With<HealthComponent>()
                              .With<BooComponent>()
                              .Without<DummyComponent>()
                              .Build();

var firstEntityOrException = filter.First();
var firstEntityOrNull = filter.FirstOrDefault();

bool filterIsEmpty = filter.IsEmpty();
int filterLengthCalculatedOnCall = filter.GetLengthSlow();

🔖 Stash

A type that contains components.
You can get components and do other operations directly from the stash, because entity methods look up the stash each time on call.
However, such code is harder to read.

var healthStash = this.World.GetStash<HealthComponent>();
var entity = this.World.CreateEntity();

ref var addedHealthComponent  = ref healthStash.Add(entity);
ref var gottenHealthComponent = ref healthStash.Get(entity);

bool removed = healthStash.Remove(entity);

healthStash.Set(entity, new HealthComponent {healthPoints = 100});

bool hasHealthComponent = healthStash.Has(entity);

//delete all components that type from the world
healthStash.RemoveAll();

var newEntity = this.World.CreateEntity();
//transfers a component from one entity to another
healthStash.Migrate(from: entity, to: newEntity);

//not a generic variation of stash, so we can only do a limited set of operations
var reflectionHealthCache = newWorld.GetReflectionStash(typeof(HealthComponent));

//set default(HealthComponent) to entity
reflectionHealthCache.Set(entity);

bool removed = reflectionHealthCache.Remove(entity);

bool hasHealthComponent = reflectionHealthCache.Has(entity);

🅿️ Providers

Morpeh has providers for integration with the game engine.
This is a MonoBehaviour that allows you to create associations between GameObject and Entity.
For each ECS component, you can create a provider; it will allow you to change the component values directly through the inspector, use prefabs and use the workflow as close as possible to classic Unity development.

There are two main types of providers.

  • EntityProvider. It automatically creates an associated entity and allows you to access it.
  • MonoProvider. It is an inheritor of EntityProvider, and adds a component to the entity. Allows you to view and change component values directly in the playmode.

Note

Precisely because providers allow you to work with component values directly from the kernel, because components are not stored in the provider, it only renders them;
We use third-party solutions for rendering inspectors like Tri Inspector or Odin Inspector.
It's a difficult task to render the completely different data that you can put into a component.

All providers do their work in the OnEnable() and OnDisable() methods.
This allows you to emulate turning components on and off, although the kernel does not have such a feature.

All providers are synchronized with each other, so if you attach several providers to one GameObject, they will be associated with one entity, and will not create several different ones.

Providers can be inherited and logic can be overridden in the Initialize() and Deinitialize() methods.
We do not use methods like Awake(), Start() and others, because the provider needs to control the creation of the entity and synchronize with other providers.
At the time of calling Initialize(), the entity is definitely created.

API:

var entityProvider = someGameObject.GetComponent<EntityProvider>();
var entity = entityProvider.Entity;
var monoProvider = someGameObject.GetComponent<MyCustomMonoProvider>();

var entity = monoProvider.Entity;
//returns serialized data or direct value of component
ref var data = ref monoProvider.GetData();
ref var data = ref monoProvider.GetData(out bool existOnEntity);
ref var serializedData = ref monoProvider.GetSerializedData();

var stash = monoProvider.Stash;

We also have one additional provider that allows you to destroy an entity when a GameObject is removed from the scene.
You can simply hang it on a GameObject and no matter how many components are left on the entity, it will be deleted.
The provider is called RemoveEntityOnDestroy.


📘 Getting Started

Important

All GIFs are hidden under spoilers. Press ➤ to open it.

First step: install Tri Inspector.
Second step: install Morpeh.

After installation import ScriptTemplates and Restart Unity.

import_script_templates.gif

Let's create our first component and open it.

Right click in project window and select Create/ECS/Component.

create_component.gif

After it, you will see something like this.

using Scellecs.Morpeh;
using UnityEngine;
using Unity.IL2CPP.CompilerServices;

[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
[System.Serializable]
public struct HealthComponent : IComponent {
}

Note

Don't care about attributes.
Il2CppSetOption attribute can give you better performance.
It is important to understand that this disables any checks for null, so in the release build any calls to a null object will lead to a hard crash.
We recommend that in places where you are in doubt about using this attribute, you check everything for null yourself.

Add health points field to the component.

public struct HealthComponent : IComponent {
    public int healthPoints;
}

It is okay.

Now let's create first system.

Right click in project window and select Create/ECS/System.

create_system.gif

Note

Icon U means UpdateSystem. Also you can create FixedUpdateSystem and LateUpdateSystem, CleanupSystem.
They are similar as MonoBehaviour's Update, FixedUpdate, LateUpdate. CleanupSystem called the most recent in LateUpdate.

System looks like this.

using Scellecs.Morpeh.Systems;
using UnityEngine;
using Unity.IL2CPP.CompilerServices;

[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
[CreateAssetMenu(menuName = "ECS/Systems/" + nameof(HealthSystem))]
public sealed class HealthSystem : UpdateSystem {
    public override void OnAwake() {
    }

    public override void OnUpdate(float deltaTime) {
    }
}

We have to add a filter to find all the entities with HealthComponent.

public sealed class HealthSystem : UpdateSystem {
    private Filter filter;
    
    public override void OnAwake() {
        this.filter = this.World.Filter.With<HealthComponent>().Build();
    }

    public override void OnUpdate(float deltaTime) {
    }
}

Note

You can chain filters by two operators With<> and Without<>.
For example this.World.Filter.With<FooComponent>().With<BarComponent>().Without<BeeComponent>().Build();

The filters themselves are very lightweight and are free to create.
They do not store entities directly, so if you like, you can declare them directly in hot methods like OnUpdate().
For example:

public sealed class HealthSystem : UpdateSystem {
    
    public override void OnAwake() {
    }

    public override void OnUpdate(float deltaTime) {
        var filter = this.World.Filter.With<HealthComponent>().Build();
        
        //Or just iterate without variable
        foreach (var entity in this.World.Filter.With<HealthComponent>().Build()) {
        }
    }
}

But we will focus on the option with caching to a variable, because we believe that the filters declared in the header of system increase the readability of the code.

Now we can iterate all needed entities.

public sealed class HealthSystem : UpdateSystem {
    private Filter filter;
    
    public override void OnAwake() {
        this.filter = this.World.Filter.With<HealthComponent>().Build();
    }

    public override void OnUpdate(float deltaTime) {
        foreach (var entity in this.filter) {
            ref var healthComponent = ref entity.GetComponent<HealthComponent>();
            Debug.Log(healthComponent.healthPoints);
        }
    }
}

Important

Don't forget about ref operator.
Components are struct and if you want to change them directly, then you must use reference operator.

For high performance, you can use stash directly.
No need to do GetComponent from entity every time, which trying to find suitable stash.
However, we use such code only in very hot areas, because it is quite difficult to read it.

public sealed class HealthSystem : UpdateSystem {
    private Filter filter;
    private Stash<HealthComponent> healthStash;
    
    public override void OnAwake() {
        this.filter = this.World.Filter.With<HealthComponent>().Build();
        this.healthStash = this.World.GetStash<HealthComponent>();
    }

    public override void OnUpdate(float deltaTime) {
        foreach (var entity in this.filter) {
            ref var healthComponent = ref healthStash.Get(entity);
            Debug.Log(healthComponent.healthPoints);
        }
    }
}

We will focus on a simplified version, because even in this version entity.GetComponent is very fast.

Let's create ScriptableObject for HealthSystem.
This will allow the system to have its inspector and we can refer to it in the scene.

Right click in project window and select Create/ECS/Systems/HealthSystem.

create_system_scriptableobject.gif

Next step: create Installer on the scene.
This will help us choose which systems should work and in which order.

Right click in hierarchy window and select ECS/Installer.

create_installer.gif

Add system to the installer and run project.

add_system_to_installer.gif

Nothing happened because we did not create our entities.
I will show the creation of entities directly related to GameObject, because to create them from the code it is enough to write world.CreateEntity().
To do this, we need a provider that associates GameObject with an entity.

Create a new provider.

Right click in project window and select Create/ECS/Provider.

create_provider.gif

using Scellecs.Morpeh.Providers;
using Unity.IL2CPP.CompilerServices;

[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public sealed class HealthProvider : MonoProvider<{YOUR_COMPONENT}> {
}

We need to specify a component for the provider.

public sealed class HealthProvider : MonoProvider<HealthComponent> {
}
Create new GameObject and add HealthProvider.

add_provider.gif

Now press the play button, and you will see Debug.Log with healthPoints.
Nice!


📖 Advanced

🧩 Filter Extensions

Filter extensions required for easy reuse of filter queries.
Let's look at an example:

We need to implement the IFilterExtension interface and the type must be a struct.

public struct SomeExtension : IFilterExtension {
    public FilterBuilder Extend(FilterBuilder rootFilter) => rootFilter.With<Translation>().With<Rotation>();
}

The next step is to call the Extend method in any order when requesting a filter.
The Extend method continues query.

private Filter filter;

public void OnAwake() {
    this.filter = this.World.Filter.With<TestA>()
                                   .Extend<SomeExtension>()
                                   .With<TestC>()
                                   .Build();
}

🔍 Aspects

An aspect is an object-like wrapper that you can use to group together a subset of an entity's components into a single C# struct. Aspects are useful for organizing component code and simplifying queries in your systems.

For example, the Transform groups together the individual position, rotation, and scale of components and enables you to access these components from a query that includes the Transform. You can also define your own aspects with the IAspect interface.

Our components:

    public struct Translation : IComponent {
        public float x;
        public float y;
        public float z;
    }
    
    public struct Rotation : IComponent {
        public float x;
        public float y;
        public float z;
        public float w;
    }

    public struct Scale : IComponent {
        public float x;
        public float y;
        public float z;
    }

Let's group them in aspect.
Simple entity version:

public struct Transform : IAspect {
    //Set on each call of AspectFactory.Get(Entity entity)
    public Entity Entity { get; set;}
    
    public ref Translation Translation => ref this.Entity.GetComponent<Translation>();
    public ref Rotation Rotation => ref this.Entity.GetComponent<Rotation>();
    public ref Scale Scale => ref this.Entity.GetComponent<Scale>();

    //Called once on world.GetAspectFactory<T>
    public void OnGetAspectFactory(World world) {
    }
}

In an aspect, you can write any combination of properties and methods to work with components on an entity.
Let's write a variation with stashes to make it work faster.

public struct Transform : IAspect {
    public Entity Entity { get; set;}
    
    public ref Translation Translation => ref this.translation.Get(this.Entity);
    public ref Rotation Rotation => ref this.rotation.Get(this.Entity);
    public ref Scale Scale => ref this.scale.Get(this.Entity);
    
    private Stash<Translation> translation;
    private Stash<Rotation> rotation;
    private Stash<Scale> scale;

    public void OnGetAspectFactory(World world) {
        this.translation = world.GetStash<Translation>();
        this.rotation = world.GetStash<Rotation>();
        this.scale = world.GetStash<Scale>();
    }
}

Let's add an IFilterExtension implementation to always have a query.

public struct Transform : IAspect, IFilterExtension {
    public Entity Entity { get; set;}
    
    public ref Translation Translation => ref this.translation.Get(this.Entity);
    public ref Rotation Rotation => ref this.rotation.Get(this.Entity);
    public ref Scale Scale => ref this.scale.Get(this.Entity);
    
    private Stash<Translation> translation;
    private Stash<Rotation> rotation;
    private Stash<Scale> scale;

    public void OnGetAspectFactory(World world) {
        this.translation = world.GetStash<Translation>();
        this.rotation = world.GetStash<Rotation>();
        this.scale = world.GetStash<Scale>();
    }
    public FilterBuilder Extend(FilterBuilder rootFilter) => rootFilter.With<Translation>().With<Rotation>().With<Scale>();
}

Now we write a system that uses our aspect.

public class TransformAspectSystem : ISystem {
    public World World { get; set; }

    private Filter filter;
    private AspectFactory<Transform> transform;
    
    public void OnAwake() {
        //Extend filter with ready query from Transform
        this.filter = this.World.Filter.Extend<Transform>().Build();
        //Getting aspect factory AspectFactory<Transform>
        this.transform = this.World.GetAspectFactory<Transform>();

        for (int i = 0, length = 100; i < length; i++) {
            var entity = this.World.CreateEntity();
            
            entity.AddComponent<Translation>();
            entity.AddComponent<Rotation>();
            entity.AddComponent<Scale>();
        }
    }
    public void OnUpdate(float deltaTime) {
        foreach (var entity in this.filter) {
            //Getting aspect copy for current entity
            var trs = this.transform.Get(entity);

            ref var trans = ref trs.Translation;
            trans.x += 1;

            ref var rot = ref trs.Rotation;
            rot.x += 1;
            
            ref var scale = ref trs.Scale;
            scale.x += 1;
        }
    }
    
    public void Dispose() {
    }
}

🧹 Component Disposing

Sometimes it becomes necessary to clear component values. For this, it is enough that the component implements IDisposable. For example:

public struct PlayerView : IComponent, IDisposable {
    public GameObject value;
    
    public void Dispose() {
        Object.Destroy(value);
    }
}

The initializer or system needs to mark the stash as disposable. For example:

public class PlayerViewDisposeInitializer : Initializer {
    public override void OnAwake() {
        this.World.GetStash<PlayerView>().AsDisposable();
    }
}

or

public class PlayerViewSystem : UpdateSystem {
    public override void OnAwake() {
        this.World.GetStash<PlayerView>().AsDisposable();
    }
    
    public override void OnUpdate(float deltaTime) {
        ...
    }
}

Now, when the component is removed from the entity, the Dispose() method will be called on the PlayerView component.

🧨 Unity Jobs And Burst

Important

Supported only in Unity. Subjected to further improvements and modifications.

You can convert Filter<T> to NativeFilter<TNative> which allows you to do component-based manipulations inside a Job.
Conversion of Stash<T> to NativeStash<TNative> allows you to operate on components based on entity ids.

Current limitations:

  • NativeFilter and NativeStash and their contents should never be re-used outside of single system tick.
  • NativeFilter and NativeStash cannot be used in-between World.Commit() calls inside Morpeh.

Example job scheduling:

public sealed class SomeSystem : UpdateSystem {
    private Filter filter;
    private Stash<HealthComponent> stash;
    ...
    public override void OnUpdate(float deltaTime) {
        var nativeFilter = this.filter.AsNative();
        var parallelJob = new ExampleParallelJob {
            entities = nativeFilter,
            healthComponents = stash.AsNative(),
            // Add more native stashes if needed
        };
        var parallelJobHandle = parallelJob.Schedule(nativeFilter.length, 64);
        parallelJobHandle.Complete();
    }
}

Example job:

[BurstCompile]
public struct TestParallelJobReference : IJobParallelFor {
    [ReadOnly]
    public NativeFilter entities;
    public NativeStash<HealthComponent> healthComponents;
        
    public void Execute(int index) {
        var entityId = this.entities[index];
        
        ref var component = ref this.healthComponents.Get(entityId, out var exists);
        if (exists) {
            component.Value += 1;
        }
        
        // Alternatively, you can avoid checking existance of the component
        // if the filter includes said component anyway
        
        ref var component = ref this.healthComponents.Get(entityId);
        component.Value += 1;
    }
}

For flexible Job scheduling, you can use World.JobHandle.
It allows you to schedule Jobs within one SystemsGroup, rather than calling .Complete() directly on the system.
Planning between SystemsGroup is impossible because in Morpeh, unlike Entities or other frameworks, there is no dependency graph that would allow Jobs to be planned among all systems, taking into account dependencies.

Example scheduling:

public sealed class SomeSystem : UpdateSystem {
    private Filter filter;
    private Stash<HealthComponent> stash;
    ...
    public override void OnUpdate(float deltaTime) {
        var nativeFilter = this.filter.AsNative();
        var parallelJob = new ExampleParallelJob {
            entities = nativeFilter,
            healthComponents = stash.AsNative()
        };
        World.JobHandle = parallelJob.Schedule(nativeFilter.length, 64, World.JobHandle);
    }
}

World.JobHandle.Complete() is called automatically after each Update type. For example:

  • Call OnUpdate() on all systems within the SystemsGroup.
  • Call World.JobHandle.Complete().
  • Call OnFixedUpdate() on all systems within the SystemsGroup.
  • Call World.JobHandle.Complete().

Warning

You cannot change the set of components on any entities if you have scheduled Jobs.
Any addition or deletion of components is considered a change.
The kernel will warn you at World.Commit() that you cannot do this.

You can manually control World.JobHandle, assign it, and call .Complete() on systems if you need to.
Currently Morpeh uses some additional temporary collections for the native part, so instead of just calling World.JobHandle.Complete() we recommend using World.JobsComplete().
This method is optional; the kernel will clear these collections one way or another, it will simply do it later.

🗒️ Defines

Can be set by user:

  • MORPEH_DEBUG Define if you need debug in application build. In editor it works automatically.
  • MORPEH_EXTERNAL_IL2CPP_ATTRS If you have conflicts with attributes, you can set this define and Morpeh core will be use internal version of attributes.
  • MORPEH_PROFILING Define for systems profiling in Unity Profiling Window.
  • MORPEH_METRICS Define for additional Morpeh Metrics in Unity Profiling Window.
  • MORPEH_NON_SERIALIZED Define to avoid serialization of Morpeh core parts.
  • MORPEH_THREAD_SAFETY Define that forces the kernel to validate that all calls come from the same thread the world was created on. The binding to a thread can be changed using the World.GetThreadId(), World.SetThreadId() methods.
  • MORPEH_DISABLE_SET_ICONS Define for disabling set icons in Project Window.
  • MORPEH_DISABLE_AUTOINITIALIZATION Define for disable default world creation and creating Morpeh Runner GameObject.

Will be set by framework:

  • MORPEH_BURST Determine if Burst is enabled, and framework has enabled Native API.

🌍️ World Plugins

Sometimes you need to make an automatic plugin for the world.
Add some systems, make a custom game loop, or automatic serialization.
World plugins are great for this.

To do this, you need to declare a class that implements the IWorldPlugin interface.
After that, create a static method with an attribute and register the plugin in the kernel.

For example:

class GlobalsWorldPlugin : IWorldPlugin {

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
    public static void RuntimeInitialize() {
        WorldExtensions.AddWorldPlugin(new GlobalsWorldPlugin());
    }
    
    public void Initialize(World world) {
        var sg = world.CreateSystemsGroup();
        sg.AddSystem(new ECS.ProcessEventsSystem());
        world.AddPluginSystemsGroup(sg);
    }
    
    public void Deinitialize(World world) {
        
    }
}

📊 Metrics

To debug the game, you may need statistics on basic data in the ECS framework, such as:

  1. Number of entities
  2. Number of archetypes
  3. Number of filters
  4. Number of systems
  5. Number of commits in the world
  6. Number of entity migrations

You can find all this in the profiler window.
To do this, you need to add the official Unity Profiling Core API package to your project.
Its quick name to search is: com.unity.profiling.core

After this, specify the MORPEH_METRICS definition in the project.
Now you can observe all the statistics for the kernel.

Open the profiler window.
On the top left, click the Profiler Modules button and find Morpeh there.
We turn it on with a checkmark and can move it higher or lower.

Metrics work the same way in debug builds, so you can see the whole picture directly from the device.

It will be look like this in playmode.

metrics.png


🔌 Plugins


📚 Examples


🔥 Games

  • One State RP - Life Simulator by Chillbase
    Android iOS

  • FatalZone by Midhard Games
    Steam

  • Zombie City by GreenButtonGames
    Android iOS

  • Fish Idle by GreenButtonGames
    Android iOS

  • Stickman of Wars: RPG Shooters by Multicast Games
    Android iOS

  • Alien Invasion: RPG Idle Space by Multicast Games
    Android iOS

  • Cowravaneer by FESUNENKO GAMES
    Android


📘 License

📄 MIT License


💬 Contacts

✉️ Telegram: olegmrzv
📧 E-Mail: [email protected]
👥 Telegram Community RU: Morpeh ECS Development

morpeh's People

Contributors

formatcvt avatar gallardo994 avatar golovchanskyva avatar krvs avatar mininaleksandr avatar olegmrzv avatar r1nge avatar sh42913 avatar stinkysteak avatar vanifatovvlad avatar warmerko avatar xk0fe avatar zudl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

morpeh's Issues

[Native] Detect Burst support in Unity

Currently, ENABLE_BURST_AOT define is set in non-burst Unity projects (for some strange reason). We need a better solution to detect Burst installations with defines.

Public setter for BasePair.System

When writing the editor extension for the inspector Installer script, I had a problem in that I could not initialize BasePair normally from the script, because the BasePair.System field does not have a public setter.

Null default world during manual world creation

При попытке создавать и контролировать World вручную, World.Default всегда возвращает Null, вследствии чего перестают работать Entity/MonoProviders.

Тут проблема в том, что список с мирами при инициализации всегда добавляет по индексу 0 null ссылку

image

Can't select bag for components with one boolean value

При попытке взять bag для компонента, в котором содерржиться только 1 булевое поле выдает ошибку.
You Select<ECSAction> marker component from filter! This makes no sense.

Предполагаю что ошибка в методе подсчета размера компонента.
Простое добовление поля типа Int убрало ошибку

image
image
image

Ошибка You're trying to get on entity a component that doesn't exists! в едиторе

Если кодом в рантайме удалить компонент, у которого есть провайдер, и при этом будет открыт инспектор этого объекта, тогда падает эта ошибка
Пример:

Exception: [MORPEH] You're trying to get on entity 212 a component that doesn't exists!
Morpeh.ComponentsCache`1[T].GetComponent (Morpeh.Entity entity) (at Library/PackageCache/com.scellecs.morpeh@22b6b7c1ca/Core/ComponentsCache.cs:148)
Morpeh.MonoProvider`1[T].get_Data () (at Library/PackageCache/com.scellecs.morpeh@22b6b7c1ca/Unity/Providers/MonoProvider.cs:24)
(wrapper dynamic-method) System.Object.Morpeh.MonoProvider`1[[HealthBarRenderComponent, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]].get_Data(Morpeh.MonoProvider`1<HealthBarRenderComponent>&)
Sirenix.OdinInspector.Editor.GetterSetter`2[TOwner,TValue].GetValue (TOwner& owner) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/Infos/GetterSetter.cs:270)
Sirenix.OdinInspector.Editor.AliasGetterSetter`4[TOwner,TValue,TPropertyOwner,TPropertyValue].GetValue (TOwner& owner) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/Infos/AliasGetterSetter.cs:70)
Sirenix.OdinInspector.Editor.PropertyValueEntry`2[TParent,TValue].UpdateValues () (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/Value Entries/PropertyValueEntry.cs:1049)
Sirenix.OdinInspector.Editor.PropertyValueEntry.Update () (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/Value Entries/PropertyValueEntry.cs:226)
Sirenix.OdinInspector.Editor.InspectorProperty.UpdateValueEntry () (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/InspectorProperty.cs:1436)
Sirenix.OdinInspector.Editor.InspectorProperty.Update (System.Boolean forceUpdate) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/InspectorProperty.cs:1090)
Sirenix.OdinInspector.Editor.InspectorProperty.OnStateUpdate (System.Int32 treeID) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/InspectorProperty.cs:663)
Sirenix.OdinInspector.Editor.InspectorProperty.OnStateUpdate (System.Int32 treeID) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/InspectorProperty.cs:668)
Sirenix.OdinInspector.Editor.PropertyTree.BeginDraw (System.Boolean withUndo) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/PropertyTree.cs:450)
Sirenix.OdinInspector.Editor.PropertyTree.Draw (System.Boolean applyUndo) (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Core/PropertyTree.cs:388)
Sirenix.OdinInspector.Editor.OdinEditor.DrawTree () (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Drawers/OdinEditor.cs:93)
Sirenix.OdinInspector.Editor.OdinEditor.DrawOdinInspector () (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Drawers/OdinEditor.cs:216)
Sirenix.OdinInspector.Editor.OdinEditor.OnInspectorGUI () (at X:/Repositories/sirenix-development/Sirenix Solution/Sirenix.OdinInspector.Editor/Drawers/OdinEditor.cs:85)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <2758fd44916644e3a3b65c9d4809b7f9>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

Add search to WorldViewer

It's too hard to use WorldViewer without search.
I added this feature to may project ([Searchable] parameter of private List Entities at WorldViewer) and it works fine.
Maybe it's good idea to add this feature to master.

License doesn't show as MIT on GitHub page

Summary

Hi there, I noticed a very small issue when reading the GitHub page for this library. Even though the license reads as an MIT license for some reason GitHub is not picking that up and indicating you should read the contents for more details.

image

Though its a very small thing, when other people read this page or view it in their search results this project would not show as having an MIT license. I've had this problem before and the way I've usually resolved it is to delete the existing license and re-add it through the GitHub website. Its usually some very slight, inane formatting or naming issue that causes it to not show correctly..

I hope this is helpful for you!

[Feature Request] Добавить EntityID

Проблема

На данный момент морпех переиспользует ID поэтому их нельзя хранить отдельно от Entity (например, для передачи в Job и обработки в следующем кадре).

[Test]
public void EntityIdUniqueness()
{
    var world = World.Create();

    var entity1 = world.CreateEntity();
    var entityId1 = entity1.ID;

    entity1.Dispose();
    world.Update(0.01f);

    var entity2 = world.CreateEntity();
    var entityId2 = entity2.ID;

    Assert.AreEqual(entityId1, entityId2);
}

Предложение

Добавить уникальное поле entity.EntityID, где EntityID это

public struct EntityID {
    public int ID; // индекс 
    public int Gen; // уникальное число

    public bool Equal(EntityID other);
    public static bool operator ==(EntityID a, EntityID b);
    public static bool operator !=(EntityID a, EntityID b);

    public static EntityID Invalid => new EntityID {ID = -1, Gen = -1};
}

и метод-расширение

// возвращает true только если 
// entityID != EntiyID.Invalid && world.entities[entityId.ID].IsAlive() && world.entities[entityId.ID].Gen == entityId.Gen
public static bool TryGetEntity(this World world, EntityID entityID, out Entity entity);

Пример использования

public class DamageEvent : CustomGlobalEvent<DamageEvent.Args> {
    public struct Args { public EntityID targetID; }
}

public class AttackSystem : UpdateSystem {
    public DamageEvent damageEvent;

    public override void OnUpdate(float deltaTime) {
        Entity target = ...;
        damageEvent.NextFrame(new DamageEvent.Args { targetID = target.EntityId });
    }
}

public class DamageSystem : UpdateSystem {
    public DamageEvent damageEvent;
    
    public override void OnUpdate(float deltaTime) {
        if (!damageEvent.IsPublished) {
            continue;
        }

        foreach (var evt in damageEvent.BatchedChanges) {
            if (!this.World.TryGetEntity(evt.targetID, out var targetEntity)) {
                continue;
            }

            // use targetEntity
        }
    }
}

Auto warmup not working on IOS build

IOS build crashes at startup with this message:

ExecutionEngineException: Attempting to call method 'Morpeh.TypeIdentifier`1[[MyTestComponent, Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]::Warmup' for which no ahead of time (AOT) code was generated.
  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <00000000000000000000000000000000>:0 
  at Morpeh.WorldExtensions.InitializationDefaultWorld () [0x00000] in <00000000000000000000000000000000>:0 
UnityEngine.UnhandledExceptionHandler:PrintException(String, Exception)
UnityEngine.UnhandledExceptionHandler:HandleUnhandledException(Object, UnhandledExceptionEventArgs)
System.UnhandledExceptionEventHandler:Invoke(Object, UnhandledExceptionEventArgs)

I fixed this wrapping these 'warm types' codes in InitializationDefaultWorld method with !UNITY_IOS define. Not sure if this problem exists on other AOT platforms too

[Feature Request] Разделить проект на отдельные пакеты

Если разделить проект на отдельные пакеты, то появится возможность использовать в проекте только нужные части морпеха (например, отказаться от использования утилит и заменить глобалы собственной реализацией)

Morpeh

  • ECS Core

Morpeh.UnityIntegration

  • World browser
  • Unity Installers
  • Unity Providers
  • Unity Systems
  • Discover (?)

Morpeh.Globals

  • Global Singleton
  • Global Variables
  • Global Events
  • BigNumber (?)
  • SceneReference (?)

Morpeh.Utils

  • AndroidKeyStore
  • CompilationTime
  • DependencyResolver
  • EditorSceneSetup
  • IconsSetter (?)
  • iOSPostProcessBuild

ComponentsCacheDisposable doesn't work with AOT

I've got error

ExecutionEngineException: Attempting to call method 'Morpeh.ComponentsCacheDisposable`1[[Tanks.GameInput.GameUser, Tanks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]::.ctor' for which no ahead of time (AOT) code was generated.

while trying to build morpeh.examples.tanks for Windows with IL2CPP using Unity 2019.4.40f1.
But everything works fine, when I change ComponentsCacheDisposable visibility to public and call constructor directly from system's OnAwake().

Replace Trailing Zeros

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private int NumberOfTrailingZeros(int i) {
        switch (((uint)(i & -i) * 0x077CB531u) >> 27) {
            case 0: return 0;
            case 1: return 1;
            case 2: return 28;
            case 3: return 2;
            case 4: return 29;
            case 5: return 14;
            case 6: return 24;
            case 7: return 3;
            case 8: return 30;
            case 9: return 22;
            case 10: return 20;
            case 11: return 15;
            case 12: return 25;
            case 13: return 17;
            case 14: return 4;
            case 15: return 8;
            case 16: return 31;
            case 17: return 27;
            case 18: return 13;
            case 19: return 23;
            case 20: return 21;
            case 21: return 19;
            case 22: return 16;
            case 23: return 7;
            case 24: return 26;
            case 25: return 12;
            case 26: return 18;
            case 27: return 6;
            case 28: return 11;
            case 29: return 5;
            case 30: return 10;
            case 31: return 9;
        }
        return 0;
    }

Namespace modification warning

I've got this warning at first startup in Unity 2020.3.41f1 for unknown reason, but it didn't lead to any other issues, everything works fine.
image

SizeOf<T> Issue

Unity 2021.1.14 Unity.Collections.LowLevel.Unsafe.UnsafeUtility.SizeOf() возвращает неверный результат для компонента с одним булевым полем из-за чего тип помечается как маркер. System.Runtime.InteropServices.Marshal.SizeOf(default(T)) отрабатывает как надо.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.