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.7 2002/12/30 03:23:29 relnev
19 * disable root dir check
21 * Revision 1.6 2002/06/17 06:33:08 relnev
22 * ryan's struct patch for gcc 2.95
24 * Revision 1.5 2002/06/09 04:41:15 relnev
25 * added copyright header
27 * Revision 1.4 2002/06/05 08:05:28 relnev
28 * stub/warning removal.
30 * reworked the sound code.
32 * Revision 1.3 2002/05/28 08:52:03 relnev
33 * implemented two assembly stubs.
35 * cleaned up a few warnings.
37 * added a little demo hackery to make it progress a little farther.
39 * Revision 1.2 2002/05/28 06:28:20 theoddone33
40 * Filesystem mods, actually reads some data files now
42 * Revision 1.1.1.1 2002/05/03 03:28:08 root
46 * 20 9/08/99 10:01p Dave
47 * Make sure game won't run in a drive's root directory. Make sure
48 * standalone routes suqad war messages properly to the host.
50 * 19 9/08/99 12:03a Dave
51 * Make squad logos render properly in D3D all the time. Added intel anim
54 * 18 9/06/99 2:35p Dave
55 * Rename briefing and debriefing voice direcrory paths properly.
57 * 17 9/03/99 1:31a Dave
58 * CD checking by act. Added support to play 2 cutscenes in a row
59 * seamlessly. Fixed super low level cfile bug related to files in the
60 * root directory of a CD. Added cheat code to set campaign mission # in
63 * 16 8/31/99 9:46a Dave
64 * Support for new cfile cbanims directory.
66 * 15 8/06/99 11:20a Johns
67 * Don't call game_cd_changed() in a demo or multiplayer beta build.
69 * 14 6/08/99 2:33p Dave
70 * Fixed release build warning. Put in hud config stuff.
72 * 13 5/19/99 4:07p Dave
73 * Moved versioning code into a nice isolated common place. Fixed up
74 * updating code on the pxo screen. Fixed several stub problems.
76 * 12 4/30/99 12:18p Dave
77 * Several minor bug fixes.
79 * 11 4/07/99 5:54p Dave
80 * Fixes for encryption in updatelauncher.
82 * 10 3/28/99 5:58p Dave
83 * Added early demo code. Make objects move. Nice and framerate
84 * independant, but not much else. Don't use yet unless you're me :)
86 * 9 2/22/99 10:31p Andsager
87 * Get rid of unneeded includes.
89 * 8 1/12/99 3:15a Dave
90 * Barracks screen support for selecting squad logos. We need real artwork
93 * 7 11/30/98 1:07p Dave
94 * 16 bit conversion, first run.
96 * 6 10/29/98 10:41a Dave
97 * Change the way cfile initializes exe directory.
99 * 5 10/13/98 9:19a Andsager
100 * Add localization support to cfile. Optional parameter with cfopen that
101 * looks for localized files.
103 * 4 10/12/98 9:54a Dave
104 * Fixed a few file organization things.
106 * 3 10/07/98 6:27p Dave
107 * Globalized mission and campaign file extensions. Removed Silent Threat
108 * special code. Moved \cache \players and \multidata into the \data
111 * 2 10/07/98 10:52a Dave
114 * 1 10/07/98 10:48a Dave
116 * 110 9/17/98 10:31a Hoffoss
117 * Changed code to use location of executable as root rather than relying
118 * on the cwd being set correctly. This is most helpful in the case of
119 * Fred launching due to the user double-clicking on an .fsm file in
120 * explorer or something (where the cwd is probably the location of the
123 * 109 9/11/98 4:14p Dave
124 * Fixed file checksumming of < file_size. Put in more verbose kicking and
125 * PXO stats store reporting.
127 * 108 9/09/98 5:53p Dave
128 * Put in new tracker packets in API. Change cfile to be able to checksum
129 * portions of a file.
131 * 107 9/04/98 3:51p Dave
132 * Put in validated mission updating and application during stats
135 * 106 8/31/98 2:06p Dave
136 * Make cfile sort the ordering or vp files. Added support/checks for
137 * recognizing "mission disk" players.
139 * 105 8/20/98 5:30p Dave
140 * Put in handy multiplayer logfile system. Now need to put in useful
141 * applications of it all over the code.
143 * 104 8/12/98 4:53p Dave
144 * Put in 32 bit checksumming for PXO missions. No validation on the
145 * actual tracker yet, though.
147 * 103 6/17/98 9:30a Allender
148 * fixed red alert replay stats clearing problem
150 * 102 6/05/98 9:46a Lawrance
151 * check for CD change on cfopen()
153 * 101 5/19/98 1:19p Allender
154 * new low level reliable socket reading code. Make all missions/campaign
155 * load/save to data missions folder (i.e. we are rid of the player
158 * 100 5/13/98 10:22p John
159 * Added cfile functions to read/write rle compressed blocks of data.
160 * Made palman use it for .clr files. Made alphacolors calculate on the
161 * fly rather than caching to/from disk.
163 * 99 5/11/98 10:59a John
164 * Moved the low-level file reading code into cfilearchive.cpp.
166 * 98 5/06/98 5:30p John
167 * Removed unused cfilearchiver. Removed/replaced some unused/little used
168 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
169 * DirectX header files and libs that fixed the Direct3D alpha blending
172 * 97 5/03/98 11:53a John
173 * Fixed filename case mangling.
175 * 96 5/03/98 8:33a John
176 * Made sure there weren't any more broken function lurking around like
177 * the one Allender fixed.
179 * 95 5/02/98 11:05p Allender
180 * fix cfilelength for pack files
185 #define _CFILE_INTERNAL
195 #include <winbase.h> /* needed for memory mapping of file functions */
198 #include <sys/stat.h>
199 #include <sys/types.h>
205 //#include "outwnd.h"
206 //#include "vecmat.h"
208 #include "cfilesystem.h"
209 #include "cfilearchive.h"
212 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
214 // During cfile_init, verify that Pathtypes[n].index == n for each item
215 // Each path must have a valid parent that can be tracable all the way back to the root
216 // so that we can create directories when we need to.
218 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
219 // What type this is Path Extensions Parent type
220 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
221 // Root must be index 1!!
222 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
223 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
225 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
226 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
227 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
228 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
229 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
230 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
231 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
232 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
233 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
234 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
235 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
236 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
237 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
238 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
239 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
240 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
241 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
242 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
243 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
244 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
245 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
246 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
247 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
248 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
249 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
250 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
251 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
252 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
253 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
254 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
255 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
256 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
257 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
259 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
260 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
261 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
262 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
263 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
264 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
265 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
266 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
267 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
268 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
269 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
270 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
271 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
272 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
273 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
274 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
275 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
276 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
277 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
278 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
279 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
280 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
281 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
282 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
283 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
284 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
285 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
286 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
287 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
288 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
289 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
290 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
291 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
296 #define CFILE_STACK_MAX 8
298 int cfile_inited = 0;
299 int Cfile_stack_pos = 0;
301 char Cfile_stack[128][CFILE_STACK_MAX];
303 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
304 CFILE Cfile_list[MAX_CFILE_BLOCKS];
306 char *Cfile_cdrom_dir = NULL;
309 // Function prototypes for internally-called functions
311 int cfget_cfile_block();
312 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
313 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
314 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
315 void cf_chksum_long_init();
319 cf_free_secondary_filelist();
322 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
323 int cfile_in_root_dir(char *exe_path)
326 char path_copy[2048] = "";
330 if(exe_path == NULL){
335 memset(path_copy, 0, 2048);
336 strncpy(path_copy, exe_path, 2047);
338 // count how many slashes there are in the path
340 tok = strtok(path_copy, "/");
342 tok = strtok(path_copy, "\\");
350 tok = strtok(NULL, "/");
352 tok = strtok(NULL, "\\");
354 } while(tok != NULL);
356 // root directory if we have <= 1 slash
357 if(token_count <= 2){
361 // not-root directory
365 // cfile_init() initializes the cfile system. Called once at application start.
367 // returns: success ==> 0
368 // error ==> non-zero
370 int cfile_init(char *exe_dir, char *cdrom_dir)
374 // initialize encryption
377 if ( !cfile_inited ) {
382 strcpy(buf, exe_dir);
386 // are we in a root directory?
387 if(cfile_in_root_dir(buf)){
388 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
408 fprintf (stderr, "Error trying to determine executable root directory!");
410 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
415 // set root directory
416 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
418 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
419 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
422 Cfile_cdrom_dir = cdrom_dir;
423 cf_build_secondary_filelist(Cfile_cdrom_dir);
425 // 32 bit CRC table init
426 cf_chksum_long_init();
428 atexit( cfile_close );
434 // Call this if pack files got added or removed or the
435 // cdrom changed. This will refresh the list of filenames
436 // stored in packfiles and on the cdrom.
439 cf_build_secondary_filelist(Cfile_cdrom_dir);
443 // Changes to a drive if valid.. 1=A, 2=B, etc
444 // If flag, then changes to it.
445 // Returns 0 if not-valid, 1 if valid.
446 int cfile_chdrive( int DriveNum, int flag )
459 _chdrive( DriveNum );
466 if ( (!flag) && (n != org) )
472 // push current directory on a 'stack' (so we can restore it) and change the directory
473 int cfile_push_chdir(int type)
477 char OriginalDirectory[128];
479 char NoDir[] = "\\.";
481 _getcwd(OriginalDirectory, 127);
482 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
483 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
485 cf_create_default_path_string( dir, type, NULL );
488 char *Drive = strchr(dir, ':');
491 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
506 // This chdir might get a critical error!
509 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
517 int cfile_chdir(char *dir)
520 char OriginalDirectory[128];
522 char NoDir[] = "\\.";
524 _getcwd(OriginalDirectory, 127);
528 char *Drive = strchr(dir, ':');
530 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
545 // This chdir might get a critical error!
548 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
557 Assert(Cfile_stack_pos);
559 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
562 // flush (delete all files in) the passed directory (by type), return the # of files deleted
563 // NOTE : WILL NOT DELETE READ-ONLY FILES
564 int cfile_flush_dir(int dir_type)
574 Assert( CF_TYPE_SPECIFIED(dir_type) );
576 // attempt to change the directory to the passed type
577 if(cfile_push_chdir(dir_type)){
581 // proceed to delete the files
582 find_handle = _findfirst( "*", &find );
584 if (find_handle != -1) {
586 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
588 cf_delete(find.name,dir_type);
590 // increment the deleted count
593 } while (!_findnext(find_handle, &find));
594 _findclose( find_handle );
597 // pop the directory back
600 // return the # of files deleted
606 // add the given extention to a filename (or filepath) if it doesn't already have this
608 // filename = name of filename or filepath to process
609 // ext = extension to add. Must start with the period
610 // Returns: new filename or filepath with extension.
611 char *cf_add_ext(char *filename, char *ext)
614 static char path[MAX_PATH_LEN];
616 flen = strlen(filename);
618 Assert(flen < MAX_PATH_LEN);
619 strcpy(path, filename);
620 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
621 Assert(flen + elen < MAX_PATH_LEN);
629 void cf_delete( char *filename, int dir_type )
631 char longname[MAX_PATH_LEN];
633 Assert( CF_TYPE_SPECIFIED(dir_type) );
635 cf_create_default_path_string( longname, dir_type, filename );
637 FILE *fp = fopen(longname, "rb");
647 // Same as _access function to read a file's access bits
648 int cf_access( char *filename, int dir_type, int mode )
650 char longname[MAX_PATH_LEN];
652 Assert( CF_TYPE_SPECIFIED(dir_type) );
654 cf_create_default_path_string( longname, dir_type, filename );
656 return access(longname,mode);
660 // Returns 1 if file exists, 0 if not.
661 int cf_exist( char *filename, int dir_type )
663 char longname[MAX_PATH_LEN];
665 Assert( CF_TYPE_SPECIFIED(dir_type) );
667 cf_create_default_path_string( longname, dir_type, filename );
669 FILE *fp = fopen(longname, "rb");
678 void cf_attrib(char *filename, int set, int clear, int dir_type)
680 char longname[MAX_PATH_LEN];
682 Assert( CF_TYPE_SPECIFIED(dir_type) );
684 cf_create_default_path_string( longname, dir_type, filename );
686 FILE *fp = fopen(longname, "rb");
693 DWORD z = GetFileAttributes(longname);
694 SetFileAttributes(longname, z | set & ~clear);
700 int cf_rename(char *old_name, char *name, int dir_type)
702 Assert( CF_TYPE_SPECIFIED(dir_type) );
705 char old_longname[_MAX_PATH];
706 char new_longname[_MAX_PATH];
708 cf_create_default_path_string( old_longname, dir_type, old_name );
709 cf_create_default_path_string( new_longname, dir_type, name );
711 ret_code = rename(old_longname, new_longname );
715 return CF_RENAME_FAIL_ACCESS;
718 return CF_RENAME_FAIL_EXIST;
722 return CF_RENAME_SUCCESS;
727 // Creates the directory path if it doesn't exist. Even creates all its
729 void cf_create_directory( int dir_type )
732 int dir_tree[CF_MAX_PATH_TYPES];
733 char longname[MAX_PATH_LEN];
735 Assert( CF_TYPE_SPECIFIED(dir_type) );
737 int current_dir = dir_type;
740 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
742 dir_tree[num_dirs++] = current_dir;
743 current_dir = Pathtypes[current_dir].parent_index;
745 } while( current_dir != CF_TYPE_ROOT );
750 for (i=num_dirs-1; i>=0; i-- ) {
751 cf_create_default_path_string( longname, dir_tree[i], NULL );
754 if ( _mkdir(longname, 0777)==0 ) {
755 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
758 if ( _mkdir(longname)==0 ) {
759 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
768 extern int game_cd_changed();
772 // parameters: *filepath ==> name of file to open (may be path+name)
773 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
774 // passing NULL to mode deletes the file if it exists and returns NULL
775 // type ==> one of: CFILE_NORMAL
776 // CFILE_MEMORY_MAPPED
777 // dir_type => override extension check, value is one of CF_TYPE* #defines
779 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
782 // returns: success ==> address of CFILE structure
786 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
788 char longname[_MAX_PATH];
790 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
791 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
793 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
795 if ( game_cd_changed() ) {
800 //================================================
801 // Check that all the parameters make sense
802 Assert(file_path && strlen(file_path));
803 Assert( mode != NULL );
805 // Can only open read-only binary files in memory mapped mode.
806 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
811 //===========================================================
812 // If in write mode, just try to open the file straight off
813 // the harddisk. No fancy packfile stuff here!
815 if ( strchr(mode,'w') ) {
816 // For write-only files, require a full path or a path type
817 if ( strpbrk(file_path,"/\\:") ) {
819 strcpy(longname, file_path );
822 Assert( dir_type != CF_TYPE_ANY );
824 // Create the directory if necessary
825 cf_create_directory( dir_type );
827 cf_create_default_path_string( longname, dir_type, file_path );
829 Assert( !(type & CFILE_MEMORY_MAPPED) );
831 // JOHN: TODO, you should create the path if it doesn't exist.
833 FILE *fp = fopen(longname, mode);
835 return cf_open_fill_cfblock(fp, dir_type);
841 //================================================
842 // Search for file on disk, on cdrom, or in a packfile
845 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
846 strcpy(copy_file_path, file_path);
849 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
851 // Fount it, now create a cfile out of it
853 if ( type & CFILE_MEMORY_MAPPED ) {
855 // Can't open memory mapped files out of pack files
862 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
864 if (hFile != INVALID_HANDLE_VALUE) {
865 return cf_open_mapped_fill_cfblock(hFile, dir_type);
872 FILE *fp = fopen( longname, "rb" );
876 // Found it in a pack file
877 return cf_open_packed_cfblock(fp, dir_type, offset, size );
879 // Found it in a normal file
880 return cf_open_fill_cfblock(fp, dir_type);
891 // ------------------------------------------------------------------------
894 // Open up a temporary file. A unique name is automatically generated. The
895 // file will be automatically deleted when file is closed.
897 // return: NULL => tmp file could not be opened
898 // pointer to CFILE => tmp file successfully opened
905 return cf_open_fill_cfblock(fp, 0);
912 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
913 // Cfile_block_list[] array and return the index.
915 // returns: success ==> index in Cfile_block_list[] array
918 int cfget_cfile_block()
923 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
924 cb = &Cfile_block_list[i];
925 if ( cb->type == CFILE_BLOCK_UNUSED ) {
928 cb->type = CFILE_BLOCK_USED;
933 // If we've reached this point, a free Cfile_block could not be found
934 nprintf(("Warning","A free Cfile_block could not be found.\n"));
935 Assert(0); // out of free cfile blocks
940 // cfclose() closes the file
942 // returns: success ==> 0
945 int cfclose( CFILE * cfile )
949 Assert(cfile != NULL);
951 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
952 cb = &Cfile_block_list[cfile->id];
956 // close memory mapped file
960 result = UnmapViewOfFile((void*)cb->data);
962 result = CloseHandle(cb->hInFile);
963 Assert(result); // Ensure file handle is closed properly
964 result = CloseHandle(cb->hMapFile);
965 Assert(result); // Ensure file handle is closed properly
969 } else if ( cb->fp != NULL ) {
970 Assert(cb->fp != NULL);
971 result = fclose(cb->fp);
976 cb->type = CFILE_BLOCK_UNUSED;
983 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
984 // for the case of a file being opened by cf_open();
986 // returns: success ==> ptr to CFILE structure.
989 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
991 int cfile_block_index;
993 cfile_block_index = cfget_cfile_block();
994 if ( cfile_block_index == -1 ) {
999 cfbp = &Cfile_block_list[cfile_block_index];
1000 cfp = &Cfile_list[cfile_block_index];;
1001 cfp->id = cfile_block_index;
1005 cfbp->dir_type = type;
1007 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1014 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1015 // for the case of a file being opened by cf_open();
1017 // returns: success ==> ptr to CFILE structure.
1020 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1022 // Found it in a pack file
1023 int cfile_block_index;
1025 cfile_block_index = cfget_cfile_block();
1026 if ( cfile_block_index == -1 ) {
1031 cfbp = &Cfile_block_list[cfile_block_index];
1033 cfp = &Cfile_list[cfile_block_index];
1034 cfp->id = cfile_block_index;
1038 cfbp->dir_type = type;
1040 cf_init_lowlevel_read_code(cfp,offset, size );
1049 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1050 // for the case of a file being opened by cf_open_mapped();
1052 // returns: ptr CFILE structure.
1054 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1056 int cfile_block_index;
1058 cfile_block_index = cfget_cfile_block();
1059 if ( cfile_block_index == -1 ) {
1065 cfbp = &Cfile_block_list[cfile_block_index];
1067 cfp = &Cfile_list[cfile_block_index];
1068 cfp->id = cfile_block_index;
1070 cfbp->hInFile = hFile;
1071 cfbp->dir_type = type;
1073 cf_init_lowlevel_read_code(cfp,0 , 0 );
1078 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1079 if (cfbp->hMapFile == NULL) {
1080 nprintf(("Error", "Could not create file-mapping object.\n"));
1084 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1085 Assert( cfbp->data != NULL );
1091 int cf_get_dir_type(CFILE *cfile)
1093 return Cfile_block_list[cfile->id].dir_type;
1096 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1097 // with the CFILE structure passed as a parameter
1101 void *cf_returndata(CFILE *cfile)
1103 Assert(cfile != NULL);
1105 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1106 cb = &Cfile_block_list[cfile->id];
1107 Assert(cb->data != NULL);
1113 // version number of opened file. Will be 0 unless you put something else here after you
1114 // open a file. Once set, you can use minimum version numbers with the read functions.
1115 void cf_set_version( CFILE * cfile, int version )
1117 Assert(cfile != NULL);
1119 cfile->version = version;
1122 // routines to read basic data types from CFILE's. Put here to
1123 // simplify mac/pc reading from cfiles.
1125 float cfread_float(CFILE *file, int ver, float deflt)
1129 if (file->version < ver)
1132 if (cfread( &f, sizeof(f), 1, file) != 1)
1135 // i = INTEL_INT(i); // hmm, not sure what to do here
1139 int cfread_int(CFILE *file, int ver, int deflt)
1143 if (file->version < ver)
1146 if (cfread( &i, sizeof(i), 1, file) != 1)
1153 uint cfread_uint(CFILE *file, int ver, uint deflt)
1157 if (file->version < ver)
1160 if (cfread( &i, sizeof(i), 1, file) != 1)
1167 short cfread_short(CFILE *file, int ver, short deflt)
1171 if (file->version < ver)
1174 if (cfread( &s, sizeof(s), 1, file) != 1)
1181 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1185 if (file->version < ver)
1188 if (cfread( &s, sizeof(s), 1, file) != 1)
1195 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1199 if (file->version < ver)
1202 if (cfread( &b, sizeof(b), 1, file) != 1)
1208 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1210 if (file->version < ver) {
1214 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1219 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1220 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1221 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1224 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1226 if (file->version < ver) {
1230 ang->p = ang->b = ang->h = 0.0f;
1235 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1236 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1237 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1240 char cfread_char(CFILE *file, int ver, char deflt)
1244 if (file->version < ver)
1247 if (cfread( &b, sizeof(b), 1, file) != 1)
1253 void cfread_string(char *buf, int n, CFILE *file)
1258 c = cfread_char(file);
1266 void cfread_string_len(char *buf,int n, CFILE *file)
1269 len = cfread_int(file);
1272 cfread(buf, len, 1, file);
1277 // equivalent write functions of above read functions follow
1279 int cfwrite_float(float f, CFILE *file)
1281 // i = INTEL_INT(i); // hmm, not sure what to do here
1282 return cfwrite(&f, sizeof(f), 1, file);
1285 int cfwrite_int(int i, CFILE *file)
1288 return cfwrite(&i, sizeof(i), 1, file);
1291 int cfwrite_uint(uint i, CFILE *file)
1294 return cfwrite(&i, sizeof(i), 1, file);
1297 int cfwrite_short(short s, CFILE *file)
1300 return cfwrite(&s, sizeof(s), 1, file);
1303 int cfwrite_ushort(ushort s, CFILE *file)
1306 return cfwrite(&s, sizeof(s), 1, file);
1309 int cfwrite_ubyte(ubyte b, CFILE *file)
1311 return cfwrite(&b, sizeof(b), 1, file);
1314 int cfwrite_vector(vector *vec, CFILE *file)
1316 if(!cfwrite_float(vec->xyz.x, file)){
1319 if(!cfwrite_float(vec->xyz.y, file)){
1322 return cfwrite_float(vec->xyz.z, file);
1325 int cfwrite_angles(angles *ang, CFILE *file)
1327 if(!cfwrite_float(ang->p, file)){
1330 if(!cfwrite_float(ang->b, file)){
1333 return cfwrite_float(ang->h, file);
1336 int cfwrite_char(char b, CFILE *file)
1338 return cfwrite( &b, sizeof(b), 1, file);
1341 int cfwrite_string(char *buf, CFILE *file)
1343 if ( (!buf) || (buf && !buf[0]) ) {
1344 return cfwrite_char(0, file);
1346 int len = strlen(buf);
1347 if(!cfwrite(buf, len, 1, file)){
1350 return cfwrite_char(0, file); // write out NULL termination
1353 int cfwrite_string_len(char *buf, CFILE *file)
1355 int len = strlen(buf);
1357 if(!cfwrite_int(len, file)){
1361 return cfwrite(buf,len,1,file);
1367 // Get the filelength
1368 int cfilelength( CFILE * cfile )
1370 Assert(cfile != NULL);
1372 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1373 cb = &Cfile_block_list[cfile->id];
1375 // TODO: return length of memory mapped file
1376 Assert( !cb->data );
1378 Assert(cb->fp != NULL);
1380 // cb->size gets set at cfopen
1384 // cfwrite() writes to the file
1386 // returns: number of full elements actually written
1389 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1391 Assert(cfile != NULL);
1392 Assert(buf != NULL);
1397 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1398 cb = &Cfile_block_list[cfile->id];
1402 // cfwrite() not supported for memory-mapped files
1403 Assert( !cb->data );
1405 Assert(cb->fp != NULL);
1406 Assert(cb->lib_offset == 0 );
1407 result = fwrite(buf, elsize, nelem, cb->fp);
1413 // cfputc() writes a character to a file
1415 // returns: success ==> returns character written
1418 int cfputc(int c, CFILE *cfile)
1422 Assert(cfile != NULL);
1424 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1425 cb = &Cfile_block_list[cfile->id];
1428 // cfputc() not supported for memory-mapped files
1429 Assert( !cb->data );
1431 Assert(cb->fp != NULL);
1432 result = fputc(c, cb->fp);
1438 // cfgetc() reads a character from a file
1440 // returns: success ==> returns character read
1443 int cfgetc(CFILE *cfile)
1445 Assert(cfile != NULL);
1449 int result = cfread(&tmp, 1, 1, cfile );
1450 if ( result == 1 ) {
1463 // cfgets() reads a string from a file
1465 // returns: success ==> returns pointer to string
1468 char *cfgets(char *buf, int n, CFILE *cfile)
1470 Assert(cfile != NULL);
1471 Assert(buf != NULL);
1477 for (i=0; i<n-1; i++ ) {
1481 int ret = cfread( &tmp_c, 1, 1, cfile );
1491 } while ( c == 13 );
1493 if ( c=='\n' ) break;
1500 // cfputs() writes a string to a file
1502 // returns: success ==> non-negative value
1505 int cfputs(char *str, CFILE *cfile)
1507 Assert(cfile != NULL);
1508 Assert(str != NULL);
1511 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1512 cb = &Cfile_block_list[cfile->id];
1517 // cfputs() not supported for memory-mapped files
1518 Assert( !cb->data );
1519 Assert(cb->fp != NULL);
1520 result = fputs(str, cb->fp);
1526 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1528 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1529 // checksumming code that he wrote a while ago.
1530 #define CRC32_POLYNOMIAL 0xEDB88320L
1531 unsigned long CRCTable[256];
1533 #define CF_CHKSUM_SAMPLE_SIZE 512
1535 // update cur_chksum with the chksum of the new_data of size new_data_size
1536 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1538 ubyte * ptr = (ubyte *)buffer;
1539 unsigned int sum1,sum2;
1541 sum1 = sum2 = (int)(seed);
1545 if (sum1 >= 255 ) sum1 -= 255;
1550 return (unsigned short)((sum1<<8)+ sum2);
1553 // update cur_chksum with the chksum of the new_data of size new_data_size
1554 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1558 unsigned long temp1;
1559 unsigned long temp2;
1561 p = (unsigned char*)buffer;
1565 temp1 = (crc>>8)&0x00FFFFFFL;
1566 temp2 = CRCTable[((int)crc^*p++)&0xff];
1573 void cf_chksum_long_init()
1578 for( i=0;i<=255;i++) {
1582 crc=(crc>>1)^CRC32_POLYNOMIAL;
1590 // single function convenient to use for both short and long checksums
1591 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1592 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1594 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1600 // determine whether we're doing a short or long checksum
1611 // if max_size is -1, set it to be the size of the file
1613 cfseek(cfile, 0, SEEK_SET);
1614 max_size = cfilelength(cfile);
1619 // determine how much we want to read
1620 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1621 read_size = CF_CHKSUM_SAMPLE_SIZE;
1623 read_size = max_size - cf_total;
1626 // read in some buffer
1627 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1629 // total we've read so far
1634 // do the proper short or long checksum
1636 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1638 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1641 } while((cf_len > 0) && (cf_total < max_size));
1646 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1647 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1650 CFILE *cfile = NULL;
1652 // zero the checksum
1655 // attempt to open the file
1656 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1661 // call the overloaded cf_chksum function()
1662 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1664 // close the file down
1668 // return the result
1672 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1673 // NOTE : preserves current file position
1674 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1679 // Returns current position of file.
1680 start_pos = cftell(file);
1681 if(start_pos == -1){
1685 // move to the beginning of the file
1686 if(cfseek(file, 0, CF_SEEK_SET)){
1689 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1690 // move back to the start position
1691 cfseek(file, start_pos, CF_SEEK_SET);
1696 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1697 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1700 CFILE *cfile = NULL;
1702 // zero the checksum
1705 // attempt to open the file
1706 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1711 // call the overloaded cf_chksum function()
1712 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1714 // close the file down
1718 // return the result
1722 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1723 // NOTE : preserves current file position
1724 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1729 // Returns current position of file.
1730 start_pos = cftell(file);
1731 if(start_pos == -1){
1735 // move to the beginning of the file
1736 if(cfseek(file, 0, CF_SEEK_SET)){
1739 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1740 // move back to the start position
1741 cfseek(file, start_pos, CF_SEEK_SET);
1747 // Flush the open file buffer
1749 // exit: 0 - success
1751 int cflush(CFILE *cfile)
1753 Assert(cfile != NULL);
1755 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1756 cb = &Cfile_block_list[cfile->id];
1758 // not supported for memory mapped files
1759 Assert( !cb->data );
1761 Assert(cb->fp != NULL);
1762 return fflush(cb->fp);