Example #1
0
void FullMasterCM::addSlave( Command& command, NodeMapObjectReplyPacket& reply )
{
    EQ_TS_THREAD( _cmdThread );
    EQASSERT( command->type == PACKETTYPE_CO_NODE );
    EQASSERT( command->command == CMD_NODE_MAP_OBJECT );

    NodePtr node = command.getNode();
    const NodeMapObjectPacket* packet = command.get< NodeMapObjectPacket >();
    const uint128_t requested  = packet->requestedVersion;
    const uint32_t instanceID = packet->instanceID;

    Mutex mutex( _slaves );
    EQASSERT( _version != VERSION_NONE );
    _checkConsistency();

    // add to subscribers
    ++_slavesCount[ node->getNodeID() ];
    _slaves->push_back( node );
    stde::usort( *_slaves );

    if( requested == VERSION_NONE ) // no data to send
    {
        _sendEmptyVersion( node, instanceID, _version );
        reply.version = _version;
        return;
    }

    const uint128_t oldest = _instanceDatas.front()->os.getVersion();
    uint128_t start = (requested == VERSION_OLDEST || requested < oldest ) ?
                          oldest : requested;
    uint128_t end = _version;
    const bool useCache = packet->masterInstanceID == _object->getInstanceID();

#ifndef NDEBUG
    if( requested != VERSION_OLDEST && requested < start )
        EQINFO << "Mapping version " << start
               << " instead of requested version " << requested << std::endl;
#endif

    reply.version = start;
    reply.useCache = packet->useCache && useCache;

    if( reply.useCache )
    {
        if( packet->minCachedVersion <= start && 
            packet->maxCachedVersion >= start )
        {
#ifdef EQ_INSTRUMENT_MULTICAST
            _hit += packet->maxCachedVersion + 1 - start;
#endif
            start = packet->maxCachedVersion + 1;
        }
        else if( packet->maxCachedVersion == end )
        {
            end = EQ_MAX( start, packet->minCachedVersion - 1 );
#ifdef EQ_INSTRUMENT_MULTICAST
            _hit += _version - end;
#endif
        }
        // TODO else cached block in the middle, send head and tail elements
    }

#if 0
    EQLOG( LOG_OBJECTS )
        << *_object << ", instantiate on " << node->getNodeID() << " with v"
        << ((requested == VERSION_OLDEST) ? oldest : requested) << " ("
        << requested << ") sending " << start << ".." << end << " have "
        << _version - _nVersions << ".." << _version << " "
        << _instanceDatas.size() << std::endl;
#endif
    EQASSERT( start >= oldest );

    // send all instance datas from start..end
    InstanceDataDeque::iterator i = _instanceDatas.begin();
    while( i != _instanceDatas.end() && (*i)->os.getVersion() < start )
        ++i;

    for( ; i != _instanceDatas.end() && (*i)->os.getVersion() <= end; ++i )
    {
        InstanceData* data = *i;
        EQASSERT( data );
        data->os.sendMapData( node, instanceID );

#ifdef EQ_INSTRUMENT_MULTICAST
        ++_miss;
#endif
    }

#ifdef EQ_INSTRUMENT_MULTICAST
    if( _miss % 100 == 0 )
        EQINFO << "Cached " << _hit << "/" << _hit + _miss
               << " instance data transmissions" << std::endl;
#endif
}
Example #2
0
        Path get_shorten_path(GameMap &gmap, const NodePtr &src, const NodePtr &dest)
        {
            OpenSet open_set;
            CloseSet closed_set;
            Path _tmpPath;
            bool found = false;
            NodePtr cur_node;
            NodePtr next_node;
            NodesMap nodes_map;

            // add to OPEN_SET
            open_set.insert(make_pair<unsigned long, Coordinate>(src->get_f(),src->get_coordinate()));
            nodes_map.insert(make_pair<Coordinate,NodePtr>(src->get_coordinate(), src));

            while (!open_set.empty() && !found)
            {
                cur_node = nodes_map[open_set.begin()->second];

                closed_set.insert(cur_node->get_coordinate());
                open_set.erase(find_if(open_set.begin(), open_set.end(),\
                                       boost::lambda::bind(&OpenSet::value_type::second,boost::lambda::_1) == \
                                       cur_node->get_coordinate()));

                if (cur_node->get_coordinate() == dest->get_coordinate())
                {
                    // arrived
                    found = true;
                    // re-path;
                    NodePtr _res_tmp = cur_node;
                    while (_res_tmp != NULL)
                    {
                        _tmpPath.push_front(_res_tmp);
                        _res_tmp = _res_tmp->get_parent();
                    }
                    break;
                    // open_set
                }

                AdjNodes adjnode_set = gmap.get_adjnodes(cur_node->get_coordinate());
                AdjNodes::iterator it = adjnode_set.begin();
                for (; it != adjnode_set.end(); ++it)
                {
                    // can't get through, like wall;
                    // already in closed set;
                    // ignore it;
                    if (!gmap.can_get_through(*it) || \
                        closed_set.count(*it) != 0)
                    {
                        continue;
                    }

                    unsigned long new_g = cur_node->get_g() + gmap.get_steps(*it);
                    bool better = false;
                    OpenSet::iterator fit = find_if(open_set.begin(), open_set.end(), 
                        boost::lambda::bind(&OpenSet::value_type::second,\
                        boost::lambda::_1)== (*it)); 
                    if (fit == open_set.end())
                    {
                        better = true;
                    }
                    else
                    {
                        if (new_g < nodes_map[fit->second]->get_g())
                        {
                            better = true;
                        }
                    }

                    if (better)
                    {
                        NodePtr _tmp(new Node(*it));

                        _tmp->set_g(new_g);
                        _tmp->set_f(gmap.get_distance(*it, dest->get_coordinate()));
                        _tmp->set_parent(cur_node);
                        open_set.insert(make_pair<unsigned long,Coordinate>(_tmp->get_f(),*it));

                        // update 
                        nodes_map[*it] = _tmp;
                    }
                } // for

            } // while

            return _tmpPath;
        }
Example #3
0
void
GuiAppInstance::createNodeGui(const NodePtr &node,
                              const NodePtr& parentMultiInstance,
                              const CreateNodeArgs& args)
{
    NodeCollectionPtr group = node->getGroup();
    NodeGraph* graph;

    if (group) {
        NodeGraphI* graph_i = group->getNodeGraph();
        assert(graph_i);
        graph = dynamic_cast<NodeGraph*>(graph_i);
        assert(graph);
    } else {
        graph = _imp->_gui->getNodeGraph();
    }
    if (!graph) {
        throw std::logic_error("");
    }

    NodesGuiList selectedNodes = graph->getSelectedNodes();
    NodeGuiPtr nodegui = _imp->_gui->createNodeGUI(node, args);
    assert(nodegui);

    if (parentMultiInstance && nodegui) {
        nodegui->hideGui();


        NodeGuiIPtr parentNodeGui_i = parentMultiInstance->getNodeGui();
        assert(parentNodeGui_i);
        nodegui->setParentMultiInstance( boost::dynamic_pointer_cast<NodeGui>(parentNodeGui_i) );
    }

    bool isViewer = node->isEffectViewerInstance() != 0;
    if (isViewer) {
        _imp->_gui->createViewerGui(node);
    }

    // Must be done after the viewer gui has been created
    _imp->_gui->createNodeViewerInterface(nodegui);


    NodeGroupPtr isGroup = node->isEffectNodeGroup();
    if ( isGroup && isGroup->isSubGraphUserVisible() ) {
        _imp->_gui->createGroupGui(node, args);
    }

    ///Don't initialize inputs if it is a multi-instance child since it is not part of  the graph
    if (!parentMultiInstance) {
        nodegui->initializeInputs();
    }
    
    NodeSerializationPtr serialization = args.getProperty<NodeSerializationPtr >(kCreateNodeArgsPropNodeSerialization);
    if ( !serialization && !isViewer ) {
        ///we make sure we can have a clean preview.
        node->computePreviewImage( getTimeLine()->currentFrame() );
        triggerAutoSave();
    }


    ///only move main instances
    if ( node->getParentMultiInstanceName().empty() && !serialization) {
        bool autoConnect = args.getProperty<bool>(kCreateNodeArgsPropAutoConnect);

        if ( selectedNodes.empty() || serialization) {
            autoConnect = false;
        }
        double xPosHint = serialization ? INT_MIN : args.getProperty<double>(kCreateNodeArgsPropNodeInitialPosition, 0);
        double yPosHint = serialization ? INT_MIN : args.getProperty<double>(kCreateNodeArgsPropNodeInitialPosition, 1);
        if ( (xPosHint != INT_MIN) && (yPosHint != INT_MIN) && (!autoConnect) ) {
            QPointF pos = nodegui->mapToParent( nodegui->mapFromScene( QPointF(xPosHint, yPosHint) ) );
            nodegui->refreshPosition( pos.x(), pos.y(), true );
        } else {
            BackdropGuiPtr isBd = toBackdropGui(nodegui);
            if (!isBd) {
                NodeGuiPtr selectedNode;
                if ( !serialization && (selectedNodes.size() == 1) ) {
                    selectedNode = selectedNodes.front();
                    BackdropGuiPtr isBdGui = toBackdropGui(selectedNode);
                    if (isBdGui) {
                        selectedNode.reset();
                    }
                }
                nodegui->getDagGui()->moveNodesForIdealPosition(nodegui, selectedNode, autoConnect);
            }
        }
    }
} // createNodeGui
Example #4
0
    //-------------------------------------------------------------------------
    bool Node::walk(WalkSink &inWalker, const FilterList *inFilterList) const
    {
      // walks the tree in a non-recursive way to protect the stack from overflowing

      ULONG mask = ZS_INTERNAL_XML_FILTER_BIT_MASK_ALL;
      if (inFilterList)
      {
        mask = 0;
        for (FilterList::const_iterator iter = inFilterList->begin(); iter != inFilterList->end(); ++iter)
        {
          mask = mask | getMaskBit(*iter);
        }
      }

      NodePtr startChild = toNode();
      NodePtr child = startChild;
      bool allowChildren = true;
      while (child)
      {
        NodePtr nextSibling = child->getNextSibling();  // just in case the current element was orphaned
        NodePtr nextParent = child->getParent();

        bool doContinue = false;
        while (allowChildren) // using as a scope rather than as a loop
        {
          if (0 != (mask & getMaskBit(child->getNodeType())))
          {
            bool result = false;
            switch (child->getNodeType())
            {
              case NodeType::Document:      result = inWalker.onDocumentEnter(child->toDocument()); break;
              case NodeType::Element:       result = inWalker.onElementEnter(child->toElement()); break;
              case NodeType::Attribute:     result = inWalker.onAttribute(child->toAttribute()); break;
              case NodeType::Text:          result = inWalker.onText(child->toText()); break;
              case NodeType::Comment:       result = inWalker.onComment(child->toComment()); break;
              case NodeType::Declaration:   result = inWalker.onDeclarationEnter(child->toDeclaration()); break;
              case NodeType::Unknown:       result = inWalker.onUnknown(child->toUnknown()); break;
            }
            if (result)
              return true;

            if ((child->getNextSibling() != nextSibling) ||
                (child->getParent() != nextParent)) {
              // the node was orphaned, do not process its children anymore
              break;
            }
          }

          AttributePtr attribute;

          if (child->isElement())
          {
            ElementPtr element = child->toElement();
            attribute = element->getFirstAttribute();
          }
          else if (child->isDeclaration())
          {
            DeclarationPtr declaration = child->toDeclaration();
            attribute = declaration->getFirstAttribute();
          }

          // walk the attributes
          if (attribute)
          {
            if (0 != (mask & getMaskBit(attribute->getNodeType())))
            {
              while (attribute)
              {
                NodePtr next = attribute->getNextSibling(); // need to do this in advanced in case the attribute is orphaned

                if (inWalker.onAttribute(attribute))
                  return true;

                if (!next)
                  break;

                attribute = next->toAttribute();
              }
            }
          }

          if (child->getFirstChild())
          {
            child = child->getFirstChild();
            doContinue = true;
            break;
          }
          break;  // not really intending to loop
        }

        if (doContinue)
          continue;

        if ((child->isDeclaration()) &&
            (0 != (mask & ZS_INTERNAL_XML_FILTER_BIT_DECLARATION)))
        {
          // reached the exit point for the declaration
          if (inWalker.onDeclarationExit(child->toDeclaration()))
            return true;
        }

        // going to be exiting this node node by way of the sibling or the parent (but only do exit for nodes that have exit)
        if ((child->isElement()) &&
            (0 != (mask & ZS_INTERNAL_XML_FILTER_BIT_ELEMENT)))
        {
          if (inWalker.onElementExit(child->toElement()))
            return true;
        }

        if ((child->isDocument()) &&
            (0 != (mask & ZS_INTERNAL_XML_FILTER_BIT_DOCUMENT)))
        {
          if (inWalker.onDocumentExit(child->toDocument()))
            return true;
        }

        if (nextSibling)
        {
          // can't go to the next sibling if on the root
          if (child == startChild)
            break;

          allowChildren = true;
          child = nextSibling;
          continue;
        }

        // cannot walk above the start child
        if (child == startChild)
          break;

        child = nextParent;
        allowChildren = false;
      }

      return false;
    }
