2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/CFile/cfile.cpp $
15 * Utilities for operating on files
18 * Revision 1.5 2002/06/09 04:41:15 relnev
19 * added copyright header
21 * Revision 1.4 2002/06/05 08:05:28 relnev
22 * stub/warning removal.
24 * reworked the sound code.
26 * Revision 1.3 2002/05/28 08:52:03 relnev
27 * implemented two assembly stubs.
29 * cleaned up a few warnings.
31 * added a little demo hackery to make it progress a little farther.
33 * Revision 1.2 2002/05/28 06:28:20 theoddone33
34 * Filesystem mods, actually reads some data files now
36 * Revision 1.1.1.1 2002/05/03 03:28:08 root
40 * 20 9/08/99 10:01p Dave
41 * Make sure game won't run in a drive's root directory. Make sure
42 * standalone routes suqad war messages properly to the host.
44 * 19 9/08/99 12:03a Dave
45 * Make squad logos render properly in D3D all the time. Added intel anim
48 * 18 9/06/99 2:35p Dave
49 * Rename briefing and debriefing voice direcrory paths properly.
51 * 17 9/03/99 1:31a Dave
52 * CD checking by act. Added support to play 2 cutscenes in a row
53 * seamlessly. Fixed super low level cfile bug related to files in the
54 * root directory of a CD. Added cheat code to set campaign mission # in
57 * 16 8/31/99 9:46a Dave
58 * Support for new cfile cbanims directory.
60 * 15 8/06/99 11:20a Johns
61 * Don't call game_cd_changed() in a demo or multiplayer beta build.
63 * 14 6/08/99 2:33p Dave
64 * Fixed release build warning. Put in hud config stuff.
66 * 13 5/19/99 4:07p Dave
67 * Moved versioning code into a nice isolated common place. Fixed up
68 * updating code on the pxo screen. Fixed several stub problems.
70 * 12 4/30/99 12:18p Dave
71 * Several minor bug fixes.
73 * 11 4/07/99 5:54p Dave
74 * Fixes for encryption in updatelauncher.
76 * 10 3/28/99 5:58p Dave
77 * Added early demo code. Make objects move. Nice and framerate
78 * independant, but not much else. Don't use yet unless you're me :)
80 * 9 2/22/99 10:31p Andsager
81 * Get rid of unneeded includes.
83 * 8 1/12/99 3:15a Dave
84 * Barracks screen support for selecting squad logos. We need real artwork
87 * 7 11/30/98 1:07p Dave
88 * 16 bit conversion, first run.
90 * 6 10/29/98 10:41a Dave
91 * Change the way cfile initializes exe directory.
93 * 5 10/13/98 9:19a Andsager
94 * Add localization support to cfile. Optional parameter with cfopen that
95 * looks for localized files.
97 * 4 10/12/98 9:54a Dave
98 * Fixed a few file organization things.
100 * 3 10/07/98 6:27p Dave
101 * Globalized mission and campaign file extensions. Removed Silent Threat
102 * special code. Moved \cache \players and \multidata into the \data
105 * 2 10/07/98 10:52a Dave
108 * 1 10/07/98 10:48a Dave
110 * 110 9/17/98 10:31a Hoffoss
111 * Changed code to use location of executable as root rather than relying
112 * on the cwd being set correctly. This is most helpful in the case of
113 * Fred launching due to the user double-clicking on an .fsm file in
114 * explorer or something (where the cwd is probably the location of the
117 * 109 9/11/98 4:14p Dave
118 * Fixed file checksumming of < file_size. Put in more verbose kicking and
119 * PXO stats store reporting.
121 * 108 9/09/98 5:53p Dave
122 * Put in new tracker packets in API. Change cfile to be able to checksum
123 * portions of a file.
125 * 107 9/04/98 3:51p Dave
126 * Put in validated mission updating and application during stats
129 * 106 8/31/98 2:06p Dave
130 * Make cfile sort the ordering or vp files. Added support/checks for
131 * recognizing "mission disk" players.
133 * 105 8/20/98 5:30p Dave
134 * Put in handy multiplayer logfile system. Now need to put in useful
135 * applications of it all over the code.
137 * 104 8/12/98 4:53p Dave
138 * Put in 32 bit checksumming for PXO missions. No validation on the
139 * actual tracker yet, though.
141 * 103 6/17/98 9:30a Allender
142 * fixed red alert replay stats clearing problem
144 * 102 6/05/98 9:46a Lawrance
145 * check for CD change on cfopen()
147 * 101 5/19/98 1:19p Allender
148 * new low level reliable socket reading code. Make all missions/campaign
149 * load/save to data missions folder (i.e. we are rid of the player
152 * 100 5/13/98 10:22p John
153 * Added cfile functions to read/write rle compressed blocks of data.
154 * Made palman use it for .clr files. Made alphacolors calculate on the
155 * fly rather than caching to/from disk.
157 * 99 5/11/98 10:59a John
158 * Moved the low-level file reading code into cfilearchive.cpp.
160 * 98 5/06/98 5:30p John
161 * Removed unused cfilearchiver. Removed/replaced some unused/little used
162 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
163 * DirectX header files and libs that fixed the Direct3D alpha blending
166 * 97 5/03/98 11:53a John
167 * Fixed filename case mangling.
169 * 96 5/03/98 8:33a John
170 * Made sure there weren't any more broken function lurking around like
171 * the one Allender fixed.
173 * 95 5/02/98 11:05p Allender
174 * fix cfilelength for pack files
179 #define _CFILE_INTERNAL
189 #include <winbase.h> /* needed for memory mapping of file functions */
192 #include <sys/stat.h>
193 #include <sys/types.h>
199 //#include "outwnd.h"
200 //#include "vecmat.h"
202 #include "cfilesystem.h"
203 #include "cfilearchive.h"
206 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
208 // During cfile_init, verify that Pathtypes[n].index == n for each item
209 // Each path must have a valid parent that can be tracable all the way back to the root
210 // so that we can create directories when we need to.
212 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
213 // What type this is Path Extensions Parent type
214 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
215 // Root must be index 1!!
216 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
217 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
219 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
220 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
221 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
222 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
223 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
224 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
225 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
226 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
227 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
228 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
229 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
230 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
231 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
232 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
233 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
234 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
235 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
236 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
237 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
238 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
239 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
240 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
241 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
242 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
243 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
244 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
245 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
246 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
247 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
248 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
249 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
250 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
251 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
253 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
254 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
255 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
256 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
257 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
258 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
259 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
260 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
261 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
262 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
263 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
264 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
265 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
266 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
267 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
268 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
269 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
270 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
271 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
272 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
273 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
274 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
275 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
276 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
277 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
278 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
279 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
280 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
281 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
282 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
283 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
284 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
285 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
290 #define CFILE_STACK_MAX 8
292 int cfile_inited = 0;
293 int Cfile_stack_pos = 0;
295 char Cfile_stack[128][CFILE_STACK_MAX];
297 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
298 CFILE Cfile_list[MAX_CFILE_BLOCKS];
300 char *Cfile_cdrom_dir = NULL;
303 // Function prototypes for internally-called functions
305 int cfget_cfile_block();
306 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
307 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
308 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
309 void cf_chksum_long_init();
313 cf_free_secondary_filelist();
316 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
317 int cfile_in_root_dir(char *exe_path)
320 char path_copy[2048] = "";
324 if(exe_path == NULL){
329 memset(path_copy, 0, 2048);
330 strncpy(path_copy, exe_path, 2047);
332 // count how many slashes there are in the path
334 tok = strtok(path_copy, "/");
336 tok = strtok(path_copy, "\\");
344 tok = strtok(NULL, "/");
346 tok = strtok(NULL, "\\");
348 } while(tok != NULL);
350 // root directory if we have <= 1 slash
351 if(token_count <= 2){
355 // not-root directory
359 // cfile_init() initializes the cfile system. Called once at application start.
361 // returns: success ==> 0
362 // error ==> non-zero
364 int cfile_init(char *exe_dir, char *cdrom_dir)
368 // initialize encryption
371 if ( !cfile_inited ) {
376 strcpy(buf, exe_dir);
379 // are we in a root directory?
380 if(cfile_in_root_dir(buf)){
382 fprintf (stderr, "ERROR: Freespace2/Fred2 cannot be run from a drive root directory!\n");
384 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
404 fprintf (stderr, "Error trying to determine executable root directory!");
406 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
411 // set root directory
412 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
414 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
415 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
418 Cfile_cdrom_dir = cdrom_dir;
419 cf_build_secondary_filelist(Cfile_cdrom_dir);
421 // 32 bit CRC table init
422 cf_chksum_long_init();
424 atexit( cfile_close );
430 // Call this if pack files got added or removed or the
431 // cdrom changed. This will refresh the list of filenames
432 // stored in packfiles and on the cdrom.
435 cf_build_secondary_filelist(Cfile_cdrom_dir);
439 // Changes to a drive if valid.. 1=A, 2=B, etc
440 // If flag, then changes to it.
441 // Returns 0 if not-valid, 1 if valid.
442 int cfile_chdrive( int DriveNum, int flag )
455 _chdrive( DriveNum );
462 if ( (!flag) && (n != org) )
468 // push current directory on a 'stack' (so we can restore it) and change the directory
469 int cfile_push_chdir(int type)
473 char OriginalDirectory[128];
475 char NoDir[] = "\\.";
477 _getcwd(OriginalDirectory, 127);
478 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
479 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
481 cf_create_default_path_string( dir, type, NULL );
484 char *Drive = strchr(dir, ':');
487 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
502 // This chdir might get a critical error!
505 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
513 int cfile_chdir(char *dir)
516 char OriginalDirectory[128];
518 char NoDir[] = "\\.";
520 _getcwd(OriginalDirectory, 127);
524 char *Drive = strchr(dir, ':');
526 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
541 // This chdir might get a critical error!
544 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
553 Assert(Cfile_stack_pos);
555 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
558 // flush (delete all files in) the passed directory (by type), return the # of files deleted
559 // NOTE : WILL NOT DELETE READ-ONLY FILES
560 int cfile_flush_dir(int dir_type)
570 Assert( CF_TYPE_SPECIFIED(dir_type) );
572 // attempt to change the directory to the passed type
573 if(cfile_push_chdir(dir_type)){
577 // proceed to delete the files
578 find_handle = _findfirst( "*", &find );
580 if (find_handle != -1) {
582 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
584 cf_delete(find.name,dir_type);
586 // increment the deleted count
589 } while (!_findnext(find_handle, &find));
590 _findclose( find_handle );
593 // pop the directory back
596 // return the # of files deleted
602 // add the given extention to a filename (or filepath) if it doesn't already have this
604 // filename = name of filename or filepath to process
605 // ext = extension to add. Must start with the period
606 // Returns: new filename or filepath with extension.
607 char *cf_add_ext(char *filename, char *ext)
610 static char path[MAX_PATH_LEN];
612 flen = strlen(filename);
614 Assert(flen < MAX_PATH_LEN);
615 strcpy(path, filename);
616 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
617 Assert(flen + elen < MAX_PATH_LEN);
625 void cf_delete( char *filename, int dir_type )
627 char longname[MAX_PATH_LEN];
629 Assert( CF_TYPE_SPECIFIED(dir_type) );
631 cf_create_default_path_string( longname, dir_type, filename );
633 FILE *fp = fopen(longname, "rb");
643 // Same as _access function to read a file's access bits
644 int cf_access( char *filename, int dir_type, int mode )
646 char longname[MAX_PATH_LEN];
648 Assert( CF_TYPE_SPECIFIED(dir_type) );
650 cf_create_default_path_string( longname, dir_type, filename );
652 return access(longname,mode);
656 // Returns 1 if file exists, 0 if not.
657 int cf_exist( char *filename, int dir_type )
659 char longname[MAX_PATH_LEN];
661 Assert( CF_TYPE_SPECIFIED(dir_type) );
663 cf_create_default_path_string( longname, dir_type, filename );
665 FILE *fp = fopen(longname, "rb");
674 void cf_attrib(char *filename, int set, int clear, int dir_type)
676 char longname[MAX_PATH_LEN];
678 Assert( CF_TYPE_SPECIFIED(dir_type) );
680 cf_create_default_path_string( longname, dir_type, filename );
682 FILE *fp = fopen(longname, "rb");
689 DWORD z = GetFileAttributes(longname);
690 SetFileAttributes(longname, z | set & ~clear);
696 int cf_rename(char *old_name, char *name, int dir_type)
698 Assert( CF_TYPE_SPECIFIED(dir_type) );
701 char old_longname[_MAX_PATH];
702 char new_longname[_MAX_PATH];
704 cf_create_default_path_string( old_longname, dir_type, old_name );
705 cf_create_default_path_string( new_longname, dir_type, name );
707 ret_code = rename(old_longname, new_longname );
711 return CF_RENAME_FAIL_ACCESS;
714 return CF_RENAME_FAIL_EXIST;
718 return CF_RENAME_SUCCESS;
723 // Creates the directory path if it doesn't exist. Even creates all its
725 void cf_create_directory( int dir_type )
728 int dir_tree[CF_MAX_PATH_TYPES];
729 char longname[MAX_PATH_LEN];
731 Assert( CF_TYPE_SPECIFIED(dir_type) );
733 int current_dir = dir_type;
736 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
738 dir_tree[num_dirs++] = current_dir;
739 current_dir = Pathtypes[current_dir].parent_index;
741 } while( current_dir != CF_TYPE_ROOT );
746 for (i=num_dirs-1; i>=0; i-- ) {
747 cf_create_default_path_string( longname, dir_tree[i], NULL );
750 if ( _mkdir(longname, 0777)==0 ) {
751 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
754 if ( _mkdir(longname)==0 ) {
755 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
764 extern int game_cd_changed();
768 // parameters: *filepath ==> name of file to open (may be path+name)
769 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
770 // passing NULL to mode deletes the file if it exists and returns NULL
771 // type ==> one of: CFILE_NORMAL
772 // CFILE_MEMORY_MAPPED
773 // dir_type => override extension check, value is one of CF_TYPE* #defines
775 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
778 // returns: success ==> address of CFILE structure
782 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
784 char longname[_MAX_PATH];
786 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
787 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
789 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
791 if ( game_cd_changed() ) {
796 //================================================
797 // Check that all the parameters make sense
798 Assert(file_path && strlen(file_path));
799 Assert( mode != NULL );
801 // Can only open read-only binary files in memory mapped mode.
802 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
807 //===========================================================
808 // If in write mode, just try to open the file straight off
809 // the harddisk. No fancy packfile stuff here!
811 if ( strchr(mode,'w') ) {
812 // For write-only files, require a full path or a path type
813 if ( strpbrk(file_path,"/\\:") ) {
815 strcpy(longname, file_path );
818 Assert( dir_type != CF_TYPE_ANY );
820 // Create the directory if necessary
821 cf_create_directory( dir_type );
823 cf_create_default_path_string( longname, dir_type, file_path );
825 Assert( !(type & CFILE_MEMORY_MAPPED) );
827 // JOHN: TODO, you should create the path if it doesn't exist.
829 FILE *fp = fopen(longname, mode);
831 return cf_open_fill_cfblock(fp, dir_type);
837 //================================================
838 // Search for file on disk, on cdrom, or in a packfile
841 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
842 strcpy(copy_file_path, file_path);
845 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
847 // Fount it, now create a cfile out of it
849 if ( type & CFILE_MEMORY_MAPPED ) {
851 // Can't open memory mapped files out of pack files
858 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
860 if (hFile != INVALID_HANDLE_VALUE) {
861 return cf_open_mapped_fill_cfblock(hFile, dir_type);
868 FILE *fp = fopen( longname, "rb" );
872 // Found it in a pack file
873 return cf_open_packed_cfblock(fp, dir_type, offset, size );
875 // Found it in a normal file
876 return cf_open_fill_cfblock(fp, dir_type);
887 // ------------------------------------------------------------------------
890 // Open up a temporary file. A unique name is automatically generated. The
891 // file will be automatically deleted when file is closed.
893 // return: NULL => tmp file could not be opened
894 // pointer to CFILE => tmp file successfully opened
901 return cf_open_fill_cfblock(fp, 0);
908 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
909 // Cfile_block_list[] array and return the index.
911 // returns: success ==> index in Cfile_block_list[] array
914 int cfget_cfile_block()
919 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
920 cb = &Cfile_block_list[i];
921 if ( cb->type == CFILE_BLOCK_UNUSED ) {
924 cb->type = CFILE_BLOCK_USED;
929 // If we've reached this point, a free Cfile_block could not be found
930 nprintf(("Warning","A free Cfile_block could not be found.\n"));
931 Assert(0); // out of free cfile blocks
936 // cfclose() closes the file
938 // returns: success ==> 0
941 int cfclose( CFILE * cfile )
945 Assert(cfile != NULL);
947 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
948 cb = &Cfile_block_list[cfile->id];
952 // close memory mapped file
956 result = UnmapViewOfFile((void*)cb->data);
958 result = CloseHandle(cb->hInFile);
959 Assert(result); // Ensure file handle is closed properly
960 result = CloseHandle(cb->hMapFile);
961 Assert(result); // Ensure file handle is closed properly
965 } else if ( cb->fp != NULL ) {
966 Assert(cb->fp != NULL);
967 result = fclose(cb->fp);
972 cb->type = CFILE_BLOCK_UNUSED;
979 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
980 // for the case of a file being opened by cf_open();
982 // returns: success ==> ptr to CFILE structure.
985 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
987 int cfile_block_index;
989 cfile_block_index = cfget_cfile_block();
990 if ( cfile_block_index == -1 ) {
995 cfbp = &Cfile_block_list[cfile_block_index];
996 cfp = &Cfile_list[cfile_block_index];;
997 cfp->id = cfile_block_index;
1001 cfbp->dir_type = type;
1003 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1010 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1011 // for the case of a file being opened by cf_open();
1013 // returns: success ==> ptr to CFILE structure.
1016 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1018 // Found it in a pack file
1019 int cfile_block_index;
1021 cfile_block_index = cfget_cfile_block();
1022 if ( cfile_block_index == -1 ) {
1027 cfbp = &Cfile_block_list[cfile_block_index];
1029 cfp = &Cfile_list[cfile_block_index];
1030 cfp->id = cfile_block_index;
1034 cfbp->dir_type = type;
1036 cf_init_lowlevel_read_code(cfp,offset, size );
1045 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1046 // for the case of a file being opened by cf_open_mapped();
1048 // returns: ptr CFILE structure.
1050 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1052 int cfile_block_index;
1054 cfile_block_index = cfget_cfile_block();
1055 if ( cfile_block_index == -1 ) {
1061 cfbp = &Cfile_block_list[cfile_block_index];
1063 cfp = &Cfile_list[cfile_block_index];
1064 cfp->id = cfile_block_index;
1066 cfbp->hInFile = hFile;
1067 cfbp->dir_type = type;
1069 cf_init_lowlevel_read_code(cfp,0 , 0 );
1074 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1075 if (cfbp->hMapFile == NULL) {
1076 nprintf(("Error", "Could not create file-mapping object.\n"));
1080 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1081 Assert( cfbp->data != NULL );
1087 int cf_get_dir_type(CFILE *cfile)
1089 return Cfile_block_list[cfile->id].dir_type;
1092 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1093 // with the CFILE structure passed as a parameter
1097 void *cf_returndata(CFILE *cfile)
1099 Assert(cfile != NULL);
1101 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1102 cb = &Cfile_block_list[cfile->id];
1103 Assert(cb->data != NULL);
1109 // version number of opened file. Will be 0 unless you put something else here after you
1110 // open a file. Once set, you can use minimum version numbers with the read functions.
1111 void cf_set_version( CFILE * cfile, int version )
1113 Assert(cfile != NULL);
1115 cfile->version = version;
1118 // routines to read basic data types from CFILE's. Put here to
1119 // simplify mac/pc reading from cfiles.
1121 float cfread_float(CFILE *file, int ver, float deflt)
1125 if (file->version < ver)
1128 if (cfread( &f, sizeof(f), 1, file) != 1)
1131 // i = INTEL_INT(i); // hmm, not sure what to do here
1135 int cfread_int(CFILE *file, int ver, int deflt)
1139 if (file->version < ver)
1142 if (cfread( &i, sizeof(i), 1, file) != 1)
1149 uint cfread_uint(CFILE *file, int ver, uint deflt)
1153 if (file->version < ver)
1156 if (cfread( &i, sizeof(i), 1, file) != 1)
1163 short cfread_short(CFILE *file, int ver, short deflt)
1167 if (file->version < ver)
1170 if (cfread( &s, sizeof(s), 1, file) != 1)
1177 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1181 if (file->version < ver)
1184 if (cfread( &s, sizeof(s), 1, file) != 1)
1191 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1195 if (file->version < ver)
1198 if (cfread( &b, sizeof(b), 1, file) != 1)
1204 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1206 if (file->version < ver) {
1210 vec->x = vec->y = vec->z = 0.0f;
1215 vec->x = cfread_float(file, ver, deflt ? deflt->x : 0.0f);
1216 vec->y = cfread_float(file, ver, deflt ? deflt->y : 0.0f);
1217 vec->z = cfread_float(file, ver, deflt ? deflt->z : 0.0f);
1220 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1222 if (file->version < ver) {
1226 ang->p = ang->b = ang->h = 0.0f;
1231 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1232 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1233 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1236 char cfread_char(CFILE *file, int ver, char deflt)
1240 if (file->version < ver)
1243 if (cfread( &b, sizeof(b), 1, file) != 1)
1249 void cfread_string(char *buf, int n, CFILE *file)
1254 c = cfread_char(file);
1262 void cfread_string_len(char *buf,int n, CFILE *file)
1265 len = cfread_int(file);
1268 cfread(buf, len, 1, file);
1273 // equivalent write functions of above read functions follow
1275 int cfwrite_float(float f, CFILE *file)
1277 // i = INTEL_INT(i); // hmm, not sure what to do here
1278 return cfwrite(&f, sizeof(f), 1, file);
1281 int cfwrite_int(int i, CFILE *file)
1284 return cfwrite(&i, sizeof(i), 1, file);
1287 int cfwrite_uint(uint i, CFILE *file)
1290 return cfwrite(&i, sizeof(i), 1, file);
1293 int cfwrite_short(short s, CFILE *file)
1296 return cfwrite(&s, sizeof(s), 1, file);
1299 int cfwrite_ushort(ushort s, CFILE *file)
1302 return cfwrite(&s, sizeof(s), 1, file);
1305 int cfwrite_ubyte(ubyte b, CFILE *file)
1307 return cfwrite(&b, sizeof(b), 1, file);
1310 int cfwrite_vector(vector *vec, CFILE *file)
1312 if(!cfwrite_float(vec->x, file)){
1315 if(!cfwrite_float(vec->y, file)){
1318 return cfwrite_float(vec->z, file);
1321 int cfwrite_angles(angles *ang, CFILE *file)
1323 if(!cfwrite_float(ang->p, file)){
1326 if(!cfwrite_float(ang->b, file)){
1329 return cfwrite_float(ang->h, file);
1332 int cfwrite_char(char b, CFILE *file)
1334 return cfwrite( &b, sizeof(b), 1, file);
1337 int cfwrite_string(char *buf, CFILE *file)
1339 if ( (!buf) || (buf && !buf[0]) ) {
1340 return cfwrite_char(0, file);
1342 int len = strlen(buf);
1343 if(!cfwrite(buf, len, 1, file)){
1346 return cfwrite_char(0, file); // write out NULL termination
1349 int cfwrite_string_len(char *buf, CFILE *file)
1351 int len = strlen(buf);
1353 if(!cfwrite_int(len, file)){
1357 return cfwrite(buf,len,1,file);
1363 // Get the filelength
1364 int cfilelength( CFILE * cfile )
1366 Assert(cfile != NULL);
1368 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1369 cb = &Cfile_block_list[cfile->id];
1371 // TODO: return length of memory mapped file
1372 Assert( !cb->data );
1374 Assert(cb->fp != NULL);
1376 // cb->size gets set at cfopen
1380 // cfwrite() writes to the file
1382 // returns: number of full elements actually written
1385 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1387 Assert(cfile != NULL);
1388 Assert(buf != NULL);
1393 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1394 cb = &Cfile_block_list[cfile->id];
1398 // cfwrite() not supported for memory-mapped files
1399 Assert( !cb->data );
1401 Assert(cb->fp != NULL);
1402 Assert(cb->lib_offset == 0 );
1403 result = fwrite(buf, elsize, nelem, cb->fp);
1409 // cfputc() writes a character to a file
1411 // returns: success ==> returns character written
1414 int cfputc(int c, CFILE *cfile)
1418 Assert(cfile != NULL);
1420 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1421 cb = &Cfile_block_list[cfile->id];
1424 // cfputc() not supported for memory-mapped files
1425 Assert( !cb->data );
1427 Assert(cb->fp != NULL);
1428 result = fputc(c, cb->fp);
1434 // cfgetc() reads a character from a file
1436 // returns: success ==> returns character read
1439 int cfgetc(CFILE *cfile)
1441 Assert(cfile != NULL);
1445 int result = cfread(&tmp, 1, 1, cfile );
1446 if ( result == 1 ) {
1459 // cfgets() reads a string from a file
1461 // returns: success ==> returns pointer to string
1464 char *cfgets(char *buf, int n, CFILE *cfile)
1466 Assert(cfile != NULL);
1467 Assert(buf != NULL);
1473 for (i=0; i<n-1; i++ ) {
1477 int ret = cfread( &tmp_c, 1, 1, cfile );
1487 } while ( c == 13 );
1489 if ( c=='\n' ) break;
1496 // cfputs() writes a string to a file
1498 // returns: success ==> non-negative value
1501 int cfputs(char *str, CFILE *cfile)
1503 Assert(cfile != NULL);
1504 Assert(str != NULL);
1507 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1508 cb = &Cfile_block_list[cfile->id];
1513 // cfputs() not supported for memory-mapped files
1514 Assert( !cb->data );
1515 Assert(cb->fp != NULL);
1516 result = fputs(str, cb->fp);
1522 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1524 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1525 // checksumming code that he wrote a while ago.
1526 #define CRC32_POLYNOMIAL 0xEDB88320L
1527 unsigned long CRCTable[256];
1529 #define CF_CHKSUM_SAMPLE_SIZE 512
1531 // update cur_chksum with the chksum of the new_data of size new_data_size
1532 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1534 ubyte * ptr = (ubyte *)buffer;
1535 unsigned int sum1,sum2;
1537 sum1 = sum2 = (int)(seed);
1541 if (sum1 >= 255 ) sum1 -= 255;
1546 return (unsigned short)((sum1<<8)+ sum2);
1549 // update cur_chksum with the chksum of the new_data of size new_data_size
1550 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1554 unsigned long temp1;
1555 unsigned long temp2;
1557 p = (unsigned char*)buffer;
1561 temp1 = (crc>>8)&0x00FFFFFFL;
1562 temp2 = CRCTable[((int)crc^*p++)&0xff];
1569 void cf_chksum_long_init()
1574 for( i=0;i<=255;i++) {
1578 crc=(crc>>1)^CRC32_POLYNOMIAL;
1586 // single function convenient to use for both short and long checksums
1587 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1588 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1590 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1596 // determine whether we're doing a short or long checksum
1607 // if max_size is -1, set it to be the size of the file
1609 cfseek(cfile, 0, SEEK_SET);
1610 max_size = cfilelength(cfile);
1615 // determine how much we want to read
1616 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1617 read_size = CF_CHKSUM_SAMPLE_SIZE;
1619 read_size = max_size - cf_total;
1622 // read in some buffer
1623 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1625 // total we've read so far
1630 // do the proper short or long checksum
1632 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1634 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1637 } while((cf_len > 0) && (cf_total < max_size));
1642 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1643 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1646 CFILE *cfile = NULL;
1648 // zero the checksum
1651 // attempt to open the file
1652 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1657 // call the overloaded cf_chksum function()
1658 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1660 // close the file down
1664 // return the result
1668 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1669 // NOTE : preserves current file position
1670 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1675 // Returns current position of file.
1676 start_pos = cftell(file);
1677 if(start_pos == -1){
1681 // move to the beginning of the file
1682 if(cfseek(file, 0, CF_SEEK_SET)){
1685 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1686 // move back to the start position
1687 cfseek(file, start_pos, CF_SEEK_SET);
1692 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1693 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1696 CFILE *cfile = NULL;
1698 // zero the checksum
1701 // attempt to open the file
1702 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1707 // call the overloaded cf_chksum function()
1708 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1710 // close the file down
1714 // return the result
1718 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1719 // NOTE : preserves current file position
1720 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1725 // Returns current position of file.
1726 start_pos = cftell(file);
1727 if(start_pos == -1){
1731 // move to the beginning of the file
1732 if(cfseek(file, 0, CF_SEEK_SET)){
1735 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1736 // move back to the start position
1737 cfseek(file, start_pos, CF_SEEK_SET);
1743 // Flush the open file buffer
1745 // exit: 0 - success
1747 int cflush(CFILE *cfile)
1749 Assert(cfile != NULL);
1751 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1752 cb = &Cfile_block_list[cfile->id];
1754 // not supported for memory mapped files
1755 Assert( !cb->data );
1757 Assert(cb->fp != NULL);
1758 return fflush(cb->fp);