Example #1
0
bool Entity::addComponent( const ComponentPtr& component )
{
	if( !component ) return false;

	Class* type = component->getType();

    if( componentsMap.Find(type) != componentsMap.End() )
	{
        LogWarn( "Component '%s' already exists in '%s'", type->name, name.CString() );
		return false;
	}

	componentsMap[type] = component;
	component->setEntity(this);

	onComponentAdded(component);
	sendEvents();

	if( IsGroup(parent) )
	{
		Group* group = (Group*) parent;
		group->onEntityComponentAdded(component);
	}

    components.Push(component);

	return true;
}
bool ComponentCollection::ValidateComponent( const ComponentPtr &component, tstring& error ) const
{
    HELIUM_ASSERT( component->GetSlot() != Reflect::ReservedTypes::Invalid );

    // Check for duplicates.
    if ( ContainsComponent( component->GetSlot() ) )
    {
        error = tstring( TXT( "The component '" ) )+ component->GetClass()->m_UIName + TXT( "' is a duplicate (a component already occupies that slot in the collection)." );
        return false;
    }

    // Check to make sure this type of collection accepts this type of component.
    if ( !ValidateCompatible( component, error ) )
    {
        return false;
    }

    // Check to make sure that each component already within the collection is valid with the new one.
    M_Component::const_iterator itr = m_Components.begin();
    M_Component::const_iterator end = m_Components.end();
    for ( ; itr != end; ++itr )
    {
        // Check both directions so that the validation rule only has to be implemented in one place.
        if ( !itr->second->ValidateSibling( component, error ) || !component->ValidateSibling( itr->second.Ptr(), error ) )
        {
            return false;
        }
    }

    return true;
}
	void ElementGroup::ProcessComponent(const ComponentPtr& component, bool removable)
	{
		bool added = AddInspector(component, component->GetType(), removable);

		// If there wasn't a specific inspector for the given type, try adding interface inspectors
		if (!added)
		{
			// Make sure the transform inspector is at the top
			const auto& actualInterfaces = component->GetInterfaces();
			auto entry = actualInterfaces.find("ITransform");
			if (entry == actualInterfaces.end())
			{
				for (auto it = actualInterfaces.begin(), end = actualInterfaces.end(); it != end; ++it)
					added |= AddInspector(component, *it, removable);
			}
			else
			{
				AddInspector(component, "ITransform", false);

				std::set<std::string> interfacesMinusTransform = actualInterfaces;
				interfacesMinusTransform.erase("ITransform");
				for (auto it = interfacesMinusTransform.begin(), end = interfacesMinusTransform.end(); it != end; ++it)
					added |= AddInspector(component, *it, removable);
			}
		}
		if (!added)
			SendToConsole("No inspector for component type: " + component->GetType());
	}