Example #5
0
bool
Project::restoreGroupFromSerialization(const SERIALIZATION_NAMESPACE::NodeSerializationList & serializedNodes,
                                       const NodeCollectionPtr& group,
                                       std::list<std::pair<NodePtr, SERIALIZATION_NAMESPACE::NodeSerializationPtr > >* createdNodesOut)
{
    bool mustShowErrorsLog = false;

    NodeGroupPtr isGrp = toNodeGroup(group);

    QString groupName;
    if (isGrp) {
        groupName = QString::fromUtf8( isGrp->getNode()->getLabel().c_str() );
    } else {
        groupName = tr("top-level");
    }
    group->getApplication()->updateProjectLoadStatus( tr("Creating nodes in group: %1").arg(groupName) );


    std::list<std::pair<NodePtr, SERIALIZATION_NAMESPACE::NodeSerializationPtr > > createdNodes;



    // Loop over all node serialization and create them first
    for (SERIALIZATION_NAMESPACE::NodeSerializationList::const_iterator it = serializedNodes.begin(); it != serializedNodes.end(); ++it) {

        NodePtr node = appPTR->createNodeForProjectLoading(*it, group);
        if (!node) {
            QString text( tr("ERROR: The node %1 version %2.%3"
                             " was found in the script but does not"
                             " exist in the loaded plug-ins.")
                         .arg( QString::fromUtf8( (*it)->_pluginID.c_str() ) )
                         .arg((*it)->_pluginMajorVersion).arg((*it)->_pluginMinorVersion) );
            appPTR->writeToErrorLog_mt_safe(tr("Project"), QDateTime::currentDateTime(), text);
            mustShowErrorsLog = true;
            continue;
        } else {
            if (node->getPluginID() == PLUGINID_NATRON_STUB) {
                // If the node could not be created and we made a stub instead, warn the user
                QString text( tr("WARNING: The node %1 (%2 version %3.%4) "
                                 "was found in the script but the plug-in could not be found. It has been replaced by a pass-through node instead.")
                             .arg( QString::fromUtf8( (*it)->_nodeScriptName.c_str() ) )
                             .arg( QString::fromUtf8( (*it)->_pluginID.c_str() ) )
                             .arg((*it)->_pluginMajorVersion)
                             .arg((*it)->_pluginMinorVersion));
                appPTR->writeToErrorLog_mt_safe(tr("Project"), QDateTime::currentDateTime(), text);
                mustShowErrorsLog = true;
            } else if ( (*it)->_pluginMajorVersion != -1 && (node->getMajorVersion() != (int)(*it)->_pluginMajorVersion) ) {
                // If the node has a IOContainer don't do this check: when loading older projects that had a
                // ReadOIIO node for example in version 2, we would now create a new Read meta-node with version 1 instead
                QString text( tr("WARNING: The node %1 (%2 version %3.%4) "
                                 "was found in the script but was loaded "
                                 "with version %5.%6 instead.")
                             .arg( QString::fromUtf8( (*it)->_nodeScriptName.c_str() ) )
                             .arg( QString::fromUtf8( (*it)->_pluginID.c_str() ) )
                             .arg((*it)->_pluginMajorVersion)
                             .arg((*it)->_pluginMinorVersion)
                             .arg( node->getPlugin()->getPropertyUnsafe<unsigned int>(kNatronPluginPropVersion, 0) )
                             .arg( node->getPlugin()->getPropertyUnsafe<unsigned int>(kNatronPluginPropVersion, 1) ) );
                appPTR->writeToErrorLog_mt_safe(tr("Project"), QDateTime::currentDateTime(), text);
            }
        }

        assert(node);

        createdNodes.push_back(std::make_pair(node, *it));

    } // for all node serialization


    group->getApplication()->updateProjectLoadStatus( tr("Restoring graph links in group: %1").arg(groupName) );


    // Connect the nodes together
    for (std::list<std::pair<NodePtr, SERIALIZATION_NAMESPACE::NodeSerializationPtr > >::const_iterator it = createdNodes.begin(); it != createdNodes.end(); ++it) {


        // Loop over the inputs map
        // This is a map <input label, input node name>
        //
        // When loading projects before Natron 2.2, the inputs contain both masks and inputs.
        //

        restoreInputs(it->first, it->second->_inputs, createdNodes, false /*isMasks*/);

        // After Natron 2.2, masks are saved separatly
        restoreInputs(it->first, it->second->_masks, createdNodes, true /*isMasks*/);

    } // for (std::list< NodeSerializationPtr >::const_iterator it = serializedNodes.begin(); it != serializedNodes.end(); ++it) {


    if (createdNodesOut) {
        *createdNodesOut = createdNodes;
    }
    // If we created all sub-groups recursively, then we are in the top-level group. We may now restore all links
    if (!group->getApplication()->isCreatingNode()) {

        // Now that we created all nodes. There may be cross-graph link(s) and they can only be truely restored now.
        restoreLinksRecursive(group, serializedNodes, createdNodesOut);
    }


    return !mustShowErrorsLog;
} // ProjectPrivate::restoreGroupFromSerialization
Example #6
0
int main(int argc, char **argv)
{
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    
    int id=glutCreateWindow("OpenSG");
    
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    GLUTWindowPtr gwin=GLUTWindow::create();
    gwin->setId(id);
    gwin->init();

    // create the scene
//    NodePtr scene = makeTorus(.5, 2, 16, 16);
    NodePtr scene = Node::create();
    beginEditCP(scene);
    scene->setCore(Group::create());
    endEditCP(scene);

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (scene);
    
    DisplayFilterForegroundPtr fg = DisplayFilterForeground::create();

    beginEditCP(fg);
    // add filter
    endEditCP(fg);

    // take the viewport
    ViewportPtr vp = gwin->getPort(0);

    beginEditCP(vp);
    vp->editMFForegrounds()->push_back(fg);    
    endEditCP  (vp);

    colorFilterPtr = ColorDisplayFilter::create();
    distortionFilterPtr = DistortionDisplayFilter::create();
    resolutionFilterPtr = ResolutionDisplayFilter::create();

    beginEditCP(colorFilterPtr);
    beginEditCP(resolutionFilterPtr);
    beginEditCP(distortionFilterPtr);
    beginEditCP(fg);
    colorFilterPtr->setMatrix(osg::Matrix(0,0,1,0,
                                          1,0,0,0,
                                          0,1,0,0,
                                          0,0,0,1));
    resolutionFilterPtr->setDownScale(0.25);

    distortionFilterPtr->setColumns(2);
    distortionFilterPtr->setRows(2);
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(0,.5));
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(.5,0));
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(.5,1));
    distortionFilterPtr->editMFPositions()->push_back(Vec2f(1,.5));
    
    fg->editMFFilter()->push_back(colorFilterPtr);
    fg->editMFFilter()->push_back(resolutionFilterPtr);
    fg->editMFFilter()->push_back(distortionFilterPtr);

    endEditCP(distortionFilterPtr);
    endEditCP(colorFilterPtr);
    endEditCP(resolutionFilterPtr);
    endEditCP(fg);

    for(UInt32 a=1 ; a<argc ;a++)
    {
        NodePtr file = SceneFileHandler::the().read(argv[a],0);
        if(file != NullFC)
            scene->addChild(file);
        else
            std::cerr << "Couldn't load file, ignoring " << argv[a] << std::endl;
    }
	if ( scene->getNChildren() == 0 )
	{
        scene->addChild(makeTorus( .5, 2, 16, 16 ));
//        scene->addChild(makeBox(.6,.6,.6,5,5,5));
    }

    // show the whole scene
    mgr->showAll();
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
    typename ThetaStar<ProblemType, Hasher>::SolutionPtr ThetaStar<ProblemType, Hasher>::operator() ( const ProblemType& problem )
    {
        SolutionPtr solution(nullptr);
        this->visits = 0;
        this->maxNodesInMemory = 0;

        NodePtr initialStateNode = this->createNode( problem.initialState() );

        this->fringe->push(initialStateNode);

        //clock_t begin = clock();

        while( !solution && !this->fringe->empty() )
        {
            if(this->fringe->size() + this->closedList.size() > this->maxNodesInMemory)
                this->maxNodesInMemory = this->fringe->size() + this->closedList.size();
            this->visits++;

            NodePtr currentNode = this->fringe->pop();
            this->notifyNodeVisitListeners(currentNode);

            if( problem.isGoal( currentNode->getState() ) )
            {
                solution = SolutionPtr(new SolutionType(currentNode));
                continue;
            }

            std::pair<const State*, NodePtr> entry(&currentNode->getState(), currentNode);
            this->closedList.insert(entry);
            this->notifyNodeClosureListeners(currentNode);

            std::list<NodePtr>&& successors = this->expand(currentNode, problem);

            for(NodePtr node: successors) {
                auto nodeIt = this->closedList.find(&node->getState());

                if(nodeIt == this->closedList.end()) {

                    if(node->hasParent()) {

                        if(node->getParent()->hasParent()) {
                            auto grandParent = node->getParent()->getParent();

                            auto actionAndCost = (*lineOfSight)(node->getState(), grandParent->getState());
                            if(actionAndCost.first != nullptr) {
                                node->setParent(grandParent, *actionAndCost.first, actionAndCost.second);
                            }
                        }
                    }

                    this->fringe->push(node);
                }
            }
        }

        //clock_t end = clock();

        //double timeSpend = (double)(end - begin) / CLOCKS_PER_SEC;
        //std::cout << "Spent " << timeSpend << " seconds on " << visit << " visits (" << visit/timeSpend << " n/s)" << std::endl;

        this->cleanUp();
        return solution;
    }
