]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - dpsoftrast.c
Change shader permutation flags to 64bit.
[xonotic/darkplaces.git] / dpsoftrast.c
index aff3befeb399e0075ed15a031d815810d4742baf..d9c72720449bd3a245da6397b5b873cb0c0da729 100644 (file)
@@ -3,15 +3,11 @@
 #define _USE_MATH_DEFINES
 #include <math.h>
 #include "quakedef.h"
+#include "thread.h"
 #include "dpsoftrast.h"
 
-#ifdef USE_SDL
-#define USE_THREADS
-#endif
-
-#ifdef USE_THREADS
-#include <SDL.h>
-#include <SDL_thread.h>
+#ifdef _MSC_VER
+#pragma warning(disable : 4324)
 #endif
 
 #ifndef __cplusplus
@@ -19,59 +15,88 @@ typedef qboolean bool;
 #endif
 
 #define ALIGN_SIZE 16
-#define ATOMIC_SIZE 32
+#define ATOMIC_SIZE 4
 
-#ifdef SSE2_PRESENT
-       #if defined(__GNUC__)
+#ifdef SSE_POSSIBLE
+       #if defined(__APPLE__)
+               #include <libkern/OSAtomic.h>
+               #define ALIGN(var) var __attribute__((__aligned__(16)))
+               #define ATOMIC(var) var __attribute__((__aligned__(4)))
+               #define MEMORY_BARRIER (_mm_sfence())
+               #define ATOMIC_COUNTER volatile int32_t 
+               #define ATOMIC_INCREMENT(counter) (OSAtomicIncrement32Barrier(&(counter)))
+               #define ATOMIC_DECREMENT(counter) (OSAtomicDecrement32Barrier(&(counter)))
+               #define ATOMIC_ADD(counter, val) ((void)OSAtomicAdd32Barrier((val), &(counter)))
+       #elif defined(__GNUC__) && defined(WIN32)
+               #define ALIGN(var) var __attribute__((__aligned__(16)))
+               #define ATOMIC(var) var __attribute__((__aligned__(4)))
+               #define MEMORY_BARRIER (_mm_sfence())
+               //(__sync_synchronize())
+               #define ATOMIC_COUNTER volatile LONG
+               // this LONG * cast serves to fix an issue with broken mingw
+               // packages on Ubuntu; these only declare the function to take
+               // a LONG *, causing a compile error here. This seems to be
+               // error- and warn-free on platforms that DO declare
+               // InterlockedIncrement correctly, like mingw on Windows.
+               #define ATOMIC_INCREMENT(counter) (InterlockedIncrement((LONG *) &(counter)))
+               #define ATOMIC_DECREMENT(counter) (InterlockedDecrement((LONG *) &(counter)))
+               #define ATOMIC_ADD(counter, val) ((void)InterlockedExchangeAdd((LONG *) &(counter), (val)))
+       #elif defined(__GNUC__)
                #define ALIGN(var) var __attribute__((__aligned__(16)))
-               #define ATOMIC(var) var __attribute__((__aligned__(32)))
-               #ifdef USE_THREADS
-                       #define MEMORY_BARRIER (_mm_sfence())
-                       //(__sync_synchronize())
-                       #define ATOMIC_COUNTER volatile int
-                       #define ATOMIC_INCREMENT(counter) (__sync_add_and_fetch(&(counter), 1))
-                       #define ATOMIC_DECREMENT(counter) (__sync_add_and_fetch(&(counter), -1))
-                       #define ATOMIC_ADD(counter, val) ((void)__sync_fetch_and_add(&(counter), (val)))
-               #endif
+               #define ATOMIC(var) var __attribute__((__aligned__(4)))
+               #define MEMORY_BARRIER (_mm_sfence())
+               //(__sync_synchronize())
+               #define ATOMIC_COUNTER volatile int
+               #define ATOMIC_INCREMENT(counter) (__sync_add_and_fetch(&(counter), 1))
+               #define ATOMIC_DECREMENT(counter) (__sync_add_and_fetch(&(counter), -1))
+               #define ATOMIC_ADD(counter, val) ((void)__sync_fetch_and_add(&(counter), (val)))
        #elif defined(_MSC_VER)
                #define ALIGN(var) __declspec(align(16)) var
-               #define ATOMIC(var) __declspec(align(32)) var
-               #ifdef USE_THREADS
-                       #define MEMORY_BARRIER (_mm_sfence())
-                       //(MemoryBarrier())
-                       #define ATOMIC_COUNTER volatile LONG
-                       #define ATOMIC_INCREMENT(counter) (InterlockedIncrement(&(counter)))
-                       #define ATOMIC_DECREMENT(counter) (InterlockedDecrement(&(counter)))
-                       #define ATOMIC_ADD(counter, val) (InterlockedExchangeAdd(&(counter), (val)))
-               #endif
-       #else
-               #undef USE_THREADS
-               #undef SSE2_PRESENT
+               #define ATOMIC(var) __declspec(align(4)) var
+               #define MEMORY_BARRIER (_mm_sfence())
+               //(MemoryBarrier())
+               #define ATOMIC_COUNTER volatile LONG
+               #define ATOMIC_INCREMENT(counter) (InterlockedIncrement(&(counter)))
+               #define ATOMIC_DECREMENT(counter) (InterlockedDecrement(&(counter)))
+               #define ATOMIC_ADD(counter, val) ((void)InterlockedExchangeAdd(&(counter), (val)))
        #endif
 #endif
 
-#ifndef SSE2_PRESENT
-       #define ALIGN(var) var
-       #define ATOMIC(var) var
+#ifndef ALIGN
+#define ALIGN(var) var
 #endif
-
-#ifndef USE_THREADS
-       #define MEMORY_BARRIER ((void)0)
-       #define ATOMIC_COUNTER int
-       #define ATOMIC_INCREMENT(counter) (++(counter))
-       #define ATOMIC_DECREMENT(counter) (--(counter))
-       #define ATOMIC_ADD(counter, val) ((void)((counter) += (val)))
+#ifndef ATOMIC
+#define ATOMIC(var) var
+#endif
+#ifndef MEMORY_BARRIER
+#define MEMORY_BARRIER ((void)0)
+#endif
+#ifndef ATOMIC_COUNTER
+#define ATOMIC_COUNTER int
+#endif
+#ifndef ATOMIC_INCREMENT
+#define ATOMIC_INCREMENT(counter) (++(counter))
+#endif
+#ifndef ATOMIC_DECREMENT
+#define ATOMIC_DECREMENT(counter) (--(counter))
+#endif
+#ifndef ATOMIC_ADD
+#define ATOMIC_ADD(counter, val) ((void)((counter) += (val)))
 #endif
 
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
 #include <emmintrin.h>
 
-#define MM_MALLOC(size) _mm_malloc(size, ATOMIC_SIZE)
+#if defined(__GNUC__) && (__GNUC < 4 || __GNUC_MINOR__ < 6) && !defined(__clang__)
+       #define _mm_cvtss_f32(val) (__builtin_ia32_vec_ext_v4sf ((__v4sf)(val), 0))
+#endif
+
+#define MM_MALLOC(size) _mm_malloc(size, ALIGN_SIZE)
 
 static void *MM_CALLOC(size_t nmemb, size_t size)
 {
-       void *ptr = _mm_malloc(nmemb*size, ATOMIC_SIZE);
-       if(ptr != NULL) memset(ptr, 0, nmemb*size);
+       void *ptr = _mm_malloc(nmemb*size, ALIGN_SIZE);
+       if (ptr != NULL) memset(ptr, 0, nmemb*size);
        return ptr;
 }
 
@@ -138,15 +163,15 @@ enum { DPSOFTRAST_OPCODE_Reset = 0 };
 #define DPSOFTRAST_DRAW_MAXCOMMANDPOOL 2097152
 #define DPSOFTRAST_DRAW_MAXCOMMANDSIZE 16384
 
