Redid the most of the file loading/saving. Now uses $HOME/.avp/ and

$AVP_DIR to look for files.
This commit is contained in:
Steven Fuller 2001-12-18 05:08:52 +00:00 committed by Patryk Obara
parent 95b8b49b76
commit 080430b3bd
40 changed files with 1400 additions and 1579 deletions

View file

@ -20,7 +20,7 @@ LDLIBS = -L/usr/X11R6/lib -lX11 -lXext -lGL `sdl-config --libs` -lopenal
AFLAGS = -g -w+macro-params -w+orphan-labels -w+number-overflow
ROOT = main.c mathline.c math.asm opengl.c net.c menus.c openal.c cdplayer.c winapi.c stubs.c frustum.c kshape.c map.c maths.c md5.c mem3dc.c mem3dcpp.cpp module.c morph.c object.c shpanim.c sphere.c tables.c vdb.c version.c
ROOT = main.c files.c winapi.c stubs.c version.c mathline.c math.asm opengl.c openal.c cdplayer.c menus.c net.c frustum.c kshape.c map.c maths.c md5.c mem3dc.c mem3dcpp.cpp module.c morph.c object.c shpanim.c sphere.c tables.c vdb.c
AVP = ai_sight.c avpview.c bh_agun.c bh_ais.c bh_alien.c bh_binsw.c bh_cable.c bh_corpse.c bh_deathvol.c bh_debri.c bh_dummy.c bh_fan.c bh_far.c bh_fhug.c bh_gener.c bh_ldoor.c bh_lift.c bh_light.c bh_lnksw.c bh_ltfx.c bh_marin.c bh_mission.c bh_near.c bh_pargen.c bh_plachier.c bh_plift.c bh_pred.c bh_queen.c bh_rubberduck.c bh_selfdest.c bh_snds.c bh_spcl.c bh_swdor.c bh_track.c bh_types.c bh_videoscreen.c bh_waypt.c bh_weap.c bh_xeno.c bonusabilities.c cconvars.cpp cdtrackselection.cpp cheatmodes.c comp_map.c comp_shp.c consolelog.cpp davehook.cpp deaths.c decal.c detaillevels.c dynamics.c dynblock.c equipmnt.c equiputl.cpp extents.c game.c game_statistics.c gamecmds.cpp gamevars.cpp hmodel.c hud.c inventry.c language.c lighting.c load_shp.c los.c maps.c mempool.c messagehistory.c missions.cpp movement.c paintball.c particle.c pfarlocs.c pheromon.c player.c pmove.c psnd.c psndproj.c pvisible.c savegame.c scream.cpp secstats.c sfx.c stratdef.c targeting.c track.c triggers.c weapons.c
SHAPES = cube.c
SUPPORT = consbind.cpp consbtch.cpp coordstr.cpp daemon.cpp indexfnt.cpp r2base.cpp r2pos666.cpp reflist.cpp refobj.cpp rentrntq.cpp scstring.cpp strtab.cpp strutil.c trig666.cpp wrapstr.cpp

39
README
View file

