From d5fe5586a0b6da98fa9f2bc8498afc06b9c89440 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gustaf=20Alh=C3=A4ll?= <gustaf@hanicef.me>
Date: Mon, 1 Jan 2024 19:36:27 +0100
Subject: [PATCH] Retain skybox and horizon line order

---
 src/hardware/hw_batching.c | 14 ++++++++++----
 src/hardware/hw_batching.h |  2 +-
 2 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/src/hardware/hw_batching.c b/src/hardware/hw_batching.c
index 0e3942761..d15db8aa5 100644
--- a/src/hardware/hw_batching.c
+++ b/src/hardware/hw_batching.c
@@ -116,15 +116,20 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt
 		polygonArray[polygonArraySize].texture = current_texture;
 		polygonArray[polygonArraySize].shader = shader;
 		polygonArray[polygonArraySize].horizonSpecial = horizonSpecial;
-		polygonArray[polygonArraySize].hash = 0;
+		// default to polygonArraySize so we don't lose order on horizon lines
+		// (yes, it's supposed to be negative, since we're sorting in that direction)
+		polygonArray[polygonArraySize].hash = -polygonArraySize;
 		polygonArraySize++;
 
 		if (!(PolyFlags & PF_NoTexture) && !horizonSpecial)
 		{
 			// use FNV-1a to hash polygons for later sorting.
-			int32_t hash = 0x811c9dc5;
+			INT32 hash = 0x811c9dc5;
 #define DIGEST(h, x) h ^= (x); h *= 0x01000193
-			DIGEST(hash, current_texture->downloaded);
+			if (current_texture)
+			{
+				DIGEST(hash, current_texture->downloaded);
+			}
 			DIGEST(hash, PolyFlags);
 			DIGEST(hash, pSurf->PolyColor.rgba);
 			if (cv_glshaders.value && gl_shadersavailable)
@@ -137,7 +142,8 @@ void HWR_ProcessPolygon(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT iNumPt
 				DIGEST(hash, pSurf->LightInfo.fade_end);
 			}
 #undef DIGEST
-			polygonArray[polygonArraySize-1].hash = hash;
+			// remove the sign bit to ensure that skybox and horizon line comes first.
+			polygonArray[polygonArraySize-1].hash = (hash & INT32_MAX);
 		}
 
 		memcpy(&unsortedVertexArray[unsortedVertexArraySize], pOutVerts, iNumPts * sizeof(FOutVector));
diff --git a/src/hardware/hw_batching.h b/src/hardware/hw_batching.h
index 4351737e3..df1a4c38b 100644
--- a/src/hardware/hw_batching.h
+++ b/src/hardware/hw_batching.h
@@ -26,7 +26,7 @@ typedef struct
 	int shader;
 	// this tells batching that the plane belongs to a horizon line and must be drawn in correct order with the skywalls
 	boolean horizonSpecial;
-	uint32_t hash;
+	INT32 hash;
 } PolygonArrayEntry;
 
 void HWR_StartBatching(void);
-- 
GitLab