-typedef ATOMIC(struct DPSOFTRAST_State_Command_Pool_s
+typedef ALIGN(struct DPSOFTRAST_State_Command_Pool_s
 {
        int freecommand;
        int usedcommands;
-       ATOMIC(unsigned char commands[DPSOFTRAST_DRAW_MAXCOMMANDPOOL]);
+       ALIGN(unsigned char commands[DPSOFTRAST_DRAW_MAXCOMMANDPOOL]);
 }
 DPSOFTRAST_State_Command_Pool);
 
-typedef ATOMIC(struct DPSOFTRAST_State_Triangle_s
+typedef ALIGN(struct DPSOFTRAST_State_Triangle_s
 {
        unsigned char mip[DPSOFTRAST_MAXTEXTUREUNITS]; // texcoord to screen space density values (for picking mipmap of textures)
        float w[3];
@@ -178,15 +203,17 @@ typedef ALIGN(struct DPSOFTRAST_State_Span_s
        int triangle; // triangle this span was generated by
        int x; // framebuffer x coord
        int y; // framebuffer y coord
-       int length; // pixel count
        int startx; // usable range (according to pixelmask)
        int endx; // usable range (according to pixelmask)
        unsigned char *pixelmask; // true for pixels that passed depth test, false for others
+       int depthbase; // depthbuffer value at x (add depthslope*startx to get first pixel's depthbuffer value)
+       int depthslope; // depthbuffer value pixel delta
 }
 DPSOFTRAST_State_Span);
 
 #define DPSOFTRAST_DRAW_MAXSPANS 1024
 #define DPSOFTRAST_DRAW_MAXTRIANGLES 128
+#define DPSOFTRAST_DRAW_MAXSPANLENGTH 256
 
 #define DPSOFTRAST_VALIDATE_FB 1
 #define DPSOFTRAST_VALIDATE_DEPTHFUNC 2
@@ -204,15 +231,14 @@ typedef enum DPSOFTRAST_BLENDMODE_e
        DPSOFTRAST_BLENDMODE_MUL2,
        DPSOFTRAST_BLENDMODE_SUBALPHA,
        DPSOFTRAST_BLENDMODE_PSEUDOALPHA,
+       DPSOFTRAST_BLENDMODE_INVADD,
        DPSOFTRAST_BLENDMODE_TOTAL
 }
 DPSOFTRAST_BLENDMODE;
 
-typedef ATOMIC(struct DPSOFTRAST_State_Thread_s
+typedef ALIGN(struct DPSOFTRAST_State_Thread_s
 {
-#ifdef USE_THREADS
-       SDL_Thread *thread;
-#endif
+       void *thread;
        int index;
        
        int cullface;
@@ -223,16 +249,16 @@ typedef ATOMIC(struct DPSOFTRAST_State_Thread_s
        int depthtest;
        int depthfunc;
        int scissortest;
-       int alphatest;
-       int alphafunc;
-       float alphavalue;
        int viewport[4];
        int scissor[4];
        float depthrange[2];
        float polygonoffset[2];
+       float clipplane[4];
+       ALIGN(float fb_clipplane[4]);
 
        int shader_mode;
-       int shader_permutation;
+       dpuint64 shader_permutation;
+       int shader_exactspecularmath;
 
        DPSOFTRAST_Texture *texbound[DPSOFTRAST_MAXTEXTUREUNITS];
        
@@ -244,7 +270,7 @@ typedef ATOMIC(struct DPSOFTRAST_State_Thread_s
 
        // derived values (DPSOFTRAST_VALIDATE_FB)
        int fb_colormask;
-       int fb_clearscissor[4];
+       int fb_scissor[4];
        ALIGN(float fb_viewportcenter[4]);
        ALIGN(float fb_viewportscale[4]);
 
@@ -254,24 +280,29 @@ typedef ATOMIC(struct DPSOFTRAST_State_Thread_s
        // derived values (DPSOFTRAST_VALIDATE_BLENDFUNC)
        int fb_blendmode;
 
+       // band boundaries
+       int miny1;
+       int maxy1;
+       int miny2;
+       int maxy2;
+
        ATOMIC(volatile int commandoffset);
 
        volatile bool waiting;
        volatile bool starving;
-#ifdef USE_THREADS
-       SDL_cond *waitcond;
-       SDL_cond *drawcond;
-       SDL_mutex *drawmutex;
-#endif
+       void *waitcond;
+       void *drawcond;
+       void *drawmutex;
 
        int numspans;
        int numtriangles;
        DPSOFTRAST_State_Span spans[DPSOFTRAST_DRAW_MAXSPANS];
        DPSOFTRAST_State_Triangle triangles[DPSOFTRAST_DRAW_MAXTRIANGLES];
+       unsigned char pixelmaskarray[DPSOFTRAST_DRAW_MAXSPANLENGTH+4]; // LordHavoc: padded to allow some termination bytes
 }
 DPSOFTRAST_State_Thread);
 
-typedef ATOMIC(struct DPSOFTRAST_State_s
+typedef ALIGN(struct DPSOFTRAST_State_s
 {
        int fb_width;
        int fb_height;
@@ -305,7 +336,8 @@ typedef ATOMIC(struct DPSOFTRAST_State_s
        int drawclipped;
        
        int shader_mode;
-       int shader_permutation;
+       dpuint64 shader_permutation;
+       int shader_exactspecularmath;
 
        int texture_max;
        int texture_end;
@@ -317,6 +349,8 @@ typedef ATOMIC(struct DPSOFTRAST_State_s
        // error reporting
        const char *errorstring;
 
+       bool usethreads;
+       int interlace;
        int numthreads;
        DPSOFTRAST_State_Thread *threads;
 
@@ -332,7 +366,9 @@ DPSOFTRAST_State dpsoftrast;
 #define DPSOFTRAST_DEPTHOFFSET (128.0f)
 #define DPSOFTRAST_BGRA8_FROM_RGBA32F(r,g,b,a) (((int)(r * 255.0f + 0.5f) << 16) | ((int)(g * 255.0f + 0.5f) << 8) | (int)(b * 255.0f + 0.5f) | ((int)(a * 255.0f + 0.5f) << 24))
 #define DPSOFTRAST_DEPTH32_FROM_DEPTH32F(d) ((int)(DPSOFTRAST_DEPTHSCALE * (1-d)))
-#define DPSOFTRAST_DRAW_MAXSPANLENGTH 256
+
+static void DPSOFTRAST_Draw_DepthTest(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_State_Span *span);
+static void DPSOFTRAST_Draw_DepthWrite(const DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Span *span);
 
 static void DPSOFTRAST_RecalcViewport(const int *viewport, float *fb_viewportcenter, float *fb_viewportscale)
 {
@@ -346,6 +382,31 @@ static void DPSOFTRAST_RecalcViewport(const int *viewport, float *fb_viewportcen
        fb_viewportscale[0] = 1.0f;
 }
 
+static void DPSOFTRAST_RecalcThread(DPSOFTRAST_State_Thread *thread)
+{
+       if (dpsoftrast.interlace)
+       {
+               thread->miny1 = (thread->index*dpsoftrast.fb_height)/(2*dpsoftrast.numthreads);
+               thread->maxy1 = ((thread->index+1)*dpsoftrast.fb_height)/(2*dpsoftrast.numthreads);
+               thread->miny2 = ((dpsoftrast.numthreads+thread->index)*dpsoftrast.fb_height)/(2*dpsoftrast.numthreads);
+               thread->maxy2 = ((dpsoftrast.numthreads+thread->index+1)*dpsoftrast.fb_height)/(2*dpsoftrast.numthreads);
+       }
+       else
+       {
+               thread->miny1 = thread->miny2 = (thread->index*dpsoftrast.fb_height)/dpsoftrast.numthreads;
+               thread->maxy1 = thread->maxy2 = ((thread->index+1)*dpsoftrast.fb_height)/dpsoftrast.numthreads;
+       }
+}
+
+static void DPSOFTRAST_RecalcClipPlane(DPSOFTRAST_State_Thread *thread)
+{
+       thread->fb_clipplane[0] = thread->clipplane[0] / thread->fb_viewportscale[1];
+       thread->fb_clipplane[1] = thread->clipplane[1] / thread->fb_viewportscale[2];
+       thread->fb_clipplane[2] = thread->clipplane[2] / thread->fb_viewportscale[3];
+       thread->fb_clipplane[3] = thread->clipplane[3] / thread->fb_viewportscale[0];
+       thread->fb_clipplane[3] -= thread->fb_viewportcenter[1]*thread->fb_clipplane[0] + thread->fb_viewportcenter[2]*thread->fb_clipplane[1] + thread->fb_viewportcenter[3]*thread->fb_clipplane[2] + thread->fb_viewportcenter[0]*thread->fb_clipplane[3];
+}
+
 static void DPSOFTRAST_RecalcFB(DPSOFTRAST_State_Thread *thread)
 {
        // calculate framebuffer scissor, viewport, viewport clipped by scissor,
@@ -361,12 +422,14 @@ static void DPSOFTRAST_RecalcFB(DPSOFTRAST_State_Thread *thread)
        if (x2 > dpsoftrast.fb_width) x2 = dpsoftrast.fb_width;
        if (y1 < 0) y1 = 0;
        if (y2 > dpsoftrast.fb_height) y2 = dpsoftrast.fb_height;
-       thread->fb_clearscissor[0] = x1;
-       thread->fb_clearscissor[1] = y1;
-       thread->fb_clearscissor[2] = x2 - x1;
-       thread->fb_clearscissor[3] = y2 - y1;
+       thread->fb_scissor[0] = x1;
+       thread->fb_scissor[1] = y1;
+       thread->fb_scissor[2] = x2 - x1;
+       thread->fb_scissor[3] = y2 - y1;
 
        DPSOFTRAST_RecalcViewport(thread->viewport, thread->fb_viewportcenter, thread->fb_viewportscale);
+       DPSOFTRAST_RecalcClipPlane(thread);
+       DPSOFTRAST_RecalcThread(thread);
 }
 
 static void DPSOFTRAST_RecalcDepthFunc(DPSOFTRAST_State_Thread *thread)
@@ -382,7 +445,7 @@ static void DPSOFTRAST_RecalcBlendFunc(DPSOFTRAST_State_Thread *thread)
                {
                #define BLENDFUNC(sfactor, dfactor, blendmode) \
                        case (sfactor<<16)|dfactor: thread->fb_blendmode = blendmode; break;
-               BLENDFUNC(GL_SRC_COLOR, GL_ONE, DPSOFTRAST_BLENDMODE_SUBALPHA)
+               BLENDFUNC(GL_SRC_ALPHA, GL_ONE, DPSOFTRAST_BLENDMODE_SUBALPHA)
                default: thread->fb_blendmode = DPSOFTRAST_BLENDMODE_OPAQUE; break;
                }
        }
@@ -399,7 +462,7 @@ static void DPSOFTRAST_RecalcBlendFunc(DPSOFTRAST_State_Thread *thread)
                BLENDFUNC(GL_DST_COLOR, GL_ZERO, DPSOFTRAST_BLENDMODE_MUL)
                BLENDFUNC(GL_DST_COLOR, GL_SRC_COLOR, DPSOFTRAST_BLENDMODE_MUL2)
                BLENDFUNC(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, DPSOFTRAST_BLENDMODE_PSEUDOALPHA)
-               BLENDFUNC(GL_SRC_COLOR, GL_ONE, DPSOFTRAST_BLENDMODE_SUBALPHA)
+               BLENDFUNC(GL_ONE_MINUS_DST_COLOR, GL_ONE, DPSOFTRAST_BLENDMODE_INVADD)
                default: thread->fb_blendmode = DPSOFTRAST_BLENDMODE_OPAQUE; break;
                }
        }
@@ -429,7 +492,7 @@ static void DPSOFTRAST_Validate(DPSOFTRAST_State_Thread *thread, int mask)
        }
 }
 
-DPSOFTRAST_Texture *DPSOFTRAST_Texture_GetByIndex(int index)
+static DPSOFTRAST_Texture *DPSOFTRAST_Texture_GetByIndex(int index)
 {
        if (index >= 1 && index < dpsoftrast.texture_end && dpsoftrast.texture[index].bytes)
                return &dpsoftrast.texture[index];
@@ -450,13 +513,13 @@ static void DPSOFTRAST_Texture_Grow(void)
                dpsoftrast.texture_max *= 2;
        dpsoftrast.texture = (DPSOFTRAST_Texture *)realloc(dpsoftrast.texture, dpsoftrast.texture_max * sizeof(DPSOFTRAST_Texture));
        for (i = 0; i < DPSOFTRAST_MAXTEXTUREUNITS; i++)
-               if(dpsoftrast.texbound[i])
+               if (dpsoftrast.texbound[i])
                        dpsoftrast.texbound[i] = dpsoftrast.texture + (dpsoftrast.texbound[i] - oldtexture);
        for (j = 0; j < dpsoftrast.numthreads; j++)
        {
                thread = &dpsoftrast.threads[j];
                for (i = 0; i < DPSOFTRAST_MAXTEXTUREUNITS; i++)
-                       if(thread->texbound[i])
+                       if (thread->texbound[i])
                                thread->texbound[i] = dpsoftrast.texture + (thread->texbound[i] - oldtexture);
        }
 }
@@ -554,9 +617,6 @@ int DPSOFTRAST_Texture_New(int flags, int width, int height, int depth)
        d = depth;
        size = 0;
        mipmaps = 0;
-       w = width;
-       h = height;
-       d = depth;
        for (;;)
        {
                s = w * h * d * sides * 4;
@@ -597,7 +657,7 @@ void DPSOFTRAST_Texture_Free(int index)
        while (dpsoftrast.texture_end > 0 && dpsoftrast.texture[dpsoftrast.texture_end-1].bytes == NULL)
                dpsoftrast.texture_end--;
 }
-void DPSOFTRAST_Texture_CalculateMipmaps(int index)
+static void DPSOFTRAST_Texture_CalculateMipmaps(int index)
 {
        int i, x, y, z, w, layer0, layer1, row0, row1;
        unsigned char *o, *i0, *i1, *i2, *i3;
@@ -683,13 +743,16 @@ void DPSOFTRAST_Texture_UpdatePartial(int index, int mip, const unsigned char *p
        texture = DPSOFTRAST_Texture_GetByIndex(index);if (!texture) return;
        if (texture->binds)
                DPSOFTRAST_Flush();
-       dst = texture->bytes + (blocky * texture->mipmap[0][2] + blockx) * 4;
-       while (blockheight > 0)
+       if (pixels)
        {
-               memcpy(dst, pixels, blockwidth * 4);
-               pixels += blockwidth * 4;
-               dst += texture->mipmap[0][2] * 4;
-               blockheight--;
+               dst = texture->bytes + texture->mipmap[0][1] +(-blocky * texture->mipmap[0][2] + blockx) * 4;
+               while (blockheight > 0)
+               {
+                       dst -= texture->mipmap[0][2] * 4;
+                       memcpy(dst, pixels, blockwidth * 4);
+                       pixels += blockwidth * 4;
+                       blockheight--;
+               }
        }
        DPSOFTRAST_Texture_CalculateMipmaps(index);
 }
@@ -699,7 +762,17 @@ void DPSOFTRAST_Texture_UpdateFull(int index, const unsigned char *pixels)
        texture = DPSOFTRAST_Texture_GetByIndex(index);if (!texture) return;
        if (texture->binds)
                DPSOFTRAST_Flush();
-       memcpy(texture->bytes, pixels, texture->mipmap[0][1]);
+       if (pixels)
+       {
+               int i, stride = texture->mipmap[0][2]*4;
+               unsigned char *dst = texture->bytes + texture->mipmap[0][1];
+               for (i = texture->mipmap[0][3];i > 0;i--)
+               {
+                       dst -= stride;
+                       memcpy(dst, pixels, stride);
+                       pixels += stride;
+               }
+       }
        DPSOFTRAST_Texture_CalculateMipmaps(index);
 }
 int DPSOFTRAST_Texture_GetWidth(int index, int mip)
@@ -742,32 +815,16 @@ void DPSOFTRAST_Texture_Filter(int index, DPSOFTRAST_TEXTURE_FILTER filter)
        texture->filter = filter;
 }
 
-void DPSOFTRAST_SetRenderTargets(int width, int height, unsigned int *depthpixels, unsigned int *colorpixels0, unsigned int *colorpixels1, unsigned int *colorpixels2, unsigned int *colorpixels3)
-{
-       if (width != dpsoftrast.fb_width || height != dpsoftrast.fb_height || depthpixels != dpsoftrast.fb_depthpixels ||
-               colorpixels0 != dpsoftrast.fb_colorpixels[0] || colorpixels1 != dpsoftrast.fb_colorpixels[1] ||
-               colorpixels2 != dpsoftrast.fb_colorpixels[2] || colorpixels3 != dpsoftrast.fb_colorpixels[3])
-               DPSOFTRAST_Flush();
-       dpsoftrast.fb_width = width;
-       dpsoftrast.fb_height = height;
-       dpsoftrast.fb_depthpixels = depthpixels;
-       dpsoftrast.fb_colorpixels[0] = colorpixels0;
-       dpsoftrast.fb_colorpixels[1] = colorpixels1;
-       dpsoftrast.fb_colorpixels[2] = colorpixels2;
-       dpsoftrast.fb_colorpixels[3] = colorpixels3;
-}
-
 static void DPSOFTRAST_Draw_FlushThreads(void);
 
 static void DPSOFTRAST_Draw_SyncCommands(void)
 {
-       MEMORY_BARRIER;
+       if(dpsoftrast.usethreads) MEMORY_BARRIER;
        dpsoftrast.drawcommand = dpsoftrast.commandpool.freecommand;
 }
 
 static void DPSOFTRAST_Draw_FreeCommandPool(int space)
 {
-#ifdef USE_THREADS
        DPSOFTRAST_State_Thread *thread;
        int i;
        int freecommand = dpsoftrast.commandpool.freecommand;
@@ -795,20 +852,17 @@ static void DPSOFTRAST_Draw_FreeCommandPool(int space)
                if (usedcommands <= DPSOFTRAST_DRAW_MAXCOMMANDPOOL-space || waitindex < 0)
                        break;
                thread = &dpsoftrast.threads[waitindex];
-               SDL_LockMutex(thread->drawmutex);
+               Thread_LockMutex(thread->drawmutex);
                if (thread->commandoffset != dpsoftrast.drawcommand)
                {
                        thread->waiting = true;
-                       if (thread->starving) SDL_CondSignal(thread->drawcond);
-                       SDL_CondWait(thread->waitcond, thread->drawmutex);
+                       if (thread->starving) Thread_CondSignal(thread->drawcond);
+                       Thread_CondWait(thread->waitcond, thread->drawmutex);
                        thread->waiting = false;
                }
-               SDL_UnlockMutex(thread->drawmutex);
+               Thread_UnlockMutex(thread->drawmutex);
        }
        dpsoftrast.commandpool.usedcommands = usedcommands;
-#else
-       DPSOFTRAST_Draw_FlushThreads();
-#endif
 }
 
 #define DPSOFTRAST_ALIGNCOMMAND(size) \
@@ -822,15 +876,18 @@ static void *DPSOFTRAST_AllocateCommand(int opcode, int size)
        int freecommand = dpsoftrast.commandpool.freecommand;
        int usedcommands = dpsoftrast.commandpool.usedcommands;
        int extra = sizeof(DPSOFTRAST_Command);
-       if(DPSOFTRAST_DRAW_MAXCOMMANDPOOL - freecommand < size)
+       if (DPSOFTRAST_DRAW_MAXCOMMANDPOOL - freecommand < size)
                extra += DPSOFTRAST_DRAW_MAXCOMMANDPOOL - freecommand;
-       if(usedcommands > DPSOFTRAST_DRAW_MAXCOMMANDPOOL - (size + extra))
+       if (usedcommands > DPSOFTRAST_DRAW_MAXCOMMANDPOOL - (size + extra))
        {
-               DPSOFTRAST_Draw_FreeCommandPool(size + extra);
+               if (dpsoftrast.usethreads)
+                       DPSOFTRAST_Draw_FreeCommandPool(size + extra);
+               else
+                       DPSOFTRAST_Draw_FlushThreads();
                freecommand = dpsoftrast.commandpool.freecommand;
                usedcommands = dpsoftrast.commandpool.usedcommands;
        }
-       if(DPSOFTRAST_DRAW_MAXCOMMANDPOOL - freecommand < size)
+       if (DPSOFTRAST_DRAW_MAXCOMMANDPOOL - freecommand < size)
        {
                command = (DPSOFTRAST_Command *) &dpsoftrast.commandpool.commands[freecommand];
                command->opcode = DPSOFTRAST_OPCODE_Reset;
@@ -853,6 +910,8 @@ static void DPSOFTRAST_UndoCommand(int size)
        int freecommand = dpsoftrast.commandpool.freecommand;
        int usedcommands = dpsoftrast.commandpool.usedcommands;
        freecommand -= size;
+       if (freecommand < 0)
+               freecommand += DPSOFTRAST_DRAW_MAXCOMMANDPOOL;
        usedcommands -= size;
        dpsoftrast.commandpool.freecommand = freecommand;
        dpsoftrast.commandpool.usedcommands = usedcommands;
@@ -885,18 +944,22 @@ void DPSOFTRAST_Viewport(int x, int y, int width, int height)
 DEFCOMMAND(2, ClearColor, float r; float g; float b; float a;) 
 static void DPSOFTRAST_Interpret_ClearColor(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_Command_ClearColor *command)
 {
-       int i, x1, y1, x2, y2, w, h, x, y, t1, t2;
+       int i, x1, y1, x2, y2, w, h, x, y;
+       int miny1, maxy1, miny2, maxy2;
+       int bandy;
        unsigned int *p;
        unsigned int c;
        DPSOFTRAST_Validate(thread, DPSOFTRAST_VALIDATE_FB);
-       x1 = thread->fb_clearscissor[0];
-       y1 = thread->fb_clearscissor[1];
-       x2 = thread->fb_clearscissor[0] + thread->fb_clearscissor[2];
-       y2 = thread->fb_clearscissor[1] + thread->fb_clearscissor[3];
-       t1 = (thread->index*dpsoftrast.fb_height)/dpsoftrast.numthreads;
-       t2 = ((thread->index+1)*dpsoftrast.fb_height)/dpsoftrast.numthreads;
-       if(y1 < t1) y1 = t1;
-       if(y2 > t2) y2 = t2;
+       miny1 = thread->miny1;
+       maxy1 = thread->maxy1;
+       miny2 = thread->miny2;
+       maxy2 = thread->maxy2;
+       x1 = thread->fb_scissor[0];
+       y1 = thread->fb_scissor[1];
+       x2 = thread->fb_scissor[0] + thread->fb_scissor[2];
+       y2 = thread->fb_scissor[1] + thread->fb_scissor[3];
+       if (y1 < miny1) y1 = miny1;
+       if (y2 > maxy2) y2 = maxy2;
        w = x2 - x1;
        h = y2 - y1;
        if (w < 1 || h < 1)
@@ -907,7 +970,8 @@ static void DPSOFTRAST_Interpret_ClearColor(DPSOFTRAST_State_Thread *thread, con
        {
                if (!dpsoftrast.fb_colorpixels[i])
                        continue;
-               for (y = y1;y < y2;y++)
+               for (y = y1, bandy = min(y2, maxy1); y < y2; bandy = min(y2, maxy2), y = max(y, miny2))
+               for (;y < bandy;y++)
                {
                        p = dpsoftrast.fb_colorpixels[i] + y * dpsoftrast.fb_width;
                        for (x = x1;x < x2;x++)
@@ -927,24 +991,29 @@ void DPSOFTRAST_ClearColor(float r, float g, float b, float a)
 DEFCOMMAND(3, ClearDepth, float depth;)
 static void DPSOFTRAST_Interpret_ClearDepth(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_Command_ClearDepth *command)
 {
-       int x1, y1, x2, y2, w, h, x, y, t1, t2;
+       int x1, y1, x2, y2, w, h, x, y;
+       int miny1, maxy1, miny2, maxy2;
+       int bandy;
        unsigned int *p;
        unsigned int c;
        DPSOFTRAST_Validate(thread, DPSOFTRAST_VALIDATE_FB);
-       x1 = thread->fb_clearscissor[0];
-       y1 = thread->fb_clearscissor[1];
-       x2 = thread->fb_clearscissor[0] + thread->fb_clearscissor[2];
-       y2 = thread->fb_clearscissor[1] + thread->fb_clearscissor[3];
-       t1 = (thread->index*dpsoftrast.fb_height)/dpsoftrast.numthreads;
-       t2 = ((thread->index+1)*dpsoftrast.fb_height)/dpsoftrast.numthreads;
-       if(y1 < t1) y1 = t1;
-       if(y2 > t2) y2 = t2;
+       miny1 = thread->miny1;
+       maxy1 = thread->maxy1;
+       miny2 = thread->miny2;
+       maxy2 = thread->maxy2;
+       x1 = thread->fb_scissor[0];
+       y1 = thread->fb_scissor[1];
+       x2 = thread->fb_scissor[0] + thread->fb_scissor[2];
+       y2 = thread->fb_scissor[1] + thread->fb_scissor[3];
+       if (y1 < miny1) y1 = miny1;
+       if (y2 > maxy2) y2 = maxy2;
        w = x2 - x1;
        h = y2 - y1;
        if (w < 1 || h < 1)
                return;
        c = DPSOFTRAST_DEPTH32_FROM_DEPTH32F(command->depth);
-       for (y = y1;y < y2;y++)
+       for (y = y1, bandy = min(y2, maxy1); y < y2; bandy = min(y2, maxy2), y = max(y, miny2))
+       for (;y < bandy;y++)
        {
                p = dpsoftrast.fb_depthpixels + y * dpsoftrast.fb_width;
                for (x = x1;x < x2;x++)
@@ -1102,30 +1171,6 @@ void DPSOFTRAST_CullFace(int mode)
        command->mode = mode;
 }
 
-DEFCOMMAND(15, AlphaTest, int enable;)
-static void DPSOFTRAST_Interpret_AlphaTest(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_Command_AlphaTest *command)
-{
-       thread->alphatest = command->enable;
-}
-void DPSOFTRAST_AlphaTest(int enable)
-{
-       DPSOFTRAST_Command_AlphaTest *command = DPSOFTRAST_ALLOCATECOMMAND(AlphaTest);
-       command->enable = enable;
-}
-
-DEFCOMMAND(16, AlphaFunc, int func; float ref;)
-static void DPSOFTRAST_Interpret_AlphaFunc(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_Command_AlphaFunc *command)
-{
-       thread->alphafunc = command->func;
-       thread->alphavalue = command->ref;
-}
-void DPSOFTRAST_AlphaFunc(int func, float ref)
-{
-       DPSOFTRAST_Command_AlphaFunc *command = DPSOFTRAST_ALLOCATECOMMAND(AlphaFunc);
-       command->func = func;
-       command->ref = ref;
-}
-
 void DPSOFTRAST_Color4f(float r, float g, float b, float a)
 {
        dpsoftrast.color[0] = r;
@@ -1143,7 +1188,6 @@ void DPSOFTRAST_GetPixelsBGRA(int blockx, int blocky, int blockwidth, int blockh
        int bx2 = blockx + blockwidth;
        int by2 = blocky + blockheight;
        int bw;
-       int bh;
        int x;
        int y;
        unsigned char *inpixels;
@@ -1155,7 +1199,6 @@ void DPSOFTRAST_GetPixelsBGRA(int blockx, int blocky, int blockwidth, int blockh
        if (bx2 > dpsoftrast.fb_width) bx2 = dpsoftrast.fb_width;
        if (by2 > dpsoftrast.fb_height) by2 = dpsoftrast.fb_height;
        bw = bx2 - bx1;
-       bh = by2 - by1;
        inpixels = (unsigned char *)dpsoftrast.fb_colorpixels[0];
        if (dpsoftrast.bigendian)
        {
@@ -1209,8 +1252,7 @@ void DPSOFTRAST_CopyRectangleToTexture(int index, int mip, int tx, int ty, int s
        DPSOFTRAST_Texture *texture;
        texture = DPSOFTRAST_Texture_GetByIndex(index);if (!texture) return;
        if (mip < 0 || mip >= texture->mipmaps) return;
-       if (texture->binds)
-               DPSOFTRAST_Flush();
+       DPSOFTRAST_Flush();
        spixels = dpsoftrast.fb_colorpixels[0];
        swidth = dpsoftrast.fb_width;
        sheight = dpsoftrast.fb_height;
@@ -1233,6 +1275,8 @@ void DPSOFTRAST_CopyRectangleToTexture(int index, int mip, int tx, int ty, int s
        if (th > sh) th = sh;
        if (tw < 1 || th < 1)
                return;
+       sy1 = sheight - sy1 - th;
+       ty1 = theight - ty1 - th;
        for (y = 0;y < th;y++)
                memcpy(tpixels + ((ty1 + y) * twidth + tx1), spixels + ((sy1 + y) * swidth + sx1), tw*4);
        if (texture->mipmaps > 1)
@@ -1267,47 +1311,51 @@ void DPSOFTRAST_SetTexture(int unitnum, int index)
        command->texture = texture;
 
        dpsoftrast.texbound[unitnum] = texture;
-       ATOMIC_ADD(texture->binds, dpsoftrast.numthreads);
+       if (texture)
+               ATOMIC_ADD(texture->binds, dpsoftrast.numthreads);
 }
 
 void DPSOFTRAST_SetVertexPointer(const float *vertex3f, size_t stride)
 {
        dpsoftrast.pointer_vertex3f = vertex3f;
-       dpsoftrast.stride_vertex = stride;
+       dpsoftrast.stride_vertex = (int)stride;
 }
 void DPSOFTRAST_SetColorPointer(const float *color4f, size_t stride)
 {
        dpsoftrast.pointer_color4f = color4f;
        dpsoftrast.pointer_color4ub = NULL;
-       dpsoftrast.stride_color = stride;
+       dpsoftrast.stride_color = (int)stride;
 }
 void DPSOFTRAST_SetColorPointer4ub(const unsigned char *color4ub, size_t stride)
 {
        dpsoftrast.pointer_color4f = NULL;
        dpsoftrast.pointer_color4ub = color4ub;
-       dpsoftrast.stride_color = stride;
+       dpsoftrast.stride_color = (int)stride;
 }
 void DPSOFTRAST_SetTexCoordPointer(int unitnum, int numcomponents, size_t stride, const float *texcoordf)
 {
        dpsoftrast.pointer_texcoordf[unitnum] = texcoordf;
        dpsoftrast.components_texcoord[unitnum] = numcomponents;
-       dpsoftrast.stride_texcoord[unitnum] = stride;
+       dpsoftrast.stride_texcoord[unitnum] = (int)stride;
 }
 
-DEFCOMMAND(18, SetShader, int mode; int permutation;)
+DEFCOMMAND(18, SetShader, int mode; dpuint64 permutation; int exactspecularmath;)
 static void DPSOFTRAST_Interpret_SetShader(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_Command_SetShader *command)
 {
        thread->shader_mode = command->mode;
        thread->shader_permutation = command->permutation;
+       thread->shader_exactspecularmath = command->exactspecularmath;
 }
-void DPSOFTRAST_SetShader(int mode, int permutation)
+void DPSOFTRAST_SetShader(int mode, dpuint64 permutation, int exactspecularmath)
 {
        DPSOFTRAST_Command_SetShader *command = DPSOFTRAST_ALLOCATECOMMAND(SetShader);
        command->mode = mode;
        command->permutation = permutation;
+       command->exactspecularmath = exactspecularmath;
 
        dpsoftrast.shader_mode = mode;
        dpsoftrast.shader_permutation = permutation;
+       dpsoftrast.shader_exactspecularmath = exactspecularmath;
 }
 
 DEFCOMMAND(19, Uniform4f, DPSOFTRAST_UNIFORM index; float val[4];)
@@ -1345,13 +1393,13 @@ static void DPSOFTRAST_Interpret_UniformMatrix4f(DPSOFTRAST_State_Thread *thread
 }
 void DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM uniform, int arraysize, int transpose, const float *v)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int i, index;
        for (i = 0, index = (int)uniform;i < arraysize;i++, index += 4, v += 16)
        {
                __m128 m0, m1, m2, m3;
                DPSOFTRAST_Command_UniformMatrix4f *command = DPSOFTRAST_ALLOCATECOMMAND(UniformMatrix4f);
-               command->index = index;
+               command->index = (DPSOFTRAST_UNIFORM)index;
                if (((size_t)v)&(ALIGN_SIZE-1))
                {
                        m0 = _mm_loadu_ps(v);
@@ -1404,7 +1452,22 @@ void DPSOFTRAST_Uniform1i(DPSOFTRAST_UNIFORM index, int i0)
        dpsoftrast.uniform1i[command->index] = i0;
 }
 
-#ifdef SSE2_PRESENT
+DEFCOMMAND(24, ClipPlane, float clipplane[4];)
+static void DPSOFTRAST_Interpret_ClipPlane(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_Command_ClipPlane *command)
+{
+       memcpy(thread->clipplane, command->clipplane, 4*sizeof(float));
+       thread->validate |= DPSOFTRAST_VALIDATE_FB;
+}
+void DPSOFTRAST_ClipPlane(float x, float y, float z, float w)
+{
+       DPSOFTRAST_Command_ClipPlane *command = DPSOFTRAST_ALLOCATECOMMAND(ClipPlane);
+       command->clipplane[0] = x;
+       command->clipplane[1] = y;
+       command->clipplane[2] = z;
+       command->clipplane[3] = w;
+}
+
+#ifdef SSE_POSSIBLE
 static void DPSOFTRAST_Load4fTo4f(float *dst, const unsigned char *src, int size, int stride)
 {
        float *end = dst + size*4;
@@ -1598,13 +1661,13 @@ static void DPSOFTRAST_Fill4f(float *dst, const float *src, int size)
 }
 #endif
 
-void DPSOFTRAST_Vertex_Transform(float *out4f, const float *in4f, int numitems, const float *inmatrix16f)
+static void DPSOFTRAST_Vertex_Transform(float *out4f, const float *in4f, int numitems, const float *inmatrix16f)
 {
-#ifdef SSE2_PRESENT
-       static const float identitymatrix[4][4] = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}};
+#ifdef SSE_POSSIBLE
+       static const float identitymatrix16f[4][4] = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}};
        __m128 m0, m1, m2, m3;
        float *end;
-       if (!memcmp(identitymatrix, inmatrix16f, sizeof(float[16])))
+       if (!memcmp(identitymatrix16f, inmatrix16f, sizeof(float[16])))
        {
                // fast case for identity matrix
                if (out4f != in4f) memcpy(out4f, in4f, numitems * sizeof(float[4]));
@@ -1646,12 +1709,14 @@ void DPSOFTRAST_Vertex_Transform(float *out4f, const float *in4f, int numitems,
 #endif
 }
 
-void DPSOFTRAST_Vertex_Copy(float *out4f, const float *in4f, int numitems)
+#if 0
+static void DPSOFTRAST_Vertex_Copy(float *out4f, const float *in4f, int numitems)
 {
        memcpy(out4f, in4f, numitems * sizeof(float[4]));
 }
+#endif
 
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
 #define DPSOFTRAST_PROJECTVERTEX(out, in, viewportcenter, viewportscale) \
 { \
        __m128 p = (in), w = _mm_shuffle_ps(p, p, _MM_SHUFFLE(3, 3, 3, 3)); \
@@ -1660,14 +1725,6 @@ void DPSOFTRAST_Vertex_Copy(float *out4f, const float *in4f, int numitems)
        out = _mm_shuffle_ps(p, p, _MM_SHUFFLE(0, 3, 2, 1)); \
 }
 
-#define DPSOFTRAST_PROJECTY(out, in, viewportcenter, viewportscale) \
-{ \
-       __m128 p = (in), w = _mm_shuffle_ps(p, p, _MM_SHUFFLE(3, 3, 3, 3)); \
-       p = _mm_move_ss(_mm_shuffle_ps(p, p, _MM_SHUFFLE(2, 1, 0, 3)), _mm_set_ss(1.0f)); \
-       p = _mm_add_ps(viewportcenter, _mm_div_ps(_mm_mul_ps(viewportscale, p), w)); \
-       out = _mm_shuffle_ps(p, p, _MM_SHUFFLE(0, 3, 2, 1)); \
-}
-
 #define DPSOFTRAST_TRANSFORMVERTEX(out, in, m0, m1, m2, m3) \
 { \
        __m128 p = (in); \
@@ -1677,10 +1734,13 @@ void DPSOFTRAST_Vertex_Copy(float *out4f, const float *in4f, int numitems)
                                                                                        _mm_mul_ps(_mm_shuffle_ps(p, p, _MM_SHUFFLE(3, 3, 3, 3)), m3)))); \
 }
 
-static int DPSOFTRAST_Vertex_BoundY(int *starty, int *endy, __m128 minpos, __m128 maxpos, __m128 viewportcenter, __m128 viewportscale, __m128 m0, __m128 m1, __m128 m2, __m128 m3)
+static int DPSOFTRAST_Vertex_BoundY(int *starty, int *endy, const float *minposf, const float *maxposf, const float *inmatrix16f)
 {
        int clipmask = 0xFF;
+       __m128 viewportcenter = _mm_load_ps(dpsoftrast.fb_viewportcenter), viewportscale = _mm_load_ps(dpsoftrast.fb_viewportscale);
        __m128 bb[8], clipdist[8], minproj = _mm_set_ss(2.0f), maxproj = _mm_set_ss(-2.0f);
+       __m128 m0 = _mm_loadu_ps(inmatrix16f), m1 = _mm_loadu_ps(inmatrix16f + 4), m2 = _mm_loadu_ps(inmatrix16f + 8), m3 = _mm_loadu_ps(inmatrix16f + 12);
+       __m128 minpos = _mm_load_ps(minposf), maxpos = _mm_load_ps(maxposf);
        m0 = _mm_shuffle_ps(m0, m0, _MM_SHUFFLE(3, 2, 0, 1));
        m1 = _mm_shuffle_ps(m1, m1, _MM_SHUFFLE(3, 2, 0, 1));
        m2 = _mm_shuffle_ps(m2, m2, _MM_SHUFFLE(3, 2, 0, 1));
@@ -1747,11 +1807,10 @@ static int DPSOFTRAST_Vertex_BoundY(int *starty, int *endy, __m128 minpos, __m12
        *endy = _mm_cvttss_si32(minproj)+1;
        return clipmask;
 }
-#endif
        
 static int DPSOFTRAST_Vertex_Project(float *out4f, float *screen4f, int *starty, int *endy, const float *in4f, int numitems)
 {
-#ifdef SSE2_PRESENT
+       static const float identitymatrix16f[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
        float *end = out4f + numitems*4;
        __m128 viewportcenter = _mm_load_ps(dpsoftrast.fb_viewportcenter), viewportscale = _mm_load_ps(dpsoftrast.fb_viewportscale);
        __m128 minpos, maxpos;
@@ -1788,22 +1847,22 @@ static int DPSOFTRAST_Vertex_Project(float *out4f, float *screen4f, int *starty,
                }
        }
        if (starty && endy) 
-               return DPSOFTRAST_Vertex_BoundY(starty, endy, minpos, maxpos, viewportcenter, viewportscale, 
-                                       _mm_setr_ps(1.0f, 0.0f, 0.0f, 0.0f),
-                                       _mm_setr_ps(0.0f, 1.0f, 0.0f, 0.0f),
-                                       _mm_setr_ps(0.0f, 0.0f, 1.0f, 0.0f),
-                                       _mm_setr_ps(0.0f, 0.0f, 0.0f, 1.0f));
+       {
+               ALIGN(float minposf[4]);
+               ALIGN(float maxposf[4]);
+               _mm_store_ps(minposf, minpos);
+               _mm_store_ps(maxposf, maxpos);
+               return DPSOFTRAST_Vertex_BoundY(starty, endy, minposf, maxposf, identitymatrix16f);
+       }
        return 0;
-#endif
 }
 
 static int DPSOFTRAST_Vertex_TransformProject(float *out4f, float *screen4f, int *starty, int *endy, const float *in4f, int numitems, const float *inmatrix16f)
 {
-#ifdef SSE2_PRESENT
-       static const float identitymatrix[4][4] = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}};
+       static const float identitymatrix16f[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
        __m128 m0, m1, m2, m3, viewportcenter, viewportscale, minpos, maxpos;
        float *end;
-       if (!memcmp(identitymatrix, inmatrix16f, sizeof(float[16])))
+       if (!memcmp(identitymatrix16f, inmatrix16f, sizeof(float[16])))
                return DPSOFTRAST_Vertex_Project(out4f, screen4f, starty, endy, in4f, numitems);
        end = out4f + numitems*4;
        viewportcenter = _mm_load_ps(dpsoftrast.fb_viewportcenter);
@@ -1847,13 +1906,20 @@ static int DPSOFTRAST_Vertex_TransformProject(float *out4f, float *screen4f, int
                }
        }
        if (starty && endy) 
-               return DPSOFTRAST_Vertex_BoundY(starty, endy, minpos, maxpos, viewportcenter, viewportscale, m0, m1, m2, m3); 
+       {
+               ALIGN(float minposf[4]);
+               ALIGN(float maxposf[4]);
+               _mm_store_ps(minposf, minpos);
+               _mm_store_ps(maxposf, maxpos);
+               return DPSOFTRAST_Vertex_BoundY(starty, endy, minposf, maxposf, inmatrix16f); 
+       }
        return 0;
-#endif
 }
+#endif
 
 static float *DPSOFTRAST_Array_Load(int outarray, int inarray)
 {
+#ifdef SSE_POSSIBLE
        float *outf = dpsoftrast.post_array4f[outarray];
        const unsigned char *inb;
        int firstvertex = dpsoftrast.firstvertex;
@@ -1905,6 +1971,9 @@ static float *DPSOFTRAST_Array_Load(int outarray, int inarray)
                break;
        }
        return outf;
+#else
+       return NULL;
+#endif
 }
 
 static float *DPSOFTRAST_Array_Transform(int outarray, int inarray, const float *inmatrix16f)
@@ -1917,20 +1986,28 @@ static float *DPSOFTRAST_Array_Transform(int outarray, int inarray, const float
 #if 0
 static float *DPSOFTRAST_Array_Project(int outarray, int inarray)
 {
+#ifdef SSE_POSSIBLE
        float *data = inarray >= 0 ? DPSOFTRAST_Array_Load(outarray, inarray) : dpsoftrast.post_array4f[outarray];
        dpsoftrast.drawclipped = DPSOFTRAST_Vertex_Project(data, dpsoftrast.screencoord4f, &dpsoftrast.drawstarty, &dpsoftrast.drawendy, data, dpsoftrast.numvertices);
        return data;
+#else
+       return NULL;
+#endif
 }
 #endif
 
 static float *DPSOFTRAST_Array_TransformProject(int outarray, int inarray, const float *inmatrix16f)
 {
+#ifdef SSE_POSSIBLE
        float *data = inarray >= 0 ? DPSOFTRAST_Array_Load(outarray, inarray) : dpsoftrast.post_array4f[outarray];
        dpsoftrast.drawclipped = DPSOFTRAST_Vertex_TransformProject(data, dpsoftrast.screencoord4f, &dpsoftrast.drawstarty, &dpsoftrast.drawendy, data, dpsoftrast.numvertices, inmatrix16f);
        return data;
+#else
+       return NULL;
+#endif
 }
 
-void DPSOFTRAST_Draw_Span_Begin(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *zf)
+static void DPSOFTRAST_Draw_Span_Begin(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *zf)
 {
        int x;
        int startx = span->startx;
@@ -1938,11 +2015,18 @@ void DPSOFTRAST_Draw_Span_Begin(DPSOFTRAST_State_Thread *thread, const DPSOFTRAS
        float wslope = triangle->w[0];
        float w = triangle->w[2] + span->x*wslope + span->y*triangle->w[1];
        float endz = 1.0f / (w + wslope * startx);
+       if (triangle->w[0] == 0)
+       {
+               // LordHavoc: fast flat polygons (HUD/menu)
+               for (x = startx;x < endx;x++)
+                       zf[x] = endz;
+               return;
+       }
        for (x = startx;x < endx;)
        {
                int nextsub = x + DPSOFTRAST_DRAW_MAXSUBSPAN, endsub = nextsub - 1;
                float z = endz, dz;
-               if(nextsub >= endx) nextsub = endsub = endx-1;
+               if (nextsub >= endx) nextsub = endsub = endx-1;
                endz = 1.0f / (w + wslope * nextsub);
                dz = x < nextsub ? (endz - z) / (nextsub - x) : 0.0f;
                for (; x <= endsub; x++, z += dz)
@@ -1950,306 +2034,318 @@ void DPSOFTRAST_Draw_Span_Begin(DPSOFTRAST_State_Thread *thread, const DPSOFTRAS
        }
 }
 
-void DPSOFTRAST_Draw_Span_Finish(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, const float * RESTRICT in4f)
+static void DPSOFTRAST_Draw_Span_FinishBGRA8(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, const unsigned char* RESTRICT in4ub)
 {
+#ifdef SSE_POSSIBLE
        int x;
        int startx = span->startx;
        int endx = span->endx;
-       int d[4];
-       float a, b;
+       int maskx;
+       int subx;
+       const unsigned int * RESTRICT ini = (const unsigned int *)in4ub;
        unsigned char * RESTRICT pixelmask = span->pixelmask;
-       unsigned char * RESTRICT pixel = (unsigned char *)dpsoftrast.fb_colorpixels[0];
-       if (!pixel)
+       unsigned int * RESTRICT pixeli = (unsigned int *)dpsoftrast.fb_colorpixels[0];
+       if (!pixeli)
                return;
-       pixel += (span->y * dpsoftrast.fb_width + span->x) * 4;
+       pixeli += span->y * dpsoftrast.fb_width + span->x;
        // handle alphatest now (this affects depth writes too)
-       if (thread->alphatest)
+       if (thread->shader_permutation & SHADERPERMUTATION_ALPHAKILL)
                for (x = startx;x < endx;x++)
-                       if (in4f[x*4+3] < 0.5f)
+                       if (in4ub[x*4+3] < 128)
                                pixelmask[x] = false;
-       // FIXME: this does not handle bigendian
+       // LordHavoc: clear pixelmask for some pixels in alphablend cases, this
+       // helps sprites, text and hud artwork
        switch(thread->fb_blendmode)
        {
-       case DPSOFTRAST_BLENDMODE_OPAQUE:
-               for (x = startx;x < endx;x++)
-               {
-                       if (!pixelmask[x])
-                               continue;
-                       d[0] = (int)(in4f[x*4+2]*255.0f);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*255.0f);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*255.0f);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*255.0f);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
-               }
-               break;
        case DPSOFTRAST_BLENDMODE_ALPHA:
-               for (x = startx;x < endx;x++)
-               {
-                       if (!pixelmask[x])
-                               continue;
-                       a = in4f[x*4+3] * 255.0f;
-                       b = 1.0f - in4f[x*4+3];
-                       d[0] = (int)(in4f[x*4+2]*a+pixel[x*4+0]*b);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*a+pixel[x*4+1]*b);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*a+pixel[x*4+2]*b);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*a+pixel[x*4+3]*b);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
-               }
-               break;
        case DPSOFTRAST_BLENDMODE_ADDALPHA:
+       case DPSOFTRAST_BLENDMODE_SUBALPHA:
+               maskx = startx;
                for (x = startx;x < endx;x++)
                {
-                       if (!pixelmask[x])
-                               continue;
-                       a = in4f[x*4+3] * 255.0f;
-                       d[0] = (int)(in4f[x*4+2]*a+pixel[x*4+0]);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*a+pixel[x*4+1]);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*a+pixel[x*4+2]);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*a+pixel[x*4+3]);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
+                       if (in4ub[x*4+3] >= 1)
+                       {
+                               startx = x;
+                               for (;;)
+                               {
+                                       while (++x < endx && in4ub[x*4+3] >= 1) ;
+                                       maskx = x;
+                                       if (x >= endx) break;
+                                       ++x;
+                                       while (++x < endx && in4ub[x*4+3] < 1) pixelmask[x] = false;
+                                       if (x >= endx) break;
+                               }
+                               break;
+                       }
                }
+               endx = maskx;
                break;
+       case DPSOFTRAST_BLENDMODE_OPAQUE:
        case DPSOFTRAST_BLENDMODE_ADD:
-               for (x = startx;x < endx;x++)
-               {
-                       if (!pixelmask[x])
-                               continue;
-                       d[0] = (int)(in4f[x*4+2]*255.0f+pixel[x*4+0]);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*255.0f+pixel[x*4+1]);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*255.0f+pixel[x*4+2]);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*255.0f+pixel[x*4+3]);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
-               }
-               break;
        case DPSOFTRAST_BLENDMODE_INVMOD:
-               for (x = startx;x < endx;x++)
-               {
-                       if (!pixelmask[x])
-                               continue;
-                       d[0] = (int)((1.0f-in4f[x*4+2])*pixel[x*4+0]);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)((1.0f-in4f[x*4+1])*pixel[x*4+1]);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)((1.0f-in4f[x*4+0])*pixel[x*4+2]);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)((1.0f-in4f[x*4+3])*pixel[x*4+3]);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
-               }
-               break;
        case DPSOFTRAST_BLENDMODE_MUL:
