From 4fa135daf0981202afd48b99253d0caa26d2e8dd Mon Sep 17 00:00:00 2001
From: Alexander Rose <alexander.rose@weirdbyte.de>
Date: Sat, 18 Feb 2023 11:33:36 -0800
Subject: [PATCH] fix near clipping avoidance in impostor shaders

---
 CHANGELOG.md                        | 1 +
 src/mol-gl/shader/cylinders.vert.ts | 8 +++++---
 src/mol-gl/shader/spheres.vert.ts   | 8 +++++---
 3 files changed, 11 insertions(+), 6 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7948192c6..3fab9bea4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Note that since we don't clearly distinguish between a public and private interf
 
 Fix impostor bond visuals not correctly updating on `sizeFactor` changes
 Fix degenerate case in PCA
+Fix near clipping avoidance in impostor shaders
 
 ## [v3.31.2] - 2023-02-12
 
diff --git a/src/mol-gl/shader/cylinders.vert.ts b/src/mol-gl/shader/cylinders.vert.ts
index 60b3f1932..c5f9d66a1 100644
--- a/src/mol-gl/shader/cylinders.vert.ts
+++ b/src/mol-gl/shader/cylinders.vert.ts
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2020-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ * Copyright (c) 2020-2023 mol* contributors, licensed under MIT, See LICENSE file for more info.
  *
  * @author Alexander Rose <alexander.rose@weirdbyte.de>
  */
@@ -71,8 +71,10 @@ void main() {
     vViewPosition = mvPosition.xyz;
     gl_Position = uProjection * mvPosition;
 
-    mvPosition.z -= 2.0 * (length(vEnd - vStart) + vSize); // avoid clipping
-    gl_Position.z = (uProjection * mvPosition).z;
+    if (gl_Position.z < -gl_Position.w) {
+        mvPosition.z -= 2.0 * (length(vEnd - vStart) + vSize); // avoid clipping
+        gl_Position.z = (uProjection * mvPosition).z;
+    }
 
     #include clip_instance
 }
diff --git a/src/mol-gl/shader/spheres.vert.ts b/src/mol-gl/shader/spheres.vert.ts
index 70a3daf72..387885098 100644
--- a/src/mol-gl/shader/spheres.vert.ts
+++ b/src/mol-gl/shader/spheres.vert.ts
@@ -1,5 +1,5 @@
 /**
- * Copyright (c) 2019-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
+ * Copyright (c) 2019-2023 mol* contributors, licensed under MIT, See LICENSE file for more info.
  *
  * @author Alexander Rose <alexander.rose@weirdbyte.de>
  */
@@ -96,8 +96,10 @@ void main(void){
 
     vModelPosition = (uModel * aTransform * position4).xyz; // for clipping in frag shader
 
-    mvPosition.z -= 2.0 * vRadius; // avoid clipping
-    gl_Position.z = (uProjection * vec4(mvPosition.xyz, 1.0)).z;
+    if (gl_Position.z < -gl_Position.w) {
+        mvPosition.z -= 2.0 * vRadius; // avoid clipping
+        gl_Position.z = (uProjection * vec4(mvPosition.xyz, 1.0)).z;
+    }
 
     #include clip_instance
 }
-- 
GitLab