コード例 #1
0
        public IComponent CreateComponent(Entity entity)
        {
            if (_type == null)
            {
                _type = fullTypeName.ToType();

                if (_type == null)
                {
                    throw new ComponentBlueprintException(
                              "Type '" + fullTypeName +
                              "' doesn't exist in any assembly!",
                              "Please check the full type name."
                              );
                }

                if (!_type.ImplementsInterface <IComponent>())
                {
                    throw new ComponentBlueprintException(
                              "Type '" + fullTypeName +
                              "' doesn't implement IComponent!",
                              typeof(ComponentBlueprint).Name +
                              " only supports IComponent."
                              );
                }
            }

            var component = entity.CreateComponent(index, _type);

            if (_componentMembers == null)
            {
                var memberInfos = _type.GetPublicMemberInfos();
                _componentMembers = new Dictionary <string, PublicMemberInfo>(
                    memberInfos.Count
                    );
                for (int i = 0; i < memberInfos.Count; i++)
                {
                    var info = memberInfos[i];
                    _componentMembers.Add(info.name, info);
                }
            }

            for (int i = 0; i < members.Length; i++)
            {
                var member = members[i];

                PublicMemberInfo memberInfo;
                if (!_componentMembers.TryGetValue(member.name, out memberInfo))
                {
                    throw new ComponentBlueprintException(
                              "Could not find member '" + member.name +
                              "' in type '" + _type.FullName + "'!",
                              "Only non-static public members are supported."
                              );
                }

                memberInfo.SetValue(component, member.value);
            }

            return(component);
        }
コード例 #2
0
        public Entity CreateCharacter()
        {
            Entity entity = new Entity();

            entity.CreateComponent <PositionComponent>();
            return(entity);
        }
コード例 #3
0
        public static Entity Replace <TComponent, TValue>(this Entity entity, IComp <TComponent, SingleValueComponent <TValue> .Editor> compData, TValue value)
            where TComponent : SingleValueComponent <TValue>, new()
        {
            TComponent comp = entity.CreateComponent <TComponent>(compData.EntitasData.Id);

            compData.Editor.SetActionReplace(entity, compData.EntitasData.Id, comp);
            return(compData.Editor.Apply(value));
        }
コード例 #4
0
 public void Run()
 {
     for (int i = 0; i < n; i++)
     {
         _e.RemoveComponent(CP.ComponentA);
         _e.AddComponent(CP.ComponentA, _e.CreateComponent <ComponentA>(CP.ComponentA));
     }
 }
コード例 #5
0
        public static void AddValueComponent(Entity entity, int compId, Type compType, object value)
        {
            var component = entity.CreateComponent(compId, compType);
            var field     = compType.GetField("value");

            field.SetValue(component, value);
            entity.AddComponent(compId, component);
        }
コード例 #6
0
        public static TEditor Replace <TComponent, TEditor>(this Entity entity, IComp <TComponent, TEditor> compData)
            where TComponent : IComponent, new()
            where TEditor : IComponentEditor <TComponent>
        {
            TComponent comp = entity.CreateComponent <TComponent>(compData.EntitasData.Id);

            compData.Editor.SetActionReplace(entity, compData.EntitasData.Id, comp);
            return(compData.Editor);
        }
コード例 #7
0
ファイル: Entity.cs プロジェクト: v-free/Entitas-Lite
        /// replace Component with a NEW one
        public static T ReplaceNewComponent <T>(this Entity entity) where T : IComponent, new()
        {
            int index = ComponentIndex <T> .FindIn(entity.contextInfo);

            T component = entity.CreateComponent <T>(index);

            entity.ReplaceComponent(index, component);

            return(component);
        }
コード例 #8
0
        private void InitialSize(Entity <IUIPool> element, bool isRoot)
        {
            if (element.Has <Size>())
            {
                return;
            }
            var size = element.CreateComponent <Size>();

            size.Value = new Vector2(0, 0);
            element.AddInstance(size);
        }
