+ int i, j;
+ float aspect = (float)width / (float)height;
+
+ for(i=0; i<height; i++) {
+ for(j=0; j<width; j++) {
+ csg_render_pixel(j, i, width, height, aspect, pixels);
+ pixels += 3;
+ }
+ }
+}
+
+static void calc_primary_ray(struct ray *ray, int x, int y, int w, int h, float aspect)
+{
+ /* TODO */
+ ray->dx = aspect * ((float)x / (float)w * 2.0f - 1.0f);
+ ray->dy = 1.0f - (float)y / (float)h * 2.0f;
+ ray->dz = -1.0f / tan(cam.fov * 0.5f);
+
+ ray->x = cam.x;
+ ray->y = cam.y;
+ ray->z = cam.z;
+}
+
+static int ray_trace(struct ray *ray, float *col)
+{
+ struct hit hit;
+
+ if(!find_intersection(ray, &hit)) {
+ background(col, ray);
+ return 0;
+ }
+
+ shade(col, ray, &hit);
+ return 1;
+}
+
+#define NULLXPOS(o) ((o)->ob.xform[12])
+#define NULLYPOS(o) ((o)->ob.xform[13])
+#define NULLZPOS(o) ((o)->ob.xform[14])
+
+static void shade(float *col, struct ray *ray, struct hit *hit)
+{
+ float ndotl, len;
+ csg_object *o, *lt = plights;
+ float dcol[3], scol[3] = {0};
+ float ldir[3];
+ struct ray sray;
+ struct hit tmphit;
+
+ o = hit->o;
+ dcol[0] = ambient[0];
+ dcol[1] = ambient[1];
+ dcol[2] = ambient[2];
+
+ while(lt) {
+ ldir[0] = NULLXPOS(lt) - hit->x;
+ ldir[1] = NULLYPOS(lt) - hit->y;
+ ldir[2] = NULLZPOS(lt) - hit->z;
+
+ sray.x = hit->x;
+ sray.y = hit->y;
+ sray.z = hit->z;
+ sray.dx = ldir[0];
+ sray.dy = ldir[1];
+ sray.dz = ldir[2];
+
+ if(!find_intersection(&sray, &tmphit) || tmphit.t < 1.0f) {
+ if((len = sqrt(ldir[0] * ldir[0] + ldir[1] * ldir[1] + ldir[2] * ldir[2])) != 0.0f) {
+ float s = 1.0f / len;
+ ldir[0] *= s;
+ ldir[1] *= s;
+ ldir[2] *= s;
+ }
+
+ if((ndotl = hit->nx * ldir[0] + hit->ny * ldir[1] + hit->nz * ldir[2]) < 0.0f) {
+ ndotl = 0.0f;
+ }
+
+ dcol[0] += o->ob.r * lt->ob.emr * ndotl;
+ dcol[1] += o->ob.g * lt->ob.emg * ndotl;
+ dcol[2] += o->ob.b * lt->ob.emb * ndotl;
+ }
+
+ lt = lt->ob.next;
+ }
+
+ col[0] = dcol[0] + scol[0];
+ col[1] = dcol[1] + scol[1];
+ col[2] = dcol[2] + scol[2];
+}
+
+static void background(float *col, struct ray *ray)
+{
+ col[0] = col[1] = col[2] = 0.0f;
+}
+
+static int find_intersection(struct ray *ray, struct hit *best)
+{
+ csg_object *o;
+ struct hit *hit;
+
+ best->t = FLT_MAX;
+ best->o = 0;
+
+ o = oblist;
+ while(o) {
+ if((hit = ray_intersect(ray, o)) && hit->t < best->t) {
+ *best = *hit;
+ }
+ free_hit_list(hit);
+ o = o->ob.next;
+ }
+
+ return best->o != 0;