void SoFCIndexedFaceSet::doAction(SoAction * action)
{
    if (action->getTypeId() == Gui::SoGLSelectAction::getClassTypeId()) {
        SoNode* node = action->getNodeAppliedTo();
        if (!node) return; // on no node applied

        // The node we have is the parent of this node and the coordinate node
        // thus we search there for it.
        SoSearchAction sa;
        sa.setInterest(SoSearchAction::FIRST);
        sa.setSearchingAll(false);
        sa.setType(SoCoordinate3::getClassTypeId(), 1);
        sa.apply(node);
        SoPath * path = sa.getPath();
        if (!path) return;

        // make sure we got the node we wanted
        SoNode* coords = path->getNodeFromTail(0);
        if (!(coords && coords->getTypeId().isDerivedFrom(SoCoordinate3::getClassTypeId())))
            return;
        startSelection(action);
        renderSelectionGeometry(static_cast<SoCoordinate3*>(coords)->point.getValues(0));
        stopSelection(action);
    }
    else if (action->getTypeId() == Gui::SoVisibleFaceAction::getClassTypeId()) {
        SoNode* node = action->getNodeAppliedTo();
        if (!node) return; // on no node applied

        // The node we have is the parent of this node and the coordinate node
        // thus we search there for it.
        SoSearchAction sa;
        sa.setInterest(SoSearchAction::FIRST);
        sa.setSearchingAll(false);
        sa.setType(SoCoordinate3::getClassTypeId(), 1);
        sa.apply(node);
        SoPath * path = sa.getPath();
        if (!path) return;

        // make sure we got the node we wanted
        SoNode* coords = path->getNodeFromTail(0);
        if (!(coords && coords->getTypeId().isDerivedFrom(SoCoordinate3::getClassTypeId())))
            return;
        startVisibility(action);
        renderVisibleFaces(static_cast<SoCoordinate3*>(coords)->point.getValues(0));
        stopVisibility(action);
    }

    inherited::doAction(action);
}
void ViewProviderVRMLObject::getLocalResources(SoNode* node, std::list<std::string>& resources)
{
    // search for SoVRMLInline files
    SoSearchAction sa;
    sa.setType(SoVRMLInline::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.setSearchingAll(true);
    sa.apply(node);

    const SoPathList & pathlist = sa.getPaths();
    for (int i = 0; i < pathlist.getLength(); i++ ) {
        SoPath * path = pathlist[i];
        SoVRMLInline * vrml = static_cast<SoVRMLInline*>(path->getTail());
        const SbString& url = vrml->getFullURLName();
        if (url.getLength() > 0) {
            // add the resource file if not yet listed
            if (std::find(resources.begin(), resources.end(), url.getString()) == resources.end()) {
                resources.push_back(url.getString());
            }

            // if the resource file could be loaded check if it references further resources
            if (vrml->getChildData()) {
                getLocalResources(vrml->getChildData(), resources);
            }
        }
    }

    // search for SoVRMLImageTexture, ... files
    getResourceFile<SoVRMLImageTexture  >(node, resources);
    getResourceFile<SoVRMLMovieTexture  >(node, resources);
    getResourceFile<SoVRMLScript        >(node, resources);
    getResourceFile<SoVRMLBackground    >(node, resources);
    getResourceFile<SoVRMLAudioClip     >(node, resources);
    getResourceFile<SoVRMLAnchor        >(node, resources);
}
SoNode* ViewProviderDocumentObject::findFrontRootOfType(const SoType& type) const
{
    // first get the document this object is part of and get its GUI counterpart
    App::Document* pAppDoc = pcObject->getDocument();
    Gui::Document* pGuiDoc = Gui::Application::Instance->getDocument(pAppDoc);

    SoSearchAction searchAction;
    searchAction.setType(type);
    searchAction.setInterest(SoSearchAction::FIRST);

    // search in all view providers for the node type
    std::vector<App::DocumentObject*> obj = pAppDoc->getObjects();
    for (std::vector<App::DocumentObject*>::iterator it = obj.begin(); it != obj.end(); ++it) {
        const ViewProvider* vp = pGuiDoc->getViewProvider(*it);
        // Ignore 'this' view provider. It could also happen that vp is 0, e.g. when
        // several objects have been added to the App::Document before notifying the
        // Gui::Document
        if (!vp || vp == this)
            continue;
        SoSeparator* front = vp->getFrontRoot();
        //if (front && front->getTypeId() == type)
        //    return front;
        if (front) {
            searchAction.apply(front);
            SoPath* path = searchAction.getPath();
            if (path)
                return path->getTail();
        }
    }

    return 0;
}
void
SoXipImageOverlayManager::updateSliceMap()
{
	// Removes all the previous entries
	mSliceMap.clear();

	SoSearchAction sa;
	sa.setInterest( SoSearchAction::ALL );
	sa.setType( SoXipShapeList::getClassTypeId() );
	sa.setSearchingAll( TRUE );
	sa.apply( mShapeSwitch );

	SoPathList paths = sa.getPaths();
	for( int i = 0; i < paths.getLength(); ++ i )
	{
		SbString label = ((SoXipShapeList *) paths[i]->getTail())->label.getValue().getString();

		int sliceIndex;
		if( sscanf( label.getString(), "%d", &sliceIndex ) != 1 )
		{
			SoDebugError::post( __FILE__, "Invalid label found '%s'", label.getString() );
			continue  ;
		}
		
		mSliceMap[ sliceIndex ] = (SoXipShapeList *) paths[i]->getTail();
	}
}
    bool isVisibleFace(int faceIndex, const SbVec2f& pos, Gui::View3DInventorViewer* viewer)
    {
        SoSeparator* root = new SoSeparator;
        root->ref();
        root->addChild(viewer->getSoRenderManager()->getCamera());
        root->addChild(vp->getRoot());

        SoSearchAction searchAction;
        searchAction.setType(PartGui::SoBrepFaceSet::getClassTypeId());
        searchAction.setInterest(SoSearchAction::FIRST);
        searchAction.apply(root);
        SoPath* selectionPath = searchAction.getPath();

        SoRayPickAction rp(viewer->getSoRenderManager()->getViewportRegion());
        rp.setNormalizedPoint(pos);
        rp.apply(selectionPath);
        root->unref();

        SoPickedPoint* pick = rp.getPickedPoint();
        if (pick) {
            const SoDetail* detail = pick->getDetail();
            if (detail && detail->isOfType(SoFaceDetail::getClassTypeId())) {
                int index = static_cast<const SoFaceDetail*>(detail)->getPartIndex();
                if (faceIndex != index)
                    return false;
                SbVec3f dir = viewer->getViewDirection();
                const SbVec3f& nor = pick->getNormal();
                if (dir.dot(nor) > 0)
                    return false; // bottom side points to user
                return true;
            }
        }

        return false;
    }
SoNodeList Renderer::getChildByName(SoSeparator * ivRoot, SbName & childName,
                                            SoType targetType, int maxResultsExpected)
{
    assert(ivRoot);
    SoNodeList resultList;

    SoSearchAction sa;
    sa.setSearchingAll(true);

    sa.setType(targetType, true);
    sa.setInterest( SoSearchAction::ALL);
    sa.setName(childName);
    sa.setFind(SoSearchAction::NAME);
    sa.apply(ivRoot);

    SoPathList &pathList = sa.getPaths();
    int numPaths = pathList.getLength();
    if (numPaths > maxResultsExpected)
    {
        //DBGA(this->className() << "::getChildByName::Found too many children of node: "
        //     << ivRoot->getName().getString()  << " with name: "
        //     <<childName.getString() << " " );
        //DBGA(this->className() << "::getChildByName:: Expected:" << maxResultsExpected
        //     << " Found:" << numPaths);
        //resultList.append(static_cast<SoNode *>(NULL));
        return resultList;
    }

    for(int i = 0; i < numPaths; ++i)
    {
        resultList.append(pathList[i]->getTail());
    }
    return resultList;
}
示例#7
0
IvDragger::IvDragger(QtCoinViewerPtr viewer, ItemPtr pItem, float draggerScale)
{
    _selectedItem = pItem;
    _viewer = viewer;
    _scale = draggerScale;
    _penv = viewer->GetEnv();
    //_ptext = NULL;

    // set some default behavioral options
    _checkCollision = false;
    _prevtransparency = pItem->GetIvTransparency()->value;
    pItem->GetIvTransparency()->value = SoGLRenderAction::SCREEN_DOOR;

    if( !!pItem &&(pItem->GetIvRoot() != NULL)) {
        _GetBounds(pItem->GetIvRoot(), _ab);

        // make the item transparent
        SoSearchAction search;
        search.setType(SoMaterial::getClassTypeId());
        search.setInterest(SoSearchAction::ALL);
        search.apply(pItem->GetIvRoot());
        for(int i = 0; i < search.getPaths().getLength(); ++i) {
            SoPath* path = search.getPaths()[i];
            SoMaterial* pmtrl = (SoMaterial*)path->getTail();
            vtransparency.push_back(pmtrl->transparency[0]);
            pmtrl->transparency = 0.25f;
        }

        _vlinkaxes.resize(pItem->GetNumIvLinks());
        for(size_t i = 0; i < _vlinkaxes.size(); ++i) {
            _vlinkaxes[i] = _CreateAxes(i == 0 ? 1.0f : 0.25f,0.5f);
            pItem->GetIvLink(i)->addChild(_vlinkaxes[i]);
        }
    }
}
示例#8
0
void
IfReplacer::replaceMaterials(SoNode *sceneRoot, const SoType &typeToReplace)
{
    // Find all nodes of the given type
    SoSearchAction sa;
    sa.setType(typeToReplace);
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(sceneRoot);

    // Replace the tail of each path with a material. To do this, we
    // need to apply an SoCallbackAction to the path to gather the
    // material components.
    for (int i = 0; i < sa.getPaths().getLength(); i++) {

	// Cast the path to a full path, just in case
	SoFullPath *path = (SoFullPath *) sa.getPaths()[i];
	ASSERT(path->getTail()->isOfType(typeToReplace));

	// The path better have at least one group above the material
	if (path->getLength() < 2 ||
	    ! path->getNodeFromTail(1)->isOfType(SoGroup::getClassTypeId()))
	    continue;

	// Create a material node that represents the material in
	// effect at the tail of the path
	SoMaterial *newMaterial = createMaterialForPath(path);
	newMaterial->ref();
	
	// Replace the tail node with that material
	SoGroup *parent = (SoGroup *) path->getNodeFromTail(1);
	parent->replaceChild(path->getTail(), newMaterial);
	       
	newMaterial->unref();
    }
}
示例#9
0
OSUInventorScene::OSUInventorScene(char *filename) {

   SoSeparator *root = ReadScene(filename);
   int numNodes = 0;

   SoCallbackAction ca;
   SoSearchAction SA;
   SA.setType(SoLight::getClassTypeId(), TRUE);
   SA.setInterest(SoSearchAction::ALL);
   SA.apply(root);
   SoPathList &paths = SA.getPaths();
#ifdef DEBUG
   cerr << "There are " << paths.getLength() << " lights " << endl;
#endif
   int i;
   for (i = 0; i < paths.getLength(); i++) {
       Lights.append(paths[i]->getTail()->copy());
   }

   SA.setType(SoCamera::getClassTypeId(), TRUE);
   SA.setInterest(SoSearchAction::FIRST);
   SA.apply(root);
   if (SA.getPath()) {
       Camera = (SoCamera *)SA.getPath()->getTail()->copy();
#ifdef DEBUG
       cerr << "Found a camera!\n";
#endif
   } else
       Camera = NULL;

   ca.addPreCallback(SoNode::getClassTypeId(), processNodesCB, (void *)
       &Objects);
   ca.apply(root);
   // Now lets find the lights and camera!
   //

#ifdef DEBUG
   cerr << "There are " << Objects.getLength() << " shape objects left!\n";
#endif
}
void SIM::Coin3D::Quarter::SoQTQuarterAdaptor::setCameraType(SoType type)
{
    if(!getSoRenderManager()->getCamera()->isOfType(SoPerspectiveCamera::getClassTypeId()) &&
            !getSoRenderManager()->getCamera()->isOfType(SoOrthographicCamera::getClassTypeId())) {
        Base::Console().Warning("Quarter::setCameraType",
                                "Only SoPerspectiveCamera and SoOrthographicCamera is supported.");
        return;
    }


    SoType perspectivetype = SoPerspectiveCamera::getClassTypeId();
    SbBool oldisperspective = getSoRenderManager()->getCamera()->getTypeId().isDerivedFrom(perspectivetype);
    SbBool newisperspective = type.isDerivedFrom(perspectivetype);

    if((oldisperspective && newisperspective) ||
            (!oldisperspective && !newisperspective)) // Same old, same old..
        return;


    SoCamera* currentcam = getSoRenderManager()->getCamera();
    SoCamera* newcamera = (SoCamera*)type.createInstance();

    // Transfer and convert values from one camera type to the other.
    if(newisperspective) {
        convertOrtho2Perspective((SoOrthographicCamera*)currentcam,
                                 (SoPerspectiveCamera*)newcamera);
    }
    else {
        convertPerspective2Ortho((SoPerspectiveCamera*)currentcam,
                                 (SoOrthographicCamera*)newcamera);
    }

    getSoRenderManager()->setCamera(newcamera);
    getSoEventManager()->setCamera(newcamera);

    //if the superscene has a camera we need to replace it too
    SoSeparator* superscene = (SoSeparator*) getSoRenderManager()->getSceneGraph();
    SoSearchAction sa;
    sa.setInterest(SoSearchAction::FIRST);
    sa.setType(SoCamera::getClassTypeId());
    sa.apply(superscene);

    if(sa.getPath()) {
        SoNode* node = sa.getPath()->getTail();
        SoGroup* parent = (SoGroup*) sa.getPath()->getNodeFromTail(1);

        if(node && node->isOfType(SoCamera::getClassTypeId())) {
            parent->replaceChild(node, newcamera);
        }
    }
};
SoCamera *
QuarterWidgetP::searchForCamera(SoNode * root)
{
  SoSearchAction sa;
  sa.setInterest(SoSearchAction::FIRST);
  sa.setType(SoCamera::getClassTypeId());
  sa.apply(root);

  if (sa.getPath()) {
    SoNode * node = sa.getPath()->getTail();
    if (node && node->isOfType(SoCamera::getClassTypeId())) {
      return (SoCamera *) node;
    }
  }
  return NULL;
}
示例#12
0
SoCamera *
SoSceneTextureCubeMapP::findCamera(void)
{
  SoSearchAction sa;

  sa.setType(SoCamera::getClassTypeId());
  sa.setInterest(SoSearchAction::FIRST);
  sa.apply(PUBLIC(this)->scene.getValue());

  SoPath * path = sa.getPath();

  if (path == NULL)
    return NULL;
  else
    return (SoCamera *)path->getTail();
}
示例#13
0
void
removeNodes(SoGroup *root, SoType type)
//
//////////////////////////////////////////////////////////////
{
    SoSearchAction act;
    act.setInterest(SoSearchAction::ALL);
    act.setType(type);
    act.apply(root);
    SoPathList &paths = act.getPaths();
    for (int i = 0; i < paths.getLength(); i++) {
	SoNode *kid = paths[i]->getTail();
	paths[i]->pop();
	SoGroup *parent = (SoGroup *)paths[i]->getTail();
	parent->removeChild(kid);
    }
}
void ViewProviderVRMLObject::getResourceFile(SoNode* node, std::list<std::string>& resources)
{
    SoSearchAction sa;
    sa.setType(T::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.setSearchingAll(true);
    sa.apply(node);
    const SoPathList & pathlist = sa.getPaths();
    for (int i = 0; i < pathlist.getLength(); i++ ) {
        SoFullPath * path = static_cast<SoFullPath *>(pathlist[i]);
        if (path->getTail()->isOfType(T::getClassTypeId())) {
            T * tex = static_cast<T*>(path->getTail());
            for (int j = 0; j < tex->url.getNum(); j++) {
                this->addResource(tex->url[j], resources);
            }
        }
    }
}
示例#15
0
void AlignmentGroup::setRandomColor()
{
    std::vector<Gui::ViewProviderDocumentObject*>::iterator it;
    for (it = this->_views.begin(); it != this->_views.end(); ++it) {
        float r = /*(float)rand()/(float)RAND_MAX*/0.0f;
        float g = (float)rand()/(float)RAND_MAX;
        float b = (float)rand()/(float)RAND_MAX;
        if ((*it)->isDerivedFrom(Gui::ViewProviderGeometryObject::getClassTypeId())) {
            SoSearchAction searchAction;
            searchAction.setType(SoMaterial::getClassTypeId());
            searchAction.setInterest(SoSearchAction::FIRST);
            searchAction.apply((*it)->getRoot());
            SoPath* selectionPath = searchAction.getPath();

            if (selectionPath) {
                SoMaterial* material = static_cast<SoMaterial*>(selectionPath->getTail());
                material->diffuseColor.setValue(r, g, b);
            }
        }
    }
}
void ViewProviderVRMLObject::getResourceFile<SoVRMLBackground>(SoNode* node, std::list<std::string>& resources)
{
    SoSearchAction sa;
    sa.setType(SoVRMLBackground::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.setSearchingAll(true);
    sa.apply(node);
    const SoPathList & pathlist = sa.getPaths();
    for (int i = 0; i < pathlist.getLength(); i++ ) {
        SoFullPath * path = static_cast<SoFullPath *>(pathlist[i]);
        if (path->getTail()->isOfType(SoVRMLBackground::getClassTypeId())) {
            SoVRMLBackground * vrml = static_cast<SoVRMLBackground*>(path->getTail());
            // backUrl
            for (int j = 0; j < vrml->backUrl.getNum(); j++) {
                addResource(vrml->backUrl[j], resources);
            }
            // bottomUrl
            for (int j = 0; j < vrml->bottomUrl.getNum(); j++) {
                addResource(vrml->bottomUrl[j], resources);
            }
            // frontUrl
            for (int j = 0; j < vrml->frontUrl.getNum(); j++) {
                addResource(vrml->frontUrl[j], resources);
            }
            // leftUrl
            for (int j = 0; j < vrml->leftUrl.getNum(); j++) {
                addResource(vrml->leftUrl[j], resources);
            }
            // rightUrl
            for (int j = 0; j < vrml->rightUrl.getNum(); j++) {
                addResource(vrml->rightUrl[j], resources);
            }
            // topUrl
            for (int j = 0; j < vrml->topUrl.getNum(); j++) {
                addResource(vrml->topUrl[j], resources);
            }
        }
    }
}
示例#17
0
IvDragger::~IvDragger()
{
    ItemPtr selectedItem = GetSelectedItem();
    if( !!selectedItem &&(selectedItem->GetIvRoot() != NULL)) {
        for(size_t i = 0; i < _vlinkaxes.size(); ++i) {
            selectedItem->GetIvLink(i)->removeChild(_vlinkaxes[i]);
        }
        _vlinkaxes.clear();

        // revert transparency
        SoSearchAction search;
        search.setType(SoMaterial::getClassTypeId());
        search.setInterest(SoSearchAction::ALL);
        search.apply(selectedItem->GetIvRoot());
        for(int i = 0; i < search.getPaths().getLength(); ++i) {
            SoPath* path = search.getPaths()[i];
            SoMaterial* pmtrl = (SoMaterial*)path->getTail();
            if( i < (int)vtransparency.size() )
                pmtrl->transparency = vtransparency[i];
        }

        selectedItem->GetIvTransparency()->value = _prevtransparency;
    }
}
bool InventorViewer::computeCorrectFaceNormal(const SoPickedPoint * pick, bool ccw_face, Eigen::Vector3d& normal, int& shapeIdx)
{
    const SoDetail *pickDetail = pick->getDetail();
    if ((pickDetail != NULL) && (pickDetail->getTypeId() == SoFaceDetail::getClassTypeId()))
    {
        // Picked object is a face
        const SoFaceDetail * fd = dynamic_cast<const SoFaceDetail*>(pickDetail);
        if (!fd)
        {
            ROS_ERROR("Could not cast to face detail");
            return false;
        }

        // face index is always 0 with triangle strips
       // ROS_INFO_STREAM("Face index: "<<fd->getFaceIndex());

        if (fd->getNumPoints() < 3)
        {
            ROS_ERROR("Clicked on degenerate face, can't compute normal");
            return false;
        }
        /*else
        {
            ROS_INFO_STREAM("Clicked on face with "<<fd->getNumPoints()<<" points.");
        }*/       
        
        //ROS_INFO("Pick path:");
        //printPath(pick->getPath());

        /*SbVec3f pickNormal = pick->getNormal();
        //SbVec3f _normalObj=pick->getObjectNormal();
        float _x, _y, _z;
        pickNormal.getValue(_x, _y, _z);
        Eigen::Vector3d normalDef = Eigen::Vector3d(_x, _y, _z);
        normal = normalDef;*/

        // ROS_INFO_STREAM("Clicked on face with "<<fd->getNumPoints()<<" points.");

        int p1 = fd->getPoint(0)->getCoordinateIndex();
        int p2 = fd->getPoint(1)->getCoordinateIndex();
        int p3 = fd->getPoint(2)->getCoordinateIndex();

        // ROS_INFO_STREAM("Face part index: "<<fd->getPartIndex());

        // ROS_INFO_STREAM("First 3 coord indices: "<<p1<<", "<<p2<<", "<<p3);

        // Find the coordinate node that is used for the faces.
        // Assume that it's the last SoCoordinate3 node traversed
        // before the picked shape.
        SoSearchAction  searchCoords;
        searchCoords.setType(SoCoordinate3::getClassTypeId());
        searchCoords.setInterest(SoSearchAction::LAST);
        searchCoords.apply(pick->getPath());

        SbVec3f coord1, coord2, coord3;

        shapeIdx=pick->getPath()->getLength()-1;
        //ROS_INFO_STREAM("Len of pick path: "<<shapeIdx);

        if (searchCoords.getPath() == NULL)
        {
            // try to find SoIndexedShape instead
            // ROS_INFO("No SoCoordinate3 node found, looking for SoIndexedShape...");

            searchCoords.setType(SoIndexedShape::getClassTypeId());
            searchCoords.setInterest(SoSearchAction::LAST);
            searchCoords.apply(pick->getPath());

            if (searchCoords.getPath() == NULL)
            {
                ROS_ERROR("Failed to find coordinate node for the picked face. Returning default normal.");
                return false;
            }

            shapeIdx=searchCoords.getPath()->getLength()-1;
            // ROS_INFO_STREAM("Coords at Idx: "<<shapeIdx);

            // ROS_INFO("SearchCoords path:");
            // printPath(searchCoords.getPath());

            SoIndexedShape * vShapeNode = dynamic_cast<SoIndexedShape*>(searchCoords.getPath()->getTail());
            if (!vShapeNode)
            {
                ROS_ERROR("Could not cast SoIndexedShape");
                return false;
            }
            SoVertexProperty * vProp = dynamic_cast<SoVertexProperty*>(vShapeNode->vertexProperty.getValue());
            if (!vProp)
            {
                ROS_ERROR_STREAM("Could not cast SoVertexProperty.");
                return false;
            }
            coord1 = vProp->vertex[p1];
            coord2 = vProp->vertex[p2];
            coord3 = vProp->vertex[p3];
        }
        else
        {
            shapeIdx=searchCoords.getPath()->getLength()-1;
            
            SoCoordinate3 * coordNode = dynamic_cast<SoCoordinate3*>(searchCoords.getPath()->getTail());
            if (!coordNode)
            {
                ROS_ERROR("Could not cast SoCoordinate3");
                return false;
            }
            coord1 = coordNode->point[p1];
            coord2 = coordNode->point[p2];
            coord3 = coordNode->point[p3];
        }

        if (fd->getNumPoints() > 3)
        {
            ROS_WARN_STREAM("Face with " << fd->getNumPoints() <<
                            " points is not a triangle and may lead to wrong normal calculations.");
        }

        /*ROS_INFO_STREAM("Coords "<<p1<<", "<<p2<<", "<<p3);
        float _x, _y, _z;
        coord1.getValue(_x, _y, _z);
        ROS_INFO_STREAM("val1 "<<_x<<", "<<_y<<", "<<_z);
        coord2.getValue(_x, _y, _z);
        ROS_INFO_STREAM("val2 "<<_x<<", "<<_y<<", "<<_z);
        coord3.getValue(_x, _y, _z);
        ROS_INFO_STREAM("val3 "<<_x<<", "<<_y<<", "<<_z);*/

        SbVec3f diff1(coord2.getValue());
        diff1 -= coord1;
        SbVec3f diff2(coord3.getValue());
        diff2 -= coord1;
        SbVec3f cross = diff1.cross(diff2);
        if (!ccw_face) cross = -cross;

        float x, y, z;
        cross.getValue(x, y, z);
        double len = sqrt(x * x + y * y + z * z);
        x /= len;
        y /= len;
        z /= len;

        normal = Eigen::Vector3d(x, y, z);

        return true;
    }
    return false;
}
示例#19
0
文件: Scene.cpp 项目: Serge45/rl
		void
		Scene::load(const ::std::string& filename, const bool& doBoundingBoxPoints, const bool& doPoints)
		{
			::rl::xml::DomParser parser;
			
			::rl::xml::Document doc = parser.readFile(filename, "", XML_PARSE_NOENT | XML_PARSE_XINCLUDE);
			
			doc.substitute(XML_PARSE_NOENT | XML_PARSE_XINCLUDE);
			
			::rl::xml::Path path(doc);
			
			::rl::xml::Object scenes = path.eval("//scene");
			
			for (int i = 0; i < ::std::min(1, scenes.getNodeNr()); ++i)
			{
				SoInput input;
				
				if (!input.openFile(scenes.getNodeTab(i).getLocalPath(scenes.getNodeTab(i).getAttribute("href").getValue()).c_str() ,true))
				{
					throw Exception("::rl::sg::Scene::load() - failed to open file");
				}
				
				SoVRMLGroup* root = SoDB::readAllVRML(&input);
				
				if (NULL == root)
				{
					throw Exception("::rl::sg::Scene::load() - failed to read file");
				}
				
				SbViewportRegion viewportRegion;
				
				root->ref();
				
				// model
				
				::rl::xml::Object models = path.eval("model", scenes.getNodeTab(i));
				
				for (int j = 0; j < models.getNodeNr(); ++j)
				{
					SoSearchAction modelSearchAction;
					modelSearchAction.setName(models.getNodeTab(j).getAttribute("name").getValue().c_str());
					modelSearchAction.apply(root);
					
					if (NULL == modelSearchAction.getPath())
					{
						continue;
					}
					
					Model* model = this->create();
					
					model->setName(models.getNodeTab(j).getAttribute("name").getValue());
					
					// body
					
					::rl::xml::Object bodies = path.eval("body", models.getNodeTab(j));
					
					for (int k = 0; k < bodies.getNodeNr(); ++k)
					{
						SoSearchAction bodySearchAction;
						bodySearchAction.setName(bodies.getNodeTab(k).getAttribute("name").getValue().c_str());
						bodySearchAction.apply(static_cast< SoFullPath* >(modelSearchAction.getPath())->getTail());
						
						if (NULL == bodySearchAction.getPath())
						{
							continue;
						}
						
						Body* body = model->create();
						
						body->setName(bodies.getNodeTab(k).getAttribute("name").getValue());
						
						SoSearchAction pathSearchAction;
						pathSearchAction.setNode(static_cast< SoFullPath* >(bodySearchAction.getPath())->getTail());
						pathSearchAction.apply(root);
						
						SoGetMatrixAction bodyGetMatrixAction(viewportRegion);
						bodyGetMatrixAction.apply(static_cast< SoFullPath* >(pathSearchAction.getPath()));
						SbMatrix bodyMatrix = bodyGetMatrixAction.getMatrix();
						
						if (!this->isScalingSupported)
						{
							SbVec3f bodyTranslation;
							SbRotation bodyRotation;
							SbVec3f bodyScaleFactor;
							SbRotation bodyScaleOrientation;
							SbVec3f bodyCenter;
							bodyMatrix.getTransform(bodyTranslation, bodyRotation, bodyScaleFactor, bodyScaleOrientation, bodyCenter);
							
							for (int l = 0; l < 3; ++l)
							{
								if (::std::abs(bodyScaleFactor[l] - 1.0f) > 1.0e-6f)
								{
									throw Exception("::rl::sg::Scene::load() - bodyScaleFactor not supported");
								}
							}
						}
						
						::rl::math::Transform frame;
						
						for (int m = 0; m < 4; ++m)
						{
							for (int n = 0; n < 4; ++n)
							{
								frame(m, n) = bodyMatrix[n][m];
							}
						}
						
						body->setFrame(frame);
						
						if (static_cast< SoFullPath* >(bodySearchAction.getPath())->getTail()->isOfType(SoVRMLTransform::getClassTypeId()))
						{
							SoVRMLTransform* bodyVrmlTransform = static_cast< SoVRMLTransform* >(static_cast< SoFullPath* >(bodySearchAction.getPath())->getTail());
							
							for (int l = 0; l < 3; ++l)
							{
								body->center(l) = bodyVrmlTransform->center.getValue()[l];
							}
						}
						
						SoPathList pathList;
						
						// shape
						
						SoSearchAction shapeSearchAction;
						shapeSearchAction.setInterest(SoSearchAction::ALL);
						shapeSearchAction.setType(SoVRMLShape::getClassTypeId());
						shapeSearchAction.apply(static_cast< SoFullPath* >(bodySearchAction.getPath())->getTail());
						
						for (int l = 0; l < shapeSearchAction.getPaths().getLength(); ++l)
						{
							SoFullPath* path = static_cast< SoFullPath* >(shapeSearchAction.getPaths()[l]);
							
							if (path->getLength() > 1)
							{
								path = static_cast< SoFullPath* >(shapeSearchAction.getPaths()[l]->copy(1, static_cast< SoFullPath* >(shapeSearchAction.getPaths()[l])->getLength() - 1));
							}
							
							pathList.append(path);
							
							SoGetMatrixAction shapeGetMatrixAction(viewportRegion);
							shapeGetMatrixAction.apply(path);
							SbMatrix shapeMatrix = shapeGetMatrixAction.getMatrix();
							
							if (!this->isScalingSupported)
							{
								SbVec3f shapeTranslation;
								SbRotation shapeRotation;
								SbVec3f shapeScaleFactor;
								SbRotation shapeScaleOrientation;
								SbVec3f shapeCenter;
								shapeMatrix.getTransform(shapeTranslation, shapeRotation, shapeScaleFactor, shapeScaleOrientation, shapeCenter);
								
								for (int m = 0; m < 3; ++m)
								{
									if (::std::abs(shapeScaleFactor[m] - 1.0f) > 1.0e-6f)
									{
										throw Exception("::rl::sg::Scene::load() - shapeScaleFactor not supported");
									}
								}
							}
							
							SoVRMLShape* shapeVrmlShape = static_cast< SoVRMLShape* >(static_cast< SoFullPath* >(shapeSearchAction.getPaths()[l])->getTail());
							
							Shape* shape = body->create(shapeVrmlShape);
							
							shape->setName(shapeVrmlShape->getName().getString());
							
							::rl::math::Transform transform;
							
							for (int m = 0; m < 4; ++m)
							{
								for (int n = 0; n < 4; ++n)
								{
									transform(m, n) = shapeMatrix[n][m];
								}
							}
							
							shape->setTransform(transform);
						}
						
						// bounding box
						
						if (doBoundingBoxPoints)
						{
							SoGetBoundingBoxAction getBoundingBoxAction(viewportRegion);
							getBoundingBoxAction.apply(pathList);
							SbBox3f boundingBox = getBoundingBoxAction.getBoundingBox();
							
							for (int l = 0; l < 3; ++l)
							{
								body->max(l) = boundingBox.getMax()[l];
								body->min(l) = boundingBox.getMin()[l];
							}
						}
						
						// convex hull
						
						if (doPoints)
						{
							SoCallbackAction callbackAction;
							callbackAction.addTriangleCallback(SoVRMLGeometry::getClassTypeId(), Scene::triangleCallback, &body->points);
							callbackAction.apply(pathList);
						}
					}
				}
				
				root->unref();
			}
		}
示例#20
0
void
IfWeeder::findMaterialsAndShapes(SoNode *root)
{
    // Since we know the structure of the given scene graph (which is
    // after fixing has occurred), we can be efficient here. Just
    // search for all materials in the scene. For each material, the
    // shapes affected by it must be under the separator that is the
    // material's parent node. So just search for all shapes under
    // that separator, making sure that the path to the shape comes
    // after the material.

    // First, create a dictionary so we can tell when we've found a
    // multiple instance of a material
    SbDict materialDict;

    // Search for all materials in the scene
    SoSearchAction sa;
    sa.setType(SoMaterial::getClassTypeId());
    sa.setInterest(SoSearchAction::ALL);
    sa.apply(root);

    // Set up another search action to find all shapes using a
    // material. Note that we have to search for all node types that
    // should be considered shapes.
    SoSearchAction sa2;
    sa2.setInterest(SoSearchAction::ALL);

    // These are the shape types
    SoTypeList shapeTypes;
    IfTypes::getShapeTypes(&shapeTypes);

    // Process each material, adding new ones to the list
    materialList = new SbPList;
    for (int i = 0; i < sa.getPaths().getLength(); i++) {

	const SoPath *path = (const SoPath *) sa.getPaths()[i];

	ASSERT(path->getLength() > 1);
	ASSERT(path->getTail()->getTypeId() == SoMaterial::getClassTypeId());

	SoMaterial  *material = (SoMaterial *) path->getTail();

	// Add to the dictionary if necessary, or use the existing
	// entry
	void *entryPtr;
	IfWeederMaterialEntry *entry;
	if (materialDict.find((unsigned long) material, entryPtr)) {
	    entry = (IfWeederMaterialEntry *) entryPtr;
	    if (! entry->canWeed)
		continue;
	}
	else {
	    entry = new IfWeederMaterialEntry;
	    entry->material = material;
	    entry->canWeed  = TRUE;
	    materialDict.enter((unsigned long) material, entry);
	    materialList->append(entry);
	}

	// If any node above the material in the path is an opaque
	// group, we can't really weed this material
	int j;
	for (j = path->getLength() - 2; j >= 0; j--) {
	    if (IfTypes::isOpaqueGroupType(path->getNode(j)->getTypeId())) {
		entry->canWeed = FALSE;
		break;
	    }
	}
	if (! entry->canWeed)
	    continue;

	ASSERT(path->getNodeFromTail(1)->
	       isOfType(SoSeparator::getClassTypeId()));

	SoSeparator *parent = (SoSeparator *) path->getNodeFromTail(1);
	int materialIndex = path->getIndexFromTail(0);

	// Find all shapes using the material, adding them to the list
	// of shapes in the material's entry. Store all the paths to
	// them in this list
	SoPathList pathsToShapes;
	for (int type = 0; type < shapeTypes.getLength(); type++) {
	    sa2.setType(shapeTypes[type]);
	    sa2.apply(parent);
	    for (j = 0; j < sa2.getPaths().getLength(); j++)
		pathsToShapes.append(sa2.getPaths()[j]);
	}

	for (j = 0; j < pathsToShapes.getLength(); j++) {

	    const SoPath *shapePath = (const SoPath *) pathsToShapes[j];

	    // We can't weed the material at all if a shape other than
	    // the one we created is found
	    SoType tailType = shapePath->getTail()->getTypeId();
	    if (tailType != SoIndexedTriangleStripSet::getClassTypeId() &&
		tailType != SoIndexedFaceSet::getClassTypeId()) {
		entry->canWeed = FALSE;
		break;
	    }

	    // Make sure the shape comes after the material and does
	    // not get its materials from a vertex property
	    // node.
	    else if (shapePath->getIndex(1) > materialIndex) {
		SoIndexedShape *is = (SoIndexedShape *) shapePath->getTail();

		// ??? If the shape's materialIndex field has the
		// ??? default value, we assume that it might have to
		// ??? access all the material values. To check, we would
		// ??? have to look at the coordIndex values if the
		// ??? material binding is not OVERALL. This change could
		// ??? not be done in time for the release. See bug 311071.
		if (is->materialIndex.getNum() == 1 &&
		    is->materialIndex[0] < 0) {
		    entry->canWeed = FALSE;
		    break;
		}

		SoVertexProperty *vp =
		    (SoVertexProperty *) is->vertexProperty.getValue();
		if (vp == NULL || vp->orderedRGBA.getNum() == 0)
		    entry->shapes.append(shapePath->getTail());
	    }
	}
    }
}
示例#21
0
int QilexDoc::doc_insert_kinematic_chain(Rchain *kineengine, SoSeparator *kinechain)
{
   int error = 0;
   int i;

   SbVec3f joinax;

   float joinangle;
   
   SbName joints[] = {"joint1", "joint2", "joint3", "joint4","joint5", "joint6",
                   "joint7", "joint8", "joint9", "joint10","joint11", "joint12",
                   "joint13", "joint14", "joint15", "joint16","joint17", "joint18",
                   "joint19", "joint20", "joint21", "joint22","joint23", "joint24",  };
   
   SoEngineList compR(kineengine->dof);
   SoNodeList Rots(kineengine->dof);

   SoSearchAction lookingforjoints;
   SoTransform *pjoint = new SoTransform;

      // Identifie the rotations and assing the job
   i = 0;

   while (i < kineengine->dof && error == 0)
   {
      lookingforjoints.setName(joints[i]);
      lookingforjoints.setType(SoTransform::getClassTypeId());
      lookingforjoints.setInterest(SoSearchAction::FIRST);
      lookingforjoints.apply(kinechain);

      //  assert(lookingforjoints.getPath() != NULL);
      SoNode * pnode = lookingforjoints.getPath()->getTail();;

      pjoint = (SoTransform *) pnode;

      if(NULL != pjoint)
      {
         Rots.append((SoTransform *) pjoint);
         compR.append(new SoQtComposeRotation);
         // cal comprobar si l'articulació es de rotació o translació: arreglar...
         ((SoTransform *) Rots[i])->rotation.getValue(joinax, joinangle);
         ((SoQtComposeRotation *) compR[i])->axis.setValue(joinax);

         ((SoTransform *) Rots[i])->rotation.connectFrom(&((SoQtComposeRotation *) compR[i])->rotation);
      }
      else
      {
         error = 5; // not a valid Model3d file
      }
      i++ ;
   }

   if (error == 0)
   {
      SoSeparator *axisworld = new SoSeparator;
      axisworld->unrefNoDelete();
		
		SoCoordinateAxis *AxisW   = new SoCoordinateAxis();
	   AxisW->fNDivision = 1;
      AxisW->fDivisionLength = 200;
		axisworld->addChild(AxisW);

      //kinechain->insertChild(AxisW,1);
      view->addNoColObject(axisworld);
		
    /*  lookingforjoints.setName("tool");
      lookingforjoints.setType(SoSeparator::getClassTypeId());
      lookingforjoints.setInterest(SoSearchAction::FIRST);
      lookingforjoints.apply(kinechain);

      if(lookingforjoints.getPath() != NULL)
      {
         SoNode * pnode = lookingforjoints.getPath()->getTail();;
      	
			SoCoordinateAxis *AxisT   = new SoCoordinateAxis();
			AxisT->fNDivision = 1;
      	AxisT->fDivisionLength = 200;

			SoSeparator *axistool = new SoSeparator;
         axistool->ref();
         axistool = (SoSeparator *) pnode;
         axistool->addChild(AxisT);
			view->addNoColObject(axistool);			
      }
      */ 
      panel_control *panel = new panel_control(0, "Panel", kineengine);

      for (int i = 0; i < kineengine->dof; i++)
      {
         // connect(panel->ldial[i], SIGNAL(valueChange(double)),((SoQtComposeRotation *) compR[i]), SLOT(setValue_angle(double)));
         connect(panel->ldial[i], SIGNAL(valueChange(double)),&panel->kinechain->list_plug[i], SLOT(setValue(double)));
         connect(&panel->kinechain->list_plug[i], SIGNAL(valueChanged(double)),((SoQtComposeRotation *) compR[i]), SLOT(setValue_angle(double)));
         connect(&panel->kinechain->list_plug[i], SIGNAL(valueChanged(double)),panel->ldial[i], SLOT(setValue(double)));
      }

      view->addRobotCell(kinechain);

      panel->show();
      panel->update_limits();
      //panel->kinechain->setconsole_mode(true); Ja estava comentada
      panel->kinechain->setconsole_mode(false);
      panel->kinechain->do_ready();
		connect(view, SIGNAL(pick_point(Rhmatrix)),panel, SLOT(move_pickpoint(Rhmatrix )));
      //panel->kinechain->setconsole_mode(false); Ja estava comentada
   }
示例#22
0
static SoSeparator *
setUpGraph(const SbViewportRegion &vpReg,
	   SoInput *sceneInput,
	   Options &options)
//
//////////////////////////////////////////////////////////////
{

    // Create a root separator to hold everything. Turn
    // caching off, since the transformation will blow
    // it anyway.
    SoSeparator *root = new SoSeparator;
    root->ref();
    root->renderCaching = SoSeparator::OFF;

    // Add a camera to view the scene
    SoPerspectiveCamera *camera = new SoPerspectiveCamera;
    root->addChild(camera);

    // Add a transform node to spin the scene
    SoTransform *sceneTransform = new SoTransform;
    sceneTransform->setName(SCENE_XFORM_NAME);
    root->addChild(sceneTransform);

    // Read and add input scene graph
    SoSeparator *inputRoot = SoDB::readAll(sceneInput);
    if (inputRoot == NULL) {
	fprintf(stderr, "Cannot read scene graph\n");
	root->unref();
	exit(1);
    }
    root->addChild(inputRoot);

    SoPath 	*path;
    SoGroup	*parent, *group;
    SoSearchAction	act;

    // expand out all File nodes and replace them with groups
    //    containing the children
    SoFile 	*fileNode;
    act.setType(SoFile::getClassTypeId());
    act.setInterest(SoSearchAction::FIRST);
    act.apply(inputRoot);
    while ((path = act.getPath()) != NULL) {
	fileNode = (SoFile *) path->getTail();
	path->pop();
	parent = (SoGroup *) path->getTail();
	group = fileNode->copyChildren();
	if (group) {
	    parent->replaceChild(fileNode, group);
	    // apply action again and continue
	    act.apply(inputRoot);
	}
    }

    // expand out all node kits and replace them with groups
    //    containing the children
    SoBaseKit	*kitNode;
    SoChildList	*childList;
    act.setType(SoBaseKit::getClassTypeId());
    act.setInterest(SoSearchAction::FIRST);
    act.apply(inputRoot);
    while ((path = act.getPath()) != NULL) {
	kitNode = (SoBaseKit *) path->getTail();
	path->pop();
	parent = (SoGroup *) path->getTail();
	group = new SoGroup;
	childList = kitNode->getChildren();
	for (int i=0; i<childList->getLength(); i++) 
	    group->addChild((*childList)[i]);
	parent->replaceChild(kitNode, group);
	act.apply(inputRoot);
    }

    // check to see if there are any lights
    // if no lights, add a directional light to the scene
    act.setType(SoLight::getClassTypeId());
    act.setInterest(SoSearchAction::FIRST);
    act.apply(inputRoot);
    if (act.getPath() == NULL) { // no lights
	SoDirectionalLight *light = new SoDirectionalLight;
	root->insertChild(light, 1);
    }
    else 
	options.hasLights = TRUE;

    // check to see if there are any texures in the scene
    act.setType(SoTexture2::getClassTypeId());
    act.setInterest(SoSearchAction::FIRST);
    act.apply(inputRoot);
    if (act.getPath() != NULL)
	options.hasTextures = TRUE;

    camera->viewAll(root, vpReg);

    // print out information about the scene graph

    int32_t numTris, numLines, numPoints, numNodes;
    countPrimitives( inputRoot, numTris, numLines, numPoints, numNodes );
    printf("Number of nodes in scene graph:     %d\n", numNodes );
    printf("Number of triangles in scene graph: %d\n", numTris );
    printf("Number of lines in scene graph:     %d\n", numLines );
    printf("Number of points in scene graph:    %d\n\n", numPoints );

    // Make the center of rotation the center of
    // the scene
    SoGetBoundingBoxAction	bba(vpReg);
    bba.apply(root);
    sceneTransform->center = bba.getBoundingBox().getCenter();

    return root;
}
示例#23
0
int
main(int argc, char ** argv)
{
  if ( argc != 3 ) {
    fprintf(stderr, "Usage: %s <infile.iv> <outfile.iv>\n", argv[0]);
    return -1;
  }

  SoDB::init();
  SoNodeKit::init();
  SoInteraction::init();

  SoGenerateSceneGraphAction::initClass();
  SoTweakAction::initClass();

  SoInput in;
  SoNode * scene, * graph;
  if ( !in.openFile(argv[1]) ) {
    fprintf(stderr, "%s: error opening \"%s\" for reading.\n", argv[0], argv[1]);
    return -1;
  }
  scene = SoDB::readAll(&in);
  if ( scene == NULL ) {
    fprintf(stderr, "%s: error parsing \"%s\"\n", argv[0], argv[1]);
    return -1;
  }
  scene->ref();

  SoGenerateSceneGraphAction action;
  // action.setDropTypeIfNameEnabled(TRUE);
  action.apply(scene);
  graph = action.getGraph();
  if ( graph == NULL ) {
    fprintf(stderr, "%s: error generating scene graph\n", argv[0]);
    return -1;
  }
  graph->ref();
  scene->unref();
  scene = NULL;

  // figure out camera settings and needed rendering canvas size
  SoGetBoundingBoxAction bbaction(SbViewportRegion(64,64)); // just something
  bbaction.apply(graph);

  SbBox3f bbox = bbaction.getBoundingBox();
  SbVec3f min = bbox.getMin();
  SbVec3f max = bbox.getMax();
  float bwidth = max[0] - min[0];
  float bheight = max[1] - min[1];
  // fprintf(stdout, "min: %g %g %g\n", min[0], min[1], min[2]);
  // fprintf(stdout, "max: %g %g %g\n", max[0], max[1], max[2]);

  // place camera
  SoSearchAction search;
  search.setType(SoCamera::getClassTypeId());
  search.setInterest(SoSearchAction::FIRST);
  search.apply(graph);
  SoPath * campath = search.getPath();
  SoOrthographicCamera * cam = (SoOrthographicCamera *) campath->getTail();
  assert(cam != NULL);
  SbVec3f pos = cam->position.getValue();
  cam->position.setValue(SbVec3f(min[0] + ((max[0]-min[0])/2.0),
                                 min[1] + ((max[1]-min[1])/2.0),
				 pos[2]));
  cam->height.setValue(bheight);

  if ( TRUE ) { // FIXME: only write .iv-scene if asked
    SoOutput out;
    if ( !out.openFile(argv[2]) ) {
      fprintf(stderr, "%s: error opening \"%s\" for writing.\n", argv[0], argv[2]);
      return -1;
    }
    SoWriteAction writer(&out);
    // writer.setCoinFormattingEnabled(TRUE);
    writer.apply(graph);
  }

  int width = (int) ceil(bwidth * 150.0) + 2;
  int height = (int) ceil(bheight * 150.0);
  fprintf(stderr, "image: %d x %d\n", width, height);
  if ( TRUE ) { // FIXME: only write image if asked
    SoOffscreenRenderer renderer(SbViewportRegion(width, height));
    SoGLRenderAction * glra = renderer.getGLRenderAction();
    glra->setNumPasses(9);
    // FIXME: auto-crop image afterwards?  seems like it's a perfect fit right now
    renderer.setComponents(SoOffscreenRenderer::RGB_TRANSPARENCY);
    renderer.setBackgroundColor(SbColor(1.0,1.0,1.0));
    renderer.render(graph);
    // FIXME: support command line option filename
    // FIXME: also support .eps
    renderer.writeToFile("output.png", "png");
  }

  graph->unref();
  return 0;
}