NXEngine v1.0.0.6
[NXEngine.git] / tools / genobjnametable.cpp
blob384a64935bbd6464438692e7982bcd111f186a90
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <string.h>
5 #include <stdlib.h>
6 #include <sys/stat.h>
7 #include <errno.h>
9 char *nametable[1000];
10 const char *infile = "object.h";
11 const char *outfile = "autogen/objnames.cpp";
13 // read data from a file until CR
14 void fgetline(FILE *fp, char *str, int maxlen)
16 int k;
17 str[0] = 0;
18 fgets(str, maxlen - 1, fp);
20 // trim the CRLF that fgets appends
21 for(k=strlen(str)-1;k>=0;k--)
23 if (str[k] != 13 && str[k] != 10) break;
24 str[k] = 0;
29 bool strbegin(const char *bigstr, const char *smallstr)
31 int i;
33 for(i=0;smallstr[i];i++)
34 if (bigstr[i] != smallstr[i]) return false;
36 return true;
40 bool gen_table(void)
42 FILE *fp, *fpo;
43 char line[1024];
44 int nobjects = -1;
45 int count = 0;
47 printf("regenerating object-names table...\n");
49 fp = fopen(infile, "rb");
50 if (!fp)
52 fprintf(stderr, "<Cannot open object.h>\n");
53 return 1;
56 fpo = fileopen(outfile, "wb");
57 if (!fpo)
59 fprintf(stderr, "<Cannot open objnames.cpp>\n");
60 fclose(fp);
61 return 1;
64 memset(nametable, 0, sizeof(nametable));
66 while(!feof(fp))
68 fgetline(fp, line, sizeof(line));
70 if (strbegin(line, "#define OBJ_"))
72 char *ptr = strstr(line, "//");
73 if (ptr) *ptr = 0;
75 strtok(line, " \t");
76 const char *obj_name = strtok(NULL, " \t");
77 const char *obj_number_str = strtok(NULL, " \t");
78 int obj_number;
80 if (obj_name && obj_number_str && (obj_number = atoi(obj_number_str)))
82 if (!strcmp(obj_name, "OBJ_LAST"))
84 nobjects = obj_number;
86 else
88 //printf("obj_name: %s obj_number: %d\n", obj_name, obj_number);
89 nametable[obj_number] = strdup(&obj_name[4]);
90 count++;
96 if (nobjects == -1)
98 fprintf(stderr, "Couldn't find OBJ_LAST\n");
99 fclose(fp);
100 fclose(fpo);
101 return 1;
104 fprintf(fpo, "\n// auto-generated by genobjnametable.cpp\n");
105 fprintf(fpo, "#include <stdio.h>\n");
106 fprintf(fpo, "\nconst char *object_names[] = {\n");
108 for(int i=0;i<nobjects;i++)
110 if (nametable[i])
112 fprintf(fpo, "\t\"%s\"", nametable[i]);
113 free(nametable[i]);
115 else
117 fprintf(fpo, "\tNULL");
120 if (i+1 != nobjects)
121 fprintf(fpo, ",\n");
122 else
123 fprintf(fpo, "\n");
126 fprintf(fpo, "};\n");
127 printf("wrote %d objects in a space of %d\n", count, nobjects);
129 fclose(fp);
130 fclose(fpo);
131 return 0;
135 int main(void)
137 struct stat instat;
138 struct stat outstat;
140 if (stat(outfile, &outstat))
142 printf("names table missing\n");
143 return gen_table();
146 if (stat(infile, &instat))
148 fprintf(stderr, "cannot stat '%s': error %d\n", infile, errno);
149 return 1;
152 if (instat.st_mtime >= outstat.st_mtime)
154 return gen_table();
157 printf("table up to date\n");
158 return 0;