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.8 2003/02/20 17:41:07 theoddone33
19 * Userdir patch from Taylor Richards
21 * Revision 1.7 2002/12/30 03:23:29 relnev
22 * disable root dir check
24 * Revision 1.6 2002/06/17 06:33:08 relnev
25 * ryan's struct patch for gcc 2.95
27 * Revision 1.5 2002/06/09 04:41:15 relnev
28 * added copyright header
30 * Revision 1.4 2002/06/05 08:05:28 relnev
31 * stub/warning removal.
33 * reworked the sound code.
35 * Revision 1.3 2002/05/28 08:52:03 relnev
36 * implemented two assembly stubs.
38 * cleaned up a few warnings.
40 * added a little demo hackery to make it progress a little farther.
42 * Revision 1.2 2002/05/28 06:28:20 theoddone33
43 * Filesystem mods, actually reads some data files now
45 * Revision 1.1.1.1 2002/05/03 03:28:08 root
49 * 20 9/08/99 10:01p Dave
50 * Make sure game won't run in a drive's root directory. Make sure
51 * standalone routes suqad war messages properly to the host.
53 * 19 9/08/99 12:03a Dave
54 * Make squad logos render properly in D3D all the time. Added intel anim
57 * 18 9/06/99 2:35p Dave
58 * Rename briefing and debriefing voice direcrory paths properly.
60 * 17 9/03/99 1:31a Dave
61 * CD checking by act. Added support to play 2 cutscenes in a row
62 * seamlessly. Fixed super low level cfile bug related to files in the
63 * root directory of a CD. Added cheat code to set campaign mission # in
66 * 16 8/31/99 9:46a Dave
67 * Support for new cfile cbanims directory.
69 * 15 8/06/99 11:20a Johns
70 * Don't call game_cd_changed() in a demo or multiplayer beta build.
72 * 14 6/08/99 2:33p Dave
73 * Fixed release build warning. Put in hud config stuff.
75 * 13 5/19/99 4:07p Dave
76 * Moved versioning code into a nice isolated common place. Fixed up
77 * updating code on the pxo screen. Fixed several stub problems.
79 * 12 4/30/99 12:18p Dave
80 * Several minor bug fixes.
82 * 11 4/07/99 5:54p Dave
83 * Fixes for encryption in updatelauncher.
85 * 10 3/28/99 5:58p Dave
86 * Added early demo code. Make objects move. Nice and framerate
87 * independant, but not much else. Don't use yet unless you're me :)
89 * 9 2/22/99 10:31p Andsager
90 * Get rid of unneeded includes.
92 * 8 1/12/99 3:15a Dave
93 * Barracks screen support for selecting squad logos. We need real artwork
96 * 7 11/30/98 1:07p Dave
97 * 16 bit conversion, first run.
99 * 6 10/29/98 10:41a Dave
100 * Change the way cfile initializes exe directory.
102 * 5 10/13/98 9:19a Andsager
103 * Add localization support to cfile. Optional parameter with cfopen that
104 * looks for localized files.
106 * 4 10/12/98 9:54a Dave
107 * Fixed a few file organization things.
109 * 3 10/07/98 6:27p Dave
110 * Globalized mission and campaign file extensions. Removed Silent Threat
111 * special code. Moved \cache \players and \multidata into the \data
114 * 2 10/07/98 10:52a Dave
117 * 1 10/07/98 10:48a Dave
119 * 110 9/17/98 10:31a Hoffoss
120 * Changed code to use location of executable as root rather than relying
121 * on the cwd being set correctly. This is most helpful in the case of
122 * Fred launching due to the user double-clicking on an .fsm file in
123 * explorer or something (where the cwd is probably the location of the
126 * 109 9/11/98 4:14p Dave
127 * Fixed file checksumming of < file_size. Put in more verbose kicking and
128 * PXO stats store reporting.
130 * 108 9/09/98 5:53p Dave
131 * Put in new tracker packets in API. Change cfile to be able to checksum
132 * portions of a file.
134 * 107 9/04/98 3:51p Dave
135 * Put in validated mission updating and application during stats
138 * 106 8/31/98 2:06p Dave
139 * Make cfile sort the ordering or vp files. Added support/checks for
140 * recognizing "mission disk" players.
142 * 105 8/20/98 5:30p Dave
143 * Put in handy multiplayer logfile system. Now need to put in useful
144 * applications of it all over the code.
146 * 104 8/12/98 4:53p Dave
147 * Put in 32 bit checksumming for PXO missions. No validation on the
148 * actual tracker yet, though.
150 * 103 6/17/98 9:30a Allender
151 * fixed red alert replay stats clearing problem
153 * 102 6/05/98 9:46a Lawrance
154 * check for CD change on cfopen()
156 * 101 5/19/98 1:19p Allender
157 * new low level reliable socket reading code. Make all missions/campaign
158 * load/save to data missions folder (i.e. we are rid of the player
161 * 100 5/13/98 10:22p John
162 * Added cfile functions to read/write rle compressed blocks of data.
163 * Made palman use it for .clr files. Made alphacolors calculate on the
164 * fly rather than caching to/from disk.
166 * 99 5/11/98 10:59a John
167 * Moved the low-level file reading code into cfilearchive.cpp.
169 * 98 5/06/98 5:30p John
170 * Removed unused cfilearchiver. Removed/replaced some unused/little used
171 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
172 * DirectX header files and libs that fixed the Direct3D alpha blending
175 * 97 5/03/98 11:53a John
176 * Fixed filename case mangling.
178 * 96 5/03/98 8:33a John
179 * Made sure there weren't any more broken function lurking around like
180 * the one Allender fixed.
182 * 95 5/02/98 11:05p Allender
183 * fix cfilelength for pack files
188 #define _CFILE_INTERNAL
198 #include <winbase.h> /* needed for memory mapping of file functions */
201 #include <sys/stat.h>
202 #include <sys/types.h>
208 //#include "outwnd.h"
209 //#include "vecmat.h"
211 #include "cfilesystem.h"
212 #include "cfilearchive.h"
214 #include "osregistry.h" // for Osreg_user_dir
217 char Cfile_user_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
219 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
221 // During cfile_init, verify that Pathtypes[n].index == n for each item
222 // Each path must have a valid parent that can be tracable all the way back to the root
223 // so that we can create directories when we need to.
225 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
226 // What type this is Path Extensions Parent type
227 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
228 // Root must be index 1!!
229 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
230 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
232 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
233 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
234 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
235 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
236 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
237 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
238 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
239 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
240 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
241 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
242 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
243 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
244 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
245 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
246 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
247 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
248 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
249 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
250 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
251 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
252 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
253 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
254 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
255 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
256 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
257 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
258 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
259 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
260 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
261 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
262 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
263 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
264 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
266 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
267 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
268 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
269 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
270 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
271 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
272 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
273 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
274 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
275 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
276 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
277 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
278 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
279 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
280 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
281 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
282 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
283 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
284 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
285 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
286 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
287 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
288 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
289 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
290 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
291 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
292 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
293 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
294 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
295 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
296 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
297 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
298 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
303 #define CFILE_STACK_MAX 8
305 int cfile_inited = 0;
306 int Cfile_stack_pos = 0;
308 char Cfile_stack[128][CFILE_STACK_MAX];
310 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
311 CFILE Cfile_list[MAX_CFILE_BLOCKS];
313 char *Cfile_cdrom_dir = NULL;
316 // Function prototypes for internally-called functions
318 int cfget_cfile_block();
319 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
320 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
321 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
322 void cf_chksum_long_init();
326 cf_free_secondary_filelist();
329 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
330 int cfile_in_root_dir(char *exe_path)
333 char path_copy[2048] = "";
337 if(exe_path == NULL){
342 memset(path_copy, 0, 2048);
343 strncpy(path_copy, exe_path, 2047);
345 // count how many slashes there are in the path
347 tok = strtok(path_copy, "/");
349 tok = strtok(path_copy, "\\");
357 tok = strtok(NULL, "/");
359 tok = strtok(NULL, "\\");
361 } while(tok != NULL);
363 // root directory if we have <= 1 slash
364 if(token_count <= 2){
368 // not-root directory
372 // cfile_init() initializes the cfile system. Called once at application start.
374 // returns: success ==> 0
375 // error ==> non-zero
377 int cfile_init(char *exe_dir, char *cdrom_dir)
381 // initialize encryption
384 if ( !cfile_inited ) {
389 strcpy(buf, exe_dir);
393 // are we in a root directory?
394 if(cfile_in_root_dir(buf)){
395 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
415 fprintf (stderr, "Error trying to determine executable root directory!");
417 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
422 // set root directory
423 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
426 snprintf(Cfile_user_dir, MAX_PATH, "%s/%s/", detect_home(), Osreg_user_dir);
428 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
429 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
432 Cfile_cdrom_dir = cdrom_dir;
433 cf_build_secondary_filelist(Cfile_cdrom_dir);
435 // 32 bit CRC table init
436 cf_chksum_long_init();
438 atexit( cfile_close );
444 // Call this if pack files got added or removed or the
445 // cdrom changed. This will refresh the list of filenames
446 // stored in packfiles and on the cdrom.
449 cf_build_secondary_filelist(Cfile_cdrom_dir);
453 // Changes to a drive if valid.. 1=A, 2=B, etc
454 // If flag, then changes to it.
455 // Returns 0 if not-valid, 1 if valid.
456 int cfile_chdrive( int DriveNum, int flag )
469 _chdrive( DriveNum );
476 if ( (!flag) && (n != org) )
482 // push current directory on a 'stack' (so we can restore it) and change the directory
483 int cfile_push_chdir(int type)
487 char OriginalDirectory[128];
489 char NoDir[] = "\\.";
491 _getcwd(OriginalDirectory, 127);
492 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
493 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
495 cf_create_default_path_string( dir, type, NULL );
498 char *Drive = strchr(dir, ':');
501 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
516 // This chdir might get a critical error!
519 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
527 int cfile_chdir(char *dir)
530 char OriginalDirectory[128];
532 char NoDir[] = "\\.";
534 _getcwd(OriginalDirectory, 127);
538 char *Drive = strchr(dir, ':');
540 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
555 // This chdir might get a critical error!
558 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
567 Assert(Cfile_stack_pos);
569 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
572 // flush (delete all files in) the passed directory (by type), return the # of files deleted
573 // NOTE : WILL NOT DELETE READ-ONLY FILES
574 int cfile_flush_dir(int dir_type)
584 Assert( CF_TYPE_SPECIFIED(dir_type) );
586 // attempt to change the directory to the passed type
587 if(cfile_push_chdir(dir_type)){
591 // proceed to delete the files
592 find_handle = _findfirst( "*", &find );
594 if (find_handle != -1) {
596 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
598 cf_delete(find.name,dir_type);
600 // increment the deleted count
603 } while (!_findnext(find_handle, &find));
604 _findclose( find_handle );
607 // pop the directory back
610 // return the # of files deleted
616 // add the given extention to a filename (or filepath) if it doesn't already have this
618 // filename = name of filename or filepath to process
619 // ext = extension to add. Must start with the period
620 // Returns: new filename or filepath with extension.
621 char *cf_add_ext(char *filename, char *ext)
624 static char path[MAX_PATH_LEN];
626 flen = strlen(filename);
628 Assert(flen < MAX_PATH_LEN);
629 strcpy(path, filename);
630 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
631 Assert(flen + elen < MAX_PATH_LEN);
639 void cf_delete( char *filename, int dir_type )
641 char longname[MAX_PATH_LEN];
643 Assert( CF_TYPE_SPECIFIED(dir_type) );
645 cf_create_default_path_string( longname, dir_type, filename );
647 FILE *fp = fopen(longname, "rb");
657 // Same as _access function to read a file's access bits
658 int cf_access( char *filename, int dir_type, int mode )
660 char longname[MAX_PATH_LEN];
662 Assert( CF_TYPE_SPECIFIED(dir_type) );
664 cf_create_default_path_string( longname, dir_type, filename );
666 return access(longname,mode);
670 // Returns 1 if file exists, 0 if not.
671 int cf_exist( char *filename, int dir_type )
673 char longname[MAX_PATH_LEN];
675 Assert( CF_TYPE_SPECIFIED(dir_type) );
677 cf_create_default_path_string( longname, dir_type, filename );
679 FILE *fp = fopen(longname, "rb");
688 void cf_attrib(char *filename, int set, int clear, int dir_type)
690 char longname[MAX_PATH_LEN];
692 Assert( CF_TYPE_SPECIFIED(dir_type) );
694 cf_create_default_path_string( longname, dir_type, filename );
696 FILE *fp = fopen(longname, "rb");
703 DWORD z = GetFileAttributes(longname);
704 SetFileAttributes(longname, z | set & ~clear);
710 int cf_rename(char *old_name, char *name, int dir_type)
712 Assert( CF_TYPE_SPECIFIED(dir_type) );
715 char old_longname[_MAX_PATH];
716 char new_longname[_MAX_PATH];
718 cf_create_default_path_string( old_longname, dir_type, old_name );
719 cf_create_default_path_string( new_longname, dir_type, name );
721 ret_code = rename(old_longname, new_longname );
725 return CF_RENAME_FAIL_ACCESS;
728 return CF_RENAME_FAIL_EXIST;
732 return CF_RENAME_SUCCESS;
737 // Creates the directory path if it doesn't exist. Even creates all its
739 void cf_create_directory( int dir_type )
742 int dir_tree[CF_MAX_PATH_TYPES];
743 char longname[MAX_PATH_LEN];
745 Assert( CF_TYPE_SPECIFIED(dir_type) );
747 int current_dir = dir_type;
750 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
752 dir_tree[num_dirs++] = current_dir;
753 current_dir = Pathtypes[current_dir].parent_index;
755 } while( current_dir != CF_TYPE_ROOT );
760 for (i=num_dirs-1; i>=0; i-- ) {
761 cf_create_default_path_string( longname, dir_tree[i], NULL );
764 if ( _mkdir(longname, 0700)==0 ) {
765 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
768 if ( _mkdir(longname)==0 ) {
769 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
778 extern int game_cd_changed();
782 // parameters: *filepath ==> name of file to open (may be path+name)
783 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
784 // passing NULL to mode deletes the file if it exists and returns NULL
785 // type ==> one of: CFILE_NORMAL
786 // CFILE_MEMORY_MAPPED
787 // dir_type => override extension check, value is one of CF_TYPE* #defines
789 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
792 // returns: success ==> address of CFILE structure
796 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
798 char longname[_MAX_PATH];
800 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
801 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
803 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
805 if ( game_cd_changed() ) {
810 //================================================
811 // Check that all the parameters make sense
812 Assert(file_path && strlen(file_path));
813 Assert( mode != NULL );
815 // Can only open read-only binary files in memory mapped mode.
816 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
821 //===========================================================
822 // If in write mode, just try to open the file straight off
823 // the harddisk. No fancy packfile stuff here!
825 if ( strchr(mode,'w') ) {
826 // For write-only files, require a full path or a path type
827 if ( strpbrk(file_path,"/\\:") ) {
829 strcpy(longname, file_path );
832 Assert( dir_type != CF_TYPE_ANY );
834 // Create the directory if necessary
835 cf_create_directory( dir_type );
837 cf_create_default_path_string( longname, dir_type, file_path );
839 Assert( !(type & CFILE_MEMORY_MAPPED) );
841 // JOHN: TODO, you should create the path if it doesn't exist.
843 FILE *fp = fopen(longname, mode);
845 return cf_open_fill_cfblock(fp, dir_type);
851 //================================================
852 // Search for file on disk, on cdrom, or in a packfile
855 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
856 strcpy(copy_file_path, file_path);
859 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
861 // Fount it, now create a cfile out of it
863 if ( type & CFILE_MEMORY_MAPPED ) {
865 // Can't open memory mapped files out of pack files
872 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
874 if (hFile != INVALID_HANDLE_VALUE) {
875 return cf_open_mapped_fill_cfblock(hFile, dir_type);
882 FILE *fp = fopen( longname, "rb" );
886 // Found it in a pack file
887 return cf_open_packed_cfblock(fp, dir_type, offset, size );
889 // Found it in a normal file
890 return cf_open_fill_cfblock(fp, dir_type);
901 // ------------------------------------------------------------------------
904 // Open up a temporary file. A unique name is automatically generated. The
905 // file will be automatically deleted when file is closed.
907 // return: NULL => tmp file could not be opened
908 // pointer to CFILE => tmp file successfully opened
915 return cf_open_fill_cfblock(fp, 0);
922 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
923 // Cfile_block_list[] array and return the index.
925 // returns: success ==> index in Cfile_block_list[] array
928 int cfget_cfile_block()
933 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
934 cb = &Cfile_block_list[i];
935 if ( cb->type == CFILE_BLOCK_UNUSED ) {
938 cb->type = CFILE_BLOCK_USED;
943 // If we've reached this point, a free Cfile_block could not be found
944 nprintf(("Warning","A free Cfile_block could not be found.\n"));
945 Assert(0); // out of free cfile blocks
950 // cfclose() closes the file
952 // returns: success ==> 0
955 int cfclose( CFILE * cfile )
959 Assert(cfile != NULL);
961 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
962 cb = &Cfile_block_list[cfile->id];
966 // close memory mapped file
970 result = UnmapViewOfFile((void*)cb->data);
972 result = CloseHandle(cb->hInFile);
973 Assert(result); // Ensure file handle is closed properly
974 result = CloseHandle(cb->hMapFile);
975 Assert(result); // Ensure file handle is closed properly
979 } else if ( cb->fp != NULL ) {
980 Assert(cb->fp != NULL);
981 result = fclose(cb->fp);
986 cb->type = CFILE_BLOCK_UNUSED;
993 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
994 // for the case of a file being opened by cf_open();
996 // returns: success ==> ptr to CFILE structure.
999 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
1001 int cfile_block_index;
1003 cfile_block_index = cfget_cfile_block();
1004 if ( cfile_block_index == -1 ) {
1009 cfbp = &Cfile_block_list[cfile_block_index];
1010 cfp = &Cfile_list[cfile_block_index];;
1011 cfp->id = cfile_block_index;
1015 cfbp->dir_type = type;
1017 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1024 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1025 // for the case of a file being opened by cf_open();
1027 // returns: success ==> ptr to CFILE structure.
1030 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1032 // Found it in a pack file
1033 int cfile_block_index;
1035 cfile_block_index = cfget_cfile_block();
1036 if ( cfile_block_index == -1 ) {
1041 cfbp = &Cfile_block_list[cfile_block_index];
1043 cfp = &Cfile_list[cfile_block_index];
1044 cfp->id = cfile_block_index;
1048 cfbp->dir_type = type;
1050 cf_init_lowlevel_read_code(cfp,offset, size );
1059 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1060 // for the case of a file being opened by cf_open_mapped();
1062 // returns: ptr CFILE structure.
1064 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1066 int cfile_block_index;
1068 cfile_block_index = cfget_cfile_block();
1069 if ( cfile_block_index == -1 ) {
1075 cfbp = &Cfile_block_list[cfile_block_index];
1077 cfp = &Cfile_list[cfile_block_index];
1078 cfp->id = cfile_block_index;
1080 cfbp->hInFile = hFile;
1081 cfbp->dir_type = type;
1083 cf_init_lowlevel_read_code(cfp,0 , 0 );
1088 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1089 if (cfbp->hMapFile == NULL) {
1090 nprintf(("Error", "Could not create file-mapping object.\n"));
1094 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1095 Assert( cfbp->data != NULL );
1101 int cf_get_dir_type(CFILE *cfile)
1103 return Cfile_block_list[cfile->id].dir_type;
1106 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1107 // with the CFILE structure passed as a parameter
1111 void *cf_returndata(CFILE *cfile)
1113 Assert(cfile != NULL);
1115 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1116 cb = &Cfile_block_list[cfile->id];
1117 Assert(cb->data != NULL);
1123 // version number of opened file. Will be 0 unless you put something else here after you
1124 // open a file. Once set, you can use minimum version numbers with the read functions.
1125 void cf_set_version( CFILE * cfile, int version )
1127 Assert(cfile != NULL);
1129 cfile->version = version;
1132 // routines to read basic data types from CFILE's. Put here to
1133 // simplify mac/pc reading from cfiles.
1135 float cfread_float(CFILE *file, int ver, float deflt)
1139 if (file->version < ver)
1142 if (cfread( &f, sizeof(f), 1, file) != 1)
1145 // i = INTEL_INT(i); // hmm, not sure what to do here
1149 int cfread_int(CFILE *file, int ver, int deflt)
1153 if (file->version < ver)
1156 if (cfread( &i, sizeof(i), 1, file) != 1)
1163 uint cfread_uint(CFILE *file, int ver, uint deflt)
1167 if (file->version < ver)
1170 if (cfread( &i, sizeof(i), 1, file) != 1)
1177 short cfread_short(CFILE *file, int ver, short deflt)
1181 if (file->version < ver)
1184 if (cfread( &s, sizeof(s), 1, file) != 1)
1191 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1195 if (file->version < ver)
1198 if (cfread( &s, sizeof(s), 1, file) != 1)
1205 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1209 if (file->version < ver)
1212 if (cfread( &b, sizeof(b), 1, file) != 1)
1218 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1220 if (file->version < ver) {
1224 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1229 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1230 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1231 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1234 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1236 if (file->version < ver) {
1240 ang->p = ang->b = ang->h = 0.0f;
1245 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1246 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1247 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1250 char cfread_char(CFILE *file, int ver, char deflt)
1254 if (file->version < ver)
1257 if (cfread( &b, sizeof(b), 1, file) != 1)
1263 void cfread_string(char *buf, int n, CFILE *file)
1268 c = cfread_char(file);
1276 void cfread_string_len(char *buf,int n, CFILE *file)
1279 len = cfread_int(file);
1282 cfread(buf, len, 1, file);
1287 // equivalent write functions of above read functions follow
1289 int cfwrite_float(float f, CFILE *file)
1291 // i = INTEL_INT(i); // hmm, not sure what to do here
1292 return cfwrite(&f, sizeof(f), 1, file);
1295 int cfwrite_int(int i, CFILE *file)
1298 return cfwrite(&i, sizeof(i), 1, file);
1301 int cfwrite_uint(uint i, CFILE *file)
1304 return cfwrite(&i, sizeof(i), 1, file);
1307 int cfwrite_short(short s, CFILE *file)
1310 return cfwrite(&s, sizeof(s), 1, file);
1313 int cfwrite_ushort(ushort s, CFILE *file)
1316 return cfwrite(&s, sizeof(s), 1, file);
1319 int cfwrite_ubyte(ubyte b, CFILE *file)
1321 return cfwrite(&b, sizeof(b), 1, file);
1324 int cfwrite_vector(vector *vec, CFILE *file)
1326 if(!cfwrite_float(vec->xyz.x, file)){
1329 if(!cfwrite_float(vec->xyz.y, file)){
1332 return cfwrite_float(vec->xyz.z, file);
1335 int cfwrite_angles(angles *ang, CFILE *file)
1337 if(!cfwrite_float(ang->p, file)){
1340 if(!cfwrite_float(ang->b, file)){
1343 return cfwrite_float(ang->h, file);
1346 int cfwrite_char(char b, CFILE *file)
1348 return cfwrite( &b, sizeof(b), 1, file);
1351 int cfwrite_string(char *buf, CFILE *file)
1353 if ( (!buf) || (buf && !buf[0]) ) {
1354 return cfwrite_char(0, file);
1356 int len = strlen(buf);
1357 if(!cfwrite(buf, len, 1, file)){
1360 return cfwrite_char(0, file); // write out NULL termination
1363 int cfwrite_string_len(char *buf, CFILE *file)
1365 int len = strlen(buf);
1367 if(!cfwrite_int(len, file)){
1371 return cfwrite(buf,len,1,file);
1377 // Get the filelength
1378 int cfilelength( CFILE * cfile )
1380 Assert(cfile != NULL);
1382 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1383 cb = &Cfile_block_list[cfile->id];
1385 // TODO: return length of memory mapped file
1386 Assert( !cb->data );
1388 Assert(cb->fp != NULL);
1390 // cb->size gets set at cfopen
1394 // cfwrite() writes to the file
1396 // returns: number of full elements actually written
1399 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1401 Assert(cfile != NULL);
1402 Assert(buf != NULL);
1407 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1408 cb = &Cfile_block_list[cfile->id];
1412 // cfwrite() not supported for memory-mapped files
1413 Assert( !cb->data );
1415 Assert(cb->fp != NULL);
1416 Assert(cb->lib_offset == 0 );
1417 result = fwrite(buf, elsize, nelem, cb->fp);
1423 // cfputc() writes a character to a file
1425 // returns: success ==> returns character written
1428 int cfputc(int c, CFILE *cfile)
1432 Assert(cfile != NULL);
1434 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1435 cb = &Cfile_block_list[cfile->id];
1438 // cfputc() not supported for memory-mapped files
1439 Assert( !cb->data );
1441 Assert(cb->fp != NULL);
1442 result = fputc(c, cb->fp);
1448 // cfgetc() reads a character from a file
1450 // returns: success ==> returns character read
1453 int cfgetc(CFILE *cfile)
1455 Assert(cfile != NULL);
1459 int result = cfread(&tmp, 1, 1, cfile );
1460 if ( result == 1 ) {
1473 // cfgets() reads a string from a file
1475 // returns: success ==> returns pointer to string
1478 char *cfgets(char *buf, int n, CFILE *cfile)
1480 Assert(cfile != NULL);
1481 Assert(buf != NULL);
1487 for (i=0; i<n-1; i++ ) {
1491 int ret = cfread( &tmp_c, 1, 1, cfile );
1501 } while ( c == 13 );
1503 if ( c=='\n' ) break;
1510 // cfputs() writes a string to a file
1512 // returns: success ==> non-negative value
1515 int cfputs(char *str, CFILE *cfile)
1517 Assert(cfile != NULL);
1518 Assert(str != NULL);
1521 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1522 cb = &Cfile_block_list[cfile->id];
1527 // cfputs() not supported for memory-mapped files
1528 Assert( !cb->data );
1529 Assert(cb->fp != NULL);
1530 result = fputs(str, cb->fp);
1536 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1538 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1539 // checksumming code that he wrote a while ago.
1540 #define CRC32_POLYNOMIAL 0xEDB88320L
1541 unsigned long CRCTable[256];
1543 #define CF_CHKSUM_SAMPLE_SIZE 512
1545 // update cur_chksum with the chksum of the new_data of size new_data_size
1546 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1548 ubyte * ptr = (ubyte *)buffer;
1549 unsigned int sum1,sum2;
1551 sum1 = sum2 = (int)(seed);
1555 if (sum1 >= 255 ) sum1 -= 255;
1560 return (unsigned short)((sum1<<8)+ sum2);
1563 // update cur_chksum with the chksum of the new_data of size new_data_size
1564 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1568 unsigned long temp1;
1569 unsigned long temp2;
1571 p = (unsigned char*)buffer;
1575 temp1 = (crc>>8)&0x00FFFFFFL;
1576 temp2 = CRCTable[((int)crc^*p++)&0xff];
1583 void cf_chksum_long_init()
1588 for( i=0;i<=255;i++) {
1592 crc=(crc>>1)^CRC32_POLYNOMIAL;
1600 // single function convenient to use for both short and long checksums
1601 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1602 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1604 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1610 // determine whether we're doing a short or long checksum
1621 // if max_size is -1, set it to be the size of the file
1623 cfseek(cfile, 0, SEEK_SET);
1624 max_size = cfilelength(cfile);
1629 // determine how much we want to read
1630 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1631 read_size = CF_CHKSUM_SAMPLE_SIZE;
1633 read_size = max_size - cf_total;
1636 // read in some buffer
1637 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1639 // total we've read so far
1644 // do the proper short or long checksum
1646 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1648 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1651 } while((cf_len > 0) && (cf_total < max_size));
1656 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1657 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1660 CFILE *cfile = NULL;
1662 // zero the checksum
1665 // attempt to open the file
1666 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1671 // call the overloaded cf_chksum function()
1672 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1674 // close the file down
1678 // return the result
1682 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1683 // NOTE : preserves current file position
1684 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1689 // Returns current position of file.
1690 start_pos = cftell(file);
1691 if(start_pos == -1){
1695 // move to the beginning of the file
1696 if(cfseek(file, 0, CF_SEEK_SET)){
1699 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1700 // move back to the start position
1701 cfseek(file, start_pos, CF_SEEK_SET);
1706 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1707 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1710 CFILE *cfile = NULL;
1712 // zero the checksum
1715 // attempt to open the file
1716 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1721 // call the overloaded cf_chksum function()
1722 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1724 // close the file down
1728 // return the result
1732 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1733 // NOTE : preserves current file position
1734 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1739 // Returns current position of file.
1740 start_pos = cftell(file);
1741 if(start_pos == -1){
1745 // move to the beginning of the file
1746 if(cfseek(file, 0, CF_SEEK_SET)){
1749 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1750 // move back to the start position
1751 cfseek(file, start_pos, CF_SEEK_SET);
1757 // Flush the open file buffer
1759 // exit: 0 - success
1761 int cflush(CFILE *cfile)
1763 Assert(cfile != NULL);
1765 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1766 cb = &Cfile_block_list[cfile->id];
1768 // not supported for memory mapped files
1769 Assert( !cb->data );
1771 Assert(cb->fp != NULL);
1772 return fflush(cb->fp);