-               for (x = startx;x < endx;x++)
-               {
-                       if (!pixelmask[x])
-                               continue;
-                       d[0] = (int)(in4f[x*4+2]*pixel[x*4+0]);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*pixel[x*4+1]);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*pixel[x*4+2]);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*pixel[x*4+3]);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
-               }
-               break;
        case DPSOFTRAST_BLENDMODE_MUL2:
-               for (x = startx;x < endx;x++)
-               {
-                       if (!pixelmask[x])
-                               continue;
-                       d[0] = (int)(in4f[x*4+2]*pixel[x*4+0]*2.0f);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*pixel[x*4+1]*2.0f);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*pixel[x*4+2]*2.0f);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*pixel[x*4+3]*2.0f);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
-               }
+       case DPSOFTRAST_BLENDMODE_PSEUDOALPHA:
+       case DPSOFTRAST_BLENDMODE_INVADD:
                break;
-       case DPSOFTRAST_BLENDMODE_SUBALPHA:
-               for (x = startx;x < endx;x++)
+       }
+       // put some special values at the end of the mask to ensure the loops end
+       pixelmask[endx] = 1;
+       pixelmask[endx+1] = 0;
+       // LordHavoc: use a double loop to identify subspans, this helps the
+       // optimized copy/blend loops to perform at their best, most triangles
+       // have only one run of pixels, and do the search using wide reads...
+       x = startx;
+       while (x < endx)
+       {
+               // if this pixel is masked off, it's probably not alone...
+               if (!pixelmask[x])
                {
-                       if (!pixelmask[x])
-                               continue;
-                       a = in4f[x*4+3] * -255.0f;
-                       d[0] = (int)(in4f[x*4+2]*a+pixel[x*4+0]);if (d[0] > 255) d[0] = 255;if (d[0] < 0) d[0] = 0;
-                       d[1] = (int)(in4f[x*4+1]*a+pixel[x*4+1]);if (d[1] > 255) d[1] = 255;if (d[1] < 0) d[1] = 0;
-                       d[2] = (int)(in4f[x*4+0]*a+pixel[x*4+2]);if (d[2] > 255) d[2] = 255;if (d[2] < 0) d[2] = 0;
-                       d[3] = (int)(in4f[x*4+3]*a+pixel[x*4+3]);if (d[3] > 255) d[3] = 255;if (d[3] < 0) d[3] = 0;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
+                       x++;
+#if 1
+                       if (x + 8 < endx)
+                       {
+                               // the 4-item search must be aligned or else it stalls badly
+                               if ((x & 3) && !pixelmask[x]) 
+                               {
+                                       if(pixelmask[x]) goto endmasked;
+                                       x++;
+                                       if (x & 3)
+                                       {
+                                               if(pixelmask[x]) goto endmasked;
+                                               x++;
+                                               if (x & 3)
+                                               {
+                                                       if(pixelmask[x]) goto endmasked;
+                                                       x++;
+                                               }
+                                       }
+                               }
+                               while (*(unsigned int *)&pixelmask[x] == 0x00000000)
+                                       x += 4;
+                       }
+#endif
+                       for (;!pixelmask[x];x++)
+                               ;
+                       // rather than continue the loop, just check the end variable
+                       if (x >= endx)
+                               break;
                }
-               break;
-       case DPSOFTRAST_BLENDMODE_PSEUDOALPHA:
-               for (x = startx;x < endx;x++)
+       endmasked:
+               // find length of subspan
+               subx = x + 1;
+#if 1
+               if (subx + 8 < endx)
                {
-                       if (!pixelmask[x])
-                               continue;
-                       a = 255.0f;
-                       b = 1.0f - in4f[x*4+3];
-                       d[0] = (int)(in4f[x*4+2]*a+pixel[x*4+0]*b);if (d[0] > 255) d[0] = 255;
-                       d[1] = (int)(in4f[x*4+1]*a+pixel[x*4+1]*b);if (d[1] > 255) d[1] = 255;
-                       d[2] = (int)(in4f[x*4+0]*a+pixel[x*4+2]*b);if (d[2] > 255) d[2] = 255;
-                       d[3] = (int)(in4f[x*4+3]*a+pixel[x*4+3]*b);if (d[3] > 255) d[3] = 255;
-                       pixel[x*4+0] = d[0];
-                       pixel[x*4+1] = d[1];
-                       pixel[x*4+2] = d[2];
-                       pixel[x*4+3] = d[3];
+                       if (subx & 3)
+                       {
+                               if(!pixelmask[subx]) goto endunmasked;
+                               subx++;
+                               if (subx & 3)
+                               {
+                                       if(!pixelmask[subx]) goto endunmasked;
+                                       subx++;
+                                       if (subx & 3)
+                                       {
+                                               if(!pixelmask[subx]) goto endunmasked;
+                                               subx++;
+                                       }
+                               }
+                       }
+                       while (*(unsigned int *)&pixelmask[subx] == 0x01010101)
+                               subx += 4;
                }
-               break;
-       }
-}
-
-void DPSOFTRAST_Draw_Span_FinishBGRA8(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, const unsigned char* RESTRICT in4ub)
-{
-#ifdef SSE2_PRESENT
-       int x;
-       int startx = span->startx;
-       int endx = span->endx;
-       const unsigned int * RESTRICT ini = (const unsigned int *)in4ub;
-       unsigned char * RESTRICT pixelmask = span->pixelmask;
-       unsigned char * RESTRICT pixel = (unsigned char *)dpsoftrast.fb_colorpixels[0];
-       unsigned int * RESTRICT pixeli = (unsigned int *)dpsoftrast.fb_colorpixels[0];
-       if (!pixel)
-               return;
-       pixel += (span->y * dpsoftrast.fb_width + span->x) * 4;
-       pixeli += span->y * dpsoftrast.fb_width + span->x;
-       // handle alphatest now (this affects depth writes too)
-       if (thread->alphatest)
-               for (x = startx;x < endx;x++)
-                       if (in4ub[x*4+3] < 0.5f)
-                               pixelmask[x] = false;
-       // FIXME: this does not handle bigendian
-       switch(thread->fb_blendmode)
-       {
-       case DPSOFTRAST_BLENDMODE_OPAQUE:
-               for (x = startx;x + 4 <= endx;)
+#endif
+               for (;pixelmask[subx];subx++)
+                       ;
+               // the checks can overshoot, so make sure to clip it...
+               if (subx > endx)
+                       subx = endx;
+       endunmasked:
+               // now that we know the subspan length...  process!
+               switch(thread->fb_blendmode)
                {
-                       if (*(const unsigned int *)&pixelmask[x] == 0x01010101)
+               case DPSOFTRAST_BLENDMODE_OPAQUE:
+#if 0
+                       if (subx - x >= 16)
                        {
-                               _mm_storeu_si128((__m128i *)&pixeli[x], _mm_loadu_si128((const __m128i *)&ini[x]));
-                               x += 4;
+                               memcpy(pixeli + x, ini + x, (subx - x) * sizeof(pixeli[x]));
+                               x = subx;
                        }
                        else
+#elif 1
+                       while (x + 16 <= subx)
+                       {
+                               _mm_storeu_si128((__m128i *)&pixeli[x], _mm_loadu_si128((const __m128i *)&ini[x]));
+                               _mm_storeu_si128((__m128i *)&pixeli[x+4], _mm_loadu_si128((const __m128i *)&ini[x+4]));
+                               _mm_storeu_si128((__m128i *)&pixeli[x+8], _mm_loadu_si128((const __m128i *)&ini[x+8]));
+                               _mm_storeu_si128((__m128i *)&pixeli[x+12], _mm_loadu_si128((const __m128i *)&ini[x+12]));
+                               x += 16;
+                       }
+#endif
                        {
-                               if (pixelmask[x])
+                               while (x + 4 <= subx)
+                               {
+                                       _mm_storeu_si128((__m128i *)&pixeli[x], _mm_loadu_si128((const __m128i *)&ini[x]));
+                                       x += 4;
+                               }
+                               if (x + 2 <= subx)
+                               {
+                                       pixeli[x] = ini[x];
+                                       pixeli[x+1] = ini[x+1];
+                                       x += 2;
+                               }
+                               if (x < subx)
+                               {
                                        pixeli[x] = ini[x];
-                               x++;
+                                       x++;
+                               }
                        }
-               }
-               for (;x < endx;x++)
-                       if (pixelmask[x])
-                               pixeli[x] = ini[x];
-               break;
-       case DPSOFTRAST_BLENDMODE_ALPHA:
-       #define FINISHBLEND(blend2, blend1) \
-               for (x = startx;x + 2 <= endx;x += 2) \
-               { \
-                       __m128i src, dst; \
-                       switch (*(const unsigned short*)&pixelmask[x]) \
+                       break;
+               case DPSOFTRAST_BLENDMODE_ALPHA:
+               #define FINISHBLEND(blend2, blend1) \
+                       for (;x + 1 < subx;x += 2) \
                        { \
-                       case 0x0101: \
+                               __m128i src, dst; \
                                src = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&ini[x]), _mm_setzero_si128()); \
                                dst = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&pixeli[x]), _mm_setzero_si128()); \
                                blend2; \
                                _mm_storel_epi64((__m128i *)&pixeli[x], _mm_packus_epi16(dst, dst)); \
-                               continue; \
-                       case 0x0100: \
-                               src = _mm_unpacklo_epi8(_mm_cvtsi32_si128(ini[x+1]), _mm_setzero_si128()); \
-                               dst = _mm_unpacklo_epi8(_mm_cvtsi32_si128(pixeli[x+1]), _mm_setzero_si128()); \
-                               blend1; \
-                               pixeli[x+1] = _mm_cvtsi128_si32(_mm_packus_epi16(dst, dst));  \
-                               continue; \
-                       case 0x0001: \
+                       } \
+                       if (x < subx) \
+                       { \
+                               __m128i src, dst; \
                                src = _mm_unpacklo_epi8(_mm_cvtsi32_si128(ini[x]), _mm_setzero_si128()); \
                                dst = _mm_unpacklo_epi8(_mm_cvtsi32_si128(pixeli[x]), _mm_setzero_si128()); \
                                blend1; \
                                pixeli[x] = _mm_cvtsi128_si32(_mm_packus_epi16(dst, dst)); \
-                               continue; \
-                       } \
-                       break; \
-               } \
-               for(;x < endx; x++) \
-               { \
-                       __m128i src, dst; \
-                       if (!pixelmask[x]) \
-                               continue; \
-                       src = _mm_unpacklo_epi8(_mm_cvtsi32_si128(ini[x]), _mm_setzero_si128()); \
-                       dst = _mm_unpacklo_epi8(_mm_cvtsi32_si128(pixeli[x]), _mm_setzero_si128()); \
-                       blend1; \
-                       pixeli[x] = _mm_cvtsi128_si32(_mm_packus_epi16(dst, dst)); \
+                               x++; \
+                       }
+                       FINISHBLEND({
+                               __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_add_epi16(dst, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(src, dst), 4), _mm_slli_epi16(blend, 4)));
+                       }, {
+                               __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_add_epi16(dst, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(src, dst), 4), _mm_slli_epi16(blend, 4)));
+                       });
+                       break;
+               case DPSOFTRAST_BLENDMODE_ADDALPHA:
+                       FINISHBLEND({
+                               __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_add_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
+                       }, {
+                               __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_add_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
+                       });
+                       break;
+               case DPSOFTRAST_BLENDMODE_ADD:
+                       FINISHBLEND({ dst = _mm_add_epi16(src, dst); }, { dst = _mm_add_epi16(src, dst); });
+                       break;
+               case DPSOFTRAST_BLENDMODE_INVMOD:
+                       FINISHBLEND({
+                               dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, src), 8));
+                       }, {
+                               dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, src), 8));
+                       });
+                       break;
+               case DPSOFTRAST_BLENDMODE_MUL:
+                       FINISHBLEND({ dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 8); }, { dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 8); });
+                       break;
+               case DPSOFTRAST_BLENDMODE_MUL2:
+                       FINISHBLEND({ dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 7); }, { dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 7); });
+                       break;
+               case DPSOFTRAST_BLENDMODE_SUBALPHA:
+                       FINISHBLEND({
+                               __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
+                       }, {
+                               __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
+                       });
+                       break;
+               case DPSOFTRAST_BLENDMODE_PSEUDOALPHA:
+                       FINISHBLEND({
+                               __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_add_epi16(src, _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, blend), 8)));
+                       }, {
+                               __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
+                               dst = _mm_add_epi16(src, _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, blend), 8)));
+                       });
+                       break;
+               case DPSOFTRAST_BLENDMODE_INVADD:
+                       FINISHBLEND({
+                               dst = _mm_add_epi16(dst, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(_mm_set1_epi16(255), dst), 4), _mm_slli_epi16(src, 4)));
+                       }, {
+                               dst = _mm_add_epi16(dst, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(_mm_set1_epi16(255), dst), 4), _mm_slli_epi16(src, 4)));
+                       });
+                       break;
                }
+       }
+#endif
+}
 
-               FINISHBLEND({
-                       __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_add_epi16(dst, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(src, dst), 4), _mm_slli_epi16(blend, 4)));
-               }, {
-                       __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_add_epi16(dst, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(src, dst), 4), _mm_slli_epi16(blend, 4)));
-               });
-               break;
-       case DPSOFTRAST_BLENDMODE_ADDALPHA:
-               FINISHBLEND({
-                       __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_add_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
-               }, {
-                       __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_add_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
-               });
-               break;
-       case DPSOFTRAST_BLENDMODE_ADD:
-               FINISHBLEND({ dst = _mm_add_epi16(src, dst); }, { dst = _mm_add_epi16(src, dst); });
-               break;
-       case DPSOFTRAST_BLENDMODE_INVMOD:
-               FINISHBLEND({
-                       dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, src), 8));
-               }, {
-                       dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, src), 8));
-               });
-               break;
-       case DPSOFTRAST_BLENDMODE_MUL:
-               FINISHBLEND({ dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 8); }, { dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 8); });
-               break;
-       case DPSOFTRAST_BLENDMODE_MUL2:
-               FINISHBLEND({ dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 7); }, { dst = _mm_srli_epi16(_mm_mullo_epi16(src, dst), 7); });
-               break;
-       case DPSOFTRAST_BLENDMODE_SUBALPHA:
-               FINISHBLEND({
-                       __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
-               }, {
-                       __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(src, blend), 8));
-               });
-               break;
-       case DPSOFTRAST_BLENDMODE_PSEUDOALPHA:
-               FINISHBLEND({
-                       __m128i blend = _mm_shufflehi_epi16(_mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_add_epi16(src, _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, blend), 8)));
-               }, {
-                       __m128i blend = _mm_shufflelo_epi16(src, _MM_SHUFFLE(3, 3, 3, 3));
-                       dst = _mm_add_epi16(src, _mm_sub_epi16(dst, _mm_srli_epi16(_mm_mullo_epi16(dst, blend), 8)));
-               });
-               break;
+static void DPSOFTRAST_Texture2DBGRA8(DPSOFTRAST_Texture *texture, int mip, float x, float y, unsigned char c[4])
+       // warning: this is SLOW, only use if the optimized per-span functions won't do
+{
+       const unsigned char * RESTRICT pixelbase;
+       const unsigned char * RESTRICT pixel[4];
+       int width = texture->mipmap[mip][2], height = texture->mipmap[mip][3];
+       int wrapmask[2] = { width-1, height-1 };
+       pixelbase = (unsigned char *)texture->bytes + texture->mipmap[mip][0] + texture->mipmap[mip][1] - 4*width;
+       if(texture->filter & DPSOFTRAST_TEXTURE_FILTER_LINEAR)
+       {
+               unsigned int tc[2] = { (unsigned int)floor(x) * (width<<12) - 2048, (unsigned int)floor(y) * (height<<12) - 2048};
+               unsigned int frac[2] = { tc[0]&0xFFF, tc[1]&0xFFF };
+               unsigned int ifrac[2] = { 0x1000 - frac[0], 0x1000 - frac[1] };
+               unsigned int lerp[4] = { ifrac[0]*ifrac[1], frac[0]*ifrac[1], ifrac[0]*frac[1], frac[0]*frac[1] };
+               int tci[2] = { (int)tc[0]>>12, (int)tc[1]>>12 };
+               int tci1[2] = { (int)tci[0] + 1, (int)tci[1] + 1 };
+               if (texture->flags & DPSOFTRAST_TEXTURE_FLAG_CLAMPTOEDGE)
+               {
+                       tci[0] = tci[0] >= 0 ? (tci[0] <= wrapmask[0] ? tci[0] : wrapmask[0]) : 0;
+                       tci[1] = tci[1] >= 0 ? (tci[1] <= wrapmask[1] ? tci[1] : wrapmask[1]) : 0;
+                       tci1[0] = tci1[0] >= 0 ? (tci1[0] <= wrapmask[0] ? tci1[0] : wrapmask[0]) : 0;
+                       tci1[1] = tci1[1] >= 0 ? (tci1[1] <= wrapmask[1] ? tci1[1] : wrapmask[1]) : 0;
+               }
+               else
+               {
+                       tci[0] &= wrapmask[0];
+                       tci[1] &= wrapmask[1];
+                       tci1[0] &= wrapmask[0];
+                       tci1[1] &= wrapmask[1];
+               }
+               pixel[0] = pixelbase + 4 * (tci[0] - tci[1]*width);
+               pixel[1] = pixelbase + 4 * (tci[0] - tci[1]*width);
+               pixel[2] = pixelbase + 4 * (tci[0] - tci1[1]*width);
+               pixel[3] = pixelbase + 4 * (tci[0] - tci1[1]*width);
+               c[0] = (pixel[0][0]*lerp[0]+pixel[1][0]*lerp[1]+pixel[2][0]*lerp[2]+pixel[3][0]*lerp[3])>>24;
+               c[1] = (pixel[0][1]*lerp[0]+pixel[1][1]*lerp[1]+pixel[2][1]*lerp[2]+pixel[3][1]*lerp[3])>>24;
+               c[2] = (pixel[0][2]*lerp[0]+pixel[1][2]*lerp[1]+pixel[2][2]*lerp[2]+pixel[3][2]*lerp[3])>>24;
+               c[3] = (pixel[0][3]*lerp[0]+pixel[1][3]*lerp[1]+pixel[2][3]*lerp[2]+pixel[3][3]*lerp[3])>>24;
+       }
+       else
+       {
+               int tci[2] = { (int)floor(x) * width, (int)floor(y) * height };
+               if (texture->flags & DPSOFTRAST_TEXTURE_FLAG_CLAMPTOEDGE)
+               {
+                       tci[0] = tci[0] >= 0 ? (tci[0] <= wrapmask[0] ? tci[0] : wrapmask[0]) : 0;
+                       tci[1] = tci[1] >= 0 ? (tci[1] <= wrapmask[1] ? tci[1] : wrapmask[1]) : 0;
+               }
+               else
+               {
+                       tci[0] &= wrapmask[0];
+                       tci[1] &= wrapmask[1];
+               }
+               pixel[0] = pixelbase + 4 * (tci[0] - tci[1]*width);
+               c[0] = pixel[0][0];
+               c[1] = pixel[0][1];
+               c[2] = pixel[0][2];
+               c[3] = pixel[0][3];
        }
-#endif
 }
 
