Esempio n. 1
0
std::string BaseLink::CreateStringPath(Base* dest, Base* from)
{
    if (!dest || dest == from) return std::string("[]");
    BaseObject* o = dest->toBaseObject();
    BaseObject* f = from->toBaseObject();
    BaseContext* ctx = from->toBaseContext();
    if (!ctx && f) ctx = f->getContext();
    if (o)
    {
        std::string objectPath = o->getName();
        BaseObject* master = o->getMaster();
        while (master)
        {
            objectPath = master->getName() + std::string("/") + objectPath;
            master = master->getMaster();
        }
        BaseNode* n = o->getContext()->toBaseNode();
        if (f && o->getContext() == ctx)
            return objectPath;
        else if (n)
            return n->getPathName() + std::string("/") + objectPath; // TODO: compute relative path
        else
            return objectPath; // we could not determine destination path, specifying simply its name might be enough to find it back
    }
    else // dest is a context
    {
        if (f && ctx == dest)
            return std::string("./");
        BaseNode* n = dest->toBaseNode();
        if (n) return n->getPathName(); // TODO: compute relative path
        else return dest->getName(); // we could not determine destination path, specifying simply its name might be enough to find it back
    }
}
Esempio n. 2
0
/// Traverse the item tree and retrive the item that are expanded. The path of the node
/// that are expanded are stored in the the pathes std::vector::std::string>.
void QSofaListView::getExpandedNodes(QTreeWidgetItem* item, std::vector<std::string>& pathes)
{
    if(!item)
        return;

    /// We have reached a leaf of the hierarchy or it is closed...so we save the path
    if( !item->isExpanded() && graphListener_->findObject(item)->toBaseNode() != nullptr )
        return;

    BaseNode* parentNode = graphListener_->findObject(item)->toBaseNode() ;
    if(parentNode == nullptr)
        return;

    std::string path = parentNode->getPathName();
    pathes.push_back(path);

    for(int i=0 ; i<item->childCount() ; i++)
    {
        QTreeWidgetItem* child = item->child(i);
        BaseNode* childNode = graphListener_->findObject(child)->toBaseNode() ;

        if(childNode==nullptr)
            continue;

        if( childNode->getParents()[0] == parentNode )
            getExpandedNodes(child, pathes) ;
    }

    return ;
}
bool BaseMultiMappingElement::initNode()
{
    using namespace core::objectmodel;
    using namespace core;
    bool result = ObjectElement::initNode();


    if( result )
    {

        BaseMapping* multimapping = this->getTypedObject()->toBaseMapping();
        NodeElement* currentNodeElement = dynamic_cast<NodeElement *>(getParent());
        simulation::Node* currentNode =  dynamic_cast<simulation::Node* >( currentNodeElement->getTypedObject() );
        helper::vector<core::BaseState*> inputStates  = multimapping->getFrom();
        helper::vector<core::BaseState*> outputStates = multimapping->getTo();


        helper::vector<core::BaseState*>::iterator iterState;
        helper::vector<simulation::Node*> inputNodes, outputNodes;

        /* get the Nodes corresponding to each input BaseState context */
        for( iterState = inputStates.begin();  iterState != inputStates.end(); ++iterState)
        {
            simulation::Node* node = dynamic_cast< simulation::Node* >((*iterState)->getContext());
            inputNodes.push_back(node);
        }
        /* */
        /* get the Nodes corresponding to each output BaseState context */
        for( iterState = outputStates.begin(); iterState != outputStates.end(); ++iterState)
        {
            simulation::Node* node = dynamic_cast< simulation::Node* >((*iterState)->getContext());
            outputNodes.push_back(node);
        }

        helper::vector<simulation::Node*>::iterator iterNode;
        BaseNode* currentBaseNode;

        /* filter out inputNodes which already belong to the currentNode ancestors */
        helper::vector<simulation::Node*> otherInputNodes;
        helper::vector<simulation::Node*> ancestorInputNodes;
        iterNode = inputNodes.begin();
        currentBaseNode = currentNode;
        for( iterNode = inputNodes.begin(); iterNode != inputNodes.end(); ++iterNode)
        {
            if( !currentBaseNode->hasAncestor(*iterNode) )
            {
                otherInputNodes.push_back(*iterNode);
            }
            else
            {
                ancestorInputNodes.push_back(*iterNode);
            }
        }

        updateSceneGraph(multimapping, ancestorInputNodes, otherInputNodes, outputNodes );

    }

    return result;
}
Esempio n. 4
0
Error BaseContext::removeUnreachableCode() {
  PodList<BaseNode*>::Link* link = _unreachableList.getFirst();
  BaseNode* stop = getStop();

  while (link != NULL) {
    BaseNode* node = link->getValue();
    if (node != NULL && node->getPrev() != NULL) {
      // Locate all unreachable nodes.
      BaseNode* first = node;
      do {
        if (node->isFetched())
          break;
        node = node->getNext();
      } while (node != stop);

      // Remove.
      if (node != first) {
        BaseNode* last = (node != NULL) ? node->getPrev() : getCompiler()->getLastNode();
        getCompiler()->removeNodes(first, last);
      }
    }

    link = link->getNext();
  }

  return kErrorOk;
}
Esempio n. 5
0
State BehaviorTree::tick(Value* target, Blackboard* blackBoard, float deltaTime) {
//    m_tick->reset();
    m_tick->setTarget(target);
    m_tick->setBlackBoard(blackBoard);
    m_tick->setTree(this);
    m_tick->setDeltaTime(deltaTime);

    State ret = this->m_root->_execute(m_tick);

    std::vector<Value>& lastOpenNodes = blackBoard->get("openNodes", this->getId()).asVector();
    std::vector<Value>& curOpenNodes = m_tick->getOpenNodes();

    int start = 0;
    int length = lastOpenNodes.size() < curOpenNodes.size() ? (int)lastOpenNodes.size() : (int)curOpenNodes.size();

    for(int i = 0; i < length; i++) {
        start = i + 1;
        if(lastOpenNodes[i] != curOpenNodes[i])
            break;
    }

    for(int i = (int)lastOpenNodes.size() - 1; i >= start; i--) {
        BaseNode* baseNode = (BaseNode*)lastOpenNodes[i].asObject();
        baseNode->_close(m_tick);
    }

    blackBoard->set("openNodes", Value(curOpenNodes), this->getId());

    return ret;
}
Esempio n. 6
0
/*! Returns a new copy of the prototype specified by prototype_id.
  The id must be valid. Functions should use the id
  returned by registerPrototype.
*/
BaseNode *NodeFactory::produce(int prototype_id) {
  assert(prototype_id >= 0);
  assert(prototype_id < static_cast<int>(prototypes.size()));
  BaseNode* clone = prototypes.at(prototype_id)->clone();
  // qDebug(qPrintable(id.toString()));
  clone->setId(QUuid::createUuid());
  return clone;
}
Esempio n. 7
0
/*! Slot. Removes the currently selected node. If the node is
    an object, it also removes all connections connected to that
    node.
*/
void Document::removeObject() {
  assert(indexOfSelectedObject >= -1);
  assert(indexOfSelectedObject < static_cast<int>(nodes.size()));

  if (indexOfSelectedObject != -1) {
    BaseNode* obj = nodes.at(indexOfSelectedObject);
    if (obj->isConnector() == false) {
      // erase all the connected connectionnodes
      // get the list of connected nodes, which are all connections
      std::list<BaseNode*> objs;
      objs = obj->getConnectedNodes();

      // iterator through that list and delete the connection nodes
      // as well as remove the pointers to this node from all objects
      // that are connected to the connection node
      std::list<BaseNode*>::iterator it;
      for (it = objs.begin(); it != objs.end(); ++it) {
        // for each of the objects that are connected to this connection,
        std::list<BaseNode*> secondaryObject;
        std::list<BaseNode*>::iterator it2;
        for (it2 = secondaryObject.begin(); it2 != secondaryObject.end(); ++it) {  // NOLINT
          // remove the connection back to the connectionode we are deleting
          (*it2)->removeConnectedNode(*it);
        }

        // delete this connection node
        for (int i = 0; i < static_cast<int>(nodes.size()); i++) {
          if (nodes.at(i) == (*it)) {
            removeFromOrdering(i);
            nodes.erase(nodes.begin()+i);
          }
        }
      }
      // now actually erase the object
      removeFromOrdering(indexOfSelectedObject);
      nodes.erase(nodes.begin()+indexOfSelectedObject);
    } else {
      // get the list of connected objects (should only be two objects)
      std::list<BaseNode*> secondaryObjects;
      secondaryObjects = obj->getConnectedNodes();

      // iterate through the list and disconnect the connectionnode we
      // are deleting from the objects.
      std::list<BaseNode*>::iterator it;  // NOLINT
      for (it = secondaryObjects.begin(); it != secondaryObjects.end(); ++it) {
        (*it)->removeConnectedNode(obj);
      }

      // now delete the actual nodecount
      removeFromOrdering(indexOfSelectedObject);
      nodes.erase(nodes.begin()+indexOfSelectedObject);
    }
  }
  setModified(true);
  indexOfSelectedObject = -1;
  emit modelChanged();
}
Esempio n. 8
0
 void BVHN<N>::clearBarrier(NodeRef& node)
 {
   if (node.isBarrier())
     node.clearBarrier();
   else if (!node.isLeaf()) {
     BaseNode* n = node.baseNode(BVH_FLAG_ALIGNED_NODE); // FIXME: flags should be stored in BVH
     for (size_t c=0; c<N; c++)
       clearBarrier(n->child(c));
   }
 }
