std::vector<TopoDS_Wire> SketchBased::getSketchWires() const { std::vector<TopoDS_Wire> result; TopoDS_Shape shape = getVerifiedSketch()->Shape.getShape()._Shape; if (shape.IsNull()) throw Base::Exception("Linked shape object is empty"); // this is a workaround for an obscure OCC bug which leads to empty tessellations // for some faces. Making an explicit copy of the linked shape seems to fix it. // The error almost happens when re-computing the shape but sometimes also for the // first time BRepBuilderAPI_Copy copy(shape); shape = copy.Shape(); if (shape.IsNull()) throw Base::Exception("Linked shape object is empty"); TopExp_Explorer ex; for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next()) { result.push_back(TopoDS::Wire(ex.Current())); } if (result.empty()) // there can be several wires throw Base::Exception("Linked shape object is not a wire"); return result; }
//======================================================================= //function : Execute //purpose : //======================================================================= Standard_Integer GEOMImpl_CylinderDriver::Execute(TFunction_Logbook& log) const { if (Label().IsNull()) return 0; Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label()); GEOMImpl_ICylinder aCI (aFunction); Standard_Integer aType = aFunction->GetType(); gp_Pnt aP; gp_Vec aV; if (aType == CYLINDER_R_H) { aP = gp::Origin(); aV = gp::DZ(); } else if (aType == CYLINDER_PNT_VEC_R_H) { Handle(GEOM_Function) aRefPoint = aCI.GetPoint(); Handle(GEOM_Function) aRefVector = aCI.GetVector(); TopoDS_Shape aShapePnt = aRefPoint->GetValue(); TopoDS_Shape aShapeVec = aRefVector->GetValue(); if (aShapePnt.IsNull() || aShapeVec.IsNull()) { Standard_NullObject::Raise("Cylinder creation aborted: point or vector is not defined"); } if (aShapePnt.ShapeType() != TopAbs_VERTEX || aShapeVec.ShapeType() != TopAbs_EDGE) { Standard_TypeMismatch::Raise("Cylinder creation aborted: point or vector shapes has wrong type"); } aP = BRep_Tool::Pnt(TopoDS::Vertex(aShapePnt)); TopoDS_Edge anE = TopoDS::Edge(aShapeVec); TopoDS_Vertex V1, V2; TopExp::Vertices(anE, V1, V2, Standard_True); if (V1.IsNull() || V2.IsNull()) { Standard_NullObject::Raise("Cylinder creation aborted: vector is not defined"); } aV = gp_Vec(BRep_Tool::Pnt(V1), BRep_Tool::Pnt(V2)); } else { return 0; } if (aCI.GetH() < 0.0) aV.Reverse(); gp_Ax2 anAxes (aP, aV); BRepPrimAPI_MakeCylinder MC (anAxes, aCI.GetR(), Abs(aCI.GetH())); MC.Build(); if (!MC.IsDone()) { StdFail_NotDone::Raise("Cylinder can't be computed from the given parameters"); } TopoDS_Shape aShape = MC.Shape(); if (aShape.IsNull()) return 0; aFunction->SetValue(aShape); log.SetTouched(Label()); return 1; }
//======================================================================= //function : Execute //purpose : //======================================================================= Standard_Integer GEOM_SubShapeDriver::Execute(TFunction_Logbook& log) const { if (Label().IsNull()) return 0; Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label()); GEOM_ISubShape aCI (aFunction); TDF_Label aLabel = aCI.GetMainShape()->GetOwnerEntry(); if (aLabel.IsRoot()) return 0; Handle(GEOM_Object) anObj = GEOM_Object::GetObject(aLabel); if (anObj.IsNull()) return 0; TopoDS_Shape aMainShape = anObj->GetValue(); if (aMainShape.IsNull()) return 0; Handle(TColStd_HArray1OfInteger) anIndices = aCI.GetIndices(); if (anIndices.IsNull() || anIndices->Length() <= 0) return 0; BRep_Builder B; TopoDS_Compound aCompound; TopoDS_Shape aShape; if (anIndices->Length() == 1 && anIndices->Value(1) == -1) { //The empty sub-shape B.MakeCompound(aCompound); aShape = aCompound; } else { TopTools_IndexedMapOfShape aMapOfShapes; TopExp::MapShapes(aMainShape, aMapOfShapes); if (anIndices->Length() > 1) { B.MakeCompound(aCompound); for (int i = anIndices->Lower(); i <= anIndices->Upper(); i++) { if (aMapOfShapes.Extent() < anIndices->Value(i)) Standard_NullObject::Raise("GEOM_SubShapeDriver::Execute: Index is out of range"); TopoDS_Shape aSubShape = aMapOfShapes.FindKey(anIndices->Value(i)); if (aSubShape.IsNull()) continue; B.Add(aCompound,aSubShape); } aShape = aCompound; } else { int i = anIndices->Lower(); if (aMapOfShapes.Extent() < anIndices->Value(i)) Standard_NullObject::Raise("GEOM_SubShapeDriver::Execute: Index is out of range"); aShape = aMapOfShapes.FindKey(anIndices->Value(i)); } } if (aShape.IsNull()) return 0; aFunction->SetValue(aShape); log.SetTouched(Label()); return 1; }
Standard_Boolean ShHealOper_RemoveFace::isReplace(const TopoDS_Shape& theShape, TopoDS_Shape& theNewShape) { Standard_Boolean isChange = Standard_False; TopTools_SequenceOfShape aSeqShapes; if(theShape.ShapeType() == TopAbs_COMPOUND || theShape.ShapeType() == TopAbs_COMPSOLID || theShape.ShapeType() == TopAbs_SOLID) { TopoDS_Iterator aEs(theShape); for( ; aEs.More(); aEs.Next()) { TopoDS_Shape aNewShell = aEs.Value(); if(aNewShell.ShapeType()!= TopAbs_SHELL) { aSeqShapes.Append(aNewShell); continue; } TopoDS_Shape as = getResultShell(TopoDS::Shell(aNewShell)); isChange = (as.IsNull() || (as.ShapeType() == TopAbs_FACE)); if(!as.IsNull()) { aSeqShapes.Append(as); } } } else if(theShape.ShapeType() == TopAbs_SHELL) { TopoDS_Shape aSh = getResultShell(TopoDS::Shell(theShape)); isChange = (aSh.IsNull() || (aSh.ShapeType() == TopAbs_FACE)); if(!aSh.IsNull()) aSeqShapes.Append(aSh); } else aSeqShapes.Append(theShape); if(aSeqShapes.IsEmpty()) return Standard_True; if(isChange) { if(aSeqShapes.Length() == 1) theNewShape = aSeqShapes.Value(1); else if (aSeqShapes.Length() > 1) { TopoDS_Compound aComp1; BRep_Builder aBB; aBB.MakeCompound(aComp1); Standard_Integer kk =1; for( ; kk <= aSeqShapes.Length(); kk++) aBB.Add(aComp1,aSeqShapes.Value(kk)); if(aSeqShapes.Length()) theNewShape = aComp1; } } else theNewShape = theShape; return isChange; }
bool IfcGeom::Kernel::convert(const IfcSchema::IfcExtrudedAreaSolid* l, TopoDS_Shape& shape) { const double height = l->Depth() * getValue(GV_LENGTH_UNIT); if (height < getValue(GV_PRECISION)) { Logger::Message(Logger::LOG_ERROR, "Non-positive extrusion height encountered for:", l->entity); return false; } TopoDS_Shape face; if ( !convert_face(l->SweptArea(),face) ) return false; gp_Trsf trsf; IfcGeom::Kernel::convert(l->Position(),trsf); gp_Dir dir; convert(l->ExtrudedDirection(),dir); shape.Nullify(); if (face.ShapeType() == TopAbs_COMPOUND) { // For compounds (most likely the result of a IfcCompositeProfileDef) // create a compound solid shape. TopExp_Explorer exp(face, TopAbs_FACE); TopoDS_CompSolid compound; BRep_Builder builder; builder.MakeCompSolid(compound); int num_faces_extruded = 0; for (; exp.More(); exp.Next(), ++num_faces_extruded) { builder.Add(compound, BRepPrimAPI_MakePrism(exp.Current(), height*dir)); } if (num_faces_extruded) { shape = compound; } } if (shape.IsNull()) { shape = BRepPrimAPI_MakePrism(face, height*dir); } // IfcSweptAreaSolid.Position (trsf) is an IfcAxis2Placement3D // and therefore has a unit scale factor shape.Move(trsf); return ! shape.IsNull(); }
//! tries to find the intersection of the section plane with the shape giving a collection of planar faces TopoDS_Compound DrawViewSection::findSectionPlaneIntersections(const TopoDS_Shape& shape) { TopoDS_Compound result; if(shape.IsNull()){ Base::Console().Log("DrawViewSection::getSectionSurface - Sectional View shape is Empty\n"); return result; } gp_Pln plnSection = getSectionPlane(); BRep_Builder builder; builder.MakeCompound(result); TopExp_Explorer expFaces(shape, TopAbs_FACE); int i; int dbAdded = 0; for (i = 1 ; expFaces.More(); expFaces.Next(), i++) { const TopoDS_Face& face = TopoDS::Face(expFaces.Current()); BRepAdaptor_Surface adapt(face); if (adapt.GetType() == GeomAbs_Plane){ gp_Pln plnFace = adapt.Plane(); if(plnSection.Contains(plnFace.Location(), Precision::Confusion()) && plnFace.Axis().IsParallel(plnSection.Axis(), Precision::Angular())) { dbAdded++; builder.Add(result, face); } } } return result; }
bool allow(App::Document*pDoc, App::DocumentObject*pObj, const char*sSubName) { this->canSelect = false; if (!pObj->isDerivedFrom(Part::Feature::getClassTypeId())) return false; if (!sSubName || sSubName[0] == '\0') return false; std::string element(sSubName); if (element.substr(0,4) != "Edge") return false; Part::Feature* fea = static_cast<Part::Feature*>(pObj); try { TopoDS_Shape sub = fea->Shape.getShape().getSubShape(sSubName); if (!sub.IsNull() && sub.ShapeType() == TopAbs_EDGE) { const TopoDS_Edge& edge = TopoDS::Edge(sub); BRepAdaptor_Curve adapt(edge); if (adapt.GetType() == GeomAbs_Line) { gp_Lin line = adapt.Line(); this->loc = line.Location(); this->dir = line.Direction(); this->canSelect = true; return true; } } } catch (...) { } return false; }
App::DocumentObjectExecReturn *Revolution::execute(void) { App::DocumentObject* link = Source.getValue(); if (!link) return new App::DocumentObjectExecReturn("No object linked"); if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) return new App::DocumentObjectExecReturn("Linked object is not a Part object"); Part::Feature *base = static_cast<Part::Feature*>(Source.getValue()); Base::Vector3d b = Base.getValue(); Base::Vector3d v = Axis.getValue(); gp_Pnt pnt(b.x,b.y,b.z); gp_Dir dir(v.x,v.y,v.z); Standard_Boolean isSolid = Solid.getValue() ? Standard_True : Standard_False; try { // Now, let's get the TopoDS_Shape //TopoDS_Shape revolve = base->Shape.getShape().revolve(gp_Ax1(pnt, dir), // Angle.getValue()/180.0f*M_PI); TopoDS_Shape revolve = base->Shape.getShape().revolve(gp_Ax1(pnt, dir), Angle.getValue()/180.0f*M_PI,isSolid); if (revolve.IsNull()) return new App::DocumentObjectExecReturn("Resulting shape is null"); this->Shape.setValue(revolve); return App::DocumentObject::StdReturn; } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); return new App::DocumentObjectExecReturn(e->GetMessageString()); } }
void DlgExtrusion::autoSolid() { try{ App::DocumentObject &dobj = this->getShapeToExtrude(); if (dobj.isDerivedFrom(Part::Feature::getClassTypeId())){ Part::Feature &feature = static_cast<Part::Feature&>(dobj); TopoDS_Shape sh = feature.Shape.getValue(); if (sh.IsNull()) return; ShapeExtend_Explorer xp; Handle(TopTools_HSequenceOfShape) leaves = xp.SeqFromCompound(sh, /*recursive= */Standard_True); int cntClosedWires = 0; for(int i = 0; i < leaves->Length(); i++){ const TopoDS_Shape &leaf = leaves->Value(i+1); if (leaf.IsNull()) return; if (leaf.ShapeType() == TopAbs_WIRE || leaf.ShapeType() == TopAbs_EDGE){ if (BRep_Tool::IsClosed(leaf)){ cntClosedWires++; } } } ui->chkSolid->setChecked( cntClosedWires == leaves->Length() ); } } catch(...) { } }
bool SweepWidget::isPathValid(const Gui::SelectionObject& sel) const { const App::DocumentObject* path = sel.getObject(); if (!(path && path->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))) return false; const std::vector<std::string>& sub = sel.getSubNames(); TopoDS_Shape pathShape; const Part::TopoShape& shape = static_cast<const Part::Feature*>(path)->Shape.getValue(); if (!sub.empty()) { try { BRepBuilderAPI_MakeWire mkWire; for (std::vector<std::string>::const_iterator it = sub.begin(); it != sub.end(); ++it) { TopoDS_Shape subshape = shape.getSubShape(it->c_str()); mkWire.Add(TopoDS::Edge(subshape)); } pathShape = mkWire.Wire(); } catch (...) { return false; } } else if (shape._Shape.ShapeType() == TopAbs_EDGE) { pathShape = shape._Shape; } else if (shape._Shape.ShapeType() == TopAbs_WIRE) { BRepBuilderAPI_MakeWire mkWire(TopoDS::Wire(shape._Shape)); pathShape = mkWire.Wire(); } return (!pathShape.IsNull()); }
bool IfcGeom::Kernel::convert(const IfcSchema::IfcCompositeProfileDef* l, TopoDS_Shape& face) { // BRepBuilderAPI_MakeFace mf; TopoDS_Compound compound; BRep_Builder builder; builder.MakeCompound(compound); IfcSchema::IfcProfileDef::list::ptr profiles = l->Profiles(); //bool first = true; for (IfcSchema::IfcProfileDef::list::it it = profiles->begin(); it != profiles->end(); ++it) { TopoDS_Face f; if (convert_face(*it, f)) { builder.Add(compound, f); /* TopExp_Explorer exp(f, TopAbs_WIRE); for (; exp.More(); exp.Next()) { const TopoDS_Wire& wire = TopoDS::Wire(exp.Current()); if (first) { mf.Init(BRepBuilderAPI_MakeFace(wire)); } else { mf.Add(wire); } first = false; } */ } } face = compound; return !face.IsNull(); }
/** * @todo: it would be nice if this algorithm would support * some progress bar interface */ void CTiglFusePlane::Perform() { if (_hasPerformed) { return; } CTiglUIDManager& uidManager = _myconfig.GetUIDManager(); CTiglAbstractPhysicalComponent* rootComponent = uidManager.GetRootComponent(); if (!rootComponent) { LOG(ERROR) << "Root component of plane not found. Cannot create fused plane."; return; } _result = FuseWithChilds(rootComponent); CCPACSFarField& farfield = _myconfig.GetFarField(); if (farfield.GetFieldType() != NONE && (_mymode == FULL_PLANE_TRIMMED_FF || _mymode == HALF_PLANE_TRIMMED_FF)) { PNamedShape ff = farfield.GetLoft(); BOPCol_ListOfShape aLS; aLS.Append(_result->Shape()); aLS.Append(ff->Shape()); BOPAlgo_PaveFiller dsfill; dsfill.SetArguments(aLS); dsfill.Perform(); CTrimShape trim1(_result, ff, dsfill, INCLUDE); PNamedShape resulttrimmed = trim1.NamedShape(); CTrimShape trim2(ff, _result, dsfill, EXCLUDE); _farfield = trim2.NamedShape(); _result = resulttrimmed; // trim intersections with far field ListPNamedShape::iterator intIt = _intersections.begin(); ListPNamedShape newInts; for (; intIt != _intersections.end(); ++intIt) { PNamedShape inters = *intIt; if (!inters) { continue; } TopoDS_Shape sh = inters->Shape(); sh = BRepAlgoAPI_Common(sh, ff->Shape()); if (! sh.IsNull()) { inters->SetShape(sh); newInts.push_back(inters); } } _intersections = newInts; } if (_result) { _result->SetName(_myconfig.GetUID().c_str()); _result->SetShortName("AIRCRAFT"); } _hasPerformed = true; }
// TODO: This code is taken from and duplicates code in Part2DObject::positionBySupport() // Note: We cannot return a reference, because it will become Null. // Not clear where, because we check for IsNull() here, but as soon as it is passed out of // this method, it becomes null! const TopoDS_Face SketchBased::getSupportFace() const { const App::PropertyLinkSub& Support = static_cast<Part::Part2DObject*>(Sketch.getValue())->Support; Part::Feature *part = static_cast<Part::Feature*>(Support.getValue()); if (!part || !part->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) throw Base::Exception("Sketch has no support shape"); const std::vector<std::string> &sub = Support.getSubValues(); assert(sub.size()==1); // get the selected sub shape (a Face) const Part::TopoShape &shape = part->Shape.getShape(); if (shape._Shape.IsNull()) throw Base::Exception("Sketch support shape is empty!"); TopoDS_Shape sh = shape.getSubShape(sub[0].c_str()); if (sh.IsNull()) throw Base::Exception("Null shape in SketchBased::getSupportFace()!"); const TopoDS_Face face = TopoDS::Face(sh); if (face.IsNull()) throw Base::Exception("Null face in SketchBased::getSupportFace()!"); BRepAdaptor_Surface adapt(face); if (adapt.GetType() != GeomAbs_Plane) throw Base::Exception("No planar face in SketchBased::getSupportFace()!"); return face; }
PyObject* TopoShapeFacePy::curveOnSurface(PyObject *args) { PyObject* e; if (!PyArg_ParseTuple(args, "O!", &(TopoShapeEdgePy::Type), &e)) return 0; try { TopoDS_Shape shape = static_cast<TopoShapeEdgePy*>(e)->getTopoShapePtr()->getShape(); if (shape.IsNull()) { PyErr_SetString(PyExc_RuntimeError, "invalid shape"); return 0; } TopoDS_Edge edge = TopoDS::Edge(shape); const TopoDS_Face& face = TopoDS::Face(getTopoShapePtr()->getShape()); Standard_Real first, last; Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface(edge, face, first, last); std::unique_ptr<Part::Geom2dCurve> geo2d = getCurve2dFromGeom2d(curve); if (!geo2d) Py_Return; Py::Tuple tuple(3); tuple.setItem(0, Py::asObject(geo2d->getPyObject())); tuple.setItem(1, Py::Float(first)); tuple.setItem(2, Py::Float(last)); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); return 0; } }
bool Translator::importVRML(const QString& file) { VrmlData_Scene vrmlScene; filebuf fb; fb.open(file.toUtf8().data(), ios::in); if(fb.is_open() == false) return false; Standard_IStream input(&fb); vrmlScene << input; fb.close(); if(vrmlScene.Status() != VrmlData_StatusOK) return false; VrmlData_DataMapOfShapeAppearance map; TopoDS_Shape shape = vrmlScene.GetShape(map); if(shape.IsNull()) return false; m_doc->insert(shape, QFileInfo(file).baseName()); return true; }
bool DlgExtrusion::canExtrude(const TopoDS_Shape& shape) const { if (shape.IsNull()) return false; TopAbs_ShapeEnum type = shape.ShapeType(); if (type == TopAbs_VERTEX || type == TopAbs_EDGE || type == TopAbs_WIRE || type == TopAbs_FACE || type == TopAbs_SHELL) return true; if (type == TopAbs_COMPOUND) { TopExp_Explorer xp; xp.Init(shape,TopAbs_SOLID); while (xp.More()) { return false; } xp.Init(shape,TopAbs_COMPSOLID); while (xp.More()) { return false; } return true; } return false; }
App::DocumentObjectExecReturn *Loft::execute(void) { if (Sections.getSize() == 0) return new App::DocumentObjectExecReturn("No sections linked."); try { TopTools_ListOfShape profiles; const std::vector<App::DocumentObject*>& shapes = Sections.getValues(); std::vector<App::DocumentObject*>::const_iterator it; for (it = shapes.begin(); it != shapes.end(); ++it) { if (!(*it)->isDerivedFrom(Part::Feature::getClassTypeId())) return new App::DocumentObjectExecReturn("Linked object is not a shape."); TopoDS_Shape shape = static_cast<Part::Feature*>(*it)->Shape.getValue(); if (shape.IsNull()) return new App::DocumentObjectExecReturn("Linked shape is invalid."); // Extract first element of a compound if (shape.ShapeType() == TopAbs_COMPOUND) { TopoDS_Iterator it(shape); for (; it.More(); it.Next()) { if (!it.Value().IsNull()) { shape = it.Value(); break; } } } if (shape.ShapeType() == TopAbs_FACE) { TopoDS_Wire faceouterWire = ShapeAnalysis::OuterWire(TopoDS::Face(shape)); profiles.Append(faceouterWire); } else if (shape.ShapeType() == TopAbs_WIRE) { BRepBuilderAPI_MakeWire mkWire(TopoDS::Wire(shape)); profiles.Append(mkWire.Wire()); } else if (shape.ShapeType() == TopAbs_EDGE) { BRepBuilderAPI_MakeWire mkWire(TopoDS::Edge(shape)); profiles.Append(mkWire.Wire()); } else if (shape.ShapeType() == TopAbs_VERTEX) { profiles.Append(shape); } else { return new App::DocumentObjectExecReturn("Linked shape is not a vertex, edge, wire nor face."); } } Standard_Boolean isSolid = Solid.getValue() ? Standard_True : Standard_False; Standard_Boolean isRuled = Ruled.getValue() ? Standard_True : Standard_False; Standard_Boolean isClosed = Closed.getValue() ? Standard_True : Standard_False; TopoShape myShape; this->Shape.setValue(myShape.makeLoft(profiles, isSolid, isRuled,isClosed)); return App::DocumentObject::StdReturn; } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); return new App::DocumentObjectExecReturn(e->GetMessageString()); } }
// constructor method int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) { double x=0.0,y=0.0,z=0.0; PyObject *object; bool success = false; if (PyArg_ParseTuple(args, "|ddd", &x,&y,&z)) { // do nothing here success = true; } if (!success) { PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { // Note: must be static_cast, not reinterpret_cast Base::Vector3d* ptr = static_cast<Base::VectorPy*>(object)->getVectorPtr(); x = ptr->x; y = ptr->y; z = ptr->z; success = true; } } if (!success) { PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args,"O!",&(PyTuple_Type), &object)) { try { Py::Tuple tuple(object); x = Py::Float(tuple.getItem(0)); y = Py::Float(tuple.getItem(1)); z = Py::Float(tuple.getItem(2)); success = true; } catch (const Py::Exception&) { return -1; } } } if (!success) { PyErr_Clear(); // set by PyArg_ParseTuple() if (PyArg_ParseTuple(args,"O!",&(Part::TopoShapePy::Type), &object)) { TopoShape* ptr = static_cast<TopoShapePy*>(object)->getTopoShapePtr(); TopoDS_Shape shape = ptr->_Shape; if (!shape.IsNull() && shape.ShapeType() == TopAbs_VERTEX) { TopoShapeVertexPy::PointerType vert = reinterpret_cast<TopoShapeVertexPy::PointerType>(_pcTwinPointer); vert->_Shape = ptr->_Shape; return 0; } } } if (!success) { PyErr_SetString(PyExc_TypeError, "Either three floats, tuple, vector or vertex expected"); return -1; } TopoShapeVertexPy::PointerType ptr = reinterpret_cast<TopoShapeVertexPy::PointerType>(_pcTwinPointer); BRepBuilderAPI_MakeVertex aBuilder(gp_Pnt(x,y,z)); TopoDS_Shape s = aBuilder.Vertex(); ptr->_Shape = s; return 0; }
void TaskCheckGeometryResults::goCheck() { Gui::WaitCursor wc; int selectedCount(0), checkedCount(0), invalidShapes(0); std::vector<Gui::SelectionSingleton::SelObj> selection = Gui::Selection().getSelection(); std::vector<Gui::SelectionSingleton::SelObj>::iterator it; ResultEntry *theRoot = new ResultEntry(); for (it = selection.begin(); it != selection.end(); ++it) { selectedCount++; Part::Feature *feature = dynamic_cast<Part::Feature *>((*it).pObject); if (!feature) continue; currentProvider = Gui::Application::Instance->activeDocument()->getViewProvider(feature); if (!currentProvider) continue; TopoDS_Shape shape = feature->Shape.getValue(); QString baseName; QTextStream baseStream(&baseName); baseStream << (*it).DocName; baseStream << "." << (*it).FeatName; if (strlen((*it).SubName) > 0) { shape = feature->Shape.getShape().getSubShape((*it).SubName); baseStream << "." << (*it).SubName; } if (shape.IsNull()) continue; checkedCount++; checkedMap.Clear(); BRepCheck_Analyzer shapeCheck(shape); if (!shapeCheck.IsValid()) { invalidShapes++; ResultEntry *entry = new ResultEntry(); entry->parent = theRoot; entry->shape = shape; entry->name = baseName; entry->type = shapeEnumToString(shape.ShapeType()); entry->error = QObject::tr("Invalid"); entry->viewProvider = currentProvider; getSetupResultBoundingBoxObject().go(entry); theRoot->children.push_back(entry); recursiveCheck(shapeCheck, shape, entry); } } model->setResults(theRoot); treeView->expandAll(); treeView->header()->resizeSections(QHeaderView::ResizeToContents); QString aMessage; QTextStream aStream(&aMessage); aStream << checkedCount << " processed out of " << selectedCount << " selected\n"; aStream << invalidShapes << " invalid shapes."; message->setText(aMessage); Gui::Selection().clearSelection(); }
App::DocumentObjectExecReturn *Chamfer::execute(void) { App::DocumentObject* link = Base.getValue(); if (!link) return new App::DocumentObjectExecReturn("No object linked"); if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) return new App::DocumentObjectExecReturn("Linked object is not a Part object"); Part::Feature *base = static_cast<Part::Feature*>(Base.getValue()); const Part::TopoShape& TopShape = base->Shape.getShape(); if (TopShape._Shape.IsNull()) return new App::DocumentObjectExecReturn("Cannot chamfer invalid shape"); const std::vector<std::string>& SubVals = Base.getSubValuesStartsWith("Edge"); if (SubVals.size() == 0) return new App::DocumentObjectExecReturn("No edges specified"); double size = Size.getValue(); this->positionByBase(); // create an untransformed copy of the base shape Part::TopoShape baseShape(TopShape); baseShape.setTransform(Base::Matrix4D()); try { BRepFilletAPI_MakeChamfer mkChamfer(baseShape._Shape); TopTools_IndexedMapOfShape mapOfEdges; TopTools_IndexedDataMapOfShapeListOfShape mapEdgeFace; TopExp::MapShapesAndAncestors(baseShape._Shape, TopAbs_EDGE, TopAbs_FACE, mapEdgeFace); TopExp::MapShapes(baseShape._Shape, TopAbs_EDGE, mapOfEdges); for (std::vector<std::string>::const_iterator it=SubVals.begin(); it != SubVals.end(); ++it) { TopoDS_Edge edge = TopoDS::Edge(baseShape.getSubShape(it->c_str())); const TopoDS_Face& face = TopoDS::Face(mapEdgeFace.FindFromKey(edge).First()); mkChamfer.Add(size, edge, face); } mkChamfer.Build(); if (!mkChamfer.IsDone()) return new App::DocumentObjectExecReturn("Failed to create chamfer"); TopoDS_Shape shape = mkChamfer.Shape(); if (shape.IsNull()) return new App::DocumentObjectExecReturn("Resulting shape is null"); TopTools_ListOfShape aLarg; aLarg.Append(baseShape._Shape); if (!BRepAlgo::IsValid(aLarg, shape, Standard_False, Standard_False)) { return new App::DocumentObjectExecReturn("Resulting shape is invalid"); } this->Shape.setValue(shape); return App::DocumentObject::StdReturn; } catch (Standard_Failure) { Handle_Standard_Failure e = Standard_Failure::Caught(); return new App::DocumentObjectExecReturn(e->GetMessageString()); } }
bool SweepWidget::isPathValid(const Gui::SelectionObject& sel) const { const App::DocumentObject* path = sel.getObject(); if (!(path && path->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))) return false; const std::vector<std::string>& sub = sel.getSubNames(); TopoDS_Shape pathShape; const Part::TopoShape& shape = static_cast<const Part::Feature*>(path)->Shape.getValue(); if (!sub.empty()) { try { BRepBuilderAPI_MakeWire mkWire; for (std::vector<std::string>::const_iterator it = sub.begin(); it != sub.end(); ++it) { TopoDS_Shape subshape = shape.getSubShape(it->c_str()); mkWire.Add(TopoDS::Edge(subshape)); } pathShape = mkWire.Wire(); } catch (...) { return false; } } else if (shape._Shape.ShapeType() == TopAbs_EDGE) { pathShape = shape._Shape; } else if (shape._Shape.ShapeType() == TopAbs_WIRE) { BRepBuilderAPI_MakeWire mkWire(TopoDS::Wire(shape._Shape)); pathShape = mkWire.Wire(); } else if (shape._Shape.ShapeType() == TopAbs_COMPOUND) { try { TopoDS_Iterator it(shape._Shape); for (; it.More(); it.Next()) { if ((it.Value().ShapeType() != TopAbs_EDGE) && (it.Value().ShapeType() != TopAbs_WIRE)) { return false; } } Handle(TopTools_HSequenceOfShape) hEdges = new TopTools_HSequenceOfShape(); Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); for (TopExp_Explorer xp(shape._Shape, TopAbs_EDGE); xp.More(); xp.Next()) hEdges->Append(xp.Current()); ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, Precision::Confusion(), Standard_True, hWires); int len = hWires->Length(); if (len != 1) return false; pathShape = hWires->Value(1); } catch (...) { return false; } } return (!pathShape.IsNull()); }
//======================================================================= //function : Execute //purpose : //======================================================================= Standard_Integer GEOMImpl_BoxDriver::Execute(TFunction_Logbook& log) const { if (Label().IsNull()) return 0; Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label()); GEOMImpl_IBox aBI (aFunction); Standard_Integer aType = aFunction->GetType(); TopoDS_Shape aShape; if (aType == BOX_DX_DY_DZ) { BRepPrimAPI_MakeBox MB (aBI.GetDX(), aBI.GetDY(), aBI.GetDZ()); MB.Build(); if (!MB.IsDone()) { StdFail_NotDone::Raise("Box with the given dimensions can not be computed"); } aShape = MB.Shape(); } else if (aType == BOX_TWO_PNT) { Handle(GEOM_Function) aRefPoint1 = aBI.GetRef1(); Handle(GEOM_Function) aRefPoint2 = aBI.GetRef2(); TopoDS_Shape aShape1 = aRefPoint1->GetValue(); TopoDS_Shape aShape2 = aRefPoint2->GetValue(); if (aShape1.ShapeType() == TopAbs_VERTEX && aShape2.ShapeType() == TopAbs_VERTEX) { gp_Pnt P1 = BRep_Tool::Pnt(TopoDS::Vertex(aShape1)); gp_Pnt P2 = BRep_Tool::Pnt(TopoDS::Vertex(aShape2)); if (std::abs(P1.X() - P2.X()) < Precision::Confusion() || std::abs(P1.Y() - P2.Y()) < Precision::Confusion() || std::abs(P1.Z() - P2.Z()) < Precision::Confusion() ) { StdFail_NotDone::Raise("Box can not be created, the points belong both to one of the OXY, OYZ or OZX planes"); return 0; } BRepPrimAPI_MakeBox MB (P1,P2); MB.Build(); if (!MB.IsDone()) { StdFail_NotDone::Raise("Box can not be computed from the given point"); } aShape = MB.Shape(); } } else { } if (aShape.IsNull()) return 0; aFunction->SetValue(aShape); log.SetTouched(Label()); return 1; }
//---------------------------------------------------------------- // Function: to update the core Surface // for any movement or Boolean operation of the body. // Author: Jane Hu //---------------------------------------------------------------- CubitStatus OCCSurface::update_OCC_entity( BRepBuilderAPI_Transform *aBRepTrsf, BRepAlgoAPI_BooleanOperation *op) { assert(aBRepTrsf != NULL || op != NULL); TopoDS_Shape shape; if (aBRepTrsf) shape = aBRepTrsf->ModifiedShape(*get_TopoDS_Face()); else { TopTools_ListOfShape shapes; shapes.Assign(op->Modified(*get_TopoDS_Face())); if(shapes.Extent() == 0) shapes.Assign(op->Generated(*get_TopoDS_Face())); if (shapes.Extent() == 1) shape = shapes.First(); else if(shapes.Extent() > 1) { //update all attributes first. TopTools_ListIteratorOfListOfShape it; it.Initialize(shapes); for(; it.More(); it.Next()) { shape = it.Value(); OCCQueryEngine::instance()->copy_attributes(*get_TopoDS_Face(), shape); } shape = shapes.First(); } else if(op->IsDeleted(*get_TopoDS_Face())) ; else return CUBIT_SUCCESS; } TopoDS_Face surface; if(!shape.IsNull()) surface = TopoDS::Face(shape); if (aBRepTrsf) { //set the loops DLIList<OCCLoop *> loops; this->get_loops(loops); for (int i = 1; i <= loops.size(); i++) { OCCLoop *loop = loops.get_and_step(); loop->update_OCC_entity(aBRepTrsf, op); } OCCQueryEngine::instance()->update_OCC_map(*myTopoDSFace, surface); } else if(op) update_OCC_entity(*myTopoDSFace, surface, op); return CUBIT_SUCCESS; }
void FaceMakerExtrusion::Build() { this->NotDone(); this->myGenerated.Clear(); this->myShapesToReturn.clear(); this->myShape = TopoDS_Shape(); TopoDS_Shape inputShape; if (mySourceShapes.empty()) throw Base::Exception("No input shapes!"); if (mySourceShapes.size() == 1){ inputShape = mySourceShapes[0]; } else { TopoDS_Builder builder; TopoDS_Compound cmp; builder.MakeCompound(cmp); for (const TopoDS_Shape& sh: mySourceShapes){ builder.Add(cmp, sh); } inputShape = cmp; } std::vector<TopoDS_Wire> wires; TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(inputShape, TopAbs_WIRE, mapOfWires); // if there are no wires then check also for edges if (mapOfWires.IsEmpty()) { TopTools_IndexedMapOfShape mapOfEdges; TopExp::MapShapes(inputShape, TopAbs_EDGE, mapOfEdges); for (int i=1; i<=mapOfEdges.Extent(); i++) { BRepBuilderAPI_MakeWire mkWire(TopoDS::Edge(mapOfEdges.FindKey(i))); wires.push_back(mkWire.Wire()); } } else { wires.reserve(mapOfWires.Extent()); for (int i=1; i<=mapOfWires.Extent(); i++) { wires.push_back(TopoDS::Wire(mapOfWires.FindKey(i))); } } if (!wires.empty()) { //try { TopoDS_Shape res = FaceMakerCheese::makeFace(wires); if (!res.IsNull()) this->myShape = res; //} //catch (...) { //} } this->Done(); }
//======================================================================= //function : GetPosition //purpose : //======================================================================= gp_Ax3 GEOMUtils::GetPosition (const TopoDS_Shape& theShape) { gp_Ax3 aResult; if (theShape.IsNull()) return aResult; // Axes aResult.Transform(theShape.Location().Transformation()); if (theShape.ShapeType() == TopAbs_FACE) { Handle(Geom_Surface) aGS = BRep_Tool::Surface(TopoDS::Face(theShape)); if (!aGS.IsNull() && aGS->IsKind(STANDARD_TYPE(Geom_Plane))) { Handle(Geom_Plane) aGPlane = Handle(Geom_Plane)::DownCast(aGS); gp_Pln aPln = aGPlane->Pln(); aResult = aPln.Position(); // In case of reverse orinetation of the face invert the plane normal // (the face's normal does not mathc the plane's normal in this case) if(theShape.Orientation() == TopAbs_REVERSED) { gp_Dir Vx = aResult.XDirection(); gp_Dir N = aResult.Direction().Mirrored(Vx); gp_Pnt P = aResult.Location(); aResult = gp_Ax3(P, N, Vx); } } } // Origin gp_Pnt aPnt; TopAbs_ShapeEnum aShType = theShape.ShapeType(); if (aShType == TopAbs_VERTEX) { aPnt = BRep_Tool::Pnt(TopoDS::Vertex(theShape)); } else { if (aShType == TopAbs_COMPOUND) { aShType = GetTypeOfSimplePart(theShape); } GProp_GProps aSystem; if (aShType == TopAbs_EDGE || aShType == TopAbs_WIRE) BRepGProp::LinearProperties(theShape, aSystem); else if (aShType == TopAbs_FACE || aShType == TopAbs_SHELL) BRepGProp::SurfaceProperties(theShape, aSystem); else BRepGProp::VolumeProperties(theShape, aSystem); aPnt = aSystem.CentreOfMass(); } aResult.SetLocation(aPnt); return aResult; }
bool IfcGeom::Kernel::convert(const IfcSchema::IfcExtrudedAreaSolid* l, TopoDS_Shape& shape) { TopoDS_Shape face; if ( !convert_face(l->SweptArea(),face) ) return false; const double height = l->Depth() * getValue(GV_LENGTH_UNIT); gp_Trsf trsf; IfcGeom::Kernel::convert(l->Position(),trsf); gp_Dir dir; convert(l->ExtrudedDirection(),dir); shape.Nullify(); if (face.ShapeType() == TopAbs_COMPOUND) { // For compounds (most likely the result of a IfcCompositeProfileDef) // create a compound solid shape. TopExp_Explorer exp(face, TopAbs_FACE); TopoDS_CompSolid compound; BRep_Builder builder; builder.MakeCompSolid(compound); int num_faces_extruded = 0; for (; exp.More(); exp.Next(), ++num_faces_extruded) { builder.Add(compound, BRepPrimAPI_MakePrism(exp.Current(), height*dir)); } if (num_faces_extruded) { shape = compound; } } if (shape.IsNull()) { shape = BRepPrimAPI_MakePrism(face, height*dir); } shape.Move(trsf); return ! shape.IsNull(); }
//======================================================================= //function : Execute //purpose : //======================================================================= Standard_Integer GEOMImpl_SphereDriver::Execute(TFunction_Logbook& log) const { if (Label().IsNull()) return 0; Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label()); GEOMImpl_ISphere aCI (aFunction); Standard_Integer aType = aFunction->GetType(); TopoDS_Shape aShape; char aMsg[] = "Sphere creation aborted: radius value less than 1e-07 is not acceptable"; double theAngle = aCI.GetAngle(); if (theAngle == 0.) theAngle = PI * 2.; double theVCoordStart = aCI.GetVCoordStart(); double theVCoordEnd = aCI.GetVCoordEnd(); if (aType == SPHERE_R) { double anR = aCI.GetR(); if (anR < Precision::Confusion()) Standard_ConstructionError::Raise(aMsg); //There seems to be an issue with the BRepPrimAPI_MakeSphere command concerning //the limitations on V coodinates of its parametric space ... (Will not be used for the moment) aShape = BRepPrimAPI_MakeSphere(anR /*, theVCoordStart, theVCoordEnd*/ , theAngle).Shape(); } else if (aType == SPHERE_PNT_R) { double anR = aCI.GetR(); if (anR < Precision::Confusion()) Standard_ConstructionError::Raise(aMsg); Handle(GEOM_Function) aRefPoint = aCI.GetPoint(); TopoDS_Shape aShapePnt = aRefPoint->GetValue(); if (aShapePnt.ShapeType() != TopAbs_VERTEX) Standard_ConstructionError::Raise("Invalid shape given for sphere center: it must be a point"); gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(aShapePnt)); aShape = BRepPrimAPI_MakeSphere(aP, anR/*, theVCoordStart, theVCoordEnd*/, theAngle).Shape(); } else { } if (aShape.IsNull()) return 0; aFunction->SetValue(aShape); log.SetTouched(Label()); return 1; }
//======================================================================= //function : Execute //purpose : //======================================================================= Standard_Integer GEOMImpl_TorusDriver::Execute(TFunction_Logbook& log) const { if (Label().IsNull()) return 0; Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label()); GEOMImpl_ITorus aCI (aFunction); Standard_Integer aType = aFunction->GetType(); TopoDS_Shape aShape; if (aType == TORUS_RR) { aShape = BRepPrimAPI_MakeTorus(aCI.GetRMajor(), aCI.GetRMinor()).Shape(); } else if (aType == TORUS_PNT_VEC_RR) { Handle(GEOM_Function) aRefPoint = aCI.GetCenter(); Handle(GEOM_Function) aRefVector = aCI.GetVector(); TopoDS_Shape aShapePnt = aRefPoint->GetValue(); TopoDS_Shape aShapeVec = aRefVector->GetValue(); if (aShapePnt.ShapeType() != TopAbs_VERTEX) { Standard_TypeMismatch::Raise("Torus Center must be a vertex"); } if (aShapeVec.ShapeType() != TopAbs_EDGE) { Standard_TypeMismatch::Raise("Torus Axis must be an edge"); } gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(aShapePnt)); TopoDS_Edge anE = TopoDS::Edge(aShapeVec); TopoDS_Vertex V1, V2; TopExp::Vertices(anE, V1, V2, Standard_True); if (V1.IsNull() || V2.IsNull()) { Standard_ConstructionError::Raise("Bad edge for the Torus Axis given"); } gp_Vec aV (BRep_Tool::Pnt(V1), BRep_Tool::Pnt(V2)); if (aV.Magnitude() < Precision::Confusion()) { Standard_ConstructionError::Raise ("End vertices of edge, defining the Torus Axis, are too close"); } gp_Ax2 anAxes (aP, aV); BRepPrimAPI_MakeTorus MT (anAxes, aCI.GetRMajor(), aCI.GetRMinor()); if (!MT.IsDone()) MT.Build(); if (!MT.IsDone()) StdFail_NotDone::Raise("Torus construction algorithm has failed"); aShape = MT.Shape(); } else { } if (aShape.IsNull()) return 0; aFunction->SetValue(aShape); log.SetTouched(Label()); return 1; }
TopoDS_Shape FaceMakerCheese::makeFace(const std::vector<TopoDS_Wire>& w) { if (w.empty()) return TopoDS_Shape(); //FIXME: Need a safe method to sort wire that the outermost one comes last // Currently it's done with the diagonal lengths of the bounding boxes std::vector<TopoDS_Wire> wires = w; std::sort(wires.begin(), wires.end(), Wire_Compare()); std::list<TopoDS_Wire> wire_list; wire_list.insert(wire_list.begin(), wires.rbegin(), wires.rend()); // separate the wires into several independent faces std::list< std::list<TopoDS_Wire> > sep_wire_list; while (!wire_list.empty()) { std::list<TopoDS_Wire> sep_list; TopoDS_Wire wire = wire_list.front(); wire_list.pop_front(); sep_list.push_back(wire); std::list<TopoDS_Wire>::iterator it = wire_list.begin(); while (it != wire_list.end()) { if (isInside(wire, *it)) { sep_list.push_back(*it); it = wire_list.erase(it); } else { ++it; } } sep_wire_list.push_back(sep_list); } if (sep_wire_list.size() == 1) { std::list<TopoDS_Wire>& wires = sep_wire_list.front(); return makeFace(wires); } else if (sep_wire_list.size() > 1) { TopoDS_Compound comp; BRep_Builder builder; builder.MakeCompound(comp); for (std::list< std::list<TopoDS_Wire> >::iterator it = sep_wire_list.begin(); it != sep_wire_list.end(); ++it) { TopoDS_Shape aFace = makeFace(*it); if (!aFace.IsNull()) builder.Add(comp, aFace); } return comp; } else { return TopoDS_Shape(); // error } }
TopoDS_Shape Feature::getSolid(const TopoDS_Shape& shape) { if (shape.IsNull()) Standard_Failure::Raise("Shape is null"); TopExp_Explorer xp; xp.Init(shape,TopAbs_SOLID); for (;xp.More(); xp.Next()) { return xp.Current(); } return TopoDS_Shape(); }