コード例 #9
0
        private void InitialPosition(Entity <IUIPool> element, bool isRoot)
        {
            if (element.Has <Position>())
            {
                return;
            }
            var position = element.CreateComponent <Position>();

            position.Value = new Vector2(0, 0);
            element.AddInstance(position);
        }
コード例 #10
0
        private void InitialPivot(Entity <IUIPool> element, bool isRoot)
        {
            if (element.Has <Pivot>())
            {
                return;
            }
            var pivot = element.CreateComponent <Pivot>();

            pivot.Value = isRoot ? new Vector2(0.5f, 0.5f) : new Vector2(0, 1);
            element.AddInstance(pivot);
        }
コード例 #11
0
        private void InitialAnchor(Entity <IUIPool> element, bool isRoot)
        {
            if (element.Has <Anchor>())
            {
                return;
            }
            var anchor = element.CreateComponent <Anchor>();

            anchor.Value = isRoot ? new Vector4(0f, 0f, 1f, 1f) : new Vector4(0f, 1f, 0f, 1f);
            element.AddInstance(anchor);
        }
コード例 #12
0
        private void InitialMargin(Entity <IUIPool> element, bool isRoot)
        {
            if (element.Has <Margin>())
            {
                return;
            }
            var margin = element.CreateComponent <Margin>();

            margin.Value = new Vector4(0, 0, 0, 0);
            element.AddInstance(margin);
        }
コード例 #13
0
        public static void DrawAndSetElement(Type type, string fieldName, object value, Entity entity, int index, IComponent component, Action <IComponent, object> setValue)
        {
            var newValue = DrawAndGetNewValue(type, fieldName, value, entity, index, component);

            if (DidValueChange(value, newValue))
            {
                var newComponent = entity.CreateComponent(index, component.GetType());
                component.CopyPublicMemberValues(newComponent);
                setValue(newComponent, newValue);
                entity.ReplaceComponent(index, newComponent);
            }
        }
コード例 #14
0
ファイル: Entity.cs プロジェクト: v-free/Entitas-Lite
        /// add a new Component, return the old one if exists
        public static T AddComponent <T>(this Entity entity, bool keepOldIfExists = false) where T : IComponent, new()
        {
            int index = ComponentIndex <T> .FindIn(entity.contextInfo);

            T component;

            if (keepOldIfExists && entity.HasComponent(index))
            {
                component = (T)entity.GetComponent(index);
                entity.MarkUpdated(index);
            }
            else
            {
                component = entity.CreateComponent <T>(index);
                entity.AddComponent(index, component);
            }

            return(component);
        }
コード例 #15
0
        public static Entity <IUIPool> AddElement(this Entity <IUIPool> @this, int order = 0)
        {
            if (@this.Has <Element>())
            {
                return(@this);
            }

            var el = @this.CreateComponent <Element>();

            el.Id = Guid.NewGuid();

            @this.Toggle <Api.Disabled>(true);

            var ord = @this.Need <Order>();

            ord.Value = order;

            return(@this.AddInstance(el).AddInstance(ord));
        }
コード例 #16
0
        public static Entity SetFlag <TComponent>(this Entity entity, IFlagComp <TComponent> compData, bool val = true)
            where TComponent : IComponent, new()
        {
            bool curVal = entity.HasComponent(compData.EntitasData.Id);

            if (curVal != val)
            {
                if (val)
                {
                    // TODO singleton instead of pooling
                    TComponent comp = entity.CreateComponent <TComponent>(compData.EntitasData.Id);
                    entity.AddComponent(compData.EntitasData.Id, comp);
                }
                else
                {
                    entity.RemoveComponent(compData.EntitasData.Id);
                }
            }
            return(entity);
        }
