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.6 2002/06/17 06:33:08 relnev
19 * ryan's struct patch for gcc 2.95
21 * Revision 1.5 2002/06/09 04:41:15 relnev
22 * added copyright header
24 * Revision 1.4 2002/06/05 08:05:28 relnev
25 * stub/warning removal.
27 * reworked the sound code.
29 * Revision 1.3 2002/05/28 08:52:03 relnev
30 * implemented two assembly stubs.
32 * cleaned up a few warnings.
34 * added a little demo hackery to make it progress a little farther.
36 * Revision 1.2 2002/05/28 06:28:20 theoddone33
37 * Filesystem mods, actually reads some data files now
39 * Revision 1.1.1.1 2002/05/03 03:28:08 root
43 * 20 9/08/99 10:01p Dave
44 * Make sure game won't run in a drive's root directory. Make sure
45 * standalone routes suqad war messages properly to the host.
47 * 19 9/08/99 12:03a Dave
48 * Make squad logos render properly in D3D all the time. Added intel anim
51 * 18 9/06/99 2:35p Dave
52 * Rename briefing and debriefing voice direcrory paths properly.
54 * 17 9/03/99 1:31a Dave
55 * CD checking by act. Added support to play 2 cutscenes in a row
56 * seamlessly. Fixed super low level cfile bug related to files in the
57 * root directory of a CD. Added cheat code to set campaign mission # in
60 * 16 8/31/99 9:46a Dave
61 * Support for new cfile cbanims directory.
63 * 15 8/06/99 11:20a Johns
64 * Don't call game_cd_changed() in a demo or multiplayer beta build.
66 * 14 6/08/99 2:33p Dave
67 * Fixed release build warning. Put in hud config stuff.
69 * 13 5/19/99 4:07p Dave
70 * Moved versioning code into a nice isolated common place. Fixed up
71 * updating code on the pxo screen. Fixed several stub problems.
73 * 12 4/30/99 12:18p Dave
74 * Several minor bug fixes.
76 * 11 4/07/99 5:54p Dave
77 * Fixes for encryption in updatelauncher.
79 * 10 3/28/99 5:58p Dave
80 * Added early demo code. Make objects move. Nice and framerate
81 * independant, but not much else. Don't use yet unless you're me :)
83 * 9 2/22/99 10:31p Andsager
84 * Get rid of unneeded includes.
86 * 8 1/12/99 3:15a Dave
87 * Barracks screen support for selecting squad logos. We need real artwork
90 * 7 11/30/98 1:07p Dave
91 * 16 bit conversion, first run.
93 * 6 10/29/98 10:41a Dave
94 * Change the way cfile initializes exe directory.
96 * 5 10/13/98 9:19a Andsager
97 * Add localization support to cfile. Optional parameter with cfopen that
98 * looks for localized files.
100 * 4 10/12/98 9:54a Dave
101 * Fixed a few file organization things.
103 * 3 10/07/98 6:27p Dave
104 * Globalized mission and campaign file extensions. Removed Silent Threat
105 * special code. Moved \cache \players and \multidata into the \data
108 * 2 10/07/98 10:52a Dave
111 * 1 10/07/98 10:48a Dave
113 * 110 9/17/98 10:31a Hoffoss
114 * Changed code to use location of executable as root rather than relying
115 * on the cwd being set correctly. This is most helpful in the case of
116 * Fred launching due to the user double-clicking on an .fsm file in
117 * explorer or something (where the cwd is probably the location of the
120 * 109 9/11/98 4:14p Dave
121 * Fixed file checksumming of < file_size. Put in more verbose kicking and
122 * PXO stats store reporting.
124 * 108 9/09/98 5:53p Dave
125 * Put in new tracker packets in API. Change cfile to be able to checksum
126 * portions of a file.
128 * 107 9/04/98 3:51p Dave
129 * Put in validated mission updating and application during stats
132 * 106 8/31/98 2:06p Dave
133 * Make cfile sort the ordering or vp files. Added support/checks for
134 * recognizing "mission disk" players.
136 * 105 8/20/98 5:30p Dave
137 * Put in handy multiplayer logfile system. Now need to put in useful
138 * applications of it all over the code.
140 * 104 8/12/98 4:53p Dave
141 * Put in 32 bit checksumming for PXO missions. No validation on the
142 * actual tracker yet, though.
144 * 103 6/17/98 9:30a Allender
145 * fixed red alert replay stats clearing problem
147 * 102 6/05/98 9:46a Lawrance
148 * check for CD change on cfopen()
150 * 101 5/19/98 1:19p Allender
151 * new low level reliable socket reading code. Make all missions/campaign
152 * load/save to data missions folder (i.e. we are rid of the player
155 * 100 5/13/98 10:22p John
156 * Added cfile functions to read/write rle compressed blocks of data.
157 * Made palman use it for .clr files. Made alphacolors calculate on the
158 * fly rather than caching to/from disk.
160 * 99 5/11/98 10:59a John
161 * Moved the low-level file reading code into cfilearchive.cpp.
163 * 98 5/06/98 5:30p John
164 * Removed unused cfilearchiver. Removed/replaced some unused/little used
165 * graphics functions, namely gradient_h and _v and pixel_sp. Put in new
166 * DirectX header files and libs that fixed the Direct3D alpha blending
169 * 97 5/03/98 11:53a John
170 * Fixed filename case mangling.
172 * 96 5/03/98 8:33a John
173 * Made sure there weren't any more broken function lurking around like
174 * the one Allender fixed.
176 * 95 5/02/98 11:05p Allender
177 * fix cfilelength for pack files
182 #define _CFILE_INTERNAL
192 #include <winbase.h> /* needed for memory mapping of file functions */
195 #include <sys/stat.h>
196 #include <sys/types.h>
202 //#include "outwnd.h"
203 //#include "vecmat.h"
205 #include "cfilesystem.h"
206 #include "cfilearchive.h"
209 char Cfile_root_dir[CFILE_ROOT_DIRECTORY_LEN] = "";
211 // During cfile_init, verify that Pathtypes[n].index == n for each item
212 // Each path must have a valid parent that can be tracable all the way back to the root
213 // so that we can create directories when we need to.
215 cf_pathtype Pathtypes[CF_MAX_PATH_TYPES] = {
216 // What type this is Path Extensions Parent type
217 { CF_TYPE_INVALID, NULL, NULL, CF_TYPE_INVALID },
218 // Root must be index 1!!
219 { CF_TYPE_ROOT, "", ".mve", CF_TYPE_ROOT },
220 { CF_TYPE_DATA, "Data", ".cfg .log .txt", CF_TYPE_ROOT },
222 { CF_TYPE_MAPS, "Data/Maps", ".pcx .ani .tga", CF_TYPE_DATA },
223 { CF_TYPE_TEXT, "Data/Text", ".txt .net", CF_TYPE_DATA },
224 { CF_TYPE_MISSIONS, "Data/Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
225 { CF_TYPE_MODELS, "Data/Models", ".pof", CF_TYPE_DATA },
226 { CF_TYPE_TABLES, "Data/Tables", ".tbl", CF_TYPE_DATA },
227 { CF_TYPE_SOUNDS, "Data/Sounds", ".wav", CF_TYPE_DATA },
228 { CF_TYPE_SOUNDS_8B22K, "Data/Sounds/8b22k", ".wav", CF_TYPE_SOUNDS },
229 { CF_TYPE_SOUNDS_16B11K, "Data/Sounds/16b11k", ".wav", CF_TYPE_SOUNDS },
230 { CF_TYPE_VOICE, "Data/Voice", "", CF_TYPE_DATA },
231 { CF_TYPE_VOICE_BRIEFINGS, "Data/Voice/Briefing", ".wav", CF_TYPE_VOICE },
232 { CF_TYPE_VOICE_CMD_BRIEF, "Data/Voice/Command_briefings",".wav", CF_TYPE_VOICE },
233 { CF_TYPE_VOICE_DEBRIEFINGS, "Data/Voice/Debriefing", ".wav", CF_TYPE_VOICE },
234 { CF_TYPE_VOICE_PERSONAS, "Data/Voice/Personas", ".wav", CF_TYPE_VOICE },
235 { CF_TYPE_VOICE_SPECIAL, "Data/Voice/Special", ".wav", CF_TYPE_VOICE },
236 { CF_TYPE_VOICE_TRAINING, "Data/Voice/Training", ".wav", CF_TYPE_VOICE },
237 { CF_TYPE_MUSIC, "Data/Music", ".wav", CF_TYPE_VOICE },
238 { CF_TYPE_MOVIES, "Data/Movies", ".mve .msb", CF_TYPE_DATA },
239 { CF_TYPE_INTERFACE, "Data/Interface", ".pcx .ani .tga", CF_TYPE_DATA },
240 { CF_TYPE_FONT, "Data/Fonts", ".vf", CF_TYPE_DATA },
241 { CF_TYPE_EFFECTS, "Data/Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
242 { CF_TYPE_HUD, "Data/Hud", ".ani .pcx .tga", CF_TYPE_DATA },
243 { CF_TYPE_PLAYER_MAIN, "Data/Players", "", CF_TYPE_DATA },
244 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data/Players/Images", ".pcx", CF_TYPE_PLAYER_MAIN },
245 { CF_TYPE_CACHE, "Data/Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
246 { CF_TYPE_PLAYERS, "Data/Players", ".hcf", CF_TYPE_DATA },
247 { CF_TYPE_SINGLE_PLAYERS, "Data/Players/Single", ".plr .csg .css", CF_TYPE_PLAYERS },
248 { CF_TYPE_MULTI_PLAYERS, "Data/Players/Multi", ".plr", CF_TYPE_DATA },
249 { CF_TYPE_MULTI_CACHE, "Data/MultiData", ".pcx .fs2", CF_TYPE_DATA },
250 { CF_TYPE_CONFIG, "Data/Config", ".cfg", CF_TYPE_DATA },
251 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data/Players/Squads", ".pcx", CF_TYPE_DATA },
252 { CF_TYPE_DEMOS, "Data/Demos", ".fsd", CF_TYPE_DATA },
253 { CF_TYPE_CBANIMS, "Data/CBAnims", ".ani", CF_TYPE_DATA },
254 { CF_TYPE_INTEL_ANIMS, "Data/IntelAnims", ".ani", CF_TYPE_DATA },
256 { CF_TYPE_MAPS, "Data\\Maps", ".pcx .ani .tga", CF_TYPE_DATA },
257 { CF_TYPE_TEXT, "Data\\Text", ".txt .net", CF_TYPE_DATA },
258 { CF_TYPE_MISSIONS, "Data\\Missions", ".fs2 .fc2 .ntl .ssv", CF_TYPE_DATA },
259 { CF_TYPE_MODELS, "Data\\Models", ".pof", CF_TYPE_DATA },
260 { CF_TYPE_TABLES, "Data\\Tables", ".tbl", CF_TYPE_DATA },
261 { CF_TYPE_SOUNDS, "Data\\Sounds", ".wav", CF_TYPE_DATA },
262 { CF_TYPE_SOUNDS_8B22K, "Data\\Sounds\\8b22k", ".wav", CF_TYPE_SOUNDS },
263 { CF_TYPE_SOUNDS_16B11K, "Data\\Sounds\\16b11k", ".wav", CF_TYPE_SOUNDS },
264 { CF_TYPE_VOICE, "Data\\Voice", "", CF_TYPE_DATA },
265 { CF_TYPE_VOICE_BRIEFINGS, "Data\\Voice\\Briefing", ".wav", CF_TYPE_VOICE },
266 { CF_TYPE_VOICE_CMD_BRIEF, "Data\\Voice\\Command_briefings",".wav", CF_TYPE_VOICE },
267 { CF_TYPE_VOICE_DEBRIEFINGS, "Data\\Voice\\Debriefing", ".wav", CF_TYPE_VOICE },
268 { CF_TYPE_VOICE_PERSONAS, "Data\\Voice\\Personas", ".wav", CF_TYPE_VOICE },
269 { CF_TYPE_VOICE_SPECIAL, "Data\\Voice\\Special", ".wav", CF_TYPE_VOICE },
270 { CF_TYPE_VOICE_TRAINING, "Data\\Voice\\Training", ".wav", CF_TYPE_VOICE },
271 { CF_TYPE_MUSIC, "Data\\Music", ".wav", CF_TYPE_VOICE },
272 { CF_TYPE_MOVIES, "Data\\Movies", ".mve .msb", CF_TYPE_DATA },
273 { CF_TYPE_INTERFACE, "Data\\Interface", ".pcx .ani .tga", CF_TYPE_DATA },
274 { CF_TYPE_FONT, "Data\\Fonts", ".vf", CF_TYPE_DATA },
275 { CF_TYPE_EFFECTS, "Data\\Effects", ".ani .pcx .neb .tga", CF_TYPE_DATA },
276 { CF_TYPE_HUD, "Data\\Hud", ".ani .pcx .tga", CF_TYPE_DATA },
277 { CF_TYPE_PLAYER_MAIN, "Data\\Players", "", CF_TYPE_DATA },
278 { CF_TYPE_PLAYER_IMAGES_MAIN, "Data\\Players\\Images", ".pcx", CF_TYPE_PLAYER_MAIN },
279 { CF_TYPE_CACHE, "Data\\Cache", ".clr .tmp", CF_TYPE_DATA }, //clr=cached color
280 { CF_TYPE_PLAYERS, "Data\\Players", ".hcf", CF_TYPE_DATA },
281 { CF_TYPE_SINGLE_PLAYERS, "Data\\Players\\Single", ".plr .csg .css", CF_TYPE_PLAYERS },
282 { CF_TYPE_MULTI_PLAYERS, "Data\\Players\\Multi", ".plr", CF_TYPE_DATA },
283 { CF_TYPE_MULTI_CACHE, "Data\\MultiData", ".pcx .fs2", CF_TYPE_DATA },
284 { CF_TYPE_CONFIG, "Data\\Config", ".cfg", CF_TYPE_DATA },
285 { CF_TYPE_SQUAD_IMAGES_MAIN, "Data\\Players\\Squads", ".pcx", CF_TYPE_DATA },
286 { CF_TYPE_DEMOS, "Data\\Demos", ".fsd", CF_TYPE_DATA },
287 { CF_TYPE_CBANIMS, "Data\\CBAnims", ".ani", CF_TYPE_DATA },
288 { CF_TYPE_INTEL_ANIMS, "Data\\IntelAnims", ".ani", CF_TYPE_DATA },
293 #define CFILE_STACK_MAX 8
295 int cfile_inited = 0;
296 int Cfile_stack_pos = 0;
298 char Cfile_stack[128][CFILE_STACK_MAX];
300 Cfile_block Cfile_block_list[MAX_CFILE_BLOCKS];
301 CFILE Cfile_list[MAX_CFILE_BLOCKS];
303 char *Cfile_cdrom_dir = NULL;
306 // Function prototypes for internally-called functions
308 int cfget_cfile_block();
309 CFILE *cf_open_fill_cfblock(FILE * fp, int type);
310 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size);
311 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type);
312 void cf_chksum_long_init();
316 cf_free_secondary_filelist();
319 // determine if the given path is in a root directory (c:\ or c:\freespace2.exe or c:\fred2.exe etc)
320 int cfile_in_root_dir(char *exe_path)
323 char path_copy[2048] = "";
327 if(exe_path == NULL){
332 memset(path_copy, 0, 2048);
333 strncpy(path_copy, exe_path, 2047);
335 // count how many slashes there are in the path
337 tok = strtok(path_copy, "/");
339 tok = strtok(path_copy, "\\");
347 tok = strtok(NULL, "/");
349 tok = strtok(NULL, "\\");
351 } while(tok != NULL);
353 // root directory if we have <= 1 slash
354 if(token_count <= 2){
358 // not-root directory
362 // cfile_init() initializes the cfile system. Called once at application start.
364 // returns: success ==> 0
365 // error ==> non-zero
367 int cfile_init(char *exe_dir, char *cdrom_dir)
371 // initialize encryption
374 if ( !cfile_inited ) {
379 strcpy(buf, exe_dir);
382 // are we in a root directory?
383 if(cfile_in_root_dir(buf)){
385 fprintf (stderr, "ERROR: Freespace2/Fred2 cannot be run from a drive root directory!\n");
387 MessageBox((HWND)NULL, "Freespace2/Fred2 cannot be run from a drive root directory!", "Error", MB_OK);
407 fprintf (stderr, "Error trying to determine executable root directory!");
409 MessageBox((HWND)NULL, "Error trying to determine executable root directory!", "Error", MB_OK);
414 // set root directory
415 strncpy(Cfile_root_dir, buf, CFILE_ROOT_DIRECTORY_LEN-1);
417 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
418 Cfile_block_list[i].type = CFILE_BLOCK_UNUSED;
421 Cfile_cdrom_dir = cdrom_dir;
422 cf_build_secondary_filelist(Cfile_cdrom_dir);
424 // 32 bit CRC table init
425 cf_chksum_long_init();
427 atexit( cfile_close );
433 // Call this if pack files got added or removed or the
434 // cdrom changed. This will refresh the list of filenames
435 // stored in packfiles and on the cdrom.
438 cf_build_secondary_filelist(Cfile_cdrom_dir);
442 // Changes to a drive if valid.. 1=A, 2=B, etc
443 // If flag, then changes to it.
444 // Returns 0 if not-valid, 1 if valid.
445 int cfile_chdrive( int DriveNum, int flag )
458 _chdrive( DriveNum );
465 if ( (!flag) && (n != org) )
471 // push current directory on a 'stack' (so we can restore it) and change the directory
472 int cfile_push_chdir(int type)
476 char OriginalDirectory[128];
478 char NoDir[] = "\\.";
480 _getcwd(OriginalDirectory, 127);
481 Assert(Cfile_stack_pos < CFILE_STACK_MAX);
482 strcpy(Cfile_stack[Cfile_stack_pos++], OriginalDirectory);
484 cf_create_default_path_string( dir, type, NULL );
487 char *Drive = strchr(dir, ':');
490 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
505 // This chdir might get a critical error!
508 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
516 int cfile_chdir(char *dir)
519 char OriginalDirectory[128];
521 char NoDir[] = "\\.";
523 _getcwd(OriginalDirectory, 127);
527 char *Drive = strchr(dir, ':');
529 if (!cfile_chdrive( *(Drive - 1) - 'a' + 1, 1))
544 // This chdir might get a critical error!
547 cfile_chdrive( OriginalDirectory[0] - 'a' + 1, 1 );
556 Assert(Cfile_stack_pos);
558 return cfile_chdir(Cfile_stack[Cfile_stack_pos]);
561 // flush (delete all files in) the passed directory (by type), return the # of files deleted
562 // NOTE : WILL NOT DELETE READ-ONLY FILES
563 int cfile_flush_dir(int dir_type)
573 Assert( CF_TYPE_SPECIFIED(dir_type) );
575 // attempt to change the directory to the passed type
576 if(cfile_push_chdir(dir_type)){
580 // proceed to delete the files
581 find_handle = _findfirst( "*", &find );
583 if (find_handle != -1) {
585 if (!(find.attrib & _A_SUBDIR) && !(find.attrib & _A_RDONLY)) {
587 cf_delete(find.name,dir_type);
589 // increment the deleted count
592 } while (!_findnext(find_handle, &find));
593 _findclose( find_handle );
596 // pop the directory back
599 // return the # of files deleted
605 // add the given extention to a filename (or filepath) if it doesn't already have this
607 // filename = name of filename or filepath to process
608 // ext = extension to add. Must start with the period
609 // Returns: new filename or filepath with extension.
610 char *cf_add_ext(char *filename, char *ext)
613 static char path[MAX_PATH_LEN];
615 flen = strlen(filename);
617 Assert(flen < MAX_PATH_LEN);
618 strcpy(path, filename);
619 if ((flen < 4) || stricmp(path + flen - elen, ext)) {
620 Assert(flen + elen < MAX_PATH_LEN);
628 void cf_delete( char *filename, int dir_type )
630 char longname[MAX_PATH_LEN];
632 Assert( CF_TYPE_SPECIFIED(dir_type) );
634 cf_create_default_path_string( longname, dir_type, filename );
636 FILE *fp = fopen(longname, "rb");
646 // Same as _access function to read a file's access bits
647 int cf_access( char *filename, int dir_type, int mode )
649 char longname[MAX_PATH_LEN];
651 Assert( CF_TYPE_SPECIFIED(dir_type) );
653 cf_create_default_path_string( longname, dir_type, filename );
655 return access(longname,mode);
659 // Returns 1 if file exists, 0 if not.
660 int cf_exist( char *filename, int dir_type )
662 char longname[MAX_PATH_LEN];
664 Assert( CF_TYPE_SPECIFIED(dir_type) );
666 cf_create_default_path_string( longname, dir_type, filename );
668 FILE *fp = fopen(longname, "rb");
677 void cf_attrib(char *filename, int set, int clear, int dir_type)
679 char longname[MAX_PATH_LEN];
681 Assert( CF_TYPE_SPECIFIED(dir_type) );
683 cf_create_default_path_string( longname, dir_type, filename );
685 FILE *fp = fopen(longname, "rb");
692 DWORD z = GetFileAttributes(longname);
693 SetFileAttributes(longname, z | set & ~clear);
699 int cf_rename(char *old_name, char *name, int dir_type)
701 Assert( CF_TYPE_SPECIFIED(dir_type) );
704 char old_longname[_MAX_PATH];
705 char new_longname[_MAX_PATH];
707 cf_create_default_path_string( old_longname, dir_type, old_name );
708 cf_create_default_path_string( new_longname, dir_type, name );
710 ret_code = rename(old_longname, new_longname );
714 return CF_RENAME_FAIL_ACCESS;
717 return CF_RENAME_FAIL_EXIST;
721 return CF_RENAME_SUCCESS;
726 // Creates the directory path if it doesn't exist. Even creates all its
728 void cf_create_directory( int dir_type )
731 int dir_tree[CF_MAX_PATH_TYPES];
732 char longname[MAX_PATH_LEN];
734 Assert( CF_TYPE_SPECIFIED(dir_type) );
736 int current_dir = dir_type;
739 Assert( num_dirs < CF_MAX_PATH_TYPES ); // Invalid Pathtypes data?
741 dir_tree[num_dirs++] = current_dir;
742 current_dir = Pathtypes[current_dir].parent_index;
744 } while( current_dir != CF_TYPE_ROOT );
749 for (i=num_dirs-1; i>=0; i-- ) {
750 cf_create_default_path_string( longname, dir_tree[i], NULL );
753 if ( _mkdir(longname, 0777)==0 ) {
754 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
757 if ( _mkdir(longname)==0 ) {
758 mprintf(( "CFILE: Created new directory '%s'\n", longname ));
767 extern int game_cd_changed();
771 // parameters: *filepath ==> name of file to open (may be path+name)
772 // *mode ==> specifies how file should be opened (eg "rb" for read binary)
773 // passing NULL to mode deletes the file if it exists and returns NULL
774 // type ==> one of: CFILE_NORMAL
775 // CFILE_MEMORY_MAPPED
776 // dir_type => override extension check, value is one of CF_TYPE* #defines
778 // NOTE: type parameter is an optional parameter. The default value is CFILE_NORMAL
781 // returns: success ==> address of CFILE structure
785 CFILE *cfopen(char *file_path, char *mode, int type, int dir_type, bool localize)
787 char longname[_MAX_PATH];
789 // nprintf(("CFILE", "CFILE -- trying to open %s\n", file_path ));
790 // #if !defined(MULTIPLAYER_BETA_BUILD) && !defined(FS2_DEMO)
792 // we no longer need to do this, and on machines with crappy-ass drivers it can slow things down horribly.
794 if ( game_cd_changed() ) {
799 //================================================
800 // Check that all the parameters make sense
801 Assert(file_path && strlen(file_path));
802 Assert( mode != NULL );
804 // Can only open read-only binary files in memory mapped mode.
805 if ( (type & CFILE_MEMORY_MAPPED) && strcmp(mode,"rb") ) {
810 //===========================================================
811 // If in write mode, just try to open the file straight off
812 // the harddisk. No fancy packfile stuff here!
814 if ( strchr(mode,'w') ) {
815 // For write-only files, require a full path or a path type
816 if ( strpbrk(file_path,"/\\:") ) {
818 strcpy(longname, file_path );
821 Assert( dir_type != CF_TYPE_ANY );
823 // Create the directory if necessary
824 cf_create_directory( dir_type );
826 cf_create_default_path_string( longname, dir_type, file_path );
828 Assert( !(type & CFILE_MEMORY_MAPPED) );
830 // JOHN: TODO, you should create the path if it doesn't exist.
832 FILE *fp = fopen(longname, mode);
834 return cf_open_fill_cfblock(fp, dir_type);
840 //================================================
841 // Search for file on disk, on cdrom, or in a packfile
844 char copy_file_path[MAX_PATH_LEN]; // FIX change in memory from cf_find_file_location
845 strcpy(copy_file_path, file_path);
848 if ( cf_find_file_location( copy_file_path, dir_type, longname, &size, &offset, localize ) ) {
850 // Fount it, now create a cfile out of it
852 if ( type & CFILE_MEMORY_MAPPED ) {
854 // Can't open memory mapped files out of pack files
861 hFile = CreateFile(longname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
863 if (hFile != INVALID_HANDLE_VALUE) {
864 return cf_open_mapped_fill_cfblock(hFile, dir_type);
871 FILE *fp = fopen( longname, "rb" );
875 // Found it in a pack file
876 return cf_open_packed_cfblock(fp, dir_type, offset, size );
878 // Found it in a normal file
879 return cf_open_fill_cfblock(fp, dir_type);
890 // ------------------------------------------------------------------------
893 // Open up a temporary file. A unique name is automatically generated. The
894 // file will be automatically deleted when file is closed.
896 // return: NULL => tmp file could not be opened
897 // pointer to CFILE => tmp file successfully opened
904 return cf_open_fill_cfblock(fp, 0);
911 // cfget_cfile_block() will try to find an empty Cfile_block structure in the
912 // Cfile_block_list[] array and return the index.
914 // returns: success ==> index in Cfile_block_list[] array
917 int cfget_cfile_block()
922 for ( i = 0; i < MAX_CFILE_BLOCKS; i++ ) {
923 cb = &Cfile_block_list[i];
924 if ( cb->type == CFILE_BLOCK_UNUSED ) {
927 cb->type = CFILE_BLOCK_USED;
932 // If we've reached this point, a free Cfile_block could not be found
933 nprintf(("Warning","A free Cfile_block could not be found.\n"));
934 Assert(0); // out of free cfile blocks
939 // cfclose() closes the file
941 // returns: success ==> 0
944 int cfclose( CFILE * cfile )
948 Assert(cfile != NULL);
950 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
951 cb = &Cfile_block_list[cfile->id];
955 // close memory mapped file
959 result = UnmapViewOfFile((void*)cb->data);
961 result = CloseHandle(cb->hInFile);
962 Assert(result); // Ensure file handle is closed properly
963 result = CloseHandle(cb->hMapFile);
964 Assert(result); // Ensure file handle is closed properly
968 } else if ( cb->fp != NULL ) {
969 Assert(cb->fp != NULL);
970 result = fclose(cb->fp);
975 cb->type = CFILE_BLOCK_UNUSED;
982 // cf_open_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
983 // for the case of a file being opened by cf_open();
985 // returns: success ==> ptr to CFILE structure.
988 CFILE *cf_open_fill_cfblock(FILE *fp, int type)
990 int cfile_block_index;
992 cfile_block_index = cfget_cfile_block();
993 if ( cfile_block_index == -1 ) {
998 cfbp = &Cfile_block_list[cfile_block_index];
999 cfp = &Cfile_list[cfile_block_index];;
1000 cfp->id = cfile_block_index;
1004 cfbp->dir_type = type;
1006 cf_init_lowlevel_read_code(cfp,0,filelength(fileno(fp)) );
1013 // cf_open_packed_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1014 // for the case of a file being opened by cf_open();
1016 // returns: success ==> ptr to CFILE structure.
1019 CFILE *cf_open_packed_cfblock(FILE *fp, int type, int offset, int size)
1021 // Found it in a pack file
1022 int cfile_block_index;
1024 cfile_block_index = cfget_cfile_block();
1025 if ( cfile_block_index == -1 ) {
1030 cfbp = &Cfile_block_list[cfile_block_index];
1032 cfp = &Cfile_list[cfile_block_index];
1033 cfp->id = cfile_block_index;
1037 cfbp->dir_type = type;
1039 cf_init_lowlevel_read_code(cfp,offset, size );
1048 // cf_open_mapped_fill_cfblock() will fill up a Cfile_block element in the Cfile_block_list[] array
1049 // for the case of a file being opened by cf_open_mapped();
1051 // returns: ptr CFILE structure.
1053 CFILE *cf_open_mapped_fill_cfblock(HANDLE hFile, int type)
1055 int cfile_block_index;
1057 cfile_block_index = cfget_cfile_block();
1058 if ( cfile_block_index == -1 ) {
1064 cfbp = &Cfile_block_list[cfile_block_index];
1066 cfp = &Cfile_list[cfile_block_index];
1067 cfp->id = cfile_block_index;
1069 cfbp->hInFile = hFile;
1070 cfbp->dir_type = type;
1072 cf_init_lowlevel_read_code(cfp,0 , 0 );
1077 cfbp->hMapFile = CreateFileMapping(cfbp->hInFile, NULL, PAGE_READONLY, 0, 0, NULL);
1078 if (cfbp->hMapFile == NULL) {
1079 nprintf(("Error", "Could not create file-mapping object.\n"));
1083 cfbp->data = (ubyte*)MapViewOfFile(cfbp->hMapFile, FILE_MAP_READ, 0, 0, 0);
1084 Assert( cfbp->data != NULL );
1090 int cf_get_dir_type(CFILE *cfile)
1092 return Cfile_block_list[cfile->id].dir_type;
1095 // cf_returndata() returns the data pointer for a memory-mapped file that is associated
1096 // with the CFILE structure passed as a parameter
1100 void *cf_returndata(CFILE *cfile)
1102 Assert(cfile != NULL);
1104 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1105 cb = &Cfile_block_list[cfile->id];
1106 Assert(cb->data != NULL);
1112 // version number of opened file. Will be 0 unless you put something else here after you
1113 // open a file. Once set, you can use minimum version numbers with the read functions.
1114 void cf_set_version( CFILE * cfile, int version )
1116 Assert(cfile != NULL);
1118 cfile->version = version;
1121 // routines to read basic data types from CFILE's. Put here to
1122 // simplify mac/pc reading from cfiles.
1124 float cfread_float(CFILE *file, int ver, float deflt)
1128 if (file->version < ver)
1131 if (cfread( &f, sizeof(f), 1, file) != 1)
1134 // i = INTEL_INT(i); // hmm, not sure what to do here
1138 int cfread_int(CFILE *file, int ver, int deflt)
1142 if (file->version < ver)
1145 if (cfread( &i, sizeof(i), 1, file) != 1)
1152 uint cfread_uint(CFILE *file, int ver, uint deflt)
1156 if (file->version < ver)
1159 if (cfread( &i, sizeof(i), 1, file) != 1)
1166 short cfread_short(CFILE *file, int ver, short deflt)
1170 if (file->version < ver)
1173 if (cfread( &s, sizeof(s), 1, file) != 1)
1180 ushort cfread_ushort(CFILE *file, int ver, ushort deflt)
1184 if (file->version < ver)
1187 if (cfread( &s, sizeof(s), 1, file) != 1)
1194 ubyte cfread_ubyte(CFILE *file, int ver, ubyte deflt)
1198 if (file->version < ver)
1201 if (cfread( &b, sizeof(b), 1, file) != 1)
1207 void cfread_vector(vector *vec, CFILE *file, int ver, vector *deflt)
1209 if (file->version < ver) {
1213 vec->xyz.x = vec->xyz.y = vec->xyz.z = 0.0f;
1218 vec->xyz.x = cfread_float(file, ver, deflt ? deflt->xyz.x : 0.0f);
1219 vec->xyz.y = cfread_float(file, ver, deflt ? deflt->xyz.y : 0.0f);
1220 vec->xyz.z = cfread_float(file, ver, deflt ? deflt->xyz.z : 0.0f);
1223 void cfread_angles(angles *ang, CFILE *file, int ver, angles *deflt)
1225 if (file->version < ver) {
1229 ang->p = ang->b = ang->h = 0.0f;
1234 ang->p = cfread_float(file, ver, deflt ? deflt->p : 0.0f);
1235 ang->b = cfread_float(file, ver, deflt ? deflt->b : 0.0f);
1236 ang->h = cfread_float(file, ver, deflt ? deflt->h : 0.0f);
1239 char cfread_char(CFILE *file, int ver, char deflt)
1243 if (file->version < ver)
1246 if (cfread( &b, sizeof(b), 1, file) != 1)
1252 void cfread_string(char *buf, int n, CFILE *file)
1257 c = cfread_char(file);
1265 void cfread_string_len(char *buf,int n, CFILE *file)
1268 len = cfread_int(file);
1271 cfread(buf, len, 1, file);
1276 // equivalent write functions of above read functions follow
1278 int cfwrite_float(float f, CFILE *file)
1280 // i = INTEL_INT(i); // hmm, not sure what to do here
1281 return cfwrite(&f, sizeof(f), 1, file);
1284 int cfwrite_int(int i, CFILE *file)
1287 return cfwrite(&i, sizeof(i), 1, file);
1290 int cfwrite_uint(uint i, CFILE *file)
1293 return cfwrite(&i, sizeof(i), 1, file);
1296 int cfwrite_short(short s, CFILE *file)
1299 return cfwrite(&s, sizeof(s), 1, file);
1302 int cfwrite_ushort(ushort s, CFILE *file)
1305 return cfwrite(&s, sizeof(s), 1, file);
1308 int cfwrite_ubyte(ubyte b, CFILE *file)
1310 return cfwrite(&b, sizeof(b), 1, file);
1313 int cfwrite_vector(vector *vec, CFILE *file)
1315 if(!cfwrite_float(vec->xyz.x, file)){
1318 if(!cfwrite_float(vec->xyz.y, file)){
1321 return cfwrite_float(vec->xyz.z, file);
1324 int cfwrite_angles(angles *ang, CFILE *file)
1326 if(!cfwrite_float(ang->p, file)){
1329 if(!cfwrite_float(ang->b, file)){
1332 return cfwrite_float(ang->h, file);
1335 int cfwrite_char(char b, CFILE *file)
1337 return cfwrite( &b, sizeof(b), 1, file);
1340 int cfwrite_string(char *buf, CFILE *file)
1342 if ( (!buf) || (buf && !buf[0]) ) {
1343 return cfwrite_char(0, file);
1345 int len = strlen(buf);
1346 if(!cfwrite(buf, len, 1, file)){
1349 return cfwrite_char(0, file); // write out NULL termination
1352 int cfwrite_string_len(char *buf, CFILE *file)
1354 int len = strlen(buf);
1356 if(!cfwrite_int(len, file)){
1360 return cfwrite(buf,len,1,file);
1366 // Get the filelength
1367 int cfilelength( CFILE * cfile )
1369 Assert(cfile != NULL);
1371 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1372 cb = &Cfile_block_list[cfile->id];
1374 // TODO: return length of memory mapped file
1375 Assert( !cb->data );
1377 Assert(cb->fp != NULL);
1379 // cb->size gets set at cfopen
1383 // cfwrite() writes to the file
1385 // returns: number of full elements actually written
1388 int cfwrite(void *buf, int elsize, int nelem, CFILE *cfile)
1390 Assert(cfile != NULL);
1391 Assert(buf != NULL);
1396 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1397 cb = &Cfile_block_list[cfile->id];
1401 // cfwrite() not supported for memory-mapped files
1402 Assert( !cb->data );
1404 Assert(cb->fp != NULL);
1405 Assert(cb->lib_offset == 0 );
1406 result = fwrite(buf, elsize, nelem, cb->fp);
1412 // cfputc() writes a character to a file
1414 // returns: success ==> returns character written
1417 int cfputc(int c, CFILE *cfile)
1421 Assert(cfile != NULL);
1423 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1424 cb = &Cfile_block_list[cfile->id];
1427 // cfputc() not supported for memory-mapped files
1428 Assert( !cb->data );
1430 Assert(cb->fp != NULL);
1431 result = fputc(c, cb->fp);
1437 // cfgetc() reads a character from a file
1439 // returns: success ==> returns character read
1442 int cfgetc(CFILE *cfile)
1444 Assert(cfile != NULL);
1448 int result = cfread(&tmp, 1, 1, cfile );
1449 if ( result == 1 ) {
1462 // cfgets() reads a string from a file
1464 // returns: success ==> returns pointer to string
1467 char *cfgets(char *buf, int n, CFILE *cfile)
1469 Assert(cfile != NULL);
1470 Assert(buf != NULL);
1476 for (i=0; i<n-1; i++ ) {
1480 int ret = cfread( &tmp_c, 1, 1, cfile );
1490 } while ( c == 13 );
1492 if ( c=='\n' ) break;
1499 // cfputs() writes a string to a file
1501 // returns: success ==> non-negative value
1504 int cfputs(char *str, CFILE *cfile)
1506 Assert(cfile != NULL);
1507 Assert(str != NULL);
1510 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1511 cb = &Cfile_block_list[cfile->id];
1516 // cfputs() not supported for memory-mapped files
1517 Assert( !cb->data );
1518 Assert(cb->fp != NULL);
1519 result = fputs(str, cb->fp);
1525 // 16 and 32 bit checksum stuff ----------------------------------------------------------
1527 // CRC code for mission validation. given to us by Kevin Bentley on 7/20/98. Some sort of
1528 // checksumming code that he wrote a while ago.
1529 #define CRC32_POLYNOMIAL 0xEDB88320L
1530 unsigned long CRCTable[256];
1532 #define CF_CHKSUM_SAMPLE_SIZE 512
1534 // update cur_chksum with the chksum of the new_data of size new_data_size
1535 ushort cf_add_chksum_short(ushort seed, char *buffer, int size)
1537 ubyte * ptr = (ubyte *)buffer;
1538 unsigned int sum1,sum2;
1540 sum1 = sum2 = (int)(seed);
1544 if (sum1 >= 255 ) sum1 -= 255;
1549 return (unsigned short)((sum1<<8)+ sum2);
1552 // update cur_chksum with the chksum of the new_data of size new_data_size
1553 unsigned long cf_add_chksum_long(unsigned long seed, char *buffer, int size)
1557 unsigned long temp1;
1558 unsigned long temp2;
1560 p = (unsigned char*)buffer;
1564 temp1 = (crc>>8)&0x00FFFFFFL;
1565 temp2 = CRCTable[((int)crc^*p++)&0xff];
1572 void cf_chksum_long_init()
1577 for( i=0;i<=255;i++) {
1581 crc=(crc>>1)^CRC32_POLYNOMIAL;
1589 // single function convenient to use for both short and long checksums
1590 // NOTE : only one of chk_short or chk_long must be non-NULL (indicating which checksum to perform)
1591 int cf_chksum_do(CFILE *cfile, ushort *chk_short, uint *chk_long, int max_size)
1593 char cf_buffer[CF_CHKSUM_SAMPLE_SIZE];
1599 // determine whether we're doing a short or long checksum
1610 // if max_size is -1, set it to be the size of the file
1612 cfseek(cfile, 0, SEEK_SET);
1613 max_size = cfilelength(cfile);
1618 // determine how much we want to read
1619 if((max_size - cf_total) >= CF_CHKSUM_SAMPLE_SIZE){
1620 read_size = CF_CHKSUM_SAMPLE_SIZE;
1622 read_size = max_size - cf_total;
1625 // read in some buffer
1626 cf_len = cfread(cf_buffer, 1, read_size, cfile);
1628 // total we've read so far
1633 // do the proper short or long checksum
1635 *chk_long = cf_add_chksum_long(*chk_long, cf_buffer, cf_len);
1637 *chk_short = cf_add_chksum_short(*chk_short, cf_buffer, cf_len);
1640 } while((cf_len > 0) && (cf_total < max_size));
1645 // get the 2 byte checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1646 int cf_chksum_short(char *filename, ushort *chksum, int max_size, int cf_type)
1649 CFILE *cfile = NULL;
1651 // zero the checksum
1654 // attempt to open the file
1655 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1660 // call the overloaded cf_chksum function()
1661 ret_val = cf_chksum_do(cfile, chksum, NULL, max_size);
1663 // close the file down
1667 // return the result
1671 // get the 2 byte checksum of the passed file - return 0 if operation failed, 1 if succeeded
1672 // NOTE : preserves current file position
1673 int cf_chksum_short(CFILE *file, ushort *chksum, int max_size)
1678 // Returns current position of file.
1679 start_pos = cftell(file);
1680 if(start_pos == -1){
1684 // move to the beginning of the file
1685 if(cfseek(file, 0, CF_SEEK_SET)){
1688 ret_code = cf_chksum_do(file, chksum, NULL, max_size);
1689 // move back to the start position
1690 cfseek(file, start_pos, CF_SEEK_SET);
1695 // get the 32 bit CRC checksum of the passed filename - return 0 if operation failed, 1 if succeeded
1696 int cf_chksum_long(char *filename, uint *chksum, int max_size, int cf_type)
1699 CFILE *cfile = NULL;
1701 // zero the checksum
1704 // attempt to open the file
1705 cfile = cfopen(filename,"rt",CFILE_NORMAL,cf_type);
1710 // call the overloaded cf_chksum function()
1711 ret_val = cf_chksum_do(cfile, NULL, chksum, max_size);
1713 // close the file down
1717 // return the result
1721 // get the 32 bit CRC checksum of the passed file - return 0 if operation failed, 1 if succeeded
1722 // NOTE : preserves current file position
1723 int cf_chksum_long(CFILE *file, uint *chksum, int max_size)
1728 // Returns current position of file.
1729 start_pos = cftell(file);
1730 if(start_pos == -1){
1734 // move to the beginning of the file
1735 if(cfseek(file, 0, CF_SEEK_SET)){
1738 ret_code = cf_chksum_do(file, NULL, chksum, max_size);
1739 // move back to the start position
1740 cfseek(file, start_pos, CF_SEEK_SET);
1746 // Flush the open file buffer
1748 // exit: 0 - success
1750 int cflush(CFILE *cfile)
1752 Assert(cfile != NULL);
1754 Assert(cfile->id >= 0 && cfile->id < MAX_CFILE_BLOCKS);
1755 cb = &Cfile_block_list[cfile->id];
1757 // not supported for memory mapped files
1758 Assert( !cb->data );
1760 Assert(cb->fp != NULL);
1761 return fflush(cb->fp);