FreeCAD

Форк
0
/
FeatureExtrusion.cpp 
472 строки · 17.3 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2008 Werner Mayer <wmayer[at]users.sourceforge.net>     *
3
 *                                                                         *
4
 *   This file is part of the FreeCAD CAx development system.              *
5
 *                                                                         *
6
 *   This library is free software; you can redistribute it and/or         *
7
 *   modify it under the terms of the GNU Library General Public           *
8
 *   License as published by the Free Software Foundation; either          *
9
 *   version 2 of the License, or (at your option) any later version.      *
10
 *                                                                         *
11
 *   This library  is distributed in the hope that it will be useful,      *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU Library General Public License for more details.                  *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU Library General Public     *
17
 *   License along with this library; see the file COPYING.LIB. If not,    *
18
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
19
 *   Suite 330, Boston, MA  02111-1307, USA                                *
20
 *                                                                         *
21
 ***************************************************************************/
22

23
#include "PreCompiled.h"
24
#ifndef _PreComp_
25
# include <BRepAdaptor_Curve.hxx>
26
# include <BRepAdaptor_Surface.hxx>
27
# include <BRepBuilderAPI_Copy.hxx>
28
# include <BRepBuilderAPI_MakeWire.hxx>
29
# include <BRepLib_FindSurface.hxx>
30
# include <BRepPrimAPI_MakePrism.hxx>
31
# include <gp_Pln.hxx>
32
# include <gp_Trsf.hxx>
33
# include <Precision.hxx>
34
# include <TopExp.hxx>
35
# include <TopExp_Explorer.hxx>
36
# include <TopoDS.hxx>
37
# include <TopTools_IndexedMapOfShape.hxx>
38
#endif
39

40
#include <Base/Exception.h>
41

42
#include "FeatureExtrusion.h"
43
#include "ExtrusionHelper.h"
44
#include "Part2DObject.h"
45

46

47
using namespace Part;
48

49
PROPERTY_SOURCE(Part::Extrusion, Part::Feature)
50

51
const char* Extrusion::eDirModeStrings[] = {
52
    "Custom",
53
    "Edge",
54
    "Normal",
55
    nullptr };
56

57
namespace
58
{
59
    std::vector<std::string> MakerEnums = {"Simple",
60
                                           "Cheese",
61
                                           "Extrusion",
62
                                           "Bullseye"};
63

64
    const char* enumToClass(const char* mode)
65
    {
66
        if (MakerEnums.at(0) == mode) {
67
            return "Part::FaceMakerSimple";
68
        }
69
        if (MakerEnums.at(1) == mode) {
70
            return "Part::FaceMakerCheese";
71
        }
72
        if (MakerEnums.at(2) == mode) {
73
            return "Part::FaceMakerExtrusion";
74
        }
75
        if (MakerEnums.at(3) == mode) {
76
            return "Part::FaceMakerBullseye";
77
        }
78

79
        return "Part::FaceMakerBullseye";
80
    }
81

82
    const char* classToEnum(const char* type)
83
    {
84
        if (strcmp(type, "Part::FaceMakerSimple") == 0) {
85
            return MakerEnums.at(0).c_str();
86
        }
87
        if (strcmp(type, "Part::FaceMakerCheese") == 0) {
88
            return MakerEnums.at(1).c_str();
89
        }
90
        if (strcmp(type, "Part::FaceMakerExtrusion") == 0) {
91
            return MakerEnums.at(2).c_str();
92
        }
93
        if (strcmp(type, "Part::FaceMakerBullseye") == 0) {
94
            return MakerEnums.at(3).c_str();
95
        }
96

97
        return MakerEnums.at(3).c_str();
98
    }
99

100
    void restoreFaceMakerMode(Extrusion* self)
101
    {
102
        const char* mode = enumToClass(self->FaceMakerMode.getValueAsString());
103
        const char* type = self->FaceMakerClass.getValue();
104
        if (strcmp(mode, type) != 0) {
105
            self->FaceMakerMode.setValue(classToEnum(type));
106
        }
107
    }
108
}
109