ComponentCollection::ComponentCollection( const ComponentPtr& component )
{
    HELIUM_ASSERT( component->GetSlot() != Reflect::ReservedTypes::Invalid );

    m_Components.insert( M_Component::value_type( component->GetSlot(), component ) );
    component->AddChangedListener( ElementChangeSignature::Delegate::Create<ComponentCollection, void (ComponentCollection::*)( const Reflect::ElementChangeArgs& )> ( this, &ComponentCollection::ComponentChanged ) );
    m_Modified = true;
}
Example #5
0
ComponentCollection::ComponentCollection( const ComponentPtr& component )
{
    HELIUM_ASSERT( component->GetSlot() != NULL );

    m_Components.insert( M_Component::value_type( component->GetSlot(), component ) );
    component->e_Changed.Add( ObjectChangeSignature::Delegate::Create<ComponentCollection, void (ComponentCollection::*)( const Reflect::ObjectChangeArgs& )> ( this, &ComponentCollection::ComponentChanged ) );
    m_Modified = true;
}
gluit::Size GridTransformerRendererLayout::layout(ComponentPtr component)
{
	GridTransformerRenderer::Ptr renderer = boost::static_pointer_cast<GridTransformerRenderer>(component);

	const Rectangle& bounds = renderer->inputBounds;

	return gluit::Size::fromDouble(bounds.getWidth(), bounds.getHeight()).shrinkToFitIn(
		component->getMaximumSize().shrink(component->getInsets())).grow(component->getInsets());
}
Example #7
0
bool ComponentGroup::AddComponent(ComponentPtr comp)
{
    PROFILE(ComponentGroup_AddComponent);
    //Check if the component have already added to component group or it's name or type are different for the component group.
    if(ContainsComponent(comp) || comp->Name() != name_ || comp->TypeName() != typeName_) 
        return false;
    components_.push_back(ComponentWeakPtr(comp));
    editor_->AddNewComponent(comp);
    return true;
}
Example #8
0
ComponentPtr ComponentManager::CreateComponent(const QString &type_name, const QString &name)
{
    ComponentFactoryMap::const_iterator iter = factories_.find(type_name);
    if (iter == factories_.end())
        return ComponentPtr();

    ComponentPtr component = (*iter->second.get())();
    component->SetName(name);
    return component;
}
Example #9
0
ComponentItem::ComponentItem(const ComponentPtr &comp, EntityItem *parent) :
    QTreeWidgetItem(parent),
    parentItem(parent),
    ptr(comp),
    typeId(comp->TypeId()),
    typeName(comp->TypeName()),
    name(comp->Name())
{
    SetText(comp.get());
}
Example #10
0
void Entity::AddComponent(component_id_t id, const ComponentPtr &component, AttributeChange::Type change)
{
    // Must exist and be free
    if (component && component->ParentEntity() == 0)
    {
        if (!id)
        {
            bool authority = true;
            if (scene_)
                authority = scene_->IsAuthority();
            // Loop until we find a free ID
            for (;;)
            {
                if (authority)
                    id = component->IsReplicated() ? idGenerator_.AllocateReplicated() : idGenerator_.AllocateLocal();
                else
                    id = component->IsReplicated() ? idGenerator_.AllocateUnacked() : idGenerator_.AllocateLocal();
                if (components_.find(id) == components_.end())
                    break;
            }
        }
        else
        {
            component->SetReplicated(id < UniqueIdGenerator::FIRST_LOCAL_ID);
            // If component ID is specified manually, but it already exists, it is an error. Do not add the component in that case.
            if (components_.find(id) != components_.end())
            {
                LogError("Can not add component: a component with id " + QString::number(id) + " already exists in entity " + ToString());
                return;
            }
            // Whenever a manual replicated ID is assigned, reset the ID generator to the highest value to avoid unnecessary free ID probing in the future
            if (id < UniqueIdGenerator::FIRST_LOCAL_ID)
                idGenerator_.ResetReplicatedId(std::max(id, idGenerator_.id));
        }
        
        QString componentTypeName = component->TypeName();
        componentTypeName.replace(0, 3, "");
        componentTypeName = componentTypeName.toLower();
        // We already have 'name' property in Entity, so ignore "EC_Name" ("name") here.
        if (componentTypeName != "name" && !property(componentTypeName.toStdString().c_str()).isValid())
        {
            QVariant var = QVariant::fromValue<QObject*>(component.get());
            setProperty(componentTypeName.toStdString().c_str(), var);
        }
        
        component->SetNewId(id);
        component->SetParentEntity(this);
        components_[id] = component;
        
        if (change != AttributeChange::Disconnected)
            emit ComponentAdded(component.get(), change == AttributeChange::Default ? component->UpdateMode() : change);
        if (scene_)
            scene_->EmitComponentAdded(this, component.get(), change);
    }
}
bool ComponentCollection::ValidateCompatible( const ComponentPtr& component, tstring& error ) const
{
    HELIUM_ASSERT( component->GetSlot() != Reflect::ReservedTypes::Invalid );

    if ( component->GetComponentBehavior() == ComponentBehaviors::Exclusive )
    {
        error = component->GetClass()->m_UIName + TXT( " cannot be added to a(n) " ) + GetClass()->m_UIName + TXT( " because it is an exclusive component." );
        return false;
    }

    return true;
}
Example #12
0
bool ComponentGroup::ContainsAttribute(const QString &name) const
{
    if(components_.empty())
        return false;

    for(uint i = 0; i < components_.size(); i++)
    {
        ComponentPtr comp = components_[i].lock();
        if(comp && comp->GetAttribute(name))
            return true;
    }
    return false;
}
Example #13
0
ComponentGroup::ComponentGroup(ComponentPtr component, ECComponentEditor *editor, bool isDynamic):
    editor_(editor),
    isDynamic_(isDynamic)
{
    assert(component);
    // No point to add component to editor cause it's already added in ECBrowser's AddNewComponentToGroup mehtod.
    if(component)
    {
        components_.push_back(ComponentWeakPtr(component));
        name_ = component->Name();
        typeName_ = component->TypeName();
    }
}
Example #14
0
bool ComponentCollection::ValidateCompatible( const ComponentPtr& component, std::string& error ) const
{
    HELIUM_ASSERT( component->GetSlot() != NULL );

    if ( component->GetComponentBehavior() == ComponentBehaviors::Exclusive )
    {
        error = *component->GetMetaClass()->m_Name;
        error += TXT( " cannot be added to a(n) " );
        error += *GetMetaClass()->m_Name;
        error += TXT( " because it is an exclusive component." );
        return false;
    }

    return true;
}
Example #15
0
void Entity::RemoveComponent(const ComponentPtr &component, AttributeChange::Type change)
{
    if (component)
    {
        ComponentMap::iterator iter = components_.find(component->Id());
        if (iter != components_.end())
        {
            RemoveComponent(iter, change);
        }
        else
        {
            LogWarning("Failed to remove component: " + component->TypeName() + " from entity: " + QString::number(Id()));
        }
    }
}
Example #16
0
bool ComponentCollection::ValidatePersistent( const ComponentPtr& component ) const
{
    HELIUM_ASSERT( component->GetSlot() != NULL );

    // by default, all attributes are persistent
    return true;
}
bool ExecuteComponentCallbackImpl::OnComponentExecError(const ComponentPtr& component, std::exception& ex)
{
	::InterlockedIncrement(& errors);
	std::wcout << std::endl << L"Error executing '" << component->id << L"' (" << component->GetDisplayName() << L"):"
		<< DVLib::string2wstring(ex.what());
	return true;
}
bool ComponentCollection::ValidatePersistent( const ComponentPtr& component ) const
{
    HELIUM_ASSERT( component->GetSlot() != Reflect::ReservedTypes::Invalid );

    // by default, all attributes are persistent
    return true;
}
Example #19
0
bool Entity::removeComponent(const ComponentPtr& component)
{
	if (!component) return false;
	
	Class* type = component->getType();

    ComponentMap::Iterator it = componentsMap.Find(type);
	
    if( it == componentsMap.End() )
		return false;

    componentsMap.Erase(it);

	onComponentRemoved(component);
	sendEvents();

	if (IsGroup(parent))
	{
		Group* group = (Group*) parent;
		group->onEntityComponentRemoved(component);
	}

	if (type->inherits(GeometryGetType()))
		getTransform()->markBoundingVolumeDirty();

	return true;
}
Example #20
0
	void Entity::AddComponent(ComponentPtr _pComponent)
	{
		const Key uSignature = _pComponent->GetSignature();
		if (m_mComponents.end() == m_mComponents.find(uSignature))
		{
			m_mComponents[uSignature] = _pComponent;
		}
	}