コード例 #17
0
        public virtual void SetComponentsTo(Entity targetEntity)
        {
#if false
            var allMemberInfos = this.GetType().GetPublicMemberInfos();
            foreach (var memberInfo in allMemberInfos)
            {
                int index   = 0;
                var memType = memberInfo.type;
                if (type2Idx.TryGetValue(memType, out int qidx))
                {
                    index = qidx;
                }
                else
                {
                    if (_name2Idx.TryGetValue(memType.Name, out int nidx))
                    {
                        index = nidx;
                        type2Idx.Add(memType, nidx);
                    }
                    else
                    {
                        Lockstep.Logging.Debug.LogError("Do not have type" + memType.Name.ToString());
                        return;
                    }
                }

                IComponent srcComp = memberInfo.GetValue(this) as IComponent;
                if (targetEntity.HasComponent(index))
                {
                    IComponent dstComp = targetEntity.GetComponent(index);
                    srcComp.CopyPublicMemberValues((object)dstComp);
                }
                else
                {
                    IComponent dstComp = targetEntity.CreateComponent(index, srcComp.GetType());
                    srcComp.CopyPublicMemberValues((object)dstComp);
                    targetEntity.AddComponent(index, dstComp);
                }
            }
#endif
        }
コード例 #18
0
        public static void Add_OnSelf <TScope, TComp>(this Entity <TScope> entity, IOnSelf <TScope, TComp> listener)
            where TScope : IScope
            where TComp : Scope <TScope>, IComponent, IEvent_Self <TScope, TComp>
        {
            var index = Lookup <TScope, Event_SelfComponent <TScope, TComp> > .Id;

            Event_SelfComponent <TScope, TComp> component;

            if (entity.HasComponent(index))
            {
                component = (Event_SelfComponent <TScope, TComp>)entity.GetComponent(index);
            }
            else
            {
                component = entity.CreateComponent <Event_SelfComponent <TScope, TComp> >(index);
                entity.AddComponent(index, component);
                component.Listeners.Clear();
            }

            component.Listeners.Add(listener);
        }
コード例 #19
0
ファイル: ReadXmlSystem.cs プロジェクト: pandey623/ReUI
        private void Parse(Entity <IUIPool> xmlEntity)
        {
            var             xmlText  = xmlEntity.Get <XmlData>().Value;
            NanoXMLDocument document = null;

            try
            {
                document = new NanoXMLDocument(xmlText);
            }
            catch (Exception e)
            {
                _uiPool.DestroyEntity(xmlEntity);
                Debug.LogError(e);
                return;
            }

            var docComponent = xmlEntity.CreateComponent <XmlDocument>();

            docComponent.Root = document.RootNode;

            xmlEntity.AddInstance(docComponent);
        }
コード例 #20
0
        public void Apply(Entity entity)
        {
            if (m_type == null)
            {
                var tuple = GetComponentType(entity);
                if (tuple == null)
                {
                    throw new ComponentBlueprintException($"Could not find '{m_name}Component' in '{entity.contextInfo.name}Context'",
                                                          "Please check component definition");
                }
                m_type  = tuple.Item1;
                m_index = tuple.Item2;

                var publicMembers = GetComponentMembers();
                foreach (var member in Members)
                {
                    member.Parse(publicMembers[member.Name]);
                }
            }

            var component = entity.CreateComponent(m_index, m_type);

            foreach (var m in Members)
            {
                PublicMemberInfo memberInfo;
                if (m_componentMembers.TryGetValue(m.Name, out memberInfo))
                {
                    memberInfo.SetValue(component, m.Value);
                }
                else
                {
                    throw new ComponentBlueprintException($"Could not find member '{m.Name} ' in type '{m_name}Component'!",
                                                          "Only non-static public members are supported.");
                }
            }

            entity.AddComponent(m_index, component);
        }
