b2e1decd968c9302ffc5afb01439f82a563a6061
[occt.git] / src / StdPrs / StdPrs_ShadedShape.cxx
1 // Created on: 1993-09-23
2 // Created by: Jean-Louis FRENKEL
3 // Copyright (c) 1993-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 #include <StdPrs_ShadedShape.hxx>
18
19 #include <Bnd_Box.hxx>
20 #include <BRep_Builder.hxx>
21 #include <BRepBndLib.hxx>
22 #include <BRepMesh_DiscretFactory.hxx>
23 #include <BRepMesh_DiscretRoot.hxx>
24 #include <BRepTools.hxx>
25 #include <Graphic3d_ArrayOfSegments.hxx>
26 #include <Graphic3d_ArrayOfTriangles.hxx>
27 #include <Graphic3d_AspectFillArea3d.hxx>
28 #include <Graphic3d_Group.hxx>
29 #include <gp_Dir.hxx>
30 #include <gp_Vec.hxx>
31 #include <gp_Pnt.hxx>
32 #include <NCollection_List.hxx>
33 #include <Precision.hxx>
34 #include <Prs3d.hxx>
35 #include <Prs3d_Drawer.hxx>
36 #include <Prs3d_LineAspect.hxx>
37 #include <Prs3d_Presentation.hxx>
38 #include <Prs3d_ShadingAspect.hxx>
39 #include <Poly_Connect.hxx>
40 #include <Poly_PolygonOnTriangulation.hxx>
41 #include <Poly_Triangulation.hxx>
42 #include <StdPrs_ToolShadedShape.hxx>
43 #include <StdPrs_WFShape.hxx>
44 #include <TopExp.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopoDS.hxx>
47 #include <TopoDS_Compound.hxx>
48 #include <TopoDS_Face.hxx>
49 #include <TopoDS_Shape.hxx>
50 #include <TColgp_Array1OfDir.hxx>
51 #include <TColgp_Array1OfPnt2d.hxx>
52 #include <TColgp_HArray1OfPnt.hxx>
53 #include <TopTools_ListOfShape.hxx>
54 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
55
56 namespace
57 {
58
59   //! Computes wireframe presentation for free wires and vertices
60   void wireframeFromShape (const Handle (Prs3d_Presentation)& thePrs,
61                            const TopoDS_Shape&                theShape,
62                            const Handle (Prs3d_Drawer)&       theDrawer)
63   {
64     Standard_Boolean aDrawAllVerticesFlag = (theDrawer->VertexDrawMode() == Prs3d_VDM_All);
65
66     if (!aDrawAllVerticesFlag && theShape.ShapeType() != TopAbs_COMPOUND)
67     {
68       return;
69     }
70
71     TopExp_Explorer aShapeIter (theShape, TopAbs_FACE);
72     if (!aShapeIter.More())
73     {
74       // compound contains no shaded elements at all
75       StdPrs_WFShape::Add (thePrs, theShape, theDrawer);
76       return;
77     }
78
79     // We have to create a compound and collect all subshapes not drawn by the shading algo.
80     // This includes:
81     // - isolated edges
82     // - isolated vertices, if aDrawAllVerticesFlag == Standard_False
83     // - all shape's vertices, if aDrawAllVerticesFlag == Standard_True
84     TopoDS_Compound aCompoundWF;
85     BRep_Builder aBuilder;
86     aBuilder.MakeCompound (aCompoundWF);
87     Standard_Boolean hasElement = Standard_False;
88
89     // isolated edges
90     for (aShapeIter.Init (theShape, TopAbs_EDGE, TopAbs_FACE); aShapeIter.More(); aShapeIter.Next())
91     {
92       hasElement = Standard_True;
93       aBuilder.Add (aCompoundWF, aShapeIter.Current());
94     }
95     // isolated or all vertices
96     aShapeIter.Init (theShape, TopAbs_VERTEX, aDrawAllVerticesFlag ? TopAbs_SHAPE : TopAbs_EDGE);
97     for (; aShapeIter.More(); aShapeIter.Next())
98     {
99       hasElement = Standard_True;
100       aBuilder.Add (aCompoundWF, aShapeIter.Current());
101     }
102     if (hasElement)
103     {
104       StdPrs_WFShape::Add (thePrs, aCompoundWF, theDrawer);
105     }
106   }
107
108   //! Gets triangulation of every face of shape and fills output array of triangles
109   static Handle(Graphic3d_ArrayOfTriangles) fillTriangles (const TopoDS_Shape&    theShape,
110                                                            const Standard_Boolean theHasTexels,
111                                                            const gp_Pnt2d&        theUVOrigin,
112                                                            const gp_Pnt2d&        theUVRepeat,
113                                                            const gp_Pnt2d&        theUVScale)
114   {
115     Handle(Poly_Triangulation) aT;
116     TopLoc_Location aLoc;
117     gp_Pnt aPoint;
118     Standard_Integer aNbTriangles = 0;
119     Standard_Integer aNbVertices  = 0;
120
121     // Precision for compare square distances
122     const Standard_Real aPreci = Precision::SquareConfusion();
123
124     TopExp_Explorer aFaceIt(theShape, TopAbs_FACE);
125     for (; aFaceIt.More(); aFaceIt.Next())
126     {
127       const TopoDS_Face& aFace = TopoDS::Face(aFaceIt.Current());
128       aT = StdPrs_ToolShadedShape::Triangulation (aFace, aLoc);
129       if (!aT.IsNull())
130       {
131         aNbTriangles += aT->NbTriangles();
132         aNbVertices  += aT->NbNodes();
133       }
134     }
135     if (aNbVertices  <  3 || aNbTriangles <= 0)
136     {
137       return Handle(Graphic3d_ArrayOfTriangles)();
138     }
139
140     Handle(Graphic3d_ArrayOfTriangles) anArray = new Graphic3d_ArrayOfTriangles (aNbVertices, 3 * aNbTriangles,
141                                                                                  Standard_True, Standard_False, theHasTexels);
142     Standard_Real aUmin (0.0), aUmax (0.0), aVmin (0.0), aVmax (0.0), dUmax (0.0), dVmax (0.0);
143     for (aFaceIt.Init (theShape, TopAbs_FACE); aFaceIt.More(); aFaceIt.Next())
144     {
145       const TopoDS_Face& aFace = TopoDS::Face(aFaceIt.Current());
146       aT = StdPrs_ToolShadedShape::Triangulation (aFace, aLoc);
147       if (aT.IsNull())
148       {
149         continue;
150       }
151       const gp_Trsf& aTrsf = aLoc.Transformation();
152       Poly_Connect aPolyConnect (aT);
153       // Extracts vertices & normals from nodes
154       const TColgp_Array1OfPnt&   aNodes   = aT->Nodes();
155       const TColgp_Array1OfPnt2d& aUVNodes = aT->UVNodes();
156       TColgp_Array1OfDir aNormals (aNodes.Lower(), aNodes.Upper());
157       StdPrs_ToolShadedShape::Normal (aFace, aPolyConnect, aNormals);
158
159       if (theHasTexels)
160       {
161         BRepTools::UVBounds (aFace, aUmin, aUmax, aVmin, aVmax);
162         dUmax = (aUmax - aUmin);
163         dVmax = (aVmax - aVmin);
164       }
165
166       const Standard_Integer aDecal = anArray->VertexNumber();
167       for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter)
168       {
169         aPoint = aNodes (aNodeIter);
170         if (!aLoc.IsIdentity())
171         {
172           aPoint.Transform (aTrsf);
173           aNormals (aNodeIter).Transform (aTrsf);
174         }
175
176         if (theHasTexels && aUVNodes.Upper() == aNodes.Upper())
177         {
178           const gp_Pnt2d aTexel = gp_Pnt2d ((-theUVOrigin.X() + (theUVRepeat.X() * (aUVNodes (aNodeIter).X() - aUmin)) / dUmax) / theUVScale.X(),
179                                             (-theUVOrigin.Y() + (theUVRepeat.Y() * (aUVNodes (aNodeIter).Y() - aVmin)) / dVmax) / theUVScale.Y());
180           anArray->AddVertex (aPoint, aNormals (aNodeIter), aTexel);
181         }
182         else
183         {
184           anArray->AddVertex (aPoint, aNormals (aNodeIter));
185         }
186       }
187
188       // Fill array with vertex and edge visibility info
189       const Poly_Array1OfTriangle& aTriangles = aT->Triangles();
190       Standard_Integer anIndex[3];
191       for (Standard_Integer aTriIter = 1; aTriIter <= aT->NbTriangles(); ++aTriIter)
192       {
193         if (aFace.Orientation() == TopAbs_REVERSED)
194         {
195           aTriangles (aTriIter).Get (anIndex[0], anIndex[2], anIndex[1]);
196         }
197         else
198         {
199           aTriangles (aTriIter).Get (anIndex[0], anIndex[1], anIndex[2]);
200         }
201
202         gp_Pnt aP1 = aNodes (anIndex[0]);
203         gp_Pnt aP2 = aNodes (anIndex[1]);
204         gp_Pnt aP3 = aNodes (anIndex[2]);
205
206         gp_Vec aV1 (aP1, aP2);
207         if (aV1.SquareMagnitude() <= aPreci)
208         {
209           continue;
210         }
211         gp_Vec aV2 (aP2, aP3);
212         if (aV2.SquareMagnitude() <= aPreci)
213         {
214           continue;
215         }
216         gp_Vec aV3 (aP3, aP1);
217         if (aV3.SquareMagnitude() <= aPreci)
218         {
219           continue;
220         }
221         aV1.Normalize();
222         aV2.Normalize();
223         aV1.Cross (aV2);
224         if (aV1.SquareMagnitude() > aPreci)
225         {
226           anArray->AddEdge (anIndex[0] + aDecal);
227           anArray->AddEdge (anIndex[1] + aDecal);
228           anArray->AddEdge (anIndex[2] + aDecal);
229         }
230       }
231     }
232     return anArray;
233   }
234
235   //! Searches closed and unclosed subshapes in shape structure
236   //! and puts them into two compounds for separate processing of closed and unclosed sub-shapes.
237   static void exploreSolids (const TopoDS_Shape& theShape,
238                              const BRep_Builder& theBuilder,
239                              TopoDS_Compound&    theCompoundForClosed,
240                              TopoDS_Compound&    theCompoundForOpened)
241   {
242     if (theShape.IsNull())
243     {
244       return;
245     }
246
247     switch (theShape.ShapeType())
248     {
249       case TopAbs_COMPOUND:
250       case TopAbs_COMPSOLID:
251       {
252         for (TopoDS_Iterator anIter (theShape); anIter.More(); anIter.Next())
253         {
254           exploreSolids (anIter.Value(), theBuilder, theCompoundForClosed, theCompoundForOpened);
255         }
256         return;
257       }
258       case TopAbs_SOLID:
259       {
260         theBuilder.Add (StdPrs_ToolShadedShape::IsClosed (theShape) ? theCompoundForClosed : theCompoundForOpened, theShape);
261         return;
262       }
263       case TopAbs_SHELL:
264       case TopAbs_FACE:
265       {
266         theBuilder.Add (theCompoundForOpened, theShape);
267         return;
268       }
269       case TopAbs_WIRE:
270       case TopAbs_EDGE:
271       case TopAbs_VERTEX:
272       case TopAbs_SHAPE:
273       default:
274         return;
275     }
276   }
277
278   //! Prepare shaded presentation for specified shape
279   static Standard_Boolean shadeFromShape (const TopoDS_Shape&               theShape,
280                                           const Handle(Prs3d_Presentation)& thePrs,
281                                           const Handle(Prs3d_Drawer)&       theDrawer,
282                                           const Standard_Boolean            theHasTexels,
283                                           const gp_Pnt2d&                   theUVOrigin,
284                                           const gp_Pnt2d&                   theUVRepeat,
285                                           const gp_Pnt2d&                   theUVScale,
286                                           const Standard_Boolean            theIsClosed)
287   {
288     Handle(Graphic3d_ArrayOfTriangles) aPArray = fillTriangles (theShape, theHasTexels, theUVOrigin, theUVRepeat, theUVScale);
289     if (aPArray.IsNull())
290     {
291       return Standard_False;
292     }
293
294     Handle(Graphic3d_Group) aGroup = Prs3d_Root::NewGroup (thePrs);
295     aGroup->SetClosed (theIsClosed);
296     if (!theDrawer->ShadingAspectGlobal())
297     {
298       Handle(Graphic3d_AspectFillArea3d) anAsp = theDrawer->ShadingAspect()->Aspect();
299       theIsClosed ? anAsp->SuppressBackFace() : anAsp->AllowBackFace();
300       aGroup->SetGroupPrimitivesAspect (anAsp);
301     }
302     aGroup->AddPrimitiveArray (aPArray);
303     return Standard_True;
304   }
305
306   //! Compute boundary presentation for faces of the shape.
307   static void computeFaceBoundaries (const TopoDS_Shape&               theShape,
308                                      const Handle(Prs3d_Presentation)& thePrs,
309                                      const Handle(Prs3d_Drawer)&       theDrawer)
310   {
311     // collection of all triangulation nodes on edges
312     // for computing boundaries presentation
313     NCollection_List<Handle(TColgp_HArray1OfPnt)> aNodeCollection;
314     Standard_Integer aNodeNumber = 0;
315
316     TopLoc_Location aTrsf;
317
318     // explore all boundary edges
319     TopTools_IndexedDataMapOfShapeListOfShape anEdgesMap;
320     TopExp::MapShapesAndAncestors (
321       theShape, TopAbs_EDGE, TopAbs_FACE, anEdgesMap);
322
323     Standard_Integer anEdgeIdx = 1;
324     for ( ; anEdgeIdx <= anEdgesMap.Extent (); anEdgeIdx++)
325     {
326       // reject free edges
327       const TopTools_ListOfShape& aFaceList = anEdgesMap.FindFromIndex (anEdgeIdx);
328       if (aFaceList.Extent() == 0)
329         continue;
330
331       // take one of the shared edges and get edge triangulation
332       const TopoDS_Face& aFace  = TopoDS::Face (aFaceList.First ());
333       const TopoDS_Edge& anEdge = TopoDS::Edge (anEdgesMap.FindKey (anEdgeIdx));
334
335       Handle(Poly_Triangulation) aTriangulation =
336         BRep_Tool::Triangulation (aFace, aTrsf);
337
338       if (aTriangulation.IsNull ())
339         continue;
340
341       Handle(Poly_PolygonOnTriangulation) anEdgePoly =
342         BRep_Tool::PolygonOnTriangulation (anEdge, aTriangulation, aTrsf);
343
344       if (anEdgePoly.IsNull ())
345         continue;
346
347       // get edge nodes indexes from face triangulation
348       const TColgp_Array1OfPnt& aTriNodes = aTriangulation->Nodes ();
349       const TColStd_Array1OfInteger& anEdgeNodes = anEdgePoly->Nodes ();
350
351       if (anEdgeNodes.Length () < 2)
352         continue;
353
354       // collect the edge nodes
355       Handle(TColgp_HArray1OfPnt) aCollected =
356         new TColgp_HArray1OfPnt (anEdgeNodes.Lower (), anEdgeNodes.Upper ());
357
358       Standard_Integer aNodeIdx = anEdgeNodes.Lower ();
359       for ( ; aNodeIdx <= anEdgeNodes.Upper (); aNodeIdx++)
360       {
361         // node index in face triangulation
362         Standard_Integer aTriIndex = anEdgeNodes.Value (aNodeIdx);
363
364         // get node and apply location transformation to the node
365         gp_Pnt aTriNode = aTriNodes.Value (aTriIndex);
366         if (!aTrsf.IsIdentity ())
367           aTriNode.Transform (aTrsf);
368
369         // add node to the boundary array
370         aCollected->SetValue (aNodeIdx, aTriNode);
371       }
372
373       aNodeNumber += anEdgeNodes.Length ();
374       aNodeCollection.Append (aCollected);
375     }
376
377     // check if it possible to continue building the presentation
378     if (aNodeNumber == 0)
379       return;
380
381     // allocate polyline array for presentation
382     Standard_Integer aSegmentEdgeNb = 
383       (aNodeNumber - aNodeCollection.Extent()) * 2;
384
385     Handle(Graphic3d_ArrayOfSegments) aSegments = 
386       new Graphic3d_ArrayOfSegments (aNodeNumber, aSegmentEdgeNb);
387
388     // build presentation for edge bondaries
389     NCollection_List<Handle(TColgp_HArray1OfPnt)>::Iterator 
390       aCollIt (aNodeCollection);
391
392     // the edge index is increased in each iteration step to
393     // avoid contiguous segments between different face edges.
394     for ( ; aCollIt.More(); aCollIt.Next () )
395     {
396       const Handle(TColgp_HArray1OfPnt)& aNodeArray = aCollIt.Value ();
397
398       Standard_Integer aNodeIdx = aNodeArray->Lower ();
399
400       // add first node (this node is not shared with previous segment).
401       // for each face edge, indices for sharing nodes 
402       // between segments begin from the first added node.
403       Standard_Integer aSegmentEdge = 
404         aSegments->AddVertex (aNodeArray->Value (aNodeIdx));
405
406       // add subsequent nodes and provide edge indexes for sharing
407       // the nodes between the sequential segments.
408       for ( aNodeIdx++; aNodeIdx <= aNodeArray->Upper (); aNodeIdx++ )
409       {
410         aSegments->AddVertex (aNodeArray->Value (aNodeIdx));
411         aSegments->AddEdge (  aSegmentEdge);
412         aSegments->AddEdge (++aSegmentEdge);
413       }
414     }
415
416     // set up aspect and add polyline data
417     Handle(Graphic3d_AspectLine3d) aBoundaryAspect = 
418       theDrawer->FaceBoundaryAspect ()->Aspect ();
419
420     Handle(Graphic3d_Group) aPrsGrp = Prs3d_Root::CurrentGroup (thePrs);
421     aPrsGrp->SetGroupPrimitivesAspect (aBoundaryAspect);
422     aPrsGrp->AddPrimitiveArray (aSegments);
423   }
424 };
425
426 // =======================================================================
427 // function : Add
428 // purpose  :
429 // =======================================================================
430 void StdPrs_ShadedShape::Add (const Handle(Prs3d_Presentation)& thePrs,
431                               const TopoDS_Shape&               theShape,
432                               const Handle(Prs3d_Drawer)&       theDrawer,
433                               const Standard_Boolean            theToExploreSolids)
434 {
435   gp_Pnt2d aDummy;
436   StdPrs_ShadedShape::Add (thePrs, theShape, theDrawer,
437                            Standard_False, aDummy, aDummy, aDummy, theToExploreSolids);
438 }
439
440 // =======================================================================
441 // function : Tessellate
442 // purpose  :
443 // =======================================================================
444 void StdPrs_ShadedShape::Tessellate (const TopoDS_Shape&          theShape,
445                                      const Handle (Prs3d_Drawer)& theDrawer)
446 {
447   // Check if it is possible to avoid unnecessary recomputation of shape triangulation
448   Standard_Real aDeflection = Prs3d::GetDeflection (theShape, theDrawer);
449   if (BRepTools::Triangulation (theShape, aDeflection))
450   {
451     return;
452   }
453
454   // retrieve meshing tool from Factory
455   BRepTools::Clean (theShape);
456   Handle(BRepMesh_DiscretRoot) aMeshAlgo = BRepMesh_DiscretFactory::Get().Discret (theShape,
457                                                                                    aDeflection,
458                                                                                    theDrawer->HLRAngle());
459   if (!aMeshAlgo.IsNull())
460   {
461     aMeshAlgo->Perform();
462   }
463 }
464
465 // =======================================================================
466 // function : Add
467 // purpose  :
468 // =======================================================================
469 void StdPrs_ShadedShape::Add (const Handle (Prs3d_Presentation)& thePrs,
470                               const TopoDS_Shape&                theShape,
471                               const Handle (Prs3d_Drawer)&       theDrawer,
472                               const Standard_Boolean             theHasTexels,
473                               const gp_Pnt2d&                    theUVOrigin,
474                               const gp_Pnt2d&                    theUVRepeat,
475                               const gp_Pnt2d&                    theUVScale,
476                               const Standard_Boolean             theToExploreSolids)
477 {
478   if (theShape.IsNull())
479   {
480     return;
481   }
482
483   // add wireframe presentation for isolated edges and vertices
484   wireframeFromShape (thePrs, theShape, theDrawer);
485
486   // IsClosed also verifies triangulation completeness - perform tessellation beforehand
487   Tessellate (theShape, theDrawer);
488   const Standard_Boolean isClosed = StdPrs_ToolShadedShape::IsClosed (theShape);
489   if ((theShape.ShapeType() == TopAbs_COMPOUND
490     || theShape.ShapeType() == TopAbs_COMPSOLID)
491    && !isClosed
492    &&  theToExploreSolids)
493   {
494     // collect two compounds: for opened and closed (solid) sub-shapes
495     TopoDS_Compound anOpened, aClosed;
496     BRep_Builder aBuilder;
497     aBuilder.MakeCompound (aClosed);
498     aBuilder.MakeCompound (anOpened);
499     exploreSolids (theShape, aBuilder, aClosed, anOpened);
500
501     TopoDS_Iterator aShapeIter (aClosed);
502     if (aShapeIter.More())
503     {
504       shadeFromShape (aClosed, thePrs, theDrawer,
505                       theHasTexels, theUVOrigin, theUVRepeat, theUVScale, Standard_True);
506     }
507
508     aShapeIter.Initialize (anOpened);
509     if (aShapeIter.More())
510     {
511       shadeFromShape (anOpened, thePrs, theDrawer,
512                       theHasTexels, theUVOrigin, theUVRepeat, theUVScale, Standard_False);
513     }
514   }
515   else
516   {
517     shadeFromShape (theShape, thePrs, theDrawer,
518                     theHasTexels, theUVOrigin, theUVRepeat, theUVScale, isClosed);
519   }
520
521   if (theDrawer->IsFaceBoundaryDraw())
522   {
523     computeFaceBoundaries (theShape, thePrs, theDrawer);
524   }
525 }