void addFacesToSelection(Gui::View3DInventorViewer* viewer,
                             const Gui::ViewVolumeProjection& proj,
                             const Base::Polygon2D& polygon,
                             const TopoDS_Shape& shape)
    {
        try {
            TopTools_IndexedMapOfShape M;

            TopExp_Explorer xp_face(shape,TopAbs_FACE);
            while (xp_face.More()) {
                M.Add(xp_face.Current());
                xp_face.Next();
            }

            App::Document* appdoc = doc->getDocument();
            for (Standard_Integer k = 1; k <= M.Extent(); k++) {
                const TopoDS_Shape& face = M(k);

                TopExp_Explorer xp_vertex(face,TopAbs_VERTEX);
                while (xp_vertex.More()) {
                    gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(xp_vertex.Current()));
                    Base::Vector3d pt2d;
                    pt2d = proj(Base::Vector3d(p.X(), p.Y(), p.Z()));
                    if (polygon.Contains(Base::Vector2D(pt2d.x, pt2d.y))) {
#if 0
                        // TODO
                        if (isVisibleFace(k-1, SbVec2f(pt2d.x, pt2d.y), viewer))
#endif
                        {
                            std::stringstream str;
                            str << "Face" << k;
                            Gui::Selection().addSelection(appdoc->getName(), obj->getNameInDocument(), str.str().c_str());
                            break;
                        }
                    }
                    xp_vertex.Next();
                }

                //GProp_GProps props;
                //BRepGProp::SurfaceProperties(face, props);
                //gp_Pnt c = props.CentreOfMass();
                //Base::Vector3d pt2d;
                //pt2d = proj(Base::Vector3d(c.X(), c.Y(), c.Z()));
                //if (polygon.Contains(Base::Vector2D(pt2d.x, pt2d.y))) {
                //    if (isVisibleFace(k-1, SbVec2f(pt2d.x, pt2d.y), viewer)) {
                //        std::stringstream str;
                //        str << "Face" << k;
                //        Gui::Selection().addSelection(appdoc->getName(), obj->getNameInDocument(), str.str().c_str());
                //    }
                //}
            }
        }
        catch (...) {
        }
    }