-void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float * RESTRICT out4f, int texunitindex, int arrayindex, const float * RESTRICT zf)
+#if 0
+static void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float * RESTRICT out4f, int texunitindex, int arrayindex, const float * RESTRICT zf)
 {
        int x;
        int startx = span->startx;
@@ -2284,7 +2380,7 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
                return;
        }
        mip = triangle->mip[texunitindex];
-       pixelbase = (unsigned char *)texture->bytes + texture->mipmap[mip][0];
+       pixelbase = (unsigned char *)texture->bytes + texture->mipmap[mip][0] + texture->mipmap[mip][1] - 4*texture->mipmap[mip][2];
        // if this mipmap of the texture is 1 pixel, just fill it with that color
        if (texture->mipmap[mip][1] == 4)
        {
@@ -2306,35 +2402,45 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
        flags = texture->flags;
        tcscale[0] = texture->mipmap[mip][2];
        tcscale[1] = texture->mipmap[mip][3];
-       tciwidth = texture->mipmap[mip][2];
+       tciwidth = -texture->mipmap[mip][2];
        tcimin[0] = 0;
        tcimin[1] = 0;
        tcimax[0] = texture->mipmap[mip][2]-1;
        tcimax[1] = texture->mipmap[mip][3]-1;
        tciwrapmask[0] = texture->mipmap[mip][2]-1;
        tciwrapmask[1] = texture->mipmap[mip][3]-1;
-       endtc[0] = (data[0] + slope[0]*startx) * zf[startx] * tcscale[0] - 0.5f;
-       endtc[1] = (data[1] + slope[1]*startx) * zf[startx] * tcscale[1] - 0.5f;
+       endtc[0] = (data[0] + slope[0]*startx) * zf[startx] * tcscale[0];
+       endtc[1] = (data[1] + slope[1]*startx) * zf[startx] * tcscale[1];
+       if (filter)
+       {
+               endtc[0] -= 0.5f;
+               endtc[1] -= 0.5f;
+       }
        for (x = startx;x < endx;)
        {
                unsigned int subtc[2];
                unsigned int substep[2];
-               float subscale = 65536.0f/DPSOFTRAST_DRAW_MAXSUBSPAN;
+               float subscale = 4096.0f/DPSOFTRAST_DRAW_MAXSUBSPAN;
                int nextsub = x + DPSOFTRAST_DRAW_MAXSUBSPAN, endsub = nextsub - 1;
-               if(nextsub >= endx)
+               if (nextsub >= endx)
                {
                        nextsub = endsub = endx-1;      
-                       if(x < nextsub) subscale = 65536.0f / (nextsub - x);
+                       if (x < nextsub) subscale = 4096.0f / (nextsub - x);
                }
                tc[0] = endtc[0];
                tc[1] = endtc[1];
-               endtc[0] = (data[0] + slope[0]*nextsub) * zf[nextsub] * tcscale[0] - 0.5f;
-               endtc[1] = (data[1] + slope[1]*nextsub) * zf[nextsub] * tcscale[1] - 0.5f;
+               endtc[0] = (data[0] + slope[0]*nextsub) * zf[nextsub] * tcscale[0];
+               endtc[1] = (data[1] + slope[1]*nextsub) * zf[nextsub] * tcscale[1];
+               if (filter)
+               {
+                       endtc[0] -= 0.5f;
+                       endtc[1] -= 0.5f;
+               }
                substep[0] = (endtc[0] - tc[0]) * subscale;
                substep[1] = (endtc[1] - tc[1]) * subscale;
-               subtc[0] = tc[0] * (1<<16);
-               subtc[1] = tc[1] * (1<<16);
-               if(filter)
+               subtc[0] = tc[0] * (1<<12);
+               subtc[1] = tc[1] * (1<<12);
+               if (filter)
                {
                        if (flags & DPSOFTRAST_TEXTURE_FLAG_CLAMPTOEDGE)
                        {
@@ -2343,8 +2449,8 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
                                        unsigned int frac[2] = { subtc[0]&0xFFF, subtc[1]&0xFFF };
                                        unsigned int ifrac[2] = { 0x1000 - frac[0], 0x1000 - frac[1] };
                                        unsigned int lerp[4] = { ifrac[0]*ifrac[1], frac[0]*ifrac[1], ifrac[0]*frac[1], frac[0]*frac[1] };
-                                       tci[0] = subtc[0]>>16;
-                                       tci[1] = subtc[1]>>16;
+                                       tci[0] = subtc[0]>>12;
+                                       tci[1] = subtc[1]>>12;
                                        tci1[0] = tci[0] + 1;
                                        tci1[1] = tci[1] + 1;
                                        tci[0] = tci[0] >= tcimin[0] ? (tci[0] <= tcimax[0] ? tci[0] : tcimax[0]) : tcimin[0];
@@ -2372,8 +2478,8 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
                                        unsigned int frac[2] = { subtc[0]&0xFFF, subtc[1]&0xFFF };
                                        unsigned int ifrac[2] = { 0x1000 - frac[0], 0x1000 - frac[1] };
                                        unsigned int lerp[4] = { ifrac[0]*ifrac[1], frac[0]*ifrac[1], ifrac[0]*frac[1], frac[0]*frac[1] };
-                                       tci[0] = subtc[0]>>16;
-                                       tci[1] = subtc[1]>>16;
+                                       tci[0] = subtc[0]>>12;
+                                       tci[1] = subtc[1]>>12;
                                        tci1[0] = tci[0] + 1;
                                        tci1[1] = tci[1] + 1;
                                        tci[0] &= tciwrapmask[0];
@@ -2399,8 +2505,8 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
                {
                        for (; x <= endsub; x++, subtc[0] += substep[0], subtc[1] += substep[1])
                        {
-                               tci[0] = subtc[0]>>16;
-                               tci[1] = subtc[1]>>16;
+                               tci[0] = subtc[0]>>12;
+                               tci[1] = subtc[1]>>12;
                                tci[0] = tci[0] >= tcimin[0] ? (tci[0] <= tcimax[0] ? tci[0] : tcimax[0]) : tcimin[0];
                                tci[1] = tci[1] >= tcimin[1] ? (tci[1] <= tcimax[1] ? tci[1] : tcimax[1]) : tcimin[1];
                                pixel[0] = pixelbase + 4 * (tci[1]*tciwidth+tci[0]);
@@ -2418,8 +2524,8 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
                {
                        for (; x <= endsub; x++, subtc[0] += substep[0], subtc[1] += substep[1])
                        {
-                               tci[0] = subtc[0]>>16;
-                               tci[1] = subtc[1]>>16;
+                               tci[0] = subtc[0]>>12;
+                               tci[1] = subtc[1]>>12;
                                tci[0] &= tciwrapmask[0];
                                tci[1] &= tciwrapmask[1];
                                pixel[0] = pixelbase + 4 * (tci[1]*tciwidth+tci[0]);
@@ -2435,10 +2541,11 @@ void DPSOFTRAST_Draw_Span_Texture2DVarying(DPSOFTRAST_State_Thread *thread, cons
                }
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char * RESTRICT out4ub, int texunitindex, int arrayindex, const float * RESTRICT zf)
+static void DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char * RESTRICT out4ub, int texunitindex, int arrayindex, const float * RESTRICT zf)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x;
        int startx = span->startx;
        int endx = span->endx;
@@ -2449,17 +2556,18 @@ void DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(DPSOFTRAST_State_Thread *thread,
        __m128i subtc, substep, endsubtc;
        int filter;
        int mip;
+       int affine; // LordHavoc: optimized affine texturing case
        unsigned int * RESTRICT outi = (unsigned int *)out4ub;
        const unsigned char * RESTRICT pixelbase;
        DPSOFTRAST_Texture *texture = thread->texbound[texunitindex];
        // if no texture is bound, just fill it with white
        if (!texture)
        {
-               memset(out4ub + startx*4, 255, span->length*4);
+               memset(out4ub + startx*4, 255, (span->endx - span->startx)*4);
                return;
        }
        mip = triangle->mip[texunitindex];
-       pixelbase = (const unsigned char *)texture->bytes + texture->mipmap[mip][0];
+       pixelbase = (const unsigned char *)texture->bytes + texture->mipmap[mip][0] + texture->mipmap[mip][1] - 4*texture->mipmap[mip][2];
        // if this mipmap of the texture is 1 pixel, just fill it with that color
        if (texture->mipmap[mip][1] == 4)
        {
@@ -2468,6 +2576,7 @@ void DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(DPSOFTRAST_State_Thread *thread,
                        outi[x] = k;
                return;
        }
+       affine = zf[startx] == zf[endx-1];
        filter = texture->filter & DPSOFTRAST_TEXTURE_FILTER_LINEAR;
        DPSOFTRAST_CALCATTRIB(triangle, span, data, slope, arrayindex);
        flags = texture->flags;
@@ -2476,22 +2585,26 @@ void DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(DPSOFTRAST_State_Thread *thread,
        tcscale = _mm_cvtepi32_ps(tcsize);
        data = _mm_mul_ps(_mm_movelh_ps(data, data), tcscale);
        slope = _mm_mul_ps(_mm_movelh_ps(slope, slope), tcscale);
-       endtc = _mm_sub_ps(_mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(startx))), _mm_load1_ps(&zf[startx])), _mm_set1_ps(0.5f));
+       endtc = _mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(startx))), _mm_load1_ps(&zf[startx]));
+       if (filter)
+               endtc = _mm_sub_ps(endtc, _mm_set1_ps(0.5f));
        endsubtc = _mm_cvtps_epi32(_mm_mul_ps(endtc, _mm_set1_ps(65536.0f)));
-       tcoffset = _mm_add_epi32(_mm_slli_epi32(_mm_shuffle_epi32(tcsize, _MM_SHUFFLE(0, 0, 0, 0)), 18), _mm_set1_epi32(4));
+       tcoffset = _mm_add_epi32(_mm_slli_epi32(_mm_sub_epi32(_mm_setzero_si128(), _mm_shuffle_epi32(tcsize, _MM_SHUFFLE(0, 0, 0, 0))), 18), _mm_set1_epi32(4));
        tcmax = _mm_packs_epi32(tcmask, tcmask);
        for (x = startx;x < endx;)
        {
                int nextsub = x + DPSOFTRAST_DRAW_MAXSUBSPAN, endsub = nextsub - 1;
                __m128 subscale = _mm_set1_ps(65536.0f/DPSOFTRAST_DRAW_MAXSUBSPAN);
-               if(nextsub >= endx)
+               if (nextsub >= endx || affine)
                {
                        nextsub = endsub = endx-1;
-                       if(x < nextsub) subscale = _mm_set1_ps(65536.0f / (nextsub - x));
+                       if (x < nextsub) subscale = _mm_set1_ps(65536.0f / (nextsub - x));
                }       
                tc = endtc;
                subtc = endsubtc;
-               endtc = _mm_sub_ps(_mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(nextsub))), _mm_load1_ps(&zf[nextsub])), _mm_set1_ps(0.5f));
+               endtc = _mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(nextsub))), _mm_load1_ps(&zf[nextsub]));
+               if (filter)
+                       endtc = _mm_sub_ps(endtc, _mm_set1_ps(0.5f));
                substep = _mm_cvtps_epi32(_mm_mul_ps(_mm_sub_ps(endtc, tc), subscale));
                endsubtc = _mm_cvtps_epi32(_mm_mul_ps(endtc, _mm_set1_ps(65536.0f)));
                subtc = _mm_unpacklo_epi64(subtc, _mm_add_epi32(subtc, substep));
@@ -2711,19 +2824,20 @@ void DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(DPSOFTRAST_State_Thread *thread,
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_TextureCubeVaryingBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char * RESTRICT out4ub, int texunitindex, int arrayindex, const float * RESTRICT zf)
+static void DPSOFTRAST_Draw_Span_TextureCubeVaryingBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char * RESTRICT out4ub, int texunitindex, int arrayindex, const float * RESTRICT zf)
 {
        // TODO: IMPLEMENT
-       memset(out4ub, 255, span->length*4);
+       memset(out4ub + span->startx*4, 255, (span->startx - span->endx)*4);
 }
 
-float DPSOFTRAST_SampleShadowmap(const float *vector)
+static float DPSOFTRAST_SampleShadowmap(const float *vector)
 {
        // TODO: IMPLEMENT
        return 1.0f;
 }
 
-void DPSOFTRAST_Draw_Span_MultiplyVarying(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *in4f, int arrayindex, const float *zf)
+#if 0
+static void DPSOFTRAST_Draw_Span_MultiplyVarying(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *in4f, int arrayindex, const float *zf)
 {
        int x;
        int startx = span->startx;
@@ -2746,8 +2860,10 @@ void DPSOFTRAST_Draw_Span_MultiplyVarying(const DPSOFTRAST_State_Triangle * REST
                out4f[x*4+3] = in4f[x*4+3] * c[3];
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_Varying(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, int arrayindex, const float *zf)
+#if 0
+static void DPSOFTRAST_Draw_Span_Varying(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, int arrayindex, const float *zf)
 {
        int x;
        int startx = span->startx;
@@ -2770,8 +2886,10 @@ void DPSOFTRAST_Draw_Span_Varying(const DPSOFTRAST_State_Triangle * RESTRICT tri
                out4f[x*4+3] = c[3];
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_AddBloom(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f, const float *subcolor)
+#if 0
+static void DPSOFTRAST_Draw_Span_AddBloom(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f, const float *subcolor)
 {
        int x, startx = span->startx, endx = span->endx;
        float c[4], localcolor[4];
@@ -2791,8 +2909,10 @@ void DPSOFTRAST_Draw_Span_AddBloom(const DPSOFTRAST_State_Triangle * RESTRICT tr
                out4f[x*4+3] = ina4f[x*4+3] + c[3];
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_MultiplyBuffers(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f)
+#if 0
+static void DPSOFTRAST_Draw_Span_MultiplyBuffers(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f)
 {
        int x, startx = span->startx, endx = span->endx;
        for (x = startx;x < endx;x++)
@@ -2803,8 +2923,10 @@ void DPSOFTRAST_Draw_Span_MultiplyBuffers(const DPSOFTRAST_State_Triangle * REST
                out4f[x*4+3] = ina4f[x*4+3] * inb4f[x*4+3];
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_AddBuffers(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f)
+#if 0
+static void DPSOFTRAST_Draw_Span_AddBuffers(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f)
 {
        int x, startx = span->startx, endx = span->endx;
        for (x = startx;x < endx;x++)
@@ -2815,8 +2937,10 @@ void DPSOFTRAST_Draw_Span_AddBuffers(const DPSOFTRAST_State_Triangle * RESTRICT
                out4f[x*4+3] = ina4f[x*4+3] + inb4f[x*4+3];
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_MixBuffers(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f)
+#if 0
+static void DPSOFTRAST_Draw_Span_MixBuffers(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *ina4f, const float *inb4f)
 {
        int x, startx = span->startx, endx = span->endx;
        float a, b;
@@ -2830,8 +2954,10 @@ void DPSOFTRAST_Draw_Span_MixBuffers(const DPSOFTRAST_State_Triangle * RESTRICT
                out4f[x*4+3] = ina4f[x*4+3] * a + inb4f[x*4+3] * b;
        }
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_MixUniformColor(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *in4f, const float *color)
+#if 0
+static void DPSOFTRAST_Draw_Span_MixUniformColor(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, float *out4f, const float *in4f, const float *color)
 {
        int x, startx = span->startx, endx = span->endx;
        float localcolor[4], ilerp, lerp;
@@ -2849,99 +2975,128 @@ void DPSOFTRAST_Draw_Span_MixUniformColor(const DPSOFTRAST_State_Triangle * REST
                out4f[x*4+3] = in4f[x*4+3] * ilerp + localcolor[3] * lerp;
        }
 }
+#endif
 
 
 
-void DPSOFTRAST_Draw_Span_MultiplyVaryingBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *in4ub, int arrayindex, const float *zf)
+static void DPSOFTRAST_Draw_Span_MultiplyVaryingBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *in4ub, int arrayindex, const float *zf)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x;
        int startx = span->startx;
        int endx = span->endx;
        __m128 data, slope;
+       __m128 mod, endmod;
+       __m128i submod, substep, endsubmod;
        DPSOFTRAST_CALCATTRIB(triangle, span, data, slope, arrayindex);
        data = _mm_shuffle_ps(data, data, _MM_SHUFFLE(3, 0, 1, 2));
        slope = _mm_shuffle_ps(slope, slope, _MM_SHUFFLE(3, 0, 1, 2));
-       data = _mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(startx)));
-       data = _mm_mul_ps(data, _mm_set1_ps(256.0f));
-       slope = _mm_mul_ps(slope, _mm_set1_ps(256.0f));
-       for (x = startx;x+2 <= endx;x += 2, data = _mm_add_ps(data, slope))
-       {
-               __m128i pix = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_loadl_epi64((const __m128i *)&in4ub[x*4]));
-               __m128i mod = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&zf[x]))), mod2;
-               data = _mm_add_ps(data, slope);
-               mod2 = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&zf[x+1])));
-               mod = _mm_unpacklo_epi64(_mm_packs_epi32(mod, mod), _mm_packs_epi32(mod2, mod2));
-               pix = _mm_mulhi_epu16(pix, mod);
-               _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix, pix));
-       }
-       for (;x < endx;x++, data = _mm_add_ps(data, slope))
+       endmod = _mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(startx))), _mm_load1_ps(&zf[startx]));
+       endsubmod = _mm_cvtps_epi32(_mm_mul_ps(endmod, _mm_set1_ps(256.0f)));
+       for (x = startx; x < endx;)
        {
-               __m128i pix = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&in4ub[x*4]));
-               __m128i mod = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&zf[x])));
-               mod = _mm_packs_epi32(mod, mod);
-               pix = _mm_mulhi_epu16(pix, mod);
-               *(int *)&out4ub[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
+               int nextsub = x + DPSOFTRAST_DRAW_MAXSUBSPAN, endsub = nextsub - 1;
+               __m128 subscale = _mm_set1_ps(256.0f/DPSOFTRAST_DRAW_MAXSUBSPAN);
+               if (nextsub >= endx)
+               {
+                       nextsub = endsub = endx-1;
+                       if (x < nextsub) subscale = _mm_set1_ps(256.0f / (nextsub - x));
+               }
+               mod = endmod;
+               submod = endsubmod;
+               endmod = _mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(nextsub))), _mm_load1_ps(&zf[nextsub]));
+               substep = _mm_cvtps_epi32(_mm_mul_ps(_mm_sub_ps(endmod, mod), subscale));
+               endsubmod = _mm_cvtps_epi32(_mm_mul_ps(endmod, _mm_set1_ps(256.0f)));
+               submod = _mm_packs_epi32(submod, _mm_add_epi32(submod, substep));
+               substep = _mm_packs_epi32(substep, substep);
+               for (; x + 1 <= endsub; x += 2, submod = _mm_add_epi16(submod, substep))
+               {
+                       __m128i pix = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_loadl_epi64((const __m128i *)&in4ub[x*4]));
+                       pix = _mm_mulhi_epu16(pix, submod);
+                       _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix, pix));
+               }
+               if (x <= endsub)
+               {
+                       __m128i pix = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&in4ub[x*4]));
+                       pix = _mm_mulhi_epu16(pix, submod);
+                       *(int *)&out4ub[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
+                       x++;
+               }
        }
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_VaryingBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, int arrayindex, const float *zf)
+static void DPSOFTRAST_Draw_Span_VaryingBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, int arrayindex, const float *zf)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x;
        int startx = span->startx;
        int endx = span->endx;
        __m128 data, slope;
+       __m128 mod, endmod;
+       __m128i submod, substep, endsubmod;
        DPSOFTRAST_CALCATTRIB(triangle, span, data, slope, arrayindex);
        data = _mm_shuffle_ps(data, data, _MM_SHUFFLE(3, 0, 1, 2));
        slope = _mm_shuffle_ps(slope, slope, _MM_SHUFFLE(3, 0, 1, 2));
-       data = _mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(startx)));
-       data = _mm_mul_ps(data, _mm_set1_ps(255.0f));
-       slope = _mm_mul_ps(slope, _mm_set1_ps(255.0f));
-       for (x = startx;x+2 <= endx;x += 2, data = _mm_add_ps(data, slope))
-       {
-               __m128i pix = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&zf[x]))), pix2;
-               data = _mm_add_ps(data, slope);
-               pix2 = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&zf[x+1])));
-               pix = _mm_unpacklo_epi64(_mm_packs_epi32(pix, pix), _mm_packs_epi32(pix2, pix2));
-               _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix, pix));
-       }
-       for (;x < endx;x++, data = _mm_add_ps(data, slope))
+       endmod = _mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(startx))), _mm_load1_ps(&zf[startx]));
+       endsubmod = _mm_cvtps_epi32(_mm_mul_ps(endmod, _mm_set1_ps(4095.0f)));
+       for (x = startx; x < endx;)
        {
-               __m128i pix = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&zf[x])));
-               pix = _mm_packs_epi32(pix, pix);
-               *(int *)&out4ub[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
+               int nextsub = x + DPSOFTRAST_DRAW_MAXSUBSPAN, endsub = nextsub - 1;
+               __m128 subscale = _mm_set1_ps(4095.0f/DPSOFTRAST_DRAW_MAXSUBSPAN);
+               if (nextsub >= endx)
+               {
+                       nextsub = endsub = endx-1;
+                       if (x < nextsub) subscale = _mm_set1_ps(4095.0f / (nextsub - x));
+               }
+               mod = endmod;
+               submod = endsubmod;
+               endmod = _mm_mul_ps(_mm_add_ps(data, _mm_mul_ps(slope, _mm_set1_ps(nextsub))), _mm_load1_ps(&zf[nextsub]));
+               substep = _mm_cvtps_epi32(_mm_mul_ps(_mm_sub_ps(endmod, mod), subscale));
+               endsubmod = _mm_cvtps_epi32(_mm_mul_ps(endmod, _mm_set1_ps(4095.0f)));
+               submod = _mm_packs_epi32(submod, _mm_add_epi32(submod, substep));
+               substep = _mm_packs_epi32(substep, substep);
+               for (; x + 1 <= endsub; x += 2, submod = _mm_add_epi16(submod, substep))
+               {
+                       __m128i pix = _mm_srai_epi16(submod, 4);
+                       _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix, pix));
+               }
+               if (x <= endsub)
+               {
+                       __m128i pix = _mm_srai_epi16(submod, 4);
+                       *(int *)&out4ub[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
+                       x++;
+               }
        }
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_AddBloomBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub, const float *subcolor)
+static void DPSOFTRAST_Draw_Span_AddBloomBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub, const float *subcolor)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x, startx = span->startx, endx = span->endx;
        __m128i localcolor = _mm_shuffle_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_loadu_ps(subcolor), _mm_set1_ps(255.0f))), _MM_SHUFFLE(3, 0, 1, 2));
-       localcolor = _mm_shuffle_epi32(_mm_packs_epi32(localcolor, localcolor), _MM_SHUFFLE(1, 0, 1, 0));
+       localcolor = _mm_packs_epi32(localcolor, localcolor);
        for (x = startx;x+2 <= endx;x+=2)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&ina4ub[x*4]), _mm_setzero_si128());
                __m128i pix2 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&inb4ub[x*4]), _mm_setzero_si128());
-               pix1 = _mm_add_epi16(pix1, _mm_sub_epi16(pix2, localcolor));
+               pix1 = _mm_add_epi16(pix1, _mm_subs_epu16(pix2, localcolor));
                _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix1, pix1));
        }
-       if(x < endx)
+       if (x < endx)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&ina4ub[x*4]), _mm_setzero_si128());
                __m128i pix2 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&inb4ub[x*4]), _mm_setzero_si128());
-               pix1 = _mm_add_epi16(pix1, _mm_sub_epi16(pix2, localcolor));
+               pix1 = _mm_add_epi16(pix1, _mm_subs_epu16(pix2, localcolor));
                *(int *)&out4ub[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix1, pix1));
        }
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_MultiplyBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub)
+static void DPSOFTRAST_Draw_Span_MultiplyBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x, startx = span->startx, endx = span->endx;
        for (x = startx;x+2 <= endx;x+=2)
        {
@@ -2950,7 +3105,7 @@ void DPSOFTRAST_Draw_Span_MultiplyBuffersBGRA8(const DPSOFTRAST_State_Triangle *
                pix1 = _mm_mulhi_epu16(pix1, pix2);
                _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix1, pix1));
        }