110
Extrusion::Extrusion()
111
{
112
    // clang-format off
113
    ADD_PROPERTY_TYPE(Base, (nullptr), "Extrude", App::Prop_None,
114
                      "Shape to extrude");
115
    ADD_PROPERTY_TYPE(Dir, (Base::Vector3d(0.0, 0.0, 1.0)), "Extrude", App::Prop_None,
116
                      "Direction of extrusion (also magnitude, if both lengths are zero).");
117
    ADD_PROPERTY_TYPE(DirMode, (dmCustom), "Extrude", App::Prop_None,
118
                      "Sets, how Dir is updated.");
119
    DirMode.setEnums(eDirModeStrings);
120
    ADD_PROPERTY_TYPE(DirLink, (nullptr), "Extrude", App::Prop_None,
121
                      "Link to edge defining extrusion direction.");
122
    ADD_PROPERTY_TYPE(LengthFwd, (0.0), "Extrude", App::Prop_None,
123
                      "Length of extrusion along direction. If both LengthFwd and LengthRev are zero, magnitude of Dir is used.");
124
    ADD_PROPERTY_TYPE(LengthRev, (0.0), "Extrude", App::Prop_None,
125
                      "Length of additional extrusion, against direction.");
126
    ADD_PROPERTY_TYPE(Solid, (false), "Extrude", App::Prop_None,
127
                      "If true, extruding a wire yields a solid. If false, a shell.");
128
    ADD_PROPERTY_TYPE(Reversed, (false), "Extrude", App::Prop_None,
129
                      "Set to true to swap the direction of extrusion.");
130
    ADD_PROPERTY_TYPE(Symmetric, (false), "Extrude", App::Prop_None,
131
                      "If true, extrusion is done in both directions to a total of LengthFwd. LengthRev is ignored.");
132
    ADD_PROPERTY_TYPE(TaperAngle, (0.0), "Extrude", App::Prop_None,
133
                      "Sets the angle of slope (draft) to apply to the sides. The angle is for outward taper; negative value yields inward tapering.");
134
    ADD_PROPERTY_TYPE(TaperAngleRev, (0.0), "Extrude", App::Prop_None,
135
                      "Taper angle of reverse part of extrusion.");
136
    // Default for old documents. See setupObject for default for new extrusions.
137
    ADD_PROPERTY_TYPE(FaceMakerClass, ("Part::FaceMakerExtrusion"), "Extrude", (App::PropertyType)(App::Prop_ReadOnly | App::Prop_Hidden),
138
                      "If Solid is true, this sets the facemaker class to use when converting wires to faces. Otherwise, ignored.");
139
    ADD_PROPERTY_TYPE(FaceMakerMode, (3L), "Extrude", App::Prop_None,
140
                      "If Solid is true, this sets the facemaker class to use when converting wires to faces. Otherwise, ignored.");
141
    FaceMakerMode.setEnums(MakerEnums);
142
    // clang-format on
143
}
144

145
short Extrusion::mustExecute() const
146
{
147
    if (Base.isTouched() ||
148
        Dir.isTouched() ||
149
        DirMode.isTouched() ||
150
        DirLink.isTouched() ||
151
        LengthFwd.isTouched() ||
152
        LengthRev.isTouched() ||
153
        Solid.isTouched() ||
154
        Reversed.isTouched() ||
155
        Symmetric.isTouched() ||
156
        TaperAngle.isTouched() ||
157
        TaperAngleRev.isTouched() ||
158
        FaceMakerClass.isTouched())
159
        return 1;
160
    return 0;
161
}
162