Example #8
0
void
ProgressPanel::startTask(const NodePtr& node,
                         const int firstFrame,
                         const int lastFrame,
                         const int frameStep,
                         const bool canPause,
                         const bool canCancel,
                         const QString& message,
                         const boost::shared_ptr<ProcessHandler>& process)
{
    assert(QThread::currentThread() == qApp->thread());
    if (!node) {
        return;
    }
    assert((canPause && firstFrame != INT_MIN && lastFrame != INT_MAX) || !canPause);
    
    ProgressTaskInfoPtr task;
    {
        
        QMutexLocker k(&_imp->tasksMutex);
        task = _imp->findTask(node);
    }
    if (task) {
        task->cancelTask(false, 1);
        removeTaskFromTable(task);
    }
    

    
    QMutexLocker k(&_imp->tasksMutex);
    
    task.reset(new ProgressTaskInfo(this,
                            node,
                            firstFrame,
                            lastFrame,
                            frameStep,
                            canPause,
                            canCancel,
                            message, process));
    
    
    if (canPause || node->getEffectInstance()->isOutput()) {
        task->createItems();
        QTimer::singleShot(NATRON_DISPLAY_PROGRESS_PANEL_AFTER_MS, this, SLOT(onShowProgressPanelTimerTriggered()));
    }
    
    if (process) {
        connectProcessSlots(task.get(), process.get());
    }
    if (!process) {
        if (node->getEffectInstance()->isOutput()) {
            OutputEffectInstance* isOutput = dynamic_cast<OutputEffectInstance*>(node->getEffectInstance().get());
            if (isOutput) {
                RenderEngine* engine = isOutput->getRenderEngine();
                assert(engine);
                QObject::connect(engine,SIGNAL(frameRendered(int,double)), task.get(), SLOT(onRenderEngineFrameComputed(int,double)));
                QObject::connect(engine, SIGNAL(renderFinished(int)), task.get(), SLOT(onRenderEngineStopped(int)));
                QObject::connect(task.get(),SIGNAL(taskCanceled()),engine,SLOT(abortRendering_Blocking()));
            }
        }
    }
Example #9
0
PickKnobDialog::PickKnobDialog(DockablePanel* panel,
                               QWidget* parent)
    : QDialog(parent)
    , _imp( new PickKnobDialogPrivate(panel) )
{
    NodeSettingsPanel* nodePanel = dynamic_cast<NodeSettingsPanel*>(panel);

    assert(nodePanel);
    if (!nodePanel) {
        throw std::logic_error("PickKnobDialog::PickKnobDialog()");
    }
    NodeGuiPtr nodeGui = nodePanel->getNodeGui();
    NodePtr node = nodeGui->getNode();
    NodeGroupPtr isGroup = node->isEffectNodeGroup();
    NodeCollectionPtr collec = node->getGroup();
    NodeGroupPtr isCollecGroup = toNodeGroup(collec);
    NodesList collectNodes = collec->getNodes();
    for (NodesList::iterator it = collectNodes.begin(); it != collectNodes.end(); ++it) {
        if ((*it)->isActivated() && (*it)->getNodeGui() && ( (*it)->getKnobs().size() > 0 ) ) {
            _imp->allNodes.push_back(*it);
        }
    }
    if (isCollecGroup) {
        _imp->allNodes.push_back( isCollecGroup->getNode() );
    }
    if (isGroup) {
        NodesList groupnodes = isGroup->getNodes();
        for (NodesList::iterator it = groupnodes.begin(); it != groupnodes.end(); ++it) {
            if ( (*it)->getNodeGui() &&
                (*it)->isActivated() &&
                ( (*it)->getKnobs().size() > 0 ) ) {
                _imp->allNodes.push_back(*it);
            }
        }
    }
    QStringList nodeNames;
    for (NodesList::iterator it = _imp->allNodes.begin(); it != _imp->allNodes.end(); ++it) {
        QString name = QString::fromUtf8( (*it)->getLabel().c_str() );
        nodeNames.push_back(name);
    }
    nodeNames.sort();

    _imp->mainLayout = new QGridLayout(this);
    _imp->selectNodeLabel = new Label( tr("Node:") );
    _imp->nodeSelectionCombo = new CompleterLineEdit(nodeNames, nodeNames, false, this);
    _imp->nodeSelectionCombo->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("Input the name of a node in the current project."), NATRON_NAMESPACE::WhiteSpaceNormal) );
    _imp->nodeSelectionCombo->setFocus(Qt::PopupFocusReason);

    _imp->knobSelectionCombo = new ComboBox(this);
    QObject::connect( _imp->knobSelectionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onKnobComboIndexChanged(int)) );
    QString useAliasTt = NATRON_NAMESPACE::convertFromPlainText(tr("If checked, an alias of the selected parameter will be created, coyping entirely its state. "
                                                           "Only the script-name, label and tooltip will be editable.\n"
                                                           "For choice parameters this will also "
                                                           "dynamically refresh the menu entries when the original parameter's menu is changed.\n"
                                                           "When unchecked, a simple expression will be set linking the two parameters, but things such as dynamic menus "
                                                           "will be disabled."), NATRON_NAMESPACE::WhiteSpaceNormal);
    _imp->useAliasLabel = new Label(tr("Make Alias:"), this);
    _imp->useAliasLabel->setToolTip(useAliasTt);
    _imp->useAliasCheckBox = new QCheckBox(this);
    _imp->useAliasCheckBox->setToolTip(useAliasTt);
    _imp->useAliasCheckBox->setChecked(true);

    QObject::connect( _imp->nodeSelectionCombo, SIGNAL(itemCompletionChosen()), this, SLOT(onNodeComboEditingFinished()) );

    _imp->destPageLabel = new Label(tr("Page:"), this);
    QString pagett = NATRON_NAMESPACE::convertFromPlainText(tr("Select the page into which the parameter will be created."), NATRON_NAMESPACE::WhiteSpaceNormal);
    _imp->destPageLabel->setToolTip(pagett);
    _imp->destPageCombo = new ComboBox(this);
    _imp->destPageCombo->setToolTip(pagett);
    QObject::connect( _imp->destPageCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onPageComboIndexChanged(int)) );
    const KnobsVec& knobs = node->getKnobs();
    for (std::size_t i = 0; i < knobs.size(); ++i) {
        if ( knobs[i]->isUserKnob() ) {
            KnobPagePtr isPage = toKnobPage(knobs[i]);
            if (isPage) {
                _imp->pages.push_back(isPage);
                _imp->destPageCombo->addItem( QString::fromUtf8( isPage->getName().c_str() ) );
            } else {
                KnobGroupPtr isGrp = toKnobGroup(knobs[i]);
                if (isGrp) {
                    _imp->groups.push_back(isGrp);
                }
            }
        }
    }
    if (_imp->destPageCombo->count() == 0) {
        _imp->destPageLabel->hide();
        _imp->destPageCombo->hide();
    }


    _imp->groupLabel = new Label(tr("Group:"), this);
    QString grouptt = NATRON_NAMESPACE::convertFromPlainText(tr("Select the group into which the parameter will be created."), NATRON_NAMESPACE::WhiteSpaceNormal);
    _imp->groupCombo = new ComboBox(this);
    _imp->groupLabel->setToolTip(grouptt);
    _imp->groupCombo->setToolTip(grouptt);
    onPageComboIndexChanged(0);

    _imp->buttons = new DialogButtonBox(QDialogButtonBox::StandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel),
                                         Qt::Horizontal, this);
    QObject::connect( _imp->buttons, SIGNAL(accepted()), this, SLOT(accept()) );
    QObject::connect( _imp->buttons, SIGNAL(rejected()), this, SLOT(reject()) );

    _imp->mainLayout->addWidget(_imp->selectNodeLabel, 0, 0, 1, 1);
    _imp->mainLayout->addWidget(_imp->nodeSelectionCombo, 0, 1, 1, 1);
    _imp->mainLayout->addWidget(_imp->knobSelectionCombo, 0, 2, 1, 1);
    _imp->mainLayout->addWidget(_imp->useAliasLabel, 1, 0, 1, 1);
    _imp->mainLayout->addWidget(_imp->useAliasCheckBox, 1, 1, 1, 1);
    _imp->mainLayout->addWidget(_imp->destPageLabel, 2, 0, 1, 1);
    _imp->mainLayout->addWidget(_imp->destPageCombo, 2, 1, 1, 1);
    _imp->mainLayout->addWidget(_imp->groupLabel, 2, 2, 1, 1);
    _imp->mainLayout->addWidget(_imp->groupCombo, 2, 3, 1, 1);
    _imp->mainLayout->addWidget(_imp->buttons, 3, 0, 1, 3);

    QTimer::singleShot( 25, _imp->nodeSelectionCombo, SLOT(showCompleter()) );
}
Example #10
0
//------------------------------------------------------------------------------
// The main method
//------------------------------------------------------------------------------
int main(int argc, char **argv) {
	osgInit(argc, argv);                 // initialize OpenSG
	int winid = setupGLUT(&argc, argv);  // initialize GLUT

	// the connection between GLUT and OpenSG is established
	GLUTWindowPtr gwin = GLUTWindow::create();
	gwin->setId(winid);
	gwin->init();

//----------------------------------------------------------------------------//
// Snippet-1-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// very first step: load the configuration of the file structures, basically
	// paths are set. The Configuration always has to be loaded first since each
	// module uses the paths set in the configuration-file
	if (!Configuration::loadConfig("config/general.xml")) {
		printf("Error: could not load config-file!\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-1-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-4 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// register callbacks
	InputInterface::registerModuleInitCallback(initInputInterface);
	SystemCore::registerModuleInitCallback(initModules);
//----------------------------------------------------------------------------//
// Snippet-2-4 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	SystemCore::registerCoreComponentInitCallback(initCoreComponents);
//----------------------------------------------------------------------------//
// Snippet-3-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-1-2 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	std::string systemCoreConfigFile = Configuration::getString(
			"SystemCore.systemCoreConfiguration");
	std::string outputInterfaceConfigFile = Configuration::getString(
			"Interfaces.outputInterfaceConfiguration");

//	// !!!!!! Remove in tutorial part 2, Snippet-2-1 - BEGIN
//	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile)) {
//		printf("Error: failed to setup SystemCore!\n");
//		return -1;
//	}
//	// !!!!!! Remove - END
//----------------------------------------------------------------------------//
// Snippet-1-2 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// !!!!!! Remove part of Snippet-1-2 (right above)
	// in addition to the SystemCore config file, modules and interfaces config
	// files have to be loaded.
	std::string modulesConfigFile = Configuration::getString(
				"Modules.modulesConfiguration");
	std::string inputInterfaceConfigFile = Configuration::getString(
			"Interfaces.inputInterfaceConfiguration");

	if (!SystemCore::configure(systemCoreConfigFile, outputInterfaceConfigFile, inputInterfaceConfigFile,
			modulesConfigFile)) {
		printf("Error: failed to setup SystemCore!\n");
		printf("Please check if the Plugins-path is correctly set to the inVRs-lib directory in the ");
		printf("'final/config/general.xml' config file, e.g.:\n");
		printf("<path name=\"Plugins\" path=\"/home/guest/inVRs/lib\"/>\n");
		return -1;
	}
//----------------------------------------------------------------------------//
// Snippet-2-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-3-1 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// generate or load and configure height maps of the used tiles
	HeightMapManager::generateTileHeightMaps();
//----------------------------------------------------------------------------//
// Snippet-3-1 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-15 - BEGIN                                                       //
//----------------------------------------------------------------------------//
	// generate and configure the SkyBox
	std::string skyPath = Configuration::getPath("Skybox");
	skybox.init(5,5,5, 1000, (skyPath+"lostatseaday/lostatseaday_dn.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_up.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_ft.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_bk.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_rt.jpg").c_str(),
		(skyPath+"lostatseaday/lostatseaday_lf.jpg").c_str());
//----------------------------------------------------------------------------//
// Snippet-2-15 - END                                                         //
//----------------------------------------------------------------------------//

	NodePtr root = Node::create();
	beginEditCP(root);
		root->setCore(Group::create());

//----------------------------------------------------------------------------//
// Snippet-1-3 - BEGIN                                                        //
//----------------------------------------------------------------------------//
		OpenSGSceneGraphInterface* sgIF =
			dynamic_cast<OpenSGSceneGraphInterface*>(OutputInterface::getSceneGraphInterface());
		if (!sgIF) {
			printf("Error: Failed to get OpenSGSceneGraphInterface!\n");
			printf("Please check if the OutputInterface configuration is correct!\n");
			return -1;
		}
		// retrieve root node of the SceneGraphInterface (method is OpenSG specific)
		NodePtr scene = sgIF->getNodePtr();

		root->addChild(scene);
//----------------------------------------------------------------------------//
// Snippet-1-3 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-2-16 - BEGIN                                                       //
//----------------------------------------------------------------------------//
		// add the SkyBox to the scene
		root->addChild(skybox.getNodePtr());
//----------------------------------------------------------------------------//
// Snippet-2-16 - END                                                         //
//----------------------------------------------------------------------------//

	endEditCP(root);

//----------------------------------------------------------------------------//
// Snippet-2-5 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// fetch users camera, it is used to tell the Navigator where we are
	localUser = UserDatabase::getLocalUser();
	if (!localUser) {
		printd(ERROR, "Error: Could not find localUser!\n");
		return -1;
	}

	camera = localUser->getCamera();
	if (!camera) {
		printd(ERROR, "Error: Could not find camera!\n");
		return -1;
	}

	avatar = localUser->getAvatar();
	if (!avatar) {
		printd(ERROR, "Error: Could not find avatar!\n");
		return -1;
	}
	avatar->showAvatar(false);

  // set our transformation to the start transformation
	TransformationData startTrans =
		WorldDatabase::getEnvironmentWithId(1)->getStartTransformation(0);
	localUser->setNavigatedTransformation(startTrans);
//----------------------------------------------------------------------------//
// Snippet-2-5 - END                                                          //
//----------------------------------------------------------------------------//

	mgr = new SimpleSceneManager;  // create the SimpleSceneManager
	mgr->setWindow(gwin);          // tell the manager what to manage
	mgr->setRoot(root);            // attach the scenegraph to the  root node
	mgr->showAll();                // show the whole scene
	mgr->getCamera()->setNear(0.1);

//----------------------------------------------------------------------------//
// Snippet-2-6 - BEGIN                                                        //
//----------------------------------------------------------------------------//
	// Navigator is part of SimpleSceneManager and not of the inVRs framework
	Navigator *nav = mgr->getNavigator();
	nav->setMode(Navigator::NONE);     // turn off the navigator
	lastTimeStamp = timer.getTime();   // initialize timestamp;
	camMatrix = gmtl::MAT_IDENTITY44F; // initial setting of the camera matrix
//----------------------------------------------------------------------------//
// Snippet-2-6 - END                                                          //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// Snippet-5-2                                                                //
//----------------------------------------------------------------------------//

	glutMainLoop(); // GLUT main loop
	return 0;
}
Example #11
0
bool StatCache::handleEvent(const struct inotify_event* event) {
  if (event->mask & IN_Q_OVERFLOW) {
    // The event queue overflowed, so all bets are off.  Start over.
    TRACE(0, "StatCache: event queue overflowed\n");
    reset();
    return true;
  }
  assertx(event->wd != -1);
  NodePtr node = folly::get_default(m_watch2Node, event->wd);
  if (!node.get()) {
    TRACE(1, "StatCache: inotify event (obsolete) %s\n",
             eventToString(event).c_str());
    return false;
  }
  TRACE(1, "StatCache: inotify event for '%s': %s\n",
           node->path().c_str(), eventToString(event).c_str());

  if (event->mask & (IN_MODIFY|IN_ATTRIB)) {
    bool touched = false;
    NodePtr child = node->getChild(event->name, true);
    if (child.get() != nullptr) {
      if ((event->mask & IN_MODIFY) && child->isLink()) {
        // A modified link is logically equivalent to IN_MOVED_FROM.
        child->expirePaths();
        node->removeChild(event->name);
      } else {
        child->touch();
      }
      touched = true;
    }
    child = node->getChild(event->name, false);
    if (child.get() != nullptr) {
      // The follow=false child is equivalent to the follow=true child unless
      // it's a link.  Avoid duplicate invalidations for non-links.
      child->touch(!touched || child->isLink());
    }
  }
  if (event->mask & (IN_MOVED_FROM|IN_MOVED_TO|IN_CREATE|IN_DELETE)) {
    // The directory itself was modified, so invalidate its cached stat
    // structure.
    node->touch();
    // Recursively invalidate the cached paths rooted at "node/name".
    bool expired = false;
    NodePtr child = node->getChild(event->name, true);
    if (child.get() != nullptr) {
      child->expirePaths();
      expired = true;
    }
    child = node->getChild(event->name, false);
    if (child.get() != nullptr) {
      // The follow=false child is equivalent to the follow=true child unless
      // it's a link.  Avoid duplicate invalidations for non-links.
      child->expirePaths(!expired || child->isLink());
      expired = true;
    }
    if (expired) {
      node->removeChild(event->name);
    }
  }
  if (event->mask & IN_IGNORED) {
    // The kernel removed the directory watch, either as a side effect of
    // directory deletion, or because inotify_rm_watch() was explicitly called
    // during Node destruction.  Delete the corresponding entry from
    // m_watch2Node.  Removal should always succeed here because no other code
    // performs removal.
    m_watch2Node.erase(event->wd);
  }
  return false;
}
Example #12
0
SceneView::SceneView( const std::string &name )
	:	View3D( name, new GafferScene::ScenePlug() ),
		m_sceneGadget( new SceneGadget )
{

	// add plugs and signal handling for them

	storeIndexOfNextChild( g_firstPlugIndex );

	addChild( new IntPlug( "minimumExpansionDepth", Plug::In, 0, 0, Imath::limits<int>::max(), Plug::Default & ~Plug::AcceptsInputs ) );

	plugSetSignal().connect( boost::bind( &SceneView::plugSet, this, ::_1 ) );

	// set up our gadgets

	viewportGadget()->setPrimaryChild( m_sceneGadget );

	viewportGadget()->keyPressSignal().connect( boost::bind( &SceneView::keyPress, this, ::_1, ::_2 ) );

	m_sceneGadget->baseState()->add( const_cast<IECoreGL::State *>( baseState() ) );
	m_sceneGadget->setContext( getContext() );
	baseStateChangedSignal().connect( boost::bind( &SceneView::baseStateChanged, this ) );

	m_lookThrough = boost::shared_ptr<LookThrough>( new LookThrough( this ) );
	m_grid = boost::shared_ptr<Grid>( new Grid( this ) );
	m_gnomon = boost::shared_ptr<Gnomon>( new Gnomon( this ) );
	m_shadingMode = boost::shared_ptr<ShadingMode>( new ShadingMode( this ) );

	//////////////////////////////////////////////////////////////////////////
	// add a preprocessor which monkeys with the scene before it is displayed.
	//////////////////////////////////////////////////////////////////////////

	NodePtr preprocessor = new Node();
	ScenePlugPtr preprocessorInput = new ScenePlug( "in" );
	preprocessor->addChild( preprocessorInput );

	// add a node for hiding things

	StandardAttributesPtr hide = new StandardAttributes( "hide" );
	hide->attributesPlug()->getChild<ValuePlug>( "visibility" )->getChild<BoolPlug>( "enabled" )->setValue( true );
	hide->attributesPlug()->getChild<ValuePlug>( "visibility" )->getChild<BoolPlug>( "value" )->setValue( false );

	preprocessor->addChild( hide );
	hide->inPlug()->setInput( preprocessorInput );

	PathFilterPtr hideFilter = new PathFilter( "hideFilter" );
	preprocessor->addChild( hideFilter );
	hide->filterPlug()->setInput( hideFilter->outPlug() );

	// add in the node from the ShadingMode

	preprocessor->addChild( m_shadingMode->preprocessor() );
	m_shadingMode->preprocessor()->inPlug()->setInput( hide->outPlug() );

	// make the output for the preprocessor

	ScenePlugPtr preprocessorOutput = new ScenePlug( "out", Plug::Out );
	preprocessor->addChild( preprocessorOutput );
	preprocessorOutput->setInput( m_shadingMode->preprocessor()->outPlug() );

	setPreprocessor( preprocessor );

	// connect up our scene gadget

	m_sceneGadget->setScene( preprocessedInPlug<ScenePlug>() );

}
Example #13
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG CGFX Shader");

    // the connection between GLUT and OpenSG
    _gwin = GLUTWindow::create();
    _gwin->setId(winid);
    _gwin->setSize( 800, 800 );
    _gwin->init();

    // init callbacks
    glutSetWindow(winid);
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutKeyboardFunc(keyboard);

    const char *effectFile = "BumpGlossedShiny.fx";

    if(argc > 1)
    {
        effectFile = argv[1];
    }

    _cgfxmat = CGFXMaterial::create();
    beginEditCP(_cgfxmat);
        _cgfxmat->setEffectFile(effectFile);
        // this multipass technique leads to a render bug, I have no idea what's wrong :-(
        //_cgfxmat->setTechnique(1);
    endEditCP(_cgfxmat);

    ChunkMaterialPtr mat2 = ChunkMaterial::create();
    MaterialChunkPtr matc = MaterialChunk::create();
    beginEditCP(matc);
        matc->setDiffuse(Color4f(1, 0, 0, 1));
    endEditCP(matc);
    beginEditCP(mat2);
        mat2->addChunk(matc);
        //mat2->addChunk(texc);
    endEditCP(mat2);

    // create root node
    _scene = Node::create();

    GeometryPtr geo1 = makeLatLongSphereGeo(50, 50, 1.0f);
    
    OSG::calcVertexTangents(geo1, 0, Geometry::TexCoords1FieldId, Geometry::TexCoords2FieldId);

    beginEditCP( geo1, Geometry::MaterialFieldMask);
        geo1->setMaterial(_cgfxmat);
    endEditCP(geo1, Geometry::MaterialFieldMask);

    NodePtr sphere1 = Node::create();
    beginEditCP(sphere1, Node::CoreFieldMask);
        sphere1->setCore(geo1);
    endEditCP(sphere1, Node::CoreFieldMask);

    TransformPtr trans1 = Transform::create();
    beginEditCP(trans1);
        trans1->getMatrix().setTranslate(-2 , 0, 0);
    endEditCP(trans1);
    NodePtr transn1 = Node::create();
    beginEditCP(transn1);
        transn1->setCore(trans1);
        transn1->addChild(sphere1);
    beginEditCP(transn1);

    //
    GeometryPtr geo2 = makeLatLongSphereGeo(50, 50, 1.0f);
    
    beginEditCP( geo2, Geometry::MaterialFieldMask);
        geo2->setMaterial(mat2);
    endEditCP(geo2, Geometry::MaterialFieldMask);

    NodePtr sphere2 = Node::create();
    beginEditCP(sphere2, Node::CoreFieldMask);
        sphere2->setCore(geo2);
    endEditCP(sphere2, Node::CoreFieldMask);

    TransformPtr trans2 = Transform::create();
    beginEditCP(trans2);
        trans2->getMatrix().setTranslate(2 , 0, 0);
    endEditCP(trans2);
    NodePtr transn2 = Node::create();
    beginEditCP(transn2);
        transn2->setCore(trans2);
        transn2->addChild(sphere2);
    beginEditCP(transn2);

    beginEditCP(_scene);
        _scene->setCore(Group::create());
        _scene->addChild(transn1);
        _scene->addChild(transn2);
    endEditCP(_scene);

    // create the SimpleSceneManager
    _mgr = new SimpleSceneManager;

    // tell the manager what to manage
    _mgr->setWindow(_gwin);

    _mgr->setRoot(_scene);

    // show the whole scene
    _mgr->showAll();

    // create a gradient background.
    GradientBackgroundPtr gback = GradientBackground::create();
    beginEditCP(gback, GradientBackground::LineFieldMask);
        gback->clearLines();
        gback->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gback->addLine(Color3f(0.0, 0.1, 0.3), 1);
    endEditCP(gback, GradientBackground::LineFieldMask);

    WindowPtr win = _mgr->getWindow();
    beginEditCP(win);
        for(int i=0;i<win->getPort().size();++i)
        {
            ViewportPtr vp = win->getPort()[i];
            beginEditCP(vp);
                vp->setBackground(gback);
            endEditCP(vp);
        }
    endEditCP(win);


    // GLUT main loop
    glutMainLoop();

    return 0;
}
Example #14
0
void Node::addChildNode(NodePtr pNode)
{
    auto pair = std::make_pair(pNode->getName(), pNode);
    this->childNodes.insert(pair);
}
Example #15
0
void keyboard(unsigned char k, int x, int y)
{
    switch(k)
    {
        case 27:
        {
            OpenSGDeformActionManager::Destroy();
            osgExit();
            exit(0);
        }
        case '1':
        {
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
            break;
        }
        case '2':
        {
            glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
            break;
        }
        case '3':
        {
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
            break;
        }
        case '5':
        {
            chairIndex = (chairIndex + 1) % 6;
            model = chairNodes[chairIndex];
            cout << "Selected model is: ";
            if (getName(model))
                cout << getName(model);
            cout << " " << model << endl;
            break;
        }
        case '6':
        {
            ax *= -1;
            break;
        }
        case '7':
        {
            if (ax < 0)
                ax = -1;
            else
                ax = 1;
            break;
        }
        case '8':
        {
            if (ax < 0)
                ax = -2;
            else
                ax = 2;
            break;
        }
        case '9':
        {
            if (ax < 0)
                ax = -3;
            else
                ax = 3;
            break;
        }
        case 'p':
        {
#if OSG_MAJOR_VERSION >= 2
			traverse(scene, boost::bind(printSceneGraph,_1));
#else
            traverse(scene, osgTypedFunctionFunctor1CPtrRef
                <Action::ResultE, NodePtr>(printSceneGraph));
#endif 
            break;
        }
        case 'h':
        {
            printUsage();
            break;
        }
        case 'i':
        {
            gmtl::AABoxf aabb;
            osgdam = OpenSGDeformActionManager::GetInstance();
            if (osgdam != 0)
            {
                osgdam->insertLattice(model, 2, 2, 2, 3);
            }
            break;
        }
        case 'j':
        {
            osgdam = OpenSGDeformActionManager::GetInstance();
            if(osgdam != 0)
            {
                gmtl::AABoxf aabb;
                Pnt3f aabbMin, aabbMax;
#if OSG_MAJOR_VERSION >= 2
				model->editVolume(true).getBounds(aabbMin, aabbMax);
#else
				model->getVolume(true).getBounds(aabbMin, aabbMax);
#endif               

                for (int i = 0; i < 3; i++)
                {
                    aabbMin[i] = aabbMin[i] - 1.0f;
                    aabbMax[i] = aabbMax[i]/2 + 1.0f;
                }
                aabb = gmtl::AABoxf(gmtl::Vec3f(aabbMin[0], aabbMin[1], aabbMin[2]),
                                    gmtl::Vec3f(aabbMax[0], aabbMax[1], aabbMax[2]));

                osgdam->insertLattice(model, 2, 2, 2, 3, true, aabb);
            }
            break;
        }
        case 'q':
        {
            NodePtr tmp = model;

            while (tmp != NullFC)
            {
                TransformPtr tcore = TransformPtr::dcast(tmp->getCore());
                if (tcore != NullFC)
                {
                    Matrix mm = tcore->getMatrix();
                    Matrix tm = Matrix::identity();

                    tm.setScale(1,2,1);
                    mm.mult(tm);

                    beginEditCP(tcore, Transform::MatrixFieldMask);
                        tcore->setMatrix(mm);
                    endEditCP(tcore, Transform::MatrixFieldMask);

                    mm = tcore->getMatrix();
                    break;
                }
                tmp = tmp->getParent();
            }
            break;
        }
        default:
            break;
    }
    if (osgdam != 0)
    {
        switch(k)
        {
            case '4':
            {
                all = !all;
                osgdam->setShowAll(model, all);
                break;
            }
            case 'e':
            {
                doExecute = !doExecute;
                osgdam->setInstantExecution(model, doExecute);
                break;
            }
            case 'r':
            {
                osgdam->removeLattice(model);
                break;
            }
            case 't':
            {
                osgdam->taper(model, 1.0f, ax);
                break;
            }
            case 'g':
            {
                osgdam->twist(model, gmtl::Math::deg2Rad(5.0f), ax);
                break;
            }
            case 'b':
            {
                osgdam->bend(model, gmtl::Math::deg2Rad(5.0f), 0.5f, ax);
                break;
            }
            case 'v':
            {
                osgdam->bend(model, -gmtl::Math::deg2Rad(5.0f), 0.0f, ax);
                break;
            }
            case 'c':
            {
                osgdam->bend(model, -gmtl::Math::deg2Rad(5.0f), 1.0f, ax);
                break;
            }
            case 'f':
            {
                osgdam->bend(model, -gmtl::Math::deg2Rad(5.0f), 0.5f, ax);
                break;
            }
            case 'd':
            {
                gmtl::Matrix44f dMatrix;
                dMatrix[0][0] = 0.5f;
                dMatrix[1][1] = 1.0f;
                dMatrix[2][2] = -1.5f;
                osgdam->deform(model, dMatrix, false);
                break;
            }
            case 'l':
            {
                selectPoints.clear();
                selectPositions.clear();
                osgdam->unselectLatticeCellPoints(model);
                break;
            }
            case 'm':
            {
                osgdam->selectLatticeCellPoint(mgr, model, x, y, true);
                break;
            }
            case 'n':
            {
                osgdam->unselectLatticeCellPoint(mgr, model, x, y);
                break;
            }
            case '-':
            {
                gmtl::Vec3f pos;
                selectPositions.clear();
                selectPoints = osgdam->getSelection(model);
                for (size_t i = 0; i < selectPoints.size(); ++i)
                {
                    osgdam->getPoint(model, selectPoints[i], pos);
                    if (ax == 1)
                        pos[0] -= 0.5f;
                    else if (ax == 2)
                        pos[1] -= 0.5f;
                    else
                        pos[2] -= 0.5f;
                    selectPositions.push_back(pos);
                }
                osgdam->setPoints(model, selectPoints, selectPositions);
                break;
            }
            case '+':
            {
                gmtl::Vec3f pos;
                selectPositions.clear();
                selectPoints = osgdam->getSelection(model);
                for (size_t i = 0; i < selectPoints.size(); ++i)
                {
                    osgdam->getPoint(model, selectPoints[i], pos);
                    if (ax == 1)
                        pos[0] += 0.5f;
                    else if (ax == 2)
                        pos[1] += 0.5f;
                    else
                        pos[2] += 0.5f;
                    selectPositions.push_back(pos);
                }
                osgdam->setPoints(model, selectPoints, selectPositions);
                break;
            }
            case 'u':
            {
                osgdam->undo(model);
                break;
            }
            case 'x':
            {
                osgdam->executeFfd(model);
                break;
            }
            case 'o':
            {
                osgdam->dump(model);
                break;
            }
            default:
                break;
        }
    }
}
Example #16
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    // load the scene
    NodePtr scene = NullFC;
    
    if(argc < 2)
    {
        FWARNING(("No file given!\n"));
        FWARNING(("Supported file formats:\n"));
        
        std::list<const char*> suffixes;
        SceneFileHandler::the().getSuffixList(suffixes, SceneFileType::OSG_READ_SUPPORTED);
        
        for(std::list<const char*>::iterator it  = suffixes.begin();
                                             it != suffixes.end();
                                           ++it)
        {
            FWARNING(("%s\n", *it));
        }

        scene = makeTorus(.5, 2, 16, 16);
    }
    else
    {
        /*
            All scene file loading is handled via the SceneFileHandler.
        */
        scene = SceneFileHandler::the().read(argv[1]);
    }
    
    // calc size of the scene
    Vec3f min, max;