-       if(x < endx)
+       if (x < endx)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&ina4ub[x*4]), _mm_setzero_si128());
                __m128i pix2 = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&inb4ub[x*4]));
@@ -2960,9 +3115,9 @@ void DPSOFTRAST_Draw_Span_MultiplyBuffersBGRA8(const DPSOFTRAST_State_Triangle *
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_AddBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub)
+static void DPSOFTRAST_Draw_Span_AddBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x, startx = span->startx, endx = span->endx;
        for (x = startx;x+2 <= endx;x+=2)
        {
@@ -2971,7 +3126,7 @@ void DPSOFTRAST_Draw_Span_AddBuffersBGRA8(const DPSOFTRAST_State_Triangle * REST
                pix1 = _mm_add_epi16(pix1, pix2);
                _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix1, pix1));
        }
-       if(x < endx)
+       if (x < endx)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&ina4ub[x*4]), _mm_setzero_si128());
                __m128i pix2 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&inb4ub[x*4]), _mm_setzero_si128());
@@ -2981,12 +3136,13 @@ void DPSOFTRAST_Draw_Span_AddBuffersBGRA8(const DPSOFTRAST_State_Triangle * REST
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_TintedAddBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub, const float *inbtintbgra)
+#if 0
+static void DPSOFTRAST_Draw_Span_TintedAddBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub, const float *inbtintbgra)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x, startx = span->startx, endx = span->endx;
        __m128i tint = _mm_cvtps_epi32(_mm_mul_ps(_mm_loadu_ps(inbtintbgra), _mm_set1_ps(256.0f)));
-       tint = _mm_shuffle_epi32(_mm_packs_epi32(tint, tint), _MM_SHUFFLE(1, 0, 1, 0));
+       tint = _mm_packs_epi32(tint, tint);
        for (x = startx;x+2 <= endx;x+=2)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i *)&ina4ub[x*4]), _mm_setzero_si128());
@@ -2994,7 +3150,7 @@ void DPSOFTRAST_Draw_Span_TintedAddBuffersBGRA8(const DPSOFTRAST_State_Triangle
                pix1 = _mm_add_epi16(pix1, _mm_mulhi_epu16(tint, pix2));
                _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix1, pix1));
        }
-       if(x < endx)
+       if (x < endx)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&ina4ub[x*4]), _mm_setzero_si128());
                __m128i pix2 = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&inb4ub[x*4]));
@@ -3003,10 +3159,11 @@ void DPSOFTRAST_Draw_Span_TintedAddBuffersBGRA8(const DPSOFTRAST_State_Triangle
        }
 #endif
 }
+#endif
 
-void DPSOFTRAST_Draw_Span_MixBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub)
+static void DPSOFTRAST_Draw_Span_MixBuffersBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *ina4ub, const unsigned char *inb4ub)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x, startx = span->startx, endx = span->endx;
        for (x = startx;x+2 <= endx;x+=2)
        {
@@ -3016,7 +3173,7 @@ void DPSOFTRAST_Draw_Span_MixBuffersBGRA8(const DPSOFTRAST_State_Triangle * REST
                pix1 = _mm_add_epi16(pix1, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(pix2, pix1), 4), _mm_slli_epi16(blend, 4)));
                _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix1, pix1));
        }
-       if(x < endx)
+       if (x < endx)
        {
                __m128i pix1 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&ina4ub[x*4]), _mm_setzero_si128());
                __m128i pix2 = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&inb4ub[x*4]), _mm_setzero_si128());
@@ -3027,12 +3184,12 @@ void DPSOFTRAST_Draw_Span_MixBuffersBGRA8(const DPSOFTRAST_State_Triangle * REST
 #endif
 }
 
-void DPSOFTRAST_Draw_Span_MixUniformColorBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *in4ub, const float *color)
+static void DPSOFTRAST_Draw_Span_MixUniformColorBGRA8(const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span, unsigned char *out4ub, const unsigned char *in4ub, const float *color)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int x, startx = span->startx, endx = span->endx;
        __m128i localcolor = _mm_shuffle_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_loadu_ps(color), _mm_set1_ps(255.0f))), _MM_SHUFFLE(3, 0, 1, 2)), blend;
-       localcolor = _mm_shuffle_epi32(_mm_packs_epi32(localcolor, localcolor), _MM_SHUFFLE(1, 0, 1, 0));
+       localcolor = _mm_packs_epi32(localcolor, localcolor);
        blend = _mm_slli_epi16(_mm_shufflehi_epi16(_mm_shufflelo_epi16(localcolor, _MM_SHUFFLE(3, 3, 3, 3)), _MM_SHUFFLE(3, 3, 3, 3)), 4);
        for (x = startx;x+2 <= endx;x+=2)
        {
@@ -3040,7 +3197,7 @@ void DPSOFTRAST_Draw_Span_MixUniformColorBGRA8(const DPSOFTRAST_State_Triangle *
                pix = _mm_add_epi16(pix, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(localcolor, pix), 4), blend));
                _mm_storel_epi64((__m128i *)&out4ub[x*4], _mm_packus_epi16(pix, pix));
        }
-       if(x < endx)
+       if (x < endx)
        {
                __m128i pix = _mm_unpacklo_epi8(_mm_cvtsi32_si128(*(const int *)&in4ub[x*4]), _mm_setzero_si128());
                pix = _mm_add_epi16(pix, _mm_mulhi_epi16(_mm_slli_epi16(_mm_sub_epi16(localcolor, pix), 4), blend));
@@ -3051,7 +3208,7 @@ void DPSOFTRAST_Draw_Span_MixUniformColorBGRA8(const DPSOFTRAST_State_Triangle *
 
 
 
-void DPSOFTRAST_VertexShader_Generic(void)
+static void DPSOFTRAST_VertexShader_Generic(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
        DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_COLOR);
@@ -3060,7 +3217,7 @@ void DPSOFTRAST_VertexShader_Generic(void)
                DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD1);
 }
 
-void DPSOFTRAST_PixelShader_Generic(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_Generic(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        unsigned char buffer_texture_colorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
@@ -3093,19 +3250,25 @@ void DPSOFTRAST_PixelShader_Generic(DPSOFTRAST_State_Thread *thread, const DPSOF
        }
        else
                DPSOFTRAST_Draw_Span_VaryingBGRA8(triangle, span, buffer_FragColorbgra8, 1, buffer_z);
+       if(thread->shader_permutation & SHADERPERMUTATION_ALPHAKILL)
+       {
+               int x;
+               for (x = span->startx;x < span->endx;x++)
+                       buffer_FragColorbgra8[x*4+3] = buffer_FragColorbgra8[x*4+3] * thread->uniform4f[DPSOFTRAST_UNIFORM_Alpha*4+0];
+       }
        DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 }
 
 
 
-void DPSOFTRAST_VertexShader_PostProcess(void)
+static void DPSOFTRAST_VertexShader_PostProcess(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
        DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD0);
-       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD1);
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD4);
 }
 
-void DPSOFTRAST_PixelShader_PostProcess(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_PostProcess(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
        // TODO: optimize!!  at the very least there is no reason to use texture sampling on the frame texture
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
@@ -3132,64 +3295,83 @@ void DPSOFTRAST_PixelShader_PostProcess(DPSOFTRAST_State_Thread *thread, const D
 
 
 
-void DPSOFTRAST_VertexShader_Depth_Or_Shadow(void)
+static void DPSOFTRAST_VertexShader_Depth_Or_Shadow(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
 }
 
-void DPSOFTRAST_PixelShader_Depth_Or_Shadow(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_Depth_Or_Shadow(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
        // this is never called (because colormask is off when this shader is used)
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
+       memset(buffer_FragColorbgra8 + span->startx*4, 0, (span->endx - span->startx)*4);
        DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 }
 
 
 
-void DPSOFTRAST_VertexShader_FlatColor(void)
+static void DPSOFTRAST_VertexShader_FlatColor(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
        DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD0, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_TexMatrixM1);
 }
 
-void DPSOFTRAST_PixelShader_FlatColor(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_FlatColor(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
+#ifdef SSE_POSSIBLE
+       unsigned char * RESTRICT pixelmask = span->pixelmask;
+       unsigned char * RESTRICT pixel = (unsigned char *)dpsoftrast.fb_colorpixels[0] + (span->y * dpsoftrast.fb_width + span->x) * 4;
        int x, startx = span->startx, endx = span->endx;
-       int Color_Ambienti[4];
+       __m128i Color_Ambientm;
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        unsigned char buffer_texture_colorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
-       Color_Ambienti[2] = (int)(thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4+0]*256.0f);
-       Color_Ambienti[1] = (int)(thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4+1]*256.0f);
-       Color_Ambienti[0] = (int)(thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4+2]*256.0f);
-       Color_Ambienti[3] = (int)(thread->uniform4f[DPSOFTRAST_UNIFORM_Alpha*4+0]        *256.0f);
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
        DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_colorbgra8, GL20TU_COLOR, 2, buffer_z);
+       if ((thread->shader_permutation & SHADERPERMUTATION_ALPHAKILL) || thread->fb_blendmode != DPSOFTRAST_BLENDMODE_OPAQUE)
+               pixel = buffer_FragColorbgra8;
+       Color_Ambientm = _mm_shuffle_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(&thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4]), _mm_set1_ps(256.0f))), _MM_SHUFFLE(3, 0, 1, 2));
+       Color_Ambientm = _mm_and_si128(Color_Ambientm, _mm_setr_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0));
+       Color_Ambientm = _mm_or_si128(Color_Ambientm, _mm_setr_epi32(0, 0, 0, (int)(thread->uniform4f[DPSOFTRAST_UNIFORM_Alpha*4+0]*255.0f)));
+       Color_Ambientm = _mm_packs_epi32(Color_Ambientm, Color_Ambientm);
        for (x = startx;x < endx;x++)
        {
-               buffer_FragColorbgra8[x*4+0] = (buffer_texture_colorbgra8[x*4+0] * Color_Ambienti[0])>>8;
-               buffer_FragColorbgra8[x*4+1] = (buffer_texture_colorbgra8[x*4+1] * Color_Ambienti[1])>>8;
-               buffer_FragColorbgra8[x*4+2] = (buffer_texture_colorbgra8[x*4+2] * Color_Ambienti[2])>>8;
-               buffer_FragColorbgra8[x*4+3] = (buffer_texture_colorbgra8[x*4+3] * Color_Ambienti[3])>>8;
+               __m128i color, pix;
+               if (x + 4 <= endx && *(const unsigned int *)&pixelmask[x] == 0x01010101)
+               {
+                       __m128i pix2;
+                       color = _mm_loadu_si128((const __m128i *)&buffer_texture_colorbgra8[x*4]);
+                       pix = _mm_mulhi_epu16(Color_Ambientm, _mm_unpacklo_epi8(_mm_setzero_si128(), color));
+                       pix2 = _mm_mulhi_epu16(Color_Ambientm, _mm_unpackhi_epi8(_mm_setzero_si128(), color));
+                       _mm_storeu_si128((__m128i *)&pixel[x*4], _mm_packus_epi16(pix, pix2));
+                       x += 3;
+                       continue;
+               }
+               if (!pixelmask[x])
+                       continue;
+               color = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&buffer_texture_colorbgra8[x*4]));
+               pix = _mm_mulhi_epu16(Color_Ambientm, color);
+               *(int *)&pixel[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
        }
-       DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
+       if (pixel == buffer_FragColorbgra8)
+               DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
+#endif
 }
 
 
 
-void DPSOFTRAST_VertexShader_VertexColor(void)
+static void DPSOFTRAST_VertexShader_VertexColor(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
        DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_COLOR);
        DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD0, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_TexMatrixM1);
 }
 
-void DPSOFTRAST_PixelShader_VertexColor(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_VertexColor(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        unsigned char * RESTRICT pixelmask = span->pixelmask;
        unsigned char * RESTRICT pixel = (unsigned char *)dpsoftrast.fb_colorpixels[0] + (span->y * dpsoftrast.fb_width + span->x) * 4;
        int x, startx = span->startx, endx = span->endx;
@@ -3201,7 +3383,7 @@ void DPSOFTRAST_PixelShader_VertexColor(DPSOFTRAST_State_Thread *thread, const D
        int arrayindex = DPSOFTRAST_ARRAY_COLOR;
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
        DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_colorbgra8, GL20TU_COLOR, 2, buffer_z);
-       if (thread->alphatest || thread->fb_blendmode != DPSOFTRAST_BLENDMODE_OPAQUE)
+       if ((thread->shader_permutation & SHADERPERMUTATION_ALPHAKILL) || thread->fb_blendmode != DPSOFTRAST_BLENDMODE_OPAQUE)
                pixel = buffer_FragColorbgra8;
        Color_Ambientm = _mm_shuffle_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(&thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4]), _mm_set1_ps(256.0f))), _MM_SHUFFLE(3, 0, 1, 2));
        Color_Ambientm = _mm_and_si128(Color_Ambientm, _mm_setr_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0));
@@ -3239,7 +3421,7 @@ void DPSOFTRAST_PixelShader_VertexColor(DPSOFTRAST_State_Thread *thread, const D
                        x += 3;
                        continue;
                }
-               if(!pixelmask[x])
+               if (!pixelmask[x])
                        continue;
                color = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&buffer_texture_colorbgra8[x*4]));
                mod = _mm_cvtps_epi32(_mm_mul_ps(data, _mm_load1_ps(&buffer_z[x]))); 
@@ -3247,23 +3429,23 @@ void DPSOFTRAST_PixelShader_VertexColor(DPSOFTRAST_State_Thread *thread, const D
                pix = _mm_mulhi_epu16(_mm_add_epi16(_mm_mulhi_epu16(mod, Color_Diffusem), Color_Ambientm), color);
                *(int *)&pixel[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
        }
-       if(pixel == buffer_FragColorbgra8)
+       if (pixel == buffer_FragColorbgra8)
                DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 #endif
 }
 
 
 
-void DPSOFTRAST_VertexShader_Lightmap(void)
+static void DPSOFTRAST_VertexShader_Lightmap(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
        DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD0, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_TexMatrixM1);
        DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_TEXCOORD4);
 }
 
-void DPSOFTRAST_PixelShader_Lightmap(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_Lightmap(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        unsigned char * RESTRICT pixelmask = span->pixelmask;
        unsigned char * RESTRICT pixel = (unsigned char *)dpsoftrast.fb_colorpixels[0] + (span->y * dpsoftrast.fb_width + span->x) * 4;
        int x, startx = span->startx, endx = span->endx;
@@ -3276,7 +3458,7 @@ void DPSOFTRAST_PixelShader_Lightmap(DPSOFTRAST_State_Thread *thread, const DPSO
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
        DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_colorbgra8, GL20TU_COLOR, DPSOFTRAST_ARRAY_TEXCOORD0, buffer_z);
        DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_lightmapbgra8, GL20TU_LIGHTMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
-       if (thread->alphatest || thread->fb_blendmode != DPSOFTRAST_BLENDMODE_OPAQUE)
+       if ((thread->shader_permutation & SHADERPERMUTATION_ALPHAKILL) || thread->fb_blendmode != DPSOFTRAST_BLENDMODE_OPAQUE)
                pixel = buffer_FragColorbgra8;
        Color_Ambientm = _mm_shuffle_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_load_ps(&thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4]), _mm_set1_ps(256.0f))), _MM_SHUFFLE(3, 0, 1, 2));
        Color_Ambientm = _mm_and_si128(Color_Ambientm, _mm_setr_epi32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0));
@@ -3311,7 +3493,7 @@ void DPSOFTRAST_PixelShader_Lightmap(DPSOFTRAST_State_Thread *thread, const DPSO
                                x += 3;
                                continue;
                        }
-                       if(!pixelmask[x])
+                       if (!pixelmask[x])
                                continue;
                        color = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&buffer_texture_colorbgra8[x*4]));
                        lightmap = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&buffer_texture_lightmapbgra8[x*4]));
@@ -3339,7 +3521,7 @@ void DPSOFTRAST_PixelShader_Lightmap(DPSOFTRAST_State_Thread *thread, const DPSO
                                x += 3;
                                continue;
                        }
-                       if(!pixelmask[x]) 
+                       if (!pixelmask[x]) 
                                continue;
                        color = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&buffer_texture_colorbgra8[x*4]));
                        lightmap = _mm_unpacklo_epi8(_mm_setzero_si128(), _mm_cvtsi32_si128(*(const int *)&buffer_texture_lightmapbgra8[x*4]));
@@ -3347,52 +3529,49 @@ void DPSOFTRAST_PixelShader_Lightmap(DPSOFTRAST_State_Thread *thread, const DPSO
                        *(int *)&pixel[x*4] = _mm_cvtsi128_si32(_mm_packus_epi16(pix, pix));
                }
        }
-       if(pixel == buffer_FragColorbgra8)
+       if (pixel == buffer_FragColorbgra8)
                DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 #endif
 }
 
 
+void DPSOFTRAST_VertexShader_LightDirection(void);
+void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span);
 
-void DPSOFTRAST_VertexShader_FakeLight(void)
+static void DPSOFTRAST_VertexShader_FakeLight(void)
 {
-       DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
+       DPSOFTRAST_VertexShader_LightDirection();
 }
 
-void DPSOFTRAST_PixelShader_FakeLight(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_FakeLight(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-       // TODO: IMPLEMENT
-       float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
-       unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
-       DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
-       DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
+       DPSOFTRAST_PixelShader_LightDirection(thread, triangle, span);
 }
 
 
 
-void DPSOFTRAST_VertexShader_LightDirectionMap_ModelSpace(void)
+static void DPSOFTRAST_VertexShader_LightDirectionMap_ModelSpace(void)
 {
-       DPSOFTRAST_VertexShader_Lightmap();
+       DPSOFTRAST_VertexShader_LightDirection();
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_TEXCOORD4);
 }
 
-void DPSOFTRAST_PixelShader_LightDirectionMap_ModelSpace(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_LightDirectionMap_ModelSpace(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-       DPSOFTRAST_PixelShader_Lightmap(thread, triangle, span);
-       // TODO: IMPLEMENT
+       DPSOFTRAST_PixelShader_LightDirection(thread, triangle, span);
 }
 
 
 
-void DPSOFTRAST_VertexShader_LightDirectionMap_TangentSpace(void)
+static void DPSOFTRAST_VertexShader_LightDirectionMap_TangentSpace(void)
 {
-       DPSOFTRAST_VertexShader_Lightmap();
+       DPSOFTRAST_VertexShader_LightDirection();
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_TEXCOORD4);
 }
 
-void DPSOFTRAST_PixelShader_LightDirectionMap_TangentSpace(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_LightDirectionMap_TangentSpace(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-       DPSOFTRAST_PixelShader_Lightmap(thread, triangle, span);
-       // TODO: IMPLEMENT
+       DPSOFTRAST_PixelShader_LightDirection(thread, triangle, span);
 }
 
 
@@ -3440,20 +3619,20 @@ void DPSOFTRAST_VertexShader_LightDirection(void)
                LightVector[0] = svector[0] * LightDir[0] + svector[1] * LightDir[1] + svector[2] * LightDir[2];
                LightVector[1] = tvector[0] * LightDir[0] + tvector[1] * LightDir[1] + tvector[2] * LightDir[2];
                LightVector[2] = normal[0] * LightDir[0] + normal[1] * LightDir[1] + normal[2] * LightDir[2];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+0] = LightVector[0];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+1] = LightVector[1];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+2] = LightVector[2];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+3] = 0.0f;
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD5][i*4+0] = LightVector[0];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD5][i*4+1] = LightVector[1];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD5][i*4+2] = LightVector[2];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD5][i*4+3] = 0.0f;
                EyeVectorModelSpace[0] = EyePosition[0] - position[0];
                EyeVectorModelSpace[1] = EyePosition[1] - position[1];
                EyeVectorModelSpace[2] = EyePosition[2] - position[2];
                EyeVector[0] = svector[0] * EyeVectorModelSpace[0] + svector[1] * EyeVectorModelSpace[1] + svector[2] * EyeVectorModelSpace[2];
                EyeVector[1] = tvector[0] * EyeVectorModelSpace[0] + tvector[1] * EyeVectorModelSpace[1] + tvector[2] * EyeVectorModelSpace[2];
                EyeVector[2] = normal[0]  * EyeVectorModelSpace[0] + normal[1]  * EyeVectorModelSpace[1] + normal[2]  * EyeVectorModelSpace[2];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+0] = EyeVector[0];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+1] = EyeVector[1];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+2] = EyeVector[2];
-               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+3] = 0.0f;
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+0] = EyeVector[0];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+1] = EyeVector[1];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+2] = EyeVector[2];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+3] = 0.0f;
        }
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, -1, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
 }
@@ -3486,6 +3665,8 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
        unsigned char buffer_texture_glowbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_texture_pantsbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_texture_shirtbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
+       unsigned char buffer_texture_deluxemapbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
+       unsigned char buffer_texture_lightmapbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        int x, startx = span->startx, endx = span->endx;
        float Color_Ambient[4], Color_Diffuse[4], Color_Specular[4], Color_Glow[4], Color_Pants[4], Color_Shirt[4], LightColor[4];
@@ -3493,11 +3674,18 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
        float LightVectorslope[4];
        float EyeVectordata[4];
        float EyeVectorslope[4];
+       float VectorSdata[4];
+       float VectorSslope[4];
+       float VectorTdata[4];
+       float VectorTslope[4];
+       float VectorRdata[4];
+       float VectorRslope[4];
        float z;
        float diffusetex[4];
        float glosstex[4];
        float surfacenormal[4];
        float lightnormal[4];
+       float lightnormal_modelspace[4];
        float eyenormal[4];
        float specularnormal[4];
        float diffuse;
@@ -3541,15 +3729,37 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
                LightColor[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_LightColor*4+1];
                LightColor[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_LightColor*4+2];
                LightColor[3] = 0.0f;
-               DPSOFTRAST_CALCATTRIB4F(triangle, span, LightVectordata, LightVectorslope, DPSOFTRAST_ARRAY_TEXCOORD1);
                DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_normalbgra8, GL20TU_NORMAL, DPSOFTRAST_ARRAY_TEXCOORD0, buffer_z);
                Color_Specular[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Specular*4+0];
                Color_Specular[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Specular*4+1];
                Color_Specular[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Specular*4+2];
                Color_Specular[3] = 0.0f;
                SpecularPower = thread->uniform4f[DPSOFTRAST_UNIFORM_SpecularPower*4+0] * (1.0f / 255.0f);
-               DPSOFTRAST_CALCATTRIB4F(triangle, span, EyeVectordata, EyeVectorslope, DPSOFTRAST_ARRAY_TEXCOORD2);
+               DPSOFTRAST_CALCATTRIB4F(triangle, span, EyeVectordata, EyeVectorslope, DPSOFTRAST_ARRAY_TEXCOORD6);
                DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_glossbgra8, GL20TU_GLOSS, DPSOFTRAST_ARRAY_TEXCOORD0, buffer_z);