163
bool Extrusion::fetchAxisLink(const App::PropertyLinkSub& axisLink, Base::Vector3d& basepoint, Base::Vector3d& dir)
164
{
165
    if (!axisLink.getValue())
166
        return false;
167

168
    auto linked = axisLink.getValue();
169

170
    TopoDS_Shape axEdge;
171
    if (!axisLink.getSubValues().empty() && axisLink.getSubValues()[0].length() > 0) {
172
        axEdge = Feature::getTopoShape(linked, axisLink.getSubValues()[0].c_str(), true /*need element*/).getShape();
173
    }
174
    else {
175
        axEdge = Feature::getShape(linked);
176
    }
177

178
    if (axEdge.IsNull())
179
        throw Base::ValueError("DirLink shape is null");
180
    if (axEdge.ShapeType() != TopAbs_EDGE)
181
        throw Base::TypeError("DirLink shape is not an edge");
182

183
    BRepAdaptor_Curve crv(TopoDS::Edge(axEdge));
184
    gp_Pnt startpoint;
185
    gp_Pnt endpoint;
186
    if (crv.GetType() == GeomAbs_Line) {
187
        startpoint = crv.Value(crv.FirstParameter());
188
        endpoint = crv.Value(crv.LastParameter());
189
        if (axEdge.Orientation() == TopAbs_REVERSED)
190
            std::swap(startpoint, endpoint);
191
    }
192
    else {
193
        throw Base::TypeError("DirLink edge is not a line.");
194
    }
195
    basepoint.Set(startpoint.X(), startpoint.Y(), startpoint.Z());
196
    gp_Vec vec = gp_Vec(startpoint, endpoint);
197
    dir.Set(vec.X(), vec.Y(), vec.Z());
198
    return true;
199
}
200

201
ExtrusionParameters Extrusion::computeFinalParameters()
202
{
203
    ExtrusionParameters result;
204
    Base::Vector3d dir;
205
    switch (this->DirMode.getValue()) {
206
    case dmCustom:
207
        dir = this->Dir.getValue();
208
        break;
209
    case dmEdge: {
210
        bool fetched;
211
        Base::Vector3d base;
212
        fetched = fetchAxisLink(this->DirLink, base, dir);
213
        if (!fetched)
214
            throw Base::ValueError("DirMode is set to use edge, but no edge is linked.");
215
        this->Dir.setValue(dir);
216
    } break;
217
    case dmNormal:
218
        dir = calculateShapeNormal(this->Base);
219
        this->Dir.setValue(dir);
220
        break;
221
    default:
222
        throw Base::ValueError("Unexpected enum value");
223
    }
224
    if (dir.Length() < Precision::Confusion())
225
        throw Base::ValueError("Direction is zero-length");
226
    result.dir = gp_Dir(dir.x, dir.y, dir.z);
227
    if (this->Reversed.getValue())
228
        result.dir.Reverse();
229

230
    result.lengthFwd = this->LengthFwd.getValue();
231
    result.lengthRev = this->LengthRev.getValue();
232
    if (fabs(result.lengthFwd) < Precision::Confusion()
233
        && fabs(result.lengthRev) < Precision::Confusion()) {
234
        result.lengthFwd = dir.Length();
235
    }
236

237
    if (this->Symmetric.getValue()) {
238
        result.lengthRev = result.lengthFwd * 0.5;
239
        result.lengthFwd = result.lengthFwd * 0.5;
240
    }
241

242
    if (fabs(result.lengthFwd + result.lengthRev) < Precision::Confusion())
243
        throw Base::ValueError("Total length of extrusion is zero.");
244

245
    result.solid = this->Solid.getValue();
246

247
    result.taperAngleFwd = this->TaperAngle.getValue() * M_PI / 180.0;
248
    if (fabs(result.taperAngleFwd) > M_PI * 0.5 - Precision::Angular())
249
        throw Base::ValueError("Magnitude of taper angle matches or exceeds 90 degrees. That is too much.");
250
    result.taperAngleRev = this->TaperAngleRev.getValue() * M_PI / 180.0;
251
    if (fabs(result.taperAngleRev) > M_PI * 0.5 - Precision::Angular())
252
        throw Base::ValueError("Magnitude of taper angle matches or exceeds 90 degrees. That is too much.");
253

254
    result.faceMakerClass = this->FaceMakerClass.getValue();
255

256
    return result;
257
}
258

