Salome HOME
Fix for a crash: Create sketch, circle, Radius constraint with 0 value.
[modules/shaper.git] / src / SketcherPrs / SketcherPrs_SymbolPrs.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        SketcherPrs_SymbolPrs.cpp
4 // Created:     12 March 2015
5 // Author:      Vitaly SMETANNIKOV
6
7 #include "SketcherPrs_SymbolPrs.h"
8 #include "SketcherPrs_Tools.h"
9 #include "SketcherPrs_PositionMgr.h"
10
11 #include <GeomAPI_Edge.h>
12 #include <GeomAPI_Vertex.h>
13 #include <GeomAPI_Curve.h>
14
15 #include <Events_Error.h>
16
17 #include <Graphic3d_ArrayOfSegments.hxx>
18 #include <Graphic3d_BndBox4f.hxx>
19
20 #include <SelectMgr_Selection.hxx>
21 #include <Select3D_SensitivePoint.hxx>
22 #include <TopLoc_Location.hxx>
23 #include <AIS_InteractiveContext.hxx>
24 #include <V3d_Viewer.hxx>
25 #include <Prs3d_Root.hxx>
26 #include <Geom_CartesianPoint.hxx>
27 #include <GeomAdaptor_Curve.hxx>
28 #include <StdPrs_DeflectionCurve.hxx>
29 #include <StdPrs_Point.hxx>
30 #include <StdPrs_Curve.hxx>
31
32 #include <OpenGl_Element.hxx>
33 #include <OpenGl_GraphicDriver.hxx>
34 #include <OpenGl_Context.hxx>
35 #include <OpenGl_View.hxx>
36 #include <OpenGl_PointSprite.hxx>
37 #include <OpenGl_VertexBuffer.hxx>
38 #include <OpenGl_ShaderManager.hxx>
39
40 #ifdef WIN32
41 # define FSEP "\\"
42 #else
43 # define FSEP "/"
44 #endif
45
46 /// Step between icons
47 static const double MyDist = 0.02;
48
49 /// Function to convert opengl data type
50 GLenum toGlDataType (const Graphic3d_TypeOfData theType, GLint& theNbComp)
51 {
52   switch (theType) {
53     case Graphic3d_TOD_USHORT:
54       theNbComp = 1;
55       return GL_UNSIGNED_SHORT;
56     case Graphic3d_TOD_UINT:
57       theNbComp = 1;
58       return GL_UNSIGNED_INT;
59     case Graphic3d_TOD_VEC2:
60       theNbComp = 2;
61       return GL_FLOAT;
62     case Graphic3d_TOD_VEC3:
63       theNbComp = 3;
64       return GL_FLOAT;
65     case Graphic3d_TOD_VEC4:
66       theNbComp = 4;
67       return GL_FLOAT;
68     case Graphic3d_TOD_VEC4UB:
69       theNbComp = 4;
70       return GL_UNSIGNED_BYTE;
71   }
72   theNbComp = 0;
73   return GL_NONE;
74 }
75
76
77 //*******************************************************************
78 //! Auxiliary class for Vertex buffer with interleaved attributes.
79 class SketcherPrs_VertexBuffer : public OpenGl_VertexBuffer
80 {
81
82 public:
83
84   //! Create uninitialized VBO..
85   SketcherPrs_VertexBuffer (const Graphic3d_Attribute* theAttribs,
86                         const Standard_Integer     theStride)
87   : Stride (theStride), NbAttributes(1)
88   {
89
90     memcpy (Attribs, theAttribs, sizeof(Graphic3d_Attribute) * NbAttributes);
91   }
92
93   //! Create uninitialized VBO.
94   SketcherPrs_VertexBuffer (const Graphic3d_Buffer& theAttribs)
95   : Stride (theAttribs.Stride), NbAttributes(1)
96   {
97     memcpy (Attribs, theAttribs.AttributesArray(), sizeof(Graphic3d_Attribute) * NbAttributes);
98   }
99
100   virtual bool HasColorAttribute() const
101   {
102     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
103       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
104       if (anAttrib.Id == Graphic3d_TOA_COLOR) {
105         return true;
106       }
107     }
108     return false;
109   }
110
111   virtual bool HasNormalAttribute() const
112   {
113     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
114       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
115       if (anAttrib.Id == Graphic3d_TOA_NORM) {
116         return true;
117       }
118     }
119     return false;
120   }
121
122   virtual void BindPositionAttribute (const Handle(OpenGl_Context)& theGlCtx) const
123   {
124     if (!OpenGl_VertexBuffer::IsValid()) {
125       return;
126     }
127
128     OpenGl_VertexBuffer::Bind (theGlCtx);
129     GLint aNbComp;
130     const GLubyte* anOffset = OpenGl_VertexBuffer::myOffset;
131     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
132       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
133       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
134       if (aDataType == GL_NONE) {
135         continue;
136       } else if (anAttrib.Id == Graphic3d_TOA_POS) {
137         OpenGl_VertexBuffer::bindAttribute (theGlCtx, Graphic3d_TOA_POS, aNbComp, aDataType, Stride, anOffset);
138         break;
139       }
140
141       anOffset += Graphic3d_Attribute::Stride (anAttrib.DataType);
142     }
143   }
144
145   virtual void BindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
146   {
147     if (!OpenGl_VertexBuffer::IsValid())
148       return;
149
150     OpenGl_VertexBuffer::Bind (theGlCtx);
151     GLint aNbComp;
152     const GLubyte* anOffset = OpenGl_VertexBuffer::myOffset;
153     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
154     {
155       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
156       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
157       if (aDataType == GL_NONE)
158         continue;
159
160       OpenGl_VertexBuffer::bindAttribute (theGlCtx, anAttrib.Id, aNbComp, aDataType, Stride, anOffset);
161       anOffset += Graphic3d_Attribute::Stride (anAttrib.DataType);
162     }
163   }
164
165   virtual void UnbindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
166   {
167     if (!OpenGl_VertexBuffer::IsValid())
168       return;
169     OpenGl_VertexBuffer::Unbind (theGlCtx);
170
171     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter) {
172       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
173       OpenGl_VertexBuffer::unbindAttribute (theGlCtx, anAttrib.Id);
174     }
175   }
176
177 public:
178
179   Graphic3d_Attribute Attribs[1];
180   Standard_Integer    Stride;
181   Standard_Integer NbAttributes;
182 };
183
184 //**************************************************************
185 //! Redefinition of OpenGl_Element
186 class SketcherPrs_Element: public OpenGl_Element
187 {
188 public:
189   SketcherPrs_Element(const Handle(SketcherPrs_SymbolPrs)& theObj) : 
190   OpenGl_Element(), myObj(theObj) {}
191
192   virtual void Render (const Handle(OpenGl_Workspace)& theWorkspace) const
193   {
194     if (!myObj.IsNull())
195       myObj->Render(theWorkspace);
196   }
197
198   virtual void Release (OpenGl_Context* theContext) 
199   {
200     if (!myObj.IsNull())
201       myObj->Release(theContext);
202   }
203
204 private:
205   Handle(SketcherPrs_SymbolPrs) myObj;
206 };
207
208
209 //**************************************************************
210 //! Definition of call back
211 OpenGl_Element* SymbolPrsCallBack(const CALL_DEF_USERDRAW * theUserDraw)
212 {
213   Handle(SketcherPrs_SymbolPrs) anIObj = (SketcherPrs_SymbolPrs*)theUserDraw->Data;
214   if (anIObj.IsNull()) {
215     std::cout << "VUserDrawCallback error: null object passed, the custom scene element will not be rendered" << std::endl;
216   }
217   return new SketcherPrs_Element(anIObj);
218 }
219
220
221 //*****************************************************************************
222 IMPLEMENT_STANDARD_HANDLE(SketcherPrs_SymbolPrs, AIS_InteractiveObject);
223 IMPLEMENT_STANDARD_RTTIEXT(SketcherPrs_SymbolPrs, AIS_InteractiveObject);
224
225
226 std::map<const char*, Handle(Image_AlienPixMap)> SketcherPrs_SymbolPrs::myIconsMap;
227
228
229 SketcherPrs_SymbolPrs::SketcherPrs_SymbolPrs(ModelAPI_Feature* theConstraint, 
230                                              const std::shared_ptr<GeomAPI_Ax3>& thePlane)
231  : AIS_InteractiveObject(), myConstraint(theConstraint), myPlane(thePlane)
232 {
233   SetAutoHilight(Standard_False);
234 }
235
236 SketcherPrs_SymbolPrs::~SketcherPrs_SymbolPrs()
237 {
238   SketcherPrs_PositionMgr* aMgr = SketcherPrs_PositionMgr::get();
239   aMgr->deleteConstraint(this);
240 }
241
242 #ifdef _WINDOWS
243 #pragma warning( disable : 4996 )
244 #endif
245
246 Handle(Image_AlienPixMap) SketcherPrs_SymbolPrs::icon()
247 {
248   if (myIconsMap.count(iconName()) == 1) {
249     return myIconsMap[iconName()];
250   }
251   char* aEnv = getenv("NEWGEOM_ROOT_DIR");
252   if (aEnv != NULL) {
253     TCollection_AsciiString aFile(aEnv);
254     aFile+=FSEP;
255     aFile+="resources";
256     aFile += FSEP;
257     aFile += iconName();
258     Handle(Image_AlienPixMap) aPixMap = new Image_AlienPixMap();
259     if (aPixMap->Load(aFile)) {
260       myIconsMap[iconName()] = aPixMap;
261       return aPixMap;
262     }
263   }
264   static const char aMsg[] = "Error! constraint images are not found";
265   cout<<aMsg<<endl;
266   Events_Error::send(aMsg);
267   myIconsMap[iconName()] = Handle(Image_AlienPixMap)();
268   return Handle(Image_AlienPixMap)();
269 }
270
271 void SketcherPrs_SymbolPrs::ClearSelected()
272 {
273   Handle( Prs3d_Presentation ) aSelectionPrs = GetSelectPresentation( NULL );  
274   if( !aSelectionPrs.IsNull() ) {
275     aSelectionPrs->Clear(); 
276   }
277 }
278
279 void SketcherPrs_SymbolPrs::prepareAspect()
280 {
281   if (myAspect.IsNull()) {
282     Handle(Image_AlienPixMap) aIcon = icon();
283     if (aIcon.IsNull()) 
284       myAspect = new Graphic3d_AspectMarker3d();
285     else
286       myAspect = new Graphic3d_AspectMarker3d(aIcon);
287   }
288 }
289
290 void SketcherPrs_SymbolPrs::addLine(const Handle(Graphic3d_Group)& theGroup, std::string theAttrName) const
291 {
292   ObjectPtr aObj = SketcherPrs_Tools::getResult(myConstraint, theAttrName);
293   std::shared_ptr<GeomAPI_Shape> aLine = SketcherPrs_Tools::getShape(aObj);
294   if (aLine.get() == NULL)
295     return;
296   std::shared_ptr<GeomAPI_Edge> aEdge = std::shared_ptr<GeomAPI_Edge>(new GeomAPI_Edge(aLine));
297
298   std::shared_ptr<GeomAPI_Pnt> aPnt1 = aEdge->firstPoint();
299   std::shared_ptr<GeomAPI_Pnt> aPnt2 = aEdge->lastPoint();
300
301   Handle(Graphic3d_ArrayOfSegments) aLines = new Graphic3d_ArrayOfSegments(2, 1);
302   aLines->AddVertex(aPnt1->impl<gp_Pnt>());
303   aLines->AddVertex(aPnt2->impl<gp_Pnt>());
304   theGroup->AddPrimitiveArray(aLines);
305 }
306
307 void SketcherPrs_SymbolPrs::HilightSelected(const Handle(PrsMgr_PresentationManager3d)& thePM, 
308                                            const SelectMgr_SequenceOfOwner& theOwners)
309 {
310
311   Handle( Prs3d_Presentation ) aSelectionPrs = GetSelectPresentation( thePM );
312   aSelectionPrs->Clear();
313   drawLines(aSelectionPrs, Quantity_NOC_WHITE);
314
315   aSelectionPrs->SetDisplayPriority(9);
316   aSelectionPrs->Display();
317   thePM->Highlight(this);
318 }
319
320 void SketcherPrs_SymbolPrs::HilightOwnerWithColor(const Handle(PrsMgr_PresentationManager3d)& thePM, 
321                                                  const Quantity_NameOfColor theColor, 
322                                                  const Handle(SelectMgr_EntityOwner)& theOwner)
323 {
324   thePM->Color(this, theColor);
325
326   Handle( Prs3d_Presentation ) aHilightPrs = GetHilightPresentation( thePM );
327   aHilightPrs->Clear();
328   drawLines(aHilightPrs, theColor);
329
330   if (thePM->IsImmediateModeOn())
331     thePM->AddToImmediateList(aHilightPrs);
332 }
333
334 void SketcherPrs_SymbolPrs::Compute(const Handle(PrsMgr_PresentationManager3d)& thePresentationManager,
335                                    const Handle(Prs3d_Presentation)& thePresentation, 
336                                    const Standard_Integer theMode)
337 {
338   prepareAspect();
339
340   Handle(AIS_InteractiveContext) aCtx = GetContext();
341   Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast(aCtx->CurrentViewer()->Driver());
342   if (!aDriver.IsNull()) {
343     // register the custom element factory function
344     aDriver->UserDrawCallback() = SymbolPrsCallBack;
345   }
346
347   if (!updatePoints(20)) {
348     return;
349   }
350
351   int aNbVertex = myPntArray->VertexNumber();
352   if (myOwner.IsNull()) {
353     myOwner = new SelectMgr_EntityOwner(this);
354   }
355
356   mySPoints.Clear();
357   for (int i = 1; i <= aNbVertex; i++) {
358     Handle(SketcherPrs_SensitivePoint) aSP = new SketcherPrs_SensitivePoint(myOwner, i);
359     mySPoints.Append(aSP);
360   }
361
362   Handle(Graphic3d_Group) aGroup = Prs3d_Root::NewGroup(thePresentation);
363   aGroup->SetPrimitivesAspect(myAspect);
364
365   Graphic3d_BndBox4f& aBnd = aGroup->ChangeBoundingBox();
366   gp_Pnt aVert;
367   aBnd.Clear();
368   for (int i = 1; i <= myPntArray->ItemNumber(); i++) {
369     aVert = myPntArray->Vertice(i);
370     aBnd.Add (Graphic3d_Vec4((float)aVert.X(), (float)aVert.Y(), (float)aVert.Z(), 1.0f));
371   }
372
373   aGroup->UserDraw(this, true);
374
375   // Disable frustum culling for this object by marking it as mutable
376   aGroup->Structure()->SetMutable(true);
377   //aGroup->AddPrimitiveArray(myPntArray);
378 }
379
380
381
382 void SketcherPrs_SymbolPrs::ComputeSelection(const Handle(SelectMgr_Selection)& aSelection,
383                                             const Standard_Integer aMode)
384 {
385   ClearSelected();
386   if ((aMode == 0) || (aMode == SketcherPrs_Tools::Sel_Constraint)) {
387     for (int i = 1; i <= mySPoints.Length(); i++)
388       aSelection->Add(mySPoints.Value(i));
389   }
390 }
391
392
393 void SketcherPrs_SymbolPrs::Render(const Handle(OpenGl_Workspace)& theWorkspace) const
394 {
395   const OpenGl_AspectMarker* anAspectMarker = theWorkspace->AspectMarker(Standard_True);
396   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
397   Handle(OpenGl_View) aView = theWorkspace->ActiveView();
398   
399   double aScale = aView->Camera()->Scale();
400   if (!updatePoints(MyDist * aScale))
401     return;
402
403   Handle(Graphic3d_Buffer) aAttribs = myPntArray->Attributes();
404
405   if (myVboAttribs.IsNull()) {
406     myVboAttribs = new SketcherPrs_VertexBuffer(*aAttribs);
407   }
408
409   if (!myVboAttribs->init(aCtx, 0, aAttribs->NbElements, aAttribs->Data(), GL_NONE, aAttribs->Stride)) {
410     myVboAttribs->Release (aCtx.operator->());
411     myVboAttribs.Nullify();
412     return;
413   }
414     
415   Handle(OpenGl_Texture) aTextureBack = theWorkspace->DisableTexture();
416
417   const Handle(OpenGl_PointSprite)& aSpriteNorm = anAspectMarker->SpriteRes(aCtx);
418       
419   if (!aSpriteNorm.IsNull() && !aSpriteNorm->IsDisplayList()) {
420     const bool toHilight = (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT) != 0;
421     const Handle(OpenGl_PointSprite)& aSprite = (toHilight && anAspectMarker->SpriteHighlightRes(aCtx)->IsValid())
422                                               ? anAspectMarker->SpriteHighlightRes(aCtx)
423                                               : aSpriteNorm;
424     theWorkspace->EnableTexture (aSprite);
425     aCtx->ShaderManager()->BindProgram(anAspectMarker, aSprite, Standard_False, Standard_False, anAspectMarker->ShaderProgramRes(aCtx));
426     const TEL_COLOUR* aLineColor  =  &anAspectMarker->Color();
427     if (theWorkspace->NamedStatus & OPENGL_NS_HIGHLIGHT)
428       aLineColor = theWorkspace->HighlightColor;
429
430     if (toHilight)
431       aCtx->core11fwd->glDisable (GL_LIGHTING);
432     else
433       aCtx->core11fwd->glEnable (GL_LIGHTING);
434
435     aCtx->SetColor4fv(*(const OpenGl_Vec4* )(aLineColor->rgb));
436
437
438     myVboAttribs->BindAllAttributes(aCtx);
439     // Textured markers will be drawn with the point sprites
440     aCtx->SetPointSize (anAspectMarker->MarkerSize());
441     aCtx->core11fwd->glEnable (GL_ALPHA_TEST);
442     aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, 0.1f);
443
444     aCtx->core11fwd->glEnable (GL_BLEND);
445     aCtx->core11fwd->glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
446
447     aCtx->core11fwd->glDrawArrays (0, 0, myVboAttribs->GetElemsNb());
448
449     aCtx->core11fwd->glDisable (GL_BLEND);
450     aCtx->core11fwd->glDisable (GL_ALPHA_TEST);
451     aCtx->SetPointSize (1.0f);
452   }
453   theWorkspace->EnableTexture (aTextureBack);
454   aCtx->BindProgram (NULL);
455
456   // Update selection position only if there is no selected object
457   // because it can corrupt selection of other objects
458   if ((GetContext()->NbCurrents() == 0) && (GetContext()->NbSelected() == 0))
459   {
460     GetContext()->MainSelector()->RebuildSensitivesTree (this);
461     GetContext()->MainSelector()->RebuildObjectsTree (false);
462   }
463 }
464
465
466 void SketcherPrs_SymbolPrs::Release (OpenGl_Context* theContext)
467 {
468   if (!myVboAttribs.IsNull()) {
469     if (theContext) {
470       theContext->DelayedRelease (myVboAttribs);
471     }
472     myVboAttribs.Nullify();
473   }
474 }
475
476 void SketcherPrs_SymbolPrs::drawShape(const std::shared_ptr<GeomAPI_Shape>& theShape, 
477                                       const Handle(Prs3d_Presentation)& thePrs) const
478 {
479   if (theShape->isEdge()) {
480     std::shared_ptr<GeomAPI_Curve> aCurve = 
481       std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(theShape));
482     if (aCurve->isLine()) {
483       GeomAdaptor_Curve aCurv(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
484       StdPrs_Curve::Add(thePrs, aCurv, myDrawer);
485     } else {
486       GeomAdaptor_Curve aAdaptor(aCurve->impl<Handle(Geom_Curve)>(), aCurve->startParam(), aCurve->endParam());
487       StdPrs_DeflectionCurve::Add(thePrs,aAdaptor,myDrawer);
488     }
489   } else if (theShape->isVertex()) {
490     std::shared_ptr<GeomAPI_Vertex> aVertex = 
491       std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex(theShape));
492     std::shared_ptr<GeomAPI_Pnt> aPnt = aVertex->point();
493     Handle(Geom_CartesianPoint) aPoint = new Geom_CartesianPoint(aPnt->impl<gp_Pnt>());
494     StdPrs_Point::Add(thePrs, aPoint, myDrawer);
495   }
496 }
497
498 void SketcherPrs_SymbolPrs::drawListOfShapes(const std::shared_ptr<ModelAPI_AttributeRefList>& theListAttr, 
499                                              const Handle(Prs3d_Presentation)& thePrs) const
500 {
501   int aNb = theListAttr->size();
502   if (aNb == 0)
503     return;
504   int i;
505   ObjectPtr aObj;
506   for (i = 0; i < aNb; i++) {
507     aObj = theListAttr->object(i);
508     std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(aObj);
509     if (aShape.get() != NULL)
510       drawShape(aShape, thePrs);
511   }
512 }
513
514 void SketcherPrs_SymbolPrs::BoundingBox (Bnd_Box& theBndBox)
515 {
516   Select3D_BndBox3d aTmpBox;
517   for (Select3D_EntitySequenceIter aPntIter (mySPoints); aPntIter.More(); aPntIter.Next())
518   {
519     const Handle(Select3D_SensitiveEntity)& anEnt = aPntIter.Value();
520     aTmpBox.Combine (anEnt->BoundingBox());
521   }
522
523   theBndBox.Update (aTmpBox.CornerMin().x(), aTmpBox.CornerMin().y(), aTmpBox.CornerMin().z(),
524                     aTmpBox.CornerMax().x(), aTmpBox.CornerMax().y(), aTmpBox.CornerMax().z());
525 }
526