Esempio n. 9
0
void Noun::detachSelf()
{
	BaseNode * pParent = parent();
	if ( pParent != NULL )
	{
		pParent->detachNodeSwap( this );
	}
	else
	{
		TRACE( "Noun::detachSelf() - NULL parent!" );
	}
}
Esempio n. 10
0
	Status MaxTime::process(Tick& tick)
	{
		float elapsedTime = tick.tree.getElapsedTime(actionId);

		BaseNode* node = tick.tree.actionManager.getActionById(child);
		// CCAssert(node != nullptr)
		Status status = node->execute(tick);
		if (elapsedTime > maxDelay)
		{
			return Status::Failure;
		}

		return status;
	}
Esempio n. 11
0
/*! Returns a new copy of the prototype specified by name, or
  null if the name isn't valid.
*/
BaseNode *NodeFactory::produceFromClassName(QString name)
{
  std::vector<BaseNode*>::iterator it;
  BaseNode* clone;

  for (it=prototypes.begin(); it < prototypes.end(); it++) {
    if ((*it)->metaObject()->className() == name) {
      clone = (*it)->clone();
      clone->setId(QUuid::createUuid());
      return clone;
    }
  }
  qDebug("Error: couldn't produce class");
  return 0;
}
Esempio n. 12
0
void Noun::setWorldFrame( const Matrix33 & frame )
{
	m_WorldFrame = frame;
	Matrix33 localFrame( frame );

	BaseNode * pBaseNode = parent();
	while( pBaseNode != NULL )
	{
		NodeTransform * pNode = WidgetCast<NodeTransform>( pBaseNode );
		if ( pNode != NULL )
			localFrame = pNode->frame() * localFrame;

		pBaseNode = pBaseNode->parent();
	}

	setFrame( localFrame );
}
Esempio n. 13
0
void Noun::setWorldPosition( const Vector3 & position )
{
	// convert the world position into a local position by enumerating all parent nodes
	m_WorldPosition = position;
	Vector3 localPosition( position );

	BaseNode * pBaseNode = parent();
	while( pBaseNode != NULL )
	{
		NodeTransform * pNode = WidgetCast<NodeTransform>( pBaseNode );
		if ( pNode != NULL )
			localPosition = pNode->frame() * (localPosition - pNode->position());

		pBaseNode = pBaseNode->parent();
	}

	setPosition( localPosition );
}
Esempio n. 14
0
void Noun::onAttached()
{
	// call the base class
	NodeTransform::onAttached();
	// clear the detach flag, just in case a detached noun is re-attached
	m_bDetach = false;
	// get our zone
	BaseNode * pParent = parent();
	m_pZone = NULL;
	while( pParent != NULL && m_pZone == NULL )
	{
		m_pZone = WidgetCast<NodeZone>( pParent );
		pParent = pParent->parent();
	}

	// inform our zone that we are attached
	if ( m_pZone != NULL )
		m_pZone->onAttachNoun( this );
}
Esempio n. 15
0
BaseNode* new_node_from_tag(SBinaryTag* tag, bool skipCopy) {

  const char* tagClass = get_string_from_dict(tag, "class");
  nodeFunctionPtr createFunction = NULL;
  for (int index = 0; index < g_createFunctionsLength; index += 1) {
    SFuncLookup* entry = &g_createFunctions[index];
    if (strcmp(entry->className, tagClass) == 0) {
      createFunction = entry->createFunction;
    }
  }
  if (createFunction == NULL) {
    fprintf(stderr, "new_node_from_tag(): Couldn't find a factory function for node class '%s'\n", tagClass);
    return NULL;
  }
  BaseNode* result = createFunction(tag, skipCopy);
  const char* name = get_string_from_dict(tag, "name");
  result->setName(name);
  return result;
}
Esempio n. 16
0
unique_ptr<const BaseContainer> AdapterChain::doArchiverExtract(const BaseNode &from_node) const
{
    if (!archiver_)	throw MethodNotApplicableException("an archiver is needed but is not specified");

    InputLumpData inex = {
        from_node.ReadableData(),
        from_node.size()
        };

    typedef decltype(inex.palettes) PaletteMap;
    for (const auto dependency : archiver_->getPaletteDependencies())
    {
        inex.palettes.insert(PaletteMap::value_type(
                                                            dependency,
                                                            from_node.getDirectory()->getPalette(dependency)
                                                      )
                            );
    }

    return archiver_->extract(inex);
}
Esempio n. 17
0
Tree<T>* singlePoint(const Tree<T>* left, const Tree<T>* right) {
    auto tree = left->clone(); // Copy left

    auto treeDepth = right->getDepth();
    auto depth = utils::random_uint(treeDepth);

    auto sourceNode = right->root; // Crossover from the right to the left
    BaseNode<T>* prevSourceNode = nullptr;

    for (unsigned int i = 0; i < depth; ++i) {
        if (sourceNode->getChildren().empty()) {
            sourceNode = prevSourceNode; // Do not copy terminators
            break;
        }
        prevSourceNode = sourceNode;
        sourceNode = sourceNode->getChildren()[utils::random_uint(
            sourceNode->getChildren().size())];
    }

    auto currentNode = tree->root;
    BaseNode<T>* prevNode = nullptr;

    for (unsigned int i = 0; i < depth; ++i) {
        prevNode = currentNode;
        auto nextNodeLocation =
            utils::random_uint(currentNode->getChildren().size());
        currentNode = currentNode->getChildren()[nextNodeLocation];

        if (sourceNode->getDepth() == currentNode->getDepth()) {
            auto& children = prevNode->getChildren();
            delete currentNode;
            children[nextNodeLocation] = sourceNode->clone();
            break;
        } else if (currentNode->getChildren().empty()) {
            break; // This point should never be reached
        }
    }

    return tree;
}
Esempio n. 18
0
void BaseNode::detachAllNodes()
{
	updateVersion();
	for(size_t i=0;i<m_Children.size();i++)
	{
		BaseNode * pChild = m_Children[ i ];
		if (! pChild )
			continue;

		// inform the child it is being detached
		pChild->onDetaching();
		// inform ourselves
		onDetach( pChild );
		// set the parent pointer to NULL
		pChild->m_pParent = NULL;
	}

	m_Children.clear();

	// notify this object that a child object has been detached
	onChildDetached();
}
Esempio n. 19
0
void BaseNode::detachNodeSwap( int nChild )
{
	if ( nChild >= 0 && nChild < (int)m_Children.size() )
	{
		updateVersion();

		BaseNode * pChild = m_Children[ nChild ];
		if ( pChild != NULL )
		{
			// inform the child it is being detached
			pChild->onDetaching();
			// inform ourselves
			onDetach( pChild );
			// null the parent pointer and remove from the child list
			pChild->m_pParent = NULL;
		}

		removeSwapIndex( m_Children, nChild );
		// notify this object that a child object has been detached
		onChildDetached();
	}
}
	Status SequenceStateful::process(Tick& tick)
	{
		Status result =  Status::Success;

		size_t idx = tick.tree.getRunningChild(actionId);

		for (size_t i = idx; i < children.size(); ++i)
		{
			BaseNode* node = tick.tree.actionManager.getActionById(children[i]);
			Status status = node->execute(tick);

			if (status != Status::Success)
			{
				if (status == Status::Running)
				{
					tick.tree.setRunningChild(actionId, i);
				}
				break;
			}
		}

		return result;
	}