259
Base::Vector3d Extrusion::calculateShapeNormal(const App::PropertyLink& shapeLink)
260
{
261
    App::DocumentObject* docobj = nullptr;
262
    Base::Matrix4D mat;
263
    TopoDS_Shape sh = Feature::getShape(shapeLink.getValue(), nullptr, false, &mat, &docobj);
264

265
    if (!docobj)
266
        throw Base::ValueError("calculateShapeNormal: link is empty");
267

268
    //special case for sketches and the like: no matter what shape they have, use their local Z axis.
269
    if (docobj->isDerivedFrom(Part::Part2DObject::getClassTypeId())) {
270
        Base::Vector3d OZ(0.0, 0.0, 1.0);
271
        Base::Vector3d result;
272
        Base::Rotation(mat).multVec(OZ, result);
273
        return result;
274
    }
275

276
    if (sh.IsNull())
277
        throw NullShapeException("calculateShapeNormal: link points to a valid object, but its shape is null.");
278

279
    //find plane
280
    BRepLib_FindSurface planeFinder(sh, -1, /*OnlyPlane=*/true);
281
    if (!planeFinder.Found())
282
        throw Base::ValueError("Can't find normal direction, because the shape is not on a plane.");
283

284
    //find plane normal and return result.
285
    GeomAdaptor_Surface surf(planeFinder.Surface());
286
    gp_Dir normal = surf.Plane().Axis().Direction();
287

288
    //now we know the plane. But if there are faces, the
289
    //plane normal direction is not dependent on face orientation (because findPlane only uses edges).
290
    //let's fix that.
291
    TopExp_Explorer ex(sh, TopAbs_FACE);
292
    if (ex.More()) {
293
        BRepAdaptor_Surface surf(TopoDS::Face(ex.Current()));
294
        normal = surf.Plane().Axis().Direction();
295
        if (ex.Current().Orientation() == TopAbs_REVERSED) {
296
            normal.Reverse();
297
        }
298
    }
299

300
    return Base::Vector3d(normal.X(), normal.Y(), normal.Z());
301
}
302

303
void Extrusion::extrudeShape(TopoShape &result, const TopoShape &source, const ExtrusionParameters& params)
304
{
305
    gp_Vec vec = gp_Vec(params.dir).Multiplied(params.lengthFwd + params.lengthRev);//total vector of extrusion
306

307
    // #0000910: Circles Extrude Only Surfaces, thus use BRepBuilderAPI_Copy
308
    TopoShape myShape(source.makeElementCopy());
309

310
    if (std::fabs(params.taperAngleFwd) >= Precision::Angular()
311
        || std::fabs(params.taperAngleRev) >= Precision::Angular()) {
312
        // Tapered extrusion!
313
#if defined(__GNUC__) && defined(FC_OS_LINUX)
314
        Base::SignalException se;
315
#endif
316
        std::vector<TopoShape> drafts;
317
        ExtrusionHelper::makeElementDraft(params, myShape, drafts, result.Hasher);
318
        if (drafts.empty()) {
319
            Standard_Failure::Raise("Drafting shape failed");
320
        }
321
        else {
322
            result.makeElementCompound(drafts,
323
                                       0,
324
                                       TopoShape::SingleShapeCompoundCreationPolicy::returnShape);
325
        }
326
    }
327
    else {
328
        // Regular (non-tapered) extrusion!
329
        if (source.isNull()) {
330
            Standard_Failure::Raise("Cannot extrude empty shape");
331
        }
332

333
        // apply reverse part of extrusion by shifting the source shape
334
        if (fabs(params.lengthRev) > Precision::Confusion()) {
335
            gp_Trsf mov;
336
            mov.SetTranslation(gp_Vec(params.dir) * (-params.lengthRev));
337
            myShape = myShape.makeElementTransform(mov);
338
        }
339

340
        // make faces from wires
341
        if (params.solid) {
342
            // test if we need to make faces from wires. If there are faces - we don't.
343
            if (!myShape.hasSubShape(TopAbs_FACE)) {
344
                if (!myShape.Hasher) {
345
                    myShape.Hasher = result.Hasher;
346
                }
347
                myShape = myShape.makeElementFace(nullptr, params.faceMakerClass.c_str());
348
            }
349
        }
350

351
        // extrude!
352
        result.makeElementPrism(myShape, vec);
353
    }
354
}
355