#ifndef OSG_2_PREP
    DynamicVolume vol;
#else
    BoxVolume     vol;
#endif
    scene->getWorldVolume(vol);
    vol.getBounds(min, max);

    Vec3f d = max - min;
    Real32 offset = d.length() / 2.0f;
    
    // now create a deep clone
    // we share the GenericAtt from the wrl loader without it crashes in deepClone setAbstrValue ...
    NodePtr sceneClone = deepCloneTree(scene, "GenericAtt");
    // this clones all nodes but the cores of type Material and Transform are shared.
    //NodePtr sceneClone = deepCloneTree(scene, "Material, Transform");
    
    // now change all geometries from the cloned scene just to show
    // that it is a real deep copy.
    traverse(sceneClone, 
             osgTypedFunctionFunctor1CPtrRef<Action::ResultE,
                                             NodePtr        >(changeGeo));
    
    // create a small scene graph with two transformation nodes.
    NodePtr root = makeCoredNode<Group>();
    ComponentTransformPtr t1;
    NodePtr tn1 = makeCoredNode<ComponentTransform>(&t1);
    ComponentTransformPtr t2;
    NodePtr tn2 = makeCoredNode<ComponentTransform>(&t2);
    
    beginEditCP(t1);
        t1->setTranslation(Vec3f(- offset, 0.0f, 0.0f));
    endEditCP(t1);
    beginEditCP(t2);
        t2->setTranslation(Vec3f(offset, 0.0f, 0.0f));
    endEditCP(t2);
    
    beginEditCP(tn1);
        tn1->addChild(scene);
    endEditCP(tn1);
    
    beginEditCP(tn2);
        tn2->addChild(sceneClone);
    endEditCP(tn2);
    
    beginEditCP(root);
        root->addChild(tn1);
        root->addChild(tn2);
    endEditCP(root);
    
    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (root);

    // show the whole scene
    mgr->showAll();
    
    // GLUT main loop
    glutMainLoop();

    return 0;
}
Example #17
0
NodePtr Puck::init()
{
	// CREATE THE PUCK
    NodePtr puck_trans_node = makeCoredNode<Transform>(&transPtr);
    beginEditCP(transPtr);
	{
		transPtr->getMatrix().setTranslate(position[0],position[1],position[2]);
	}
    endEditCP(transPtr);


    NodePtr puck = OSG::makeCylinder(PUCK_HALF_HEIGHT*2.0,radius, 32, true, true ,true);
    beginEditCP(puck_trans_node);
	{
		puck_trans_node->addChild(puck);
	}
    endEditCP(puck_trans_node);

    SimpleMaterialPtr puck_mat = SimpleMaterial::create();
    beginEditCP(puck_mat);
	{
		puck_mat->setAmbient(Color3f(0.0,0.0,0.0));
		puck_mat->setDiffuse(Color3f(1.0,0.0,0.0));
	}
    endEditCP(puck_mat);

    GeometryPtr puck_geo = GeometryPtr::dcast(puck->getCore());
    beginEditCP(puck_geo);
		puck_geo->setMaterial(puck_mat);
    beginEditCP(puck_geo);

	/////////////////////////////
	// SETUP THE INTERSECTION TEST COMPONENTS
	// Create a small geometry to show the ray and what was hit
    // Contains a line and a single triangle.
    // The line shows the ray, the triangle whatever was hit.
	isectPoints = GeoPositions3f::create();
    beginEditCP(isectPoints);
    {
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
        isectPoints->addValue(Pnt3f(0,0,0));
    }
    endEditCP(isectPoints);
	GeoIndicesUI32Ptr index = GeoIndicesUI32::create();     
    beginEditCP(index);
    {
        index->addValue(0);
        index->addValue(1);
        index->addValue(2);
        index->addValue(3);
        index->addValue(4);
    }
    endEditCP(index);

    GeoPLengthsUI32Ptr lens = GeoPLengthsUI32::create();    
    beginEditCP(lens);
    {
        lens->addValue(2);
        lens->addValue(3);
    }
    endEditCP(lens);
    
    GeoPTypesUI8Ptr type = GeoPTypesUI8::create();  
    beginEditCP(type);
    {
        type->addValue(GL_LINES);
        type->addValue(GL_TRIANGLES);
    }
    endEditCP(type);
    
    SimpleMaterialPtr red = SimpleMaterial::create();
    
    beginEditCP(red);
    {
        red->setDiffuse     (Color3f( 1,0,0 ));   
        red->setTransparency(0.5);   
        red->setLit         (false);   
    }
    endEditCP  (red);

    testgeocore = Geometry::create();
    beginEditCP(testgeocore);
    {
        testgeocore->setPositions(isectPoints);
        testgeocore->setIndices(index);
        testgeocore->setLengths(lens);
        testgeocore->setTypes(type);
        testgeocore->setMaterial(red);
    }
    endEditCP(testgeocore);   

	NodePtr testgeo = Node::create();
    beginEditCP(testgeo);
    {
        testgeo->setCore(testgeocore);
    }
    endEditCP(testgeo);
    
	beginEditCP(puck_trans_node);
	{
		puck_trans_node->addChild(testgeo);
	}


	return puck_trans_node;
}
Example #18
0
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindowEventProducer = createDefaultWindowEventProducer();
    WindowPtr MainWindow = TutorialWindowEventProducer->initWindow();

    TutorialWindowEventProducer->setDisplayCallback(display);
    TutorialWindowEventProducer->setReshapeCallback(reshape);

    TutorialUpdateListener TheUpdateListener;
    TutorialWindowEventProducer->addUpdateListener(&TheUpdateListener);

    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // Tell the Manager what to manage
    mgr->setWindow(MainWindow);
	

    // Make Main Scene Node and add the Torus
    NodePtr scene = osg::Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
        scene->setCore(osg::Group::create());
    endEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    //Create a FBO Source
    FBOSourceTextureFilterPtr TutorialFBOSourceTextureFilter = FBOSourceTextureFilter::create();
    beginEditCP(TutorialFBOSourceTextureFilter, FBOSourceTextureFilter::FBOFieldMask | FBOSourceTextureFilter::FBOSizeFieldMask);
        TutorialFBOSourceTextureFilter->setFBO(createSceneFBO());
        TutorialFBOSourceTextureFilter->setFBOSize(Vec2f(-1.0,-1.0));
    endEditCP(TutorialFBOSourceTextureFilter, FBOSourceTextureFilter::FBOFieldMask | FBOSourceTextureFilter::FBOSizeFieldMask);

    //Create a HDR filter
    std::string HDRFragProg = "";
    HDRFragProg += 
        "uniform sampler2D Slot0Texture;"
        "uniform float Exposure;"
        "uniform float MaxLuminance;"
        "uniform float Gamma;"
        "void main()"
        "{"
        "    vec3 Color = texture2D(Slot0Texture,gl_TexCoord[0].st).rgb;"
        //"    float Intensity = dot(vec3(0.3,0.59,0.11),Color);"
        "    float TonePercent = Exposure * ((Exposure/MaxLuminance + 1.0)/(Exposure + 1.0));"
        //Apply Tone Mapping And Gamma Correction
        "    Color = pow(Color * TonePercent, vec3(Gamma));"
        "    gl_FragColor = vec4(Color, 1.0);"
        "}";

    //Create a shader Filter
    HDRTextureFilter = ShaderTextureFilter::create();
    HDRTextureFilter->attachSource(TutorialFBOSourceTextureFilter, 0, 0);
    HDRTextureFilter->setFragmentSource(HDRFragProg);
    HDRTextureFilter->setUniformParameter("Exposure", Exposure);
    HDRTextureFilter->setUniformParameter("MaxLuminance", MaxLuminance);
    HDRTextureFilter->setUniformParameter("Gamma", Gamma);
	
	// Create the ImageProcessed Foreground Object
    ImageProcessedForegroundPtr TutorialImageProcessedForeground = ImageProcessedForeground::create();

    beginEditCP(TutorialImageProcessedForeground, ImageProcessedForeground::FilterFieldMask | ImageProcessedForeground::OutputSlotFieldMask);
        TutorialImageProcessedForeground->setFilter(HDRTextureFilter);
        TutorialImageProcessedForeground->setOutputSlot(0);
    endEditCP(TutorialImageProcessedForeground, ImageProcessedForeground::FilterFieldMask | ImageProcessedForeground::OutputSlotFieldMask);

    mgr->setRoot(scene);

    // Add the ImageProcessed Foreground Object to the Scene
    ViewportPtr TutorialViewport = mgr->getWindow()->getPort(0);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);
        TutorialViewport->getForegrounds().push_back(TutorialImageProcessedForeground);
    beginEditCP(TutorialViewport, Viewport::ForegroundsFieldMask);

    // Show the whole Scene
    mgr->showAll();


    //Open Window
    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
            WinSize,
            "03ScenePostProcessing");

    //Enter main Loop
    TutorialWindowEventProducer->mainLoop();

    osgExit();

    return 0;
}
Example #19
0
int MAST (NTree &T1, NTree &T2)
{
	int result = 0;

	// 1. create lists of the nodes in T1 and T2 in postorder
    int count = 0;
    NodeVector pot1;
    NodeIterator <Node> n1 (T1.GetRoot());
    Node *q = n1.begin();
    while (q)
    {
    	q->SetIndex (count);
		pot1.push_back ((NNode *)q);
		count++;
		q = n1.next();
    }

    count = 0;
    NodeVector pot2;
    NodeIterator <Node> n2 (T2.GetRoot());
    q = n2.begin();
    while (q)
    {
    	q->SetIndex (count);
		pot2.push_back ((NNode *)q);
		count++;
        q = n2.next();
    }

	// Matrix to hold solutions
    int **m;

    m = new int *[T1.GetNumNodes()];
    for (int i = 0; i < T1.GetNumNodes(); i++)
    	m[i] = new int [T2.GetNumNodes()];

    for (int i = 0; i < T1.GetNumNodes(); i++)
    	for (int j = 0; j <T2.GetNumNodes(); j++)
        	m[i][j] = 0;


	// 2. Visit all pairs of nodes in T1 and T2
     for (int i = 0; i < T1.GetNumNodes(); i++)
     {
    	for (int j = 0; j <T2.GetNumNodes(); j++)
        {
			if (pot1[i]->IsLeaf() || pot2[j]->IsLeaf())
            {
            	// Both are leaves, so MAST[i,j] is 1 if labels are identical
            	if (pot1[i]->IsLeaf() && pot2[j]->IsLeaf())
				{
                	if ( pot1[i]->GetLabel() == pot2[j]->GetLabel())
                    	m[i][j] = 1;
				}
				else
				{
            		// Only one is a leaf, so MAST[i,j] is 1 if leaf is element in cluster
					IntegerSet common;
					std::set_intersection (pot1[i]->Cluster.begin(), pot1[i]->Cluster.end(),
						pot2[j]->Cluster.begin(), pot2[j]->Cluster.end(),
						std::inserter (common, common.end()));
					int w = common.size();
                	m[i][j] = w;
				}
        	}
            else
            {
            	// Both are internals so MAST[i,j] is MAX (diag, match)
                std::vector <NodePtr> pchildren, qchildren;

                // diag
                int diag = 0;

                // Get MAST of base of subtree in t1 and immediate children of
                // base of subtree in t2, and at the same time store list of
                // immediate children
                NodePtr p = pot2[j]->GetChild();
                while (p)
                {
                	qchildren.push_back(p);
                	diag = std::max (diag, m[i][p->GetIndex()]);
                    p = p->GetSibling();
                }
                // get MAST of base of subtree in t2 and immediate children of
                // base of subtree in t1, and at the same time store list of
                // immediate children
                NodePtr q = pot1[i]->GetChild();
                while (q)
                {
                	pchildren.push_back(q);
                	diag = std::max (diag, m[q->GetIndex()][j]);
                    q = q->GetSibling();
                }

                // maximum weighted bipartite matching
				
#if USE_MATCHING
				int match = 0;
				graph g;
				g.make_directed();
				
				// Nodes for p and q children
				map <int, node, less <int> > p_node;
				map <int, node, less <int> > q_node;
				for (int k = 0; k < pchildren.size(); k++)
                {
					node n = g.new_node();
					p_node[k] = n;
                }
				for (int k = 0; k < qchildren.size(); k++)
                {
					node n = g.new_node();
					q_node[k] = n;
                }
				// Edges
				edge_map<int> weights(g, 0);

				
				for (int k = 0; k < pchildren.size(); k++)
				{
					for (int r = 0; r < qchildren.size(); r++)
					{
						int v = pchildren[k]->GetIndex();
                        int w = qchildren[r]->GetIndex();
						
						// It seems that if the partition "from" is much larger than "to,
						// the matching algorithm can blow up with a memory access error
						// in fheap.c. Reversing the graph seems to help.
						
						edge e;
						if (pchildren.size() < qchildren.size())
							e = g.new_edge (p_node[k], q_node[r]);
						else
							e = g.new_edge (q_node[r], p_node[k]);
						
						weights[e] = m[v][w];
					}
				}
				
//				cout << "g" << endl;
//				cout << g;
//				g.save();
//				cout << "Start matching...";
				
				if (g.number_of_nodes() == 0)
				{
					match = 0;
				}
				
				else
				{
				
				mwbmatching mwbm;
				mwbm.set_vars (weights);
				
				if (mwbm.check(g) != algorithm::GTL_OK)
				{
					cout << "Maximum weight bipartite matching algorithm check failed" << endl;
					exit(1);
				}
				else
				{
					if (mwbm.run(g) != algorithm::GTL_OK)
					{
						cout << "Error running maximum weight bipartite matching algorithm" << endl;
						exit(1);
					}
					else
					{
						match = mwbm.get_mwbm();
					}
				}
				}
//				cout << "matching done (" << match << ")" << endl;
#else
                // For now (sigh) brute force generation of all matchings. Eventually
                // will need to do this more efficiently
                int n = std::max (pchildren.size(), qchildren.size());

                // Store a vector of indices of children of subtree in t2.
                // We will permute this to generate all matchings. If t2
                // has fewer children than subtree in t1, vector will contain
                // one or more "null" (-1) values.
                std::vector <int> perm;
                for (int k = 0; k < n; k++)
                {
                	if (k < qchildren.size())
	                	perm.push_back (k);
                    else
                    	perm.push_back (-1);
                }

                // Generate all matchings

                // First matching
                int match = 0;
               	for (int k = 0; k < n; k++)
                {
                    if ((k < pchildren.size()) && (perm[k] != -1))
                    {
                    	int v = pchildren[k]->GetIndex();
                        int w = qchildren[perm[k]]->GetIndex();
                        match += m[v][w];
                    }
                }

                // Remaining matchings
                while  (next_permutation (perm.begin(), perm.end()) )
                {
                	int this_match = 0;
                    for (int k = 0; k < n; k++)
                    {
                        if ((k < pchildren.size()) && (perm[k] != -1))
                        {
                            int v = pchildren[k]->GetIndex();
                            int w = qchildren[perm[k]]->GetIndex();
                            this_match += m[v][w];
                        }
                    }
                    match = std::max (match, this_match);
                }
#endif
                m[i][j] = std::max (diag, match);
            }
		}
     }

     result = m[T1.GetNumNodes() - 1][T2.GetNumNodes() - 1];
	 
	 // Show matrix
/*	 for (int i = 0; i < T1.GetNumNodes(); i++)
	 {
	 	cout << setw(3) << i << "|";
		for (int j = 0; j < T2.GetNumNodes(); j++)
			cout << setw(3) << m[i][j];
		cout << endl;
	}
*/

     // clean up
    for (int i = 0; i < T1.GetNumNodes(); i++)
       	delete [] m[i];

    delete [] m;

	return result;
}
Example #20
0
FBOViewportPtr createSceneFBO(void)
{
    //Create Camera Beacon
    Matrix CameraMat;
    CameraMat.setTranslate(0.0f,0.0f,4.0f);
    TransformPtr CameraBeconCore = Transform::create();
    beginEditCP(CameraBeconCore, Transform::MatrixFieldMask);
        CameraBeconCore->setMatrix(CameraMat);
    endEditCP(CameraBeconCore, Transform::MatrixFieldMask);

    NodePtr CameraBeconNode = Node::create();
    beginEditCP(CameraBeconNode, Node::CoreFieldMask);
        CameraBeconNode->setCore(CameraBeconCore);
    endEditCP(CameraBeconNode, Node::CoreFieldMask);

    //Create Camera
    PerspectiveCameraPtr TheCamera = PerspectiveCamera::create();
    beginEditCP(TheCamera);
        TheCamera->setFov(deg2rad(60.0f));
        TheCamera->setAspect(1.0f);
        TheCamera->setNear(0.1f);
        TheCamera->setFar(100.0f);
        TheCamera->setBeacon(CameraBeconNode);
    endEditCP(TheCamera);
    
    //Make the Material
    BlinnMaterialPtr TheMaterial = BlinnMaterial::create();
    beginEditCP(TheMaterial);
        TheMaterial->setDiffuse(0.8);
        TheMaterial->setColor(Color3f(1.0,1.0,1.0));
        TheMaterial->setAmbientColor(Color3f(1.0,1.0,1.0));
        TheMaterial->setNumLights(1);
    endEditCP(TheMaterial);

										
    // Make Torus Node (creates Torus in background of scene)
    NodePtr TorusGeometryNode = makeTorus(.5, 2, 24, 48);

    beginEditCP(TorusGeometryNode->getCore());
        GeometryPtr::dcast(TorusGeometryNode->getCore())->setMaterial(TheMaterial);
    endEditCP(TorusGeometryNode->getCore());
    calcVertexNormals(GeometryPtr::dcast(TorusGeometryNode->getCore()));
    calcVertexTangents(GeometryPtr::dcast(TorusGeometryNode->getCore()),0,Geometry::TexCoords7FieldId, Geometry::TexCoords6FieldId);

    RootTransformCore = Transform::create();

    NodePtr TorusTransformNode = Node::create();
    beginEditCP(TorusTransformNode, Node::CoreFieldMask);
        TorusTransformNode->setCore(RootTransformCore);
        TorusTransformNode->addChild(TorusGeometryNode);
    endEditCP(TorusTransformNode, Node::CoreFieldMask);

    //Create Light Beacon
    Matrix LightMat;
    LightMat.setTranslate(0.0f,10.0f,1.0f);
    TransformPtr LightBeconCore = Transform::create();
    beginEditCP(LightBeconCore, Transform::MatrixFieldMask);
        LightBeconCore->setMatrix(LightMat);
    endEditCP(LightBeconCore, Transform::MatrixFieldMask);

    NodePtr LightBeconNode = Node::create();
    beginEditCP(LightBeconNode, Node::CoreFieldMask);
        LightBeconNode->setCore(LightBeconCore);
    endEditCP(LightBeconNode, Node::CoreFieldMask);

    //Create Light
    TheLight = PointLight::create();
    beginEditCP(TheLight);
        TheLight->setBeacon(LightBeconNode);
    endEditCP(TheLight);

    NodePtr LightNode = Node::create();
    beginEditCP(LightNode, Node::CoreFieldMask);
        LightNode->setCore(TheLight);
        LightNode->addChild(TorusTransformNode);
    endEditCP(LightNode, Node::CoreFieldMask);


    //Create Root

    NodePtr TheRoot = Node::create();
    beginEditCP(TheRoot);
        TheRoot->setCore(Group::create());
        TheRoot->addChild(CameraBeconNode);
        TheRoot->addChild(LightNode);
        TheRoot->addChild(LightBeconNode);
    endEditCP(TheRoot);

    //Create Background
    SolidBackgroundPtr TheBackground = SolidBackground::create();
    TheBackground->setColor(Color3f(1.0,0.0,0.0));

    //DepthClearBackgroundPtr TheBackground = DepthClearBackground::create();

    //Create the Image
    ImagePtr TheColorImage = Image::create();
    TheColorImage->set(Image::OSG_RGB_PF,2,2,1,1,1,0.0f,0,Image::OSG_FLOAT16_IMAGEDATA);

    //Create the texture
    TextureChunkPtr TheColorTextureChunk = TextureChunk::create();
    beginEditCP(TheColorTextureChunk);
        TheColorTextureChunk->setImage(TheColorImage);

        TheColorTextureChunk->setMinFilter(GL_NEAREST);
        TheColorTextureChunk->setMagFilter(GL_NEAREST);

        TheColorTextureChunk->setWrapS(GL_CLAMP_TO_EDGE);
        TheColorTextureChunk->setWrapR(GL_CLAMP_TO_EDGE);

        TheColorTextureChunk->setScale(false);
        TheColorTextureChunk->setNPOTMatrixScale(true);
        
        TheColorTextureChunk->setEnvMode(GL_REPLACE);
        TheColorTextureChunk->setInternalFormat(GL_RGB16F);

    endEditCP(TheColorTextureChunk);


    //Create FBO
    FBOViewportPtr TheFBO = FBOViewport::create();
    beginEditCP(TheFBO);
        TheFBO->setBackground(TheBackground);
        TheFBO->setRoot(TheRoot);
        TheFBO->setCamera(TheCamera);

        TheFBO->setEnabled(true);
        TheFBO->getTextures().push_back(TheColorTextureChunk);

        TheFBO->setStorageWidth(TheColorTextureChunk->getImage()->getWidth());
        TheFBO->setStorageHeight(TheColorTextureChunk->getImage()->getHeight());
        
        TheFBO->setSize(0,0,TheColorTextureChunk->getImage()->getWidth()-1, TheColorTextureChunk->getImage()->getHeight()-1);
    endEditCP(TheFBO);
    return TheFBO;
}
Example #21
0
void NodeVisitor::visit(NodePtr node)
{
    node->accept(this, node);
}
Example #22
0
bool Object::send( NodePtr node, ObjectPacket& packet )
{
    EQASSERT( isAttached( ));
    packet.objectID  = _id;
    return node->send( packet );
}
Example #23
0
void
Project::restoreInput(const NodePtr& node,
                      const std::string& inputLabel,
                      const std::string& inputNodeScriptName,
                      const std::list<std::pair<NodePtr, SERIALIZATION_NAMESPACE::NodeSerializationPtr > >& allCreatedNodesInGroup,
                      bool isMaskInput)
{
    if ( inputNodeScriptName.empty() ) {
        return;
    }
    int index = inputLabel.empty() ? -1 : node->getInputNumberFromLabel(inputLabel);
    if (index == -1) {

        // If the name of the input was not serialized, the string is the index
        bool ok;
        index = QString::fromUtf8(inputLabel.c_str()).toInt(&ok);
        if (!ok) {
            index = -1;
        }
        if (index == -1) {
            appPTR->writeToErrorLog_mt_safe(QString::fromUtf8(node->getScriptName().c_str()), QDateTime::currentDateTime(),
                                            tr("Could not find input named %1")
                                            .arg( QString::fromUtf8( inputNodeScriptName.c_str() ) ) );

        }

        // If the node had a single mask, the inputLabel was "0", indicating the index of the mask
        // So iterate through masks to find it
        if (isMaskInput) {
            // Find the mask corresponding to the index
            int nInputs = node->getMaxInputCount();
            int maskIndex = 0;
            for (int i = 0; i < nInputs; ++i) {
                if (node->getEffectInstance()->isInputMask(i)) {
                    if (maskIndex == index) {
                        index = i;
                        break;
                    }
                    ++maskIndex;
                    break;
                }
            }
        }
    }
    
    NodeCollectionPtr nodeGroup = node->getGroup();
    if (!nodeGroup) {
        return;
    }
    // The nodes created from the serialization may have changed name if another node with the same script-name already existed.
    // By chance since we created all nodes within the same Group at the same time, we have a list of the old node serialization
    // and the corresponding created node (with its new script-name).
    // If we find a match, make sure we use the new node script-name to restore the input.
    NodePtr foundNode = findNodeWithScriptName(inputNodeScriptName, allCreatedNodesInGroup);
    if (!foundNode) {
        return;


        // Commented-out: Do not attempt to get the node in the nodes list: all nodes within a sub-graph should be connected to nodes at this level.
        // If it cannot be found in the allCreatedNodesInGroup then this is likely the user does not want the input to connect.
        //foundNode = nodeGroup->getNodeByName(inputNodeScriptName);
    }

    bool ok = node->getGroup()->connectNodes(index, foundNode, node);
    (void)ok;


} //restoreInput
Example #24
0
void
OutputEffectInstance::reportStats(int time,
                                  ViewIdx view,
                                  double wallTime,
                                  const std::map<NodePtr, NodeRenderStats > & stats)
{
    std::string filename;
    KnobPtr fileKnob = getKnobByName(kOfxImageEffectFileParamName);

    if (fileKnob) {
        KnobOutputFile* strKnob = dynamic_cast<KnobOutputFile*>( fileKnob.get() );
        if  (strKnob) {
            QString qfileName = QString::fromUtf8( SequenceParsing::generateFileNameFromPattern(strKnob->getValue( 0, ViewIdx(view) ), getApp()->getProject()->getProjectViewNames(), time, view).c_str() );
            QtCompat::removeFileExtension(qfileName);
            qfileName.append( QString::fromUtf8("-stats.txt") );
            filename = qfileName.toStdString();
        }
    }

    //If there's no filename knob, do not write anything
    if ( filename.empty() ) {
        std::cout << tr("Cannot write render statistics file: "
                        "%1 does not seem to have a parameter named \"filename\" "
                        "to determine the location where to write the stats file.")
            .arg( QString::fromUtf8( getScriptName_mt_safe().c_str() ) ).toStdString();

        return;
    }


    FStreamsSupport::ofstream ofile;
    FStreamsSupport::open(&ofile, filename);
    if (!ofile) {
        std::cout << tr("Failure to write render statistics file.").toStdString() << std::endl;

        return;
    }

    ofile << "Time spent to render frame (wall clock time): " << Timer::printAsTime(wallTime, false).toStdString() << std::endl;
    for (std::map<NodePtr, NodeRenderStats >::const_iterator it = stats.begin(); it != stats.end(); ++it) {
        ofile << "------------------------------- " << it->first->getScriptName_mt_safe() << "------------------------------- " << std::endl;
        ofile << "Time spent rendering: " << Timer::printAsTime(it->second.getTotalTimeSpentRendering(), false).toStdString() << std::endl;
        const RectD & rod = it->second.getRoD();
        ofile << "Region of definition: x1 = " << rod.x1  << " y1 = " << rod.y1 << " x2 = " << rod.x2 << " y2 = " << rod.y2 << std::endl;
        ofile << "Is Identity to Effect? ";
        NodePtr identity = it->second.getInputImageIdentity();
        if (identity) {
            ofile << "Yes, to " << identity->getScriptName_mt_safe() << std::endl;
        } else {
            ofile << "No" << std::endl;
        }
        ofile << "Has render-scale support? ";
        if ( it->second.isRenderScaleSupportEnabled() ) {
            ofile << "Yes";
        } else {
            ofile << "No";
        }
        ofile << std::endl;
        ofile << "Has tiles support? ";
        if ( it->second.isTilesSupportEnabled() ) {
            ofile << "Yes";
        } else {
            ofile << "No";
        }
        ofile << std::endl;
        ofile << "Channels processed: ";

        std::bitset<4> processChannels = it->second.getChannelsRendered();
        if (processChannels[0]) {
            ofile << "red ";
        }
        if (processChannels[1]) {
            ofile << "green ";
        }
        if (processChannels[2]) {
            ofile << "blue ";
        }
        if (processChannels[3]) {
            ofile << "alpha";
        }
        ofile << std::endl;

        ofile << "Output alpha premultiplication: ";
        switch ( it->second.getOutputPremult() ) {
        case eImagePremultiplicationOpaque:
            ofile << "opaque";
            break;
        case eImagePremultiplicationPremultiplied:
            ofile << "premultiplied";
            break;
        case eImagePremultiplicationUnPremultiplied:
            ofile << "unpremultiplied";
            break;
        }
        ofile << std::endl;

        ofile << "Mipmap level(s) rendered: ";
        for (std::set<unsigned int>::const_iterator it2 = it->second.getMipMapLevelsRendered().begin(); it2 != it->second.getMipMapLevelsRendered().end(); ++it2) {
            ofile << *it2 << ' ';
        }
        ofile << std::endl;
        int nbCacheMiss, nbCacheHit, nbCacheHitButDownscaled;
        it->second.getCacheAccessInfos(&nbCacheMiss, &nbCacheHit, &nbCacheHitButDownscaled);
        ofile << "Nb cache hit: " << nbCacheMiss << std::endl;
        ofile << "Nb cache miss: " << nbCacheMiss << std::endl;
        ofile << "Nb cache hit requiring mipmap downscaling: " << nbCacheHitButDownscaled << std::endl;

        const std::set<std::string> & planes = it->second.getPlanesRendered();
        ofile << "Plane(s) rendered: ";
        for (std::set<std::string>::const_iterator it2 = planes.begin(); it2 != planes.end(); ++it2) {
            ofile << *it2 << ' ';
        }
        ofile << std::endl;

        std::list<std::pair<RectI, NodePtr > > identityRectangles = it->second.getIdentityRectangles();
        const std::list<RectI> & renderedRectangles = it->second.getRenderedRectangles();

        ofile << "Identity rectangles: " << identityRectangles.size() << std::endl;
        for (std::list<std::pair<RectI, NodePtr > > ::iterator it2 = identityRectangles.begin(); it2 != identityRectangles.end(); ++it2) {
            ofile << "Origin: " << it2->second->getScriptName_mt_safe() << ", rect: x1 = " << it2->first.x1
                  << " y1 = " << it2->first.y1 << " x2 = " << it2->first.x2 << " y2 = " << it2->first.y2 << std::endl;
        }

        ofile << "Rectangles rendered: " << renderedRectangles.size() << std::endl;
        for (std::list<RectI>::const_iterator it2 = renderedRectangles.begin(); it2 != renderedRectangles.end(); ++it2) {
            ofile << "x1 = " << it2->x1 << " y1 = " << it2->y1 << " x2 = " << it2->x2 << " y2 = " << it2->y2 << std::endl;
        }
    }
} // OutputEffectInstance::reportStats
Example #25
0
 void post(NIFFile *nif)
 {
     Controller::post(nif);
     emitter.post(nif);
     extra.post(nif);
 }
