56170b4fc5e3cf8292be4bde81978e2fd93e7f90
[occt.git] / src / OpenGl / OpenGl_Workspace.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 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_Workspace.hxx>
17
18 #include <OpenGl_ArbFBO.hxx>
19 #include <OpenGl_Aspects.hxx>
20 #include <OpenGl_Context.hxx>
21 #include <OpenGl_Element.hxx>
22 #include <OpenGl_FrameBuffer.hxx>
23 #include <OpenGl_GlCore15.hxx>
24 #include <OpenGl_SceneGeometry.hxx>
25 #include <OpenGl_Structure.hxx>
26 #include <OpenGl_Sampler.hxx>
27 #include <OpenGl_ShaderManager.hxx>
28 #include <OpenGl_Texture.hxx>
29 #include <OpenGl_View.hxx>
30 #include <OpenGl_Window.hxx>
31
32 #include <Graphic3d_TextureParams.hxx>
33 #include <Graphic3d_TransformUtils.hxx>
34 #include <NCollection_AlignedAllocator.hxx>
35
36 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,Standard_Transient)
37
38 namespace
39 {
40   static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
41   static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
42
43   static const OpenGl_Matrix myDefaultMatrix =
44   {
45     {{ 1.0F, 0.0F, 0.0F, 0.0F },
46      { 0.0F, 1.0F, 0.0F, 0.0F },
47      { 0.0F, 0.0F, 1.0F, 0.0F },
48      { 0.0F, 0.0F, 0.0F, 1.0F }}
49   };
50
51 }
52
53 // =======================================================================
54 // function : Init
55 // purpose  :
56 // =======================================================================
57 void OpenGl_Material::Init (const OpenGl_Context& theCtx,
58                             const Graphic3d_MaterialAspect& theMat,
59                             const Quantity_Color& theInteriorColor)
60 {
61   Common.ChangeShine()        = 128.0f * theMat.Shininess();
62   Common.ChangeTransparency() = theMat.Alpha();
63
64   Pbr.ChangeMetallic()  = theMat.PBRMaterial().Metallic();
65   Pbr.ChangeRoughness() = theMat.PBRMaterial().NormalizedRoughness();
66   Pbr.EmissionIOR = Graphic3d_Vec4 (theMat.PBRMaterial().Emission(), theMat.PBRMaterial().IOR());
67
68   const OpenGl_Vec3& aSrcAmb = theMat.AmbientColor();
69   const OpenGl_Vec3& aSrcDif = theMat.DiffuseColor();
70   const OpenGl_Vec3& aSrcSpe = theMat.SpecularColor();
71   const OpenGl_Vec3& aSrcEms = theMat.EmissiveColor();
72   Common.Specular.SetValues (aSrcSpe, 1.0f); // interior color is ignored for Specular
73   switch (theMat.MaterialType())
74   {
75     case Graphic3d_MATERIAL_ASPECT:
76     {
77       Common.Ambient .SetValues (aSrcAmb * theInteriorColor, 1.0f);
78       Common.Diffuse .SetValues (aSrcDif * theInteriorColor, 1.0f);
79       Common.Emission.SetValues (aSrcEms * theInteriorColor, 1.0f);
80       Pbr  .BaseColor.SetValues (theInteriorColor, theMat.Alpha());
81       break;
82     }
83     case Graphic3d_MATERIAL_PHYSIC:
84     {
85       Common.Ambient .SetValues (aSrcAmb, 1.0f);
86       Common.Diffuse .SetValues (aSrcDif, 1.0f);
87       Common.Emission.SetValues (aSrcEms, 1.0f);
88       Pbr.BaseColor = theMat.PBRMaterial().Color();
89       break;
90     }
91   }
92
93   Common.Ambient  = theCtx.Vec4FromQuantityColor (Common.Ambient);
94   Common.Diffuse  = theCtx.Vec4FromQuantityColor (Common.Diffuse);
95   Common.Specular = theCtx.Vec4FromQuantityColor (Common.Specular);
96   Common.Emission = theCtx.Vec4FromQuantityColor (Common.Emission);
97 }
98
99 // =======================================================================
100 // function : OpenGl_Workspace
101 // purpose  :
102 // =======================================================================
103 OpenGl_Workspace::OpenGl_Workspace (OpenGl_View* theView, const Handle(OpenGl_Window)& theWindow)
104 : myView (theView),
105   myWindow (theWindow),
106   myGlContext (!theWindow.IsNull() ? theWindow->GetGlContext() : NULL),
107   myUseZBuffer    (Standard_True),
108   myUseDepthWrite (Standard_True),
109   //
110   myNbSkippedTranspElems (0),
111   myRenderFilter (OpenGl_RenderFilter_Empty),
112   //
113   myAspectsSet (&myDefaultAspects),
114   //
115   ViewMatrix_applied (&myDefaultMatrix),
116   StructureMatrix_applied (&myDefaultMatrix),
117   myToAllowFaceCulling (false),
118   myModelViewMatrix (myDefaultMatrix)
119 {
120   if (!myGlContext.IsNull() && myGlContext->MakeCurrent())
121   {
122     myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
123
124     // General initialization of the context
125   #if !defined(GL_ES_VERSION_2_0)
126     if (myGlContext->core11 != NULL)
127     {
128       // enable two-side lighting by default
129       glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
130       glHint (GL_POINT_SMOOTH_HINT, GL_FASTEST);
131       if (myGlContext->caps->ffpEnable)
132       {
133         glHint (GL_FOG_HINT, GL_FASTEST);
134       }
135     }
136
137     glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
138     glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
139     if (myGlContext->Vendor() == "microsoft corporation"
140     && !myGlContext->IsGlGreaterEqual (1, 2))
141     {
142       // this software implementation causes too slow rendering into GL_FRONT on modern Windows
143       theView->SetImmediateModeDrawToFront (false);
144     }
145   #endif
146   }
147
148   myNoneCulling .Aspect()->SetSuppressBackFaces (false);
149   myNoneCulling .Aspect()->SetDrawEdges (false);
150   myNoneCulling .Aspect()->SetAlphaMode (Graphic3d_AlphaMode_Opaque);
151
152   myFrontCulling.Aspect()->SetSuppressBackFaces (true);
153   myFrontCulling.Aspect()->SetDrawEdges (false);
154   myFrontCulling.Aspect()->SetAlphaMode (Graphic3d_AlphaMode_Opaque);
155 }
156
157 // =======================================================================
158 // function : Activate
159 // purpose  :
160 // =======================================================================
161 Standard_Boolean OpenGl_Workspace::Activate()
162 {
163   if (myWindow.IsNull() || !myWindow->Activate())
164   {
165     return Standard_False;
166   }
167
168   ViewMatrix_applied      = &myDefaultMatrix;
169   StructureMatrix_applied = &myDefaultMatrix;
170
171   ResetAppliedAspect();
172
173   // reset state for safety
174   myGlContext->BindProgram (Handle(OpenGl_ShaderProgram)());
175   if (myGlContext->core20fwd != NULL)
176   {
177     myGlContext->core20fwd->glUseProgram (OpenGl_ShaderProgram::NO_PROGRAM);
178   }
179   if (myGlContext->caps->ffpEnable)
180   {
181     myGlContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
182   }
183   return Standard_True;
184 }
185
186 //=======================================================================
187 //function : ResetAppliedAspect
188 //purpose  : Sets default values of GL parameters in accordance with default aspects
189 //=======================================================================
190 void OpenGl_Workspace::ResetAppliedAspect()
191 {
192   myGlContext->BindDefaultVao();
193
194   myHighlightStyle.Nullify();
195   myToAllowFaceCulling  = false;
196   myAspectsSet = &myDefaultAspects;
197   myAspectsApplied.Nullify();
198   myGlContext->SetPolygonOffset (Graphic3d_PolygonOffset());
199
200   ApplyAspects();
201   myGlContext->SetLineStipple(myDefaultAspects.Aspect()->LinePattern());
202   myGlContext->SetLineWidth  (myDefaultAspects.Aspect()->LineWidth());
203   if (myGlContext->core15fwd != NULL)
204   {
205     myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
206   }
207 }
208
209 // =======================================================================
210 // function : SetDefaultPolygonOffset
211 // purpose  :
212 // =======================================================================
213 Graphic3d_PolygonOffset OpenGl_Workspace::SetDefaultPolygonOffset (const Graphic3d_PolygonOffset& theOffset)
214 {
215   Graphic3d_PolygonOffset aPrev = myDefaultAspects.Aspect()->PolygonOffset();
216   myDefaultAspects.Aspect()->SetPolygonOffset (theOffset);
217   if (myAspectsApplied == myDefaultAspects.Aspect()
218    || myAspectsApplied.IsNull()
219    || (myAspectsApplied->PolygonOffset().Mode & Aspect_POM_None) == Aspect_POM_None)
220   {
221     myGlContext->SetPolygonOffset (theOffset);
222   }
223   return aPrev;
224 }
225
226 // =======================================================================
227 // function : SetAspects
228 // purpose  :
229 // =======================================================================
230 const OpenGl_Aspects* OpenGl_Workspace::SetAspects (const OpenGl_Aspects* theAspect)
231 {
232   const OpenGl_Aspects* aPrevAspects = myAspectsSet;
233   myAspectsSet = theAspect;
234   return aPrevAspects;
235 }
236
237 // =======================================================================
238 // function : ApplyAspects
239 // purpose  :
240 // =======================================================================
241 const OpenGl_Aspects* OpenGl_Workspace::ApplyAspects (bool theToBindTextures)
242 {
243   if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
244   {
245     bool toSuppressBackFaces = myToAllowFaceCulling
246                             && myAspectsSet->Aspect()->ToSuppressBackFaces();
247     if (toSuppressBackFaces)
248     {
249       if (myAspectsSet->Aspect()->InteriorStyle() == Aspect_IS_HATCH
250        || myAspectsSet->Aspect()->AlphaMode() == Graphic3d_AlphaMode_Blend
251        || myAspectsSet->Aspect()->AlphaMode() == Graphic3d_AlphaMode_Mask
252        || (myAspectsSet->Aspect()->AlphaMode() == Graphic3d_AlphaMode_BlendAuto
253         && myAspectsSet->Aspect()->FrontMaterial().Transparency() != 0.0f))
254       {
255         // disable culling in case of translucent shading aspect
256         toSuppressBackFaces = false;
257       }
258     }
259     myGlContext->SetCullBackFaces (toSuppressBackFaces);
260   }
261
262   if (myAspectsSet->Aspect() == myAspectsApplied
263    && myHighlightStyle == myAspectFaceAppliedWithHL)
264   {
265     return myAspectsSet;
266   }
267   myAspectFaceAppliedWithHL = myHighlightStyle;
268
269   // Aspect_POM_None means: do not change current settings
270   if ((myAspectsSet->Aspect()->PolygonOffset().Mode & Aspect_POM_None) != Aspect_POM_None)
271   {
272     myGlContext->SetPolygonOffset (myAspectsSet->Aspect()->PolygonOffset());
273   }
274
275   const Aspect_InteriorStyle anIntstyle = myAspectsSet->Aspect()->InteriorStyle();
276   if (myAspectsApplied.IsNull()
277    || myAspectsApplied->InteriorStyle() != anIntstyle)
278   {
279   #if !defined(GL_ES_VERSION_2_0)
280     myGlContext->SetPolygonMode (anIntstyle == Aspect_IS_POINT ? GL_POINT : GL_FILL);
281     myGlContext->SetPolygonHatchEnabled (anIntstyle == Aspect_IS_HATCH);
282   #endif
283   }
284
285 #if !defined(GL_ES_VERSION_2_0)
286   if (anIntstyle == Aspect_IS_HATCH)
287   {
288     myGlContext->SetPolygonHatchStyle (myAspectsSet->Aspect()->HatchStyle());
289   }
290 #endif
291
292   // Case of hidden line
293   if (anIntstyle == Aspect_IS_HIDDENLINE)
294   {
295     // copy all values including line edge aspect
296     *myAspectFaceHl.Aspect() = *myAspectsSet->Aspect();
297     myAspectFaceHl.Aspect()->SetShadingModel (Graphic3d_TOSM_UNLIT);
298     myAspectFaceHl.Aspect()->SetInteriorColor (myView->BackgroundColor().GetRGB());
299     myAspectFaceHl.Aspect()->SetDistinguish (false);
300     myAspectFaceHl.SetNoLighting();
301     myAspectsSet = &myAspectFaceHl;
302   }
303   else
304   {
305     myGlContext->SetShadingMaterial (myAspectsSet, myHighlightStyle);
306   }
307
308   if (theToBindTextures)
309   {
310     const Handle(OpenGl_TextureSet)& aTextureSet = TextureSet();
311     myGlContext->BindTextures (aTextureSet, Handle(OpenGl_ShaderProgram)());
312   }
313
314   if ((myView->myShadingModel == Graphic3d_TOSM_PBR
315     || myView->myShadingModel == Graphic3d_TOSM_PBR_FACET)
316    && !myView->myPBREnvironment.IsNull()
317    &&  myView->myPBREnvironment->IsNeededToBeBound())
318   {
319     myView->myPBREnvironment->Bind (myGlContext);
320   }
321
322   myAspectsApplied = myAspectsSet->Aspect();
323   return myAspectsSet;
324 }
325
326 // =======================================================================
327 // function : Width
328 // purpose  :
329 // =======================================================================
330 Standard_Integer OpenGl_Workspace::Width()  const
331 {
332   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
333 }
334
335 // =======================================================================
336 // function : Height
337 // purpose  :
338 // =======================================================================
339 Standard_Integer OpenGl_Workspace::Height() const
340 {
341   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
342 }
343
344 // =======================================================================
345 // function : FBOCreate
346 // purpose  :
347 // =======================================================================
348 Handle(OpenGl_FrameBuffer) OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
349                                                         const Standard_Integer theHeight)
350 {
351   // activate OpenGL context
352   if (!Activate())
353     return Handle(OpenGl_FrameBuffer)();
354
355   // create the FBO
356   const Handle(OpenGl_Context)& aCtx = GetGlContext();
357   aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
358   Handle(OpenGl_FrameBuffer) aFrameBuffer = new OpenGl_FrameBuffer();
359   if (!aFrameBuffer->Init (aCtx, theWidth, theHeight, GL_SRGB8_ALPHA8, GL_DEPTH24_STENCIL8, 0))
360   {
361     aFrameBuffer->Release (aCtx.operator->());
362     return Handle(OpenGl_FrameBuffer)();
363   }
364   return aFrameBuffer;
365 }
366
367 // =======================================================================
368 // function : FBORelease
369 // purpose  :
370 // =======================================================================
371 void OpenGl_Workspace::FBORelease (Handle(OpenGl_FrameBuffer)& theFbo)
372 {
373   // activate OpenGL context
374   if (!Activate()
375    || theFbo.IsNull())
376   {
377     return;
378   }
379
380   theFbo->Release (GetGlContext().operator->());
381   theFbo.Nullify();
382 }
383
384 // =======================================================================
385 // function : BufferDump
386 // purpose  :
387 // =======================================================================
388 Standard_Boolean OpenGl_Workspace::BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo,
389                                                Image_PixMap&                     theImage,
390                                                const Graphic3d_BufferType&       theBufferType)
391 {
392   return !theImage.IsEmpty()
393       && Activate()
394       && OpenGl_FrameBuffer::BufferDump (GetGlContext(), theFbo, theImage, theBufferType);
395 }
396
397 // =======================================================================
398 // function : ShouldRender
399 // purpose  :
400 // =======================================================================
401 bool OpenGl_Workspace::ShouldRender (const OpenGl_Element* theElement)
402 {
403   // render only non-raytracable elements when RayTracing is enabled
404   if ((myRenderFilter & OpenGl_RenderFilter_NonRaytraceableOnly) != 0)
405   {
406     if (OpenGl_Raytrace::IsRaytracedElement (theElement))
407     {
408       return false;
409     }
410   }
411   else if ((myRenderFilter & OpenGl_RenderFilter_FillModeOnly) != 0)
412   {
413     if (!theElement->IsFillDrawMode())
414     {
415       return false;
416     }
417   }
418
419   // handle opaque/transparency render passes
420   if ((myRenderFilter & OpenGl_RenderFilter_OpaqueOnly) != 0)
421   {
422     if (!theElement->IsFillDrawMode())
423     {
424       return true;
425     }
426
427     if (OpenGl_Context::CheckIsTransparent (myAspectsSet, myHighlightStyle))
428     {
429       ++myNbSkippedTranspElems;
430       return false;
431     }
432   }
433   else if ((myRenderFilter & OpenGl_RenderFilter_TransparentOnly) != 0)
434   {
435     if (!theElement->IsFillDrawMode())
436     {
437       if (dynamic_cast<const OpenGl_Aspects*> (theElement) == NULL)
438       {
439         return false;
440       }
441     }
442     else if (!OpenGl_Context::CheckIsTransparent (myAspectsSet, myHighlightStyle))
443     {
444       return false;
445     }
446   }
447   return true;
448 }
449
450 // =======================================================================
451 // function : DumpJson
452 // purpose  :
453 // =======================================================================
454 void OpenGl_Workspace::DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth) const
455 {
456   OCCT_DUMP_TRANSIENT_CLASS_BEGIN (theOStream)
457
458   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myUseZBuffer)
459   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myUseDepthWrite)
460
461   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myNoneCulling)
462   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myFrontCulling)
463
464   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myNbSkippedTranspElems)
465   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myRenderFilter)
466
467   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myDefaultAspects)
468
469   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, myAspectsSet)
470   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, myAspectsApplied.get())
471
472   OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, myToAllowFaceCulling)
473
474   OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &myAspectFaceHl)
475 }