polyadvent

A game engine from scratch in C
git clone git://jb55.com/polyadvent
Log | Files | Refs | README

util.c (1327B)


      1 
      2 #include "util.h"
      3 #include "vec3.h"
      4 #include "mat4.h"
      5 #include "quat.h"
      6 #include <stdlib.h>
      7 
      8 int clampi(int a, int mina, int maxa) {
      9   if (a > maxa)
     10     return maxa;
     11 
     12   if (a < mina)
     13     return mina;
     14 
     15   return a;
     16 }
     17 
     18 double clamp(double a, double mina, double maxa) {
     19   if (a > maxa)
     20     return maxa;
     21 
     22   if (a < mina)
     23     return mina;
     24 
     25   return a;
     26 }
     27 
     28 
     29 double rand_0to1() {
     30   return (double) rand() / RAND_MAX;
     31 }
     32 
     33 void look_at(vec3 *eye, vec3 *target, vec3 *up, mat4 *dest) {
     34   float z[3], x[3], y[3];
     35 
     36   vec3_subtract(eye, target, z);
     37 
     38   /* if (vec3_lengthsq(z) == 0) */
     39   /*   z[2] = 0; */
     40 
     41   vec3_normalize(z, z);
     42   vec3_cross(up, z, x);
     43 
     44   if (vec3_lengthsq(x) == 0) {
     45     // up and z are parallel
     46 
     47     if (fabs(up[2]) == 1.0)
     48       z[0] += 0.0001;
     49     else
     50       z[2] += 0.0001;
     51 
     52     vec3_normalize(z, z);
     53     vec3_cross(up, z, x);
     54   }
     55 
     56   vec3_normalize(x, x);
     57   vec3_cross(z, x, y);
     58 
     59   dest[0] = x[0];
     60   dest[1] = x[1];
     61   dest[2] = x[2];
     62   /* dest[3] = 0.0; */
     63   /* dest[3] = vec3_dot(x, eye); */
     64 
     65   dest[4] = y[0];
     66   dest[5] = y[1];
     67   dest[6] = y[2];
     68   /* dest[7] = 0.0; */
     69   /* dest[7] = vec3_dot(y, eye); */
     70 
     71   dest[8]  = z[0];
     72   dest[9]  = z[1];
     73   dest[10] = z[2];
     74   /* dest[11] = 0.0; */
     75   /* dest[11] = vec3_dot(z, eye); */
     76 
     77   dest[12] = eye[0];
     78   dest[13] = eye[1];
     79   dest[14] = eye[2];
     80   /* dest[15] = 0.0; */
     81 }
     82 
     83