From 4a154d9c4ee5f60dacafa7107494ea89282382ea Mon Sep 17 00:00:00 2001 From: Luke Benstead Date: Thu, 31 May 2018 09:38:34 +0100 Subject: [PATCH] Add a near-z line clipping function in preparation for implementing near-z clipping --- GL/clip.c | 34 ++++++++++++++++++++++++++++++++++ GL/clip.h | 22 ++++++++++++++++++++++ GL/private.h | 2 +- Makefile | 2 +- 4 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 GL/clip.c create mode 100644 GL/clip.h diff --git a/GL/clip.c b/GL/clip.c new file mode 100644 index 0000000..a5c101d --- /dev/null +++ b/GL/clip.c @@ -0,0 +1,34 @@ +#include +#include "clip.h" + +ClipResult clipLineToNearZ(const float* v1, const float* v2, const float dist, float* vout, float* t) { + if(v1[2] < dist && v2[2] < dist) { + // Both behind, no clipping + return CLIP_RESULT_ALL_BEHIND; + } + + if(v1[2] > dist && v2[2] > dist) { + return CLIP_RESULT_ALL_IN_FRONT; + } + + float vec [] = {v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]}; + + /* + * The plane normal will always be pointing down the negative Z so we can simplify the dot products as x and y will always be zero + * the resulting calculation will result in simply -z of the vector + */ + float vecDotP = -vec[2]; + + /* If the dot product is zero there is no intersection */ + if(vecDotP > FLT_MIN || vecDotP < -FLT_MIN) { + *t = (-(dist - v1[2])) / vecDotP; + + vout[0] = v1[0] + (vec[0] * (*t)); + vout[1] = v1[1] + (vec[1] * (*t)); + vout[2] = v1[2] + (vec[2] * (*t)); + + return (v1[2] >= dist) ? CLIP_RESULT_FRONT_TO_BACK : CLIP_RESULT_BACK_TO_FRONT; + } else { + return CLIP_RESULT_ALL_ON_PLANE; + } +} diff --git a/GL/clip.h b/GL/clip.h new file mode 100644 index 0000000..c6a496b --- /dev/null +++ b/GL/clip.h @@ -0,0 +1,22 @@ +#ifndef CLIP_H +#define CLIP_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + CLIP_RESULT_ALL_IN_FRONT, + CLIP_RESULT_ALL_BEHIND, + CLIP_RESULT_ALL_ON_PLANE, + CLIP_RESULT_FRONT_TO_BACK, + CLIP_RESULT_BACK_TO_FRONT +} ClipResult; + +ClipResult clipLineToNearZ(const float* v1, const float* v2, const float dist, float* vout, float* t); + +#ifdef __cplusplus +} +#endif + +#endif // CLIP_H diff --git a/GL/private.h b/GL/private.h index 5f837c1..eac62de 100644 --- a/GL/private.h +++ b/GL/private.h @@ -4,7 +4,7 @@ #include "../include/gl.h" #include "../containers/aligned_vector.h" #include "../containers/named_array.h" - +#include "./clip.h" #define TRACE_ENABLED 0 #define TRACE() if(TRACE_ENABLED) {fprintf(stderr, "%s\n", __func__);} diff --git a/Makefile b/Makefile index 5dc4723..4f25a13 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ TARGET = libGLdc.a OBJS = GL/draw.o GL/flush.o GL/framebuffer.o GL/immediate.o GL/lighting.o GL/state.o GL/texture.o GL/glu.o -OBJS += GL/matrix.o GL/fog.o GL/error.o containers/stack.o containers/named_array.o containers/aligned_vector.o +OBJS += GL/matrix.o GL/fog.o GL/error.o GL/clip.o containers/stack.o containers/named_array.o containers/aligned_vector.o SUBDIRS =