Esempio n. 21
0
void CSceneRender::OnCameraZoomextents() 
{
	ScenePort * pDoc = dynamic_cast<ScenePort *>( GetDocument() );
	ASSERT( pDoc );

	m_TargetPosition = Vector3(0,0,0);
	m_TargetDistance = 50.0f;

	if ( pDoc->m_pSelectedNode )
	{
		// find the world position of the selected node
		BaseNode * pBaseNode = pDoc->m_pSelectedNode->getCachedNode();
		if ( pBaseNode )
		{
			// get the hull of the selected node
			BoxHull hull( pBaseNode->hull() );

			Vector3 position( 0.0f );
			while( pBaseNode )
			{
				if ( dynamic_cast< NodeTransform * >( pBaseNode ) )
				{
					NodeTransform * pNode = (NodeTransform *)pBaseNode;
					position = (~pNode->frame() * position) + pNode->position();
				}
				pBaseNode = pBaseNode->parent();
			}

			m_TargetPosition = position;
			m_TargetDistance = hull.radius() * 2.0f;
		}
	}

	// redraw the scene
	OnUpdate(this,true,NULL);
	OnDraw(NULL);
}
Esempio n. 22
0
/*! Slot. This will create a new object at the specified position. The
  prototypeID of the new object will have been set by a previous signal
  to setNewObjectID. Uses NodeFactory.
*/
void Document::createObject(const QPoint &position) {
  assert(indexOfSelectedObject >= -1);
  assert(indexOfSelectedObject < static_cast<int>(nodes.size()));

  // testing
  int objectUnder = getIndexAt(position);
  if (objectUnder != -1) {
    setSelectedObject(position);
    return;
  }

  // create a new node using the factory
  BaseNode* newNode;
  newNode = NodeFactory::getInstance()->produce(newObjectID);
  newNode->setPosition(position);

  // add newnode to a vector of nodes.
  addNodeToList(newNode);

  // add the node to the ordering
  ordering.append(nodes.size()-1);

  // reset the selected property of previously selected node
  if (indexOfSelectedObject != -1) {
    nodes.at(indexOfSelectedObject)->setSelected(false);
  }

  // set the selected index to be the created object
  indexOfSelectedObject = nodes.size()-1;
  nodes.at(indexOfSelectedObject)->setSelected(true);

  setModified(true);
  emit modelChanged();

  this->showPropertiesDialog();
  setSelectedObject(position);
}
Esempio n. 23
0
Error BaseContext::compile(FuncNode* func) {
  BaseNode* end = func->getEnd();
  BaseNode* stop = end->getNext();

  _func = func;
  _stop = stop;
  _extraBlock = end;

  ASMJIT_PROPAGATE_ERROR(fetch());
  ASMJIT_PROPAGATE_ERROR(removeUnreachableCode());
  ASMJIT_PROPAGATE_ERROR(analyze());

  if (_compiler->hasLogger())
    ASMJIT_PROPAGATE_ERROR(annotate());

  ASMJIT_PROPAGATE_ERROR(translate());

  // We alter the compiler cursor, because it doesn't make sense to reference
  // it after compilation - some nodes may disappear and it's forbidden to add
  // new code after the compilation is done.
  _compiler->_setCursor(NULL);

  return kErrorOk;
}
Esempio n. 24
0
void WindowButton::onButtonUp()
{
	m_ButtonDown = false;
	m_Flags &= ~DEPRESSED;

	// play select sound
	selectSound();
	// post message to listeners
	postMessage( WB_BUTTONUP, StringHash( name() ), 0 );

	// abort any ButtonPopup parents
	BaseNode * pParent = parent();
	while( pParent != NULL )
	{
		ButtonPopup * pPopup = WidgetCast<ButtonPopup>( pParent );
		if ( pPopup != NULL )
		{
			pPopup->onButtonAbort();
			break;
		}
		// next parent object
		pParent = pParent->parent();
	}
}
Esempio n. 25
0
void BehaviorTree::dump() {
    if(!m_root)
        return;

    char buffer[1024];
    char space[64];
    std::stack<BaseNode*> stack;
    stack.push(m_root);

    sprintf(space, "");

    while(stack.size() > 0) {
        BaseNode* node = stack.top();
        stack.pop();

        if(node->getCategory() == COMPOSITE) {

        } else if(node->getCategory() == DECORATOR) {

        } else {
            sprintf(buffer, "%s{\n%s id:%s\n%s name:%s\n%s description:%s\n%s}\n", space, space, node->getId().c_str(), space, node->getName().c_str(), space, node->getDescription().c_str(), space);
        }
    }
}
Esempio n. 26
0
void BaseNode::detachNode( int child )
{
	ASSERT( this != NULL );

	if ( child >= 0 && child < (int)m_Children.size() )
	{
		updateVersion();

		BaseNode * pChild = m_Children[ child ];
		if ( pChild != NULL )
		{
			// inform the child it is being detached
			pChild->onDetaching();
			// inform ourselves
			onDetach( pChild );
			// null the parent pointer and remove from the child list
			pChild->m_pParent = NULL;
		}

		m_Children.erase( m_Children.begin() + child );
		// notify this object that a child object has been detached
		onChildDetached();
	}
}
Esempio n. 27
0
Asteroid* Game::SpawnAsteroid(const Vector2& position, const GameSide& side)
{
    // Main
    ObjectId objId = this->SpawnEntity();
    Asteroid* unit = new Asteroid(this, -1);
    this->addComponent(objId, unit);

    // Render Component
    BaseNode* graphic = new BaseNode(kSpriteAsteroid);    
    graphic->setPosition(position.x, position.y);  
    graphic->setScale(0.5f);
    GFGame::Components::RenderComponent* node = new GFGame::Components::RenderComponent(graphic);
    this->addComponent(objId, node);

    // Physics Component
    GFGame::Components::PhysicsComponent* physics = new GFGame::Components::PhysicsComponent();
    b2Body* body = GFort::Core::Physics::PhysicsHelper::CreateCircle(
        phys_controller_.World(),
        b2_dynamicBody,
        position,
        min(graphic->getContentSize().width, graphic->getContentSize().height) * 0.5 * graphic->getScale());
    body->SetFixedRotation(false);
    body->SetAngularDamping(0);
    body->SetAngularVelocity(10);

    // Set the dynamic body fixture.
    b2Fixture* fixture = body->GetFixtureList();	
    b2Filter filter = fixture[0].GetFilterData();
    filter.categoryBits = kCategoryBitsObstacle;
    filter.maskBits = kMaskBitsObstacle;
    fixture[0].SetFilterData(filter);

    physics->AddBody("root", body);
    graphic->SetBody(body);
    this->addComponent(objId, physics);
    unit->physics_component_ = physics;

    return unit;
    //return objId;
}
Esempio n. 28
0
/*! Opens specified file. This function does not ask the user to save an
    unsaved modified diagram. That is the MainWindow's job. This function
    will simply clear out the node vector and load the file in.
*/
void Document::openDocument(QString openName)
{
    QDomDocument* xmlDoc = openSaveFile(openName);
    QDomElement docElem = getNextDocumentElement(xmlDoc);
    QDomElement nodesVectorElement;
    QDomElement n;
    BaseNode* newNode;

    // Clear the nodes vector
    nodes.clear();
    ordering.clear();

    // Get the diagram type
    diagramType = static_cast<BaseNode::DiagramType>(docElem.attribute("diagramType").toInt());

    // First get out the first (and hopefully only) nodes_vector_element.
    nodesVectorElement = docElem.firstChildElement("nodes_vector_element");

    // Now we have to iterate over all the Node elements and restor them.
    // This style of iteration loop was taken from the Qt documentation for
    // QDomElement.
    n = nodesVectorElement.firstChildElement("Node");
    for (; !n.isNull(); n = n.nextSiblingElement("Node")) {
      // Now that we have the QDomElement, try to produce the node
      newNode = NodeFactory::getInstance()->produceFromClassName(n.attribute("class_name"));

      // Check we failed
      if (newNode == 0) {
        qDebug() << "Document::openDocument Error: Couldn't produce a " << n.attribute("class_name") << " with the node factory.";
      } else {
        // Restore the unique id and all the properties
        newNode->from_xml(n);

        // Push the node onto the node vector
        nodes.push_back(newNode);
        ordering.push_back(nodes.size()-1);
      }
    }

    // Now that we have all the id's restored, we can restore the connections
    // between the nodes. We loop over all the Node elements in
    // node_vector_element and loop over all the ConnectedObject elements in
    // each Node.
    n = nodesVectorElement.firstChildElement("Node");
    for (; !n.isNull(); n = n.nextSiblingElement("Node")) {
      BaseNode* sourcenode;
      QUuid sourceid;

      // Find the node that we created earlier from this element
      sourceid = QUuid(n.attribute("Id"));
      sourcenode = this->findNodeById(sourceid);

      if (sourcenode == 0) {
        qDebug() << "Document::openDocument Error: Couldn't find source node by id";
      } else {
        QUuid targetid;
        BaseNode* targetnode;

        // Now that we have the element and it's associated node, iterate
        // over all of the element's children ("ConnectedObjects")
        QDomElement child = n.firstChildElement("ConnectedObject");
        for (; !child.isNull(); child = child.nextSiblingElement("ConnectedObject")) {
          // Find the targeted node by id
          targetid = QUuid(child.attribute("id"));
          targetnode = this->findNodeById(targetid);

          // Check if it failed
          if (targetnode == 0) {
            qDebug() << "Document::openDocument Error: Couldn't find a target node by id";
          } else {
            // If it didn't fail, add the connection!
            sourcenode->addConnectedNode(targetnode);
          }
        }
      }
    }

    setFilename(openName);
    setModified(false);
    update();
}
Esempio n. 29
0
/*! Slot. Sets the second point in a new connection node.
  This function actually creates the node using the NodeFactory.
  It doesn't create the node if the first or second point is invalid.
*/
void Document::createConnectionPoint2(const QPoint &point) {
  // Create the object only if a valid first object was found
  int index;
  // creates a temp object node for self connectors
  BaseNode *tempnode;
  tempnode = NodeFactory::getInstance()->produce(newObjectID);

  if (firstConnectionIndex != -1) {
    index = getIndexAt(point);
    // And the second index was found
    if (((index != -1) &&
         (nodes.at(index)->isConnector() == false)) &&
            index != firstConnectionIndex) {
      // produce the object
      BaseNode *newNode;
      newNode = NodeFactory::getInstance()->produce(newObjectID);

      // now connect the connection to both objects, and connect the
      // objects to the connections
      newNode->addConnectedNode(nodes.at(firstConnectionIndex));
      newNode->addConnectedNode(nodes.at(index));
      nodes.at(firstConnectionIndex)->addConnectedNode(newNode);
      nodes.at(index)->addConnectedNode(newNode);

      addNodeToList(newNode);
      ordering.append(nodes.size()-1);

      nodes.at(index)->setSelectedForConnectionPoint(false);

      setModified(true);
      emit modelChanged();
    }
    //  Self connectors
    // And the second index was found
    else if ((((index != -1) &&
         (nodes.at(index)->isConnector() == false)) &&
            (index == firstConnectionIndex) &&
              (tempnode->getText() == "Collaboration Self Line")) ||
             ((index != -1) && (nodes.at(index)->isConnector() == false)
             &&(index == firstConnectionIndex) && (tempnode->getText() == "State Self Line"))) {

        // produce the object
      BaseNode *newNode;
      newNode = NodeFactory::getInstance()->produce(newObjectID);

      // now connect the connection to both objects, and connect the
      // objects to the connections
      newNode->addConnectedNode(nodes.at(firstConnectionIndex));
      newNode->addConnectedNode(nodes.at(index));
      nodes.at(firstConnectionIndex)->addConnectedNode(newNode);
      nodes.at(index)->addConnectedNode(newNode);

      addNodeToList(newNode);
      ordering.append(nodes.size()-1);

      nodes.at(index)->setSelectedForConnectionPoint(false);

      setModified(true);
      emit modelChanged();
    }
// end of  self connect
    else {
      QMessageBox::information(0, "pUML", "No second object selected");
    }
  }

  if (firstConnectionIndex != -1) {
    nodes.at(firstConnectionIndex)->setSelectedForConnectionPoint(false);
  }
}
Esempio n. 30
0
int main(void){
	int i, j, tmp;
	const int size = 10;
	vector<int>::iterator vi;
	Address a;
	TKey ans;
	BaseNode *p = NULL;
	int data[size] = {5, 2, 7, 1, 9, 4, 0, 6, 3, 8};
	vector<int> v(data, data+size);
	vector<int> vn;
	time_t t_start, t_end;

	// Initialize
	for(i = 0; i < BlockNum; i++)
		blockUsed[i] = false;
	for(i = 0; i < IndexNum; i++)
		indexRootBlockId[i] = -1;
	for(i = 0; i < IndexNum; i++)
		indexDataBlockId[i] = -1;
	for(i = 0; i < IndexNum; i++)
		indexType[i] = TYPE_INT;
	
	for(i = 0; i < DATA_NUM; i++)
		vn.push_back(i);
	srand((unsigned int)time(0));
	for(i = 0; i < DATA_NUM; i++){
		j = rand() % DATA_NUM;
		tmp = vn.at(j);
		vn.erase(vn.begin() + j);
		vn.push_back(tmp);
	}
	/*for(i = 0; i < DATA_NUM; i++){
		cout << vn.at(i) << ' ';
	}
	system("pause");
	return 0;*/

	// test
	try{
		cout << "----------------insert " << DATA_NUM << " numbers----------------------" << endl;
		time(&t_start);
		//for(i = 0; i < 15; i++){
		//for(i = DATA_NUM; i >= 0; i--){
		for(vi = vn.begin(); vi != vn.end(); vi++){
			i = *vi;
			if(!(i % (DATA_NUM / PRINT_NUM)))
				cout << "-------------insert " << i << "---------------" << endl;
			try{
				a = InsertIndex(0, 0, TKey(i));
			}
			catch(ErKeyNotFound &e){
				cout << e.what() << e.key() << endl;
			}
			catch(DbEr &e){
				cout << e.what() << endl;
			}
			//p = (BaseNode *)GetBlock(a.blockId);

			//cout << "Insert Data Block: " << a.blockId << endl;

			//p->data[a.offset] = i;

			//PrintIndex(GetRootBlockId(0), p);
			//PrintCatalog();
		}
		time(&t_end);
		cout << "Run time for insert " << DATA_NUM << " data: " << t_end - t_start << "s" << endl;
		//PrintData(0, p);
		//PrintIndex(GetRootBlockId(0), p);

		cout << "----------------query " << DATA_NUM << " numbers----------------------" << endl;
		time(&t_start);
		//for(i = 0; i <= DATA_NUM; i++){
		for(vi = vn.begin(); vi != vn.end(); vi++){
			i = *vi;
			if(!(i % (DATA_NUM / PRINT_NUM)))
				cout << "-------------query " << i << "----------------" << endl;
			try{
				a = FindIndex(0, 0, TKey(i));
				p = (BaseNode *)GetBlock(a.blockId);
				ans = TKey(p->Key(a.offset), p->type);
				if(ans.iKey != i){
					throw ErKeyNotFound(TKey(i));
				}
			}
			catch(ErKeyNotFound &e){
				cout << e.what() << e.key() << endl;
			}
			catch(DbEr &e){
				cout << e.what() << endl;
			}

			//PrintIndex(GetRootBlockId(0), p);
			//PrintCatalog();
		}
		time(&t_end);
		cout << "Run time for query " << DATA_NUM << " data: " << t_end - t_start << "s" << endl;
		PrintCatalog();

		cout << "----------------delete " << DATA_NUM << " numbers----------------------" << endl;
		time(&t_start);
		//for(i = 0; i <= DATA_NUM; i++){
		for(vi = vn.begin(); vi != vn.end(); vi++){
			i = *vi;
			if(!(i % (DATA_NUM / PRINT_NUM)))
				cout << "-------------delete " << i << "---------------" << endl;
			try{
				DeleteIndex(0, 0, TKey(i));
			}
			catch(ErKeyNotFound &e){
				cout << e.what() << e.key() << endl;
			}
			catch(DbEr &e){
				cout << e.what() << endl;
			}

			//PrintIndex(GetRootBlockId(0), p);
			//PrintData(GetDataBlockId(0), p);
			//PrintCatalog();
		}
		time(&t_end);
		cout << "Run time for delete " << DATA_NUM << " data: " << t_end - t_start << "s" << endl;

		PrintData(GetDataBlockId(0), p);
		DropIndex(0, 0);
		PrintCatalog();
		/*for(i = 0; i < 15; i++){
			a = FindIndex(0, i);
			cout << "Find \"" << i << "\" in offset " << a.offset
				<< " of Block " << a.blockId << endl;
		}*/
	}
	catch(ErKeyNotFound &e){
		cout << e.what() << e.key() << endl;
	}
	catch(DbEr &e){
		cout << e.what() << endl;
	}

	system("pause");
}