コード例 #21
0
ファイル: ParseXmlSystem.cs プロジェクト: pandey623/ReUI
        private void FillElement(Entity <IUIPool> root, Entity <IUIPool> element, IXmlNode node)
        {
            element.Add <Scope>(s => s.Id = root.Get <Element>().Id);

            var xmlElement = element.CreateComponent <XmlElement>();

            xmlElement.Name       = node.Name;
            xmlElement.Attributes = node.Attributes.ToDictionary(a => a.Name, a => a.Value);
            xmlElement.Content    = node.Value;

            foreach (var extraNode in node.SubNodes.Where(child => _extraElementNodesDictionary.ContainsKey(child.Name))
                     )
            {
                var extraType = _extraElementNodesDictionary[extraNode.Name];
                var value     = extraNode.Value;
                if (string.IsNullOrEmpty(value))
                {
                    value = extraNode.Attributes.FirstOrDefault(a => a.Name == "Value")?.Value;
                }
                xmlElement.Attributes.Add(extraNode.Name, value);
            }

            element.AddInstance(xmlElement);
        }
コード例 #22
0
        public static void DrawComponent(bool[] unfoldedComponents, Entity entity, int index, IComponent component)
        {
            var componentType = component.GetType();

            var componentName = componentType.Name.RemoveComponentSuffix();
            if (componentName.ToLower().Contains(_componentNameSearchTerm.ToLower())) {

                var boxStyle = getColoredBoxStyle(entity.totalComponents, index);
                EntitasEditorLayout.BeginVerticalBox(boxStyle);
                {
                    var memberInfos = componentType.GetPublicMemberInfos();
                    EntitasEditorLayout.BeginHorizontal();
                    {
                        if (memberInfos.Count == 0) {
                            EditorGUILayout.LabelField(componentName, EditorStyles.boldLabel);
                        } else {
                            unfoldedComponents[index] = EditorGUILayout.Foldout(unfoldedComponents[index], componentName, _foldoutStyle);
                        }
                        if (GUILayout.Button("-", GUILayout.Width(19), GUILayout.Height(14))) {
                            entity.RemoveComponent(index);
                        }
                    }
                    EntitasEditorLayout.EndHorizontal();

                    if (unfoldedComponents[index]) {

                        var componentDrawer = getComponentDrawer(componentType);
                        if (componentDrawer != null) {
                            var newComponent = entity.CreateComponent(index, componentType);
                            component.CopyPublicMemberValues(newComponent);
                            EditorGUI.BeginChangeCheck();
                            {
                                componentDrawer.DrawComponent(newComponent);
                            }
                            var changed = EditorGUI.EndChangeCheck();
                            if (changed) {
                                entity.ReplaceComponent(index, newComponent);
                            } else {
                                entity.GetComponentPool(index).Push(newComponent);
                            }
                        } else {
                            foreach (var info in memberInfos) {
                                DrawAndSetElement(info.type, info.name, info.GetValue(component),
                                    entity, index, component, info.SetValue);
                            }
                        }
                    }
                }
                EntitasEditorLayout.EndVertical();
            }
        }
コード例 #23
0
 public static void DrawAndSetElement(Type memberType, string memberName, object value, Entity entity, int index, IComponent component, Action<IComponent, object> setValue)
 {
     var newValue = DrawAndGetNewValue(memberType, memberName, value, entity, index, component);
     if (DidValueChange(value, newValue)) {
         var newComponent = entity.CreateComponent(index, component.GetType());
         component.CopyPublicMemberValues(newComponent);
         setValue(newComponent, newValue);
         entity.ReplaceComponent(index, newComponent);
     }
 }
