source: git/src/img.c @ ee11c6a7

RELEASE/1.0RELEASE/1.1RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since ee11c6a7 was d4d3655, checked in by Olly Betts <olly@…>, 23 years ago

Factored out "enlarge label buffer if necessary" code into check_label_space()

git-svn-id: file:///home/survex-svn/survex/trunk@1809 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 29.7 KB
Line 
1/* img.c
2 * Routines for reading and writing Survex ".3d" image files
3 * Copyright (C) 1993-2002 Olly Betts
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 */
19
20#ifdef HAVE_CONFIG_H
21# include <config.h>
22#endif
23
24#include <stdio.h>
25#include <string.h>
26#include <stdlib.h>
27#include <time.h>
28#include <ctype.h>
29
30#include "img.h"
31
32#ifdef IMG_HOSTED
33# include "debug.h"
34# include "filelist.h"
35# include "filename.h"
36# include "message.h"
37# include "useful.h"
38# define TIMENA msg(/*Date and time not available.*/108)
39# define TIMEFMT msg(/*%a,%Y.%m.%d %H:%M:%S %Z*/107)
40#else
41# define INT32_T long
42# define TIMENA "Time not available."
43# define TIMEFMT "%a,%Y.%m.%d %H:%M:%S %Z"
44# define EXT_SVX_3D "3d"
45# define xosmalloc(L) malloc((L))
46# define xosrealloc(L,S) realloc((L),(S))
47# define osfree(P) free((P))
48# define ossizeof(T) sizeof(T)
49/* in IMG_HOSTED mode, this tests if a filename refers to a directory */
50# define fDirectory(X) 0
51/* open file FNM with mode MODE, maybe using path PTH and/or extension EXT */
52/* path isn't used in img.c, but EXT is */
53# define fopenWithPthAndExt(PTH,FNM,EXT,MODE,X) fopen(FNM,MODE)
54# define fFalse 0
55# define fTrue 1
56# define bool int
57/* dummy do {...} while(0) hack to permit stuff like
58 * if (s) fputsnl(s,fh); else exit(1);
59 * to work as intended
60 */
61# define fputsnl(S, FH) do {fputs((S), (FH)); putc('\n', (FH));} while(0)
62# define ASSERT(X)
63
64static long
65get32(FILE *fh)
66{
67   long w = getc(fh);
68   w |= (long)getc(fh) << 8l;
69   w |= (long)getc(fh) << 16l;
70   w |= (long)getc(fh) << 24l;
71   return w;
72}
73
74static void
75put32(long w, FILE *fh)
76{
77   putc((char)(w), fh);
78   putc((char)(w >> 8l), fh);
79   putc((char)(w >> 16l), fh);
80   putc((char)(w >> 24l), fh);
81}
82
83#endif
84
85#ifdef HAVE_ROUND
86# include <math.h>
87extern double round(double); /* prototype is often missing... */
88# define my_round round
89#else
90static double
91my_round(double x) {
92   if (x >= 0.0) return floor(x + 0.5);
93   return ceil(x - 0.5);
94}
95#endif
96
97/* portable case insensitive string compare */
98#if defined(strcasecmp) || defined(HAVE_STRCASECMP)
99# define my_strcasecmp strcasecmp
100#else
101/* What about top bit set chars? */
102int my_strcasecmp(const char *s1, const char *s2) {
103   register c1, c2;
104   do {
105      c1 = *s1++;
106      c2 = *s2++;
107   } while (c1 && toupper(c1) == toupper(c2));
108   /* now calculate real difference */
109   return c1 - c2;
110}
111#endif
112
113unsigned int img_output_version = 3;
114
115#ifdef IMG_HOSTED
116static enum {
117   IMG_NONE = 0,
118   IMG_FILENOTFOUND = /*Couldn't open data file `%s'*/24,
119   IMG_OUTOFMEMORY  = /*Out of memory %.0s*/38,
120   IMG_DIRECTORY    = /*Filename `%s' refers to directory*/44,
121   IMG_CANTOPENOUT  = /*Failed to open output file `%s'*/47,
122   IMG_BADFORMAT    = /*Bad 3d image file `%s'*/106,
123   IMG_READERROR    = /*Error reading from file `%s'*/109,
124   IMG_WRITEERROR   = /*Error writing to file `%s'*/110,
125   IMG_TOONEW       = /*File `%s' has a newer format than this program can understand*/114
126} img_errno = IMG_NONE;
127#else
128static img_errcode img_errno = IMG_NONE;
129#endif
130
131#define FILEID "Survex 3D Image File"
132
133#define EXT_PLT "plt"
134
135/* Attempt to string paste to ensure we are passed a literal string */
136#define LITLEN(S) (sizeof(S"") - 1)
137
138static char *
139my_strdup(const char *str)
140{
141   char *p;
142   size_t len = strlen(str) + 1;
143   p = xosmalloc(len);
144   if (p) memcpy(p, str, len);
145   return p;
146}
147
148static char *
149getline_alloc(FILE *fh)
150{
151   int ch;
152   size_t i = 0;
153   size_t len = 16;
154   char *buf = xosmalloc(len);
155   if (!buf) return NULL;
156
157   ch = getc(fh);
158   while (ch != '\n' && ch != '\r' && ch != EOF) {
159      buf[i++] = ch;
160      if (i == len - 1) {
161         char *p;
162         len += len;
163         p = xosrealloc(buf, len);
164         if (!p) {
165            osfree(buf);
166            return NULL;
167         }
168         buf = p;
169      }
170      ch = getc(fh);
171   }
172   if (ch == '\n' || ch == '\r') {
173      /* remove any further eol chars (for DOS text files) */
174      do {
175         ch = getc(fh);
176      } while (ch == '\n' || ch == '\r');
177      ungetc(ch, fh); /* we don't want it, so put it back */
178   }
179   buf[i++] = '\0';
180   return buf;
181}
182
183#ifndef IMG_HOSTED
184img_errcode
185img_error(void)
186{
187   return img_errno;
188}
189#else
190int
191img_error(void)
192{
193   return (int)img_errno;
194}
195#endif
196
197static bool
198check_label_space(img *pimg, size_t len)
199{
200   if (len > pimg->buf_len) {
201      char *b = xosrealloc(pimg->label_buf, len);
202      if (!b) return fFalse;
203      pimg->label = (pimg->label - pimg->label_buf) + b;
204      pimg->label_buf = b;
205      pimg->buf_len = len;
206   }
207   return fTrue;
208}
209
210img *
211img_open_survey(const char *fnm, const char *survey)
212{
213   img *pimg;
214   size_t len;
215   char buf[LITLEN(FILEID) + 1];
216   int ch;
217
218   if (fDirectory(fnm)) {
219      img_errno = IMG_DIRECTORY;
220      return NULL;
221   }
222
223   pimg = (img *)xosmalloc(ossizeof(img));
224   if (pimg == NULL) {
225      img_errno = IMG_OUTOFMEMORY;
226      return NULL;
227   }
228
229   pimg->buf_len = 257;
230   pimg->label_buf = xosmalloc(pimg->buf_len);
231   if (!pimg->label_buf) {
232      osfree(pimg);
233      img_errno = IMG_OUTOFMEMORY;
234      return NULL;
235   }
236
237   pimg->fh = fopenWithPthAndExt("", fnm, EXT_SVX_3D, "rb", NULL);
238   if (pimg->fh == NULL) {
239      osfree(pimg);
240      img_errno = IMG_FILENOTFOUND;
241      return NULL;
242   }
243
244   pimg->fRead = fTrue; /* reading from this file */
245   img_errno = IMG_NONE;
246
247   pimg->flags = 0;
248
249   /* for version 3 we use label_buf to store the prefix for reuse */
250   pimg->label_len = 0;
251
252   pimg->survey = NULL;
253   pimg->survey_len = 0;
254
255   pimg->title = NULL;
256   if (survey) {
257      len = strlen(survey);
258      if (len) {
259         if (survey[len - 1] == '.') len--;
260         if (len) {
261            char *p;
262            pimg->survey = osmalloc(len + 2);
263            memcpy(pimg->survey, survey, len);
264            /* Set title to leaf survey name */
265            pimg->survey[len] = '\0';
266            p = strchr(pimg->survey, '.');
267            if (p) p++; else p = pimg->survey;
268            pimg->title = my_strdup(p);
269            if (!pimg->title) {
270               img_errno = IMG_OUTOFMEMORY;
271               goto error;
272            }
273            pimg->survey[len] = '.';
274            pimg->survey[len + 1] = '\0';
275         }
276      }
277      pimg->survey_len = len;
278   }
279
280   /* [version -2] pending IMG_LINE ('D') or IMG_MOVE ('M')
281    * [version -1] already skipped heading line, or there wasn't one
282    * [version 0] not in the middle of a 'LINE' command
283    * [version 3] not in the middle of turning a LINE into a MOVE
284    */
285   pimg->pending = 0;
286
287   len = strlen(fnm);
288   if (len > LITLEN(EXT_SVX_POS) + 1 &&
289       fnm[len - LITLEN(EXT_SVX_POS) - 1] == FNM_SEP_EXT &&
290       my_strcasecmp(fnm + len - LITLEN(EXT_SVX_POS), EXT_SVX_POS) == 0) {
291      pimg->version = -1;
292      if (!pimg->survey) pimg->title = baseleaf_from_fnm(fnm);
293      pimg->datestamp = my_strdup(TIMENA);
294      if (!pimg->datestamp) {
295         img_errno = IMG_OUTOFMEMORY;
296         goto error;
297      }
298      pimg->start = 0;
299      return pimg;
300   }
301
302   if (len > LITLEN(EXT_PLT) + 1 &&
303       fnm[len - LITLEN(EXT_PLT) - 1] == FNM_SEP_EXT &&
304       my_strcasecmp(fnm + len - LITLEN(EXT_PLT), EXT_PLT) == 0) {
305      char *line = NULL;
306
307      pimg->version = -2;
308      if (!pimg->survey) pimg->title = baseleaf_from_fnm(fnm);
309      pimg->datestamp = my_strdup(TIMENA);
310      if (!pimg->datestamp) {
311         img_errno = IMG_OUTOFMEMORY;
312         goto error;
313      }
314      do {
315         do {
316            osfree(line);
317            line = getline_alloc(pimg->fh);
318            if (!line) {
319               img_errno = IMG_OUTOFMEMORY;
320               goto error;
321            }
322            if (line[0] == '\x1a') {
323               osfree(line);
324               pimg->pending = img_STOP + 4;
325               return pimg;
326            }
327            if (feof(pimg->fh)) {
328               osfree(line);
329               img_errno = IMG_BADFORMAT;
330               goto error;
331            }
332         } while (line[0] != 'N');
333
334         len = 1;
335         while (line[len] > 32) ++len;
336      } while (pimg->survey && (pimg->survey_len != len - 1 ||
337               memcmp(line + 1, pimg->survey, pimg->survey_len) != 0));
338
339      if (!check_label_space(pimg, len)) {
340         img_errno = IMG_OUTOFMEMORY;
341         goto error;
342      }
343
344      --len;
345      pimg->label_len = len;
346      pimg->label = pimg->label_buf;
347      memcpy(pimg->label, line + 1, len);
348      pimg->label[len] = '\0';
349      if (pimg->survey) {
350         char *q = strchr(line + len, 'C');
351         if (q && q[1]) {
352            osfree(pimg->title);
353            pimg->title = osstrdup(q + 1);
354         } else if (!pimg->title) {
355            pimg->title = osstrdup(pimg->label);
356         }
357         if (!pimg->title) {
358            img_errno = IMG_OUTOFMEMORY;
359            goto error;
360         }
361      }
362      osfree(line);
363      pimg->start = 0;
364      return pimg;
365   }
366
367   if (fread(buf, LITLEN(FILEID) + 1, 1, pimg->fh) != 1 ||
368       memcmp(buf, FILEID"\n", LITLEN(FILEID)) != 0) {
369      img_errno = IMG_BADFORMAT;
370      goto error;
371   }
372
373   /* check file format version */
374   ch = getc(pimg->fh);
375   pimg->version = 0;
376   if (tolower(ch) == 'b') {
377      /* binary file iff B/b prefix */
378      pimg->version = 1;
379      ch = getc(pimg->fh);
380   }
381   if (ch != 'v') {
382      img_errno = IMG_BADFORMAT;
383      goto error;
384   }
385   ch = getc(pimg->fh);
386   if (ch == '0') {
387      if (fread(buf, 4, 1, pimg->fh) != 1 || memcmp(buf, ".01\n", 4) != 0) {
388         img_errno = IMG_BADFORMAT;
389         goto error;
390      }
391      /* nothing special to do */
392   } else if (pimg->version == 0) {
393      if (ch < '2' || ch > '3' || getc(pimg->fh) != '\n') {
394         img_errno = IMG_TOONEW;
395         goto error;
396      }
397      pimg->version = ch - '0';
398   } else {
399      img_errno = IMG_BADFORMAT;
400      goto error;
401   }
402
403   if (!pimg->title)
404       pimg->title = getline_alloc(pimg->fh);
405   else
406       osfree(getline_alloc(pimg->fh));
407   pimg->datestamp = getline_alloc(pimg->fh);
408   if (!pimg->title || !pimg->datestamp) {
409      img_errno = IMG_OUTOFMEMORY;
410      error:
411      osfree(pimg->title);
412      osfree(pimg->datestamp);
413      fclose(pimg->fh);
414      osfree(pimg);
415      return NULL;
416   }
417
418   pimg->start = ftell(pimg->fh);
419
420   return pimg;
421}
422
423int
424img_rewind(img *pimg)
425{
426   if (!pimg->fRead) {
427      img_errno = IMG_WRITEERROR;
428      return 0;
429   }
430   if (fseek(pimg->fh, pimg->start, SEEK_SET) != 0) {
431      img_errno = IMG_READERROR;
432      return 0;
433   }
434   clearerr(pimg->fh);
435   /* [version -1] already skipped heading line, or there wasn't one
436    * [version 0] not in the middle of a 'LINE' command
437    * [version 3] not in the middle of turning a LINE into a MOVE */
438   pimg->pending = 0; /* FIXME: consider rewind on .plt with survey matching nothing ... */
439
440   img_errno = IMG_NONE;
441
442   /* for version 3 we use label_buf to store the prefix for reuse */
443   pimg->label_len = 0;
444   return 1;
445}
446
447img *
448img_open_write(const char *fnm, char *title_buf, bool fBinary)
449{
450   time_t tm;
451   img *pimg;
452
453   fBinary = fBinary;
454
455   if (fDirectory(fnm)) {
456      img_errno = IMG_DIRECTORY;
457      return NULL;
458   }
459
460   pimg = (img *)xosmalloc(ossizeof(img));
461   if (pimg == NULL) {
462      img_errno = IMG_OUTOFMEMORY;
463      return NULL;
464   }
465
466   pimg->buf_len = 257;
467   pimg->label_buf = xosmalloc(pimg->buf_len);
468   if (!pimg->label_buf) {
469      osfree(pimg);
470      img_errno = IMG_OUTOFMEMORY;
471      return NULL;
472   }
473
474   pimg->fh = fopen(fnm, "wb");
475   if (!pimg->fh) {
476      osfree(pimg);
477      img_errno = IMG_CANTOPENOUT;
478      return NULL;
479   }
480
481   /* Output image file header */
482   fputs("Survex 3D Image File\n", pimg->fh); /* file identifier string */
483   if (img_output_version < 2) {
484      pimg->version = 1;
485      fputs("Bv0.01\n", pimg->fh); /* binary file format version number */
486   } else {
487      pimg->version = (img_output_version > 2) ? 3 : 2;
488      fprintf(pimg->fh, "v%d\n", pimg->version); /* file format version no. */
489   }
490   fputsnl(title_buf, pimg->fh);
491   tm = time(NULL);
492   if (tm == (time_t)-1) {
493      fputsnl(TIMENA, pimg->fh);
494   } else {
495      char date[256];
496      /* output current date and time in format specified */
497      strftime(date, 256, TIMEFMT, localtime(&tm));
498      fputsnl(date, pimg->fh);
499   }
500   pimg->fRead = fFalse; /* writing to this file */
501   img_errno = IMG_NONE;
502
503   /* for version 3 we use label_buf to store the prefix for reuse */
504   pimg->label_buf[0] = '\0';
505   pimg->label_len = 0;
506
507   /* Don't check for write errors now - let img_close() report them... */
508   return pimg;
509}
510
511static int
512read_coord(FILE *fh, img_point *pt)
513{
514   ASSERT(fh);
515   ASSERT(pt);
516   pt->x = get32(fh) / 100.0;
517   pt->y = get32(fh) / 100.0;
518   pt->z = get32(fh) / 100.0;
519   if (ferror(fh) || feof(fh)) {
520      img_errno = feof(fh) ? IMG_BADFORMAT : IMG_READERROR;
521      return 0;
522   }
523   return 1;
524}
525
526static int
527skip_coord(FILE *fh)
528{
529    return (fseek(fh, 12, SEEK_CUR) == 0);
530}
531
532int
533img_read_item(img *pimg, img_point *p)
534{
535   int result;
536   pimg->flags = 0;
537
538   if (pimg->version == 3) {
539      int opt;
540      if (pimg->pending >= 0x80) {
541         *p = pimg->mv;
542         pimg->flags = (int)(pimg->pending) & 0x3f;
543         pimg->pending = 0;
544         return img_LINE;
545      }
546      again3: /* label to goto if we get a prefix */
547      pimg->label = pimg->label_buf;
548      opt = getc(pimg->fh);
549      if (opt == EOF) {
550         img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
551         return img_BAD;
552      }
553      switch (opt >> 6) {
554       case 0:
555         if (opt == 0) {
556            if (!pimg->label_len) return img_STOP; /* end of data marker */
557            pimg->label_len = 0;
558            goto again3;
559         }
560         if (opt < 15) {
561            /* 1-14 mean trim that many levels from current prefix */
562            int c;
563            if (pimg->label_len <= 16) {
564               /* zero prefix using "0" */
565               img_errno = IMG_BADFORMAT;
566               return img_BAD;
567            }
568            c = pimg->label_len - 16 - 1;
569            while (pimg->label_buf[c] != '.' || --opt > 0) {
570               if (--c < 0) {
571                  /* zero prefix using "0" */
572                  img_errno = IMG_BADFORMAT;
573                  return img_BAD;
574               }
575            }
576            c++;
577            pimg->label_len = c;
578            goto again3;
579         }
580         if (opt == 15) {
581            result = img_MOVE;
582            break;
583         }
584         /* 16-31 mean remove (n - 15) characters from the prefix */
585         /* zero prefix using 0 */
586         if (pimg->label_len <= (size_t)(opt - 15)) {
587            img_errno = IMG_BADFORMAT;
588            return img_BAD;
589         }
590         pimg->label_len -= (opt - 15);
591         goto again3;
592       case 1: case 2: {
593         char *q;
594         long len = getc(pimg->fh);
595         if (len == EOF) {
596            img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
597            return img_BAD;
598         }
599         if (len == 0xfe) {
600            len += get16(pimg->fh);
601            if (feof(pimg->fh)) {
602               img_errno = IMG_BADFORMAT;
603               return img_BAD;
604            }
605            if (ferror(pimg->fh)) {
606               img_errno = IMG_READERROR;
607               return img_BAD;
608            }
609         } else if (len == 0xff) {
610            len = get32(pimg->fh);
611            if (ferror(pimg->fh)) {
612               img_errno = IMG_READERROR;
613               return img_BAD;
614            }
615            if (feof(pimg->fh) || len < 0xfe + 0xffff) {
616               img_errno = IMG_BADFORMAT;
617               return img_BAD;
618            }
619         }
620
621         pimg->label_len += len;
622         if (!check_label_space(pimg, pimg->label_len + 1)) {
623            img_errno = IMG_OUTOFMEMORY;
624            return img_BAD;
625         }
626         q = pimg->label_buf + pimg->label_len;
627         if (len && fread(q, len, 1, pimg->fh) != 1) {
628            img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
629            return img_BAD;
630         }
631         q[len] = '\0';
632
633         result = opt & 0x40 ? img_LABEL : img_LINE;
634
635         if (pimg->survey_len) {
636            size_t l = pimg->survey_len;
637            const char *s = pimg->label_buf;
638            if (result == img_LINE) {
639               if (strncmp(pimg->survey, s, l) != 0 ||
640                   !(s[l] == '.' || s[l] == '\0')) {
641                  if (!read_coord(pimg->fh, &(pimg->mv))) return img_BAD;
642                  pimg->pending = 15;
643                  goto again3;
644               }
645            } else {
646               if (strncmp(pimg->survey, s, l + 1) != 0) {
647                  if (!skip_coord(pimg->fh)) return img_BAD;
648                  pimg->pending = 0;
649                  goto again3;
650               }
651            }
652            pimg->label += l;
653            /* skip the dot if there */
654            if (*pimg->label) pimg->label++;
655         }
656
657         if (result == img_LINE && pimg->pending) {
658            *p = pimg->mv;
659            if (!read_coord(pimg->fh, &(pimg->mv))) return img_BAD;
660            pimg->pending = opt;
661            return img_MOVE;
662         }
663         pimg->flags = (int)opt & 0x3f;
664         break;
665       }
666       default:
667         img_errno = IMG_BADFORMAT;
668         return img_BAD;
669      }
670      if (!read_coord(pimg->fh, p)) return img_BAD;
671      pimg->pending = 0;
672      return result;
673   }
674
675   pimg->label = pimg->label_buf;
676
677   if (pimg->version > 0) {
678      static long opt_lookahead = 0;
679      static img_point pt = { 0.0, 0.0, 0.0 };
680      long opt;
681      again: /* label to goto if we get a cross */
682      pimg->label[0] = '\0';
683
684      if (pimg->version == 1) {
685         if (opt_lookahead) {
686            opt = opt_lookahead;
687            opt_lookahead = 0;
688         } else {
689            opt = get32(pimg->fh);
690         }
691      } else {
692         opt = getc(pimg->fh);
693      }
694
695      if (feof(pimg->fh)) {
696         img_errno = IMG_BADFORMAT;
697         return img_BAD;
698      }
699      if (ferror(pimg->fh)) {
700         img_errno = IMG_READERROR;
701         return img_BAD;
702      }
703
704      switch (opt) {
705       case -1: case 0:
706         return img_STOP; /* end of data marker */
707       case 1:
708         /* skip coordinates */
709         if (!skip_coord(pimg->fh)) {
710            img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
711            return img_BAD;
712         }
713         goto again;
714       case 2: case 3: {
715         char *q;
716         int ch;
717         result = img_LABEL;
718         ch = getc(pimg->fh);
719         if (ch == EOF) {
720            img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
721            return img_BAD;
722         }
723         if (ch != '\\') ungetc(ch, pimg->fh);
724         fgets(pimg->label_buf, 257, pimg->fh);
725         if (feof(pimg->fh)) {
726            img_errno = IMG_BADFORMAT;
727            return img_BAD;
728         }
729         if (ferror(pimg->fh)) {
730            img_errno = IMG_READERROR;
731            return img_BAD;
732         }
733         q = pimg->label_buf + strlen(pimg->label_buf) - 1;
734         if (*q != '\n') {
735            img_errno = IMG_BADFORMAT;
736            return img_BAD;
737         }
738         /* Ignore empty labels in some .3d files (caused by a bug) */
739         if (q == pimg->label_buf) goto again;
740         *q = '\0';
741         pimg->flags = img_SFLAG_UNDERGROUND; /* no flags given... */
742         if (opt == 2) goto done;
743         break;
744       }
745       case 6: case 7: {
746         long len;
747         result = img_LABEL;
748
749         if (opt == 7)
750            pimg->flags = getc(pimg->fh);
751         else
752            pimg->flags = img_SFLAG_UNDERGROUND; /* no flags given... */
753
754         len = get32(pimg->fh);
755
756         if (feof(pimg->fh)) {
757            img_errno = IMG_BADFORMAT;
758            return img_BAD;
759         }
760         if (ferror(pimg->fh)) {
761            img_errno = IMG_READERROR;
762            return img_BAD;
763         }
764
765         /* Ignore empty labels in some .3d files (caused by a bug) */
766         if (len == 0) goto again;
767         if (!check_label_space(pimg, len + 1)) {
768            img_errno = IMG_OUTOFMEMORY;
769            return img_BAD;
770         }
771         if (fread(pimg->label_buf, len, 1, pimg->fh) != 1) {
772            img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
773            return img_BAD;
774         }
775         break;
776       }
777       case 4:
778         result = img_MOVE;
779         break;
780       case 5:
781         result = img_LINE;
782         break;
783       default:
784         switch ((int)opt & 0xc0) {
785          case 0x80:
786            pimg->flags = (int)opt & 0x3f;
787            result = img_LINE;
788            break;
789          case 0x40: {
790            char *q;
791            pimg->flags = (int)opt & 0x3f;
792            result = img_LABEL;
793            if (!fgets(pimg->label_buf, 257, pimg->fh)) {
794               img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
795               return img_BAD;
796            }
797            q = pimg->label_buf + strlen(pimg->label_buf) - 1;
798            /* Ignore empty-labels in some .3d files (caused by a bug) */
799            if (q == pimg->label_buf) goto again;
800            if (*q != '\n') {
801               img_errno = IMG_BADFORMAT;
802               return img_BAD;
803            }
804            *q = '\0';
805            break;
806          }
807          case 0xc0:
808            /* use this for an extra leg or station flag if we need it */
809          default:
810            img_errno = IMG_BADFORMAT;
811            return img_BAD;
812         }
813         break;
814      }
815
816      if (!read_coord(pimg->fh, &pt)) return img_BAD;
817
818      if (result == img_LABEL && pimg->survey_len) {
819         if (strncmp(pimg->label_buf, pimg->survey, pimg->survey_len + 1) != 0)
820            goto again;
821         pimg->label += pimg->survey_len + 1;
822      }
823
824      done:
825      *p = pt;
826
827      if (result == img_MOVE && pimg->version == 1) {
828         /* peek at next code and see if it's an old-style label */
829         opt_lookahead = get32(pimg->fh);
830
831         if (feof(pimg->fh)) {
832            img_errno = IMG_BADFORMAT;
833            return img_BAD;
834         }
835         if (ferror(pimg->fh)) {
836            img_errno = IMG_READERROR;
837            return img_BAD;
838         }
839
840         if (opt_lookahead == 2) return img_read_item(pimg, p);
841      }
842
843      return result;
844   } else if (pimg->version == 0) {
845      ascii_again:
846      pimg->label[0] = '\0';
847      if (feof(pimg->fh)) return img_STOP;
848      if (pimg->pending) {
849         pimg->pending = 0;
850         result = img_LINE;
851      } else {
852         char cmd[7];
853         /* Stop if nothing found */
854         if (fscanf(pimg->fh, "%6s", cmd) < 1) return img_STOP;
855         if (strcmp(cmd, "move") == 0)
856            result = img_MOVE;
857         else if (strcmp(cmd, "draw") == 0)
858            result = img_LINE;
859         else if (strcmp(cmd, "line") == 0) {
860            /* set flag to indicate to process second triplet as LINE */
861            pimg->pending = 1;
862            result = img_MOVE;
863         } else if (strcmp(cmd, "cross") == 0) {
864            if (fscanf(pimg->fh, "%lf%lf%lf", &p->x, &p->y, &p->z) < 3) {
865               img_errno = feof(pimg->fh) ? IMG_BADFORMAT : IMG_READERROR;
866               return img_BAD;
867            }
868            goto ascii_again;
869         } else if (strcmp(cmd, "name") == 0) {
870            size_t off = 0;
871            int ch = getc(pimg->fh);
872            if (ch == ' ') ch = getc(pimg->fh);
873            while (ch != ' ') {
874               if (ch == '\n' || ch == EOF) {
875                  img_errno = ferror(pimg->fh) ? IMG_READERROR : IMG_BADFORMAT;
876                  return img_BAD;
877               }
878               if (off == pimg->buf_len) {
879                  if (!check_label_space(pimg, pimg->buf_len * 2)) {
880                     img_errno = IMG_OUTOFMEMORY;
881                     return img_BAD;
882                  }
883               }
884               pimg->label_buf[off++] = ch;
885               ch = getc(pimg->fh);
886            }
887            pimg->label_buf[off] = '\0';
888
889            pimg->label = pimg->label_buf;
890            if (pimg->label[0] == '\\') pimg->label++;
891
892            result = img_LABEL;
893         } else {
894            img_errno = IMG_BADFORMAT;
895            return img_BAD; /* unknown keyword */
896         }
897      }
898
899      if (fscanf(pimg->fh, "%lf%lf%lf", &p->x, &p->y, &p->z) < 3) {
900         img_errno = ferror(pimg->fh) ? IMG_READERROR : IMG_BADFORMAT;
901         return img_BAD;
902      }
903
904      if (result == img_LABEL && pimg->survey_len) {
905         if (strncmp(pimg->label, pimg->survey, pimg->survey_len + 1) != 0)
906            goto ascii_again;
907         pimg->label += pimg->survey_len + 1;
908      }
909
910      return result;
911   } else if (pimg->version == -1) {
912      /* version -1: .pos file */
913      size_t off;
914      pimg->flags = img_SFLAG_UNDERGROUND; /* default flags */
915      againpos:
916      off = 0;
917      while (fscanf(pimg->fh, "(%lf,%lf,%lf ) ", &p->x, &p->y, &p->z) != 3) {
918         int ch;
919         if (ferror(pimg->fh)) {
920            img_errno = IMG_READERROR;
921            return img_BAD;
922         }
923         if (feof(pimg->fh)) return img_STOP;
924         if (pimg->pending) {
925            img_errno = IMG_BADFORMAT;
926            return img_BAD;
927         }
928         pimg->pending = 1;
929         /* ignore rest of line */
930         do {
931            ch = getc(pimg->fh);
932         } while (ch != '\n' && ch != '\r' && ch != EOF);
933      }
934
935      pimg->label_buf[0] = '\0';
936      while (!feof(pimg->fh)) {
937         char *b;
938         if (!fgets(pimg->label_buf + off, pimg->buf_len - off, pimg->fh)) {
939            img_errno = IMG_READERROR;
940            return img_BAD;
941         }
942
943         off += strlen(pimg->label_buf + off);
944         if (off && pimg->label_buf[off - 1] == '\n') {
945            pimg->label_buf[off - 1] = '\0';
946            break;
947         }
948         if (!check_label_space(pimg, pimg->buf_len * 2)) {
949            img_errno = IMG_OUTOFMEMORY;
950            return img_BAD;
951         }
952      }
953
954      pimg->label = pimg->label_buf;
955
956      if (pimg->label[0] == '\\') pimg->label++;
957
958      if (pimg->survey_len) {
959         size_t l = pimg->survey_len + 1;
960         if (strncmp(pimg->survey, pimg->label, l) != 0) goto againpos;
961         pimg->label += l;
962      }
963
964      return img_LABEL;
965   } else {
966      /* version -2: Compass .plt file */
967      if (pimg->pending) {
968         /* pending MOVE or LINE or STOP */
969         int r = pimg->pending - 4;
970         pimg->pending = 0;
971         pimg->flags = 0;
972         pimg->label[pimg->label_len] = '\0';
973         return r;
974      }
975
976      while (1) {
977         char *line = getline_alloc(pimg->fh);
978         char *q;
979         size_t len = 0;
980
981         switch (line[0]) {
982            case 'M': case 'D':
983               /* Move or Draw */
984               if (sscanf(line + 1, "%lf %lf %lf", &p->x, &p->y, &p->z) != 3) {
985                  osfree(line);
986                  if (ferror(pimg->fh)) {
987                     img_errno = IMG_READERROR;
988                  } else {
989                     img_errno = IMG_BADFORMAT;
990                  }
991                  return img_BAD;
992               }
993               q = strchr(line, 'S');
994               if (!q) {
995                  osfree(line);
996                  img_errno = IMG_BADFORMAT;
997                  return img_BAD;
998               }
999               ++q;
1000               len = 0;
1001               while (q[len] > ' ') ++len;
1002               q[len] = '\0';
1003               len += 2; /* '.' and '\0' */
1004               if (!check_label_space(pimg, pimg->label_len + len)) {
1005                  img_errno = IMG_OUTOFMEMORY;
1006                  return img_BAD;
1007               }
1008               pimg->label = pimg->label_buf;
1009               pimg->label[pimg->label_len] = '.';
1010               memcpy(pimg->label + pimg->label_len + 1, q, len - 1);
1011               pimg->pending = (line[0] == 'M' ? img_MOVE : img_LINE) + 4;
1012               osfree(line);
1013               pimg->flags = img_SFLAG_UNDERGROUND; /* default flags */
1014               return img_LABEL;
1015            case 'X': case 'F': case 'S':
1016               /* bounding boX (marks end of survey), Feature survey, or
1017                * new Section - skip to next survey */
1018               do {
1019                  do {
1020                     osfree(line);
1021                     line = getline_alloc(pimg->fh);
1022                     if (!line) {
1023                        img_errno = IMG_OUTOFMEMORY;
1024                        return img_BAD;
1025                     }
1026                     if (line[0] == '\x1a') {
1027                        osfree(line);
1028                        return img_STOP;
1029                     }
1030                     if (feof(pimg->fh)) {
1031                        osfree(line);
1032                        img_errno = IMG_BADFORMAT;
1033                        return img_BAD;
1034                     }
1035                  } while (line[0] != 'N');
1036
1037                  len = 1;
1038                  while (line[len] > 32) ++len;
1039               } while (pimg->survey && (pimg->survey_len != len - 1 ||
1040                        memcmp(line + 1, pimg->survey, pimg->survey_len) != 0));
1041
1042               if (!check_label_space(pimg, len)) {
1043                  img_errno = IMG_OUTOFMEMORY;
1044                  return img_BAD;
1045               }
1046               --len;
1047               pimg->label_len = len;
1048               pimg->label = pimg->label_buf;
1049               memcpy(pimg->label, line + 1, len);
1050               pimg->label[len] = '\0';
1051
1052               osfree(line);
1053               break;
1054            default:
1055               osfree(line);
1056               img_errno = IMG_BADFORMAT;
1057               return img_BAD;
1058         }
1059      }
1060   }
1061}
1062
1063static int
1064write_v3label(img *pimg, int opt, const char *s)
1065{
1066   size_t len, n, dot;
1067
1068   /* find length of common prefix */
1069   dot = 0;
1070   for (len = 0; s[len] == pimg->label_buf[len] && s[len] != '\0'; len++) {
1071      if (s[len] == '.') dot = len + 1;
1072   }
1073
1074   ASSERT(len <= pimg->label_len);
1075   n = pimg->label_len - len;
1076   if (len == 0) {
1077      if (pimg->label_len) putc(0, pimg->fh);
1078   } else if (n <= 16) {
1079      if (n) putc(n + 15, pimg->fh);
1080   } else if (dot == 0) {
1081      if (pimg->label_len) putc(0, pimg->fh);
1082      len = 0;
1083   } else {
1084      const char *p = pimg->label_buf + dot;
1085      n = 1;
1086      for (len = pimg->label_len - dot - 17; len; len--) {
1087         if (*p++ == '.') n++;
1088      }
1089      if (n <= 14) {
1090         putc(n, pimg->fh);
1091         len = dot;
1092      } else {
1093         if (pimg->label_len) putc(0, pimg->fh);
1094         len = 0;
1095      }
1096   }
1097
1098   n = strlen(s + len);
1099   putc(opt, pimg->fh);
1100   if (n < 0xfe) {
1101      putc(n, pimg->fh);
1102   } else if (n < 0xffff + 0xfe) {
1103      putc(0xfe, pimg->fh);
1104      put16(n - 0xfe, pimg->fh);
1105   } else {
1106      putc(0xff, pimg->fh);
1107      put32(n, pimg->fh);
1108   }
1109   fwrite(s + len, n, 1, pimg->fh);
1110
1111   n += len;
1112   pimg->label_len = n;
1113   if (!check_label_space(pimg, n + 1))
1114      return 0; /* FIXME: distinguish out of memory... */
1115   memcpy(pimg->label_buf + len, s + len, n - len + 1);
1116
1117   return !ferror(pimg->fh);
1118}
1119
1120void
1121img_write_item(img *pimg, int code, int flags, const char *s,
1122               double x, double y, double z)
1123{
1124   if (!pimg) return;
1125   if (pimg->version == 3) {
1126      int opt = 0;
1127      switch (code) {
1128       case img_LABEL:
1129         write_v3label(pimg, 0x40 | flags, s);
1130         opt = 0;
1131         break;
1132       case img_MOVE:
1133         opt = 15;
1134         break;
1135       case img_LINE:
1136         write_v3label(pimg, 0x80 | flags, s ? s : "");
1137         opt = 0;
1138         break;
1139       default: /* ignore for now */
1140         return;
1141      }
1142      if (opt) putc(opt, pimg->fh);
1143      /* Output in cm */
1144      put32((INT32_T)my_round(x * 100.0), pimg->fh);
1145      put32((INT32_T)my_round(y * 100.0), pimg->fh);
1146      put32((INT32_T)my_round(z * 100.0), pimg->fh);
1147   } else {
1148      size_t len;
1149      INT32_T opt = 0;
1150      ASSERT(pimg->version > 0);
1151      switch (code) {
1152       case img_LABEL:
1153         if (pimg->version == 1) {
1154            /* put a move before each label */
1155            img_write_item(pimg, img_MOVE, 0, NULL, x, y, z);
1156            put32(2, pimg->fh);
1157            fputsnl(s, pimg->fh);
1158            return;
1159         }
1160         len = strlen(s);
1161         if (len > 255 || strchr(s, '\n')) {
1162            /* long label - not in early incarnations of v2 format, but few
1163             * 3d files will need these, so better not to force incompatibility
1164             * with a new version I think... */
1165            putc(7, pimg->fh);
1166            putc(flags, pimg->fh);
1167            put32(len, pimg->fh);
1168            fputs(s, pimg->fh);
1169         } else {
1170            putc(0x40 | (flags & 0x3f), pimg->fh);
1171            fputsnl(s, pimg->fh);
1172         }
1173         opt = 0;
1174         break;
1175       case img_MOVE:
1176         opt = 4;
1177         break;
1178       case img_LINE:
1179         if (pimg->version > 1) {
1180            opt = 0x80 | (flags & 0x3f);
1181            break;
1182         }
1183         opt = 5;
1184         break;
1185       default: /* ignore for now */
1186         return;
1187      }
1188      if (pimg->version == 1) {
1189         put32(opt, pimg->fh);
1190      } else {
1191         if (opt) putc(opt, pimg->fh);
1192      }
1193      /* Output in cm */
1194      put32((INT32_T)my_round(x * 100.0), pimg->fh);
1195      put32((INT32_T)my_round(y * 100.0), pimg->fh);
1196      put32((INT32_T)my_round(z * 100.0), pimg->fh);
1197   }
1198}
1199
1200int
1201img_close(img *pimg)
1202{
1203   int result = 1;
1204   if (pimg) {
1205      if (pimg->fh) {
1206         if (pimg->fRead) {
1207            osfree(pimg->survey);
1208            osfree(pimg->title);
1209            osfree(pimg->datestamp);
1210         } else {
1211            /* write end of data marker */
1212            switch (pimg->version) {
1213             case 1:
1214               put32((INT32_T)-1, pimg->fh);
1215               break;
1216             case 2:
1217               putc(0, pimg->fh);
1218               break;
1219             case 3:
1220               if (pimg->label_len) putc(0, pimg->fh);
1221               putc(0, pimg->fh);
1222               break;
1223            }
1224         }
1225         if (ferror(pimg->fh)) result = 0;
1226         if (fclose(pimg->fh)) result = 0;
1227         img_errno = pimg->fRead ? IMG_READERROR : IMG_WRITEERROR;
1228      }
1229      osfree(pimg->label_buf);
1230      osfree(pimg);
1231   }
1232   return result;
1233}
Note: See TracBrowser for help on using the repository browser.