Example #21
0
	void CLRenderWorld::OnActivation(const ComponentPtr& component)
	{
		if (component->GetType() == "CLSprite")
		{
			auto sprite = boost::dynamic_pointer_cast<CLSprite>(component);
			if (sprite)
			{
				FSN_ASSERT(std::find(m_Drawables.begin(), m_Drawables.end(), sprite) == m_Drawables.end());
				m_Drawables.push_back(sprite);
				m_Sprites.push_back(sprite);
			}
		}
		if (component->GetType() == "StreamingCamera")
		{
			if (auto camComponent = boost::dynamic_pointer_cast<StreamingCamera>(component))
			{
				const bool shared = camComponent->GetSyncType() == ICamera::Shared;
				const bool synced = camComponent->GetParent()->IsSyncedEntity();

				if (synced)
				{
					// Shared cameras have no owner
					const PlayerID owner = shared ? 0 : camComponent->GetParent()->GetOwnerID();
					camComponent->m_Camera = m_CameraManager->GetCamera(camComponent->GetParent()->GetID(), owner);
				}
				else
				{
					// Attached to a pseudo-entity: create an un-synchronised camera
					camComponent->m_Camera = std::make_shared<Camera>();
					// Unsynchronised cameras are only useful for creating viewports at the moment
					SendToConsole("Warning: unsynchronised camera created: cameras attached to unsynchronised entities won't cause the map to load.");
				}

				if (shared || PlayerRegistry::IsLocal(camComponent->GetParent()->GetOwnerID()) || !synced)
				{
					if (camComponent->m_ViewportEnabled)
					{
						camComponent->m_Viewport = std::make_shared<Viewport>(camComponent->m_ViewportRect, camComponent->m_Camera);
						AddViewport(camComponent->m_Viewport);
					}
				}
				m_Cameras.push_back(camComponent);
			}
		}
	}