+
+               if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE)
+               {
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, VectorSdata, VectorSslope, DPSOFTRAST_ARRAY_TEXCOORD1);
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, VectorTdata, VectorTslope, DPSOFTRAST_ARRAY_TEXCOORD2);
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, VectorRdata, VectorRslope, DPSOFTRAST_ARRAY_TEXCOORD3);
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_lightmapbgra8, GL20TU_LIGHTMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_deluxemapbgra8, GL20TU_DELUXEMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+               }
+               else if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE)
+               {
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_lightmapbgra8, GL20TU_LIGHTMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_deluxemapbgra8, GL20TU_DELUXEMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+               }
+               else if(thread->shader_mode == SHADERMODE_FAKELIGHT)
+               {
+                       // nothing of this needed
+               }
+               else
+               {
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, LightVectordata, LightVectorslope, DPSOFTRAST_ARRAY_TEXCOORD5);
+               }
+
                for (x = startx;x < endx;x++)
                {
                        z = buffer_z[x];
@@ -3573,24 +3783,106 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
                        surfacenormal[2] = buffer_texture_normalbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
                        DPSOFTRAST_Vector3Normalize(surfacenormal);
 
-                       lightnormal[0] = (LightVectordata[0] + LightVectorslope[0]*x) * z;
-                       lightnormal[1] = (LightVectordata[1] + LightVectorslope[1]*x) * z;
-                       lightnormal[2] = (LightVectordata[2] + LightVectorslope[2]*x) * z;
-                       DPSOFTRAST_Vector3Normalize(lightnormal);
+                       if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE)
+                       {
+                               // myhalf3 lightnormal_modelspace = myhalf3(dp_texture2D(Texture_Deluxemap, TexCoordSurfaceLightmap.zw)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n";
+                               lightnormal_modelspace[0] = buffer_texture_deluxemapbgra8[x*4+2] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal_modelspace[1] = buffer_texture_deluxemapbgra8[x*4+1] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal_modelspace[2] = buffer_texture_deluxemapbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
+
+                               // lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
+                               lightnormal[0] = lightnormal_modelspace[0] * (VectorSdata[0] + VectorSslope[0] * x)
+                                              + lightnormal_modelspace[1] * (VectorSdata[1] + VectorSslope[1] * x)
+                                              + lightnormal_modelspace[2] * (VectorSdata[2] + VectorSslope[2] * x);
+
+                               // lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
+                               lightnormal[1] = lightnormal_modelspace[0] * (VectorTdata[0] + VectorTslope[0] * x)
+                                              + lightnormal_modelspace[1] * (VectorTdata[1] + VectorTslope[1] * x)
+                                              + lightnormal_modelspace[2] * (VectorTdata[2] + VectorTslope[2] * x);
+
+                               // lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
+                               lightnormal[2] = lightnormal_modelspace[0] * (VectorRdata[0] + VectorRslope[0] * x)
+                                              + lightnormal_modelspace[1] * (VectorRdata[1] + VectorRslope[1] * x)
+                                              + lightnormal_modelspace[2] * (VectorRdata[2] + VectorRslope[2] * x);
+
+                               // lightnormal = normalize(lightnormal); // VectorS/T/R are not always perfectly normalized, and EXACTSPECULARMATH is very picky about this\n"
+                               DPSOFTRAST_Vector3Normalize(lightnormal);
+
+                               // myhalf3 lightcolor = myhalf3(dp_texture2D(Texture_Lightmap, TexCoordSurfaceLightmap.zw));\n";
+                               {
+                                       float f = 1.0f / (256.0f * max(0.25f, lightnormal[2]));
+                                       LightColor[0] = buffer_texture_lightmapbgra8[x*4+0] * f;
+                                       LightColor[1] = buffer_texture_lightmapbgra8[x*4+1] * f;
+                                       LightColor[2] = buffer_texture_lightmapbgra8[x*4+2] * f;
+                               }
+                       }
+                       else if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE)
+                       {
+                               lightnormal[0] = buffer_texture_deluxemapbgra8[x*4+2] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal[1] = buffer_texture_deluxemapbgra8[x*4+1] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal[2] = buffer_texture_deluxemapbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
+                               {
+                                       float f = 1.0f / 256.0f;
+                                       LightColor[0] = buffer_texture_lightmapbgra8[x*4+0] * f;
+                                       LightColor[1] = buffer_texture_lightmapbgra8[x*4+1] * f;
+                                       LightColor[2] = buffer_texture_lightmapbgra8[x*4+2] * f;
+                               }
+                       }
+                       else if(thread->shader_mode == SHADERMODE_FAKELIGHT)
+                       {
+                               lightnormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
+                               lightnormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
+                               lightnormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(lightnormal);
+
+                               LightColor[0] = 1.0;
+                               LightColor[1] = 1.0;
+                               LightColor[2] = 1.0;
+                       }
+                       else
+                       {
+                               lightnormal[0] = (LightVectordata[0] + LightVectorslope[0]*x) * z;
+                               lightnormal[1] = (LightVectordata[1] + LightVectorslope[1]*x) * z;
+                               lightnormal[2] = (LightVectordata[2] + LightVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(lightnormal);
+                       }
 
-                       eyenormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
-                       eyenormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
-                       eyenormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
-                       DPSOFTRAST_Vector3Normalize(eyenormal);
+                       diffuse = DPSOFTRAST_Vector3Dot(surfacenormal, lightnormal);if (diffuse < 0.0f) diffuse = 0.0f;
 
-                       specularnormal[0] = lightnormal[0] + eyenormal[0];
-                       specularnormal[1] = lightnormal[1] + eyenormal[1];
-                       specularnormal[2] = lightnormal[2] + eyenormal[2];
-                       DPSOFTRAST_Vector3Normalize(specularnormal);
+                       if(thread->shader_exactspecularmath)
+                       {
+                               // reflect lightnormal at surfacenormal, take the negative of that
+                               // i.e. we want (2*dot(N, i) * N - I) for N=surfacenormal, I=lightnormal
+                               float f;
+                               f = DPSOFTRAST_Vector3Dot(lightnormal, surfacenormal);
+                               specularnormal[0] = 2*f*surfacenormal[0] - lightnormal[0];
+                               specularnormal[1] = 2*f*surfacenormal[1] - lightnormal[1];
+                               specularnormal[2] = 2*f*surfacenormal[2] - lightnormal[2];
+
+                               // dot of this and normalize(EyeVectorFogDepth.xyz)
+                               eyenormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
+                               eyenormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
+                               eyenormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(eyenormal);
+
+                               specular = DPSOFTRAST_Vector3Dot(eyenormal, specularnormal);if (specular < 0.0f) specular = 0.0f;
+                       }
+                       else
+                       {
+                               eyenormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
+                               eyenormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
+                               eyenormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(eyenormal);
+
+                               specularnormal[0] = lightnormal[0] + eyenormal[0];
+                               specularnormal[1] = lightnormal[1] + eyenormal[1];
+                               specularnormal[2] = lightnormal[2] + eyenormal[2];
+                               DPSOFTRAST_Vector3Normalize(specularnormal);
+
+                               specular = DPSOFTRAST_Vector3Dot(surfacenormal, specularnormal);if (specular < 0.0f) specular = 0.0f;
+                       }
+                       specular = pow(specular, 1.0f + SpecularPower * glosstex[3]);
 
-                       diffuse = DPSOFTRAST_Vector3Dot(surfacenormal, lightnormal);if (diffuse < 0.0f) diffuse = 0.0f;
-                       specular = DPSOFTRAST_Vector3Dot(surfacenormal, specularnormal);if (specular < 0.0f) specular = 0.0f;
-                       specular = pow(specular, SpecularPower * glosstex[3]);
                        if (thread->shader_permutation & SHADERPERMUTATION_GLOW)
                        {
                                d[0] = (int)(buffer_texture_glowbgra8[x*4+0] * Color_Glow[0] + diffusetex[0] * Color_Ambient[0] + (diffusetex[0] * Color_Diffuse[0] * diffuse + glosstex[0] * Color_Specular[0] * specular) * LightColor[0]);if (d[0] > 255) d[0] = 255;
@@ -3605,6 +3897,7 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
                                d[2] = (int)(                                                  diffusetex[2] * Color_Ambient[2] + (diffusetex[2] * Color_Diffuse[2] * diffuse + glosstex[2] * Color_Specular[2] * specular) * LightColor[2]);if (d[2] > 255) d[2] = 255;
                                d[3] = (int)(                                                  diffusetex[3] * Color_Ambient[3]);if (d[3] > 255) d[3] = 255;
                        }
+
                        buffer_FragColorbgra8[x*4+0] = d[0];
                        buffer_FragColorbgra8[x*4+1] = d[1];
                        buffer_FragColorbgra8[x*4+2] = d[2];
@@ -3621,8 +3914,30 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
                LightColor[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_LightColor*4+1];
                LightColor[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_LightColor*4+2];
                LightColor[3] = 0.0f;
-               DPSOFTRAST_CALCATTRIB4F(triangle, span, LightVectordata, LightVectorslope, DPSOFTRAST_ARRAY_TEXCOORD1);
                DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_normalbgra8, GL20TU_NORMAL, DPSOFTRAST_ARRAY_TEXCOORD0, buffer_z);
+
+               if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE)
+               {
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, VectorSdata, VectorSslope, DPSOFTRAST_ARRAY_TEXCOORD1);
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, VectorTdata, VectorTslope, DPSOFTRAST_ARRAY_TEXCOORD2);
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, VectorRdata, VectorRslope, DPSOFTRAST_ARRAY_TEXCOORD3);
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_lightmapbgra8, GL20TU_LIGHTMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_deluxemapbgra8, GL20TU_DELUXEMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+               }
+               else if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE)
+               {
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_lightmapbgra8, GL20TU_LIGHTMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+                       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_deluxemapbgra8, GL20TU_DELUXEMAP, DPSOFTRAST_ARRAY_TEXCOORD4, buffer_z);
+               }
+               else if(thread->shader_mode == SHADERMODE_FAKELIGHT)
+               {
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, EyeVectordata, EyeVectorslope, DPSOFTRAST_ARRAY_TEXCOORD6);
+               }
+               else
+               {
+                       DPSOFTRAST_CALCATTRIB4F(triangle, span, LightVectordata, LightVectorslope, DPSOFTRAST_ARRAY_TEXCOORD5);
+               }
+
                for (x = startx;x < endx;x++)
                {
                        z = buffer_z[x];
@@ -3635,10 +3950,69 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
                        surfacenormal[2] = buffer_texture_normalbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
                        DPSOFTRAST_Vector3Normalize(surfacenormal);
 
-                       lightnormal[0] = (LightVectordata[0] + LightVectorslope[0]*x) * z;
-                       lightnormal[1] = (LightVectordata[1] + LightVectorslope[1]*x) * z;
-                       lightnormal[2] = (LightVectordata[2] + LightVectorslope[2]*x) * z;
-                       DPSOFTRAST_Vector3Normalize(lightnormal);
+                       if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE)
+                       {
+                               // myhalf3 lightnormal_modelspace = myhalf3(dp_texture2D(Texture_Deluxemap, TexCoordSurfaceLightmap.zw)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n";
+                               lightnormal_modelspace[0] = buffer_texture_deluxemapbgra8[x*4+2] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal_modelspace[1] = buffer_texture_deluxemapbgra8[x*4+1] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal_modelspace[2] = buffer_texture_deluxemapbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
+
+                               // lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
+                               lightnormal[0] = lightnormal_modelspace[0] * (VectorSdata[0] + VectorSslope[0] * x)
+                                              + lightnormal_modelspace[1] * (VectorSdata[1] + VectorSslope[1] * x)
+                                              + lightnormal_modelspace[2] * (VectorSdata[2] + VectorSslope[2] * x);
+
+                               // lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
+                               lightnormal[1] = lightnormal_modelspace[0] * (VectorTdata[0] + VectorTslope[0] * x)
+                                              + lightnormal_modelspace[1] * (VectorTdata[1] + VectorTslope[1] * x)
+                                              + lightnormal_modelspace[2] * (VectorTdata[2] + VectorTslope[2] * x);
+
+                               // lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
+                               lightnormal[2] = lightnormal_modelspace[0] * (VectorRdata[0] + VectorRslope[0] * x)
+                                              + lightnormal_modelspace[1] * (VectorRdata[1] + VectorRslope[1] * x)
+                                              + lightnormal_modelspace[2] * (VectorRdata[2] + VectorRslope[2] * x);
+
+                               // lightnormal = normalize(lightnormal); // VectorS/T/R are not always perfectly normalized, and EXACTSPECULARMATH is very picky about this\n"
+                               DPSOFTRAST_Vector3Normalize(lightnormal);
+
+                               // myhalf3 lightcolor = myhalf3(dp_texture2D(Texture_Lightmap, TexCoordSurfaceLightmap.zw));\n";
+                               {
+                                       float f = 1.0f / (256.0f * max(0.25f, lightnormal[2]));
+                                       LightColor[0] = buffer_texture_lightmapbgra8[x*4+0] * f;
+                                       LightColor[1] = buffer_texture_lightmapbgra8[x*4+1] * f;
+                                       LightColor[2] = buffer_texture_lightmapbgra8[x*4+2] * f;
+                               }
+                       }
+                       else if(thread->shader_mode == SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE)
+                       {
+                               lightnormal[0] = buffer_texture_deluxemapbgra8[x*4+2] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal[1] = buffer_texture_deluxemapbgra8[x*4+1] * (1.0f / 128.0f) - 1.0f;
+                               lightnormal[2] = buffer_texture_deluxemapbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
+                               {
+                                       float f = 1.0f / 256.0f;
+                                       LightColor[0] = buffer_texture_lightmapbgra8[x*4+0] * f;
+                                       LightColor[1] = buffer_texture_lightmapbgra8[x*4+1] * f;
+                                       LightColor[2] = buffer_texture_lightmapbgra8[x*4+2] * f;
+                               }
+                       }
+                       else if(thread->shader_mode == SHADERMODE_FAKELIGHT)
+                       {
+                               lightnormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
+                               lightnormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
+                               lightnormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(lightnormal);
+
+                               LightColor[0] = 1.0;
+                               LightColor[1] = 1.0;
+                               LightColor[2] = 1.0;
+                       }
+                       else
+                       {
+                               lightnormal[0] = (LightVectordata[0] + LightVectorslope[0]*x) * z;
+                               lightnormal[1] = (LightVectordata[1] + LightVectorslope[1]*x) * z;
+                               lightnormal[2] = (LightVectordata[2] + LightVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(lightnormal);
+                       }
 
                        diffuse = DPSOFTRAST_Vector3Dot(surfacenormal, lightnormal);if (diffuse < 0.0f) diffuse = 0.0f;
                        if (thread->shader_permutation & SHADERPERMUTATION_GLOW)
@@ -3665,7 +4039,7 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
        {
                for (x = startx;x < endx;x++)
                {
-                       z = buffer_z[x];
+                       // z = buffer_z[x];
                        diffusetex[0] = buffer_texture_colorbgra8[x*4+0];
                        diffusetex[1] = buffer_texture_colorbgra8[x*4+1];
                        diffusetex[2] = buffer_texture_colorbgra8[x*4+2];
@@ -3696,7 +4070,7 @@ void DPSOFTRAST_PixelShader_LightDirection(DPSOFTRAST_State_Thread *thread, cons
 
 
 
-void DPSOFTRAST_VertexShader_LightSource(void)
+static void DPSOFTRAST_VertexShader_LightSource(void)
 {
        int i;
        int numvertices = dpsoftrast.numvertices;
@@ -3763,9 +4137,9 @@ void DPSOFTRAST_VertexShader_LightSource(void)
        DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelToLightM1);
 }
 
-void DPSOFTRAST_PixelShader_LightSource(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_LightSource(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        unsigned char buffer_texture_colorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_texture_normalbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
@@ -3775,7 +4149,7 @@ void DPSOFTRAST_PixelShader_LightSource(DPSOFTRAST_State_Thread *thread, const D
        unsigned char buffer_texture_shirtbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        int x, startx = span->startx, endx = span->endx;
-       float Color_Ambient[4], Color_Diffuse[4], Color_Specular[4], Color_Glow[4], Color_Pants[4], Color_Shirt[4], LightColor[4];
+       float Color_Ambient[4], Color_Diffuse[4], Color_Specular[4], /*Color_Glow[4],*/ Color_Pants[4], Color_Shirt[4], LightColor[4];
        float CubeVectordata[4];
        float CubeVectorslope[4];
        float LightVectordata[4];
@@ -3795,10 +4169,12 @@ void DPSOFTRAST_PixelShader_LightSource(DPSOFTRAST_State_Thread *thread, const D
        float CubeVector[4];
        float attenuation;
        int d[4];
+#if 0
        Color_Glow[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Glow*4+0];
        Color_Glow[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Glow*4+1];
        Color_Glow[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Glow*4+2];
        Color_Glow[3] = 0.0f;
+#endif
        Color_Ambient[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4+0];
        Color_Ambient[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4+1];
        Color_Ambient[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_Color_Ambient*4+2];
@@ -3882,19 +4258,42 @@ void DPSOFTRAST_PixelShader_LightSource(DPSOFTRAST_State_Thread *thread, const D
                        lightnormal[2] = (LightVectordata[2] + LightVectorslope[2]*x) * z;
                        DPSOFTRAST_Vector3Normalize(lightnormal);
 
-                       eyenormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
-                       eyenormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
-                       eyenormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
-                       DPSOFTRAST_Vector3Normalize(eyenormal);
+                       diffuse = DPSOFTRAST_Vector3Dot(surfacenormal, lightnormal);if (diffuse < 0.0f) diffuse = 0.0f;
+
+                       if(thread->shader_exactspecularmath)
+                       {
+                               // reflect lightnormal at surfacenormal, take the negative of that
+                               // i.e. we want (2*dot(N, i) * N - I) for N=surfacenormal, I=lightnormal
+                               float f;
+                               f = DPSOFTRAST_Vector3Dot(lightnormal, surfacenormal);
+                               specularnormal[0] = 2*f*surfacenormal[0] - lightnormal[0];
+                               specularnormal[1] = 2*f*surfacenormal[1] - lightnormal[1];
+                               specularnormal[2] = 2*f*surfacenormal[2] - lightnormal[2];
+
+                               // dot of this and normalize(EyeVectorFogDepth.xyz)
+                               eyenormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
+                               eyenormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
+                               eyenormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(eyenormal);
+
+                               specular = DPSOFTRAST_Vector3Dot(eyenormal, specularnormal);if (specular < 0.0f) specular = 0.0f;
+                       }
+                       else
+                       {
+                               eyenormal[0] = (EyeVectordata[0] + EyeVectorslope[0]*x) * z;
+                               eyenormal[1] = (EyeVectordata[1] + EyeVectorslope[1]*x) * z;
+                               eyenormal[2] = (EyeVectordata[2] + EyeVectorslope[2]*x) * z;
+                               DPSOFTRAST_Vector3Normalize(eyenormal);
 
-                       specularnormal[0] = lightnormal[0] + eyenormal[0];
-                       specularnormal[1] = lightnormal[1] + eyenormal[1];
-                       specularnormal[2] = lightnormal[2] + eyenormal[2];
-                       DPSOFTRAST_Vector3Normalize(specularnormal);
+                               specularnormal[0] = lightnormal[0] + eyenormal[0];
+                               specularnormal[1] = lightnormal[1] + eyenormal[1];
+                               specularnormal[2] = lightnormal[2] + eyenormal[2];
+                               DPSOFTRAST_Vector3Normalize(specularnormal);
+
+                               specular = DPSOFTRAST_Vector3Dot(surfacenormal, specularnormal);if (specular < 0.0f) specular = 0.0f;
+                       }
+                       specular = pow(specular, 1.0f + SpecularPower * glosstex[3]);
 
-                       diffuse = DPSOFTRAST_Vector3Dot(surfacenormal, lightnormal);if (diffuse < 0.0f) diffuse = 0.0f;
-                       specular = DPSOFTRAST_Vector3Dot(surfacenormal, specularnormal);if (specular < 0.0f) specular = 0.0f;
-                       specular = pow(specular, SpecularPower * glosstex[3]);
                        if (thread->shader_permutation & SHADERPERMUTATION_CUBEFILTER)
                        {
                                // scale down the attenuation to account for the cubefilter multiplying everything by 255
@@ -4037,87 +4436,292 @@ void DPSOFTRAST_PixelShader_LightSource(DPSOFTRAST_State_Thread *thread, const D
 
 
 
-void DPSOFTRAST_VertexShader_Refraction(void)
+static void DPSOFTRAST_VertexShader_Refraction(void)
 {
+       DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
+       DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD0, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_TexMatrixM1);
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
 }
 
-void DPSOFTRAST_PixelShader_Refraction(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_Refraction(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-       // TODO: IMPLEMENT
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
+       //float z;
+       int x, startx = span->startx, endx = span->endx;
+
+       // texture reads
+       unsigned char buffer_texture_normalbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
+
+       // varyings
+       float ModelViewProjectionPositiondata[4];
+       float ModelViewProjectionPositionslope[4];
+
+       // uniforms
+       float ScreenScaleRefractReflect[2];
+       float ScreenCenterRefractReflect[2];
+       float DistortScaleRefractReflect[2];
+       float RefractColor[4];
+
+       DPSOFTRAST_Texture *texture = thread->texbound[GL20TU_REFRACTION];
+       if(!texture) return;
+
+       // read textures
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
+       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_normalbgra8, GL20TU_NORMAL, DPSOFTRAST_ARRAY_TEXCOORD0, buffer_z);
+
+       // read varyings
+       DPSOFTRAST_CALCATTRIB4F(triangle, span, ModelViewProjectionPositiondata, ModelViewProjectionPositionslope, DPSOFTRAST_ARRAY_TEXCOORD4);
+
+       // read uniforms
+       ScreenScaleRefractReflect[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect*4+0];
+       ScreenScaleRefractReflect[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect*4+1];
+       ScreenCenterRefractReflect[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect*4+0];
+       ScreenCenterRefractReflect[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect*4+1];
+       DistortScaleRefractReflect[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_DistortScaleRefractReflect*4+0];
+       DistortScaleRefractReflect[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_DistortScaleRefractReflect*4+1];
+       RefractColor[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+2];
+       RefractColor[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+1];
+       RefractColor[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+0];
+       RefractColor[3] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+3];
+
+       // do stuff
+       for (x = startx;x < endx;x++)
+       {
+               float SafeScreenTexCoord[2];
+               float ScreenTexCoord[2];
+               float v[3];
+               float iw;
+               unsigned char c[4];
+
+               //z = buffer_z[x];
+
+               // "    vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
+               iw = 1.0f / (ModelViewProjectionPositiondata[3] + ModelViewProjectionPositionslope[3]*x); // / z
+
+               // "    vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
+               SafeScreenTexCoord[0] = (ModelViewProjectionPositiondata[0] + ModelViewProjectionPositionslope[0]*x) * iw * ScreenScaleRefractReflect[0] + ScreenCenterRefractReflect[0]; // * z (disappears)
+               SafeScreenTexCoord[1] = (ModelViewProjectionPositiondata[1] + ModelViewProjectionPositionslope[1]*x) * iw * ScreenScaleRefractReflect[1] + ScreenCenterRefractReflect[1]; // * z (disappears)
+
+               // "    vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(dp_texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
+               v[0] = buffer_texture_normalbgra8[x*4+2] * (1.0f / 128.0f) - 1.0f;
+               v[1] = buffer_texture_normalbgra8[x*4+1] * (1.0f / 128.0f) - 1.0f;
+               v[2] = buffer_texture_normalbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
+               DPSOFTRAST_Vector3Normalize(v);
+               ScreenTexCoord[0] = SafeScreenTexCoord[0] + v[0] * DistortScaleRefractReflect[0];
+               ScreenTexCoord[1] = SafeScreenTexCoord[1] + v[1] * DistortScaleRefractReflect[1];
+
+               // "    dp_FragColor = vec4(dp_texture2D(Texture_Refraction, ScreenTexCoord).rgb, 1.0) * RefractColor;\n"
+               DPSOFTRAST_Texture2DBGRA8(texture, 0, ScreenTexCoord[0], ScreenTexCoord[1], c);
+
+               buffer_FragColorbgra8[x*4+0] = c[0] * RefractColor[0];
+               buffer_FragColorbgra8[x*4+1] = c[1] * RefractColor[1];
+               buffer_FragColorbgra8[x*4+2] = c[2] * RefractColor[2];
+               buffer_FragColorbgra8[x*4+3] = min(RefractColor[3] * 256, 255);
+       }
+
        DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 }
 
 
 
-void DPSOFTRAST_VertexShader_Water(void)
+static void DPSOFTRAST_VertexShader_Water(void)
 {
-       DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
+       int i;
+       int numvertices = dpsoftrast.numvertices;
+       float EyePosition[4];
+       float EyeVectorModelSpace[4];
+       float EyeVector[4];
+       float position[4];
+       float svector[4];
+       float tvector[4];
+       float normal[4];
+       EyePosition[0] = dpsoftrast.uniform4f[DPSOFTRAST_UNIFORM_EyePosition*4+0];
+       EyePosition[1] = dpsoftrast.uniform4f[DPSOFTRAST_UNIFORM_EyePosition*4+1];
+       EyePosition[2] = dpsoftrast.uniform4f[DPSOFTRAST_UNIFORM_EyePosition*4+2];
+       EyePosition[3] = dpsoftrast.uniform4f[DPSOFTRAST_UNIFORM_EyePosition*4+3];
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION);
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD1);
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD2);
+       DPSOFTRAST_Array_Load(DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD3);
+       for (i = 0;i < numvertices;i++)
+       {
+               position[0] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_POSITION][i*4+0];
+               position[1] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_POSITION][i*4+1];
+               position[2] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_POSITION][i*4+2];
+               svector[0] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+0];
+               svector[1] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+1];
+               svector[2] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD1][i*4+2];
+               tvector[0] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+0];
+               tvector[1] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+1];
+               tvector[2] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD2][i*4+2];
+               normal[0] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD3][i*4+0];
+               normal[1] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD3][i*4+1];
+               normal[2] = dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD3][i*4+2];
+               EyeVectorModelSpace[0] = EyePosition[0] - position[0];
+               EyeVectorModelSpace[1] = EyePosition[1] - position[1];
+               EyeVectorModelSpace[2] = EyePosition[2] - position[2];
+               EyeVector[0] = svector[0] * EyeVectorModelSpace[0] + svector[1] * EyeVectorModelSpace[1] + svector[2] * EyeVectorModelSpace[2];
+               EyeVector[1] = tvector[0] * EyeVectorModelSpace[0] + tvector[1] * EyeVectorModelSpace[1] + tvector[2] * EyeVectorModelSpace[2];
+               EyeVector[2] = normal[0]  * EyeVectorModelSpace[0] + normal[1]  * EyeVectorModelSpace[1] + normal[2]  * EyeVectorModelSpace[2];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+0] = EyeVector[0];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+1] = EyeVector[1];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+2] = EyeVector[2];
+               dpsoftrast.post_array4f[DPSOFTRAST_ARRAY_TEXCOORD6][i*4+3] = 0.0f;
+       }
+       DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, -1, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
+       DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
+       DPSOFTRAST_Array_Transform(DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD0, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_TexMatrixM1);
 }
 
 