@ -11,8 +11,7 @@ end users." Hopefully this status will change in the not-so-distant future.
(Please see note below regarding installation/running.)
Obviously this README is totally incomplete, and will probably remain so for
@ -42,12 +41,29 @@ If you are wanting to run the Alien demo (the installer is an .exe but you
can just use unzip to extract the files from the .exe), add -DALIEN_DEMO to
the CFLAGS line (the one that's uncommented) in the Makefile. Rename all game
files lowercase. Be sure to install SDL 1.2 (http://www.libsdl.org) with
OpenGL support, nasm 0.98, PhysicsFS 0.1.4 (http://icculus.org/physfs/),
and the latest OpenAL CVS (http://www.openal.org). AvP requires a 3D card
with OpenGL support.
OpenGL support, nasm 0.98, and the latest OpenAL CVS (http://www.openal.org).
AvP requires a 3D card with OpenGL support.
Create the MPConfig and User_Profiles directories if they do not exist.
(Note: Windows profiles probably do not work in Linux and vice versa)
***
IMPORTANT:
AvP now uses $HOME/.avp/ to load/store configs, logs, etc.
NOTE: Windows profiles probably do not work in Linux and vice versa.
AvP will no longer use the current working directory to look for files. You
must either copy or symlink the AvP binary to the game data directory and run
that, or set AVP_DATA to the data directory.
Currently:
If you want to install the mappacks from
http://www.avpnews.com/files/avpfiles.html, install them with the rest of
the game data, not in ~/.avp/. Make sure everything is lowercase (although,
the maps in avp_rifs/Custom do not have to be totally lowercase, just the .rif
extension). Maybe in the future users will be able to install the files in
~/.avp/ also.
Hopefully all the necessary file loading changes were made. Please let me
know if something goes wrong.
***
If you have the regular edition, add -DREGULAR_EDITION to CFLAGS.
@ -64,14 +80,11 @@ have to uncomment a LDLIBS line in the Makefile.
relnev:~/avp/AvP Demo 3 - Alien$ ls
aenglish.txt alienavp_huds/ alienfastfile/ avp_rifs/ MPConfig/
User_Profiles/
aenglish.txt alienavp_huds/ alienfastfile/ avp_rifs/
relnev:~/avp/Gold Edition$ ls
avp_huds/ avp_rifs/ cd tracks.txt default.cfg fastfile/ language.txt
MPConfig/ User_Profiles/
avp_huds/ avp_rifs/ cd tracks.txt fastfile/ language.txt
Support for the demo is not quite complete (some sounds are missing and some
text is incorrect/missing).
Support for the demo is not quite complete (some sounds are missing).
Linux Port-specific commands:

View file

@ -112,8 +112,9 @@ void LoadCDTrackList()
//clear out the old list first
EmptyCDTrackList();
HANDLE file=CreateFile(CDTrackFileName,GENERIC_READ, 0, 0, OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0);
if(file==INVALID_HANDLE_VALUE)
FILE *file = OpenGameFile(CDTrackFileName, FILEMODE_READONLY, FILETYPE_OPTIONAL);
if(file==NULL)
{
LOGDXFMT(("Failed to open %s",CDTrackFileName));
return;
@ -121,13 +122,15 @@ void LoadCDTrackList()
char* buffer;
int file_size;
unsigned long bytes_read;
fseek(file, 0, SEEK_END);
file_size = ftell(file);
rewind(file);
//copy the file contents into a buffer
file_size= GetFileSize(file,0);
buffer=new char[file_size+1];
ReadFile(file,buffer,file_size,&bytes_read,0);
CloseHandle(file);
fread(buffer, 1, file_size, file);
fclose(file);
char* bufferptr=buffer;

View file

@ -511,10 +511,10 @@ void Sound_Play(SOUNDINDEX soundNumber, char *format, ...)
if(loop) ActiveSounds[newIndex].loop = 1;
else ActiveSounds[newIndex].loop = 0;
/*
printf("Play: new = %d. num = %d, p = %d, v = %d, pi = %d, l = %d, mi = %d, rev = %d\n", newIndex, soundNumber, priority, volume, pitch, loop, marine_ignore, reverb_off);
printf("Play: %d %d %s l:%d\n", newIndex, soundNumber, GameSounds[soundNumber].wavName, loop);
*/
#if 0
fprintf(stderr, "PSND: Play: new = %d. num = %d, p = %d, v = %d, pi = %d, l = %d, mi = %d, rev = %d\n", newIndex, soundNumber, priority, volume, pitch, loop, marine_ignore, reverb_off);
fprintf(stderr, "PSND: Play: %d %d %s l:%d\n", newIndex, soundNumber, GameSounds[soundNumber].wavName, loop);
#endif
if(worldPosn)
{
@ -562,8 +562,10 @@ printf("Play: %d %d %s l:%d\n", newIndex, soundNumber, GameSounds[soundNumber].w
// //sound starts part of the way in
// IDirectSoundBuffer_SetCurrentPosition(ActiveSounds[newIndex].dsBufferP,soundStartPosition);
// }
#if 0 /* TODO */
if (soundStartPosition)
fprintf(stderr, "Sound_Play: sound starts part of the way in (%d)\n", soundStartPosition);
#endif
}
void Sound_Stop(int activeSoundNumber)
@ -590,9 +592,11 @@ void Sound_Stop(int activeSoundNumber)
/* stop the sound: it may have already stopped, of course, but never mind */
PlatStopSound(activeSoundNumber);
/*
printf("Stop: %d %d %s\n", activeSoundNumber, soundNo, GameSounds[soundNo].wavName);
*/
#if 0
fprintf(stderr, "PSND: Stop: %d %d %s\n", activeSoundNumber, soundNo, GameSounds[soundNo].wavName);
#endif
/* release the active sound slot */
buf = ActiveSounds[activeSoundNumber].ds3DBufferP;
ActiveSounds[activeSoundNumber] = BlankActiveSound;
@ -853,8 +857,9 @@ void Save_SoundState(int* soundHandle)
// IDirectSoundBuffer_GetCurrentPosition(sound->dsBufferP,(LPDWORD)&block->position,NULL);
// else
block->position = 0;
#if 0 /* TODO */
fprintf(stderr, "Save_SoundState: GetCurrentPosition!\n");
#endif
strcpy((char*)(block+1),name);
}
@ -944,7 +949,9 @@ void Save_SoundsWithNoReference()
// IDirectSoundBuffer_GetCurrentPosition(sound->dsBufferP,(LPDWORD)&block->position,NULL);
// else
block->position = 0;
#if 0 /* TODO */
fprintf(stderr, "Save_SoundsWithNoReference: GetCurrentPosition!\n");
#endif
strcpy((char*)(block+1),name);
}

View file

@ -867,16 +867,14 @@ int FindAndLoadWavFile(int soundNum,char* wavFileName)
{
//check to see if file exists locally first
FILE* wavFile=fopen(sound_name,"rb");
FILE* wavFile = OpenGameFile(sound_name, FILEMODE_READONLY, FILETYPE_PERM);
if(!wavFile && SecondSoundDir)
{
//look for sound over network
sprintf (sound_name, "%s%s", SecondSoundDir,wavFileName);
wavFile=fopen(sound_name,"rb");
if(!wavFile)
{
wavFile = OpenGameFile(sound_name, FILEMODE_READONLY, FILETYPE_PERM);
if(!wavFile) {
LOGDXFMT(("Failed to find %s\n",wavFileName));
return 0;
}
@ -905,7 +903,7 @@ void *LoadRebSndFile(char *filename)
void *bufferPtr;
long int save_pos, size_of_file;
FILE *fp;
fp = fopen(filename,"rb");
fp = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_PERM);
if (!fp) goto error;

View file

@ -397,8 +397,7 @@ static BOOL SaveGameAllowed()
void SaveGame()
{
char filename[100];
HANDLE file;
DWORD bytes_written;
FILE *file;
int headerLength;
HuffmanPackage *packagePtr;
@ -456,34 +455,27 @@ void SaveGame()
SaveGameRequest = SAVELOAD_REQUEST_NONE;
//write the file
file = CreateFile(filename,GENERIC_WRITE, 0, 0, CREATE_ALWAYS,FILE_FLAG_RANDOM_ACCESS, 0);
file = OpenGameFile(filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (file == INVALID_HANDLE_VALUE)
if (file == NULL)
{
GLOBALASSERT("Error saving file"==0);
return;
}
WriteFile(file,SaveInfo.BufferStart,headerLength,&bytes_written,0);
fwrite(SaveInfo.BufferStart, headerLength, 1, file);
packagePtr = HuffmanCompression(SaveInfo.BufferStart+headerLength,SaveInfo.BufferSpaceUsed-headerLength);
WriteFile(file,packagePtr,packagePtr->CompressedDataSize+sizeof(HuffmanPackage),&bytes_written,0);
CloseHandle(file);
fwrite(packagePtr, packagePtr->CompressedDataSize+sizeof(HuffmanPackage), 1, file);
fclose(file);
NewOnScreenMessage(GetTextString(TEXTSTRING_SAVEGAME_GAMESAVED));
DisplaySavesLeft();
}
static void EndLoadGame()
{
@ -495,7 +487,6 @@ static void EndLoadGame()
LoadInfo.BufferPos = NULL;
LoadInfo.BufferSize = 0;
LoadInfo.BufferSpaceLeft = 0;
}
extern SAVE_SLOT_HEADER SaveGameSlot[];
@ -535,9 +526,8 @@ void LoadSavedGame()
{
SAVE_SLOT_HEADER* save_slot;
char filename[100];
HANDLE file;
FILE *file;
BOOL terminal_error = FALSE;
unsigned int bytes_read;
if(LoadGameRequest == SAVELOAD_REQUEST_NONE) return;
@ -576,31 +566,32 @@ void LoadSavedGame()
LoadGameRequest = SAVELOAD_REQUEST_NONE;
//load the file
file = CreateFile(filename,GENERIC_READ, 0, 0, OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0);
file = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_CONFIG);
if(file==INVALID_HANDLE_VALUE)
if(file==NULL)
{
//failed to load
EndLoadGame();
return;
}
LoadInfo.BufferSize = GetFileSize(file,0);
fseek(file, 0, SEEK_END);
LoadInfo.BufferSize = ftell(file);
rewind(file);
if(!LoadInfo.BufferSize)
{
CloseHandle(file);
fclose(file);
EndLoadGame();
return;
}
//allocate buffer , and read file into memory
LoadInfo.BufferStart = (char*) AllocateMem(LoadInfo.BufferSize);
ReadFile(file,LoadInfo.BufferStart,LoadInfo.BufferSize,(LPDWORD)&bytes_read,0);
CloseHandle(file);
fread(LoadInfo.BufferStart, LoadInfo.BufferSize, 1, file);
fclose(file);
LoadInfo.BufferPos = LoadInfo.BufferStart;
LoadInfo.BufferSpaceLeft = LoadInfo.BufferSize;
@ -1340,10 +1331,6 @@ static void SaveMiscGlobalStuff()
GetFMVInformation(&block->FMV_MessageNumber,&block->FMV_FrameNumber);
}
extern void DisplaySavesLeft()
{
char text [100];
@ -1353,9 +1340,6 @@ extern void DisplaySavesLeft()
NewOnScreenMessage(text);
}
extern void ResetNumberOfSaves()
{
switch(AvP.Difficulty)
@ -1370,7 +1354,7 @@ extern void ResetNumberOfSaves()
case I_Impossible :
NumberOfSavesLeft = NUM_SAVES_FOR_HARD_MODE;
break;
default:
break;
}
}

View file

@ -56,7 +56,6 @@ static CharacterSoundEffects QueenSounds={0,0,0,SID_NOSOUND};
//static SOUNDINDEX global_last_sound;
/* TODO: dir separator */
#if ALIEN_DEMO
#define ScreamFilePath "alienfastfile/"
#elif LOAD_SCREAMS_FROM_FASTFILES
@ -65,95 +64,6 @@ static CharacterSoundEffects QueenSounds={0,0,0,SID_NOSOUND};
#define ScreamFilePath "sound/"
#endif
#if 0
void LoadScreamSounds()
{
if(voice_types) return;
HANDLE file=CreateFile(ScreamFileName,GENERIC_READ, 0, 0, OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0);
if(file==INVALID_HANDLE_VALUE)
{
LOGDXFMT(("Failed to open %s",ScreamFileName));
return;
}
char* buffer;
int file_size;
unsigned long bytes_read;
file_size= GetFileSize(file,0);
buffer=new char[file_size+1];
ReadFile(file,buffer,file_size,&bytes_read,0);
CloseHandle(file);
if(strncmp("MARSOUND",buffer,8))
{
return;
}
char* bufpos=buffer+8;
num_voice_types=*(int*)bufpos;
bufpos+=4;
num_voice_cats=*(int*)bufpos;
bufpos+=4;
voice_types=(ScreamVoiceType*) PoolAllocateMem(num_voice_types * sizeof(ScreamVoiceType));
/* TODO: dir separator */
char wavpath[200]="npc/marinevoice/";
char* wavname=&wavpath[strlen(wavpath)];
for(int i=0;i<num_voice_types;i++)
{
voice_types[i].category=(ScreamSoundCategory*) PoolAllocateMem( num_voice_cats * sizeof(ScreamSoundCategory));
for(int j=0;j<num_voice_cats;j++)
{
ScreamSoundCategory* cat=&voice_types[i].category[j];
cat->last_sound=SID_NOSOUND;
cat->num_sounds=*(int*)bufpos;
bufpos+=4;
if(cat->num_sounds)
{
cat->sounds=(ScreamSound*) PoolAllocateMem(cat->num_sounds * sizeof(ScreamSound));
}
else
{
cat->sounds=0;
}
for(int k=0;k<cat->num_sounds;)
{
ScreamSound * sound=&cat->sounds[k];
strcpy(wavname,bufpos);
bufpos+=strlen(bufpos)+1;
sound->pitch=*(int*)bufpos;
bufpos+=4;
sound->volume=*(int*)bufpos;
bufpos+=4;
sound->sound_loaded=GetSound(wavpath);
if(sound->sound_loaded)
{
k++;
}
else
{
cat->num_sounds--;
}
}
}
}
delete [] buffer;
}
#endif
void CharacterSoundEffects::LoadSounds(const char* filename,const char* directory)
{
@ -162,8 +72,8 @@ void CharacterSoundEffects::LoadSounds(const char* filename,const char* director
char path[100]=ScreamFilePath;
strcat(path,filename);
HANDLE file=CreateFile(path,GENERIC_READ, 0, 0, OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0);
if(file==INVALID_HANDLE_VALUE)
FILE *file = OpenGameFile(path, FILEMODE_READONLY, FILETYPE_PERM);
if(file==NULL)
{
LOGDXFMT(("Failed to open %s",path));
return;
@ -171,12 +81,15 @@ void CharacterSoundEffects::LoadSounds(const char* filename,const char* director
char* buffer;
int file_size;
unsigned long bytes_read;
file_size= GetFileSize(file,0);
fseek(file, 0, SEEK_END);
file_size = ftell(file);
rewind(file);
buffer=new char[file_size+1];
ReadFile(file,buffer,file_size,&bytes_read,0);
CloseHandle(file);
fread(buffer, file_size, 1, file);
fclose(file);
if(strncmp("MARSOUND",buffer,8))
{
@ -347,7 +260,6 @@ void UnloadScreamSounds()
}
/* TODO: dir separator */
void LoadMarineScreamSounds()
{
MarineSounds.LoadSounds("marsound.dat","npc\\marinevoice\\");

View file

@ -53,19 +53,7 @@
#endif
extern unsigned char KeyboardInput[];
extern unsigned char DebouncedKeyboardInput[];
#if 0
extern OurBool DaveDebugOn;
extern FDIEXTENSIONTAG FDIET_Dummy;
extern IFEXTENSIONTAG IFET_Dummy;
extern FDIQUAD FDIQuad_WholeScreen;
extern FDIPOS FDIPos_Origin;
extern FDIPOS FDIPos_ScreenCentre;
extern IFOBJECTLOCATION IFObjLoc_Origin;
extern UncompressedGlobalPlotAtomID UGPAID_StandardNull;
extern IFCOLOUR IFColour_Dummy;
extern IFVECTOR IFVec_Zero;
#endif
#ifdef __cplusplus
};
#endif
@ -111,7 +99,8 @@ KeyBinding :: ParseBindCommand
SCString* pSCString_ToBind = new SCString(pProjCh_FollowingTheKey);
// Create the KeyBinding object:
KeyBinding* pNewBinding = new KeyBinding
KeyBinding* pNewBinding;
pNewBinding = new KeyBinding
(
theKey,
pSCString_ToBind
@ -185,7 +174,7 @@ KeyBinding :: ParseUnbindCommand
{
OurBool bGotMatch = No;
unsigned int LongestMatch = 0;
BindableKey theKey_ToUnbind;
BindableKey theKey_ToUnbind = (BindableKey)0;
for (int i=0;i<MAX_VALUE_BINDABLE_KEY; i++)
{
@ -384,7 +373,7 @@ void KeyBinding :: WriteToConfigFile(char* Filename)
GLOBALASSERT(Filename);
FILE* pFile = fopen(Filename,"w");
FILE* pFile = OpenGameFile(Filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (!pFile)
{

View file

@ -83,7 +83,7 @@ BatchFileProcessing :: Run(char* Filename)
RefList<SCString> PendingList;
{
FILE* pFile = fopen(Filename,"r");
FILE* pFile = OpenGameFile(Filename, FILEMODE_READONLY, FILETYPE_CONFIG);
if (NULL==pFile)
{

View file

@ -69,7 +69,7 @@ void ReportError(char const * mesg1, char const * mesg2)
/***************/
#define READ_FILE(fname,post_proc,on_return,h,data,n_bytes,n_bytes_read,p5) \
if (!ReadFile(h,data,n_bytes,&n_bytes_read,p5)) \
if ((n_bytes_read = fread(data, 1, n_bytes, h)) == 0) \
{ \
ReportError(fname); \
post_proc; \
@ -181,8 +181,6 @@ FFHeaderI::FFHeaderI(char const *_filename,BOOL _should_be_kept)
{
filename = new char [strlen(_filename) + 1];
strcpy(filename,_filename);
FixFilename(filename);
Read();
}
@ -280,9 +278,9 @@ FFError FFHeaderI::Read(char const *_filename)
strcpy(filename,_filename);
}
HANDLE h = CreateFile (filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
FILE *h = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_PERM);
if (INVALID_HANDLE_VALUE==h)
if (h == NULL)
{
ReportError(filename);
return FF_COULDNOTOPENFILE;
@ -298,40 +296,40 @@ FFError FFHeaderI::Read(char const *_filename)
DWORD bytes_read;
READ_FILE(filename,(void)0,CloseHandle(h),h,magic,4,bytes_read,0)
READ_FILE(filename,(void)0,CloseHandle(h),h,&rffl_version,4,bytes_read,0)
READ_FILE(filename,(void)0,CloseHandle(h),h,&num_files,4,bytes_read,0)
READ_FILE(filename,(void)0,CloseHandle(h),h,&total_headsize,4,bytes_read,0)
READ_FILE(filename,(void)0,CloseHandle(h),h,&length,4,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,magic,4,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,&rffl_version,4,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,&num_files,4,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,&total_headsize,4,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,&length,4,bytes_read,0)
if (strncmp(magic,"RFFL",4))
{
ReportError(filename,"Incorrect file type");
CloseHandle(h);
fclose(h);
return FF_COULDNOTREADFILE;
}
if (rffl_version>0)
{
ReportError(filename,"Version not supported");
CloseHandle(h);
fclose(h);
return FF_COULDNOTREADFILE;
}
void * header = malloc(total_headsize);
READ_FILE(filename,(void)0,CloseHandle(h),h,header,total_headsize,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,header,total_headsize,bytes_read,0)
data = malloc(length);
READ_FILE(filename,(void)0,CloseHandle(h),h,data,length,bytes_read,0)
READ_FILE(filename,(void)0,fclose(h),h,data,length,bytes_read,0)
CloseHandle(h);
fclose(h);
// now parse the header
void * headerP = header;
for (int i=0; i<num_files; ++i)
for (unsigned int i=0; i<num_files; ++i)
{
char const * fnameP = (char *)((size_t)headerP + 8);
size_t leng = *(size_t *)((size_t)headerP + 4);

View file

@ -54,7 +54,7 @@ FFileDesc::FFileDesc(char const * infoline, char const * path)
do
{
c2 = c1 = *infoline++;
if (';'==c1||'\n'==c1)
if (';'==c1||'\n'==c1||'\r'==c1)
c1 = 0;
*dbufP++ = (char)c1;
}
@ -65,7 +65,7 @@ FFileDesc::FFileDesc(char const * infoline, char const * path)
do
{
c1 = *infoline++;
if ('\n'==c1)
if ('\n'==c1||'\r'==c1)
c1 = 0;
*fbufP++ = (char)c1;
}
@ -158,7 +158,7 @@ static List<FFILE *> openlist;
int ffInit(char const * infofilename, char const * ffpath)
{
FILE * fp = fopen(infofilename,"r");
FILE * fp = OpenGameFile(infofilename, FILEMODE_READONLY, FILETYPE_PERM);
if (!fp) return 0;
while (fdesclist.size())
@ -370,7 +370,9 @@ FFILE * ffopen(char const * filename, char const * mode)
#if debug && 0 // dont do this, caller should handle this situation
LOGDXFMT(("%s not in any fastfile",filename));
FILE * sfp = fopen(filename,mode);
/* mode is always "rb" */
FILE *sfp = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_PERM);
if (!sfp) return 0;
fseek(sfp,0,SEEK_END);
@ -442,7 +444,7 @@ int ffseek(FFILE * fp, long offset, int whence)
switch (whence)
{
case SEEK_SET:
if (offset > fp->length || offset < 0)
if ((unsigned long)offset > fp->length || offset < 0)
{
fp->flag |= FFF_ERR;
errno = EDOM;

View file

@ -182,26 +182,25 @@ static char *RifNamesForEnvironments[] =
"Not a Level",//AVP_ENVIRONMENT_END_OF_LIST
//multipack multiplayer levels
"Leadworks",//AVP_ENVIRONMENT_LEADWORKS_MP,
"HadleysHope",//AVP_ENVIRONMENT_HADLEYSHOPE_MP,
"Meat_Factory",//AVP_ENVIRONMENT_MEATFACTORY_MP,
"Nostromo",//AVP_ENVIRONMENT_NOSTROMO_MP,
"Subway",//AVP_ENVIRONMENT_SUBWAY_MP,
"Elevator",//AVP_ENVIRONMENT_ELEVATOR_MP,
"Lab14",//AVP_ENVIRONMENT_LAB14_MP,
"Compound",//AVP_ENVIRONMENT_COMPOUND_MP,
"Office",//AVP_ENVIRONMENT_OFFICE_MP,
"leadworks",//AVP_ENVIRONMENT_LEADWORKS_MP,
"hadleyshope",//AVP_ENVIRONMENT_HADLEYSHOPE_MP,
"meat_factory",//AVP_ENVIRONMENT_MEATFACTORY_MP,
"nostromo",//AVP_ENVIRONMENT_NOSTROMO_MP,
"subway",//AVP_ENVIRONMENT_SUBWAY_MP,
"elevator",//AVP_ENVIRONMENT_ELEVATOR_MP,
"lab14",//AVP_ENVIRONMENT_LAB14_MP,
"compound",//AVP_ENVIRONMENT_COMPOUND_MP,
"office",//AVP_ENVIRONMENT_OFFICE_MP,
//multipack multiplayer cooperative levels
"Leadworks_coop",//AVP_ENVIRONMENT_LEADWORKS_COOP,
"leadworks_coop",//AVP_ENVIRONMENT_LEADWORKS_COOP,
"hadleyshope_coop",//AVP_ENVIRONMENT_HADLEYSHOPE_COOP,
"Co-op_Meat_Factory",//AVP_ENVIRONMENT_MEATFACTORY_COOP,
"Nostromo_Coop",//AVP_ENVIRONMENT_NOSTROMO_COOP,
"SubwayCoop",//AVP_ENVIRONMENT_SUBWAY_COOP,
"Elevator_co-op",//AVP_ENVIRONMENT_ELEVATOR_COOP,
"Lab14coop",//AVP_ENVIRONMENT_LAB14_COOP,
"CompoundCoop",//AVP_ENVIRONMENT_COMPOUND_COOP,
"co-op_meat_factory",//AVP_ENVIRONMENT_MEATFACTORY_COOP,
"nostromo_coop",//AVP_ENVIRONMENT_NOSTROMO_COOP,
"subwaycoop",//AVP_ENVIRONMENT_SUBWAY_COOP,
"elevator_co-op",//AVP_ENVIRONMENT_ELEVATOR_COOP,
"lab14coop",//AVP_ENVIRONMENT_LAB14_COOP,
"compoundcoop",//AVP_ENVIRONMENT_COMPOUND_COOP,
};
extern char LevelName[];
@ -5142,7 +5141,7 @@ void SetLevelToLoadForMultiplayer(int episode)
{
//it certainly is
//(the game type sent passed to the function doesn't really matter , as long as it isn't NGT_COOP)
sprintf(LevelName,"Custom\\%s",GetCustomMultiplayerLevelName(episode,NGT_Individual));
sprintf(LevelName,"Custom/%s",GetCustomMultiplayerLevelName(episode,NGT_Individual));
}
else
{
@ -5155,7 +5154,7 @@ void SetLevelToLoadForCooperative(int episode)
if(episode>=MAX_NO_OF_COOPERATIVE_EPISODES)
{
//it certainly is
sprintf(LevelName,"Custom\\%s",GetCustomMultiplayerLevelName(episode,NGT_Coop));
sprintf(LevelName,"Custom/%s",GetCustomMultiplayerLevelName(episode,NGT_Coop));
}
else
{
@ -5200,14 +5199,14 @@ int NumberForCurrentLevel(void) {
static BOOL DoesNamedLevelExist(const char* level_name)
{
HANDLE file_handle;
FILE *file_handle;
char filename[200];
sprintf(filename,"avp_rifs\\%s.rif",level_name);
sprintf(filename, "avp_rifs/%s.rif", level_name);
file_handle = CreateFile(filename,GENERIC_READ,0,0,OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0);
if(file_handle == INVALID_HANDLE_VALUE) return FALSE;
CloseHandle(file_handle);
file_handle = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_PERM);
if(file_handle == NULL) return FALSE;
fclose(file_handle);
return TRUE;
}

View file

@ -110,7 +110,6 @@ static void KeyboardEntryQueue_Clear(void);
static void KeyboardEntryQueue_StartProcessing(void);
void ScanSaveSlots(void);
extern void GetFilenameForSaveSlot(int i, unsigned char *filenamePtr);
static void GetHeaderInfoForSaveSlot(SAVE_SLOT_HEADER* save_slot,const char* filename);
static void PasteFromClipboard(char* Text,int MaxTextLength);
/* KJL 11:23:03 23/06/98 - Requirements
@ -4451,7 +4450,7 @@ void DisplayVideoModeUnavailableScreen(void)
void CheckForCredits(void)
{
#if 0
FILE *fp = fopen("credits.txt","rb");
FILE *fp = OpenGameFile("credits.txt", FILEMODE_READONLY, FILETYPE_PERM);
if (!fp)
{
@ -5437,28 +5436,6 @@ static char KeyboardEntryQueue_ProcessCharacter(void)
void ScanSaveSlots(void)
{
unsigned char filename[100];
int i;
SAVE_SLOT_HEADER *slotPtr = SaveGameSlot;
for (i=0; i<NUMBER_OF_SAVE_SLOTS; i++, slotPtr++)
{
GetFilenameForSaveSlot(i,filename);
GetHeaderInfoForSaveSlot(slotPtr,filename);
}
}
extern void GetFilenameForSaveSlot(int i, unsigned char *filenamePtr)
{
sprintf(filenamePtr,"%s%s_%d.sav",USER_PROFILES_PATH,UserProfilePtr->Name,i+1);
}
/*------------------------------------**
** Loading and saving main level info **
**------------------------------------*/
@ -5502,7 +5479,6 @@ void SaveLevelHeader()
block->Difficulty = AvP.Difficulty;
block->NumberOfSavesLeft = (unsigned char) NumberOfSavesLeft;
}
void LoadLevelHeader(SAVE_BLOCK_HEADER* header)
@ -5514,48 +5490,43 @@ void LoadLevelHeader(SAVE_BLOCK_HEADER* header)
AvP.ElapsedHours = block->ElapsedTime_Hours;
AvP.ElapsedMinutes = block->ElapsedTime_Minutes;
AvP.ElapsedSeconds = block->ElapsedTime_Seconds;
}
static void GetHeaderInfoForSaveSlot(SAVE_SLOT_HEADER* save_slot,const char* filename)
static void GetHeaderInfoForSaveSlot(SAVE_SLOT_HEADER* save_slot, const GameDirectoryFile *gdf)
{
LEVEL_SAVE_BLOCK block;
unsigned int file_size;
unsigned int bytes_read;
HANDLE file;
unsigned char filename[100];
FILE *file;
save_slot->SlotUsed = 0;
file = CreateFile(filename,GENERIC_READ, 0, 0, OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0);
sprintf(filename, "%s%s", USER_PROFILES_PATH, gdf->filename);
file = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_CONFIG);
if(file==INVALID_HANDLE_VALUE)
if (file==NULL)
{
//failed to load (probably doesn't exist)
return;
}
file_size = GetFileSize(file,0);
fseek(file, 0, SEEK_END);
file_size = ftell(file);
rewind(file);
if(file_size < sizeof(LEVEL_SAVE_BLOCK))
{
//obviously not much of a save file then...
CloseHandle(file);
fclose(file);
return;
}
{
struct stat buf;
if (stat(filename, &buf) != -1) {
save_slot->TimeStamp = buf.st_mtime;
}
}
save_slot->TimeStamp = gdf->timestamp;
//load the level header
ReadFile(file,&block,sizeof(block),(LPDWORD)&bytes_read,0);
CloseHandle(file);
fread(&block, sizeof(block), 1, file);
fclose(file);
//a few checks
if(block.header.type != SaveBlock_MainHeader ||
@ -5580,6 +5551,40 @@ static void GetHeaderInfoForSaveSlot(SAVE_SLOT_HEADER* save_slot,const char* fil
save_slot->SavesLeft = block.NumberOfSavesLeft;
}
void ScanSaveSlots(void)
{
unsigned char pattern[100], *ptr;
int i;
void *gd;
GameDirectoryFile *gdf;
sprintf(pattern, "%s_?.sav", UserProfilePtr->Name);
gd = OpenGameDirectory(USER_PROFILES_PATH, pattern, FILETYPE_CONFIG);
if (gd == NULL)
return;
while ((gdf = ScanGameDirectory(gd)) != NULL) {
if ((gdf->attr & FILEATTR_DIRECTORY) != 0)
continue;
if ((gdf->attr & FILEATTR_READABLE) == 0)
continue;
ptr = strrchr(gdf->filename, '.');
if (ptr == NULL)
continue;
ptr--;
i = *ptr - '1';
if (i >= 0 && (i < NUMBER_OF_SAVE_SLOTS)) {
GetHeaderInfoForSaveSlot(&SaveGameSlot[i], gdf);
}
}
}
extern void GetFilenameForSaveSlot(int i, unsigned char *filenamePtr)
{
sprintf(filenamePtr,"%s%s_%d.sav",USER_PROFILES_PATH,UserProfilePtr->Name,i+1);
}
static void CheckForLoadGame()
{

View file

@ -15,22 +15,16 @@
#define UseLocalAssert Yes
#include "ourasert.h"
#include <glob.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
extern "C"
{
extern void SetDefaultMultiplayerConfig();
extern char MP_SessionName[];
extern char MP_Config_Description[];
#define MP_CONFIG_DIR "MPConfig"
#define MP_CONFIG_WILDCARD "MPConfig/*.cfg"
#define MP_CONFIG_DIR "MPConfig/"
#define MP_CONFIG_WILDCARD "*.cfg"
#define SKIRMISH_CONFIG_WILDCARD "MPConfig/*.skirmish_cfg"
#define SKIRMISH_CONFIG_WILDCARD "*.skirmish_cfg"
static List<char*> ConfigurationFilenameList;
static List<char*> ConfigurationLocalisedFilenameList;
@ -63,68 +57,48 @@ BOOL BuildLoadMPConfigMenu()
load_name=SKIRMISH_CONFIG_WILDCARD;
}
glob_t globbuf;
if (glob(load_name, 0, NULL, &globbuf))
void *gd;
GameDirectoryFile *gdf;
gd = OpenGameDirectory(MP_CONFIG_DIR, load_name, FILETYPE_CONFIG);
if (gd == NULL) {
CreateGameDirectory(MP_CONFIG_DIR); /* maybe it didn't exist.. */
return FALSE;
// get any path in the load_name
int nPathLen = 0;
char * pColon = strrchr(load_name,':');
if (pColon) nPathLen = pColon - load_name + 1;
char * pBackSlash = strrchr(load_name,'\\');
if (pBackSlash)
{
int nLen = pBackSlash - load_name + 1;
if (nLen > nPathLen) nPathLen = nLen;
}
char * pSlash = strrchr(load_name,'/');
if (pSlash)
{
int nLen = pSlash - load_name + 1;
if (nLen > nPathLen) nPathLen = nLen;
}
for (unsigned int i = 0; i < globbuf.gl_pathc; i++) {
struct stat buf;
if (stat(globbuf.gl_pathv[i], &buf) == -1)
while ((gdf = ScanGameDirectory(gd)) != NULL) {
if ((gdf->attr & FILEATTR_DIRECTORY) != 0)
continue;
if ((gdf->attr & FILEATTR_READABLE) == 0)
continue;
if (S_ISREG(buf.st_mode) && (access(globbuf.gl_pathv[i], R_OK) == 0)) {
char *filename = strrchr(globbuf.gl_pathv[i], '/');
if (filename)
filename++;
else
filename = globbuf.gl_pathv[i];
char* name=new char[strlen(filename)+1];
strcpy(name,filename);
char* dotpos=strrchr(name,'.');
if(dotpos) *dotpos=0;
ConfigurationFilenameList.add_entry(name);
char* name=new char[strlen(gdf->filename)+1];
strcpy(name,gdf->filename);
char* dotpos=strrchr(name,'.');
if(dotpos) *dotpos=0;
ConfigurationFilenameList.add_entry(name);
BOOL localisedFilename=FALSE;
BOOL localisedFilename=FALSE;
//seeif this is one of the default language localised configurations
if(!strncmp(name,"Config",6))
//seeif this is one of the default language localised configurations
if(!strncmp(name,"Config",6))
{
if(name[6]>='1' && name[6]<='7' && name[7]=='\0')
{
if(name[6]>='1' && name[6]<='7' && name[7]=='\0')
{
TEXTSTRING_ID string_index=(TEXTSTRING_ID)(TEXTSTRING_MPCONFIG1_FILENAME+(name[6]-'1'));
ConfigurationLocalisedFilenameList.add_entry(GetTextString(string_index));
localisedFilename=TRUE;
}
}
if(!localisedFilename)
{
ConfigurationLocalisedFilenameList.add_entry(name);
TEXTSTRING_ID string_index=(TEXTSTRING_ID)(TEXTSTRING_MPCONFIG1_FILENAME+(name[6]-'1'));
ConfigurationLocalisedFilenameList.add_entry(GetTextString(string_index));
localisedFilename=TRUE;
}
}
if(!localisedFilename)
{
ConfigurationLocalisedFilenameList.add_entry(name);
}
}
globfree(&globbuf);
CloseGameDirectory(gd);
//delete the old menu
if(AvPMenu_Multiplayer_LoadConfig) delete AvPMenu_Multiplayer_LoadConfig;
@ -195,7 +169,7 @@ const char* GetMultiplayerConfigDescription(int index)
else
sprintf(filename,"%s/%s.cfg",MP_CONFIG_DIR,name);
file=fopen(filename,"rb");
file= OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_CONFIG);
if(!file)
{
return 0;
@ -233,7 +207,7 @@ void LoadMultiplayerConfiguration(const char* name)
else
sprintf(filename,"%s/%s.cfg",MP_CONFIG_DIR,name);
file=fopen(filename,"rb");
file= OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_CONFIG);
if(!file) return;
@ -330,7 +304,6 @@ void LoadMultiplayerConfiguration(const char* name)
netGameData.customLevelName[0] = 0;
}
}
}
void SaveMultiplayerConfiguration(const char* name)
@ -342,10 +315,15 @@ void SaveMultiplayerConfiguration(const char* name)
else
sprintf(filename,"%s/%s.cfg",MP_CONFIG_DIR,name);
CreateDirectory(MP_CONFIG_DIR,0);
file=fopen(filename,"wb");
if(!file) return;
file = OpenGameFile(filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (file == NULL) {
CreateGameDirectory(MP_CONFIG_DIR); /* try again */
file = OpenGameFile(filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (file == NULL)
return;
}
fwrite(&netGameData.gameType,sizeof(int),1,file);
fwrite(&netGameData.levelNumber,sizeof(int),1,file);
fwrite(&netGameData.scoreLimit,sizeof(int),1,file);
@ -427,7 +405,6 @@ void SaveMultiplayerConfiguration(const char* name)
delete [] LastDescriptionText;
LastDescriptionFile=0;
LastDescriptionText=0;
}
@ -441,12 +418,12 @@ void DeleteMultiplayerConfigurationByIndex(int index)
else
sprintf(filename,"%s/%s.cfg",MP_CONFIG_DIR,ConfigurationFilenameList[index]);
DeleteFile(filename);
DeleteGameFile(filename);
}
#define IP_ADDRESS_DIR "IP_Address"
#define IP_ADDRESS_WILDCARD "IP_Address/*.IP Address"
#define IP_ADDRESS_DIR "IP_Address/"
#define IP_ADDRESS_WILDCARD "*.IP Address"
static List<char*> IPAddFilenameList;
@ -465,52 +442,29 @@ BOOL BuildLoadIPAddressMenu()
//do a search for all the addresses in the address directory
glob_t globbuf;
const char* load_name=IP_ADDRESS_WILDCARD;
if (glob(load_name, 0, NULL, &globbuf))
void *gd;
GameDirectoryFile *gdf;
gd = OpenGameDirectory(IP_ADDRESS_DIR, IP_ADDRESS_WILDCARD, FILETYPE_CONFIG);
if (gd == NULL) {
CreateGameDirectory(IP_ADDRESS_DIR); /* maybe it didn't exist.. */
return FALSE;
}
// get any path in the load_name
int nPathLen = 0;
char * pColon = strrchr(load_name,':');
if (pColon) nPathLen = pColon - load_name + 1;
char * pBackSlash = strrchr(load_name,'\\');
if (pBackSlash)
{
int nLen = pBackSlash - load_name + 1;
if (nLen > nPathLen) nPathLen = nLen;
}
char * pSlash = strrchr(load_name,'/');
if (pSlash)
{
int nLen = pSlash - load_name + 1;
if (nLen > nPathLen) nPathLen = nLen;
}
for (unsigned int i = 0; i < globbuf.gl_pathc; i++) {
struct stat buf;
if (stat(globbuf.gl_pathv[i], &buf) == -1)
while ((gdf = ScanGameDirectory(gd)) != NULL) {
if ((gdf->attr & FILEATTR_DIRECTORY) != 0)
continue;
if ((gdf->attr & FILEATTR_READABLE) == 0)
continue;
if (S_ISREG(buf.st_mode) && (access(globbuf.gl_pathv[i], R_OK) == 0)) {
char *filename = strrchr(globbuf.gl_pathv[i], '/');
if (filename)
filename++;
else
filename = globbuf.gl_pathv[i];
char* name=new char[strlen(filename)+1];
strcpy(name,filename);
char* dotpos=strchr(name,'.');
if(dotpos) *dotpos=0;
IPAddFilenameList.add_entry(name);
}
char* name=new char[strlen(gdf->filename)+1];
strcpy(name,gdf->filename);
char* dotpos=strchr(name,'.');
if(dotpos) *dotpos=0;
IPAddFilenameList.add_entry(name);
}
globfree(&globbuf);
CloseGameDirectory(gd);
//delete the old menu
if(AvPMenu_Multiplayer_LoadIPAddress) delete [] AvPMenu_Multiplayer_LoadIPAddress;
@ -544,9 +498,13 @@ void SaveIPAddress(const char* name,const char* address)
char filename[200];
sprintf(filename,"%s/%s.IP Address",IP_ADDRESS_DIR,name);
CreateDirectory(IP_ADDRESS_DIR,0);
file=fopen(filename,"wb");
if(!file) return;
file = OpenGameFile(filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (file == NULL) {
CreateGameDirectory(IP_ADDRESS_DIR); /* try again */
file = OpenGameFile(filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (file == NULL)
return;
}
fwrite(address,1,strlen(address)+1,file);
@ -556,15 +514,14 @@ void SaveIPAddress(const char* name,const char* address)
void LoadIPAddress(const char* name)
{
extern char IPAddressString[];
if(!name) return;
FILE* file;
char filename[200];
sprintf(filename,"%s/%s.IP Address",IP_ADDRESS_DIR,name);
file=fopen(filename,"rb");
file=OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_CONFIG);
if(!file) return;
fread(IPAddressString,1,16,file);
@ -598,41 +555,33 @@ void BuildMultiplayerLevelNameArray()
//first do a search for custom level rifs
// allow a wildcard search
const char* load_name="avp_rifs/custom/*.rif";
void *gd;
GameDirectoryFile *gdf;
glob_t globbuf;
if (glob(load_name, 0, NULL, &globbuf) == 0) {
/* TODO: Have to use PERM until the load_rif code can handle CONFIG */
if ((gd = OpenGameDirectory("avp_rifs/Custom/", "*.rif", FILETYPE_PERM)) != NULL) {
char* custom_string = GetTextString(TEXTSTRING_CUSTOM_LEVEL);
int cs_len = strlen(custom_string);
for (unsigned int i = 0; i < globbuf.gl_pathc; i++) {
struct stat buf;
if (stat(globbuf.gl_pathv[i], &buf) == -1)
while ((gdf = ScanGameDirectory(gd)) != NULL) {
if ((gdf->attr & FILEATTR_DIRECTORY) != 0)
continue;
if (S_ISREG(buf.st_mode) && (access(globbuf.gl_pathv[i], R_OK) == 0)) {
char *filename = strrchr(globbuf.gl_pathv[i], '/');
if (filename)
filename++;
else
filename = globbuf.gl_pathv[i];
char* name=new char[strlen(filename)+cs_len+3+1];
if ((gdf->attr & FILEATTR_READABLE) == 0)
continue;
char* name=new char[strlen(gdf->filename)+cs_len+3+1];
strcpy(name, filename);
char* dotpos=strrchr(name,'.');
if(dotpos) *dotpos=0;
strcat(name," (");
strcat(name,custom_string);
strcat(name,")");
CustomLevelNameList.add_entry(name);
}
strcpy(name, gdf->filename);
char* dotpos=strrchr(name,'.');
if(dotpos) *dotpos=0;
strcat(name," (");
strcat(name,custom_string);
strcat(name,")");
CustomLevelNameList.add_entry(name);
}
globfree(&globbuf);
CloseGameDirectory(gd);
} else {
CreateGameDirectory("Custom/"); /* maybe it didn't exist.. */
}
NumCustomLevels = CustomLevelNameList.size();

View file

@ -20,11 +20,6 @@ extern "C"
#include "pldnet.h"
#include <time.h>
#include <glob.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
static int LoadUserProfiles(void);
static void EmptyUserProfilesList(void);
@ -112,9 +107,9 @@ extern int SaveUserProfile(AVP_USER_PROFILE *profilePtr)
strcat(filename,profilePtr->Name);
strcat(filename,USER_PROFILES_SUFFIX);
FILE* file=fopen(filename,"wb");
FILE* file=OpenGameFile(filename, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
delete [] filename;
if(!file) return 0;
if (!file) return 0;
SaveSettingsToUserProfile(profilePtr);
@ -135,7 +130,7 @@ extern void DeleteUserProfile(int number)
strcat(filename,profilePtr->Name);
strcat(filename,USER_PROFILES_SUFFIX);
DeleteFile(filename);
DeleteGameFile(filename);
delete [] filename;
{
@ -145,7 +140,7 @@ extern void DeleteUserProfile(int number)
for (i=0; i<NUMBER_OF_SAVE_SLOTS; i++)
{
sprintf(filename,"%s%s_%d.sav",USER_PROFILES_PATH,profilePtr->Name,i+1);
DeleteFile(filename);
DeleteGameFile(filename);
}
delete [] filename;
}
@ -180,71 +175,54 @@ static int ProfileIsMoreRecent(AVP_USER_PROFILE *profilePtr, AVP_USER_PROFILE *p
static int LoadUserProfiles(void)
{
glob_t globbuf;
const char* load_name=USER_PROFILES_WILDCARD_NAME;
void *gd;
GameDirectoryFile *gdf;
if (glob(load_name, 0, NULL, &globbuf))
gd = OpenGameDirectory(USER_PROFILES_PATH, USER_PROFILES_WILDCARD_NAME, FILETYPE_CONFIG);
if (gd == NULL) {
CreateGameDirectory(USER_PROFILES_PATH); /* maybe it didn't exist.. */
return 0;
// get any path in the load_name
int nPathLen = 0;
char * pColon = strrchr(load_name,':');
if (pColon) nPathLen = pColon - load_name + 1;
char * pBackSlash = strrchr(load_name,'\\');
if (pBackSlash)
{
int nLen = pBackSlash - load_name + 1;
if (nLen > nPathLen) nPathLen = nLen;
}
char * pSlash = strrchr(load_name,'/');
if (pSlash)
{
int nLen = pSlash - load_name + 1;
if (nLen > nPathLen) nPathLen = nLen;
}
for (unsigned int i = 0; i < globbuf.gl_pathc; i++) {
struct stat buf;
if (stat(globbuf.gl_pathv[i], &buf) == -1)
int nPathLen = strlen(USER_PROFILES_PATH);
while ((gdf = ScanGameDirectory(gd)) != NULL) {
if ((gdf->attr & FILEATTR_DIRECTORY) != 0)
continue;
if ((gdf->attr & FILEATTR_READABLE) == 0)
continue;
if (S_ISREG(buf.st_mode) && (access(globbuf.gl_pathv[i], R_OK) == 0))
char * pszFullPath = new char [nPathLen+strlen(gdf->filename)+1];
strcpy(pszFullPath, USER_PROFILES_PATH);
strcat(pszFullPath, gdf->filename);
FILE *rif_file;
rif_file = OpenGameFile(pszFullPath, FILEMODE_READONLY, FILETYPE_CONFIG);
if(rif_file==NULL)
{
char * pszFullPath = new char [nPathLen+strlen(globbuf.gl_pathv[i])+1];
// strncpy(pszFullPath,load_name,nPathLen);
strcpy(pszFullPath /* +nPathLen */, globbuf.gl_pathv[i]);
HANDLE rif_file;
rif_file = CreateFile (pszFullPath, GENERIC_READ, 0, 0, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, 0);
if(rif_file==INVALID_HANDLE_VALUE)
{
delete[] pszFullPath;
continue;
}
AVP_USER_PROFILE *profilePtr = new AVP_USER_PROFILE;
unsigned long bytes_read;
if (!ReadFile(rif_file, profilePtr, sizeof(AVP_USER_PROFILE), &bytes_read, 0))
{
CloseHandle (rif_file);
delete[] pszFullPath;
delete profilePtr;
continue;
}
profilePtr->FileTime = buf.st_mtime;
InsertProfileIntoList(profilePtr);
CloseHandle (rif_file);
delete[] pszFullPath;
continue;
}
AVP_USER_PROFILE *profilePtr = new AVP_USER_PROFILE;
if (fread(profilePtr, 1, sizeof(AVP_USER_PROFILE), rif_file) != sizeof(AVP_USER_PROFILE))
{
fclose(rif_file);
delete[] pszFullPath;
delete profilePtr;
continue;
}
profilePtr->FileTime = gdf->timestamp;
InsertProfileIntoList(profilePtr);
fclose(rif_file);
delete[] pszFullPath;
}
globfree(&globbuf);
CloseGameDirectory(gd);
return 1;
}

View file

@ -145,7 +145,7 @@ typedef struct
#define USER_PROFILES_PATH "User_Profiles/"
#define USER_PROFILES_WILDCARD_NAME "User_Profiles/*.prf"
#define USER_PROFILES_WILDCARD_NAME "*.prf"
#define USER_PROFILES_SUFFIX ".prf"

View file

@ -3719,6 +3719,9 @@ void setup_sounds (Environment_Data_Chunk * envd)
stt->outer_range = snd->outer_range * local_scale;
stt->max_volume = snd->max_volume;
stt->pitch = snd->pitch;
stt->playing = 0;
stt->loop = 0;
if(snd->flags & SoundObjectFlag_NotPlayingAtStart)
stt->playing=0;
@ -3729,13 +3732,11 @@ void setup_sounds (Environment_Data_Chunk * envd)
stt->loop=0;
else
stt->loop=1;
stt->sound_name =(char*) PoolAllocateMem(strlen (snd->wav_name) + 1);
strcpy(stt->sound_name,snd->wav_name);
stt->sound_loaded=GetSoundForMainRif(snd->wav_name);
AddToBehaviourList(snd->snd_name,snd->CalculateID(), I_BehaviourPlacedSound, (void *) stt);
}
}

View file

@ -52,7 +52,7 @@ void catpathandextension(char* dst, char* src)
if ((len > 0 && (dst[len-1] != '\\' && dst[len-1] != '/')) && *src != '.')
{
lstrcat(dst,"\\");
lstrcat(dst,"/");
}
lstrcat(dst,src);
@ -367,7 +367,7 @@ char *LoadTextFile(char *filename)
char *bufferPtr;
long int save_pos, size_of_file;
FILE *fp;
fp = fopen(filename,"rb");
fp = OpenGameFile(filename, FILEMODE_READONLY, FILETYPE_PERM);
if (!fp) goto error;

View file

@ -84,12 +84,6 @@ const char * SubShps_Directory = "SubShps\\All\\";
// const char * GenTex_Directory = 0;
const char * FixTex_Directory = "\\\\Kate\\Kate Share\\avp\\Fix-Tex\\";
const char * GameTex_Directory = "\\\\Kate\\Kate Share\\avp\\game-tex\\";
// these link with pcmenus.cpp
const char * GenTex4bit_Directory = "\\\\Kate\\Kate Share\\avp\\G4bitTex\\";
const char * GenTex8bit_Directory = "\\\\Kate\\Kate Share\\avp\\GenG-Tex\\";
const char * GenTex75pc_Directory = "\\\\Kate\\Kate Share\\avp\\Gen34Tex\\";
const char * GenTex50pc_Directory = "\\\\Kate\\Kate Share\\avp\\Gen12Tex\\";
// new directories for new-style graphics - to be determined properly
char const * FirstTex_Directory = "Graphics"; // currently relative to cwd
char const * SecondTex_Directory = 0; // will be the src safe shadow for development builds
@ -357,9 +351,9 @@ struct LoadedPlacedHierarchy
#define NumPlacedHierarchy 3
LoadedPlacedHierarchy PlacedHierarchyArray[NumPlacedHierarchy]=
{
"dropship","dropship",INVALID_RIFFHANDLE,
"pred ship fury","pred ship fury",INVALID_RIFFHANDLE,
"pred ship ob","pred ship ob",INVALID_RIFFHANDLE,
{ "dropship","dropship",INVALID_RIFFHANDLE },
{ "pred ship fury","pred ship fury",INVALID_RIFFHANDLE },
{ "pred ship ob","pred ship ob",INVALID_RIFFHANDLE },
};
@ -368,7 +362,6 @@ void LoadedPlacedHierarchy::load_rif()
if(placed_rif!=INVALID_RIFFHANDLE) return;
char file_path[100];
/* TODO: dir seperator */
sprintf(file_path,"avp_huds/%s.rif",file_name);
placed_rif=avp_load_rif_non_env(file_path);
@ -505,7 +498,6 @@ Global_Hierarchy_Store::Global_Hierarchy_Store (RIFFHANDLE h)
sound_array[index].volume=isc->max_volume;
if(dir_chunk)
{
/* TODO: dir separator */
sprintf(wavname,"%s\\%s",dir_chunk->directory,isc->wav_name);
sound_array[index].sound_loaded=GetSound(wavname);
}
@ -516,14 +508,9 @@ Global_Hierarchy_Store::Global_Hierarchy_Store (RIFFHANDLE h)
if(sound_array[index].sound_loaded)
{
sound_array[index].sound_index=(SOUNDINDEX)sound_array[index].sound_loaded->sound_num;
}
}
}
}
}
@ -1989,7 +1976,6 @@ BOOL copy_rif_data (RIFFHANDLE h, int flags,int progress_start,int progress_inte
int start_shape_no = rt_temp.start_list_pos;
int list_pos = rt_temp.main_list_pos;
db_logf3(("Shape copied to %d",list_pos));
MORPHCTRL * mc = rt_temp.mc;
#else
int list_pos = copy_to_mainshapelist(h,shplif(),flags,&ob->object_data);
int start_shape_no = list_pos;
@ -3010,10 +2996,9 @@ void DeallocateLoadedShapeheader(SHAPEHEADER * shp)
void DeallocateModules()
{
MODULE ** m_arrayPtr = MainScene.sm_marray;
#if !USE_LEVEL_MEMORY_POOL
MODULE ** m_arrayPtr = MainScene.sm_marray;
while (*m_arrayPtr)
{
List<Light_Chunk *> lights_for_this_module;
@ -3092,7 +3077,7 @@ void avp_undo_rif_load(RIFFHANDLE h)
RIFFHANDLE avp_load_rif (const char * fname)
{
//see if there is a local copy of the rif file
FILE* rifFile = fopen(fname,"rb");
FILE* rifFile = OpenGameFile(fname, FILEMODE_READONLY, FILETYPE_PERM);
/* TODO: Let's find a better method */
if (!rifFile && AvpCDPath)
@ -3111,7 +3096,7 @@ RIFFHANDLE avp_load_rif (const char * fname)
RIFFHANDLE avp_load_rif_non_env (const char * fname)
{
//see if there is a local copy of the rif file
FILE* rifFile = fopen(fname, "rb");
FILE* rifFile = OpenGameFile(fname, FILEMODE_READONLY, FILETYPE_PERM);
/* TODO: Let's find a better method */
if (!rifFile && AvpCDPath)

View file

@ -27,10 +27,13 @@ extern void LoadModuleData();
void LogCameraPosForModuleLinking()
{
fprintf(stderr, "STUB: LogCameraPosForModuleLinking()\n");
#if 0 /* TODO: commented out because I want to know if its actually used */
if(!playerPherModule) return;
if(!playerPherModule->name) return;
char Filename[100]={"avp_rifs\\"};
char Filename[100]={"avp_rifs/"};
strcat(Filename,Env_List[AvP.CurrentEnv]->main);
strcat(Filename,".mlf");
@ -59,6 +62,7 @@ void LogCameraPosForModuleLinking()
fwrite(&output_buffer[0],4,length/4,file);
fclose(file);
textprint("Saving camera for module links");
#endif
}
int SaveCameraPosKeyPressed=0;
static BOOL ModuleLinkAssist=FALSE;
@ -115,7 +119,7 @@ void ScreenShot()
{
Name[length]=i/10+'0';
Name[length+1]=(i%10)+'0';
FILE* tempfp=fopen(Name,"r");
FILE* tempfp = OpenGameFile(Name, FILEMODE_READONLY, FILETYPE_CONFIG);
if(!tempfp)break;
else
{
@ -124,7 +128,7 @@ void ScreenShot()
}
if(i==100) return;
FILE * fp = fopen(Name,"wb");
FILE *fp = OpenGameFile(Name, FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (!fp)
{
return;
@ -190,7 +194,7 @@ void ScreenShot()
unsigned char *BufferPtr = &buf[0];
for (i=h.WinInfo.Height-1; i>=0; --i)
{
int j;
unsigned int j;
for (j=0; j<h.WinInfo.Width; ++j)
{
PutByte((BYTE)BufferPtr[j*3+2],fp); //b

View file

@ -734,8 +734,8 @@ void IntegrateNewEnvironment()
}
const char GameDataDirName[20] = {"AVP_RIFS"};
const char FileNameExtension[5] = {".RIF"};
const char GameDataDirName[20] = {"avp_rifs"};
const char FileNameExtension[5] = {".rif"};
void LoadRifFile()
{
@ -760,8 +760,6 @@ void LoadRifFile()
catpathandextension(&file_and_path[0], Env_List[AvP.CurrentEnv]->main); /* root of the file name,smae as dir*/
catpathandextension(&file_and_path[0], (char *)&FileNameExtension[0]); /* extension*/
FixFilename(file_and_path);
env_rif = avp_load_rif((const char*)&file_and_path[0]);
Set_Progress_Bar_Position(PBAR_LEVEL_START+PBAR_LEVEL_INTERVAL*.4);
@ -772,10 +770,6 @@ void LoadRifFile()
};
// #ifdef __WATCOMC__
// #pragma message("Note: use copy_chunks_from_envronment(CCF_ENVIRONMENT) iff a character rif is loaded")
// #endif
#if MaxImageGroups>1
SetCurrentImageGroup(2); // FOR ENV
#endif

View file

@ -1718,7 +1718,7 @@ void SaveAKeyConfiguration(char* Filename)
void SaveDefaultPrimaryConfigs(void)
{
FILE* file=fopen("default.cfg","wb");
FILE *file = OpenGameFile("default.cfg", FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if(!file) return;
fwrite(&DefaultMarineInputPrimaryConfig,sizeof(PLAYER_INPUT_CONFIGURATION),1,file);
@ -1729,7 +1729,7 @@ void SaveDefaultPrimaryConfigs(void)
}
void LoadDefaultPrimaryConfigs(void)
{
FILE* file=fopen("default.cfg","rb");
FILE *file = OpenGameFile("default.cfg", FILEMODE_READONLY, FILETYPE_CONFIG);
if(!file) return;
fread(&DefaultMarineInputPrimaryConfig,sizeof(PLAYER_INPUT_CONFIGURATION),1,file);

View file

@ -1,682 +0,0 @@
/****
Project specific (or potentially
project specific) windows functionality
****/
// To link code to main C functions
extern "C" {
#include "3dc.h"
#include "inline.h"
#include "cd_player.h"
#include "psndplat.h"
#include "rentrntq.h"
// Added 21/11/97 by DHM: support for a queue of Windows
// messages to avoid problems with re-entrancy due to WinProc()
#include "alt_tab.h"
#include "dxlog.h"
#include "zmouse.h"
void MakeToAsciiTable(void);
// mousewheel msg id
UINT const RWM_MOUSEWHEEL = RegisterWindowMessage(MSH_MOUSEWHEEL);
signed int MouseWheelStatus;
extern LPDIRECTDRAWSURFACE lpDDSBack;
extern LPDIRECTDRAWSURFACE lpDDSPrimary;
extern LPDIRECTDRAWSURFACE lpZBuffer;
extern LPDIRECTDRAWSURFACE lpDDBackdrop;
unsigned char ksarray[256];
unsigned char ToAsciiTable[256][256];
// Dubious
#define grabmousecapture No
/*
Name of project window etc for Win95 interface
Project specific (fairly obviously...).
Determines the default menu in which the application
appears (altho' other code will undoubtedly be needed
as well...), so that a NULL here should ensure no menu.
*/
#define NAME "AvP"
#define TITLE "AvP"
// Necessary globals
HWND hWndMain;
BOOL bActive = TRUE; // is application active?
// Parameters for main (assumed full screen) window
int WinLeftX, WinRightX, WinTopY, WinBotY;
int WinWidth, WinHeight;
// Externs
extern int VideoMode;
extern int WindowMode;
extern WINSCALEXY TopLeftSubWindow;
extern WINSCALEXY ExtentXYSubWindow;
// Window procedure (to run continuously while WinMain is active).
// Only necessary functions are handling keyboard input (for the moment
// at least - cf. DirectInput) and dealing with important system
// messages, e.g. WM_PAINT.
// Remember to support all the keys you need for your project
// for both KEYUP and KEYDOWN messages!!!
// IMPORTANT!!! The WindowProc is project specific
// by default, since various nifty hacks can always
// be implemented directly via the windows procedure
#define RESTORE_SURFACE(lpDDS) { \
if (lpDDS) { \
if (DDERR_SURFACELOST == (lpDDS)->IsLost()) { \
HRESULT hResult = (lpDDS)->Restore(); \
LOGDXFMT(("%s surface was restored", #lpDDS )); \
LOGDXERR(hResult); \
} else { \
LOGDXFMT(("%s surface wasn't lost", #lpDDS )); \
} \
} \
else { \
LOGDXFMT(("?&@#! no %s surface", #lpDDS )); \
} \
}
extern void KeyboardEntryQueue_Add(char c);
extern IngameKeyboardInput_KeyDown(unsigned char key);
extern IngameKeyboardInput_KeyUp(unsigned char key);
extern IngameKeyboardInput_ClearBuffer(void);
long FAR PASCAL WindowProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
RECT NewWindCoord;
if (message==RWM_MOUSEWHEEL)
{
message = WM_MOUSEWHEEL;
wParam <<= 16;
}
switch(message)
{
case WM_MOUSEWHEEL:
{
MouseWheelStatus = wParam;
MouseWheelStatus>>=16;
return 0;
}
// 21/11/97 DHM: Added porcessing of WM_CHAR messages:
case WM_CHAR:
RE_ENTRANT_QUEUE_WinProc_AddMessage_WM_CHAR
(
(char) wParam
);
KeyboardEntryQueue_Add((char)wParam);
return 0;
case WM_KEYDOWN:
RE_ENTRANT_QUEUE_WinProc_AddMessage_WM_KEYDOWN
(
wParam
);
// it's intentional for this case to fall through to WM_SYSKEYDOWN
case WM_SYSKEYDOWN:
{
int scancode = (lParam>>16)&255;
unsigned char vkcode = (wParam&255);
// ignore the status of caps lock
//ksarray[VK_CAPITAL] = 0;
//ksarray[VK_CAPITAL] = GetKeyState(VK_CAPITAL);
if (vkcode!=VK_CAPITAL && vkcode!=VK_SCROLL)
{
#if 0
WORD output;
if (ToAscii(vkcode,scancode,&ksarray[0],&output,0))
{
IngameKeyboardInput_KeyDown((unsigned char)(output));
}
#else
if (ToAsciiTable[vkcode][scancode])
{
IngameKeyboardInput_KeyDown(ToAsciiTable[vkcode][scancode]);
}
#endif
}
// reset caps lock status
//ksarray[VK_CAPITAL] = GetKeyState(VK_CAPITAL);
//ToAscii(wParam&255,scancode,&ksarray[0],&output,0);
}
return 0;
case WM_SYSKEYUP:
case WM_KEYUP:
{
int scancode = (lParam>>16)&255;
unsigned char vkcode = (wParam&255);
// ignore the status of caps lock
//ksarray[VK_CAPITAL] = 0;
//MakeToAsciiTable();
//ksarray[VK_CAPITAL] = GetKeyState(VK_CAPITAL);
if (vkcode!=VK_CAPITAL && vkcode!=VK_SCROLL)
{
#if 0
WORD output;
unsigned char z = ToAscii(vkcode,scancode,&ksarray[0],&output,0);
unsigned char a = (unsigned char)output;
unsigned char b = ToAsciiTable[vkcode][scancode];
#endif
#if 0
WORD output;
if (ToAscii(vkcode,scancode,&ksarray[0],&output,0))
{
IngameKeyboardInput_KeyUp((unsigned char)(output));
}
#else
if (ToAsciiTable[vkcode][scancode])
{
IngameKeyboardInput_KeyUp(ToAsciiTable[vkcode][scancode]);
}
#endif
}
// reset caps lock status
//ksarray[VK_CAPITAL] = GetKeyState(VK_CAPITAL);
//ToAscii(wParam&255,scancode,&ksarray[0],&output,0);
}
return 0;
// This, in combination with code in win_func,
// will hopefully disable Alt-Tabbing...
case WM_ACTIVATEAPP:
bActive = (BOOL) wParam;
LOGDXFMT(("WM_ACTIVATEAPP msg: bActive = %d",(int)bActive));
if (bActive)
{
// need to restore all surfaces - do the special ones first
RESTORE_SURFACE(lpDDSPrimary)
RESTORE_SURFACE(lpDDSBack)
RESTORE_SURFACE(lpZBuffer)
// dodgy, this is meant to be graphic, so it'll really need to be reloaded
RESTORE_SURFACE(lpDDBackdrop)
// now do all the graphics surfaces and textures, etc.
ATOnAppReactivate();
}
IngameKeyboardInput_ClearBuffer();
return 0;
// Three below are for safety, to turn off
// as much as possible of the more annoying
// functionality of the default Windows
// procedure handler
case WM_ACTIVATE:
return 0;
#if 0
case WM_SYSKEYUP:
return 0;
case WM_SYSKEYDOWN:
return 0;
#endif
case WM_CREATE:
break;
case WM_MOVE:
// Necessary to stop it crashing in 640x480
// FullScreen modes on window initialisation
if (WindowMode == WindowModeSubWindow)
{
GetWindowRect(hWndMain, &NewWindCoord);
WinLeftX = NewWindCoord.left;
WinTopY = NewWindCoord.top;
WinRightX = NewWindCoord.right;
WinBotY = NewWindCoord.bottom;
}
break;
case WM_SIZE:
// Necessary to stop it crashing in 640x480
// FullScreen modes on window initialisation
if (WindowMode == WindowModeSubWindow)
{
GetWindowRect(hWndMain, &NewWindCoord);
WinLeftX = NewWindCoord.left;
WinTopY = NewWindCoord.top;
WinRightX = NewWindCoord.right;
WinBotY = NewWindCoord.bottom;
}
break;
case WM_SETCURSOR:
SetCursor(NULL);
return TRUE;
case WM_ERASEBKGND:
return TRUE;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
return TRUE;
/* Patrick 11/6/97: this to detects the end of a cdda track */
case MM_MCINOTIFY:
PlatCDDAManagementCallBack(wParam, lParam);
break;
case WM_DESTROY:
// Calls ReleaseDirect3D DIRECTLY,
// so as to avoid calling ExitSystem and exiting the
// Windows system inside the windows procedure
// IMPORTANT!!! For this to work, release functions
// must be re-entrant. Since this may be causing
// problems under obscure cirumstances, I am removing
// this now (25/7/96).
// And putting it back... (20/9/96)
ReleaseDirect3D();
/* patrick 9/6/97: hmmmmm.... */
PlatEndSoundSys();
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
/*
Persuade Win95 to give us the window we want and, like,
TOTAL CONTROL, and then shut up, stop whinging and
go away.
Or at least as much control as we can get.. safely...
elegantly... ummm...
*/
// IMPORTANT!!! Windows initialisation is project specific,
// because of the project name and title if nothing else
// This function now takes a mode which is
// set to full or change. Full should be
// run ONLY when the system is starting.
// Change is used to change the window
// characteristics during a run, e.g. to
// change from SubWindow to FullScreen
// mode, and will not attempt to register
// the windows class.
BOOL InitialiseWindowsSystem(HANDLE hInstance, int nCmdShow,
int WinInitMode)
{
WNDCLASS wc;
BOOL rc;
MakeToAsciiTable();
/*
Set up the width and height we want from
the VideoMode, taking account of WindowMode.
*/
// This has now been modified to just set the
// size to the current system metrics, which
// may or may not be ideal. Surprisingly, it
// seems not to make much difference.
if (WindowMode == WindowModeSubWindow)
{
//force window to be 640x480 to avoid stretch blits.
WinWidth=640;
WinHeight=480;
WinLeftX = (int) (TopLeftSubWindow.x *
(float) GetSystemMetrics(SM_CXSCREEN));
WinTopY = (int) (TopLeftSubWindow.y *
(float) GetSystemMetrics(SM_CYSCREEN));
WinRightX = (WinLeftX + WinWidth);
WinBotY = (WinTopY + WinHeight);
}
else if (WindowMode == WindowModeFullScreen)
{
#if 1
WinWidth = GetSystemMetrics(SM_CXSCREEN);
WinHeight = GetSystemMetrics(SM_CYSCREEN);
#else
// This version of the code MUST be
// kept up to date with new video modes!!!
if ((VideoMode == VideoMode_DX_320x200x8) ||
(VideoMode == VideoMode_DX_320x200x8T))
{
WinWidth = 320;
WinHeight = 200;
}
else if (VideoMode == VideoMode_DX_320x240x8)
{
WinWidth = 320;
WinHeight = 240;
}
else // Default to 640x480
{
WinWidth = 640;
WinHeight = 480;
}
#endif
// Set up globals for window corners
WinLeftX = 0;
WinTopY = 0;
WinRightX = WinWidth;
WinBotY = WinHeight;
}
else
return FALSE;
// We only want to register the class in
// WinInitFull mode!!!
if (WinInitMode == WinInitFull)
{
/*
Set up and register window class
*/
// get double click messages from mouse if user double-clicks it
wc.style = CS_DBLCLKS;
// Name of window procedure (see above)
wc.lpfnWndProc = WindowProc;
/*
Extra bytes for obscure purposes bearing a sordid relationship to
dialog box conventions. Zero for us.
*/
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
// Instance which window is within
wc.hInstance = (HINSTANCE) hInstance;
/*
System icon resource. This one is generic. For an actual
game this icon will be project specific.
*/
#if 1
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
#else
wc.hIcon = NULL;
#endif
// System cursor resource. This one is generic.
#if 1
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
#else
wc.hCursor = NULL;
#endif
/*
NULL background forces application to redraw
the background ITSELF when it receives a WM_ERASEBKGND
message, leaving graphical control with the engine
*/
wc.hbrBackground = NULL;
// Project name and class for windows menus etc.
wc.lpszMenuName = NAME;
wc.lpszClassName = NAME;
/*
Register the class we have constructed as a valid window that
can then be created. Return code indicates success or
failure.
*/
rc = RegisterClass(&wc);
if (!rc)
return FALSE;
}
/*
Create a window (extended function call) and return
handle. Before returning, WM_CREATE, WM_GETMINMAXINFO
and WM_NCCREATE messages will be sent to the window
procedure.
NOTE!!! AT present even with debug on we get a
topmost full screen window.
*/
#if debug
if (WindowMode == WindowModeSubWindow)
{
hWndMain = CreateWindowEx(
0, // WS_EX_TOPMOST
NAME, // Name of class (registered by RegisterClass call above)
TITLE, // Name of window
WS_OVERLAPPED |
WS_CAPTION |
WS_THICKFRAME,
/*
Initial horizontal and vertical position. For a pop-up window,
these are the coordinates of the upper left corner.
*/
WinLeftX,
WinTopY,
/*
Width and height of window. These are set to the current full
screen widths as determined by a Win32 GetSystemMetrics call
(GetSystemMetrics(SM_CXSCREEN) and
GetSystemMetrics(SM_CYSCREEN)).
*/
WinWidth,
WinHeight,
// Parent window (could possibly be set in tools system?)
NULL,
// Child/menu window (could possibly be set in tools system?)
NULL,
// Handle for module associated with window
(HINSTANCE)hInstance,
// Parameter for associated structure (null in this case)
NULL);
}
else if (WindowMode == WindowModeFullScreen)
{
hWndMain = CreateWindowEx(
/*
WS_EX_TOPMOST forces this window to be topmost except
for other topmost windows, even when deactivated.
*/
WS_EX_TOPMOST,
NAME, // Name of class (registered by RegisterClass call above)
TITLE, // Name of window
WS_VISIBLE | // kills Alt-Space and strews its entrails over fifteen miles. Heh heh heh.
WS_POPUP, // i.e. specify window is style pop up, i.e. non-application
/*
Initial horizontal and vertical position. For a pop-up window,
these are the coordinates of the upper left corner.
*/
WinLeftX,
WinTopY,
/*
Width and height of window. These are set to the current full
screen widths as determined by a Win32 GetSystemMetrics call
(GetSystemMetrics(SM_CXSCREEN) and
GetSystemMetrics(SM_CYSCREEN)).
*/
WinWidth,
WinHeight,
// Parent window (null for a full screen game)
NULL,
// Child/menu window (null for a full screen game)
NULL,
// Handle for module associated with window
(HINSTANCE)hInstance,
// Parameter for associated structure (null in this case)
NULL);
}
else
return FALSE;
#else
if (WindowMode == WindowModeSubWindow)
{
hWndMain = CreateWindowEx(
0, // WS_EX_TOPMOST
NAME, // Name of class (registered by RegisterClass call above)
TITLE, // Name of window
WS_OVERLAPPED |
WS_CAPTION |
WS_THICKFRAME,
/*
Initial horizontal and vertical position. For a pop-up window,
these are the coordinates of the upper left corner.
*/
WinLeftX,
WinTopY,
/*
Width and height of window. These are set to the current full
screen widths as determined by a Win32 GetSystemMetrics call
(GetSystemMetrics(SM_CXSCREEN) and
GetSystemMetrics(SM_CYSCREEN)).
*/
WinWidth,
WinHeight,
// Parent window (could be set in tools system?)
NULL,
// Child/menu window (could be set in tools system?)
NULL,
// Handle for module associated with window
hInstance,
// Parameter for associated structure (null in this case)
NULL);
}
else if (WindowMode == WindowModeFullScreen)
{
hWndMain = CreateWindowEx(
/*
WS_EX_TOPMOST forces this window to be topmost except
for other topmost windows, even when deactivated.
*/
WS_EX_TOPMOST,
NAME, // Name of class (registered by RegisterClass call above)
TITLE, // Name of window
WS_VISIBLE | // kills Alt-Space and strews its entrails for fifteen miles. Heh heh heh.
WS_POPUP, // Specify window is style pop up, i.e. non-application
/*
Initial horizontal and vertical position. For a pop-up window,
these are the coordinates of the upper left corner.
*/
WinLeftX,
WinTopY,
/*
Width and height of window. These are set to the current full
screen widths as determined by a Win32 GetSystemMetrics call
(GetSystemMetrics(SM_CXSCREEN) and
GetSystemMetrics(SM_CYSCREEN)).
*/
WinWidth,
WinHeight,
// Parent window (null for a full screen game)
NULL,
// Child/menu window (null for a full screen game)
NULL,
// Handle for module associated with window
hInstance,
// Parameter for associated structure (null in this case)
NULL);
}
else
return FALSE;
#endif
if (!hWndMain)
return FALSE;
// Experiment only!!!!
// Set the window up to be displayed
ShowWindow(hWndMain, nCmdShow);
// Update once (i.e. send WM_PAINT message to the window procedure)
UpdateWindow(hWndMain);
// Grab ALL mouse messages for our window.
// Note this will only work if the window is
// foreground (as it is... ). This ensures that
// we will still get MOUSEMOVE etc messages even
// if the mouse is out of the defined window area.
#if grabmousecapture
SetCapture(hWndMain);
// Load null cursor shape
SetCursor(NULL);
#endif
MakeToAsciiTable();
return TRUE;
}
// Project specific to go with the initialiser
BOOL ExitWindowsSystem(void)
{
BOOL rc = TRUE;
// Release dedicated mouse capture
#if grabmousecapture
ReleaseCapture();
#endif
rc = DestroyWindow(hWndMain);
return rc;
}
void MakeToAsciiTable(void)
{
WORD output;
for (int k=0; k<=255; k++)
{
ksarray[k]=0;
}
for (int i=0; i<=255; i++)
{
for (int s=0; s<=255; s++)
{
if(ToAscii(i,s,&ksarray[0],&output,0)!=0)
{
ToAsciiTable[i][s] = (unsigned char)output;
}
else
{
ToAsciiTable[i][s] = 0;
}
}
}
}
// End of extern C declaration
};

575
src/files.c Normal file
View file

@ -0,0 +1,575 @@
#define _BSD_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <fnmatch.h>
#include "files.h"
static char *local_dir;
static char *global_dir;
/*
Sets the local and global directories used by the other functions.
Local = ~/.dir, where config and user-installed files are kept.
Global = installdir, where installed data is stored.
*/
int SetGameDirectories(const char *local, const char *global)
{
struct stat buf;
local_dir = strdup(local);
global_dir = strdup(global);
if (stat(local_dir, &buf) == -1) {
printf("Creating local directory %s...\n", local_dir);
mkdir(local_dir, S_IRWXU);
}
return 0;
}
#define DIR_SEPARATOR "/"
static char *FixFilename(const char *filename, const char *prefix, int force)
{
char *f, *ptr;
int flen;
flen = strlen(filename) + strlen(prefix) + 2;
f = (char *)malloc(flen);
strcpy(f, prefix);
strcat(f, DIR_SEPARATOR);
strcat(f, filename);
ptr = f;
while (*ptr) {
if ((*ptr == '/') || (*ptr == '\\') || (*ptr == ':')) {
*ptr = DIR_SEPARATOR[0];
} else if (*ptr == '\r' || *ptr == '\n') {
*ptr = 0;
break;
} else {
if (force)
*ptr = tolower(*ptr);
}
ptr++;
}
return f;
}
/*
Open a file of type type, with mode mode.
Mode can be:
#define FILEMODE_READONLY 0x01
#define FILEMODE_WRITEONLY 0x02
#define FILEMODE_READWRITE 0x04
#define FILEMODE_APPEND 0x08
Type is (mode = ReadOnly):
#define FILETYPE_PERM 0x08 // try the global dir only
#define FILETYPE_OPTIONAL 0x10 // try the global dir first, then try the local dir
#define FILETYPE_CONFIG 0x20 // try the local dir only
Type is (mode = WriteOnly or ReadWrite):
FILETYPE_PERM: error
FILETYPE_OPTIONAL: error
FILETYPE_CONFIG: try the local dir only
*/
FILE *OpenGameFile(const char *filename, int mode, int type)
{
char *rfilename;
char *openmode;
FILE *fp;
if ((type != FILETYPE_CONFIG) && (mode != FILEMODE_READONLY))
return NULL;
switch(mode) {
case FILEMODE_READONLY:
openmode = "rb";
break;
case FILEMODE_WRITEONLY:
openmode = "wb";
break;
case FILEMODE_READWRITE:
openmode = "w+";
break;
case FILEMODE_APPEND:
openmode = "ab";
break;
default:
return NULL;
}
if (type != FILETYPE_CONFIG) {
rfilename = FixFilename(filename, global_dir, 0);
fp = fopen(rfilename, openmode);
free(rfilename);
if (fp != NULL) {
return fp;
}
rfilename = FixFilename(filename, global_dir, 1);
fp = fopen(rfilename, openmode);
free(rfilename);
if (fp != NULL) {
return fp;
}
}
if (type != FILETYPE_PERM) {
rfilename = FixFilename(filename, local_dir, 0);
fp = fopen(rfilename, openmode);
free(rfilename);
if (fp != NULL) {
return fp;
}
rfilename = FixFilename(filename, local_dir, 1);
fp = fopen(rfilename, openmode);
free(rfilename);
return fp;
}
return NULL;
}
/*
Close a fd returned from OpenGameFile
Currently this just uses stdio, so CloseGameFile is redundant.
*/
int CloseGameFile(FILE *pfd)
{
return fclose(pfd);
}
/*
Get the filesystem attributes of a file
#define FILEATTR_DIRECTORY 0x0100
#define FILEATTR_READABLE 0x0200
#define FILEATTR_WRITABLE 0x0400
Error or can't access it: return value of 0 (What is the game going to do about it anyway?)
*/
static int GetFA(const char *filename)
{
struct stat buf;
int attr;
attr = 0;
if (stat(filename, &buf) == 0) {
if (S_ISDIR(buf.st_mode)) {
attr |= FILEATTR_DIRECTORY;
}
if (access(filename, R_OK) == 0) {
attr |= FILEATTR_READABLE;
}
if (access(filename, W_OK) == 0) {
attr |= FILEATTR_WRITABLE;
}
}
return attr;
}
static time_t GetTS(const char *filename)
{
struct stat buf;
if (stat(filename, &buf) == 0) {
return buf.st_mtime;
}
return 0;
}
int GetGameFileAttributes(const char *filename, int type)
{
struct stat buf;
char *rfilename;
int attr;
attr = 0;
if (type != FILETYPE_CONFIG) {
rfilename = FixFilename(filename, global_dir, 0);
if (stat(rfilename, &buf) == 0) {
if (S_ISDIR(buf.st_mode)) {
attr |= FILEATTR_DIRECTORY;
}
if (access(rfilename, R_OK) == 0) {
attr |= FILEATTR_READABLE;
}
if (access(rfilename, W_OK) == 0) {
attr |= FILEATTR_WRITABLE;
}
free(rfilename);
return attr;
}
free(rfilename);
rfilename = FixFilename(filename, global_dir, 1);
if (stat(rfilename, &buf) == 0) {
if (S_ISDIR(buf.st_mode)) {
attr |= FILEATTR_DIRECTORY;
}
if (access(rfilename, R_OK) == 0) {
attr |= FILEATTR_READABLE;
}
if (access(rfilename, W_OK) == 0) {
attr |= FILEATTR_WRITABLE;
}
free(rfilename);
return attr;
}
free(rfilename);
}
if (type != FILETYPE_PERM) {
rfilename = FixFilename(filename, local_dir, 0);
if (stat(rfilename, &buf) == 0) {
if (S_ISDIR(buf.st_mode)) {
attr |= FILEATTR_DIRECTORY;
}
if (access(rfilename, R_OK) == 0) {
attr |= FILEATTR_READABLE;
}
if (access(rfilename, W_OK) == 0) {
attr |= FILEATTR_WRITABLE;
}
free(rfilename);
return attr;
}
free(rfilename);
rfilename = FixFilename(filename, local_dir, 1);
if (stat(rfilename, &buf) == 0) {
if (S_ISDIR(buf.st_mode)) {
attr |= FILEATTR_DIRECTORY;
}
if (access(rfilename, R_OK) == 0) {
attr |= FILEATTR_READABLE;
}
if (access(rfilename, W_OK) == 0) {
attr |= FILEATTR_WRITABLE;
}
free(rfilename);
return attr;
}
free(rfilename);
}
return 0;
}
/*
Delete a file: local dir only
*/
int DeleteGameFile(const char *filename)
{
char *rfilename;
int ret;
rfilename = FixFilename(filename, local_dir, 0);
ret = unlink(rfilename);
free(rfilename);
if (ret == -1) {
rfilename = FixFilename(filename, local_dir, 1);
ret = unlink(rfilename);
free(rfilename);
}
return ret;
}
/*
Create a directory: local dir only
TODO: maybe also mkdir parent directories, if they do not exist?
*/
int CreateGameDirectory(const char *dirname)
{
char *rfilename;
int ret;
rfilename = FixFilename(dirname, local_dir, 0);
ret = mkdir(rfilename, S_IRWXU);
free(rfilename);
if (ret == -1) {
rfilename = FixFilename(dirname, local_dir, 1);
ret = mkdir(rfilename, S_IRWXU);
free(rfilename);
}
return ret;
}
/* This struct is private. */
typedef struct GameDirectory
{
DIR *localdir; /* directory opened with opendir */
DIR *globaldir;
char *localdirname;
char *globaldirname;
char *pat; /* pattern to match */
GameDirectoryFile tmp; /* Temp space */
} GameDirectory;
/*
"Open" a directory dirname, with type type
Returns a pointer to a directory datatype
Pattern is the pattern to match
*/
void *OpenGameDirectory(const char *dirname, const char *pattern, int type)
{
char *localdirname, *globaldirname;
DIR *localdir, *globaldir;
GameDirectory *gd;
globaldir = NULL;
globaldirname = NULL;
if (type != FILETYPE_CONFIG) {
globaldirname = FixFilename(dirname, global_dir, 0);
globaldir = opendir(globaldirname);
if (globaldir == NULL) {
free(globaldirname);
globaldirname = FixFilename(dirname, global_dir, 1);
globaldir = opendir(globaldirname);
if (globaldir == NULL)
free(globaldirname);
}
}
localdir = NULL;
localdirname = NULL;
if (type != FILETYPE_PERM) {
localdirname = FixFilename(dirname, local_dir, 0);
localdir = opendir(localdirname);
if (localdir == NULL) {
free(localdirname);
localdirname = FixFilename(dirname, local_dir, 1);
localdir = opendir(localdirname);
if (localdir == NULL)
free(localdirname);
}
}
if (localdir == NULL && globaldir == NULL)
return NULL;
gd = (GameDirectory *)malloc(sizeof(GameDirectory));
gd->localdir = localdir;
gd->globaldir = globaldir;
gd->localdirname = localdirname;
gd->globaldirname = globaldirname;
gd->pat = strdup(pattern);
return gd;
}
/*
This struct is public.
typedef struct GameDirectoryFile
{
char *filename;
int attr;
} GameDirectoryFile;
*/
/*
Returns the next match of pattern with the contents of dir
f is the current file
*/
GameDirectoryFile *ScanGameDirectory(void *dir)
{
char *ptr;
struct dirent *file;
GameDirectory *directory;
directory = (GameDirectory *)dir;
if (directory->globaldir) {
while ((file = readdir(directory->globaldir)) != NULL) {
if (fnmatch(directory->pat, file->d_name, FNM_PATHNAME) == 0) {
ptr = FixFilename(file->d_name, directory->globaldirname, 0);
directory->tmp.attr = GetFA(ptr);
free(ptr);
directory->tmp.filename = file->d_name;
return &directory->tmp;
}
}
closedir(directory->globaldir);
free(directory->globaldirname);
directory->globaldir = NULL;
directory->globaldirname = NULL;
}
if (directory->localdir) {
while ((file = readdir(directory->localdir)) != NULL) {
if (fnmatch(directory->pat, file->d_name, FNM_PATHNAME) == 0) {
ptr = FixFilename(file->d_name, directory->localdirname, 0);
directory->tmp.attr = GetFA(ptr);
directory->tmp.timestamp = GetTS(ptr);
free(ptr);
directory->tmp.filename = file->d_name;
return &directory->tmp;
}
}
closedir(directory->localdir);
free(directory->localdirname);
directory->localdir = NULL;
directory->localdirname = NULL;
}
return NULL;
}
/*
Close directory
*/
int CloseGameDirectory(void *dir)
{
GameDirectory *directory = (GameDirectory *)dir;
if (directory) {
free(directory->pat);
if (directory->localdirname)
free(directory->localdirname);
if (directory->globaldirname)
free(directory->globaldirname);
if (directory->localdir)
closedir(directory->localdir);
if (directory->globaldir)
closedir(directory->globaldir);
return 0;
}
return -1;
}
#ifdef FILES_DRIVER
int main(int argc, char *argv[])
{
FILE *fp;
char buf[64];
void *dir;
SetGameDirectories("tmp1", "tmp2");
fp = OpenGameFile("tester", FILEMODE_WRITEONLY, FILETYPE_CONFIG);
fputs("test\n", fp);
CloseGameFile(fp);
CreateGameDirectory("yaya");
CreateGameDirectory("tester2");
CreateGameDirectory("tester2/blah");
fp = OpenGameFile("tester", FILEMODE_READONLY, FILETYPE_OPTIONAL);
printf("Read: %s", fgets(buf, 60, fp));
CloseGameFile(fp);
fp = OpenGameFile("tester", FILEMODE_READONLY, FILETYPE_CONFIG);
printf("Read: %s", fgets(buf, 60, fp));
CloseGameFile(fp);
dir = OpenGameDirectory(".", "*", FILETYPE_OPTIONAL);
if (dir != NULL) {
GameDirectoryFile *gd;
while ((gd = ScanGameDirectory(dir)) != NULL) {
printf("Name: %s, Attr: %08X\n", gd->filename, gd->attr);
}
CloseGameDirectory(dir);
} else {
printf("Could not open the directory...\n");
}
DeleteGameFile("tester");
return 0;
}
#endif

34
src/files.h Normal file
View file

@ -0,0 +1,34 @@
#ifndef __FILES_H__
#define __FILES_H__
#define FILEMODE_READONLY 0x01
#define FILEMODE_WRITEONLY 0x02
#define FILEMODE_READWRITE 0x04
#define FILEMODE_APPEND 0x08
#define FILETYPE_PERM 0x10
#define FILETYPE_OPTIONAL 0x20
#define FILETYPE_CONFIG 0x40
#define FILEATTR_DIRECTORY 0x0100
#define FILEATTR_READABLE 0x0200
#define FILEATTR_WRITABLE 0x0400
typedef struct GameDirectoryFile
{
char *filename;
int attr;
time_t timestamp;
} GameDirectoryFile;
int SetGameDirectories(const char *local, const char *global);
FILE *OpenGameFile(const char *filename, int mode, int type);
int CloseGameFile(FILE *pfd);
int GetGameFileAttributes(const char *filename, int type);
int DeleteGameFile(const char *filename);
int CreateGameDirectory(const char *dirname);
void *OpenGameDirectory(const char *dirname, const char *pattern, int type);
GameDirectoryFile *ScanGameDirectory(void *dir);
int CloseGameDirectory(void *dir);
#endif

View file

@ -11,7 +11,7 @@ extern "C" {
#include <limits.h>
#include <inttypes.h> /* int64_t */
void FixFilename(char *str);
#include "files.h"
#define PACKED __attribute__((packed))

View file

@ -48,17 +48,20 @@ int JoystickEnabled;
int MouseVelX;
int MouseVelY;
extern int ScanDrawMode; /* to fix image loading */
extern int ScanDrawMode;
extern SCREENDESCRIPTORBLOCK ScreenDescriptorBlock;
extern unsigned char KeyboardInput[MAX_NUMBER_OF_INPUT_KEYS];
extern unsigned char GotAnyKey;
extern int NormalFrameTime;
SDL_Surface *surface;
/* SDL_Joystick *joy; */
/* defaults */
static int WantFullscreen = 1;
static int WantSound = 1;
int WantSound = 1;
static int WantCDRom = 1;
static int WantJoystick = 1;
#if GL_EXT_secondary_color
PFNGLSECONDARYCOLORPOINTEREXTPROC pglSecondaryColorPointerEXT;
@ -195,13 +198,10 @@ const int TotalVideoModes = sizeof(VideoModeList) / sizeof(VideoModeList[0]);
void LoadDeviceAndVideoModePreferences()
{
/*
fprintf(stderr, "LoadDeviceAndVideoModePreferences()\n");
*/
FILE *fp;
int mode;
fp = fopen("AvP_TempVideo.cfg", "r");
fp = OpenGameFile("AvP_TempVideo.cfg", FILEMODE_READONLY, FILETYPE_CONFIG);
if (fp != NULL) {
if (fscanf(fp, "%d", &mode) == 1) {
@ -235,12 +235,9 @@ void LoadDeviceAndVideoModePreferences()
void SaveDeviceAndVideoModePreferences()
{
/*
fprintf(stderr, "SaveDeviceAndVideoModePreferences()\n");
*/
FILE *fp;
fp = fopen("AvP_TempVideo.cfg", "w");
fp = OpenGameFile("AvP_TempVideo.cfg", FILEMODE_WRITEONLY, FILETYPE_CONFIG);
if (fp != NULL) {
fprintf(fp, "%d\n", CurrentVideoMode);
fclose(fp);
@ -249,9 +246,6 @@ void SaveDeviceAndVideoModePreferences()
void PreviousVideoMode2()
{
/*
fprintf(stderr, "PreviousVideoMode2()\n");
*/
int cur = CurrentVideoMode;
do {
@ -267,9 +261,6 @@ void PreviousVideoMode2()
void NextVideoMode2()
{
/*
fprintf(stderr, "NextVideoMode2()\n");
*/
int cur = CurrentVideoMode;
do {
@ -286,17 +277,11 @@ void NextVideoMode2()
char *GetVideoModeDescription2()
{
/*
fprintf(stderr, "GetVideoModeDescription2()\n");
*/
return "SDL";
}
char *GetVideoModeDescription3()
{
/*
fprintf(stderr, "GetVideoModeDescription3()\n");
*/
static char buf[64];
snprintf(buf, 64, "%dx%d", VideoModeList[CurrentVideoMode].w, VideoModeList[CurrentVideoMode].h);
@ -357,6 +342,19 @@ int InitSDL()
}
LoadDeviceAndVideoModePreferences();
#if 0
if (WantJoystick) {
SDL_Init(SDL_INIT_JOYSTICK);
if (SDL_NumJoysticks() > 0) {
joy = SDL_JoystickOpen(0);
if (joy) {
GotJoystick = 1;
}
}
}
#endif
surface = NULL;
@ -539,6 +537,18 @@ int InitialiseWindowsSystem(HANDLE hInstance, int nCmdShow, int WinInitMode)
return 0;
}
int ExitWindowsSystem()
{
#if 0
if (joy) {
SDL_JoystickClose(joy);
}
#endif
SDL_Quit();
return 0;
}
static int GotPrintScn, HavePrintScn;
static int KeySymToKey(int keysym)
@ -848,6 +858,7 @@ static void handle_buttonpress(int button, int press)
DebouncedKeyboardInput[key] = 1;
}
GotAnyKey = 1;
KeyboardInput[key] = press;
}
@ -924,7 +935,34 @@ void CheckForWindowsMessages()
MouseVelX = 0;
MouseVelY = 0;
}
/*
This is half of the necessary joystick code, the rest of the changes
involve avp/win95/usr_io.c. I don't own a joystick so I have no idea
how things should be implemented.
*/
#if 0
if (GotJoystick) {
int numbuttons;
SDL_JoystickUpdate();
numbuttons = SDL_JoystickNumButtons(joy);
if (numbuttons > 16) numbuttons = 16;
for (x = 0; x < numbuttons; x++) {
if (SDL_JoystickGetButton(joy, x)) {
GotAnyKey = 1;
if (!KeyboardInput[KEY_JOYSTICK_BUTTON_1+x]) {
KeyboardInput[KEY_JOYSTICK_BUTTON_1+x] = 1;
DebouncedKeyboardInput[KEY_JOYSTICK_BUTTON_1+x] = 1;
}
} else {
KeyboardInput[KEY_JOYSTICK_BUTTON_1+x] = 0;
}
}
}
#endif
if ((KeyboardInput[KEY_LEFTALT]||KeyboardInput[KEY_RIGHTALT]) && DebouncedKeyboardInput[KEY_CR]) {
SDL_GrabMode gm;
@ -967,11 +1005,53 @@ void FlipBuffers()
SDL_Flip(surface);
}
int ExitWindowsSystem()
{
SDL_Quit();
char *AvpCDPath = 0;
return 0;
void InitGameDirectories(char *argv0)
{
extern char *SecondTex_Directory;
extern char *SecondSoundDir;
char *homedir, *gamedir, *localdir, *tmp;
SecondTex_Directory = "graphics/";
SecondSoundDir = "sound/";
/*
printf("argv[0] = %s\n", argv0);
printf("$HOME = %s\n", getenv("HOME"));
printf("$AVP_DATA = %s\n", getenv("AVP_DATA"));
*/
homedir = getenv("HOME");
if (homedir == NULL)
homedir = ".";
localdir = (char *)malloc(strlen(homedir)+10);
strcpy(localdir, homedir);
strcat(localdir, "/");
strcat(localdir, ".avp");
tmp = NULL;
/* TODO: for each step, check existance of avp_rifs directory? */
gamedir = getenv("AVP_DATA");
if (gamedir == NULL) {
tmp = strdup(argv0);
gamedir = strrchr(tmp, '/');
if (gamedir == NULL) {
gamedir = ".";
} else {
*gamedir = 0;
gamedir = tmp;
}
}
SetGameDirectories(localdir, gamedir);
free(localdir);
if (tmp)
free(tmp);
/* delete some log files */
DeleteGameFile("dx_error.log");
}
static struct option getopt_long_options[] = {
@ -981,9 +1061,10 @@ static struct option getopt_long_options[] = {
{ "windowed", 0, NULL, 'w' },
{ "nosound", 0, NULL, 's' },
{ "nocdrom", 0, NULL, 'c' },
/* { "nojoy", 0, NULL, 'j' }, */
{ "debug", 0, NULL, 'd' },
/*
{ "loadrifs", 0, NULL, 'l' },
{ "loadrifs", 1, NULL, 'l' },
{ "server", 0, someval, 1 },
{ "client", 1, someval, 2 },
*/
@ -999,6 +1080,7 @@ static const char *usage_string =
" [-w | --windowed] Run the game in a window\n"
" [-s | --nosound] Do not access the soundcard\n"
" [-c | --nocdrom] Do not access the CD-ROM\n"
/* " [-j | --nojoy] Do not access the joystick\n" */
;
int main(int argc, char *argv[])
@ -1026,6 +1108,11 @@ int main(int argc, char *argv[])
case 'c':
WantCDRom = 0;
break;
/*
case 'j':
WantJoystick = 0;
break;
*/
case 'd': {
extern int DebuggingCommandsActive;
DebuggingCommandsActive = 1;
@ -1037,6 +1124,8 @@ int main(int argc, char *argv[])
}
}
InitGameDirectories(argv[0]);
if (InitSDL() == -1) {
fprintf(stderr, "Could not find a sutable resolution!\n");
fprintf(stderr, "At least 512x384 is needed. Does OpenGL work?\n");
@ -1047,9 +1136,6 @@ int main(int argc, char *argv[])
SetFastRandom();
/* WeWantAnIntro(); */
GetPathFromRegistry();
#if MARINE_DEMO
ffInit("fastfile/mffinfo.txt","fastfile/");
#elif ALIEN_DEMO
@ -1071,7 +1157,7 @@ int main(int argc, char *argv[])
LoadKeyConfiguration();
if (WantSound) SoundSys_Start();
SoundSys_Start();
if (WantCDRom) CDDA_Start();
InitTextStrings();

View file

@ -31,12 +31,15 @@ ALCdevice *AvpSoundDevice;
ALvoid *AvpSoundContext;
int AvpFrequency = 44100;
extern int WantSound;
static int SoundActivated = 0;
/*
openal.c TODO:
1. AL_PITCH code does not work.
OpenAL alf_tpitch is currently broken.
OpenAL alf_tpitch is currently broken. (Doesn't work with LOOPING, etc.)
Maps like Last Stand use it for (some rather odd) ambient sounds.
2. Panning somewhat works now. Need someone to verify.
3. There is no EAX/Reverb. But there's probably not much I can do...
4. Restarting sound system may or may not work.
@ -58,14 +61,16 @@ int PlatStartSoundSys()
0
};
SoundActivated = 0;
if (WantSound == 0)
return 0;
attrlist[0] = ALC_FREQUENCY;
attrlist[1] = AvpFrequency;
attrlist[2] = ALC_SYNC;
attrlist[3] = AL_FALSE;
attrlist[4] = 0;
SoundActivated = 0;
snprintf(buf, sizeof(buf), "'( (sampling-rate %d ))\n", AvpFrequency);
AvpSoundDevice = alcOpenDevice(buf);
@ -128,7 +133,7 @@ int PlatStartSoundSys()
void PlatEndSoundSys()
{
/* TODO - free everything */
printf("PlatEndSoundSys()\n");
fprintf(stderr, "OPENAL: PlatEndSoundSys()\n");
}
// this table plots the frequency change for
@ -391,7 +396,11 @@ int PlatPlaySound(int activeIndex)
if (!PlatSoundHasStopped(activeIndex))
PlatStopSound (activeIndex);
/* TODO: hack until pitching works right */
if (GameSounds[si].pitch < -500)
return 0;
alSourcei (ActiveSounds[activeIndex].ds3DBufferP, AL_BUFFER,
GameSounds[si].dsBufferP);
@ -427,18 +436,16 @@ int PlatPlaySound(int activeIndex)
if (!ActiveSounds[activeIndex].paused) {
alSourcePlay (ActiveSounds[activeIndex].ds3DBufferP);
#ifdef OPENAL_DEBUG
if (ActiveSounds[activeIndex].loop) {
/*
printf("Playing sound %i %s looping in slot %i\n",
fprintf(stderr, "OPENAL: Playing sound %i %s looping in slot %i\n",
si, GameSounds[si].wavName, activeIndex);
*/
} else {
/*
printf("Playing sound %i %s once in slot %i\n",
si, GameSounds[si].wavName, activeIndex);
*/
fprintf(stderr, "OPENAL: Playing sound %i %s once in slot %i\n",
si, GameSounds[si].wavName, activeIndex);
}
#endif
}
return 1;
@ -446,8 +453,9 @@ int PlatPlaySound(int activeIndex)
void PlatStopSound(int activeIndex)
{
/* printf("PlatStopSound(%d)\n", activeIndex); */
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: PlatStopSound(%d)\n", activeIndex);
#endif
if (!SoundActivated)
return;
@ -521,19 +529,25 @@ int PlatChangeSoundPitch(int activeIndex, int pitch)
GameSounds[gsi].pitch, pitch);
}
if (pitch < -500) { /* currently can't play it anyway... */
alSourceStop(ActiveSounds[activeIndex].ds3DBufferP);
return 0;
}
ActiveSounds[activeIndex].pitch = pitch;
/*
printf("NEWFREQ PlatChangeSoundPitch(%d, %d) = %f\n", activeIndex, pitch, (double)frequency / (double)GameSounds[ActiveSounds[activeIndex].soundIndex].dsFrequency);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: PlatChangeSoundPitch(%d, %d) = %f\n", activeIndex, pitch, (double)frequency / (double)GameSounds[ActiveSounds[activeIndex].soundIndex].dsFrequency);
#endif
return 1;
}
int PlatSoundHasStopped(int activeIndex)
{
ALint val;
/*
printf("PlatSoundHasStopped(%d)\n", activeIndex);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "PlatSoundHasStopped(%d)\n", activeIndex);
#endif
if (!SoundActivated)
return 0;
@ -574,12 +588,12 @@ int PlatDo3dSound(int activeIndex)
if (ActiveSounds[activeIndex].paused) {
if (distance < (ActiveSounds[activeIndex].threedeedata.outer_range + SOUND_DEACTIVATERANGE)) {
PlatStopSound (activeIndex);
#if 1 /* PLEASE REMOVE IFDEF! */
if (ActiveSounds[activeIndex].loop)
alSourcei (ActiveSounds[activeIndex].ds3DBufferP, AL_LOOPING, AL_TRUE);
else
alSourcei (ActiveSounds[activeIndex].ds3DBufferP, AL_LOOPING, AL_FALSE);
#endif
alSourcePlay (ActiveSounds[activeIndex].ds3DBufferP);
newVolume = 0;
ActiveSounds[activeIndex].paused = 0;
@ -616,9 +630,11 @@ int PlatDo3dSound(int activeIndex)
newVolume = VOLUME_MAX;
if (newVolume < VOLUME_MIN)
newVolume = VOLUME_MIN;
/*
printf("PlatDo3dSound: idx = %d, volume = %d, distance = %d\n", activeIndex, newVolume, distance);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: PlatDo3dSound: idx = %d, volume = %d, distance = %d\n", activeIndex, newVolume, distance);
#endif
if (PlatChangeSoundVolume (activeIndex, newVolume) == SOUND_PLATFORMERROR) {
return SOUND_PLATFORMERROR;
}
@ -634,9 +650,9 @@ int PlatDo3dSound(int activeIndex)
ActiveSounds[activeIndex].PropSetP_pos[2] = (ALfloat)relativePosn.vz / (ALfloat)distance;
alSourcefv (ActiveSounds[activeIndex].ds3DBufferP, AL_POSITION, ActiveSounds[activeIndex].PropSetP_pos);
/*
printf("Sound : (%f, %f, %f) [%d] [%d,%d]\n", ActiveSounds[activeIndex].PropSetP_pos[0], ActiveSounds[activeIndex].PropSetP_pos[1], ActiveSounds[activeIndex].PropSetP_pos[2], activeIndex, ActiveSounds[activeIndex].threedeedata.inner_range, ActiveSounds[activeIndex].threedeedata.outer_range);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: Sound : (%f, %f, %f) [%d] [%d,%d]\n", ActiveSounds[activeIndex].PropSetP_pos[0], ActiveSounds[activeIndex].PropSetP_pos[1], ActiveSounds[activeIndex].PropSetP_pos[2], activeIndex, ActiveSounds[activeIndex].threedeedata.inner_range, ActiveSounds[activeIndex].threedeedata.outer_range);
#endif
ActiveSounds[activeIndex].PropSetP_vel[0] =
ActiveSounds[activeIndex].threedeedata.velocity.vx;
ActiveSounds[activeIndex].PropSetP_vel[1] =
@ -695,9 +711,9 @@ void PlatUpdatePlayer()
pos[1] = Global_VDB_Ptr->VDB_World.vy; // 10000.0;
pos[2] = Global_VDB_Ptr->VDB_World.vz; // 10000.0;
/*
printf("Player: (%f, %f, %f) (%f, %f, %f %f, %f, %f)\n", pos[0], pos[1], pos[2], or[0], or[1], or[2], or[3], or[4], or[5]);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: Player: (%f, %f, %f) (%f, %f, %f %f, %f, %f)\n", pos[0], pos[1], pos[2], or[0], or[1], or[2], or[3], or[4], or[5]);
#endif
// fixme: add reverb check
alListenerfv (AL_ORIENTATION, or);
// alListenerfv (AL_VELOCITY, vel);
@ -709,6 +725,14 @@ void PlatEndGameSound(SOUNDINDEX index)
{
int i;
GameSounds[index].loaded = 0;
GameSounds[index].dsFrequency = 0;
if (GameSounds[index].wavName) {
DeallocateMem(GameSounds[index].wavName);
GameSounds[index].wavName = NULL;
}
if (!SoundActivated)
return;
@ -726,32 +750,23 @@ void PlatEndGameSound(SOUNDINDEX index)
alDeleteBuffers(1, &(GameSounds[index].dsBufferP));
GameSounds[index].dsBufferP = 0;
}
GameSounds[index].loaded = 0;
GameSounds[index].dsFrequency = 0;
if (GameSounds[index].wavName) {
DeallocateMem(GameSounds[index].wavName);
GameSounds[index].wavName = NULL;
}
}
unsigned int PlatMaxHWSounds()
{
/*
printf("PlatMaxHWSounds()\n");
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: PlatMaxHWSounds()\n");
#endif
return 32;
}
void InitialiseBaseFrequency(SOUNDINDEX soundNum)
{
/* just set the pitch everytime. */
#if 0
int frequency;
printf("FREQ InitialiseBaseFrequency(%d) [%d]\n", soundNum, GameSounds[soundNum].pitch==PITCH_DEFAULTPLAT);
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: InitialiseBaseFrequency(%d) [%d] pitch = %d\n", soundNum, GameSounds[soundNum].pitch==PITCH_DEFAULTPLAT, GameSounds[soundNum].pitch);
#endif
if(GameSounds[soundNum].pitch>PITCH_MAXPLAT) GameSounds[soundNum].pitch=PITCH_MAXPLAT;
if(GameSounds[soundNum].pitch<PITCH_MINPLAT) GameSounds[soundNum].pitch=PITCH_MINPLAT;
@ -761,28 +776,29 @@ void InitialiseBaseFrequency(SOUNDINDEX soundNum)
PITCH_DEFAULTPLAT, GameSounds[soundNum].pitch);
GameSounds[soundNum].dsFrequency = frequency;
#endif
}
void PlatSetEnviroment(unsigned int env_index, float reverb_mix)
{
/*
printf("PlatSetEnvironment(%d, %f)\n", env_index, reverb_mix);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: PlatSetEnvironment(%d, %f)\n", env_index, reverb_mix);
#endif
}
void UpdateSoundFrequencies()
{
extern int SoundSwitchedOn;
/* extern int TimeScale; */
extern int TimeScale;
int i;
/* printf("FREQ UpdateSoundFreqncies()\n"); */
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: UpdateSoundFreqncies()\n");
#endif
if (!SoundActivated)
return;
if (!SoundSwitchedOn) /* TODO: maybe I should have used this var.. */
if (!SoundSwitchedOn)
return;
for (i = 0; i < SOUND_MAXACTIVE; i++) {
@ -790,11 +806,13 @@ void UpdateSoundFrequencies()
if (gameIndex == SID_NOSOUND)
continue;
/*
if (TimeScale != ONE_FIXED)
printf("NEWFREQ UpdateSoundFreqncies %d, f = %d\n", i, MUL_FIXED(GameSounds[gameIndex].dsFrequency,TimeScale));
*/
/* TODO: huh? */
if (TimeScale != ONE_FIXED) {
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: UpdateSoundFreqncies %d, f = %d\n", i, MUL_FIXED(GameSounds[gameIndex].dsFrequency,TimeScale));
#endif
}
if (ActiveSounds[i].pitch != GameSounds[gameIndex].pitch)
PlatChangeSoundPitch(i,ActiveSounds[i].pitch);
}
@ -805,27 +823,6 @@ void UpdateSoundFrequencies()
extern void *acLoadWAV (void *data, ALuint *size, void **udata,
ALushort *fmt, ALushort *chan, ALushort *freq);
int LoadWavFile(int soundNum, char * wavFileName)
{
ALsizei size, freq, bits;
ALenum format;
ALvoid *data;
/*
printf("LoadWavFile(%d, %s) - sound\n", soundNum, wavFileName);
*/
if (!SoundActivated)
return 0;
alutLoadWAV (wavFileName, &data, &format, &size, &bits, &freq);
alGenBuffers (1, &(GameSounds[soundNum].dsBufferP));
alBufferData (GameSounds[soundNum].dsBufferP, format, data, size, freq);
GameSounds[soundNum].loaded = 1;
free (data);
return 0;
}
static unsigned char *Force8to16 (unsigned char *buf, int *len)
{
@ -843,44 +840,137 @@ static unsigned char *Force8to16 (unsigned char *buf, int *len)
*len *= 2;
return nbuf;
}
int LoadWavFile(int soundNum, char * wavFileName)
{
ALuint size;
ALushort freq, chan, format;
ALvoid *data, *bufferPtr;
int len, seclen;
FILE *fp;
#ifdef OPENAL_DEBUG
fprintf(stderr, "LoadWavFile(%d, %s) - sound\n", soundNum, wavFileName);
#endif
if (!SoundActivated)
return 0;
/* TODO: Perm for now, until custom rifs can be loaded in ~/.avp */
fp = OpenGameFile(wavFileName, FILEMODE_READONLY, FILETYPE_PERM);
if (fp == NULL)
return 0;
fseek(fp, 0, SEEK_END);
len = ftell(fp);
rewind(fp);
data = malloc(len);
fread(data, 1, len, fp);
fclose(fp);
if (acLoadWAV (data, &size, &bufferPtr, &format,
&chan, &freq) == NULL) {
fprintf(stderr, "LoadWavFile: Unable to convert data\n");
free(data);
return 0;
}
free(data);
data = bufferPtr;
len = size;
/* openal conv. 8->16 is not good at all */
if (format == AUDIO_U8) {
unsigned char *nb = Force8to16 (data, &len);
format = AUDIO_S16LSB;
free (data);
data = nb;
}
if ((format == AUDIO_S16LSB) || (format == AUDIO_S16MSB)) {
int bps;
if (chan == 2) {
format = AL_FORMAT_STEREO16;
bps = freq * 2 * 2;
} /* else if (rchan == 1) */ {
format = AL_FORMAT_MONO16;
bps = freq * 2 * 1;
}
seclen = DIV_FIXED(len, bps);
} else {
free(data);
return 0;
}
alGenBuffers (1, &(GameSounds[soundNum].dsBufferP));
alBufferData (GameSounds[soundNum].dsBufferP, format, data, len, freq);
{
char * wavname = strrchr (wavFileName, '\\');
if (wavname)
wavname++;
else
wavname = wavFileName;
GameSounds[soundNum].wavName = (char *)AllocateMem (strlen (wavname) + 1);
strcpy (GameSounds[soundNum].wavName, wavname);
}
GameSounds[soundNum].flags = SAMPLE_IN_HW;
GameSounds[soundNum].length = (seclen != 0) ? seclen : 1;
GameSounds[soundNum].dsFrequency = freq;
free (data);
return 1;
}
unsigned char *ExtractWavFile(int soundIndex, unsigned char *bufferPtr)
{
ALint len, seclen = 0;
unsigned char *nb;
void *udata;
ALushort rfmt, rchan, rfreq;
ALuint rsize;
int slen;
/* printf("ExtractWavFile(%d, %p)\n", soundIndex, bufferPtr); */
if (!SoundActivated)
return 0;
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: ExtractWavFile(%d, %p)\n", soundIndex, bufferPtr);
#endif
slen = strlen (bufferPtr) + 1;
GameSounds[soundIndex].wavName = (char *)AllocateMem (slen);
strcpy (GameSounds[soundIndex].wavName, bufferPtr);
if (!SoundActivated)
return 0;
bufferPtr += slen;
/*
printf("Loaded %s\n", GameSounds[soundIndex].wavName);
*/
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: Loaded %s\n", GameSounds[soundIndex].wavName);
#endif
#if 1 /* TODO: replace with own routine later */
if (acLoadWAV (bufferPtr, &rsize, &udata, &rfmt,
&rchan, &rfreq) == NULL) {
printf("Unable to convert data\n");
return (unsigned char *)0;
fprintf(stderr, "ExtractWavFile: Unable to convert data\n");
return NULL;
}
len = rsize;
/* openal conv. 8->16 is not good at all */
if ((rfmt == AUDIO_U8)) {
nb = Force8to16 (udata, &len);
if (rfmt == AUDIO_U8) {
unsigned char *nb = Force8to16 (udata, &len);
rfmt = AUDIO_S16LSB;
free (udata);
udata = nb;
}
}
if ((rfmt == AUDIO_S16LSB) || (rfmt == AUDIO_S16MSB)) {
int bps;
@ -902,11 +992,11 @@ printf("Loaded %s\n", GameSounds[soundIndex].wavName);
alBufferData (GameSounds[soundIndex].dsBufferP,
rfmt, udata, len, rfreq);
GameSounds[soundIndex].loaded = 1;
/* GameSounds[soundIndex].loaded = 1; */
GameSounds[soundIndex].flags = SAMPLE_IN_HW;
GameSounds[soundIndex].length = (seclen != 0) ? seclen : 1;
GameSounds[soundIndex].dsFrequency = rfreq;
GameSounds[soundIndex].pitch = PITCH_DEFAULTPLAT;
/* GameSounds[soundIndex].pitch = PITCH_DEFAULTPLAT; */
#if 1 /* TODO: see above */
free (udata);
@ -923,11 +1013,10 @@ int LoadWavFromFastFile(int soundNum, char * wavFileName)
FFILE *fp;
unsigned char *buf;
unsigned int len = 0;
/* printf("LoadWavFromFastFile(%d, %s)\n", soundNum, wavFileName); */
if (!SoundActivated)
return 0;
#ifdef OPENAL_DEBUG
fprintf(stderr, "OPENAL: LoadWavFromFastFile(%d, %s)\n", soundNum, wavFileName);
#endif
if ((fp = ffopen (wavFileName, "rb")) != NULL) {
ffseek (fp, 0, SEEK_END);

View file

@ -121,21 +121,6 @@ void ATRemoveTexture(void * pTexture)
}
/* avpreg.cpp */
char *AvpCDPath = 0;
void GetPathFromRegistry()
{
extern char * SecondTex_Directory;
extern char * SecondSoundDir;
fprintf(stderr, "GetPathFromRegistry()\n");
SecondTex_Directory = "./graphics";
SecondSoundDir = "./sounds";
}
/* d3_func.cpp */
int GetTextureHandle(IMAGEHEADER *imageHeaderPtr)
{
@ -191,32 +176,6 @@ void CheckWireFrameMode(int shouldBeOn)
fprintf(stderr, "CheckWireFrameMode(%d)\n", shouldBeOn);
}
void WriteEndCodeToExecuteBuffer()
{
fprintf(stderr, "WriteEndCodeToExecuteBuffer()\n");
}
BOOL UnlockExecuteBufferAndPrepareForUse()
{
fprintf(stderr, "UnlockExecuteBufferAndPrepareForUse()\n");
return FALSE;
}
BOOL ExecuteBuffer()
{
fprintf(stderr, "ExecuteBuffer()\n");
return FALSE;
}
BOOL EndD3DScene()
{
fprintf(stderr, "EndD3DScene()\n");
return FALSE;
}
/* ddplat.cpp */
void MinimizeAllDDGraphics()
@ -304,17 +263,12 @@ void GenerateDirectDrawSurface()
}
/* dx_proj.cpp */
int use_mmx_math = 0;
/* dxlog.c */
void dx_str_log(char const * str, int line, char const * file)
{
FILE *fp;
fp = fopen("dx_error.log", "a");
fp = OpenGameFile("dx_error.log", FILEMODE_APPEND, FILETYPE_CONFIG);
if (fp == NULL)
fp = stderr;
@ -328,7 +282,7 @@ void dx_strf_log(char const * fmt, ... )
va_list ap;
FILE *fp;
fp = fopen("dx_error.log", "a");
fp = OpenGameFile("dx_error.log", FILEMODE_APPEND, FILETYPE_CONFIG);
if (fp == NULL)
fp = stderr;
@ -345,7 +299,7 @@ void dx_line_log(int line, char const * file)
{
FILE *fp;
fp = fopen("dx_error.log", "a");
fp = OpenGameFile("dx_error.log", FILEMODE_APPEND, FILETYPE_CONFIG);
if (fp == NULL)
fp = stderr;

View file

@ -156,20 +156,20 @@ namespace AwTl
{
public:
inline CreateTextureParms()
: fileNameS(NULL)
, fileH(INVALID_HANDLE_VALUE)
: loadTextureB(false)
, fileNameS(NULL)
, fileH(NULL)
, dataP(NULL)
, restoreH(NULL)
, maxReadBytes(UINT_MAX)
, bytesReadP(NULL)
, flags(AW_TLF_DEFAULT)
, originalWidthP(NULL)
, originalHeightP(NULL)
, widthP(NULL)
, heightP(NULL)
, originalWidthP(NULL)
, originalHeightP(NULL)
, prevTexP(static_cast<D3DTexture *>(NULL))
, prevTexB(false)
, loadTextureB(false)
, callbackF(NULL)
, rectA(NULL)
{
@ -180,7 +180,7 @@ namespace AwTl
bool loadTextureB;
char *fileNameS;
HANDLE fileH;
FILE *fileH;
PtrUnionConst dataP;
AW_BACKUPTEXTUREHANDLE restoreH;
@ -228,7 +228,7 @@ namespace AwTl
db_log1(("AW: Potential Memory Leaks Detected!!!"));
}
#ifdef _CPPRTTI
#pragma message("Run-Time Type Identification (RTTI) is enabled")
#warning "Run-Time Type Identification (RTTI) is enabled"
for (Iterator itLeak(*this) ; !itLeak.Done() ; itLeak.Next())
{
db_logf1(("\tAW Object not deallocated: Type: %s RefCnt: %u",typeid(*itLeak.Get()).name(),itLeak.Get()->m_nRefCnt));
@ -238,7 +238,7 @@ namespace AwTl
db_log1(("AW: Object dump complete"));
}
#else // ! _CPPRTTI
#pragma message("Run-Time Type Identification (RTTI) is not enabled - memory leak checking will not report types")
#warning "Run-Time Type Identification (RTTI) is not enabled - memory leak checking will not report types"
unsigned nRefs(0);
for (Iterator itLeak(*this) ; !itLeak.Done() ; itLeak.Next())
{
@ -1762,9 +1762,9 @@ namespace AwTl {
SurfUnion CreateTextureParms::DoCreate() const
{
if (INVALID_HANDLE_VALUE!=fileH)
if (NULL != fileH)
{
MediaWinFileMedium * pMedium = new MediaWinFileMedium;
MediaStdFileMedium * pMedium = new MediaStdFileMedium;
pMedium->Attach(fileH);
SurfUnion pTex = LoadTexture(pMedium,*this);
pMedium->Detach();
@ -1802,7 +1802,7 @@ namespace AwTl {
switch (*_argFormatS++)
{
case 's':
if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH)
if (pParams->fileNameS || NULL!=pParams->fileH || pParams->dataP || pParams->restoreH)
bad_parmsB = true;
else
{
@ -1811,16 +1811,16 @@ namespace AwTl {
}
break;
case 'h':
if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH)
if (pParams->fileNameS || NULL!=pParams->fileH || pParams->dataP || pParams->restoreH)
bad_parmsB = true;
else
{
pParams->fileH = va_arg(ap,HANDLE);
db_logf4(("\tFile HANDLE = 0x%08x",pParams->fileH));
pParams->fileH = va_arg(ap,FILE *);
db_logf4(("\tFile HANDLE = %p",pParams->fileH));
}
break;
case 'p':
if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH)
if (pParams->fileNameS || NULL!=pParams->fileH || pParams->dataP || pParams->restoreH)
bad_parmsB = true;
else
{
@ -1829,7 +1829,7 @@ namespace AwTl {
}
break;
case 'r':
if (pParams->fileNameS || INVALID_HANDLE_VALUE!=pParams->fileH || pParams->dataP || pParams->restoreH || UINT_MAX!=pParams->maxReadBytes || pParams->bytesReadP)
if (pParams->fileNameS || NULL!=pParams->fileH || pParams->dataP || pParams->restoreH || UINT_MAX!=pParams->maxReadBytes || pParams->bytesReadP)
bad_parmsB = true;
else
{
@ -1948,7 +1948,7 @@ namespace AwTl {
}
}
if (!pParams->fileNameS && INVALID_HANDLE_VALUE==pParams->fileH && !pParams->dataP && !pParams->restoreH)
if (!pParams->fileNameS && NULL==pParams->fileH && !pParams->dataP && !pParams->restoreH)
{
awTlLastErr = AW_TLE_BADPARMS;
db_log2("AwCreateGraphic(): ERROR: No data medium is specified");
@ -1973,9 +1973,9 @@ namespace AwTl {
{
if (pParams->fileNameS)
{
pParams->fileH = CreateFile(pParams->fileNameS,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
pParams->fileH = OpenGameFile(pParams->fileNameS, FILEMODE_READONLY, FILETYPE_PERM);
if (INVALID_HANDLE_VALUE==pParams->fileH)
if (NULL==pParams->fileH)
{
awTlLastErr = AW_TLE_CANTOPENFILE;
// awTlLastWinErr = GetLastError();
@ -1986,7 +1986,7 @@ namespace AwTl {
SurfUnion textureP = pParams->DoCreate();
CloseHandle(pParams->fileH);
fclose(pParams->fileH);
return textureP;
}

View file

@ -254,7 +254,7 @@ namespace AwTl {
case 4:
{
unsigned shift=0;
unsigned val;
unsigned val=0;
--_dstRowP.byteP; // decrement here because we increment before the first write
for (unsigned colcount = _srcWidth; colcount; --colcount)
{
@ -441,7 +441,7 @@ namespace AwTl {
class TypicalTexFileLoader : public TexFileLoader
{
protected:
TypicalTexFileLoader() : m_pRowBuf(NULL), m_ppPixMap(NULL), m_pPalette(NULL) {}
TypicalTexFileLoader() : m_pPalette(NULL), m_ppPixMap(NULL), m_pRowBuf(NULL) {}
virtual ~TypicalTexFileLoader();

View file

@ -23,7 +23,7 @@ FORCE_CHUNK_INCLUDE_IMPLEMENT(bmpnames)
BMP_Name::BMP_Name (const char * fname, int const gbnc_version)
: flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (gbnc_version << BMPNAME_PARENT_VER_SHIFT), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0), enum_id(0)
: flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (gbnc_version << BMPNAME_PARENT_VER_SHIFT), enum_id(0), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0)
#if cencon
, md5val(0)
#endif
@ -33,7 +33,7 @@ BMP_Name::BMP_Name (const char * fname, int const gbnc_version)
}
BMP_Name::BMP_Name (const char * fname)
: flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (0), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0), enum_id(0)
: flags((BMPN_Flags)DEFAULT_BMPN_FLAGS), index(0), version_num (0), enum_id(0), priority (DEFAULT_BMPN_PRIORITY), transparency_colour_union(0)
#if cencon
, md5val(0)
#endif
@ -824,8 +824,6 @@ Matching_Images_Chunk::Matching_Images_Chunk(Chunk_With_Children * parent, char
: Chunk(parent,"MATCHIMG")
, flags ((MICFlags)(*(int *)(datablock+8) & MICF_MASK))
{
char const * datastart = datablock;
spares[0] = *(int *)datablock;
spares[1] = *(int *)(datablock+4);
@ -888,7 +886,7 @@ ImageDescriptor const & Matching_Images_Chunk::GetLoadImage(ImageDescriptor cons
RIF_IMPLEMENT_DYNCREATE("BMPMD5ID",Bitmap_MD5_Chunk)
Bitmap_MD5_Chunk::Bitmap_MD5_Chunk(Chunk_With_Children * parent, int const * md5id, BMP_Name const & rcbmp, char const * rname, char const * sname)
: Chunk(parent,"BMPMD5ID"), spare(0), flags(BMD5F_0), version_num(rcbmp.version_num)
: Chunk(parent,"BMPMD5ID"), flags(BMD5F_0), version_num(rcbmp.version_num), spare(0)
{
memcpy(md5_val,md5id,16);
@ -907,7 +905,7 @@ Bitmap_MD5_Chunk::Bitmap_MD5_Chunk(Chunk_With_Children * parent, int const * md5
}
Bitmap_MD5_Chunk::Bitmap_MD5_Chunk(Chunk_With_Children * parent, char const * datablock, size_t)
: Chunk(parent,"BMPMD5ID"), spare(*(int *)datablock), flags((BMPMD5_Flags)(*(int *)(datablock+4) & BMD5F_MASK)), version_num(*(int *)(datablock+8))
: Chunk(parent,"BMPMD5ID"), flags((BMPMD5_Flags)(*(int *)(datablock+4) & BMD5F_MASK)), version_num(*(int *)(datablock+8)), spare(*(int *)datablock)
{
memcpy(md5_val,datablock+12,16);
datablock += 28;

View file

@ -378,32 +378,32 @@ ShapeInMSL const * ShapeInMSL::GetByName(char const * nam)
}
ShapeInMSL::ShapeInMSL()
: shptr(0)
, listpos(GLS_NOTINLIST)
: listpos(GLS_NOTINLIST)
, shptr(0)
, in_hash_table(FALSE)
{
}
ShapeInMSL::ShapeInMSL(int _p)
: shptr(0)
, listpos(_p)
: listpos(_p)
, shptr(0)
, in_hash_table(FALSE)
{
}
ShapeInMSL::ShapeInMSL(SHAPEHEADER * _s, char const * _n, int _p)
: shptr(_s)
: listpos(_p)
, shptr(_s)
, name(_n)
, listpos(_p)
, in_hash_table(FALSE)
{
AddToHashTables();
}
ShapeInMSL::ShapeInMSL(ShapeInMSL const & sim)
: shptr(sim.shptr)
: listpos(sim.listpos)
, shptr(sim.shptr)
, name(sim.name)
, listpos(sim.listpos)
, in_hash_table(FALSE)
{
if (sim.in_hash_table) AddToHashTables();
@ -479,11 +479,7 @@ RIFFHANDLE load_rif (const char * fname)
CL_LogFile.lprintf("FAILED TO LOAD RIF: %s\n",fname);
#endif
ReleaseDirect3D();
#if 0
char message[200];
sprintf(message,"Error loading %s",fname);
MessageBox(NULL,message,"AvP",MB_OK+MB_SYSTEMMODAL);
#endif
fprintf(stderr, "load_rif: Error loading %s\n", fname);
exit(0x111);
return INVALID_RIFFHANDLE;
@ -516,13 +512,9 @@ RIFFHANDLE load_rif_non_env (const char * fname)
#endif
ReleaseDirect3D();
#if 0
char message[200];
sprintf(message,"Error loading %s",fname);
MessageBox(NULL,message,"AvP",MB_OK+MB_SYSTEMMODAL);
#endif
fprintf(stderr, "load_rif_non_env: Error loading %s\n", fname);
exit(0x111);
return INVALID_RIFFHANDLE;
}
#if OUTPUT_LOG
@ -1559,10 +1551,7 @@ void DeallocateRifLoadedShapeheader(SHAPEHEADER * shp)
#if !StandardShapeLanguage
#error Must have standard shape language
#endif
int max_num_texs = 0;
int i;
if(shp->animation_header)
{
// so it gets deallocated properly
@ -1576,6 +1565,9 @@ void DeallocateRifLoadedShapeheader(SHAPEHEADER * shp)
}
#if !USE_LEVEL_MEMORY_POOL
int max_num_texs = 0;
int i;
if (shp->points)
{
if (*shp->points) DeallocateMem(*shp->points);

View file

@ -109,12 +109,13 @@ static inline bool IsFileInFastFile(char const * pszFileName)
static bool DoesFileExist(char const * pszFileName)
{
DWORD dwFileAttributes = GetFileAttributes(pszFileName);
if (0xffffffff == dwFileAttributes || dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
unsigned int attr = GetGameFileAttributes(pszFileName, FILETYPE_PERM);
if ((attr & FILEATTR_DIRECTORY) != 0)
return false;
else
return true;
if ((attr & FILEATTR_READABLE) == 0)
return false;
return true;
}
static char * GetPath(char * pszFileNameBuf, unsigned nBufSize, ImageDescriptor const & idsc, Chunk_With_Children * pEnvDataChunk, bool bGloballyPalettized)

View file

@ -85,7 +85,7 @@ int db_option = 0; /* Default is off. */
* logfile will go in the directory that is current when db_log_init()
* is called.
*/
#define ABSOLUTE_PATH 0
#define ABSOLUTE_PATH 1
/* M A C R O S ******************************************************** */
@ -152,12 +152,14 @@ static const char* db_assert_textA[ 3 ] =
"Expression: %s",
"File: %s Line: %d"
};
#if 0
#ifndef DB_NOWINDOWS
static const char* db_prompt_std =
"Quit program/force e(x)ception? [y/n/x]";
static const char* db_prompt_windows =
"Quit program? [Yes/No]/force exception? [Cancel]";
#endif
static const char* db_assert_log_begin_text =
"DB: FAILED ASSERTION BEGINS";
static const char* db_assert_log_end_text =
@ -394,7 +396,7 @@ void db_log_fired(const char *strP)
if(!InitialisedLog) db_log_init();
{
/* Open a file for appending, creating one if it doesn't yet exist. */
FILE *fP = fopen(LogFileNameP, "a+");
FILE *fP = OpenGameFile(LogFileNameP, FILEMODE_APPEND, FILETYPE_CONFIG);
if(!fP) return;
@ -409,13 +411,12 @@ void db_log_init(void)
sprintf( LogFileNameP, "%s", db_log_file_name );
#else
/* Append the log file name to the current working directory. */
/* TODO - path seperator */
sprintf( LogFileNameP, "%s/%s", getcwd( LogFileNameP, 240 ),
db_log_file_name );
#endif
/* Delete old log file. */
remove(LogFileNameP);
DeleteGameFile(LogFileNameP);
/* Flag that we have initialised the log file. */
InitialisedLog = 1;

View file

@ -84,10 +84,6 @@ namespace IFF
return true;
}
// The uninitialised part of byte is shifted out.
#ifdef _MSC_VER
#pragma warning(disable: 4701)
#endif
bool IlbmBodyChunk::EncodeNextRow(unsigned const * pRow)
{
if (!pEncodeDst) return false;
@ -96,7 +92,7 @@ namespace IFF
{
UBYTE * pBuf = pEncodeSrc;
unsigned byte;
unsigned byte=0;
for (unsigned x=0; x<nWidth; ++x)
{
byte <<= 1;
@ -164,9 +160,6 @@ namespace IFF
return true;
}
#ifdef _MSC_VER
#pragma warning(default: 4701)
#endif
bool IlbmBodyChunk::EndEncode()
{
@ -206,10 +199,6 @@ namespace IFF
return pData != NULL;
}
// The uninitialised part of pDecodeDst is shifted out.
#ifdef _MSC_VER
#pragma warning(disable: 4701)
#endif
unsigned const * IlbmBodyChunk::DecodeNextRow() const
{
if (!pDecodeSrc || !pDecodeDst) return NULL;
@ -224,7 +213,7 @@ namespace IFF
for (unsigned b=0; b<nBitPlanes; ++b)
{
unsigned byte;
unsigned byte=0;
for (unsigned x=0; x<nWidth; ++x)
{
if (!(x&7))
@ -282,7 +271,7 @@ namespace IFF
{
for (unsigned b=0; b<nBitPlanes; ++b)
{
unsigned byte;
unsigned byte=0;
for (unsigned x=0; x<nWidth; ++x)
{
if (!(x&7))
@ -304,9 +293,6 @@ namespace IFF
return pDecodeDst;
}
#ifdef _MSC_VER
#pragma warning(default: 4701)
#endif
IlbmBodyChunk::~IlbmBodyChunk()
{

View file

@ -2,7 +2,7 @@
#define _INCLUDED_MEDIA_HPP_
//#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) || defined(_WINDOWS)
#define _MEDIA_WIN_TARGET
// #define _MEDIA_WIN_TARGET
// #include <windows.h>
//#endif // WIN32 || _WIN32 || WINDOWS || _WINDOWS
@ -497,7 +497,12 @@ class MediaStdFileMedium : public MediaMedium
void Open(char const * pszFileName, char const * pszOpenMode)
{
m_pFile = fopen(pszFileName,pszOpenMode);
if (pszOpenMode[0] != 'r' || pszOpenMode[1] != 'b') {
fprintf(stderr, "Open(%s, %s)\n", pszFileName, pszOpenMode);
m_fError |= MME_OPENFAIL;
return;
}
m_pFile = OpenGameFile(pszFileName, FILEMODE_READONLY, FILETYPE_PERM);
if (!m_pFile)
m_fError |= MME_OPENFAIL;
}

View file

@ -116,8 +116,7 @@ BOOL Lockable_Chunk_With_Children::lock_chunk(File_Chunk & fchunk)
CloseHandle (rif_file);
return TRUE;
#endif
#endif
}
BOOL Lockable_Chunk_With_Children::unlock_chunk (File_Chunk & fchunk, BOOL updateyn)
@ -362,10 +361,9 @@ File_Chunk::File_Chunk(const char * file_name)
// Load in whole chunk and traverse
char rifIsCompressed = FALSE;
char *uncompressedData = NULL;
HANDLE rif_file;
FILE *rif_file;
DWORD file_size;
DWORD file_size_from_file;
unsigned long bytes_read;
char * buffer;
char * buffer_ptr;
char id_buffer[9];
@ -380,27 +378,28 @@ File_Chunk::File_Chunk(const char * file_name)
strcpy (filename, file_name);
rif_file = CreateFileA (file_name, GENERIC_READ, 0, 0, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, 0);
rif_file = OpenGameFile(file_name, FILEMODE_READONLY, FILETYPE_PERM);
if (rif_file == INVALID_HANDLE_VALUE) {
if (rif_file == NULL) {
error_code = CHUNK_FAILED_ON_LOAD;
return;
}
file_size = GetFileSize (rif_file, 0);
fseek(rif_file, 0, SEEK_END);
file_size = ftell(rif_file);
rewind(rif_file);
if (!ReadFile(rif_file, id_buffer, 8, &bytes_read, 0)) {
if (fread(id_buffer, 1, 8, rif_file) != 8) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
#if UseOldChunkLoader
if (strncmp (id_buffer, "REBINFLF", 8)) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
#else
@ -412,7 +411,7 @@ File_Chunk::File_Chunk(const char * file_name)
else if (strncmp (id_buffer, "REBINFF2", 8))
{
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
#endif
@ -423,10 +422,9 @@ File_Chunk::File_Chunk(const char * file_name)
pointer to the original data. */
if (rifIsCompressed)
{
if (!ReadFile(rif_file, buffer+8, (file_size-8), &bytes_read, 0))
{
if (fread(buffer+8, 1, (file_size-8), rif_file) != (file_size-8)) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
uncompressedData = HuffmanDecompress((HuffmanPackage*)buffer);
@ -438,27 +436,28 @@ File_Chunk::File_Chunk(const char * file_name)
}
else // the normal uncompressed approach:
{
if (!ReadFile(rif_file, &file_size_from_file, 4, &bytes_read, 0)) {
if (fread(&file_size_from_file, 1, 4, rif_file) != 4) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
if (file_size != file_size_from_file) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
if (!ReadFile(rif_file, buffer, (file_size-12), &bytes_read, 0))
{
if (fread(buffer, 1, (file_size-12), rif_file) != (file_size-12)) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
buffer_ptr = buffer;
}
fclose(rif_file);
// Process the RIF
// The start of the first chunk
@ -471,7 +470,6 @@ File_Chunk::File_Chunk(const char * file_name)
DynCreate(buffer_ptr);
buffer_ptr += *(int *)(buffer_ptr + 8);
}
/* KJL 17:59:42 19/09/98 - release the memory holding the rif */
@ -484,10 +482,7 @@ File_Chunk::File_Chunk(const char * file_name)
delete [] buffer;
}
CloseHandle (rif_file);
post_input_processing();
}
File_Chunk::File_Chunk()
@ -1549,10 +1544,7 @@ Environment_Data_Chunk * File_Chunk::get_env_data()
if (e_list.size())
return e_list.first_entry();
else
{
return(0);
}
return 0;
}
void File_Chunk::build_object_array()
@ -1751,10 +1743,9 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
{
char rifIsCompressed = FALSE;
char *uncompressedData = NULL;
HANDLE rif_file;
FILE *rif_file;
DWORD file_size;
DWORD file_size_from_file;
unsigned long bytes_read;
char * buffer;
char * buffer_ptr;
char id_buffer[9];
@ -1766,21 +1757,21 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
error_code = 0;
rif_file = CreateFileA (file_name, GENERIC_READ, 0, 0, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, 0);
rif_file = OpenGameFile(file_name, FILEMODE_READONLY, FILETYPE_PERM);
if (rif_file == INVALID_HANDLE_VALUE) {
if (rif_file == NULL) {
error_code = CHUNK_FAILED_ON_LOAD;
Parent_File = ParentFileStore;
return;
}
file_size = GetFileSize (rif_file, 0);
fseek(rif_file, 0, SEEK_END);
file_size = ftell(rif_file);
rewind(rif_file);
if (!ReadFile(rif_file, id_buffer, 8, &bytes_read, 0)) {
if (fread(id_buffer, 1, 8, rif_file) != 8) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
Parent_File = ParentFileStore;
return;
}
@ -1792,7 +1783,7 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
}
else if (strncmp (id_buffer, "REBINFF2", 8)) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
Parent_File = ParentFileStore;
return;
}
@ -1804,10 +1795,9 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
pointer to the original data. */
if (rifIsCompressed)
{
if (!ReadFile(rif_file, buffer+8, (file_size-8), &bytes_read, 0))
{
if (fread(buffer+8, 1, (file_size-8), rif_file) != (file_size-8)) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
Parent_File = ParentFileStore;
delete [] buffer;
return;
@ -1822,9 +1812,9 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
else // the normal uncompressed approach:
{
//get the file size stored in the rif file
if (!ReadFile(rif_file, &file_size_from_file, 4, &bytes_read, 0)) {
if (fread(&file_size_from_file, 1, 4, rif_file) != 4) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
Parent_File = ParentFileStore;
delete [] buffer;
return;
@ -1833,25 +1823,24 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
//and compare with the actual file size
if (file_size != file_size_from_file) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
Parent_File = ParentFileStore;
delete [] buffer;
return;
}
//read the rest of the file into the buffer
if (!ReadFile(rif_file, buffer, (file_size-12), &bytes_read, 0))
{
if (fread(buffer, 1, (file_size-12), rif_file) != (file_size-12)) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
Parent_File = ParentFileStore;
delete [] buffer;
return;
}
buffer_ptr = buffer;
}
fclose(rif_file);
// Process the RIF
@ -1879,12 +1868,9 @@ RIF_File_Chunk::RIF_File_Chunk (Chunk_With_Children * parent, const char * file_
delete [] buffer;
}
CloseHandle (rif_file);
post_input_processing();
Parent_File = ParentFileStore;
}
void RIF_File_Chunk::post_input_processing()
@ -1991,8 +1977,5 @@ Environment_Data_Chunk * RIF_File_Chunk::get_env_data()
if (e_list.size())
return e_list.first_entry();
else
{
return(0);
}
return 0;
}

View file

@ -184,10 +184,9 @@ Sprite_Header_Chunk::Sprite_Header_Chunk(const char * file_name, Chunk_With_Chil
: Chunk_With_Children(parent,"SPRIHEAD")
{
// Load in whole chunk and traverse
HANDLE rif_file;
FILE *rif_file;
DWORD file_size;
DWORD file_size_from_file;
unsigned long bytes_read;
char * buffer;
char * buffer_ptr;
char id_buffer[9];
@ -197,49 +196,51 @@ Sprite_Header_Chunk::Sprite_Header_Chunk(const char * file_name, Chunk_With_Chil
error_code = 0;
rif_file = CreateFileA (file_name, GENERIC_READ, 0, 0, OPEN_EXISTING,
FILE_FLAG_RANDOM_ACCESS, 0);
if (rif_file == INVALID_HANDLE_VALUE) {
rif_file = OpenGameFile(file_name, FILEMODE_READONLY, FILETYPE_PERM);
if (rif_file == NULL) {
return;
}
file_size = GetFileSize (rif_file, 0);
fseek(rif_file, 0, SEEK_END);
file_size = ftell(rif_file);
rewind(rif_file);
if (!ReadFile(rif_file, id_buffer, 8, &bytes_read, 0)) {
if (fread(id_buffer, 1, 8, rif_file) != 8) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
if (strncmp (id_buffer, "SPRIHEAD", 8)) {
if (strncmp(id_buffer, "SPRIHEAD", 8) != 0) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
if (!ReadFile(rif_file, &file_size_from_file, 4, &bytes_read, 0)) {
if (fread(&file_size_from_file, 1, 4, rif_file) != 4) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
if (file_size != file_size_from_file) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
CloseHandle (rif_file);
fclose(rif_file);
return;
}
buffer = new char [file_size];
if (!ReadFile(rif_file, buffer, (file_size-12), &bytes_read, 0)) {
if (fread(buffer, 1, (file_size-12), rif_file) != (file_size-12)) {
error_code = CHUNK_FAILED_ON_LOAD;
CloseHandle (rif_file);
delete [] buffer;
fclose(rif_file);
return;
}
fclose(rif_file);
// Process the file
buffer_ptr = buffer;
@ -248,7 +249,6 @@ Sprite_Header_Chunk::Sprite_Header_Chunk(const char * file_name, Chunk_With_Chil
// The start of the first chunk
while ((buffer_ptr-buffer)< ((signed) file_size-12) && !error_code) {
if ((*(int *)(buffer_ptr + 8)) + (buffer_ptr-buffer) > ((signed) file_size-12)) {
error_code = CHUNK_FAILED_ON_LOAD_NOT_RECOGNISED;
break;
@ -256,13 +256,9 @@ Sprite_Header_Chunk::Sprite_Header_Chunk(const char * file_name, Chunk_With_Chil
DynCreate(buffer_ptr);
buffer_ptr += *(int *)(buffer_ptr + 8);
}
delete [] buffer;
CloseHandle (rif_file);
}
@ -960,5 +956,4 @@ void Sprite_Extent_Chunk::fill_data_block(char* data_start)
data_start+=4;
*(int*)data_start=spare2;
data_start+=4;
}

View file

@ -10,23 +10,6 @@
#include "fixer.h"
void FixFilename(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len; i++) {
if (str[i] == '\\')
str[i] = '/';
else if (str[i] == '\r')
str[i] = 0;
else if (str[i] == '\n')
str[i] = 0;
else
str[i] = tolower(str[i]);
}
}
size_t _mbclen(const unsigned char *s)
{
return strlen((const char *)s);
@ -35,9 +18,9 @@ size_t _mbclen(const unsigned char *s)
HANDLE CreateFile(const char *file, int mode, int x, int y, int flags, int flags2, int z)
{
int fd;
/*
fprintf(stderr, "CreateFile(%s, %d, %d, %d, %d, %d, %d)\n", file, mode, x, y, flags, flags2, z);
*/
switch(mode) {
case GENERIC_READ:
if (flags != OPEN_EXISTING) {
@ -78,9 +61,9 @@ HANDLE CreateFileA(const char *file, int write, int x, int y, int flags, int fla
int WriteFile(HANDLE file, const void *data, int len, void *byteswritten, int lpOverlapped)
{
unsigned long *bw, i;
/*
fprintf(stderr, "WriteFile(%d, %p, %d, %p, %d)\n", file, data, len, byteswritten, lpOverlapped);
*/
bw = (unsigned long *)byteswritten;
*bw = 0;
@ -96,9 +79,9 @@ int WriteFile(HANDLE file, const void *data, int len, void *byteswritten, int lp
int ReadFile(HANDLE file, void *data, int len, void *bytesread, int lpOverlapped)
{
unsigned long *br, i;
/*
fprintf(stderr, "ReadFile(%d, %p, %d, %p, %d)\n", file, data, len, bytesread, lpOverlapped);
*/
br = (unsigned long *)bytesread;
*br = 0;
@ -114,9 +97,9 @@ int ReadFile(HANDLE file, void *data, int len, void *bytesread, int lpOverlapped
int GetFileSize(HANDLE file, int lpFileSizeHigh)
{
struct stat buf;
/*
fprintf(stderr, "GetFileSize(%d, %d)\n", file, lpFileSizeHigh);
*/
if (fstat(file, &buf) == -1)
return -1;
return buf.st_size;
@ -124,9 +107,9 @@ int GetFileSize(HANDLE file, int lpFileSizeHigh)
int CloseHandle(HANDLE file)
{
/*
fprintf(stderr, "CloseHandle(%d)\n", file);
*/
if (close(file) == -1)
return 0;
else
@ -137,9 +120,9 @@ int CloseHandle(HANDLE file)
int DeleteFile(const char *file)
{
/*
fprintf(stderr, "DeleteFile(%s)\n", file);
*/
if (unlink(file) == -1)
return 0;
else
@ -160,9 +143,9 @@ int GetDiskFreeSpace(int x, unsigned long *a, unsigned long *b, unsigned long *c
int CreateDirectory(char *dir, int lpSecurityAttributes)
{
/*
fprintf(stderr, "CreateDirectory(%s, %d)\n", dir, lpSecurityAttributes);
*/
if (mkdir(dir, S_IRWXU) == -1)
return 0;
else