void ViewProviderStructured::cut(const std::vector<SbVec2f>& picked, Gui::View3DInventorViewer &Viewer)
{
    // create the polygon from the picked points
    Base::Polygon2D cPoly;
    for (std::vector<SbVec2f>::const_iterator it = picked.begin(); it != picked.end(); ++it) {
        cPoly.Add(Base::Vector2D((*it)[0],(*it)[1]));
    }

    // get a reference to the point feature
    Points::Feature* fea = static_cast<Points::Feature*>(pcObject);
    const Points::PointKernel& points = fea->Points.getValue();

    SoCamera* pCam = Viewer.getSoRenderManager()->getCamera();
    SbViewVolume  vol = pCam->getViewVolume();

    // search for all points inside/outside the polygon
    Points::PointKernel newKernel;
    newKernel.reserve(points.size());

    bool invalidatePoints = false;
    double nan = std::numeric_limits<double>::quiet_NaN();
    for (Points::PointKernel::const_iterator jt = points.begin(); jt != points.end(); ++jt) {
        // valid point?
        Base::Vector3d vec(*jt);
        if (!(boost::math::isnan(jt->x) || boost::math::isnan(jt->y) || boost::math::isnan(jt->z))) {
            SbVec3f pt(jt->x,jt->y,jt->z);

            // project from 3d to 2d
            vol.projectToScreen(pt, pt);
            if (cPoly.Contains(Base::Vector2D(pt[0],pt[1]))) {
                invalidatePoints = true;
                vec.Set(nan, nan, nan);
            }
        }

        newKernel.push_back(vec);
    }

    if (invalidatePoints) {
        //Remove the points from the cloud and open a transaction object for the undo/redo stuff
        Gui::Application::Instance->activeDocument()->openCommand("Cut points");

        // sets the points outside the polygon to update the Inventor node
        fea->Points.setValue(newKernel);

        // unset the modified flag because we don't need the features' execute() to be called
        Gui::Application::Instance->activeDocument()->commitCommand();
        fea->purgeTouched();
    }
}
void TaskCreateNodeSet::DefineNodes(const Base::Polygon2D &polygon,const Gui::ViewVolumeProjection &proj,bool inner)
{
    const SMESHDS_Mesh* data = const_cast<SMESH_Mesh*>(pcObject->FemMesh.getValue<Fem::FemMeshObject*>()->FemMesh.getValue().getSMesh())->GetMeshDS();

    SMDS_NodeIteratorPtr aNodeIter = data->nodesIterator();
    Base::Vector3f pt2d;

    if(! ui->checkBox_Add->isChecked())
        tempSet.clear();

    while (aNodeIter->more()) {
        const SMDS_MeshNode* aNode = aNodeIter->next();
        Base::Vector3f vec(aNode->X(),aNode->Y(),aNode->Z());
        pt2d = proj(vec);
        if (polygon.Contains(Base::Vector2D(pt2d.x, pt2d.y)) == inner)
            tempSet.insert(aNode->GetID());
    }

    MeshViewProvider->setHighlightNodes(tempSet);
}
bool MeshTrimming::IsPolygonPointInFacet(unsigned long ulIndex, Base::Vector3f& clPoint)
{
    Base::Vector2D A, B, C, P;
    float u,v,w, fDetPAC, fDetPBC, fDetPAB, fDetABC;
    Base::Polygon2D clFacPoly;
    const MeshGeomFacet &rclFacet = myMesh.GetFacet(ulIndex);
  
    for (int i=0; i<3; i++) {
        Base::Vector3f clPt = (*myProj)(rclFacet._aclPoints[i]);
        clFacPoly.Add(Base::Vector2D(clPt.x, clPt.y));
    }

    A = clFacPoly[0];
    B = clFacPoly[1];
    C = clFacPoly[2];
    fDetABC = A.fX*B.fY+A.fY*C.fX+B.fX*C.fY-(B.fY*C.fX+A.fY*B.fX+A.fX*C.fY);

    for (unsigned long j=0; j<myPoly.GetCtVectors(); j++) {
        // facet contains a polygon point -> calculate the corresponding 3d-point
        if (clFacPoly.Contains(myPoly[j])) {
            P = myPoly[j];
            fDetPAC = A.fX*P.fY+A.fY*C.fX+P.fX*C.fY-(P.fY*C.fX+A.fY*P.fX+A.fX*C.fY);
            fDetPBC = P.fX*B.fY+P.fY*C.fX+B.fX*C.fY-(B.fY*C.fX+P.fY*B.fX+P.fX*C.fY);
            fDetPAB = A.fX*B.fY+A.fY*P.fX+B.fX*P.fY-(B.fY*P.fX+A.fY*B.fX+A.fX*P.fY);
            u = fDetPBC / fDetABC;
            v = fDetPAC / fDetABC;
            w = fDetPAB / fDetABC;
      
            // point is on edge or no valid convex combination
            if (u == 0.0f || v == 0.0f || w == 0.0f || fabs(u+v+w-1.0f) >= 0.001)
                return false;
            // 3d point
            clPoint = u*rclFacet._aclPoints[0]+v*rclFacet._aclPoints[1]+w*rclFacet._aclPoints[2];

            return true;
        }
    }

    return false;
}
bool MeshTrimming::HasIntersection(const MeshGeomFacet& rclFacet) const
{
    int i;
    unsigned long j;
    Base::Polygon2D clPoly;
    Base::Line2D clFacLine, clPolyLine;
    Base::Vector2D S;
    // is corner of facet inside the polygon
    for (i=0; i<3; i++) {
        Base::Vector3f clPt2d = myProj->operator ()(rclFacet._aclPoints[i]);
        if (myPoly.Contains(Base::Vector2D(clPt2d.x, clPt2d.y)) == myInner)
            return true;
        else
            clPoly.Add(Base::Vector2D(clPt2d.x, clPt2d.y));
    }

    // is corner of polygon inside the facet
    for (j=0; j<myPoly.GetCtVectors(); j++) {
        if (clPoly.Contains(myPoly[j]))
            return true;
    }
  
    // check for other intersections
    for (j=0; j<myPoly.GetCtVectors(); j++) {
        clPolyLine.clV1 = myPoly[j];
        clPolyLine.clV2 = myPoly[(j+1)%myPoly.GetCtVectors()];

        for (i=0; i<3; i++) {
            clFacLine.clV1 = clPoly[i];
            clFacLine.clV2 = clPoly[(i+1)%3];

            if (clPolyLine.IntersectAndContain(clFacLine, S))
                return true;
        }
    }

    // no intersection
    return false;
}
void ViewProviderPoints::cut(const std::vector<SbVec2f>& picked, Gui::View3DInventorViewer &Viewer)
{
    // create the polygon from the picked points
    Base::Polygon2D cPoly;
    for (std::vector<SbVec2f>::const_iterator it = picked.begin(); it != picked.end(); ++it) {
        cPoly.Add(Base::Vector2D((*it)[0],(*it)[1]));
    }

    // get a reference to the point feature
    Points::Feature* fea = (Points::Feature*)pcObject;
    const Points::PointKernel& points = fea->Points.getValue();

    SoCamera* pCam = Viewer.getSoRenderManager()->getCamera();  
    SbViewVolume  vol = pCam->getViewVolume(); 

    // search for all points inside/outside the polygon
    Points::PointKernel newKernel;
    for ( Points::PointKernel::const_iterator jt = points.begin(); jt != points.end(); ++jt ) {
        SbVec3f pt(jt->x,jt->y,jt->z);

        // project from 3d to 2d
        vol.projectToScreen(pt, pt);
        if (!cPoly.Contains(Base::Vector2D(pt[0],pt[1])))
            newKernel.push_back(*jt);
    }

    if (newKernel.size() == points.size())
        return; // nothing needs to be done

    //Remove the points from the cloud and open a transaction object for the undo/redo stuff
    Gui::Application::Instance->activeDocument()->openCommand("Cut points");

    // sets the points outside the polygon to update the Inventor node
    fea->Points.setValue(newKernel);

    // unset the modified flag because we don't need the features' execute() to be called
    Gui::Application::Instance->activeDocument()->commitCommand();
    fea->purgeTouched();
}
void DefineNodesCallback(void * ud, SoEventCallback * n)
{
    Fem::FemAnalysis        *Analysis;

    if(getConstraintPrerequisits(&Analysis))
        return;

    // show the wait cursor because this could take quite some time
    Gui::WaitCursor wc;

    // When this callback function is invoked we must in either case leave the edit mode
    Gui::View3DInventorViewer* view  = reinterpret_cast<Gui::View3DInventorViewer*>(n->getUserData());
    view->setEditing(false);
    view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), DefineNodesCallback,ud);
    n->setHandled();

    SbBool clip_inner;
    std::vector<SbVec2f> clPoly = view->getGLPolygon(&clip_inner);
    if (clPoly.size() < 3)
        return;
    if (clPoly.front() != clPoly.back())
        clPoly.push_back(clPoly.front());

    SoCamera* cam = view->getCamera();
    SbViewVolume vv = cam->getViewVolume();
    Gui::ViewVolumeProjection proj(vv);
    Base::Polygon2D polygon;
    for (std::vector<SbVec2f>::const_iterator it = clPoly.begin(); it != clPoly.end(); ++it)
        polygon.Add(Base::Vector2D((*it)[0],(*it)[1]));


    std::vector<App::DocumentObject*> docObj = Gui::Selection().getObjectsOfType(Fem::FemMeshObject::getClassTypeId());
    if(docObj.size() !=1)
        return;

    const SMESHDS_Mesh* data = const_cast<SMESH_Mesh*>(dynamic_cast<Fem::FemMeshObject*>(docObj[0])->FemMesh.getValue().getSMesh())->GetMeshDS();

    SMDS_NodeIteratorPtr aNodeIter = data->nodesIterator();
    Base::Vector3f pt2d;
    std::set<int> IntSet;

    for (int i=0;aNodeIter->more();) {
        const SMDS_MeshNode* aNode = aNodeIter->next();
        Base::Vector3f vec(aNode->X(),aNode->Y(),aNode->Z());
        pt2d = proj(vec);
        if (polygon.Contains(Base::Vector2D(pt2d.x, pt2d.y)) == true) 
            IntSet.insert(aNode->GetID());
    }
    
    std::stringstream  set;

    set << "[";
    for(std::set<int>::const_iterator it=IntSet.begin();it!=IntSet.end();++it)
        if(it==IntSet.begin())
            set << *it ;
        else
            set << "," << *it ;
    set << "]";

    
    Gui::Command::openCommand("Place robot");
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.addObject('Fem::FemSetNodesObject','NodeSet')");
    Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.ActiveObject.Nodes = %s",set.str().c_str());
    Gui::Command::doCommand(Gui::Command::Doc,"App.activeDocument().%s.Member = App.activeDocument().%s.Member + [App.activeDocument().NodeSet]",Analysis->getNameInDocument(),Analysis->getNameInDocument());
    ////Gui::Command::updateActive();
    Gui::Command::commitCommand();

    //std::vector<Gui::ViewProvider*> views = view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId());
    //if (!views.empty()) {
    //    Gui::Application::Instance->activeDocument()->openCommand("Cut");
    //    for (std::vector<Gui::ViewProvider*>::iterator it = views.begin(); it != views.end(); ++it) {
    //        ViewProviderMesh* that = static_cast<ViewProviderMesh*>(*it);
    //        if (that->getEditingMode() > -1) {
    //            that->finishEditing();
    //            that->cutMesh(clPoly, *view, clip_inner);
    //        }
    //    }

    //    Gui::Application::Instance->activeDocument()->commitCommand();

    //    view->render();
    //}
}
void ViewProviderScattered::cut(const std::vector<SbVec2f>& picked, Gui::View3DInventorViewer &Viewer)
{
    // create the polygon from the picked points
    Base::Polygon2D cPoly;
    for (std::vector<SbVec2f>::const_iterator it = picked.begin(); it != picked.end(); ++it) {
        cPoly.Add(Base::Vector2D((*it)[0],(*it)[1]));
    }

    // get a reference to the point feature
    Points::Feature* fea = static_cast<Points::Feature*>(pcObject);
    const Points::PointKernel& points = fea->Points.getValue();

    SoCamera* pCam = Viewer.getSoRenderManager()->getCamera();
    SbViewVolume  vol = pCam->getViewVolume();

    // search for all points inside/outside the polygon
    std::vector<unsigned long> removeIndices;
    removeIndices.reserve(points.size());

    unsigned long index = 0;
    for (Points::PointKernel::const_iterator jt = points.begin(); jt != points.end(); ++jt, ++index) {
        SbVec3f pt(jt->x,jt->y,jt->z);

        // project from 3d to 2d
        vol.projectToScreen(pt, pt);
        if (cPoly.Contains(Base::Vector2D(pt[0],pt[1])))
            removeIndices.push_back(index);
    }

    if (removeIndices.empty())
        return; // nothing needs to be done

    //Remove the points from the cloud and open a transaction object for the undo/redo stuff
    Gui::Application::Instance->activeDocument()->openCommand("Cut points");

    // sets the points outside the polygon to update the Inventor node
    fea->Points.removeIndices(removeIndices);

    std::map<std::string,App::Property*> Map;
    pcObject->getPropertyMap(Map);

    for (std::map<std::string,App::Property*>::iterator it = Map.begin(); it != Map.end(); ++it) {
        Base::Type type = it->second->getTypeId();
        if (type == Points::PropertyNormalList::getClassTypeId()) {
            static_cast<Points::PropertyNormalList*>(it->second)->removeIndices(removeIndices);
        }
        else if (type == Points::PropertyGreyValueList::getClassTypeId()) {
            static_cast<Points::PropertyGreyValueList*>(it->second)->removeIndices(removeIndices);
        }
        else if (type == App::PropertyColorList::getClassTypeId()) {
            //static_cast<App::PropertyColorList*>(it->second)->removeIndices(removeIndices);
            const std::vector<App::Color>& colors = static_cast<App::PropertyColorList*>(it->second)->getValues();

            if (removeIndices.size() > colors.size())
                break;

            std::vector<App::Color> remainValue;
            remainValue.reserve(colors.size() - removeIndices.size());

            std::vector<unsigned long>::iterator pos = removeIndices.begin();
            for (std::vector<App::Color>::const_iterator jt = colors.begin(); jt != colors.end(); ++jt) {
                unsigned long index = jt - colors.begin();
                if (pos == removeIndices.end())
                    remainValue.push_back( *jt );
                else if (index != *pos)
                    remainValue.push_back( *jt );
                else 
                    ++pos;
            }

            static_cast<App::PropertyColorList*>(it->second)->setValues(remainValue);
        }
    }

    // unset the modified flag because we don't need the features' execute() to be called
    Gui::Application::Instance->activeDocument()->commitCommand();
    fea->purgeTouched();
}