void dump_objects(inv_t *i) { obj_t *o; int j; if(!i) { dsprintf("No objects here!"); return; } for(j = 0; j < 52; j++) { o = i->object[j]; if(o) { dsprintf("\n"); dsprintf("OID: %d\tBasename: %s\tType: %s", o->oid, o->basename, otypestrings[o->type]); if(o->type == OT_GOLD) dsprintf("Amount: %d\n", o->quantity); if(is_armor(o)) dsprintf("AC: %d\n", o->ac); dsprintf("Attack modifier:%s%d\n", (o->attackmod >= 0 ? " +" : " "), o->attackmod); dsprintf("Damage modifier:%s%d\n", (o->damagemod >= 0 ? " +" : " "), o->damagemod); dsprintf("Unique: %s\n", is_unique(o) ? "yes" : "no"); if(is_weapon(o)) dsprintf("Damage: %dd%d\n", o->dice, o->sides); dsprintf("\n"); } } }
static int readEncodings(ListPtr encodings, char *dirname) { char *fullname; DIR *dirp; struct dirent *file; char **names, **name; if(strlen(dirname) > 1 && dirname[strlen(dirname) - 1] == '/') dirname[strlen(dirname) - 1] = '\0'; dirp = opendir(dirname); if(dirp == NULL) { perror("opendir"); return -1; } while((file = readdir(dirp)) != NULL) { fullname = dsprintf("%s/%s", dirname, file->d_name); if(fullname == NULL) { fprintf(stderr, "Couldn't allocate fullname\n"); closedir(dirp); return -1; } names = FontEncIdentify(fullname); if(!names) continue; for(name = names; *name; name++) { if(fullname[0] != '/' && !relative) { char *n; n = dsprintf("%s%s", encodingPrefix, fullname); if(n == NULL) { fprintf(stderr, "Couldn't allocate name\n"); closedir(dirp); return -1; } encodingsToDo = listConsF(encodingsToDo, "%s %s", *name, n); free(n); } else { encodingsToDo = listConsF(encodingsToDo, "%s %s", *name, fullname); } if(encodingsToDo == NULL) { fprintf(stderr, "Couldn't allocate encodings\n"); closedir(dirp); return -1; } } free(names); /* only the spine */ } closedir(dirp); return 0; }
void dump_monsterdefs() { monster_t *m, *n; int i; n = monsterdefs->head; for(i=0;i<monsterdefs->head->x;i++) { m = n->next; dsprintf("%s\t%c\nstr\t%d\tphy\t%d\tintl\t%d\twis\t%d\tdex\t%d\tcha\t%d\n", m->name, m->c, m->attr.str, m->attr.phy, m->attr.intl, m->attr.wis, m->attr.dex, m->attr.cha); dsprintf("hp\t%d\t\tlevel\t%d\tspeed\t%.1f\n", m->hp, m->level, m->speed); dsprintf("Can use weapon: %s\tCan use armor: %s\tCan have gold: %s\n", m->flags & MF_CANUSEWEAPON ? "Yes" : "No", m->flags & MF_CANUSEARMOR ? "Yes" : "No", m->flags & MF_CANHAVEGOLD ? "Yes" : "No"); dsprintf("\n"); n = m; } }
bool LuaState::DoBuffer(const char* name, const char* buffer, unsigned int size) { if(!buffer) { dsprintf("\n[LUASTATE|%s] Asset doesnt exist, no buffer: %s\n", mName, name); return false; } // This is pushed for the pcall below. (Doesn't do syntax errors) lua_pushcfunction(mLuaState, LuaState::LuaError); int fail = luaL_loadbuffer ( mLuaState, buffer, size, name ); if(fail) { // This is for syntax errors on loading the string. // The cfunction pushed above, is used by the pcall below // Not by loadstring OnError(); return false; } else { // Execute the string on the stack // If anything goes wrong call the function under that bool result = lua_pcall(mLuaState, 0, LUA_MULTRET, -2) == 0; lua_pop(mLuaState, 1); // remove error function return result; } }
void inc_year(dstime *t, int i) { t->year += i; if(t->year > 9999) { dsprintf("I think you may have played long enough now! How about some fresh air?"); } }
/* CL_Rcon_f Send the rest of the command line over as an unconnected command. */ static void CL_Rcon_f (void) { static dstring_t *message; netadr_t to; if (!message) message = dstring_new (); dsprintf (message, "\377\377\377\377rcon %s %s", rcon_password->string, Cmd_Args (1)); if (cls.state >= ca_connected) to = cls.netchan.remote_address; else { if (!rcon_address->string[0]) { Sys_Printf ("You must either be connected, or set the " "'rcon_address' cvar to issue rcon commands\n"); return; } NET_StringToAdr (rcon_address->string, &to); if (to.port == 0) to.port = BigShort (27500); } Netchan_SendPacket (strlen (message->str) + 1, message->str, to); }
int DDAudio::Play(const char* name, bool loop) { dsprintf("Being asked to play [%s] Loop: [%s]\n", name, loop? "true" : "false"); int buffer = GetSound(name); int channel = FindNextFreeChannel(); alSourceStop(channel); if(channel == -1) { printf("Couldn't find free channel.\n"); return -1; } alSourcei(channel, AL_BUFFER, buffer); alSourcef(channel, AL_PITCH, 1); alSourcef(channel, AL_GAIN, 1); alSource3f(channel, AL_POSITION, 0, 0, 0); alSource3f(channel, AL_VELOCITY, 0, 0, 0); alSourcei(channel, AL_LOOPING, loop); alSourcePlay(channel); int error = alGetError(); if(error != AL_NO_ERROR) { return -1; } return channel; }
void intermediate_file (dstring_t *ifile, const char *filename, const char *ext, int local) { if (options.save_temps) { char *basename = strdup (filename); char *temp; temp = strrchr (basename, '/'); if (!temp) temp = basename; temp = strrchr (temp, '.'); if (temp) *temp = '\0'; // ignore the rest of the string temp = strrchr (basename, '/'); if (!temp) temp = basename; else temp++; if (*sourcedir) { dsprintf (ifile, "%s%c%s.%s", sourcedir, PATH_SEPARATOR, temp, ext); } else { dsprintf (ifile, "%s.%s", temp, ext); } free (basename); } else if (local) { char *temp2 = strrchr (this_program, PATH_SEPARATOR); dsprintf (ifile, "%sXXXXXX", temp2 ? temp2 + 1 : this_program); } else { const char *temp1 = getenv ("TMPDIR"); char *temp2 = strrchr (this_program, PATH_SEPARATOR); if ((!temp1) || (!temp1[0])) { temp1 = getenv ("TEMP"); if ((!temp1) || (!temp1[0])) { temp1 = "/tmp"; } } dsprintf (ifile, "%s%c%sXXXXXX", temp1, PATH_SEPARATOR, temp2 ? temp2 + 1 : this_program); } }
Asset* DDAudio::GetStream(const char* name) { if(mStreamNameAsset.find(name) == mStreamNameAsset.end()) { dsprintf("ERROR: Couldn't find stream [%s]", name); return NULL; } return mStreamNameAsset.find(name)->second; }
// // NOTE: If you've already enabled this, it won't show // Clean the saved data with: // >Grrr@Grrr-PC ~/Documents/mycode/dancing-squid/src/android // >$ adb shell pm clear com.godpatterns.dinodeck // >Success // // void ScoreLoop::ShowTOS() { dsprintf("ShowTOS();\n"); #if ANDROID AndroidWrapper* wrapper = AndroidWrapper::GetInstance(); return wrapper->ScoreLoopShowTOS(); #endif }
int DDAudio::GetSound(const char* name) { if(mSoundNameId.find(name) == mSoundNameId.end()) { dsprintf("ERROR: Couldn't find sound [%s]", name); return -1; } return mSoundNameId.find(name)->second; }
DDAudio::DDAudio() { gDevice = alcOpenDevice(NULL); gContext = alcCreateContext(gDevice, NULL); alcMakeContextCurrent(gContext); int error = alGetError(); if(error != AL_NO_ERROR) { dsprintf("OpenAL setup error : %d", error); return; } // // Defaults for 2d sound // alListener3f(AL_POSITION, 0, 0, 0); // alListener3f(AL_VELOCITY, 0, 0, 0); // alListener3f(AL_ORIENTATION, 0, 0, -1); // // Reserve sound channels. // gChannels.clear(); while(gChannels.size() < MAX_SOUND_CHANNELS) { unsigned int src; alGenSources(1, &src); error = alGetError(); if(error == AL_NO_ERROR) { gChannels.push_back(src); } else { dsprintf("OpenAL sound channel error : %d\n", error); break; } } dsprintf("%d sound channels found.\n", (int)gChannels.size()); }
static int readFontScale(HashTablePtr entries, char *dirname) { int n = strlen(dirname); char *filename; FILE *in; int rc, count, i; char file[MAXFONTFILENAMELEN+1], font[MAXFONTNAMELEN+1]; if(dirname[n - 1] == '/') filename = dsprintf("%sfonts.scale", dirname); else filename = dsprintf("%s/fonts.scale", dirname); if(filename == NULL) return -1; in = fopen(filename, "r"); free(filename); if(in == NULL) { if(errno != ENOENT) perror("open(fonts.scale)"); return -1; } rc = fscanf(in, "%d\n", &count); if(rc != 1) { fprintf(stderr, "Invalid fonts.scale in %s.\n", dirname); fclose(in); return -1; } for(i = 0; i < count; i++) { rc = fscanf(in, "%" STRINGIFY(MAXFONTFILENAMELEN) "s " "%" STRINGIFY(MAXFONTNAMELEN) "[^\n]\n", file, font); if(rc != 2) break; putHash(entries, font, file, 100); } fclose(in); return 1; }
ScoreLoop::ScoreLoop(const char* secret) { // Call Java to do // Client.init(this, SECRET, null); dsprintf("ScoreLoop created with key: %s \n", secret); #if ANDROID AndroidWrapper* wrapper = AndroidWrapper::GetInstance(); wrapper->ScoreLoopInit(secret); #endif }
void dump_monsters(monster_t *list) { monster_t *m; m = list->next; while(m) { dsprintf("monsterdump: %s\n", m->name); m = m->next; } }
void LuaState::OnError() { // Prints out the error and a stack trace mLastError = lua_tostring(mLuaState, -1); dsprintf("\n[LUASTATE|%s] Error: %s\n", mName, mLastError.c_str()); // Push the debug library on the stack lua_getfield(mLuaState, LUA_GLOBALSINDEX, "debug"); if(!lua_istable(mLuaState, -1)) { dsprintf("[LUASTATE|%s] Debug library not loaded. Couldn't get stack trace\n", mName); lua_pop(mLuaState, 1); // pop the non-table return; } // Debug library is on the stack // A traceback is the most basic thing we can do but we can also // Get variable information and all that good stuff - it's just // a question of how to present it. // Push the traceback on to the stack as a field lua_getfield(mLuaState, -1, "traceback"); if(!lua_isfunction(mLuaState, -1)) { // If the traceback field doesn't exist dsprintf("[LUASTATE|%s] Tried to get trackback but function doesnt exist.\n", mName); dsprintf("[LUASTATE|%s] Have you overidden the default debug table?\n", mName); lua_pop(mLuaState, 2); // pop table and field return; } // Call function on the top of the stack, with no arguements, expecting one return. lua_call(mLuaState, 0, 1); mLastErrorCallstack = lua_tostring(mLuaState, -1); dsprintf("[LUASTATE|%s] %s\n", mName, mLastErrorCallstack.c_str()); return; }
void dump_action_queue() { int i; struct actionqueue *tmp; tmp = aq; i = 0; while(tmp) { dsprintf("item %d\taction %d\tnum %d\n", i, tmp->action, tmp->num); tmp = tmp->next; i++; } }
void ScoreLoop::GetLeaderboard(int type, int onSuccessId, int onFailureId) { dsprintf("Calling GetLeaderboard(%d, %d, %d)\n", type, onSuccessId, onFailureId); #if ANDROID int callbackId = DDLuaCallbacks::StoreCallback(onSuccessId, onFailureId); AndroidWrapper* wrapper = AndroidWrapper::GetInstance(); wrapper->ScoreLoopGetLeaderboard ( type, callbackId ); #endif }
bool DDAudio::OnAssetReload(Asset& asset) { dsprintf("Being asked to load [%s]\n", asset.Name().c_str()); if(asset.Type() == Asset::Sound) { ALuint buffer; ALsizei size; ALsizei frequency; ALenum format; bool success = Wave::LoadToOpenALBuffer(asset.Path().c_str(), &buffer, &size, &frequency, &format); if(!success) { return false; } mSoundNameId.insert ( std::pair<std::string, int> ( std::string(asset.Name()), buffer ) ); return true; } else if(asset.Type() == Asset::Stream) { mStreamNameAsset.insert ( std::pair<std::string, Asset*> ( std::string(asset.Name()), &asset ) ); return true; } else { assert(false); } return false; }
void ScoreLoop::PostScore(double primary, double secondary, int onSuccessId, int onFailureId) { // Needs going up to Java and some release mechanism for the // success, failure ids (hopefully be able to reuse the http ones.) dsprintf("Calling PostScore(%f, %f, %d, %d)\n", primary, secondary, onSuccessId, onFailureId); #if ANDROID int callbackId = DSLuaCallbacks::StoreCallback(onSuccessId, onFailureId); AndroidWrapper* wrapper = AndroidWrapper::GetInstance(); wrapper->ScoreLoopPushScore ( primary, secondary, callbackId ); #endif }
/* CF_BuildQuota Calculates the currently used space */ static void CF_BuildQuota (void) { static dstring_t *path; struct dirent *i; DIR *dir; if (!path) path = dstring_new (); dsprintf (path, "%s/%s/%s", qfs_userpath, qfs_gamedir->dir.def, CF_DIR); dir = opendir (path->str); if (!dir) return; cf_cursize = 0; while ((i = readdir (dir))) { cf_cursize += CF_GetFileSize (va ("%s/%s", path->str, i->d_name)); } closedir (dir); }
/* CL_SendConnectPacket called by CL_Connect_f and CL_CheckResend */ static void CL_SendConnectPacket (void) { dstring_t *data; double t1, t2; // JACK: Fixed bug where DNS lookups would cause two connects real fast // Now, adds lookup time to the connect time. // Should I add it to realtime instead?!?! if (cls.state != ca_disconnected) return; t1 = Sys_DoubleTime (); if (!NET_StringToAdr (cls.servername->str, &cls.server_addr)) { Sys_Printf ("Bad server address\n"); connect_time = -1; return; } if (cls.server_addr.port == 0) cls.server_addr.port = BigShort (27500); t2 = Sys_DoubleTime (); connect_time = realtime + t2 - t1; // for retransmit requests cls.qport = qport->int_val; data = dstring_new (); dsprintf (data, "%c%c%c%cconnect %i %i %i \"%s\"\n", 255, 255, 255, 255, PROTOCOL_VERSION, cls.qport, cls.challenge, Info_MakeString (cls.userinfo, 0)); Netchan_SendPacket (strlen (data->str), data->str, cls.server_addr); dstring_delete (data); }
LuaState::~LuaState() { dsprintf("[LUASTATE|%s] DESTROYED\n", mName); lua_close(mLuaState); }
void gl_Mod_MakeAliasModelDisplayLists (model_t *m, aliashdr_t *hdr, void *_m, int _s, int extra) { dstring_t *cache, *fullpath; unsigned char model_digest[MDFOUR_DIGEST_BYTES]; unsigned char mesh_digest[MDFOUR_DIGEST_BYTES]; int i, j; int *cmds; QFile *f; qboolean remesh = true; qboolean do_cache = false; aliasmodel = m; paliashdr = hdr; cache = dstring_new (); fullpath = dstring_new (); if (!gl_alias_render_tri->int_val) { if (gl_mesh_cache->int_val && gl_mesh_cache->int_val <= paliashdr->mdl.numtris) { do_cache = true; mdfour (model_digest, (unsigned char *) _m, _s); // look for a cached version dstring_copystr (cache, "glquake/"); dstring_appendstr (cache, m->name); QFS_StripExtension (m->name + strlen ("progs/"), cache->str + strlen ("glquake/")); dstring_appendstr (cache, ".qfms"); QFS_FOpenFile (cache->str, &f); if (f) { unsigned char d1[MDFOUR_DIGEST_BYTES]; unsigned char d2[MDFOUR_DIGEST_BYTES]; struct mdfour md; int len, vers; int nc = 0, no = 0; int *c = 0, *vo = 0; memset (d1, 0, sizeof (d1)); memset (d2, 0, sizeof (d2)); Qread (f, &vers, sizeof (int)); Qread (f, &len, sizeof (int)); Qread (f, &nc, sizeof (int)); Qread (f, &no, sizeof (int)); if (vers == 1 && (nc + no) == len) { c = malloc (((nc + 1023) & ~1023) * sizeof (c[0])); vo = malloc (((no + 1023) & ~1023) * sizeof (vo[0])); if (!c || !vo) Sys_Error ("gl_mesh.c: out of memory"); Qread (f, c, nc * sizeof (c[0])); Qread (f, vo, no * sizeof (vo[0])); Qread (f, d1, MDFOUR_DIGEST_BYTES); Qread (f, d2, MDFOUR_DIGEST_BYTES); Qclose (f); mdfour_begin (&md); mdfour_update (&md, (unsigned char *) &vers, sizeof(int)); mdfour_update (&md, (unsigned char *) &len, sizeof(int)); mdfour_update (&md, (unsigned char *) &nc, sizeof(int)); mdfour_update (&md, (unsigned char *) &no, sizeof(int)); mdfour_update (&md, (unsigned char *) c, nc * sizeof (c[0])); mdfour_update (&md, (unsigned char *) vo, no * sizeof (vo[0])); mdfour_update (&md, d1, MDFOUR_DIGEST_BYTES); mdfour_result (&md, mesh_digest); if (memcmp (d2, mesh_digest, MDFOUR_DIGEST_BYTES) == 0 && memcmp (d1, model_digest, MDFOUR_DIGEST_BYTES) == 0) { remesh = false; numcommands = nc; numorder = no; if (numcommands > commands_size) { if (commands) free (commands); commands_size = (numcommands + 1023) & ~1023; commands = c; } else { memcpy (commands, c, numcommands * sizeof (c[0])); free(c); } if (numorder > vertexorder_size) { if (vertexorder) free (vertexorder); vertexorder_size = (numorder + 1023) & ~1023; vertexorder = vo; } else { memcpy (vertexorder, vo, numorder * sizeof (vo[0])); free (vo); } } } } } if (remesh) { // build it from scratch Sys_MaskPrintf (SYS_DEV, "meshing %s...\n", m->name); BuildTris (); // trifans or lists if (do_cache) { // save out the cached version dsprintf (fullpath, "%s/%s", qfs_gamedir->dir.def, cache->str); f = QFS_WOpen (fullpath->str, 9); if (f) { struct mdfour md; int vers = 1; int len = numcommands + numorder; mdfour_begin (&md); mdfour_update (&md, (unsigned char *) &vers, sizeof (int)); mdfour_update (&md, (unsigned char *) &len, sizeof (int)); mdfour_update (&md, (unsigned char *) &numcommands, sizeof (int)); mdfour_update (&md, (unsigned char *) &numorder, sizeof (int)); mdfour_update (&md, (unsigned char *) commands, numcommands * sizeof (commands[0])); mdfour_update (&md, (unsigned char *) vertexorder, numorder * sizeof (vertexorder[0])); mdfour_update (&md, model_digest, MDFOUR_DIGEST_BYTES); mdfour_result (&md, mesh_digest); Qwrite (f, &vers, sizeof (int)); Qwrite (f, &len, sizeof (int)); Qwrite (f, &numcommands, sizeof (int)); Qwrite (f, &numorder, sizeof (int)); Qwrite (f, commands, numcommands * sizeof (commands[0])); Qwrite (f, vertexorder, numorder * sizeof (vertexorder[0])); Qwrite (f, model_digest, MDFOUR_DIGEST_BYTES); Qwrite (f, mesh_digest, MDFOUR_DIGEST_BYTES); Qclose (f); } } } // save the data out paliashdr->poseverts = numorder; cmds = Hunk_Alloc (numcommands * sizeof (int)); paliashdr->commands = (byte *) cmds - (byte *) paliashdr; memcpy (cmds, commands, numcommands * sizeof (int)); } else { tex_coord_t *tex_coord; numorder = 0; for (i=0; i < pheader->mdl.numtris; i++) { add_vertex(triangles[i].vertindex[0]); add_vertex(triangles[i].vertindex[1]); add_vertex(triangles[i].vertindex[2]); } paliashdr->poseverts = numorder; tex_coord = Hunk_Alloc (numorder * sizeof(tex_coord_t)); paliashdr->tex_coord = (byte *) tex_coord - (byte *) paliashdr; for (i=0; i < numorder; i++) { float s, t; int k; k = vertexorder[i]; s = stverts[k].s; t = stverts[k].t; if (!triangles[i/3].facesfront && stverts[k].onseam) s += pheader->mdl.skinwidth / 2; // on back side s = (s + 0.5) / pheader->mdl.skinwidth; t = (t + 0.5) / pheader->mdl.skinheight; tex_coord[i].st[0] = s; tex_coord[i].st[1] = t; } } if (extra) { trivertx16_t *verts; verts = Hunk_Alloc (paliashdr->numposes * paliashdr->poseverts * sizeof (trivertx16_t)); paliashdr->posedata = (byte *) verts - (byte *) paliashdr; for (i = 0; i < paliashdr->numposes; i++) { trivertx_t *pv = poseverts[i]; for (j = 0; j < numorder; j++) { trivertx16_t v; // convert MD16's split coordinates into something a little // saner. The first chunk of vertices is fully compatible with // IDPO alias models (even the scale). The second chunk is the // fractional bits of the vertex, giving 8.8. However, it's // easier for us to multiply everything by 256 and adjust the // model scale appropriately VectorMultAdd (pv[vertexorder[j] + hdr->mdl.numverts].v, 256, pv[vertexorder[j]].v, v.v); v.lightnormalindex = poseverts[i][vertexorder[j]].lightnormalindex; *verts++ = v; } } } else { trivertx_t *verts; verts = Hunk_Alloc (paliashdr->numposes * paliashdr->poseverts * sizeof (trivertx_t)); paliashdr->posedata = (byte *) verts - (byte *) paliashdr; for (i = 0; i < paliashdr->numposes; i++) { for (j = 0; j < numorder; j++) *verts++ = poseverts[i][vertexorder[j]]; } } dstring_delete (cache); dstring_delete (fullpath); }
static int lua_ScoreLoop_SendScore(lua_State* state) { // score double primaryScore = 0; double secondaryScore = 0; ScoreLoop* scoreLoop = LuaState::GetFuncParam<ScoreLoop>(state, 1); if(NULL == scoreLoop) { return 0; } // May allow this to be a table? if(lua_isnumber(state, 2)) // score { primaryScore = lua_tonumber(state, 2); } else if(lua_istable(state, 2)) { lua_pushvalue(state, 2); // [table] // Does it have a key called primary lua_pushstring(state, "primary"); // first key [key[table]] lua_gettable(state, -2); // [value[table]] if(lua_isnumber(state, -1)) { primaryScore = lua_tonumber(state, -1); dsprintf("Primary score is: %g\n", primaryScore); } // Otherwise ignore it. lua_pop(state, 1); lua_pushstring(state, "secondary"); // first key [key[table]] lua_gettable(state, -2); // [value[table]] if(lua_isnumber(state, -1)) { secondaryScore = lua_tonumber(state, -1); dsprintf("Secondary score is: %g\n", secondaryScore); } // Otherwise ignore it. lua_pop(state, 1); lua_pop(state, 1); // pop off the table //dsprintf("Is function at correct place: %s\n", lua_isfunction(state, 3)?"true":"false"); } else { return luaL_typerror(state, 2, "number or table"); } if(!lua_isfunction(state, 3)) // success callback { return luaL_typerror(state, 3, "function"); } if(!lua_isfunction(state, 4)) // failure callback { return luaL_typerror(state, 4, "function"); } // Push success and failure calls into the lua registry and save // the callback ids lua_pushvalue(state, 3); int onSuccessRef = luaL_ref(state, LUA_REGISTRYINDEX); // [-1, +0, m] lua_pushvalue(state, 4); int onFailureRef = luaL_ref(state, LUA_REGISTRYINDEX); // [-1, +0, m] scoreLoop->PostScore ( primaryScore, secondaryScore, onSuccessRef, onFailureRef ); return 0; }
void G_PlayDemo(const char* name) { int i; int p; char filename[256]; gameaction = ga_nothing; endDemo = false; p = M_CheckParm("-playdemo"); if(p && p < myargc-1) { // 20120107 bkw: add .lmp extension if missing. if(dstrrchr(myargv[p+1], '.')) { dstrcpy(filename, myargv[p+1]); } else { dsprintf(filename, "%s.lmp", myargv[p+1]); } CON_DPrintf("--------Reading demo %s--------\n", filename); if(M_ReadFile(filename, &demobuffer) == -1) { gameaction = ga_exitdemo; return; } demo_p = demobuffer; } else { if(W_CheckNumForName(name) == -1) { gameaction = ga_exitdemo; return; } CON_DPrintf("--------Playing demo %s--------\n", name); demobuffer = demo_p = W_CacheLumpName(name, PU_STATIC); } if(strncmp((char*)demo_p, "DM64", 4)) { I_Error("G_PlayDemo: Mismatched demo header"); return; } G_SaveDefaults(); demo_p++; demo_p++; demo_p++; demo_p++; demo_p++; startskill = *demo_p++; startmap = *demo_p++; deathmatch = *demo_p++; respawnparm = *demo_p++; respawnitem = *demo_p++; fastparm = *demo_p++; nomonsters = *demo_p++; consoleplayer = *demo_p++; rngseed = *demo_p++ & 0xff; rngseed <<= 8; rngseed += *demo_p++ & 0xff; rngseed <<= 8; rngseed += *demo_p++ & 0xff; rngseed <<= 8; rngseed += *demo_p++ & 0xff; gameflags = *demo_p++ & 0xff; gameflags <<= 8; gameflags += *demo_p++ & 0xff; gameflags <<= 8; gameflags += *demo_p++ & 0xff; gameflags <<= 8; gameflags += *demo_p++ & 0xff; compatflags = *demo_p++ & 0xff; compatflags <<= 8; compatflags += *demo_p++ & 0xff; compatflags <<= 8; compatflags += *demo_p++ & 0xff; compatflags <<= 8; compatflags += *demo_p++ & 0xff; for(i = 0; i < MAXPLAYERS; i++) { playeringame[i] = *demo_p++; } G_InitNew(startskill, startmap); if(playeringame[1]) { netgame = true; netdemo = true; } precache = true; usergame = false; demoplayback = true; G_RunGame(); iwadDemo = false; }
/* * read or write I/O to a file * buffer is allocated by the procedure. path is UTF-8 */ BOOL FileIo(BOOL save, char* path, char** buffer, DWORD* size) { SECURITY_ATTRIBUTES s_attr, *ps = NULL; SECURITY_DESCRIPTOR s_desc; PSID sid = NULL; HANDLE handle; BOOL r; BOOL ret = FALSE; // Change the owner from admin to regular user sid = GetSid(); if ( (sid != NULL) && InitializeSecurityDescriptor(&s_desc, SECURITY_DESCRIPTOR_REVISION) && SetSecurityDescriptorOwner(&s_desc, sid, FALSE) ) { s_attr.nLength = sizeof(SECURITY_ATTRIBUTES); s_attr.bInheritHandle = FALSE; s_attr.lpSecurityDescriptor = &s_desc; ps = &s_attr; } else { dprintf("could not set security descriptor: %s", WindowsErrorString()); } if (!save) { *buffer = NULL; } handle = CreateFileU(path, save?GENERIC_WRITE:GENERIC_READ, FILE_SHARE_READ, ps, save?CREATE_ALWAYS:OPEN_EXISTING, 0, NULL); if (handle == INVALID_HANDLE_VALUE) { dprintf("Could not %s file '%s'", save?"create":"open", path); goto out; } if (save) { r = WriteFile(handle, *buffer, *size, size, NULL); } else { *size = GetFileSize(handle, NULL); *buffer = (char*)malloc(*size); if (*buffer == NULL) { dprintf("Could not allocate buffer for reading file"); goto out; } r = ReadFile(handle, *buffer, *size, size, NULL); } if (!r) { dprintf("I/O Error: %s", WindowsErrorString()); goto out; } dsprintf("%s '%s'", save?"Saved file as":"Opened file", path); ret = TRUE; out: CloseHandle(handle); if (!ret) { // Only leave a buffer allocated if successful *size = 0; if (!save) { safe_free(*buffer); } } return ret; }
static int doDirectory(const char *dirname_given, int numEncodings, ListPtr encodingsToDo) { char *dirname, *fontscale_name, *filename, *encdir; FILE *fontscale, *encfile; DIR *dirp; struct dirent *entry; FT_Error ftrc; FT_Face face; ListPtr encoding, xlfd, lp; HashTablePtr entries; HashBucketPtr *array; int i, n, found, rc; int isBitmap=0,xl=0; if (exclusionSuffix) xl = strlen (exclusionSuffix); i = strlen(dirname_given); if(i == 0) dirname = dsprintf("./"); else if(dirname_given[i - 1] != '/') dirname = dsprintf("%s/", dirname_given); else dirname = dsprintf("%s", dirname_given); if(dirname == NULL) { perror("dirname"); exit(1); } if (onlyEncodings) goto encodings; entries = makeHashTable(); if(doBitmaps && !doScalable) { readFontScale(entries, dirname); } if(strcmp(outfilename, "-") == 0) fontscale_name = NULL; else { if(outfilename[0] == '/') fontscale_name = dsprintf("%s", outfilename); else fontscale_name = dsprintf("%s%s", dirname, outfilename); if(fontscale_name == NULL) { perror("fontscale_name"); exit(1); } } dirp = opendir(dirname); if(dirp == NULL) { fprintf(stderr, "%s: ", dirname); perror("opendir"); return 0; } if(fontscale_name == NULL) fontscale = stdout; else fontscale = fopen(fontscale_name, "wb"); if(fontscale == NULL) { fprintf(stderr, "%s: ", fontscale_name); perror("fopen(w)"); return 0; } while((entry = readdir(dirp)) != NULL) { int have_face = 0; char *xlfd_name = NULL; struct stat f_stat; int tprio = 1; xlfd = NULL; if (xl) { int dl = strlen (entry->d_name); if (strcmp (entry->d_name + dl - xl, exclusionSuffix) == 0) continue; } filename = dsprintf("%s%s", dirname, entry->d_name); #define PRIO(x) ((x << 1) + tprio) #ifdef DT_LNK if (entry->d_type != DT_UNKNOWN) { if (entry->d_type == DT_LNK) tprio = 0; } else #endif #ifdef S_ISLNK { #ifndef WIN32 if (lstat(filename, &f_stat)) goto done; if (S_ISLNK(f_stat.st_mode)) tprio = 0; #endif } #else ; #endif if(doBitmaps) rc = bitmapIdentify(filename, &xlfd_name); else rc = 0; if(rc < 0) goto done; if(rc == 0) { ftrc = FT_New_Face(ft_library, filename, 0, &face); if(ftrc) goto done; have_face = 1; isBitmap = ((face->face_flags & FT_FACE_FLAG_SCALABLE) == 0); if(!isBitmap) { /* Workaround for bitmap-only SFNT fonts */ if(FT_IS_SFNT(face) && face->num_fixed_sizes > 0 && strcmp(FT_Get_X11_Font_Format(face), "TrueType") == 0) { TT_MaxProfile *maxp; maxp = FT_Get_Sfnt_Table(face, ft_sfnt_maxp); if(maxp != NULL && maxp->maxContours == 0) isBitmap = 1; } } if(isBitmap) { if(!doBitmaps) goto done; } else { if(!doScalable) goto done; } if(isBitmap) { BDF_PropertyRec prop; rc = FT_Get_BDF_Property(face, "FONT", &prop); if(rc == 0 && prop.type == BDF_PROPERTY_TYPE_ATOM) { xlfd_name = strdup(prop.u.atom); if(xlfd_name == NULL) goto done; } } } if(xlfd_name) { /* We know it's a bitmap font, and we know its XLFD */ int n = strlen(xlfd_name); if(reencodeLegacy && n >= 12 && strcasecmp(xlfd_name + n - 11, "-iso10646-1") == 0) { char *s; s = malloc(n - 10); memcpy(s, xlfd_name, n - 11); s[n - 11] = '\0'; xlfd = listCons(s, xlfd); } else { /* Not a reencodable font -- skip all the rest of the loop body */ putHash(entries, xlfd_name, entry->d_name, PRIO(filePrio(entry->d_name))); goto done; } } if(!have_face) { ftrc = FT_New_Face(ft_library, filename, 0, &face); if(ftrc) goto done; have_face = 1; isBitmap = ((face->face_flags & FT_FACE_FLAG_SCALABLE) == 0); if(!isBitmap) { if(face->num_fixed_sizes > 0) { TT_MaxProfile *maxp; maxp = FT_Get_Sfnt_Table(face, ft_sfnt_maxp); if(maxp != NULL && maxp->maxContours == 0) isBitmap = 1; } } } if(xlfd == NULL) xlfd = makeXLFD(entry->d_name, face, isBitmap); found = 0; for(lp = xlfd; lp; lp = lp->next) { char buf[MAXFONTNAMELEN]; for(encoding = encodings; encoding; encoding = encoding->next) { if(checkEncoding(face, encoding->value)) { found = 1; snprintf(buf, MAXFONTNAMELEN, "%s-%s", lp->value, encoding->value); putHash(entries, buf, entry->d_name, PRIO(filePrio(entry->d_name))); } } for(encoding = extra_encodings; encoding; encoding = encoding->next) { if(checkExtraEncoding(face, encoding->value, found)) { /* Do not set found! */ snprintf(buf, MAXFONTNAMELEN, "%s-%s", lp->value, encoding->value); putHash(entries, buf, entry->d_name, PRIO(filePrio(entry->d_name))); } } } done: if(have_face) FT_Done_Face(face); deepDestroyList(xlfd); xlfd = NULL; free(filename); #undef PRIO } closedir(dirp); n = hashElements(entries); fprintf(fontscale, "%d\n", n); array = hashArray(entries, 1); for(i = 0; i < n; i++) fprintf(fontscale, "%s %s\n", array[i]->value, array[i]->key); destroyHashArray(array); entries = NULL; if(fontscale_name) { fclose(fontscale); free(fontscale_name); } encodings: encdir = dsprintf("%s%s", dirname, "encodings.dir"); if(encdir == NULL) { perror("encodings"); exit(1); } unlink(encdir); if (numEncodings) { encfile = fopen(encdir, "w"); if(encfile == NULL) { perror("open(encodings.dir)"); exit(1); } fprintf(encfile, "%d\n", numEncodings); encodingsToDo = sortList(encodingsToDo); for(lp = encodingsToDo; lp; lp = lp->next) { fprintf(encfile, "%s\n", lp->value); } fclose (encfile); } free(dirname); return 1; }
/* * Load wave file function. No need for ALUT with this */ bool Wave::LoadToOpenALBuffer(const char* filename, ALuint* buffer, ALsizei* size, ALsizei* frequency, ALenum* format) { //Local Declarations WAVE_Format wave_format; RIFF_Header riff_header; WAVE_Data wave_data; unsigned char* data; // Need to implement //FILE* soundFile = fopen(filename, "rb"); DDFile soundFile(filename); if (!DDFile::FileExists(filename)) { dsprintf("ERROR: Failed to load. Couldn't find file [%s].\n", filename); return false; } soundFile.LoadFileIntoBuffer(); void* readPtr = (void*)soundFile.Buffer(); // Read in the first chunk into the struct //size_t readCount = fread(&riff_header, sizeof(RIFF_Header), 1, soundFile); // dsprintf("ReadPtr1 %p.\n", readPtr); soundFile.Read(&riff_header, sizeof(RIFF_Header), readPtr); // dsprintf("ReadPtr2 %p.\n", readPtr); //check for RIFF and WAVE tag in memeory if ((riff_header.chunkID[0] != 'R' || riff_header.chunkID[1] != 'I' || riff_header.chunkID[2] != 'F' || riff_header.chunkID[3] != 'F') && (riff_header.format[0] != 'W' || riff_header.format[1] != 'A' || riff_header.format[2] != 'V' || riff_header.format[3] != 'E')) { dsprintf("ERROR: Failed to load. Wave header tag missing.\n"); return false; } //Read in the 2nd chunk for the wave info //readCount = fread(&wave_format, sizeof(WAVE_Format), 1, soundFile); soundFile.Read(&wave_format, sizeof(WAVE_Format), readPtr); //check for fmt tag in memory if (wave_format.subChunkID[0] != 'f' || wave_format.subChunkID[1] != 'm' || wave_format.subChunkID[2] != 't' || wave_format.subChunkID[3] != ' ') { dsprintf("ERROR: Failed to load. Wave fmt tag missing.\n"); return false; } //check for extra parameters; if (wave_format.subChunkSize > 16) { dsprintf("Warning: Wave.cpp untested code running\n"); //fseek(soundFile, sizeof(short), SEEK_CUR); soundFile.Seek((int)sizeof(short), readPtr); } //Read in the the last byte of data before the sound file //fread(&wave_data, sizeof(WAVE_Data), 1, soundFile); soundFile.Read(&wave_data, sizeof(WAVE_Data), readPtr); //check for data tag in memory if (wave_data.subChunkID[0] != 'd' || wave_data.subChunkID[1] != 'a' || wave_data.subChunkID[2] != 't' || wave_data.subChunkID[3] != 'a') { dsprintf("ERROR: Failed to load. Data tag missing.\n"); return false; } //Allocate memory for data data = new unsigned char[wave_data.subChunk2Size]; // Read in the sound data into the soundData variable if (!soundFile.Read(data, wave_data.subChunk2Size, /*1,*/ readPtr)) { dsprintf("ERROR: Failed to read header into struct.\n"); delete [] data; data = NULL; return false; } //Now we set the variables that we passed in with the //data from the structs *size = wave_data.subChunk2Size; *frequency = wave_format.sampleRate; //The format is worked out by looking at the number of //channels and the bits per sample. if(wave_format.numChannels == 1) { if(wave_format.bitsPerSample == 8) { *format = AL_FORMAT_MONO8; } else if(wave_format.bitsPerSample == 16) { *format = AL_FORMAT_MONO16; } } else if(wave_format.numChannels == 2) { if(wave_format.bitsPerSample == 8 ) { *format = AL_FORMAT_STEREO8; } else if(wave_format.bitsPerSample == 16) { *format = AL_FORMAT_STEREO16; } } //create our openAL buffer and check for success alGenBuffers(1, buffer); //errorCheck(); //now we put our data into the openAL buffer and //check for success alBufferData(*buffer, *format, (void*) data, *size, *frequency); delete [] data; // errorCheck(); //clean up and return true if successful //fclose(soundFile); return true; }
/* CF_Open cfopen opens a file, either for reading or writing (not both). returns a file descriptor >= 0 on success, < 0 on failure. mode is either r or w. */ int CF_Open (const char *path, const char *mode) { char *j; dstring_t *fullpath = dstring_new (); int desc, oldsize, i; QFile *file; if (cf_openfiles >= CF_MAXFILES) { return -1; } // check for paths with .. if (strequal (path, "..") || !strncmp (path, "../", 3) || strstr (path, "/../") || (strlen (path) >= 3 && strequal (path + strlen (path) - 3, "/.."))) { return -1; } if (!(strequal(mode, "w") || strequal(mode, "r") || strequal(mode, "a"))) { return -1; } if (mode[0] == 'w' && cf_maxsize < 0) { // can't even delete if quota < 0 return -1; } dsprintf (fullpath, "%s/%s/%s", qfs_gamedir->dir.def, CF_DIR, path); j = fullpath->str + strlen (fullpath->str) - strlen (path); for (i = 0; path[i]; i++, j++) // strcpy, but force lowercase *j = tolower ((byte) path[i]); *j = '\0'; if (CF_AlreadyOpen (fullpath->str, mode[0])) { dstring_delete (fullpath); return -1; } if (mode[0] == 'w') oldsize = CF_GetFileSize (fullpath->str); else oldsize = 0; file = QFS_Open (fullpath->str, mode); if (file) { if (cf_openfiles >= cf_filepcount) { cf_filepcount++; cf_filep = realloc (cf_filep, sizeof (cf_file_t) * cf_filepcount); if (!cf_filep) { Sys_Error ("CF_Open: memory allocation error!"); } cf_filep[cf_filepcount - 1].file = 0; } for (desc = 0; cf_filep[desc].file; desc++) ; cf_filep[desc].path = fullpath->str; cf_filep[desc].file = file; cf_filep[desc].buf = 0; cf_filep[desc].size = 0; cf_filep[desc].writtento = 0; cf_filep[desc].mode = mode[0]; cf_cursize -= oldsize; cf_openfiles++; return desc; } return -1; }