コード例 #24
0
    void when_creating()
    {
        Pool   pool   = null;
        Entity entity = null;

        before = () => {
            pool   = new Pool(CID.TotalComponents);
            entity = pool.CreateEntity();
        };

        context["ComponentBlueprint"] = () => {
            it["creates a component blueprint from a component without members"] = () => {
                var component = new ComponentA();

                const int index = 42;

                var componentBlueprint = new ComponentBlueprint(index, component);
                componentBlueprint.index.should_be(index);
                componentBlueprint.fullTypeName.should_be(component.GetType().FullName);
                componentBlueprint.members.Length.should_be(0);
            };

            it["throws when unknown type"] = expect <ComponentBlueprintException>(() => {
                var componentBlueprint          = new ComponentBlueprint();
                componentBlueprint.fullTypeName = "UnknownType";
                componentBlueprint.CreateComponent(null);
            });

            it["throws when type doesn't implement IComponent"] = expect <ComponentBlueprintException>(() => {
                var componentBlueprint          = new ComponentBlueprint();
                componentBlueprint.fullTypeName = "string";
                componentBlueprint.CreateComponent(null);
            });

            it["creates a component blueprint from a component with members"] = () => {
                var component = new NameAgeComponent();
                component.name = "Max";
                component.age  = 42;

                const int index = 24;

                var componentBlueprint = new ComponentBlueprint(index, component);
                componentBlueprint.index.should_be(index);
                componentBlueprint.fullTypeName.should_be(component.GetType().FullName);
                componentBlueprint.members.Length.should_be(2);

                componentBlueprint.members[0].name.should_be("name");
                componentBlueprint.members[0].value.should_be(component.name);

                componentBlueprint.members[1].name.should_be("age");
                componentBlueprint.members[1].value.should_be(component.age);
            };

            it["creates a component and sets members values"] = () => {
                var componentBlueprint = new ComponentBlueprint();
                componentBlueprint.fullTypeName = typeof(ComponentWithFieldsAndProperties).FullName;
                componentBlueprint.index        = CID.ComponentB;
                componentBlueprint.members      = new [] {
                    new SerializableMember("publicField", "publicFieldValue"),
                    new SerializableMember("publicProperty", "publicPropertyValue")
                };

                var component = (ComponentWithFieldsAndProperties)componentBlueprint.CreateComponent(entity);
                component.publicField.should_be("publicFieldValue");
                component.publicProperty.should_be("publicPropertyValue");
            };

            it["throws when invalid member name"] = expect <ComponentBlueprintException>(() => {
                var componentBlueprint          = new ComponentBlueprint();
                componentBlueprint.index        = 0;
                componentBlueprint.fullTypeName = typeof(NameAgeComponent).FullName;
                componentBlueprint.members      = new [] {
                    new SerializableMember("xxx", "publicFieldValue"),
                    new SerializableMember("publicProperty", "publicPropertyValue")
                };
                componentBlueprint.CreateComponent(entity);
            });
        };

        context["Blueprint"] = () => {
            it["creates a blueprint from an entity"] = () => {
                entity.AddComponentA();

                var component = new NameAgeComponent();
                component.name = "Max";
                component.age  = 42;

                entity.AddComponent(CID.ComponentB, component);

                var blueprint = new Blueprint("My Pool", "Hero", entity);
                blueprint.poolIdentifier.should_be("My Pool");
                blueprint.name.should_be("Hero");
                blueprint.components.Length.should_be(2);

                blueprint.components[0].index.should_be(CID.ComponentA);
                blueprint.components[0].fullTypeName.should_be(Component.A.GetType().FullName);

                blueprint.components[1].index.should_be(CID.ComponentB);
                blueprint.components[1].fullTypeName.should_be(component.GetType().FullName);
            };

            context["when applying blueprint"] = () => {
                Blueprint blueprint = null;

                before = () => {
                    var component1 = new ComponentBlueprint();
                    component1.index        = CID.ComponentA;
                    component1.fullTypeName = typeof(ComponentA).FullName;
                    component1.members      = new SerializableMember[0];

                    var component2 = new ComponentBlueprint();
                    component2.index        = CID.ComponentB;
                    component2.fullTypeName = typeof(NameAgeComponent).FullName;
                    component2.members      = new [] {
                        new SerializableMember("name", "Max"),
                        new SerializableMember("age", 42)
                    };

                    blueprint            = new Blueprint();
                    blueprint.name       = "Hero";
                    blueprint.components = new [] { component1, component2 };
                };

                it["applies blueprint to entity"] = () => {
                    entity.ApplyBlueprint(blueprint).should_be(entity);

                    entity.GetComponents().Length.should_be(2);

                    entity.GetComponent(CID.ComponentA).GetType().should_be(typeof(ComponentA));

                    var nameAgeComponent = (NameAgeComponent)entity.GetComponent(CID.ComponentB);
                    nameAgeComponent.GetType().should_be(typeof(NameAgeComponent));
                    nameAgeComponent.name.should_be("Max");
                    nameAgeComponent.age.should_be(42);
                };

                it["throws when entity already has a component which should be added from blueprint"] = expect <EntityAlreadyHasComponentException>(() => {
                    entity.AddComponentA();
                    entity.ApplyBlueprint(blueprint);
                });

                it["can overwrite existing components"] = () => {
                    var nameAgeComponent = new NameAgeComponent();
                    nameAgeComponent.name = "Jack";
                    nameAgeComponent.age  = 24;
                    entity.AddComponent(CID.ComponentB, nameAgeComponent);

                    entity.ApplyBlueprint(blueprint, true);
                };

                it["uses component from componentPool"] = () => {
                    var component = new ComponentBlueprint();
                    component.index        = CID.ComponentA;
                    component.fullTypeName = typeof(ComponentA).FullName;
                    component.members      = new SerializableMember[0];

                    blueprint            = new Blueprint();
                    blueprint.name       = "Hero";
                    blueprint.components = new [] { component };

                    var componentA = entity.CreateComponent <ComponentA>(CID.ComponentA);
                    entity.AddComponent(CID.ComponentA, componentA);
                    entity.RemoveComponentA();

                    entity.ApplyBlueprint(blueprint);

                    entity.GetComponentA().should_be_same(componentA);
                };
            };
        };
    }
