Salome HOME
Synchronize adm files
[modules/geom.git] / src / GEOMImpl / GEOMImpl_ProjectionDriver.cxx
1 // Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 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 GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include <Standard_Stream.hxx>
24
25 #include <GEOMImpl_ProjectionDriver.hxx>
26
27 #include <GEOMImpl_IMirror.hxx>
28 #include <GEOMImpl_IProjection.hxx>
29 #include <GEOMImpl_Types.hxx>
30 #include <GEOM_Function.hxx>
31
32 #include <BRep_Tool.hxx>
33 #include <BRepBuilderAPI_Transform.hxx>
34 #include <BRepBuilderAPI_MakeVertex.hxx>
35 #include <BRepClass_FaceClassifier.hxx>
36 #include <BRepExtrema_DistShapeShape.hxx>
37 #include <BRepOffsetAPI_NormalProjection.hxx>
38 #include <BRepTools.hxx>
39
40 #include <TopAbs.hxx>
41 #include <TopExp.hxx>
42 #include <TopoDS.hxx>
43 #include <TopoDS_Shape.hxx>
44 #include <TopoDS_Edge.hxx>
45 #include <TopoDS_Face.hxx>
46 #include <TopoDS_Vertex.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48
49 #include <GeomAPI_ProjectPointOnSurf.hxx>
50 #include <Geom_Curve.hxx>
51 #include <Geom_Plane.hxx>
52
53 #include <gp_Trsf.hxx>
54 #include <gp_Pnt.hxx>
55 #include <gp_Vec.hxx>
56
57 //=======================================================================
58 //function : GetID
59 //purpose  :
60 //======================================================================= 
61 const Standard_GUID& GEOMImpl_ProjectionDriver::GetID()
62 {
63   static Standard_GUID aProjectionDriver ("FF1BBB70-5D14-4df2-980B-3A668264EA16");
64   return aProjectionDriver; 
65 }
66
67
68 //=======================================================================
69 //function : GEOMImpl_ProjectionDriver
70 //purpose  : 
71 //=======================================================================
72
73 GEOMImpl_ProjectionDriver::GEOMImpl_ProjectionDriver() 
74 {
75 }
76
77 //=======================================================================
78 //function : Execute
79 //purpose  :
80 //======================================================================= 
81 Standard_Integer GEOMImpl_ProjectionDriver::Execute(TFunction_Logbook& log) const
82 {
83   if (Label().IsNull())  return 0;    
84   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
85
86   if (aFunction.IsNull()) return 0;
87
88   Standard_Integer aType = aFunction->GetType();
89
90   if (aType == PROJECTION_COPY) {
91     // Projection
92     TopoDS_Shape aShape;
93     gp_Trsf aTrsf;
94
95     GEOMImpl_IMirror TI (aFunction);
96
97     Handle(GEOM_Function) anOriginalFunction = TI.GetOriginal();
98     if (anOriginalFunction.IsNull()) return 0;
99
100     TopoDS_Shape anOriginal = anOriginalFunction->GetValue();
101     if (anOriginal.IsNull()) return 0;
102
103     // Source shape (point, edge or wire)
104     if (anOriginal.ShapeType() != TopAbs_VERTEX &&
105         anOriginal.ShapeType() != TopAbs_EDGE &&
106         anOriginal.ShapeType() != TopAbs_WIRE) {
107       Standard_ConstructionError::Raise
108         ("Projection aborted : the source shape is neither a vertex, nor an edge or a wire");
109     }
110
111     // Target face
112     Handle(GEOM_Function) aTargetFunction = TI.GetPlane();
113     if (aTargetFunction.IsNull()) return 0;
114     TopoDS_Shape aFaceShape = aTargetFunction->GetValue();
115     //if (aFaceShape.IsNull() || aFaceShape.ShapeType() != TopAbs_FACE) {
116     //  Standard_ConstructionError::Raise
117     //    ("Projection aborted : the target shape is not a face");
118     //}
119
120     Standard_Real tol = 1.e-4;        
121
122     if (anOriginal.ShapeType() == TopAbs_VERTEX) {
123       if (aFaceShape.IsNull() || aFaceShape.ShapeType() != TopAbs_FACE) {
124         Standard_ConstructionError::Raise
125           ("Projection aborted : the target shape is not a face");
126       }
127       TopoDS_Face aFace = TopoDS::Face(aFaceShape);
128       Handle(Geom_Surface) surface = BRep_Tool::Surface(aFace);
129       double U1, U2, V1, V2;
130       //surface->Bounds(U1, U2, V1, V2);
131       BRepTools::UVBounds(aFace, U1, U2, V1, V2);
132
133       // projector
134       GeomAPI_ProjectPointOnSurf proj;
135       proj.Init(surface, U1, U2, V1, V2, tol);
136
137       gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(anOriginal));
138       proj.Perform(aPnt);
139       if (!proj.IsDone()) {
140         Standard_ConstructionError::Raise
141           ("Projection aborted : the algorithm failed");
142       }
143       int nbPoints = proj.NbPoints();
144       if (nbPoints < 1) {
145         Standard_ConstructionError::Raise("No solution found");
146       }
147
148       Quantity_Parameter U, V;
149       proj.LowerDistanceParameters(U, V);
150       gp_Pnt2d aProjPnt (U, V);
151
152       // classifier
153       BRepClass_FaceClassifier aClsf (aFace, aProjPnt, tol);
154       if (aClsf.State() != TopAbs_IN && aClsf.State() != TopAbs_ON) {
155         bool isSol = false;
156         double minDist = RealLast();
157         for (int i = 1; i <= nbPoints; i++) {
158           Quantity_Parameter Ui, Vi;
159           proj.Parameters(i, Ui, Vi);
160           aProjPnt = gp_Pnt2d(Ui, Vi);
161           aClsf.Perform(aFace, aProjPnt, tol);
162           if (aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON) {
163             isSol = true;
164             double dist = proj.Distance(i);
165             if (dist < minDist) {
166               minDist = dist;
167               U = Ui;
168               V = Vi;
169             }
170           }
171         }
172         if (!isSol) {
173           Standard_ConstructionError::Raise("No solution found");
174         }
175       }
176
177       gp_Pnt surfPnt = surface->Value(U, V);
178
179       aShape = BRepBuilderAPI_MakeVertex(surfPnt).Shape();
180     }
181     else {
182       //see BRepTest_BasicCommands.cxx for example of BRepOffsetAPI_NormalProjection
183       BRepOffsetAPI_NormalProjection OrtProj (aFaceShape);
184       OrtProj.Add(anOriginal);
185
186       // Compute maximal tolerance of projection.
187       TopExp_Explorer anExp(anOriginal,TopAbs_VERTEX);
188       Standard_Real   aMaxTol = Precision::Confusion();
189
190       for(; anExp.More(); anExp.Next()) { 
191         const TopoDS_Vertex aVtx    = TopoDS::Vertex(anExp.Current());
192         const Standard_Real aCurTol = BRep_Tool::Tolerance(aVtx);
193
194         if (aMaxTol < aCurTol) {
195           aMaxTol = aCurTol;
196         }
197       }
198
199       Standard_Real tol2d = Pow(aMaxTol, 2./3);
200       GeomAbs_Shape Continuity = GeomAbs_C2;
201       Standard_Integer MaxDeg = 14;
202       Standard_Integer MaxSeg = 16;
203
204       OrtProj.SetParams(aMaxTol, tol2d, Continuity, MaxDeg, MaxSeg);
205
206       try {
207         OrtProj.Build();
208       } catch (Standard_Failure) {
209         Handle(Standard_Failure) aFail = Standard_Failure::Caught();
210         TCollection_AsciiString aMsg (aFail->GetMessageString());
211         if (!aMsg.Length())
212           aMsg = "Projection aborted : possibly the source shape intersects the cylinder's axis";
213         Standard_ConstructionError::Raise(aMsg.ToCString());
214       }
215       if (!OrtProj.IsDone()) {
216         Standard_ConstructionError::Raise
217           ("Projection aborted : BRepOffsetAPI_NormalProjection failed");
218       }
219
220       aShape = OrtProj.Shape();
221
222       // check that the result shape is an empty compound
223       // (IPAL22905: TC650: Projection on face dialog problems)
224       if( !aShape.IsNull() && aShape.ShapeType() == TopAbs_COMPOUND )
225       {
226         TopoDS_Iterator anIter( aShape );
227         if( !anIter.More() )
228           Standard_ConstructionError::Raise("Projection aborted : empty compound produced");
229       }
230     }
231
232     if (aShape.IsNull()) return 0;
233
234     aFunction->SetValue(aShape);
235     log.SetTouched(Label()); 
236   } else if (aType == PROJECTION_ON_WIRE) {
237     // Perform projection of point on a wire or an edge.
238     GEOMImpl_IProjection aProj (aFunction);
239     Handle(GEOM_Function) aPointFunction = aProj.GetPoint();
240     Handle(GEOM_Function) aShapeFunction = aProj.GetShape();
241
242     if (aPointFunction.IsNull() || aShapeFunction.IsNull()) {
243       return 0;
244     }
245
246     TopoDS_Shape aPoint = aPointFunction->GetValue();
247     TopoDS_Shape aShape = aShapeFunction->GetValue();
248
249     if (aPoint.IsNull() || aShape.IsNull()) {
250       return 0;
251     }
252
253     // Check shape types.
254     if (aPoint.ShapeType() != TopAbs_VERTEX) {
255       Standard_ConstructionError::Raise
256         ("Projection aborted : the point is not a vertex");
257     }
258
259     if (aShape.ShapeType() != TopAbs_EDGE &&
260         aShape.ShapeType() != TopAbs_WIRE) {
261       Standard_ConstructionError::Raise
262         ("Projection aborted : the shape is neither an edge nor a wire");
263     }
264
265     // Perform projection.
266     BRepExtrema_DistShapeShape aDistShSh(aPoint, aShape, Extrema_ExtFlag_MIN);
267
268     if (aDistShSh.IsDone() == Standard_False) {
269       Standard_ConstructionError::Raise("Projection not done");
270     }
271
272     Standard_Boolean hasValidSolution = Standard_False;
273     Standard_Integer aNbSolutions     = aDistShSh.NbSolution();
274     Standard_Integer i;
275     double           aParam   = 0.;
276     Standard_Real    aTolConf = BRep_Tool::Tolerance(TopoDS::Vertex(aPoint));
277     Standard_Real    aTolAng  = 1.e-4;        
278
279     for (i = 1; i <= aNbSolutions; i++) {
280       Standard_Boolean        isValid       = Standard_False;
281       BRepExtrema_SupportType aSupportType  = aDistShSh.SupportTypeShape2(i);
282       TopoDS_Shape            aSupportShape = aDistShSh.SupportOnShape2(i);
283
284       if (aSupportType == BRepExtrema_IsOnEdge) {
285         // Minimal distance inside edge is really a projection.
286         isValid = Standard_True;
287         aDistShSh.ParOnEdgeS2(i, aParam);
288       } else if (aSupportType == BRepExtrema_IsVertex) {
289         TopExp_Explorer anExp(aShape, TopAbs_EDGE);
290
291         if (aDistShSh.Value() <= aTolConf) {
292           // The point lies on the shape. This means this point
293           // is really a projection.
294           for (; anExp.More() && !isValid; anExp.Next()) {
295             TopoDS_Edge aCurEdge = TopoDS::Edge(anExp.Current());
296
297             if (aCurEdge.IsNull() == Standard_False) {
298               TopoDS_Vertex aVtx[2];
299                         
300               TopExp::Vertices(aCurEdge, aVtx[0], aVtx[1]);
301
302               for (int j = 0; j < 2; j++) {
303                 if (aSupportShape.IsSame(aVtx[j])) {
304                   // The current edge is a projection edge.
305                   isValid       = Standard_True;
306                   aSupportShape = aCurEdge;
307                   aParam        = BRep_Tool::Parameter(aVtx[j], aCurEdge);
308                   break;
309                 }
310               }
311             }
312           }
313         } else {
314           // Minimal distance to vertex is not always a real projection.
315           gp_Pnt aPnt    = BRep_Tool::Pnt(TopoDS::Vertex(aPoint));
316           gp_Pnt aPrjPnt = BRep_Tool::Pnt(TopoDS::Vertex(aSupportShape));
317           gp_Vec aDProjP(aPrjPnt, aPnt);
318
319           for (; anExp.More() && !isValid; anExp.Next()) {
320             TopoDS_Edge aCurEdge = TopoDS::Edge(anExp.Current());
321  
322             if (aCurEdge.IsNull() == Standard_False) {
323               TopoDS_Vertex aVtx[2];
324                           
325               TopExp::Vertices(aCurEdge, aVtx[0], aVtx[1]);
326  
327               for (int j = 0; j < 2; j++) {
328                 if (aSupportShape.IsSame(aVtx[j])) {
329                   // Check if the point is a projection to the current edge.
330                   Standard_Real      anEdgePars[2];
331                   Handle(Geom_Curve) aCurve =
332                     BRep_Tool::Curve(aCurEdge, anEdgePars[0], anEdgePars[1]);
333                   gp_Pnt             aVal;
334                   gp_Vec             aD1;
335
336                   aParam = BRep_Tool::Parameter(aVtx[j], aCurEdge);
337                   aCurve->D1(aParam, aVal, aD1);
338
339                   if (Abs(aD1.Dot(aDProjP)) <= aTolAng) {
340                     // The current edge is a projection edge.
341                     isValid       = Standard_True;
342                     aSupportShape = aCurEdge;
343                     break;
344                   }
345                 }
346               }
347             }
348           }
349         }
350       }
351       
352
353       if (isValid) {
354         if (hasValidSolution) {
355           Standard_ConstructionError::Raise
356             ("Projection aborted : multiple solutions");
357         }
358
359         // Store the valid solution.
360         hasValidSolution = Standard_True;
361
362         // Normalize parameter.
363         TopoDS_Edge aSupportEdge = TopoDS::Edge(aSupportShape);
364         Standard_Real aF, aL;
365
366         BRep_Tool::Range(aSupportEdge, aF, aL);
367
368         if (Abs(aL - aF) <= aTolConf) {
369           Standard_ConstructionError::Raise
370             ("Projection aborted : degenerated projection edge");
371         }
372
373         aParam = (aParam - aF)/(aL - aF);
374         aProj.SetU(aParam);
375
376         // Compute edge index.
377         TopExp_Explorer anExp(aShape, TopAbs_EDGE);
378         int anIndex = 0;
379
380         for (; anExp.More(); anExp.Next(), anIndex++) {
381           if (aSupportShape.IsSame(anExp.Current())) {
382             aProj.SetIndex(anIndex);
383             break;
384           }
385         }
386
387         if (!anExp.More()) {
388           Standard_ConstructionError::Raise
389             ("Projection aborted : Can't define edge index");
390         }
391
392         // Construct a projection vertex.
393         const gp_Pnt &aPntProj = aDistShSh.PointOnShape2(i);
394         TopoDS_Shape  aProj    = BRepBuilderAPI_MakeVertex(aPntProj).Shape();
395         
396         aFunction->SetValue(aProj);
397       }
398     }
399
400     if (!hasValidSolution) {
401       Standard_ConstructionError::Raise("Projection aborted : no projection");
402     }
403   }
404
405   return 1;
406 }
407
408 //================================================================================
409 /*!
410  * \brief Returns a name of creation operation and names and values of creation parameters
411  */
412 //================================================================================
413
414 bool GEOMImpl_ProjectionDriver::
415 GetCreationInformation(std::string&             theOperationName,
416                        std::vector<GEOM_Param>& theParams)
417 {
418   if (Label().IsNull()) return 0;
419   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
420
421   Standard_Integer aType = function->GetType();
422
423   theOperationName = "PROJECTION";
424
425   switch ( aType ) {
426   case PROJECTION_COPY:
427     {
428       GEOMImpl_IMirror aCI( function );
429
430       AddParam( theParams, "Source object", aCI.GetOriginal() );
431       AddParam( theParams, "Target face", aCI.GetPlane() );
432       break;
433     }
434   case PROJECTION_ON_WIRE:
435     {
436       GEOMImpl_IProjection aProj (function);
437
438       AddParam(theParams, "Point", aProj.GetPoint());
439       AddParam(theParams, "Shape", aProj.GetShape());
440
441       break;
442     }
443   default:
444     return false;
445   }
446   
447   return true;
448 }
449
450 IMPLEMENT_STANDARD_HANDLE (GEOMImpl_ProjectionDriver,GEOM_BaseDriver);
451 IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_ProjectionDriver,GEOM_BaseDriver);