Example #22
0
QScriptValue toScriptValueComponentVector(QScriptEngine *engine, const Entity::ComponentVector &components)
{
    QScriptValue obj = engine->newArray();
    Entity::ComponentVector::const_iterator iter = components.begin();
    quint32 i = 0;
    while(iter != components.end())
    {
        ComponentPtr comp = (*iter);
        if (comp.get())
        {
            obj.setProperty(i, engine->newQObject(comp.get()));
            i++;
        }
        ++iter;
    }

    return obj;
}
Example #23
0
ComponentPtr ComponentManager::CloneComponent(const ComponentPtr &component)
{
    ComponentFactoryMap::const_iterator iter = factories_.find(component->TypeName());
    if (iter == factories_.end())
        return ComponentPtr();

    ComponentPtr newComponent = (*iter->second.get())(component);
    return newComponent;
}
void ComponentCollection::CopyTo(const Reflect::ElementPtr& destination)
{
    __super::CopyTo( destination );

    ComponentCollection* destCollection = Reflect::ObjectCast< ComponentCollection >( destination );
    if ( destCollection )
    {
        // Remove all attributes, we're going to bring them over manually
        destCollection->Clear(); 

        // For each component in this component collection
        Reflect::Registry* registry = Reflect::Registry::GetInstance();
        M_Component::const_iterator attrItr = m_Components.begin();
        M_Component::const_iterator attrEnd = m_Components.end();
        for ( ; attrItr != attrEnd; ++attrItr )
        {
            // Create a new copy of the component and try to add it to the destination
            const ComponentPtr& attrib = attrItr->second;
            ComponentPtr destAttrib = Reflect::AssertCast< ComponentBase >( registry->CreateInstance( attrib->GetClass() ) );
            if ( !CopyComponentTo( *destCollection, destAttrib, attrib ) )
            {
                // Component could not be added to the destination collection, check sibling classes
                const std::set<tstring>& derived = ( registry->GetClass( attrib->GetClass()->m_Base ) )->m_Derived;
                std::set<tstring>::const_iterator derivedItr = derived.begin();
                std::set<tstring>::const_iterator derivedEnd = derived.end();
                for ( ; derivedItr != derivedEnd; ++derivedItr )
                {
                    const Reflect::Class* currentType = Reflect::Registry::GetInstance()->GetClass(*derivedItr);
                    if ( currentType->m_TypeID != attrib->GetType() )
                    {
                        destAttrib = Reflect::AssertCast< ComponentBase >( registry->CreateInstance( currentType ) );
                        if ( destAttrib.ReferencesObject() )
                        {
                            if ( CopyComponentTo( *destCollection, destAttrib, attrib ) )
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #25
0
bool ComponentCollection::SetComponent(const ComponentPtr& component, bool validate, std::string* error )
{
    HELIUM_ASSERT( component->GetSlot() != NULL );

    M_Component::const_iterator found = m_Components.find( component->GetSlot() );
    if (found != m_Components.end() && found->second == component)
    {
        return true; // nothing to do, this is already in the collection
    }

    std::string errorMessage;
    if ( validate && !ValidateComponent( component, errorMessage ) )
    {
        if ( error )
        {
            std::string componentName;
            Helium::ConvertString( component->GetMetaClass()->m_Name, componentName );

            std::string collectionName;
            Helium::ConvertString( GetMetaClass()->m_Name, collectionName );

            *error = std::string( TXT( "Component '" ) ) + componentName + TXT( "' is not valid for collection '" ) + collectionName + TXT( "': " ) + errorMessage;
        }

        return false;
    }

    // Event args
    ComponentCollectionChanged args ( this, component );

    // Set the component and connect the collection
    m_Components[ component->GetSlot() ] = component;
    component->SetCollection( this );

    // Start caring about change to the component
    component->e_Changed.Add( ObjectChangeSignature::Delegate::Create<ComponentCollection, void (ComponentCollection::*)( const Reflect::ObjectChangeArgs& )> ( this, &ComponentCollection::ComponentChanged ) );

    // Raise event
    m_Modified = true;
    m_ComponentAdded.Raise( args );
    return true;
}
Example #26
0
bool ComponentGroup::ContainsComponent(ComponentPtr component) const
{
    for(uint i = 0; i < components_.size(); i++)
    {
        if(components_[i].expired())
            continue;
        if(components_[i].lock().get() == component.get())
            return true;
    }
    return false;
}
Example #27
0
 void
 I18nContext::addChild(const ComponentPtr theChild) {
     Container::addChild(theChild);
     I18nItemPtr myChild = boost::dynamic_pointer_cast<I18nItem>(theChild);
     if (!myChild) {
         throw I18nItemNotFoundException("adding child " + theChild->getName() + " to I18nContext " + getName() + " does not work because theChild is not an I18nItem", PLUS_FILE_LINE);
     }
     if (language_ != NO_LANGUAGE) {
         myChild->switchLanguage(language_);
     }
 }
Example #28
0
void EC_Mesh::SetPlaceable(ComponentPtr placeable)
{
    if (placeable && !dynamic_cast<EC_Placeable*>(placeable.get()))
    {
        LogError("Attempted to set placeable which is not " + EC_Placeable::TypeNameStatic());
        return;
    }
    
    DetachEntity();
    placeable_ = placeable;
    AttachEntity();
}
Example #29
0
void Actor::AddComponent(ComponentPtr component, Component::UpdateType update)
{
	component->Register();
	if (update == Component::PostTick)
	{
		mPostTickComponents.emplace(component);
	}
	else
	{
		mPreTickComponents.emplace(component);
	}
}
Example #30
0
void InstallerWindow::AddComponent(const ComponentPtr& component)
{
	htmlayout::dom::element opt = htmlayout::dom::element::create("widget", component->description.c_str());
	opt["type"] = L"checkbox";
	opt["id"] = component->id.GetValue().c_str();
	opt["component_ptr"] = DVLib::towstring(get(component)).c_str();
	if (component->checked) opt["checked"] = L"true";
	if (component->disabled) opt["disabled"] = L"true";
	opt["installed"] = (component->installed ? L"true" : L"false");
	opt["required"] = (component->IsRequired() ? L"true" : L"false");
	htmlayout::queue::push(new html_insert_task(& components, opt, html_insert_task::last), HtmlWindow::s_hwnd);
}