util.c (1947B)


      1 #include <stdlib.h>
      2 #include <stdio.h>
      3 #include <stdint.h>
      4 #include <unistd.h>
      5 #include <fcntl.h>
      6 #include <math.h>
      7 
      8 #include "util.h"
      9 
     10 /* This is a super-fast hex character value lookup table. */
     11 static const int8_t hextable[] = {
     12     [0 ... 255] = -1,
     13     ['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
     14     ['A'] = 10, 11, 12, 13, 14, 15,
     15     ['a'] = 10, 11, 12, 13, 14, 15
     16 };
     17 
     18 /*
     19  * Parse an ASCII hex representation of a color into an int32_t. A negative
     20  * value indicates that an error occured while parsing.
     21  *
     22  * If you need an OpenGL-compatible color, see convert_hex_color.
     23  */
     24 int32_t parse_hex_color(const char *hex)
     25 {
     26     int32_t raw = 0;
     27     while (*hex && raw >= 0) {
     28 	raw = (raw << 4) | hextable[(uint8_t) * hex++];
     29     }
     30 
     31     return raw;
     32 }
     33 
     34 /*
     35  * Extract red, green and blue values from an int32_t and convert then to OpenGL
     36  * compatible float colors. Alpha is ignored since the signed bit is generally
     37  * used to indicate errors.
     38  */
     39 scout_color_t convert_hex_color(int32_t color)
     40 {
     41     scout_color_t c;
     42 
     43     c.r = (float) ((color >> 16) & 0xFF) / 255.0f;
     44     c.g = (float) ((color >> 8) & 0xFF) / 255.0f;
     45     c.b = (float) (color & 0xFF) / 255.0f;
     46 
     47     return c;
     48 }
     49 
     50 /*
     51  * Read from the given path into a newly allocated buffer.
     52  * TODO: Handle errors
     53  */
     54 char *readfile(char *path)
     55 {
     56     FILE *fp = fopen(path, "r");
     57     fseek(fp, 0, SEEK_END);
     58     long length = ftell(fp);
     59     fseek(fp, 0, SEEK_SET);
     60     char *buffer = (char *) malloc(length);
     61     fread(buffer, length, 1, fp);
     62     fclose(fp);
     63     return buffer;
     64 }
     65 
     66 /*
     67  * Read from the given file descriptor into a newly allocated buffer.
     68  */
     69 char *fdreadfile(int fd)
     70 {
     71     off_t size = lseek(fd, 0, SEEK_END);
     72     lseek(fd, 0, SEEK_SET);
     73     char *buf = malloc(size + 1);
     74     read(fd, buf, size);
     75     buf[size] = '\0';
     76 
     77     return buf;
     78 }
     79 
     80 /* Decay is approx 1...25, slow...fast */
     81 float exp_decay(float a, float b, float decay, float dt) {
     82     return b + (a - b) * exp(-decay*dt);
     83 }