2 * $Logfile: /Freespace2/code/CFile/cfile.cpp $
7 * Utilities for operating on files
10 * Revision 1.1 2002/05/03 03:28:08 root
14 * 20 9/08/99 10:01p Dave
15 * Make sure game won't run in a drive's root directory. Make sure
16 * standalone routes suqad war messages properly to the host.
18 * 19 9/08/99 12:03a Dave
19 * Make squad logos render properly in D3D all the time. Added intel anim
22 * 18 9/06/99 2:35p Dave
23 * Rename briefing and debriefing voice direcrory paths properly.
25 * 17 9/03/99 1:31a Dave
26 * CD checking by act. Added support to play 2 cutscenes in a row
27 * seamlessly. Fixed super low level cfile bug related to files in the
28 * root directory of a CD. Added cheat code to set campaign mission # in
31 * 16 8/31/99 9:46a Dave
32 * Support for new cfile cbanims directory.
34 * 15 8/06/99 11:20a Johns
35 * Don't call game_cd_changed() in a demo or multiplayer beta build.
37 * 14 6/08/99 2:33p Dave
38 * Fixed release build warning. Put in hud config stuff.
40 * 13 5/19/99 4:07p Dave
41 * Moved versioning code into a nice isolated common place. Fixed up
42 * updating code on the pxo screen. Fixed several stub problems.
44 * 12 4/30/99 12:18p Dave
45 * Several minor bug fixes.
47 * 11 4/07/99 5:54p Dave
48 * Fixes for encryption in updatelauncher.
50 * 10 3/28/99 5:58p Dave
51 * Added early demo code. Make objects move. Nice and framerate
52 * independant, but not much else. Don't use yet unless you're me :)
54 * 9 2/22/99 10:31p Andsager
55 * Get rid of unneeded includes.
57 * 8 1/12/99 3:15a Dave
58 * Barracks screen support for selecting squad logos. We need real artwork
61 * 7 11/30/98 1:07p Dave
62 * 16 bit conversion, first run.
64 * 6 10/29/98 10:41a Dave
65 * Change the way cfile initializes exe directory.
67 * 5 10/13/98 9:19a Andsager
68 * Add localization support to cfile. Optional parameter with cfopen that
69 * looks for localized files.
71 * 4 10/12/98 9:54a Dave
72 * Fixed a few file organization things.
74 * 3 10/07/98 6:27p Dave
75 * Globalized mission and campaign file extensions. Removed Silent Threat
76 * special code. Moved \cache \players and \multidata into the \data
79 * 2 10/07/98 10:52a Dave
82 * 1 10/07/98 10:48a Dave
84 * 110 9/17/98 10:31a Hoffoss
85 * Changed code to use location of executable as root rather than relying
86 * on the cwd being set correctly. This is most helpful in the case of
87 * Fred launching due to the user double-clicking on an .fsm file in
88 * explorer or something (where the cwd is probably the location of the
91 * 109 9/11/98 4:14p Dave
92 * Fixed file checksumming of < file_size. Put in more verbose kicking and
93 * PXO stats store reporting.
95 * 108 9/09/98 5:53p Dave
96 * Put in new tracker packets in API. Change cfile to be able to checksum
99 * 107 9/04/98 3:51p Dave
100 * Put in validated mission updating and application during stats
103 * 106 8/31/98 2:06p Dave
104 * Make cfile sort the ordering or vp files. Added support/checks for
105 * recognizing "mission disk" players.
107 * 105 8/20/98 5:30p Dave
108 * Put in handy multiplayer logfile system. Now need to put in useful
109 * applications of it all over the code.
111 * 104 8/12/98 4:53p Dave
112 * Put in 32 bit checksumming for PXO missions. No validation on the
113 * actual tracker yet, though.
115 * 103 6/17/98 9:30a Allender
116 * fixed red alert replay stats clearing problem
118 * 102 6/05/98 9:46a Lawrance
119 * check for CD change on cfopen()
121 * 101 5/19/98 1:19p Allender
122 * new low level reliable socket reading code. Make all missions/campaign
123 * load/save to data missions folder (i.e. we are rid of the player
126 * 100 5/13/98 10:22p John
127 * Added cfile functions to read/write rle compressed blocks of data.
128 * Made palman use it for .clr files. Made alphacolors calculate on the
129 * fly rather than caching to/from disk.
131 * 99 5/11/98 10:59a John
132 * Moved the low-level file reading code into cfilearchive.cpp.
134 * 98 5/06/98 5:30p John
135 * Removed unused cfilearchiver. Removed/replaced some unused/little used
136 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
137 * DirectX header files and libs that fixed the Direct3D alpha blending
140 * 97 5/03/98 11:53a John
141 * Fixed filename case mangling.
143 * 96 5/03/98 8:33a John
144 * Made sure there weren't any more broken function lurking around like
145 * the one Allender fixed.
147 * 95 5/02/98 11:05p Allender
148 * fix cfilelength for pack files
153 #define _CFILE_INTERNAL
163 #include <winbase.h> /* needed for memory mapping of file functions */
166 #include <sys/stat.h>
167 #include <sys/types.h>
173 //#include "outwnd.h"
174 //#include "vecmat.h"
176 #include "cfilesystem.h"
177 #include "cfilearchive.h"
180 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
182 // During cfile_init, verify that Pathtypes[n].index == n for each item
183 // Each path must have a valid parent that can be tracable all the way back to the root
184 // so that we can create directories when we need to.
186 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
187 // What type this is Path Extensions Parent type
188 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
189 // Root must be index 1!!
190 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
191 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
192 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
193 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
194 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
195 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
196 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
197 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
198 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
199 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
200 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
201 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
202 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
203 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
204 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
205 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
206 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
207 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
208 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
209 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
210 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
211 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
212 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
213 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
214 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
215 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
216 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
217 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
218 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
219 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
220 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
221 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
222 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
223 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
224 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
228 #define CFILE_STACK_MAX 8
230 int cfile_inited = 0;
231 int Cfile_stack_pos = 0;
233 char Cfile_stack[128][CFILE_STACK_MAX];
235 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
236 CFILE Cfile_list[MAX_CFILE_BLOCKS];
238 char *Cfile_cdrom_dir = NULL;
241 // Function prototypes for internally-called functions
243 int cfget_cfile_block();
244 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
245 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
246 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
247 void cf_chksum_long_init();
251 cf_free_secondary_filelist();
254 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
255 int cfile_in_root_dir(char *exe_path)
258 char path_copy[2048] = "";
262 if(exe_path == NULL){
267 memset(path_copy, 0, 2048);
268 strncpy(path_copy, exe_path, 2047);
270 // count how many slashes there are in the path
271 tok = strtok(path_copy, "\\");
277 tok = strtok(NULL, "\\");
278 } while(tok != NULL);
280 // root directory if we have <= 1 slash
281 if(token_count <= 2){
285 // not-root directory
289 // cfile_init() initializes the cfile system. Called once at application start.
291 // returns: success ==> 0
292 // error ==> non-zero
294 int cfile_init(char *exe_dir, char *cdrom_dir)
298 // initialize encryption
301 if ( !cfile_inited ) {
306 strcpy(buf, exe_dir);
309 // are we in a root directory?
310 if(cfile_in_root_dir(buf)){
312 fprintf (stderr, "ERROR: Freespace2/Fred2 cannot be run from a drive root directory!");
314 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
330 fprintf (stderr, "Error trying to determine executable root directory!");
332 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
337 // set root directory
338 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
340 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
341 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
344 Cfile_cdrom_dir = cdrom_dir;
345 cf_build_secondary_filelist(Cfile_cdrom_dir);
347 // 32 bit CRC table init
348 cf_chksum_long_init();
350 atexit( cfile_close );
356 // Call this if pack files got added or removed or the
357 // cdrom changed. This will refresh the list of filenames
358 // stored in packfiles and on the cdrom.
361 cf_build_secondary_filelist(Cfile_cdrom_dir);
365 // Changes to a drive if valid.. 1=A, 2=B, etc
366 // If flag, then changes to it.
367 // Returns 0 if not-valid, 1 if valid.
368 int cfile_chdrive( int DriveNum, int flag )
381 _chdrive( DriveNum );
388 if ( (!flag) && (n != org) )
394 // push current directory on a 'stack' (so we can restore it) and change the directory
395 int cfile_push_chdir(int type)
399 char OriginalDirectory[128];
401 char NoDir[] = "\\.";
403 _getcwd(OriginalDirectory, 127);
404 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
405 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
407 cf_create_default_path_string( dir, type, NULL );
409 Drive = strchr(dir, ':');
412 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
425 // This chdir might get a critical error!
428 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
436 int cfile_chdir(char *dir)
439 char OriginalDirectory[128];
441 char NoDir[] = "\\.";
443 _getcwd(OriginalDirectory, 127);
446 Drive = strchr(dir, ':');
448 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
461 // This chdir might get a critical error!
464 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
473 Assert(Cfile_stack_pos);
475 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
478 // flush (delete all files in) the passed directory (by type), return the # of files deleted
479 // NOTE : WILL NOT DELETE READ-ONLY FILES
480 int cfile_flush_dir(int dir_type)
490 Assert( CF_TYPE_SPECIFIED(dir_type) );
492 // attempt to change the directory to the passed type
493 if(cfile_push_chdir(dir_type)){
497 // proceed to delete the files
498 find_handle = _findfirst( "*", &find );
500 if (find_handle != -1) {
502 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
504 cf_delete(find.name,dir_type);
506 // increment the deleted count
509 } while (!_findnext(find_handle, &find));
510 _findclose( find_handle );
513 // pop the directory back
516 // return the # of files deleted
522 // add the given extention to a filename (or filepath) if it doesn't already have this
524 // filename = name of filename or filepath to process
525 // ext = extension to add. Must start with the period
526 // Returns: new filename or filepath with extension.
527 char *cf_add_ext(char *filename, char *ext)
530 static char path[MAX_PATH_LEN];
532 flen = strlen(filename);
534 Assert(flen < MAX_PATH_LEN);
535 strcpy(path, filename);
536 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
537 Assert(flen + elen < MAX_PATH_LEN);
545 void cf_delete( char *filename, int dir_type )
547 char longname[MAX_PATH_LEN];
549 Assert( CF_TYPE_SPECIFIED(dir_type) );
551 cf_create_default_path_string( longname, dir_type, filename );
553 FILE *fp = fopen(longname, "rb");
563 // Same as _access function to read a file's access bits
564 int cf_access( char *filename, int dir_type, int mode )
566 char longname[MAX_PATH_LEN];
568 Assert( CF_TYPE_SPECIFIED(dir_type) );
570 cf_create_default_path_string( longname, dir_type, filename );
572 return access(longname,mode);
576 // Returns 1 if file exists, 0 if not.
577 int cf_exist( char *filename, int dir_type )
579 char longname[MAX_PATH_LEN];
581 Assert( CF_TYPE_SPECIFIED(dir_type) );
583 cf_create_default_path_string( longname, dir_type, filename );
585 FILE *fp = fopen(longname, "rb");
594 void cf_attrib(char *filename, int set, int clear, int dir_type)
596 char longname[MAX_PATH_LEN];
598 Assert( CF_TYPE_SPECIFIED(dir_type) );
600 cf_create_default_path_string( longname, dir_type, filename );
602 FILE *fp = fopen(longname, "rb");
609 DWORD z = GetFileAttributes(longname);
610 SetFileAttributes(longname, z | set & ~clear);
616 int cf_rename(char *old_name, char *name, int dir_type)
618 Assert( CF_TYPE_SPECIFIED(dir_type) );
621 char old_longname[_MAX_PATH];
622 char new_longname[_MAX_PATH];
624 cf_create_default_path_string( old_longname, dir_type, old_name );
625 cf_create_default_path_string( new_longname, dir_type, name );
627 ret_code = rename(old_longname, new_longname );
631 return CF_RENAME_FAIL_ACCESS;
634 return CF_RENAME_FAIL_EXIST;
638 return CF_RENAME_SUCCESS;
643 // Creates the directory path if it doesn't exist. Even creates all its
645 void cf_create_directory( int dir_type )
648 int dir_tree[CF_MAX_PATH_TYPES];
649 char longname[MAX_PATH_LEN];
651 Assert( CF_TYPE_SPECIFIED(dir_type) );
653 int current_dir = dir_type;
656 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
658 dir_tree[num_dirs++] = current_dir;
659 current_dir = Pathtypes[current_dir].parent_index;
661 } while( current_dir != CF_TYPE_ROOT );
666 for (i=num_dirs-1; i>=0; i-- ) {
667 cf_create_default_path_string( longname, dir_tree[i], NULL );
670 if ( _mkdir(longname, 0777)==0 ) {
671 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
674 if ( _mkdir(longname)==0 ) {
675 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
684 extern int game_cd_changed();
688 // parameters: *filepath ==> name of file to open (may be path+name)
689 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
690 // passing NULL to mode deletes the file if it exists and returns NULL
691 // type ==> one of: CFILE_NORMAL
692 // CFILE_MEMORY_MAPPED
693 // dir_type => override extension check, value is one of CF_TYPE* #defines
695 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
698 // returns: success ==> address of CFILE structure
702 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
704 char longname[_MAX_PATH];
706 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
707 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
709 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
711 if ( game_cd_changed() ) {
716 //================================================
717 // Check that all the parameters make sense
718 Assert(file_path && strlen(file_path));
719 Assert( mode != NULL );
721 // Can only open read-only binary files in memory mapped mode.
722 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
727 //===========================================================
728 // If in write mode, just try to open the file straight off
729 // the harddisk. No fancy packfile stuff here!
731 if ( strchr(mode,'w') ) {
732 // For write-only files, require a full path or a path type
733 if ( strpbrk(file_path,"/\\:") ) {
735 strcpy(longname, file_path );
738 Assert( dir_type != CF_TYPE_ANY );
740 // Create the directory if necessary
741 cf_create_directory( dir_type );
743 cf_create_default_path_string( longname, dir_type, file_path );
745 Assert( !(type & CFILE_MEMORY_MAPPED) );
747 // JOHN: TODO, you should create the path if it doesn't exist.
749 FILE *fp = fopen(longname, mode);
751 return cf_open_fill_cfblock(fp, dir_type);
757 //================================================
758 // Search for file on disk, on cdrom, or in a packfile
761 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
762 strcpy(copy_file_path, file_path);
765 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
767 // Fount it, now create a cfile out of it
769 if ( type & CFILE_MEMORY_MAPPED ) {
771 // Can't open memory mapped files out of pack files
778 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
780 if (hFile != INVALID_HANDLE_VALUE) {
781 return cf_open_mapped_fill_cfblock(hFile, dir_type);
788 FILE *fp = fopen( longname, "rb" );
792 // Found it in a pack file
793 return cf_open_packed_cfblock(fp, dir_type, offset, size );
795 // Found it in a normal file
796 return cf_open_fill_cfblock(fp, dir_type);
807 // ------------------------------------------------------------------------
810 // Open up a temporary file. A unique name is automatically generated. The
811 // file will be automatically deleted when file is closed.
813 // return: NULL => tmp file could not be opened
814 // pointer to CFILE => tmp file successfully opened
821 return cf_open_fill_cfblock(fp, 0);
828 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
829 // Cfile_block_list[] array and return the index.
831 // returns: success ==> index in Cfile_block_list[] array
834 int cfget_cfile_block()
839 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
840 cb = &Cfile_block_list[i];
841 if ( cb->type == CFILE_BLOCK_UNUSED ) {
844 cb->type = CFILE_BLOCK_USED;
849 // If we've reached this point, a free Cfile_block could not be found
850 nprintf(("Warning","A free Cfile_block could not be found.\n"));
851 Assert(0); // out of free cfile blocks
856 // cfclose() closes the file
858 // returns: success ==> 0
861 int cfclose( CFILE * cfile )
865 Assert(cfile != NULL);
867 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
868 cb = &Cfile_block_list[cfile->id];
872 // close memory mapped file
876 result = UnmapViewOfFile((void*)cb->data);
878 result = CloseHandle(cb->hInFile);
879 Assert(result); // Ensure file handle is closed properly
880 result = CloseHandle(cb->hMapFile);
881 Assert(result); // Ensure file handle is closed properly
885 } else if ( cb->fp != NULL ) {
886 Assert(cb->fp != NULL);
887 result = fclose(cb->fp);
892 cb->type = CFILE_BLOCK_UNUSED;
899 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
900 // for the case of a file being opened by cf_open();
902 // returns: success ==> ptr to CFILE structure.
905 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
907 int cfile_block_index;
909 cfile_block_index = cfget_cfile_block();
910 if ( cfile_block_index == -1 ) {
915 cfbp = &Cfile_block_list[cfile_block_index];
916 cfp = &Cfile_list[cfile_block_index];;
917 cfp->id = cfile_block_index;
921 cfbp->dir_type = type;
923 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
930 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
931 // for the case of a file being opened by cf_open();
933 // returns: success ==> ptr to CFILE structure.
936 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
938 // Found it in a pack file
939 int cfile_block_index;
941 cfile_block_index = cfget_cfile_block();
942 if ( cfile_block_index == -1 ) {
947 cfbp = &Cfile_block_list[cfile_block_index];
949 cfp = &Cfile_list[cfile_block_index];
950 cfp->id = cfile_block_index;
954 cfbp->dir_type = type;
956 cf_init_lowlevel_read_code(cfp,offset, size );
965 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
966 // for the case of a file being opened by cf_open_mapped();
968 // returns: ptr CFILE structure.
970 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
972 int cfile_block_index;
974 cfile_block_index = cfget_cfile_block();
975 if ( cfile_block_index == -1 ) {
981 cfbp = &Cfile_block_list[cfile_block_index];
983 cfp = &Cfile_list[cfile_block_index];
984 cfp->id = cfile_block_index;
986 cfbp->hInFile = hFile;
987 cfbp->dir_type = type;
989 cf_init_lowlevel_read_code(cfp,0 , 0 );
994 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
995 if (cfbp->hMapFile == NULL) {
996 nprintf(("Error", "Could not create file-mapping object.\n"));
1000 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1001 Assert( cfbp->data != NULL );
1007 int cf_get_dir_type(CFILE *cfile)
1009 return Cfile_block_list[cfile->id].dir_type;
1012 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1013 // with the CFILE structure passed as a parameter
1017 void *cf_returndata(CFILE *cfile)
1019 Assert(cfile != NULL);
1021 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1022 cb = &Cfile_block_list[cfile->id];
1023 Assert(cb->data != NULL);
1029 // version number of opened file. Will be 0 unless you put something else here after you
1030 // open a file. Once set, you can use minimum version numbers with the read functions.
1031 void cf_set_version( CFILE * cfile, int version )
1033 Assert(cfile != NULL);
1035 cfile->version = version;
1038 // routines to read basic data types from CFILE's. Put here to
1039 // simplify mac/pc reading from cfiles.
1041 float cfread_float(CFILE *file, int ver, float deflt)
1045 if (file->version < ver)
1048 if (cfread( &f, sizeof(f), 1, file) != 1)
1051 // i = INTEL_INT(i); // hmm, not sure what to do here
1055 int cfread_int(CFILE *file, int ver, int deflt)
1059 if (file->version < ver)
1062 if (cfread( &i, sizeof(i), 1, file) != 1)
1069 uint cfread_uint(CFILE *file, int ver, uint deflt)
1073 if (file->version < ver)
1076 if (cfread( &i, sizeof(i), 1, file) != 1)
1083 short cfread_short(CFILE *file, int ver, short deflt)
1087 if (file->version < ver)
1090 if (cfread( &s, sizeof(s), 1, file) != 1)
1097 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1101 if (file->version < ver)
1104 if (cfread( &s, sizeof(s), 1, file) != 1)
1111 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1115 if (file->version < ver)
1118 if (cfread( &b, sizeof(b), 1, file) != 1)
1124 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1126 if (file->version < ver) {
1130 vec->x = vec->y = vec->z = 0.0f;
1135 vec->x = cfread_float(file, ver, deflt ? deflt->x : NULL);
1136 vec->y = cfread_float(file, ver, deflt ? deflt->y : NULL);
1137 vec->z = cfread_float(file, ver, deflt ? deflt->z : NULL);
1140 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1142 if (file->version < ver) {
1146 ang->p = ang->b = ang->h = 0.0f;
1151 ang->p = cfread_float(file, ver, deflt ? deflt->p : NULL);
1152 ang->b = cfread_float(file, ver, deflt ? deflt->b : NULL);
1153 ang->h = cfread_float(file, ver, deflt ? deflt->h : NULL);
1156 char cfread_char(CFILE *file, int ver, char deflt)
1160 if (file->version < ver)
1163 if (cfread( &b, sizeof(b), 1, file) != 1)
1169 void cfread_string(char *buf, int n, CFILE *file)
1174 c = cfread_char(file);
1182 void cfread_string_len(char *buf,int n, CFILE *file)
1185 len = cfread_int(file);
1188 cfread(buf, len, 1, file);
1193 // equivalent write functions of above read functions follow
1195 int cfwrite_float(float f, CFILE *file)
1197 // i = INTEL_INT(i); // hmm, not sure what to do here
1198 return cfwrite(&f, sizeof(f), 1, file);
1201 int cfwrite_int(int i, CFILE *file)
1204 return cfwrite(&i, sizeof(i), 1, file);
1207 int cfwrite_uint(uint i, CFILE *file)
1210 return cfwrite(&i, sizeof(i), 1, file);
1213 int cfwrite_short(short s, CFILE *file)
1216 return cfwrite(&s, sizeof(s), 1, file);
1219 int cfwrite_ushort(ushort s, CFILE *file)
1222 return cfwrite(&s, sizeof(s), 1, file);
1225 int cfwrite_ubyte(ubyte b, CFILE *file)
1227 return cfwrite(&b, sizeof(b), 1, file);
1230 int cfwrite_vector(vector *vec, CFILE *file)
1232 if(!cfwrite_float(vec->x, file)){
1235 if(!cfwrite_float(vec->y, file)){
1238 return cfwrite_float(vec->z, file);
1241 int cfwrite_angles(angles *ang, CFILE *file)
1243 if(!cfwrite_float(ang->p, file)){
1246 if(!cfwrite_float(ang->b, file)){
1249 return cfwrite_float(ang->h, file);
1252 int cfwrite_char(char b, CFILE *file)
1254 return cfwrite( &b, sizeof(b), 1, file);
1257 int cfwrite_string(char *buf, CFILE *file)
1259 if ( (!buf) || (buf && !buf[0]) ) {
1260 return cfwrite_char(0, file);
1262 int len = strlen(buf);
1263 if(!cfwrite(buf, len, 1, file)){
1266 return cfwrite_char(0, file); // write out NULL termination
1269 int cfwrite_string_len(char *buf, CFILE *file)
1271 int len = strlen(buf);
1273 if(!cfwrite_int(len, file)){
1277 return cfwrite(buf,len,1,file);
1283 // Get the filelength
1284 int cfilelength( CFILE * cfile )
1286 Assert(cfile != NULL);
1288 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1289 cb = &Cfile_block_list[cfile->id];
1291 // TODO: return length of memory mapped file
1292 Assert( !cb->data );
1294 Assert(cb->fp != NULL);
1296 // cb->size gets set at cfopen
1300 // cfwrite() writes to the file
1302 // returns: number of full elements actually written
1305 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1307 Assert(cfile != NULL);
1308 Assert(buf != NULL);
1313 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1314 cb = &Cfile_block_list[cfile->id];
1318 // cfwrite() not supported for memory-mapped files
1319 Assert( !cb->data );
1321 Assert(cb->fp != NULL);
1322 Assert(cb->lib_offset == 0 );
1323 result = fwrite(buf, elsize, nelem, cb->fp);
1329 // cfputc() writes a character to a file
1331 // returns: success ==> returns character written
1334 int cfputc(int c, CFILE *cfile)
1338 Assert(cfile != NULL);
1340 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1341 cb = &Cfile_block_list[cfile->id];
1344 // cfputc() not supported for memory-mapped files
1345 Assert( !cb->data );
1347 Assert(cb->fp != NULL);
1348 result = fputc(c, cb->fp);
1354 // cfgetc() reads a character from a file
1356 // returns: success ==> returns character read
1359 int cfgetc(CFILE *cfile)
1361 Assert(cfile != NULL);
1365 int result = cfread(&tmp, 1, 1, cfile );
1366 if ( result == 1 ) {
1379 // cfgets() reads a string from a file
1381 // returns: success ==> returns pointer to string
1384 char *cfgets(char *buf, int n, CFILE *cfile)
1386 Assert(cfile != NULL);
1387 Assert(buf != NULL);
1393 for (i=0; i<n-1; i++ ) {
1397 int ret = cfread( &tmp_c, 1, 1, cfile );
1407 } while ( c == 13 );
1409 if ( c=='\n' ) break;
1416 // cfputs() writes a string to a file
1418 // returns: success ==> non-negative value
1421 int cfputs(char *str, CFILE *cfile)
1423 Assert(cfile != NULL);
1424 Assert(str != NULL);
1427 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1428 cb = &Cfile_block_list[cfile->id];
1433 // cfputs() not supported for memory-mapped files
1434 Assert( !cb->data );
1435 Assert(cb->fp != NULL);
1436 result = fputs(str, cb->fp);
1442 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1444 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1445 // checksumming code that he wrote a while ago.
1446 #define CRC32_POLYNOMIAL 0xEDB88320L
1447 unsigned long CRCTable[256];
1449 #define CF_CHKSUM_SAMPLE_SIZE 512
1451 // update cur_chksum with the chksum of the new_data of size new_data_size
1452 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1454 ubyte * ptr = (ubyte *)buffer;
1455 unsigned int sum1,sum2;
1457 sum1 = sum2 = (int)(seed);
1461 if (sum1 >= 255 ) sum1 -= 255;
1466 return (unsigned short)((sum1<<8)+ sum2);
1469 // update cur_chksum with the chksum of the new_data of size new_data_size
1470 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1474 unsigned long temp1;
1475 unsigned long temp2;
1477 p = (unsigned char*)buffer;
1481 temp1 = (crc>>8)&0x00FFFFFFL;
1482 temp2 = CRCTable[((int)crc^*p++)&0xff];
1489 void cf_chksum_long_init()
1494 for( i=0;i<=255;i++) {
1498 crc=(crc>>1)^CRC32_POLYNOMIAL;
1506 // single function convenient to use for both short and long checksums
1507 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1508 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1510 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1516 // determine whether we're doing a short or long checksum
1527 // if max_size is -1, set it to be the size of the file
1529 cfseek(cfile, 0, SEEK_SET);
1530 max_size = cfilelength(cfile);
1535 // determine how much we want to read
1536 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1537 read_size = CF_CHKSUM_SAMPLE_SIZE;
1539 read_size = max_size - cf_total;
1542 // read in some buffer
1543 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1545 // total we've read so far
1550 // do the proper short or long checksum
1552 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1554 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1557 } while((cf_len > 0) && (cf_total < max_size));
1562 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1563 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1566 CFILE *cfile = NULL;
1568 // zero the checksum
1571 // attempt to open the file
1572 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1577 // call the overloaded cf_chksum function()
1578 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1580 // close the file down
1584 // return the result
1588 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1589 // NOTE : preserves current file position
1590 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1595 // Returns current position of file.
1596 start_pos = cftell(file);
1597 if(start_pos == -1){
1601 // move to the beginning of the file
1602 if(cfseek(file, 0, CF_SEEK_SET)){
1605 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1606 // move back to the start position
1607 cfseek(file, start_pos, CF_SEEK_SET);
1612 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1613 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1616 CFILE *cfile = NULL;
1618 // zero the checksum
1621 // attempt to open the file
1622 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1627 // call the overloaded cf_chksum function()
1628 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1630 // close the file down
1634 // return the result
1638 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1639 // NOTE : preserves current file position
1640 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1645 // Returns current position of file.
1646 start_pos = cftell(file);
1647 if(start_pos == -1){
1651 // move to the beginning of the file
1652 if(cfseek(file, 0, CF_SEEK_SET)){
1655 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1656 // move back to the start position
1657 cfseek(file, start_pos, CF_SEEK_SET);
1663 // Flush the open file buffer
1665 // exit: 0 - success
1667 int cflush(CFILE *cfile)
1669 Assert(cfile != NULL);
1671 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1672 cb = &Cfile_block_list[cfile->id];
1674 // not supported for memory mapped files
1675 Assert( !cb->data );
1677 Assert(cb->fp != NULL);
1678 return fflush(cb->fp);