polyadvent

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

util.c (1266B)


      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 void look_at(vec3 *eye, vec3 *target, vec3 *up, mat4 *dest) {
     30   float z[3], x[3], y[3];
     31 
     32   vec3_subtract(eye, target, z);
     33 
     34   /* if (vec3_lengthsq(z) == 0) */
     35   /*   z[2] = 0; */
     36 
     37   vec3_normalize(z, z);
     38   vec3_cross(up, z, x);
     39 
     40   if (vec3_lengthsq(x) == 0) {
     41     // up and z are parallel
     42 
     43     if (fabs(up[2]) == 1.0)
     44       z[0] += 0.0001;
     45     else
     46       z[2] += 0.0001;
     47 
     48     vec3_normalize(z, z);
     49     vec3_cross(up, z, x);
     50   }
     51 
     52   vec3_normalize(x, x);
     53   vec3_cross(z, x, y);
     54 
     55   dest[0] = x[0];
     56   dest[1] = x[1];
     57   dest[2] = x[2];
     58   /* dest[3] = 0.0; */
     59   /* dest[3] = vec3_dot(x, eye); */
     60 
     61   dest[4] = y[0];
     62   dest[5] = y[1];
     63   dest[6] = y[2];
     64   /* dest[7] = 0.0; */
     65   /* dest[7] = vec3_dot(y, eye); */
     66 
     67   dest[8]  = z[0];
     68   dest[9]  = z[1];
     69   dest[10] = z[2];
     70   /* dest[11] = 0.0; */
     71   /* dest[11] = vec3_dot(z, eye); */
     72 
     73   dest[12] = eye[0];
     74   dest[13] = eye[1];
     75   dest[14] = eye[2];
     76   /* dest[15] = 0.0; */
     77 }
     78 
     79