-void DPSOFTRAST_PixelShader_Water(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_Water(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
-       // TODO: IMPLEMENT
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
+       // float z;
+       int x, startx = span->startx, endx = span->endx;
+
+       // texture reads
+       unsigned char buffer_texture_normalbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
-       DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
-       DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
-}
 
+       // varyings
+       float ModelViewProjectionPositiondata[4];
+       float ModelViewProjectionPositionslope[4];
+       float EyeVectordata[4];
+       float EyeVectorslope[4];
 
+       // uniforms
+       float ScreenScaleRefractReflect[4];
+       float ScreenCenterRefractReflect[4];
+       float DistortScaleRefractReflect[4];
+       float RefractColor[4];
+       float ReflectColor[4];
+       float ReflectFactor;
+       float ReflectOffset;
 
-void DPSOFTRAST_VertexShader_ShowDepth(void)
-{
-       DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
-}
+       DPSOFTRAST_Texture *texture_refraction = thread->texbound[GL20TU_REFRACTION];
+       DPSOFTRAST_Texture *texture_reflection = thread->texbound[GL20TU_REFLECTION];
+       if(!texture_refraction || !texture_reflection) return;
 
-void DPSOFTRAST_PixelShader_ShowDepth(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
-{
-       // TODO: IMPLEMENT
-       float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
-       unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
+       // read textures
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
+       DPSOFTRAST_Draw_Span_Texture2DVaryingBGRA8(thread, triangle, span, buffer_texture_normalbgra8, GL20TU_NORMAL, DPSOFTRAST_ARRAY_TEXCOORD0, buffer_z);
+
+       // read varyings
+       DPSOFTRAST_CALCATTRIB4F(triangle, span, ModelViewProjectionPositiondata, ModelViewProjectionPositionslope, DPSOFTRAST_ARRAY_TEXCOORD4);
+       DPSOFTRAST_CALCATTRIB4F(triangle, span, EyeVectordata, EyeVectorslope, DPSOFTRAST_ARRAY_TEXCOORD6);
+
+       // read uniforms
+       ScreenScaleRefractReflect[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect*4+0];
+       ScreenScaleRefractReflect[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect*4+1];
+       ScreenScaleRefractReflect[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect*4+2];
+       ScreenScaleRefractReflect[3] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect*4+3];
+       ScreenCenterRefractReflect[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect*4+0];
+       ScreenCenterRefractReflect[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect*4+1];
+       ScreenCenterRefractReflect[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect*4+2];
+       ScreenCenterRefractReflect[3] = thread->uniform4f[DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect*4+3];
+       DistortScaleRefractReflect[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_DistortScaleRefractReflect*4+0];
+       DistortScaleRefractReflect[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_DistortScaleRefractReflect*4+1];
+       DistortScaleRefractReflect[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_DistortScaleRefractReflect*4+2];
+       DistortScaleRefractReflect[3] = thread->uniform4f[DPSOFTRAST_UNIFORM_DistortScaleRefractReflect*4+3];
+       RefractColor[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+2];
+       RefractColor[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+1];
+       RefractColor[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+0];
+       RefractColor[3] = thread->uniform4f[DPSOFTRAST_UNIFORM_RefractColor*4+3];
+       ReflectColor[0] = thread->uniform4f[DPSOFTRAST_UNIFORM_ReflectColor*4+2];
+       ReflectColor[1] = thread->uniform4f[DPSOFTRAST_UNIFORM_ReflectColor*4+1];
+       ReflectColor[2] = thread->uniform4f[DPSOFTRAST_UNIFORM_ReflectColor*4+0];
+       ReflectColor[3] = thread->uniform4f[DPSOFTRAST_UNIFORM_ReflectColor*4+3];
+       ReflectFactor = thread->uniform4f[DPSOFTRAST_UNIFORM_ReflectFactor*4+0];
+       ReflectOffset = thread->uniform4f[DPSOFTRAST_UNIFORM_ReflectOffset*4+0];
+
+       // do stuff
+       for (x = startx;x < endx;x++)
+       {
+               float SafeScreenTexCoord[4];
+               float ScreenTexCoord[4];
+               float v[3];
+               float iw;
+               unsigned char c1[4];
+               unsigned char c2[4];
+               float Fresnel;
+
+               // z = buffer_z[x];
+
+               // "    vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
+               iw = 1.0f / (ModelViewProjectionPositiondata[3] + ModelViewProjectionPositionslope[3]*x); // / z
+
+               // "    vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
+               SafeScreenTexCoord[0] = (ModelViewProjectionPositiondata[0] + ModelViewProjectionPositionslope[0]*x) * iw * ScreenScaleRefractReflect[0] + ScreenCenterRefractReflect[0]; // * z (disappears)
+               SafeScreenTexCoord[1] = (ModelViewProjectionPositiondata[1] + ModelViewProjectionPositionslope[1]*x) * iw * ScreenScaleRefractReflect[1] + ScreenCenterRefractReflect[1]; // * z (disappears)
+               SafeScreenTexCoord[2] = (ModelViewProjectionPositiondata[0] + ModelViewProjectionPositionslope[0]*x) * iw * ScreenScaleRefractReflect[2] + ScreenCenterRefractReflect[2]; // * z (disappears)
+               SafeScreenTexCoord[3] = (ModelViewProjectionPositiondata[1] + ModelViewProjectionPositionslope[1]*x) * iw * ScreenScaleRefractReflect[3] + ScreenCenterRefractReflect[3]; // * z (disappears)
+
+               // "    vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(dp_texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
+               v[0] = buffer_texture_normalbgra8[x*4+2] * (1.0f / 128.0f) - 1.0f;
+               v[1] = buffer_texture_normalbgra8[x*4+1] * (1.0f / 128.0f) - 1.0f;
+               v[2] = buffer_texture_normalbgra8[x*4+0] * (1.0f / 128.0f) - 1.0f;
+               DPSOFTRAST_Vector3Normalize(v);
+               ScreenTexCoord[0] = SafeScreenTexCoord[0] + v[0] * DistortScaleRefractReflect[0];
+               ScreenTexCoord[1] = SafeScreenTexCoord[1] + v[1] * DistortScaleRefractReflect[1];
+               ScreenTexCoord[2] = SafeScreenTexCoord[2] + v[0] * DistortScaleRefractReflect[2];
+               ScreenTexCoord[3] = SafeScreenTexCoord[3] + v[1] * DistortScaleRefractReflect[3];
+
+               // "    float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
+               v[0] = (EyeVectordata[0] + EyeVectorslope[0] * x); // * z (disappears)
+               v[1] = (EyeVectordata[1] + EyeVectorslope[1] * x); // * z (disappears)
+               v[2] = (EyeVectordata[2] + EyeVectorslope[2] * x); // * z (disappears)
+               DPSOFTRAST_Vector3Normalize(v);
+               Fresnel = 1.0f - v[2];
+               Fresnel = min(1.0f, Fresnel);
+               Fresnel = Fresnel * Fresnel * ReflectFactor + ReflectOffset;
+
+               // "    dp_FragColor = vec4(dp_texture2D(Texture_Refraction, ScreenTexCoord).rgb, 1.0) * RefractColor;\n"
+               // "    dp_FragColor = mix(vec4(dp_texture2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, vec4(dp_texture2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
+               DPSOFTRAST_Texture2DBGRA8(texture_refraction, 0, ScreenTexCoord[0], ScreenTexCoord[1], c1);
+               DPSOFTRAST_Texture2DBGRA8(texture_reflection, 0, ScreenTexCoord[2], ScreenTexCoord[3], c2);
+
+               buffer_FragColorbgra8[x*4+0] = (c1[0] * RefractColor[0]) * (1.0f - Fresnel) + (c2[0] * ReflectColor[0]) * Fresnel;
+               buffer_FragColorbgra8[x*4+1] = (c1[1] * RefractColor[1]) * (1.0f - Fresnel) + (c2[1] * ReflectColor[1]) * Fresnel;
+               buffer_FragColorbgra8[x*4+2] = (c1[2] * RefractColor[2]) * (1.0f - Fresnel) + (c2[2] * ReflectColor[2]) * Fresnel;
+               buffer_FragColorbgra8[x*4+3] = min((    RefractColor[3] *  (1.0f - Fresnel) +          ReflectColor[3]  * Fresnel) * 256, 255);
+       }
+
        DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 }
 
 
 
-void DPSOFTRAST_VertexShader_DeferredGeometry(void)
+static void DPSOFTRAST_VertexShader_DeferredGeometry(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
 }
 
-void DPSOFTRAST_PixelShader_DeferredGeometry(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_DeferredGeometry(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
        // TODO: IMPLEMENT
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
+       memset(buffer_FragColorbgra8 + span->startx*4, 0, (span->endx - span->startx)*4);
        DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 }
 
 
 
-void DPSOFTRAST_VertexShader_DeferredLightSource(void)
+static void DPSOFTRAST_VertexShader_DeferredLightSource(void)
 {
        DPSOFTRAST_Array_TransformProject(DPSOFTRAST_ARRAY_POSITION, DPSOFTRAST_ARRAY_POSITION, dpsoftrast.uniform4f + 4*DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1);
 }
 
-void DPSOFTRAST_PixelShader_DeferredLightSource(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
+static void DPSOFTRAST_PixelShader_DeferredLightSource(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Triangle * RESTRICT triangle, const DPSOFTRAST_State_Span * RESTRICT span)
 {
        // TODO: IMPLEMENT
        float buffer_z[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        unsigned char buffer_FragColorbgra8[DPSOFTRAST_DRAW_MAXSPANLENGTH*4];
        DPSOFTRAST_Draw_Span_Begin(thread, triangle, span, buffer_z);
-       memset(buffer_FragColorbgra8, 0, span->length*4);
+       memset(buffer_FragColorbgra8 + span->startx*4, 0, (span->endx - span->startx)*4);
        DPSOFTRAST_Draw_Span_FinishBGRA8(thread, triangle, span, buffer_FragColorbgra8);
 }
 
@@ -4135,114 +4739,118 @@ DPSOFTRAST_ShaderModeInfo;
 
 static const DPSOFTRAST_ShaderModeInfo DPSOFTRAST_ShaderModeTable[SHADERMODE_COUNT] =
 {
-       {2, DPSOFTRAST_VertexShader_Generic,                        DPSOFTRAST_PixelShader_Generic,                        {DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, ~0}, {GL20TU_FIRST, GL20TU_SECOND, ~0}},
-       {2, DPSOFTRAST_VertexShader_PostProcess,                    DPSOFTRAST_PixelShader_PostProcess,                    {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, ~0}, {GL20TU_FIRST, GL20TU_SECOND, ~0}},
-       {2, DPSOFTRAST_VertexShader_Depth_Or_Shadow,                DPSOFTRAST_PixelShader_Depth_Or_Shadow,                {~0}, {~0}},
-       {2, DPSOFTRAST_VertexShader_FlatColor,                      DPSOFTRAST_PixelShader_FlatColor,                      {DPSOFTRAST_ARRAY_TEXCOORD0, ~0}, {GL20TU_COLOR, ~0}},
-       {2, DPSOFTRAST_VertexShader_VertexColor,                    DPSOFTRAST_PixelShader_VertexColor,                    {DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_TEXCOORD0, ~0}, {GL20TU_COLOR, ~0}},
-       {2, DPSOFTRAST_VertexShader_Lightmap,                       DPSOFTRAST_PixelShader_Lightmap,                       {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD4, ~0}, {GL20TU_COLOR, GL20TU_LIGHTMAP, GL20TU_GLOW, ~0}},
-       {2, DPSOFTRAST_VertexShader_FakeLight,                      DPSOFTRAST_PixelShader_FakeLight,                      {~0}, {~0}},
-       {2, DPSOFTRAST_VertexShader_LightDirectionMap_ModelSpace,   DPSOFTRAST_PixelShader_LightDirectionMap_ModelSpace,   {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD4, ~0}, {GL20TU_COLOR, GL20TU_LIGHTMAP, GL20TU_GLOW, ~0}},
-       {2, DPSOFTRAST_VertexShader_LightDirectionMap_TangentSpace, DPSOFTRAST_PixelShader_LightDirectionMap_TangentSpace, {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD4, ~0}, {GL20TU_COLOR, GL20TU_LIGHTMAP, GL20TU_GLOW, ~0}},
-       {2, DPSOFTRAST_VertexShader_LightDirection,                 DPSOFTRAST_PixelShader_LightDirection,                 {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, ~0}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, ~0}},
-       {2, DPSOFTRAST_VertexShader_LightSource,                    DPSOFTRAST_PixelShader_LightSource,                    {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD4, ~0}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, GL20TU_CUBE, ~0}},
-       {2, DPSOFTRAST_VertexShader_Refraction,                     DPSOFTRAST_PixelShader_Refraction,                     {~0}},
-       {2, DPSOFTRAST_VertexShader_Water,                          DPSOFTRAST_PixelShader_Water,                          {~0}},
-       {2, DPSOFTRAST_VertexShader_ShowDepth,                      DPSOFTRAST_PixelShader_ShowDepth,                      {~0}},
-       {2, DPSOFTRAST_VertexShader_DeferredGeometry,               DPSOFTRAST_PixelShader_DeferredGeometry,               {~0}},
-       {2, DPSOFTRAST_VertexShader_DeferredLightSource,            DPSOFTRAST_PixelShader_DeferredLightSource,            {~0}}
+       {2, DPSOFTRAST_VertexShader_Generic,                        DPSOFTRAST_PixelShader_Generic,                        {DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, 0xFF}, {GL20TU_FIRST, GL20TU_SECOND, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_PostProcess,                    DPSOFTRAST_PixelShader_PostProcess,                    {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, 0xFF}, {GL20TU_FIRST, GL20TU_SECOND, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_Depth_Or_Shadow,                DPSOFTRAST_PixelShader_Depth_Or_Shadow,                {0xFF}, {0xFF}},
+       {2, DPSOFTRAST_VertexShader_FlatColor,                      DPSOFTRAST_PixelShader_FlatColor,                      {DPSOFTRAST_ARRAY_TEXCOORD0, 0xFF}, {GL20TU_COLOR, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_VertexColor,                    DPSOFTRAST_PixelShader_VertexColor,                    {DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_TEXCOORD0, 0xFF}, {GL20TU_COLOR, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_Lightmap,                       DPSOFTRAST_PixelShader_Lightmap,                       {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD4, 0xFF}, {GL20TU_COLOR, GL20TU_LIGHTMAP, GL20TU_GLOW, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_FakeLight,                      DPSOFTRAST_PixelShader_FakeLight,                      {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD5, DPSOFTRAST_ARRAY_TEXCOORD6, 0xFF}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_LightDirectionMap_ModelSpace,   DPSOFTRAST_PixelShader_LightDirectionMap_ModelSpace,   {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_TEXCOORD5, DPSOFTRAST_ARRAY_TEXCOORD6, 0xFF}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, GL20TU_LIGHTMAP, GL20TU_DELUXEMAP, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_LightDirectionMap_TangentSpace, DPSOFTRAST_PixelShader_LightDirectionMap_TangentSpace, {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_TEXCOORD5, DPSOFTRAST_ARRAY_TEXCOORD6, 0xFF}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, GL20TU_LIGHTMAP, GL20TU_DELUXEMAP, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_Lightmap,                       DPSOFTRAST_PixelShader_Lightmap,                       {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD4, 0xFF}, {GL20TU_COLOR, GL20TU_LIGHTMAP, GL20TU_GLOW, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_VertexColor,                        DPSOFTRAST_PixelShader_VertexColor,                    {DPSOFTRAST_ARRAY_COLOR, DPSOFTRAST_ARRAY_TEXCOORD0, 0xFF}, {GL20TU_COLOR, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_LightDirection,                 DPSOFTRAST_PixelShader_LightDirection,                 {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD5, DPSOFTRAST_ARRAY_TEXCOORD6, 0xFF}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_LightSource,                    DPSOFTRAST_PixelShader_LightSource,                    {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD4, 0xFF}, {GL20TU_COLOR, GL20TU_PANTS, GL20TU_SHIRT, GL20TU_GLOW, GL20TU_NORMAL, GL20TU_GLOSS, GL20TU_CUBE, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_Refraction,                     DPSOFTRAST_PixelShader_Refraction,                     {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD4, 0xFF}, {GL20TU_NORMAL, GL20TU_REFRACTION, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_Water,                          DPSOFTRAST_PixelShader_Water,                          {DPSOFTRAST_ARRAY_TEXCOORD0, DPSOFTRAST_ARRAY_TEXCOORD1, DPSOFTRAST_ARRAY_TEXCOORD2, DPSOFTRAST_ARRAY_TEXCOORD3, DPSOFTRAST_ARRAY_TEXCOORD4, DPSOFTRAST_ARRAY_TEXCOORD6, 0xFF}, {GL20TU_NORMAL, GL20TU_REFLECTION, GL20TU_REFRACTION, 0xFF}},
+       {2, DPSOFTRAST_VertexShader_DeferredGeometry,               DPSOFTRAST_PixelShader_DeferredGeometry,               {0xFF}},
+       {2, DPSOFTRAST_VertexShader_DeferredLightSource,            DPSOFTRAST_PixelShader_DeferredLightSource,            {0xFF}},
 };
 
-void DPSOFTRAST_Draw_ProcessSpans(DPSOFTRAST_State_Thread *thread)
+static void DPSOFTRAST_Draw_DepthTest(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_State_Span *span)
 {
-       int i;
        int x;
        int startx;
        int endx;
-//     unsigned int c;
-//     unsigned int *colorpixel;
        unsigned int *depthpixel;
-       float w;
-       float wslope;
        int depth;
        int depthslope;
        unsigned int d;
+       unsigned char *pixelmask;
+       depthpixel = dpsoftrast.fb_depthpixels + span->y * dpsoftrast.fb_width + span->x;
+       startx = span->startx;
+       endx = span->endx;
+       depth = span->depthbase;
+       depthslope = span->depthslope;
+       pixelmask = thread->pixelmaskarray;
+       if (thread->depthtest && dpsoftrast.fb_depthpixels)
+       {
+               switch(thread->fb_depthfunc)
+               {
+               default:
+               case GL_ALWAYS:  for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = true; break;
+               case GL_LESS:    for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = depthpixel[x] < d; break;
+               case GL_LEQUAL:  for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = depthpixel[x] <= d; break;
+               case GL_EQUAL:   for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = depthpixel[x] == d; break;
+               case GL_GEQUAL:  for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = depthpixel[x] >= d; break;
+               case GL_GREATER: for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = depthpixel[x] > d; break;
+               case GL_NEVER:   for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope) pixelmask[x] = false; break;
+               }
+               while (startx < endx && !pixelmask[startx])
+                       startx++;
+               while (endx > startx && !pixelmask[endx-1])
+                       endx--;
+       }
+       else
+       {
+               // no depth testing means we're just dealing with color...
+               memset(pixelmask + startx, 1, endx - startx);
+       }
+       span->pixelmask = pixelmask;
+       span->startx = startx;
+       span->endx = endx;
+}
+
+static void DPSOFTRAST_Draw_DepthWrite(const DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_State_Span *span)
+{
+       int x, d, depth, depthslope, startx, endx;
+       const unsigned char *pixelmask;
+       unsigned int *depthpixel;
+       if (thread->depthmask && thread->depthtest && dpsoftrast.fb_depthpixels)
+       {
+               depth = span->depthbase;
+               depthslope = span->depthslope;
+               pixelmask = span->pixelmask;
+               startx = span->startx;
+               endx = span->endx;
+               depthpixel = dpsoftrast.fb_depthpixels + span->y * dpsoftrast.fb_width + span->x;
+               for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope)
+                       if (pixelmask[x])
+                               depthpixel[x] = d;
+       }
+}
+
+static void DPSOFTRAST_Draw_ProcessSpans(DPSOFTRAST_State_Thread *thread)
+{
+       int i;
        DPSOFTRAST_State_Triangle *triangle;
        DPSOFTRAST_State_Span *span;
-       unsigned char pixelmask[DPSOFTRAST_DRAW_MAXSPANLENGTH];
        for (i = 0; i < thread->numspans; i++)
        {
                span = &thread->spans[i];
                triangle = &thread->triangles[span->triangle];
-               if (thread->depthtest && dpsoftrast.fb_depthpixels)
-               {
-                       wslope = triangle->w[0];
-                       w = triangle->w[2] + span->x*wslope + span->y*triangle->w[1];
-                       depthslope = (int)(wslope*DPSOFTRAST_DEPTHSCALE);
-                       depth = (int)(w*DPSOFTRAST_DEPTHSCALE - DPSOFTRAST_DEPTHOFFSET*(thread->polygonoffset[1] + fabs(wslope)*thread->polygonoffset[0]));
-                       depthpixel = dpsoftrast.fb_depthpixels + span->y * dpsoftrast.fb_width + span->x;
-                       switch(thread->fb_depthfunc)
-                       {
-                       default:
-                       case GL_ALWAYS:  for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = true; break;
-                       case GL_LESS:    for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = depthpixel[x] < d; break;
-                       case GL_LEQUAL:  for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = depthpixel[x] <= d; break;
-                       case GL_EQUAL:   for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = depthpixel[x] == d; break;
-                       case GL_GEQUAL:  for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = depthpixel[x] >= d; break;
-                       case GL_GREATER: for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = depthpixel[x] > d; break;
-                       case GL_NEVER:   for (x = 0, d = depth;x < span->length;x++, d += depthslope) pixelmask[x] = false; break;
-                       }
-                       //colorpixel = dpsoftrast.fb_colorpixels[0] + (span->y * dpsoftrast.fb_width + span->x) * 4;;
-                       //for (x = 0;x < span->length;x++)
-                       //      colorpixel[x] = (depthpixel[x] & 0xFF000000) ? (0x00FF0000) : (depthpixel[x] & 0x00FF0000);
-                       // if there is no color buffer, skip pixel shader
-                       startx = 0;
-                       endx = span->length;
-                       while (startx < endx && !pixelmask[startx])
-                               startx++;
-                       while (endx > startx && !pixelmask[endx-1])
-                               endx--;
-                       if (startx >= endx)
-                               continue; // no pixels to fill
-                       span->pixelmask = pixelmask;
-                       span->startx = startx;
-                       span->endx = endx;
-                       // run pixel shader if appropriate
-                       // do this before running depthmask code, to allow the pixelshader
-                       // to clear pixelmask values for alpha testing
-                       if (dpsoftrast.fb_colorpixels[0] && thread->fb_colormask)
-                               DPSOFTRAST_ShaderModeTable[thread->shader_mode].Span(thread, triangle, span);
-                       if (thread->depthmask)
-                               for (x = startx, d = depth + depthslope*startx;x < endx;x++, d += depthslope)
-                                       if (pixelmask[x])
-                                               depthpixel[x] = d;
-               }
-               else
-               {
-                       // no depth testing means we're just dealing with color...
-                       // if there is no color buffer, skip pixel shader
-                       if (dpsoftrast.fb_colorpixels[0] && thread->fb_colormask)
-                       {
-                               memset(pixelmask, 1, span->length);
-                               span->pixelmask = pixelmask;
-                               span->startx = 0;
-                               span->endx = span->length;
-                               DPSOFTRAST_ShaderModeTable[thread->shader_mode].Span(thread, triangle, span);
-                       }
-               }
+               DPSOFTRAST_Draw_DepthTest(thread, span);
+               if (span->startx >= span->endx)
+                       continue;
+               // run pixel shader if appropriate
+               // do this before running depthmask code, to allow the pixelshader
+               // to clear pixelmask values for alpha testing
+               if (dpsoftrast.fb_colorpixels[0] && thread->fb_colormask)
+                       DPSOFTRAST_ShaderModeTable[thread->shader_mode].Span(thread, triangle, span);
+               DPSOFTRAST_Draw_DepthWrite(thread, span);
        }
        thread->numspans = 0;
 }
 
-DEFCOMMAND(22, Draw, int datasize; int starty; int endy; ATOMIC_COUNTER refcount; int clipped; int firstvertex; int numvertices; int numtriangles; float *arrays; int *element3i; unsigned short *element3s;);
+DEFCOMMAND(22, Draw, int datasize; int starty; int endy; ATOMIC_COUNTER refcount; int clipped; int firstvertex; int numvertices; int numtriangles; float *arrays; int *element3i; unsigned short *element3s;)
 
 static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAST_Command_Draw *command)
 {
-#ifdef SSE2_PRESENT
+#ifdef SSE_POSSIBLE
        int cullface = thread->cullface;
-       int width = dpsoftrast.fb_width;
-       int miny = (thread->index*dpsoftrast.fb_height)/dpsoftrast.numthreads;
-       int maxy = ((thread->index+1)*dpsoftrast.fb_height)/dpsoftrast.numthreads;
+       int minx, maxx, miny, maxy;
+       int miny1, maxy1, miny2, maxy2;
        __m128i fbmin, fbmax;
        __m128 viewportcenter, viewportscale;
        int firstvertex = command->firstvertex;
@@ -4257,16 +4865,25 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
        int y;
        int e[3];
        __m128i screeny;
-       int starty, endy;
+       int starty, endy, bandy;
        int numpoints;
        int clipcase;
        float clipdist[4];
+       float clip0origin, clip0slope;
+       int clip0dir;
        __m128 triangleedge1, triangleedge2, trianglenormal;
        __m128 clipfrac[3];
        __m128 screen[4];
        DPSOFTRAST_State_Triangle *triangle;
        DPSOFTRAST_Texture *texture;
-       if (command->starty >= maxy || command->endy <= miny)
+       DPSOFTRAST_ValidateQuick(thread, DPSOFTRAST_VALIDATE_DRAW);
+       miny = thread->fb_scissor[1];
+       maxy = thread->fb_scissor[1] + thread->fb_scissor[3];
+       miny1 = bound(miny, thread->miny1, maxy);
+       maxy1 = bound(miny, thread->maxy1, maxy);
+       miny2 = bound(miny, thread->miny2, maxy);
+       maxy2 = bound(miny, thread->maxy2, maxy);
+       if ((command->starty >= maxy1 || command->endy <= miny1) && (command->starty >= maxy2 || command->endy <= miny2))
        {
                if (!ATOMIC_DECREMENT(command->refcount))
                {
@@ -4275,9 +4892,10 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
                }
                return;
        }
-       DPSOFTRAST_ValidateQuick(thread, DPSOFTRAST_VALIDATE_DRAW);
-       fbmin = _mm_setr_epi16(0, miny, 0, miny, 0, miny, 0, miny);
-       fbmax = _mm_sub_epi16(_mm_setr_epi16(width, maxy, width, maxy, width, maxy, width, maxy), _mm_set1_epi16(1));
+       minx = thread->fb_scissor[0];
+       maxx = thread->fb_scissor[0] + thread->fb_scissor[2];
+       fbmin = _mm_setr_epi16(minx, miny1, minx, miny1, minx, miny1, minx, miny1);
+       fbmax = _mm_sub_epi16(_mm_setr_epi16(maxx, maxy2, maxx, maxy2, maxx, maxy2, maxx, maxy2), _mm_set1_epi16(1));
        viewportcenter = _mm_load_ps(thread->fb_viewportcenter);
        viewportscale = _mm_load_ps(thread->fb_viewportscale);
        screen[3] = _mm_setzero_ps();
@@ -4442,6 +5060,8 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
                                continue;
                        starty = _mm_extract_epi16(screenmin, 1);
                        endy = _mm_extract_epi16(screenmax, 1)+1;
+                       if (starty >= maxy1 && endy <= miny2)
+                               continue;
                        screeny = _mm_srai_epi32(screeni, 16);
                }
 
@@ -4475,6 +5095,43 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
                        _mm_store_ss(&triangle->w[0], attribxslope);
                        _mm_store_ss(&triangle->w[1], attribyslope);
                        _mm_store_ss(&triangle->w[2], attriborigin);
+                       
+                       clip0origin = 0;
+                       clip0slope = 0;
+                       clip0dir = 0;
+                       if(thread->fb_clipplane[0] || thread->fb_clipplane[1] || thread->fb_clipplane[2])
+                       {
+                               float cliporigin, clipxslope, clipyslope;
+                               attriborigin = _mm_shuffle_ps(screen[1], screen[1], _MM_SHUFFLE(2, 2, 2, 2));
+                               attribedge1 = _mm_sub_ss(_mm_shuffle_ps(screen[0], screen[0], _MM_SHUFFLE(2, 2, 2, 2)), attriborigin);
+                               attribedge2 = _mm_sub_ss(_mm_shuffle_ps(screen[2], screen[2], _MM_SHUFFLE(2, 2, 2, 2)), attriborigin);
+                               attribxslope = _mm_sub_ss(_mm_mul_ss(attribuxslope, attribedge1), _mm_mul_ss(attribvxslope, attribedge2));
+                               attribyslope = _mm_sub_ss(_mm_mul_ss(attribvyslope, attribedge2), _mm_mul_ss(attribuyslope, attribedge1));
+                               attriborigin = _mm_sub_ss(attriborigin, _mm_add_ss(_mm_mul_ss(attribxslope, x1), _mm_mul_ss(attribyslope, y1)));
+                               cliporigin = _mm_cvtss_f32(attriborigin)*thread->fb_clipplane[2] + thread->fb_clipplane[3];
+                               clipxslope = thread->fb_clipplane[0] + _mm_cvtss_f32(attribxslope)*thread->fb_clipplane[2];
+                               clipyslope = thread->fb_clipplane[1] + _mm_cvtss_f32(attribyslope)*thread->fb_clipplane[2];
+                               if(clipxslope != 0)
+                               {
+                                       clip0origin = -cliporigin/clipxslope;
+                                       clip0slope = -clipyslope/clipxslope;
+                                       clip0dir = clipxslope > 0 ? 1 : -1;
+                               }
+                               else if(clipyslope > 0)
+                               {
+                                       clip0origin = dpsoftrast.fb_width*floor(cliporigin/clipyslope);
+                                       clip0slope = dpsoftrast.fb_width;
+                                       clip0dir = -1;
+                               }
+                               else if(clipyslope < 0)
+                               {
+                                       clip0origin = dpsoftrast.fb_width*ceil(cliporigin/clipyslope);
+                                       clip0slope = -dpsoftrast.fb_width;
+                                       clip0dir = -1;
+                               }
+                               else if(clip0origin < 0) continue;
+                       }
+
                        mipedgescale = _mm_setzero_ps();
                        for (j = 0;j < DPSOFTRAST_ARRAY_TOTAL; j++)
                        {
@@ -4490,9 +5147,9 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
                                attribxslope = _mm_sub_ps(_mm_mul_ps(attribuxslope, attribedge1), _mm_mul_ps(attribvxslope, attribedge2));
                                attribyslope = _mm_sub_ps(_mm_mul_ps(attribvyslope, attribedge2), _mm_mul_ps(attribuyslope, attribedge1));
                                attriborigin = _mm_sub_ps(attriborigin, _mm_add_ps(_mm_mul_ps(attribxslope, x1), _mm_mul_ps(attribyslope, y1)));
-                               _mm_stream_ps(triangle->attribs[k][0], attribxslope);
-                               _mm_stream_ps(triangle->attribs[k][1], attribyslope);
-                               _mm_stream_ps(triangle->attribs[k][2], attriborigin);
+                               _mm_storeu_ps(triangle->attribs[k][0], attribxslope);
+                               _mm_storeu_ps(triangle->attribs[k][1], attribyslope);
+                               _mm_storeu_ps(triangle->attribs[k][2], attriborigin);
                                if (k == DPSOFTRAST_ShaderModeTable[thread->shader_mode].lodarrayindex)
                                {
                                        mipedgescale = _mm_movelh_ps(triangleedge1, triangleedge2);
@@ -4527,14 +5184,17 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
                                }
                        }
                }
-
-               for (y = starty; y < endy;)
+       
+               for (y = starty, bandy = min(endy, maxy1); y < endy; bandy = min(endy, maxy2), y = max(y, miny2))
+               for (; y < bandy;)
                {
                        __m128 xcoords, xslope;
                        __m128i ycc = _mm_cmpgt_epi32(_mm_set1_epi32(y), screeny);
                        int yccmask = _mm_movemask_epi8(ycc);
                        int edge0p, edge0n, edge1p, edge1n;
                        int nexty;
+                       float w, wslope;
+                       float clip0;
                        if (numpoints == 4)
                        {
                                switch(yccmask)
@@ -4577,39 +5237,58 @@ static void DPSOFTRAST_Interpret_Draw(DPSOFTRAST_State_Thread *thread, DPSOFTRAS
                        ycc = _mm_min_epi16(ycc, _mm_shuffle_epi32(ycc, _MM_SHUFFLE(1, 0, 3, 2)));
                        ycc = _mm_min_epi16(ycc, _mm_shuffle_epi32(ycc, _MM_SHUFFLE(2, 3, 0, 1)));
                        nexty = _mm_extract_epi16(ycc, 0);
-                       if(nexty >= endy) nexty = endy-1;
-                       if (_mm_ucomigt_ss(_mm_max_ss(screen[edge0n], screen[edge0p]), _mm_min_ss(screen[edge1n], screen[edge1p])))
-                       {
-                               int tmp = edge0n;
-                               edge0n = edge1n;
-                               edge1n = tmp;
-                               tmp = edge0p;
-                               edge0p = edge1p;
-                               edge1p = tmp;
-                       }
+                       if (nexty >= bandy) nexty = bandy-1;
                        xslope = _mm_sub_ps(_mm_movelh_ps(screen[edge0n], screen[edge1n]), _mm_movelh_ps(screen[edge0p], screen[edge1p]));
                        xslope = _mm_div_ps(xslope, _mm_shuffle_ps(xslope, xslope, _MM_SHUFFLE(3, 3, 1, 1)));
                        xcoords = _mm_add_ps(_mm_movelh_ps(screen[edge0p], screen[edge1p]),
                                                                _mm_mul_ps(xslope, _mm_sub_ps(_mm_set1_ps(y), _mm_shuffle_ps(screen[edge0p], screen[edge1p], _MM_SHUFFLE(1, 1, 1, 1)))));
                        xcoords = _mm_add_ps(xcoords, _mm_set1_ps(0.5f));
-                       for(; y <= nexty; y++, xcoords = _mm_add_ps(xcoords, xslope))
+                       if (_mm_ucomigt_ss(xcoords, _mm_shuffle_ps(xcoords, xcoords, _MM_SHUFFLE(1, 0, 3, 2))))
+                       {
+                               xcoords = _mm_shuffle_ps(xcoords, xcoords, _MM_SHUFFLE(1, 0, 3, 2));
+                               xslope = _mm_shuffle_ps(xslope, xslope, _MM_SHUFFLE(1, 0, 3, 2));
+                       }
+                       clip0 = clip0origin + (y+0.5f)*clip0slope + 0.5f;
+                       for(; y <= nexty; y++, xcoords = _mm_add_ps(xcoords, xslope), clip0 += clip0slope)
                        {
                                int startx, endx, offset;
                                startx = _mm_cvtss_si32(xcoords);
                                endx = _mm_cvtss_si32(_mm_movehl_ps(xcoords, xcoords));
-                               if (startx < 0) startx = 0;
-                               if (endx > dpsoftrast.fb_width) endx = dpsoftrast.fb_width;
+                               if (startx < minx) startx = minx;
+                               if (endx > maxx) endx = maxx;
                                if (startx >= endx) continue;
-                               for (offset = startx; offset < endx;)
+
+                               if (clip0dir)
+                               {
+                                       if (clip0dir > 0)
+                                       {
+                                               if (startx < clip0) 
+                                               {
+                                                       if(endx <= clip0) continue;
+                                                       startx = (int)clip0;
+                                               }
+                                       }
+                                       else if (endx > clip0) 
+                                       {
+                                               if(startx >= clip0) continue;
+                                               endx = (int)clip0;
+                                       }
+                               }
+                                               
+                               for (offset = startx; offset < endx;offset += DPSOFTRAST_DRAW_MAXSPANLENGTH)
                                {
                                        DPSOFTRAST_State_Span *span = &thread->spans[thread->numspans];
                                        span->triangle = thread->numtriangles;
                                        span->x = offset;
                                        span->y = y;
-                                       span->length = endx - offset;
-                                       if (span -> length > DPSOFTRAST_DRAW_MAXSPANLENGTH)
-                                               span -> length = DPSOFTRAST_DRAW_MAXSPANLENGTH;
-                                       offset += span->length;
+                                       span->startx = 0;
+                                       span->endx = min(endx - offset, DPSOFTRAST_DRAW_MAXSPANLENGTH);
+                                       if (span->startx >= span->endx)
+                                               continue;
+                                       wslope = triangle->w[0];
+                                       w = triangle->w[2] + span->x*wslope + span->y*triangle->w[1];
+                                       span->depthslope = (int)(wslope*DPSOFTRAST_DEPTHSCALE);
+                                       span->depthbase = (int)(w*DPSOFTRAST_DEPTHSCALE - DPSOFTRAST_DEPTHOFFSET*(thread->polygonoffset[1] + fabs(wslope)*thread->polygonoffset[0]));
                                        if (++thread->numspans >= DPSOFTRAST_DRAW_MAXSPANS)
                                                DPSOFTRAST_Draw_ProcessSpans(thread);
                                }
@@ -4717,23 +5396,46 @@ void DPSOFTRAST_DrawTriangles(int firstvertex, int numvertices, int numtriangles
        command->clipped = dpsoftrast.drawclipped;
        command->refcount = dpsoftrast.numthreads;
 
-#ifdef USE_THREADS
-       DPSOFTRAST_Draw_SyncCommands();
+       if (dpsoftrast.usethreads)
        {
                int i;
-               int nexty = 0;
+               DPSOFTRAST_Draw_SyncCommands();
                for (i = 0; i < dpsoftrast.numthreads; i++)
                {
                        DPSOFTRAST_State_Thread *thread = &dpsoftrast.threads[i];
-                       int y = nexty;
-                       nexty = ((i+1)*dpsoftrast.fb_height)/dpsoftrast.numthreads;
-                       if (command->starty < nexty && command->endy > y && thread->starving)
-                               SDL_CondSignal(thread->drawcond);
+                       if (((command->starty < thread->maxy1 && command->endy > thread->miny1) || (command->starty < thread->maxy2 && command->endy > thread->miny2)) && thread->starving)
+                               Thread_CondSignal(thread->drawcond);
                }
        }
-#else
-       DPSOFTRAST_Draw_FlushThreads();
-#endif
+       else
+       {
+               DPSOFTRAST_Draw_FlushThreads();
+       }
+}
+
+DEFCOMMAND(23, SetRenderTargets, int width; int height;)
+static void DPSOFTRAST_Interpret_SetRenderTargets(DPSOFTRAST_State_Thread *thread, const DPSOFTRAST_Command_SetRenderTargets *command)
+{
+       thread->validate |= DPSOFTRAST_VALIDATE_FB;
+}
+void DPSOFTRAST_SetRenderTargets(int width, int height, unsigned int *depthpixels, unsigned int *colorpixels0, unsigned int *colorpixels1, unsigned int *colorpixels2, unsigned int *colorpixels3)
+{
+       DPSOFTRAST_Command_SetRenderTargets *command;
+       if (width != dpsoftrast.fb_width || height != dpsoftrast.fb_height || depthpixels != dpsoftrast.fb_depthpixels ||
+               colorpixels0 != dpsoftrast.fb_colorpixels[0] || colorpixels1 != dpsoftrast.fb_colorpixels[1] ||
+               colorpixels2 != dpsoftrast.fb_colorpixels[2] || colorpixels3 != dpsoftrast.fb_colorpixels[3])
+               DPSOFTRAST_Flush();
+       dpsoftrast.fb_width = width;
+       dpsoftrast.fb_height = height;
+       dpsoftrast.fb_depthpixels = depthpixels;
+       dpsoftrast.fb_colorpixels[0] = colorpixels0;
+       dpsoftrast.fb_colorpixels[1] = colorpixels1;
+       dpsoftrast.fb_colorpixels[2] = colorpixels2;
+       dpsoftrast.fb_colorpixels[3] = colorpixels3;
+       DPSOFTRAST_RecalcViewport(dpsoftrast.viewport, dpsoftrast.fb_viewportcenter, dpsoftrast.fb_viewportscale);
+       command = DPSOFTRAST_ALLOCATECOMMAND(SetRenderTargets);
+       command->width = width;
+       command->height = height;
 }
  
 static void DPSOFTRAST_Draw_InterpretCommands(DPSOFTRAST_State_Thread *thread, int endoffset)
@@ -4765,13 +5467,13 @@ static void DPSOFTRAST_Draw_InterpretCommands(DPSOFTRAST_State_Thread *thread, i
                INTERPCOMMAND(DepthRange)
                INTERPCOMMAND(PolygonOffset)
                INTERPCOMMAND(CullFace)
-               INTERPCOMMAND(AlphaTest)
-               INTERPCOMMAND(AlphaFunc)
                INTERPCOMMAND(SetTexture)
                INTERPCOMMAND(SetShader)
                INTERPCOMMAND(Uniform4f)
                INTERPCOMMAND(UniformMatrix4f)
                INTERPCOMMAND(Uniform1i)
+               INTERPCOMMAND(SetRenderTargets)
+               INTERPCOMMAND(ClipPlane)
 
                case DPSOFTRAST_OPCODE_Draw:
                        DPSOFTRAST_Interpret_Draw(thread, (DPSOFTRAST_Command_Draw *)command);
@@ -4789,7 +5491,6 @@ static void DPSOFTRAST_Draw_InterpretCommands(DPSOFTRAST_State_Thread *thread, i
        thread->commandoffset = commandoffset;
 }
 
-#ifdef USE_THREADS
 static int DPSOFTRAST_Draw_Thread(void *data)
 {
        DPSOFTRAST_State_Thread *thread = (DPSOFTRAST_State_Thread *)data;
@@ -4801,58 +5502,62 @@ static int DPSOFTRAST_Draw_Thread(void *data)
                }
                else 
                {
-                       SDL_LockMutex(thread->drawmutex);
+                       Thread_LockMutex(thread->drawmutex);
                        if (thread->commandoffset == dpsoftrast.drawcommand && thread->index >= 0)
                        {
-                               if (thread->waiting) SDL_CondSignal(thread->waitcond);
+                               if (thread->waiting) Thread_CondSignal(thread->waitcond);
                                thread->starving = true;
-                               SDL_CondWait(thread->drawcond, thread->drawmutex);
+                               Thread_CondWait(thread->drawcond, thread->drawmutex);
                                thread->starving = false;
                        }
-                       SDL_UnlockMutex(thread->drawmutex);
+                       Thread_UnlockMutex(thread->drawmutex);
                }
        }   
        return 0;
 }
-#endif
 
 static void DPSOFTRAST_Draw_FlushThreads(void)
 {
        DPSOFTRAST_State_Thread *thread;
        int i;
        DPSOFTRAST_Draw_SyncCommands();
-#ifdef USE_THREADS
-       for (i = 0; i < dpsoftrast.numthreads; i++)
+       if (dpsoftrast.usethreads) 
        {
-               thread = &dpsoftrast.threads[i];
-               if (thread->commandoffset != dpsoftrast.drawcommand)
+               for (i = 0; i < dpsoftrast.numthreads; i++)
                {
-                       SDL_LockMutex(thread->drawmutex);
-                       if (thread->commandoffset != dpsoftrast.drawcommand && thread->starving)
-                               SDL_CondSignal(thread->drawcond);
-                       SDL_UnlockMutex(thread->drawmutex);
+                       thread = &dpsoftrast.threads[i];
+                       if (thread->commandoffset != dpsoftrast.drawcommand)
+                       {
+                               Thread_LockMutex(thread->drawmutex);
+                               if (thread->commandoffset != dpsoftrast.drawcommand && thread->starving)
+                                       Thread_CondSignal(thread->drawcond);
+                               Thread_UnlockMutex(thread->drawmutex);
+                       }
                }
-       }
-#endif                 
-       for (i = 0; i < dpsoftrast.numthreads; i++)
-       {
-               thread = &dpsoftrast.threads[i];
-#ifdef USE_THREADS
-               if (thread->commandoffset != dpsoftrast.drawcommand)
+               for (i = 0; i < dpsoftrast.numthreads; i++)
                {
-                       SDL_LockMutex(thread->drawmutex);
+                       thread = &dpsoftrast.threads[i];
                        if (thread->commandoffset != dpsoftrast.drawcommand)
                        {
-                               thread->waiting = true;
-                               SDL_CondWait(thread->waitcond, thread->drawmutex);
-                               thread->waiting = false;
+                               Thread_LockMutex(thread->drawmutex);
+                               if (thread->commandoffset != dpsoftrast.drawcommand)
+                               {
+                                       thread->waiting = true;
+                                       Thread_CondWait(thread->waitcond, thread->drawmutex);
+                                       thread->waiting = false;
+                               }
+                               Thread_UnlockMutex(thread->drawmutex);
                        }
-                       SDL_UnlockMutex(thread->drawmutex);
                }
-#else
-               if (thread->commandoffset != dpsoftrast.drawcommand)
-                       DPSOFTRAST_Draw_InterpretCommands(thread, dpsoftrast.drawcommand);
-#endif
+       }
+       else
+       {
+               for (i = 0; i < dpsoftrast.numthreads; i++)
+               {
+                       thread = &dpsoftrast.threads[i];
+                       if (thread->commandoffset != dpsoftrast.drawcommand)
+                               DPSOFTRAST_Draw_InterpretCommands(thread, dpsoftrast.drawcommand);
+               }
        }
        dpsoftrast.commandpool.usedcommands = 0;
 }
@@ -4867,7 +5572,7 @@ void DPSOFTRAST_Finish(void)
        DPSOFTRAST_Flush();
 }
 
-void DPSOFTRAST_Init(int width, int height, int numthreads, unsigned int *colorpixels, unsigned int *depthpixels)
+int DPSOFTRAST_Init(int width, int height, int numthreads, int interlace, unsigned int *colorpixels, unsigned int *depthpixels)
 {
        int i;
        union
@@ -4898,17 +5603,16 @@ void DPSOFTRAST_Init(int width, int height, int numthreads, unsigned int *colorp
        dpsoftrast.color[1] = 1;
        dpsoftrast.color[2] = 1;
        dpsoftrast.color[3] = 1;
-#ifdef USE_THREADS
-       dpsoftrast.numthreads = bound(1, numthreads, 64);
-#else
-       dpsoftrast.numthreads = 1;
-#endif
+       dpsoftrast.usethreads = numthreads > 0 && Thread_HasThreads();
+       dpsoftrast.interlace = dpsoftrast.usethreads ? bound(0, interlace, 1) : 0;
+       dpsoftrast.numthreads = dpsoftrast.usethreads ? bound(1, numthreads, 64) : 1;
        dpsoftrast.threads = (DPSOFTRAST_State_Thread *)MM_CALLOC(dpsoftrast.numthreads, sizeof(DPSOFTRAST_State_Thread));
        for (i = 0; i < dpsoftrast.numthreads; i++)
        {
                DPSOFTRAST_State_Thread *thread = &dpsoftrast.threads[i];
                thread->index = i;
                thread->cullface = GL_BACK;
+               thread->colormask[0] = 1; 
                thread->colormask[1] = 1;
                thread->colormask[2] = 1;
                thread->colormask[3] = 1;
@@ -4918,9 +5622,6 @@ void DPSOFTRAST_Init(int width, int height, int numthreads, unsigned int *colorp
                thread->depthtest = true;
                thread->depthfunc = GL_LEQUAL;
                thread->scissortest = false;
-               thread->alphatest = false;
-               thread->alphafunc = GL_GREATER;
-               thread->alphavalue = 0.5f;
                thread->viewport[0] = 0;
                thread->viewport[1] = 0;
                thread->viewport[2] = dpsoftrast.fb_width;
@@ -4933,47 +5634,50 @@ void DPSOFTRAST_Init(int width, int height, int numthreads, unsigned int *colorp
                thread->depthrange[1] = 1;
                thread->polygonoffset[0] = 0;
                thread->polygonoffset[1] = 0;
-
+               thread->clipplane[0] = 0;
+               thread->clipplane[1] = 0;
+               thread->clipplane[2] = 0;
+               thread->clipplane[3] = 1;
+       
                thread->numspans = 0;
                thread->numtriangles = 0;
                thread->commandoffset = 0;
                thread->waiting = false;
                thread->starving = false;
-#ifdef USE_THREADS
-               thread->waitcond = SDL_CreateCond();
-               thread->drawcond = SDL_CreateCond();
-               thread->drawmutex = SDL_CreateMutex();
-#endif
-
+          
                thread->validate = -1;
                DPSOFTRAST_Validate(thread, -1);
-#ifdef USE_THREADS
-               thread->thread = SDL_CreateThread(DPSOFTRAST_Draw_Thread, thread);
-#endif
+               if (dpsoftrast.usethreads)
+               {
+                       thread->waitcond = Thread_CreateCond();
+                       thread->drawcond = Thread_CreateCond();
+                       thread->drawmutex = Thread_CreateMutex();
+                       thread->thread = Thread_CreateThread(DPSOFTRAST_Draw_Thread, thread);
+               }
        }
+       return 0;
 }
 
 void DPSOFTRAST_Shutdown(void)
 {
        int i;
-#ifdef USE_THREADS
-       if(dpsoftrast.numthreads > 0)
+       if (dpsoftrast.usethreads && dpsoftrast.numthreads > 0)
        {
                DPSOFTRAST_State_Thread *thread;
                for (i = 0; i < dpsoftrast.numthreads; i++)
                {
                        thread = &dpsoftrast.threads[i];
-                       SDL_LockMutex(thread->drawmutex);
+                       Thread_LockMutex(thread->drawmutex);
                        thread->index = -1;
-                       SDL_CondSignal(thread->drawcond);
-                       SDL_UnlockMutex(thread->drawmutex);
-                       SDL_WaitThread(thread->thread, NULL);
-                       SDL_DestroyCond(thread->waitcond);
-                       SDL_DestroyCond(thread->drawcond);
-                       SDL_DestroyMutex(thread->drawmutex);
+                       Thread_CondSignal(thread->drawcond);
+                       Thread_UnlockMutex(thread->drawmutex);
+                       Thread_WaitThread(thread->thread, 0);
+                       Thread_DestroyCond(thread->waitcond);
+                       Thread_DestroyCond(thread->drawcond);
+                       Thread_DestroyMutex(thread->drawmutex);
                }
        }
-#endif
        for (i = 0;i < dpsoftrast.texture_end;i++)
                if (dpsoftrast.texture[i].bytes)
                        MM_FREE(dpsoftrast.texture[i].bytes);