+int dlightdivtable[32768];
+
+/*
+ R_AddDynamicLights
+*/
+int R_AddDynamicLights (msurface_t *surf)
+{
+ int sdtable[18], lnum, td, maxdist, maxdist2, maxdist3, i, j, s, t, smax, tmax, red, green, blue, lit, dist2, impacts, impactt;
+ unsigned int *bl;
+ float dist;
+ vec3_t impact, local;
+
+ // LordHavoc: use 64bit integer... shame it's not very standardized...
+//#if _MSC_VER || __BORLANDC__
+// __int64 k;
+//#else
+// long long k;
+//#endif
+
+ // LordHavoc: later note: MSVC and hopefully all other C compilers use a 64bit result for 32bit*32bit multiply, so that was not necessary
+ int k;
+
+ lit = false;
+
+ if (!dlightdivtable[1])
+ {
+ dlightdivtable[0] = 4194304;
+ for (s = 1; s < 32768; s++)
+ dlightdivtable[s] = 4194304 / (s << 7);
+ }
+
+ smax = (surf->extents[0] >> 4) + 1;
+ tmax = (surf->extents[1] >> 4) + 1;
+
+ for (lnum = 0; lnum < MAX_DLIGHTS; lnum++)
+ {
+ if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
+ continue; // not lit by this light
+
+ VectorSubtract (cl_dlights[lnum].origin, currententity->origin, local);
+ dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
+
+ // for comparisons to minimum acceptable light
+ maxdist = (int) ((cl_dlights[lnum].radius * cl_dlights[lnum].radius) * LIGHTSCALE);
+
+ // clamp radius to avoid exceeding 32768 entry division table
+ if (maxdist > 4194304)
+ maxdist = 4194304;
+
+ dist2 = dist * dist;
+ if (dist2 >= maxdist)
+ continue;
+
+ impact[0] = cl_dlights[lnum].origin[0] - surf->plane->normal[0] * dist;
+ impact[1] = cl_dlights[lnum].origin[1] - surf->plane->normal[1] * dist;
+ impact[2] = cl_dlights[lnum].origin[2] - surf->plane->normal[2] * dist;
+
+ impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
+ impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
+
+ s = bound(0, impacts, smax * 16) - impacts;
+ t = bound(0, impactt, tmax * 16) - impactt;
+ i = s * s + t * t + dist2;
+ if (i > maxdist)
+ continue;
+
+ // reduce calculations
+ for (s = 0, i = impacts; s < smax; s++, i -= 16)
+ sdtable[s] = i * i + dist2;
+
+ maxdist3 = maxdist - (int) (dist * dist);
+
+ // convert to 8.8 blocklights format and scale up by radius
+ red = cl_dlights[lnum].color[0] * maxdist;
+ green = cl_dlights[lnum].color[1] * maxdist;
+ blue = cl_dlights[lnum].color[2] * maxdist;
+ bl = blocklights;
+
+ i = impactt;
+ for (t = 0; t < tmax; t++, i -= 16)
+ {
+ td = i * i;
+ // make sure some part of it is visible on this line
+ if (td < maxdist3)
+ {
+ maxdist2 = maxdist - td;
+ for (s = 0; s < smax; s++)
+ {
+ if (sdtable[s] < maxdist2)
+ {
+ k = dlightdivtable[(sdtable[s] + td) >> 7];
+ j = (red * k) >> 9;bl[0] += j;
+ j = (green * k) >> 9;bl[1] += j;
+ j = (blue * k) >> 9;bl[2] += j;
+ lit = true;
+ }
+ bl += 3;
+ }
+ }
+ else // skip line
+ bl += smax * 3;
+ }
+ }
+ return lit;
+}
+
+