Example #26
0
 static void drop(DrawActionBase *action, NodePtr node, Color3f col)
 {
     node->updateVolume();
     
     drop(action, node->getVolume(), col);
 }
Example #27
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);
    gwin = GLUTWindow::create();

    // create root
    rootNode = makeCoredNode<Group>();
    NodePtr scene = makeCoredNode<Group>();

    // create lights
    TransformPtr point1_trans;
    NodePtr point1 = makeCoredNode<PointLight>(&_point1_core);
    NodePtr point1_beacon = makeCoredNode<Transform>(&point1_trans);
    beginEditCP(point1_trans);
        point1_trans->editMatrix().setTranslate(0.0, 0.0, 25.0);
    endEditCP(point1_trans);

    beginEditCP(_point1_core);
        _point1_core->setAmbient(0.15,0.15,0.15,1);
        _point1_core->setDiffuse(0.4,0.4,0.4,1);
        _point1_core->setSpecular(0.0,0.0,0.0,1);
        _point1_core->setBeacon(point1_beacon);
        _point1_core->setOn(true);
    endEditCP(_point1_core);

    TransformPtr point2_trans;
    NodePtr point2 = makeCoredNode<PointLight>(&_point2_core);
    NodePtr point2_beacon = makeCoredNode<Transform>(&point2_trans);
    beginEditCP(point2_trans);
        point2_trans->editMatrix().setTranslate(5.0, 5.0, 20.0);
    endEditCP(point2_trans);

    beginEditCP(_point2_core);
        _point2_core->setAmbient(0.15,0.15,0.15,1);
        _point2_core->setDiffuse(0.4,0.4,0.4,1);
        _point2_core->setSpecular(0.0,0.0,0.0,1);
        _point2_core->setBeacon(point2_beacon);
        _point2_core->setOn(true);
    endEditCP(_point2_core);

    beginEditCP(point1);
        point1->addChild(point2);
    endEditCP(point1);

    beginEditCP(point2);
        point2->addChild(scene);
    endEditCP(point2);

    // create scene
    
    // bottom
    NodePtr plane = makePlane(25.0, 25.0, 128, 128);
    
    int size = imageWinWidth*imageWinHeight*256;

    ImagePtr plane_img = Image::create();

    beginEditCP(plane_img);
    plane_img->set(Image::OSG_RGBA_PF, imageWinWidth, imageWinHeight, 1, 1, 1, 0, NULL);
    endEditCP(plane_img);

    TextureChunkPtr plane_tex = TextureChunk::create();
    beginEditCP(plane_tex);
        plane_tex->setImage(plane_img);
        plane_tex->setMinFilter(GL_LINEAR);
        plane_tex->setMagFilter(GL_LINEAR);
        plane_tex->setTarget(GL_TEXTURE_2D);
        plane_tex->setInternalFormat(GL_RGBA16F_ARB);
    endEditCP(plane_tex);

    SHLChunkPtr shl = SHLChunk::create();
    beginEditCP(shl);
        shl->setVertexProgram(_vp_program);
        shl->setFragmentProgram(_fp_program);
        shl->setUniformParameter("tex0", 0);
    endEditCP(shl);

    SimpleMaterialPtr plane_mat = SimpleMaterial::create();
    beginEditCP(plane_mat);
        plane_mat->setAmbient(Color3f(0.3,0.3,0.3));
        plane_mat->setDiffuse(Color3f(1.0,1.0,1.0));
        plane_mat->addChunk(plane_tex);
        plane_mat->addChunk(shl);
    endEditCP(plane_mat);

    GeometryPtr plane_geo = GeometryPtr::dcast(plane->getCore());
    beginEditCP(plane_geo);
        plane_geo->setMaterial(plane_mat);
    beginEditCP(plane_geo);
    
    // box
    box_trans_node = makeCoredNode<Transform>(&_box_trans);
    beginEditCP(_box_trans);
        _box_trans->editMatrix().setTranslate(0.0, 0.0, 12.0);
    endEditCP(_box_trans);
    NodePtr box = makeBox(4.0, 4.0, 0.8, 10, 10 , 10);
    beginEditCP(box_trans_node);
        box_trans_node->addChild(box);
    endEditCP(box_trans_node);
    
    PolygonChunkPtr pchunk = osg::PolygonChunk::create();
    beginEditCP(pchunk);
        pchunk->setCullFace(GL_BACK);
    endEditCP(pchunk);

    SimpleMaterialPtr box_mat = SimpleMaterial::create();
    beginEditCP(box_mat);
        box_mat->setAmbient(Color3f(0.0,0.0,0.0));
        box_mat->setDiffuse(Color3f(0.0,0.0,1.0));
        box_mat->addChunk(pchunk);
    endEditCP(box_mat);

    GeometryPtr box_geo = GeometryPtr::dcast(box->getCore());
    beginEditCP(box_geo);
        box_geo->setMaterial(box_mat);
    beginEditCP(box_geo);

    // cylinder1
    NodePtr cylinder1_trans_node = makeCoredNode<Transform>(&_cylinder1_trans);
    beginEditCP(_cylinder1_trans);
        _cylinder1_trans->editMatrix().setTranslate(0.0, 0.0, 5.0);
    endEditCP(_cylinder1_trans);
    NodePtr cylinder1 = OSG::makeCylinder(10.0, 0.4, 32, true, true ,true);
    beginEditCP(cylinder1_trans_node);
        cylinder1_trans_node->addChild(cylinder1);
    endEditCP(cylinder1_trans_node);

    SimpleMaterialPtr cylinder1_mat = SimpleMaterial::create();
    beginEditCP(cylinder1_mat);
        cylinder1_mat->setAmbient(Color3f(0.0,0.0,0.0));
        cylinder1_mat->setDiffuse(Color3f(1.0,0.0,0.0));
        cylinder1_mat->addChunk(pchunk);
    endEditCP(cylinder1_mat);

    GeometryPtr cylinder1_geo = GeometryPtr::dcast(cylinder1->getCore());
    beginEditCP(cylinder1_geo);
        cylinder1_geo->setMaterial(cylinder1_mat);
    beginEditCP(cylinder1_geo);
    
    // cylinder2
    NodePtr cylinder2_trans_node = makeCoredNode<Transform>(&_cylinder2_trans);
    beginEditCP(_cylinder2_trans);
        _cylinder2_trans->editMatrix().setTranslate(0.0, 0.0, 8.0);
    endEditCP(_cylinder2_trans);
    NodePtr cylinder2 = OSG::makeCylinder(10.0, 0.4, 32, true, true ,true);
    beginEditCP(cylinder2_trans_node);
        cylinder2_trans_node->addChild(cylinder2);
    endEditCP(cylinder2_trans_node);

    SimpleMaterialPtr cylinder2_mat = SimpleMaterial::create();
    beginEditCP(cylinder2_mat);
        cylinder2_mat->setAmbient(Color3f(0.0,0.0,0.0));
        cylinder2_mat->setDiffuse(Color3f(0.0,1.0,0.0));
        cylinder2_mat->addChunk(pchunk);
    endEditCP(cylinder2_mat);

    GeometryPtr cylinder2_geo = GeometryPtr::dcast(cylinder2->getCore());
    beginEditCP(cylinder2_geo);
        cylinder2_geo->setMaterial(cylinder2_mat);
    beginEditCP(cylinder2_geo);

    // scene
    beginEditCP(scene);
        scene->addChild(plane);
        scene->addChild(box_trans_node);
        scene->addChild(cylinder1_trans_node);
        scene->addChild(cylinder2_trans_node);
    endEditCP(scene);

    vp = ShadowViewport::create();
    
    GradientBackgroundPtr gbg = GradientBackground::create();
    SolidBackgroundPtr sbg = SolidBackground::create();

    UChar8 imgdata[] = {  255,0,0,  0,255,0,  0,0,255, 255,255,0 };
    ImagePtr img1 = Image::create();
    img1->set(Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, imgdata);

    TextureChunkPtr tcPtr = TextureChunk::create();
    beginEditCP(tcPtr);
        tcPtr->setImage(img1);
    endEditCP(tcPtr);
    TextureBackgroundPtr bkg = TextureBackground::create();
    beginEditCP(bkg);
        bkg->setTexture(tcPtr);
    endEditCP(bkg);
    
    beginEditCP(sbg);
        sbg->setColor(Color3f(0.2,0.4,0.6));
    endEditCP(sbg);
    
    beginEditCP(gbg);
        gbg->addLine(Color3f(0.7, 0.7, 0.8), 0);
        gbg->addLine(Color3f(0.1, 0.1, 0.3), 1);
    endEditCP(gbg);

    beginEditCP(rootNode);
        rootNode->addChild(point1);
        rootNode->addChild(point1_beacon);
        rootNode->addChild(point2_beacon);
    endEditCP(rootNode);

    //FBOViewportPtr
    fbo_vp = FBOViewport::create();
    addRefCP(fbo_vp);

    // the Camera for the map
    cam = PerspectiveCamera::create();
    beginEditCP(cam);
        cam->setFov(osgdegree2rad(90));
        cam->setAspect(1);
        cam->setNear(0.001);
        cam->setFar(10000);
        cam->setBeacon(box_trans_node);
    endEditCP(cam);

    beginEditCP(fbo_vp);
        fbo_vp->setBackground(bkg);
        fbo_vp->setRoot(rootNode);
        fbo_vp->setCamera(cam);
        fbo_vp->setSize(0,0,imageWinWidth-1, imageWinHeight-1);
        fbo_vp->setStorageWidth(imageWinWidth);
        fbo_vp->setStorageHeight(imageWinHeight);
        fbo_vp->setDirty(true);
        fbo_vp->editMFTextures    ()->push_back(plane_tex);
        fbo_vp->editMFExcludeNodes()->push_back(plane);
        fbo_vp->setFboOn(true);
    endEditCP(fbo_vp);

    // normal shadow viewport
    beginEditCP(vp);
        vp->setBackground(gbg);
        vp->setRoot(rootNode);
        vp->setSize(0,0,1,1);
    endEditCP(vp);

    beginEditCP(gwin); //Window
        gwin->setId(winid);
        gwin->addPort(vp);
        gwin->init();
    endEditCP(gwin);

    Vec3f min,max;
    rootNode->updateVolume();
    rootNode->getVolume().getBounds( min, max );

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    mgr->setWindow(gwin);
    mgr->setRoot(rootNode);

    //Viewport
    beginEditCP(vp);
        vp->setCamera(mgr->getCamera());
    endEditCP(vp);

    mgr->turnHeadlightOff();

    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