コード例 #25
0
        public static void DrawComponent(bool[] unfoldedComponents, Entity entity, int index, IComponent component)
        {
            var componentType = component.GetType();

            var componentName = componentType.Name.RemoveComponentSuffix();

            if (componentName.ToLower().Contains(_componentNameSearchTerm.ToLower()))
            {
                var boxStyle = getColoredBoxStyle(entity.totalComponents, index);
                EntitasEditorLayout.BeginVerticalBox(boxStyle);
                {
                    var memberInfos = componentType.GetPublicMemberInfos();
                    EntitasEditorLayout.BeginHorizontal();
                    {
                        if (memberInfos.Count == 0)
                        {
                            EditorGUILayout.LabelField(componentName, EditorStyles.boldLabel);
                        }
                        else
                        {
                            unfoldedComponents[index] = EntitasEditorLayout.Foldout(unfoldedComponents[index], componentName, _foldoutStyle);
                        }
                        if (GUILayout.Button("-", GUILayout.Width(19), GUILayout.Height(14)))
                        {
                            entity.RemoveComponent(index);
                        }
                    }
                    EntitasEditorLayout.EndHorizontal();

                    if (unfoldedComponents[index])
                    {
                        var componentDrawer = getComponentDrawer(componentType);
                        if (componentDrawer != null)
                        {
                            var newComponent = entity.CreateComponent(index, componentType);
                            component.CopyPublicMemberValues(newComponent);
                            EditorGUI.BeginChangeCheck();
                            {
                                componentDrawer.DrawComponent(newComponent);
                            }
                            var changed = EditorGUI.EndChangeCheck();
                            if (changed)
                            {
                                entity.ReplaceComponent(index, newComponent);
                            }
                            else
                            {
                                entity.GetComponentPool(index).Push(newComponent);
                            }
                        }
                        else
                        {
                            foreach (var info in memberInfos)
                            {
                                DrawAndSetElement(info.type, info.name, info.GetValue(component),
                                                  entity, index, component, info.SetValue);
                            }
                        }
                    }
                }
                EntitasEditorLayout.EndVertical();
            }
        }