0030076: Visualization, TKV3d - API to update certain vertex attribute(s) without...
[occt.git] / src / OpenGl / OpenGl_PrimitiveArray.cxx
1 // Created on: 2011-07-13
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2013 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <OpenGl_AspectFace.hxx>
17 #include <OpenGl_Context.hxx>
18 #include <OpenGl_GraphicDriver.hxx>
19 #include <OpenGl_IndexBuffer.hxx>
20 #include <OpenGl_PointSprite.hxx>
21 #include <OpenGl_PrimitiveArray.hxx>
22 #include <OpenGl_Sampler.hxx>
23 #include <OpenGl_ShaderManager.hxx>
24 #include <OpenGl_ShaderProgram.hxx>
25 #include <OpenGl_Structure.hxx>
26 #include <OpenGl_VertexBufferCompat.hxx>
27 #include <OpenGl_Workspace.hxx>
28 #include <Graphic3d_TextureParams.hxx>
29 #include <NCollection_AlignedAllocator.hxx>
30
31 namespace
32 {
33   //! Convert data type to GL info
34   inline GLenum toGlDataType (const Graphic3d_TypeOfData theType,
35                               GLint&                     theNbComp)
36   {
37     switch (theType)
38     {
39       case Graphic3d_TOD_USHORT:
40         theNbComp = 1;
41         return GL_UNSIGNED_SHORT;
42       case Graphic3d_TOD_UINT:
43         theNbComp = 1;
44         return GL_UNSIGNED_INT;
45       case Graphic3d_TOD_VEC2:
46         theNbComp = 2;
47         return GL_FLOAT;
48       case Graphic3d_TOD_VEC3:
49         theNbComp = 3;
50         return GL_FLOAT;
51       case Graphic3d_TOD_VEC4:
52         theNbComp = 4;
53         return GL_FLOAT;
54       case Graphic3d_TOD_VEC4UB:
55         theNbComp = 4;
56         return GL_UNSIGNED_BYTE;
57       case Graphic3d_TOD_FLOAT:
58         theNbComp = 1;
59         return GL_FLOAT;
60     }
61     theNbComp = 0;
62     return GL_NONE;
63   }
64
65 }
66
67 //! Auxiliary template for VBO with interleaved attributes.
68 template<class TheBaseClass, int NbAttributes>
69 class OpenGl_VertexBufferT : public TheBaseClass
70 {
71 public:
72
73   //! Create uninitialized VBO.
74   OpenGl_VertexBufferT (const Graphic3d_Buffer& theAttribs)
75   : Stride (theAttribs.IsInterleaved() ? theAttribs.Stride : 0)
76   {
77     memcpy (Attribs, theAttribs.AttributesArray(), sizeof(Graphic3d_Attribute) * NbAttributes);
78   }
79
80   virtual bool HasColorAttribute() const
81   {
82     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
83     {
84       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
85       if (anAttrib.Id == Graphic3d_TOA_COLOR)
86       {
87         return true;
88       }
89     }
90     return false;
91   }
92
93   virtual bool HasNormalAttribute() const
94   {
95     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
96     {
97       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
98       if (anAttrib.Id == Graphic3d_TOA_NORM)
99       {
100         return true;
101       }
102     }
103     return false;
104   }
105
106   virtual void BindPositionAttribute (const Handle(OpenGl_Context)& theGlCtx) const
107   {
108     if (!TheBaseClass::IsValid())
109     {
110       return;
111     }
112
113     TheBaseClass::Bind (theGlCtx);
114     GLint aNbComp;
115     const GLubyte* anOffset = TheBaseClass::myOffset;
116     const Standard_Size aMuliplier = Stride != 0 ? 1 : TheBaseClass::myElemsNb;
117     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
118     {
119       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
120       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
121       if (anAttrib.Id == Graphic3d_TOA_POS
122        && aDataType != GL_NONE)
123       {
124         TheBaseClass::bindAttribute (theGlCtx, Graphic3d_TOA_POS, aNbComp, aDataType, Stride, anOffset);
125         break;
126       }
127
128       anOffset += aMuliplier * Graphic3d_Attribute::Stride (anAttrib.DataType);
129     }
130   }
131
132   virtual void BindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
133   {
134     if (!TheBaseClass::IsValid())
135     {
136       return;
137     }
138
139     TheBaseClass::Bind (theGlCtx);
140     GLint aNbComp;
141     const GLubyte* anOffset = TheBaseClass::myOffset;
142     const Standard_Size aMuliplier = Stride != 0 ? 1 : TheBaseClass::myElemsNb;
143     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
144     {
145       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
146       const GLenum   aDataType = toGlDataType (anAttrib.DataType, aNbComp);
147       if (aDataType != GL_NONE)
148       {
149         TheBaseClass::bindAttribute (theGlCtx, anAttrib.Id, aNbComp, aDataType, Stride, anOffset);
150       }
151       anOffset += aMuliplier * Graphic3d_Attribute::Stride (anAttrib.DataType);
152     }
153   }
154
155   virtual void UnbindAllAttributes (const Handle(OpenGl_Context)& theGlCtx) const
156   {
157     if (!TheBaseClass::IsValid())
158     {
159       return;
160     }
161     TheBaseClass::Unbind (theGlCtx);
162
163     for (Standard_Integer anAttribIter = 0; anAttribIter < NbAttributes; ++anAttribIter)
164     {
165       const Graphic3d_Attribute& anAttrib = Attribs[anAttribIter];
166       TheBaseClass::unbindAttribute (theGlCtx, anAttrib.Id);
167     }
168   }
169
170 private:
171
172   Graphic3d_Attribute Attribs[NbAttributes];
173   Standard_Integer    Stride;
174
175 };
176
177 // =======================================================================
178 // function : clearMemoryGL
179 // purpose  :
180 // =======================================================================
181 void OpenGl_PrimitiveArray::clearMemoryGL (const Handle(OpenGl_Context)& theGlCtx) const
182 {
183   if (!myVboIndices.IsNull())
184   {
185     myVboIndices->Release (theGlCtx.operator->());
186     myVboIndices.Nullify();
187   }
188   if (!myVboAttribs.IsNull())
189   {
190     myVboAttribs->Release (theGlCtx.operator->());
191     myVboAttribs.Nullify();
192   }
193 }
194
195 // =======================================================================
196 // function : initNormalVbo
197 // purpose  :
198 // =======================================================================
199 Standard_Boolean OpenGl_PrimitiveArray::initNormalVbo (const Handle(OpenGl_Context)& theCtx) const
200 {
201   switch (myAttribs->NbAttributes)
202   {
203     case 1:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 1> (*myAttribs); break;
204     case 2:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 2> (*myAttribs); break;
205     case 3:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 3> (*myAttribs); break;
206     case 4:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 4> (*myAttribs); break;
207     case 5:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 5> (*myAttribs); break;
208     case 6:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 6> (*myAttribs); break;
209     case 7:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 7> (*myAttribs); break;
210     case 8:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 8> (*myAttribs); break;
211     case 9:  myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 9> (*myAttribs); break;
212     case 10: myVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBuffer, 10>(*myAttribs); break;
213   }
214
215   const Standard_Boolean isAttribMutable     = myAttribs->IsMutable();
216   const Standard_Boolean isAttribInterleaved = myAttribs->IsInterleaved();
217   if (myAttribs->NbElements != myAttribs->NbMaxElements()
218    && myIndices.IsNull()
219    && (!isAttribInterleaved || isAttribMutable))
220   {
221     throw Standard_ProgramError ("OpenGl_PrimitiveArray::buildVBO() - vertex attribute data with reserved size is not supported");
222   }
223
224   // specify data type as Byte and NbComponents as Stride, so that OpenGl_VertexBuffer::EstimatedDataSize() will return correct value
225   const Standard_Integer aNbVertexes = (isAttribMutable || !isAttribInterleaved) ? myAttribs->NbMaxElements() : myAttribs->NbElements;
226   if (!myVboAttribs->init (theCtx, myAttribs->Stride, aNbVertexes, myAttribs->Data(), GL_UNSIGNED_BYTE, myAttribs->Stride))
227   {
228     TCollection_ExtendedString aMsg = TCollection_ExtendedString("VBO creation for Primitive Array has failed for ") + aNbVertexes + " vertices. Out of memory?";
229     theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PERFORMANCE, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
230
231     clearMemoryGL (theCtx);
232     return Standard_False;
233   }
234   else if (myIndices.IsNull())
235   {
236     if (isAttribMutable && isAttribInterleaved)
237     {
238       // for mutable interlaced array we can change dynamically number of vertexes (they will be just skipped at the end of buffer);
239       // this doesn't matter in case if we have indexed array
240       myVboAttribs->SetElemsNb (myAttribs->NbElements);
241     }
242     return Standard_True;
243   }
244
245   const Standard_Integer aNbIndexes = !myIndices->IsMutable() ? myIndices->NbElements : myIndices->NbMaxElements();
246   myVboIndices = new OpenGl_IndexBuffer();
247   bool isOk = false;
248   switch (myIndices->Stride)
249   {
250     case 2:
251     {
252       isOk = myVboIndices->Init (theCtx, 1, aNbIndexes, reinterpret_cast<const GLushort*> (myIndices->Data()));
253       myVboIndices->SetElemsNb (myIndices->NbElements);
254       myIndices->Validate();
255       break;
256     }
257     case 4:
258     {
259       isOk = myVboIndices->Init (theCtx, 1, aNbIndexes, reinterpret_cast<const GLuint*> (myIndices->Data()));
260       myVboIndices->SetElemsNb (myIndices->NbElements);
261       myIndices->Validate();
262       break;
263     }
264     default:
265     {
266       clearMemoryGL (theCtx);
267       return Standard_False;
268     }
269   }
270   if (!isOk)
271   {
272     TCollection_ExtendedString aMsg = TCollection_ExtendedString("VBO creation for Primitive Array has failed for ") + aNbIndexes + " indices. Out of memory?";
273     theCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PERFORMANCE, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
274     clearMemoryGL (theCtx);
275     return Standard_False;
276   }
277   return Standard_True;
278 }
279
280 // =======================================================================
281 // function : buildVBO
282 // purpose  :
283 // =======================================================================
284 Standard_Boolean OpenGl_PrimitiveArray::buildVBO (const Handle(OpenGl_Context)& theCtx,
285                                                   const Standard_Boolean        theToKeepData) const
286 {
287   bool isNormalMode = theCtx->ToUseVbo();
288   clearMemoryGL (theCtx);
289   if (myAttribs.IsNull()
290    || myAttribs->IsEmpty()
291    || myAttribs->NbElements < 1
292    || myAttribs->NbAttributes < 1
293    || myAttribs->NbAttributes > 10)
294   {
295     // vertices should be always defined - others are optional
296     return Standard_False;
297   }
298
299   if (isNormalMode
300    && initNormalVbo (theCtx))
301   {
302     if (!theCtx->caps->keepArrayData
303      && !theToKeepData
304      && !myAttribs->IsMutable())
305     {
306       myIndices.Nullify();
307       myAttribs.Nullify();
308     }
309     else
310     {
311       myAttribs->Validate();
312     }
313     return Standard_True;
314   }
315
316   Handle(OpenGl_VertexBufferCompat) aVboAttribs;
317   switch (myAttribs->NbAttributes)
318   {
319     case 1:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 1> (*myAttribs); break;
320     case 2:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 2> (*myAttribs); break;
321     case 3:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 3> (*myAttribs); break;
322     case 4:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 4> (*myAttribs); break;
323     case 5:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 5> (*myAttribs); break;
324     case 6:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 6> (*myAttribs); break;
325     case 7:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 7> (*myAttribs); break;
326     case 8:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 8> (*myAttribs); break;
327     case 9:  aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 9> (*myAttribs); break;
328     case 10: aVboAttribs = new OpenGl_VertexBufferT<OpenGl_VertexBufferCompat, 10>(*myAttribs); break;
329   }
330   aVboAttribs->initLink (myAttribs, 0, myAttribs->NbElements, GL_NONE);
331   if (!myIndices.IsNull())
332   {
333     Handle(OpenGl_VertexBufferCompat) aVboIndices = new OpenGl_VertexBufferCompat();
334     switch (myIndices->Stride)
335     {
336       case 2:
337       {
338         aVboIndices->initLink (myIndices, 1, myIndices->NbElements, GL_UNSIGNED_SHORT);
339         break;
340       }
341       case 4:
342       {
343         aVboIndices->initLink (myIndices, 1, myIndices->NbElements, GL_UNSIGNED_INT);
344         break;
345       }
346       default:
347       {
348         return Standard_False;
349       }
350     }
351     myVboIndices = aVboIndices;
352   }
353   myVboAttribs = aVboAttribs;
354   if (!theCtx->caps->keepArrayData
355    && !theToKeepData)
356   {
357     // does not make sense for compatibility mode
358     //myIndices.Nullify();
359     //myAttribs.Nullify();
360   }
361
362   return Standard_True;
363 }
364
365 // =======================================================================
366 // function : updateVBO
367 // purpose  :
368 // =======================================================================
369 void OpenGl_PrimitiveArray::updateVBO (const Handle(OpenGl_Context)& theCtx) const
370 {
371   if (!myAttribs.IsNull())
372   {
373     Graphic3d_BufferRange aRange = myAttribs->InvalidatedRange();
374     if (!aRange.IsEmpty()
375      &&  myVboAttribs->IsValid()
376      && !myVboAttribs->IsVirtual())
377     {
378       myVboAttribs->Bind (theCtx);
379       theCtx->core15fwd->glBufferSubData (myVboAttribs->GetTarget(),
380                                           aRange.Start,
381                                           aRange.Length,
382                                           myAttribs->Data() + aRange.Start);
383       myVboAttribs->Unbind (theCtx);
384       if (myAttribs->IsInterleaved())
385       {
386         myVboAttribs->SetElemsNb (myAttribs->NbElements);
387       }
388     }
389     myAttribs->Validate();
390   }
391   if (!myIndices.IsNull())
392   {
393     Graphic3d_BufferRange aRange = myIndices->InvalidatedRange();
394     if (!aRange.IsEmpty()
395      &&  myVboIndices->IsValid()
396      && !myVboIndices->IsVirtual())
397     {
398       myVboIndices->Bind (theCtx);
399       theCtx->core15fwd->glBufferSubData (myVboIndices->GetTarget(),
400                                           aRange.Start,
401                                           aRange.Length,
402                                           myIndices->Data() + aRange.Start);
403       myVboIndices->Unbind (theCtx);
404       myVboIndices->SetElemsNb (myIndices->NbElements);
405     }
406     myIndices->Validate();
407   }
408 }
409
410 // =======================================================================
411 // function : drawArray
412 // purpose  :
413 // =======================================================================
414 void OpenGl_PrimitiveArray::drawArray (const Handle(OpenGl_Workspace)& theWorkspace,
415                                        const Graphic3d_Vec4*           theFaceColors,
416                                        const Standard_Boolean          theHasVertColor) const
417 {
418   if (myVboAttribs.IsNull())
419   {
420   #if !defined(GL_ES_VERSION_2_0)
421     if (myDrawMode == GL_POINTS)
422     {
423       // extreme compatibility mode - without sprites but with markers
424       drawMarkers (theWorkspace);
425     }
426   #endif
427     return;
428   }
429
430   const Handle(OpenGl_Context)& aGlContext = theWorkspace->GetGlContext();
431   const bool                    toHilight  = theWorkspace->ToHighlight();
432   const GLenum aDrawMode = !aGlContext->ActiveProgram().IsNull()
433                          && aGlContext->ActiveProgram()->HasTessellationStage()
434                          ? GL_PATCHES
435                          : myDrawMode;
436   myVboAttribs->BindAllAttributes (aGlContext);
437   if (theHasVertColor && toHilight)
438   {
439     // disable per-vertex color
440     OpenGl_VertexBuffer::unbindAttribute (aGlContext, Graphic3d_TOA_COLOR);
441   }
442   if (!myVboIndices.IsNull())
443   {
444     myVboIndices->Bind (aGlContext);
445     GLubyte* anOffset = myVboIndices->GetDataOffset();
446     if (!myBounds.IsNull())
447     {
448       // draw primitives by vertex count with the indices
449       const size_t aStride = myVboIndices->GetDataType() == GL_UNSIGNED_SHORT ? sizeof(unsigned short) : sizeof(unsigned int);
450       for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
451       {
452         const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
453         if (theFaceColors != NULL) aGlContext->SetColor4fv (theFaceColors[aGroupIter]);
454         glDrawElements (aDrawMode, aNbElemsInGroup, myVboIndices->GetDataType(), anOffset);
455         anOffset += aStride * aNbElemsInGroup;
456       }
457     }
458     else
459     {
460       // draw one (or sequential) primitive by the indices
461       glDrawElements (aDrawMode, myVboIndices->GetElemsNb(), myVboIndices->GetDataType(), anOffset);
462     }
463     myVboIndices->Unbind (aGlContext);
464   }
465   else if (!myBounds.IsNull())
466   {
467     GLint aFirstElem = 0;
468     for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
469     {
470       const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
471       if (theFaceColors != NULL) aGlContext->SetColor4fv (theFaceColors[aGroupIter]);
472       glDrawArrays (aDrawMode, aFirstElem, aNbElemsInGroup);
473       aFirstElem += aNbElemsInGroup;
474     }
475   }
476   else
477   {
478     if (myDrawMode == GL_POINTS)
479     {
480       drawMarkers (theWorkspace);
481     }
482     else
483     {
484       glDrawArrays (aDrawMode, 0, myVboAttribs->GetElemsNb());
485     }
486   }
487
488   // bind with 0
489   myVboAttribs->UnbindAllAttributes (aGlContext);
490 }
491
492 // =======================================================================
493 // function : drawEdges
494 // purpose  :
495 // =======================================================================
496 void OpenGl_PrimitiveArray::drawEdges (const OpenGl_Vec4&              theEdgeColour,
497                                        const Handle(OpenGl_Workspace)& theWorkspace) const
498 {
499   const Handle(OpenGl_Context)& aGlContext = theWorkspace->GetGlContext();
500   if (myVboAttribs.IsNull())
501   {
502     return;
503   }
504
505   const OpenGl_AspectLine* anAspectLineOld = theWorkspace->SetAspectLine (theWorkspace->AspectFace()->AspectEdge());
506   const OpenGl_AspectLine* anAspect = theWorkspace->ApplyAspectLine();
507
508 #if !defined(GL_ES_VERSION_2_0)
509   glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
510 #endif
511
512   if (aGlContext->core20fwd != NULL)
513   {
514     aGlContext->ShaderManager()->BindLineProgram (Handle(OpenGl_TextureSet)(), anAspect->Aspect()->Type(),
515                                                   Graphic3d_TOSM_UNLIT, Graphic3d_AlphaMode_Opaque, Standard_False,
516                                                   anAspect->ShaderProgramRes (aGlContext));
517   }
518   const GLenum aDrawMode = !aGlContext->ActiveProgram().IsNull()
519                          && aGlContext->ActiveProgram()->HasTessellationStage()
520                          ? GL_PATCHES
521                          : myDrawMode;
522 #if !defined(GL_ES_VERSION_2_0)
523   if (aGlContext->ActiveProgram().IsNull()
524    && aGlContext->core11 != NULL)
525   {
526     glDisable (GL_LIGHTING);
527   }
528 #endif
529
530   /// OCC22236 NOTE: draw edges for all situations:
531   /// 1) draw elements with GL_LINE style as edges from myPArray->bufferVBO[VBOEdges] indices array
532   /// 2) draw elements from vertex array, when bounds defines count of primitive's vertices.
533   /// 3) draw primitive's edges by vertexes if no edges and bounds array is specified
534   myVboAttribs->BindPositionAttribute (aGlContext);
535
536   aGlContext->SetColor4fv   (theEdgeColour);
537   aGlContext->SetTypeOfLine (anAspect->Aspect()->Type());
538   aGlContext->SetLineWidth  (anAspect->Aspect()->Width());
539
540   if (!myVboIndices.IsNull())
541   {
542     myVboIndices->Bind (aGlContext);
543     GLubyte* anOffset = myVboIndices->GetDataOffset();
544
545     // draw primitives by vertex count with the indices
546     if (!myBounds.IsNull())
547     {
548       const size_t aStride = myVboIndices->GetDataType() == GL_UNSIGNED_SHORT ? sizeof(unsigned short) : sizeof(unsigned int);
549       for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
550       {
551         const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
552         glDrawElements (aDrawMode, aNbElemsInGroup, myVboIndices->GetDataType(), anOffset);
553         anOffset += aStride * aNbElemsInGroup;
554       }
555     }
556     // draw one (or sequential) primitive by the indices
557     else
558     {
559       glDrawElements (aDrawMode, myVboIndices->GetElemsNb(), myVboIndices->GetDataType(), anOffset);
560     }
561     myVboIndices->Unbind (aGlContext);
562   }
563   else if (!myBounds.IsNull())
564   {
565     GLint aFirstElem = 0;
566     for (Standard_Integer aGroupIter = 0; aGroupIter < myBounds->NbBounds; ++aGroupIter)
567     {
568       const GLint aNbElemsInGroup = myBounds->Bounds[aGroupIter];
569       glDrawArrays (aDrawMode, aFirstElem, aNbElemsInGroup);
570       aFirstElem += aNbElemsInGroup;
571     }
572   }
573   else
574   {
575     glDrawArrays (aDrawMode, 0, !myVboAttribs.IsNull() ? myVboAttribs->GetElemsNb() : myAttribs->NbElements);
576   }
577
578   // unbind buffers
579   myVboAttribs->UnbindAttribute (aGlContext, Graphic3d_TOA_POS);
580
581   // restore line context
582   theWorkspace->SetAspectLine (anAspectLineOld);
583 }
584
585 // =======================================================================
586 // function : drawMarkers
587 // purpose  :
588 // =======================================================================
589 void OpenGl_PrimitiveArray::drawMarkers (const Handle(OpenGl_Workspace)& theWorkspace) const
590 {
591   const OpenGl_AspectMarker* anAspectMarker = theWorkspace->ApplyAspectMarker();
592   const Handle(OpenGl_Context)&     aCtx    = theWorkspace->GetGlContext();
593   const GLenum aDrawMode = !aCtx->ActiveProgram().IsNull()
594                          && aCtx->ActiveProgram()->HasTessellationStage()
595                          ? GL_PATCHES
596                          : myDrawMode;
597
598   const Handle(OpenGl_TextureSet)& aSpriteNormRes = anAspectMarker->SpriteRes (aCtx);
599   const OpenGl_PointSprite* aSpriteNorm = !aSpriteNormRes.IsNull() ? dynamic_cast<const OpenGl_PointSprite*> (aSpriteNormRes->First().get()) : NULL;
600   if (aSpriteNorm != NULL
601   && !aSpriteNorm->IsDisplayList())
602   {
603     // Textured markers will be drawn with the point sprites
604     aCtx->SetPointSize (anAspectMarker->MarkerSize());
605     aCtx->SetPointSpriteOrigin();
606   #if !defined(GL_ES_VERSION_2_0)
607     if (aCtx->core11 != NULL)
608     {
609       aCtx->core11fwd->glEnable (GL_ALPHA_TEST);
610       aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, 0.1f);
611     }
612   #endif
613
614     aCtx->core11fwd->glEnable (GL_BLEND);
615     aCtx->core11fwd->glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
616
617     aCtx->core11fwd->glDrawArrays (aDrawMode, 0, !myVboAttribs.IsNull() ? myVboAttribs->GetElemsNb() : myAttribs->NbElements);
618
619     aCtx->core11fwd->glDisable (GL_BLEND);
620   #if !defined(GL_ES_VERSION_2_0)
621     if (aCtx->core11 != NULL)
622     {
623       if (aCtx->ShaderManager()->MaterialState().AlphaCutoff() >= ShortRealLast())
624       {
625         aCtx->core11fwd->glDisable (GL_ALPHA_TEST);
626       }
627       else
628       {
629         aCtx->core11fwd->glAlphaFunc (GL_GEQUAL, aCtx->ShaderManager()->MaterialState().AlphaCutoff());
630       }
631     }
632   #endif
633     aCtx->SetPointSize (1.0f);
634     return;
635   }
636   else if (anAspectMarker->Aspect()->Type() == Aspect_TOM_POINT)
637   {
638     aCtx->SetPointSize (anAspectMarker->MarkerSize());
639     aCtx->core11fwd->glDrawArrays (aDrawMode, 0, !myVboAttribs.IsNull() ? myVboAttribs->GetElemsNb() : myAttribs->NbElements);
640     aCtx->SetPointSize (1.0f);
641   }
642 #if !defined(GL_ES_VERSION_2_0)
643   // Textured markers will be drawn with the glBitmap
644   else if (anAspectMarker->Aspect()->Type() != Aspect_TOM_POINT
645         && aSpriteNorm != NULL)
646   {
647     /**if (!isHilight && (myPArray->vcolours != NULL))
648     {
649       for (Standard_Integer anIter = 0; anIter < myAttribs->NbElements; anIter++)
650       {
651         glColor4ubv    (myPArray->vcolours[anIter].GetData());
652         glRasterPos3fv (myAttribs->Value<Graphic3d_Vec3> (anIter).GetData());
653         aSpriteNorm->DrawBitmap (theWorkspace->GetGlContext());
654       }
655     }
656     else*/
657     {
658       for (Standard_Integer anIter = 0; anIter < myAttribs->NbElements; anIter++)
659       {
660         aCtx->core11->glRasterPos3fv (myAttribs->Value<Graphic3d_Vec3> (anIter).GetData());
661         aSpriteNorm->DrawBitmap (theWorkspace->GetGlContext());
662       }
663     }
664   }
665 #endif
666 }
667
668 // =======================================================================
669 // function : OpenGl_PrimitiveArray
670 // purpose  :
671 // =======================================================================
672 OpenGl_PrimitiveArray::OpenGl_PrimitiveArray (const OpenGl_GraphicDriver* theDriver)
673
674 : myDrawMode  (DRAW_MODE_NONE),
675   myIsFillType(Standard_False),
676   myIsVboInit (Standard_False)
677 {
678   if (theDriver != NULL)
679   {
680     myUID = theDriver->GetNextPrimitiveArrayUID();
681   }
682 }
683
684 // =======================================================================
685 // function : OpenGl_PrimitiveArray
686 // purpose  :
687 // =======================================================================
688 OpenGl_PrimitiveArray::OpenGl_PrimitiveArray (const OpenGl_GraphicDriver*          theDriver,
689                                               const Graphic3d_TypeOfPrimitiveArray theType,
690                                               const Handle(Graphic3d_IndexBuffer)& theIndices,
691                                               const Handle(Graphic3d_Buffer)&      theAttribs,
692                                               const Handle(Graphic3d_BoundBuffer)& theBounds)
693
694 : myIndices   (theIndices),
695   myAttribs   (theAttribs),
696   myBounds    (theBounds),
697   myDrawMode  (DRAW_MODE_NONE),
698   myIsFillType(Standard_False),
699   myIsVboInit (Standard_False)
700 {
701   if (!myIndices.IsNull()
702     && myIndices->NbElements < 1)
703   {
704     // dummy index buffer?
705     myIndices.Nullify();
706   }
707
708   if (theDriver != NULL)
709   {
710     myUID = theDriver->GetNextPrimitiveArrayUID();
711   #if defined (GL_ES_VERSION_2_0)
712     const Handle(OpenGl_Context)& aCtx = theDriver->GetSharedContext();
713     if (!aCtx.IsNull())
714     {
715       processIndices (aCtx);
716     }
717   #endif
718   }
719
720   setDrawMode (theType);
721 }
722
723 // =======================================================================
724 // function : ~OpenGl_PrimitiveArray
725 // purpose  :
726 // =======================================================================
727 OpenGl_PrimitiveArray::~OpenGl_PrimitiveArray()
728 {
729   //
730 }
731
732 // =======================================================================
733 // function : Release
734 // purpose  :
735 // =======================================================================
736 void OpenGl_PrimitiveArray::Release (OpenGl_Context* theContext)
737 {
738   myIsVboInit = Standard_False;
739   if (!myVboIndices.IsNull())
740   {
741     if (theContext)
742     {
743       theContext->DelayedRelease (myVboIndices);
744     }
745     myVboIndices.Nullify();
746   }
747   if (!myVboAttribs.IsNull())
748   {
749     if (theContext)
750     {
751       theContext->DelayedRelease (myVboAttribs);
752     }
753     myVboAttribs.Nullify();
754   }
755 }
756
757 // =======================================================================
758 // function : Render
759 // purpose  :
760 // =======================================================================
761 void OpenGl_PrimitiveArray::Render (const Handle(OpenGl_Workspace)& theWorkspace) const
762 {
763   if (myDrawMode == DRAW_MODE_NONE)
764   {
765     return;
766   }
767
768   const OpenGl_AspectFace*   anAspectFace   = theWorkspace->ApplyAspectFace();
769   const OpenGl_AspectLine*   anAspectLine   = theWorkspace->ApplyAspectLine();
770   const OpenGl_AspectMarker* anAspectMarker = myDrawMode == GL_POINTS
771                                             ? theWorkspace->ApplyAspectMarker()
772                                             : theWorkspace->AspectMarker();
773
774   // create VBOs on first render call
775   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
776   if (!myIsVboInit)
777   {
778     // compatibility - keep data to draw markers using display lists
779     Standard_Boolean toKeepData = Standard_False;
780     if (myDrawMode == GL_POINTS)
781     {
782       const Handle(OpenGl_TextureSet)& aSpriteNormRes = anAspectMarker->SpriteRes (aCtx);
783       const OpenGl_PointSprite* aSpriteNorm = !aSpriteNormRes.IsNull() ? dynamic_cast<const OpenGl_PointSprite*> (aSpriteNormRes->First().get()) : NULL;
784       toKeepData = aSpriteNorm != NULL
785                &&  aSpriteNorm->IsDisplayList();
786     }
787   #if defined (GL_ES_VERSION_2_0)
788     processIndices (aCtx);
789   #endif
790     buildVBO (aCtx, toKeepData);
791     myIsVboInit = Standard_True;
792   }
793   else if ((!myAttribs.IsNull()
794          &&  myAttribs->IsMutable())
795         || (!myIndices.IsNull()
796          &&  myIndices->IsMutable()))
797   {
798     updateVBO (aCtx);
799   }
800
801   // Temporarily disable environment mapping
802   Handle(OpenGl_TextureSet) aTextureBack;
803   bool toDrawArray = true;
804   if (myDrawMode > GL_LINE_STRIP)
805   {
806     toDrawArray = anAspectFace->Aspect()->InteriorStyle() != Aspect_IS_EMPTY;
807   }
808   else if (myDrawMode <= GL_LINE_STRIP)
809   {
810     aTextureBack = aCtx->BindTextures (Handle(OpenGl_TextureSet)());
811     if (myDrawMode == GL_POINTS)
812     {
813       toDrawArray = anAspectMarker->Aspect()->Type() != Aspect_TOM_EMPTY;
814     }
815     else
816     {
817       toDrawArray = anAspectLine->Aspect()->Type() != Aspect_TOL_EMPTY;
818     }
819   }
820
821   Graphic3d_TypeOfShadingModel aShadingModel = Graphic3d_TOSM_UNLIT;
822   if (toDrawArray)
823   {
824     const bool hasColorAttrib = !myVboAttribs.IsNull()
825                               && myVboAttribs->HasColorAttribute();
826     const bool toHilight    = theWorkspace->ToHighlight();
827     const bool hasVertColor = hasColorAttrib && !toHilight;
828     const bool hasVertNorm  = !myVboAttribs.IsNull() && myVboAttribs->HasNormalAttribute();
829     switch (myDrawMode)
830     {
831       case GL_POINTS:
832       {
833         aShadingModel = aCtx->ShaderManager()->ChooseMarkerShadingModel (anAspectFace->ShadingModel(), hasVertNorm);
834         const Handle(OpenGl_TextureSet)& aSpriteNormRes = anAspectMarker->SpriteRes (aCtx);
835         const OpenGl_PointSprite* aSpriteNorm = !aSpriteNormRes.IsNull() ? dynamic_cast<const OpenGl_PointSprite*> (aSpriteNormRes->First().get()) : NULL;
836         if (aSpriteNorm != NULL
837         && !aSpriteNorm->IsDisplayList())
838         {
839           const Handle(OpenGl_TextureSet)& aSprite = toHilight && anAspectMarker->SpriteHighlightRes (aCtx)->First()->IsValid()
840                                                    ? anAspectMarker->SpriteHighlightRes (aCtx)
841                                                    : aSpriteNormRes;
842           aCtx->BindTextures (aSprite);
843           aCtx->ShaderManager()->BindMarkerProgram (aSprite, aShadingModel, Graphic3d_AlphaMode_Opaque, hasVertColor, anAspectMarker->ShaderProgramRes (aCtx));
844         }
845         else
846         {
847           aCtx->ShaderManager()->BindMarkerProgram (Handle(OpenGl_TextureSet)(), aShadingModel, Graphic3d_AlphaMode_Opaque, hasVertColor, anAspectMarker->ShaderProgramRes (aCtx));
848         }
849         break;
850       }
851       case GL_LINES:
852       case GL_LINE_STRIP:
853       {
854         aShadingModel = aCtx->ShaderManager()->ChooseLineShadingModel (anAspectFace->ShadingModel(), hasVertNorm);
855         aCtx->ShaderManager()->BindLineProgram (NULL,
856                                                 anAspectLine->Aspect()->Type(),
857                                                 aShadingModel,
858                                                 Graphic3d_AlphaMode_Opaque,
859                                                 hasVertColor,
860                                                 anAspectLine->ShaderProgramRes (aCtx));
861         break;
862       }
863       default:
864       {
865         aShadingModel = aCtx->ShaderManager()->ChooseFaceShadingModel (anAspectFace->ShadingModel(), hasVertNorm);
866         const Handle(OpenGl_TextureSet)& aTextures = aCtx->ActiveTextures();
867         const Standard_Boolean toEnableEnvMap = (!aTextures.IsNull() && (aTextures == theWorkspace->EnvironmentTexture()));
868         aCtx->ShaderManager()->BindFaceProgram (aTextures,
869                                                 aShadingModel,
870                                                 anAspectFace->Aspect()->AlphaMode(),
871                                                 hasVertColor,
872                                                 toEnableEnvMap,
873                                                 anAspectFace->ShaderProgramRes (aCtx));
874         break;
875       }
876     }
877
878   #if !defined(GL_ES_VERSION_2_0)
879     // manage FFP lighting
880     if (aCtx->ActiveProgram().IsNull()
881      && aCtx->core11 != NULL)
882     {
883       if (aShadingModel == Graphic3d_TOSM_UNLIT)
884       {
885         glDisable (GL_LIGHTING);
886       }
887       else
888       {
889         glEnable (GL_LIGHTING);
890       }
891     }
892   #endif
893
894     if (!aCtx->ActiveTextures().IsNull()
895      && !aCtx->ActiveTextures()->IsEmpty()
896      && !aCtx->ActiveTextures()->First().IsNull()
897      && myDrawMode != GL_POINTS) // transformation is not supported within point sprites
898     {
899       aCtx->SetTextureMatrix (aCtx->ActiveTextures()->First()->Sampler()->Parameters());
900     }
901
902     if (myDrawMode <= GL_LINE_STRIP)
903     {
904       const OpenGl_Vec4& aLineColor = myDrawMode == GL_POINTS ? theWorkspace->MarkerColor() : theWorkspace->LineColor();
905       aCtx->SetColor4fv (aLineColor);
906     }
907     else
908     {
909       const OpenGl_Vec4& anInteriorColor = theWorkspace->InteriorColor();
910       aCtx->SetColor4fv (anInteriorColor);
911     }
912     if (myDrawMode == GL_LINES
913      || myDrawMode == GL_LINE_STRIP)
914     {
915       aCtx->SetTypeOfLine (anAspectLine->Aspect()->Type());
916       aCtx->SetLineWidth  (anAspectLine->Aspect()->Width());
917     }
918
919     const Graphic3d_Vec4* aFaceColors = !myBounds.IsNull() && !toHilight && anAspectFace->Aspect()->InteriorStyle() != Aspect_IS_HIDDENLINE
920                                       ?  myBounds->Colors
921                                       :  NULL;
922     drawArray (theWorkspace, aFaceColors, hasColorAttrib);
923   }
924
925   if (myDrawMode <= GL_LINE_STRIP)
926   {
927     aCtx->BindTextures (aTextureBack);
928   }
929   else
930   {
931     if (anAspectFace->Aspect()->ToDrawEdges()
932      || anAspectFace->Aspect()->InteriorStyle() == Aspect_IS_HIDDENLINE)
933     {
934       const OpenGl_Vec4& anEdgeColor = theWorkspace->EdgeColor();
935       drawEdges (anEdgeColor, theWorkspace);
936
937       // restore OpenGL polygon mode if needed
938     #if !defined(GL_ES_VERSION_2_0)
939       if (anAspectFace->Aspect()->InteriorStyle() >= Aspect_IS_HATCH)
940       {
941         glPolygonMode (GL_FRONT_AND_BACK,
942           anAspectFace->Aspect()->InteriorStyle() == Aspect_IS_POINT ? GL_POINT : GL_FILL);
943       }
944     #endif
945     }
946   }
947 }
948
949 // =======================================================================
950 // function : setDrawMode
951 // purpose  :
952 // =======================================================================
953 void OpenGl_PrimitiveArray::setDrawMode (const Graphic3d_TypeOfPrimitiveArray theType)
954 {
955   if (myAttribs.IsNull())
956   {
957     myDrawMode = DRAW_MODE_NONE;
958     myIsFillType = false;
959     return;
960   }
961
962   switch (theType)
963   {
964     case Graphic3d_TOPA_POINTS:
965       myDrawMode   = GL_POINTS;
966       myIsFillType = false;
967       break;
968     case Graphic3d_TOPA_SEGMENTS:
969       myDrawMode   = GL_LINES;
970       myIsFillType = false;
971       break;
972     case Graphic3d_TOPA_POLYLINES:
973       myDrawMode   = GL_LINE_STRIP;
974       myIsFillType = false;
975       break;
976     case Graphic3d_TOPA_TRIANGLES:
977       myDrawMode   = GL_TRIANGLES;
978       myIsFillType = true;
979       break;
980     case Graphic3d_TOPA_TRIANGLESTRIPS:
981       myDrawMode   = GL_TRIANGLE_STRIP;
982       myIsFillType = true;
983       break;
984     case Graphic3d_TOPA_TRIANGLEFANS:
985       myDrawMode   = GL_TRIANGLE_FAN;
986       myIsFillType = true;
987       break;
988     //
989     case Graphic3d_TOPA_LINES_ADJACENCY:
990       myDrawMode = GL_LINES_ADJACENCY;
991       myIsFillType = false;
992       break;
993     case Graphic3d_TOPA_LINE_STRIP_ADJACENCY:
994       myDrawMode   = GL_LINE_STRIP_ADJACENCY;
995       myIsFillType = false;
996       break;
997     case Graphic3d_TOPA_TRIANGLES_ADJACENCY:
998       myDrawMode   = GL_TRIANGLES_ADJACENCY;
999       myIsFillType = true;
1000       break;
1001     case Graphic3d_TOPA_TRIANGLE_STRIP_ADJACENCY:
1002       myDrawMode   = GL_TRIANGLE_STRIP_ADJACENCY;
1003       myIsFillType = true;
1004       break;
1005     //
1006   #if !defined(GL_ES_VERSION_2_0)
1007     case Graphic3d_TOPA_QUADRANGLES:
1008       myDrawMode   = GL_QUADS;
1009       myIsFillType = true;
1010       break;
1011     case Graphic3d_TOPA_QUADRANGLESTRIPS:
1012       myDrawMode   = GL_QUAD_STRIP;
1013       myIsFillType = true;
1014       break;
1015     case Graphic3d_TOPA_POLYGONS:
1016       myDrawMode   = GL_POLYGON;
1017       myIsFillType = true;
1018       break;
1019   #else
1020     case Graphic3d_TOPA_QUADRANGLES:
1021     case Graphic3d_TOPA_QUADRANGLESTRIPS:
1022     case Graphic3d_TOPA_POLYGONS:
1023   #endif
1024     case Graphic3d_TOPA_UNDEFINED:
1025       myDrawMode   = DRAW_MODE_NONE;
1026       myIsFillType = false;
1027       break;
1028   }
1029 }
1030
1031 // =======================================================================
1032 // function : processIndices
1033 // purpose  :
1034 // =======================================================================
1035 Standard_Boolean OpenGl_PrimitiveArray::processIndices (const Handle(OpenGl_Context)& theContext) const
1036 {
1037   if (myIndices.IsNull()
1038    || myAttribs.IsNull()
1039    || theContext->hasUintIndex)
1040   {
1041     return Standard_True;
1042   }
1043
1044   if (myAttribs->NbElements > std::numeric_limits<GLushort>::max())
1045   {
1046     Handle(Graphic3d_Buffer) anAttribs = new Graphic3d_Buffer (new NCollection_AlignedAllocator (16));
1047     if (!anAttribs->Init (myIndices->NbElements, myAttribs->AttributesArray(), myAttribs->NbAttributes))
1048     {
1049       return Standard_False; // failed to initialize attribute array
1050     }
1051
1052     for (Standard_Integer anIdxIdx = 0; anIdxIdx < myIndices->NbElements; ++anIdxIdx)
1053     {
1054       const Standard_Integer anIndex = myIndices->Index (anIdxIdx);
1055       memcpy (anAttribs->ChangeData() + myAttribs->Stride * anIdxIdx,
1056               myAttribs->Data()       + myAttribs->Stride * anIndex,
1057               myAttribs->Stride);
1058     }
1059
1060     myIndices.Nullify();
1061     myAttribs = anAttribs;
1062   }
1063
1064   return Standard_True;
1065 }
1066
1067 // =======================================================================
1068 // function : InitBuffers
1069 // purpose  :
1070 // =======================================================================
1071 void OpenGl_PrimitiveArray::InitBuffers (const Handle(OpenGl_Context)&        theContext,
1072                                          const Graphic3d_TypeOfPrimitiveArray theType,
1073                                          const Handle(Graphic3d_IndexBuffer)& theIndices,
1074                                          const Handle(Graphic3d_Buffer)&      theAttribs,
1075                                          const Handle(Graphic3d_BoundBuffer)& theBounds)
1076 {
1077   // Release old graphic resources
1078   Release (theContext.operator->());
1079
1080   myIndices = theIndices;
1081   myAttribs = theAttribs;
1082   myBounds = theBounds;
1083 #if defined(GL_ES_VERSION_2_0)
1084   processIndices (theContext);
1085 #endif
1086
1087   setDrawMode (theType);
1088 }