Example #28
0
void
BaseTest::disconnectNodes(const NodePtr& input,
                          const NodePtr& output,
                          bool expectedReturnvalue)
{
    if (expectedReturnvalue) {
        ///check that the connections are internally all set as "expected"

        ///the input must have in its output the node 'output'
        EXPECT_TRUE( input->hasOutputConnected() );
        const NodesWList & outputs = input->getGuiOutputs();
        bool foundOutput = false;
        for (NodesWList::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
            if (it->lock() == output) {
                foundOutput = true;
                break;
            }
        }

        ///the output must have in its inputs the node 'input'
        const std::vector<NodeWPtr> & inputs = output->getGuiInputs();
        int inputIndex = 0;
        bool foundInput = false;
        for (U32 i = 0; i < inputs.size(); ++i) {
            if (inputs[i].lock() == input) {
                foundInput = true;
                break;
            }
            ++inputIndex;
        }

        EXPECT_TRUE(foundInput);
        EXPECT_TRUE(foundOutput);
        EXPECT_EQ(output->getInput(inputIndex), input);
        EXPECT_TRUE( output->isInputConnected(inputIndex) );
    }

    ///call disconnect
    bool ret = getApp()->getProject()->disconnectNodes(input, output);
    EXPECT_EQ(expectedReturnvalue, ret);

    if (expectedReturnvalue) {
        ///check that the disconnection went OK

        const NodesWList & outputs = input->getGuiOutputs();
        bool foundOutput = false;
        for (NodesWList::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
            if (it->lock() == output) {
                foundOutput = true;
                break;
            }
        }

        ///the output must have in its inputs the node 'input'
        const std::vector<NodeWPtr> & inputs = output->getGuiInputs();
        int inputIndex = 0;
        bool foundInput = false;
        for (U32 i = 0; i < inputs.size(); ++i) {
            if (inputs[i].lock() == input) {
                foundInput = true;
                break;
            }
            ++inputIndex;
        }

        EXPECT_FALSE(foundOutput);
        EXPECT_FALSE(foundInput);
        EXPECT_EQ( (Node*)NULL, output->getInput(inputIndex).get() );
        EXPECT_FALSE( output->isInputConnected(inputIndex) );
    }
} // disconnectNodes
Example #29
0
	virtual bool equalTo(const NodePtr& other)
	{
		NumericType* nt = dynamic_cast<NumericType*>(other.get());
		if (!nt) return false;
		return (name == nt->name);
	}
Example #30
0
 void read(NIFStream *nif)
 {
     data.read(nif);
     root.read(nif);
     bones.read(nif);
 }