From 0c90253a5dddc5da1ca056773eaae1a16ca53836 Mon Sep 17 00:00:00 2001
From: "alexey.lysiuk" <alexey.lysiuk@gmail.com>
Date: Tue, 30 May 2017 13:01:51 +0300
Subject: [PATCH] Fixed potentially broken portal rendering after OpenGL
 context change

https://forum.zdoom.org/viewtopic.php?t=56393
---
 src/gl/renderer/gl_renderer.cpp |  5 +++++
 src/gl/scene/gl_portal.cpp      | 16 +++++++++++++++-
 src/gl/scene/gl_portal.h        |  3 +++
 3 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/src/gl/renderer/gl_renderer.cpp b/src/gl/renderer/gl_renderer.cpp
index 51fbd1f90..77d8d6bc3 100644
--- a/src/gl/renderer/gl_renderer.cpp
+++ b/src/gl/renderer/gl_renderer.cpp
@@ -50,6 +50,7 @@
 #include "gl/data/gl_data.h"
 #include "gl/data/gl_vertexbuffer.h"
 #include "gl/scene/gl_drawinfo.h"
+#include "gl/scene/gl_portal.h"
 #include "gl/shaders/gl_shader.h"
 #include "gl/shaders/gl_ambientshader.h"
 #include "gl/shaders/gl_bloomshader.h"
@@ -184,10 +185,14 @@ void FGLRenderer::Initialize(int width, int height)
 	mShaderManager = new FShaderManager;
 	mSamplerManager = new FSamplerManager;
 	gl_LoadModels();
+
+	GLPortal::Initialize();
 }
 
 FGLRenderer::~FGLRenderer() 
 {
+	GLPortal::Shutdown();
+
 	gl_FlushModels();
 	AActor::DeleteAllAttachedLights();
 	FMaterial::FlushAll();
diff --git a/src/gl/scene/gl_portal.cpp b/src/gl/scene/gl_portal.cpp
index 93073d722..b5671923f 100644
--- a/src/gl/scene/gl_portal.cpp
+++ b/src/gl/scene/gl_portal.cpp
@@ -205,7 +205,6 @@ bool GLPortal::Start(bool usestencil, bool doquery)
 				else if (gl_noquery) doquery = false;
 
 				// If occlusion query is supported let's use it to avoid rendering portals that aren't visible
-				if (!QueryObject && doquery) glGenQueries(1, &QueryObject);
 				if (QueryObject)
 				{
 					glBeginQuery(GL_SAMPLES_PASSED, QueryObject);
@@ -1264,6 +1263,21 @@ void GLEEHorizonPortal::DrawContents()
 
 }
 
+void GLPortal::Initialize()
+{
+	assert(0 == QueryObject);
+	glGenQueries(1, &QueryObject);
+}
+
+void GLPortal::Shutdown()
+{
+	if (0 != QueryObject)
+	{
+		glDeleteQueries(1, &QueryObject);
+		QueryObject = 0;
+	}
+}
+
 const char *GLSkyPortal::GetName() { return "Sky"; }
 const char *GLSkyboxPortal::GetName() { return "Skybox"; }
 const char *GLSectorStackPortal::GetName() { return "Sectorstack"; }
diff --git a/src/gl/scene/gl_portal.h b/src/gl/scene/gl_portal.h
index 128db2dc8..9ef8cf5f7 100644
--- a/src/gl/scene/gl_portal.h
+++ b/src/gl/scene/gl_portal.h
@@ -177,6 +177,9 @@ public:
 	static bool RenderFirstSkyPortal(int recursion);
 	static void EndFrame();
 	static GLPortal * FindPortal(const void * src);
+
+	static void Initialize();
+	static void Shutdown();
 };
 
 struct GLLinePortal : public GLPortal