356
App::DocumentObjectExecReturn* Extrusion::execute()
357
{
358
    App::DocumentObject* link = Base.getValue();
359
    if (!link) {
360
        return new App::DocumentObjectExecReturn("No object linked");
361
    }
362

363
    try {
364
        ExtrusionParameters params = computeFinalParameters();
365
        TopoShape result(0);
366
        extrudeShape(result, Feature::getTopoShape(link), params);
367
        this->Shape.setValue(result);
368
        return App::DocumentObject::StdReturn;
369
    }
370
    catch (Standard_Failure& e) {
371
        return new App::DocumentObjectExecReturn(e.GetMessageString());
372
    }
373
}
374

375
//----------------------------------------------------------------
376

377
TYPESYSTEM_SOURCE(Part::FaceMakerExtrusion, Part::FaceMakerCheese)
378

379
std::string FaceMakerExtrusion::getUserFriendlyName() const
380
{
381
    return {tr("Part Extrude facemaker").toStdString()};
382
}
383

384
std::string FaceMakerExtrusion::getBriefExplanation() const
385
{
386
    return {tr("Supports making faces with holes, does not support nesting.").toStdString()};
387
}
388

389
#if OCC_VERSION_HEX >= 0x070600
390
void FaceMakerExtrusion::Build(const Message_ProgressRange&)
391
#else
392
void FaceMakerExtrusion::Build()
393
#endif
394
{
395
    this->NotDone();
396
    this->myGenerated.Clear();
397
    this->myShapesToReturn.clear();
398
    this->myShape = TopoDS_Shape();
399
    TopoDS_Shape inputShape;
400
    if (mySourceShapes.empty())
401
        throw Base::ValueError("No input shapes!");
402
    if (mySourceShapes.size() == 1) {
403
        inputShape = mySourceShapes[0].getShape();
404
    }
405
    else {
406
        TopoDS_Builder builder;
407
        TopoDS_Compound cmp;
408
        builder.MakeCompound(cmp);
409
        for (const auto &sh : mySourceShapes) {
410
            builder.Add(cmp, sh.getShape());
411
        }
412
        inputShape = cmp;
413
    }
414

415
    std::vector<TopoDS_Wire> wires;
416
    TopTools_IndexedMapOfShape mapOfWires;
417
    TopExp::MapShapes(inputShape, TopAbs_WIRE, mapOfWires);
418

419
    // if there are no wires then check also for edges
420
    if (mapOfWires.IsEmpty()) {
421
        TopTools_IndexedMapOfShape mapOfEdges;
422
        TopExp::MapShapes(inputShape, TopAbs_EDGE, mapOfEdges);
423
        for (int i = 1; i <= mapOfEdges.Extent(); i++) {
424
            BRepBuilderAPI_MakeWire mkWire(TopoDS::Edge(mapOfEdges.FindKey(i)));
425
            wires.push_back(mkWire.Wire());
426
        }
427
    }
428
    else {
429
        wires.reserve(mapOfWires.Extent());
430
        for (int i = 1; i <= mapOfWires.Extent(); i++) {
431
            wires.push_back(TopoDS::Wire(mapOfWires.FindKey(i)));
432
        }
433
    }
434

435
    if (!wires.empty()) {
436
        //try {
437
        TopoDS_Shape res = FaceMakerCheese::makeFace(wires);
438
        if (!res.IsNull())
439
            this->myShape = res;
440
        //}
441
        //catch (...) {
442

443
        //}
444
    }
445

446
    this->Done();
447

448
}
449

450
void Part::Extrusion::setupObject()
451
{
452
    Part::Feature::setupObject();
453
     //default for newly created features
454
    this->FaceMakerMode.setValue(MakerEnums.at(3).c_str());
455
    this->FaceMakerClass.setValue("Part::FaceMakerBullseye");
456
}
457

458
void Extrusion::onDocumentRestored()
459
{
460
    restoreFaceMakerMode(this);
461
}
462

463
void Part::Extrusion::onChanged(const App::Property* prop)
464
{
465
    if (prop == &FaceMakerMode) {
466
        if (!isRestoring()) {
467
            FaceMakerClass.setValue(enumToClass(FaceMakerMode.getValueAsString()));
468
        }
469
    }
470

471
    Part::Feature::onChanged(prop);
472
}
473

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.