4849ec3fd2097a32ecb9ec8e345f7d1eb1f63797
[gbajam21] / tools / tungen.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdint.h>
4 #include <math.h>
5
6 int main(int argc, char **argv)
7 {
8         int i, j, xsz = 240, ysz = 160, texsz = 128;
9         struct vec2 *tunbuf, *tun;
10         float aspect;
11
12         for(i=1; i<argc; i++) {
13                 if(argv[i][0] == '-') {
14                         if(argv[i][2] != 0) goto invalopt;
15                         switch(argv[i][1]) {
16                         case 's':
17                                 if(sscanf(argv[++i], "%dx%d", &xsz, &ysz) != 2 || xsz <= 1 || ysz <= 1) {
18                                         fprintf(stderr, "-s must be followed by WxH\n");
19                                         return 1;
20                                 }
21                                 break;
22
23                         case 't':
24                                 if(!(texsz = atoi(argv[++i])) || texsz > 256) {
25                                         fprintf(stderr, "-t must be followed by the texture size (1-256)\n");
26                                         return 1;
27                                 }
28                                 break;
29
30                         default:
31                                 goto invalopt;
32                         }
33                 } else {
34 invalopt:       fprintf(stderr, "invalid argument: %s\n", argv[i]);
35                         return 1;
36                 }
37         }
38
39         FILE *fp = fopen("tun_preview.ppm", "wb");
40         if(fp) {
41                 fprintf(fp, "P6\n%d %d\n255\n", xsz, ysz);
42         }
43
44         aspect = (float)xsz / (float)ysz;
45
46         tun = tunbuf;
47         for(i=0; i<ysz; i++) {
48                 float y = 2.0f * (float)i / (float)(ysz - 1) - 1.0f;
49                 for(j=0; j<xsz; j++) {
50                         float x = (2.0f * (float)j / (float)(xsz - 1) - 1.0f) * aspect;
51
52                         float r = sqrt(x * x + y * y);
53                         float theta = atan2(y, x);
54
55                         float u = 0.5f * theta / M_PI + 0.5f;
56                         float v = r;
57
58                         uint32_t out = ((uint32_t)(u * 65535.0f) & 0xffff) |
59                                 (((uint32_t)(v * 65535.0f) & 0xffff) << 16);
60                         fwrite(&out, sizeof out, 1, stdout);
61
62                         if(fp) {
63                                 int cr = (int)(u * 2048.0f) & 0xff;
64                                 int cb = (int)(r * 2048.0f) & 0xff;
65                                 fputc(cr, fp);
66                                 fputc(0, fp);
67                                 fputc(cb, fp);
68                         }
69                 }
70         }
71         fflush(stdout);
72
73         if(fp) fclose(fp);
74         return 0;
75 }