From 05a11326d6f425bb633354c8d42259679ad4b7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Kera=CC=88nen?= Date: Tue, 31 May 2016 20:40:04 +0300 Subject: [PATCH] Cleanup|libdoomsday: Whitespace style refresh Use a space in `if`, `for`, etc. statements after the keyword. This commit only contains whitespace changes. --- .../include/doomsday/defs/dedarray.h | 16 +- .../include/doomsday/defs/dedtypes.h | 8 +- .../include/doomsday/filesys/filetype.h | 2 +- .../include/doomsday/filesys/fs_main.h | 4 +- .../include/doomsday/world/thinkerdata.h | 4 +- doomsday/apps/libdoomsday/src/busymode.cpp | 28 +- .../apps/libdoomsday/src/console/alias.cpp | 34 +- doomsday/apps/libdoomsday/src/console/cmd.cpp | 110 +-- .../apps/libdoomsday/src/console/exec.cpp | 258 +++---- .../libdoomsday/src/console/knownword.cpp | 62 +- doomsday/apps/libdoomsday/src/console/var.cpp | 132 ++-- doomsday/apps/libdoomsday/src/defs/ded.cpp | 122 +-- .../apps/libdoomsday/src/defs/dedfile.cpp | 18 +- .../apps/libdoomsday/src/defs/dedparser.cpp | 700 +++++++++--------- .../apps/libdoomsday/src/defs/dedregister.cpp | 42 +- .../apps/libdoomsday/src/defs/definition.cpp | 2 +- .../apps/libdoomsday/src/defs/episode.cpp | 32 +- doomsday/apps/libdoomsday/src/defs/model.cpp | 16 +- doomsday/apps/libdoomsday/src/defs/music.cpp | 6 +- doomsday/apps/libdoomsday/src/defs/sprite.cpp | 16 +- doomsday/apps/libdoomsday/src/doomsdayapp.cpp | 74 +- .../apps/libdoomsday/src/filesys/datafile.cpp | 2 +- .../libdoomsday/src/filesys/datafolder.cpp | 6 +- .../apps/libdoomsday/src/filesys/file.cpp | 8 +- .../libdoomsday/src/filesys/filehandle.cpp | 42 +- .../apps/libdoomsday/src/filesys/fileid.cpp | 4 +- .../apps/libdoomsday/src/filesys/filetype.cpp | 8 +- .../apps/libdoomsday/src/filesys/fs_main.cpp | 262 +++---- .../libdoomsday/src/filesys/fs_scheme.cpp | 72 +- .../apps/libdoomsday/src/filesys/fs_util.cpp | 98 +-- .../libdoomsday/src/filesys/lumpcache.cpp | 32 +- .../libdoomsday/src/filesys/lumpindex.cpp | 110 +-- .../libdoomsday/src/filesys/sys_direc.cpp | 68 +- .../src/filesys/virtualmappings.cpp | 26 +- doomsday/apps/libdoomsday/src/filesys/wad.cpp | 50 +- doomsday/apps/libdoomsday/src/filesys/zip.cpp | 130 ++-- doomsday/apps/libdoomsday/src/game.cpp | 84 +-- doomsday/apps/libdoomsday/src/game_init.cpp | 64 +- .../apps/libdoomsday/src/gameprofiles.cpp | 10 +- doomsday/apps/libdoomsday/src/games.cpp | 42 +- doomsday/apps/libdoomsday/src/help.cpp | 38 +- doomsday/apps/libdoomsday/src/library.cpp | 20 +- doomsday/apps/libdoomsday/src/player.cpp | 4 +- doomsday/apps/libdoomsday/src/players.cpp | 14 +- doomsday/apps/libdoomsday/src/plugins.cpp | 46 +- .../apps/libdoomsday/src/resource/bundles.cpp | 54 +- .../libdoomsday/src/resource/colorpalette.cpp | 68 +- .../libdoomsday/src/resource/databundle.cpp | 52 +- .../libdoomsday/src/resource/lumpcatalog.cpp | 14 +- .../src/resource/lumpdirectory.cpp | 12 +- .../libdoomsday/src/resource/manifest.cpp | 66 +- .../libdoomsday/src/resource/mapmanifest.cpp | 2 +- .../apps/libdoomsday/src/resource/patch.cpp | 38 +- .../libdoomsday/src/resource/resources.cpp | 24 +- .../apps/libdoomsday/src/resource/wav.cpp | 26 +- .../apps/libdoomsday/src/savedsession.cpp | 84 +-- doomsday/apps/libdoomsday/src/session.cpp | 12 +- doomsday/apps/libdoomsday/src/uri.cpp | 52 +- .../apps/libdoomsday/src/world/actions.cpp | 8 +- .../libdoomsday/src/world/entitydatabase.cpp | 12 +- .../apps/libdoomsday/src/world/entitydef.cpp | 90 +-- doomsday/apps/libdoomsday/src/world/map.cpp | 12 +- .../libdoomsday/src/world/propertyvalue.cpp | 2 +- .../apps/libdoomsday/src/world/thinker.cpp | 26 +- doomsday/apps/libdoomsday/src/world/world.cpp | 2 +- doomsday/apps/libdoomsday/src/world/xg.cpp | 4 +- 66 files changed, 1793 insertions(+), 1793 deletions(-) diff --git a/doomsday/apps/libdoomsday/include/doomsday/defs/dedarray.h b/doomsday/apps/libdoomsday/include/doomsday/defs/dedarray.h index 7d01a4980e..19a5e9d33c 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/defs/dedarray.h +++ b/doomsday/apps/libdoomsday/include/doomsday/defs/dedarray.h @@ -82,7 +82,7 @@ struct LIBDOOMSDAY_PUBLIC DEDArray void releaseAll() { - for(int i = 0; i < count.num; ++i) + for (int i = 0; i < count.num; ++i) { elements[i].release(); } @@ -98,7 +98,7 @@ struct LIBDOOMSDAY_PUBLIC DEDArray PODType *copied = (PODType *) M_Malloc(sizeof(PODType) * count.max); memcpy(copied, elements, sizeof(PODType) * count.num); elements = copied; - for(int i = 0; i < count.num; ++i) + for (int i = 0; i < count.num; ++i) { elements[i].reallocate(); } @@ -152,10 +152,10 @@ struct LIBDOOMSDAY_PUBLIC DEDArray int const first = count.num; count.num += addedCount; - if(count.num > count.max) + if (count.num > count.max) { count.max *= 2; // Double the size of the array. - if(count.num > count.max) count.max = count.num; + if (count.num > count.max) count.max = count.num; elements = reinterpret_cast(M_Realloc(elements, sizeof(PODType) * count.max)); } @@ -169,7 +169,7 @@ struct LIBDOOMSDAY_PUBLIC DEDArray DENG2_ASSERT(index >= 0); DENG2_ASSERT(index < size()); - if(index < 0 || index >= size()) return; + if (index < 0 || index >= size()) return; elements[index].release(); @@ -177,7 +177,7 @@ struct LIBDOOMSDAY_PUBLIC DEDArray elements + (index + 1), sizeof(PODType) * (count.num - index - 1)); - if(--count.num < count.max / 2) + if (--count.num < count.max / 2) { count.max /= 2; elements = (PODType *) M_Realloc(elements, sizeof(PODType) * count.max); @@ -209,7 +209,7 @@ struct LIBDOOMSDAY_PUBLIC DEDArray int indexOf(PODType const *element) const { - if(size() > 0 && element >= &first() && element <= &last()) + if (size() > 0 && element >= &first() && element <= &last()) return element - elements; return -1; } @@ -218,7 +218,7 @@ struct LIBDOOMSDAY_PUBLIC DEDArray { releaseAll(); - if(elements) M_Free(elements); + if (elements) M_Free(elements); elements = 0; count.num = count.max = 0; diff --git a/doomsday/apps/libdoomsday/include/doomsday/defs/dedtypes.h b/doomsday/apps/libdoomsday/include/doomsday/defs/dedtypes.h index 81d934d4ca..44a1779f25 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/defs/dedtypes.h +++ b/doomsday/apps/libdoomsday/include/doomsday/defs/dedtypes.h @@ -428,14 +428,14 @@ typedef struct LIBDOOMSDAY_PUBLIC ded_group_s { } ded_group_member_t *tryFindFirstMemberWithMaterial(de::Uri const &materialUri) { - if(!materialUri.isEmpty()) { - for(int i = 0; i < members.size(); ++i) { - if(members[i].material && *members[i].material == materialUri) { + if (!materialUri.isEmpty()) { + for (int i = 0; i < members.size(); ++i) { + if (members[i].material && *members[i].material == materialUri) { return &members[i]; } // Only animate if the first frame in the group? - if(flags & AGF_FIRST_ONLY) break; + if (flags & AGF_FIRST_ONLY) break; } } return nullptr; // Not found. diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h index f56f6c4647..d7e53caa2e 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h @@ -102,7 +102,7 @@ namespace de { // We require an extension for this. String ext = path.fileNameExtension(); - if(!ext.isEmpty()) + if (!ext.isEmpty()) { return knownFileNameExtensions_.contains(ext, Qt::CaseInsensitive); } diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h index 512d845f94..3ddfc68fd0 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h @@ -496,10 +496,10 @@ class LIBDOOMSDAY_PUBLIC FS1 findAll(predicate, parameters, found); // Filter out the wrong types. QMutableListIterator i(found); - while(i.hasNext()) + while (i.hasNext()) { i.next(); - if(!i.value()->file().is()) + if (!i.value()->file().is()) { i.remove(); } diff --git a/doomsday/apps/libdoomsday/include/doomsday/world/thinkerdata.h b/doomsday/apps/libdoomsday/include/doomsday/world/thinkerdata.h index 023486e10d..b4050c81fe 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/world/thinkerdata.h +++ b/doomsday/apps/libdoomsday/include/doomsday/world/thinkerdata.h @@ -82,12 +82,12 @@ class LIBDOOMSDAY_PUBLIC ThinkerData }; DENG2_SCRIPT_ARGUMENT_TYPE(ThinkerData *, - if(!arg) return ScriptLex::NONE; + if (!arg) return ScriptLex::NONE; return scriptArgumentAsText(arg->objectNamespace()); ) DENG2_SCRIPT_ARGUMENT_TYPE(ThinkerData const *, - if(!arg) return ScriptLex::NONE; + if (!arg) return ScriptLex::NONE; return scriptArgumentAsText(arg->objectNamespace()); ) diff --git a/doomsday/apps/libdoomsday/src/busymode.cpp b/doomsday/apps/libdoomsday/src/busymode.cpp index 3444d93344..16728c8f77 100644 --- a/doomsday/apps/libdoomsday/src/busymode.cpp +++ b/doomsday/apps/libdoomsday/src/busymode.cpp @@ -48,7 +48,7 @@ DENG2_PIMPL(BusyMode) int performTask(BusyTask *task) { DENG2_ASSERT(task); - if(!task) return 0; + if (!task) return 0; DENG2_ASSERT(!busyInited); @@ -58,11 +58,11 @@ DENG2_PIMPL(BusyMode) busyInited = true; ITaskRunner::Result result; - if(runner) + if (runner) { result = runner->runTask(task); } - if(!result.wasRun) + if (!result.wasRun) { // As a fallback, just run the callback. result.returnValue = task->worker(task->workerData); @@ -71,13 +71,13 @@ DENG2_PIMPL(BusyMode) // Clean up. busyInited = false; - if(task->name) + if (task->name) { LOG_VERBOSE("Busy task \"%s\" performed in %.2f seconds") << task->name << taskStartedAt.since(); } - if(busyTaskEndedWithError) + if (busyTaskEndedWithError) { throw Error("BusyMode::performTask", "Task failed: " + busyError); } @@ -126,7 +126,7 @@ BusyTask *BusyMode::currentTask() const { DENG2_GUARD(d) - if(!isActive()) return nullptr; + if (!isActive()) return nullptr; return d->busyTask; } @@ -161,7 +161,7 @@ static BusyTask *newTask(int mode, std::function worker, void* wor task->workerData = workerData; // Take a copy of the task name. - if(!taskName.isEmpty()) + if (!taskName.isEmpty()) { task->name = M_StrDup(taskName.toLatin1()); } @@ -172,7 +172,7 @@ static BusyTask *newTask(int mode, std::function worker, void* wor static void deleteTask(BusyTask *task) { DENG_ASSERT(task); - if(task->name) M_Free((void *)task->name); + if (task->name) M_Free((void *)task->name); delete task; } @@ -213,7 +213,7 @@ int BusyMode::runTasks(BusyTask *tasks, int numTasks) DENG2_ASSERT(!isActive()); - if(!tasks || numTasks <= 0) return result; // Hmm, no work? + if (!tasks || numTasks <= 0) return result; // Hmm, no work? // Pick the first task. task = tasks; @@ -224,10 +224,10 @@ int BusyMode::runTasks(BusyTask *tasks, int numTasks) } // Process tasks. - for(i = 0; i < numTasks; ++i, ++task) + for (i = 0; i < numTasks; ++i, ++task) { // If no new task name is specified, continue using the name of the previous task. - if(task->name) + if (task->name) { currentTaskName = task->name; } @@ -237,7 +237,7 @@ int BusyMode::runTasks(BusyTask *tasks, int numTasks) /* /// @todo Kludge: Force BUSYF_STARTUP here so that the animation of one task /// is not drawn on top of the last frame of the previous. - if(numTasks > 1) + if (numTasks > 1) { mode |= BUSYF_STARTUP; } @@ -245,7 +245,7 @@ int BusyMode::runTasks(BusyTask *tasks, int numTasks) */ // Null tasks are not processed (implicit success). - if(!task->worker) continue; + if (!task->worker) continue; /** * Process the work. @@ -268,7 +268,7 @@ int BusyMode::runTasks(BusyTask *tasks, int numTasks) i->busyTaskCompleted(*task); } - if(result) break; + if (result) break; } DENG2_FOR_AUDIENCE2(End, i) diff --git a/doomsday/apps/libdoomsday/src/console/alias.cpp b/doomsday/apps/libdoomsday/src/console/alias.cpp index 6dbfac8f7a..65ccc4c108 100644 --- a/doomsday/apps/libdoomsday/src/console/alias.cpp +++ b/doomsday/apps/libdoomsday/src/console/alias.cpp @@ -34,11 +34,11 @@ void Con_InitAliases() void Con_ClearAliases() { - if(caliases) + if (caliases) { // Free the alias data. calias_t** cal = caliases; - for(uint i = 0; i < numCAliases; ++i, ++cal) + for (uint i = 0; i < numCAliases; ++i, ++cal) { M_Free((*cal)->name); M_Free((*cal)->command); @@ -57,19 +57,19 @@ calias_t *Con_FindAlias(char const *name) dd_bool isDone; int result; - if(numCAliases == 0) return 0; - if(!name || !name[0]) return 0; + if (numCAliases == 0) return 0; + if (!name || !name[0]) return 0; bottomIdx = 0; topIdx = numCAliases-1; cal = NULL; isDone = false; - while(bottomIdx <= topIdx && !isDone) + while (bottomIdx <= topIdx && !isDone) { pivot = bottomIdx + (topIdx - bottomIdx)/2; result = qstricmp(caliases[pivot]->name, name); - if(result == 0) + if (result == 0) { // Found. cal = caliases[pivot]; @@ -77,9 +77,9 @@ calias_t *Con_FindAlias(char const *name) } else { - if(result > 0) + if (result > 0) { - if(pivot == 0) + if (pivot == 0) { // Not present. isDone = true; @@ -97,20 +97,20 @@ calias_t *Con_FindAlias(char const *name) calias_t* Con_AddAlias(char const* name, char const* command) { - if(!name || !name[0] || !command || !command[0]) return 0; + if (!name || !name[0] || !command || !command[0]) return 0; caliases = (calias_t**) M_Realloc(caliases, sizeof(*caliases) * ++numCAliases); // Find the insertion point. uint idx; - for(idx = 0; idx < numCAliases-1; ++idx) + for (idx = 0; idx < numCAliases-1; ++idx) { - if(qstricmp(caliases[idx]->name, name) > 0) + if (qstricmp(caliases[idx]->name, name) > 0) break; } // Make room for the new alias. - if(idx != numCAliases-1) + if (idx != numCAliases-1) memmove(caliases + idx + 1, caliases + idx, sizeof(*caliases) * (numCAliases - 1 - idx)); // Add the new variable, making a static copy of the name in the zone (this allows @@ -130,12 +130,12 @@ void Con_DeleteAlias(calias_t* cal) DENG_ASSERT(cal); uint idx; - for(idx = 0; idx < numCAliases; ++idx) + for (idx = 0; idx < numCAliases; ++idx) { - if(caliases[idx] == cal) + if (caliases[idx] == cal) break; } - if(idx == numCAliases) return; + if (idx == numCAliases) return; Con_UpdateKnownWords(); @@ -143,7 +143,7 @@ void Con_DeleteAlias(calias_t* cal) M_Free(cal->command); M_Free(cal); - if(idx < numCAliases - 1) + if (idx < numCAliases - 1) { memmove(caliases + idx, caliases + idx + 1, sizeof(*caliases) * (numCAliases - idx - 1)); } @@ -163,7 +163,7 @@ String Con_AliasAsStyledText(calias_t *alias) void Con_AddKnownWordsForAliases() { calias_t** cal = caliases; - for(uint i = 0; i < numCAliases; ++i, ++cal) + for (uint i = 0; i < numCAliases; ++i, ++cal) { Con_AddKnownWord(WT_CALIAS, *cal); } diff --git a/doomsday/apps/libdoomsday/src/console/cmd.cpp b/doomsday/apps/libdoomsday/src/console/cmd.cpp index ebdbd1eec4..065b630033 100644 --- a/doomsday/apps/libdoomsday/src/console/cmd.cpp +++ b/doomsday/apps/libdoomsday/src/console/cmd.cpp @@ -49,7 +49,7 @@ void Con_InitCommands() void Con_ClearCommands(void) { - if(ccmdBlockSet) + if (ccmdBlockSet) { BlockSet_Delete(ccmdBlockSet); } @@ -62,10 +62,10 @@ void Con_ClearCommands(void) void Con_AddKnownWordsForCommands() { /// @note ccmd list is NOT yet sorted. - for(ccmd_t* ccmd = ccmdListHead; ccmd; ccmd = ccmd->next) + for (ccmd_t* ccmd = ccmdListHead; ccmd; ccmd = ccmd->next) { // Skip overloaded variants. - if(ccmd->prevOverload) continue; + if (ccmd->prevOverload) continue; Con_AddKnownWord(WT_CCMD, ccmd); } @@ -77,12 +77,12 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) cvartype_t args[DENG_MAX_ARGS]; ccmd_t* newCCmd, *overloaded = 0; - if(!ccmd) return; + if (!ccmd) return; DENG_ASSERT(ccmd->name != 0); // Decode the usage string if present. - if(ccmd->argTemplate != 0) + if (ccmd->argTemplate != 0) { size_t l, len; cvartype_t type = CVT_NULL; @@ -92,10 +92,10 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) len = strlen(ccmd->argTemplate); minArgs = 0; unlimitedArgs = false; - for(l = 0; l < len; ++l) + for (l = 0; l < len; ++l) { c = ccmd->argTemplate[l]; - switch(c) + switch (c) { // Supported type symbols: case 'b': type = CVT_BYTE; break; @@ -106,7 +106,7 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) // Special symbols: case '*': // Variable arg list. - if(l != len-1) + if (l != len-1) App_FatalError("Con_AddCommand: CCmd '%s': '*' character " "not last in argument template: \"%s\".", ccmd->name, ccmd->argTemplate); @@ -122,9 +122,9 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) ccmd->argTemplate); } - if(type != CVT_NULL) + if (type != CVT_NULL) { - if(minArgs >= DENG_MAX_ARGS) + if (minArgs >= DENG_MAX_ARGS) App_FatalError("Con_AddCommand: CCmd '%s': Too many arguments. " "Limit is %i.", ccmd->name, DENG_MAX_ARGS); @@ -133,10 +133,10 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) } // Set the min/max parameter counts for this ccmd. - if(unlimitedArgs) + if (unlimitedArgs) { maxArgs = -1; - if(minArgs == 0) + if (minArgs == 0) minArgs = -1; } else @@ -153,51 +153,51 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) // We allow multiple ccmds with the same name if we can determine by // their paramater lists that they are unique (overloading). { ccmd_t* other; - if((other = Con_FindCommand(ccmd->name)) != 0) + if ((other = Con_FindCommand(ccmd->name)) != 0) { dd_bool unique = true; // The ccmd being registered is NOT a deng validated ccmd // and there is already an existing ccmd by this name? - if(minArgs == -1 && maxArgs == -1) + if (minArgs == -1 && maxArgs == -1) unique = false; - if(unique) + if (unique) { // Check each variant. ccmd_t* variant = other; do { // An existing ccmd with no validation? - if(variant->minArgs == -1 && variant->maxArgs == -1) + if (variant->minArgs == -1 && variant->maxArgs == -1) unique = false; // An existing ccmd with a lower minimum and no maximum? - else if(variant->minArgs < minArgs && variant->maxArgs == -1) + else if (variant->minArgs < minArgs && variant->maxArgs == -1) unique = false; // An existing ccmd with a larger min and this ccmd has no max? - else if(variant->minArgs > minArgs && maxArgs == -1) + else if (variant->minArgs > minArgs && maxArgs == -1) unique = false; // An existing ccmd with the same minimum number of args? - else if(variant->minArgs == minArgs) + else if (variant->minArgs == minArgs) { // \todo Implement support for paramater type checking. unique = false; } // Sanity check. - if(!unique && variant->execFunc == ccmd->execFunc) + if (!unique && variant->execFunc == ccmd->execFunc) App_FatalError("Con_AddCommand: A CCmd by the name '%s' is already registered and the callback funcs are " "the same, is this really what you wanted?", ccmd->name); - } while((variant = variant->nextOverload) != 0); + } while ((variant = variant->nextOverload) != 0); } - if(!unique) + if (!unique) App_FatalError("Con_AddCommand: A CCmd by the name '%s' is already registered. Their parameter lists would be ambiguant.", ccmd->name); overloaded = other; }} - if(!ccmdBlockSet) + if (!ccmdBlockSet) ccmdBlockSet = BlockSet_New(sizeof(ccmd_t), 32); newCCmd = (ccmd_t*) BlockSet_Allocate(ccmdBlockSet); @@ -205,7 +205,7 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) // Make a static copy of the name in the zone (this allows the source // data to change in case of dynamic registrations). char* nameCopy = (char*) Z_Malloc(strlen(ccmd->name) + 1, PU_APPSTATIC, NULL); - if(!nameCopy) App_FatalError("Con_AddCommand: Failed on allocation of %lu bytes for command name.", (unsigned long) (strlen(ccmd->name) + 1)); + if (!nameCopy) App_FatalError("Con_AddCommand: Failed on allocation of %lu bytes for command name.", (unsigned long) (strlen(ccmd->name) + 1)); strcpy(nameCopy, ccmd->name); newCCmd->name = nameCopy; @@ -220,7 +220,7 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) newCCmd->next = ccmdListHead; ccmdListHead = newCCmd; - if(!overloaded) + if (!overloaded) { ++numUniqueNamedCCmds; Con_UpdateKnownWords(); @@ -234,8 +234,8 @@ void Con_AddCommand(ccmdtemplate_t const* ccmd) void Con_AddCommandList(ccmdtemplate_t const* cmdList) { - if(!cmdList) return; - for(; cmdList->name; ++cmdList) + if (!cmdList) return; + for (; cmdList->name; ++cmdList) { Con_AddCommand(cmdList); } @@ -244,14 +244,14 @@ void Con_AddCommandList(ccmdtemplate_t const* cmdList) ccmd_t *Con_FindCommand(char const *name) { /// @todo Use a faster than O(n) linear search. - if(name && name[0]) + if (name && name[0]) { - for(ccmd_t *ccmd = ccmdListHead; ccmd; ccmd = ccmd->next) + for (ccmd_t *ccmd = ccmdListHead; ccmd; ccmd = ccmd->next) { - if(qstricmp(name, ccmd->name)) continue; + if (qstricmp(name, ccmd->name)) continue; // Locate the head of the overload list. - while(ccmd->prevOverload) { ccmd = ccmd->prevOverload; } + while (ccmd->prevOverload) { ccmd = ccmd->prevOverload; } return ccmd; } } @@ -267,19 +267,19 @@ ccmd_t *Con_FindCommand(char const *name) */ void Con_PrintCommandUsage(ccmd_t const *ccmd, bool allOverloads) { - if(!ccmd) return; + if (!ccmd) return; - if(allOverloads) + if (allOverloads) { // Locate the head of the overload list. - while(ccmd->prevOverload) { ccmd = ccmd->prevOverload; } + while (ccmd->prevOverload) { ccmd = ccmd->prevOverload; } } LOG_SCR_NOTE(_E(b) "Usage:" _E(.) "\n " _E(>) + Con_CmdUsageAsStyledText(ccmd)); - if(allOverloads) + if (allOverloads) { - while((ccmd = ccmd->nextOverload)) + while ((ccmd = ccmd->nextOverload)) { LOG_SCR_MSG(" " _E(>) + Con_CmdUsageAsStyledText(ccmd)); } @@ -288,9 +288,9 @@ void Con_PrintCommandUsage(ccmd_t const *ccmd, bool allOverloads) ccmd_t *Con_FindCommandMatchArgs(cmdargs_t *args) { - if(!args) return 0; + if (!args) return 0; - if(ccmd_t *ccmd = Con_FindCommand(args->argv[0])) + if (ccmd_t *ccmd = Con_FindCommand(args->argv[0])) { // Check each variant. ccmd_t *variant = ccmd; @@ -300,14 +300,14 @@ ccmd_t *Con_FindCommandMatchArgs(cmdargs_t *args) // Are we validating the arguments? // Note that strings are considered always valid. - if(!(variant->minArgs == -1 && variant->maxArgs == -1)) + if (!(variant->minArgs == -1 && variant->maxArgs == -1)) { // Do we have the right number of arguments? - if(args->argc-1 < variant->minArgs) + if (args->argc-1 < variant->minArgs) { invalidArgs = true; } - else if(variant->maxArgs != -1 && args->argc-1 > variant->maxArgs) + else if (variant->maxArgs != -1 && args->argc-1 > variant->maxArgs) { invalidArgs = true; } @@ -315,9 +315,9 @@ ccmd_t *Con_FindCommandMatchArgs(cmdargs_t *args) { // Presently we only validate upto the minimum number of args. /// @todo Validate non-required args. - for(int i = 0; i < variant->minArgs && !invalidArgs; ++i) + for (int i = 0; i < variant->minArgs && !invalidArgs; ++i) { - switch(variant->args[i]) + switch (variant->args[i]) { case CVT_BYTE: invalidArgs = !M_IsStringValidByte(args->argv[i+1]); @@ -335,11 +335,11 @@ ccmd_t *Con_FindCommandMatchArgs(cmdargs_t *args) } } - if(!invalidArgs) + if (!invalidArgs) { return variant; // This is the one! } - } while((variant = variant->nextOverload) != 0); + } while ((variant = variant->nextOverload) != 0); // Perhaps the user needs some help. Con_PrintCommandUsage(ccmd); @@ -351,11 +351,11 @@ ccmd_t *Con_FindCommandMatchArgs(cmdargs_t *args) dd_bool Con_IsValidCommand(char const* name) { - if(!name || !name[0]) + if (!name || !name[0]) return false; // Try the console commands first. - if(Con_FindCommand(name) != 0) + if (Con_FindCommand(name) != 0) return true; // Try the aliases (aliai?) then. @@ -366,14 +366,14 @@ String Con_CmdUsageAsStyledText(ccmd_t const *ccmd) { DENG2_ASSERT(ccmd != 0); - if(ccmd->minArgs == -1 && ccmd->maxArgs == -1) + if (ccmd->minArgs == -1 && ccmd->maxArgs == -1) return String(); // Print the expected form for this ccmd. String argText; - for(int i = 0; i < ccmd->minArgs; ++i) + for (int i = 0; i < ccmd->minArgs; ++i) { - switch(ccmd->args[i]) + switch (ccmd->args[i]) { case CVT_BYTE: argText += " (byte)"; break; case CVT_INT: argText += " (int)"; break; @@ -383,7 +383,7 @@ String Con_CmdUsageAsStyledText(ccmd_t const *ccmd) default: break; } } - if(ccmd->maxArgs == -1) + if (ccmd->maxArgs == -1) { argText += " ..."; } @@ -394,7 +394,7 @@ String Con_CmdUsageAsStyledText(ccmd_t const *ccmd) String Con_CmdAsStyledText(ccmd_t *cmd) { char const *str; - if((str = DH_GetString(DH_Find(cmd->name), HST_DESCRIPTION))) + if ((str = DH_GetString(DH_Find(cmd->name), HST_DESCRIPTION))) { return String(_E(b) "%1 " _E(.) _E(>) _E(2) "%2" _E(.) _E(<)).arg(cmd->name).arg(str); } @@ -414,7 +414,7 @@ D_CMD(MappedConfigVariable) Variable &var = App::config()[found.value()]; - if(argc == 1) + if (argc == 1) { // No argumnets, just print the current value. LOG_SCR_MSG(_E(b) "%s" _E(.) " = " _E(>) "%s " _E(l)_E(C) "[Config.%s]") @@ -422,10 +422,10 @@ D_CMD(MappedConfigVariable) << var.value().asText() << found.value(); } - else if(argc > 1) + else if (argc > 1) { // Retain the current type of the Config variable (numeric or text). - if(var.value().maybeAs()) + if (var.value().maybeAs()) { var.set(new TextValue(argv[1])); } diff --git a/doomsday/apps/libdoomsday/src/console/exec.cpp b/doomsday/apps/libdoomsday/src/console/exec.cpp index 8e77cc2305..5ebe47bc56 100644 --- a/doomsday/apps/libdoomsday/src/console/exec.cpp +++ b/doomsday/apps/libdoomsday/src/console/exec.cpp @@ -155,13 +155,13 @@ static void PrepareCmdArgs(cmdargs_t *cargs, const char *lpCmdLine) strcpy(cargs->cmdLine, lpCmdLine); // Prepare. - for(i = 0; i < len; ++i) + for (i = 0; i < len; ++i) { // Whitespaces are separators. - if(DENG_ISSPACE(cargs->cmdLine[i])) + if (DENG_ISSPACE(cargs->cmdLine[i])) cargs->cmdLine[i] = 0; - if(cargs->cmdLine[i] == '\\' && IS_ESC_CHAR(cargs->cmdLine[i + 1])) + if (cargs->cmdLine[i] == '\\' && IS_ESC_CHAR(cargs->cmdLine[i + 1])) { // Escape sequence. memmove(cargs->cmdLine + i, cargs->cmdLine + i + 1, sizeof(cargs->cmdLine) - i - 1); @@ -169,14 +169,14 @@ static void PrepareCmdArgs(cmdargs_t *cargs, const char *lpCmdLine) continue; } - if(cargs->cmdLine[i] == '"') + if (cargs->cmdLine[i] == '"') { // Find the end. size_t start = i; cargs->cmdLine[i] = 0; - for(++i; i < len && cargs->cmdLine[i] != '"'; ++i) + for (++i; i < len && cargs->cmdLine[i] != '"'; ++i) { - if(cargs->cmdLine[i] == '\\' && IS_ESC_CHAR(cargs->cmdLine[i + 1])) // Escape sequence? + if (cargs->cmdLine[i] == '\\' && IS_ESC_CHAR(cargs->cmdLine[i + 1])) // Escape sequence? { memmove(cargs->cmdLine + i, cargs->cmdLine + i + 1, sizeof(cargs->cmdLine) - i - 1); @@ -186,25 +186,25 @@ static void PrepareCmdArgs(cmdargs_t *cargs, const char *lpCmdLine) } // Quote not terminated? - if(i == len) + if (i == len) break; // An empty set of quotes? - if(i == start + 1) + if (i == start + 1) cargs->cmdLine[i] = SC_EMPTY_QUOTE; else cargs->cmdLine[i] = 0; } - if(cargs->cmdLine[i] == '{') + if (cargs->cmdLine[i] == '{') { // Find matching end, braces are another notation for quotes. int level = 0; size_t start = i; cargs->cmdLine[i] = 0; - for(++i; i < len; ++i) + for (++i; i < len; ++i) { - if(cargs->cmdLine[i] == '\\' && IS_ESC_CHAR(cargs->cmdLine[i + 1])) // Escape sequence? + if (cargs->cmdLine[i] == '\\' && IS_ESC_CHAR(cargs->cmdLine[i + 1])) // Escape sequence? { memmove(cargs->cmdLine + i, cargs->cmdLine + i + 1, sizeof(cargs->cmdLine) - i - 1); @@ -213,24 +213,24 @@ static void PrepareCmdArgs(cmdargs_t *cargs, const char *lpCmdLine) continue; } - if(cargs->cmdLine[i] == '}') + if (cargs->cmdLine[i] == '}') { - if(!level) + if (!level) break; level--; } - if(cargs->cmdLine[i] == '{') + if (cargs->cmdLine[i] == '{') level++; } // Quote not terminated? - if(i == len) + if (i == len) break; // An empty set of braces? - if(i == start + 1) + if (i == start + 1) cargs->cmdLine[i] = SC_EMPTY_QUOTE; else cargs->cmdLine[i] = 0; @@ -239,13 +239,13 @@ static void PrepareCmdArgs(cmdargs_t *cargs, const char *lpCmdLine) // Scan through the cmdLine and get the beginning of each token. cargs->argc = 0; - for(i = 0; i < len; ++i) + for (i = 0; i < len; ++i) { - if(!cargs->cmdLine[i]) + if (!cargs->cmdLine[i]) continue; // Is this an empty quote? - if(cargs->cmdLine[i] == char(SC_EMPTY_QUOTE)) + if (cargs->cmdLine[i] == char(SC_EMPTY_QUOTE)) cargs->cmdLine[i] = 0; // Just an empty string. cargs->argv[cargs->argc++] = cargs->cmdLine + i; @@ -261,7 +261,7 @@ static Value *Function_Console_ListVars(Context &, Function::ArgumentValues cons Con_TermsRegex(vars, args.at(0)->asText(), WT_CVAR); std::unique_ptr result(new ArrayValue); - for(String v : vars) + for (String v : vars) { *result << new TextValue(v); } @@ -270,7 +270,7 @@ static Value *Function_Console_ListVars(Context &, Function::ArgumentValues cons dd_bool Con_Init(void) { - if(ConsoleInited) return true; + if (ConsoleInited) return true; LOG_SCR_VERBOSE("Initializing the console..."); @@ -292,7 +292,7 @@ dd_bool Con_Init(void) void Con_Shutdown(void) { - if(!ConsoleInited) return; + if (!ConsoleInited) return; LOG_SCR_VERBOSE("Shutting down the console..."); @@ -314,7 +314,7 @@ static void Con_Send(const char *command, byte src, int silent) ushort len = (ushort) strlen(command); LOG_AS("Con_Send"); - if(len >= 0x8000) + if (len >= 0x8000) { LOGDEV_NET_ERROR("Command is too long, length=%i") << len; return; @@ -339,14 +339,14 @@ static void Con_QueueCmd(const char *singleCmd, timespan_t atSecond, int i; // Look for an empty spot. - for(i = 0; i < exBuffSize; ++i) - if(!exBuff[i].used) + for (i = 0; i < exBuffSize; ++i) + if (!exBuff[i].used) { ptr = exBuff + i; break; } - if(ptr == NULL) + if (ptr == NULL) { // No empty places, allocate a new one. exBuff = (execbuff_t *) M_Realloc(exBuff, sizeof(execbuff_t) * ++exBuffSize); @@ -384,11 +384,11 @@ static dd_bool Con_CheckExecBuffer(void) TimeDelta const now = TimeDelta::sinceStartOfProcess(); // Execute the commands whose time has come. - for(i = 0; i < exBuffSize; ++i) + for (i = 0; i < exBuffSize; ++i) { execbuff_t *ptr = exBuff + i; - if(!ptr->used || ptr->when > now) + if (!ptr->used || ptr->when > now) continue; // We'll now execute this command. @@ -399,17 +399,17 @@ static dd_bool Con_CheckExecBuffer(void) bool const isInteractive = (ptr->source == CMDS_CONSOLE || ptr->source == CMDS_CMDLINE); - if(isInteractive) + if (isInteractive) { Log::threadLog().beginInteractive(); } - if(!executeSubCmd(storage, ptr->source, ptr->isNetCmd)) + if (!executeSubCmd(storage, ptr->source, ptr->isNetCmd)) { ret = false; } - if(isInteractive) + if (isInteractive) { Log::threadLog().endInteractive(); } @@ -434,15 +434,15 @@ static void expandWithArguments(char **expCommand, cmdargs_t *args) char *text = *expCommand; size_t i, off, size = strlen(text) + 1; - for(i = 0; text[i]; ++i) + for (i = 0; text[i]; ++i) { - if(text[i] == '%' && (text[i + 1] >= '1' && text[i + 1] <= '9')) + if (text[i] == '%' && (text[i + 1] >= '1' && text[i + 1] <= '9')) { char *substr; int aidx = text[i + 1] - '1' + 1; // Expand! (or delete) - if(aidx > args->argc - 1) + if (aidx > args->argc - 1) substr = (char *) ""; else substr = args->argv[aidx]; @@ -452,7 +452,7 @@ static void expandWithArguments(char **expCommand, cmdargs_t *args) // Reallocate. off = strlen(substr); text = *expCommand = (char *) M_Realloc(*expCommand, size += off - 2); - if(off) + if (off) { // Make room for the insert. memmove(text + i + off, text + i, size - i - off); @@ -460,12 +460,12 @@ static void expandWithArguments(char **expCommand, cmdargs_t *args) } i += off - 1; } - else if(text[i] == '%' && text[i + 1] == '0') + else if (text[i] == '%' && text[i + 1] == '0') { // First get rid of the %0. memmove(text + i, text + i + 2, size - i - 2); text = *expCommand = (char *) M_Realloc(*expCommand, size -= 2); - for(p = args->argc - 1; p > 0; p--) + for (p = args->argc - 1; p > 0; p--) { off = strlen(args->argv[p]) + 1; text = *expCommand = (char *) M_Realloc(*expCommand, size += off); @@ -488,19 +488,19 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) calias_t *cal; PrepareCmdArgs(&args, subCmd); - if(!args.argc) + if (!args.argc) return true; // Try to find a matching console command. ccmd = Con_FindCommandMatchArgs(&args); - if(ccmd != NULL) + if (ccmd != NULL) { // Found a match. Are we allowed to execute? dd_bool canExecute = true; // Trying to issue a command requiring a loaded game? // dj: This should be considered a short-term solution. Ideally we want some namespacing mechanics. - if((ccmd->flags & CMDF_NO_NULLGAME) && DoomsdayApp::game().isNull()) + if ((ccmd->flags & CMDF_NO_NULLGAME) && DoomsdayApp::game().isNull()) { LOG_SCR_ERROR("Execution of command '%s' is only allowed when a game is loaded") << ccmd->name; return true; @@ -509,17 +509,17 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) /// @todo Access control needs revising. -jk #if 0 // A dedicated server, trying to execute a ccmd not available to us? - if(isDedicated && (ccmd->flags & CMDF_NO_DEDICATED)) + if (isDedicated && (ccmd->flags & CMDF_NO_DEDICATED)) { LOG_SCR_ERROR("Execution of command '%s' not possible in dedicated mode") << ccmd->name; return true; } // Net commands sent to servers have extra protection. - if(isServer && isNetCmd) + if (isServer && isNetCmd) { // Is the command permitted for use by clients? - if(ccmd->flags & CMDF_CLIENT) + if (ccmd->flags & CMDF_CLIENT) { LOG_NET_ERROR("Execution of command '%s' blocked (client attempted invocation);" "this command is not permitted for use by clients") << ccmd->name; @@ -538,7 +538,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) // // The next step will then be allowing select console commands // to be executed by non-logged in clients. - switch(src) + switch (src) { case CMDS_UNKNOWN: case CMDS_CONFIG: @@ -556,49 +556,49 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) #endif // Is the src permitted for this command? - switch(src) + switch (src) { case CMDS_UNKNOWN: canExecute = false; break; case CMDS_DDAY: - if(ccmd->flags & CMDF_DDAY) + if (ccmd->flags & CMDF_DDAY) canExecute = false; break; case CMDS_GAME: - if(ccmd->flags & CMDF_GAME) + if (ccmd->flags & CMDF_GAME) canExecute = false; break; case CMDS_CONSOLE: - if(ccmd->flags & CMDF_CONSOLE) + if (ccmd->flags & CMDF_CONSOLE) canExecute = false; break; case CMDS_BIND: - if(ccmd->flags & CMDF_BIND) + if (ccmd->flags & CMDF_BIND) canExecute = false; break; case CMDS_CONFIG: - if(ccmd->flags & CMDF_CONFIG) + if (ccmd->flags & CMDF_CONFIG) canExecute = false; break; case CMDS_PROFILE: - if(ccmd->flags & CMDF_PROFILE) + if (ccmd->flags & CMDF_PROFILE) canExecute = false; break; case CMDS_CMDLINE: - if(ccmd->flags & CMDF_CMDLINE) + if (ccmd->flags & CMDF_CMDLINE) canExecute = false; break; case CMDS_SCRIPT: - if(ccmd->flags & CMDF_DED) + if (ccmd->flags & CMDF_DED) canExecute = false; break; @@ -606,13 +606,13 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) return true; } - if(!canExecute) + if (!canExecute) { LOG_SCR_ERROR("'%s' cannot be executed via %s") << ccmd->name << CMDTYPESTR(src); return true; } - if(canExecute) + if (canExecute) { /** * Execute the command! @@ -621,7 +621,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) * this call. */ int result; - if((result = ccmd->execFunc(src, args.argc, args.argv)) == false) + if ((result = ccmd->execFunc(src, args.argc, args.argv)) == false) { LOG_SCR_ERROR("'%s' failed") << args.argv[0]; } @@ -632,7 +632,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) // Then try the cvars? cvar = Con_FindVariable(args.argv[0]); - if(cvar != NULL) + if (cvar != NULL) { dd_bool outOfRange = false, setting = false, hasCallback; @@ -643,18 +643,18 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) */ hasCallback = (cvar->notifyChanged != 0); - if(args.argc == 2 || + if (args.argc == 2 || (args.argc == 3 && !qstricmp(args.argv[1], "force"))) { char* argptr = args.argv[args.argc - 1]; dd_bool forced = args.argc == 3; setting = true; - if(cvar->flags & CVF_READ_ONLY) + if (cvar->flags & CVF_READ_ONLY) { CVar_PrintReadOnlyWarning(cvar); } - else if((cvar->flags & CVF_PROTECTED) && !forced) + else if ((cvar->flags & CVF_PROTECTED) && !forced) { AutoStr* name = CVar_ComposePath(cvar); LOG_SCR_NOTE("%s is protected; you shouldn't change its value -- " @@ -663,11 +663,11 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) } else { - switch(cvar->type) + switch (cvar->type) { case CVT_BYTE: { byte val = (byte) strtol(argptr, NULL, 0); - if(!forced && + if (!forced && ((!(cvar->flags & CVF_NO_MIN) && val < cvar->min) || (!(cvar->flags & CVF_NO_MAX) && val > cvar->max))) outOfRange = true; @@ -677,7 +677,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) } case CVT_INT: { int val = strtol(argptr, NULL, 0); - if(!forced && + if (!forced && ((!(cvar->flags & CVF_NO_MIN) && val < cvar->min) || (!(cvar->flags & CVF_NO_MAX) && val > cvar->max))) outOfRange = true; @@ -687,7 +687,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) } case CVT_FLOAT: { float val = strtod(argptr, NULL); - if(!forced && + if (!forced && ((!(cvar->flags & CVF_NO_MIN) && val < cvar->min) || (!(cvar->flags & CVF_NO_MAX) && val > cvar->max))) outOfRange = true; @@ -707,16 +707,16 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) } } - if(outOfRange) + if (outOfRange) { AutoStr* name = CVar_ComposePath(cvar); - if(!(cvar->flags & (CVF_NO_MIN | CVF_NO_MAX))) + if (!(cvar->flags & (CVF_NO_MIN | CVF_NO_MAX))) { char temp[20]; strcpy(temp, M_TrimmedFloat(cvar->min)); LOG_SCR_ERROR("%s <= %s <= %s") << temp << Str_Text(name) << M_TrimmedFloat(cvar->max); } - else if(cvar->flags & CVF_NO_MAX) + else if (cvar->flags & CVF_NO_MAX) { LOG_SCR_ERROR("%s >= %s") << Str_Text(name) << M_TrimmedFloat(cvar->min); } @@ -725,15 +725,15 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) LOG_SCR_ERROR("%s <= %s") << Str_Text(name) << M_TrimmedFloat(cvar->max); } } - else if(!setting) // Show the value. + else if (!setting) // Show the value. { - if(setting && hasCallback) + if (setting && hasCallback) { // Lookup the cvar again - our pointer may have been invalidated. cvar = Con_FindVariable(args.argv[0]); } - if(cvar) + if (cvar) { // It still exists. Con_PrintCVar(cvar, ""); @@ -744,7 +744,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) // How about an alias then? cal = Con_FindAlias(args.argv[0]); - if(cal != NULL) + if (cal != NULL) { char* expCommand; @@ -759,7 +759,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) } // What *is* that? - if(Con_FindCommand(args.argv[0])) + if (Con_FindCommand(args.argv[0])) { LOG_SCR_WARNING("%s: command arguments invalid") << args.argv[0]; Con_Executef(CMDS_DDAY, false, "help %s", args.argv[0]); @@ -786,37 +786,37 @@ static void Con_SplitIntoSubCommands(const char *command, size_t gPos = 0, scPos = 0, len; // Is there a command to execute? - if(!command || command[0] == 0) + if (!command || command[0] == 0) return; // Jump over initial semicolons. len = strlen(command); - while(gPos < len && command[gPos] == ';' && command[gPos] != 0) + while (gPos < len && command[gPos] == ';' && command[gPos] != 0) gPos++; subCmd[0] = subCmd[BUFFSIZE-1] = 0; // The command may actually contain many commands, separated // with semicolons. This isn't a very clear algorithm... - for(; command[gPos];) + for (; command[gPos];) { escape = false; - if(inQuotes && command[gPos] == '\\') // Escape sequence? + if (inQuotes && command[gPos] == '\\') // Escape sequence? { subCmd[scPos++] = command[gPos++]; escape = true; } - if(command[gPos] == '"' && !escape) + if (command[gPos] == '"' && !escape) inQuotes = !inQuotes; // Collect characters. subCmd[scPos++] = command[gPos++]; - if(subCmd[0] == ' ') + if (subCmd[0] == ' ') scPos = 0; // No spaces in the beginning. - if((command[gPos] == ';' && !inQuotes) || command[gPos] == 0) + if ((command[gPos] == ';' && !inQuotes) || command[gPos] == 0) { - while(gPos < len && command[gPos] == ';' && command[gPos] != 0) + while (gPos < len && command[gPos] == ';' && command[gPos] != 0) gPos++; // The subcommand ends. subCmd[scPos] = 0; @@ -837,7 +837,7 @@ static void Con_SplitIntoSubCommands(const char *command, int Con_Execute(byte src, const char *command, int silent, dd_bool netCmd) { - if(silent) + if (silent) { ConsoleSilent = true; } @@ -845,7 +845,7 @@ int Con_Execute(byte src, const char *command, int silent, dd_bool netCmd) Con_SplitIntoSubCommands(command, 0, src, netCmd); int ret = Con_CheckExecBuffer(); - if(silent) + if (silent) { ConsoleSilent = false; } @@ -873,16 +873,16 @@ bool Con_Parse(File const &file, bool silently) // This file is filled with console commands. QTextStream in(&contents); int currentLine = 1; - while(!in.atEnd()) + while (!in.atEnd()) { // Each line is a command. String const line = String(in.readLine()).leftStrip(); - if(!line.isEmpty() && line.first() != '#') + if (!line.isEmpty() && line.first() != '#') { // Execute the commands silently. - if(!Con_Execute(CMDS_CONFIG, line.toUtf8(), silently, false)) + if (!Con_Execute(CMDS_CONFIG, line.toUtf8(), silently, false)) { - if(!silently) + if (!silently) { LOG_SCR_WARNING("%s (line %i): error executing command \"%s\"") << file.description() @@ -906,19 +906,19 @@ static void makeAlias(char *aName, char *command) dd_bool remove = false; // Will we remove this alias? - if(command == NULL) + if (command == NULL) remove = true; - else if(command[0] == 0) + else if (command[0] == 0) remove = true; - if(cal && remove) // This alias will be removed. + if (cal && remove) // This alias will be removed. { Con_DeleteAlias(cal); return; // We're done. } // Does the alias already exist? - if(cal) + if (cal) { cal->command = (char *) M_Realloc(cal->command, strlen(command) + 1); strcpy(cal->command, command); @@ -933,7 +933,7 @@ D_CMD(Alias) { DENG2_UNUSED(src); - if(argc != 3 && argc != 2) + if (argc != 3 && argc != 2) { LOG_SCR_NOTE("Usage: %s (alias) (cmd)") << argv[0]; LOG_SCR_MSG("Example: alias bigfont \"font size 3\""); @@ -942,7 +942,7 @@ D_CMD(Alias) } makeAlias(argv[1], argc == 3 ? argv[2] : NULL); - if(argc != 3) + if (argc != 3) { LOG_SCR_MSG("Alias '%s' deleted") << argv[1]; } @@ -955,7 +955,7 @@ D_CMD(Parse) int i; - for(i = 1; i < argc; ++i) + for (i = 1; i < argc; ++i) { try { @@ -964,7 +964,7 @@ D_CMD(Parse) NativeFile::newStandalone(App::app().nativeHomePath() / NativePath(argv[i]))); Con_Parse(*file, false /*not silent*/); } - catch(Error const &er) + catch (Error const &er) { LOG_SCR_ERROR("Failed to parse \"%s\": %s") << argv[i] << er.asText(); @@ -980,7 +980,7 @@ D_CMD(Wait) timespan_t offset; offset = strtod(argv[1], NULL) / 35; // Offset in seconds. - if(offset < 0) + if (offset < 0) offset = 0; Con_SplitIntoSubCommands(argv[2], offset, CMDS_CONSOLE, false); return true; @@ -996,7 +996,7 @@ D_CMD(Repeat) count = atoi(argv[1]); interval = strtod(argv[2], NULL) / 35; // In seconds. offset = 0; - while(count-- > 0) + while (count-- > 0) { offset += interval; Con_SplitIntoSubCommands(argv[3], offset, CMDS_CONSOLE, false); @@ -1010,7 +1010,7 @@ D_CMD(Echo) int i; - for(i = 1; i < argc; ++i) + for (i = 1; i < argc; ++i) { LOG_MSG("%s") << argv[i]; } @@ -1022,25 +1022,25 @@ static dd_bool cvarAddSub(const char* name, float delta, dd_bool force) cvar_t* cvar = Con_FindVariable(name); float val; - if(!cvar) + if (!cvar) { - if(name && name[0]) + if (name && name[0]) LOG_SCR_ERROR("%s is not a known cvar") << name; return false; } - if(cvar->flags & CVF_READ_ONLY) + if (cvar->flags & CVF_READ_ONLY) { CVar_PrintReadOnlyWarning(cvar); return false; } val = CVar_Float(cvar) + delta; - if(!force) + if (!force) { - if(!(cvar->flags & CVF_NO_MAX) && val > cvar->max) + if (!(cvar->flags & CVF_NO_MAX) && val > cvar->max) val = cvar->max; - if(!(cvar->flags & CVF_NO_MIN) && val < cvar->min) + if (!(cvar->flags & CVF_NO_MIN) && val < cvar->min) val = cvar->min; } CVar_SetFloat(cvar, val); @@ -1057,19 +1057,19 @@ D_CMD(AddSub) dd_bool force = false; float delta = 0; - if(argc <= 2) + if (argc <= 2) { LOG_SCR_NOTE("Usage: %s (cvar) (val) (force)") << argv[0]; LOG_SCR_MSG("Use force to make cvars go off limits."); return true; } - if(argc >= 4) + if (argc >= 4) { force = !qstricmp(argv[3], "force"); } delta = strtod(argv[2], NULL); - if(!qstricmp(argv[0], "sub")) + if (!qstricmp(argv[0], "sub")) delta = -delta; return cvarAddSub(argv[1], delta, force); @@ -1086,21 +1086,21 @@ D_CMD(IncDec) cvar_t* cvar; float val; - if(argc == 1) + if (argc == 1) { LOG_SCR_NOTE("Usage: %s (cvar) (force)") << argv[0]; LOG_SCR_MSG("Use force to make cvars go off limits."); return true; } - if(argc >= 3) + if (argc >= 3) { force = !qstricmp(argv[2], "force"); } cvar = Con_FindVariable(argv[1]); - if(!cvar) + if (!cvar) return false; - if(cvar->flags & CVF_READ_ONLY) + if (cvar->flags & CVF_READ_ONLY) { LOG_SCR_ERROR("%s (cvar) is read-only, it cannot be changed (even with force)") << argv[1]; return false; @@ -1109,11 +1109,11 @@ D_CMD(IncDec) val = CVar_Float(cvar); val += !qstricmp(argv[0], "inc")? 1 : -1; - if(!force) + if (!force) { - if(!(cvar->flags & CVF_NO_MAX) && val > cvar->max) + if (!(cvar->flags & CVF_NO_MAX) && val > cvar->max) val = cvar->max; - if(!(cvar->flags & CVF_NO_MIN) && val < cvar->min) + if (!(cvar->flags & CVF_NO_MIN) && val < cvar->min) val = cvar->min; } @@ -1129,7 +1129,7 @@ D_CMD(Toggle) DENG2_UNUSED2(src, argc); cvar_t *cvar = Con_FindVariable(argv[1]); - if(!cvar) return false; + if (!cvar) return false; CVar_SetInteger(cvar, CVar_Integer(cvar)? 0 : 1); return true; @@ -1157,7 +1157,7 @@ D_CMD(If) cvar_t *var; dd_bool isTrue = false; - if(argc != 5 && argc != 6) + if (argc != 5 && argc != 6) { LOG_SCR_NOTE("Usage: %s (cvar) (operator) (value) (cmd) (else-cmd)") << argv[0]; LOG_SCR_MSG("Operator must be one of: not, =, >, <, >=, <="); @@ -1166,21 +1166,21 @@ D_CMD(If) } var = Con_FindVariable(argv[1]); - if(!var) + if (!var) return false; // Which operator? - for(i = 0; operators[i].opstr; ++i) - if(!qstricmp(operators[i].opstr, argv[2])) + for (i = 0; operators[i].opstr; ++i) + if (!qstricmp(operators[i].opstr, argv[2])) { oper = operators[i].op; break; } - if(!operators[i].opstr) + if (!operators[i].opstr) return false; // Bad operator. // Value comparison depends on the type of the variable. - switch(var->type) + switch (var->type) { case CVT_BYTE: case CVT_INT: @@ -1227,11 +1227,11 @@ D_CMD(If) } // Should the command be executed? - if(isTrue) + if (isTrue) { Con_Execute(src, argv[4], ConsoleSilent, false); } - else if(argc == 6) + else if (argc == 6) { Con_Execute(src, argv[5], ConsoleSilent, false); } @@ -1276,7 +1276,7 @@ void Con_DataRegister() void Con_InitDatabases(void) { - if(inited) return; + if (inited) return; Con_InitVariableDirectory(); Con_InitCommands(); @@ -1288,7 +1288,7 @@ void Con_InitDatabases(void) void Con_ClearDatabases(void) { - if(!inited) return; + if (!inited) return; Con_ClearKnownWords(); Con_ClearAliases(); Con_ClearCommands(); @@ -1297,7 +1297,7 @@ void Con_ClearDatabases(void) void Con_ShutdownDatabases(void) { - if(!inited) return; + if (!inited) return; Con_ClearDatabases(); Con_DeinitVariableDirectory(); @@ -1316,11 +1316,11 @@ static int printKnownWordWorker(knownword_t const *word, void *parameters) DENG_ASSERT(word); uint *numPrinted = (uint *) parameters; - switch(word->type) + switch (word->type) { case WT_CCMD: { ccmd_t *ccmd = (ccmd_t *) word->data; - if(ccmd->prevOverload) + if (ccmd->prevOverload) { return 0; // Skip overloaded variants. } @@ -1329,7 +1329,7 @@ static int printKnownWordWorker(knownword_t const *word, void *parameters) case WT_CVAR: { cvar_t *cvar = (cvar_t *) word->data; - if(cvar->flags & CVF_HIDE) + if (cvar->flags & CVF_HIDE) { return 0; // Skip hidden variables. } @@ -1349,7 +1349,7 @@ static int printKnownWordWorker(knownword_t const *word, void *parameters) break; } - if(numPrinted) ++(*numPrinted); + if (numPrinted) ++(*numPrinted); return 0; // Continue iteration. } diff --git a/doomsday/apps/libdoomsday/src/console/knownword.cpp b/doomsday/apps/libdoomsday/src/console/knownword.cpp index 0da3fb746c..fb000d6b02 100644 --- a/doomsday/apps/libdoomsday/src/console/knownword.cpp +++ b/doomsday/apps/libdoomsday/src/console/knownword.cpp @@ -56,7 +56,7 @@ static bool compareKnownWordByName(knownword_t const &a, knownword_t const &b) knownword_t const *wB = &b; AutoStr *textA = 0, *textB = 0; - switch(wA->type) + switch (wA->type) { case WT_CALIAS: textA = AutoStr_FromTextStd(((calias_t *)wA->data)->name); break; case WT_CCMD: textA = AutoStr_FromTextStd(((ccmd_t *)wA->data)->name); break; @@ -68,7 +68,7 @@ static bool compareKnownWordByName(knownword_t const &a, knownword_t const &b) exit(1); // Unreachable } - switch(wB->type) + switch (wB->type) { case WT_CALIAS: textB = AutoStr_FromTextStd(((calias_t *)wB->data)->name); break; case WT_CCMD: textB = AutoStr_FromTextStd(((ccmd_t *)wB->data)->name); break; @@ -90,7 +90,7 @@ static AutoStr *textForKnownWord(knownword_t const *word) { AutoStr *text = 0; - switch(word->type) + switch (word->type) { case WT_CALIAS: text = AutoStr_FromTextStd(((calias_t *)word->data)->name); break; case WT_CCMD: text = AutoStr_FromTextStd(((ccmd_t *)word->data)->name); break; @@ -110,11 +110,11 @@ static dd_bool removeFromKnownWords(knownwordtype_t type, void* data) { DENG_ASSERT(VALID_KNOWNWORDTYPE(type) && data != 0); - for(int i = 0; i < knownWords.size(); ++i) + for (int i = 0; i < knownWords.size(); ++i) { knownword_t const &word = knownWords.at(i); - if(word.type != type || word.data != data) + if (word.type != type || word.data != data) continue; knownWords.removeAt(i); @@ -143,7 +143,7 @@ void Con_UpdateKnownWords() */ static void updateKnownWords(void) { - if(!knownWordsNeedUpdate) return; + if (!knownWordsNeedUpdate) return; /* // Count the number of visible console variables. @@ -152,7 +152,7 @@ static void updateKnownWords(void) countCVarParams.type = cvartype_t(-1); countCVarParams.hidden = false; countCVarParams.ignoreHidden = true; - if(cvarDirectory) + if (cvarDirectory) { cvarDirectory->traverse(PathTree::NoBranch, NULL, CVarDirectory::no_hash, countVariable, &countCVarParams); }*/ @@ -179,7 +179,7 @@ static void updateKnownWords(void) // Add aliases? Con_AddKnownWordsForAliases(); - if(appWordsCallback) + if (appWordsCallback) { appWordsCallback(); } @@ -216,33 +216,33 @@ int Con_IterateKnownWords(KnownWordMatchMode matchMode, updateKnownWords(); - for(int i = 0; i < knownWords.size(); ++i) + for (int i = 0; i < knownWords.size(); ++i) { knownword_t const *word = &knownWords.at(i); - if(matchType != WT_ANY && word->type != type) continue; + if (matchType != WT_ANY && word->type != type) continue; - if(patternLength) + if (patternLength) { AutoStr* textString = textForKnownWord(word); - if(matchMode == KnownWordStartsWith) + if (matchMode == KnownWordStartsWith) { - if(qstrnicmp(Str_Text(textString), pattern, patternLength)) + if (qstrnicmp(Str_Text(textString), pattern, patternLength)) continue; // Didn't match. } - else if(matchMode == KnownWordExactMatch) + else if (matchMode == KnownWordExactMatch) { - if(strcasecmp(Str_Text(textString), pattern)) + if (strcasecmp(Str_Text(textString), pattern)) continue; // Didn't match. } - else if(matchMode == KnownWordRegex) + else if (matchMode == KnownWordRegex) { - if(!regex.exactMatch(Str_Text(textString))) + if (!regex.exactMatch(Str_Text(textString))) continue; // Didn't match. } } result = callback(word, parameters); - if(result) break; + if (result) break; } return result; @@ -275,9 +275,9 @@ knownword_t const** Con_CollectKnownWordsMatchingWord(char const* word, uint localCount = 0; Con_IterateKnownWords(word, type, countMatchedWordWorker, &localCount); - if(count) *count = localCount; + if (count) *count = localCount; - if(localCount != 0) + if (localCount != 0) { // Collect the pointers. collectmatchedwordworker_paramaters_t p; @@ -298,7 +298,7 @@ static int aproposPrinter(knownword_t const *word, void *matching) AutoStr *text = textForKnownWord(word); // See if 'matching' is anywhere in the known word. - if(strcasestr(Str_Text(text), (const char*)matching)) + if (strcasestr(Str_Text(text), (const char*)matching)) { char const* wType[KNOWNWORDTYPE_COUNT] = { "cmd ", "var ", "alias ", "game " @@ -312,15 +312,15 @@ static int aproposPrinter(knownword_t const *word, void *matching) // Look for a short description. String tmp; - if(word->type == WT_CCMD || word->type == WT_CVAR) + if (word->type == WT_CCMD || word->type == WT_CVAR) { char const *desc = DH_GetString(DH_Find(Str_Text(text)), HST_DESCRIPTION); - if(desc) + if (desc) { tmp = desc; } } - else if(word->type == WT_GAME) + else if (word->type == WT_GAME) { tmp = reinterpret_cast(word->data)->title(); } @@ -359,20 +359,20 @@ static int annotateMatchedWordCallback(knownword_t const *word, void *parameters AutoStr *name = Con_KnownWordToString(word); de::String found; - if(!work->terms.contains(Str_Text(name))) + if (!work->terms.contains(Str_Text(name))) return false; // keep going - switch(word->type) + switch (word->type) { case WT_CVAR: - if(!(((cvar_t *)word->data)->flags & CVF_HIDE)) + if (!(((cvar_t *)word->data)->flags & CVF_HIDE)) { found = Con_VarAsStyledText((cvar_t *) word->data, ""); } break; case WT_CCMD: - if(!((ccmd_t *)word->data)->prevOverload) + if (!((ccmd_t *)word->data)->prevOverload) { found = Con_CmdAsStyledText((ccmd_t *) word->data); } @@ -390,9 +390,9 @@ static int annotateMatchedWordCallback(knownword_t const *word, void *parameters break; } - if(!found.isEmpty()) + if (!found.isEmpty()) { - if(!work->result.isEmpty()) work->result.append("\n"); + if (!work->result.isEmpty()) work->result.append("\n"); work->result.append(found); } @@ -402,7 +402,7 @@ static int annotateMatchedWordCallback(knownword_t const *word, void *parameters de::String Con_AnnotatedConsoleTerms(QStringList terms) { AnnotationWork work; - foreach(QString term, terms) + foreach (QString term, terms) { work.terms.insert(term); } diff --git a/doomsday/apps/libdoomsday/src/console/var.cpp b/doomsday/apps/libdoomsday/src/console/var.cpp index 111cb583a8..9944a0c71f 100644 --- a/doomsday/apps/libdoomsday/src/console/var.cpp +++ b/doomsday/apps/libdoomsday/src/console/var.cpp @@ -60,14 +60,14 @@ static int markVariableUserDataFreed(CVarDirectory::Node &node, void *context) cvar_t *var = reinterpret_cast(node.userPointer()); void **ptr = (void **) context; - if(var) - switch(CVar_Type(var)) + if (var) + switch (CVar_Type(var)) { case CVT_CHARPTR: - if(*ptr == CV_CHARPTR(var)) var->flags &= ~CVF_CAN_FREE; + if (*ptr == CV_CHARPTR(var)) var->flags &= ~CVF_CAN_FREE; break; case CVT_URIPTR: - if(*ptr == CV_URIPTR(var)) var->flags &= ~CVF_CAN_FREE; + if (*ptr == CV_URIPTR(var)) var->flags &= ~CVF_CAN_FREE; break; default: break; } @@ -77,18 +77,18 @@ static int markVariableUserDataFreed(CVarDirectory::Node &node, void *context) static int clearVariable(CVarDirectory::Node& node, void * /*context*/) { cvar_t *var = reinterpret_cast(node.userPointer()); - if(var) + if (var) { // Detach our user data from this node. node.setUserPointer(0); - if(CVar_Flags(var) & CVF_CAN_FREE) + if (CVar_Flags(var) & CVF_CAN_FREE) { void** ptr = NULL; - switch(CVar_Type(var)) + switch (CVar_Type(var)) { case CVT_CHARPTR: - if(!CV_CHARPTR(var)) break; + if (!CV_CHARPTR(var)) break; ptr = (void**)var->ptr; /// @note Multiple vars could be using the same pointer (so only free once). @@ -97,7 +97,7 @@ static int clearVariable(CVarDirectory::Node& node, void * /*context*/) break; case CVT_URIPTR: - if(!CV_URIPTR(var)) break; + if (!CV_URIPTR(var)) break; ptr = (void**)var->ptr; /// @note Multiple vars could be using the same pointer (so only free once). @@ -124,7 +124,7 @@ void Con_ClearVariables() #else PathTree::ComparisonFlags flags = PathTree::NoBranch; #endif - if(!cvarDirectory) return; + if (!cvarDirectory) return; cvarDirectory->traverse(flags, NULL, CVarDirectory::no_hash, clearVariable); cvarDirectory->clear(); @@ -138,7 +138,7 @@ static cvar_t* addVariable(cvartemplate_t const& tpl) cvar_t* newVar; DENG_ASSERT(!node->userPointer()); - if(node->userPointer()) + if (node->userPointer()) { throw Error("Con_AddVariable", "A variable with path '" + String(tpl.path) + "' is already known!"); } @@ -162,7 +162,7 @@ String CVar_TypeAsText(cvar_t const *var) { // Human-readable type name. DENG_ASSERT(var); - switch(var->type) + switch (var->type) { case CVT_BYTE: return "byte"; @@ -240,20 +240,20 @@ void CVar_SetUri2(cvar_t *var, de::Uri const &uri, int svFlags) de::Uri *newUri; bool changed = false; - if((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) + if ((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) { CVar_PrintReadOnlyWarning(var); return; } - if(var->type != CVT_URIPTR) + if (var->type != CVT_URIPTR) { App_FatalError("CVar::SetUri: Not of type %s.", Str_Text(CVar_TypeName(CVT_URIPTR))); return; // Unreachable. } /* - if(!CV_URIPTR(var) && !uri) + if (!CV_URIPTR(var) && !uri) { return; } @@ -262,13 +262,13 @@ void CVar_SetUri2(cvar_t *var, de::Uri const &uri, int svFlags) // Compose the new uri. newUri = new de::Uri(uri); - if(!CV_URIPTR(var) || *CV_URIPTR(var) != *newUri) + if (!CV_URIPTR(var) || *CV_URIPTR(var) != *newUri) { changed = true; } // Free the old uri, if one exists. - if((var->flags & CVF_CAN_FREE) && CV_URIPTR(var)) + if ((var->flags & CVF_CAN_FREE) && CV_URIPTR(var)) { delete CV_URIPTR(var); } @@ -277,7 +277,7 @@ void CVar_SetUri2(cvar_t *var, de::Uri const &uri, int svFlags) CV_URIPTR(var) = newUri; // Make the change notification callback - if(var->notifyChanged && changed) + if (var->notifyChanged && changed) { var->notifyChanged(); } @@ -295,13 +295,13 @@ void CVar_SetString2(cvar_t *var, char const *text, int svFlags) bool changed = false; size_t oldLen, newLen; - if((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) + if ((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) { CVar_PrintReadOnlyWarning(var); return; } - if(var->type != CVT_CHARPTR) + if (var->type != CVT_CHARPTR) { printTypeWarning(var, "text", text); return; @@ -310,14 +310,14 @@ void CVar_SetString2(cvar_t *var, char const *text, int svFlags) oldLen = (!CV_CHARPTR(var)? 0 : strlen(CV_CHARPTR(var))); newLen = (!text ? 0 : strlen(text)); - if(oldLen == 0 && newLen == 0) + if (oldLen == 0 && newLen == 0) return; - if(oldLen != newLen || qstricmp(text, CV_CHARPTR(var))) + if (oldLen != newLen || qstricmp(text, CV_CHARPTR(var))) changed = true; // Free the old string, if one exists. - if((var->flags & CVF_CAN_FREE) && CV_CHARPTR(var)) + if ((var->flags & CVF_CAN_FREE) && CV_CHARPTR(var)) free(CV_CHARPTR(var)); // Allocate a new string. @@ -326,7 +326,7 @@ void CVar_SetString2(cvar_t *var, char const *text, int svFlags) qstrcpy(CV_CHARPTR(var), text); // Make the change notification callback - if(var->notifyChanged != NULL && changed) + if (var->notifyChanged != NULL && changed) var->notifyChanged(); } @@ -341,26 +341,26 @@ void CVar_SetInteger2(cvar_t* var, int value, int svFlags) bool changed = false; - if((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) + if ((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) { CVar_PrintReadOnlyWarning(var); return; } - switch(var->type) + switch (var->type) { case CVT_INT: - if(CV_INT(var) != value) + if (CV_INT(var) != value) changed = true; CV_INT(var) = value; break; case CVT_BYTE: - if(CV_BYTE(var) != (byte) value) + if (CV_BYTE(var) != (byte) value) changed = true; CV_BYTE(var) = (byte) value; break; case CVT_FLOAT: - if(CV_FLOAT(var) != (float) value) + if (CV_FLOAT(var) != (float) value) changed = true; CV_FLOAT(var) = (float) value; break; @@ -371,7 +371,7 @@ void CVar_SetInteger2(cvar_t* var, int value, int svFlags) } // Make a change notification callback? - if(var->notifyChanged != 0 && changed) + if (var->notifyChanged != 0 && changed) var->notifyChanged(); } @@ -388,26 +388,26 @@ void CVar_SetFloat2(cvar_t* var, float value, int svFlags) LOG_AS("CVar_SetFloat2"); - if((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) + if ((var->flags & CVF_READ_ONLY) && !(svFlags & SVF_WRITE_OVERRIDE)) { CVar_PrintReadOnlyWarning(var); return; } - switch(var->type) + switch (var->type) { case CVT_INT: - if(CV_INT(var) != (int) value) + if (CV_INT(var) != (int) value) changed = true; CV_INT(var) = (int) value; break; case CVT_BYTE: - if(CV_BYTE(var) != (byte) value) + if (CV_BYTE(var) != (byte) value) changed = true; CV_BYTE(var) = (byte) value; break; case CVT_FLOAT: - if(CV_FLOAT(var) != value) + if (CV_FLOAT(var) != value) changed = true; CV_FLOAT(var) = value; break; @@ -418,7 +418,7 @@ void CVar_SetFloat2(cvar_t* var, float value, int svFlags) } // Make a change notification callback? - if(var->notifyChanged != 0 && changed) + if (var->notifyChanged != 0 && changed) var->notifyChanged(); } @@ -437,7 +437,7 @@ static void printConversionWarning(cvar_t const *var) int CVar_Integer(cvar_t const* var) { DENG_ASSERT(var); - switch(var->type) + switch (var->type) { case CVT_BYTE: return CV_BYTE(var); case CVT_INT: return CV_INT(var); @@ -453,7 +453,7 @@ int CVar_Integer(cvar_t const* var) float CVar_Float(cvar_t const* var) { DENG_ASSERT(var); - switch(var->type) + switch (var->type) { case CVT_BYTE: return CV_BYTE(var); case CVT_INT: return CV_INT(var); @@ -469,7 +469,7 @@ float CVar_Float(cvar_t const* var) byte CVar_Byte(cvar_t const* var) { DENG_ASSERT(var); - switch(var->type) + switch (var->type) { case CVT_BYTE: return CV_BYTE(var); case CVT_INT: return CV_INT(var); @@ -486,7 +486,7 @@ char const* CVar_String(cvar_t const* var) { DENG_ASSERT(var); /// @todo Why not implement in-place value to string conversion? - switch(var->type) + switch (var->type) { case CVT_CHARPTR: return CV_CHARPTR(var); default: { @@ -498,10 +498,10 @@ char const* CVar_String(cvar_t const* var) de::Uri const &CVar_Uri(cvar_t const *var) { - if(!var) return *emptyUri; + if (!var) return *emptyUri; /// @todo Why not implement in-place string to uri conversion? - switch(var->type) + switch (var->type) { case CVT_URIPTR: return *CV_URIPTR(var); default: { @@ -515,9 +515,9 @@ void Con_AddVariable(cvartemplate_t const *tpl) { LOG_AS("Con_AddVariable"); - if(!tpl) return; + if (!tpl) return; - if(CVT_NULL == tpl->type) + if (CVT_NULL == tpl->type) { LOGDEV_SCR_WARNING("Ignored attempt to register variable '%s' as type %s") << tpl->path << Str_Text(CVar_TypeName(CVT_NULL)); @@ -529,11 +529,11 @@ void Con_AddVariable(cvartemplate_t const *tpl) void Con_AddVariableList(cvartemplate_t const *tplList) { - if(!tplList) return; + if (!tplList) return; - for(; tplList->path; ++tplList) + for (; tplList->path; ++tplList) { - if(Con_FindVariable(tplList->path)) + if (Con_FindVariable(tplList->path)) { App_FatalError("Console variable with the name '%s' is already registered", tplList->path); } @@ -543,7 +543,7 @@ void Con_AddVariableList(cvartemplate_t const *tplList) cvar_t *Con_FindVariable(char const *path) { - if(!path || !path[0]) return 0; + if (!path || !path[0]) return 0; try { @@ -551,29 +551,29 @@ cvar_t *Con_FindVariable(char const *path) PathTree::NoBranch | PathTree::MatchFull); return (cvar_t*) node.userPointer(); } - catch(CVarDirectory::NotFoundError const&) + catch (CVarDirectory::NotFoundError const&) {} // Ignore this error. return 0; } String Con_VarAsStyledText(cvar_t *var, char const *prefix) { - if(!var) return ""; + if (!var) return ""; char equals = '='; - if((var->flags & CVF_PROTECTED) || (var->flags & CVF_READ_ONLY)) + if ((var->flags & CVF_PROTECTED) || (var->flags & CVF_READ_ONLY)) equals = ':'; String str; QTextStream os(&str); - if(prefix) os << prefix; + if (prefix) os << prefix; AutoStr* path = CVar_ComposePath(var); os << _E(b) << Str_Text(path) << _E(.) << " " << equals << " " << _E(>); - switch(var->type) + switch (var->type) { case CVT_BYTE: os << CV_BYTE(var); break; case CVT_INT: os << CV_INT(var); break; @@ -601,7 +601,7 @@ static int addVariableToKnownWords(CVarDirectory::Node& node, void* /*parameters cvar_t* var = reinterpret_cast( node.userPointer() ); //uint* index = (uint*) parameters; - if(var && !(var->flags & CVF_HIDE)) + if (var && !(var->flags & CVF_HIDE)) { Con_AddKnownWord(WT_CVAR, var); } @@ -610,7 +610,7 @@ static int addVariableToKnownWords(CVarDirectory::Node& node, void* /*parameters void Con_AddKnownWordsForVariables() { - if(!cvarDirectory) return; + if (!cvarDirectory) return; cvarDirectory->traverse(PathTree::NoBranch, NULL, CVarDirectory::no_hash, addVariableToKnownWords); @@ -620,12 +620,12 @@ static Value *Function_Console_Get(Context &, Function::ArgumentValues const &ar { String const name = args.at(0)->asText(); cvar_t *var = Con_FindVariable(name.toUtf8()); - if(!var) + if (!var) { throw Error("Function_Console_Get", QString("Unknown console variable: %1").arg(name)); } - switch(var->type) + switch (var->type) { case CVT_BYTE: return new NumberValue(CVar_Byte(var)); @@ -652,14 +652,14 @@ static Value *Function_Console_Set(Context &, Function::ArgumentValues const &ar { String const name = args.at(0)->asText(); cvar_t *var = Con_FindVariable(name.toUtf8()); - if(!var) + if (!var) { throw Error("Function_Console_Set", QString("Unknown console variable: %1").arg(name)); } Value const &value = *args.at(1); - switch(var->type) + switch (var->type) { case CVT_BYTE: case CVT_INT: @@ -707,14 +707,14 @@ static int countVariable(CVarDirectory::Node& node, void* parameters) countvariableparams_t* p = (countvariableparams_t*) parameters; cvar_t* var = reinterpret_cast( node.userPointer() ); - if(!(p->ignoreHidden && (var->flags & CVF_HIDE))) + if (!(p->ignoreHidden && (var->flags & CVF_HIDE))) { - if(!VALID_CVARTYPE(p->type) && !p->hidden) + if (!VALID_CVARTYPE(p->type) && !p->hidden) { - if(!p->ignoreHidden || !(var->flags & CVF_HIDE)) + if (!p->ignoreHidden || !(var->flags & CVF_HIDE)) ++(p->count); } - else if((p->hidden && (var->flags & CVF_HIDE)) || + else if ((p->hidden && (var->flags & CVF_HIDE)) || (VALID_CVARTYPE(p->type) && p->type == CVar_Type(var))) { ++(p->count); @@ -730,12 +730,12 @@ D_CMD(PrintVarStats) uint numCVars = 0, numCVarsHidden = 0; LOG_SCR_MSG(_E(b) "Console Variable Statistics:"); - if(cvarDirectory) + if (cvarDirectory) { countvariableparams_t p; p.hidden = false; p.ignoreHidden = false; - for(uint i = uint(CVT_BYTE); i < uint(CVARTYPE_COUNT); ++i) + for (uint i = uint(CVT_BYTE); i < uint(CVARTYPE_COUNT); ++i) { p.count = 0; p.type = cvartype_t(i); @@ -752,7 +752,7 @@ D_CMD(PrintVarStats) } LOG_SCR_MSG(" Total: %i\n Hidden: %i") << numCVars << numCVarsHidden; - if(cvarDirectory) + if (cvarDirectory) { cvarDirectory->debugPrintHashDistribution(); cvarDirectory->debugPrint(CVARDIRECTORY_DELIMITER); diff --git a/doomsday/apps/libdoomsday/src/defs/ded.cpp b/doomsday/apps/libdoomsday/src/defs/ded.cpp index 77b0b8e323..81eb414df3 100644 --- a/doomsday/apps/libdoomsday/src/defs/ded.cpp +++ b/doomsday/apps/libdoomsday/src/defs/ded.cpp @@ -43,7 +43,7 @@ using namespace de; float ded_ptcstage_t::particleRadius(int ptcIDX) const { - if(radiusVariance) + if (radiusVariance) { static float const rnd[16] = { .875f, .125f, .3125f, .75f, .5f, .375f, .5625f, .0625f, 1, .6875f, .625f, .4375f, .8125f, .1875f, @@ -260,14 +260,14 @@ int DED_AddTextureEnv(ded_t* ded, char const* id) int DED_AddCompositeFont(ded_t* ded, char const* uri) { ded_compositefont_t* cfont = ded->compositeFonts.append(); - if(uri) cfont->uri = new de::Uri(uri, RC_NULL); + if (uri) cfont->uri = new de::Uri(uri, RC_NULL); return ded->compositeFonts.indexOf(cfont); } int DED_AddValue(ded_t* ded, char const* id) { ded_value_t* val = ded->values.append(); - if(id) + if (id) { val->id = (char *) M_Malloc(strlen(id) + 1); strcpy(val->id, id); @@ -282,7 +282,7 @@ int DED_AddDetail(ded_t *ded, char const *lumpname) // Default usage is allowed with custom textures and external replacements. dtl->flags = DTLF_PWAD|DTLF_EXTERNAL; - if(lumpname && lumpname[0]) + if (lumpname && lumpname[0]) { dtl->stage.texture = new de::Uri(lumpname, RC_NULL); } @@ -360,13 +360,13 @@ int DED_AddLineType(ded_t* ded, int id) int ded_s::getMobjNum(String const &id) const { - if(Record const *def = things.tryFind("id", id)) + if (Record const *def = things.tryFind("id", id)) { return def->geti("__order__"); } /* - for(i = 0; i < mobjs.size(); ++i) - if(!qstricmp(mobjs[i].id, id)) + for (i = 0; i < mobjs.size(); ++i) + if (!qstricmp(mobjs[i].id, id)) return i;*/ return -1; @@ -374,14 +374,14 @@ int ded_s::getMobjNum(String const &id) const int ded_s::getMobjNumForName(const char *name) const { - if(!name || !name[0]) + if (!name || !name[0]) return -1; /* - for(int i = mobjs.size() - 1; i >= 0; --i) - if(!qstricmp(mobjs[i].name, name)) + for (int i = mobjs.size() - 1; i >= 0; --i) + if (!qstricmp(mobjs[i].name, name)) return i;*/ - if(Record const *def = things.tryFind("name", name)) + if (Record const *def = things.tryFind("name", name)) { return def->geti("__order__"); } @@ -391,14 +391,14 @@ int ded_s::getMobjNumForName(const char *name) const String ded_s::getMobjName(int num) const { - if(num < 0) return "(<0)"; - if(num >= things.size()) return "(>mobjtypes)"; + if (num < 0) return "(<0)"; + if (num >= things.size()) return "(>mobjtypes)"; return things[num].gets("id"); } int ded_s::getStateNum(String const &id) const { - if(Record const *def = states.tryFind("id", id)) + if (Record const *def = states.tryFind("id", id)) { return def->geti("__order__"); } @@ -416,7 +416,7 @@ dint ded_s::evalFlags(char const *ptr) const dint value = 0; - while(*ptr) + while (*ptr) { ptr = M_SkipWhite(const_cast(ptr)); @@ -424,7 +424,7 @@ dint ded_s::evalFlags(char const *ptr) const String flagName(ptr, flagNameLength); ptr += flagNameLength; - if(Record const *flag = flags.tryFind("id", flagName.toLower())) + if (Record const *flag = flags.tryFind("id", flagName.toLower())) { value |= flag->geti("value"); } @@ -438,7 +438,7 @@ dint ded_s::evalFlags(char const *ptr) const int ded_s::getEpisodeNum(String const &id) const { - if(Record const *def = episodes.tryFind("id", id)) + if (Record const *def = episodes.tryFind("id", id)) { return def->geti("__order__"); } @@ -447,7 +447,7 @@ int ded_s::getEpisodeNum(String const &id) const int ded_s::getMapInfoNum(de::Uri const &uri) const { - if(Record const *def = mapInfos.tryFind("id", uri.compose())) + if (Record const *def = mapInfos.tryFind("id", uri.compose())) { return def->geti("__order__"); } @@ -456,27 +456,27 @@ int ded_s::getMapInfoNum(de::Uri const &uri) const int ded_s::getMaterialNum(de::Uri const &uri) const { - if(uri.isEmpty()) return -1; // Not found. + if (uri.isEmpty()) return -1; // Not found. - if(uri.scheme().isEmpty()) + if (uri.scheme().isEmpty()) { // Caller doesn't care which scheme - use a priority search order. de::Uri temp(uri); temp.setScheme("Sprites"); int idx = getMaterialNum(temp); - if(idx >= 0) return idx; + if (idx >= 0) return idx; temp.setScheme("Textures"); idx = getMaterialNum(temp); - if(idx >= 0) return idx; + if (idx >= 0) return idx; temp.setScheme("Flats"); idx = getMaterialNum(temp); - /*if(idx >= 0)*/ return idx; + /*if (idx >= 0)*/ return idx; } - if(Record const *def = materials.tryFind("id", uri.compose())) + if (Record const *def = materials.tryFind("id", uri.compose())) { return def->geti("__order__"); } @@ -485,36 +485,36 @@ int ded_s::getMaterialNum(de::Uri const &uri) const int ded_s::getModelNum(const char *id) const { - if(Record const *def = models.tryFind("id", id)) + if (Record const *def = models.tryFind("id", id)) { return def->geti("__order__"); } return -1; /* int idx = -1; - if(id && id[0] && !models.empty()) + if (id && id[0] && !models.empty()) { int i = 0; do { - if(!qstricmp(models[i].id, id)) idx = i; - } while(idx == -1 && ++i < (int)models.size()); + if (!qstricmp(models[i].id, id)) idx = i; + } while (idx == -1 && ++i < (int)models.size()); } return idx;*/ } int ded_s::getSkyNum(char const *id) const { - if(Record const *def = skies.tryFind("id", id)) + if (Record const *def = skies.tryFind("id", id)) { return def->geti("__order__"); } return -1; - /*if(!id || !id[0]) return -1; + /*if (!id || !id[0]) return -1; - for(int i = skies.size() - 1; i >= 0; i--) + for (int i = skies.size() - 1; i >= 0; i--) { - if(!qstricmp(skies[i].id, id)) + if (!qstricmp(skies[i].id, id)) return i; } return -1;*/ @@ -528,23 +528,23 @@ int ded_s::getSoundNum(String const &id) const int ded_s::getSoundNum(const char *id) const { int idx = -1; - if(id && id[0] && sounds.size()) + if (id && id[0] && sounds.size()) { int i = 0; do { - if(!qstricmp(sounds[i].id, id)) idx = i; - } while(idx == -1 && ++i < sounds.size()); + if (!qstricmp(sounds[i].id, id)) idx = i; + } while (idx == -1 && ++i < sounds.size()); } return idx; } int ded_s::getSoundNumForName(const char *name) const { - if(!name || !name[0]) + if (!name || !name[0]) return -1; - for(int i = 0; i < sounds.size(); ++i) - if(!qstricmp(sounds[i].name, name)) + for (int i = 0; i < sounds.size(); ++i) + if (!qstricmp(sounds[i].name, name)) return i; return 0; @@ -557,11 +557,11 @@ int ded_s::getSpriteNum(String const &id) const int ded_s::getSpriteNum(char const *id) const { - if(id && id[0]) + if (id && id[0]) { - for(dint i = 0; i < sprites.size(); ++i) + for (dint i = 0; i < sprites.size(); ++i) { - if(!qstricmp(sprites[i].id, id)) + if (!qstricmp(sprites[i].id, id)) return i; } } @@ -570,31 +570,31 @@ int ded_s::getSpriteNum(char const *id) const int ded_s::getMusicNum(char const *id) const { - if(Record const *def = musics.tryFind("id", id)) + if (Record const *def = musics.tryFind("id", id)) { return def->geti("__order__"); } return -1; /*int idx = -1; - if(id && id[0] && musics.size()) + if (id && id[0] && musics.size()) { int i = 0; do { - if(!qstricmp(musics[i].id, id)) idx = i; - } while(idx == -1 && ++i < musics.size()); + if (!qstricmp(musics[i].id, id)) idx = i; + } while (idx == -1 && ++i < musics.size()); } return idx;*/ } int ded_s::getValueNum(char const *id) const { - if(id && id[0]) + if (id && id[0]) { // Read backwards to allow patching. - for(dint i = values.size() - 1; i >= 0; i--) + for (dint i = values.size() - 1; i >= 0; i--) { - if(!qstricmp(values[i].id, id)) + if (!qstricmp(values[i].id, id)) return i; } } @@ -608,12 +608,12 @@ int ded_s::getValueNum(String const &id) const ded_value_t *ded_s::getValueById(char const *id) const { - if(!id || !id[0]) return nullptr; + if (!id || !id[0]) return nullptr; // Read backwards to allow patching. - for(dint i = values.size() - 1; i >= 0; i--) + for (dint i = values.size() - 1; i >= 0; i--) { - if(!qstricmp(values[i].id, id)) + if (!qstricmp(values[i].id, id)) return &values[i]; } return nullptr; @@ -625,7 +625,7 @@ ded_value_t *ded_s::getValueById(String const &id) const ded_value_t *ded_s::getValueByUri(de::Uri const &uri) const { - if(!uri.scheme().compareWithoutCase("Values")) + if (!uri.scheme().compareWithoutCase("Values")) { return getValueById(uri.pathCStr()); } @@ -634,10 +634,10 @@ ded_value_t *ded_s::getValueByUri(de::Uri const &uri) const ded_compositefont_t *ded_s::findCompositeFontDef(de::Uri const &uri) const { - for(dint i = compositeFonts.size() - 1; i >= 0; i--) + for (dint i = compositeFonts.size() - 1; i >= 0; i--) { ded_compositefont_t *def = &compositeFonts[i]; - if(def->uri && uri == *def->uri) + if (def->uri && uri == *def->uri) { return def; } @@ -648,25 +648,25 @@ ded_compositefont_t *ded_s::findCompositeFontDef(de::Uri const &uri) const ded_compositefont_t *ded_s::getCompositeFont(char const *uriCString) const { ded_compositefont_t *def = nullptr; - if(uriCString && uriCString[0]) + if (uriCString && uriCString[0]) { de::Uri uri(uriCString, RC_NULL); - if(uri.scheme().isEmpty()) + if (uri.scheme().isEmpty()) { // Caller doesn't care which scheme - use a priority search order. de::Uri temp(uri); temp.setScheme("Game"); def = findCompositeFontDef(temp); - if(!def) + if (!def) { temp.setScheme("System"); def = findCompositeFontDef(temp); } } - if(!def) + if (!def) { def = findCompositeFontDef(uri); } @@ -676,12 +676,12 @@ ded_compositefont_t *ded_s::getCompositeFont(char const *uriCString) const int ded_s::getTextNum(char const *id) const { - if(id && id[0]) + if (id && id[0]) { // Search in reverse insertion order to allow patching. - for(int i = text.size() - 1; i >= 0; i--) + for (int i = text.size() - 1; i >= 0; i--) { - if(!qstricmp(text[i].id, id)) return i; + if (!qstricmp(text[i].id, id)) return i; } } return -1; // Not found. diff --git a/doomsday/apps/libdoomsday/src/defs/dedfile.cpp b/doomsday/apps/libdoomsday/src/defs/dedfile.cpp index 01ea67cf4a..bb24b2690c 100644 --- a/doomsday/apps/libdoomsday/src/defs/dedfile.cpp +++ b/doomsday/apps/libdoomsday/src/defs/dedfile.cpp @@ -42,40 +42,40 @@ void Def_ReadProcessDED(ded_t *defs, String sourcePath) { LOG_AS("Def_ReadProcessDED"); - if(sourcePath.isEmpty()) return; + if (sourcePath.isEmpty()) return; // Try FS2 first. try { Block text; App::rootFolder().locate(sourcePath) >> text; - if(!DED_ReadData(defs, text, sourcePath, true/*consider it custom; there is no way to check...*/)) + if (!DED_ReadData(defs, text, sourcePath, true/*consider it custom; there is no way to check...*/)) { App_FatalError("Def_ReadProcessDED: %s\n", dedReadError); } return; // Done! } - catch(...) + catch (...) { // Try FS1 as fallback. } de::Uri const uri(sourcePath, RC_NULL); - if(!App_FileSystem().accessFile(uri)) + if (!App_FileSystem().accessFile(uri)) { LOG_RES_WARNING("\"%s\" not found!") << NativePath(uri.asText()).pretty(); return; } // We use the File Ids to prevent loading the same files multiple times. - if(!App_FileSystem().checkFileId(uri)) + if (!App_FileSystem().checkFileId(uri)) { // Already handled. LOG_RES_XVERBOSE("\"%s\" has already been read") << NativePath(uri.asText()).pretty(); return; } - if(!DED_Read(defs, sourcePath)) + if (!DED_Read(defs, sourcePath)) { App_FatalError("Def_ReadProcessDED: %s\n", dedReadError); } @@ -86,7 +86,7 @@ int DED_ReadLump(ded_t *ded, lumpnum_t lumpNum) try { File1 &lump = App_FileSystem().lump(lumpNum); - if(lump.size() > 0) + if (lump.size() > 0) { uint8_t const *data = lump.cache(); String sourcePath = lump.container().composePath(); @@ -96,7 +96,7 @@ int DED_ReadLump(ded_t *ded, lumpnum_t lumpNum) } return true; } - catch(LumpIndex::NotFoundError const&) + catch (LumpIndex::NotFoundError const&) {} // Ignore error. DED_SetError("Bad lump number"); return false; @@ -130,7 +130,7 @@ int DED_Read(ded_t *ded, String path) M_Free(bufferedDef); return result; } - catch(FS1::NotFoundError const &) + catch (FS1::NotFoundError const &) {} // Ignore. DED_SetError("File could not be opened for reading"); diff --git a/doomsday/apps/libdoomsday/src/defs/dedparser.cpp b/doomsday/apps/libdoomsday/src/defs/dedparser.cpp index fc34144beb..eff10c7dd7 100644 --- a/doomsday/apps/libdoomsday/src/defs/dedparser.cpp +++ b/doomsday/apps/libdoomsday/src/defs/dedparser.cpp @@ -85,68 +85,68 @@ using namespace de; #define ISTOKEN(X) (!stricmp(token, X)) -#define READSTR(X) if(!ReadString(X, sizeof(X))) { \ +#define READSTR(X) if (!ReadString(X, sizeof(X))) { \ setError("Syntax error in string value."); \ retVal = false; goto ded_end_read; } -#define READURI(X, SHM) if(!ReadUri(X, SHM)) { \ +#define READURI(X, SHM) if (!ReadUri(X, SHM)) { \ setError("Syntax error parsing resource path."); \ retVal = false; goto ded_end_read; } #define MISSING_SC_ERROR setError("Missing semicolon."); \ retVal = false; goto ded_end_read; -#define CHECKSC if(source->version <= 5) { ReadToken(); if(!ISTOKEN(";")) { MISSING_SC_ERROR; } } +#define CHECKSC if (source->version <= 5) { ReadToken(); if (!ISTOKEN(";")) { MISSING_SC_ERROR; } } -#define FINDBEGIN while(!ISTOKEN("{") && !source->atEnd) ReadToken(); -#define FINDEND while(!ISTOKEN("}") && !source->atEnd) ReadToken(); +#define FINDBEGIN while (!ISTOKEN("{") && !source->atEnd) ReadToken(); +#define FINDEND while (!ISTOKEN("}") && !source->atEnd) ReadToken(); #define ISLABEL(X) (!stricmp(label, X)) -#define READLABEL if(!ReadLabel(label)) { retVal = false; goto ded_end_read; } \ - if(ISLABEL("}")) break; +#define READLABEL if (!ReadLabel(label)) { retVal = false; goto ded_end_read; } \ + if (ISLABEL("}")) break; -#define READLABEL_NOBREAK if(!ReadLabel(label)) { retVal = false; goto ded_end_read; } +#define READLABEL_NOBREAK if (!ReadLabel(label)) { retVal = false; goto ded_end_read; } #define FAILURE retVal = false; goto ded_end_read; -#define READBYTE(X) if(!ReadByte(&X)) { FAILURE } -#define READINT(X) if(!ReadInt(&X, false)) { FAILURE } -#define READUINT(X) if(!ReadInt(&X, true)) { FAILURE } -#define READFLT(X) if(!ReadFloat(&X)) { FAILURE } -#define READNBYTEVEC(X,N) if(!ReadNByteVector(X, N)) { FAILURE } -#define READFLAGS(X,P) if(!ReadFlags(&X, P)) { FAILURE } -#define READBLENDMODE(X) if(!ReadBlendmode(&X)) { FAILURE } -#define READSTRING(S,I) if(!ReadString(S, sizeof(S))) { I = strtol(token,0,0); } -#define READVECTOR(X,N) if(!ReadVector(X, N)) { FAILURE } - -#define RV_BYTE(lab, X) if(ISLABEL(lab)) { READBYTE(X); } else -#define RV_INT(lab, X) if(ISLABEL(lab)) { READINT(X); } else -#define RV_UINT(lab, X) if(ISLABEL(lab)) { READUINT(X); } else -#define RV_FLT(lab, X) if(ISLABEL(lab)) { READFLT(X); } else -#define RV_VEC(lab, X, N) if(ISLABEL(lab)) { int b; FINDBEGIN; \ - for(b=0; b= MAX_RECUR_DEPTH) + if (source && source - sourceStack >= MAX_RECUR_DEPTH) { App_FatalError("DED_InitReader: Include recursion is too deep.\n"); } - if(!source) + if (!source) { // This'll be the first source. source = sourceStack; @@ -222,7 +222,7 @@ DENG2_PIMPL(DEDParser) void DED_CloseReader() { - if(source == sourceStack) + if (source == sourceStack) { source = 0; } @@ -251,13 +251,13 @@ DENG2_PIMPL(DEDParser) { int ch = (unsigned char) *source->pos; - if(ch) + if (ch) source->pos++; else source->atEnd = true; - if(ch == '\n') + if (ch == '\n') source->lineNumber++; - if(ch == '\r') + if (ch == '\r') return FGetC(); return ch; @@ -268,11 +268,11 @@ DENG2_PIMPL(DEDParser) */ int FUngetC(int ch) { - if(source->atEnd) + if (source->atEnd) return 0; - if(ch == '\n') + if (ch == '\n') source->lineNumber--; - if(source->pos > source->buffer) + if (source->pos > source->buffer) source->pos--; return ch; @@ -286,26 +286,26 @@ DENG2_PIMPL(DEDParser) int ch = FGetC(); dd_bool seq = false; - if(ch == '\n') + if (ch == '\n') return; // Comment ends right away. - if(ch != '>') // Single-line comment? + if (ch != '>') // Single-line comment? { - while(FGetC() != '\n' && !source->atEnd) {} + while (FGetC() != '\n' && !source->atEnd) {} } else // Multiline comment? { - while(!source->atEnd) + while (!source->atEnd) { ch = FGetC(); - if(seq) + if (seq) { - if(ch == '#') + if (ch == '#') break; seq = false; } - if(ch == '<') + if (ch == '<') seq = true; } } @@ -317,7 +317,7 @@ DENG2_PIMPL(DEDParser) char* out = token; // Has a token been unread? - if(unreadToken[0]) + if (unreadToken[0]) { strcpy(token, unreadToken); strcpy(unreadToken, ""); @@ -325,29 +325,29 @@ DENG2_PIMPL(DEDParser) } ch = FGetC(); - if(source->atEnd) + if (source->atEnd) return false; // Skip whitespace and comments in the beginning. - while((ch == '#' || isspace(ch))) + while ((ch == '#' || isspace(ch))) { - if(ch == '#') + if (ch == '#') SkipComment(); ch = FGetC(); - if(source->atEnd) + if (source->atEnd) return false; } // Always store the first character. *out++ = ch; - if(STOPCHAR(ch)) + if (STOPCHAR(ch)) { // Stop here. *out = 0; return true; } - while(!STOPCHAR(ch) && !source->atEnd) + while (!STOPCHAR(ch) && !source->atEnd) { // Store the character in the buffer. ch = FGetC(); @@ -374,10 +374,10 @@ DENG2_PIMPL(DEDParser) */ int ReadString(String &dest, bool inside = false, bool doubleq = false) { - if(!inside) + if (!inside) { ReadToken(); - if(!ISTOKEN("\"")) + if (!ISTOKEN("\"")) return false; } @@ -385,15 +385,15 @@ DENG2_PIMPL(DEDParser) // Start reading the characters. int ch = FGetC(); - while(esc || ch != '"') // The string-end-character. + while (esc || ch != '"') // The string-end-character. { - if(source->atEnd) + if (source->atEnd) return false; // If a newline is found, skip all whitespace that follows. - if(newl) + if (newl) { - if(isspace(ch)) + if (isspace(ch)) { ch = FGetC(); continue; @@ -406,7 +406,7 @@ DENG2_PIMPL(DEDParser) } // An escape character? - if(!esc && ch == '\\') + if (!esc && ch == '\\') { esc = true; } @@ -414,18 +414,18 @@ DENG2_PIMPL(DEDParser) { // In case it's something other than \" or \\, just insert // the whole sequence as-is. - if(esc && ch != '"' && ch != '\\') + if (esc && ch != '"' && ch != '\\') dest += '\\'; esc = false; } - if(ch == '\n') + if (ch == '\n') newl = true; // Store the character in the buffer. - if(!esc && !newl) + if (!esc && !newl) { dest += char(ch); - if(doubleq && ch == '"') + if (doubleq && ch == '"') dest += '"'; } @@ -440,7 +440,7 @@ DENG2_PIMPL(DEDParser) { DENG_ASSERT(dest != 0); String buffer; - if(!ReadString(buffer)) return false; + if (!ReadString(buffer)) return false; qstrncpy(dest, buffer.toUtf8().constData(), maxLen); return true; } @@ -448,7 +448,7 @@ DENG2_PIMPL(DEDParser) int ReadString(Variable &var, int) { String buffer; - if(!ReadString(buffer)) return false; + if (!ReadString(buffer)) return false; var.set(TextValue(buffer)); return true; } @@ -460,11 +460,11 @@ DENG2_PIMPL(DEDParser) { String buffer; - if(!ReadString(buffer)) + if (!ReadString(buffer)) return false; // Get rid of the old string. - if(*dest) + if (*dest) M_Free(*dest); // Make a copy. @@ -479,18 +479,18 @@ DENG2_PIMPL(DEDParser) { String buffer; - if(!ReadString(buffer)) + if (!ReadString(buffer)) return false; // URIs are expected to use forward slashes. buffer = Path::normalizeString(buffer); - if(!*dest) + if (!*dest) *dest = new de::Uri(buffer, RC_NULL); else (*dest)->setUri(buffer, RC_NULL); - if(defaultScheme && defaultScheme[0] && (*dest)->scheme().isEmpty()) + if (defaultScheme && defaultScheme[0] && (*dest)->scheme().isEmpty()) (*dest)->setScheme(defaultScheme); return true; @@ -499,7 +499,7 @@ DENG2_PIMPL(DEDParser) int ReadUri(Variable &var, char const *defaultScheme) { de::Uri *uri = 0; - if(!ReadUri(&uri, defaultScheme)) return false; + if (!ReadUri(&uri, defaultScheme)) return false; var.set(TextValue(uri->compose())); delete uri; return true; @@ -508,10 +508,10 @@ DENG2_PIMPL(DEDParser) int ReadNByteVector(Variable &var, int count) { FINDBEGIN; - for(int i = 0; i < count; ++i) + for (int i = 0; i < count; ++i) { ReadToken(); - if(ISTOKEN("}")) + if (ISTOKEN("}")) return true; var.array().setElement(i, strtoul(token, 0, 0)); } @@ -525,7 +525,7 @@ DENG2_PIMPL(DEDParser) int ReadByte(unsigned char* dest) { ReadToken(); - if(ISTOKEN(";")) + if (ISTOKEN(";")) { setError("Missing integer value"); return false; @@ -541,7 +541,7 @@ DENG2_PIMPL(DEDParser) int ReadInt(int* dest, int unsign) { ReadToken(); - if(ISTOKEN(";")) + if (ISTOKEN(";")) { setError("Missing integer value"); return false; @@ -554,7 +554,7 @@ DENG2_PIMPL(DEDParser) int ReadInt(Variable *var, int unsign) { int value = 0; - if(ReadInt(&value, unsign)) + if (ReadInt(&value, unsign)) { var->set(NumberValue(value)); return true; @@ -568,7 +568,7 @@ DENG2_PIMPL(DEDParser) int ReadFloat(float* dest) { ReadToken(); - if(ISTOKEN(";")) + if (ISTOKEN(";")) { setError("Missing float value"); return false; @@ -581,7 +581,7 @@ DENG2_PIMPL(DEDParser) int ReadFloat(Variable *var) { float value = 0; - if(ReadFloat(&value)) + if (ReadFloat(&value)) { var->set(NumberValue(value)); return true; @@ -592,10 +592,10 @@ DENG2_PIMPL(DEDParser) int ReadVector(Variable &var, int componentCount) { FINDBEGIN; - for(int b = 0; b < componentCount; ++b) + for (int b = 0; b < componentCount; ++b) { float value = 0; - if(!ReadFloat(&value)) return false; + if (!ReadFloat(&value)) return false; var.array().setElement(b, value); } ReadToken(); @@ -610,12 +610,12 @@ DENG2_PIMPL(DEDParser) *dest = 0; ReadToken(); - if(ISTOKEN(";")) + if (ISTOKEN(";")) { setError("Missing flags value"); return false; } - if(ISTOKEN("0")) + if (ISTOKEN("0")) { // No flags defined. return true; @@ -623,15 +623,15 @@ DENG2_PIMPL(DEDParser) UnreadToken(token); String flag; - if(ISTOKEN("\"")) + if (ISTOKEN("\"")) { // The old format. - if(!ReadString(flag)) + if (!ReadString(flag)) return false; flag.strip(); - if(!flag.isEmpty()) + if (!flag.isEmpty()) { *dest = ded->evalFlags(flag.toUtf8().constData()); } @@ -642,7 +642,7 @@ DENG2_PIMPL(DEDParser) { // Read the flag. ReadToken(); - if(prefix) + if (prefix) { flag = String(prefix) + String(token); } @@ -653,15 +653,15 @@ DENG2_PIMPL(DEDParser) flag.strip(); - if(!flag.isEmpty()) + if (!flag.isEmpty()) { *dest |= ded->evalFlags(flag.toUtf8().constData()); } - if(!ReadToken()) + if (!ReadToken()) break; - if(!ISTOKEN("|")) // | is required for multiple flags. + if (!ISTOKEN("|")) // | is required for multiple flags. { UnreadToken(token); break; @@ -674,10 +674,10 @@ DENG2_PIMPL(DEDParser) int ReadFlags(Variable *dest, char const *prefix, int elementIndex = -1) { int value = 0; - if(ReadFlags(&value, prefix)) + if (ReadFlags(&value, prefix)) { std::unique_ptr flagsValue(new NumberValue(value, NumberValue::Hex)); - if(elementIndex < 0) + if (elementIndex < 0) { dest->set(flagsValue.release()); } @@ -699,10 +699,10 @@ DENG2_PIMPL(DEDParser) ReadToken(); UnreadToken(token); - if(ISTOKEN("\"")) + if (ISTOKEN("\"")) { // The old format. - if(!ReadString(flag)) return false; + if (!ReadString(flag)) return false; bm = blendmode_t(ded->evalFlags(flag.toUtf8().constData())); } @@ -716,7 +716,7 @@ DENG2_PIMPL(DEDParser) bm = blendmode_t(ded->evalFlags(flag.toUtf8().constData())); } - if(bm != BM_NORMAL) + if (bm != BM_NORMAL) { *dest = bm; } @@ -732,7 +732,7 @@ DENG2_PIMPL(DEDParser) int ReadBlendmode(Variable *var) { blendmode_t mode = BM_NORMAL; - if(!ReadBlendmode(&mode)) return false; + if (!ReadBlendmode(&mode)) return false; var->set(NumberValue(int(mode))); return true; } @@ -743,32 +743,32 @@ DENG2_PIMPL(DEDParser) int ReadLabel(char* label) { strcpy(label, ""); - for(;;) + for (;;) { ReadToken(); - if(source->atEnd) + if (source->atEnd) { setError("Unexpected end of file"); return false; } - if(ISTOKEN("}")) // End block. + if (ISTOKEN("}")) // End block. { strcpy(label, token); return true; } - if(ISTOKEN(";")) + if (ISTOKEN(";")) { - if(source->version <= 5) + if (source->version <= 5) { setError("Label without value"); return false; } continue; // Semicolons are optional in v6. } - if(ISTOKEN("=") || ISTOKEN("{")) + if (ISTOKEN("=") || ISTOKEN("{")) break; - if(label[0]) + if (label[0]) strcat(label, " "); strcat(label, token); } @@ -785,12 +785,12 @@ DENG2_PIMPL(DEDParser) { dd_bool value = false; - if(cond[0] == '-') + if (cond[0] == '-') { // A command line option. value = (CommandLine_Check(token) != 0); } - else if(isalnum(cond[0]) && !DoomsdayApp::game().isNull()) + else if (isalnum(cond[0]) && !DoomsdayApp::game().isNull()) { // A game mode. value = !String(cond).compareWithoutCase(DoomsdayApp::game().id()); @@ -827,37 +827,37 @@ DENG2_PIMPL(DEDParser) // For including other files -- we must know where we are. String sourceFileDir = sourceFile.fileNamePath(); - if(sourceFileDir.isEmpty()) + if (sourceFileDir.isEmpty()) { sourceFileDir = NativePath::workPath(); } - while(ReadToken()) + while (ReadToken()) { - if(ISTOKEN("Copy") || ISTOKEN("*")) + if (ISTOKEN("Copy") || ISTOKEN("*")) { bCopyNext = true; continue; // Read the next token. } - if(ISTOKEN(";")) + if (ISTOKEN(";")) { // Unnecessary semicolon? Just skip it. continue; } - if(ISTOKEN("SkipIf")) + if (ISTOKEN("SkipIf")) { dd_bool expected = true; ReadToken(); - if(ISTOKEN("Not")) + if (ISTOKEN("Not")) { expected = false; ReadToken(); } - if(DED_CheckCondition(token, expected)) + if (DED_CheckCondition(token, expected)) { // Ah, we're done. Get out of here. goto ded_end_read; @@ -865,7 +865,7 @@ DENG2_PIMPL(DEDParser) CHECKSC; } - if(ISTOKEN("Include")) + if (ISTOKEN("Include")) { // A new include. READSTR(tmp); @@ -875,18 +875,18 @@ DENG2_PIMPL(DEDParser) strcpy(label, ""); } - if(ISTOKEN("IncludeIf")) // An optional include. + if (ISTOKEN("IncludeIf")) // An optional include. { dd_bool expected = true; ReadToken(); - if(ISTOKEN("Not")) + if (ISTOKEN("Not")) { expected = false; ReadToken(); } - if(DED_CheckCondition(token, expected)) + if (DED_CheckCondition(token, expected)) { READSTR(tmp); CHECKSC; @@ -902,7 +902,7 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("ModelPath")) + if (ISTOKEN("ModelPath")) { READSTR(label); CHECKSC; @@ -912,13 +912,13 @@ DENG2_PIMPL(DEDParser) scheme.addSearchPath(reinterpret_cast(newSearchPath), FS1::ExtraPaths); } - if(ISTOKEN("Header")) + if (ISTOKEN("Header")) { FINDBEGIN; - for(;;) + for (;;) { READLABEL; - if(ISLABEL("Version")) + if (ISLABEL("Version")) { READINT(ded->version); source->version = ded->version; @@ -938,7 +938,7 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("Flag")) + if (ISTOKEN("Flag")) { ded_stringid_t id; int value = 0; @@ -957,29 +957,29 @@ DENG2_PIMPL(DEDParser) CHECKSC; } - if(qstrlen(id)) + if (qstrlen(id)) { ded->addFlag(id, value); Record &flag = ded->flags.find("id", id); DENG2_ASSERT(flag.geti("value") == value); // Sanity check. - if(source->custom) flag.set("custom", true); + if (source->custom) flag.set("custom", true); } } - if(ISTOKEN("Episode")) + if (ISTOKEN("Episode")) { bool bModify = false; Record dummyEpsd; Record *epsd = 0; ReadToken(); - if(!ISTOKEN("Mods")) + if (!ISTOKEN("Mods")) { // New episodes are appended to the end of the list. idx = ded->addEpisode(); epsd = &ded->episodes[idx]; } - else if(!bCopyNext) + else if (!bCopyNext) { ded_stringid_t otherEpisodeId; @@ -987,7 +987,7 @@ DENG2_PIMPL(DEDParser) ReadToken(); idx = ded->getEpisodeNum(otherEpisodeId); - if(idx >= 0) + if (idx >= 0) { epsd = &ded->episodes[idx]; bModify = true; @@ -1011,11 +1011,11 @@ DENG2_PIMPL(DEDParser) } DENG2_ASSERT(epsd != 0); - if(prevEpisodeDefIdx >= 0 && bCopyNext) + if (prevEpisodeDefIdx >= 0 && bCopyNext) { ded->episodes.copy(prevEpisodeDefIdx, *epsd); } - if(source->custom) epsd->set("custom", true); + if (source->custom) epsd->set("custom", true); defn::Episode mainDef(*epsd); int hub = 0; @@ -1025,7 +1025,7 @@ DENG2_PIMPL(DEDParser) { READLABEL; // ID cannot be changed when modifying - if(!bModify && ISLABEL("ID")) + if (!bModify && ISLABEL("ID")) { READSTR((*epsd)["id"]); } @@ -1034,17 +1034,17 @@ DENG2_PIMPL(DEDParser) RV_STR("Menu Help Info", (*epsd)["menuHelpInfo"]) RV_URI("Menu Image", (*epsd)["menuImage"], "Patches") RV_STR("Menu Shortcut", (*epsd)["menuShortcut"]) - if(ISLABEL("Hub")) + if (ISLABEL("Hub")) { Record *hubRec; // Add another hub. - if(hub >= mainDef.hubCount()) + if (hub >= mainDef.hubCount()) { mainDef.addHub(); } DENG_ASSERT(hub < mainDef.hubCount()); hubRec = &mainDef.hub(hub); - if(source->custom) hubRec->set("custom", true); + if (source->custom) hubRec->set("custom", true); int map = 0; FINDBEGIN; @@ -1052,10 +1052,10 @@ DENG2_PIMPL(DEDParser) { READLABEL; RV_STR("ID", (*hubRec)["id"]) - if(ISLABEL("Map")) + if (ISLABEL("Map")) { // Add another map. - if(map >= int(hubRec->geta("map").size())) + if (map >= int(hubRec->geta("map").size())) { QScopedPointer map(new Record); defn::MapGraphNode(*map).resetToDefaults(); @@ -1064,7 +1064,7 @@ DENG2_PIMPL(DEDParser) } DENG_ASSERT(map < int(hubRec->geta("map").size())); Record &mapRec = *hubRec->geta("map")[map].as().record(); - if(source->custom) mapRec.set("custom", true); + if (source->custom) mapRec.set("custom", true); int exit = 0; FINDBEGIN; @@ -1073,18 +1073,18 @@ DENG2_PIMPL(DEDParser) READLABEL; RV_URI("ID", mapRec["id"], "Maps") RV_INT("Warp Number", mapRec["warpNumber"]) - if(ISLABEL("Exit")) + if (ISLABEL("Exit")) { defn::MapGraphNode mgNodeDef(mapRec); // Add another exit. - if(exit >= mgNodeDef.exitCount()) + if (exit >= mgNodeDef.exitCount()) { mgNodeDef.addExit(); } DENG_ASSERT(exit < mgNodeDef.exitCount()); Record &exitRec = mgNodeDef.exit(exit); - if(source->custom) exitRec.set("custom", true); + if (source->custom) exitRec.set("custom", true); FINDBEGIN; forever @@ -1107,10 +1107,10 @@ DENG2_PIMPL(DEDParser) } hub++; } - else if(ISLABEL("Map")) + else if (ISLABEL("Map")) { // Add another none-hub map. - if(notHubMap >= int(epsd->geta("map").size())) + if (notHubMap >= int(epsd->geta("map").size())) { QScopedPointer map(new Record); defn::MapGraphNode(*map).resetToDefaults(); @@ -1119,7 +1119,7 @@ DENG2_PIMPL(DEDParser) } DENG_ASSERT(notHubMap < int(epsd->geta("map").size())); Record &mapRec = *epsd->geta("map")[notHubMap].as().record(); - if(source->custom) mapRec.set("custom", true); + if (source->custom) mapRec.set("custom", true); int exit = 0; FINDBEGIN; @@ -1128,18 +1128,18 @@ DENG2_PIMPL(DEDParser) READLABEL; RV_URI("ID", mapRec["id"], "Maps") RV_INT("Warp Number", mapRec["warpNumber"]) - if(ISLABEL("Exit")) + if (ISLABEL("Exit")) { defn::MapGraphNode mgNodeDef(mapRec); // Add another exit. - if(exit >= mgNodeDef.exitCount()) + if (exit >= mgNodeDef.exitCount()) { mgNodeDef.addExit(); } DENG_ASSERT(exit < mgNodeDef.exitCount()); Record &exitRec = mgNodeDef.exit(exit); - if(source->custom) exitRec.set("custom", true); + if (source->custom) exitRec.set("custom", true); FINDBEGIN; forever @@ -1162,33 +1162,33 @@ DENG2_PIMPL(DEDParser) } // If we did not read into a dummy update the previous index. - if(idx > 0) + if (idx > 0) { prevEpisodeDefIdx = idx; } } - if(ISTOKEN("Mobj") || ISTOKEN("Thing")) + if (ISTOKEN("Mobj") || ISTOKEN("Thing")) { dd_bool bModify = false; Record* mo; Record dummyMo; ReadToken(); - if(!ISTOKEN("Mods")) + if (!ISTOKEN("Mods")) { // A new mobj type. idx = ded->addThing(""); mo = &ded->things[idx]; } - else if(!bCopyNext) + else if (!bCopyNext) { String otherMobjId; - if(!ReadString(otherMobjId)) { FAILURE } + if (!ReadString(otherMobjId)) { FAILURE } ReadToken(); idx = ded->getMobjNum(otherMobjId); - if(idx < 0) + if (idx < 0) { LOG_RES_WARNING("Ignoring unknown Mobj \"%s\" in %s on line #%i") << otherMobjId << (source? source->fileName : "?") @@ -1211,18 +1211,18 @@ DENG2_PIMPL(DEDParser) goto ded_end_read; } - if(prevMobjDefIdx >= 0 && bCopyNext) + if (prevMobjDefIdx >= 0 && bCopyNext) { // Should we copy the previous definition? ded->things.copy(prevMobjDefIdx, *mo); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; // ID cannot be changed when modifying - if(!bModify && ISLABEL("ID")) + if (!bModify && ISLABEL("ID")) { READSTR((*mo)["id"]); } @@ -1265,26 +1265,26 @@ DENG2_PIMPL(DEDParser) } // If we did not read into a dummy update the previous index. - if(idx > 0) + if (idx > 0) { prevMobjDefIdx = idx; } } - if(ISTOKEN("State")) + if (ISTOKEN("State")) { dd_bool bModify = false; Record *st; Record dummyState; ReadToken(); - if(!ISTOKEN("Mods")) + if (!ISTOKEN("Mods")) { // A new state. idx = ded->addState(""); st = &ded->states[idx]; } - else if(!bCopyNext) + else if (!bCopyNext) { ded_stateid_t otherStateId; @@ -1292,7 +1292,7 @@ DENG2_PIMPL(DEDParser) ReadToken(); idx = ded->getStateNum(otherStateId); - if(idx < 0) + if (idx < 0) { LOG_RES_WARNING("Ignoring unknown State \"%s\" in %s on line #%i") << otherStateId << (source? source->fileName : "?") @@ -1315,22 +1315,22 @@ DENG2_PIMPL(DEDParser) goto ded_end_read; } - if(prevStateDefIdx >= 0 && bCopyNext) + if (prevStateDefIdx >= 0 && bCopyNext) { // Should we copy the previous definition? ded->states.copy(prevStateDefIdx, *st); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; // ID cannot be changed when modifying - if(!bModify && ISLABEL("ID")) + if (!bModify && ISLABEL("ID")) { READSTR((*st)["id"]); } - else if(ISLABEL("Frame")) + else if (ISLABEL("Frame")) { // Legacy state frame flags: #define FF_FULLBRIGHT 0x8000 @@ -1338,7 +1338,7 @@ DENG2_PIMPL(DEDParser) int frame = 0; READINT(frame); - if(frame & FF_FULLBRIGHT) + if (frame & FF_FULLBRIGHT) { frame &= FF_FRAMEMASK; st->set("flags", st->geti("flags") | STF_FULLBRIGHT); @@ -1362,18 +1362,18 @@ DENG2_PIMPL(DEDParser) } // If we did not read into a dummy update the previous index. - if(idx > 0) + if (idx > 0) { prevStateDefIdx = idx; } } - if(ISTOKEN("Sprite")) + if (ISTOKEN("Sprite")) { // A new sprite. idx = DED_AddSprite(ded, ""); FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_STR("ID", ded->sprites[idx].id) @@ -1382,7 +1382,7 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("Light")) + if (ISTOKEN("Light")) { ded_light_t* lig; @@ -1391,13 +1391,13 @@ DENG2_PIMPL(DEDParser) lig = &ded->lights[idx]; // Should we copy the previous definition? - if(prevLightDefIdx >= 0 && bCopyNext) + if (prevLightDefIdx >= 0 && bCopyNext) { ded->lights.copyTo(lig, prevLightDefIdx); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_STR("State", lig->state) @@ -1411,17 +1411,17 @@ DENG2_PIMPL(DEDParser) RV_FLT("Green", lig->color[1]) RV_FLT("Blue", lig->color[2]) RV_VEC("Color", lig->color, 3) - if(ISLABEL("Sector levels")) + if (ISLABEL("Sector levels")) { int b; FINDBEGIN; - for(b = 0; b < 2; ++b) + for (b = 0; b < 2; ++b) { READFLT(lig->lightLevel[b]) lig->lightLevel[b] /= 255.0f; - if(lig->lightLevel[b] < 0) + if (lig->lightLevel[b] < 0) lig->lightLevel[b] = 0; - else if(lig->lightLevel[b] > 1) + else if (lig->lightLevel[b] > 1) lig->lightLevel[b] = 1; } ReadToken(); @@ -1439,27 +1439,27 @@ DENG2_PIMPL(DEDParser) prevLightDefIdx = idx; } - if(ISTOKEN("Material")) + if (ISTOKEN("Material")) { Record dummyMat; Record *mat = nullptr; bool bModify = false; ReadToken(); - if(!ISTOKEN("Mods")) + if (!ISTOKEN("Mods")) { // New materials are appended to the end of the list. idx = ded->addMaterial(); mat = &ded->materials[idx]; } - else if(!bCopyNext) + else if (!bCopyNext) { de::Uri *otherMat = nullptr; READURI(&otherMat, nullptr); ReadToken(); idx = ded->getMaterialNum(*otherMat); - if(idx >= 0) + if (idx >= 0) { mat = &ded->materials[idx]; bModify = true; @@ -1487,7 +1487,7 @@ DENG2_PIMPL(DEDParser) DENG2_ASSERT(mat); // Should we copy the previous definition? - if(prevMaterialDefIdx >= 0 && bCopyNext) + if (prevMaterialDefIdx >= 0 && bCopyNext) { ded->materials.copy(prevMaterialDefIdx, *mat); } @@ -1500,7 +1500,7 @@ DENG2_PIMPL(DEDParser) { READLABEL; // ID cannot be changed when modifying - if(!bModify && ISLABEL("ID")) + if (!bModify && ISLABEL("ID")) { READURI((*mat)["id"], nullptr); } @@ -1508,9 +1508,9 @@ DENG2_PIMPL(DEDParser) RV_FLAGS("Flags", (*mat)["flags"], "matf_") RV_INT_ELEM("Width", (*mat)["dimensions"], 0) RV_INT_ELEM("Height", (*mat)["dimensions"], 1) - if(ISLABEL("Layer")) + if (ISLABEL("Layer")) { - if(layer >= DED_MAX_MATERIAL_LAYERS) + if (layer >= DED_MAX_MATERIAL_LAYERS) { setError("Too many Material.Layers"); retVal = false; @@ -1518,7 +1518,7 @@ DENG2_PIMPL(DEDParser) } // Add another layer. - if(layer >= mainDef.layerCount()) mainDef.addLayer(); + if (layer >= mainDef.layerCount()) mainDef.addLayer(); defn::MaterialLayer layerDef(mainDef.layer(layer)); int stage = 0; @@ -1526,14 +1526,14 @@ DENG2_PIMPL(DEDParser) forever { READLABEL; - if(ISLABEL("Stage")) + if (ISLABEL("Stage")) { // Need to allocate a new stage? - if(stage >= layerDef.stageCount()) + if (stage >= layerDef.stageCount()) { layerDef.addStage(); - if(mainDef.getb("autoGenerated") && stage > 0) + if (mainDef.getb("autoGenerated") && stage > 0) { // When adding a new stage to an autogenerated material // initialize by copying values from the previous stage. @@ -1562,9 +1562,9 @@ DENG2_PIMPL(DEDParser) } layer++; } - else if(ISLABEL("Light")) + else if (ISLABEL("Light")) { - if(decor >= DED_MAX_MATERIAL_DECORATIONS) + if (decor >= DED_MAX_MATERIAL_DECORATIONS) { setError("Too many Material.Lights"); retVal = false; @@ -1572,7 +1572,7 @@ DENG2_PIMPL(DEDParser) } // Add another decoration. - if(decor >= mainDef.decorationCount()) mainDef.addDecoration(); + if (decor >= mainDef.decorationCount()) mainDef.addDecoration(); defn::MaterialDecoration decorDef(mainDef.decoration(decor)); int stage = 0; @@ -1582,10 +1582,10 @@ DENG2_PIMPL(DEDParser) READLABEL; RV_VEC_VAR("Pattern offset", decorDef.def()["patternOffset"], 2) RV_VEC_VAR("Pattern skip", decorDef.def()["patternSkip"], 2) - if(ISLABEL("Stage")) + if (ISLABEL("Stage")) { // Need to allocate a new stage? - if(stage >= decorDef.stageCount()) + if (stage >= decorDef.stageCount()) { decorDef.addStage(); } @@ -1602,11 +1602,11 @@ DENG2_PIMPL(DEDParser) RV_VEC_VAR("Color", st["color"], 3) RV_FLT("Radius", st["radius"]) RV_FLT("Halo radius", st["haloRadius"]) - if(ISLABEL("Levels")) + if (ISLABEL("Levels")) { FINDBEGIN; Vector2f levels; - for(int b = 0; b < 2; ++b) + for (int b = 0; b < 2; ++b) { float val; READFLT(val) @@ -1636,13 +1636,13 @@ DENG2_PIMPL(DEDParser) } // If we did not read into a dummy update the previous index. - if(idx > 0) + if (idx > 0) { prevMaterialDefIdx = idx; } } - if(ISTOKEN("Model")) + if (ISTOKEN("Model")) { Record *prevModel = 0; int sub = 0; @@ -1651,13 +1651,13 @@ DENG2_PIMPL(DEDParser) idx = ded->addModel(); Record &mdl = ded->models[idx]; - if(prevModelDefIdx >= 0) + if (prevModelDefIdx >= 0) { prevModel = &ded->models[prevModelDefIdx]; - if(bCopyNext) ded->models.copy(prevModelDefIdx, mdl); + if (bCopyNext) ded->models.copy(prevModelDefIdx, mdl); } - if(source->custom) mdl.set("custom", true); + if (source->custom) mdl.set("custom", true); FINDBEGIN; forever @@ -1674,7 +1674,7 @@ DENG2_PIMPL(DEDParser) RV_FLT("Inter", mdl["interMark"]) RV_INT("Skin tics", mdl["skinTics"]) RV_FLT("Resize", mdl["resize"]) - if(ISLABEL("Scale")) + if (ISLABEL("Scale")) { float scale; READFLT(scale); mdl["scale"] = new ArrayValue(Vector3f(scale, scale, scale)); @@ -1685,12 +1685,12 @@ DENG2_PIMPL(DEDParser) RV_VEC_VAR("Offset XYZ", mdl["offset"], 3) RV_VEC_VAR("Interpolate", mdl["interRange"], 2) RV_FLT("Shadow radius", mdl["shadowRadius"]) - if(ISLABEL("Md2") || ISLABEL("Sub")) + if (ISLABEL("Md2") || ISLABEL("Sub")) { defn::Model mainDef(mdl); // Add another submodel. - if(sub >= mainDef.subCount()) + if (sub >= mainDef.subCount()) { mainDef.addSub(); } @@ -1699,7 +1699,7 @@ DENG2_PIMPL(DEDParser) Record &subDef = mainDef.sub(sub); FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_URI("File", subDef["filename"], "Models") @@ -1729,7 +1729,7 @@ DENG2_PIMPL(DEDParser) CHECKSC; } - if(prevModel) + if (prevModel) { defn::Model(mdl).cleanupAfterParsing(*prevModel); } @@ -1737,7 +1737,7 @@ DENG2_PIMPL(DEDParser) prevModelDefIdx = idx; } - if(ISTOKEN("Sound")) + if (ISTOKEN("Sound")) { // A new sound. ded_sound_t* snd; @@ -1745,7 +1745,7 @@ DENG2_PIMPL(DEDParser) snd = &ded->sounds[idx]; FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_STR("ID", snd->id) @@ -1766,20 +1766,20 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("Music")) + if (ISTOKEN("Music")) { bool bModify = false; Record dummyMusic; Record *music = 0; ReadToken(); - if(!ISTOKEN("Mods")) + if (!ISTOKEN("Mods")) { // New musics are appended to the end of the list. idx = ded->addMusic(); music = &ded->musics[idx]; } - else if(!bCopyNext) + else if (!bCopyNext) { ded_stringid_t otherMusicId; @@ -1787,7 +1787,7 @@ DENG2_PIMPL(DEDParser) ReadToken(); idx = ded->getMusicNum(otherMusicId); - if(idx >= 0) + if (idx >= 0) { music = &ded->musics[idx]; bModify = true; @@ -1796,7 +1796,7 @@ DENG2_PIMPL(DEDParser) { // Don't print a warning about the translated MAPINFO definitions // (see issue #2083). - if(!source || source->fileName != "[TranslatedMapInfos]") + if (!source || source->fileName != "[TranslatedMapInfos]") { LOG_RES_WARNING("Ignoring unknown Music \"%s\" in %s on line #%i") << otherMusicId << (source? source->fileName : "?") @@ -1816,18 +1816,18 @@ DENG2_PIMPL(DEDParser) } DENG2_ASSERT(music != 0); - if(prevMusicDefIdx >= 0 && bCopyNext) + if (prevMusicDefIdx >= 0 && bCopyNext) { ded->musics.copy(prevMusicDefIdx, *music); } - if(source->custom) music->set("custom", true); + if (source->custom) music->set("custom", true); FINDBEGIN; forever { READLABEL; // ID cannot be changed when modifying - if(!bModify && ISLABEL("ID")) + if (!bModify && ISLABEL("ID")) { READSTR((*music)["id"]); } @@ -1842,13 +1842,13 @@ DENG2_PIMPL(DEDParser) } // If we did not read into a dummy update the previous index. - if(idx > 0) + if (idx > 0) { prevMusicDefIdx = idx; } } - if(ISTOKEN("Sky")) + if (ISTOKEN("Sky")) { int model = 0; @@ -1856,12 +1856,12 @@ DENG2_PIMPL(DEDParser) idx = ded->addSky(); Record &sky = ded->skies[idx]; - if(prevSkyDefIdx >= 0 && bCopyNext) + if (prevSkyDefIdx >= 0 && bCopyNext) { //Record *prevSky = &ded->skies[prevSkyDefIdx]; ded->skies.copy(prevSkyDefIdx, sky); } - if(source->custom) sky.set("custom", true); + if (source->custom) sky.set("custom", true); FINDBEGIN; forever @@ -1872,11 +1872,11 @@ DENG2_PIMPL(DEDParser) RV_FLT("Height", sky["height"]) RV_FLT("Horizon offset", sky["horizonOffset"]) RV_VEC_VAR("Light color", sky["color"], 3) - if(ISLABEL("Layer 1") || ISLABEL("Layer 2")) + if (ISLABEL("Layer 1") || ISLABEL("Layer 2")) { defn::Sky mainDef(sky); Record &layerDef = mainDef.layer(atoi(label+6) - 1); - if(source->custom) layerDef.set("custom", true); + if (source->custom) layerDef.set("custom", true); FINDBEGIN; forever @@ -1892,11 +1892,11 @@ DENG2_PIMPL(DEDParser) CHECKSC; } } - else if(ISLABEL("Model")) + else if (ISLABEL("Model")) { defn::Sky mainDef(sky); - if(model == 32/*MAX_SKY_MODELS*/) + if (model == 32/*MAX_SKY_MODELS*/) { // Too many! setError("Too many Sky models"); @@ -1905,14 +1905,14 @@ DENG2_PIMPL(DEDParser) } // Add another model. - if(model >= mainDef.modelCount()) + if (model >= mainDef.modelCount()) { mainDef.addModel(); } DENG_ASSERT(model < mainDef.modelCount()); Record &mdlDef = mainDef.model(model); - if(source->custom) mdlDef.set("custom", true); + if (source->custom) mdlDef.set("custom", true); FINDBEGIN; forever @@ -1939,10 +1939,10 @@ DENG2_PIMPL(DEDParser) prevSkyDefIdx = idx; } - if(ISTOKEN("Map")) // Info + if (ISTOKEN("Map")) // Info { ReadToken(); - if(!ISTOKEN("Info")) + if (!ISTOKEN("Info")) { setError("Unknown token 'Map" + String(token) + "'"); retVal = false; @@ -1955,20 +1955,20 @@ DENG2_PIMPL(DEDParser) int model = 0; ReadToken(); - if(!ISTOKEN("Mods")) + if (!ISTOKEN("Mods")) { // New mapinfos are appended to the end of the list. idx = ded->addMapInfo(); mi = &ded->mapInfos[idx]; } - else if(!bCopyNext) + else if (!bCopyNext) { de::Uri *otherMap = nullptr; READURI(&otherMap, "Maps"); ReadToken(); idx = ded->getMapInfoNum(*otherMap); - if(idx >= 0) + if (idx >= 0) { mi = &ded->mapInfos[idx]; bModify = true; @@ -1982,25 +1982,25 @@ DENG2_PIMPL(DEDParser) } delete otherMap; - if(mi && ISTOKEN("if")) + if (mi && ISTOKEN("if")) { bool negate = false; bool testCustom = false; forever { ReadToken(); - if(ISTOKEN("{")) + if (ISTOKEN("{")) { break; } - if(!testCustom) + if (!testCustom) { - if(ISTOKEN("not")) + if (ISTOKEN("not")) { negate = !negate; } - else if(ISTOKEN("custom")) + else if (ISTOKEN("custom")) { testCustom = true; } @@ -2009,9 +2009,9 @@ DENG2_PIMPL(DEDParser) else RV_END } - if(testCustom) + if (testCustom) { - if(mi->getb("custom") != !negate) + if (mi->getb("custom") != !negate) { mi = nullptr; // skip } @@ -2024,7 +2024,7 @@ DENG2_PIMPL(DEDParser) } } - if(!mi) + if (!mi) { // We'll read into a dummy definition. defn::MapInfo(dummyMi).resetToDefaults(); @@ -2039,22 +2039,22 @@ DENG2_PIMPL(DEDParser) } DENG2_ASSERT(mi != 0); - if(prevMapInfoDefIdx >= 0 && bCopyNext) + if (prevMapInfoDefIdx >= 0 && bCopyNext) { // Record *prevMapInfo = &ded->mapInfos[prevMapInfoDefIdx]; ded->mapInfos.copy(prevMapInfoDefIdx, *mi); } - if(source->custom) mi->set("custom", true); + if (source->custom) mi->set("custom", true); Record &sky = mi->subrecord("sky"); - if(source->custom) sky.set("custom", true); + if (source->custom) sky.set("custom", true); FINDBEGIN; forever { READLABEL; // ID cannot be changed when modifying - if(!bModify && ISLABEL("ID")) + if (!bModify && ISLABEL("ID")) { READURI((*mi)["id"], "Maps"); } @@ -2079,11 +2079,11 @@ DENG2_PIMPL(DEDParser) RV_FLT("Sky height", sky["height"]) RV_FLT("Horizon offset", sky["horizonOffset"]) RV_VEC_VAR("Sky light color", sky["color"], 3) - if(ISLABEL("Sky Layer 1") || ISLABEL("Sky Layer 2")) + if (ISLABEL("Sky Layer 1") || ISLABEL("Sky Layer 2")) { defn::Sky skyDef(sky); Record &layerDef = skyDef.layer(atoi(label+10) - 1); - if(source->custom) layerDef.set("custom", true); + if (source->custom) layerDef.set("custom", true); FINDBEGIN; forever @@ -2099,11 +2099,11 @@ DENG2_PIMPL(DEDParser) CHECKSC; } } - else if(ISLABEL("Sky Model")) + else if (ISLABEL("Sky Model")) { defn::Sky skyDef(sky); - if(model == 32/*MAX_SKY_MODELS*/) + if (model == 32/*MAX_SKY_MODELS*/) { // Too many! setError("Too many Sky models"); @@ -2112,14 +2112,14 @@ DENG2_PIMPL(DEDParser) } // Add another model. - if(model >= skyDef.modelCount()) + if (model >= skyDef.modelCount()) { skyDef.addModel(); } DENG_ASSERT(model < skyDef.modelCount()); Record &mdlDef = skyDef.model(model); - if(source->custom) mdlDef.set("custom", true); + if (source->custom) mdlDef.set("custom", true); FINDBEGIN; forever @@ -2144,27 +2144,27 @@ DENG2_PIMPL(DEDParser) } // If we did not read into a dummy update the previous index. - if(idx > 0) + if (idx > 0) { prevMapInfoDefIdx = idx; } } - if(ISTOKEN("Text")) + if (ISTOKEN("Text")) { // A new text. idx = DED_AddText(ded, ""); ded_text_t *txt = &ded->text[idx]; FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_STR("ID", txt->id) - if(ISLABEL("Text")) + if (ISLABEL("Text")) { String buffer; - if(ReadString(buffer)) + if (ReadString(buffer)) { QByteArray bufferUtf8 = buffer.toUtf8(); txt->text = (char *) M_Realloc(txt->text, bufferUtf8.length() + 1); @@ -2182,10 +2182,10 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("Texture")) + if (ISTOKEN("Texture")) { ReadToken(); - if(ISTOKEN("Environment")) + if (ISTOKEN("Environment")) { // A new environment. ded_tenviron_t* tenv; @@ -2193,20 +2193,20 @@ DENG2_PIMPL(DEDParser) tenv = &ded->textureEnv[idx]; FINDBEGIN; - for(;;) + for (;;) { ded_uri_t *mn; READLABEL; RV_STR("ID", tenv->id) - if(ISLABEL("Material") || ISLABEL("Texture") || ISLABEL("Flat")) + if (ISLABEL("Material") || ISLABEL("Texture") || ISLABEL("Flat")) { // A new material path. ddstring_t schemeName; Str_Init(&schemeName); Str_Set(&schemeName, ISLABEL("Material")? "" : ISLABEL("Texture")? "Textures" : "Flats"); mn = tenv->materials.append(); FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_URI("ID", &mn->uri, Str_Text(&schemeName)) @@ -2221,10 +2221,10 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("Composite")) + if (ISTOKEN("Composite")) { ReadToken(); - if(ISTOKEN("BitmapFont")) + if (ISTOKEN("BitmapFont")) { ded_compositefont_t* cfont; @@ -2232,39 +2232,39 @@ DENG2_PIMPL(DEDParser) cfont = &ded->compositeFonts[idx]; FINDBEGIN; - for(;;) + for (;;) { READLABEL; - if(ISLABEL("ID")) + if (ISLABEL("ID")) { READURI(&cfont->uri, "Game") CHECKSC; } - else if(M_IsStringValidInt(label)) + else if (M_IsStringValidInt(label)) { ded_compositefont_mappedcharacter_t* mc = 0; int ascii = atoi(label); - if(ascii < 0 || ascii > 255) + if (ascii < 0 || ascii > 255) { setError("Invalid ascii code"); retVal = false; goto ded_end_read; } - for(int i = 0; i < cfont->charMap.size(); ++i) + for (int i = 0; i < cfont->charMap.size(); ++i) { - if(cfont->charMap[i].ch == (unsigned char) ascii) + if (cfont->charMap[i].ch == (unsigned char) ascii) mc = &cfont->charMap[i]; } - if(mc == 0) + if (mc == 0) { mc = cfont->charMap.append(); mc->ch = ascii; } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_URI("Texture", &mc->path, "Patches") @@ -2278,29 +2278,29 @@ DENG2_PIMPL(DEDParser) } } - if(ISTOKEN("Values")) // String Values + if (ISTOKEN("Values")) // String Values { depth = 0; rootStr = (char*) M_Calloc(1); // A null string. FINDBEGIN; - for(;;) + for (;;) { // Get the next label but don't stop on }. READLABEL_NOBREAK; - if(strchr(label, '|')) + if (strchr(label, '|')) { setError("Value labels can not include '|' characters (ASCII 124)"); retVal = false; goto ded_end_read; } - if(ISTOKEN("=")) + if (ISTOKEN("=")) { // Define a new string. String buffer; - if(ReadString(buffer)) + if (ReadString(buffer)) { // Get a new value entry. idx = DED_AddValue(ded, 0); @@ -2322,7 +2322,7 @@ DENG2_PIMPL(DEDParser) goto ded_end_read; } } - else if(ISTOKEN("{")) + else if (ISTOKEN("{")) { // Begin a new group. rootStr = (char*) M_Realloc(rootStr, strlen(rootStr) + strlen(label) + 2); @@ -2332,12 +2332,12 @@ DENG2_PIMPL(DEDParser) depth++; continue; } - else if(ISTOKEN("}")) + else if (ISTOKEN("}")) { size_t len; // End group. - if(!depth) + if (!depth) break; // End root depth. // Decrease level and modify rootStr. @@ -2345,7 +2345,7 @@ DENG2_PIMPL(DEDParser) len = strlen(rootStr); rootStr[len-1] = 0; // Remove last |. ptr = strrchr(rootStr, '|'); - if(ptr) + if (ptr) { ptr[1] = 0; rootStr = (char*) M_Realloc(rootStr, strlen(rootStr) + 1); @@ -2370,39 +2370,39 @@ DENG2_PIMPL(DEDParser) rootStr = 0; } - if(ISTOKEN("Detail")) // Detail Texture + if (ISTOKEN("Detail")) // Detail Texture { idx = DED_AddDetail(ded, ""); ded_detailtexture_t *dtl = &ded->details[idx]; // Should we copy the previous definition? - if(prevDetailDefIdx >= 0 && bCopyNext) + if (prevDetailDefIdx >= 0 && bCopyNext) { ded->details.copyTo(dtl, prevDetailDefIdx); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_FLAGS("Flags", dtl->flags, "dtf_") - if(ISLABEL("Texture")) + if (ISLABEL("Texture")) { READURI(&dtl->material1, "Textures") } - else if(ISLABEL("Wall")) // Alias + else if (ISLABEL("Wall")) // Alias { READURI(&dtl->material1, "Textures") } - else if(ISLABEL("Flat")) + else if (ISLABEL("Flat")) { READURI(&dtl->material2, "Flats") } - else if(ISLABEL("Lump")) + else if (ISLABEL("Lump")) { READURI(&dtl->stage.texture, "Lumps") } - else if(ISLABEL("File")) + else if (ISLABEL("File")) { READURI(&dtl->stage.texture, 0) } @@ -2416,7 +2416,7 @@ DENG2_PIMPL(DEDParser) prevDetailDefIdx = idx; } - if(ISTOKEN("Reflection")) // Surface reflection + if (ISTOKEN("Reflection")) // Surface reflection { ded_reflection_t* ref = 0; @@ -2424,13 +2424,13 @@ DENG2_PIMPL(DEDParser) ref = &ded->reflections[idx]; // Should we copy the previous definition? - if(prevRefDefIdx >= 0 && bCopyNext) + if (prevRefDefIdx >= 0 && bCopyNext) { ded->reflections.copyTo(ref, prevRefDefIdx); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_FLAGS("Flags", ref->flags, "rff_") @@ -2441,15 +2441,15 @@ DENG2_PIMPL(DEDParser) RV_URI("Mask map", &ref->stage.maskTexture, "LightMaps") RV_FLT("Mask width", ref->stage.maskWidth) RV_FLT("Mask height", ref->stage.maskHeight) - if(ISLABEL("Material")) + if (ISLABEL("Material")) { READURI(&ref->material, 0) } - else if(ISLABEL("Texture")) + else if (ISLABEL("Texture")) { READURI(&ref->material, "Textures") } - else if(ISLABEL("Flat")) + else if (ISLABEL("Flat")) { READURI(&ref->material, "Flats") } @@ -2459,7 +2459,7 @@ DENG2_PIMPL(DEDParser) prevRefDefIdx = idx; } - if(ISTOKEN("Generator")) // Particle Generator + if (ISTOKEN("Generator")) // Particle Generator { ded_ptcgen_t* gen; int sub = 0; @@ -2468,25 +2468,25 @@ DENG2_PIMPL(DEDParser) gen = &ded->ptcGens[idx]; // Should we copy the previous definition? - if(prevGenDefIdx >= 0 && bCopyNext) + if (prevGenDefIdx >= 0 && bCopyNext) { ded->ptcGens.copyTo(gen, prevGenDefIdx); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_STR("State", gen->state) - if(ISLABEL("Material")) + if (ISLABEL("Material")) { READURI(&gen->material, 0) } - else if(ISLABEL("Flat")) + else if (ISLABEL("Flat")) { READURI(&gen->material, "Flats") } - else if(ISLABEL("Texture")) + else if (ISLABEL("Texture")) { READURI(&gen->material, "Textures") } @@ -2518,11 +2518,11 @@ DENG2_PIMPL(DEDParser) RV_FLT("Force radius", gen->forceRadius) RV_FLT("Force", gen->force) RV_VEC("Force origin", gen->forceOrigin, 3) - if(ISLABEL("Stage")) + if (ISLABEL("Stage")) { ded_ptcstage_t *st = NULL; - if(sub >= gen->stages.size()) + if (sub >= gen->stages.size()) { // Allocate new stage. sub = DED_AddPtcGenStage(gen); @@ -2531,7 +2531,7 @@ DENG2_PIMPL(DEDParser) st = &gen->stages[sub]; FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_FLAGS("Type", st->type, "pt_") @@ -2564,12 +2564,12 @@ DENG2_PIMPL(DEDParser) prevGenDefIdx = idx; } - if(ISTOKEN("Finale") || ISTOKEN("InFine")) + if (ISTOKEN("Finale") || ISTOKEN("InFine")) { // New finales are appended to the end of the list. idx = ded->addFinale(); Record &fin = ded->finales[idx]; - if(source->custom) fin.set("custom", true); + if (source->custom) fin.set("custom", true); FINDBEGIN; forever @@ -2579,19 +2579,19 @@ DENG2_PIMPL(DEDParser) RV_URI("Before", fin["before"], "Maps") RV_URI("After", fin["after"], "Maps") RV_INT("Game", dummyInt) - if(ISLABEL("Script")) + if (ISLABEL("Script")) { String buffer; buffer.reserve(1600); FINDBEGIN; ReadToken(); - while(!ISTOKEN("}") && !source->atEnd) + while (!ISTOKEN("}") && !source->atEnd) { - if(!buffer.isEmpty()) + if (!buffer.isEmpty()) buffer += ' '; buffer += String(token); - if(ISTOKEN("\"")) + if (ISTOKEN("\"")) { ReadString(buffer, true, true); buffer += '"'; @@ -2607,13 +2607,13 @@ DENG2_PIMPL(DEDParser) } // An oldschool (light) decoration definition? - if(ISTOKEN("Decoration")) + if (ISTOKEN("Decoration")) { idx = ded->addDecoration(); Record &decor = ded->decorations[idx]; // Should we copy the previous definition? - if(prevDecorDefIdx >= 0 && bCopyNext) + if (prevDecorDefIdx >= 0 && bCopyNext) { ded->decorations.copy(prevDecorDefIdx, decor); } @@ -2625,21 +2625,21 @@ DENG2_PIMPL(DEDParser) { READLABEL; RV_FLAGS("Flags", decor["flags"], "dcf_") - if(ISLABEL("Material")) + if (ISLABEL("Material")) { READURI(decor["texture"], 0) } - else if(ISLABEL("Texture")) + else if (ISLABEL("Texture")) { READURI(decor["texture"], "Textures") } - else if(ISLABEL("Flat")) + else if (ISLABEL("Flat")) { READURI(decor["texture"], "Flats") } - else if(ISLABEL("Light")) + else if (ISLABEL("Light")) { - if(light == DED_MAX_MATERIAL_DECORATIONS) + if (light == DED_MAX_MATERIAL_DECORATIONS) { setError("Too many Decoration.Lights"); retVal = false; @@ -2647,7 +2647,7 @@ DENG2_PIMPL(DEDParser) } // Add another light. - if(light >= mainDef.lightCount()) mainDef.addLight(); + if (light >= mainDef.lightCount()) mainDef.addLight(); defn::MaterialDecoration lightDef(mainDef.light(light)); // One implicit stage. @@ -2663,11 +2663,11 @@ DENG2_PIMPL(DEDParser) RV_FLT("Halo radius", st["haloRadius"]) RV_VEC_VAR("Pattern offset", lightDef.def()["patternOffset"], 2) RV_VEC_VAR("Pattern skip", lightDef.def()["patternSkip"], 2) - if(ISLABEL("Levels")) + if (ISLABEL("Levels")) { FINDBEGIN; Vector2f levels; - for(int b = 0; b < 2; ++b) + for (int b = 0; b < 2; ++b) { float val; READFLT(val) @@ -2693,7 +2693,7 @@ DENG2_PIMPL(DEDParser) prevDecorDefIdx = idx; } - if(ISTOKEN("Group")) + if (ISTOKEN("Group")) { idx = DED_AddGroup(ded); ded_group_t *grp = &ded->groups[idx]; @@ -2703,12 +2703,12 @@ DENG2_PIMPL(DEDParser) forever { READLABEL; - if(ISLABEL("Texture") || ISLABEL("Flat")) + if (ISLABEL("Texture") || ISLABEL("Flat")) { bool const haveTexture = ISLABEL("Texture"); // Need to allocate new stage? - if(sub >= grp->members.size()) + if (sub >= grp->members.size()) { sub = DED_AddGroupMember(grp); } @@ -2719,10 +2719,10 @@ DENG2_PIMPL(DEDParser) { READLABEL; RV_URI("ID", &memb->material, (haveTexture? "Textures" : "Flats")) - if(ISLABEL("Tics")) + if (ISLABEL("Tics")) { READINT(memb->tics); - if(memb->tics < 0) + if (memb->tics < 0) { LOG_RES_WARNING("Invalid Group.%s.Tics: %i (< min: 0) in \"%s\" on line #%i" "\nWill ignore this Group if used for Material animation") @@ -2744,7 +2744,7 @@ DENG2_PIMPL(DEDParser) } } - /*if(ISTOKEN("XGClass")) // XG Class + /*if (ISTOKEN("XGClass")) // XG Class { // A new XG Class definition idx = DED_AddXGClass(ded); @@ -2752,16 +2752,16 @@ DENG2_PIMPL(DEDParser) sub = 0; FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_STR("ID", xgc->id) RV_STR("Name", xgc->name) - if(ISLABEL("Property")) + if (ISLABEL("Property")) { ded_xgclass_property_t *xgcp = NULL; - if(sub >= xgc->properties_count.num) + if (sub >= xgc->properties_count.num) { // Allocate new property sub = DED_AddXGClassProperty(xgc); @@ -2770,7 +2770,7 @@ DENG2_PIMPL(DEDParser) xgcp = &xgc->properties[sub]; FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_FLAGS("ID", xgcp->id, "xgcp_") @@ -2787,7 +2787,7 @@ DENG2_PIMPL(DEDParser) } }*/ - if(ISTOKEN("Line")) // Line Type + if (ISTOKEN("Line")) // Line Type { ded_linetype_t* l; @@ -2796,13 +2796,13 @@ DENG2_PIMPL(DEDParser) l = &ded->lineTypes[idx]; // Should we copy the previous definition? - if(prevLineTypeDefIdx >= 0 && bCopyNext) + if (prevLineTypeDefIdx >= 0 && bCopyNext) { ded->lineTypes.copyTo(l, prevLineTypeDefIdx); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_INT("ID", l->id) @@ -2844,19 +2844,19 @@ DENG2_PIMPL(DEDParser) RV_INT("Act chain", l->actChain) RV_INT("Deact chain", l->deactChain) RV_FLAGS("Wall section", l->wallSection, "lws_") - if(ISLABEL("Act material")) + if (ISLABEL("Act material")) { READURI(&l->actMaterial, 0) } - else if(ISLABEL("Act texture")) // Alias + else if (ISLABEL("Act texture")) // Alias { READURI(&l->actMaterial, "Textures") } - else if(ISLABEL("Deact material")) + else if (ISLABEL("Deact material")) { READURI(&l->deactMaterial, 0) } - else if(ISLABEL("Deact texture")) // Alias + else if (ISLABEL("Deact texture")) // Alias { READURI(&l->deactMaterial, "Textures") } @@ -2914,19 +2914,19 @@ DENG2_PIMPL(DEDParser) RV_STR("Sp2", l->sparm[2]) RV_STR("Sp3", l->sparm[3]) RV_STR("Sp4", l->sparm[4]) - if(l->lineClass) + if (l->lineClass) { // IpX Alt names can only be used if the class is defined first! // they also support the DED v6 flags format. int i; - for(i = 0; i < 20; ++i) + for (i = 0; i < 20; ++i) { xgclassparm_t const& iParm = xgClassLinks[l->lineClass].iparm[i]; - if(!iParm.name[0]) continue; - if(!ISLABEL(iParm.name)) continue; + if (!iParm.name[0]) continue; + if (!ISLABEL(iParm.name)) continue; - if(iParm.flagPrefix[0]) + if (iParm.flagPrefix[0]) { READFLAGS(l->iparm[i], iParm.flagPrefix) } @@ -2937,7 +2937,7 @@ DENG2_PIMPL(DEDParser) break; } // Not a known label? - if(i == 20) RV_END + if (i == 20) RV_END } else RV_END @@ -2946,7 +2946,7 @@ DENG2_PIMPL(DEDParser) prevLineTypeDefIdx = idx; } - if(ISTOKEN("Sector")) // Sector Type + if (ISTOKEN("Sector")) // Sector Type { ded_sectortype_t* sec; @@ -2954,14 +2954,14 @@ DENG2_PIMPL(DEDParser) idx = DED_AddSectorType(ded, 0); sec = &ded->sectorTypes[idx]; - if(prevSectorTypeDefIdx >= 0 && bCopyNext) + if (prevSectorTypeDefIdx >= 0 && bCopyNext) { // Should we copy the previous definition? ded->sectorTypes.copyTo(sec, prevSectorTypeDefIdx); } FINDBEGIN; - for(;;) + for (;;) { READLABEL; RV_INT("ID", sec->id) @@ -3058,7 +3058,7 @@ DENG2_PIMPL(DEDParser) Str_InitStd(&tmp); Str_Set(&tmp, fileName); F_FixSlashes(&tmp, &tmp); F_ExpandBasePath(&tmp, &tmp); - if(!F_IsAbsolute(&tmp)) + if (!F_IsAbsolute(&tmp)) { Str_PrependChar(&tmp, '/'); Str_Prepend(&tmp, parentDirectory.toUtf8().constData()); diff --git a/doomsday/apps/libdoomsday/src/defs/dedregister.cpp b/doomsday/apps/libdoomsday/src/defs/dedregister.cpp index ec3aab781a..d6299381c2 100644 --- a/doomsday/apps/libdoomsday/src/defs/dedregister.cpp +++ b/doomsday/apps/libdoomsday/src/defs/dedregister.cpp @@ -55,7 +55,7 @@ DENG2_PIMPL(DEDRegister) ~Instance() { - if(names) names->audienceForDeletion() -= this; + if (names) names->audienceForDeletion() -= this; } void recordBeingDeleted(Record &DENG2_DEBUG_ONLY(record)) @@ -73,7 +73,7 @@ DENG2_PIMPL(DEDRegister) #ifdef DENG2_DEBUG DENG2_ASSERT(parents.isEmpty()); - foreach(String const &key, keys.keys()) + foreach (String const &key, keys.keys()) { DENG2_ASSERT(lookup(key).size() == 0); } @@ -113,9 +113,9 @@ DENG2_PIMPL(DEDRegister) std::function operation) const { auto foundKey = keys.constFind(key); - if(foundKey == keys.constEnd()) return 0; + if (foundKey == keys.constEnd()) return 0; - if(!foundKey.value().flags.testFlag(CaseSensitive)) + if (!foundKey.value().flags.testFlag(CaseSensitive)) { // Case insensitive lookup is done in lower case. value = value.lower(); @@ -130,7 +130,7 @@ DENG2_PIMPL(DEDRegister) [] (DictionaryValue const &lut, String v) -> Record const * { TextValue const val(v); auto i = lut.elements().find(DictionaryValue::ValueRef(&val)); - if(i == lut.elements().end()) return 0; // Value not in dictionary. + if (i == lut.elements().end()) return 0; // Value not in dictionary. return i->second->as().record(); }); } @@ -166,31 +166,31 @@ DENG2_PIMPL(DEDRegister) bool isValidKeyValue(Value const &value) const { // Empty strings are not indexable. - if(isEmptyKeyValue(value)) return false; + if (isEmptyKeyValue(value)) return false; return true; } /// Returns @c true if the value was added. bool addToLookup(String const &key, Value const &value, Record &def) { - if(!isValidKeyValue(value)) + if (!isValidKeyValue(value)) return false; String valText = value.asText(); DENG2_ASSERT(!valText.isEmpty()); DENG2_ASSERT(keys.contains(key)); - if(!keys[key].flags.testFlag(CaseSensitive)) + if (!keys[key].flags.testFlag(CaseSensitive)) { valText = valText.lower(); } DictionaryValue &dict = lookup(key); - if(keys[key].flags.testFlag(OnlyFirst)) + if (keys[key].flags.testFlag(OnlyFirst)) { // Only index the first one that is found. - if(dict.contains(TextValue(valText))) return false; + if (dict.contains(TextValue(valText))) return false; } // Index definition using its current value. @@ -202,14 +202,14 @@ DENG2_PIMPL(DEDRegister) { //qDebug() << "removeFromLookup" << key << value.asText() << &def; - if(!isValidKeyValue(value)) + if (!isValidKeyValue(value)) return false; String valText = value.asText(); DENG2_ASSERT(!valText.isEmpty()); DENG2_ASSERT(keys.contains(key)); - if(!keys[key].flags.testFlag(CaseSensitive)) + if (!keys[key].flags.testFlag(CaseSensitive)) { valText = valText.lower(); } @@ -217,12 +217,12 @@ DENG2_PIMPL(DEDRegister) DictionaryValue &dict = lookup(key); // Remove from the index. - if(dict.contains(TextValue(valText))) + if (dict.contains(TextValue(valText))) { Value const &indexed = dict.element(TextValue(valText)); //qDebug() << " -" << indexed.as().record() << &def; Record const *indexedDef = indexed.as().record(); - if(!indexedDef || indexedDef == &def) + if (!indexedDef || indexedDef == &def) { // This is the definition that was indexed using the key value. // Let's remove it. @@ -241,11 +241,11 @@ DENG2_PIMPL(DEDRegister) void recordMemberAdded(Record &def, Variable &key) { // Keys must be observed so that they are indexed in the lookup table. - if(keys.contains(key.name())) + if (keys.contains(key.name())) { // Index definition using its current value. // Observe empty keys so we'll get the key's value when it's set. - if(addToLookup(key.name(), key.value(), def) || + if (addToLookup(key.name(), key.value(), def) || isEmptyKeyValue(key.value())) { parents.insert(&key, &def); @@ -256,7 +256,7 @@ DENG2_PIMPL(DEDRegister) void recordMemberRemoved(Record &def, Variable &key) { - if(keys.contains(key.name())) + if (keys.contains(key.name())) { key.audienceForChangeFrom() -= this; parents.remove(&key); @@ -309,7 +309,7 @@ Record &DEDRegister::copy(int fromIndex, Record &to) // therefore duplicates should not occur. DENG2_FOR_EACH_CONST(Instance::Keys, i, d->keys) { - if(i.value().flags.testFlag(AllowCopy)) continue; + if (i.value().flags.testFlag(AllowCopy)) continue; omitted << i.key(); } @@ -353,12 +353,12 @@ Record &DEDRegister::find(String const &key, String const &value) Record const &DEDRegister::find(String const &key, String const &value) const { - if(!d->keys.contains(key)) + if (!d->keys.contains(key)) { throw UndefinedKeyError("DEDRegister::find", "Key '" + key + "' not defined"); } Record const *rec = tryFind(key, value); - if(!rec) + if (!rec) { throw NotFoundError("DEDRegister::find", key + " '" + value + "' not found"); } @@ -367,7 +367,7 @@ Record const &DEDRegister::find(String const &key, String const &value) const DictionaryValue const &DEDRegister::lookup(String const &key) const { - if(!d->keys.contains(key)) + if (!d->keys.contains(key)) { throw UndefinedKeyError("DEDRegister::lookup", "Key '" + key + "' not defined"); } diff --git a/doomsday/apps/libdoomsday/src/defs/definition.cpp b/doomsday/apps/libdoomsday/src/defs/definition.cpp index c723006835..a8454cbd1d 100644 --- a/doomsday/apps/libdoomsday/src/defs/definition.cpp +++ b/doomsday/apps/libdoomsday/src/defs/definition.cpp @@ -36,7 +36,7 @@ Record const &Definition::def() const int Definition::order() const { - if(!accessedRecordPtr()) return -1; + if (!accessedRecordPtr()) return -1; return geti("__order__"); } diff --git a/doomsday/apps/libdoomsday/src/defs/episode.cpp b/doomsday/apps/libdoomsday/src/defs/episode.cpp index 13cc022fc7..fa693f1556 100644 --- a/doomsday/apps/libdoomsday/src/defs/episode.cpp +++ b/doomsday/apps/libdoomsday/src/defs/episode.cpp @@ -78,15 +78,15 @@ Record const &Episode::hub(int index) const Record *Episode::tryFindHubByMapId(String const &mapId) { de::Uri const mapUri(mapId, RC_NULL); - if(!mapUri.path().isEmpty()) + if (!mapUri.path().isEmpty()) { - for(int i = 0; i < hubCount(); ++i) + for (int i = 0; i < hubCount(); ++i) { Record &hubRec = hub(i); - foreach(Value *mapIt, hubRec.geta("map").elements()) + foreach (Value *mapIt, hubRec.geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); - if(mapUri == de::Uri(mgNodeDef.gets("id"), RC_NULL)) + if (mapUri == de::Uri(mgNodeDef.gets("id"), RC_NULL)) { return &hubRec; } @@ -99,26 +99,26 @@ Record *Episode::tryFindHubByMapId(String const &mapId) Record *Episode::tryFindMapGraphNode(String const &mapId) { de::Uri const mapUri(mapId, RC_NULL); - if(!mapUri.path().isEmpty()) + if (!mapUri.path().isEmpty()) { // First, try the hub maps. - for(int i = 0; i < hubCount(); ++i) + for (int i = 0; i < hubCount(); ++i) { Record const &hubRec = hub(i); - foreach(Value *mapIt, hubRec.geta("map").elements()) + foreach (Value *mapIt, hubRec.geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); - if(mapUri == de::Uri(mgNodeDef.gets("id"), RC_NULL)) + if (mapUri == de::Uri(mgNodeDef.gets("id"), RC_NULL)) { return &mgNodeDef; } } } // Try the non-hub maps. - foreach(Value *mapIt, geta("map").elements()) + foreach (Value *mapIt, geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); - if(mapUri == de::Uri(mgNodeDef.gets("id"), RC_NULL)) + if (mapUri == de::Uri(mgNodeDef.gets("id"), RC_NULL)) { return &mgNodeDef; } @@ -129,26 +129,26 @@ Record *Episode::tryFindMapGraphNode(String const &mapId) de::Record *Episode::tryFindMapGraphNodeByWarpNumber(int warpNumber) { - if(warpNumber > 0) + if (warpNumber > 0) { // First, try the hub maps. - for(int i = 0; i < hubCount(); ++i) + for (int i = 0; i < hubCount(); ++i) { Record const &hubRec = hub(i); - foreach(Value *mapIt, hubRec.geta("map").elements()) + foreach (Value *mapIt, hubRec.geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); - if(mgNodeDef.geti("warpNumber") == warpNumber) + if (mgNodeDef.geti("warpNumber") == warpNumber) { return &mgNodeDef; } } } // Try the non-hub maps. - foreach(Value *mapIt, geta("map").elements()) + foreach (Value *mapIt, geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); - if(mgNodeDef.geti("warpNumber") == warpNumber) + if (mgNodeDef.geti("warpNumber") == warpNumber) { return &mgNodeDef; } diff --git a/doomsday/apps/libdoomsday/src/defs/model.cpp b/doomsday/apps/libdoomsday/src/defs/model.cpp index 912e657a52..edaed6fbdb 100644 --- a/doomsday/apps/libdoomsday/src/defs/model.cpp +++ b/doomsday/apps/libdoomsday/src/defs/model.cpp @@ -69,7 +69,7 @@ Record &Model::addSub() sub->addNumber("selSkinShift", 0); ArrayValue *skins = new ArrayValue; - for(int i = 0; i < 8; ++i) *skins << NumberValue(0); + for (int i = 0; i < 8; ++i) *skins << NumberValue(0); sub->addArray ("selSkins", skins); sub->addText ("shinySkin", ""); @@ -105,23 +105,23 @@ Record const &Model::sub(int index) const void Model::cleanupAfterParsing(Record const &prev) { - if(gets("state") == "-") + if (gets("state") == "-") { def().set("state", prev.gets("state")); } - if(gets("sprite") == "-") + if (gets("sprite") == "-") { def().set("sprite", prev.gets("sprite")); } - for(int i = 0; i < subCount(); ++i) + for (int i = 0; i < subCount(); ++i) { Record &subDef = sub(i); - if(subDef.gets("filename") == "-") subDef.set("filename", ""); - if(subDef.gets("skinFilename") == "-") subDef.set("skinFilename", ""); - if(subDef.gets("shinySkin") == "-") subDef.set("shinySkin", ""); - if(subDef.gets("frame") == "-") subDef.set("frame", ""); + if (subDef.gets("filename") == "-") subDef.set("filename", ""); + if (subDef.gets("skinFilename") == "-") subDef.set("skinFilename", ""); + if (subDef.gets("shinySkin") == "-") subDef.set("shinySkin", ""); + if (subDef.gets("frame") == "-") subDef.set("frame", ""); } } diff --git a/doomsday/apps/libdoomsday/src/defs/music.cpp b/doomsday/apps/libdoomsday/src/defs/music.cpp index 072fbaf925..9e55c653f6 100644 --- a/doomsday/apps/libdoomsday/src/defs/music.cpp +++ b/doomsday/apps/libdoomsday/src/defs/music.cpp @@ -39,15 +39,15 @@ void Music::resetToDefaults() dint Music::cdTrack() const { - if(dint track = geti("cdTrack")) + if (dint track = geti("cdTrack")) return track; String const path = gets("path"); - if(!path.compareWithoutCase("cd")) + if (!path.compareWithoutCase("cd")) { bool ok; dint track = path.toInt(&ok); - if(ok) return track; + if (ok) return track; } return 0; diff --git a/doomsday/apps/libdoomsday/src/defs/sprite.cpp b/doomsday/apps/libdoomsday/src/defs/sprite.cpp index 06956160f8..5ac2fe696f 100644 --- a/doomsday/apps/libdoomsday/src/defs/sprite.cpp +++ b/doomsday/apps/libdoomsday/src/defs/sprite.cpp @@ -46,7 +46,7 @@ Record &Sprite::addView(String material, dint angle, bool mirrorX) view->addText ("material", material); view->addBoolean("mirrorX", mirrorX); - if(angle <= 0) + if (angle <= 0) { def()["views"] = new ArrayValue; } @@ -64,12 +64,12 @@ dint Sprite::viewCount() const bool Sprite::hasView(dint angle) const { - if(getb("frontOnly")) angle = 0; + if (getb("frontOnly")) angle = 0; - for(Value const *val : geta("views").elements()) + for (Value const *val : geta("views").elements()) { Record const &view = val->as().dereference(); - if(view.geti("angle") == angle) + if (view.geti("angle") == angle) return true; } return false; @@ -77,12 +77,12 @@ bool Sprite::hasView(dint angle) const Record &Sprite::view(dint angle) { - if(getb("frontOnly")) angle = 0; + if (getb("frontOnly")) angle = 0; - for(Value *val : def().geta("views").elements()) + for (Value *val : def().geta("views").elements()) { Record &view = val->as().dereference(); - if(view.geti("angle") == angle) + if (view.geti("angle") == angle) return view; } /// @throw MissingViewError Invalid angle specified. @@ -93,7 +93,7 @@ Record &Sprite::nearestView(angle_t mobjAngle, angle_t angleToEye, bool noRotati { dint angle = 0; // Use the front view (default). - if(!noRotation && !def().getb("frontOnly")) + if (!noRotation && !def().getb("frontOnly")) { // Choose a view according to the relative angle with viewer (the eye). angle = ((angleToEye - mobjAngle + (unsigned) (ANG45 / 2) * 9) - (unsigned) (ANGLE_180 / 16)) >> 28; diff --git a/doomsday/apps/libdoomsday/src/doomsdayapp.cpp b/doomsday/apps/libdoomsday/src/doomsdayapp.cpp index 209c04ec9d..320c7aa293 100644 --- a/doomsday/apps/libdoomsday/src/doomsdayapp.cpp +++ b/doomsday/apps/libdoomsday/src/doomsdayapp.cpp @@ -127,9 +127,9 @@ DENG2_PIMPL(DoomsdayApp) void attachWadFeed(String const &description, NativePath const &path) { - if(!path.isEmpty()) + if (!path.isEmpty()) { - if(path.exists()) + if (path.exists()) { LOG_RES_NOTE("Using %s WAD folder: %s") << description << path.pretty(); App::rootFolder().locate(PATH_LOCAL_WADS).attach( @@ -145,9 +145,9 @@ DENG2_PIMPL(DoomsdayApp) void attachPacksFeed(String const &description, NativePath const &path) { - if(!path.isEmpty()) + if (!path.isEmpty()) { - if(path.exists()) + if (path.exists()) { LOG_RES_NOTE("Using %s package folder (including subfolders): %s") << description << path.pretty(); @@ -180,7 +180,7 @@ DENG2_PIMPL(DoomsdayApp) // Check for games installed using Steam. NativePath const steamBase = steamBasePath(); - if(steamBase.exists()) + if (steamBase.exists()) { NativePath steamPath = steamBase / "SteamApps/common/"; LOG_RES_NOTE("Detected SteamApps path: %s") << steamPath.pretty(); @@ -195,10 +195,10 @@ DENG2_PIMPL(DoomsdayApp) "DOOM 3 BFG Edition/base/wads" }; - for(auto const &appDir : appDirs) + for (auto const &appDir : appDirs) { NativePath const p = steamPath / appDir; - if(p.exists()) + if (p.exists()) { attachWadFeed("Steam", p); } @@ -207,26 +207,26 @@ DENG2_PIMPL(DoomsdayApp) #ifdef UNIX NativePath const systemWads("/usr/share/games/doom"); - if(systemWads.exists()) + if (systemWads.exists()) { attachWadFeed("system", systemWads); } #endif // Add all paths from the DOOMWADPATH environment variable. - if(getenv("DOOMWADPATH")) + if (getenv("DOOMWADPATH")) { // Interpreted similarly to the PATH variable. QStringList paths = String(getenv("DOOMWADPATH")) .split(ENV_PATH_SEP_CHAR, String::SkipEmptyParts); - while(!paths.isEmpty()) + while (!paths.isEmpty()) { attachWadFeed(_E(m) "DOOMWADPATH" _E(.), startupPath / paths.takeLast()); } } // Add the path from the DOOMWADDIR environment variable. - if(getenv("DOOMWADDIR")) + if (getenv("DOOMWADDIR")) { attachWadFeed(_E(m) "DOOMWADDIR" _E(.), startupPath / getenv("DOOMWADDIR")); } @@ -234,18 +234,18 @@ DENG2_PIMPL(DoomsdayApp) #ifdef UNIX // There may be an iwaddir specified in a system-level config file. filename_t fn; - if(UnixInfo_GetConfigValue("paths", "iwaddir", fn, FILENAME_T_MAXLEN)) + if (UnixInfo_GetConfigValue("paths", "iwaddir", fn, FILENAME_T_MAXLEN)) { attachWadFeed("UnixInfo " _E(i) "paths.iwaddir" _E(.), startupPath / fn); } #endif // Command line paths. - if(auto arg = cmdLine.check("-iwad", 1)) // has at least one parameter + if (auto arg = cmdLine.check("-iwad", 1)) // has at least one parameter { - for(dint p = arg.pos + 1; p < cmdLine.count(); ++p) + for (dint p = arg.pos + 1; p < cmdLine.count(); ++p) { - if(cmdLine.isOption(p)) break; + if (cmdLine.isOption(p)) break; cmdLine.makeAbsolutePath(p); attachWadFeed("command-line", cmdLine.at(p)); @@ -269,7 +269,7 @@ DENG2_PIMPL(DoomsdayApp) #ifdef UNIX // There may be an iwaddir specified in a system-level config file. filename_t fn; - if(UnixInfo_GetConfigValue("paths", "packsdir", fn, FILENAME_T_MAXLEN)) + if (UnixInfo_GetConfigValue("paths", "packsdir", fn, FILENAME_T_MAXLEN)) { attachPacksFeed("UnixInfo " _E(i) "paths.packsdir" _E(.), cmdLine.startupPath() / fn); @@ -277,11 +277,11 @@ DENG2_PIMPL(DoomsdayApp) #endif // Command line paths. - if(auto arg = cmdLine.check("-packs", 1)) + if (auto arg = cmdLine.check("-packs", 1)) { - for(dint p = arg.pos + 1; p < cmdLine.count(); ++p) + for (dint p = arg.pos + 1; p < cmdLine.count(); ++p) { - if(cmdLine.isOption(p)) break; + if (cmdLine.isOption(p)) break; cmdLine.makeAbsolutePath(p); attachPacksFeed("command-line", cmdLine.at(p)); @@ -306,7 +306,7 @@ DENG2_PIMPL(DoomsdayApp) void determineGlobalPaths() { // Use a custom base directory? - if(CommandLine_CheckWith("-basedir", 1)) + if (CommandLine_CheckWith("-basedir", 1)) { DD_SetBasePath(CommandLine_Next()); } @@ -376,7 +376,7 @@ void DoomsdayApp::initWadFolders() d->initWadFolders(); d->dataBundles.identify(); - if(d->initialized) + if (d->initialized) { games().checkReadiness(); } @@ -435,12 +435,12 @@ NativePath DoomsdayApp::steamBasePath() { QSettings st("HKEY_CURRENT_USER\\Software\\Valve\\Steam\\", QSettings::NativeFormat); String path = st.value("SteamPath").toString(); - if(!path.isEmpty()) return path; + if (!path.isEmpty()) return path; } { QSettings st("HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\", QSettings::NativeFormat); String path = st.value("InstallPath").toString(); - if(!path.isEmpty()) return path; + if (!path.isEmpty()) return path; } #elif MACOSX return NativePath(QDir::homePath()) / "Library/Application Support/Steam/"; @@ -517,11 +517,11 @@ void DoomsdayApp::unloadGame(Game const &/*upcomingGame*/) { auto &gx = plugins().gameExports(); - if(App_GameLoaded()) + if (App_GameLoaded()) { LOG_MSG("Unloading game..."); - if(gx.Shutdown) + if (gx.Shutdown) { gx.Shutdown(); } @@ -531,7 +531,7 @@ void DoomsdayApp::unloadGame(Game const &/*upcomingGame*/) void *unloader = plugins().findEntryPoint(game().pluginId(), "DP_Unload"); LOGDEV_MSG("Calling DP_Unload %p") << unloader; plugins().setActivePluginId(game().pluginId()); - if(unloader) ((pluginfunc_t)unloader)(); + if (unloader) ((pluginfunc_t)unloader)(); plugins().setActivePluginId(0); } @@ -591,17 +591,17 @@ void DoomsdayApp::setGame(Game const &game) void DoomsdayApp::makeGameCurrent(Game const &newGame) { - if(!newGame.isNull()) + if (!newGame.isNull()) { LOG_MSG("Loading game '%s'...") << newGame.id(); } Library_ReleaseGames(); - if(!isShuttingDown()) + if (!isShuttingDown()) { // Re-initialize subsystems needed even when in Home. - if(!plugins().exchangeGameEntryPoints(newGame.pluginId())) + if (!plugins().exchangeGameEntryPoints(newGame.pluginId())) { throw Plugins::EntryPointError("DoomsdayApp::makeGameCurrent", "Failed to exchange entrypoints with plugin " + @@ -627,12 +627,12 @@ bool DoomsdayApp::changeGame(Game const &newGame, Behaviors behaviors) { // Ignore attempts to reload the current game? - if(game().id() == newGame.id()) + if (game().id() == newGame.id()) { // We are reloading. - if(!behaviors.testFlag(AllowReload)) + if (!behaviors.testFlag(AllowReload)) { - if(isGameLoaded()) + if (isGameLoaded()) { LOG_NOTE("%s (%s) is already loaded") << newGame.title() << newGame.id(); } @@ -655,7 +655,7 @@ bool DoomsdayApp::changeGame(Game const &newGame, * If we aren't shutting down then we are either loading a game or switching * to Home (the current game will have already been unloaded). */ - if(!isShuttingDown()) + if (!isShuttingDown()) { /* * The bulk of this we can do in busy mode unless we are already busy @@ -682,19 +682,19 @@ bool DoomsdayApp::changeGame(Game const &newGame, p.initiatedBusyMode = !BusyMode_Active(); - if(isGameLoaded()) + if (isGameLoaded()) { // Tell the plugin it is being loaded. /// @todo Must this be done in the main thread? void *loader = plugins().findEntryPoint(game().pluginId(), "DP_Load"); LOGDEV_MSG("Calling DP_Load %p") << loader; plugins().setActivePluginId(game().pluginId()); - if(loader) ((pluginfunc_t)loader)(); + if (loader) ((pluginfunc_t)loader)(); plugins().setActivePluginId(0); } /// @todo Kludge: Use more appropriate task names when unloading a game. - if(newGame.isNull()) + if (newGame.isNull()) { gameChangeTasks[0].name = "Unloading game..."; gameChangeTasks[3].name = "Switching to Home..."; @@ -703,7 +703,7 @@ bool DoomsdayApp::changeGame(Game const &newGame, BusyMode_RunTasks(gameChangeTasks, sizeof(gameChangeTasks)/sizeof(gameChangeTasks[0])); - if(isGameLoaded()) + if (isGameLoaded()) { Game::printBanner(game()); } diff --git a/doomsday/apps/libdoomsday/src/filesys/datafile.cpp b/doomsday/apps/libdoomsday/src/filesys/datafile.cpp index 6e8a88cb38..2e12f1034e 100644 --- a/doomsday/apps/libdoomsday/src/filesys/datafile.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/datafile.cpp @@ -28,7 +28,7 @@ DataFile::DataFile(Format format, File &sourceFile) { setSource(&sourceFile); - if(format == Iwad || format == Pwad) + if (format == Iwad || format == Pwad) { // Automatically set the correct format. Block fileType; diff --git a/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp b/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp index 7548b8b350..2bcd2f3949 100644 --- a/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp @@ -30,12 +30,12 @@ DataFolder::DataFolder(Format format, File &sourceFile) setSource(&sourceFile); // Contents of ZIP archives appear inside the folder automatically. - if(ZipArchive::recognize(sourceFile)) + if (ZipArchive::recognize(sourceFile)) { attach(new ArchiveFeed(sourceFile)); } - /*else if(sourceFile.originFeed()) + /*else if (sourceFile.originFeed()) { attach(sourceFile.originFeed()->newSubFeed(sourceFile.name())); } @@ -58,7 +58,7 @@ String DataFolder::describe() const // The folder contents (if any) are produced by feeds. String const feedDesc = describeFeeds(); - if(!feedDesc.isEmpty()) + if (!feedDesc.isEmpty()) { desc += String(" (%1)").arg(feedDesc); } diff --git a/doomsday/apps/libdoomsday/src/filesys/file.cpp b/doomsday/apps/libdoomsday/src/filesys/file.cpp index 6391a05fc8..380b63d5bb 100644 --- a/doomsday/apps/libdoomsday/src/filesys/file.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/file.cpp @@ -46,7 +46,7 @@ File1::File1(FileHandle &hndl, String _path, FileInfo const &_info, File1 *_cont File1::~File1() { App_FileSystem().releaseFile(*this); - if(handle_) delete handle_; + if (handle_) delete handle_; } FileInfo const &File1::info() const @@ -61,7 +61,7 @@ bool File1::isContained() const File1 &File1::container() const { - if(!container_) throw NotContainedError("File1::container", "File \"" + NativePath(composePath()).pretty() + " is not contained"); + if (!container_) throw NotContainedError("File1::container", "File \"" + NativePath(composePath()).pretty() + " is not contained"); return *container_; } @@ -87,7 +87,7 @@ bool File1::hasStartup() const File1 &File1::setStartup(bool yes) { - if(yes) flags |= Startup; + if (yes) flags |= Startup; else flags &= ~Startup; return *this; } @@ -99,7 +99,7 @@ bool File1::hasCustom() const File1 &File1::setCustom(bool yes) { - if(yes) flags |= Custom; + if (yes) flags |= Custom; else flags &= ~Custom; return *this; } diff --git a/doomsday/apps/libdoomsday/src/filesys/filehandle.cpp b/doomsday/apps/libdoomsday/src/filesys/filehandle.cpp index 30f417cb00..ec5644ae1c 100644 --- a/doomsday/apps/libdoomsday/src/filesys/filehandle.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/filehandle.cpp @@ -67,7 +67,7 @@ struct FileHandle::Instance static void errorIfNotValid(FileHandle const &file, char const * /*callerName*/) { DENG2_ASSERT(file.isValid()); - if(!file.isValid()) exit(1); + if (!file.isValid()) exit(1); } FileHandle::FileHandle() @@ -80,7 +80,7 @@ FileHandle::~FileHandle() close(); // Free any cached data. - if(d->data) + if (d->data) { M_Free(d->data); d->data = 0; } @@ -90,13 +90,13 @@ FileHandle::~FileHandle() FileHandle &FileHandle::close() { - if(!d->flags.open) return *this; - if(d->hndl) + if (!d->flags.open) return *this; + if (d->hndl) { fclose(d->hndl); d->hndl = 0; } // Free any cached data. - if(d->data) + if (d->data) { M_Free(d->data); d->data = 0; } @@ -142,7 +142,7 @@ File1 &FileHandle::file() const size_t FileHandle::baseOffset() const { - if(d->flags.reference) + if (d->flags.reference) { return d->file->handle().baseOffset(); } @@ -152,7 +152,7 @@ size_t FileHandle::baseOffset() const size_t FileHandle::length() { errorIfNotValid(*this, "FileHandle::Length"); - if(d->flags.reference) + if (d->flags.reference) { return d->file->handle().length(); } @@ -168,17 +168,17 @@ size_t FileHandle::length() size_t FileHandle::read(uint8_t *buffer, size_t count) { errorIfNotValid(*this, "FileHandle::read"); - if(d->flags.reference) + if (d->flags.reference) { return d->file->handle().read(buffer, count); } else { - if(d->hndl) + if (d->hndl) { // Normal file. count = fread(buffer, 1, count, d->hndl); - if(feof(d->hndl)) + if (feof(d->hndl)) { d->flags.eof = true; } @@ -187,12 +187,12 @@ size_t FileHandle::read(uint8_t *buffer, size_t count) // Is there enough room in the file? size_t bytesleft = d->size - (d->pos - d->data); - if(count > bytesleft) + if (count > bytesleft) { count = bytesleft; d->flags.eof = true; } - if(count) + if (count) { memcpy(buffer, d->pos, count); d->pos += count; @@ -204,7 +204,7 @@ size_t FileHandle::read(uint8_t *buffer, size_t count) bool FileHandle::atEnd() { errorIfNotValid(*this, "FileHandle::atEnd"); - if(d->flags.reference) + if (d->flags.reference) { return d->file->handle().atEnd(); } @@ -223,13 +223,13 @@ unsigned char FileHandle::getC() size_t FileHandle::tell() { errorIfNotValid(*this, "FileHandle::tell"); - if(d->flags.reference) + if (d->flags.reference) { return d->file->handle().tell(); } else { - if(d->hndl) + if (d->hndl) { return (size_t) ftell(d->hndl); } @@ -239,7 +239,7 @@ size_t FileHandle::tell() size_t FileHandle::seek(size_t offset, SeekMethod whence) { - if(d->flags.reference) + if (d->flags.reference) { return d->file->handle().seek(offset, whence); } @@ -248,7 +248,7 @@ size_t FileHandle::seek(size_t offset, SeekMethod whence) size_t oldpos = tell(); d->flags.eof = false; - if(d->hndl) + if (d->hndl) { int fwhence = whence == SeekSet? SEEK_SET : whence == SeekCur? SEEK_CUR : SEEK_END; @@ -257,11 +257,11 @@ size_t FileHandle::seek(size_t offset, SeekMethod whence) } else { - if(whence == SeekSet) + if (whence == SeekSet) d->pos = d->data + offset; - else if(whence == SeekEnd) + else if (whence == SeekEnd) d->pos = d->data + (d->size + offset); - else if(whence == SeekCur) + else if (whence == SeekCur) d->pos += offset; } @@ -301,7 +301,7 @@ FileHandle *FileHandle::fromLump(File1 &lump, bool dontBuffer) // static // Init and load in the lump data. hndl->d->file = &lump; hndl->d->flags.open = true; - if(!dontBuffer) + if (!dontBuffer) { hndl->d->size = lump.size(); hndl->d->pos = hndl->d->data = (uint8_t *) M_Malloc(hndl->d->size); diff --git a/doomsday/apps/libdoomsday/src/filesys/fileid.cpp b/doomsday/apps/libdoomsday/src/filesys/fileid.cpp index b4c007e097..bbaf1a6852 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fileid.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fileid.cpp @@ -73,7 +73,7 @@ String FileId::asText() const { String txt; txt.reserve(32); - for(int i = 0; i < 16; ++i) + for (int i = 0; i < 16; ++i) { txt += String("%1").arg(String::number((byte)md5_.at(i), 16), 2, '0'); } @@ -92,7 +92,7 @@ FileId FileId::fromPath(String path) FileId::Md5Hash FileId::hash(String path) { // Ensure we've a normalized path. - if(QDir::isRelativePath(path)) + if (QDir::isRelativePath(path)) { path = App_BasePath() / path; } diff --git a/doomsday/apps/libdoomsday/src/filesys/filetype.cpp b/doomsday/apps/libdoomsday/src/filesys/filetype.cpp index 26eda2243a..56f004ed3e 100644 --- a/doomsday/apps/libdoomsday/src/filesys/filetype.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/filetype.cpp @@ -32,22 +32,22 @@ void DD_AddFileType(FileType const &ftype) FileType const &DD_FileTypeByName(String name) { - if(!name.isEmpty()) + if (!name.isEmpty()) { FileTypes::const_iterator found = fileTypeMap.constFind(name.toLower()); - if(found != fileTypeMap.constEnd()) return **found; + if (found != fileTypeMap.constEnd()) return **found; } return nullFileType; // Not found. } FileType const &DD_GuessFileTypeFromFileName(String path) { - if(!path.isEmpty()) + if (!path.isEmpty()) { DENG2_FOR_EACH_CONST(FileTypes, i, fileTypeMap) { FileType const &ftype = **i; - if(ftype.fileNameIsKnown(path)) + if (ftype.fileNameIsKnown(path)) return ftype; } } diff --git a/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp b/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp index 72080093e6..257921fdaa 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp @@ -78,12 +78,12 @@ typedef QList PathMappings; */ static FS1::FileList::iterator findListFile(FS1::FileList &list, File1 &file) { - if(list.empty()) return list.end(); + if (list.empty()) return list.end(); // Perform the search. FS1::FileList::iterator i; - for(i = list.begin(); i != list.end(); ++i) + for (i = list.begin(); i != list.end(); ++i) { - if(&file == &(*i)->file()) + if (&file == &(*i)->file()) { break; // This is the node we are looking for. } @@ -97,15 +97,15 @@ static FS1::FileList::iterator findListFile(FS1::FileList &list, File1 &file) */ static FS1::FileList::iterator findListFileByPath(FS1::FileList &list, String path) { - if(list.empty()) return list.end(); - if(path.isEmpty()) return list.end(); + if (list.empty()) return list.end(); + if (path.isEmpty()) return list.end(); // Perform the search. FS1::FileList::iterator i; - for(i = list.begin(); i != list.end(); ++i) + for (i = list.begin(); i != list.end(); ++i) { File1 &file = (*i)->file(); - if(!file.composePath().compare(path, Qt::CaseInsensitive)) + if (!file.composePath().compare(path, Qt::CaseInsensitive)) { break; // This is the node we are looking for. } @@ -131,20 +131,20 @@ static bool matchFileName(String const &string, String const &pattern) QChar const *in = string.constData(), *st = pattern.constData(); - while(!in->isNull()) + while (!in->isNull()) { - if(*st == ASTERISK) + if (*st == ASTERISK) { st++; continue; } - if(*st != QUESTION_MARK && st->toLower() != in->toLower()) + if (*st != QUESTION_MARK && st->toLower() != in->toLower()) { // A mismatch. Hmm. Go back to a previous '*'. - while(st >= pattern && *st != ASTERISK) { st--; } + while (st >= pattern && *st != ASTERISK) { st--; } - if(st < pattern) + if (st < pattern) return false; // No match! // The asterisk lets us continue. } @@ -157,7 +157,7 @@ static bool matchFileName(String const &string, String const &pattern) // Match is good if the end of the pattern was reached. // Skip remaining asterisks. - while(*st == ASTERISK) { st++; } + while (*st == ASTERISK) { st++; } return st->isNull(); } @@ -212,11 +212,11 @@ DENG2_PIMPL(FS1) /// @return @c true if the FileId associated with @a path was released. bool releaseFileId(String path) { - if(!path.isEmpty()) + if (!path.isEmpty()) { FileId fileId = FileId::fromPath(path); FileIds::iterator place = qLowerBound(fileIds.begin(), fileIds.end(), fileId); - if(place != fileIds.end() && *place == fileId) + if (place != fileIds.end() && *place == fileId) { LOGDEV_RES_XVERBOSE_DEBUGONLY("Released FileId %s - \"%s\"", *place << fileId.path()); fileIds.erase(place); @@ -231,10 +231,10 @@ DENG2_PIMPL(FS1) loadedFilesCRC = 0; // Unload in reverse load order. - for(int i = loadedFiles.size() - 1; i >= 0; i--) + for (int i = loadedFiles.size() - 1; i >= 0; i--) { File1 &file = loadedFiles[i]->file(); - if(!index || index->catalogues(file)) + if (!index || index->catalogues(file)) { self.deindex(file); delete &file; @@ -244,7 +244,7 @@ DENG2_PIMPL(FS1) void clearOpenFiles() { - while(!openFiles.isEmpty()){ delete openFiles.takeLast(); } + while (!openFiles.isEmpty()){ delete openFiles.takeLast(); } } void clearIndexes() @@ -269,13 +269,13 @@ DENG2_PIMPL(FS1) // Perform the search. Scheme::FoundNodes foundNodes; - if(scheme.findAll(name, foundNodes)) + if (scheme.findAll(name, foundNodes)) { // At least one node name was matched (perhaps partially). DENG2_FOR_EACH_CONST(Scheme::FoundNodes, i, foundNodes) { PathTree::Node &node = **i; - if(!node.comparePath(search.path(), PathTree::NoBranch)) + if (!node.comparePath(search.path(), PathTree::NoBranch)) { // This is the file we are looking for. return node.path(); @@ -286,12 +286,12 @@ DENG2_PIMPL(FS1) /// @todo Should return not-found here but some searches are still dependent /// on falling back to a wider search. -ds } - catch(UnknownSchemeError const &) + catch (UnknownSchemeError const &) {} // Ignore this error. // Try a wider search of the whole virtual file system. QScopedPointer file(openFile(search.path(), "rb", 0, true /* allow duplicates */)); - if(!file.isNull()) + if (!file.isNull()) { return file->composePath(); } @@ -301,31 +301,31 @@ DENG2_PIMPL(FS1) File1 *findLump(String path, String const & /*mode*/) { - if(path.isEmpty()) return 0; + if (path.isEmpty()) return 0; // We must have an absolute path - prepend the base path if necessary. - if(QDir::isRelativePath(path)) + if (QDir::isRelativePath(path)) { path = App_BasePath() / path; } // First check the Zip lump index. lumpnum_t lumpNum = zipFileIndex.findLast(path); - if(lumpNum >= 0) + if (lumpNum >= 0) { return &zipFileIndex[lumpNum]; } // Nope. Any applicable dir/WAD redirects? - if(!lumpMappings.empty()) + if (!lumpMappings.empty()) { DENG2_FOR_EACH_CONST(LumpMappings, i, lumpMappings) { LumpMapping const &mapping = *i; - if(mapping.first.compare(path)) continue; + if (mapping.first.compare(path)) continue; lumpnum_t lumpNum = self.lumpNumForName(mapping.second); - if(lumpNum < 0) continue; + if (lumpNum < 0) continue; return &self.lump(lumpNum); } @@ -343,34 +343,34 @@ DENG2_PIMPL(FS1) // Translate mymode to the C-lib's fopen() mode specifiers. char mode[8] = ""; - if(mymode.contains('r')) strcat(mode, "r"); - else if(mymode.contains('w')) strcat(mode, "w"); - if(mymode.contains('b')) strcat(mode, "b"); - else if(mymode.contains('t')) strcat(mode, "t"); + if (mymode.contains('r')) strcat(mode, "r"); + else if (mymode.contains('w')) strcat(mode, "w"); + if (mymode.contains('b')) strcat(mode, "b"); + else if (mymode.contains('t')) strcat(mode, "t"); // First try a real native file at this absolute path. NativePath nativePath = NativePath(path); FILE *nativeFile = fopen(nativePath.toUtf8().constData(), mode); - if(nativeFile) + if (nativeFile) { foundPath = nativePath.expand().withSeparators('/'); return nativeFile; } // Nope. Any applicable virtual directory mappings? - if(!pathMappings.empty()) + if (!pathMappings.empty()) { QByteArray pathUtf8 = path.toUtf8(); AutoStr *mapped = AutoStr_NewStd(); DENG2_FOR_EACH_CONST(PathMappings, i, pathMappings) { Str_Set(mapped, pathUtf8.constData()); - if(!applyPathMapping(mapped, *i)) continue; + if (!applyPathMapping(mapped, *i)) continue; // The mapping was successful. nativePath = NativePath(Str_Text(mapped)); nativeFile = fopen(nativePath.toUtf8().constData(), mode); - if(nativeFile) + if (nativeFile) { foundPath = nativePath.expand().withSeparators('/'); return nativeFile; @@ -384,7 +384,7 @@ DENG2_PIMPL(FS1) File1 *openFile(String path, String const& mode, size_t baseOffset, bool allowDuplicate) { - if(path.isEmpty()) return 0; + if (path.isEmpty()) return 0; LOG_AS("FS1::openFile"); @@ -399,12 +399,12 @@ DENG2_PIMPL(FS1) FileInfo info; // The temporary info descriptor. // First check for lumps? - if(!reqNativeFile) + if (!reqNativeFile) { - if(File1 *found = findLump(path, mode)) + if (File1 *found = findLump(path, mode)) { // Do not read files twice. - if(!allowDuplicate && !self.checkFileId(found->composeUri())) return 0; + if (!allowDuplicate && !self.checkFileId(found->composeUri())) return 0; // Get a handle to the lump we intend to open. /// @todo The way this buffering works is nonsensical it should not be done here @@ -417,13 +417,13 @@ DENG2_PIMPL(FS1) } // Not found? - try a native file. - if(!hndl) + if (!hndl) { String foundPath; - if(FILE *found = findAndOpenNativeFile(path, mode, foundPath)) + if (FILE *found = findAndOpenNativeFile(path, mode, foundPath)) { // Do not read files twice. - if(!allowDuplicate && !self.checkFileId(de::Uri(foundPath, RC_NULL))) + if (!allowDuplicate && !self.checkFileId(de::Uri(foundPath, RC_NULL))) { fclose(found); return 0; @@ -438,7 +438,7 @@ DENG2_PIMPL(FS1) } // Nothing? - if(!hndl) return 0; + if (!hndl) return 0; // Search path is used here rather than found path as the latter may have // been mapped to another location. We want the file to be attributed with @@ -446,7 +446,7 @@ DENG2_PIMPL(FS1) File1 &file = self.interpret(*hndl, path, info); - if(loadingForStartup) + if (loadingForStartup) { file.setStartup(true); } @@ -463,7 +463,7 @@ FS1::Scheme &FS1::createScheme(String name, Scheme::Flags flags) DENG2_ASSERT(name.length() >= Scheme::min_name_length); // Ensure this is a unique name. - if(knownScheme(name)) return scheme(name); + if (knownScheme(name)) return scheme(name); // Create a new scheme. Scheme *newScheme = new Scheme(name, flags); @@ -476,17 +476,17 @@ void FS1::index(File1 &file) #ifdef DENG_DEBUG // Ensure this hasn't yet been indexed. FileList::const_iterator found = findListFile(d->loadedFiles, file); - if(found != d->loadedFiles.end()) + if (found != d->loadedFiles.end()) throw Error("FS1::index", "File \"" + NativePath(file.composePath()).pretty() + "\" has already been indexed"); #endif // Publish lumps to one or more indexes? - if(Zip *zip = file.maybeAs()) + if (Zip *zip = file.maybeAs()) { - if(!zip->isEmpty()) + if (!zip->isEmpty()) { // Insert the lumps into their rightful places in the index. - for(int i = 0; i < zip->lumpCount(); ++i) + for (int i = 0; i < zip->lumpCount(); ++i) { File1 &lump = zip->lump(i); @@ -497,12 +497,12 @@ void FS1::index(File1 &file) } } } - else if(Wad *wad = file.maybeAs()) + else if (Wad *wad = file.maybeAs()) { - if(!wad->isEmpty()) + if (!wad->isEmpty()) { // Insert the lumps into their rightful places in the index. - for(int i = 0; i < wad->lumpCount(); ++i) + for (int i = 0; i < wad->lumpCount(); ++i) { d->primaryIndex.catalogLump(wad->lump(i)); } @@ -518,7 +518,7 @@ void FS1::index(File1 &file) void FS1::deindex(File1 &file) { FileList::iterator found = findListFile(d->loadedFiles, file); - if(found == d->loadedFiles.end()) return; // Most peculiar.. + if (found == d->loadedFiles.end()) return; // Most peculiar.. d->releaseFileId(file.composePath()); @@ -533,26 +533,26 @@ void FS1::deindex(File1 &file) File1 &FS1::find(de::Uri const &search) { LOG_AS("FS1::find"); - if(!search.isEmpty()) + if (!search.isEmpty()) { try { String searchPath = search.resolved(); // Convert to an absolute path. - if(!QDir::isAbsolutePath(searchPath)) + if (!QDir::isAbsolutePath(searchPath)) { searchPath = App_BasePath() / searchPath; } FileList::iterator found = findListFileByPath(d->loadedFiles, searchPath); - if(found != d->loadedFiles.end()) + if (found != d->loadedFiles.end()) { DENG_ASSERT((*found)->hasFile()); return (*found)->file(); } } - catch(de::Uri::ResolveError const &er) + catch (de::Uri::ResolveError const &er) { // Log but otherwise ignore unresolved paths. LOGDEV_RES_VERBOSE(er.asText()); @@ -566,7 +566,7 @@ File1 &FS1::find(de::Uri const &search) String FS1::findPath(de::Uri const &search, int flags, ResourceClass &rclass) { LOG_AS("FS1::findPath"); - if(!search.isEmpty()) + if (!search.isEmpty()) { try { @@ -574,16 +574,16 @@ String FS1::findPath(de::Uri const &search, int flags, ResourceClass &rclass) // If an extension was specified, first look for files of the same type. String ext = searchPath.fileNameExtension(); - if(!ext.isEmpty() && ext.compare(".*")) + if (!ext.isEmpty() && ext.compare(".*")) { String found = d->findPath(de::Uri(search.scheme(), searchPath)); - if(!found.isEmpty()) return found; + if (!found.isEmpty()) return found; // If we are looking for a particular file type, get out of here. - if(flags & RLF_MATCH_EXTENSION) return ""; + if (flags & RLF_MATCH_EXTENSION) return ""; } - if(isNullResourceClass(rclass) || !rclass.fileTypeCount()) return ""; + if (isNullResourceClass(rclass) || !rclass.fileTypeCount()) return ""; /* * Try each expected file type name extension for this resource class. @@ -596,11 +596,11 @@ String FS1::findPath(de::Uri const &search, int flags, ResourceClass &rclass) { String const &ext = *i; String found = d->findPath(de::Uri(search.scheme(), searchPathWithoutFileNameExtension + ext)); - if(!found.isEmpty()) return found; + if (!found.isEmpty()) return found; } }; } - catch(de::Uri::ResolveError const &er) + catch (de::Uri::ResolveError const &er) { // Log but otherwise ignore unresolved paths. LOGDEV_RES_VERBOSE(er.asText()); @@ -650,7 +650,7 @@ int FS1::unloadAllNonStartupFiles() { #ifdef DENG_DEBUG // List all open files with their identifiers. - if(LogBuffer::get().isEnabled(LogEntry::Generic | LogEntry::Verbose)) + if (LogBuffer::get().isEnabled(LogEntry::Generic | LogEntry::Verbose)) { LOGDEV_RES_VERBOSE("Open files at reset:"); printFileList(d->openFiles); @@ -660,10 +660,10 @@ int FS1::unloadAllNonStartupFiles() // Perform non-startup file unloading (in reverse load order). int numUnloadedFiles = 0; - for(int i = d->loadedFiles.size() - 1; i >= 0; i--) + for (int i = d->loadedFiles.size() - 1; i >= 0; i--) { File1 &file = d->loadedFiles[i]->file(); - if(file.hasStartup()) continue; + if (file.hasStartup()) continue; deindex(file); delete &file; @@ -672,7 +672,7 @@ int FS1::unloadAllNonStartupFiles() #ifdef DENG_DEBUG // Sanity check: look for orphaned identifiers. - if(!d->fileIds.empty()) + if (!d->fileIds.empty()) { LOGDEV_RES_MSG("Orphan FileIds:"); printFileIds(d->fileIds); @@ -684,12 +684,12 @@ int FS1::unloadAllNonStartupFiles() bool FS1::checkFileId(de::Uri const &path) { - if(!accessFile(path)) return false; + if (!accessFile(path)) return false; // Calculate the identifier. FileId fileId = FileId::fromPath(path.compose()); FileIds::iterator place = qLowerBound(d->fileIds.begin(), d->fileIds.end(), fileId); - if(place != d->fileIds.end() && *place == fileId) return false; + if (place != d->fileIds.end() && *place == fileId) return false; LOGDEV_RES_XVERBOSE_DEBUGONLY("checkFileId \"%s\" => %s", fileId.path() << fileId); /* path() is debug-only */ @@ -716,10 +716,10 @@ lumpnum_t FS1::lumpNumForName(String name) { LOG_AS("FS1::lumpNumForName"); - if(name.isEmpty()) return -1; + if (name.isEmpty()) return -1; // Append a .lmp extension if none is specified. - if(name.fileNameExtension().isEmpty()) + if (name.fileNameExtension().isEmpty()) { name += ".lmp"; } @@ -730,10 +730,10 @@ lumpnum_t FS1::lumpNumForName(String name) void FS1::releaseFile(File1 &file) { - for(int i = d->openFiles.size() - 1; i >= 0; i--) + for (int i = d->openFiles.size() - 1; i >= 0; i--) { FileHandle &hndl = *(d->openFiles[i]); - if(&hndl.file() == &file) + if (&hndl.file() == &file) { d->openFiles.removeAt(i); } @@ -743,13 +743,13 @@ void FS1::releaseFile(File1 &file) /// @return @c NULL= Not found. static Wad *findFirstWadFile(FS1::FileList &list, bool custom) { - if(list.empty()) return 0; + if (list.empty()) return 0; DENG2_FOR_EACH(FS1::FileList, i, list) { File1 &file = (*i)->file(); - if(custom != file.hasCustom()) continue; + if (custom != file.hasCustom()) continue; - if(Wad *wad = file.maybeAs()) + if (Wad *wad = file.maybeAs()) { return wad; } @@ -759,7 +759,7 @@ static Wad *findFirstWadFile(FS1::FileList &list, bool custom) uint FS1::loadedFilesCRC() { - if(!d->loadedFilesCRC) + if (!d->loadedFilesCRC) { /** * We define the CRC as that of the lump directory of the first loaded IWAD. @@ -767,7 +767,7 @@ uint FS1::loadedFilesCRC() */ // CRC not calculated yet, let's do it now. Wad *iwad = findFirstWadFile(d->loadedFiles, false/*not-custom*/); - if(!iwad) return 0; + if (!iwad) return 0; d->loadedFilesCRC = iwad->calculateCRC(); } return d->loadedFilesCRC; @@ -785,7 +785,7 @@ int FS1::findAll(bool (*predicate)(File1 &file, void *parameters), void *paramet DENG2_FOR_EACH_CONST(FS1::FileList, i, d->loadedFiles) { // Interested in this file? - if(predicate && !predicate((*i)->file(), parameters)) continue; // Nope. + if (predicate && !predicate((*i)->file(), parameters)) continue; // Nope. found.push_back(*i); numFound += 1; @@ -798,7 +798,7 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) int const numFoundSoFar = found.count(); // We must have an absolute path - prepend the base path if necessary. - if(!QDir::isAbsolutePath(searchPattern)) + if (!QDir::isAbsolutePath(searchPattern)) { searchPattern = App_BasePath() / searchPattern; } @@ -813,7 +813,7 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) String filePath; bool patternMatched; - if(!(flags & SearchPath::NoDescend)) + if (!(flags & SearchPath::NoDescend)) { filePath = lump.composePath(); patternMatched = matchFileName(filePath, searchPattern); @@ -823,10 +823,10 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) patternMatched = !node.comparePath(searchPattern, PathTree::MatchFull); } - if(!patternMatched) continue; + if (!patternMatched) continue; // Not yet composed the path? - if(filePath.isEmpty()) + if (filePath.isEmpty()) { filePath = lump.composePath(); } @@ -837,11 +837,11 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) /* * Check the dir/WAD direcs. */ - if(!d->lumpMappings.empty()) + if (!d->lumpMappings.empty()) { DENG2_FOR_EACH_CONST(LumpMappings, i, d->lumpMappings) { - if(!matchFileName(i->first, searchPattern)) continue; + if (!matchFileName(i->first, searchPattern)) continue; found.push_back(PathListItem(i->first, 0 /*only filepaths (i.e., leaves) can be mapped to lumps*/)); } @@ -853,40 +853,40 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) * Check native paths. */ String searchDirectory = searchPattern.toString().fileNamePath(); - if(!searchDirectory.isEmpty()) + if (!searchDirectory.isEmpty()) { QByteArray searchDirectoryUtf8 = searchDirectory.toUtf8(); PathList nativeFilePaths; AutoStr *wildPath = AutoStr_NewStd(); Str_Reserve(wildPath, searchDirectory.length() + 2 + 16); // Conservative estimate. - for(int i = -1; i < (int)d->pathMappings.count(); ++i) + for (int i = -1; i < (int)d->pathMappings.count(); ++i) { Str_Clear(wildPath); Str_Appendf(wildPath, "%s/", searchDirectoryUtf8.constData()); - if(i > -1) + if (i > -1) { // Possible mapping? - if(!applyPathMapping(wildPath, d->pathMappings[i])) continue; + if (!applyPathMapping(wildPath, d->pathMappings[i])) continue; } Str_AppendChar(wildPath, '*'); FindData fd; - if(!FindFile_FindFirst(&fd, Str_Text(wildPath))) + if (!FindFile_FindFirst(&fd, Str_Text(wildPath))) { // First path found. do { // Ignore relative directory symbolics. - if(Str_Compare(&fd.name, ".") && Str_Compare(&fd.name, "..")) + if (Str_Compare(&fd.name, ".") && Str_Compare(&fd.name, "..")) { String foundPath = searchDirectory / NativePath(Str_Text(&fd.name)).withSeparators('/'); - if(!matchFileName(foundPath, searchPattern)) continue; + if (!matchFileName(foundPath, searchPattern)) continue; nativeFilePaths.push_back(PathListItem(foundPath, fd.attrib)); } - } while(!FindFile_FindNext(&fd)); + } while (!FindFile_FindNext(&fd)); } FindFile_Finish(&fd); } @@ -909,30 +909,30 @@ File1 &FS1::interpret(FileHandle &hndl, String filePath, FileInfo const &info) // Firstly try the interpreter for the guessed resource types. FileType const &ftypeGuess = DD_GuessFileTypeFromFileName(filePath); - if(NativeFileType const* fileType = dynamic_cast(&ftypeGuess)) + if (NativeFileType const* fileType = dynamic_cast(&ftypeGuess)) { interpretedFile = fileType->interpret(hndl, filePath, info); } // If not yet interpreted - try each recognisable format in order. - if(!interpretedFile) + if (!interpretedFile) { FileTypes const &fileTypes = DD_FileTypes(); DENG2_FOR_EACH_CONST(FileTypes, i, fileTypes) { - if(NativeFileType const *fileType = dynamic_cast(*i)) + if (NativeFileType const *fileType = dynamic_cast(*i)) { // Already tried this? - if(fileType == &ftypeGuess) continue; + if (fileType == &ftypeGuess) continue; interpretedFile = fileType->interpret(hndl, filePath, info); - if(interpretedFile) break; + if (interpretedFile) break; } } } // Still not interpreted? - if(!interpretedFile) + if (!interpretedFile) { // Use a generic file. File1 *container = (hndl.hasFile() && hndl.file().isContained())? &hndl.file().container() : 0; @@ -946,15 +946,15 @@ File1 &FS1::interpret(FileHandle &hndl, String filePath, FileInfo const &info) FileHandle &FS1::openFile(String const &path, String const &mode, size_t baseOffset, bool allowDuplicate) { #ifdef DENG_DEBUG - for(int i = 0; i < mode.length(); ++i) + for (int i = 0; i < mode.length(); ++i) { - if(mode[i] != 'r' && mode[i] != 't' && mode[i] != 'b' && mode[i] != 'f') + if (mode[i] != 'r' && mode[i] != 't' && mode[i] != 'b' && mode[i] != 'f') throw Error("FS1::openFile", "Unknown argument in mode string '" + mode + "'"); } #endif File1 *file = d->openFile(path, mode, baseOffset, allowDuplicate); - if(!file) throw NotFoundError("FS1::openFile", "No files found matching '" + path + "'"); + if (!file) throw NotFoundError("FS1::openFile", "No files found matching '" + path + "'"); // Add a handle to the opened files list. FileHandle &hndl = *FileHandle::fromFile(*file); @@ -977,7 +977,7 @@ bool FS1::accessFile(de::Uri const &search) QScopedPointer file(d->openFile(search.resolved(), "rb", 0, true /* allow duplicates */)); return !file.isNull(); } - catch(de::Uri::ResolveError const &er) + catch (de::Uri::ResolveError const &er) { // Log but otherwise ignore unresolved paths. LOGDEV_RES_VERBOSE(er.asText()); @@ -987,10 +987,10 @@ bool FS1::accessFile(de::Uri const &search) void FS1::addPathLumpMapping(String lumpName, String destination) { - if(lumpName.isEmpty() || destination.isEmpty()) return; + if (lumpName.isEmpty() || destination.isEmpty()) return; // We require an absolute path - prepend the CWD if necessary. - if(QDir::isRelativePath(destination)) + if (QDir::isRelativePath(destination)) { String workPath = DENG2_APP->currentWorkPath().withSeparators('/'); destination = workPath / destination; @@ -998,15 +998,15 @@ void FS1::addPathLumpMapping(String lumpName, String destination) // Have already mapped this path? LumpMappings::iterator found = d->lumpMappings.begin(); - for(; found != d->lumpMappings.end(); ++found) + for (; found != d->lumpMappings.end(); ++found) { LumpMapping const &ldm = *found; - if(!ldm.first.compare(destination, Qt::CaseInsensitive)) + if (!ldm.first.compare(destination, Qt::CaseInsensitive)) break; } LumpMapping *ldm; - if(found == d->lumpMappings.end()) + if (found == d->lumpMappings.end()) { // No. Acquire another mapping. d->lumpMappings.push_back(LumpMapping(destination, lumpName)); @@ -1030,10 +1030,10 @@ void FS1::clearPathLumpMappings() /// @return @c true iff the mapping matched the path. static bool applyPathMapping(ddstring_t *path, PathMapping const &pm) { - if(!path) return false; + if (!path) return false; QByteArray destUtf8 = pm.first.toUtf8(); AutoStr *dest = AutoStr_FromTextStd(destUtf8.constData()); - if(qstrnicmp(Str_Text(path), Str_Text(dest), Str_Length(dest))) return false; + if (qstrnicmp(Str_Text(path), Str_Text(dest), Str_Length(dest))) return false; // Replace the beginning with the source path. QByteArray sourceUtf8 = pm.second.toUtf8(); @@ -1045,19 +1045,19 @@ static bool applyPathMapping(ddstring_t *path, PathMapping const &pm) void FS1::addPathMapping(String source, String destination) { - if(source.isEmpty() || destination.isEmpty()) return; + if (source.isEmpty() || destination.isEmpty()) return; // Have already mapped this source path? PathMappings::iterator found = d->pathMappings.begin(); - for(; found != d->pathMappings.end(); ++found) + for (; found != d->pathMappings.end(); ++found) { PathMapping const &pm = *found; - if(!pm.second.compare(source, Qt::CaseInsensitive)) + if (!pm.second.compare(source, Qt::CaseInsensitive)) break; } PathMapping* pm; - if(found == d->pathMappings.end()) + if (found == d->pathMappings.end()) { // No. Acquire another mapping. d->pathMappings.push_back(PathMapping(destination, source)); @@ -1087,7 +1087,7 @@ void FS1::printDirectory(Path path) path = path / "*"; PathList found; - if(findAllPaths(path, 0, found)) + if (findAllPaths(path, 0, found)) { qSort(found.begin(), found.end()); @@ -1100,20 +1100,20 @@ void FS1::printDirectory(Path path) bool FS1::knownScheme(String name) { - if(!name.isEmpty()) + if (!name.isEmpty()) { Schemes::iterator found = d->schemes.find(name.toLower()); - if(found != d->schemes.end()) return true; + if (found != d->schemes.end()) return true; } return false; } FS1::Scheme &FS1::scheme(String name) { - if(!name.isEmpty()) + if (!name.isEmpty()) { Schemes::iterator found = d->schemes.find(name.toLower()); - if(found != d->schemes.end()) return **found; + if (found != d->schemes.end()) return **found; } /// @throw UnknownSchemeError An unknown scheme was referenced. throw UnknownSchemeError("FS1::scheme", "No scheme found matching '" + name + "'"); @@ -1128,9 +1128,9 @@ FS1::Schemes const &FS1::allSchemes() D_CMD(Dir) { DENG2_UNUSED(src); - if(argc > 1) + if (argc > 1) { - for(int i = 1; i < argc; ++i) + for (int i = 1; i < argc; ++i) { String path = NativePath(argv[i]).expand().withSeparators('/'); App_FileSystem().printDirectory(path); @@ -1148,10 +1148,10 @@ D_CMD(DumpLump) { DENG2_UNUSED2(src, argc); - if(fileSystem) + if (fileSystem) { lumpnum_t lumpNum = App_FileSystem().lumpNumForName(argv[1]); - if(lumpNum >= 0) + if (lumpNum >= 0) { return F_DumpFile(App_FileSystem().lump(lumpNum), 0); } @@ -1166,7 +1166,7 @@ D_CMD(ListLumps) { DENG2_UNUSED3(src, argc, argv); - if(!fileSystem) return false; + if (!fileSystem) return false; LumpIndex const &lumpIndex = App_FileSystem().nameIndex(); int const numRecords = lumpIndex.size(); @@ -1202,7 +1202,7 @@ D_CMD(ListFiles) int totalFiles = 0; int totalPackages = 0; - if(fileSystem) + if (fileSystem) { FS1::FileList const &allLoadedFiles = App_FileSystem().loadedFiles(); DENG2_FOR_EACH_CONST(FS1::FileList, i, allLoadedFiles) @@ -1211,11 +1211,11 @@ D_CMD(ListFiles) uint crc = 0; int fileCount = 1; - if(de::Zip *zip = file.maybeAs()) + if (de::Zip *zip = file.maybeAs()) { fileCount = zip->lumpCount(); } - else if(de::Wad *wad = file.maybeAs()) + else if (de::Wad *wad = file.maybeAs()) { fileCount = wad->lumpCount(); crc = (!file.hasCustom()? wad->calculateCRC() : 0); @@ -1252,7 +1252,7 @@ void FS1::consoleRegister() FS1 &App_FileSystem() { - if(!fileSystem) throw Error("App_FileSystem", "File system not yet initialized"); + if (!fileSystem) throw Error("App_FileSystem", "File system not yet initialized"); return *fileSystem; } @@ -1269,7 +1269,7 @@ void F_Init() void F_Shutdown() { - if(!fileSystem) return; + if (!fileSystem) return; delete fileSystem; fileSystem = 0; } diff --git a/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp b/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp index ed4335e68f..5d302823ca 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp @@ -117,9 +117,9 @@ struct NameHash void clear() { - for(hash_type hashKey = 0; hashKey < hash_range; ++hashKey) + for (hash_type hashKey = 0; hashKey < hash_range; ++hashKey) { - while(buckets[hashKey].first) + while (buckets[hashKey].first) { NameHash::Node *nextNode = buckets[hashKey].first->next; delete buckets[hashKey].first; @@ -132,7 +132,7 @@ struct NameHash Node *findDirectoryNode(hash_type hashKey, PathTree::Node const &directoryNode) { Node *node = buckets[hashKey].first; - while(node && &node->fileRef.directoryNode() != &directoryNode) + while (node && &node->fileRef.directoryNode() != &directoryNode) { node = node->next; } @@ -143,10 +143,10 @@ struct NameHash { hash_type hashKey = 0; int op = 0; - for(int i = 0; i < str.length(); ++i) + for (int i = 0; i < str.length(); ++i) { ushort unicode = str.at(i).toLower().unicode(); - switch(op) + switch (op) { case 0: hashKey ^= unicode; ++op; break; case 1: hashKey *= unicode; ++op; break; @@ -204,7 +204,7 @@ struct FS1::Scheme::Instance addDirectoryPathAndMaybeDescendBranch(true/*do descend*/, searchPath.resolved(), true/*is-directory*/, searchPath.flags()); } - catch(de::Uri::ResolveError const &er) + catch (de::Uri::ResolveError const &er) { LOGDEV_RES_VERBOSE(er.asText()); } @@ -217,7 +217,7 @@ struct FS1::Scheme::Instance */ void addFromSearchPaths(FS1::PathGroup group) { - for(FS1::Scheme::SearchPaths::const_iterator i = searchPaths.find(group); + for (FS1::Scheme::SearchPaths::const_iterator i = searchPaths.find(group); i != searchPaths.end() && i.key() == group; ++i) { addFromSearchPath(*i); @@ -226,23 +226,23 @@ struct FS1::Scheme::Instance UserDataNode *addDirectoryPath(String path) { - if(path.isEmpty()) return 0; + if (path.isEmpty()) return 0; // Try to make it a relative path. - if(QDir::isAbsolutePath(path)) + if (QDir::isAbsolutePath(path)) { String const basePath = App_BasePath(); - if(path.beginsWith(basePath)) + if (path.beginsWith(basePath)) { path = path.mid(basePath.length() + 1); } } // If this is equal to the base path, return that node. - if(path.isEmpty()) + if (path.isEmpty()) { // Time to construct the relative base node? - if(!rootNode) + if (!rootNode) { rootNode = &directory.insert(Path("./")); } @@ -254,7 +254,7 @@ struct FS1::Scheme::Instance void addDirectoryChildren(PathTree::Node &node, int flags) { - if(node.isLeaf()) return; + if (node.isLeaf()) return; // Compose the search pattern. We're interested in *everything*. Path searchPattern = node.path() / "*"; @@ -281,21 +281,21 @@ struct FS1::Scheme::Instance { // Add this path to the directory. UserDataNode *node = addDirectoryPath(filePath); - if(!node) return; + if (!node) return; - if(!node->isLeaf()) + if (!node->isLeaf()) { // Descend into this subdirectory? - if(descendBranch) + if (descendBranch) { // Already processed? - if(node->userValue()) + if (node->userValue()) { // Process it again? DENG2_FOR_EACH_CONST(PathTree::Nodes, i, directory.leafNodes()) { PathTree::Node &sibling = **i; - if(&sibling.parent() == node) + if (&sibling.parent() == node) { self.add(sibling); } @@ -347,7 +347,7 @@ void FS1::Scheme::clear() void FS1::Scheme::rebuild() { // Is a rebuild not necessary? - if(!d->nameHashIsDirty) return; + if (!d->nameHashIsDirty) return; LOG_AS("Scheme::rebuild"); LOGDEV_RES_MSG("Rebuilding '%s'...") << d->name; @@ -379,7 +379,7 @@ static inline String composeSchemeName(String const &filePath) bool FS1::Scheme::add(PathTree::Node &resourceNode) { // We are only interested in leafs (i.e., files and not folders). - if(!resourceNode.isLeaf()) return false; + if (!resourceNode.isLeaf()) return false; String name = composeSchemeName(resourceNode.name()); NameHash::hash_type hashKey = NameHash::hashName(name); @@ -387,7 +387,7 @@ bool FS1::Scheme::add(PathTree::Node &resourceNode) // Is this a new file? bool isNewNode = false; NameHash::Node *hashNode = d->nameHash.findDirectoryNode(hashKey, resourceNode); - if(!hashNode) + if (!hashNode) { isNewNode = true; @@ -400,9 +400,9 @@ bool FS1::Scheme::add(PathTree::Node &resourceNode) // Link it to the list for this bucket. NameHash::Bucket &bucket = d->nameHash.buckets[hashKey]; - if(bucket.last) bucket.last->next = hashNode; + if (bucket.last) bucket.last->next = hashNode; bucket.last = hashNode; - if(!bucket.first) bucket.first = hashNode; + if (!bucket.first) bucket.first = hashNode; // We will need to rebuild this scheme (if we aren't already doing so, // in the case of auto-populated schemes built from FileDirectorys). @@ -433,7 +433,7 @@ bool FS1::Scheme::addSearchPath(SearchPath const &search, FS1::PathGroup group) LOG_AS("Scheme::addSearchPath"); // Ensure this is a well formed path. - if(search.isEmpty() || + if (search.isEmpty() || !search.path().toString().compareWithoutCase("/") || !search.path().toString().endsWith("/")) return false; @@ -445,7 +445,7 @@ bool FS1::Scheme::addSearchPath(SearchPath const &search, FS1::PathGroup group) DENG2_FOR_EACH(SearchPaths, i, d->searchPaths) { // Compare using the unresolved textual representations. - if(!i->asText().compareWithoutCase(search.asText())) + if (!i->asText().compareWithoutCase(search.asText())) { i->setFlags(search.flags()); return true; @@ -481,7 +481,7 @@ int FS1::Scheme::findAll(String name, FoundNodes &found) int numFoundSoFar = found.count(); NameHash::hash_type fromKey, toKey; - if(!name.isEmpty()) + if (!name.isEmpty()) { fromKey = NameHash::hashName(name); toKey = fromKey; @@ -492,15 +492,15 @@ int FS1::Scheme::findAll(String name, FoundNodes &found) toKey = NameHash::hash_range - 1; } - for(NameHash::hash_type key = fromKey; key < toKey + 1; ++key) + for (NameHash::hash_type key = fromKey; key < toKey + 1; ++key) { NameHash::Bucket &bucket = d->nameHash.buckets[key]; - for(NameHash::Node *hashNode = bucket.first; hashNode; hashNode = hashNode->next) + for (NameHash::Node *hashNode = bucket.first; hashNode; hashNode = hashNode->next) { FileRef &fileRef = hashNode->fileRef; PathTree::Node &node = fileRef.directoryNode(); - if(!name.isEmpty() && !node.name().beginsWith(name, Qt::CaseInsensitive)) continue; + if (!name.isEmpty() && !node.name().beginsWith(name, Qt::CaseInsensitive)) continue; found.push_back(&node); } @@ -511,15 +511,15 @@ int FS1::Scheme::findAll(String name, FoundNodes &found) bool FS1::Scheme::mapPath(String &path) const { - if(path.isEmpty()) return false; + if (path.isEmpty()) return false; // Are virtual path mappings in effect for this scheme? - if(!(d->flags & MappedInPackages)) return false; + if (!(d->flags & MappedInPackages)) return false; // Does this path qualify for mapping? - if(path.length() <= name().length()) return false; - if(path.at(name().length()) != '/') return false; - if(!path.beginsWith(name(), Qt::CaseInsensitive)) return false; + if (path.length() <= name().length()) return false; + if (path.at(name().length()) != '/') return false; + if (!path.beginsWith(name(), Qt::CaseInsensitive)) return false; // Yes. path = String("$(App.DataPath)/$(GamePlugin.Name)") / path; @@ -533,10 +533,10 @@ void FS1::Scheme::debugPrint() const LOGDEV_RES_MSG("%p:") << this; uint schemeIdx = 0; - for(NameHash::hash_type key = 0; key < NameHash::hash_range; ++key) + for (NameHash::hash_type key = 0; key < NameHash::hash_range; ++key) { NameHash::Bucket &bucket = d->nameHash.buckets[key]; - for(NameHash::Node *node = bucket.first; node; node = node->next) + for (NameHash::Node *node = bucket.first; node; node = node->next) { FileRef const &fileRef = node->fileRef; diff --git a/doomsday/apps/libdoomsday/src/filesys/fs_util.cpp b/doomsday/apps/libdoomsday/src/filesys/fs_util.cpp index f9cd0c799d..5125950531 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fs_util.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fs_util.cpp @@ -62,7 +62,7 @@ int F_Access(char const *nativePath) int F_FileExists(char const *path) { int result = -1; - if(path && path[0]) + if (path && path[0]) { ddstring_t buf; // Normalize the path into one we can process. @@ -100,7 +100,7 @@ dd_bool F_MakePath(char const *path) App::fileSystem().makeFolder(path); return true; } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("Failed to create path \"%s\": %s") << path << er.asText(); return false; @@ -121,7 +121,7 @@ dd_bool F_MakePath(char const *path) F_ToNativeSlashes(&full, &full); // Does this path already exist? - if(0 == access(Str_Text(&full), 0)) + if (0 == access(Str_Text(&full), 0)) { Str_Free(&full); return true; @@ -133,11 +133,11 @@ dd_bool F_MakePath(char const *path) do { endptr = strchr(ptr, DENG_DIR_SEP_CHAR); - if(!endptr) + if (!endptr) Str_Append(&buf, ptr); else Str_PartAppend(&buf, ptr, 0, endptr - ptr); - if(0 != access(Str_Text(&buf), 0)) + if (0 != access(Str_Text(&buf), 0)) { // Path doesn't exist, create it. #ifdef WIN32 @@ -148,7 +148,7 @@ dd_bool F_MakePath(char const *path) } Str_AppendChar(&buf, DENG_DIR_SEP_CHAR); ptr = endptr + 1; - } while(NULL != endptr); + } while (NULL != endptr); result = (0 == access(Str_Text(&full), 0)); Str_Free(&buf); @@ -161,28 +161,28 @@ dd_bool F_FixSlashes(ddstring_t* dstStr, const ddstring_t* srcStr) dd_bool result = false; assert(dstStr && srcStr); - if(!Str_IsEmpty(srcStr)) + if (!Str_IsEmpty(srcStr)) { char* dst = Str_Text(dstStr); const char* src = Str_Text(srcStr); size_t i; - if(dstStr != srcStr) + if (dstStr != srcStr) { Str_Clear(dstStr); Str_Reserve(dstStr, Str_Length(srcStr)); } - for(i = 0; src[i]; ++i) + for (i = 0; src[i]; ++i) { - if(src[i] != '\\') + if (src[i] != '\\') { - if(dstStr != srcStr) + if (dstStr != srcStr) Str_AppendChar(dstStr, src[i]); continue; } - if(dstStr != srcStr) + if (dstStr != srcStr) Str_AppendChar(dstStr, '/'); else dst[i] = '/'; @@ -199,7 +199,7 @@ dd_bool F_FixSlashes(ddstring_t* dstStr, const ddstring_t* srcStr) #ifdef UNIX static bool F_AppendMissingSlash(ddstring_t *pathStr) { - if(Str_RAt(pathStr, 0) != '/') + if (Str_RAt(pathStr, 0) != '/') { Str_AppendChar(pathStr, '/'); return true; @@ -210,7 +210,7 @@ static bool F_AppendMissingSlash(ddstring_t *pathStr) dd_bool F_AppendMissingSlashCString(char* path, size_t maxLen) { - if(path[strlen(path) - 1] != '/') + if (path[strlen(path) - 1] != '/') { M_StrCat(path, "/", maxLen); return true; @@ -223,28 +223,28 @@ dd_bool F_ToNativeSlashes(ddstring_t* dstStr, const ddstring_t* srcStr) dd_bool result = false; assert(dstStr && srcStr); - if(!Str_IsEmpty(srcStr)) + if (!Str_IsEmpty(srcStr)) { char* dst = Str_Text(dstStr); const char* src = Str_Text(srcStr); size_t i; - if(dstStr != srcStr) + if (dstStr != srcStr) { Str_Clear(dstStr); Str_Reserve(dstStr, Str_Length(srcStr)); } - for(i = 0; src[i]; ++i) + for (i = 0; src[i]; ++i) { - if(src[i] != DENG_DIR_WRONG_SEP_CHAR) + if (src[i] != DENG_DIR_WRONG_SEP_CHAR) { - if(dstStr != srcStr) + if (dstStr != srcStr) Str_AppendChar(dstStr, src[i]); continue; } - if(dstStr != srcStr) + if (dstStr != srcStr) Str_AppendChar(dstStr, DENG_DIR_SEP_CHAR); else dst[i] = DENG_DIR_SEP_CHAR; @@ -278,10 +278,10 @@ static dd_bool F_RemoveBasePath(ddstring_t *dst, ddstring_t const *absPath) ddstring_t basePath; Str_InitStatic(&basePath, DD_BasePath()); - if(F_IsRelativeToBase(Str_Text(absPath), Str_Text(&basePath))) + if (F_IsRelativeToBase(Str_Text(absPath), Str_Text(&basePath))) { dd_bool mustCopy = (dst == absPath); - if(mustCopy) + if (mustCopy) { ddstring_t buf; Str_Init(&buf); @@ -297,7 +297,7 @@ static dd_bool F_RemoveBasePath(ddstring_t *dst, ddstring_t const *absPath) } // Do we need to copy anyway? - if(dst != absPath) + if (dst != absPath) { Str_Set(dst, Str_Text(absPath)); } @@ -308,13 +308,13 @@ static dd_bool F_RemoveBasePath(ddstring_t *dst, ddstring_t const *absPath) dd_bool F_IsAbsolute(const ddstring_t* str) { - if(!str) + if (!str) return false; /// @todo Should not handle both separators - refactor callers. - if(Str_At(str, 0) == DENG_DIR_SEP_CHAR || Str_At(str, 0) == DENG_DIR_WRONG_SEP_CHAR || Str_At(str, 1) == ':') + if (Str_At(str, 0) == DENG_DIR_SEP_CHAR || Str_At(str, 0) == DENG_DIR_WRONG_SEP_CHAR || Str_At(str, 1) == ':') return true; #ifdef UNIX - if(Str_At(str, 0) == '~') + if (Str_At(str, 0) == '~') return true; #endif return false; @@ -323,10 +323,10 @@ dd_bool F_IsAbsolute(const ddstring_t* str) dd_bool F_ExpandBasePath(ddstring_t* dst, const ddstring_t* src) { assert(dst && src); - if(Str_At(src, 0) == '>' || Str_At(src, 0) == '}') + if (Str_At(src, 0) == '>' || Str_At(src, 0) == '}') { dd_bool mustCopy = (dst == src); - if(mustCopy) + if (mustCopy) { ddstring_t buf; Str_Init(&buf); Str_Set(&buf, DD_BasePath()); @@ -341,9 +341,9 @@ dd_bool F_ExpandBasePath(ddstring_t* dst, const ddstring_t* src) return true; } #ifdef UNIX - else if(Str_At(src, 0) == '~') + else if (Str_At(src, 0) == '~') { - if(Str_At(src, 1) == '/' && getenv("HOME")) + if (Str_At(src, 1) == '/' && getenv("HOME")) { // Replace it with the HOME environment variable. ddstring_t buf; ddstring_t homeStr; @@ -369,13 +369,13 @@ dd_bool F_ExpandBasePath(ddstring_t* dst, const ddstring_t* src) const char* p = Str_Text(src)+2; Str_Init(&userName); - if((p = Str_CopyDelim2(&userName, p, '/', CDF_OMIT_DELIMITER))) + if ((p = Str_CopyDelim2(&userName, p, '/', CDF_OMIT_DELIMITER))) { ddstring_t buf; struct passwd* pw; Str_Init(&buf); - if((pw = getpwnam(Str_Text(&userName))) != NULL) + if ((pw = getpwnam(Str_Text(&userName))) != NULL) { ddstring_t pwStr; Str_Init(&pwStr); @@ -391,14 +391,14 @@ dd_bool F_ExpandBasePath(ddstring_t* dst, const ddstring_t* src) Str_Free(&buf); } Str_Free(&userName); - if(result) + if (result) return result; } } #endif // Do we need to copy anyway? - if(dst != src) + if (dst != src) Str_Set(dst, Str_Text(src)); // No expansion done. @@ -408,12 +408,12 @@ dd_bool F_ExpandBasePath(ddstring_t* dst, const ddstring_t* src) /// @return @c true if @a path begins with a known directive. static dd_bool pathHasDirective(const char* path) { - if(NULL != path && path[0]) + if (NULL != path && path[0]) { #ifdef UNIX - if('~' == path[0]) return true; + if ('~' == path[0]) return true; #endif - if('}' == path[0] || '>' == path[0]) return true; + if ('}' == path[0] || '>' == path[0]) return true; } return false; } @@ -427,11 +427,11 @@ const char* F_PrettyPath(const char* path) ddstring_t* buf = NULL; int len; - if(!path || 0 == (len = (int)strlen(path))) + if (!path || 0 == (len = (int)strlen(path))) return path; // Hide relative directives like '}' - if(len > 1 && pathHasDirective(path)) + if (len > 1 && pathHasDirective(path)) { buf = &buffers[index++ % NUM_BUFS]; Str_Clear(buf); @@ -440,9 +440,9 @@ const char* F_PrettyPath(const char* path) } // If within our the base directory cut out the base path. - if(F_IsRelativeToBase(path, DD_BasePath())) + if (F_IsRelativeToBase(path, DD_BasePath())) { - if(!buf) + if (!buf) { buf = &buffers[index++ % NUM_BUFS]; Str_Set(buf, path); @@ -452,17 +452,17 @@ const char* F_PrettyPath(const char* path) } // Swap directory separators with their system-specific version. - if(strchr(path, DENG_DIR_WRONG_SEP_CHAR)) + if (strchr(path, DENG_DIR_WRONG_SEP_CHAR)) { int i; - if(!buf) + if (!buf) { buf = &buffers[index++ % NUM_BUFS]; Str_Set(buf, path); } - for(i = 0; i < len; ++i) + for (i = 0; i < len; ++i) { - if(buf->str[i] == DENG_DIR_WRONG_SEP_CHAR) + if (buf->str[i] == DENG_DIR_WRONG_SEP_CHAR) buf->str[i] = DENG_DIR_SEP_CHAR; } path = Str_Text(buf); @@ -478,14 +478,14 @@ dd_bool F_Dump(void const *data, size_t size, char const *path) { DENG2_ASSERT(data != 0 && path != 0); - if(!size) return false; + if (!size) return false; AutoStr *nativePath = AutoStr_NewStd(); Str_Set(nativePath, path); F_ToNativeSlashes(nativePath, nativePath); FILE *outFile = fopen(Str_Text(nativePath), "wb"); - if(!outFile) + if (!outFile) { LOG_RES_WARNING("Failed to open \"%s\" for writing: %s") << F_PrettyPath(Str_Text(nativePath)) << strerror(errno); @@ -509,7 +509,7 @@ dd_bool F_DumpFile(File1 &file, char const *outputPath) LOG_RES_VERBOSE("%s dumped to %s") << file.name() << out.description(); return true; } - catch(Error const &er) + catch (Error const &er) { LOG_RES_ERROR("Failed to write to \"%s\": %s") << dumpPath << er.asText(); return false; @@ -525,7 +525,7 @@ bool F_DumpNativeFile(Block const &data, NativePath const &filePath) *file << data; return true; } - catch(Error const &er) + catch (Error const &er) { return false; } diff --git a/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp b/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp index 0cc2c5fae3..48b6d425e6 100644 --- a/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp @@ -36,7 +36,7 @@ LumpCache::Data::~Data() uint8_t *LumpCache::Data::data() const { - if(data_ && Z_GetTag(data_) == PU_PURGELEVEL) + if (data_ && Z_GetTag(data_) == PU_PURGELEVEL) { // Reaquire the data. Z_ChangeTag2(data_, PU_APPSTATIC); @@ -49,7 +49,7 @@ uint8_t const *LumpCache::Data::replaceData(uint8_t *newData) { clearData(); data_ = newData; - if(data_) + if (data_) { Z_ChangeUser(data_, &data_); } @@ -59,20 +59,20 @@ uint8_t const *LumpCache::Data::replaceData(uint8_t *newData) LumpCache::Data &LumpCache::Data::clearData(bool *retCleared) { bool hasData = !!data_; - if(hasData) + if (hasData) { /// @todo Implement a proper thread-safe locking mechanism. // Elevate the cached data to purge level so it will be explicitly // free'd by the Zone the next time the rover passes it. - if(Z_GetTag(data_) != PU_PURGELEVEL) + if (Z_GetTag(data_) != PU_PURGELEVEL) { Z_ChangeTag2(data_, PU_PURGELEVEL); } // Mark the data as unowned. Z_ChangeUser(data_, (void *) 0x2); } - if(retCleared) *retCleared = hasData; + if (retCleared) *retCleared = hasData; return *this; } @@ -85,7 +85,7 @@ LumpCache::Data &LumpCache::Data::lock() LumpCache::Data &LumpCache::Data::unlock() { /// @todo Implement a proper thread-safe locking mechanism. - if(data_) + if (data_) { Z_ChangeTag2(data_, PU_PURGELEVEL); } @@ -97,7 +97,7 @@ LumpCache::LumpCache(uint size) : _size(size), _dataCache(0) LumpCache::~LumpCache() { - if(_dataCache) delete _dataCache; + if (_dataCache) delete _dataCache; } uint LumpCache::size() const @@ -120,10 +120,10 @@ uint8_t const *LumpCache::data(uint lumpIdx) const LumpCache &LumpCache::insert(uint lumpIdx, uint8_t *data) { LOG_AS("LumpCache::insert"); - if(!isValidIndex(lumpIdx)) throw Error("LumpCache::insert", QString("Invalid index %1").arg(lumpIdx)); + if (!isValidIndex(lumpIdx)) throw Error("LumpCache::insert", QString("Invalid index %1").arg(lumpIdx)); // Time to allocate the data cache? - if(!_dataCache) + if (!_dataCache) { _dataCache = new DataCache(_size); } @@ -141,7 +141,7 @@ LumpCache &LumpCache::insertAndLock(uint lumpIdx, uint8_t *data) LumpCache &LumpCache::lock(uint lumpIdx) { LOG_AS("LumpCache::lock"); - if(!isValidIndex(lumpIdx)) throw Error("LumpCache::lock", QString("Invalid index %1").arg(lumpIdx)); + if (!isValidIndex(lumpIdx)) throw Error("LumpCache::lock", QString("Invalid index %1").arg(lumpIdx)); Data* record = cacheRecord(lumpIdx); record->lock(); return *this; @@ -150,7 +150,7 @@ LumpCache &LumpCache::lock(uint lumpIdx) LumpCache &LumpCache::unlock(uint lumpIdx) { LOG_AS("LumpCache::unlock"); - if(!isValidIndex(lumpIdx)) throw Error("LumpCache::unlock", QString("Invalid index %1").arg(lumpIdx)); + if (!isValidIndex(lumpIdx)) throw Error("LumpCache::unlock", QString("Invalid index %1").arg(lumpIdx)); Data* record = cacheRecord(lumpIdx); record->unlock(); return *this; @@ -159,11 +159,11 @@ LumpCache &LumpCache::unlock(uint lumpIdx) LumpCache &LumpCache::remove(uint lumpIdx, bool *retRemoved) { Data *record = cacheRecord(lumpIdx); - if(record) + if (record) { record->clearData(retRemoved); } - else if(retRemoved) + else if (retRemoved) { *retRemoved = false; } @@ -172,7 +172,7 @@ LumpCache &LumpCache::remove(uint lumpIdx, bool *retRemoved) LumpCache &LumpCache::clear() { - if(_dataCache) + if (_dataCache) { DENG2_FOR_EACH(DataCache, i, *_dataCache) { @@ -184,12 +184,12 @@ LumpCache &LumpCache::clear() LumpCache::Data *LumpCache::cacheRecord(uint lumpIdx) { - if(!isValidIndex(lumpIdx)) return 0; + if (!isValidIndex(lumpIdx)) return 0; return _dataCache? &(*_dataCache)[lumpIdx] : 0; } LumpCache::Data const *LumpCache::cacheRecord(uint lumpIdx) const { - if(!isValidIndex(lumpIdx)) return 0; + if (!isValidIndex(lumpIdx)) return 0; return _dataCache? &(*_dataCache)[lumpIdx] : 0; } diff --git a/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp b/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp index e746676ccc..c92e2d5ed6 100644 --- a/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp @@ -43,11 +43,11 @@ namespace internal LumpSortInfo const *infoA = (LumpSortInfo const *)a; LumpSortInfo const *infoB = (LumpSortInfo const *)b; - if(int delta = infoA->path.compare(infoB->path, Qt::CaseInsensitive)) + if (int delta = infoA->path.compare(infoB->path, Qt::CaseInsensitive)) return delta; // Still matched; try the file load order indexes. - if(int delta = (infoA->lump->container().loadOrderIndex() - + if (int delta = (infoA->lump->container().loadOrderIndex() - infoB->lump->container().loadOrderIndex())) return delta; @@ -78,19 +78,19 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu // Keep checking lumps to see if its a map data lump. dint const numLumps = lumpIndex.size(); String sourceFile; - for(d->lastLump = de::max(lumpIndexOffset, 0); d->lastLump < numLumps; ++d->lastLump) + for (d->lastLump = de::max(lumpIndexOffset, 0); d->lastLump < numLumps; ++d->lastLump) { // Lump name determines whether this lump is a candidate. File1 &lump = lumpIndex[d->lastLump]; DataType dataType = typeForLumpName(lump.name()); - if(d->lumps.isEmpty()) + if (d->lumps.isEmpty()) { // No sequence has yet begun. Continue the scan? - if(dataType == UnknownData) continue; + if (dataType == UnknownData) continue; // Missing a header? - if(d->lastLump == 0) return; + if (d->lastLump == 0) return; // The id of the map is the name of the lump which precedes the first // recognized data lump (which should be the header). Note that some @@ -101,10 +101,10 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu else { // The first unrecognized lump ends the sequence. - if(dataType == UnknownData) break; + if (dataType == UnknownData) break; // A lump from another source file also ends the sequence. - if(sourceFile.compareWithoutCase(lump.container().composePath())) + if (sourceFile.compareWithoutCase(lump.container().composePath())) break; } @@ -113,17 +113,17 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu d->lumps.insert(dataType, &lump); } - if(d->lumps.isEmpty()) return; + if (d->lumps.isEmpty()) return; // At this point we know we've found something that could be map data. // Some data lumps are specific to a particular map format and thus their // presence unambiguously identifies the format. - if(d->lumps.contains(BehaviorData)) + if (d->lumps.contains(BehaviorData)) { d->format = HexenFormat; } - else if(d->lumps.contains(MacroData) || d->lumps.contains(TintColorData) || + else if (d->lumps.contains(MacroData) || d->lumps.contains(TintColorData) || d->lumps.contains(LeafData)) { d->format = Doom64Format; @@ -144,7 +144,7 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu duint *elemCountAddr = 0; dsize const elemSize = elementSizeForDataType(d->format, dataType); - switch(dataType) + switch (dataType) { default: break; @@ -156,9 +156,9 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu case TintColorData: elemCountAddr = &numLights; break; } - if(elemCountAddr) + if (elemCountAddr) { - if(lump.size() % elemSize != 0) + if (lump.size() % elemSize != 0) { // What *is* this?? d->format = UnknownFormat; @@ -172,7 +172,7 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu // A valid map contains at least one of each of these element types. /// @todo Support loading "empty" maps. - if(!numVertexes || !numLines || !numSides || !numSectors) + if (!numVertexes || !numLines || !numSides || !numSectors) { d->format = UnknownFormat; d->id.clear(); @@ -199,7 +199,7 @@ LumpIndex::Id1MapRecognizer::Lumps const &LumpIndex::Id1MapRecognizer::lumps() c File1 *LumpIndex::Id1MapRecognizer::sourceFile() const { - if(d->lumps.isEmpty()) return 0; + if (d->lumps.isEmpty()) return 0; return &lumps().find(VertexData).value()->container(); } @@ -216,7 +216,7 @@ String const &LumpIndex::Id1MapRecognizer::formatName(Format id) // static /* MF_HEXEN */ "id Tech 1 (Hexen)", /* MF_DOOM64 */ "id Tech 1 (Doom64)" }; - if(id >= DoomFormat && id < KnownFormatCount) + if (id >= DoomFormat && id < KnownFormatCount) { return names[1 + id]; } @@ -257,12 +257,12 @@ LumpIndex::Id1MapRecognizer::DataType LumpIndex::Id1MapRecognizer::typeForLumpNa // Ignore the file extension if present. name = name.fileNameWithoutExtension(); - if(!name.isEmpty()) + if (!name.isEmpty()) { - for(dint i = 0; !lumpTypeInfo[i].name.isEmpty(); ++i) + for (dint i = 0; !lumpTypeInfo[i].name.isEmpty(); ++i) { LumpTypeInfo const &info = lumpTypeInfo[i]; - if(!info.name.compareWithoutCase(name) && + if (!info.name.compareWithoutCase(name) && info.name.length() == name.length()) { return info.type; @@ -289,7 +289,7 @@ dsize LumpIndex::Id1MapRecognizer::elementSizeForDataType(Format mapFormat, Data dsize const SIZEOF_XTHING = (2 * 7 + 1 * 6); dsize const SIZEOF_LIGHT = (1 * 6); - switch(dataType) + switch (dataType) { default: return 0; @@ -340,7 +340,7 @@ DENG2_PIMPL(LumpIndex) void buildLumpsByPathIfNeeded() { - if(!lumpsByPath.isNull()) return; + if (!lumpsByPath.isNull()) return; int const numElements = lumps.size(); lumpsByPath.reset(new PathHash(numElements)); @@ -353,7 +353,7 @@ DENG2_PIMPL(LumpIndex) // Prepend nodes to each chain, in first-to-last load order, so that // the last lump with a given name appears first in the chain. - for(int i = 0; i < numElements; ++i) + for (int i = 0; i < numElements; ++i) { File1 const &lump = *(lumps[i]); PathTree::Node const &node = lump.directoryNode(); @@ -378,11 +378,11 @@ DENG2_PIMPL(LumpIndex) int const numRecords = lumps.size(); int numFlagged = 0; - for(int i = 0; i < numRecords; ++i) + for (int i = 0; i < numRecords; ++i) { File1 *lump = lumps[i]; - if(pruneFlags.testBit(i)) continue; - if(!lump->isContained() || &lump->container() != &file) continue; + if (pruneFlags.testBit(i)) continue; + if (!lump->isContained() || &lump->container() != &file) continue; pruneFlags.setBit(i, true); numFlagged += 1; } @@ -398,15 +398,15 @@ DENG2_PIMPL(LumpIndex) DENG2_ASSERT(pruneFlags.size() == lumps.size()); // Any work to do? - if(!pathsAreUnique) return 0; - if(!needPruneDuplicateLumps) return 0; + if (!pathsAreUnique) return 0; + if (!needPruneDuplicateLumps) return 0; int const numRecords = lumps.size(); - if(numRecords <= 1) return 0; + if (numRecords <= 1) return 0; // Sort in descending load order for pruning. LumpSortInfo *sortInfos = new LumpSortInfo[numRecords]; - for(int i = 0; i < numRecords; ++i) + for (int i = 0; i < numRecords; ++i) { LumpSortInfo &sortInfo = sortInfos[i]; File1 const *lump = lumps[i]; @@ -419,10 +419,10 @@ DENG2_PIMPL(LumpIndex) // Flag the lumps we'll be pruning. int numFlagged = 0; - for(int i = 1; i < numRecords; ++i) + for (int i = 1; i < numRecords; ++i) { - if(pruneFlags.testBit(i)) continue; - if(sortInfos[i - 1].path.compare(sortInfos[i].path, Qt::CaseInsensitive)) continue; + if (pruneFlags.testBit(i)) continue; + if (sortInfos[i - 1].path.compare(sortInfos[i].path, Qt::CaseInsensitive)) continue; pruneFlags.setBit(sortInfos[i].origIndex, true); numFlagged += 1; } @@ -440,22 +440,22 @@ DENG2_PIMPL(LumpIndex) // Have we lumps to prune? int const numFlaggedForPrune = flaggedLumps.count(true); - if(numFlaggedForPrune) + if (numFlaggedForPrune) { // We'll need to rebuild the hash after this. lumpsByPath.reset(); int numRecords = lumps.size(); - if(numRecords == numFlaggedForPrune) + if (numRecords == numFlaggedForPrune) { lumps.clear(); } else { // Do this one lump at a time, respecting the possibly-sorted order. - for(int i = 0, newIdx = 0; i < numRecords; ++i) + for (int i = 0, newIdx = 0; i < numRecords; ++i) { - if(!flaggedLumps.testBit(i)) + if (!flaggedLumps.testBit(i)) { ++newIdx; continue; @@ -475,11 +475,11 @@ DENG2_PIMPL(LumpIndex) void pruneDuplicatesIfNeeded() { - if(!needPruneDuplicateLumps) return; + if (!needPruneDuplicateLumps) return; needPruneDuplicateLumps = false; int const numRecords = lumps.size(); - if(numRecords <= 1) return; + if (numRecords <= 1) return; QBitArray pruneFlags(numRecords); flagDuplicateLumps(pruneFlags); @@ -504,14 +504,14 @@ bool LumpIndex::hasLump(lumpnum_t lumpNum) const static String invalidIndexMessage(int invalidIdx, int lastValidIdx) { String msg = String("Invalid lump index %1").arg(invalidIdx); - if(lastValidIdx < 0) msg += " (file is empty)"; + if (lastValidIdx < 0) msg += " (file is empty)"; else msg += String(", valid range: [0..%2)").arg(lastValidIdx); return msg; } File1 &LumpIndex::lump(lumpnum_t lumpNum) const { - if(!hasLump(lumpNum)) throw NotFoundError("LumpIndex::lump", invalidIndexMessage(lumpNum, size() - 1)); + if (!hasLump(lumpNum)) throw NotFoundError("LumpIndex::lump", invalidIndexMessage(lumpNum, size() - 1)); return *d->lumps[lumpNum]; } @@ -534,7 +534,7 @@ int LumpIndex::lastIndex() const int LumpIndex::pruneByFile(File1 &file) { - if(d->lumps.empty()) return 0; + if (d->lumps.empty()) return 0; int const numRecords = d->lumps.size(); QBitArray pruneFlags(numRecords); @@ -556,12 +556,12 @@ int LumpIndex::pruneByFile(File1 &file) bool LumpIndex::pruneLump(File1 &lump) { - if(d->lumps.empty()) return 0; + if (d->lumps.empty()) return 0; d->pruneDuplicatesIfNeeded(); // Prune this lump. - if(!d->lumps.removeOne(&lump)) return false; + if (!d->lumps.removeOne(&lump)) return false; // We'll need to rebuild the path hash chains. d->lumpsByPath.reset(); @@ -574,7 +574,7 @@ void LumpIndex::catalogLump(File1 &lump) d->lumps.push_back(&lump); d->lumpsByPath.reset(); // We'll need to rebuild the path hash chains. - if(d->pathsAreUnique) + if (d->pathsAreUnique) { // We may need to prune duplicate paths. d->needPruneDuplicateLumps = true; @@ -595,7 +595,7 @@ bool LumpIndex::catalogues(File1 &file) DENG2_FOR_EACH(Lumps, i, d->lumps) { File1 const &lump = **i; - if(&lump.container() == &file) + if (&lump.container() == &file) return true; } @@ -613,7 +613,7 @@ int LumpIndex::findAll(Path const &path, FoundIndices &found) const found.clear(); - if(path.isEmpty() || d->lumps.empty()) return 0; + if (path.isEmpty() || d->lumps.empty()) return 0; d->pruneDuplicatesIfNeeded(); d->buildLumpsByPathIfNeeded(); @@ -621,13 +621,13 @@ int LumpIndex::findAll(Path const &path, FoundIndices &found) const // Perform the search. DENG2_ASSERT(!d->lumpsByPath.isNull()); ushort hash = path.lastSegment().hash() % d->lumpsByPath->size(); - for(int idx = (*d->lumpsByPath)[hash].head; idx != -1; + for (int idx = (*d->lumpsByPath)[hash].head; idx != -1; idx = (*d->lumpsByPath)[idx].nextInLoadOrder) { File1 const &lump = *d->lumps[idx]; PathTree::Node const &node = lump.directoryNode(); - if(!node.comparePath(path, 0)) + if (!node.comparePath(path, 0)) { found.push_front(idx); } @@ -638,7 +638,7 @@ int LumpIndex::findAll(Path const &path, FoundIndices &found) const lumpnum_t LumpIndex::findLast(Path const &path) const { - if(path.isEmpty() || d->lumps.empty()) return -1; + if (path.isEmpty() || d->lumps.empty()) return -1; d->pruneDuplicatesIfNeeded(); d->buildLumpsByPathIfNeeded(); @@ -646,13 +646,13 @@ lumpnum_t LumpIndex::findLast(Path const &path) const // Perform the search. DENG2_ASSERT(!d->lumpsByPath.isNull()); ushort hash = path.lastSegment().hash() % d->lumpsByPath->size(); - for(int idx = (*d->lumpsByPath)[hash].head; idx != -1; + for (int idx = (*d->lumpsByPath)[hash].head; idx != -1; idx = (*d->lumpsByPath)[idx].nextInLoadOrder) { File1 const &lump = *d->lumps[idx]; PathTree::Node const &node = lump.directoryNode(); - if(!node.comparePath(path, 0)) + if (!node.comparePath(path, 0)) { return idx; // This is the lump we are looking for. } @@ -663,7 +663,7 @@ lumpnum_t LumpIndex::findLast(Path const &path) const lumpnum_t LumpIndex::findFirst(Path const &path) const { - if(path.isEmpty() || d->lumps.empty()) return -1; + if (path.isEmpty() || d->lumps.empty()) return -1; d->pruneDuplicatesIfNeeded(); d->buildLumpsByPathIfNeeded(); @@ -673,13 +673,13 @@ lumpnum_t LumpIndex::findFirst(Path const &path) const // Perform the search. DENG2_ASSERT(!d->lumpsByPath.isNull()); ushort hash = path.lastSegment().hash() % d->lumpsByPath->size(); - for(int idx = (*d->lumpsByPath)[hash].head; idx != -1; + for (int idx = (*d->lumpsByPath)[hash].head; idx != -1; idx = (*d->lumpsByPath)[idx].nextInLoadOrder) { File1 const &lump = *d->lumps[idx]; PathTree::Node const &node = lump.directoryNode(); - if(!node.comparePath(path, 0)) + if (!node.comparePath(path, 0)) { earliest = idx; // This is now the first lump loaded. } diff --git a/doomsday/apps/libdoomsday/src/filesys/sys_direc.cpp b/doomsday/apps/libdoomsday/src/filesys/sys_direc.cpp index a3892f1bf1..2339e9f9f0 100644 --- a/doomsday/apps/libdoomsday/src/filesys/sys_direc.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/sys_direc.cpp @@ -107,7 +107,7 @@ directory_t* Dir_NewFromCWD(void) directory_t* Dir_FromText(const char* path) { directory_t* dir; - if(!path || !path[0]) + if (!path || !path[0]) return Dir_NewFromCWD(); dir = (directory_t*) M_Calloc(sizeof *dir); @@ -165,7 +165,7 @@ static void prependBasePath(char* newPath, const char* path, size_t maxLen) { DENG_ASSERT(newPath && path); // Cannot prepend to absolute paths. - if(!Dir_IsAbsolutePath(path)) + if (!Dir_IsAbsolutePath(path)) { filename_t buf; dd_snprintf(buf, maxLen, "%s%s", DD_BasePath(), path); @@ -180,16 +180,16 @@ static void resolveAppRelativeDirectives(char* translated, const char* path, siz filename_t buf; DENG_ASSERT(translated && path); - if(path[0] == '>' || path[0] == '}') + if (path[0] == '>' || path[0] == '}') { path++; - if(!Dir_IsAbsolutePath(path)) + if (!Dir_IsAbsolutePath(path)) prependBasePath(buf, path, maxLen); else strncpy(buf, path, maxLen); strncpy(translated, buf, maxLen); } - else if(translated != path) + else if (translated != path) { strncpy(translated, path, maxLen); } @@ -201,15 +201,15 @@ static void resolveHomeRelativeDirectives(char* path, size_t maxLen) filename_t buf; DENG_ASSERT(path); - if(!path[0] || 0 == maxLen || path[0] != '~') return; + if (!path[0] || 0 == maxLen || path[0] != '~') return; memset(buf, 0, sizeof(buf)); - if(path[1] == '/') + if (path[1] == '/') { // Replace it with the HOME environment variable. strncpy(buf, getenv("HOME"), FILENAME_T_MAXLEN); - if(DENG_LAST_CHAR(buf) != '/') + if (DENG_LAST_CHAR(buf) != '/') M_StrCat(buf, "/", FILENAME_T_MAXLEN); // Append the rest of the original path. @@ -225,10 +225,10 @@ static void resolveHomeRelativeDirectives(char* path, size_t maxLen) userName[end - path - 1] = 0; pw = getpwnam(userName); - if(pw) + if (pw) { strncpy(buf, pw->pw_dir, FILENAME_T_MAXLEN); - if(DENG_LAST_CHAR(buf) != '/') + if (DENG_LAST_CHAR(buf) != '/') M_StrCat(buf, "/", FILENAME_T_MAXLEN); } @@ -248,16 +248,16 @@ static void resolvePathRelativeDirectives(char* path) char* end = path + strlen(path); char* prev = path; // Assume an absolute path. - for(; *ch; ch++) + for (; *ch; ch++) { - if(ch[0] == '/' && ch[1] == '.') + if (ch[0] == '/' && ch[1] == '.') { - if(ch[2] == '/') + if (ch[2] == '/') { memmove(ch, ch + 2, end - ch - 1); ch--; } - else if(ch[2] == '.' && ch[3] == '/') + else if (ch[2] == '.' && ch[3] == '/') { memmove(prev, ch + 3, end - ch - 2); // Must restart from the beginning. @@ -266,14 +266,14 @@ static void resolvePathRelativeDirectives(char* path) continue; } } - if(*ch == '/') + if (*ch == '/') prev = ch; } } void Dir_CleanPath(char* path, size_t len) { - if(!path || 0 == len) return; + if (!path || 0 == len) return; M_Strip(path, len); #if defined(UNIX) @@ -296,7 +296,7 @@ char* Dir_CurrentPath(void) { de::String path = de::App::currentWorkPath(); // FS1 generally assumes that paths end with a separator. - if(!path.endsWith(de::NativePath::separator())) + if (!path.endsWith(de::NativePath::separator())) { path += de::NativePath::separator(); } @@ -306,18 +306,18 @@ char* Dir_CurrentPath(void) static void Dir_FileName(char* name, const char* path, size_t len) { char ext[100]; /// @todo Use dynamic string. - if(!path || !name || 0 == len) return; + if (!path || !name || 0 == len) return; _splitpath(path, 0, 0, name, ext); M_StrCat(name, ext, len); } static int Dir_IsAbsolutePath(const char* path) { - if(!path || !path[0]) return 0; - if(path[0] == '/' || path[1] == ':') + if (!path || !path[0]) return 0; + if (path[0] == '/' || path[1] == ':') return true; #if defined(UNIX) - if(path[0] == '~') + if (path[0] == '~') return true; #endif return false; @@ -333,14 +333,14 @@ dd_bool Dir_mkpath(const char* path) filename_t full, buf; char* ptr, *endptr; - if(!path || !path[0]) return false; + if (!path || !path[0]) return false; // Convert all backslashes to normal slashes. strncpy(full, path, FILENAME_T_MAXLEN); Dir_ToNativeSeparators(full, FILENAME_T_MAXLEN); // Does this path already exist? - if(0 == access(full, 0)) + if (0 == access(full, 0)) return true; // Check and create the path in segments. @@ -349,12 +349,12 @@ dd_bool Dir_mkpath(const char* path) do { endptr = strchr(ptr, DENG_DIR_SEP_CHAR); - if(!endptr) + if (!endptr) M_StrCat(buf, ptr, FILENAME_T_MAXLEN); else M_StrnCat(buf, ptr, endptr - ptr, FILENAME_T_MAXLEN); - if(buf[0] && access(buf, 0)) + if (buf[0] && access(buf, 0)) { // Path doesn't exist, create it. #if defined(WIN32) @@ -366,7 +366,7 @@ dd_bool Dir_mkpath(const char* path) M_StrCat(buf, DENG_DIR_SEP_STR, FILENAME_T_MAXLEN); ptr = endptr + 1; - } while(endptr); + } while (endptr); return (0 == access(full, 0)); } @@ -375,7 +375,7 @@ dd_bool Dir_mkpath(const char* path) void Dir_MakeAbsolutePath(char* path, size_t len) { filename_t buf; - if(!path || !path[0] || 0 == len) return; + if (!path || !path[0] || 0 == len) return; #if defined(UNIX) resolveHomeRelativeDirectives(path, len); @@ -388,11 +388,11 @@ void Dir_MakeAbsolutePath(char* path, size_t len) static void Dir_ToNativeSeparators(char* path, size_t len) { size_t i; - if(!path || !path[0] || 0 == len) return; + if (!path || !path[0] || 0 == len) return; - for(i = 0; i < len && path[i]; ++i) + for (i = 0; i < len && path[i]; ++i) { - if(path[i] == DENG_DIR_WRONG_SEP_CHAR) + if (path[i] == DENG_DIR_WRONG_SEP_CHAR) path[i] = DENG_DIR_SEP_CHAR; } } @@ -400,11 +400,11 @@ static void Dir_ToNativeSeparators(char* path, size_t len) static void Dir_FixSeparators(char* path, size_t len) { size_t i; - if(!path || !path[0] || 0 == len) return; + if (!path || !path[0] || 0 == len) return; - for(i = 0; i < len && path[i]; ++i) + for (i = 0; i < len && path[i]; ++i) { - if(path[i] == '\\') + if (path[i] == '\\') path[i] = '/'; } } @@ -414,7 +414,7 @@ static void Dir_FixSeparators(char* path, size_t len) LOG_AS("Dir"); bool success = false; - if(path && path[0]) + if (path && path[0]) { success = de::NativePath::setWorkPath(path); } diff --git a/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp b/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp index f0bf599a3d..addea5ba13 100644 --- a/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp @@ -34,18 +34,18 @@ void FS_InitVirtualPathMappings() { App_FileSystem().clearPathMappings(); - if(DoomsdayApp::app().isShuttingDown()) return; + if (DoomsdayApp::app().isShuttingDown()) return; // Create virtual directory mappings by processing all -vdmap options. dint argC = CommandLine_Count(); - for(dint i = 0; i < argC; ++i) + for (dint i = 0; i < argC; ++i) { - if(strnicmp("-vdmap", CommandLine_At(i), 6)) + if (strnicmp("-vdmap", CommandLine_At(i), 6)) { continue; } - if(i < argC - 1 && !CommandLine_IsOption(i + 1) && !CommandLine_IsOption(i + 2)) + if (i < argC - 1 && !CommandLine_IsOption(i + 1) && !CommandLine_IsOption(i + 2)) { String source = NativePath(CommandLine_PathAt(i + 1)).expand().withSeparators('/'); String destination = NativePath(CommandLine_PathAt(i + 2)).expand().withSeparators('/'); @@ -59,7 +59,7 @@ void FS_InitVirtualPathMappings() static inline char const *skipSpace(char const *ptr) { DENG2_ASSERT(ptr != 0); - while(*ptr && *ptr != '\n' && isspace(*ptr)) + while (*ptr && *ptr != '\n' && isspace(*ptr)) { ptr++; } return ptr; } @@ -72,15 +72,15 @@ static bool parsePathLumpMapping(char lumpName[9/*LUMPNAME_T_MAXLEN*/], ddstring char const *ptr = skipSpace(buffer); // Just whitespace? - if(!*ptr || *ptr == '\n') return false; + if (!*ptr || *ptr == '\n') return false; // Find the end of the lump name. char const *end = (char const *)M_FindWhite((char *)ptr); - if(!*end || *end == '\n') return false; + if (!*end || *end == '\n') return false; size_t len = end - ptr; // Invalid lump name? - if(len > 8) return false; + if (len > 8) return false; memset(lumpName, 0, 9/*LUMPNAME_T_MAXLEN*/); strncpy(lumpName, ptr, len); @@ -88,7 +88,7 @@ static bool parsePathLumpMapping(char lumpName[9/*LUMPNAME_T_MAXLEN*/], ddstring // Find the start of the file path. ptr = skipSpace(end); - if(!*ptr || *ptr == '\n') return false; // Missing file path. + if (!*ptr || *ptr == '\n') return false; // Missing file path. // We're at the file path. Str_Set(path, ptr); @@ -116,7 +116,7 @@ static bool parsePathLumpMappings(char const *buffer) do { ch = Str_GetLine(&line, ch); - if(!parsePathLumpMapping(lumpName, &path, Str_Text(&line))) + if (!parsePathLumpMapping(lumpName, &path, Str_Text(&line))) { // Failure parsing the mapping. // Ignore errors in individual mappings and continue parsing. @@ -127,7 +127,7 @@ static bool parsePathLumpMappings(char const *buffer) String destination = NativePath(Str_Text(&path)).expand().withSeparators('/'); App_FileSystem().addPathLumpMapping(lumpName, destination); } - } while(*ch); + } while (*ch); // Success. successful = true; @@ -143,7 +143,7 @@ void FS_InitPathLumpMappings() // Free old paths, if any. App_FileSystem().clearPathLumpMappings(); - if(DoomsdayApp::app().isShuttingDown()) return; + if (DoomsdayApp::app().isShuttingDown()) return; size_t bufSize = 0; uint8_t *buf = 0; @@ -159,7 +159,7 @@ void FS_InitPathLumpMappings() FileInfo const &lumpInfo = lump.info(); // Make a copy of it so we can ensure it ends in a null. - if(bufSize < lumpInfo.size + 1) + if (bufSize < lumpInfo.size + 1) { bufSize = lumpInfo.size + 1; buf = (uint8_t *) M_Realloc(buf, bufSize); diff --git a/doomsday/apps/libdoomsday/src/filesys/wad.cpp b/doomsday/apps/libdoomsday/src/filesys/wad.cpp index eee3a52f55..a74bb969c6 100644 --- a/doomsday/apps/libdoomsday/src/filesys/wad.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/wad.cpp @@ -45,7 +45,7 @@ struct FileHeader { uint8_t buf[12]; dsize readBytes = from.read(buf, 12); - if(readBytes != 12) throw ReadError("FileHeader::operator << (FileHandle &)", "Source file is truncated"); + if (readBytes != 12) throw ReadError("FileHeader::operator << (FileHandle &)", "Source file is truncated"); identification = Block(buf, 4); lumpRecordsCount = littleEndianByteOrder.toNative(*(dint32 *)(buf + 4)); @@ -65,7 +65,7 @@ struct IndexEntry { uint8_t buf[16]; dsize readBytes = from.read(buf, 16); - if(readBytes != 16) throw ReadError("IndexEntry::operator << (FileHandle &)", "Source file is truncated"); + if (readBytes != 16) throw ReadError("IndexEntry::operator << (FileHandle &)", "Source file is truncated"); name = Block(buf + 8, 8); offset = littleEndianByteOrder.toNative(*(dint32 *)(buf)); @@ -79,9 +79,9 @@ struct IndexEntry // Determine the actual length of the name. int nameLen = 0; - while(nameLen < 8 && name[nameLen]) { nameLen++; } + while (nameLen < 8 && name[nameLen]) { nameLen++; } - for(int i = 0; i < nameLen; ++i) + for (int i = 0; i < nameLen; ++i) { /// The Hexen demo on Mac uses the 0x80 on some lumps, maybe has significance? /// @todo Ensure that this doesn't break other IWADs. The 0x80-0xff @@ -92,7 +92,7 @@ struct IndexEntry // WAD format allows characters not normally permitted in native paths. // To achieve uniformity we apply a percent encoding to the "raw" names. - if(!normName.isEmpty()) + if (!normName.isEmpty()) { normName = QString(normName.toLatin1().toPercentEncoding()); } @@ -104,7 +104,7 @@ struct IndexEntry } // All lumps are ordained with an extension if they don't have one. - if(normName.fileNameExtension().isEmpty()) + if (normName.fileNameExtension().isEmpty()) { normName += !normName.compareWithoutCase("DEHACKED")? ".deh" : ".lmp"; } @@ -116,7 +116,7 @@ struct IndexEntry static QString invalidIndexMessage(int invalidIdx, int lastValidIdx) { QString msg = QString("Invalid lump index %1 ").arg(invalidIdx); - if(lastValidIdx < 0) msg += "(file is empty)"; + if (lastValidIdx < 0) msg += "(file is empty)"; else msg += QString("(valid range: [0..%2])").arg(lastValidIdx); return msg; } @@ -193,11 +193,11 @@ Wad::Wad(FileHandle &hndl, String path, FileInfo const &info, File1 *container) hdr << *handle_; // Read the lump entries: - if(hdr.lumpRecordsCount <= 0) return; + if (hdr.lumpRecordsCount <= 0) return; // Seek to the start of the lump index. handle_->seek(hdr.lumpRecordsOffset, SeekSet); - for(int i = 0; i < hdr.lumpRecordsCount; ++i) + for (int i = 0; i < hdr.lumpRecordsCount; ++i) { IndexEntry lump; lump << *handle_; @@ -229,11 +229,11 @@ void Wad::clearCachedLump(int lumpIndex, bool *retCleared) { LOG_AS("Wad::clearCachedLump"); - if(retCleared) *retCleared = false; + if (retCleared) *retCleared = false; - if(hasLump(lumpIndex)) + if (hasLump(lumpIndex)) { - if(!d->dataCache.isNull()) + if (!d->dataCache.isNull()) { d->dataCache->remove(lumpIndex, retCleared); } @@ -247,7 +247,7 @@ void Wad::clearCachedLump(int lumpIndex, bool *retCleared) void Wad::clearLumpCache() { LOG_AS("Wad::clearLumpCache"); - if(!d->dataCache.isNull()) + if (!d->dataCache.isNull()) { d->dataCache->clear(); } @@ -265,16 +265,16 @@ uint8_t const *Wad::cacheLump(int lumpIndex) << (lumpFile.info().isCompressed()? ", compressed" : ""); // Time to create the cache? - if(d->dataCache.isNull()) + if (d->dataCache.isNull()) { d->dataCache.reset(new LumpCache(LumpIndex::size())); } uint8_t const *data = d->dataCache->data(lumpIndex); - if(data) return data; + if (data) return data; uint8_t *region = (uint8_t *) Z_Malloc(lumpFile.info().size, PU_APPSTATIC, 0); - if(!region) throw Error("Wad::cacheLump", QString("Failed on allocation of %1 bytes for cache copy of lump #%2").arg(lumpFile.info().size).arg(lumpIndex)); + if (!region) throw Error("Wad::cacheLump", QString("Failed on allocation of %1 bytes for cache copy of lump #%2").arg(lumpFile.info().size).arg(lumpIndex)); readLump(lumpIndex, region, false); d->dataCache->insert(lumpIndex, region); @@ -289,9 +289,9 @@ void Wad::unlockLump(int lumpIndex) << NativePath(composePath()).pretty() << NativePath(lump(lumpIndex).composePath()).pretty(); - if(hasLump(lumpIndex)) + if (hasLump(lumpIndex)) { - if(!d->dataCache.isNull()) + if (!d->dataCache.isNull()) { d->dataCache->unlock(lumpIndex); } @@ -323,11 +323,11 @@ size_t Wad::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, << length; // Try to avoid a file system read by checking for a cached copy. - if(tryCache) + if (tryCache) { uint8_t const *data = (!d->dataCache.isNull() ? d->dataCache->data(lumpIndex) : 0); LOGDEV_RES_XVERBOSE("Cache %s on #%i") << (data? "hit" : "miss") << lumpIndex; - if(data) + if (data) { size_t readBytes = de::min(size_t(lumpFile.size()), length); std::memcpy(buffer, data + startOffset, readBytes); @@ -339,7 +339,7 @@ size_t Wad::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, size_t readBytes = handle_->read(buffer, length); /// @todo Do not check the read length here. - if(readBytes < length) + if (readBytes < length) throw Error("Wad::readLumpSection", QString("Only read %1 of %2 bytes of lump #%3").arg(readBytes).arg(length).arg(lumpIndex)); return readBytes; @@ -348,7 +348,7 @@ size_t Wad::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, uint Wad::calculateCRC() { uint crc = 0; - foreach(File1 *file, allLumps()) + foreach (File1 *file, allLumps()) { Entry &entry = static_cast(file->as().directoryNode()); entry.update(); @@ -371,13 +371,13 @@ bool Wad::recognise(FileHandle &file) hdr << file; readOk = true; } - catch(FileHeader::ReadError const &) + catch (FileHeader::ReadError const &) {} // Ignore // Return the stream to its original position. file.seek(initPos, SeekSet); - if(!readOk) return false; + if (!readOk) return false; return (hdr.identification == "IWAD" || hdr.identification == "PWAD"); } @@ -398,7 +398,7 @@ void Wad::Entry::update() crc = uint(file().size()); String const lumpName = Node::name(); int const nameLen = lumpName.length(); - for(int i = 0; i < nameLen; ++i) + for (int i = 0; i < nameLen; ++i) { crc += lumpName.at(i).unicode(); } diff --git a/doomsday/apps/libdoomsday/src/filesys/zip.cpp b/doomsday/apps/libdoomsday/src/filesys/zip.cpp index 9470fd5cd4..7604b1038d 100644 --- a/doomsday/apps/libdoomsday/src/filesys/zip.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/zip.cpp @@ -134,7 +134,7 @@ static bool readArchiveHeader(FileHandle &file, localfileheader_t &hdr) readBytes = file.read((uint8_t *)&hdr, sizeof(localfileheader_t)); // Return the stream to its original position. file.seek(initPos, SeekSet); - if(!(readBytes < sizeof(localfileheader_t))) + if (!(readBytes < sizeof(localfileheader_t))) { hdr.signature = littleEndianByteOrder.toNative(hdr.signature); hdr.requiredVersion = littleEndianByteOrder.toNative(hdr.requiredVersion); @@ -166,7 +166,7 @@ typedef struct centralend_s { static bool readCentralEnd(FileHandle &file, centralend_t &end) { size_t readBytes = file.read((uint8_t *)&end, sizeof(centralend_t)); - if(!(readBytes < sizeof(centralend_t))) + if (!(readBytes < sizeof(centralend_t))) { end.disk = littleEndianByteOrder.toNative(end.disk); end.centralStartDisk= littleEndianByteOrder.toNative(end.centralStartDisk); @@ -183,7 +183,7 @@ static bool readCentralEnd(FileHandle &file, centralend_t &end) static String invalidIndexMessage(int invalidIdx, int lastValidIdx) { String msg = String("Invalid lump index %1").arg(invalidIdx); - if(lastValidIdx < 0) msg += " (file is empty)"; + if (lastValidIdx < 0) msg += " (file is empty)"; else msg += String(", valid range: [0..%2)").arg(lastValidIdx); return msg; } @@ -199,29 +199,29 @@ static String invalidIndexMessage(int invalidIdx, int lastValidIdx) static bool applyGamePathMappings(String &path) { // Manually mapped to Defs? - if(path.beginsWith('@')) + if (path.beginsWith('@')) { path.remove(0, 1); - if(path.at(0) == '/') path.remove(0, 1); + if (path.at(0) == '/') path.remove(0, 1); path = String("$(App.DefsPath)/$(GamePlugin.Name)/auto") / path; return true; } // Manually mapped to Data? - if(path.beginsWith('#')) + if (path.beginsWith('#')) { path.remove(0, 1); - if(path.at(0) == '/') path.remove(0, 1); + if (path.at(0) == '/') path.remove(0, 1); // Is there a prefix to be omitted in the name? - if(int slash = path.lastIndexOf('/')) + if (int slash = path.lastIndexOf('/')) { // The slash must not be too early in the string. - if(slash >= 2) + if (slash >= 2) { // Good old negative indices. - if(path.at(slash - 2) == '.' && path.at(slash - 1) >= '1' && path.at(slash - 1) <= '9') + if (path.at(slash - 2) == '.' && path.at(slash - 1) >= '1' && path.at(slash - 1) <= '9') path.remove(slash - 2, 2); } } @@ -231,12 +231,12 @@ static bool applyGamePathMappings(String &path) } // Implicitly mapped to another location? - if(!path.contains('/')) + if (!path.contains('/')) { // No directory separators; i.e., a root file. FileType const &ftype = DD_GuessFileTypeFromFileName(path.fileName()); - switch(ftype.defaultClass()) + switch (ftype.defaultClass()) { case RC_PACKAGE: // Mapped to the Data directory. @@ -257,7 +257,7 @@ static bool applyGamePathMappings(String &path) FS1::Schemes const &schemes = App_FileSystem().allSchemes(); DENG2_FOR_EACH_CONST(FS1::Schemes, i, schemes) { - if((*i)->mapPath(path)) + if ((*i)->mapPath(path)) { return true; } @@ -336,11 +336,11 @@ DENG2_PIMPL(Zip) FileInfo const &lumpInfo = lump.info(); self.handle_->seek(lumpInfo.baseOffset, SeekSet); - if(lumpInfo.isCompressed()) + if (lumpInfo.isCompressed()) { bool result; uint8_t *compressedData = (uint8_t *) M_Malloc(lumpInfo.compressedSize); - if(!compressedData) throw Error("Zip::bufferLump", QString("Failed on allocation of %1 bytes for decompression buffer").arg(lumpInfo.compressedSize)); + if (!compressedData) throw Error("Zip::bufferLump", QString("Failed on allocation of %1 bytes for decompression buffer").arg(lumpInfo.compressedSize)); // Read the compressed data into a temporary buffer for decompression. self.handle_->read(compressedData, lumpInfo.compressedSize); @@ -349,7 +349,7 @@ DENG2_PIMPL(Zip) result = uncompressRaw(compressedData, lumpInfo.compressedSize, buffer, lumpInfo.size); M_Free(compressedData); - if(!result) return 0; // Inflate failed. + if (!result) return 0; // Inflate failed. } else { @@ -372,13 +372,13 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) { int pos = CENTRAL_END_SIZE; // Offset from the end. uint32_t signature; - while(!foundCentralDirectory && pos < MAXIMUM_COMMENT_SIZE) + while (!foundCentralDirectory && pos < MAXIMUM_COMMENT_SIZE) { handle_->seek(-pos, SeekEnd); // Is this the signature? handle_->read((uint8_t *)&signature, sizeof(signature)); - if(littleEndianByteOrder.toNative(signature) == SIG_END_OF_CENTRAL_DIR) + if (littleEndianByteOrder.toNative(signature) == SIG_END_OF_CENTRAL_DIR) { foundCentralDirectory = true; // Yes, this is it. } @@ -390,7 +390,7 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) } } - if(!foundCentralDirectory) + if (!foundCentralDirectory) throw FormatError("Zip", "Central directory in \"" + NativePath(composePath()).pretty() + "\" not found"); // Read the central directory end record. @@ -398,14 +398,14 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) readCentralEnd(*handle_, summary); // Does the summary say something we don't like? - if(summary.diskEntryCount != summary.totalEntryCount) + if (summary.diskEntryCount != summary.totalEntryCount) throw FormatError("Zip", "Multipart zip file \"" + NativePath(composePath()).pretty() + "\" not supported"); // We'll load the file directory using one continous read into a temporary // local buffer before we process it into our runtime representation. // Read the entire central directory into memory. void *centralDirectory = M_Malloc(summary.size); - if(!centralDirectory) throw FormatError("Zip", String("Failed on allocation of %1 bytes for temporary copy of the central centralDirectory").arg(summary.size)); + if (!centralDirectory) throw FormatError("Zip", String("Failed on allocation of %1 bytes for temporary copy of the central centralDirectory").arg(summary.size)); handle_->seek(summary.offset, SeekSet); handle_->read((uint8_t *)centralDirectory, summary.size); @@ -416,11 +416,11 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) */ char *pos; int entryCount = 0; - for(int pass = 0; pass < 2; ++pass) + for (int pass = 0; pass < 2; ++pass) { - if(pass == 1) + if (pass == 1) { - if(entryCount == 0) break; + if (entryCount == 0) break; } // Position the read cursor at the start of the buffered central centralDirectory. @@ -428,7 +428,7 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) // Read all the entries. uint lumpIdx = 0; - for(int index = 0; index < summary.totalEntryCount; ++index, pos += sizeof(centralfileheader_t)) + for (int index = 0; index < summary.totalEntryCount; ++index, pos += sizeof(centralfileheader_t)) { centralfileheader_t const *header = (centralfileheader_t *) pos; char const *nameStart = pos + sizeof(centralfileheader_t); @@ -440,25 +440,25 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) String filePath = NativePath(nameStart, DD_USHORT(header->fileNameSize)).withSeparators('/'); // Skip directories (we don't presently model these). - if(DD_ULONG(header->size) == 0 && filePath.last() == '/') continue; + if (DD_ULONG(header->size) == 0 && filePath.last() == '/') continue; // Do we support the format of this lump? - if(DD_USHORT(header->compression) != ZFC_NO_COMPRESSION && + if (DD_USHORT(header->compression) != ZFC_NO_COMPRESSION && DD_USHORT(header->compression) != ZFC_DEFLATED) { - if(pass != 0) continue; + if (pass != 0) continue; LOG_RES_WARNING("Zip %s:'%s' uses an unsupported compression algorithm") << NativePath(composePath()).pretty() << NativePath(filePath).pretty(); } - if(DD_USHORT(header->flags) & ZFH_ENCRYPTED) + if (DD_USHORT(header->flags) & ZFH_ENCRYPTED) { - if(pass != 0) continue; + if (pass != 0) continue; LOG_RES_WARNING("Zip %s:'%s' is encrypted; encryption is not supported") << NativePath(composePath()).pretty() << NativePath(filePath).pretty(); } - if(pass == 0) + if (pass == 0) { // Another record will be needed. ++entryCount; @@ -473,7 +473,7 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) + DD_USHORT(header->fileNameSize) + DD_USHORT(localHeader.extraFieldSize); size_t compressedSize; - if(DD_USHORT(header->compression) == ZFC_DEFLATED) + if (DD_USHORT(header->compression) == ZFC_DEFLATED) { // Compressed using the deflate algorithm. compressedSize = DD_ULONG(header->compressedSize); @@ -483,19 +483,19 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) compressedSize = DD_ULONG(header->size); } - if(!DoomsdayApp::game().isNull()) + if (!DoomsdayApp::game().isNull()) { // In some cases the path to the file is mapped to some // other location in the virtual file system. String filePathCopy = filePath; - if(applyGamePathMappings(filePathCopy)) + if (applyGamePathMappings(filePathCopy)) { try { // Resolve all symbolic references in the path. filePath = Uri(filePathCopy, RC_NULL).resolved(); } - catch(de::Uri::ResolveError const& er) + catch (de::Uri::ResolveError const& er) { LOG_RES_WARNING(er.asText()); } @@ -533,11 +533,11 @@ void Zip::clearCachedLump(int lumpIndex, bool *retCleared) { LOG_AS("Zip::clearCachedLump"); - if(retCleared) *retCleared = false; + if (retCleared) *retCleared = false; - if(hasLump(lumpIndex)) + if (hasLump(lumpIndex)) { - if(!d->dataCache.isNull()) + if (!d->dataCache.isNull()) { d->dataCache->remove(lumpIndex, retCleared); } @@ -551,7 +551,7 @@ void Zip::clearCachedLump(int lumpIndex, bool *retCleared) void Zip::clearLumpCache() { LOG_AS("Zip::clearLumpCache"); - if(!d->dataCache.isNull()) + if (!d->dataCache.isNull()) { d->dataCache->clear(); } @@ -569,16 +569,16 @@ uint8_t const *Zip::cacheLump(int lumpIndex) << (lumpFile.info().isCompressed()? ", compressed" : ""); // Time to create the cache? - if(d->dataCache.isNull()) + if (d->dataCache.isNull()) { d->dataCache.reset(new LumpCache(lumpCount())); } uint8_t const *data = d->dataCache->data(lumpIndex); - if(data) return data; + if (data) return data; uint8_t *region = (uint8_t *) Z_Malloc(lumpFile.info().size, PU_APPSTATIC, 0); - if(!region) throw Error("Zip::cacheLump", QString("Failed on allocation of %1 bytes for cache copy of lump #%2").arg(lumpFile.info().size).arg(lumpIndex)); + if (!region) throw Error("Zip::cacheLump", QString("Failed on allocation of %1 bytes for cache copy of lump #%2").arg(lumpFile.info().size).arg(lumpIndex)); readLump(lumpIndex, region, false); d->dataCache->insert(lumpIndex, region); @@ -593,9 +593,9 @@ void Zip::unlockLump(int lumpIndex) << NativePath(composePath()).pretty() << NativePath(lump(lumpIndex).composePath()).pretty(); - if(hasLump(lumpIndex)) + if (hasLump(lumpIndex)) { - if(!d->dataCache.isNull()) + if (!d->dataCache.isNull()) { d->dataCache->unlock(lumpIndex); } @@ -627,11 +627,11 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, << length; // Try to avoid a file system read by checking for a cached copy. - if(tryCache) + if (tryCache) { uint8_t const *data = (!d->dataCache.isNull() ? d->dataCache->data(lumpIndex) : 0); LOGDEV_RES_XVERBOSE("Cache %s on #%i") << (data? "hit" : "miss") << lumpIndex; - if(data) + if (data) { size_t readBytes = de::min(size_t(lumpFile.size()), length); std::memcpy(buffer, data + startOffset, readBytes); @@ -640,7 +640,7 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, } size_t readBytes = 0; - if(!startOffset && length == lumpFile.size()) + if (!startOffset && length == lumpFile.size()) { // Read it straight to the caller's data buffer. readBytes = d->bufferLump(lumpFile, buffer); @@ -649,9 +649,9 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, { // Allocate a temporary buffer and read the whole lump into it(!). uint8_t *readBuf = (uint8_t *) M_Malloc(lumpFile.size()); - if(!readBuf) throw Error("Zip::readLump", QString("Failed on allocation of %1 bytes for work buffer").arg(lumpFile.size())); + if (!readBuf) throw Error("Zip::readLump", QString("Failed on allocation of %1 bytes for work buffer").arg(lumpFile.size())); - if(d->bufferLump(lumpFile, readBuf)) + if (d->bufferLump(lumpFile, readBuf)) { readBytes = de::min(size_t(lumpFile.size()), length); std::memcpy(buffer, readBuf + startOffset, readBytes); @@ -661,7 +661,7 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, } /// @todo Do not check the read length here. - if(readBytes < de::min(size_t(lumpFile.size()), length)) + if (readBytes < de::min(size_t(lumpFile.size()), length)) throw Error("Zip::readLump", QString("Only read %1 of %2 bytes of lump #%3").arg(readBytes).arg(length).arg(lumpIndex)); return readBytes; @@ -670,7 +670,7 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, bool Zip::recognise(FileHandle &file) { localfileheader_t hdr; - if(!readArchiveHeader(file, hdr)) return false; + if (!readArchiveHeader(file, hdr)) return false; return hdr.signature == SIG_LOCAL_FILE_HEADER; } @@ -702,16 +702,16 @@ uint8_t *Zip::compressAtLevel(uint8_t *in, size_t inSize, size_t *outSize, int l stream.zfree = Z_NULL; stream.opaque = Z_NULL; - if(level < Z_NO_COMPRESSION) + if (level < Z_NO_COMPRESSION) { level = Z_NO_COMPRESSION; } - if(level > Z_BEST_COMPRESSION) + if (level > Z_BEST_COMPRESSION) { level = Z_BEST_COMPRESSION; } result = deflateInit(&stream, level); - if(result != Z_OK) + if (result != Z_OK) { M_Free(output); return 0; @@ -723,17 +723,17 @@ uint8_t *Zip::compressAtLevel(uint8_t *in, size_t inSize, size_t *outSize, int l stream.next_out = chunk; stream.avail_out = CHUNK_SIZE; result = deflate(&stream, Z_FINISH); - if(result == Z_STREAM_ERROR) + if (result == Z_STREAM_ERROR) { M_Free(output); *outSize = 0; return 0; } have = CHUNK_SIZE - stream.avail_out; - if(have) + if (have) { // Need more memory? - if(*outSize + have > allocSize) + if (*outSize + have > allocSize) { // Need more memory. allocSize *= 2; @@ -743,7 +743,7 @@ uint8_t *Zip::compressAtLevel(uint8_t *in, size_t inSize, size_t *outSize, int l std::memcpy(output + *outSize, chunk, have); *outSize += have; } - } while(!stream.avail_out); // output chunk full, more data may follow + } while (!stream.avail_out); // output chunk full, more data may follow DENG2_ASSERT(result == Z_STREAM_END); DENG2_ASSERT(stream.total_out == *outSize); @@ -775,7 +775,7 @@ uint8_t *Zip::uncompress(uint8_t *in, size_t inSize, size_t *outSize) stream.avail_in = (uInt) inSize; result = inflateInit(&stream); - if(result != Z_OK) + if (result != Z_OK) { M_Free(output); return 0; @@ -787,17 +787,17 @@ uint8_t *Zip::uncompress(uint8_t *in, size_t inSize, size_t *outSize) stream.next_out = chunk; stream.avail_out = INF_CHUNK_SIZE; result = inflate(&stream, Z_FINISH); - if(result == Z_STREAM_ERROR) + if (result == Z_STREAM_ERROR) { M_Free(output); *outSize = 0; return 0; } have = INF_CHUNK_SIZE - stream.avail_out; - if(have) + if (have) { // Need more memory? - if(*outSize + have > allocSize) + if (*outSize + have > allocSize) { // Need more memory. allocSize *= 2; @@ -807,7 +807,7 @@ uint8_t *Zip::uncompress(uint8_t *in, size_t inSize, size_t *outSize) std::memcpy(output + *outSize, chunk, have); *outSize += have; } - } while(!stream.avail_out); // output chunk full, more data may follow + } while (!stream.avail_out); // output chunk full, more data may follow // We should now be at the end. DENG2_ASSERT(result == Z_STREAM_END); @@ -832,13 +832,13 @@ bool Zip::uncompressRaw(uint8_t *in, size_t inSize, uint8_t *out, size_t outSize stream.next_out = (Bytef *) out; stream.avail_out = (uInt) outSize; - if(inflateInit2(&stream, -MAX_WBITS) != Z_OK) + if (inflateInit2(&stream, -MAX_WBITS) != Z_OK) return false; // Do the inflation in one call. result = inflate(&stream, Z_FINISH); - if(stream.total_out != outSize) + if (stream.total_out != outSize) { inflateEnd(&stream); LOG_RES_WARNING("Failure due to %s (result code: %i)") diff --git a/doomsday/apps/libdoomsday/src/game.cpp b/doomsday/apps/libdoomsday/src/game.cpp index 0a8d3993f6..4b7a926d5c 100644 --- a/doomsday/apps/libdoomsday/src/game.cpp +++ b/doomsday/apps/libdoomsday/src/game.cpp @@ -65,11 +65,11 @@ DENG2_PIMPL(Game) , params(parms) { // Define the optional parameters if needed. - if(!params.has(DEF_CONFIG_MAIN_PATH)) + if (!params.has(DEF_CONFIG_MAIN_PATH)) { params.set(DEF_CONFIG_MAIN_PATH, "/home/configs"/params.gets(DEF_CONFIG_DIR)/"game.cfg"); } - if(!params.has(DEF_CONFIG_BINDINGS_PATH)) + if (!params.has(DEF_CONFIG_BINDINGS_PATH)) { params.set(DEF_CONFIG_BINDINGS_PATH, "/home/configs"/params.gets(DEF_CONFIG_DIR)/"player/bindings.cfg"); } @@ -85,7 +85,7 @@ DENG2_PIMPL(Game) StringList packagesFromProfile() const { auto const *profile = DoomsdayApp::gameProfiles().tryFind(self.title())->maybeAs(); - if(profile) + if (profile) { return profile->packages(); } @@ -120,14 +120,14 @@ String Game::variantOf() const String Game::family() const { - if(d->params.has(DEF_FAMILY)) + if (d->params.has(DEF_FAMILY)) { return d->params.gets(DEF_FAMILY); } // We can make a guess... - if(id().contains("doom")) return "doom"; - if(id().contains("heretic")) return "heretic"; - if(id().contains("hexen")) return "hexen"; + if (id().contains("doom")) return "doom"; + if (id().contains("heretic")) return "heretic"; + if (id().contains("hexen")) return "hexen"; return ""; } @@ -150,7 +150,7 @@ void Game::addManifest(ResourceManifest &manifest) { // Ensure we don't add duplicates. Manifests::const_iterator found = d->manifests.find(manifest.resourceClass(), &manifest); - if(found == d->manifests.end()) + if (found == d->manifests.end()) { d->manifests.insert(manifest.resourceClass(), &manifest); } @@ -158,17 +158,17 @@ void Game::addManifest(ResourceManifest &manifest) bool Game::allStartupFilesFound() const { - for(String const &pkg : d->requiredPackages + d->packagesFromProfile()) + for (String const &pkg : d->requiredPackages + d->packagesFromProfile()) { - if(!App::packageLoader().isAvailable(pkg)) + if (!App::packageLoader().isAvailable(pkg)) return false; } - foreach(ResourceManifest *manifest, d->manifests) + foreach (ResourceManifest *manifest, d->manifests) { int const flags = manifest->fileFlags(); - if((flags & FF_STARTUP) && !(flags & FF_FOUND)) + if ((flags & FF_STARTUP) && !(flags & FF_FOUND)) return false; } return true; @@ -181,11 +181,11 @@ bool Game::isPlayable() const Game::Status Game::status() const { - if(App_GameLoaded() && &DoomsdayApp::currentGame() == this) + if (App_GameLoaded() && &DoomsdayApp::currentGame() == this) { return Loaded; } - if(allStartupFilesFound()) + if (allStartupFilesFound()) { return Complete; } @@ -240,11 +240,11 @@ String Game::logoImageForId(String const &id) { /// @todo The name of the plugin should be accessible via the plugin loader. String plugName; - if(id.contains("heretic")) + if (id.contains("heretic")) { plugName = "libheretic"; } - else if(id.contains("hexen")) + else if (id.contains("hexen")) { plugName = "libhexen"; } @@ -264,17 +264,17 @@ String Game::legacySavegameNameExp() const String Game::legacySavegamePath() const { NativePath nativeSavePath = Resources::get().nativeSavePath(); - if(nativeSavePath.isEmpty()) return ""; - if(isNull()) return ""; + if (nativeSavePath.isEmpty()) return ""; + if (isNull()) return ""; - if(App::commandLine().has("-savedir")) + if (App::commandLine().has("-savedir")) { // A custom path. The savegames are in the root of this folder. return nativeSavePath; } // The default save path. The savegames are in a game-specific folder. - if(!d->params.gets(DEF_LEGACYSAVEGAME_SUBFOLDER, "").isEmpty()) + if (!d->params.gets(DEF_LEGACYSAVEGAME_SUBFOLDER, "").isEmpty()) { return App::app().nativeHomePath() / d->params.gets(DEF_LEGACYSAVEGAME_SUBFOLDER) / id(); } @@ -322,19 +322,19 @@ bool Game::isRequiredFile(File1 &file) const // If this resource is from a container we must use the path of the // root file container instead. File1 &rootFile = file; - while(rootFile.isContained()) + while (rootFile.isContained()) { rootFile = rootFile.container(); } String absolutePath = rootFile.composePath(); bool isRequired = false; - for(Manifests::const_iterator i = d->manifests.find(RC_PACKAGE); + for (Manifests::const_iterator i = d->manifests.find(RC_PACKAGE); i != d->manifests.end() && i.key() == RC_PACKAGE; ++i) { ResourceManifest &manifest = **i; - if(!(manifest.fileFlags() & FF_STARTUP)) continue; + if (!(manifest.fileFlags() & FF_STARTUP)) continue; - if(!manifest.resolvedPath(true/*try locate*/).compare(absolutePath, Qt::CaseInsensitive)) + if (!manifest.resolvedPath(true/*try locate*/).compare(absolutePath, Qt::CaseInsensitive)) { isRequired = true; break; @@ -347,13 +347,13 @@ bool Game::isRequiredFile(File1 &file) const void Game::addResource(resourceclassid_t classId, dint rflags, char const *names, void const *params) { - if(!VALID_RESOURCECLASSID(classId)) + if (!VALID_RESOURCECLASSID(classId)) { throw Error("Game::addResource", "Unknown resource class " + QString::number(classId)); } - if(!names || !names[0]) + if (!names || !names[0]) { throw Error("Game::addResource", "Invalid name argument"); } @@ -364,16 +364,16 @@ void Game::addResource(resourceclassid_t classId, dint rflags, // Add the name list to the resource record. QStringList nameList = String(names).split(";", QString::SkipEmptyParts); - foreach(QString const &nameRef, nameList) + foreach (QString const &nameRef, nameList) { manifest->addName(nameRef); } - if(params && classId == RC_PACKAGE) + if (params && classId == RC_PACKAGE) { // Add the identityKey list to the resource record. QStringList idKeys = String((char const *) params).split(";", QString::SkipEmptyParts); - foreach(QString const &idKeyRef, idKeys) + foreach (QString const &idKeyRef, idKeys) { manifest->addIdentityKey(idKeyRef); } @@ -382,7 +382,7 @@ void Game::addResource(resourceclassid_t classId, dint rflags, void Game::loadPackages() const { - for(String const &id : d->requiredPackages + d->packagesFromProfile()) + for (String const &id : d->requiredPackages + d->packagesFromProfile()) { App::packageLoader().load(id); } @@ -391,7 +391,7 @@ void Game::loadPackages() const void Game::unloadPackages() const { StringList const allPackages = d->requiredPackages + d->packagesFromProfile(); - for(int i = allPackages.size() - 1; i >= 0; --i) + for (int i = allPackages.size() - 1; i >= 0; --i) { App::packageLoader().unload(allPackages.at(i)); } @@ -420,20 +420,20 @@ String Game::filesAsText(int rflags, bool withStatus) const // Group output by resource class. Manifests const &manifs = manifests(); - for(uint i = 0; i < RESOURCECLASS_COUNT; ++i) + for (uint i = 0; i < RESOURCECLASS_COUNT; ++i) { resourceclassid_t const classId = resourceclassid_t(i); - for(Manifests::const_iterator i = manifs.find(classId); + for (Manifests::const_iterator i = manifs.find(classId); i != manifs.end() && i.key() == classId; ++i) { ResourceManifest &manifest = **i; - if(rflags >= 0 && (rflags & manifest.fileFlags())) + if (rflags >= 0 && (rflags & manifest.fileFlags())) { bool const resourceFound = (manifest.fileFlags() & FF_FOUND) != 0; - if(!text.isEmpty()) text += "\n" _E(0); + if (!text.isEmpty()) text += "\n" _E(0); - if(withStatus) + if (withStatus) { text += (resourceFound? " - " : _E(1) " ! " _E(.)); } @@ -443,10 +443,10 @@ String Game::filesAsText(int rflags, bool withStatus) const .arg(!resourceFound? _E(D) : "") .arg(manifest.names().join(_E(l) " or " _E(.))); - if(withStatus) + if (withStatus) { text += String(": ") + _E(>) + (!resourceFound? _E(b) "missing " _E(.) : ""); - if(resourceFound) + if (resourceFound) { text += String(_E(C) "\"%1\"" _E(.)).arg(NativePath(manifest.resolvedPath(false/*don't try to locate*/)).expand().pretty()); } @@ -458,7 +458,7 @@ String Game::filesAsText(int rflags, bool withStatus) const } } - if(text.isEmpty()) return " none"; + if (text.isEmpty()) return " none"; return text; } @@ -473,10 +473,10 @@ D_CMD(InspectGame) DENG2_UNUSED(src); Game const *game = 0; - if(argc < 2) + if (argc < 2) { // No game identity key was specified - assume the current game. - if(!App_GameLoaded()) + if (!App_GameLoaded()) { LOG_WARNING("No game is currently loaded.\nPlease specify the identifier of the game to inspect."); return false; @@ -490,7 +490,7 @@ D_CMD(InspectGame) { game = &DoomsdayApp::games()[idKey]; } - catch(Games::NotFoundError const &) + catch (Games::NotFoundError const &) { LOG_WARNING("Unknown game '%s'") << idKey; return false; diff --git a/doomsday/apps/libdoomsday/src/game_init.cpp b/doomsday/apps/libdoomsday/src/game_init.cpp index 51e185f5d5..58b9e56c50 100644 --- a/doomsday/apps/libdoomsday/src/game_init.cpp +++ b/doomsday/apps/libdoomsday/src/game_init.cpp @@ -49,7 +49,7 @@ int beginGameChangeBusyWorker(void *context) DoomsdayApp::GameChangeParameters &parms = *(DoomsdayApp::GameChangeParameters *) context; P_InitMapEntityDefs(); - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress(200); } @@ -70,9 +70,9 @@ static File1 *tryLoadFile(de::Uri const &search, size_t baseOffset = 0) return &hndl.file(); } - catch(FS1::NotFoundError const&) + catch (FS1::NotFoundError const&) { - if(fs1.accessFile(search)) + if (fs1.accessFile(search)) { // Must already be loaded. LOG_RES_XVERBOSE("\"%s\" already loaded") << NativePath(search.asText()).pretty(); @@ -91,15 +91,15 @@ static void loadResource(ResourceManifest &manifest) DENG2_ASSERT(manifest.resourceClass() == RC_PACKAGE); de::Uri path(manifest.resolvedPath(false/*do not locate resource*/), RC_NULL); - if(path.isEmpty()) return; + if (path.isEmpty()) return; - if(File1 *file = tryLoadFile(path)) + if (File1 *file = tryLoadFile(path)) { // Mark this as an original game resource. file->setCustom(false); // Print the 'CRC' number of IWADs, so they can be identified. - if(Wad *wad = file->maybeAs()) + if (Wad *wad = file->maybeAs()) { LOG_RES_MSG("IWAD identification: %08x") << wad->calculateCRC(); } @@ -110,14 +110,14 @@ static void parseStartupFilePathsAndAddFiles(char const *pathString) { static char const *ATWSEPS = ",; \t"; - if(!pathString || !pathString[0]) return; + if (!pathString || !pathString[0]) return; size_t len = strlen(pathString); char *buffer = (char *) M_Malloc(len + 1); strcpy(buffer, pathString); char *token = strtok(buffer, ATWSEPS); - while(token) + while (token) { tryLoadFile(de::Uri(token, RC_NULL)); token = strtok(nullptr, ATWSEPS); @@ -128,14 +128,14 @@ static void parseStartupFilePathsAndAddFiles(char const *pathString) static dint addListFiles(QStringList const &list, FileType const &ftype) { dint numAdded = 0; - foreach(QString const &path, list) + foreach (QString const &path, list) { - if(&ftype != &DD_GuessFileTypeFromFileName(path)) + if (&ftype != &DD_GuessFileTypeFromFileName(path)) { continue; } - if(tryLoadFile(de::Uri(path, RC_NULL))) + if (tryLoadFile(de::Uri(path, RC_NULL))) { numAdded += 1; } @@ -152,12 +152,12 @@ int loadGameStartupResourcesBusyWorker(void *context) FS_InitVirtualPathMappings(); App_FileSystem().resetAllSchemes(); - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress(50); } - if(App_GameLoaded()) + if (App_GameLoaded()) { // Create default Auto mappings in the runtime directory. @@ -169,14 +169,14 @@ int loadGameStartupResourcesBusyWorker(void *context) } // Load data files. - for(DataBundle const *bundle : DoomsdayApp::bundles().loaded()) + for (DataBundle const *bundle : DoomsdayApp::bundles().loaded()) { LOG_RES_NOTE("Loading %s from %s") << bundle->description() << bundle->sourceFile().description(); - if(NativeFile const *nativeFile = bundle->sourceFile().maybeAs()) + if (NativeFile const *nativeFile = bundle->sourceFile().maybeAs()) { - if(File1 *file = File1::tryLoad(de::Uri::fromNativePath(nativeFile->nativePath()))) + if (File1 *file = File1::tryLoad(de::Uri::fromNativePath(nativeFile->nativePath()))) { file->setCustom(false); LOG_RES_VERBOSE("%s: ok") << nativeFile->nativePath(); @@ -195,25 +195,25 @@ int loadGameStartupResourcesBusyWorker(void *context) */ GameManifests const &gameManifests = DoomsdayApp::game().manifests(); int const numPackages = gameManifests.count(RC_PACKAGE); - if(numPackages) + if (numPackages) { LOG_RES_MSG("Loading game resources..."); int packageIdx = 0; - for(GameManifests::const_iterator i = gameManifests.find(RC_PACKAGE); + for (GameManifests::const_iterator i = gameManifests.find(RC_PACKAGE); i != gameManifests.end() && i.key() == RC_PACKAGE; ++i, ++packageIdx) { loadResource(**i); // Update our progress. - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress((packageIdx + 1) * (200 - 50) / numPackages - 1); } } } - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress(200); } @@ -238,7 +238,7 @@ static dint findAllGameDataPaths(FS1::PathList &found) #endif }; dint const numFoundSoFar = found.count(); - for(String const &ext : extensions) + for (String const &ext : extensions) { DENG2_ASSERT(!ext.isEmpty()); String const searchPath = de::Uri(Path("$(App.DataPath)/$(GamePlugin.Name)/auto/*." + ext)).resolved(); @@ -261,9 +261,9 @@ static dint loadFilesFromDataGameAuto() DENG2_FOR_EACH_CONST(FS1::PathList, i, found) { // Ignore directories. - if(i->attrib & A_SUBDIR) continue; + if (i->attrib & A_SUBDIR) continue; - if(tryLoadFile(de::Uri(i->path, RC_NULL))) + if (tryLoadFile(de::Uri(i->path, RC_NULL))) { numLoaded += 1; } @@ -281,7 +281,7 @@ static void autoLoadFiles() * exist in the auto-load directory. */ dint numNewFiles; - while((numNewFiles = loadFilesFromDataGameAuto()) > 0) + while ((numNewFiles = loadFilesFromDataGameAuto()) > 0) { LOG_RES_VERBOSE("Autoload round completed with %i new files") << numNewFiles; } @@ -293,7 +293,7 @@ int loadAddonResourcesBusyWorker(void *context) /* // User-selected files specified in the game itself. - for(String const &path : DoomsdayApp::game().userFiles()) + for (String const &path : DoomsdayApp::game().userFiles()) { NativePath const nativePath(path); Session::profile().resourceFiles << nativePath.withSeparators('/'); @@ -305,17 +305,17 @@ int loadAddonResourcesBusyWorker(void *context) * Add additional game-startup files. * @note These must take precedence over Auto but not game-resource files. */ - if(startupFiles && startupFiles[0]) + if (startupFiles && startupFiles[0]) { parseStartupFilePathsAndAddFiles(startupFiles); } - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress(50); } - if(App_GameLoaded()) + if (App_GameLoaded()) { /** * Phase 3: Add real files from the Auto directory. @@ -327,13 +327,13 @@ int loadAddonResourcesBusyWorker(void *context) DENG2_FOR_EACH_CONST(FS1::PathList, i, found) { // Ignore directories. - if(i->attrib & A_SUBDIR) continue; + if (i->attrib & A_SUBDIR) continue; /// @todo Is expansion of symbolics still necessary here? prof.resourceFiles << NativePath(i->path).expand().withSeparators('/'); } - if(!prof.resourceFiles.isEmpty()) + if (!prof.resourceFiles.isEmpty()) { // First ZIPs then WADs (they may contain WAD files). addListFiles(prof.resourceFiles, DD_FileTypeByName("FT_ZIP")); @@ -344,7 +344,7 @@ int loadAddonResourcesBusyWorker(void *context) autoLoadFiles(); } - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress(180); } @@ -355,7 +355,7 @@ int loadAddonResourcesBusyWorker(void *context) // on existing search paths (probably that is). App_FileSystem().resetAllSchemes(); - if(parms.initiatedBusyMode) + if (parms.initiatedBusyMode) { updateProgress(200); } diff --git a/doomsday/apps/libdoomsday/src/gameprofiles.cpp b/doomsday/apps/libdoomsday/src/gameprofiles.cpp index 15c9d7628b..f73302bd1a 100644 --- a/doomsday/apps/libdoomsday/src/gameprofiles.cpp +++ b/doomsday/apps/libdoomsday/src/gameprofiles.cpp @@ -42,7 +42,7 @@ DENG2_PIMPL(GameProfiles) * configuration for each game is persistently stored using these profiles. * (User-created profiles must use different names.) */ - if(!self.tryFind(game.title())) + if (!self.tryFind(game.title())) { auto *prof = new Profile(game.title()); prof->setGame(game.id()); @@ -66,7 +66,7 @@ LoopResult GameProfiles::forAll(std::function func) { return Profiles::forAll([&func] (AbstractProfile &prof) -> LoopResult { - if(auto result = func(prof.as())) + if (auto result = func(prof.as())) { return result; } @@ -80,10 +80,10 @@ Profiles::AbstractProfile *GameProfiles::profileFromInfoBlock(Info::BlockElement prof->setGame(block.keyValue(VAR_GAME).text); - if(Info::ListElement const *pkgs = block.findAs(VAR_PACKAGES)) + if (Info::ListElement const *pkgs = block.findAs(VAR_PACKAGES)) { StringList ids; - for(auto const &val : pkgs->values()) ids << val.text; + for (auto const &val : pkgs->values()) ids << val.text; prof->setPackages(ids); } @@ -158,7 +158,7 @@ StringList GameProfiles::Profile::allRequiredPackages() const bool GameProfiles::Profile::resetToDefaults() { - if(isReadOnly()) return false; + if (isReadOnly()) return false; d->packages.clear(); return true; diff --git a/doomsday/apps/libdoomsday/src/games.cpp b/doomsday/apps/libdoomsday/src/games.cpp index e9372d1e14..7bf4749691 100644 --- a/doomsday/apps/libdoomsday/src/games.cpp +++ b/doomsday/apps/libdoomsday/src/games.cpp @@ -107,7 +107,7 @@ DENG2_PIMPL(Games) Game *findById(String id) const { auto found = idLookup.constFind(id.toLower()); - if(found != idLookup.constEnd()) + if (found != idLookup.constEnd()) { return found.value(); } @@ -134,9 +134,9 @@ Game &Games::nullGame() const int Games::numPlayable() const { int count = 0; - foreach(Game *game, d->games) + foreach (Game *game, d->games) { - if(game->allStartupFilesFound()) + if (game->allStartupFilesFound()) { count += 1; } @@ -146,16 +146,16 @@ int Games::numPlayable() const Game *Games::firstPlayable() const { - foreach(Game *game, d->games) + foreach (Game *game, d->games) { - if(game->allStartupFilesFound()) return game; + if (game->allStartupFilesFound()) return game; } return NULL; } Game &Games::operator [] (String const &id) const { - if(auto *game = d->findById(id)) + if (auto *game = d->findById(id)) { return *game; } @@ -171,7 +171,7 @@ bool Games::contains(String const &id) const Game &Games::byIndex(int idx) const { - if(idx < 0 || idx > d->games.count()) + if (idx < 0 || idx > d->games.count()) { /// @throw NotFoundError No game is associated with index @a idx. throw NotFoundError("Games::byIndex", QString("There is no Game at index %i").arg(idx)); @@ -192,7 +192,7 @@ Games::All const &Games::all() const int Games::collectAll(GameList &collected) { int numFoundSoFar = collected.count(); - foreach(Game *game, d->games) + foreach (Game *game, d->games) { collected.push_back(GameListItem(game)); } @@ -212,7 +212,7 @@ Game &Games::defineGame(String const &id, Record const ¶meters) << parameters.gets(Game::DEF_TITLE) << id; throw Error("Games::defineGame", String("Duplicate game ID: ") + id); } - catch(Games::NotFoundError const &) + catch (Games::NotFoundError const &) {} // Ignore the error. // Add this game to our records. @@ -227,7 +227,7 @@ void Games::locateStartupResources(Game &game) { Game *oldCurrentGame = &DoomsdayApp::currentGame(); - if(oldCurrentGame != &game) + if (oldCurrentGame != &game) { /// @attention Kludge: Temporarily switch Game. DoomsdayApp::setGame(game); @@ -237,16 +237,16 @@ void Games::locateStartupResources(Game &game) App_FileSystem().resetAllSchemes(); } - foreach(ResourceManifest *manifest, game.manifests()) + foreach (ResourceManifest *manifest, game.manifests()) { // We are only interested in startup resources at this time. - if(manifest->fileFlags() & FF_STARTUP) + if (manifest->fileFlags() & FF_STARTUP) { manifest->locateFile(); } } - if(oldCurrentGame != &game) + if (oldCurrentGame != &game) { // Kludge end - Restore the old Game. DoomsdayApp::setGame(*oldCurrentGame); @@ -260,9 +260,9 @@ void Games::locateStartupResources(Game &game) LoopResult Games::forAll(std::function callback) const { - foreach(Game *game, all()) + foreach (Game *game, all()) { - if(auto result = callback(*game)) + if (auto result = callback(*game)) { return result; } @@ -311,11 +311,11 @@ void Games::checkReadiness() /*void Games::forgetAllResources() { - foreach(Game *game, d->games) + foreach (Game *game, d->games) { - foreach(ResourceManifest *manifest, game->manifests()) + foreach (ResourceManifest *manifest, game->manifests()) { - if(manifest->fileFlags() & FF_STARTUP) + if (manifest->fileFlags() & FF_STARTUP) { manifest->forgetFile(); } @@ -328,7 +328,7 @@ D_CMD(ListGames) DENG2_UNUSED3(src, argc, argv); Games &games = DoomsdayApp::games(); - if(!games.count()) + if (!games.count()) { LOG_MSG("No games are currently registered."); return true; @@ -353,7 +353,7 @@ D_CMD(ListGames) Game *game = i->game; bool isCurrent = (&DoomsdayApp::currentGame() == game); - if(!list.isEmpty()) list += "\n"; + if (!list.isEmpty()) list += "\n"; list += String(_E(0) _E(Ta) "%1%2 " @@ -366,7 +366,7 @@ D_CMD(ListGames) .arg(game->title()) .arg(game->author()); - if(game->allStartupFilesFound()) + if (game->allStartupFilesFound()) { numCompleteGames++; } diff --git a/doomsday/apps/libdoomsday/src/help.cpp b/doomsday/apps/libdoomsday/src/help.cpp index 10f39c80ad..a13686c675 100644 --- a/doomsday/apps/libdoomsday/src/help.cpp +++ b/doomsday/apps/libdoomsday/src/help.cpp @@ -51,16 +51,16 @@ void Help_ReadStrings(File const &file) de::Reader reader(file); StringsByType *node = 0; - while(!reader.atEnd()) + while (!reader.atEnd()) { String line = reader.readLine().trimmed(); // Comments and empty lines are ignored. - if(line.isEmpty() || line.startsWith("#")) + if (line.isEmpty() || line.startsWith("#")) continue; // A new node? - if(line.startsWith("[")) + if (line.startsWith("[")) { int end = line.indexOf(']'); String id = line.mid(1, end > 0? end - 1 : -1).trimmed().toLower(); @@ -68,18 +68,18 @@ void Help_ReadStrings(File const &file) LOG_TRACE_DEBUGONLY("Help node '%s'", id); } - else if(node && line.contains('=')) // It must be a key? + else if (node && line.contains('=')) // It must be a key? { int type = HST_DESCRIPTION; - if(line.startsWith("cv", Qt::CaseInsensitive)) + if (line.startsWith("cv", Qt::CaseInsensitive)) { type = HST_CONSOLE_VARIABLE; } - else if(line.startsWith("def", Qt::CaseInsensitive)) + else if (line.startsWith("def", Qt::CaseInsensitive)) { type = HST_DEFAULT_VALUE; } - else if(line.startsWith("inf", Qt::CaseInsensitive)) + else if (line.startsWith("inf", Qt::CaseInsensitive)) { type = HST_INFO; } @@ -91,21 +91,21 @@ void Help_ReadStrings(File const &file) QString text; // The value may be split over multiple lines. - while(!line.isEmpty()) + while (!line.isEmpty()) { // Process the current line. bool escape = false; - foreach(QChar ch, line) + foreach (QChar ch, line) { - if(ch == QChar('\\')) + if (ch == QChar('\\')) { escape = true; } - else if(escape) + else if (escape) { if (ch == QChar('n') ) text = text % "\n"; - else if(ch == QChar('b') ) text = text % "\b"; - else if(ch == QChar('\\')) text = text % "\\"; + else if (ch == QChar('b') ) text = text % "\b"; + else if (ch == QChar('\\')) text = text % "\\"; escape = false; } else @@ -117,7 +117,7 @@ void Help_ReadStrings(File const &file) // This part has been processed. line.clear(); - if(escape) + if (escape) { // Line ended with a backslash; read the next line. line = reader.readLine().trimmed(); @@ -135,7 +135,7 @@ HelpId DH_Find(char const *id) { // The identifiers are case insensitive. HelpStrings::const_iterator found = helps.constFind(String(id).lower()); - if(found != helps.constEnd()) + if (found != helps.constEnd()) { return &found.value(); } @@ -144,13 +144,13 @@ HelpId DH_Find(char const *id) char const *DH_GetString(HelpId found, int type) { - if(!found) return 0; - if(type < 0 || type > NUM_HELPSTRING_TYPES) return 0; + if (!found) return 0; + if (type < 0 || type > NUM_HELPSTRING_TYPES) return 0; StringsByType const *hs = reinterpret_cast(found); StringsByType::const_iterator i = hs->constFind(type); - if(i != hs->constEnd()) + if (i != hs->constEnd()) { return Str_Text(AutoStr_FromTextStd(i.value().toUtf8().constData())); } @@ -165,7 +165,7 @@ void DD_InitHelp() Help_ReadStrings(App::packageLoader().package("net.dengine.base") .root().locate("helpstrings.txt")); } - catch(Error const &er) + catch (Error const &er) { LOG_RES_WARNING("") << er.asText(); } diff --git a/doomsday/apps/libdoomsday/src/library.cpp b/doomsday/apps/libdoomsday/src/library.cpp index 4ff9758254..e6b8b6ac6e 100644 --- a/doomsday/apps/libdoomsday/src/library.cpp +++ b/doomsday/apps/libdoomsday/src/library.cpp @@ -58,9 +58,9 @@ void Library_ReleaseGames() { #ifdef UNIX LOG_AS("Library_ReleaseGames"); - for(Library *lib : loadedLibs) + for (Library *lib : loadedLibs) { - if(lib->isGamePlugin) + if (lib->isGamePlugin) { LOGDEV_RES_VERBOSE("Closing '%s'") << Str_Text(lib->path); @@ -77,7 +77,7 @@ static void reopenLibraryIfNeeded(Library *lib) { DENG2_ASSERT(lib); - if(!lib->file->loaded()) + if (!lib->file->loaded()) { LOGDEV_RES_XVERBOSE("Re-opening '%s'") << Str_Text(lib->path); @@ -98,7 +98,7 @@ Library *Library_New(char const *filePath) Str_Clear(lastError); auto &libFile = de::App::rootFolder().locate(filePath); - if(libFile.library().type() == de::Library::DEFAULT_TYPE) + if (libFile.library().type() == de::Library::DEFAULT_TYPE) { // This is just a shared library, not a plugin. // We don't have to keep it loaded. @@ -116,7 +116,7 @@ Library *Library_New(char const *filePath) // Symbols from game plugins conflict with each other, so we have to // keep track of games. - if(libFile.library().type() == "deng-plugin/game") + if (libFile.library().type() == "deng-plugin/game") { lib->isGamePlugin = true; } @@ -124,7 +124,7 @@ Library *Library_New(char const *filePath) DoomsdayApp::plugins().publishAPIs(lib); return lib; } - catch(de::Error const &er) + catch (de::Error const &er) { Str_Set(lastError, er.asText().toLatin1().constData()); LOG_RES_WARNING("Library_New: Error opening \"%s\": ") << filePath << er.asText(); @@ -134,7 +134,7 @@ Library *Library_New(char const *filePath) void Library_Delete(Library *lib) { - if(!lib) return; + if (!lib) return; // Unload the library from memory. lib->file->clear(); @@ -167,7 +167,7 @@ void *Library_Symbol(Library *lib, char const *symbolName) #endif return lib->file->library().address(symbolName); } - catch(de::Library::SymbolMissingError const &er) + catch (de::Library::SymbolMissingError const &er) { Str_Set(lastError, er.asText().toLatin1().constData()); return nullptr; @@ -185,9 +185,9 @@ de::LoopResult Library_ForAll(std::function DENG2_FOR_EACH_CONST(de::FS::Index, i, libs) { auto &libraryFile = i->second->as(); - if(libraryFile.path().beginsWith("/bin/")) + if (libraryFile.path().beginsWith("/bin/")) { - if(auto result = func(libraryFile)) + if (auto result = func(libraryFile)) return result; } } diff --git a/doomsday/apps/libdoomsday/src/player.cpp b/doomsday/apps/libdoomsday/src/player.cpp index 90b51407df..3d54ee1def 100644 --- a/doomsday/apps/libdoomsday/src/player.cpp +++ b/doomsday/apps/libdoomsday/src/player.cpp @@ -100,8 +100,8 @@ short P_LookDirToShort(float lookDir) { int dir = int( lookDir/110.f * DDMAXSHORT ); - if(dir < DDMINSHORT) return DDMINSHORT; - if(dir > DDMAXSHORT) return DDMAXSHORT; + if (dir < DDMINSHORT) return DDMINSHORT; + if (dir > DDMAXSHORT) return DDMAXSHORT; return (short) dir; } diff --git a/doomsday/apps/libdoomsday/src/players.cpp b/doomsday/apps/libdoomsday/src/players.cpp index ace1b01d63..46ca64bd7f 100644 --- a/doomsday/apps/libdoomsday/src/players.cpp +++ b/doomsday/apps/libdoomsday/src/players.cpp @@ -33,7 +33,7 @@ DENG2_PIMPL_NOREF(Players) Players::Players(Constructor playerConstructor) : d(new Instance) { - for(auto &plr : d->players) + for (auto &plr : d->players) { plr = playerConstructor(); DENG2_ASSERT(plr->is()); @@ -54,9 +54,9 @@ int Players::count() const LoopResult Players::forAll(std::function func) const { - for(auto &plr : d->players) + for (auto &plr : d->players) { - if(auto result = func(*plr)) + if (auto result = func(*plr)) { return result; } @@ -66,9 +66,9 @@ LoopResult Players::forAll(std::function func) const int Players::indexOf(Player const *player) const { - for(int i = 0; i < DDMAXPLAYERS; ++i) + for (int i = 0; i < DDMAXPLAYERS; ++i) { - if(d->players[i] == player) + if (d->players[i] == player) { return i; } @@ -78,9 +78,9 @@ int Players::indexOf(Player const *player) const int Players::indexOf(ddplayer_s const *publicData) const { - for(int i = 0; i < DDMAXPLAYERS; ++i) + for (int i = 0; i < DDMAXPLAYERS; ++i) { - if(&d->players[i]->publicData() == publicData) + if (&d->players[i]->publicData() == publicData) { return i; } diff --git a/doomsday/apps/libdoomsday/src/plugins.cpp b/doomsday/apps/libdoomsday/src/plugins.cpp index 570e25b5ec..6ff91efb57 100644 --- a/doomsday/apps/libdoomsday/src/plugins.cpp +++ b/doomsday/apps/libdoomsday/src/plugins.cpp @@ -40,7 +40,7 @@ struct ThreadState # define DENG_LOCAL_DATA_POINTER QThreadStorage pluginState; ///< Thread-local plugin state. void initLocalData() { - if(!pluginState.hasLocalData()) pluginState.setLocalData(new ThreadState); + if (!pluginState.hasLocalData()) pluginState.setLocalData(new ThreadState); } #else QThreadStorage pluginState; ///< Thread-local plugin state. @@ -48,9 +48,9 @@ QThreadStorage pluginState; ///< Thread-local plugin state. bool Plugins::Hook::operator == (Hook const &other) const { - if(!(_pluginId == 0 || other._pluginId == 0)) + if (!(_pluginId == 0 || other._pluginId == 0)) { - if(_pluginId != other._pluginId) return false; + if (_pluginId != other._pluginId) return false; } return _type == other._type && _function == other._function; } @@ -92,9 +92,9 @@ DENG2_PIMPL_NOREF(Plugins) PluginHandle *findFirstUnusedPluginHandle() { - for(int i = 0; i < MAX_PLUGS; ++i) + for (int i = 0; i < MAX_PLUGS; ++i) { - if(!hInstPlug[i]) + if (!hInstPlug[i]) { return &hInstPlug[i]; } @@ -107,22 +107,22 @@ DENG2_PIMPL_NOREF(Plugins) typedef void (*PluginInitializer)(void); // We are only interested in native files. - if(!lib.source()->is()) + if (!lib.source()->is()) return 0; // Continue iteration. DENG2_ASSERT(!lib.path().isEmpty()); - if(strcasestr("/bin/audio_", lib.path().toUtf8().constData())) + if (strcasestr("/bin/audio_", lib.path().toUtf8().constData())) { // Do not touch audio plugins at this point. return true; } ::Library *plugin = Library_New(lib.path().toUtf8().constData()); - if(!plugin) + if (!plugin) { #ifdef UNIX String const fn = Path(lib.path()).fileName(); - if(fn.contains("libfmodex") || fn.contains("libassimp")) + if (fn.contains("libfmodex") || fn.contains("libassimp")) { // No need to warn about these shared libs. return 0; @@ -132,7 +132,7 @@ DENG2_PIMPL_NOREF(Plugins) return 0; // Continue iteration. } - if(!strcmp(Library_Type(plugin), "deng-plugin/audio")) + if (!strcmp(Library_Type(plugin), "deng-plugin/audio")) { // Audio plugins will be loaded later, on demand. Library_Delete(plugin); @@ -140,7 +140,7 @@ DENG2_PIMPL_NOREF(Plugins) } PluginInitializer initializer = de::function_cast(Library_Symbol(plugin, "DP_Initialize")); - if(!initializer) + if (!initializer) { LOG_RES_WARNING("Cannot load plugin \"%s\": no entrypoint called 'DP_Initialize'") << lib.path(); @@ -153,7 +153,7 @@ DENG2_PIMPL_NOREF(Plugins) // Assign a handle and ID to the plugin. PluginHandle *handle = findFirstUnusedPluginHandle(); pluginid_t const plugId = handle - hInstPlug + 1; - if(!handle) + if (!handle) { LOG_RES_WARNING("Cannot load \"%s\": too many plugins loaded already loaded") << lib.path(); @@ -178,7 +178,7 @@ DENG2_PIMPL_NOREF(Plugins) bool unloadPlugin(PluginHandle *handle) { DENG2_ASSERT(handle != nullptr); - if(!*handle) return false; + if (!*handle) return false; Library_Delete(*handle); *handle = nullptr; @@ -243,7 +243,7 @@ void Plugins::loadAll() void Plugins::unloadAll() { - for(int i = 0; i < MAX_PLUGS && d->hInstPlug[i]; ++i) + for (int i = 0; i < MAX_PLUGS && d->hInstPlug[i]; ++i) { d->unloadPlugin(&d->hInstPlug[i]); } @@ -271,7 +271,7 @@ void *Plugins::findEntryPoint(pluginid_t pluginId, char const *fn) const DENG2_ASSERT(plugIndex >= 0 && plugIndex < MAX_PLUGS); void *addr = Library_Symbol(d->hInstPlug[plugIndex], fn); - if(!addr) + if (!addr) { LOGDEV_RES_WARNING("Error getting address of \"%s\": %s") << fn << Library_LastError(); @@ -283,10 +283,10 @@ bool Plugins::exchangeGameEntryPoints(pluginid_t pluginId) { zap(d->gameExports); - if(pluginId != 0) + if (pluginId != 0) { // Do the API transfer. - if(!(d->getGameAPI = (GETGAMEAPI) findEntryPoint(pluginId, "GetGameAPI"))) + if (!(d->getGameAPI = (GETGAMEAPI) findEntryPoint(pluginId, "GetGameAPI"))) { return false; } @@ -323,14 +323,14 @@ void Plugins::addHook(HookType type, hookfunc_t function) // to a plugin, and then set it back to zero after it gets control back. DENG2_ASSERT(d->activePluginId() != 0); - if(function) + if (function) { // Add the hook. If the plugin is unidentified the ID will be zero. Hook temp; temp._type = type; temp._function = function; temp._pluginId = d->activePluginId(); - if(!d->hooks[type].contains(temp)) + if (!d->hooks[type].contains(temp)) { d->hooks[type].append(temp); // a copy is made. } @@ -340,7 +340,7 @@ void Plugins::addHook(HookType type, hookfunc_t function) bool Plugins::removeHook(HookType type, hookfunc_t function) { DENG2_ASSERT(type >= 0 && type < NUM_HOOK_TYPES); - if(function) + if (function) { Hook temp; temp._type = type; @@ -353,9 +353,9 @@ bool Plugins::removeHook(HookType type, hookfunc_t function) LoopResult Plugins::forAllHooks(HookType type, std::function func) const { - for(Hook const &hook : d->hooks[type]) + for (Hook const &hook : d->hooks[type]) { - if(auto result = func(hook)) + if (auto result = func(hook)) return result; } return LoopContinue; @@ -367,7 +367,7 @@ int Plugins::callAllHooks(HookType type, int parm, void *data) int results = 2; // Assume all good. forAllHooks(type, [&parm, &data, &results] (Hook const &hook) { - if(hook.execute(parm, data)) + if (hook.execute(parm, data)) { results |= 1; // One success. } diff --git a/doomsday/apps/libdoomsday/src/resource/bundles.cpp b/doomsday/apps/libdoomsday/src/resource/bundles.cpp index ea6b2cb92b..470911efb7 100644 --- a/doomsday/apps/libdoomsday/src/resource/bundles.cpp +++ b/doomsday/apps/libdoomsday/src/resource/bundles.cpp @@ -50,7 +50,7 @@ DENG2_PIMPL(Bundles) { DENG2_ASSERT(dataFile.is()); bundlesToIdentify << dataFile.maybeAs(); - if(mainCall.isEmpty()) + if (mainCall.isEmpty()) { mainCall.enqueue([this] () { identifyAddedDataBundles(); }); } @@ -61,7 +61,7 @@ DENG2_PIMPL(Bundles) DENG2_ASSERT(App::rootFolder().has("/sys/bundles")); LOG_RES_MSG("Identifying %i data bundles") << bundlesToIdentify.size(); - for(DataBundle const *bundle : bundlesToIdentify) + for (DataBundle const *bundle : bundlesToIdentify) { DENG2_ASSERT(bundle); bundle->identifyPackages(); @@ -73,19 +73,19 @@ DENG2_PIMPL(Bundles) { using Info = de::Info; - if(!identityRegistry.isEmpty()) return; + if (!identityRegistry.isEmpty()) return; String const defPath = "/packs/net.dengine.base/databundles.dei"; formatEntries.clear(); identityRegistry.parse(App::rootFolder().locate(defPath)); - for(auto const *elem : identityRegistry.root().contentsInOrder()) + for (auto const *elem : identityRegistry.root().contentsInOrder()) { - if(!elem->isBlock()) continue; + if (!elem->isBlock()) continue; Info::BlockElement const &block = elem->as(); - if(block.blockType() != QStringLiteral("package")) + if (block.blockType() != QStringLiteral("package")) { // Not sure what this is... continue; @@ -102,7 +102,7 @@ DENG2_PIMPL(Bundles) format == "ded"? DataBundle::Ded : DataBundle::Unknown); - if(bundleFormat == DataBundle::Unknown) + if (bundleFormat == DataBundle::Unknown) { throw InvalidError("Bundles::parseRegistry", defPath + ": invalid format for \"" + block.name() + "\""); @@ -146,25 +146,25 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const File const &source = bundle.asFile(); // Find the best match from the registry. - for(auto const *def : formatEntries(bundle.format())) + for (auto const *def : formatEntries(bundle.format())) { int score = 0; // Match the file name. - if(auto const *fileName = def->find(QStringLiteral("fileName"))) + if (auto const *fileName = def->find(QStringLiteral("fileName"))) { - if(fileName->isKey() && + if (fileName->isKey() && fileName->as().value() .text.compareWithoutCase(source.name()) == 0) { ++score; } - else if(fileName->isList()) + else if (fileName->isList()) { // Any of the provided alternatives will be accepted. - for(auto const &cand : fileName->as().values()) + for (auto const &cand : fileName->as().values()) { - if(!cand.text.compareWithoutCase(source.name())) + if (!cand.text.compareWithoutCase(source.name())) { ++score; break; @@ -175,8 +175,8 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const // Match the file type. String fileType = def->keyValue(QStringLiteral("fileType")); - if(fileType.isEmpty()) fileType = "file"; // prefer files by default - if((!fileType.compareWithoutCase(QStringLiteral("file")) && source.status().type() == File::Status::FILE) || + if (fileType.isEmpty()) fileType = "file"; // prefer files by default + if ((!fileType.compareWithoutCase(QStringLiteral("file")) && source.status().type() == File::Status::FILE) || (!fileType.compareWithoutCase(QStringLiteral("folder")) && source.status().type() == File::Status::FOLDER)) { ++score; @@ -184,7 +184,7 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const // Match the file size. String fileSize = def->keyValue(QStringLiteral("fileSize")); - if(!fileSize.isEmpty() && fileSize.toUInt() == source.size()) + if (!fileSize.isEmpty() && fileSize.toUInt() == source.size()) { ++score; } @@ -192,13 +192,13 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const bool crcMismatch = false; // Additional criteria for recognizing WADs. - if(bundle.format() == DataBundle::Iwad || + if (bundle.format() == DataBundle::Iwad || bundle.format() == DataBundle::Pwad) { String lumpDirCRC32 = def->keyValue(QStringLiteral("lumpDirCRC32")); - if(!lumpDirCRC32.isEmpty()) + if (!lumpDirCRC32.isEmpty()) { - if(lumpDirCRC32.toUInt(nullptr, 16) == bundle.lumpDirectory()->crc32()) + if (lumpDirCRC32.toUInt(nullptr, 16) == bundle.lumpDirectory()->crc32()) { // Low probability of a false negative => more significant. score += 2; @@ -209,17 +209,17 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const } } - if(auto const *lumps = def->find(QStringLiteral("lumps"))->maybeAs()) + if (auto const *lumps = def->find(QStringLiteral("lumps"))->maybeAs()) { ++score; // will be subtracted if not matched - for(auto const &val : lumps->values()) + for (auto const &val : lumps->values()) { QRegExp const sizeCondition("(.*)==([0-9]+)"); Block lumpName; int requiredSize = 0; - if(sizeCondition.exactMatch(val)) + if (sizeCondition.exactMatch(val)) { lumpName = sizeCondition.cap(1).toUtf8(); requiredSize = sizeCondition.cap(2).toInt(); @@ -230,13 +230,13 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const requiredSize = -1; } - if(!bundle.lumpDirectory()->has(lumpName)) + if (!bundle.lumpDirectory()->has(lumpName)) { --score; break; } - if(requiredSize >= 0 && + if (requiredSize >= 0 && bundle.lumpDirectory()->lumpSize(lumpName) != duint32(requiredSize)) { --score; @@ -246,7 +246,7 @@ Bundles::MatchResult Bundles::match(DataBundle const &bundle) const } } - if(score > 0 && score >= match.bestScore) + if (score > 0 && score >= match.bestScore) { match.bestMatch = def; match.bestScore = score; @@ -274,9 +274,9 @@ QList Bundles::loaded() const QList loadedBundles; // Check all the loaded packages to see which ones are data bundles. - for(auto *f : App::packageLoader().loadedPackagesAsFilesInPackageOrder()) + for (auto *f : App::packageLoader().loadedPackagesAsFilesInPackageOrder()) { - if(DataBundle const *bundle = f->maybeAs()) + if (DataBundle const *bundle = f->maybeAs()) { loadedBundles << bundle; } diff --git a/doomsday/apps/libdoomsday/src/resource/colorpalette.cpp b/doomsday/apps/libdoomsday/src/resource/colorpalette.cpp index 41efc38dbb..4cd18757af 100644 --- a/doomsday/apps/libdoomsday/src/resource/colorpalette.cpp +++ b/doomsday/apps/libdoomsday/src/resource/colorpalette.cpp @@ -42,34 +42,34 @@ static void parseColorFormat(QString const &fmt, Vector3ui &compOrder, Vector3ui int readComponents = 0; int pos = 0; - while(pos < end) + while (pos < end) { QChar ch = fmt[pos]; pos++; int comp = -1; if (ch == 'R' || ch == 'r') comp = 0; - else if(ch == 'G' || ch == 'g') comp = 1; - else if(ch == 'B' || ch == 'b') comp = 2; + else if (ch == 'G' || ch == 'g') comp = 1; + else if (ch == 'B' || ch == 'b') comp = 2; - if(comp != -1 && compBits[comp] == 0) + if (comp != -1 && compBits[comp] == 0) { compOrder[comp] = readComponents++; // Read the number of bits. int start = pos; ch = fmt[pos]; - while(ch.isDigit() && ++pos < end) + while (ch.isDigit() && ++pos < end) { ch = fmt[pos]; } int numDigits = pos - start; - if(numDigits) + if (numDigits) { compBits[comp] = fmt.mid(start, numDigits).toInt(); // Are we done? - if(readComponents == 3) + if (readComponents == 3) break; continue; @@ -80,7 +80,7 @@ static void parseColorFormat(QString const &fmt, Vector3ui &compOrder, Vector3ui throw ColorTableReader::FormatError("parseColorFormat", QString("Unexpected character '%1' at position %2").arg(ch).arg(pos)); } - if(readComponents != 3) + if (readComponents != 3) { /// @throw ColorTableReader::FormatError throw ColorTableReader::FormatError("parseColorFormat", "Incomplete format specification"); @@ -99,11 +99,11 @@ ColorTable ColorTableReader::read(String format, int colorCount, ColorTable colors(colorCount); // Already in the format we want? - if(8 == bits.x && 8 == bits.y && 8 == bits.z) + if (8 == bits.x && 8 == bits.y && 8 == bits.z) { // Great! Just copy it as-is. dbyte const *src = colorData; - for(int i = 0; i < colorCount; ++i, src += 3) + for (int i = 0; i < colorCount; ++i, src += 3) { colors[i] = Vector3ub(src[order.x], src[order.y], src[order.z]); } @@ -113,7 +113,7 @@ ColorTable ColorTableReader::read(String format, int colorCount, // Conversion is necessary. dbyte const *src = colorData; dbyte cb = 0; - for(int i = 0; i < colorCount; ++i) + for (int i = 0; i < colorCount; ++i) { Vector3ub &dst = colors[i]; @@ -123,25 +123,25 @@ ColorTable ColorTableReader::read(String format, int colorCount, M_ReadBits(bits[order.z], &src, &cb, (dbyte *) &(tmp[order.z])); // Need to do any scaling? - if(8 != bits.x) + if (8 != bits.x) { - if(bits.x < 8) + if (bits.x < 8) tmp.x <<= 8 - bits.x; else tmp.x >>= bits.x - 8; } - if(8 != bits.y) + if (8 != bits.y) { - if(bits.y < 8) + if (bits.y < 8) tmp.y <<= 8 - bits.y; else tmp.y >>= bits.y - 8; } - if(8 != bits.z) + if (8 != bits.z) { - if(bits.z < 8) + if (bits.z < 8) tmp.z <<= 8 - bits.z; else tmp.z >>= bits.z - 8; @@ -181,7 +181,7 @@ DENG2_PIMPL(ColorPalette) Translation *translation(String id) { Translations::iterator found = translations.find(id); - if(found != translations.end()) + if (found != translations.end()) { return &found.value(); } @@ -203,25 +203,25 @@ DENG2_PIMPL(ColorPalette) need18To8Update = false; - if(xlat18To8.isNull()) + if (xlat18To8.isNull()) { xlat18To8.reset(new XLat18To8(COLORS18BIT)); } - for(int r = 0; r < 64; ++r) - for(int g = 0; g < 64; ++g) - for(int b = 0; b < 64; ++b) + for (int r = 0; r < 64; ++r) + for (int g = 0; g < 64; ++g) + for (int b = 0; b < 64; ++b) { int nearest = 0; int smallestDiff = DDMAXINT; - for(int i = 0; i < colors.count(); ++i) + for (int i = 0; i < colors.count(); ++i) { Color const &color = colors[i]; int diff = (color.x - (r << 2)) * (color.x - (r << 2)) + (color.y - (g << 2)) * (color.y - (g << 2)) + (color.z - (b << 2)) * (color.z - (b << 2)); - if(diff < smallestDiff) + if (diff < smallestDiff) { smallestDiff = diff; nearest = i; @@ -271,7 +271,7 @@ ColorPalette &ColorPalette::replaceColorTable(ColorTable const &colorTable) // When the color count changes all existing translations are destroyed as // they will no longer be valid. - if(colorCountBefore != colorCount()) + if (colorCountBefore != colorCount()) { clearTranslations(); } @@ -283,13 +283,13 @@ Vector3ub ColorPalette::color(int colorIndex) const { LOG_AS("ColorPalette"); - if(colorIndex < 0 || colorIndex >= d->colors.count()) + if (colorIndex < 0 || colorIndex >= d->colors.count()) { LOG_DEBUG("Index %i out of range %s in palette %s, will clamp.") << colorIndex << Rangeui(0, d->colors.count()).asText() << d->id; } - if(!d->colors.isEmpty()) + if (!d->colors.isEmpty()) { return d->colors[de::clamp(0, colorIndex, d->colors.count() - 1)]; } @@ -306,10 +306,10 @@ int ColorPalette::nearestIndex(Vector3ub const &rgb) const { LOG_AS("ColorPalette"); - if(d->colors.isEmpty()) return -1; + if (d->colors.isEmpty()) return -1; // Ensure we've prepared the 18 to 8 table. - if(d->need18To8Update || d->xlat18To8.isNull()) + if (d->need18To8Update || d->xlat18To8.isNull()) { d->prepareNearestLUT(); } @@ -333,7 +333,7 @@ void ColorPalette::newTranslation(String id, Translation const &mappings) { LOG_AS("ColorPalette"); - if(!colorCount()) + if (!colorCount()) { //qDebug() << "Cannot define a translation for an empty palette!"; return; @@ -341,10 +341,10 @@ void ColorPalette::newTranslation(String id, Translation const &mappings) DENG2_ASSERT(mappings.count() == colorCount()); // sanity check - if(!id.isEmpty()) + if (!id.isEmpty()) { Translation *xlat = d->translation(id); - if(!xlat) + if (!xlat) { // An entirely new translation. xlat = &d->translations.insert(id, Translation()).value(); @@ -354,10 +354,10 @@ void ColorPalette::newTranslation(String id, Translation const &mappings) *xlat = mappings; // Ensure the mappings are within valid range. - for(int i = 0; i < colorCount(); ++i) + for (int i = 0; i < colorCount(); ++i) { int palIdx = (*xlat)[i]; - if(palIdx < 0 || palIdx >= colorCount()) + if (palIdx < 0 || palIdx >= colorCount()) { (*xlat)[i] = i; } diff --git a/doomsday/apps/libdoomsday/src/resource/databundle.cpp b/doomsday/apps/libdoomsday/src/resource/databundle.cpp index 08de2e2749..a2dd330ffa 100644 --- a/doomsday/apps/libdoomsday/src/resource/databundle.cpp +++ b/doomsday/apps/libdoomsday/src/resource/databundle.cpp @@ -75,13 +75,13 @@ DENG2_PIMPL(DataBundle) LOG_AS("DataBundle"); DENG2_ASSERT(packageId.isEmpty()); // should be only called once - if(!packageId.isEmpty()) return; + if (!packageId.isEmpty()) return; // Load the lump directory of WAD files. - if(format == Wad || format == Pwad || format == Iwad) + if (format == Wad || format == Pwad || format == Iwad) { lumpDir.reset(new res::LumpDirectory(source->as())); - if(!lumpDir->isValid()) + if (!lumpDir->isValid()) { throw FormatError("DataBundle::identify", dynamic_cast(thisPublic)->description() + @@ -95,7 +95,7 @@ DENG2_PIMPL(DataBundle) << "\nfileSize:" << source->size() << "\nlumpDirCRC32:" << QString::number(lumpDir->crc32(), 16).toLatin1();*/ } - else if(self.isNested()) + else if (self.isNested()) { //qDebug() << "[DataBundle]" << source->description().toLatin1().constData() // << "is nested, no package will be generated"; @@ -105,7 +105,7 @@ DENG2_PIMPL(DataBundle) // Search for known data files in the bundle registry. res::Bundles::MatchResult matched = DoomsdayApp::bundles().match(self); - if(matched) + if (matched) { packageId = matched.packageId; } @@ -145,7 +145,7 @@ DENG2_PIMPL(DataBundle) File &dataFile = self.asFile(); // Finally, make a link that represents the package. - if(auto chosen = chooseUniqueLinkPathAndVersion(dataFile, packageId, + if (auto chosen = chooseUniqueLinkPathAndVersion(dataFile, packageId, matched.packageVersion, matched.bestScore)) { @@ -157,7 +157,7 @@ DENG2_PIMPL(DataBundle) Record &metadata = Package::initializeMetadata(*pkgLink, packageId); metadata.set("path", dataFile.path()); metadata.set("version", !chosen.version.isEmpty()? chosen.version : "0.0"); - if(lumpDir) + if (lumpDir) { metadata.set("lumpDirCRC32", lumpDir->crc32()) .value().as().setSemanticHints(NumberValue::Hex); @@ -165,14 +165,14 @@ DENG2_PIMPL(DataBundle) metadata.set("bundleScore", matched.bestScore); // Get the rest of the metadata. - if(matched) + if (matched) { metadata.set("title", matched.bestMatch->keyValue("info:title")); metadata.set("tags", matched.bestMatch->keyValue("info:tags")); metadata.set("author", matched.bestMatch->keyValue("info:author")); String license = matched.bestMatch->keyValue("info:license"); - if(license.isEmpty()) license = "Unknown"; + if (license.isEmpty()) license = "Unknown"; metadata.set("license", license); } else @@ -202,23 +202,23 @@ DENG2_PIMPL(DataBundle) Version const &packageVersion, dint bundleScore) { - for(int attempt = 0; attempt < 3; ++attempt) + for (int attempt = 0; attempt < 3; ++attempt) { String linkPath = packageId; String version = (packageVersion.isValid()? packageVersion.asText() : ""); // Try a few different ways to generate a locally unique version number. - switch(attempt) + switch (attempt) { case 0: // unmodified break; case 1: // parent folder as version label - if(dataFile.path().fileNamePath() != "/local/wads") + if (dataFile.path().fileNamePath() != "/local/wads") { - if(version.isEmpty()) version = "0"; + if (version.isEmpty()) version = "0"; Path const filePath(dataFile.path()); - if(filePath.segmentCount() >= 2) + if (filePath.segmentCount() >= 2) { version += "-" + filePath.segment(filePath.segmentCount() - 2).toString().toLower(); } @@ -231,7 +231,7 @@ DENG2_PIMPL(DataBundle) break; } - if(!version.isEmpty()) + if (!version.isEmpty()) { linkPath += QString("_%1.pack").arg(version); } @@ -241,7 +241,7 @@ DENG2_PIMPL(DataBundle) } // Each link must have a unique name. - if(!bundleFolder().has(linkPath)) + if (!bundleFolder().has(linkPath)) { return PathAndVersion(linkPath, version); } @@ -249,7 +249,7 @@ DENG2_PIMPL(DataBundle) { // This could still be a better scored match. Record const &pkgInfo = bundleFolder().locate(linkPath).objectNamespace(); - if(bundleScore > pkgInfo.geti("bundleScore")) + if (bundleScore > pkgInfo.geti("bundleScore")) { // Forget about the previous link. bundleFolder().removeFile(linkPath); @@ -280,7 +280,7 @@ DataBundle::Format DataBundle::format() const String DataBundle::description() const { - if(!d->source) + if (!d->source) { return "invalid data bundle"; } @@ -306,7 +306,7 @@ File const &DataBundle::sourceFile() const IByteArray::Size DataBundle::size() const { - if(d->source) + if (d->source) { return d->source->size(); } @@ -315,7 +315,7 @@ IByteArray::Size DataBundle::size() const void DataBundle::get(Offset at, Byte *values, Size count) const { - if(!d->source) + if (!d->source) { throw File::InputError("DataBundle::get", "Source file has been destroyed"); } @@ -350,7 +350,7 @@ void DataBundle::identifyPackages() const { d->identify(); } - catch(Error const &er) + catch (Error const &er) { LOG_RES_WARNING("Failed to identify %s") << description(); } @@ -366,9 +366,9 @@ DataBundle const *DataBundle::containerBundle() const auto const *file = dynamic_cast(this); DENG2_ASSERT(file != nullptr); - for(Folder const *folder = file->parent(); folder; folder = folder->parent()) + for (Folder const *folder = file->parent(); folder; folder = folder->parent()) { - if(auto const *data = folder->maybeAs()) + if (auto const *data = folder->maybeAs()) return data; } return nullptr; @@ -399,15 +399,15 @@ File *DataBundle::Interpreter::interpretFile(File *sourceData) const { ".box", Collection }, }; String const ext = sourceData->name().fileNameExtension(); - for(auto const &fmt : formats) + for (auto const &fmt : formats) { - if(!ext.compareWithoutCase(fmt.str)) + if (!ext.compareWithoutCase(fmt.str)) { LOG_RES_VERBOSE("Interpreted ") << sourceData->description() << " as " << ::internal::formatDescriptions[fmt.format]; - switch(fmt.format) + switch (fmt.format) { case Pk3: case Collection: diff --git a/doomsday/apps/libdoomsday/src/resource/lumpcatalog.cpp b/doomsday/apps/libdoomsday/src/resource/lumpcatalog.cpp index 851e570e65..e50bea0a2d 100644 --- a/doomsday/apps/libdoomsday/src/resource/lumpcatalog.cpp +++ b/doomsday/apps/libdoomsday/src/resource/lumpcatalog.cpp @@ -48,13 +48,13 @@ DENG2_PIMPL(LumpCatalog) { bundles.clear(); - for(auto const &pkg : packageIds) + for (auto const &pkg : packageIds) { // The package must be available as a file. - if(File const *file = App::packageLoader().select(pkg)) + if (File const *file = App::packageLoader().select(pkg)) { auto const *bundle = file->target().maybeAs(); - if(bundle && bundle->lumpDirectory()) + if (bundle && bundle->lumpDirectory()) { bundles << bundle; } @@ -68,10 +68,10 @@ DENG2_PIMPL(LumpCatalog) Found found { nullptr, LumpDirectory::InvalidPos }; // The last bundle is checked first. - for(int i = bundles.size() - 1; i >= 0; --i) + for (int i = bundles.size() - 1; i >= 0; --i) { auto const pos = bundles.at(i)->lumpDirectory()->find(lumpName); - if(pos != LumpDirectory::InvalidPos) + if (pos != LumpDirectory::InvalidPos) { found = Found(bundles.at(i), pos); break; @@ -92,7 +92,7 @@ void LumpCatalog::clear() bool LumpCatalog::setPackages(StringList const &packageIds) { - if(packageIds != d->packageIds) + if (packageIds != d->packageIds) { d->packageIds = packageIds; d->updateBundles(); @@ -105,7 +105,7 @@ Block LumpCatalog::read(String const &lumpName) const { Block data; Instance::Found found = d->findLump(lumpName); - if(found.first) + if (found.first) { auto const &entry = found.first->lumpDirectory()->entry(found.second); data.copyFrom(*found.first, entry.offset, entry.size); diff --git a/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp b/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp index e0f892604b..f128448647 100644 --- a/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp +++ b/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp @@ -43,7 +43,7 @@ DENG2_PIMPL_NOREF(LumpDirectory) Block typeId; reader.readBytes(4, typeId); type = (typeId == "PWAD"? Pwad : typeId == "IWAD"? Iwad : Invalid); - if(type == Invalid) return; + if (type == Invalid) return; duint32 count = 0; duint32 dirOffset = 0; @@ -58,7 +58,7 @@ DENG2_PIMPL_NOREF(LumpDirectory) // Read all the entries. Reader lumpReader(data); - for(duint32 i = 0; i < count; ++i) + for (duint32 i = 0; i < count; ++i) { Entry entry; lumpReader >> entry.offset >> entry.size; @@ -69,7 +69,7 @@ DENG2_PIMPL_NOREF(LumpDirectory) // Make an index of all the lumps. index.clear(); - for(int i = 0; i < entries.size(); ++i) + for (int i = 0; i < entries.size(); ++i) { index.insert(entries.at(i).name, i); } @@ -99,7 +99,7 @@ LumpDirectory::Pos LumpDirectory::count() const LumpDirectory::Entry const &LumpDirectory::entry(Pos pos) const { - if(pos >= count()) + if (pos >= count()) { throw OffsetError("LumpDirectory::entry", QString("Invalid position %1 (lump count: %2)") @@ -116,7 +116,7 @@ duint32 LumpDirectory::crc32() const duint32 LumpDirectory::lumpSize(Block const &lumpName) const { auto found = d->index.constFind(lumpName); - if(found != d->index.constEnd()) + if (found != d->index.constEnd()) { return d->entries.at(found.value()).size; } @@ -131,7 +131,7 @@ bool LumpDirectory::has(Block const &lumpName) const LumpDirectory::Pos LumpDirectory::find(Block const &lumpName) const { auto found = d->index.constFind(lumpName); - if(found != d->index.constEnd()) + if (found != d->index.constEnd()) { return found.value(); } diff --git a/doomsday/apps/libdoomsday/src/resource/manifest.cpp b/doomsday/apps/libdoomsday/src/resource/manifest.cpp index 5e3f744fde..8d35dbd49c 100644 --- a/doomsday/apps/libdoomsday/src/resource/manifest.cpp +++ b/doomsday/apps/libdoomsday/src/resource/manifest.cpp @@ -64,15 +64,15 @@ DENG2_PIMPL(ResourceManifest) ResourceManifest::ResourceManifest(resourceclassid_t resClass, int fFlags, String *name) : d(new Instance(this, resClass, fFlags)) { - if(name) addName(*name); + if (name) addName(*name); } void ResourceManifest::addName(String newName) { - if(newName.isEmpty()) return; + if (newName.isEmpty()) return; // Is this name unique? We don't want duplicates. - if(!d->names.contains(newName, Qt::CaseInsensitive)) + if (!d->names.contains(newName, Qt::CaseInsensitive)) { d->names.prepend(newName); } @@ -80,10 +80,10 @@ void ResourceManifest::addName(String newName) void ResourceManifest::addIdentityKey(String newIdKey) { - if(newIdKey.isEmpty()) return; + if (newIdKey.isEmpty()) return; // Is this key unique? We don't want duplicates. - if(!d->identityKeys.contains(newIdKey, Qt::CaseInsensitive)) + if (!d->identityKeys.contains(newIdKey, Qt::CaseInsensitive)) { d->identityKeys.append(newIdKey); } @@ -110,23 +110,23 @@ static void checkSizeConditionInIdentityKey(String &idKey, lumpsizecondition_t * int condPos = -1; int argPos = -1; - if((condPos = idKey.indexOf("==")) >= 0) + if ((condPos = idKey.indexOf("==")) >= 0) { *pCond = LSCOND_EQUAL; argPos = condPos + 2; } - else if((condPos = idKey.indexOf(">=")) >= 0) + else if ((condPos = idKey.indexOf(">=")) >= 0) { *pCond = LSCOND_GREATER_OR_EQUAL; argPos = condPos + 2; } - else if((condPos = idKey.indexOf("<=")) >= 0) + else if ((condPos = idKey.indexOf("<=")) >= 0) { *pCond = LSCOND_LESS_OR_EQUAL; argPos = condPos + 2; } - if(condPos < 0) return; + if (condPos < 0) return; // Get the argument. *pSize = idKey.mid(argPos).toULong(); @@ -137,7 +137,7 @@ static void checkSizeConditionInIdentityKey(String &idKey, lumpsizecondition_t * static lumpnum_t lumpNumForIdentityKey(LumpIndex const &lumpIndex, String idKey) { - if(idKey.isEmpty()) return -1; + if (idKey.isEmpty()) return -1; // The key may contain a size condition (==, >=, <=). lumpsizecondition_t sizeCond; @@ -148,28 +148,28 @@ static lumpnum_t lumpNumForIdentityKey(LumpIndex const &lumpIndex, String idKey) String name = idKey; // Append a .lmp extension if none is specified. - if(idKey.fileNameExtension().isEmpty()) + if (idKey.fileNameExtension().isEmpty()) { name += ".lmp"; } lumpnum_t lumpNum = lumpIndex.findLast(Path(name)); - if(lumpNum < 0) return -1; + if (lumpNum < 0) return -1; // Check the condition. size_t lumpSize = lumpIndex[lumpNum].info().size; - switch(sizeCond) + switch (sizeCond) { case LSCOND_EQUAL: - if(lumpSize != refSize) return -1; + if (lumpSize != refSize) return -1; break; case LSCOND_GREATER_OR_EQUAL: - if(lumpSize < refSize) return -1; + if (lumpSize < refSize) return -1; break; case LSCOND_LESS_OR_EQUAL: - if(lumpSize > refSize) return -1; + if (lumpSize > refSize) return -1; break; default: break; @@ -186,12 +186,12 @@ static bool validateWad(String const &filePath, QStringList const &identityKeys) { FileHandle &hndl = App_FileSystem().openFile(filePath, "rb", 0/*baseOffset*/, true /*allow duplicates*/); - if(Wad *wad = hndl.file().maybeAs()) + if (Wad *wad = hndl.file().maybeAs()) { // Ensure all identity lumps are present. - if(identityKeys.count()) + if (identityKeys.count()) { - if(wad->isEmpty()) + if (wad->isEmpty()) { // Clear not what we are looking for. validated = false; @@ -200,7 +200,7 @@ static bool validateWad(String const &filePath, QStringList const &identityKeys) { // Publish lumps to a temporary index. LumpIndex lumpIndex; - for(int i = 0; i < wad->lumpCount(); ++i) + for (int i = 0; i < wad->lumpCount(); ++i) { lumpIndex.catalogLump(wad->lump(i)); } @@ -208,7 +208,7 @@ static bool validateWad(String const &filePath, QStringList const &identityKeys) // Check each lump. DENG2_FOR_EACH_CONST(QStringList, i, identityKeys) { - if(lumpNumForIdentityKey(lumpIndex, *i) < 0) + if (lumpNumForIdentityKey(lumpIndex, *i) < 0) { validated = false; break; @@ -226,7 +226,7 @@ static bool validateWad(String const &filePath, QStringList const &identityKeys) App_FileSystem().releaseFile(hndl.file()); delete &hndl; } - catch(FS1::NotFoundError const &) + catch (FS1::NotFoundError const &) {} // Ignore this error. return validated; @@ -244,7 +244,7 @@ static bool validateZip(String const &filePath, QStringList const & /*identityKe delete &hndl; return result; } - catch(FS1::NotFoundError const &) + catch (FS1::NotFoundError const &) {} // Ignore error. return false; } @@ -252,11 +252,11 @@ static bool validateZip(String const &filePath, QStringList const & /*identityKe void ResourceManifest::locateFile() { // Already found? - if(d->flags & FF_FOUND) return; + if (d->flags & FF_FOUND) return; // Perform the search. int nameIndex = 0; - for(QStringList::const_iterator i = d->names.constBegin(); i != d->names.constEnd(); ++i, ++nameIndex) + for (QStringList::const_iterator i = d->names.constBegin(); i != d->names.constEnd(); ++i, ++nameIndex) { StringList candidates; @@ -268,7 +268,7 @@ void ResourceManifest::locateFile() foundPath = App_BasePath() / foundPath; // Ensure the path is absolute. candidates << foundPath; } - catch(FS1::NotFoundError const &) + catch (FS1::NotFoundError const &) {} // Ignore this error. // Also check what FS2 has to offer. FS1 can't access FS2's files, so we'll @@ -276,22 +276,22 @@ void ResourceManifest::locateFile() App::fileSystem().forAll(*i, [&candidates] (File &f) { // We ignore interpretations and go straight to the source. - if(NativeFile const *native = f.source()->maybeAs()) + if (NativeFile const *native = f.source()->maybeAs()) { candidates << native->nativePath(); } return LoopContinue; }); - for(String foundPath : candidates) + for (String foundPath : candidates) { // Perform identity validation. bool validated = false; - if(d->classId == RC_PACKAGE) + if (d->classId == RC_PACKAGE) { /// @todo The identity configuration should declare the type of resource... validated = validateWad(foundPath, d->identityKeys); - if(!validated) + if (!validated) validated = validateZip(foundPath, d->identityKeys); } else @@ -300,7 +300,7 @@ void ResourceManifest::locateFile() validated = true; } - if(validated) + if (validated) { // This is the resource we've been looking for. d->flags |= FF_FOUND; @@ -314,7 +314,7 @@ void ResourceManifest::locateFile() void ResourceManifest::forgetFile() { - if(d->flags & FF_FOUND) + if (d->flags & FF_FOUND) { d->foundPath.clear(); d->foundNameIndex = -1; @@ -324,7 +324,7 @@ void ResourceManifest::forgetFile() String const &ResourceManifest::resolvedPath(bool tryLocate) { - if(tryLocate) + if (tryLocate) { locateFile(); } diff --git a/doomsday/apps/libdoomsday/src/resource/mapmanifest.cpp b/doomsday/apps/libdoomsday/src/resource/mapmanifest.cpp index 7f101498a1..cf672add33 100644 --- a/doomsday/apps/libdoomsday/src/resource/mapmanifest.cpp +++ b/doomsday/apps/libdoomsday/src/resource/mapmanifest.cpp @@ -31,7 +31,7 @@ String MapManifest::description(de::Uri::ComposeAsTextFlags uriCompositionFlags) { String info = String("%1").arg(composeUri().compose(uriCompositionFlags | de::Uri::DecodePath), ( uriCompositionFlags.testFlag(de::Uri::OmitScheme)? -14 : -22 ) ); - if(_sourceFile) + if (_sourceFile) { info += String(" " _E(C) "\"%1\"" _E(.)).arg(NativePath(sourceFile()->composePath()).pretty()); } diff --git a/doomsday/apps/libdoomsday/src/resource/patch.cpp b/doomsday/apps/libdoomsday/src/resource/patch.cpp index 3f01eadd27..ef033219b6 100644 --- a/doomsday/apps/libdoomsday/src/resource/patch.cpp +++ b/doomsday/apps/libdoomsday/src/resource/patch.cpp @@ -90,7 +90,7 @@ static bool readNextPost(Post &post, Reader &reader) reader.mark(); dbyte nextByte; reader >> nextByte; reader.rewind(); - if(nextByte == END_OF_POSTS) return false; + if (nextByte == END_OF_POSTS) return false; // Another post begins. reader >> post; @@ -117,7 +117,7 @@ static Columns readPosts(ColumnOffsets const &offsets, Reader &reader) Column &column = columns.back(); // Read all posts. - while(readNextPost(post, reader)) + while (readNextPost(post, reader)) { column.push_back(post); @@ -139,7 +139,7 @@ static ColumnOffsets readColumnOffsets(int width, Reader &reader) offsets.reserve(width); #endif - for(int col = 0; col < width; ++col) + for (int col = 0; col < width; ++col) { dint32 offset; reader >> offset; offsets.push_back(offset); @@ -168,13 +168,13 @@ static int calcRealHeight(Columns const &columns) Post const &post = *postIt; // Does this post extend the previous one? (a so-called "tall-patch"). - if(post.topOffset <= tallTop) + if (post.topOffset <= tallTop) tallTop += post.topOffset; else tallTop = post.topOffset; // Skip invalid posts. - if(post.length <= 0) continue; + if (post.length <= 0) continue; // Unite the geometry of the post. geom |= QRect(QPoint(0, tallTop), QSize(1, post.length)); @@ -194,7 +194,7 @@ static Block compositeImage(Reader &reader, ColorPaletteTranslation const *xlatT #ifdef DENG2_DEBUG // Is the "logical" height of the image equal to the actual height of the // composited pixel posts? - if(meta.logicalDimensions.y != meta.dimensions.y) + if (meta.logicalDimensions.y != meta.dimensions.y) { int postCount = 0; DENG2_FOR_EACH_CONST(Columns, i, columns) @@ -231,24 +231,24 @@ static Block compositeImage(Reader &reader, ColorPaletteTranslation const *xlatT Post const &post = *postIt; // Does this post extend the previous one? (a so-called "tall-patch"). - if(post.topOffset <= tallTop) + if (post.topOffset <= tallTop) tallTop += post.topOffset; else tallTop = post.topOffset; // Skip invalid posts. - if(post.length <= 0) continue; + if (post.length <= 0) continue; // Determine the destination height range. int y = tallTop; int length = post.length; // Clamp height range within bounds. - if(y + length > h) + if (y + length > h) length = h - y; int offset = 0; - if(y < 0) + if (y < 0) { offset = de::min(-y, length); y = 0; @@ -257,7 +257,7 @@ static Block compositeImage(Reader &reader, ColorPaletteTranslation const *xlatT length = de::max(0, length - offset); // Skip empty ranges. - if(!length) continue; + if (!length) continue; // Find the start of the pixel data for the post. reader.setOffset(post.firstPixel + offset); @@ -266,24 +266,24 @@ static Block compositeImage(Reader &reader, ColorPaletteTranslation const *xlatT dbyte *outAlpha = topAlpha + tallTop * w; // Composite pixels from the post to the output buffer. - while(length--) + while (length--) { // Read the next palette index. dbyte palIdx; reader >> palIdx; // Is palette index translation in effect? - if(xlatTable) + if (xlatTable) { palIdx = dbyte(xlatTable->at(palIdx)); } - if(!maskZero || palIdx) + if (!maskZero || palIdx) { *out = palIdx; } - if(maskZero) + if (maskZero) *outAlpha = (palIdx? 0xff : 0); else *outAlpha = 0xff; @@ -355,19 +355,19 @@ bool Patch::recognize(IByteArray const &data) Reader from = Reader(data); Header hdr; from >> hdr; - if(!hdr.dimensions[0] || !hdr.dimensions[1]) return false; + if (!hdr.dimensions[0] || !hdr.dimensions[1]) return false; - for(int col = 0; col < hdr.dimensions[0]; ++col) + for (int col = 0; col < hdr.dimensions[0]; ++col) { dint32 offset; from >> offset; - if(offset < 0 || (unsigned) offset >= from.source()->size()) return false; + if (offset < 0 || (unsigned) offset >= from.source()->size()) return false; } // Validated. return true; } - catch(IByteArray::OffsetError const &) + catch (IByteArray::OffsetError const &) { // Invalid! return false; diff --git a/doomsday/apps/libdoomsday/src/resource/resources.cpp b/doomsday/apps/libdoomsday/src/resource/resources.cpp index e4d1c162f0..575c1086b6 100644 --- a/doomsday/apps/libdoomsday/src/resource/resources.cpp +++ b/doomsday/apps/libdoomsday/src/resource/resources.cpp @@ -50,7 +50,7 @@ DENG2_PIMPL(Resources) << new ResourceClass("RC_FONT", "Fonts"); // Determine the root directory of the saved session repository. - if(auto arg = App::commandLine().check("-savedir", 1)) + if (auto arg = App::commandLine().check("-savedir", 1)) { // Using a custom root save directory. App::commandLine().makeAbsolutePath(arg.pos + 1); @@ -86,11 +86,11 @@ Resources &Resources::get() ResourceClass &Resources::resClass(String name) { - if(!name.isEmpty()) + if (!name.isEmpty()) { - foreach(ResourceClass *resClass, d->resClasses) + foreach (ResourceClass *resClass, d->resClasses) { - if(!resClass->name().compareWithoutCase(name)) + if (!resClass->name().compareWithoutCase(name)) return *resClass; } } @@ -99,8 +99,8 @@ ResourceClass &Resources::resClass(String name) ResourceClass &Resources::resClass(resourceclassid_t id) { - if(id == RC_NULL) return d->nullResourceClass; - if(VALID_RESOURCECLASSID(id)) + if (id == RC_NULL) return d->nullResourceClass; + if (VALID_RESOURCECLASSID(id)) { return *d->resClasses.at(uint(id)); } @@ -111,7 +111,7 @@ ResourceClass &Resources::resClass(resourceclassid_t id) void Resources::updateOverrideIWADPathFromConfig() { String path = App::config().gets("resource.iwadFolder", ""); - if(!path.isEmpty()) + if (!path.isEmpty()) { LOG_RES_NOTE("Using user-selected primary IWAD folder: \"%s\"") << path; @@ -130,9 +130,9 @@ NativePath Resources::nativeSavePath() const res::MapManifest &Resources::findMapManifest(de::Uri const &mapUri) const { // Only one resource scheme is known for maps. - if(!mapUri.scheme().compareWithoutCase("Maps")) + if (!mapUri.scheme().compareWithoutCase("Maps")) { - if(res::MapManifest *found = d->mapManifests.tryFind( + if (res::MapManifest *found = d->mapManifests.tryFind( mapUri.path(), PathTree::MatchFull | PathTree::NoBranch)) return *found; } @@ -143,7 +143,7 @@ res::MapManifest &Resources::findMapManifest(de::Uri const &mapUri) const res::MapManifest *Resources::tryFindMapManifest(de::Uri const &mapUri) const { // Only one resource scheme is known for maps. - if(mapUri.scheme().compareWithoutCase("Maps")) return nullptr; + if (mapUri.scheme().compareWithoutCase("Maps")) return nullptr; return d->mapManifests.tryFind(mapUri.path(), PathTree::MatchFull | PathTree::NoBranch); } @@ -161,11 +161,11 @@ void Resources::initMapManifests() /// the central lump index. LumpIndex const &lumpIndex = App_FileSystem().nameIndex(); lumpnum_t lastLump = -1; - while(lastLump < lumpIndex.size()) + while (lastLump < lumpIndex.size()) { std::unique_ptr recognizer(new Id1MapRecognizer(lumpIndex, lastLump)); lastLump = recognizer->lastLump(); - if(recognizer->format() != Id1MapRecognizer::UnknownFormat) + if (recognizer->format() != Id1MapRecognizer::UnknownFormat) { File1 *sourceFile = recognizer->sourceFile(); String const mapId = recognizer->id(); diff --git a/doomsday/apps/libdoomsday/src/resource/wav.cpp b/doomsday/apps/libdoomsday/src/resource/wav.cpp index 008ef3bdc2..507ee6c865 100644 --- a/doomsday/apps/libdoomsday/src/resource/wav.cpp +++ b/doomsday/apps/libdoomsday/src/resource/wav.cpp @@ -82,7 +82,7 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, LOG_AS("WAV_MemoryLoad"); - if(!WAV_CheckFormat((const char*)data)) + if (!WAV_CheckFormat((const char*)data)) { LOG_RES_WARNING("Not WAV format data"); return NULL; @@ -98,7 +98,7 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, #endif // Start readin' the chunks, baby! - while(data < end) + while (data < end) { // Read next chunk header. WReadAndAdvance(data, &riff_chunk, sizeof(riff_chunk)); @@ -107,7 +107,7 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, riff_chunk.len = DD_ULONG(riff_chunk.len); // What have we got here? - if(!strncmp(riff_chunk.id, "fmt ", 4)) + if (!strncmp(riff_chunk.id, "fmt ", 4)) { // Read format chunk. WReadAndAdvance(data, &wave_format, sizeof(wave_format)); @@ -123,19 +123,19 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, assert(wave_format.wFormatTag == WAVE_FORMAT_PCM); // linear PCM // Check that it's a format we know how to read. - if(wave_format.wFormatTag != WAVE_FORMAT_PCM) + if (wave_format.wFormatTag != WAVE_FORMAT_PCM) { LOG_RES_WARNING("Unsupported format (%i)") << wave_format.wFormatTag; return NULL; } - if(wave_format.wChannels != 1) + if (wave_format.wChannels != 1) { LOG_RES_WARNING("Too many channels (only mono supported)"); return NULL; } // Read the extra format information. //WReadAndAdvance(&data, &wave_format2, sizeof(*wave_format2)); - /*if(wave_format->wBitsPerSample == 0) + /*if (wave_format->wBitsPerSample == 0) { // We'll have to guess... *bits = 8*wave_format->dwAvgBytesPerSec/ @@ -143,7 +143,7 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, } else { */ - if(wave_format.wBitsPerSample != 8 && + if (wave_format.wBitsPerSample != 8 && wave_format.wBitsPerSample != 16) { LOG_RES_WARNING("Must have 8 or 16 bits per sample"); @@ -153,9 +153,9 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, *bits = wave_format.wBitsPerSample; *rate = wave_format.dwSamplesPerSec; } - else if(!strncmp(riff_chunk.id, "data", 4)) + else if (!strncmp(riff_chunk.id, "data", 4)) { - if(!wave_format.wFormatTag) + if (!wave_format.wFormatTag) { LOG_RES_WARNING("Malformed WAV data"); return NULL; @@ -167,10 +167,10 @@ void* WAV_MemoryLoad(const byte* data, size_t datalength, int* bits, int* rate, memcpy(sampledata, data, riff_chunk.len); #ifdef __BIG_ENDIAN__ // Correct endianness. - /*if(wave_format->wBitsPerSample == 16) + /*if (wave_format->wBitsPerSample == 16) { ushort* sample = sampledata; - for(; sample < ((short*)sampledata) + *samples; ++sample) + for (; sample < ((short*)sampledata) + *samples; ++sample) *sample = DD_USHORT(*sample); }*/ #endif @@ -211,7 +211,7 @@ void *WAV_Load(char const *filename, int *bits, int *rate, int *samples) // Parse the RIFF data. void *sampledata = WAV_MemoryLoad((byte const *) data, size, bits, rate, samples); - if(!sampledata) + if (!sampledata) { LOG_RES_WARNING("Failed to load \"%s\"") << filename; } @@ -219,7 +219,7 @@ void *WAV_Load(char const *filename, int *bits, int *rate, int *samples) M_Free(data); return sampledata; } - catch(de::FS1::NotFoundError const &) + catch (de::FS1::NotFoundError const &) {} // Ignore. return 0; } diff --git a/doomsday/apps/libdoomsday/src/savedsession.cpp b/doomsday/apps/libdoomsday/src/savedsession.cpp index 07f4390fd7..07ea41c962 100644 --- a/doomsday/apps/libdoomsday/src/savedsession.cpp +++ b/doomsday/apps/libdoomsday/src/savedsession.cpp @@ -39,11 +39,11 @@ static String const BLOCK_GAMERULE = "gamerule"; static Value *makeValueFromInfoValue(de::Info::Element::Value const &v) { String const text = v; - if(!text.compareWithoutCase("True")) + if (!text.compareWithoutCase("True")) { return new NumberValue(true, NumberValue::Boolean); } - else if(!text.compareWithoutCase("False")) + else if (!text.compareWithoutCase("False")) { return new NumberValue(false, NumberValue::Boolean); } @@ -65,36 +65,36 @@ void SavedSession::Metadata::parse(String const &source) // Rebuild the game rules subrecord. Record &rules = addSubrecord("gameRules"); - foreach(Info::Element const *elem, info.root().contentsInOrder()) + foreach (Info::Element const *elem, info.root().contentsInOrder()) { - if(Info::KeyElement const *key = elem->maybeAs()) + if (Info::KeyElement const *key = elem->maybeAs()) { QScopedPointer v(makeValueFromInfoValue(key->value())); add(key->name()) = v.take(); continue; } - if(Info::ListElement const *list = elem->maybeAs()) + if (Info::ListElement const *list = elem->maybeAs()) { QScopedPointer arr(new ArrayValue); - foreach(Info::Element::Value const &v, list->values()) + foreach (Info::Element::Value const &v, list->values()) { *arr << makeValueFromInfoValue(v); } addArray(list->name(), arr.take()); continue; } - if(Info::BlockElement const *block = elem->maybeAs()) + if (Info::BlockElement const *block = elem->maybeAs()) { // Perhaps a ruleset group? - if(block->blockType() == BLOCK_GROUP) + if (block->blockType() == BLOCK_GROUP) { - foreach(Info::Element const *grpElem, block->contentsInOrder()) + foreach (Info::Element const *grpElem, block->contentsInOrder()) { - if(!grpElem->isBlock()) continue; + if (!grpElem->isBlock()) continue; // Perhaps a gamerule? Info::BlockElement const &ruleBlock = grpElem->as(); - if(ruleBlock.blockType() == BLOCK_GAMERULE) + if (ruleBlock.blockType() == BLOCK_GAMERULE) { QScopedPointer v(makeValueFromInfoValue(ruleBlock.keyValue("value"))); rules.add(ruleBlock.name()) = v.take(); @@ -106,7 +106,7 @@ void SavedSession::Metadata::parse(String const &source) } // Ensure the map URI has the "Maps" scheme set. - if(!gets("mapUri").beginsWith("Maps:", Qt::CaseInsensitive)) + if (!gets("mapUri").beginsWith("Maps:", Qt::CaseInsensitive)) { set("mapUri", String("Maps:") + gets("mapUri")); } @@ -115,14 +115,14 @@ void SavedSession::Metadata::parse(String const &source) // this info explicitly. The assumption was that the episode was inferred by / encoded // in the map URI. If the episode is not present in the metadata then we'll assume it // is encoded in the map URI and extract it. - if(!has("episode")) + if (!has("episode")) { String const mapUriPath = gets("mapUri").substr(5); - if(mapUriPath.beginsWith("MAP", Qt::CaseInsensitive)) + if (mapUriPath.beginsWith("MAP", Qt::CaseInsensitive)) { set("episode", "1"); } - else if(mapUriPath.at(0).toLower() == 'e' && mapUriPath.at(2).toLower() == 'm') + else if (mapUriPath.at(0).toLower() == 'e' && mapUriPath.at(2).toLower() == 'm') { set("episode", mapUriPath.substr(1, 1)); } @@ -134,12 +134,12 @@ void SavedSession::Metadata::parse(String const &source) } // Ensure we have a valid description. - if(gets("userDescription").isEmpty()) + if (gets("userDescription").isEmpty()) { set("userDescription", "UNNAMED"); } } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING(er.asText()); } @@ -149,7 +149,7 @@ String SavedSession::Metadata::asStyledText() const { String currentMapText = String(_E(l)" - Uri: " _E(.) "%1" _E(.)).arg(gets("mapUri")); // Is the time in the current map known? - if(has("mapTime")) + if (has("mapTime")) { int time = geti("mapTime") / 35 /*TICRATE*/; int const hours = time / 3600; time -= hours * 3600; @@ -165,9 +165,9 @@ String SavedSession::Metadata::asStyledText() const String gameRulesText; QStringList rules = gets("gameRules", "None").split("\n", QString::SkipEmptyParts); rules.replaceInStrings(QRegExp("(.*)\\s*:\\s*([^ ].*)"), _E(l) "\\1: " _E(.) "\\2"); - for(int i = 0; i < rules.size(); ++i) + for (int i = 0; i < rules.size(); ++i) { - if(i) gameRulesText += "\n"; + if (i) gameRulesText += "\n"; gameRulesText += " - " + rules.at(i).trimmed(); } @@ -197,38 +197,38 @@ String SavedSession::Metadata::asTextWithInfoSyntax() const QTextStream os(&text); os.setCodec("UTF-8"); - if(has("gameIdentityKey")) os << "gameIdentityKey: " << gets("gameIdentityKey"); - if(has("episode")) os << "\nepisode: " << gets("episode"); - if(has("mapTime")) os << "\nmapTime: " << String::number(geti("mapTime")); - if(has("mapUri")) os << "\nmapUri: " << gets("mapUri"); - if(has("players")) + if (has("gameIdentityKey")) os << "gameIdentityKey: " << gets("gameIdentityKey"); + if (has("episode")) os << "\nepisode: " << gets("episode"); + if (has("mapTime")) os << "\nmapTime: " << String::number(geti("mapTime")); + if (has("mapUri")) os << "\nmapUri: " << gets("mapUri"); + if (has("players")) { os << "\nplayers <"; ArrayValue const &playersArray = geta("players"); DENG2_FOR_EACH_CONST(ArrayValue::Elements, i, playersArray.elements()) { Value const *value = *i; - if(i != playersArray.elements().begin()) os << ", "; + if (i != playersArray.elements().begin()) os << ", "; os << (value->as().isTrue()? "True" : "False"); } os << ">"; } - if(has("visitedMaps")) + if (has("visitedMaps")) { os << "\nvisitedMaps <"; ArrayValue const &visitedMapsArray = geta("visitedMaps"); DENG2_FOR_EACH_CONST(ArrayValue::Elements, i, visitedMapsArray.elements()) { Value const *value = *i; - if(i != visitedMapsArray.elements().begin()) os << ", "; + if (i != visitedMapsArray.elements().begin()) os << ", "; os << "\"" << String(value->as()) << "\""; } os << ">"; } - if(has("sessionId")) os << "\nsessionId: " << String::number(geti("sessionId")); - if(has("userDescription")) os << "\nuserDescription: " << gets("userDescription"); + if (has("sessionId")) os << "\nsessionId: " << String::number(geti("sessionId")); + if (has("userDescription")) os << "\nuserDescription: " << gets("userDescription"); - if(hasSubrecord("gameRules")) + if (hasSubrecord("gameRules")) { os << "\n" << BLOCK_GROUP << " ruleset {"; @@ -237,7 +237,7 @@ String SavedSession::Metadata::asTextWithInfoSyntax() const { Value const &value = i.value()->value(); String valueAsText = value.asText(); - if(value.is()) + if (value.is()) { valueAsText = "\"" + valueAsText.replace("\"", "''") + "\""; } @@ -296,19 +296,19 @@ DENG2_PIMPL(SavedSession) // So far so good. return true; } - catch(IByteArray::OffsetError const &) + catch (IByteArray::OffsetError const &) { LOG_RES_WARNING("Archive in %s is truncated") << self.description(); } - catch(IIStream::InputError const &) + catch (IIStream::InputError const &) { LOG_RES_WARNING("%s cannot be read") << self.description(); } - catch(Archive::FormatError const &) + catch (Archive::FormatError const &) { LOG_RES_WARNING("Archive in %s is invalid") << self.description(); } - catch(Folder::NotFoundError const &) + catch (Folder::NotFoundError const &) { LOG_RES_WARNING("%s does not appear to be a .save package") << self.description(); } @@ -346,7 +346,7 @@ void SavedSession::readMetadata() // Determine if a .save package exists in the repository and if so, read the metadata. Metadata newMetadata; - if(!d->readMetadata(newMetadata)) + if (!d->readMetadata(newMetadata)) { // Unrecognized or the file could not be accessed (perhaps its a network path?). // Return the session to the "null/invalid" state. @@ -359,7 +359,7 @@ void SavedSession::readMetadata() SavedSession::Metadata const &SavedSession::metadata() const { - if(d->needCacheMetadata) + if (d->needCacheMetadata) { const_cast(this)->readMetadata(); } @@ -378,7 +378,7 @@ void SavedSession::cacheMetadata(Metadata const &copied) String SavedSession::stateFilePath(String const &path) //static { - if(!path.fileName().isEmpty()) + if (!path.fileName().isEmpty()) { return path + "State"; } @@ -389,10 +389,10 @@ File *SavedSession::Interpreter::interpretFile(File *sourceData) const { try { - if(ZipArchive::recognize(*sourceData)) + if (ZipArchive::recognize(*sourceData)) { // It is a ZIP archive: we will represent it as a folder. - if(sourceData->name().fileNameExtension() == ".save") + if (sourceData->name().fileNameExtension() == ".save") { /// @todo fixme: Don't assume this is a save package. LOG_RES_VERBOSE("Interpreted %s as a SavedSession") << sourceData->description(); @@ -405,7 +405,7 @@ File *SavedSession::Interpreter::interpretFile(File *sourceData) const } } } - catch(Error const &er) + catch (Error const &er) { // Even though it was recognized as an archive, the file // contents may still prove to be corrupted. diff --git a/doomsday/apps/libdoomsday/src/session.cpp b/doomsday/apps/libdoomsday/src/session.cpp index 8acf13c57d..b4dce4085d 100644 --- a/doomsday/apps/libdoomsday/src/session.cpp +++ b/doomsday/apps/libdoomsday/src/session.cpp @@ -36,7 +36,7 @@ Session::Profile &Session::profile() //static void Session::removeSaved(String const &path) //static { - if(App::rootFolder().has(path)) + if (App::rootFolder().has(path)) { App::rootFolder().removeFile(path); } @@ -44,7 +44,7 @@ void Session::removeSaved(String const &path) //static void Session::copySaved(String const &destPath, String const &sourcePath) //static { - if(!destPath.compareWithoutCase(sourcePath)) return; + if (!destPath.compareWithoutCase(sourcePath)) return; LOG_AS("GameSession"); @@ -64,7 +64,7 @@ DENG2_PIMPL(Session::SavedIndex) void notifyAvailabilityUpdate() { - if(availabilityUpdateDisabled) return; + if (availabilityUpdateDisabled) return; DENG2_FOR_PUBLIC_AUDIENCE2(AvailabilityUpdate, i) i->savedIndexAvailabilityUpdate(self); } @@ -93,7 +93,7 @@ void Session::SavedIndex::clear() void Session::SavedIndex::add(SavedSession &saved) { String const path = saved.path().toLower(); - if(!d->entries.contains(path) || d->entries[path] != &saved) + if (!d->entries.contains(path) || d->entries[path] != &saved) { d->entries[path] = &saved; d->notifyAvailabilityUpdate(); @@ -102,7 +102,7 @@ void Session::SavedIndex::add(SavedSession &saved) void Session::SavedIndex::remove(String path) { - if(d->entries.remove(path.toLower())) + if (d->entries.remove(path.toLower())) { d->notifyAvailabilityUpdate(); } @@ -111,7 +111,7 @@ void Session::SavedIndex::remove(String path) SavedSession *Session::SavedIndex::find(String path) const { All::iterator found = d->entries.find(path.toLower()); - if(found != d->entries.end()) + if (found != d->entries.end()) { return found.value(); } diff --git a/doomsday/apps/libdoomsday/src/uri.cpp b/doomsday/apps/libdoomsday/src/uri.cpp index 8b77fdc91a..ed5a62bf1f 100644 --- a/doomsday/apps/libdoomsday/src/uri.cpp +++ b/doomsday/apps/libdoomsday/src/uri.cpp @@ -50,7 +50,7 @@ static String extractScheme(String &stringWithScheme) { String scheme; int pos = stringWithScheme.indexOf(':'); - if(pos > URI_MINSCHEMELENGTH) // could be Windows-style driver letter "c:" + if (pos > URI_MINSCHEMELENGTH) // could be Windows-style driver letter "c:" { scheme = stringWithScheme.left(pos); stringWithScheme.remove(0, pos + 1); @@ -102,13 +102,13 @@ DENG2_PIMPL_NOREF(Uri) clearCachedResolved(); scheme = extractScheme(rawUri); // scheme removed - if(sep != '/') rawUri.replace(sep, '/'); // force slashes as separator + if (sep != '/') rawUri.replace(sep, '/'); // force slashes as separator path = rawUri; strPath = path.toString(); // for legacy code - if(!scheme.isEmpty()) + if (!scheme.isEmpty()) { - if(defaultResourceClass == RC_NULL || App_FileSystem().knownScheme(scheme)) + if (defaultResourceClass == RC_NULL || App_FileSystem().knownScheme(scheme)) { // Scheme is accepted as is. return; @@ -117,12 +117,12 @@ DENG2_PIMPL_NOREF(Uri) } // Attempt to guess the scheme by interpreting the path? - if(defaultResourceClass == RC_UNKNOWN) + if (defaultResourceClass == RC_UNKNOWN) { defaultResourceClass = DD_GuessFileTypeFromFileName(strPath).defaultClass(); } - if(VALID_RESOURCECLASSID(defaultResourceClass)) + if (VALID_RESOURCECLASSID(defaultResourceClass)) { FS1::Scheme &fsScheme = App_FileSystem().scheme(ResourceClass::classForId(defaultResourceClass).defaultScheme()); scheme = fsScheme.name(); @@ -131,7 +131,7 @@ DENG2_PIMPL_NOREF(Uri) String resolveSymbol(QStringRef const &symbol) const { - if(!resolverFunc) + if (!resolverFunc) { return symbol.toString(); } @@ -153,10 +153,10 @@ DENG2_PIMPL_NOREF(Uri) // Keep scanning the path for embedded expressions. QStringRef expression; int expEnd = 0, expBegin; - while((expBegin = strPath.indexOf('$', expEnd)) >= 0) + while ((expBegin = strPath.indexOf('$', expEnd)) >= 0) { // Is the next char the start-of-expression character? - if(strPath.at(expBegin + 1) == '(') + if (strPath.at(expBegin + 1) == '(') { // Copy everything up to the '$'. result += strPath.mid(expEnd, expBegin - expEnd); @@ -166,7 +166,7 @@ DENG2_PIMPL_NOREF(Uri) // Find the end-of-expression character. expEnd = strPath.indexOf(')', expBegin); - if(expEnd < 0) + if (expEnd < 0) { LOG_RES_WARNING("Ignoring expression \"" + strPath + "\": " "missing a closing ')'"); @@ -206,7 +206,7 @@ Uri::Uri() : d(new Instance) Uri::Uri(String const &percentEncoded, resourceclassid_t defaultResourceClass, QChar sep) : d(new Instance) { - if(!percentEncoded.isEmpty()) + if (!percentEncoded.isEmpty()) { setUri(percentEncoded, defaultResourceClass, sep); } @@ -236,23 +236,23 @@ Uri::Uri(char const *nullTerminatedCStr) : d(new Instance) Uri Uri::fromUserInput(char **argv, int argc, bool (*knownScheme) (String name)) { Uri output; - if(argv) + if (argv) { // [0: :] or [0: ] or [0: ]. - switch(argc) + switch (argc) { case 1: { // Try to extract the scheme and encode the rest of the path. String rawUri(argv[0]); int pos = rawUri.indexOf(':'); - if(pos >= 0) + if (pos >= 0) { output.setScheme(rawUri.left(pos)); rawUri.remove(0, pos + 1); output.setPath(Path::normalize(QString(QByteArray(rawUri.toUtf8()).toPercentEncoding()))); } // Just a scheme name? - else if(knownScheme && knownScheme(rawUri)) + else if (knownScheme && knownScheme(rawUri)) { output.setScheme(rawUri); } @@ -297,23 +297,23 @@ bool Uri::isEmpty() const bool Uri::operator == (Uri const &other) const { - if(this == &other) return true; + if (this == &other) return true; // First, lets check if the scheme differs. - if(d->scheme.compareWithoutCase(other.d->scheme)) return false; + if (d->scheme.compareWithoutCase(other.d->scheme)) return false; // We can skip resolving if the paths are identical. - if(d->path == other.d->path) return true; + if (d->path == other.d->path) return true; // We must be able to resolve both paths to compare. try { // Do not match partial paths. - if(resolvedRef().length() != other.resolvedRef().length()) return false; + if (resolvedRef().length() != other.resolvedRef().length()) return false; return resolvedRef().compareWithoutCase(other.resolvedRef()) == 0; } - catch(ResolveError const &) + catch (ResolveError const &) { // Ignore the error. } @@ -369,7 +369,7 @@ String const &Uri::resolvedRef() const void *currentGame = (void *) (!App::appExists() || DoomsdayApp::game().isNull()? 0 : &DoomsdayApp::game()); #ifndef LIBDENG_DISABLE_URI_RESOLVE_CACHING - if(d->resolvedForGame && d->resolvedForGame == currentGame) + if (d->resolvedForGame && d->resolvedForGame == currentGame) { // We can just return the previously prepared resolved URI. return d->resolvedPath.toStringRef(); @@ -425,17 +425,17 @@ Uri &Uri::setUri(String rawUri, resourceclassid_t defaultResourceClass, QChar se String Uri::compose(ComposeAsTextFlags compositionFlags, QChar sep) const { String text; - if(!(compositionFlags & OmitScheme)) + if (!(compositionFlags & OmitScheme)) { - if(!d->scheme.isEmpty()) + if (!d->scheme.isEmpty()) { text += d->scheme + ":"; } } - if(!(compositionFlags & OmitPath)) + if (!(compositionFlags & OmitPath)) { QString path = d->path.withSeparators(sep); - if(compositionFlags & DecodePath) + if (compositionFlags & DecodePath) { path = QByteArray::fromPercentEncoding(path.toUtf8()); } @@ -560,7 +560,7 @@ LIBDENG_DEFINE_UNITTEST(Uri) DENG_ASSERT(u.path().reverseSegment(2).toString() == "some"); } } - catch(Error const &er) + catch (Error const &er) { qWarning() << er.asText(); return false; diff --git a/doomsday/apps/libdoomsday/src/world/actions.cpp b/doomsday/apps/libdoomsday/src/world/actions.cpp index ae6bfb0509..8afb7991ab 100644 --- a/doomsday/apps/libdoomsday/src/world/actions.cpp +++ b/doomsday/apps/libdoomsday/src/world/actions.cpp @@ -33,10 +33,10 @@ void P_GetGameActions() ::actions.clear(); // Action links are provided by the game (which owns the actual action functions). - if(auto getVar = DoomsdayApp::plugins().gameExports().GetVariable) + if (auto getVar = DoomsdayApp::plugins().gameExports().GetVariable) { auto const *links = (actionlink_t const *) getVar(DD_ACTION_LINK); - for(actionlink_t const *link = links; link && link->name; link++) + for (actionlink_t const *link = links; link && link->name; link++) { ::actions.insert(String(link->name).toLower(), link->func); } @@ -45,10 +45,10 @@ void P_GetGameActions() acfnptr_t P_GetAction(String const &name) { - if(!name.isEmpty()) + if (!name.isEmpty()) { auto found = actions.find(name.toLower()); - if(found != actions.end()) return found.value(); + if (found != actions.end()) return found.value(); } return nullptr; // Not found. } diff --git a/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp b/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp index 9e95e145f0..2a266a38ba 100644 --- a/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp +++ b/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp @@ -71,9 +71,9 @@ DENG2_PIMPL(EntityDatabase) { // Do we already have a record for this entity? Entities::iterator found = set.find(elementIndex); - if(found != set.end()) return &found->second; + if (found != set.end()) return &found->second; - if(!canCreate) return 0; + if (!canCreate) return 0; // A new entity. std::pair result; @@ -105,13 +105,13 @@ PropertyValue const &EntityDatabase::property(MapEntityPropertyDef const *def, DENG2_ASSERT(def); Entities *set = d->entities(def->entity->id); Entity *entity = d->entityByElementIndex(*set, elementIndex, false /*do not create*/); - if(!entity) + if (!entity) throw Error("EntityDatabase::property", QString("There is no element %1 of type %2") .arg(elementIndex) .arg(Str_Text(P_NameForMapEntityDef(def->entity)))); Entity::const_iterator found = entity->find(def->id); - if(found == entity->end()) + if (found == entity->end()) throw Error("EntityDatabase::property", QString("Element %1 of type %2 has no value for property %3") .arg(elementIndex) .arg(Str_Text(P_NameForMapEntityDef(def->entity))) @@ -125,12 +125,12 @@ void EntityDatabase::setProperty(MapEntityPropertyDef const *def, int elementInd DENG2_ASSERT(def); Entities *set = d->entities(def->entity->id); Entity *entity = d->entityByElementIndex(*set, elementIndex, true); - if(!entity) + if (!entity) throw Error("EntityDatabase::setProperty", "Failed adding new entity element record"); // Do we already have a record for this? Entity::iterator found = entity->find(def->id); - if(found != entity->end()) + if (found != entity->end()) { PropertyValue **adr = &found->second; delete *adr; diff --git a/doomsday/apps/libdoomsday/src/world/entitydef.cpp b/doomsday/apps/libdoomsday/src/world/entitydef.cpp index f3835c26f3..5b32b100d5 100644 --- a/doomsday/apps/libdoomsday/src/world/entitydef.cpp +++ b/doomsday/apps/libdoomsday/src/world/entitydef.cpp @@ -42,13 +42,13 @@ static EntityDefIdMap entityDefIdMap; static void clearEntityDefs() { - if(!::entityDefs) return; + if (!::entityDefs) return; ::entityDefs->forAll([] (StringPool::Id id) { auto *def = static_cast( ::entityDefs->userPointer(id) ); DENG2_ASSERT(def); - for(duint i = 0; i < def->numProps; ++i) + for (duint i = 0; i < def->numProps; ++i) { M_Free(def->props[i].name); } @@ -65,7 +65,7 @@ static void clearEntityDefs() MapEntityDef *P_MapEntityDef(int id) { EntityDefIdMap::iterator i = entityDefIdMap.find(id); - if(i != entityDefIdMap.end()) + if (i != entityDefIdMap.end()) { StringPool::Id id = i->second; return static_cast( entityDefs->userPointer(id) ); @@ -75,7 +75,7 @@ MapEntityDef *P_MapEntityDef(int id) MapEntityDef *P_MapEntityDefByName(char const *name) { - if(name && entityDefs) + if (name && entityDefs) { StringPool::Id id = entityDefs->isInterned(String(name)); return static_cast( entityDefs->userPointer(id) ); @@ -86,11 +86,11 @@ MapEntityDef *P_MapEntityDefByName(char const *name) AutoStr *P_NameForMapEntityDef(MapEntityDef *def) { String name; // Not found. - if(def) + if (def) { ::entityDefs->forAll([&def, &name] (StringPool::Id id) { - if(::entityDefs->userPointer(id) == def) + if (::entityDefs->userPointer(id) == def) { name = ::entityDefs->string(id); return LoopAbort; @@ -106,16 +106,16 @@ int MapEntityDef_Property(MapEntityDef *def, int propertyId, { DENG2_ASSERT(def); MapEntityPropertyDef *found = 0; - for(uint i = 0; i < def->numProps; ++i) + for (uint i = 0; i < def->numProps; ++i) { MapEntityPropertyDef *prop = def->props + i; - if(prop->id == propertyId) + if (prop->id == propertyId) { found = prop; break; } } - if(retDef) *retDef = found; + if (retDef) *retDef = found; return found? found - def->props : -1/* not found */; } @@ -124,19 +124,19 @@ int MapEntityDef_PropertyByName(MapEntityDef *def, char const *propertyName, { DENG2_ASSERT(def); MapEntityPropertyDef *found = 0; - if(propertyName && propertyName[0]) + if (propertyName && propertyName[0]) { - for(uint i = 0; i < def->numProps; ++i) + for (uint i = 0; i < def->numProps; ++i) { MapEntityPropertyDef *prop = def->props + i; - if(!stricmp(prop->name, propertyName)) + if (!stricmp(prop->name, propertyName)) { found = prop; break; } } } - if(retDef) *retDef = found; + if (retDef) *retDef = found; return found? found - def->props : -1/* not found */; } @@ -145,14 +145,14 @@ void MapEntityDef_AddProperty(MapEntityDef* def, int propertyId, const char* pro { DENG2_ASSERT(def); - if(propertyId == 0) // Not a valid identifier. + if (propertyId == 0) // Not a valid identifier. throw Error("MapEntityDef_AddProperty", "0 is not a valid propertyId"); - if(!propertyName || !propertyName[0]) // Must have a name. + if (!propertyName || !propertyName[0]) // Must have a name. throw Error("MapEntityDef_AddProperty", "Invalid propertyName (zero-length string)"); // A supported value type? - switch(type) + switch (type) { case DDVT_BYTE: case DDVT_SHORT: @@ -167,16 +167,16 @@ void MapEntityDef_AddProperty(MapEntityDef* def, int propertyId, const char* pro } // Ensure both the identifer and the name for the new property are unique. - if(MapEntityDef_Property(def, propertyId) >= 0) + if (MapEntityDef_Property(def, propertyId) >= 0) throw Error("MapEntityDef_AddProperty", QString("propertyId %1 not unique for %2") .arg(propertyId).arg(Str_Text(P_NameForMapEntityDef(def)))); - if(MapEntityDef_PropertyByName(def, propertyName) >= 0) + if (MapEntityDef_PropertyByName(def, propertyName) >= 0) throw Error("MapEntityDef_AddProperty", QString("propertyName \"%1\" not unique for %2") .arg(propertyName).arg(Str_Text(P_NameForMapEntityDef(def)))); // Looks good! Add it to the list of properties. def->props = (MapEntityPropertyDef*) M_Realloc(def->props, ++def->numProps * sizeof(*def->props)); - if(!def->props) + if (!def->props) throw Error("MapEntityDef_AddProperty", QString("Failed on (re)allocation of %1 bytes for new MapEntityPropertyDef array") .arg((unsigned long) sizeof(*def->props))); @@ -186,7 +186,7 @@ void MapEntityDef_AddProperty(MapEntityDef* def, int propertyId, const char* pro int len = (int)strlen(propertyName); prop->name = (char *) M_Malloc(sizeof(*prop->name) * (len + 1)); - if(!prop->name) + if (!prop->name) throw Error("MapEntityDef_AddProperty", QString("Failed on allocation of %1 bytes for property name") .arg((unsigned long) (sizeof(*prop->name) * (len + 1)))); @@ -207,31 +207,31 @@ void MapEntityDef_AddProperty(MapEntityDef* def, int propertyId, const char* pro static MapEntityDef *findMapEntityDef(int identifier, char const *entityName, bool canCreate) { - if(identifier == 0 && (!entityName || !entityName[0])) return 0; + if (identifier == 0 && (!entityName || !entityName[0])) return 0; // Is this an already known entity? - if(entityName && entityName[0]) + if (entityName && entityName[0]) { MapEntityDef *found = P_MapEntityDefByName(entityName); - if(found) return found; + if (found) return found; } else { MapEntityDef *found = P_MapEntityDef(identifier); - if(found) return found; + if (found) return found; } // An unknown entity. Are we creating? - if(!canCreate) return 0; + if (!canCreate) return 0; // Ensure the name is unique. - if(P_MapEntityDefByName(entityName)) return 0; + if (P_MapEntityDefByName(entityName)) return 0; // Ensure the identifier is unique. - if(P_MapEntityDef(identifier)) return 0; + if (P_MapEntityDef(identifier)) return 0; // Have we yet to initialize the map entity definition dataset? - if(!entityDefs) + if (!entityDefs) { entityDefs = new StringPool; } @@ -256,12 +256,12 @@ DENG_EXTERN_C dd_bool P_RegisterMapObjProperty(int entityId, int propertyId, try { MapEntityDef *def = findMapEntityDef(entityId, 0, false /*do not create*/); - if(!def) throw Error("P_RegisterMapObjProperty", QString("Unknown entityId %1").arg(entityId)); + if (!def) throw Error("P_RegisterMapObjProperty", QString("Unknown entityId %1").arg(entityId)); MapEntityDef_AddProperty(def, propertyId, propertyName, type); return true; // Success! } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Ignoring.") << er.asText(); } @@ -283,11 +283,11 @@ static MapEntityPropertyDef *entityPropertyDef(int entityId, int propertyId) { // Is this a known entity? MapEntityDef *entity = P_MapEntityDef(entityId); - if(!entity) throw Error("entityPropertyDef", QString("Unknown entity definition id %1").arg(entityId)); + if (!entity) throw Error("entityPropertyDef", QString("Unknown entity definition id %1").arg(entityId)); // Is this a known property? MapEntityPropertyDef *property; - if(MapEntityDef_Property(entity, propertyId, &property) < 0) + if (MapEntityDef_Property(entity, propertyId, &property) < 0) throw Error("entityPropertyDef", QString("Entity definition %1 has no property with id %2") .arg(Str_Text(P_NameForMapEntityDef(entity))) .arg(propertyId)); @@ -297,7 +297,7 @@ static MapEntityPropertyDef *entityPropertyDef(int entityId, int propertyId) static void setValue(void *dst, valuetype_t dstType, PropertyValue const &pvalue) { - switch(dstType) + switch (dstType) { case DDVT_FIXED: *((fixed_t *) dst) = pvalue.asFixed(); break; case DDVT_FLOAT: *( (float *) dst) = pvalue.asFloat(); break; @@ -313,7 +313,7 @@ static void setValue(void *dst, valuetype_t dstType, PropertyValue const &pvalue DENG_EXTERN_C byte P_GetGMOByte(int entityId, int elementIndex, int propertyId) { byte returnVal = 0; - if(World::get().hasMap()) + if (World::get().hasMap()) { try { @@ -322,7 +322,7 @@ DENG_EXTERN_C byte P_GetGMOByte(int entityId, int elementIndex, int propertyId) setValue(&returnVal, DDVT_BYTE, db.property(propDef, elementIndex)); } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Returning 0.") << er.asText(); } @@ -333,7 +333,7 @@ DENG_EXTERN_C byte P_GetGMOByte(int entityId, int elementIndex, int propertyId) DENG_EXTERN_C short P_GetGMOShort(int entityId, int elementIndex, int propertyId) { short returnVal = 0; - if(World::get().hasMap()) + if (World::get().hasMap()) { try { @@ -342,7 +342,7 @@ DENG_EXTERN_C short P_GetGMOShort(int entityId, int elementIndex, int propertyId setValue(&returnVal, DDVT_SHORT, db.property(propDef, elementIndex)); } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Returning 0.") << er.asText(); } @@ -353,7 +353,7 @@ DENG_EXTERN_C short P_GetGMOShort(int entityId, int elementIndex, int propertyId DENG_EXTERN_C int P_GetGMOInt(int entityId, int elementIndex, int propertyId) { int returnVal = 0; - if(World::get().hasMap()) + if (World::get().hasMap()) { try { @@ -362,7 +362,7 @@ DENG_EXTERN_C int P_GetGMOInt(int entityId, int elementIndex, int propertyId) setValue(&returnVal, DDVT_INT, db.property(propDef, elementIndex)); } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Returning 0.") << er.asText(); } @@ -373,7 +373,7 @@ DENG_EXTERN_C int P_GetGMOInt(int entityId, int elementIndex, int propertyId) DENG_EXTERN_C fixed_t P_GetGMOFixed(int entityId, int elementIndex, int propertyId) { fixed_t returnVal = 0; - if(World::get().hasMap()) + if (World::get().hasMap()) { try { @@ -382,7 +382,7 @@ DENG_EXTERN_C fixed_t P_GetGMOFixed(int entityId, int elementIndex, int property setValue(&returnVal, DDVT_FIXED, db.property(propDef, elementIndex)); } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Returning 0.") << er.asText(); } @@ -393,7 +393,7 @@ DENG_EXTERN_C fixed_t P_GetGMOFixed(int entityId, int elementIndex, int property DENG_EXTERN_C angle_t P_GetGMOAngle(int entityId, int elementIndex, int propertyId) { angle_t returnVal = 0; - if(World::get().hasMap()) + if (World::get().hasMap()) { try { @@ -402,7 +402,7 @@ DENG_EXTERN_C angle_t P_GetGMOAngle(int entityId, int elementIndex, int property setValue(&returnVal, DDVT_ANGLE, db.property(propDef, elementIndex)); } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Returning 0.") << er.asText(); } @@ -413,7 +413,7 @@ DENG_EXTERN_C angle_t P_GetGMOAngle(int entityId, int elementIndex, int property DENG_EXTERN_C float P_GetGMOFloat(int entityId, int elementIndex, int propertyId) { float returnVal = 0; - if(World::get().hasMap()) + if (World::get().hasMap()) { try { @@ -422,7 +422,7 @@ DENG_EXTERN_C float P_GetGMOFloat(int entityId, int elementIndex, int propertyId setValue(&returnVal, DDVT_FLOAT, db.property(propDef, elementIndex)); } - catch(Error const &er) + catch (Error const &er) { LOG_WARNING("%s. Returning 0.") << er.asText(); } diff --git a/doomsday/apps/libdoomsday/src/world/map.cpp b/doomsday/apps/libdoomsday/src/world/map.cpp index 36b483bfb0..58ad3b71ef 100644 --- a/doomsday/apps/libdoomsday/src/world/map.cpp +++ b/doomsday/apps/libdoomsday/src/world/map.cpp @@ -35,14 +35,14 @@ DENG2_PIMPL(BaseMap) ~Instance() { - if(manifest) manifest->audienceForDeletion() -= this; + if (manifest) manifest->audienceForDeletion() -= this; DENG2_FOR_PUBLIC_AUDIENCE2(Deletion, i) i->mapBeingDeleted(self); } void recordBeingDeleted(Record &record) { // The manifest is not owned by us, it may be deleted by others. - if(manifest == &record) + if (manifest == &record) { manifest = nullptr; } @@ -63,7 +63,7 @@ BaseMap::~BaseMap() String BaseMap::id() const { - if(!hasManifest()) return ""; + if (!hasManifest()) return ""; return manifest().gets("id"); } @@ -74,7 +74,7 @@ bool BaseMap::hasManifest() const res::MapManifest &BaseMap::manifest() const { - if(hasManifest()) + if (hasManifest()) { DENG2_ASSERT(d->manifest != nullptr); return *d->manifest; @@ -85,11 +85,11 @@ res::MapManifest &BaseMap::manifest() const void BaseMap::setManifest(res::MapManifest *newManifest) { - if(d->manifest) d->manifest->audienceForDeletion() -= d; + if (d->manifest) d->manifest->audienceForDeletion() -= d; d->manifest = newManifest; - if(d->manifest) d->manifest->audienceForDeletion() += d; + if (d->manifest) d->manifest->audienceForDeletion() += d; } EntityDatabase &BaseMap::entityDatabase() const diff --git a/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp b/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp index 141e05b92f..52838a2b02 100644 --- a/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp +++ b/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp @@ -27,7 +27,7 @@ using namespace de; PropertyValue *BuildPropertyValue(valuetype_t type, void *valueAdr) { DENG2_ASSERT(valueAdr != 0); - switch(type) + switch (type) { case DDVT_BYTE: return new PropertyByteValue (*( (byte *) valueAdr)); case DDVT_SHORT: return new PropertyInt16Value(*( (short *) valueAdr)); diff --git a/doomsday/apps/libdoomsday/src/world/thinker.cpp b/doomsday/apps/libdoomsday/src/world/thinker.cpp index 88327d5eae..75a51af3a6 100644 --- a/doomsday/apps/libdoomsday/src/world/thinker.cpp +++ b/doomsday/apps/libdoomsday/src/world/thinker.cpp @@ -36,7 +36,7 @@ DENG2_PIMPL_NOREF(Thinker) , base(0) , data(data_) { - if(alloc == AllocateStandard) + if (alloc == AllocateStandard) { base = reinterpret_cast(M_Calloc(size)); base->_flags = THINKF_STD_MALLOC; @@ -46,7 +46,7 @@ DENG2_PIMPL_NOREF(Thinker) base = reinterpret_cast(Z_Calloc(size, PU_MAP, NULL)); } - if(data) data->setThinker(base); + if (data) data->setThinker(base); } Instance(Instance const &other) @@ -57,7 +57,7 @@ DENG2_PIMPL_NOREF(Thinker) , data(other.data? other.data->duplicate() : 0) { base->d = data; - if(data) data->setThinker(base); + if (data) data->setThinker(base); } Instance(thinker_s *podThinkerToTake, dsize sizeInBytes) @@ -73,9 +73,9 @@ DENG2_PIMPL_NOREF(Thinker) void release() { - if(base) + if (base) { - if(isStandardAllocated()) + if (isStandardAllocated()) { M_Free(base); } @@ -105,7 +105,7 @@ DENG2_PIMPL_NOREF(Thinker) { bool const stdAlloc = CPP_BOOL(base->_flags & THINKF_STD_MALLOC); memset(base, 0, size); - if(stdAlloc) base->_flags |= THINKF_STD_MALLOC; + if (stdAlloc) base->_flags |= THINKF_STD_MALLOC; } }; @@ -145,9 +145,9 @@ Thinker::Thinker(thinker_s const &podThinker, dsize sizeInBytes, AllocMethod all // Retain the original allocation flag, though. d->base->_flags &= ~THINKF_STD_MALLOC; - if(alloc == AllocateStandard) d->base->_flags |= THINKF_STD_MALLOC; + if (alloc == AllocateStandard) d->base->_flags |= THINKF_STD_MALLOC; - if(podThinker.d) + if (podThinker.d) { setData(reinterpret_cast(podThinker.d)->duplicate()); } @@ -229,7 +229,7 @@ void Thinker::destroy(thinker_s *thinkerBase) release(*thinkerBase); - if(thinkerBase->_flags & THINKF_STD_MALLOC) + if (thinkerBase->_flags & THINKF_STD_MALLOC) { M_Free(thinkerBase); } @@ -253,12 +253,12 @@ void Thinker::zap(thinker_s &thinkerBase, dsize sizeInBytes) void Thinker::setData(Thinker::IData *data) { - if(d->data) delete d->data; + if (d->data) delete d->data; d->data = data; d->base->d = data; - if(data) + if (data) { data->setThinker(*this); } @@ -266,13 +266,13 @@ void Thinker::setData(Thinker::IData *data) dd_bool Thinker_InStasis(thinker_s const *thinker) { - if(!thinker) return false; + if (!thinker) return false; return (thinker->_flags & THINKF_DISABLED) != 0; } void Thinker_SetStasis(thinker_t *thinker, dd_bool on) { - if(thinker) + if (thinker) { applyFlagOperation(thinker->_flags, duint32(THINKF_DISABLED), on? SetFlags : UnsetFlags); diff --git a/doomsday/apps/libdoomsday/src/world/world.cpp b/doomsday/apps/libdoomsday/src/world/world.cpp index 3a204e6701..d4314469c6 100644 --- a/doomsday/apps/libdoomsday/src/world/world.cpp +++ b/doomsday/apps/libdoomsday/src/world/world.cpp @@ -64,7 +64,7 @@ void World::reset() ddpl.flags &= ~DDPF_CAMERA; // States have changed, the state pointers are unknown. - for(ddpsprite_t &pspr : ddpl.pSprites) + for (ddpsprite_t &pspr : ddpl.pSprites) { pspr.statePtr = nullptr; } diff --git a/doomsday/apps/libdoomsday/src/world/xg.cpp b/doomsday/apps/libdoomsday/src/world/xg.cpp index 99e688744c..6473ec264c 100644 --- a/doomsday/apps/libdoomsday/src/world/xg.cpp +++ b/doomsday/apps/libdoomsday/src/world/xg.cpp @@ -30,11 +30,11 @@ void XG_GetGameClasses() ::xgClassLinks = nullptr; // XG class links are provided by the game (which defines the class specific parameter names). - if(auto getVar = DoomsdayApp::plugins().gameExports().GetVariable) + if (auto getVar = DoomsdayApp::plugins().gameExports().GetVariable) { ::xgClassLinks = (xgclass_t *) getVar(DD_XGFUNC_LINK); } - if(!::xgClassLinks) + if (!::xgClassLinks) { ::xgClassLinks = &::nullXgClassLinks; }